blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
55884a59514464a78f8002779532a7eb01b8331c | sudajzp/jzp-s-python | /FBNQ_py/Fib_circle.py | 854 | 3.84375 | 4 | #coding utf-8
'''
斐波那契数列-循环法
'''
def Fib_circle():
while True: # 去掉while循环,只用for循环
num_1 = 0
num_2 = 1
fib_array = [0] # 用于存储计算出的FB数列值
m = input('你想要查找的起始项:')
n = input('你想要查找的结束项:')
if m.isdigit() and n.isdigit(): # 在这个实现函数中,不要进行检验。每个函数只做一个事情
m = int(m) # 将输入化为整数型
n = int(n)
for i in range(n):
num_1, num_2 = num_2, num_1 + num_2
fib_array.append(num_1)
print(f'你要查找的数列为{list(enumerate(fib_array[m:], m))}')
break
else:
print('请输入有效的正整数')
if __name__ == '__main__':
Fib_circle()
|
bbdbe92fa64d8a4006a4a6f7ef2ffc862ffaadb2 | waffle-iron/osmaxx | /osmaxx/utils/directory_changer_helper.py | 1,710 | 3.609375 | 4 | import shutil
import os
class changed_dir: # pragma: nocover # noqa -> disable=N801
"""
Changes into a arbitrary directory, switching back to the directory after execution of the with statement.
directory:
the directory that should be changed into.
create_if_not_exists:
set this to False, if the chgdir should fail loudly. If set to `True`,
tries to create the directory if it doesn't exist
fallback_to_tempdir_as_last_resort:
assumes create_if_not_exists is also True
creates a tmp directory as last resort, and does work there. Defaults to False.
"""
def __init__(self, directory, create_if_not_exists=True):
self.old_dir = os.getcwd()
self.new_dir = directory
self.success = None
self.create_if_not_exists = create_if_not_exists
def __enter__(self):
try:
try:
# see if we can enter the directory
os.chdir(self.new_dir)
self.success = True
except OSError:
if self.create_if_not_exists:
try:
# see if we can create it
os.mkdir(self.new_dir)
os.chdir(self.new_dir)
self.success = True
except OSError:
raise
else:
raise
finally:
return self
def __exit__(self, type, value, traceback):
os.chdir(self.old_dir)
try:
if not self.success:
shutil.rmtree(self.new_dir)
except:
pass
return isinstance(value, OSError)
|
dadbdd33b087e16ffcbb985b8b28e1e215f5fc53 | Sandro37/Introducao_ao_python-CURSO-Digital_Innovation-One | /aula02.py | 1,172 | 4.25 | 4 | #O que são variáveis e como manipulá-las através
# de operadores aritméticos e interação com o osuário
valorA = int(input("Entre com o primeiro valor: "))
valorB = int(input("Entre com o segundo valor: "))
soma = valorA + valorB
subtracao = valorA - valorB
multiplicacao = valorA * valorB
divisao = valorA / valorB
restoDivisao = valorA % valorB
print(soma)
print(subtracao)
print(multiplicacao)
print(divisao)
print(restoDivisao)
print("soma: " + str(soma))
print("________________________________________")
print("Soma: {}".format(soma))
print("Substração: {}".format(subtracao))
print("Multiplicação: {}".format(multiplicacao))
print("Divisão: {}".format(divisao))
print("Resto da divisão: {}".format(restoDivisao))
print("________________________________________________________________")
x = '1'
soma2 = int(x) + 1
print("Soma convertida = {}".format(soma2))
print("________________________________________________________________")
print("soma: {soma}. \nSubtração: {sub}\nMultiplicacao: {multiplicacao}\nDivisão: {div}\nResto da Divisão: {resto}".format(soma=soma, sub=subtracao,multiplicacao=multiplicacao,div=divisao,resto=restoDivisao)) |
4f532cd9216766b1dfdb41705e9d643798d70225 | Sandro37/Introducao_ao_python-CURSO-Digital_Innovation-One | /aula05.py | 1,138 | 4.125 | 4 | #como organizar os dados em uma lista ou tupla
# e realizar operações com elas
lista = [12,20,1,3,5,7]
lista_animal = ['cachorro', 'gato', 'elefante']
# print(lista_animal[1])
soma = 0
for x in lista:
soma += x
print(soma)
print(sum(lista))
print(max(lista))
print(min(lista))
print(max(lista_animal))
print(min(lista_animal))
# nova_lista = lista_animal * 3
#
# print(nova_lista)
if 'gato' in lista_animal:
print('Existe um gato na lista')
else:
print('Não existe um gato na lista')
if 'lobo' in lista_animal:
print('Existe um lobo na lista')
else:
print('Não existe um lobo na lista. Será incluido')
lista_animal.append('lobo')
print(lista_animal)
lista_animal.pop()
print(lista_animal)
lista_animal.remove('elefante')
print(lista_animal)
#ordenando lista
lista_animal.sort()
lista.sort()
print(lista_animal)
print(lista)
# reverse
lista_animal.reverse()
lista.reverse()
print(lista_animal)
print(lista)
# tuplas (imutável)
tupla = (1,10,12,14,20,185)
print(len(tupla))
tupla_animal = tuple(lista_animal)
print(tupla_animal)
lista_numerica = list(tupla)
print(lista_numerica)
|
425854801551920590427c26c97c6cc791ee7d43 | lxy1992/LeetCode | /Python/interview/找零问题.py | 799 | 3.671875 | 4 | # -*- coding: UTF-8 -*-
def coinChange(values, money, coinsUsed):
#values T[1:n]数组
#valuesCounts 钱币对应的种类数
#money 找出来的总钱数
#coinsUsed 对应于 前钱币总数i所使 的硬币数
for cents in range(1, money+1):
minCoins = cents
#从第 个开始到money的所有情况初始
for value in values:
if value <= cents:
temp = coinsUsed[cents - value] + 1
if temp < minCoins:
minCoins = temp
coinsUsed[cents] = minCoins
print(' 值为:{0} 的最 硬币数 为:{1} '.format(cents, coinsUsed[cents]))
if __name__ == '__main__':
values = [25, 21, 10, 5, 1]
money = 63
coinsUsed = {i: 0 for i in range(money + 1)}
coinChange(values, money, coinsUsed) |
1da8f86df0eb1737339a4ffc51f9f37e6aaaba24 | bui-brian/FinalGradesPrediction-ML | /studentLRM.py | 1,620 | 3.625 | 4 | # Author: Brian Bui
# Date: May 1, 2021
# File: studentLRM.py - Student Performance Linear Regression Model
# Desc: predicting grades of a student by using a linear regression model
# importing all of the necessary ML packages
import numpy as np
import pandas as pd
import sklearn
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
# importing the Portuguese language course dataset
df = pd.read_csv("student-por.csv", sep=';')
# selecting specific attributes we want to use for this model
df = df[['G1', 'G2', 'G3', 'studytime', 'failures', 'freetime', 'goout', 'health', 'absences']]
# what we are trying to predict: the final grade
outputPrediction = 'G3'
# creating 2 numpy arrays to hold our x and y values
x = np.array(df.drop([outputPrediction], 1))
y = np.array(df[outputPrediction])
# splitting data into testing and training
x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size = 0.1)
# creating a model and implementing Linear Regression
model = LinearRegression().fit(x_train, y_train)
accuracy = model.score(x_test, y_test)
print('Accuracy of prediction:', accuracy) # score above 80% is good
print('\nSlope:', model.coef_)
print('\nIntercept:', model.intercept_)
# predicting the response
prediction = model.predict(x_test)
print('\nPredicted response:', prediction)
# plotting the model with matplotlib
plot = 'G1'
#plot = 'G2'
#plot = 'studytime'
#plot = 'failures'
#plot = 'freetime'
#plot = 'goout'
#plot = 'health'
#plot = 'absences'
plt.scatter(df[plot], df['G3'])
plt.xlabel(plot)
plt.ylabel('Final Grade')
plt.show() |
5db0164f453ff465f1b12d6c90902573c4404578 | ritobanrc/cryptography-toolkit | /cryptography_toolkit/tests/test_encryption.py | 985 | 3.6875 | 4 | import unittest
from cryptography_toolkit import encrpytion as en
class EncryptionTest(unittest.TestCase):
def test_reverse_cipher(self):
self.assertEqual(en.reverse_cipher("Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
".tile gnicsipida rutetcesnoc ,tema tis rolod muspi meroL")
def test_caesar_cipher(self):
self.assertEqual(en.caesar_cipher("Lorem ipsum dolor sit amet, consectetur adipiscing elit.", 7),
"svylt pwzbt kvsvy zpa htla, jvuzljalaby hkpwpzjpun lspa.")
def test_transposition_cipher(self):
self.assertEqual(en.transposition_cipher("Common sense is not so common.", 8), "Cenoonommstmme oo snnio. s s c")
def test_rot13(self):
self.assertEqual(en.rot13_cipher("Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
"yberz vcfhz qbybe fvg nzrg, pbafrpgrghe nqvcvfpvat ryvg.")
if __name__ == '__main__':
unittest.main()
|
f3a8fa37a1285908b5069546c484b7b5443b37f5 | ni26/MAPCP2019U | /Homework/3/fib.py | 533 | 3.984375 | 4 |
# coding: utf-8
# In[1]:
def fibo(n_int):
if n_int == 0:
return 0
if n_int == 1:
return 1
if n_int >= 2:
return (fibo(n_int-1)+fibo(n_int-2))
# In[4]:
def fib(n):
if isinstance(n,float):
print('The input argument {} is not a non-negative integer!'.format(n))
elif isinstance(n,str):
print('The input argument {} is not a non-negative integer!'.format(n))
else:
return fibo(n)
# In[13]:
fib ('hi')
# In[14]:
fib(5.2)
# In[5]:
fib(12)
|
a3f1d3d28fb81c256fd37fd3f6da1ded15395248 | mhelal/COMM054 | /python/evennumberedexercise/Exercise03_12.py | 390 | 3.546875 | 4 | import turtle
length = eval(input("Enter the length of a star: "))
turtle.penup()
turtle.goto(0, length / 2)
turtle.pendown()
turtle.right(72)
turtle.forward(length)
turtle.right(144)
turtle.forward(length)
turtle.right(144)
turtle.forward(length)
turtle.right(144)
turtle.forward(length)
turtle.right(144)
turtle.forward(length)
turtle.done()
|
92ead6f875e82d780d89a676e0c602737dafb509 | mhelal/COMM054 | /python/evennumberedexercise/Exercise03_06.py | 175 | 4.21875 | 4 | # Prompt the user to enter a degree in Celsius
code = eval(input("Enter an ASCII code: "))
# Display result
print("The character for ASCII code", code, "is", chr(code))
|
db0efc096311e8d2bd40a9f845af2a4ee2a38caf | mhelal/COMM054 | /python/evennumberedexercise/Exercise4_6.py | 525 | 4.3125 | 4 | # Prompt the user to enter weight in pounds
weight = eval(input("Enter weight in pounds: "))
# Prompt the user to enter height
feet = eval(input("Enter feet: "))
inches = eval(input("Enter inches: "))
height = feet * 12 + inches
# Compute BMI
bmi = weight * 0.45359237 / ((height * 0.0254) * (height * 0.0254))
# Display result
print("BMI is", bmi)
if bmi < 18.5:
print("Underweight")
elif bmi < 25:
print("Normal")
elif bmi < 30:
print("Overweight")
else:
print("Obese") |
b53f694546230e659192bcc46194c791ff1c68a3 | IvoNet/StackOverflow | /src/main/python/005.py | 501 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def bubble_sort(seq):
changed = True
while changed:
changed = False
for i in range(len(seq) - 1):
if seq[i] > seq[i + 1]:
seq[i], seq[i + 1] = seq[i + 1], seq[i]
changed = True
print(seq)
return None
if __name__ == '__main__':
# l = list(range(0, 10, -1)) # Wring
l = list(range(10, 0, -1))
bubble_sort(l)
|
d808f1b2b598f8549208cbdfe36b635d2f12c6f8 | nsnoel/Fifth-Assignment-nsnoel | /medium_assign.py | 5,672 | 4.21875 | 4 | '''
Implement the following functions based on the question. Retain the name of the functions, and parameters as is in the question.
=================
1. compute_number_of_occurences(file_name) --> 50%
Read the file large_sample.txt, and create dictionary of words where the key is the word, and value is the number of occurences of it.
Your function should output three parameters: word_dictionary and longest_word and no_of_unique_words
------------------------------------------------
2. word_list_game(file_name) & get_leader_board() --> 50%
Write a function to create a game that reads the word_list.csv file.
Based on this create a game where the users are meant to guess the meaning of a word.
For each turn, display 4 meanings as 4 options, where one is the correct meaning of the word.
Get input of the option from user, and see if the user got the meaning right.
Each option entered is to be considered as a "try" by the user.
A try is successfull if user guesses meaning correctly, and try is mistake otherwise.
End the game when the user gets 3 mistakes.
Create a file leaderboard.csv where you maintain the name and successful tries by each user.
Write a function get_leader_board() which displays the top scorers sorted by score in following fashion:
Rank | Name | Score
1 | John | 10
2 | Jane | 8
'''
1
import string
def strip_text(file_name):
text = file_name.read()
words = text.split()
words = text.split("--")
words = text.split(",")
table = str.maketrans("", "", string.punctuation)
inter_reader = [w.translate(table) for w in words]
return inter_reader
def compute_number_of_occurences(file_name):
inter_reader = strip_text(file_name)
word_dictionary = dict()
for line in inter_reader:
line = line.strip()
line = line.lower()
words = line.split(" ")
for word in words:
if word in word_dictionary:
word_dictionary[word] = word_dictionary[word] +1
else:
word_dictionary[word] = 1
for key in list(word_dictionary.keys()):
print(key, ":", word_dictionary[key])
longest_word = ''
longest_size = 0
for word in word_dictionary:
if (len(word) > longest_size):
longest_word = word
longest_size = len(word)
print(longest_word)
no_of_unique_words = len(word_dictionary)
return f"The full dictionary is :{word_dictionary}, The longest word is {longest_word}. The number of unique words is {no_of_unique_words}"
if __name__ == "__main__":
input_file = open('large_sample.txt','r')
dictionary = compute_number_of_occurences(input_file)
print(dictionary)
import random
import csv
def word_list_game(file_name):
csv_fd = open(file_name, 'r')
csv_reader = csv.reader(csv_fd) # opens and reads file, make it into a string
player_name = input("Enter name: ") #new name
list_of_words = []
definition_list = []
for row in csv_reader:
if row[0] != 'WORD': #word is column, if the row of 0 doesnt = word, means it isnt the first row
list_of_words.append(row[0]) # append the value from the file to a new list (all the words)
definition_list.append(row[1]) # append the definitions (column 2)
game = "" # initialize the variables, game is = to an empty string right now
wrong_try = 0
successful_try = 0
while game != 'over': #while the game isn't over
guess_key = random.randint(0,len(list_of_words)) #random word from list
guess_word = list_of_words[guess_key] #the definition of that random word
print(f"The definition of {guess_word} is : ")
print()
letters = ['A', 'B', 'C', 'D']
correct_alpha = random.randint(0,3)
for i in range(4):
if i == correct_alpha:
print(f"{letters[correct_alpha]} {definition_list[guess_key]}")
else:
rand_def = random.randint(0,len(list_of_words) - 1)
while rand_def == guess_key:
rand_def = random.randint(0,len(list_of_words) - 1)
print(f"{letters[i]} {definition_list[rand_def]}")
guess = input("Which is the correct definition? (A,B,C,D): ")
guess = guess.upper() #upper cases
print()
if not guess in 'ABCD':
print("That is simply not an option :)")
if guess != letters[correct_alpha]: #index out of range only when guess != correct alpha
wrong_try += 1
if wrong_try != 3:
print(f"Not right, but you still have {3 - wrong_try} tries left before the game is absolutely over.")
if wrong_try == 3:
print("Game is over, sorry. ")
game = 'over'
else:
successful_try += 1
print("Yes.")
csv_fd.close()
leader_fd_append = open('leaderboard.csv', 'a')
csv_writer = csv.writer(leader_fd_append)
leader_fd_read = open('leaderboard.csv', 'r')
csv_reader = csv.reader(leader_fd_read)
if len(list(csv_reader)) == 0:
csv_writer.writerow(["Player", "Score"])
csv_writer.writerow([player_name, successful_try])
leader_fd_append.close()
leader_fd_read.close()
def get_leader_board():
leader_fd = open('leaderboard.csv', 'r')
csv_reader = csv.reader(leader_fd)
for row in csv_reader: #writing new rows
print(row[0], " | ", row[1])
if __name__ == "__main__":
word_list_game("word_list.csv")
get_leader_board()
|
0aa83c8b941db62f131b3a469d7c96f74e68e7df | jenny-jt/HW-Accounting-Scripts | /melon_info.py | 439 | 3.65625 | 4 | """Print out all the melons in our inventory."""
melon_info = {
'Honeydew': [True, 0.99],
'Crenshaw': [False, 2.00],
'Crane': [False, 2.50],
'Casaba': [False, 2.50],
'Cantaloupe': [False, 0.99]
}
def print_melon(melon_info):
"""Print each melon with corresponding attribute information."""
for name, attributes in melon_info.items():
seedless, price = attributes
print(name.upper(), seedless, price) |
7c5c01a3d83699a0b7813d8d486c6e24fdf7d213 | VinceBy/newone | /python/001-PythonCooked/第一章 数据结构与算法/14-dictcum.py | 538 | 4.09375 | 4 | prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
#zip创建了一个迭代器,只能使用一次
min_price = min(zip(prices.values(), prices.keys()))
print("min_price:",min_price)
max_price = max(zip(prices.values(), prices.keys()))
print("max_price:",max_price)
print('==========================')
print(min(prices.values()))
print(max(prices.values()))
print("2222222222222222222222222222")
print(max(prices,key=lambda k:prices[k]))
print(min(prices,key=lambda k:prices[k]))
|
41bbf42e97518fdcaf99fdb6e344d919e466c20e | VinceBy/newone | /python/3day/1.py | 189 | 3.640625 | 4 | #99乘法表
#记录乘法表的长度
i=9
j=1
n=1
while j<=i:
m=1
while m<=j:
n=j*m
print('%d*%d=%-2d'%(m,j,n),end=" ")
m=m+1
print('\n')
j=j+1
|
db1aaeb45d9bbc3493dd74a71d4a17bbaf145046 | VinceBy/newone | /python/04-python高级/01-线程/05-多线程的缺点.py | 480 | 3.703125 | 4 | from threading import Thread
import time
g_num = 0
def test1():
global g_num
for i in range(1000000):
g_num +=1
print("-----test1-----g_num=%d"%g_num)
def test2():
global g_num
for i in range(1000000):
g_num += 1
print("----test2----g_num=%d"%g_num)
p1 = Thread(target=test1)
p1.start()
time.sleep(3) #取消屏蔽之后 再次运行注释,结果会不一样.
p2 = Thread(target=test2)
p2.start()
print("----g_num=%d----"%g_num)
|
a571691e818d6ab77a2397e4d23d9e929941f5dd | VinceBy/newone | /python/2 day/11.py | 83 | 3.734375 | 4 | i=0
while i<=100:
print("%d"%i,end="-")
i=i+1
if i==100:
print("\n")
|
959dc83e6aefc1ce5885b903a6124461f47fd60b | VinceBy/newone | /python/02-python高级-2/06-内建属性/02-内建函数.py | 1,269 | 3.515625 | 4 | from functools import reduce
print('='*30)
print('对map的操作')
#map(f,l1,l2)分别表示 f:函数 l1:操作数1 l2:操作数2
def f1(x,y):
return (x,y)
l1 = [0,1,2,3,4,5,6]
l2 = ['sun','M','T','W','T','F','S',]
l3 = map(f1,l1,l2)
print(list(l3))
print("="*30)
print("对filter的操作")
#filter(f,l) 分别表示 f:函数 True l:操作数
#过滤
a = filter(lambda x: x%2,[1,2,3,4,5,6,7])
print(list(a))
print('='*30)
print('对reduce的操作')
b = reduce(lambda x,y:x+y,['a','b','c','d'],'f')
print(str(b))
c = reduce(lambda x,y:x+y,[1,2,3,4,5,7],8)
print(int(c))
print("="*30)
print("对sort的操作")
a = [112,43,34,545,4,57,3,23,25,656,78,45]
a.sort()
print('正序'+str(a))
a.sort(reverse = True)
print('倒序'+str(a))
d = sorted([1,23,4,5,6,78,],reverse = 1)
print(d)
print("="*30)
#集合set
#去重
print("利用集合set去重方法")
print('原列表:')
a = [12,3,34,34,65,23,542,35,45,23]
print(a)
print("转换成集合:")
b = set(a)
print(b)
print("把集合转换成列表:")
a =list(b)
print(a)
print("="*30)
print('集合的交并差补')
a = 'abcdef'
b = set(a)
print(b)
A = 'bdf'
B = set(A)
print(B)
print("交集")
print(B&b)#交集
print('并集')
print(B|b)#并集
print('差集')
print(b-B)#差
print("对称差集")
print(b^B)
|
eec99a1173918d15dcc2abde23d40d29c451b5fd | VinceBy/newone | /python/suanfa/13-quick-sort.py | 825 | 3.78125 | 4 | def quick_sort(alist,first,last):
if first>=last:
return
mid_value = alist[first]
low = first
high = last
while low < high:
#high的游标左移
while low < high and alist[high] >= mid_value:
high -= 1
alist[low] = alist[high]
#low 右移
while low < high and alist[low] < mid_value:
low += 1
alist[high] = alist[low]
#从循环退出时low= high
alist[low] = mid_value
#对low 左边的列表执行快速排序
quick_sort(alist,first,low-1)
#对low 右边的列表排序
quick_sort(alist,low+1,last)
if __name__ == "__main__":
alist = [12,343,235,23,54,54,523,523,532,5]
print(alist)
n = len(alist)-1
quick_sort(alist, 0, n)
print(alist)
|
b0a9cdc7356c886265143290404671c56a7d069a | VinceBy/newone | /python/1016/01-保护对象的属性.py | 595 | 3.5625 | 4 | class Person():
def __init__(self,name,age):
#只要属性名前面有两个下划线,那么就表示私有的属性
#所谓私有,不能在外部使用 对象名.属性名获取
#
#原来没有__的属性,默认是 公有
self.__name = name
self.__age = age
def setNewAge(self,newAge):
if newAge>0 and newAge<=100:
self.__age = newAge
def getAge(self):
return self.__age
def __test(self):
print('-------------sdff------------')
laowang = Person('laowang',30)
laowang.setNewAge(31)
age = laowang.getAge()
print(age)
#私有方法无法访问
#laowang.__test()
|
d2b672a5c8dfcacb09f474dc279991ed76ad9afc | VinceBy/newone | /python/01-python高级-1/02-私有化/03-test.py | 426 | 3.59375 | 4 | class Test(object):
def __init__(self):
self.__num = 100
def setNum(self,newNum):
print("----------setter-------")
self.__num = newNum
def getNum(self):
print('-----------getter------')
return self.__num
num = property(getNum,setNum)
t =Test()
#t.__num = 200
#print(t.__num)
print(t.getNum())
t.setNum(50)
print(t.getNum())
print('-'*30)
t.num = 200
print(t.num)
|
b02653080a7a155f673e8bcd85171c44d13485e9 | VinceBy/newone | /python/001-PythonCooked/第一章 数据结构与算法/29-从字典中提取子集.py | 510 | 3.859375 | 4 |
prices = {
'ACME':45.23,
'AAPL':612.78,
'IBM':205.55,
'HPQ':37.20,
'FB':10.75
}
#make directonary of all prices
p1 = {key:value for key,value in prices.items() if value>200}
p1 = dict((key,value) for key,value in prices.items() if value>200)
print(p1)
#make a dictionary of tech stocks
tech_names = {'AAPL','IBM','HPQ','MSFT'}
tech_names = {key:value for key,value in prices.items() if key in tech_names}
p2 = {key:prices[key] for key in prices.keys()&tech_names }
print(tech_names,p2)
|
cf1a30476f4384a36235c62bd8a4b83a4d3678b2 | VinceBy/newone | /python/1017/03-类方法.py | 739 | 3.890625 | 4 | class Test(object):
#类属性
num = 0
#实例属性
def __init__(self):
#实例属性
self.age = 1
def test(self):
print(self.age)
#类方法
#可以由类名直接调用类属性或更改类属性
#也可以由类的对象调用
@classmethod
def setNum(cls,newNum):
cls.num = newNum
#静态方法
#可以由类直接调用不需要参数也可以由对象调用
@staticmethod
def printTest():
print('当前这个程序,是验证Test类的')
Test.printTest()
a = Test()
print(Test.num)
#a.setNum(200)
Test.setNum(300)
print(Test.num)
a.printTest()
#不允许使用类名访问实例属性
#print("Test.age")
#Test.printTest
|
87d55680fd9999f2b7676dfce3a813750fd56977 | ethanfebs/Minesweeper | /Minesweeper_Playable.py | 2,511 | 3.890625 | 4 | import random
nearby_offsets = [(-1, 0), (0, 1), (1, 0), (0, -1),
(-1, -1), (-1, 1), (1, -1), (1, 1)]
def print_board(board):
"""
Prints board in 2D format
board - 2D list of mine locations
"""
d = len(board)
# print upper border
for i in range(d):
print("==", end='')
print()
# print 2D list
for i in range(d):
for j in range(d):
print(board[i][j], end=' ')
print()
# print lower border
for i in range(d):
print("==", end='')
print()
def gen_board(d: int, n: int):
"""
Generates a d x d square board with randomly placed mines
d - dimension of the board
n - number of mines
"""
# select n integers from the set {0 ... d*d}
mines = random.sample(range(d*d), n)
# create d x d nested list with values preset to 0
board = [[0 for i in range(d)] for j in range(d)]
for mine in mines:
# for each mine location set corresponding board location to 1
board[mine // d][mine % d] = 1
return board
def query(q, board):
"""
Given a position and board as input
returns 'M' if there is a mine at pos
and returns the number of surrounding mines otherwise
q - position on board to query
board - 2D list of mine locations
"""
# if a mine exists at q return M
if(board[q[0]][q[1]] == 1):
return 'M'
count = 0
d = len(board)
# iterate over 8 surrounding board locations
for i in range(len(nearby_offsets)):
offset_i, offset_j = nearby_offsets[i]
pos = (q[0] + offset_i, q[1]+offset_j)
# if pos is out of bounds, continue
if(pos[0] < 0 or pos[0] >= d or pos[1] < 0 or pos[1] >= d):
continue
count += board[pos[0]][pos[1]]
# return number of surrounding mines
return count
d = 5
board = gen_board(d, 5)
kb = [["?" for i in range(d)] for j in range(d)]
score = 0
revealed = 0
while(True):
print_board(kb)
q = (int(input("Query X: ")), int(input("Query Y: ")))
if(kb[q[0]][q[1]] != '?'):
print("ERROR that location has already been queried")
continue
kb[q[0]][q[1]] = query(q, board)
revealed += 1
if(input("Flag as Mine(Y/N): ") == 'Y'):
if(kb[q[0]][q[1]] == 'M'):
score += 1
else:
print("ERROR flagged a clear space")
break
if(revealed == d**2):
print("Congratulations! Score: "+str(score))
break
|
b098be5aec4d590c64ed78d96a60fa82031ed103 | FerGrant/ProyectoFinal | /ConvergenciaDivergencia/codigo.py | 475 | 3.71875 | 4 | import numpy as np
import matplotlib.pyplot as plt
def xnew(x):
return (2*x**2 + 3)/ 5
x0 = 0
x1 = 0
itera = 0
x0array = np.zeros(100)
x1array = np.zeros(100)
xexe= np.zeros(100)
for i in range (10):
x1 = xnew(x0)
xexe[i] = 1
x0array[i]= x0
x1array[i]= x1
if abs (x1 - x0) < 0.00000001:
break
x0 = x1
itera += 1
print("La raíz es %.5f"%(x1))
print("Usando %i iteraciones"%(itera))
plt.plot(xexe,x0array,x1array)
plt.grid()
|
71a19ea2fdcbe4ee378e6859e127addf842acb16 | ashusaini1988/melbourne | /fibo.py | 333 | 3.984375 | 4 | def fibonacci(n):
'''
This is a fibonacci series function.
Comment
'''
a, b = 0, 1
while n > 0:
a, b = b, a+b
n -= 1
return a
#print fibonacci(1000)
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(2) == 1
assert fibonacci(3) == 2
assert fibonacci(5) == 5
|
865e8db4c54b14cfa8f9a4bb332938d240f471ea | ashusaini1988/melbourne | /complex_if.py | 150 | 3.5 | 4 | import sys
a = int(sys.argv[1])
if (a<50) and (a>0):
print "Minor"
elif (a>=50) and (a <1000):
print "Major"
else:
print "severe"
|
e64b941a4dcd7ab11fb3c54aed574abe25959efd | TimKillingsworth/Codio-Assignments | /src/dictionaries/person_dict1.py | 239 | 4.0625 | 4 | #Here's the code for Ringo
person = {'first_name':'Ringo','last_name':'Starr'}
#Add the new entries
person['instrument'] = 'drums'
person['born'] = 1940
#Print the result
print(person['first_name'] + ' was born in ' + str(person['born'])) |
b37520ed33b2fef924c8ea17c96d34799b78cc37 | TimKillingsworth/Codio-Assignments | /src/dictionaries/person_with_school.py | 306 | 4.34375 | 4 | #Create dictionary with person information. Assign the dictionary to the variable person
person={'name':'Lisa', 'age':29}
#Print out the contents of person
print(person)
#Add the school which Lisa attends
person['school'] = 'SNHU'
#Print out the contents of person after adding the school
print(person) |
38a0c28141a41c88aa2d7210c96ffce37abe6e30 | TimKillingsworth/Codio-Assignments | /src/lists/max.py | 317 | 3.8125 | 4 |
# Get our numbers from the command line
import sys
numbers= sys.argv[1].split(',')
numbers= [int(i) for i in numbers]
# Your code goes here
index = 0
maxVal = 0
maxIndex = index
for index in range(0, len(numbers)):
if numbers[index] > maxVal:
maxVal = numbers[index]
maxIndex = index
print(maxIndex) |
d54f448967d127688cc7b4d37c2a9db11aeb5d60 | TimKillingsworth/Codio-Assignments | /src/functions/red.py | 221 | 3.734375 | 4 |
# Get our input from the command line
import sys
text= sys.argv[1]
# Write your code here
def isRed(str):
found = str.find('red')
if found >= 0:
return True
else:
return False
print(str(isRed(text)))
|
5dff174f4164bb5933de55efcf58c74152287e51 | TimKillingsworth/Codio-Assignments | /src/dictionaries/list_of_dictionary.py | 336 | 4.59375 | 5 | #Create a pre-populated list containing the informatin of three persons
persons=[{'name':'Lisa','age':29,'school':'SNHU'},
{'name': 'Jay', 'age': 25, 'school': 'SNHU'},
{'name': 'Doug', 'age': 27, 'school': 'SNHU'}]
#Print the person list
print(persons)
#Access the name of the first person
print(persons[1]['name']) |
462acf5fc99890cc95f83ba89f716be60bb7e6fb | Joey238/python_laicode | /Laicode/binarysearch_recursion_2/bisearchtest.py | 5,569 | 4.09375 | 4 | """
Python standard library for binary search tree is bisection method,
which module named bisect
"""
import bisect
def binary_search_tree(sortedlist, target):
if not sortedlist:
return None
left = 0
right = len(sortedlist)-1
"""
1. 首先判断能不能进while loop, 如果只有一个元素在list里面, so, 我需要left <= right
2. right = mid-1, not right = mid. 因为如果我们只有一个元素在list里面,这个元素并不等于target,
那while loop会陷入死循环.
"""
while left <= right:
mid = left + (right - left)//2
if sortedlist[mid] == target:
return mid
if sortedlist[mid] > target:
right = mid - 1
else:
left = mid + 1
def bisect_right(a, x, lo=0, hi=None):
"""Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e <= x, and all e in
a[i:] have e > x. So if x already appears in the list, a.insert(x) will
insert just after the rightmost x already there.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
"""
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if x < a[mid]: hi = mid
else: lo = mid+1
return lo
def bisect_left(a, x, lo=0, hi=None):
"""Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e < x, and all e in
a[i:] have e >= x. So if x already appears in the list, a.insert(x) will
insert just before the leftmost x already there.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
"""
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if x > a[mid]: lo = mid+1
else: hi = mid
return lo
def binary_search(sarray, target):
if not sarray and isinstance(target, int):
raise 'sarray none'
left = 0
right = len(sarray) -1
while left<= right: # only < miss one element
mid = left + (right - left)//2
if sarray[mid] == target:
return mid
elif sarray[mid] < target:
right = mid -1
else:
left = mid + 1
def search_in_sorted_matrix(array, target):
print(array)
if not array or len(array[0]) == 0:
return 'NOT 2D ARRAY'
rows = len(array)
cols = len(array[0])
right = rows * cols -1
left = 0
while left <= right:
mid = left + (right - left)//2
r = mid // cols
c = mid % cols
if array[r][c] == target:
print(r,c)
return r, c
elif array[r][c] > target:
right = mid -1
else:
left = mid+1
def binary_searh_2(array, target):
if not array:
return none
left = 0
right = len(array) -1
while left < right-1: # if 左边界 == 右边界-1就相邻了, terminates
mid = left + (right - left)//2
if array[mid] == target:
return mid
elif array[mid] < target:
left = mid #if mid + 1 就错过了后面的值
else:
right = mid
#post processing: 不同的提议,稍微不一样
if abs(array[left] -target) < abs(array[right]-target):
return left
else:
return right
def binary_search_1st_Occur(array, target):
'''
return the index of the first occurrence of an element, say 5?
'''
left = 0
right = len(array) - 1
while left < right -1:
mid = left + (right - left)//2
if array[mid] == target:
right = mid # = mid -1 wrong: [4,5,5], right = mid -1 => right =4, miss掉了index=1的5, 不能把此target排除为非1st target! do not stop here, keeping track the left.
elif array[mid] < target:
mid = left + 1
else:
mid = right - 1
# post processing
if array[left] == target:
return left
elif array[right] == target:
return right
def k_closest_in_sorted_array(array, target, k):
if not isinstance(k, int) or not array:
return 'not valid input'
left = 0
right = len(array) -1
# find largets smaller or equal target element 's index in the array
while left < right-1:
mid = left +(right - left) //2
if array[mid] <= target:
left = mid
else:
right = mid
i = 0
kclosest = []
while i < k:
if right >= len(array) or left >= 0 and abs(array[left] -target) < abs(array[right]-target):
kclosest.append(left)
left -= 1
else:
kclosest.append(right)
right +=1
i +=1
return kclosest
def test():
# sortedList = [7, 8, 9, 10, 11, 12]
# target_po = binary_search(sortedList, 12)
# print(target_po)
# arr2D = [[3,5],[6,7],[8,9],[10,11],[21,23]]
# r,c = search_in_sorted_matrix(arr2D, 23)
# arr_1stocc =[4, 5,5]
# index = binary_search_1st_Occur(arr_1stocc, 5)
# print(index)
array = [1, 2, 3, 8,9 ]
kclosests = k_closest_in_sorted_array(array, 4, 2)
print(f'kcloests: {kclosests}')
if __name__ == "__main__":
test() |
061398644a97dd50567debc6204b049734d63fcd | Joey238/python_laicode | /Laicode/heap_graph_5/deque_demo.py | 376 | 4.0625 | 4 | from collections import deque
'''
deque:
- stacks and queues (double ended queue0
- thread-save, memory efficient appends and pops from either side of the deque O(1)
'''
queue = deque('Breadth-1st Search')
queue.append('algorithm')
queue.appendleft('hello')
for i in queue:
print(i)
print(f'size: {len(queue)}')
first=queue.popleft()
print(f'first: {first}')
|
99bbfce8bd57964e1a177617ef1e3307e6ec3953 | SumitB-2094/My_Money_Bank | /part-1 mini project.py | 810 | 4.0625 | 4 | name=(input("Enter your name:"))
print("-------------------------------------------------------------------------------------------")
a=print("1-Add expense:")
b=print("2-Read expense report:")
c=print("3-Email expense report:")
ans=int(input("Enter your choice:"))
def database():
global database
global ans
if ans==1:
a1=str(input("Topic of Expense:"))
b1=(input("Expense:"))
report_file=open(name+".txt",'a')
report_file.write(a1)
report_file.write("-->")
report_file.write("RS."+b1)
report_file.write("\n")
report_file.close()
database()
def asking_():
global database
d=print("4-Add expenses:")
e=print("5-LOGOUT")
ans1=int(input("Enter your choice:"))
if ans1==4:
return database()
asking_()
|
ba5f25636ecc3855c69a5e9a8c7548f3ea6f6e4a | Riicha/PythonChallenge | /PyBoss/Employee.py | 1,167 | 4.03125 | 4 | from datetime import datetime
class Employee:
"""Construct employee class and its members/operations"""
# constructor of employee class
def __init__(self,EmployeeId,Name,DOB,SSN,State):
"""Initialize the employee and return a new employee object. """
self.EmployeeId = EmployeeId
# Need to split the name into First Name and Last Name
name = Name.split(" ")
self.FirstName = name[0]
self.LastName = name[1]
self.DOB = DOB
self.SSN = SSN
self.State = State
# function to display employee details
def DisplayEmployee(self):
""" 1. It formats the DOB
2. Masks the SSN
3. Sends all the attributes as CSV
"""
#Need to change the date format
formatDate = datetime.strptime(self.DOB,'%Y-%m-%d').strftime("%m/%d/%Y")
#Need to mask the SSN
maskSSN = "***-**-"+self.SSN[-4:]
#The format for displaying the employee
#214,Sarah,Simpson,12/04/1985,***-**-8166,FL
return self.EmployeeId + "," + self.FirstName + "," + self.LastName + "," + formatDate + "," + maskSSN + "," + self.State
|
04b3b24788c05906c147423474ec64bcb76a781e | LiamLead/get-initials | /initials.py | 98 | 4.09375 | 4 | name = str(input("Name: ")).title()
for n in name:
if n.isupper():
print(n, end=" ")
|
72dc04ca9c52407b1149442b0d32f377c5e28a12 | nidiodolfini/descubra-o-python | /Guanabara/desafio95.py | 1,211 | 3.6875 | 4 | jogador = dict()
jogadores = list()
gols = list()
while True:
jogador.clear()
jogador['nome'] = str(input('Nome do Jogador: '))
partidas = int(input(f'Quantas partidas {jogador["nome"]} jogou? '))
for i in range(0, partidas):
gols.append(int(input(f"Quantos gols na partida {i + 1}: ")))
jogador['gols'] = gols[:]
jogador['total'] = sum(gols)
jogadores.append(jogador.copy())
gols.clear()
while True:
resp = str(input("Quer continuar:")).upper()[0]
if resp in 'SN':
break
print('Erro responda apenas S ou N.')
if resp in "N":
break
print('-='*30)
print(jogadores)
print('-='*30)
print(f'{"COD":<5}{"Nome":<10}{"gols"}{"total":>15}')
for i, v in enumerate(jogadores):
print(f'{i:<2} {v["nome"]:<10} {v["gols"]} {v["total"]:>10}')
print('-='*30)
resp = 0
while resp != 999:
resp = int(input("Mostrar dados de qual jogador (999 para)? "))
if resp < len(jogadores):
print(f'Levantamento do jogador: {jogadores[resp]["nome"]}')
for k, i in enumerate(jogadores[resp]["gols"]):
print(f'No jogo {k} fez {i} gols')
elif resp < 999:
print("Digite um valor valido")
|
e7663c7fb9c123e506298ec2a308be41a5348cce | nidiodolfini/descubra-o-python | /URI/1010.py | 545 | 3.859375 | 4 | # a,w,e = input().split(" ") # pega 3 valores na mesma linha e atribui a variáveis
# # Converte o valor para os tipos necessários
# a = int(a)
# w = int(w)
# e = float(e)
lista = input().split(" ")
lista2 = input().split(" ")
codigo_peca = int(lista[0])
numero_de_peca = int(lista[1])
valor_pecas = float(lista[2])
codigo_peca2 = int(lista2[0])
numero_de_peca2 = int(lista2[1])
valor_pecas2 = float(lista2[2])
valor_total = (numero_de_peca * valor_pecas) + (numero_de_peca2 * valor_pecas2)
print("VALOR A PAGAR: R$ %0.2f" %valor_total) |
0b0b1b9c830b91417b2c0e2095378548dee688f6 | nidiodolfini/descubra-o-python | /URI/1012.py | 392 | 3.734375 | 4 | dados = input().split(" ")
a = float(dados[0])
b = float(dados[1])
c = float(dados[2])
pi = 3.14159
triangulo = (a * c) / 2
circulo = (c ** 2) * pi
trapezio = (( a + b) * c) /2
quadrado = b * b
retangulo = a * b
print("TRIANGULO: %0.3f" %triangulo)
print("CIRCULO: %0.3f" %circulo)
print("TRAPEZIO: %0.3f" %trapezio)
print("QUADRADO: %0.3f" %quadrado)
print("RETANGULO: %0.3f" %retangulo) |
354337fe40f7e1df55cb6c5e935499841b20a20d | nidiodolfini/descubra-o-python | /Guanabara/desafio89.py | 1,631 | 3.828125 | 4 | ficha = list()
while True:
nome = str(input('Nome: '))
nota1 = float(input('Nota 1: '))
nota2 = float(input('Nota 2: '))
media = (nota1 + nota2) / 2
ficha.append([nome, [nota1, nota2], media])
resp = str(input('Quer continuar? S/N: '))
if resp in 'Nn':
break
print('-='*30)
print(f'{"No.":<4}{"Nome":<10}{"Média":>8}')
print('_'*26)
for i, a in enumerate(ficha):
print(f'{i:<4}{a[0]:<10}{a[2]:>8.1f}')
while True:
print('_'*26)
opc = int(input('Mostrar nota de qual aluno? (999 interrompe): '))
if opc == 999:
print('FINALIZANDO')
break
if opc <= len(ficha) -1:
print(f'Notas de {ficha[opc][0]} são {ficha[opc][1]} ')
print('Volte sempre')
# dadosAlunosTemp = list()
# dadosAlunos = list()
# print('Digita o nome e as notas dos alunos: ')
# while True:
# dadosAlunosTemp.append(str(input('Digite o nome do aluno: ')))
# dadosAlunosTemp.append(float(input('Digite a primeira nota: ')))
# dadosAlunosTemp.append(float(input('Digite a segunda nota: ')))
#
# dadosAlunos.append(dadosAlunosTemp[:])
# dadosAlunosTemp.clear()
# resp = str(input('Quer continuar? '))
# if resp in 'Nn':
# break
# print(f'NO. Nome Média')
# for i, l in enumerate(dadosAlunos):
# print(f'{i:^3} {l[0]:^8} {(l[1]+l[2])/2}')
#
# interrompe = 0
# while interrompe != 999:
# interrompe = int(input('mostrar nota de qual aluno: (999 interrompe): '))
# if interrompe <= len(dadosAlunos):
# print(f'Notas de {dadosAlunos[interrompe][0]} são [{dadosAlunos[interrompe][1], dadosAlunos[interrompe][2]}]')
# print('saiu') |
855d056333d0d84f9a450399717f640238d9fe16 | nidiodolfini/descubra-o-python | /CS50/marioLess.py | 240 | 3.890625 | 4 | tamanho = 3
for i in range(tamanho):
for j in range(1,tamanho+1):
if j == tamanho - i:
for b in range(tamanho, j-1, -1):
print("#", end='')
break
print(" ", end='')
print() |
850a2be484f2de91195eadc731948930aaeb9acc | nidiodolfini/descubra-o-python | /Guanabara/desafio76.py | 359 | 3.53125 | 4 | listagem = ( 'Lapis', 1.75,
'Borracha', 2.00,
'Carderno', 20.25,
'Estojo', 9.99 )
print('-'* 40)
print(f'{"Listagem de Preços":^40}')
print('-'*40)
for pos in range(0, len(listagem)):
if pos % 2 == 0:
print(f'{listagem[pos]:.<30}', end='')
else:
print(f'R${listagem[pos]:>7.2f}')
print('-'*40)
|
765c0c8fe31f4e036da13d40ae79199a85395466 | nidiodolfini/descubra-o-python | /URI/1035.py | 242 | 3.796875 | 4 | numeros = input().split(" ")
a = int(numeros[0])
b = int(numeros[1])
c = int(numeros[2])
d = int(numeros[3])
if ((a % 2 == 0) and (b > c) and (d > a) and ( c + d > a + b)):
print("Valores aceitos")
else:
print("Valores nao aceitos") |
f4f5f02467f01e945a826b16feffa495e89ee51f | nidiodolfini/descubra-o-python | /Guanabara/desafio86.py | 263 | 3.875 | 4 | lista = [[0,0,0], [0,0,0],[0,0,0]]
for l in range(0,3):
for c in range(0,3):
lista[l][c] = int(input(f'Digite um valor na posição: [{l},{c}] '))
for l in range(0,3):
for c in range(0,3):
print(f'[{lista[l][c]:^5}]', end='')
print()
|
bfadb9cad0df6a7f350498a4a4bf0ef05587d6c7 | nidiodolfini/descubra-o-python | /Guanabara/desafio102.py | 335 | 3.734375 | 4 | def fatorial(num=1, show=True):
if show:
fat = num
for i in range(1, num + 1):
if fat != 1:
print(f'{fat}', end=' x ')
else:
print(f'{fat}', end=' = ')
fat -= 1
for i in range(1, num):
num *= i
print(f'{num}')
fatorial(5, True)
|
92695e87a783152773fc6fc09851190db2a6d1c7 | nidiodolfini/descubra-o-python | /Guanabara/desafio84.py | 800 | 3.75 | 4 | temp = []
dados = []
maior = menor = 0
while True:
temp.append(str(input('digite o nome: ')))
temp.append(int(input('Digite o peso: ')))
if len(dados) == 0:
maior = menor = temp[1]
else:
if temp[1] > maior:
maior = temp[1]
if temp[1] < menor:
menor = temp[1]
dados.append(temp[:])
temp.clear()
print('menor peso' , menor, ' maior peso' , maior)
resp = str(input('quer continuar: '))
if resp in 'Nn':
break
print('os mais pesados são: ', end='')
for p in dados:
if p[1] == maior:
print(f'[{p[0]}]', end='')
print()
print('os menores pesos foram: ', end='')
for p in dados:
if p[1] == menor:
print(f'[{p[0]}]', end='')
print()
print(f' numeros de pessoas na lista {len(dados)}') |
62e1b57f1ad0ba73813481a24ba2159fd3d5d714 | Eunsol-Lee/projectEulerPythonSolve | /p14 Longest Collatz sequence.py | 370 | 3.671875 | 4 | # Problem 14
# Longest Collatz sequence
#
# By Eunsol
num = {}
num[1] = 1
def seq(x):
if x in num:
return num[x]
if x % 2:
num[x] = seq(3 * x + 1) + 1
else:
num[x] = seq(x / 2) + 1
return num[x]
largest = 0
for i in range(1, 1000001):
if largest < seq(i):
largest = seq(i)
index = i
print (index, largest)
|
1e758a4591812d3906e4cf6d95a20873f3769720 | jerryAnu/Detecting-Depression-from-Physiological-Features-on-the-basis-of-Neural-Networks-and-Genetic-Algorit | /nn.py | 16,179 | 4.125 | 4 | """
This file is used to detect levels of depression by using a neural network model.
This model is a three-layer network.
This model is not combined with the GIS technique or genetic algorithm.
"""
# import libraries
import pandas as pd
import torch
"""
Define a neural network
Here we build a neural network with one hidden layer.
input layer: 85 neurons, representing the physiological features of observers
hidden layer: 60 neurons, using Sigmoid as activation function
output layer: 4 neurons, representing various levels of depression
The network will be trained with Adam as an optimiser,
that will hold the current state and will update the parameters
based on the computed gradients.
Its performance will be evaluated using cross-entropy.
"""
# define a customised neural network structure
class TwoLayerNet(torch.nn.Module):
def __init__(self, n_input, n_hidden, n_output):
"""
This function is to initialize the net model; specifically, we define
a linear hidden layer and a linear output layer.
:param n_input: the number of input neurons
:param n_hidden: the number of hidden neurons
:param n_output: the number of output neurons
"""
super(TwoLayerNet, self).__init__()
# define linear hidden layer output
self.hidden = torch.nn.Linear(n_input, n_hidden)
# define linear output layer output
self.out = torch.nn.Linear(n_hidden, n_output)
def forward(self, x):
"""
This function is to define the process of performing forward pass,
that is to accept a Variable of input data, x, and return a Variable
of output data, y_pred.
:param x: a variable of input data
:return: a variable of output data
"""
# get hidden layer input
h_input = self.hidden(x)
# use dropout function to reduce the impact of overfitting
h_input = torch.dropout(h_input, p=0.5, train=True)
# define activation function for hidden layer
h_output = torch.sigmoid(h_input)
# get output layer output
y_pred = self.out(h_output)
return y_pred
def prec_reca_f1(confusion):
"""
This function is used to calculate evaluation measures of this task
including the precision, recall and F1-score.
Precision: the number of true positive classifications divided by the number of
true positive plus false positive classifications.
Recall: the number of true positive classifications divided by the number of
true positive plus false negative classifications.
F1-score: 2 * Precision * Recall / (Precision + Recall)
Besides, this function also calculates overall accuracy.
Overall accuracy: the sum of correct predictions for all levels divided by
the number of data points.
:param confusion: a confusion matrix
:return: the precision, recall and F1-score for all levels of depression
as well as overall accuracy
"""
# calculate the numbers of true positive classifications, true positive
# plus false positive classifications and true positive plus
# false negative classifications for all four levels of depression.
tp_none, tp_fp_none, tp_fn_none = confusion[0, 0], sum(confusion[:, 0]), sum(confusion[0, :])
tp_mild, tp_fp_mild, tp_fn_mild = confusion[1, 1], sum(confusion[:, 1]), sum(confusion[1, :])
tp_moderate, tp_fp_moderate, tp_fn_moderate = confusion[2, 2], sum(confusion[:, 2]), sum(confusion[2, :])
tp_severe, tp_fp_severe, tp_fn_severe = confusion[3, 3], sum(confusion[:, 3]), sum(confusion[3, :])
# avoid divided by zero and calculate the precision
if tp_fp_none == 0:
precision_none = 0
else:
precision_none = tp_none / tp_fp_none
if tp_fp_mild == 0:
precision_mild = 0
else:
precision_mild = tp_mild / tp_fp_mild
if tp_fp_moderate == 0:
precision_moderate = 0
else:
precision_moderate = tp_moderate / tp_fp_moderate
if tp_fp_severe == 0:
precision_severe = 0
else:
precision_severe = tp_severe / tp_fp_severe
# calculate the average precision
precision_average = (precision_none + precision_mild + precision_moderate + precision_severe) / 4
# avoid divided by zero and calculate the recall
if tp_fn_none == 0:
recall_none = 0
else:
recall_none = tp_none / tp_fn_none
if tp_fn_mild == 0:
recall_mild = 0
else:
recall_mild = tp_mild / tp_fn_mild
if tp_fn_moderate == 0:
recall_moderate = 0
else:
recall_moderate = tp_moderate / tp_fn_moderate
if tp_fn_severe == 0:
recall_severe = 0
else:
recall_severe = tp_severe / tp_fn_severe
# calculate the average recall
recall_average = (recall_none + recall_mild + recall_moderate + recall_severe) / 4
# avoid divided by zero and calculate the F1-score
if precision_none == 0 and recall_none == 0:
f1_score_none = 0
else:
f1_score_none = 2 * precision_none * recall_none / (precision_none + recall_none)
if precision_mild == 0 and recall_mild == 0:
f1_score_mild = 0
else:
f1_score_mild = 2 * precision_mild * recall_mild / (precision_mild + recall_mild)
if precision_moderate == 0 and recall_moderate == 0:
f1_score_moderate = 0
else:
f1_score_moderate = 2 * precision_moderate * recall_moderate / (precision_moderate + recall_moderate)
if precision_severe == 0 and recall_severe == 0:
f1_score_severe = 0
else:
f1_score_severe = 2 * precision_severe * recall_severe / (precision_severe + recall_severe)
# calculate the average F1-score
f1_score_average = (f1_score_none + f1_score_mild + f1_score_moderate + f1_score_severe) / 4
# calculate overall accuracy
overall_accuracy = (confusion[0, 0] + confusion[1, 1] + confusion[2, 2] + confusion[3, 3]) / (torch.sum(confusion))
# combine the precision, recall, the F1-score and overall accuracy
res = [[precision_none, precision_mild, precision_moderate, precision_severe],
[recall_none, recall_mild, recall_moderate, recall_severe],
[f1_score_none, f1_score_mild, f1_score_moderate, f1_score_severe],
[precision_average, recall_average, f1_score_average, overall_accuracy]]
return res
if __name__ == "__main__":
# load training set and testing set
train_data = pd.read_csv("train.csv")
test_data = pd.read_csv("test.csv")
# the number of features
n_features = train_data.shape[1] - 1
# split training data into input and target
# the first column is target; others are features
train_input = train_data.iloc[:, 1:n_features + 1]
train_target = train_data.iloc[:, 0]
# normalise training data by columns
for column in train_input:
train_input[column] = train_input.loc[:, [column]].apply(lambda x: (x - x.min()) /
(x.max() - x.min()))
# This part is used to compare different methods of normalization
# normalise for comparison (subtracted from the mean and divided by the standard deviation)
# for column in train_input:
# train_input[column] = train_input.loc[:, [column]].apply(lambda x: (x - x.mean()) / x.std())
# split testing data into input and target
# the first column is target; others are features
test_input = test_data.iloc[:, 1:n_features + 1]
test_target = test_data.iloc[:, 0]
# normalise testing input data by columns
for column in test_input:
test_input[column] = test_input.loc[:, [column]].apply(lambda x: (x - x.min()) /
(x.max() - x.min()))
# This part is used to compare different methods of normalization
# normalise for comparison (subtracted from the mean and divided by the standard deviation)
# for column in test_input:
# test_input[column] = test_input.loc[:, [column]].apply(lambda x: (x - x.mean()) / x.std())
# create Tensors to hold inputs and outputs for training data
X = torch.Tensor(train_input.values).float()
Y = torch.Tensor(train_target.values).long()
# create Tensors to hold inputs and outputs for testing data
X_test = torch.Tensor(test_input.values).float()
Y_test = torch.Tensor(test_target.values).long()
# define the number of input neurons, hidden neurons, output neurons,
# learning rate and training epochs
input_neurons = n_features
hidden_layer = 60
output_neurons = 4
learning_rate = 0.01
num_epochs = 500
# define a neural network using the customised structure
net = TwoLayerNet(input_neurons, hidden_layer, output_neurons)
# define loss function
loss_func = torch.nn.CrossEntropyLoss()
# define optimiser
optimiser = torch.optim.Adam(net.parameters(), lr=learning_rate)
# This part is used to compare different methods of optimiser
# optimiser = torch.optim.Adadelta(net.parameters(), lr=learning_rate)
# optimiser = torch.optim.Adagrad(net.parameters(), lr=learning_rate)
# store all losses for visualisation
all_losses = []
# store the previous recorded overall accuracy
previous_accuracy = 0
# count how many times overall accuracy drops compared with
# the previous recorded one.
# if the value is more than 1, then stop training.
count = 0
# train a neural network
for epoch in range(num_epochs):
# perform forward pass: compute predicted y by passing x to the model.
Y_pred = net(X)
# compute loss
loss = loss_func(Y_pred, Y)
all_losses.append(loss.item())
# print progress
if epoch % 50 == 0:
# use softmax function for classification
Y_pred = torch.softmax(Y_pred, 1)
# convert four-column predicted Y values to one column for comparison
_, predicted = torch.max(Y_pred, 1)
# create a confusion matrix, indicating for every level (rows)
# which level the network guesses (columns).
confusion = torch.zeros(output_neurons, output_neurons)
# see how well the network performs on different categories
for i in range(train_data.shape[0]):
actual_class = Y.data[i]
predicted_class = predicted.data[i]
confusion[actual_class][predicted_class] += 1
# calculate evaluation measures and print the loss as well as
# overall accuracy
res = prec_reca_f1(confusion)
print('Epoch [%d/%d] Loss: %.4f Overall accuracy: %.2f %%'
% (epoch + 1, num_epochs, loss.item(), 100 * res[3][3]))
# if current overall accuracy is less than the previous one, "count"
# is added one; otherwise, set "count" to zero and store current
# overall accuracy
# if "count" is more than 1, stop training
if previous_accuracy >= res[3][3]:
# "count" is added one
count += 1
if count > 1:
# stop training
count = 0
break
else:
# otherwise, set "count" to zero
count = 0
# store current overall accuracy
previous_accuracy = res[3][3]
# clear the gradients before running the backward pass.
net.zero_grad()
# perform backward pass
loss.backward()
# calling the step function on an Optimiser makes an update to its
# parameters
optimiser.step()
"""
Evaluating the Results
To see how well the network performs on different categories, we will
create a confusion matrix, indicating for every level (rows)
which level the network guesses (columns).
"""
# create a confusion matrix
confusion = torch.zeros(output_neurons, output_neurons)
# perform forward pass: compute predicted y by passing x to the model.
Y_pred = net(X)
# convert four-column predicted Y values to one column for comparison
_, predicted = torch.max(Y_pred, 1)
# calculate the confusion matrix and print the matrix
for i in range(train_data.shape[0]):
actual_class = Y.data[i]
predicted_class = predicted.data[i]
confusion[actual_class][predicted_class] += 1
print('')
print('Confusion matrix for training:')
print(confusion)
# calculate evaluation measures and print the evaluation measures
res_train = prec_reca_f1(confusion)
print('Test of Precision of None: %.2f %% Precision of Mild: %.2f %% Precision of Moderate: %.2f %% Precision'
' of Severe: %.2f %%' % (100 * res_train[0][0], 100 * res_train[0][1],
100 * res_train[0][2], 100 * res_train[0][3]))
print('Test of Recall of None: %.2f %% Recall of Mild: %.2f %% Recall of Moderate: %.2f %% Recall'
' of Severe: %.2f %%' % (100 * res_train[1][0], 100 * res_train[1][1],
100 * res_train[1][2], 100 * res_train[1][3]))
print('Test of F1 score of None: %.2f %% F1 score of Mild: %.2f %% F1 score of Moderate: %.2f %% F1 score'
' of Severe: %.2f %%' % (100 * res_train[2][0], 100 * res_train[2][1],
100 * res_train[2][2], 100 * res_train[2][3]))
print('Average precision: %.2f %% Average recall: %.2f %% Average F1 score: %.2f %%'
% (100 * res_train[3][0], 100 * res_train[3][1], 100 * res_train[3][2]))
print('Overall accuracy: %.2f %%' % (100 * res_train[3][3]))
"""
Test the neural network
Pass testing data to the built neural network and get its performance
"""
# test the neural network using testing data
# It is actually performing a forward pass computation of predicted y
# by passing x to the model.
# Here, Y_pred_test contains four columns
Y_pred_test = net(X_test)
# get prediction
# convert four-column predicted Y values to one column for comparison
_, predicted_test = torch.max(Y_pred_test, 1)
"""
Evaluating the Results
To see how well the network performs on different categories, we will
create a confusion matrix, indicating for every iris flower (rows)
which class the network guesses (columns).
"""
# create a confusion matrix
confusion_test = torch.zeros(output_neurons, output_neurons)
# calculate the confusion matrix and print the matrix
for i in range(test_data.shape[0]):
actual_class = Y_test.data[i]
predicted_class = predicted_test.data[i]
confusion_test[actual_class][predicted_class] += 1
print('')
print('Confusion matrix for testing:')
print(confusion_test)
# calculate evaluation measures and print the evaluation measures
res_test = prec_reca_f1(confusion_test)
print('Test of Precision of None: %.2f %% Precision of Mild: %.2f %% Precision of Moderate: %.2f %% Precision'
' of Severe: %.2f %%' % (100 * res_test[0][0], 100 * res_test[0][1],
100 * res_test[0][2], 100 * res_test[0][3]))
print('Test of Recall of None: %.2f %% Recall of Mild: %.2f %% Recall of Moderate: %.2f %% Recall'
' of Severe: %.2f %%' % (100 * res_test[1][0], 100 * res_test[1][1], 100 * res_test[1][2],
100 * res_test[1][3]))
print('Test of F1 score of None: %.2f %% F1 score of Mild: %.2f %% F1 score of Moderate: %.2f %% F1 score'
' of Severe: %.2f %%' % (100 * res_test[2][0], 100 * res_test[2][1],
100 * res_test[2][2], 100 * res_test[2][3]))
print('Average precision: %.2f %% Average recall: %.2f %% Average F1 score: %.2f %%'
% (100 * res_test[3][0], 100 * res_test[3][1], 100 * res_test[3][2]))
print('Overall accuracy: %.2f %%' % (100 * res_test[3][3]))
|
e076131a45b7aa04318f73ea7e9d163d1dbf1cf2 | Nireka74/gy-sbj | /excise/duixiang.py | 1,147 | 3.71875 | 4 | #类的封装
# class aaa():
#类变量
# pub_res = '公有变量'
# _pri_res = '私有变量'
# __pri_res = '私有变量2'
#类变量通过类直接调用,双下划线私有变量不能调用。单下划线私有变量能调用,不能修改。
# print(aaa.pub_res)
# print(aaa._pri_res)
# class aaa():
# 实例方法
# def pub_function(self):
# print('公有方法')
# def _pri_function(self):
# print('私有方法')
# def __pri_function(self):
# print('私有方法2')
#实例方法通过对象调用
# print(aaa().pub_function())
# print(aaa()._pri_function())
#类的继承
class Woman():
money =1000000
house =10
__yi_wu = '裙子'
def __init__(self,a):
self.a = a
def skill(self):
print('吃喝玩乐')
# w = Woman(123)
# print(w.a)
# class Man(Woman):
# hobby = '花钱'
# def __init__(self,a):
# super().__init__(a)
#
# def skill(self):
# print('白嫖')# 方法重写
# super().skill()
#
# m = Man(123)
# print(m.skill())
# print(Man.money)
# print(m.house)
# print(m.hobby)
# m.skill()
# print(m.a)
|
47f7f996f21d85e5b7613aa14c1a6d2752faaa82 | zaidjubapu/pythonjourney | /h5fileio.py | 1,969 | 4.15625 | 4 | # file io basic
'''f = open("zaid.txt","rt")
content=f.read(10) # it will read only first 10 character of file
print(content)
content=f.read(10) # it will read next 10 character of the file
print(content
f.close()
# must close the file in every program'''
'''f = open("zaid.txt","rt")
content=f.read() # it will read all the files
print(1,content) # print content with one
content=f.read()
print(2,content) # it will print only 2 because content are printed allready
f.close()'''
'''if we want to read the file in a loop with
f = open("zaid.txt","rt")
for line in f:
print(line,end="")'''
# if want to read character in line by line
'''f = open("zaid.txt","rt")
content=f.read()
for c in content:
print(c)'''
#read line function
'''f = open("zaid.txt","rt")
print(f.readline()) # it wiil read a first line of the file
print(f.readline()) # it will read next line of the file it will give a space because the new line wil already exist in that
f.close()'''
# readlines functon wil use to create a list of a file with 1 line as 1 index
'''f = open("zaid.txt","rt")
print(f.readlines())'''
# writ functions
'''f=open("zaid.txt","w")
f.write("hello how are you") # replce the content with what we have written
f.close()'''
'''f=open("zaid1.txt","w") # the new file wil come with name zaid1
f.write("hello how are you") # the new file will created and the content will what we have written
f.close()'''
# append mode in write
'''f=open("zaid2.txt","a") # the new file wil come with name zaid1 and will append the character at the end how much we run the program
a=f.write("hello how are you\n") # the new file will created and the content will what we have written
print(a) # it will display the no of character in the file
f.close()'''
#if want to use read and write function simultaneously
f=open("zaid.txt","r+") #r+ is used for read and write
print(f.read())
f.write("thankyou")
f.write("zaid")
f.close()
|
6a72313370336294491913d7eb3b50aaa6c81b65 | zaidjubapu/pythonjourney | /h22operatoroverloadingdunder.py | 970 | 3.9375 | 4 | class Employees:
no_of_l=8
def __init__(self,aname,asalary):
self.name=aname
self.salary=asalary
def printdetails(self):
return f"Namae is {self.name}. salary is {self.salary}"
@classmethod
def change_leaves(cls,newleaves):
cls.no_of_l=newleaves
def __add__(self, other):
return self.salary+other.salary
def __repr__(self):
return self.printdetails()
def __str__(self):
return self.printdetails()
harry=Employees("harry",500)
larry=Employees("zaid",600)
print(harry+larry) # it will run untill dunder method is created
# run of repr method
print(harry) # to run this type of method we create repr method
# run of str method: automatically it will run str method untill it will not define be repr
print(harry) # it wil run str method
print(str(harry)) # this also run str method.. if str mthod is not there then also this eqn will run
print(repr(harry)) # it wil run repr method
|
014987c11429d51e6d1462e3a6d0b7fb97b11822 | zaidjubapu/pythonjourney | /enumeratefunction.py | 592 | 4.59375 | 5 | '''enumerate functions: use for to easy the method of for loop the with enumerate method
we can find out index of the list
ex:
list=["a","b","c"]
for index,i in enumerate(list):
print(index,i)
'''
''' if ___name function :
print("and the name is ",__name__)# it will give main if it is written before
if __name__ == '__main__': # it is used for if we want to use function in other file
print("hello my name is zaid")'''
'''
join function:
used to concatenat list in to string
list=["a","b","c","d"]
z=" and ".join(list) #used to concatenate the items of the sting
print(z)'''
|
50e523c196fc0df4be3ce6acab607f623119f4e1 | zaidjubapu/pythonjourney | /h23abstractbaseclassmethod.py | 634 | 4.21875 | 4 | # from abc import ABCMeta,abstractmethod
# class shape(metaclass=ABCMeta):
# or
from abc import ABC,abstractmethod
class shape(ABC):
@abstractmethod
def printarea(self):
return 0
class Rectangle(shape):
type= "Rectangle"
sides=4
def __init__(self):
self.length=6
self.b=7
# def printarea(self):
# return self.length+self.b
harry=Rectangle() # if we use abstract method before any function. then if we inherit the class then it gives an errr
# untill that method is not created inside that class
# now it wil give error
# we cant create an object of abstract base class method
|
dfc07a2dd914fa785f5c9c581772f92637dea0a7 | zaidjubapu/pythonjourney | /h9recursion.py | 1,167 | 4.28125 | 4 | '''
recursive and iterative method;
factorial using iterative method:
# using iterative method
def factorialiterative(n):
fac=1
for i in range(n):
print(i)
fac=fac*(i+1)
return fac
# recusion method which mean callingthe function inside the function
def factorialrecursion(n):
if n==1:
return 1
else:
z= n * factorialrecursion(n-1)
return z
n=int(input("enter the fact n0"))
print("the factorial iteration is", factorialiterative(n))
print("the factorial recursion is", factorialrecursion(n))
print(factorialrecursion(3))'''
# fibonaccis series:0 1 1 2 3 5 8 13 which adding the backwaard two numbers
'''
def fibonacci(n):
if n==1:
return 0
elif n==2:
return 1
elif n==3: # if we want 3 addition
return 1
return fibonacci(n-1) + fibonacci(n-2)# + fibonacci(n-3) if we want 3 addition in line
n=int(input("enter the nuber"))
print(fibonacci(n))'''
def factorialrecursion(n):
if n==1:
return 1
else:
z= n + factorialrecursion(n-1)
return z
n=int(input("enter the fact n0"))
print("the factorial iteration is", factorialrecursion(n)) |
cb8b23c641448a238fd11bdfc9ea7b8116d8991e | zaidjubapu/pythonjourney | /exe7.py | 857 | 3.53125 | 4 | sentences=["python is python very good laguage","python python is python is cool","python is awesome","javascript is good"]
import time
# join=sentences[0].split()
# print(join)
inp=[x for x in (input("enter the word you want to search").split())]
searchmatch=[]
# dict1={}
c=time.time()
for search in inp:
a = 0
for i in sentences:
a = 0
d=i.split()
for j in d:
if j == search:
a+=1
searchmatch.append(a)
print(searchmatch)
f=[]
b=time.time()-c
# print(f'{e} result found in {b} second')
# print(searchmatch[::-1])
# print(dict1)
k=[]
for i in range(len(searchmatch)/2):
s=searchmatch[i+4]
k.append(s)
l=sorted((zip(k,sentences)),reverse=True)
print(l)
for i,v in l:
if i>=1:
f.append(v)
e=len(f)
print(f'{e} result found in {b} second')
for i in f:
print(i)
|
b7544654e79a09747fc2ab42643cf265a7a77dc4 | zaidjubapu/pythonjourney | /rough.py | 1,135 | 3.625 | 4 | # # # a="hello"
# # # b="python"
# # # print(a,b,"fish",sep="zain",end="!")
# # # print(a,b,"zain",end="!")
# # a=["ima zaid","iam zuha"]
# # z=a.sort()
# # print(a)
# # import pyaudio
# b=open("zaid.txt",'r')
# for a in b:
# a=a.rstrip()
# print(a)
# import pyaudio1
#to tell you in wich your you will become 100 year old
class age:
cy=2020
# def __init__(self,a):
# self.ag=a
# self.ye=a
def year(self):
print(f"you will become 100 year old at the year{a+100}")
def ages(self):
print(f"you will become 100 year old at the year {age.cy-a + 100}")
if __name__ == '__main__':
print("to tell you in which year you will become 100 year old")
while True:
try:
classage=age()
a=int(input("please enter year of birth or your current age : "))
if a>200:
classage.year()
else:
classage.ages()
except Exception as e:
print(f"the error is {e}")
b=input("press s to continue or n to exit")
if b == "s":
continue
else:
break
|
22773f2a2796ae9a493020885a6e3a987047e7f8 | Pegasus-01/hackerrank-python-works | /02-division in python.py | 454 | 4.125 | 4 | ##Task
##The provided code stub reads two integers, a and b, from STDIN.
##Add logic to print two lines. The first line should contain the result of integer division, a// b.
##The second line should contain the result of float division, a/ b.
##No rounding or formatting is necessary.
if __name__ == '__main__':
a = int(input())
b = int(input())
intdiv = a//b
floatdiv = a/b
print(intdiv)
print(floatdiv)
|
6f31574f1e99ad506ecfdc4d1d74dc292f1083be | YuyangZhang/leetcode | /81.py | 1,089 | 3.515625 | 4 | class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return an integer
def search(self, A, target):
B=list(set(A))
return find(B,target,0,len(B)-1)
def find(A,target,start,end):
if A==[]:
return False
if start+1<len(A):
if A[start]==A[start+1]:
del A[start]
return find(A,target,start,end-1)
if end-1>0:
if A[end]==A[end-1]:
del A[end]
return find(A,target,start,end-1)
if start==end:
if target==A[end]:
return True
else:
return False
if A[start]==A[end]:
del A[end]
return find(A,target,start,end-1)
elif A[start]<A[end]:
if target<A[start] or target>A[end]:
return False
else:
return find(A,target,start,int((start+end)/2)) or find(A,target,int((start+end)/2)+1,end)
else:
return find(A,target,start,int((start+end)/2)) or find(A,target,int((start+end)/2)+1,end)
s=Solution()
print(s.search([0,0,1,1,2,0],2))
|
d8ef559f6a0a87acaa355bf458504cfa53afa5dd | YuyangZhang/leetcode | /153.py | 605 | 3.59375 | 4 | class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return an integer
def findMin(self, num):
return findPeak(num,0,len(num)-1)
def findPeak(A,start,end):
if A[start]<A[end] or start==end:
return A[start]
else:
if end-start==1:
return A[end]
elif A[int((start+end)/2)]>A[int((start+end)/2)+1]:
return A[int((start+end)/2)+1]
else:
return min(findPeak(A,start,int((start+end)/2)),findPeak(A,int((start+end)/2)+1,end))
s=Solution()
print(s.findMin([3,1,2]))
|
4bea0d3f0b98fe2b2749aa0a2587efb6d7bc1dcb | YuyangZhang/leetcode | /2.py | 935 | 3.59375 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @return a ListNode
def addTwoNumbers(self, l1, l2):
i1=1
i2=1
num1=0
num2=0
while True:
num1+=l1.val*i1
if l1.next==None:
break
else:
l1=l1.next
i1*=10
while True:
num2+=l2.val*i2
if l2.next==None:
break
else:
l2=l2.next
i2*=10
num=num1+num2
print(num)
pre=ListNode(num%10)
l=pre
for i in range(1,len(str(num))):
cur=ListNode(int(str(num)[-1-i]))
pre.next=cur
pre=cur
return l
s=Solution()
l1=ListNode(1)
l1.next=ListNode(8)
l2=ListNode(1)
l2.next=ListNode(9)
s.addTwoNumbers(l1,l2)
|
9a5fea44aa42331fafd6654f693ed6792fec0a12 | shudongW/python | /Exercise/Python48.py | 403 | 3.6875 | 4 | #-*- coding:UTF-8 -*-
#笨办法学编程py3---异常,扫描
def cover_number(s) :
try:
print("this function's value:", s)
return int(s)
except ValueError:
return None
'''
a = cover_number('python')
print(a)
b = cover_number(12305)
print(b)
'''
stuff = input("> ")
print("input value:",stuff)
words = stuff.split()
print("split value:",words)
#sentence.scan(words)
|
e1988a2808048261146e27e94d513fc79053aaf9 | shudongW/python | /Exercise/Python21.py | 709 | 4.09375 | 4 | #-*- coding:UTF-8 -*-
#笨办法学编程py3---函数和变量
def add(a,b):
print("ADDING %d + %d " % (a,b))
return a + b
def substract(a,b):
print("SUBTRACT %d - %d " % (a, b))
return a - b
def multiply(a,b):
print("MULTIPLY %d * %d " % (a,b))
return a * b
def divide(a,b):
print("DEVIDE %d / %d" % (a,b))
return a / b
print("Let's do some math with just functions!")
age = add(30,5)
height = substract(78,4)
weight = multiply(90,2)
iq = divide(100,2)
print("Age:%d,Height:%d,weight:%d,IQ:%d " % (age,height,weight,iq))
print("Here is a puzzle")
what = add(age,substract(height,multiply(weight,divide(iq,2))))
print("That becames: ",what, "Can you do it by hand?")
|
379509ed51eb7ac9484e7b9a5acbb537b4de7c5b | shudongW/python | /Exercise/Python09.py | 287 | 4 | 4 | # -*-coding: UTF-8 -*-
#笨办法学编程py3-输入
print("How old are you?",end="")
age = input()
print("How tall are you?",end="")
height = input()
print("How much do you weight?",end="")
weight = input()
print("So you're %r old,%r tall and %r heavry." %(age,height,weight))
|
139d9c55627188c10bc2304695fd3c66c700ceb2 | shudongW/python | /Exercise/Python40.py | 507 | 4.25 | 4 | #-*- coding:UTF-8 -*-
#笨办法学编程py3---字典
cities ={'CA':'San Francisco','MI':'Detroit','FL':'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
def find_city(themap, state) :
if state in themap:
return themap[state]
else:
return "Not found."
cities['_find'] = find_city
while True :
print("State? (ENTER to quit)", end = " ")
state = input("> ")
if not state : break
city_found = cities['_find'](cities,state)
print(city_found)
|
fc89e815a53416d1e274bfe9e5eff307f69b3d37 | Jerkow/BNP_Datathon | /datathon_ai/interfaces/responses.py | 1,110 | 3.5 | 4 | from dataclasses import dataclass
from typing import List
@dataclass
class QuestionResponse:
"""
Interface that represents the response of one question.
"""
answer_id: int
question_id: int
justification: str = None
@dataclass
class FormCompanyResponse:
"""
Interface that represents the response of one form company.
"""
answers: List[QuestionResponse]
@classmethod
def from_list_question_response(cls, question_responses: List[QuestionResponse]):
data_model_questions_id = {i for i in range(1, 23)} # 22 questions in total
extracted_questions_id = {response.question_id for response in question_responses}
if data_model_questions_id == extracted_questions_id:
return cls(answers=question_responses)
raise ValueError(
f"Missing questions number for the company : {data_model_questions_id.difference(extracted_questions_id)}"
)
def sort_by_question_id(self):
sorted_answers = sorted(self.answers, key=lambda x: x.question_id)
self.answers = sorted_answers
|
a0c6ea7a8f1310a36a81b72c6edf4214def0ae62 | BarunBlog/Python-Files | /14 Tuple.py | 468 | 4.375 | 4 | tpl = (1, 2, 3, "Hello", 3.5, [4,5,6,10])
print(type(tpl)," ",tpl,"\n")
print(tpl[5]," ",tpl[-3])
for i in tpl:
print(i, end=" ")
print("\n")
#converting tuple to list
li = list(tpl)
print(type(li),' ',li,"\n")
tpl2 = 1,2,3
print(type(tpl2)," ",tpl2)
a,b,c = tpl2
print(a," ",b," ",c)
t = (1)
print(type(t))
t1 = (1,)
print(type(t1))
'''
difference between tuple & list
Can not overwrite vales in tuple
'''
tpl3 = (1,2,3, [12,10], (14,15), 20)
print(tpl3)
|
eefb8356e729952c086e208211ef64f5831a0290 | BarunBlog/Python-Files | /17 Read & Write file.py | 222 | 3.640625 | 4 | fw = open('sample.txt','w') ##'w' for writing file
fw.write('Writing some stuff in my text file\n')
fw.write('Barun Bhattacharjee')
fw.close()
fr = open('sample.txt','r') ##'r' for reading file
text = fr.read()
print(text)
fr.close()
|
fee9b0aa24b959b9e61ce49bdd723327ec68981d | BarunBlog/Python-Files | /leap_year.py | 153 | 3.6875 | 4 |
def main():
n = int(input())
str = ''
for i in range(1,n+1):
str = str + f"{i}"
print(str)
if __name__=="__main__":
main()
|
5a4c0c930ea92260b88f0282297db9c9e5bffe3f | BarunBlog/Python-Files | /Learn Python3 the Hard Way by Zed Shaw/13_Function&Files_ex20.py | 1,236 | 4.21875 | 4 | from sys import argv
script, input_file = argv
def print_all(f):
print(f.read())
def rewind(f):
f.seek(0)
'''
fp.seek(offset, from_what)
where fp is the file pointer you're working with; offset means how many positions you will move; from_what defines your point of reference:
0: means your reference point is the beginning of the file
1: means your reference point is the current file position
2: means your reference point is the end of the file
if omitted, from_what defaults to 0.
'''
def print_a_line(line_count, f):
print(line_count, f.readline())
'''
readline() reads one entire line from the file.
fileObject.readline( size );
size − This is the number of bytes to be read from the file.
The fle f is responsible for maintaining the current position in the fle after each readline() call
'''
current_file = open(input_file)
print("First let's print the whole file:\n")
print_all(current_file)
print("Now let's rewind, kind of like a tape.")
rewind(current_file)
print("Let's print three lines:")
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
|
b6fefcbd7ae15032f11a372c583c5b9d7b3199d9 | BarunBlog/Python-Files | /02 String operation.py | 993 | 4.21875 | 4 | str1 = "Barun "
str2 = "Hello "+"World"
print(str1+" "+str2)
'''
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
'''
str3 = 'I don\'t think so'
print(str3)
print('Source:D \Barun\Python files\first project.py')
# raw string changed heres
print(r'Source:D \Barun\Python files\first project.py') # r means rush string..
#raw string stays the way you wrote it
str4 = str1+str2
print(str4)
print(str1 * 5)
x = ' '
print(str2.find('World'),x,str2.find('Word'))
print(len(str2))
print(str2.replace('Hello','hello')) # replace returns string but don't replace parmanently
print(str2,"\n")
new_str2 = str2.replace('H','h')
print(new_str2)
print(str2)
str5 = "Hello World!"
print(str5)
del str5
#print(str5) # it will give an error
st1 = "Barun Bhattacharjee"
st2 = "Hello World!"
li = st2.split(" ")
print(li)
st3 = li[0] +' '+ st1
print(st3)
st4 = st2.replace("World!", st1)
print(st4)
|
37b61edb32bd793db26b3ec05d4013e0dec76765 | BarunBlog/Python-Files | /Python modules.py | 312 | 3.9375 | 4 | ## Modules: bunch of codes in pyhon library
import calendar ## importing calendar module
year = int(input('Enter a year number: '))
calendar.prcal(year) ## prcal() is a sub-module of calendar module
import math
fact = int(input('Enter a number: '))
print('The Factorial of ',fact,'is: ',math.factorial(fact))
|
fbdbdd1019c438c8cbcff0a8f5ece04701a5ccb4 | sklx2016/Salary-of-Adults | /AdultSalary.py | 1,628 | 3.53125 | 4 | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Loading the Data Set
data = pd.read_csv("train.csv")
null = data.isnull().sum() #To determine the the no. of NaN
# Imputing the NaN Values , other methods such as kNN, sklearn Imputer can also be used
#Education
data.workclass.value_counts(sort=True)
data.workclass.fillna('Private',inplace=True)
#Occupation
data.occupation.value_counts(sort=True)
data.occupation.fillna('Prof-specialty',inplace=True)
#Native Country
data['native.country'].value_counts(sort=True)
data['native.country'].fillna('United-States',inplace=True)
# Label Encoding
from sklearn import preprocessing
for x in data.columns:
if data[x].dtype == 'object':
lbl = preprocessing.LabelEncoder()
lbl.fit(list(data[x].values))
data[x] = lbl.transform(list(data[x].values))
# Creating Randomforest Model
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import cross_val_score
from sklearn.metrics import accuracy_score
y = data['target']
del data['target'] # removes the index
X = data
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=1,stratify=y)
#train the RF classifier
clf = RandomForestClassifier(n_estimators = 500, max_depth = 6)
clf.fit(X_train,y_train)
#make prediction and check model's accuracy
prediction = clf.predict(X_test)
acc = accuracy_score(np.array(y_test),prediction)
print ('The accuracy of Random Forest is {}'.format(acc))
|
6f95262465fd4e871d264b3e21469cb6ca41083f | Sartaj-S/Portfolio | /Python/Guess The Word Game/GuessTheWord Game.py | 2,248 | 4.09375 | 4 | import random
def search(letter, word):
n=0
i=0
for x in word:
if letter==x:
n=i
i= i+1
#load words
word=[ 'apple', 'notebook', 'phone', 'monitor', 'coconut', 'burrito', 'convertible', 'mansion', 'unorthodox', 'hangman']
#get random word
i=(random.randint(0,9))
man=word[i]
#get length of word, declare it to x to work with it
x=len(man)
tries=6
#Creating the word with dashes
display = list(man)
i=0
for y in man:
display[i]=' _ '
i+=1
#Begin game:
print("WELCOME TO HANGMAN!")
print("You have %i tries to guess the word"%tries)
print("YOUR WORD:")
print(display)
#keeps program going while the user has tries left
while tries>0:
r=0
#if there are not any dashes left, meaning the user found all the letters in the word, they win
if not(' _ ' in display):
print("Congratulations! You have found the word, please play again by restarting the program")
break
#displays tries and asks for input
print("You still have %i tries left to guess the word"%tries)
let=input("\nEnter a letter to guess: ")
#if the user enters the whole word, they win
if let==man:
print("Congratulations! You have found the word, please play again by restarting the program")
break
# if the letter is found in the word
if let in man:
i=0
#search for all occurances of the word
for y in range(0,x):
if let==man[i]:
#this segment checks if the letter has already been found and sets r to 1 so that the
#congratulations statement doesn't appear again
if let==display[i]:
print("You found that letter already silly")
r=1
break
display[i]=let
i=i+1
if not r==1:
print("Awesome! You got it")
elif (let in str(display)):
print("You already found that letter! Try again.")
else:
print("That letter is not in the word, sorry! Try again.")
tries=tries-1
print (display)
if tries==0:
print("You tried!")
print("Unfortunately, you failed. The word was: "+man)
|
cc727eb2b7cbea8092a744aab971403dfde6b790 | AdamBucholc/SpaceX | /API_CSV.py | 906 | 3.75 | 4 | # Program that writes data from an API to a CSV file.
import requests
import csv
url = "https://api.spacexdata.com/v3/launches"
response = requests.get(url) # Data download.
with open("flights.csv", mode='w') as flights_file:
csv_w = csv.writer(flights_file)
csv_w.writerow([ #Save strings in a CSV file.
"flight_number:",
"mission_name:",
"rocket_id:",
"rocket_number:",
"launch_date_utc:",
"video_link: "
])
for informations in response.json(): #Loop that saves data in a CSV file.
csv_w.writerow([
informations["flight_number"],
informations["mission_name"],
informations["rocket"]["rocket_id"],
informations["rocket"]['rocket_name'],
informations["launch_date_utc"],
informations["links"]["video_link"]
])
|
adf3fb5c5918ebccec51fe5b9709cacf78dbf511 | mont-grunthal/titanic_kaggle | /Titanic_training.py | 8,227 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#import required modules
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sklearn as sk
import scipy as sp
from sklearn.ensemble import RandomForestClassifier,RandomForestRegressor
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
#Read in the datasets
train = pd.read_csv('C://Users//Monty//Desktop//Titanic//train.csv')
test = pd.read_csv('C://Users//Monty//Desktop//Titanic//test.csv')
# # Alexis Cook's Model
#
# Using the method in Alexis Cook's tutorial, we were able to achieve and accuracy of:
#
# 0.77511.
#
# We can likely improve on this model. My first thought is that we should explore the data to see if we can impove our feature selection to train the model on more and perhaps more informative features. Additionally, we might dicover that there are preprocessing tools that might impove out
# # Exploratory Data Analysis
# In[2]:
#View the data
#It appears that some features may be unique identifiers
#Such as, Ticket and PassengerId
#cabin is a unique identifier but it may incode useful spatial information
train.head()
# In[3]:
#Look for any suspicious data. Fare having a minimum
#of zero could be an indication of missing values or
#maybe workers were listed as having zero fare.
#Maybe some got compliminetery tickets.
train.describe()
# In[4]:
#Very few people got complintary tickets on the titanic so I will
#only consider that the zeros may be explained by workers.
#That assumes that crew are on this list
#Whats the probability that <=1.6% of the training sample is crew given that
#our data is a random sample of everyone on the titanic?
#36% of the population were workers
#1.6% of the sample is workers
true_prop = (900/2435)
sample_prop = (15/891)
#The sample population had 891 individuals
#The population had 2435 individuals
sample_pop = 891
pop = 2435
#np is over 10
#n(1-p) is over 10
#we can use approximate as normal distribution
z = (sample_prop-true_prop)/np.sqrt((true_prop*(1-true_prop))/sample_pop)
#What is the probability that P(z<-21)?
p = sp.stats.norm.cdf(z)
print(f"n*p = {sample_pop*sample_prop}")
print(f"n*(1-p) = {sample_pop*(1-sample_prop)}")
print(f"Z = {z}")
print(" ")
print(f"The probability that we would sample less that 15 workers out of 891 from the titanic is {(p*100):0.2}%")
print(" ")
print("Definitly not explainable as crew!")
# In[5]:
#store all feature names for indexing
all_features = list(train.columns)
percent_incomplete = []
#count the number of missing values in each coloumn
print("Name and number of missing elements for each feature.")
print(" ")
for col in all_features:
num_nan = train[col].isna().sum()
print(f"{col}: {num_nan}")
perc = (num_nan/len(train[col]))
percent_incomplete.append((col,perc))
# In[6]:
#find percent missing elements per feature
for feat in percent_incomplete:
print(f"{feat[0]} is {feat[1]:.1%} inclompete")
# In[7]:
#Plot histograms of each feature (excluding unique features like ticket number)
fig, axs = plt.subplots(3,3);
axs[0,0].hist(train["SibSp"])
axs[0,0].set_title("SibSp");
axs[0,1].hist(train["Pclass"], bins = 3);
axs[0,1].set_title("Pclass");
axs[0,2].hist(train["Survived"], bins = 2)
axs[0,2].set_title("Survived");
axs[1,0].hist(train["Parch"]);
axs[1,0].set_title("Parch");
axs[1,1].hist(train["Fare"]);
axs[1,1].set_title("Fare");
axs[1,2].hist(train["Sex"], bins = 2)
axs[1,2].set_title("Sex");
axs[2,0].hist(train["Cabin"].dropna(0));
axs[2,0].set_title("Cabin");
axs[2,0].get_xaxis().set_visible(False)
axs[2,1].hist(train["Embarked"].dropna(0), bins = 3);
axs[2,1].set_title("Embarked");
axs[2,2].hist(train["Age"]);
axs[2,2].set_title("Age");
plt.tight_layout()
# In[8]:
#plot correlation matrix
f = plt.figure(figsize=(19, 15))
plt.matshow(train.corr(), fignum=f.number)
plt.xticks(range(train.select_dtypes(['number']).shape[1]), train.select_dtypes(['number']).columns, fontsize=14, rotation=45)
plt.yticks(range(train.select_dtypes(['number']).shape[1]), train.select_dtypes(['number']).columns, fontsize=14)
cb = plt.colorbar()
cb.ax.tick_params(labelsize=14)
plt.title('Correlation Matrix', fontsize=16);
# # Exploratory Data Analysis: Results
#
# From our small exploratoration of the data, we've learned the following. These insights are as follows:
#
# 1. We know intuitivly that some of our features, such as Name, PassengerId, Ticket, and Embark are unique or arbitrary enough that they dont yeild any information about survival. Cabin seems arbitrary, but if we can gleam spatial information out of it and passengers in sertain sections were more likely to die, it could be informative.
#
# 2. Some features have missing values. For the most part, this isn't to much of a problem. However, Cabin is over 77% missing data and should therefor be excluded from the model. And we have reaon to belive that there are some missing values inthe Fare feature.
#
# 3. Features such as Parch and Age are skewed. Other features are very different in scale. As we are using a tree based classifier, this won't be an issue. It should still be noted for when we apply different models in the future.
#
# 4. We have both numerical, ordenal, and categorical features. We should not encode these for random forest but may need to for future classifiers.
# # Preprocessing
# Based on this preliminary exploration. I will not consider Name, PassengerId, Ticket, Embarked, and Cabin from the training. Our only preprocessing step for random forest is to remove unwanted features and deal with the missing values for age. We will assume that the missing values in Age and Fare are Missing at Random and Missing Completly at random. We will use an iterative multivatiate imputer here. In the future, we will make a few more assumtions about the data in order to fill the data using Markov Chain Monte Carlo methods to impute the data. Its overkill for this problem but MCMC was one of my favorite courses in undergrad.
# In[9]:
test_feat = ['Age', 'Fare', 'Parch', 'Pclass', 'Sex', 'SibSp']
features = ['Survived','Age', 'Fare', 'Parch', 'Pclass', 'Sex', 'SibSp']
# In[10]:
#convert catigorical sex to categorica int for classification
train["Sex"] = train["Sex"].replace({"male": 0, "female": 1})
#convert catigorical sex to categorica int for classification
test["Sex"] = test["Sex"].replace({"male": 0, "female": 1})
#convert zeros in fare to NaN for imputer
#loop because find and replace has trouble w/ float zeros
count = 0
for i,elem in enumerate(train["Fare"]):
if elem < 0.001:
train["Fare"][i] = math.nan
#convert zeros in fare to NaN for imputer
#loop because find and replace has trouble w/ float zeros
count = 0
for i,elem in enumerate(test["Fare"]):
if elem < 0.001:
test["Fare"][i] = math.nan
# In[11]:
#Impute missing values in fare and age
imputed_data = []
for df in [train,test]:
imputed_df = df.copy()
numerical = ['Age','Fare']
#define an imputer for numerical columns
imp_num = IterativeImputer(estimator=RandomForestRegressor(),
initial_strategy='median',
max_iter=10,
random_state=0)
#impute the numerical column(Age)
imputed_df[numerical] = imp_num.fit_transform(imputed_df[numerical])
imputed_df['Age'] = imputed_df['Age'].apply(lambda x:int(round(x,0)))
imputed_data.append(imputed_df)
train = imputed_data[0]
test = imputed_data[1]
# # Train and Run
# In[12]:
#encode categorical attributes
X = train[features]
X_test = test[test_feat]
#define output for training
y = X["Survived"]
x = X[test_feat]
#build and fit model
model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=1)
model.fit(x, y)
#apply model to test objects
predictions = model.predict(X_test)
#save predictions
output = pd.DataFrame({'PassengerId': test.PassengerId, 'Survived': predictions})
output.to_csv('my_submission_preprocessing_unencoded.csv', index=False)
|
4c137f2f6e171fd84d296099ea98cf0333dba392 | TheCodingRecruiter/joblistinggenerator | /generatorlisting.py | 616 | 3.546875 | 4 | class Hiring:
def __init__(self, title, skills, location):
self.title = title
self.skills = skills
self.location = location
def listjob(self):
print('We have a current job opening for a ' + str(self.title) + ' who is skilled in ' + str(self.skills) + '. The position is located in ' + str(self.location) + '. Apply today if you are interested' )
pythondev = Hiring('Python Dev', 'Django/Flask, Machine Learning', 'Des Moines, IA')
javadev = Hiring('Java Developer', 'Hibernate/Spring, AWS, Rest', 'Dallas, TX')
pythondev.listjob()
javadev.listjob()
|
5c5af8b01b167bcf1229a33b6fcd2e8b468322da | kenji-kk/algorithm_py | /list1-19.py | 237 | 3.78125 | 4 | #1から12までを8をスキップして繰り返す
#ダメなら例
for i in range(1,150):
if i == 8:
continue
print(i, end='')
print()
#良い例
for i in list(range(1, 8)) + list(range(9, 150)):
print(i, end=' ')
print()
|
08b2822f41f28adf122c2f069681edf81153cbe2 | DylanDu123/leetcode | /94.二叉树的中序遍历.py | 968 | 3.625 | 4 | #
# @lc app=leetcode.cn id=94 lang=python3
#
# [94] 二叉树的中序遍历
#
# @lc code=start
# Definition for a binary tree node.
import collections
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> [int]:
result, curr, stack = [], root, []
while len(stack) or curr:
while curr:
stack.append(curr)
curr = curr.left
node = stack.pop()
result.append(node.val)
curr = node.right
return result
def sortedArrayToBST(self, nums: [int]) -> TreeNode:
if len(nums):
mid = int(len(nums)/2)
root = TreeNode(nums[mid])
root.left = self.sortedArrayToBST(nums[:mid])
root.right = self.sortedArrayToBST(nums[mid+1:])
return root
return None
# @lc code=end
|
8ed06dba5c6dac0ec030f4a000f274de68a6c2e7 | DylanDu123/leetcode | /48.旋转图像.py | 808 | 3.71875 | 4 | #
# @lc app=leetcode.cn id=48 lang=python3
#
# [48] 旋转图像
#
# @lc code=start
class Solution:
def rotate(self, matrix: [[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
size = len(matrix)
l = size - 1
for row in range(0, int(size/2)):
for column in range(0, int((size + 1)/2)):
temp = matrix[row][column]
matrix[row][column] = matrix[l-column][row]
matrix[l-column][row] = matrix[l-row][l-column]
matrix[l-row][l-column] = matrix[column][l-row]
matrix[column][l-row] = temp
pass
# if __name__ == "__main__":
# l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Solution().rotate(l)
# print(l)
# @lc code=end
|
ac705d9e1b145b8d47a927c79c0917f651da0101 | sanjayait/Python-Tkinter-Library | /Tkinter _Libarary/tic_tac_toe_game.py | 5,792 | 4.03125 | 4 | # Tutorial 17 Tic-Tac-Toe Game
from tkinter import *
root=Tk()
root.minsize(400,400)
root.resizable(0,0)
# Define function to change label of button
x=1
def show(b):
global x
x=x+1
if x%2 == 0:
if (b["text"]==""):
b["text"]="O"
else:
if (b["text"]==""):
b["text"]="X"
# For Row 0
if btn1["text"]=="O" and btn2["text"]=="O" and btn3["text"]=="O":
btn1["bg"]="green"
btn2["bg"]="green"
btn3["bg"]="green"
var.set("Player One Is Winner.!!!")
if btn1["text"]=="X" and btn2["text"]=="X" and btn3["text"]=="X":
btn1["bg"]="green"
btn2["bg"]="green"
btn3["bg"]="green"
var.set("Player Two Is Winner.!!!")
# For Row 1
if btn4["text"]=="O" and btn5["text"]=="O" and btn6["text"]=="O":
btn4["bg"]="green"
btn5["bg"]="green"
btn6["bg"]="green"
var.set("Player One Is Winner.!!!")
if btn4["text"]=="X" and btn5["text"]=="X" and btn6["text"]=="X":
btn4["bg"]="green"
btn5["bg"]="green"
btn6["bg"]="green"
var.set("Player Two Is Winner.!!!")
# For Row 2
if btn7["text"]=="O" and btn8["text"]=="O" and btn9["text"]=="O":
btn7["bg"]="green"
btn8["bg"]="green"
btn9["bg"]="green"
var.set("Player One Is Winner.!!!")
if btn7["text"]=="X" and btn8["text"]=="X" and btn9["text"]=="X":
btn7["bg"]="green"
btn8["bg"]="green"
btn9["bg"]="green"
var.set("Player Two Is Winner.!!!")
# For Column 0
if btn1["text"]=="O" and btn4["text"]=="O" and btn7["text"]=="O":
btn1["bg"]="green"
btn4["bg"]="green"
btn7["bg"]="green"
var.set("Player One Is Winner.!!!")
if btn1["text"]=="X" and btn4["text"]=="X" and btn7["text"]=="X":
btn1["bg"]="green"
btn4["bg"]="green"
btn7["bg"]="green"
var.set("Player Two Is Winner.!!!")
# For Column 1
if btn2["text"]=="O" and btn5["text"]=="O" and btn8["text"]=="O":
btn2["bg"]="green"
btn5["bg"]="green"
btn8["bg"]="green"
var.set("Player One Is Winner.!!!")
if btn2["text"]=="X" and btn5["text"]=="X" and btn8["text"]=="X":
btn2["bg"]="green"
btn5["bg"]="green"
btn8["bg"]="green"
var.set("Player Two Is Winner.!!!")
# For Column 2
if btn3["text"]=="O" and btn6["text"]=="O" and btn9["text"]=="O":
btn3["bg"]="green"
btn6["bg"]="green"
btn9["bg"]="green"
var.set("Player One Is Winner.!!!")
if btn3["text"]=="X" and btn6["text"]=="X" and btn9["text"]=="X":
btn3["bg"]="green"
btn6["bg"]="green"
btn9["bg"]="green"
var.set("Player Two Is Winner.!!!")
# For Diagonal 1,5,9
if btn1["text"]=="O" and btn5["text"]=="O" and btn9["text"]=="O":
btn1["bg"]="green"
btn5["bg"]="green"
btn9["bg"]="green"
var.set("Player One Is Winner.!!!")
if btn1["text"]=="X" and btn5["text"]=="X" and btn9["text"]=="X":
btn1["bg"]="green"
btn5["bg"]="green"
btn9["bg"]="green"
var.set("Player Two Is Winner.!!!")
# For Diagonal 3,5,7
if btn3["text"]=="O" and btn5["text"]=="O" and btn7["text"]=="O":
btn3["bg"]="green"
btn5["bg"]="green"
btn7["bg"]="green"
var.set("Player One Is Winner.!!!")
if btn3["text"]=="X" and btn5["text"]=="X" and btn7["text"]=="X":
btn3["bg"]="green"
btn5["bg"]="green"
btn7["bg"]="green"
var.set("Player Two Is Winner.!!!")
# Define reset function
def reset():
global x
btn1["text"]="";btn2["text"]="";btn3["text"]=""
btn4["text"]="";btn5["text"]="";btn6["text"]=""
btn7["text"]="";btn8["text"]="";btn9["text"]=""
btn1["bg"]="lightblue";btn2["bg"]="lightblue";btn3["bg"]="lightblue"
btn4["bg"]="lightblue";btn5["bg"]="lightblue";btn6["bg"]="lightblue"
btn7["bg"]="lightblue";btn8["bg"]="lightblue";btn9["bg"]="lightblue"
x=1
var.set("")
# Create Button
# Row 0
btn1=Button(root,text='',bg='lightblue',fg='black',width=25,height=5,command=lambda:show(btn1))
btn1.grid(row=0,column=0,)
btn2=Button(root,text='',bg='lightblue',fg='black',width=25,height=5,command=lambda:show(btn2))
btn2.grid(row=0,column=1)
btn3=Button(root,text='',bg='lightblue',fg='black',width=25,height=5,command=lambda:show(btn3))
btn3.grid(row=0,column=2)
# Row 1
btn4=Button(root,text='',bg='lightblue',fg='black',width=25,height=5,command=lambda:show(btn4))
btn4.grid(row=1,column=0)
btn5=Button(root,text='',bg='lightblue',fg='black',width=25,height=5,command=lambda:show(btn5))
btn5.grid(row=1,column=1)
btn6=Button(root,text='',bg='lightblue',fg='black',width=25,height=5,command=lambda:show(btn6))
btn6.grid(row=1,column=2)
# Row 2
btn7=Button(root,text='',bg='lightblue',fg='black',width=25,height=5,command=lambda:show(btn7))
btn7.grid(row=2,column=0)
btn8=Button(root,text='',bg='lightblue',fg='black',width=25,height=5,command=lambda:show(btn8))
btn8.grid(row=2,column=1)
btn9=Button(root,text='',bg='lightblue',fg='black',width=25,height=5,command=lambda:show(btn9))
btn9.grid(row=2,column=2)
var=StringVar()
# Create Input Field
e1=Entry(root,font=("Arial",15),fg="green",textvariable=var)
e1.grid(row=3,column=0,columnspan=3,pady=25,ipady=10)
# Reset Button
btn10=Button(root,text='Reset',bg='lightgreen',fg='black',width=25,height=2,command=reset)
btn10.grid(row=4,column=0,columnspan=3)
root.mainloop() |
48406d347ca5ca5ec379bf78ed0280bab6f62569 | sanjayait/Python-Tkinter-Library | /Tkinter _Libarary/Label_widget.py | 388 | 4.03125 | 4 | # Tutorial 1 Label widget
from tkinter import *
# Create window object
root=Tk()
# Define size of window
root.minsize(600, 300)
# To fix size of window
root.resizable(0, 0)
# Create label in window using "Label" class
lbl=Label(root,text="Sanjay\nGoyal\nBhind",font=("Arial",15),bg='lightgreen',fg='black',width=40,
height=3)
lbl.pack()
root.mainloop()
|
ed0c0537b5e48a9f86c70957a9b69f4fba67e35e | AnkitAvi11/100-Days-of-Code | /Strings/longest.py | 511 | 3.765625 | 4 |
def count_substring_length(string : str) -> int :
seen = dict()
last_index = 0
max_len = 0
for i in range(len(string)) :
if string[i] in seen :
last_index = max(last_index, seen[string[i]] + 1)
seen[string[i]] = i
max_len = max(max_len, i - last_index + 1)
return max_len
def main() :
t = int(input())
for _ in range(t) :
string = input()
print(count_substring_length(string))
if __name__ == '__main__' :
main()
|
54515c6f31106af4e112942e09b8d08e9f5b370c | AnkitAvi11/100-Days-of-Code | /Day 11 to 20/Sort.py | 458 | 4.03125 | 4 | # List sorting in python
class Person(object) :
def __init__(self, name, age) :
self.name = name
self.age = age
def __str__(self) :
return "Name = {} and age = {}".format(self.name, self.age)
if __name__ == "__main__":
mylist = [
Person('Ankit', 22),
Person('Priya', 20),
Person('Puneet', 20)
]
mylist.sort(key = lambda item : item.name)
for el in mylist :
print(el) |
047dd0b26413c4e4130f551a9aec46fafafd753f | AnkitAvi11/100-Days-of-Code | /Strings/union.py | 973 | 4.1875 | 4 | # program to find the union of two sorted arrays
class Solution :
def find_union(self, arr1, arr2) :
i, j = 0, 0
while i < len(arr1) and j < len(arr2) :
if arr1[i] < arr2[j] :
print(arr1[i], end = " ")
i+=1
elif arr2[j] < arr1[i] :
print(arr2[j], end = " ")
j += 1
elif arr1[i] == arr2[j] :
print(arr1[i], end = " ")
i += 1
j += 1
if i == len(arr1) :
for el in arr2[j:] :
print(el, end = " ")
else :
for el in arr1[i:] :
print(el, end = " ")
def main() :
t = int(input())
for _ in range(t) :
arr1 = list(map(int, input().split()))
arr2 = list(map(int, input().split()))
solution = Solution()
solution.find_union(arr1, arr2)
if __name__ == '__main__' :
main() |
6e778eca7af31d0913539cda877f26d6ee5436c3 | AnkitAvi11/100-Days-of-Code | /Day 11 to 20/duplicateinarray.py | 462 | 4.0625 | 4 | # program to find the duplicate in an array of N+1 integers
def find_duplicate(arr : list) -> None :
slow = arr[0];fast = arr[0]
slow = arr[slow]
fast = arr[arr[fast]]
while slow != fast :
slow = arr[slow]
fast = arr[arr[fast]]
fast = arr[0]
while slow != fast :
slow = arr[slow]
fast = arr[fast]
return slow
if __name__ == "__main__":
arr = [1,3,4,2,2]
print(find_duplicate(arr))
|
6c727ec6706b42ea057f264ff97d6f39b7481338 | AnkitAvi11/100-Days-of-Code | /Day 11 to 20/MoveAllnegative.py | 798 | 4.59375 | 5 | """
python program to move all the negative elements to one side of the array
-------------------------------------------------------------------------
In this, the sequence of the array does not matter.
Time complexity : O(n)
space complexity : O(1)
"""
# function to move negatives to the right of the array
def move_negative(arr : list) -> None :
left = 0;right = len(arr) - 1
while left < right :
if arr[left] < 0 :
while arr[right] < 0 : right-=1
# swap the two ends of the array
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
else :
left += 1
# driver code
if __name__ == "__main__":
arr = [1,2,-1,3,5,-2,7,8]
move_negative(arr)
print(arr) |
8d431c5c7681b0a7298e20e69d916c106bfba8f9 | AnkitAvi11/100-Days-of-Code | /Strings/equalstring.py | 1,114 | 3.9375 | 4 | """
Equal Strings
-------------
You are given N strings, You have to make all the strings equal if possible.
Output : Print the minimum number of moves required to make all the strings equal or -1 if it is not possible to make them equal at all
"""
# function to get the minimum number of moves
def min_moves(arr : list) -> int :
arr.sort()
min_moves = 99999
for i in range(len(arr)) :
count = 0
for j in range(len(arr)) :
if i!=j and arr[i] != arr[j] :
temp = arr[j] + arr[j]
if temp.count(arr[i]) > 0 :
count += temp.index(arr[i])
else:
return -1
min_moves = min(min_moves, count)
return min_moves
# main function
def main() :
# input
t = int(input())
for _ in range(t) :
n = int(input())
arr = list()
for _ in range(n) :
arr.append(input())
# calling of the min_moves functions
print(min_moves(arr))
# driver code
if __name__ == '__main__' :
main() |
f035dfbeb10ccb98eb85ae9f7625666fbf31e409 | AnkitAvi11/100-Days-of-Code | /Day 11 to 20/Pangrams.py | 239 | 3.90625 | 4 |
def pangrams(string : str) :
string = string.upper()
alpha = [0]*26
for el in string :
if el.isalpha() : alpha[ord(el) - 65] += 1
return all(alpha)
if __name__ == "__main__":
print(pangrams("ankit")) |
b595a08c2935570d1d5fa83805f03119444ab3f7 | AnkitAvi11/100-Days-of-Code | /Strings/fakepassword.py | 909 | 3.84375 | 4 | def rotate_string(string : list, i : int, j : int) -> None :
while i <= j :
string[i], string[j] = string[j], string[i]
i+=1;j-=1
def main() :
t = int(input())
for _ in range(t) :
original_string = input()
fake_string = list(input())
temp = fake_string.copy()
rotate_string(fake_string, 0, 1)
rotate_string(fake_string,2,len(fake_string)-1)
rotate_string(fake_string, 0, len(fake_string) - 1)
if "".join(fake_string) == original_string :
print("Yes")
else :
rotate_string(temp, len(temp)-2, len(temp)-1)
rotate_string(temp,0,len(fake_string)-3)
rotate_string(temp, 0, len(fake_string) - 1)
if "".join(fake_string) == original_string :
print("Yes")
else :
print("No")
if __name__ == '__main__' :
main() |
0ada57c61248ca2d1bc470a1d0dd6fd52b8da72e | AnkitAvi11/100-Days-of-Code | /Recursion/ass3.py | 361 | 3.875 | 4 | def decode_message(string) :
res = list()
for el in string :
next_char = chr(ord(el) - 3)
if ord(el) - 3 < 65 :
next_char = chr(ord(el) - 3 + 26)
res.append(next_char)
return res
if __name__ == '__main__' :
string = input()
res = decode_message(string)
res.reverse()
print(''.join(res)) |
4986274f00f6a7686333e7cddb05dc0b1767e1b8 | siddharthkarnam/leetcode1992 | /151-200/200.py | 1,535 | 3.875 | 4 | '''
200. Number of Islands
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
'''
class Solution:
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
visited = set()
stack = []
islandNo = 0
for row, rval in enumerate(grid):
for col, cval in enumerate(rval):
if ((row, col) in visited) or (int(cval) == 0):
continue
visited.add((row, col))
stack.append((row, col))
while stack:
seed = stack.pop()
neighbors = [(seed[0]-1, seed[1]),(seed[0]+1, seed[1]),\
(seed[0], seed[1]-1),(seed[0], seed[1]+1)]
for nei in neighbors:
if (0<= nei[0] < len(grid)) and ( 0<= nei[1] < len(grid[0]) ) and int(grid[nei[0]][nei[1]]) and (nei not in visited):
stack.append(nei)
visited.add(nei)
islandNo += 1
return islandNo |
4337472b441001cdb16b3774358b4653148a68e6 | C9Adrian/FaceNET | /facepic.py | 1,849 | 3.90625 | 4 | import curses
#-----------------
# Curses Variables
#-----------------
stdscr = curses.initscr() # Initiate the curses terminal
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_BLUE, curses.COLOR_BLACK)
curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)
curses.init_pair(5, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
k = 0
optNum = 1
name = ""
while True:
stdscr.clear()
height, width = stdscr.getmaxyx()
XCursor = width // 6
YCursor = height // 6
# Print title
stdscr.attron(curses.color_pair(3))
stdscr.attron(curses.A_BOLD)
stdscr.addstr(YCursor, XCursor, "Photo Booth")
stdscr.attroff(curses.color_pair(3))
stdscr.attroff(curses.A_BOLD)
# Print OPTIONS
YCursor = YCursor + 2
stdscr.attron(curses.A_ITALIC)
stdscr.attron(curses.color_pair(5))
stdscr.addstr(YCursor, XCursor, "Select an option using the UP/DOWN arrows and ENTER:")
stdscr.attroff(curses.A_ITALIC)
stdscr.attroff(curses.color_pair(5))
XCursor = XCursor + 5
YCursor = YCursor + 2
if optNum == 1:
stdscr.addstr(YCursor, XCursor, "Enter your Name: " + name, curses.A_STANDOUT)
else:
stdscr.addstr(YCursor, XCursor, "Enter your Name: " + name)
stdscr.refresh()
k = stdscr.getch()
if(k != 8):
name = name + chr(k)
print(name)
# Exit the settings
if k == 27:
break
if k == 8:
if (len(name) > 0):
name = name[:-1]
if optNum == 1 and k == 10:
if name[:-1] != "":
name = name[:-1]
path = "Face_Database/" + name+ ".jpg"
print(path)
break
|
2745adacab5e9df7eee9e5b1b6dff266012519b4 | kollyQAQ/wx-robot | /learning/chart/main.py | 333 | 3.84375 | 4 | fig = dict({
"data": [{"type": "bar",
"x": [1, 2, 3],
"y": [1, 3, 2]}],
"layout": {"title": {"text": "A Figure Specified By Python Dictionary"}}
})
# To display the figure defined by this dict, use the low-level plotly.io.show function
import plotly.io as pio
# pio.show(fig)
print(range(1,101)) |
e4649cc9aea90f14b3a27effd33b8367bdeda2c3 | jackrosetti/ProjectEulerSolutions | /Python/prob17.py | 806 | 3.796875 | 4 | # If the numbers 1 to 5 are written out in words: one, two, three, four, five,
# then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
#
# If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
#
#
# NOTE: Do not count spaces or hyphens.
# For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters.
# The use of "and" when writing out numbers is in compliance with British usage.
#
#We need to get the names for each number then in a loop add the length of them up
#Recursion would be nice but i think the array solution is better
import standard_math
def main():
res = sum(len(standard_math.num_to_word(i))for i in range(1, 1001))
return str(res)
print(main()) |
0354cd26dbab16b6c889222b491e5b3bba47b33c | kishoreramesh84/python-75-hackathon | /scopedemo.py | 187 | 3.625 | 4 | x=10
def fun1():
#"x=x+1"
print("x=x+1 this statement produces error as this function treats x as a local variable")
def fun2():
global x
x=x+1
print(x)
fun1()
fun2()
|
9f076e1b7465ff2d509b27296a2b963dd392a7f9 | kishoreramesh84/python-75-hackathon | /filepy2.py | 523 | 4.28125 | 4 | print("Reading operation from a file")
f2=open("newfile2.txt","w")
f2.write(" Hi! there\n")
f2.write("My python demo file\n")
f2.write("Thank u")
f2.close()
f3=open("newfile2.txt","r+")
print("Method 1:")
for l in f3: #Method 1 reading file using loops
print(l,end=" ")
f3.seek(0) #seek is used to place a pointer to a specific location
print("\nMethod 2:")
print(f3.read(10))#Method 2 it reads 10 character from file
f3.seek(0)
print("Method 3:")
print(f3.readlines())#Method 3 it prints the text in a list
f3.close()
|
cf268b95b8fffc6af24f53bd1412ecf5cc72ca1a | kishoreramesh84/python-75-hackathon | /turtlerace.py | 888 | 3.90625 | 4 | import turtle
from turtle import *
from random import randint
wn=turtle.Screen()
wn.bgcolor("light yellow")
wn.title("Race")
turtle.pencolor("dark blue")
penup()
goto(-200,200)
write("RACE TRACK!!",align='center')
goto(-160,160)
for s in range(16):
write(s)
right(90)
forward(10)
pendown()
forward(150)
penup()
backward(160)
left(90)
forward(20)
sub=100
p=int(input("Enter no of participants:"))
a=[0 for i in range(p)]
c=[0 for i in range(p)]
for i in range(p):
a[i]=Turtle()
c[i]=input("enter color:")
a[i].color(c[i])
a[i].shape('turtle')
a[i].penup()
a[i].goto(-160,sub)
a[i].pendown()
sub=sub-30
for turn in range(100):
for i in range(p):
a[i].forward(randint(1,5))
max=a[0].pos()
index=0
for i in range(p):
if(a[i].pos()>max):
max=a[i].pos()
index=i
print("THE WINNER IS ",c[index]) |
6628b79efc3e8d60d67344ecb44be3e03c3217ce | Jemanuel27/URI | /URI_SALARIO_1008.py | 142 | 3.640625 | 4 | N = int(input())
H = int(input())
R = float(input())
salario = float(H * R)
print ("NUMBER = %d" %N)
print("SALARY = U$%.2f" %salario) |
End of preview. Expand
in Dataset Viewer.
SmolLM-Corpus: Python-Edu
This dataset contains the python-edu
subset of SmolLM-Corpus with the contents of the files stored in a new text
field. All files were downloaded from the S3 bucket on January the 8th 2025, using the blob IDs from the original dataset with revision 3ba9d605774198c5868892d7a8deda78031a781f
. Only 1 file was marked as not found and the corresponding row removed from the dataset (content/39c3e5b85cc678d1d54b4d93a55271c51d54126c
which I suspect is caused by a mallformed blob ID).
Please refer to the original README for all other information.
Dataset Features
blob_id (string)
: Software Heritage (SWH) ID of the file on AWS S3.repo_name (string)
: Repository name on GitHub.path (string)
: The file path within the repository.length_bytes (int64)
: Length of the file content in UTF-8 bytes.score (float32)
: The output of the educational scoring model.int_score (uint8)
: The rounded educational score.text (string)
: The downloaded python file text.
- Downloads last month
- 32