blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
3966c5e5e1951e694ab0c4655ffce657ea471055 | ignacioParraCajal/probandoGit | /main.py | 578 | 3.75 | 4 |
#calcular el porcentaje de tiempo que lleva viva una persona segun su edad
def calculadorEdadPorcentual():
edad = int(input("ingrese edad: "))
promedioDeVida = int(input("Promedio de años de vida: "))
calculo = (edad/promedioDeVida) * 100
redondeo = round(calculo)
print(f"{redondeo}% de tiempo vivo segun la esperanza de vida de tu pais")
calculadorEdadPorcentual()
def calculadorDiasDeVida():
minutos = 60 #segundos
horas = 60 #minutos
dias = 24 #horas
semanas = 7 #dias
meses = 31 #dias
año = 365 #dias
#calculo =
|
1565c2219a95ec932063124361af62c0c4bf2a70 | arun-bhadouriya/100daysOfPython | /Day02/tipCalculator.py | 605 | 4.21875 | 4 | print("Welcome to Tip Calculator")
total_bill = float(input("What is the Total Bill? $"))
total_person = float(input("Ho many people to split the bill? "))
percent = float(input("What Percentage tip you would like to give? 10,12, or 15? "))
# Calculation for the tip and the share each person will pay
each_person_pay = (total_bill/total_person)+((total_bill/total_person)*(percent/100))
print(f"each person pays ${round(each_person_pay,2)}")
# num_char = len(input("wht is your name? "))
# print(type(num_char))
# print("your name is of " + str(num_char) + " charachters")
# print(((3*(3+3))/3)-3) |
1eac0aa88454812ee24184c9e133f90afd8f5437 | Mazev/Python-Advance | /06.Exercise Tuples and Sets/01. Unique Usernames.py | 214 | 3.5625 | 4 | def input_to_list(count):
lines = []
for _ in range(count):
lines.append(input())
return lines
num = int(input())
result = input_to_list(num)
result = set(result)
for i in result:
print(i) |
df4508f24f81c9c15bede056dc6a87d1d3b19b86 | Bongkot-Kladklaen/Programming_tutorial_code | /Python/Matplotlib/ep6_bars.py | 342 | 3.515625 | 4 | import matplotlib.pyplot as plt
import numpy as np
'''
#? การพล็อตกราฟแท่ง
#? แสดงกราฟแนวนอนด้วย plt.bart()
#? ปรับขนาดด้วย parameter width=0.1
'''
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x,y)
plt.show()
|
cd6747c2cbd96116fff75d0306d719dbfc4c386d | wuchaowei2012/movie-recommend | /extract.py | 1,950 | 3.5625 | 4 | """
The data, in form of 100k records has to be extracted and formed into a user vs movie rating matrix and user vs watched movie list
The initial record
user id, movie id, rating, timestamp
are read and stored in a list of lists - records
943 users and 1682 movies
The first one is a matrix so its a list of lists
user vs watched movies on the other hand can be a dictionary of lists
We need a persisitent way to store these values since the size is vast
Current choices are RDBMS and Pickle dump
The program uses pickle dump
Since python is 0-indexed, -1 should be used while indexing
Generating the movie_count as list and pickling
@author : Abhishek P, Bharath Kashyapa, Akshay A Malpani """
import time
import pickle
start_time = time.time()
file = open("source_data/u.data", "r")
records = []
for i in range(100000):
records.append(file.readline().rstrip().split("\t"));
file2 = open("dumps/records.pickle", "wb")
pickle.dump(records, file2);
file2.close()
# converting the strings to int, float
for i in records:
i[0] = int(i[0])
i[1] = int(i[1])
i[2] = float(i[2])
# the user vs movies list
user_movies = {}
movie_count = [0 for x in range(1682)]
for i in records:
if (i[0] not in user_movies):
user_movies[i[0]] = list()
user_movies[i[0]].append(i[1])
movie_count[i[1] - 1] = movie_count[i[1] - 1] + 1
user_movies_dump = open("dumps/user_movies.pickle", "wb")
pickle.dump(user_movies, user_movies_dump)
user_movies_dump.close()
with open("dumps/movie_count.pickle", "wb") as movie_count_dump:
pickle.dump(movie_count, movie_count_dump)
# generating the user vs movie matrix with 0 or ratings at user id, movie id
user_vs_movie = [[0 for x in range(1682)] for y in range(943)]
for i in records:
user_vs_movie[i[0] - 1][i[1] - 1] = i[2]
user_vs_movie_dump = open("dumps/user_vs_movie.pickle", "wb")
pickle.dump(user_vs_movie, user_vs_movie_dump)
user_vs_movie_dump.close()
print "Time:", time.time() - start_time
|
0ba3f94a356af564b05a3acff24e46f6353446f8 | vini52/Exercicios_PI_Python | /ece/lista1/lista1_4.py | 265 | 3.65625 | 4 | frase = input()
alfabeto = 'abcdefghijklmnopqrstuvwxyz'
cont = 0
frase = frase.lower()
for letra in alfabeto:
for caracter in frase:
if letra == caracter:
cont += 1
break
if cont == 26:
print('SIM')
else:
print('NAO') |
0069c4decce40af702b3549106a63c49a65f9233 | ReedJessen/CodeEval | /PrimePalindrome.py | 251 | 3.828125 | 4 |
def is_palindrome(x):
y = int(str(x)[::-1])
return x == y
def is_prime(x):
return x > 1 and all(x % i for i in xrange(2, x))
for i in range(1000,-1,-1):
if is_palindrome(i) and is_prime(i):
print i
break
|
9abf9284c1a81293271c9c06c3dbfc3738b29144 | YaroslavBkh/python_stuff | /pig_latin, any().py | 397 | 3.9375 | 4 | def has_numbers(word):
return any(char.isdigit() for char in word)
def pig_latin(word):
"""Returns a simplified Pig Latin version of received word"""
if has_numbers(word):
print("Pig Latin doesn't work numbers, sorry")
elif word[0] in ('e','a','i','o','u'):
print("{}way".format(word))
else:
print("{}{}ay".format(word[1:],word[0]))
pig_latin('owl')
|
07a3c4110629c6467e953005d92a4e0bddb64542 | keyu-lai/cs61a | /lab/lab04_extra.py | 1,544 | 4.1875 | 4 | from lab04 import *
# Q5
def reverse_iter(lst):
"""Returns the reverse of the given list.
>>> reverse_iter([1, 2, 3, 4])
[4, 3, 2, 1]
"""
"*** YOUR CODE HERE ***"
assert type(lst) == list, "lst must be a list"
re = []
for item in lst:
re = [item] + re
return re
def reverse_recursive(lst):
"""Returns the reverse of the given list.
>>> reverse_recursive([1, 2, 3, 4])
[4, 3, 2, 1]
"""
"*** YOUR CODE HERE ***"
assert type(lst) == list, "lst must be a list"
if len(lst) < 2:
return lst
return (reverse_recursive(lst[1:]) + [lst[0]])
# Q8
def mergesort(seq):
"""Mergesort algorithm.
>>> mergesort([4, 2, 5, 2, 1])
[1, 2, 2, 4, 5]
>>> mergesort([]) # sorting an empty list
[]
>>> mergesort([1]) # sorting a one-element list
[1]
"""
"*** YOUR CODE HERE ***"
#iterative
# if not seq:
# return []
# queue = [[elem] for elem in seq]
# while len(queue) > 1:
# first, second = queue[0], queue[1]
# queue = queue[2:] + [merge(first, second)]
# return queue[0]
# recursive
assert type(seq) == list
if len(seq) < 2:
return seq
middle = len(seq) // 2
return merge(mergesort(seq[:middle]), mergesort(seq[middle:]))
# Q12
def add_matrices(x, y):
"""
>>> add_matrices([[1, 3], [2, 0]], [[-3, 0], [1, 2]])
[[-2, 3], [3, 2]]
"""
"*** YOUR CODE HERE ***"
return [[x[i][j] + y[i][j] for j in range(len(x[0]))] for i in range(len(x))]
|
cb81bdd06689007dd321e8e8d463381ed1685d82 | tartakynov/sandbox | /basic-algorithms/dijkstra.py | 1,143 | 3.796875 | 4 | #!/usr/bin/env python
def shortest_path(adjacency, vertices, a, b):
n = len(adjacency)
start, finish = vertices.index(a), vertices.index(b)
unvisited = range(n)
parents = [0] * n
distances = [1000000] * n
distances[start] = 0
u_prev = -1
while unvisited:
u = unvisited[0]
for i in unvisited:
if distances[i] < distances[u]:
u = i
parents[u] = u_prev
for i in xrange(n):
if adjacency[u][i] > 0 and i in unvisited:
distances[i] = min(distances[u] + adjacency[u][i], distances[i])
unvisited.remove(u)
u_prev = u
path = []
p = finish
while p != -1:
path.insert(0, vertices[p])
p = parents[p]
return distances[finish], path
def main():
adjacency = [
[0, 14, 0, 0, 7, 9],
[14, 0, 9, 0, 0, 2],
[0, 9, 0, 6, 0, 0],
[0, 0, 6, 0, 15, 11],
[7, 0, 0, 15, 0, 10],
[9, 2, 0, 11, 10, 0]
]
print shortest_path(adjacency=adjacency, vertices=['A', 'B', 'C', 'D', 'E', 'F'], a='A', b='C')
if __name__ == "__main__":
main()
|
003e5826f3928d22d73160bc247526fd09f1efb1 | zhukaijun0629/Coursera_Algorithms | /Course #3/PA #3-4/knapsack1.py | 821 | 3.65625 | 4 | def knapsack(items,num,size):
cache = [[],[]]
for k in range(0,size+1):
cache[0].append(0)
cache[1].append(0)
for i in range(1,num+1):
for k in range(1,size+1):
if k < items[i][1]:
cache[1][k] = cache[0][k]
else:
cache[1][k] = max(cache[0][k] , cache[0][k-items[i][1]] + items[i][0])
cache[0],cache[1] = cache[1],cache[0]
return cache[0][size]
items = [(0,0)]
with open('knapsack1.txt') as f:
first_line = f.readline()[:-1]
first_line = first_line.split()
size, number_of_items = first_line
data = f.readlines()
for line in data:
elements = list(map(int,line[:-1].split()))
items.append((elements[0],elements[1]))
f.close()
print(knapsack(items,int(number_of_items),int(size)))
|
98136947ef4a2861256d9a1e56a8c86695edaf77 | frankylamps/python-project-lvl1 | /brain_games/games/calc.py | 408 | 3.734375 | 4 | import random
from operator import add, mul, sub
RULES = 'What is the result of the expression?'
def start_round():
num1 = random.randint(10, 15)
num2 = random.randint(1, 5)
function, symbol = random.choice([
(add, '+'),
(mul, '*'),
(sub, '-'),
])
question = ('{} {} {}'.format(num1, symbol, num2))
answer = function(num1, num2)
return question, answer
|
fef0fc9c25492938e16183c6f6ee61463e766d01 | bhirbec/interview-preparation | /CTCI/8.5.py | 276 | 3.84375 | 4 | # Note: I used the first two hints to solve this problem
def multiply(a, b):
if b == 1:
return a
s = multiply(a, b >> 1) << 1
if b & 1:
s += a
return s
def main():
a = 123
b = 123312
print multiply(a, b)
print a * b
main()
|
fa8dc3f159af7c617e96f7d8e97711e79c240a45 | Yucheng7713/CodingPracticeByYuch | /Practice/stringPermutation.py | 292 | 3.890625 | 4 |
def stringPermutation(p_str):
def permutation(prefix, remain):
if not remain:
print(prefix)
for i in range(len(remain)):
permutation(prefix + remain[i], remain[:i] + remain[i+1:])
permutation("", p_str)
p_str = "abc"
stringPermutation(p_str) |
560a8ee167acb875f0c6754dd082b46faf383b48 | NikoleiAdvani/breakout | /ball.py | 1,368 | 4 | 4 | # Nikolei Advani, 12/16/2016
# This class creates the ball
import pygame
import random
class Ball(pygame.sprite.Sprite):
def __init__(self, color, windowWidth, windowHeight):
super().__init__()
self.RADIUS = 10
self.color = color
self.windowWidth = windowWidth
self.windowHeight = windowHeight
self.image2 = pygame.Surface((self.RADIUS, self.RADIUS))
self.rect = self.image2.get_rect()
self.image2.fill(self.color)
self.vx = random.randint(1, 3)
if random.random() > 0.5:
self.vx = -self.vx
self.vy = 5
# This method tells the ball how to move
def move(self):
self.rect.x += self.vx
self.rect.y += self.vy
if self.rect.x > self.windowWidth or self.rect.x < 0:
self.vx = -self.vx
if self.rect.y > self.windowHeight or self.rect.y < 0:
self.vy = -self.vy
# This method takes a brick away from the sprite group if it is hit and changes the direction of the ball
def collideBricks(self, spriteGroup):
if pygame.sprite.spritecollide(self, spriteGroup, True):
self.vy = -self.vy
# This method allows the ball to bounce off of the paddle
def collidePaddle(self, spriteGroup):
if pygame.sprite.spritecollide(self, spriteGroup, False):
self.vy = -self.vy
|
bc8cee3f1a680e1580dc7bbf8c2e93509f77e3bb | EmineKala/Python-101 | /Python/Hafta4/alistirma6.py | 619 | 3.90625 | 4 | #Tüm kullanıcı adlarını ve şifreleri takip eden users adında sözlüğe dayanarak bir kullanıcı adı ve şifrenin doğru olup olmadığını kontrol eden bir fonksiyon yazın.
#Fonksiyonunuz, verilen kullanıcı adı ve şifrenin doğru olup olmadığına bağlı olarak True veya False dönmelidir.
users = dict()
users["eminekala"] = "1234"
username = input("Kullanıcı adı:")
password = input("Şifre:")
def check_login(username, password):
if username in users.keys() and users[username] == password:
return True
else:
return False
print(check_login(username, password))
|
aadb11ead55cca52257df4dadd6c6d2ae9fcb859 | RonakAthos/Python-WorkSapce | /helloworld.py | 444 | 4.0625 | 4 | string1 = "hello"
string2 = "king"
#list example
my_list = ["world", "war", "writen"]
my_list.append("working")
print(my_list)
print(len(my_list))
#Dictionaries example
my_dict = {'key1': 100, 'key2':200}
print(my_dict)
my_dict.items()
my_dict['key3'] = {'k1':1, 'k2' : 2, 'k3': 3}
print(my_dict['key3'])
print(my_dict['key3']['k2'])
my_dict['key4'] = (1, 2, 3, 4, 5, 6)
print(len(my_dict))
print(len(my_dict['key3']))
|
cd39672b84f454cf65774ea4f5b9f4d99ef8a959 | mylgcs/python | /训练营day01/05_for.py | 271 | 3.984375 | 4 | # 打印5个"我也很帅"
for i in range(5):
print("我也很帅")
# 从1 打印到 20
for i in range(1, 21):
print(i)
# 从20打到1
for i in range(20, 0, -1):
print(i)
# break和continue
for i in range(1, 21):
if i == 15:
break
print(i) |
7defed8f5c16c0656b1f764aac655220ec57b3f0 | Nain08/Python-Codes | /palindrome.py | 221 | 4.125 | 4 | #palindrome
sum=0
num=int(input("Enter a number"))
numcopy=num
while numcopy>0:
sum=sum*10
sum=sum+(numcopy%10)
numcopy=numcopy//10
if num==sum:
print("Palindrome")
else:
print("Not Palindrome")
|
23a5ed49ae7de044c3dc105dc1b5474c56d61e82 | jolovillanueva47/coding-problems | /binarygap.py | 659 | 3.59375 | 4 | #About
def binarygap(num):
binaryForm="{0:b}".format(num)
indices = [i for i, x in enumerate(binaryForm) if x == "1"]
if(len(indices)<=1):
return 0
else:
currentLargestGap=0
largestGap=0
for index, obj in enumerate(indices):
try:
largestGap=indices[index+1]-obj
if(largestGap>currentLargestGap):
currentLargestGap=largestGap
except IndexError:
pass
return currentLargestGap-1
print(binarygap(9)) #2
print(binarygap(529)) #4
print(binarygap(20))
print(binarygap(32))
print(binarygap(1041))
print(binarygap(15)) |
23b915c36e24e404de63cd1ff223dd4adf9a97e8 | xytracy/python | /ex4.py | 585 | 3.828125 | 4 | cars=100
space_in_a_car=4.0
drivers=30
passengers=90
cars_not_driven=cars-drivers
cars_driven=drivers
carpool_capacity=cars_driven*space_in_a_car
average_passengers_per_car=passengers/cars_driven
#give values to the variables
print"there are",cars,"cars available."
print"there are only",drivers,"drivers available."
print"there will be",cars_not_driven,"empty cars today"
print "we can transport",carpool_capacity,"people today."
print"we have",passengers,"to carpool today."
print"we need to put about ",average_passengers_per_car , "in each car."
#print the results |
622cf66419efa55057b1d9d6e64834698a9be7d6 | chijuzipi/Interview-Prep | /amazon/spiral.py | 1,716 | 3.59375 | 4 | '''
spiral order visit of a matrix
-->two method
--> corner case:
1) nums
2) only one element?
'''
def spiral(nums):
if not nums or len(nums) == 0 or len(nums[0]) == 0:
return []
h = len(nums)
w = len(nums[0])
total = h * w
res = []
res.append(nums[0][0])
i = 0
j = 0
layer = 0
while len(res) < total:
while j + 1 < w-layer and len(res) < total:
j += 1
res.append(nums[i][j])
while i + 1 < h-layer and len(res) < total:
i += 1
res.append(nums[i][j])
while j-1 >= layer and len(res) < total:
j -= 1
res.append(nums[i][j])
while i-1 > layer and len(res) < total:
i -= 1
res.append(nums[i][j])
layer += 1
return res
def spiral(nums):
if not nums or len(nums) == 0 or len(nums[0]) == 0:
return []
rowT = len(nums)
colT = len(nums[0])
rowS = 0
colS = 0
out = []
while rowS < rowT and colS < colT:
if rowS < rowT and colS < colT:
for i in range(colS, colT):
out.append(nums[rowS][i])
rowS += 1
if rowS < rowT and colS < colT:
for i in range(rowS, rowT):
out.append(nums[i][colT-1])
colT -= 1
if rowS < rowT and colS < colT:
for i in range(colT-1, colS-1, -1):
out.append(nums[rowT-1][i])
rowT -= 1
if rowS < rowT and colS < colT:
for i in range(rowT-1, rowS-1, -1):
out.append(nums[i][colS])
colS += 1
return out
nums = [[ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]
print spiral(nums)
|
b6d76d17dd13eeaf274ae0589ad98253e96f8cb1 | Aadhya-Solution/PythonExample | /for_examples/for_prime_n_m.py | 167 | 3.734375 | 4 | n,m=input("Enter N,M:")
for i in range(n,m+1):
flag=True
for j in range(2,i):
if i%j==0:
flag=False
if flag:
print("Prime:",i)
|
8842421c3a352fc3d5ccfd0212c14cff6904777b | ByronHsu/leetcode | /python/543-diameter-of-binary-tree.py | 595 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def dfs(self, root):
if root == None: return 0
L, R = self.dfs(root.left) + 1, self.dfs(root.right) + 1
self.ans = max(self.ans, L + R - 1)
return max(L, R)
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.ans = 0
self.dfs(root)
if not root: return 0
else: return self.ans - 1 |
39f98276f730686b245937b04ace0377ed831df7 | Nishadguru/python-sample1 | /6th.py | 65 | 3.9375 | 4 | num = int(input("enter the number"))
sum = 0
sum+=num
print(num)
|
a60d492766c1462c3e445e577a9a724073d50fdf | flaviasilvaa/ProgramPython | /22.AnalysingText.py | 739 | 4.34375 | 4 | #this program is going to ask a user to type their full name and the program is going to show the name in upper case and lower case
#how many letters in their name and how many letters the user have in their first name
name = str(input("Type insert your name?\n")).strip()
print('-=-'*30,'Analysing your name')
print(f'Your name in upper case is {name.upper()}')
print(f'Your name in lower case is {name.lower()}')
print('The amount of letter in yor name is {}'.format(len(name) - name.count(' ')))#minus the space counting
print(f"Your first name have {name.find(' ')} letters")
#####another way to check the first name######
separate = name.split()
print(f'Your first name is {separate[0]} and your name has {len(separate[0])} letters')
|
babe30d24fb47737744647e904725a5ca4c5433d | yestemir/web | /week8/codingbat/string2.py | 800 | 3.8125 | 4 | # 1
def double_char(str):
ans = ""
for char in str:
ans += 2 * char
return ans
# 2
def count_hi(str):
return str.count('hi')
# 3
def cat_dog(str):
cat = str.count('cat')
dog = str.count('dog')
if cat == dog:
return True
else:
return False
# 4
def count_code(str):
result = 0
for i in range(len(str) - 3):
if str[i:i + 2] == 'co' and str[i + 3] == 'e':
result += 1
return result
# 5
def end_other(a, b):
s = []
if len(a) < len(b):
s = b[-len(a):]
if s.lower() == a.lower():
return True
else:
return False
else:
s = a[-len(b):]
if s.lower() == b.lower():
return True
else:
return False
# 6
def xyz_there(str):
if 'xyz' in str and '.xyz' not in str: return True
if str.count('xyz') > str.count('.xyz'):
return True
else:
return False
|
004f62538e027529268b88a947153281bcfb21d9 | venkii83/DE-Python | /Master_Bank.py | 3,688 | 4.375 | 4 | class Customers:
def __init__(self, firstname, lastname, age, gender):
"""Create __init__() method with name, age & gender of the customer"""
self.name = name = ""
self.age = age
self.gender = gender
def show_details(self):
print("Customer details")
print("")
print("name", self.name)
print("age", self.age)
print("gender", self.gender)
class BankAccount:
def __init__(self:
self.balance = 0
def deposit(self, amount):
"""Defining the deposit amount and it's calculation"""
self.amount = amount
self.balance = self.balance + self.amount
print("Account balance updated", self.balance)
def withdraw(self, amount):
"""Defining the withdrawal procedure"""
self.amount = amount
if self.amount > self.balance:
print("Insufficient balance", self.balance)
else:
self.balance = self.balance - self.amount
print("Account bal has been updated: $", self.balance)
def View_balance(self):
"""Defining the view balance options"""
self.show_details()
print("Account bal has been updated: $", self.balance)
class CheckingAccount(BankAccount):
"""Defining checking account & its characterstics"""
def __init__(self, balance, limit):
"""Calling the parent constructor using Class name __init__"""
BankAccount __init__(self, balance)
self.limit = limit
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount, fee):
if fee <= self.limit:
BankAccount.withdraw(self, amount - fee)
else:
BankAccount.withdraw(self, amount - self.limit)
class SavingsAccount(BankAccount):
"""Defining savings account & its characterstics"""
def __init__(self, balance, interest_rate):
"""Calling the parent constructor using Class name __init__"""
BankAccount __init__(self, balance)
self.interest_rate = interest_rate
"""New Functionality"""
def compute_interest(self, n_years =1):
return self.balance * ((1 + self.interest_rate) ** n_years - 1)
class BalanceError(Exception): pass
"""Defining exceptions/errors"""
class BankAccount:
def __init__(self, name, balance):
if balance < 0:
raise BalanceError("Balance has to be non-negative")
else:
self.name, self.balance = name, balance
class Employee:
def __init__(self, name, salary=50000):
self.name = name
self.salary = salary
def give_raise(self, amount):
"""Add a give_raise method"""
self.salary += amount
"""Defining a sub class Manager"""
class Manager(Employee):
def display(self):
print("Manager ", self.name)
def __init__(self, name, salary=80000, project=None)
Employee.__init__(self, name, salary)
self.project = project
"""Add a give_raise method"""
def give_raise(self, amount, bonus=1.05):
new_amount = amount * bonus
Employee.give_raise(self, new_amount)
class SalaryError(ValueError):
"""Define SalaryError inherited from ValueError"""
pass
class BonusError(SalaryError):
"""Define BonusError inherited from SalaryError"""
pass
class Employee:
MIN_SALARY = 50000
MAX_RAISE = 5000
def __init__(self, name, salary=50000):
self.name = name
self.salary = salary
"""If salary is too low"""
if salary < MIN_SALARY:
# Raise a SalaryError exception
raise SalaryError("Salary is too low!")
self.salary = salary
|
96a7a25e2e724f70ae9d30b78bb216a867f9e44f | Harsh-Agarwals/python-turtle-module-projects | /Colored Hexagon/coloredHexagon.py | 251 | 3.671875 | 4 | import turtle
color = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo']
turtle.bgcolor('black')
for x in range(360):
turtle.pencolor(color[x % 6])
turtle.width(x/100 + 1)
turtle.forward(x)
turtle.left(59)
turtle.done()
|
ccd411dfb8db1bcca4fbcde4b5309e255051dd14 | supria68/ProjectEuler | /python/prime_permutations.py | 1,256 | 3.546875 | 4 | """
EP - 49
The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another.
There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence.
What 12-digit number do you form by concatenating the three terms in this sequence?
"""
import math
def isPrime(num):
if num % 2 == 0 or num % 3 == 0:
return False
for i in range(5, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
def compute():
"""
Triplets: a, b, c must be prime and permutations of each other
a = b - 3330 = c - 6660
upper limit (4-digit) = 10000 - 6660 = 3340
"""
for a in range(1489, 3340):
b = a + 3330
c = b + 3330
# check permutations
if sorted(set(str(a))) == sorted(set(str(b))) and sorted(set(str(a))) == sorted(set(str(c))):
# check if one of them is prime
if isPrime(a):
result = (a * 10000 + b) * 10000 + c
return result
if name == "__main__":
print(compute())
|
190304092bb20976662120844ccbbf6e694fa1fb | Balde641/TkInter | /Osat0--11/OSA PROJEKTI2.py | 273 | 4.15625 | 4 | from tkinter import *
root = Tk()
# We are creating label widget
myLabel1 = Label(root, text="Hello World")
myLabel2 = Label(root, text="My name is Balde")
# We are showing it onto the screen
myLabel1.grid(row=0, column=0)
myLabel2.grid(row=1, column=1)
root.mainloop() |
032af1c8a7fa60272a8487c560973642283eef2e | kryskaliska/KurcheuskayaLiza | /Homework/MultiplayerBMI.py | 30,538 | 4.0625 | 4 | d = dict()
z = 0
while z <= 10:
print('Введите Ваше имя: ')
name = input()
if name == 'end':
break
elif name in d:
print('Ваши данные', d[name])
else:
pol = input('Введите Ваш пол (муж или жен) ')
vozr = int(input('Введите Ваш возраст (полных лет) '))
ves = int(input('Какой у Вас вес в килограммах? '))
rost = float(input('Какой у Вас рост в метрах? '))
bmi = round(ves / (rost**2))
print('Ваш индекс массы тела: ', bmi)
a = bmi - 11
scale = "10" + "="*a + str(bmi) + "="*(48 - a) + "60"
print(scale)
# We check different options depending on gender and age
# Female and 3 and under 3 years old
if pol == 'жен' and vozr <= 3:
if bmi <= 14:
print('Критически недостаточная масса. Рекомендуется срочно обратиться'\
' к врачу для проведения обследования')
elif 14 < bmi < 16:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин')
elif 16 <= bmi <= 18:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif bmi > 18:
print('Избыточный вес. Есть угроза ожирения. Рекомендуем обратиться к врачу'\
' для консультации по поводу изменений в режиме питания и физической'\
' активности.')
# Female and over 3 but under or equal 7 years old
elif pol == 'жен' and 3 < vozr <= 7:
if bmi <= 13:
print('Критически недостаточная масса. Рекомендуется срочно обратиться'\
' к врачу для проведения обследования')
elif 13 < bmi < 15:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин')
elif 15 <= bmi <= 18:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif bmi > 18:
print('Избыточный вес. Есть угроза ожирения. Рекомендуем обратиться к врачу'\
' для консультации по поводу изменений в режиме питания и физической'\
' активности.')
# Female and over 7 but under or equal 9 years old
elif pol == 'жен' and 7 < vozr <= 9:
if bmi <= 12:
print('Критически недостаточная масса. Рекомендуется срочно обратиться'\
' к врачу для проведения обследования')
elif 12 < bmi < 16:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин')
elif 16 <= bmi <= 21:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif bmi > 21:
print('Избыточный вес. Есть угроза ожирения. Рекомендуем обратиться к врачу'\
' для консультации по поводу изменений в режиме питания и физической'\
' активности.')
# Female and over 9 but under or equal 14 years old
elif pol == 'жен' and 9 < vozr <= 14:
if bmi <= 15:
print('Критически недостаточная масса. Рекомендуется срочно обратиться'\
' к врачу для проведения обследования')
elif 15 < bmi < 17:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин')
elif 17 <= bmi <= 21:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif bmi > 21:
print('Избыточный вес. Есть угроза ожирения. Рекомендуем обратиться к врачу'\
' для консультации по поводу изменений в режиме питания и физической'\
' активности.')
# Female and over 14 but under 18 years old
elif pol == 'жен' and 14 < vozr < 18:
if bmi <= 17:
print('Критически недостаточная масса. Рекомендуется срочно обратиться'\
' к врачу для проведения обследования')
elif 17 < bmi < 20:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин')
elif 20 <= bmi <= 24:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif bmi > 24:
print('Избыточный вес. Есть угроза ожирения. Рекомендуем обратиться к врачу'\
' для консультации по поводу изменений в режиме питания и физической'\
' активности.')
# Female and over or equal 18 but under 30 years old
elif pol == 'жен' and 18 <= vozr < 30:
if bmi < 16:
print('Выраженный дефицит массы. Рекомендуется обратиться к врачу для'\
' проведения обследования')
elif 16 <= bmi < 18:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин.'\
' Необходимо проконтролировать режим питания и сна.')
elif 18 <= bmi < 25:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif 25 <= bmi < 30:
print('Избыточный вес. Предожирение. Рекомендуем контролировать режим питания'\
' и сна.')
elif 30 <= bmi < 35:
print('Ожирение первой степени. Рекомендуем обратиться к врачу для'\
' консультации по поводу изменений в режиме питания, сна и физической'\
' активности.')
elif 35 <= bmi < 40:
print('Ожирение второй степени. Рекомендуем обратиться к врачу для проведения'\
' обследования и лечения')
elif bmi >= 40:
print('Ожирение третьей степени. Рекомендуем регулярное наблюдение у врача,'\
' выполнение исследований и лечение в целях снижения излишнего веса.')
# Female and over or equal 30 but under 50 years old
elif pol == 'жен' and 30 <= vozr < 50:
if bmi < 16:
print('Выраженный дефицит массы. Рекомендуется обратиться к врачу для'\
' проведения обследования')
elif 16 <= bmi < 18:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин.'\
' Необходимо проконтролировать режим питания и сна.')
elif 18 <= bmi < 25:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif 25 <= bmi < 30:
print('Избыточный вес. Предожирение. Рекомендуем контролировать режим питания'\
' и сна.')
elif 30 <= bmi < 35:
print('Ожирение первой степени. Риск сердечно-сосудистых заболеваний.'\
' Рекомендуем обратиться к врачу для консультации по поводу изменений'\
' в режиме питания, сна и физической активности.')
elif 35 <= bmi < 40:
print('Ожирение второй степени. Повышенный риск сердечно-сосудистых заболеваний.'\
' Рекомендуем обратиться к врачу для проведения обследования и лечения')
elif bmi >= 40:
print('Ожирение третьей степени. Рекомендуем регулярное наблюдение у врача,'\
' выполнение исследований и лечение в целях снижения излишнего веса.')
# Female and over or equal 50 but under 70 years old
elif pol == 'жен' and 50 <= vozr < 70:
if bmi < 15:
print('Выраженный дефицит массы. Рекомендуется обратиться к врачу для'\
' проведения обследования')
elif 15 <= bmi < 17:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин.'\
' Необходимо проконтролировать режим питания и сна.')
elif 17 <= bmi < 24:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif 24 <= bmi < 29:
print('Избыточный вес. Предожирение. Рекомендуем контролировать режим питания'\
' и сна.')
elif 29 <= bmi < 35:
print('Ожирение первой степени. Повышенный риск сердечно-сосудистых заболеваний.'\
' Рекомендуем обратиться к врачу для консультации по поводу изменений в режиме'\
' питания, сна и физической активности.')
elif 35 <= bmi < 40:
print('Ожирение второй степени. Рекомендуем обратиться к врачу для проведения'\
' обследования и лечения')
elif bmi >= 40:
print('Ожирение третьей степени. Рекомендуем регулярное наблюдение у врача,'\
' выполнение исследований и лечение в целях снижения излишнего веса.')
# Female and over or equal 70 years old
elif pol == 'жен' and vozr >= 70:
if bmi < 15:
print('Выраженный дефицит массы. Рекомендуется обратиться к врачу для'\
' проведения обследования')
elif 15 <= bmi < 17:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин.'\
' Необходимо проконтролировать режим питания и сна.')
elif 17 <= bmi < 24:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif 24 <= bmi < 29:
print('Избыточный вес. Предожирение. Риск сердечно-сосудистых заболеваний.'\
' Рекомендуем контролировать режим питания и сна.')
elif 29 <= bmi < 34:
print('Ожирение первой степени. Рекомендуем обратиться к врачу для'\
' консультации по поводу изменений в режиме питания, сна и физической'\
' активности.')
elif 34 <= bmi < 39:
print('Ожирение второй степени. Рекомендуем обратиться к врачу для проведения'\
' обследования и лечения')
elif bmi >= 39:
print('Ожирение третьей степени. Рекомендуем регулярное наблюдение у врача,'\
' выполнение исследований и лечение в целях снижения излишнего веса.')
# Male and 3 and under 3 years old
if pol == 'муж' and vozr <= 3:
if bmi <= 14:
print('Критически недостаточная масса. Рекомендуется срочно обратиться'\
' к врачу для проведения обследования')
elif 14 < bmi < 16:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин')
elif 16 <= bmi <= 18:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif bmi > 18:
print('Избыточный вес. Есть угроза ожирения. Рекомендуем обратиться к врачу'\
' для консультации по поводу изменений в режиме питания и физической'\
' активности.')
# Male and over 3 but under or equal 7 years old
elif pol == 'муж' and 3 < vozr <= 7:
if bmi <= 13:
print('Критически недостаточная масса. Рекомендуется срочно обратиться'\
' к врачу для проведения обследования')
elif 13 < bmi < 15:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин')
elif 15 <= bmi <= 18:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif bmi > 18:
print('Избыточный вес. Есть угроза ожирения. Рекомендуем обратиться к врачу'\
' для консультации по поводу изменений в режиме питания и физической'\
' активности.')
# Male and over 7 but under or equal 9 years old
elif pol == 'муж' and 7 < vozr <= 9:
if bmi <= 12:
print('Критически недостаточная масса. Рекомендуется срочно обратиться'\
' к врачу для проведения обследования')
elif 12 < bmi < 16:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин')
elif 16 <= bmi <= 21:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif bmi > 21:
print('Избыточный вес. Есть угроза ожирения. Рекомендуем обратиться к врачу'\
' для консультации по поводу изменений в режиме питания и физической'\
' активности.')
# Male and over 9 but under or equal 14 years old
elif pol == 'муж' and 9 < vozr <= 14:
if bmi <= 15:
print('Критически недостаточная масса. Рекомендуется срочно обратиться'\
' к врачу для проведения обследования')
elif 15 < bmi < 17:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин')
elif 17 <= bmi <= 21:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif bmi > 21:
print('Избыточный вес. Есть угроза ожирения. Рекомендуем обратиться к врачу'\
' для консультации по поводу изменений в режиме питания и физической'\
' активности.')
# Male and over 14 but under 18 years old
elif pol == 'муж' and 14 < vozr < 18:
if bmi <= 17:
print('Критически недостаточная масса. Рекомендуется срочно обратиться'\
' к врачу для проведения обследования')
elif 17 < bmi < 20:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин')
elif 20 <= bmi <= 24:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif bmi > 24:
print('Избыточный вес. Есть угроза ожирения. Рекомендуем обратиться к врачу'\
' для консультации по поводу изменений в режиме питания и физической'\
' активности.')
# Male and over or equal 18 but under 30 years old
elif pol == 'муж' and 18 <= vozr < 30:
if bmi < 18:
print('Выраженный дефицит массы. Рекомендуется обратиться к врачу для'\
' проведения обследования')
elif 18 <= bmi < 21:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин.'\
' Необходимо проконтролировать режим питания и сна.')
elif 21 <= bmi < 24:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif 24 <= bmi < 26:
print('Избыточный вес. Предожирение. Рекомендуем контролировать режим питания'\
' и сна.')
elif 26 <= bmi < 32:
print('Ожирение первой степени. Рекомендуем обратиться к врачу для'\
' консультации по поводу изменений в режиме питания, сна и физической'\
' активности.')
elif 32 <= bmi < 37:
print('Ожирение второй степени. Рекомендуем обратиться к врачу для проведения'\
' обследования и лечения')
elif bmi >= 37:
print('Ожирение третьей степени. Рекомендуем регулярное наблюдение у врача,'\
' выполнение исследований и лечение в целях снижения излишнего веса.')
# Male and over or equal 30 but under 50 years old
elif pol == 'муж' and 30 <= vozr < 50:
if bmi < 18:
print('Выраженный дефицит массы. Рекомендуется обратиться к врачу для'\
' проведения обследования')
elif 18 <= bmi < 21:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин.'\
' Необходимо проконтролировать режим питания и сна.')
elif 21 <= bmi < 24:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif 24 <= bmi < 26:
print('Избыточный вес. Предожирение, риск сердечно-сосудистых заболеваний.'\
' Рекомендуем контролировать режим питания и сна.')
elif 26 <= bmi < 32:
print('Ожирение первой степени. Повышенный риск сердечно-сосудистых заболеваний.'\
' Рекомендуем обратиться к врачу для консультации по поводу изменений'\
' в режиме питания, сна и физической активности.')
elif 32 <= bmi < 37:
print('Ожирение второй степени. Рекомендуем обратиться к врачу для проведения'\
' обследования и лечения. Необходимо снизить избыточный вес.')
elif bmi >= 37:
print('Ожирение третьей степени. Рекомендуем регулярное наблюдение у врача,'\
' выполнение исследований, лечение в целях снижения излишнего веса и'\
' нормализации всех жизненных фунций организма.')
# Male and over or equal 50 but under 70 years old
elif pol == 'муж' and 50 <= vozr < 70:
if bmi < 15:
print('Выраженный дефицит массы. Рекомендуется обратиться к врачу для'\
' проведения обследования')
elif 15 <= bmi < 17:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин.'\
' Необходимо проконтролировать режим питания и сна.')
elif 17 <= bmi < 24:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif 24 <= bmi < 29:
print('Избыточный вес. Предожирение. Рекомендуем контролировать режим питания'\
' и сна.')
elif 29 <= bmi < 35:
print('Ожирение первой степени. Рекомендуем обратиться к врачу для'\
' консультации по поводу изменений в режиме питания, сна и физической'\
' активности.')
elif 35 <= bmi < 40:
print('Ожирение второй степени. Рекомендуем регулярное наблюдение у врача,'\
' выполнение исследований, лечение в целях снижения излишнего веса и'\
' нормализации всех жизненных фунций организма.')
elif bmi >= 40:
print('Ожирение третьей степени. Рекомендуем регулярное наблюдение у врача,'\
' выполнение исследований, лечение в целях снижения излишнего веса и'\
' нормализации всех жизненных фунций организма.')
# Male and over or equal 70 years old
elif pol == 'муж' and vozr >= 70:
if bmi < 15:
print('Выраженный дефицит массы. Рекомендуется обратиться к врачу для'\
' проведения обследования')
elif 15 <= bmi < 17:
print('Недостаточная масса. Рекомендуем обратиться к врачу для выяснения причин.'\
' Необходимо проконтролировать режим питания и сна.')
elif 17 <= bmi < 24:
print('Здоровый вес. Рекомендуем поддерживать при помощи правильного'\
' образа жизни')
elif 24 <= bmi < 29:
print('Избыточный вес. Предожирение, риск сердечно-сосудистых заболеваний.'\
' Рекомендуем контролировать режим питания и сна.')
elif 29 <= bmi < 34:
print('Ожирение первой степени. Рекомендуем регулярное наблюдение у врача,'\
' выполнение исследований, лечение в целях снижения излишнего веса и'\
' нормализации всех жизненных фунций организма.')
elif 34 <= bmi < 39:
print('Ожирение второй степени. Рекомендуем регулярное наблюдение у врача,'\
' выполнение исследований, лечение в целях снижения излишнего веса и'\
' нормализации всех жизненных фунций организма.')
elif bmi >= 39:
print('Ожирение третьей степени. Рекомендуем регулярное наблюдение у врача,'\
' выполнение исследований, лечение в целях снижения излишнего веса и'\
' нормализации всех жизненных фунций организма.')
d[name] = {'Пол': pol,
'Возраст': vozr,
'Вес': ves,
'Рост': rost,
'BMI': bmi
}
for key, val in d.items():
print(key, val)
z = z + 1
|
53db0dce8f7a24c3d490db5e66d590168b7ea01d | parxhall/com404 | /1-basics/3-decision/11-review/bot.py | 1,028 | 4.3125 | 4 | #ask for input
direction = input("Which way should we run?\n")
#if statement
if direction == "left":
#input
action = input("There is a branch in the way what should we do?\n")
#nested if statement
if action == "jump":
print("Yes we made it over!")
elif action =="go round":
print("We are being too slow he is gaining!")
else:
print("You didn't decide fast enough")
#else if statement
elif direction == "right":
speed = input("How fast are you running\n")
if speed == "fast" or "speedy":
print("Good choice, we're getting away!")
elif speed == "not fast" or "slow":
print("The monster is gaining on us!")
#else statment
else:
print("You didn't decide fast enough")
#multiple conditions with logical if or statement
if direction == "right":
print("Well done! We made it out alive!")
#else if and or statemant
elif (direction == "left") and (action != "jump" or "go round"):
print("You didn't decide fast enough and the monster got you o-o")
|
9293dec395810d8c32305b9ca862f09a045d6616 | Naveenkota55/maze_test | /test_2.py | 2,966 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 00:10:55 2020
@author: naveenkota
"""
import turtle
wn=turtle.Screen();
wn.bgcolor("white");
wn.setup(700,700);
wn.title("Maze 2");
class Marker(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.color("black")
self.shape("square")
self.penup()
self.speed(0)
class Player(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.color("red")
self.shape("square")
self.penup()
self.speed(0)
def go_up(self):
move_x= self.xcor()
move_y= self.ycor()+24
if (move_x,move_y) not in wall:
self.goto(move_x,move_y)
def go_down(self):
move_x= self.xcor()
move_y= self.ycor()-24
if (move_x,move_y) not in wall:
self.goto(move_x,move_y)
def go_right(self):
move_x= self.xcor()+24
move_y= self.ycor()
if (move_x,move_y) not in wall:
self.goto(move_x,move_y)
def go_left(self):
move_x= self.xcor()-24
move_y= self.ycor()
if (move_x,move_y) not in wall:
self.goto(move_x,move_y)
levels=[""];
level_1= [
"XXXXXXXXXXXXXXXXXXXXXXXXX",
"XP XXXXXXXXXXX XXX GXXX",
"X XXXXXXXXXXX XXX XX",
"X XXXXXXXX XXXXX XXX",
"XX XXXXXXXX G XX",
"XX XXXXXXXXXXXX XXXXXX",
"XX XXXXXXXXXXXX XXXXXXX",
"XXX XXXXX",
"XXXXXXX XXX XX XXXXXXX",
"XXXXXXX XXXGXX XXXXXXX",
"XXXX XXXXXX XXXXXXX",
"XXXX XXXXXX XXXXXXX",
"XXXXXXXXXXXXXXXX XXXXXXX",
"XXXXX XXX GX",
"XXXXX XXXXXXXXXXXXX X",
"XXXXX XXXXXXXXXXXX XX",
"XXXXX XX",
"XXXXXXXXX XXXXXXXXXX",
"XXXXXXXXX XXXXXXXXXX",
"XXXXXXXXX XXXXXXXXXX",
"XXXXXXXXX XXXX",
"XXXXXXXXXXXXXXXXX XXXX",
"XXXXX GXXXX",
"XXXXXG XXXXXXXXXXXXXXXXX",
"XXXXXXXXXXXXXXXXXXXXXXXXX",
];
levels.append(level_1);
def maze_setup(level):
for y in range(len(level)):
for x in range(len(level[y])):
charc=level[y][x];
screen_x= -288 + (x*24);
screen_y =288- (y*24);
if charc=="X":
marker.goto(screen_x,screen_y);
marker.stamp();
wall.append((screen_x,screen_y))
if charc=="P":
player.goto(screen_x,screen_y);
if charc=="G":
player.goto(screen_)
marker=Marker();
level=levels[1];
player=Player();
wall=[];
maze_setup(level);
turtle.listen()
turtle.onkey(player.go_left,"Left")
turtle.onkey(player.go_right,"Right")
turtle.onkey(player.go_up,"Up")
turtle.onkey(player.go_down,"Down")
#turn screen updates oof
wn.tracer(0)
#main game loop
while True:
wn.update() |
3b0b8161abc02dcd9a68dcafbe0405fc3e364ddc | SanGlebovskii/lesson_5 | /homework_5_4.py | 164 | 3.8125 | 4 | n = int(input())
def sum_of_n(number) -> int:
summary = 0
for i in range(1, number + 1):
summary += 1 / i
return summary
print(sum_of_n(n))
|
1d546ea8d170fc0c62002293aa16e216708943ef | IceAge0/hello-world | /GUI_for_py/TryMainWindow.py | 737 | 3.578125 | 4 | from tkinter import *
class MainWindow:
def __init__(self):
self.frame=Tk()
self.label_name = Label(self.frame,text='name:')
self.label_age = Label(self.frame,text='age:')
self.label_sex = Label(self.frame,text='sex:')
self.text_name = Text(self.frame,height='1',width=30)
self.text_age = Text(self.frame,height='1',width=30)
self.text_sex = Text(self.frame,height='1',width=30)
#按照网格线排列文本框
self.label_name.grid(row=0,colum=0)
self.label_age.grid(row=1,colum=0)
self.label_sex.grid(row=2,colum=0)
self.button_ok =Button(self.frame,text='ok',width=10)
self.button_cancel =Button(self.frame,text='cancel',width=10)
self.frame.mainloop()
frame = MainWindow() |
4b47cd1d45c5a4a1a5587b8f14d48b896eab145b | vc2309/interview_prep | /dp/knapsack.py | 515 | 3.796875 | 4 | def knapsack(W, weights, values):
K={w:v for w,v in zip(weights,values)}
for i in range(W+1):
max_weight=0
for j,wi in enumerate(weights):
if wi <=i:
rem_val=K.get(i-wi) if K.get(i-wi) else 0
max_weight=max(rem_val+wi,rem_val)
K[i]=max_weight
return K[W]
def main():
weights=[2,2,3,4]
values=[10,40,30,100]
print("Weight\tValue")
for w,v in zip(weights,values):
print(str(w)+"\t"+str(v))
W=int(input("Enter weight"))
print(knapsack(W,weights,values))
if __name__ == '__main__':
main() |
f122116a725b6cd0776182155202b4b64c4edd4d | rperezl-dev/S1-TAREA1-POO | /Ejemplo 4.py | 649 | 4 | 4 | #Ejemplo 4
#Construir un algoritmo tal, que dado como dato la calificación de un alumno en un examen, presente un alumno aprueba
# si la calificación es mayor o igual que 7
class Examen():
def __init__(self):
self.calificacion=float
def calificacion_exam(self):
try:
calificacion = float(input('Ingrese la califacion obtenida en el examen: '))
if calificacion >= 7:
print('¡Alumno aprobado!')
else:
print('¡Alumno Reprobado!')
except:
print('Error, ingrese solo valores númericos.')
Miexamen=Examen()
Miexamen.calificacion_exam() |
9a4882b0f8d534283008bee7da063a8f791a7d6d | MadisMaisalu/prog_alused_vs20 | /otsast peale/yl2/yl3.py | 2,077 | 3.71875 | 4 | vanus = int(input("Sisestage enda vanus: "))
while vanus >= 150: # vanuse limiidiks on 150
vanus = int(input("Viga! Proovige uuesti: ")) # veateade kui on üle 150
sugu = input("Sisestage enda sugu (Mees/Naine): ")
while (sugu !="Mees") or (sugu !="Naine"): # veateade kui pole Mees või Naine !!!!SIIN ON MINGI VIGA!!!!! EI LASE VALIDA NAINE
sugu = input("Viga! Proovige uuesti! Kasutage suurt esitähte (Mees/Naine): ")
treening = input("Valge treeningtüüp: Tervisetreening, Põhivastupidavus, Intensiivne ")
while treening != "Tervisetreening" or treening != "Põhivastupidavus" or treening != "Intensiivne":
treening = input("Viga! Valige treeningtüüp(Tõstutundlik): Tervisetreening, Põhivastupidavus, Intensiivne ") # ainult tervisetreening töötab
# mehed
meeste_max_pulss = (220 - vanus)
naiste_max_pulss = (206 - vanus*0.88)
if treening == "Tervisetreening" and sugu == "Mees":
print("Teie normaalne pulsisagedus on " +
str(round(meeste_max_pulss*0.5)) +
" kuni " + str(round(meeste_max_pulss*0.75)))
if treening == "Põhivastupidavus" and sugu == "Mees":
print("Teie normaalne pulsisagedus on " +
str(round(meeste_max_pulss*0.7)) +
" kuni " + str(round(meeste_max_pulss*0.80)))
if treening == "Intensiivne" and sugu == "Mees":
print("Teie normaalne pulsisagedus on " +
str(round(meeste_max_pulss*0.8)) +
" kuni " + str(round(meeste_max_pulss*0.87)))
# naised
if treening == "Tervisetreening" and sugu == "Naine":
print("Teie normaalne pulsisagedus on " +
str(round(naiste_max_pulss*0.5)) +
" kuni " + str(round(naiste_max_pulss*0.75)))
if treening == "Põhivastupidavus" and sugu == "Naine":
print("Teie normaalne pulsisagedus on " +
str(round(naiste_max_pulss*0.7)) +
" kuni " + str(round(naiste_max_pulss*0.80)))
if treening == "Intensiivne" and sugu == "Naine":
print("Teie normaalne pulsisagedus on " +
str(round(naiste_max_pulss*0.8)) +
" kuni " + str(round(naiste_max_pulss*0.87)))
|
28e0f23c9eecd1302ca6ffd7d7161b66a0e893c2 | tapanprakasht/Simple-Python-Programs | /str1.py | 243 | 3.734375 | 4 | #!/usr/bin/python3
class Palindrome:
def __init__(self):
self.string=""
self.length
def getString(self):
self.string=input("Enter the string:"))
self.length=len(self.string)
def findPalindrome(self):
temp=self.length |
a2f729047406e1550433844dcb8834da77eb3a5c | mukishrita/-rita-final-week-BC-UG | /test_cases/dojo_test.py | 1,489 | 3.609375 | 4 | import unittest
from class_models.the_dojo import Dojo
class TestCreateRoom(unittest.TestCase):
"""Dojo allocates rooms to staff and fellow"""
def test_create_room_successfully(self):
dojo_instance = Dojo()
initial_room_count = len(dojo_instance.list_rooms)
blue_office = dojo_instance.create_room("Blue", "office")
self.assertTrue(blue_office)
new_room_count = len(dojo_instance.list_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
def test_room_already_exists(self):
dojo_instance = Dojo()
blue_office = dojo_instance.create_room("Blue", "office")
blue_exists = dojo_instance.room_exists("Blue")
self.assertTrue(blue_exists)
def test_add_person_successfully(self):
dojo_instance = Dojo()
initial_people_count = len(dojo_instance.list_people)
rita_fellow = dojo_instance.add_person("Rita", "fellow")
self.assertTrue(rita_fellow)
new_people_count = len(dojo_instance.list_people)
self.assertEqual(new_people_count - initial_people_count, 1)
def test_person_already_exists(self):
dojo_instance = Dojo()
rita = dojo_instance.add_person("Rita", "fellow")
rita_exists = dojo_instance.person_exists("Rita")
self.assertTrue(rita_exists)
# def test_person_name_str():
# pass
if __name__ == '__main__':
unittest.main()
|
db401e9f7d3daf566325c896d749779f63d4047c | aadarshraj4321/Python-Small-Programs-And-Algorithms | /Data Structure Problems/dictionary/search_element_dict.py | 256 | 4.09375 | 4 |
myDict = {"name": "Elon Musk", "age": 45, "year": 2021}
def searchDict(dictionary, value):
for key in dictionary:
if(dictionary[key] == value):
return [key, value]
return []
print(searchDict(myDict, 2021))
|
1beb2568dea5f30e8ee3ca31c2c4d08d9c3a038b | Ahmad-Omar-Ahsan/Python_tutorials | /Exercise/polygon.py | 1,734 | 4.25 | 4 | import TurtleWorld
import math as m
world = TurtleWorld.TurtleWorld()
bob = TurtleWorld.Turtle()
print(bob)
"""
for i in range(4):
print ('Hello!')
for num in range(4):
fd(bob, 100)
rt(bob)
"""
def square(t, length):
""" Draw a square with sides of given length
:param t:
:param length:
:return: returns the turtle to staring position or location
"""
for num in range(4):
TurtleWorld.fd(t, length)
TurtleWorld.rt(t)
def polyline(t, n, length, angle):
for i in range(n):
TurtleWorld.fd(t, length)
TurtleWorld.rt(t, angle)
def polygon(t, length, n):
""" Draws a polygon with n sides
:param t: Turtle
:param length: length of each side
:param n: number of sides
:return:
"""
angle = 360 / n
polyline(t, n, length, angle)
# polygon(bob,100,6)
def circle(t, r):
"""
Draws a circle with given radius
:param t: turtle
:param r: radius
:return:
"""
circumference = 2 * m.pi * r
n = int(circumference / 3) + 1
length = circumference / n
polygon(t, length, n)
def arc(t, r, angle):
arc_length = 2 * m.pi * r * angle / 360
n = int(arc_length / 3) + 1
step_length = arc_length / n
step_angle = float(angle) / n
polyline(t, n, step_length, step_angle)
#square(bob, 150)
#polygon(bob, 100, 6)
#bob.delay = 0.01
#circle(bob, 50)
#arc(bob, 100, 90)
def draw(t, length, n):
if n == 0:
return
angle = 50
TurtleWorld.fd(t, length*n)
TurtleWorld.lt(t, angle)
draw(t, length, n-1)
TurtleWorld.rt(t, 2*angle)
draw(t, length, n-1)
TurtleWorld.lt(t, angle)
TurtleWorld.bk(t, length*n)
draw(bob, 10, 10)
TurtleWorld.wait_for_user()
|
420e99b8201ca9461cfcea344d0adf0f430096b0 | Orusake/Guess_a_number | /GameEngine.py | 1,736 | 4.4375 | 4 | # Drawing Functions
# the Drawing Functions are only used to draw function, not used to change values! They only display them.
# Add colors
# https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-python
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m' # red
ENDC = '\033[0m' # stop the color
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def drawWelcomeMessage():
print("Hello! Welcome to my little game Guess my number! :) What's your name?")
def drawRemaining(guesses_available, guesses_taken):
print("Now you have", guesses_available - guesses_taken , "guesses remaining.")
def drawResultNotCorrect(guess, number):
if guess < number:
print(bcolors.FAIL + "Your guess is too low." + bcolors.ENDC)
if guess > number:
print(bcolors.FAIL + "Your guess is too high." + bcolors.ENDC)
def drawWinningMessage(my_name, guesses_taken, win_score, loose_score):
print(bcolors.OKGREEN + "Bravo, " + my_name + "! You guessed my number in " + str(guesses_taken) + " guesses!" + bcolors.ENDC)
print("You win " + str(win_score) + " times." "You loose " + str(loose_score) + " times.")
def drawLoosingMessage(my_name, number, win_score, loose_score):
print(bcolors.OKBLUE + "How bad, "+ my_name + ". The number I was thinking of was " + str(number) +"." + bcolors.ENDC)
print("You win " + str(win_score) + " times." "You loose " + str(loose_score) + " times.")
def drawLine(length):
print("-" * length)
def drawSadEmoji():
print(bcolors.OKGREEN + "(T.T) No? OK..." + bcolors.ENDC)
def drawHappyEmoji():
print(bcolors.OKGREEN + "\(^0^)/ Great!" + bcolors.ENDC)
|
5b8166afdd457a1d27a3f48f05b788667cec22aa | hung1451020115/1451020115 | /songuyento.py | 312 | 3.734375 | 4 | print("nhap vao 1 so")
a = int(input())
if a < 2:
print("a không là số nguyên tố")
if (a == 2):
print(a,"là số nguyên tố")
else:
for i in range(3,n,1):
if (n % i ==0):2
print("a không là số nguyên tố")
else:
print("a là số nguyên tố") |
5df7f91c9b8426ef1fc05777c2353afaad99fdc3 | varshavasthavi/SummerProjects18 | /RE-Cryptography/Sessions-5-&-6/VarunKM/VarunKM-caesar_encryption.py | 876 | 3.609375 | 4 |
f1 = open("VarunKM-message-caesar.txt","r") # open file1
f2 = open("VarunKM-caesar_ciphertext.txt","w+")
while True:
char = f1.read(1) # read char by char from file1
if not char: # break when endoffile is reached
break
else:
if str(char).isalpha(): # to check if char is an alphabet
encr_char = ((ord(char) + 7 - 96) % 26) # adding caesar cipher
if encr_char:
encr_char = chr(encr_char + 96)
else:
encr_char = 'z'
else:
encr_char = char # no change if char is not an alphabet
f2.write(encr_char) # write encripted char into file2
f1.close()
f2.close() # close all files
|
2448a0727775c5e99f195aeb5c592277b50446c7 | crazyguy106/cfclinux | /steven/python/personal_workshop/loops/loop_dictionary.py | 242 | 4.1875 | 4 | #!/usr/bin/python3
dictionary = {'first': 1, 'second': 2, 'third': 3}
print('keys', dictionary.keys())
print('values', dictionary.values())
print('items', dictionary.items())
for key, value in dictionary.items():
print(key)
print(value)
|
99caa3c41e5c422ecd0296c09ea9b06960a7a07b | dyeap-zz/CS_Practice | /Facebook/Sliding Window/LongestSubstringKChar.py | 1,107 | 3.6875 | 4 | '''
detect unique characters
start L/R beginning
move R pointer up until k+1 unique char.
longest = l+R-1
move L pointer until k unique char
var-
num_unique_char
dictionary to keep track of num off occ
0 to 1 num_unique_char + 1
1 to 0 num_unique_char - 1
while r<len
update r
if num_uni == k:
1. store res
while move left
2. move left until d[num] ==0
update r
'''
def longest_unique(arr,k):
res = -1
l, r, u = 0 , 0, 0
d = {}
# move r
while r < len(arr):
num = arr[r]
if num not in d or d[num] == 0:
u += 1
d[num] = 1
else:
d[num] += 1
# left
if u == k+1:
#print(l,r)
res = max(res,r-l)
while True:
#print(l)
l_num = arr[l]
d[l_num] -= 1
l += 1
if d[arr[l-1]] == 0:
u -= 1
break
r += 1
if u == k:
res = max(res,r-l)
return res
arr = "aabbcc"
k = 3
print(longest_unique(arr,k)) |
c04b11fab70c49aae7815dd1ac2fa27a75eee8e6 | ajaymore/python-lang | /F03_data_structures.py | 2,581 | 3.671875 | 4 | __author__ = 'Mystique'
# Queue
from collections import deque
queue = deque(['Eric', 'john', 'Michael'])
queue.append('Terry')
queue.append('Graham')
queue.popleft()
queue.popleft()
print(queue)
# List Comprehensions
squares = list(map(lambda x: x ** 2, range(10)))
squares1 = [x ** 2 for x in range(10)]
pairs = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
print(squares)
print(squares1)
print(pairs)
vec = [-4, -2, 0, 2, 4]
# create a new list with the values doubled
result = [x * 2 for x in vec]
# filter the list to exclude negative numbers
result = [x for x in vec if x >= 0]
# apply a function to all the elements
result = [abs(x) for x in vec]
# call a method on each element
fresh_fruit = [' banana', ' loganberry ', 'passion fruit ']
result = [weapon.strip() for weapon in fresh_fruit]
# create a list of 2-tuples like (number, square)
result = [(x, x ** 2) for x in range(6)]
# flatten a list using a listcomp with two 'for'
vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = [num for elem in vec for num in elem]
# complex nested
from math import pi
result = [str(round(pi, i)) for i in range(1, 6)]
print(result)
# 3*4 matrix
result = [[row * 4 + num for num in range(4)] for row in range(4)]
print(result)
print(list(zip(*result)))
# del keyword
a = [-1, 1, 66.25, 333, 333, 1234.5]
del a[0]
del a[2:4]
del a[:]
del a
# tuples
t = 12345, 54321, 'hello!'
print(t[0])
u = t, (1, 2, 3) # nesting
print(u)
empty = () # empty tuple
singleton = 'one',
# Sets
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print('apple' in basket)
a = set('abracadabra')
b = set('alacazam')
print(a)
print(b)
print(a - b)
print(a | b)
print(a & b)
print(a ^ b)
# set comprehension
a = {x for x in 'abracadabra' if x not in 'abc'}
# Dictionaries
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
print(tel['jack'])
del tel['sape']
tel['irv'] = 4127
print(tel)
print(list(tel.keys()))
print('guido' in tel)
print('jack' not in tel)
# dictionary constructor
dictionary = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
dictionary = dict(sape=4139, guido=4127, jack=4098)
print(dictionary)
# Looping techniques
# dictionary
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
print(k, v)
# sequence
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
# loop two or more sequences at the same time
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print('What is your {0}? It is {1}.'.format(q, a)) |
2cbd81c64e374d23c08a4f2e4d036570a3a9410a | unsortedtosorted/FastePrep | /Trees/delete_zero_sum_subtree.py | 941 | 3.8125 | 4 | """
Delete Zero Sum Sub-Trees
Given the root of a binary tree, delete any subtrees whose nodes sum up to zero.
1. delete_zero_sum_subtree left sub tree
2. delete_zero_sum_subtree right sub tree
3. return root.val + left subtree sum +right subtree sum
Runtime : O(N)
Memory : O(h)
Recursive solution has O(h) memory complexity as it will consume memory
on the stack up to height of binary tree h.
It will be O(logn) for balanced tree and in the worst case can be O(n).
"""
def delete_zero_sum_subtree(root):
def delesumsub(root):
if root:
if root.left or root.right:
lsum = delesumsub(root.left)
rsum = delesumsub(root.right)
if lsum == 0:
root.left = None
if rsum == 0:
root.right = None
return root.data+lsum+rsum
else:
return root.data
delesumsub(root)
return root
|
8b0f0aa35bcdc645924dcc76ae43dbd7fc5d2ef9 | ivklisurova/SoftUni_Fundamentals_module | /Basic_Syntax_Conditional_Statements_Loops/Double_Char.py | 104 | 4 | 4 | word = input()
double_word = ''
for letter in word:
double_word += letter * 2
print(double_word)
|
6ce2e284d8e874017b13957f0cd86a044f8d1788 | linhye04/python_calc | /My Calculator.py | 786 | 3.609375 | 4 | from tkinter import*
window=Tk()
window.title("My Calculator")
display=Entry(window, width=33, bg="pink")
display.grid(row=0, column=0, columnspan=5)
button_list=[
'7', '8', '9', '/', 'C',
'4', '5', '6', '*', '%',
'1', '2', '3', '-', '//',
'0', '.', "=", '+', '']
def click(key):
if key=="=":
result=eval(display.get())
s=str(result)
display.insert(END, "="+s)
elif key=="C":
display.delete(0, END)
else:
display.insert(END, key)
row_index=1
col_index=0
for button_text in button_list:
def process(t=button_text):
click(t)
Button(window, text=button_text, width=5, command=process).grid(row=row_index, column=col_index)
col_index+=1
if col_index>4:
row_index+=1
col_index=0
|
0990e4bf6104e5578129c70402f784e58ace9503 | chimble/what-to-watch | /movie_lib3.py | 1,075 | 3.75 | 4 | import csv
class Movie():
def __init__(self, movie_id, movie_name):
self.movie_id = movie_id
self.movie_name = movie_name
def get_name(self, movie_id):
#return movie name given ID
return self.movie_name
#print(movie.get_name('1'))
def movie_data():
with open('u.item.test.csv') as f:
fieldnames = ['movie_id', 'movie_name']
reader = csv.DictReader(f, fieldnames = fieldnames, delimiter = '|')
dict_of_movie_name_id = {}
list_of_dicts = []
list_of_movies = []
for row in reader:
#movie = movie(row)
dict_of_movie_name_id[row['movie_id']] = row['movie_name'][0:-7]
list_of_dicts.append({'movie_id': row['movie_id'], 'movie_name': row['movie_name'][0:-7]})
movie = Movie(row['movie_id'], row['movie_name'][0:-7])
list_of_movies.append(movie)
print(list_of_movies)
print(dict_of_movie_name_id)
print(list_of_dicts)
# print(dict_of_movie_name_id)
movie_data()
print(movie.get_name('3'))
|
51e27f6b75e1b05d8b3e104c5461091904689a0c | BlairWu/python_pycharm | /structure.py | 9,377 | 4.15625 | 4 | #!/usr/bin/python3
print("=============== 列表 ================")
"""
Python中列表是可变的,这是它区别于字符串和元组的最重要的特点,
一句话概括即:列表可以修改,而字符串和元组不能。
方法 描述
list.append(x) 把一个元素添加到列表的结尾,相当于 a[len(a):] = [x]。
list.extend(L) 通过添加指定列表的所有元素来扩充列表,相当于 a[len(a):] = L。
list.insert(i, x) 在指定位置插入一个元素。第一个参数是准备插入到其前面的那个元素的索引,例如 a.insert(0, x) 会插入到整个列表之前,而 a.insert(len(a), x) 相当于 a.append(x) 。
list.remove(x) 删除列表中值为 x 的第一个元素。如果没有这样的元素,就会返回一个错误。
list.pop([i]) 从列表的指定位置移除元素,并将其返回。如果没有指定索引,a.pop()返回最后一个元素。元素随即从列表中被移除。(方法中 i 两边的方括号表示这个参数是可选的,而不是要求你输入一对方括号,你会经常在 Python 库参考手册中遇到这样的标记。)
list.clear() 移除列表中的所有项,等于del a[:]。
list.index(x) 返回列表中第一个值为 x 的元素的索引。如果没有匹配的元素就会返回一个错误。
list.count(x) 返回 x 在列表中出现的次数。
list.sort() 对列表中的元素进行排序。
list.reverse() 倒排列表中的元素。
list.copy() 返回列表的浅复制,等于a[:]。
注意:类似 insert, remove 或 sort 等修改列表的方法没有返回值。
"""
# a = [66.25, 333, 333, 1, 1234.5]
# print("a.count(333) =",a.count(333))
# print("a.count(66.25) =",a.count(66.25))
# print("a.count('x') =",a.count('x'))
# a.insert(2, -1) # 无返回值
# print("a.insert(2, -1) =",a)
# a.append(333) # 无返回值
# print("a.append(333) =",a)
# a.remove(333) # 无返回值
# print("a.remove(333) =",a)
# a.reverse() # 无返回值
# print("a.reverse() =",a)
# a.sort() # 无返回值
# print("a.sort() =",a)
# print("a.index(333) =",a.index(333)) # 有返回值
print("=============== 将列表当做堆栈使用 ================")
"""
将列表当做堆栈使用
列表方法使得列表可以很方便的作为一个堆栈来使用,堆栈作为特定的数据结构,最先进入的元素最后一个被释放(后进先出)。
用 append() 方法可以把一个元素添加到堆栈顶。用不指定索引的 pop() 方法可以把一个元素从堆栈顶释放出来。
"""
# stack = [3, 4, 5]
# stack.append(6) # 无返回值
# stack.append(7) # 无返回值
# print(stack)
# print(stack.pop()) # 有返回值
# print(stack)
# print(stack.pop()) # 有返回值
# print(stack)
# print(stack.pop()) # 有返回值
# print(stack)
# print(stack.pop()) # 有返回值
# print(stack)
# print(stack.pop()) # 有返回值
# print(stack)
print("=============== 将列表当作队列使用 ================")
"""
也可以把列表当做队列用,只是在队列里第一加入的元素,第一个取出来;但是拿列表用作这样的目的效率不高。
在列表的最后添加或者弹出元素速度快,然而在列表里插入或者从头部弹出速度却不快(因为所有其他的元素都得一个一个地移动)。
"""
# from collections import deque
# queue = deque(["Eric", "John", "Michael"])
# queue.append("Terry")
# queue.append("Graham")
# print("queue.popleft():",queue.popleft())
# print("queue.popleft():",queue.popleft())
# print("queue:",queue)
print("=============== 列表推导式 ================")
"""
列表推导式提供了从序列创建列表的简单途径。
通常应用程序将一些操作应用于某个序列的每个元素,
用其获得的结果作为生成新列表的元素,或者根据确定的判定条件创建子序列。
***每个列表推导式都在 for 之后跟一个表达式,然后有零到多个 for 或 if 子句。***
返回结果是一个根据表达从其后的 for 和 if 上下文环境中生成出来的列表。
如果希望表达式推导出一个元组,就必须使用括号。
"""
# vec = [2,4,6]
# a = [3*x for x in vec] # [6, 12, 18]
# print(a)
# a1 = [3*x for x in vec if x > 3]
# print(a1)
# a2 = [3*x for x in vec if x < 2]
# print(a2)
# b = [[x,x**2] for x in vec] # [[2, 4], [4, 16], [6, 36]]
# print(b)
# freshfruit = [' banana',' loganberry ','passion fruit ']
# c = [weapon.strip() for weapon in freshfruit]
# print(c)
# vec1 = [2, 4, 6]
# vec2 = [4, 3, -9]
# d = [x*y for x in vec1 for y in vec2]
# print(d)
# d1 = [x+y for x in vec1 for y in vec2]
# print(d1)
# d2 = [vec1[i]*vec2[i] for i in range(len(vec1))]
# print(d2)
# e = [str(round(355/113, i)) for i in range(1, 20)]
# print(e)
print("=============== 嵌套列表解析 ================")
# 3X4的矩阵列表
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10,11,12],
]
# print([[row[i] for row in matrix] for i in range(4)])
"""
法二:
transposed = []
for i in range(4):
transposed.append([row[i] for row in matrix])
print(transposed)
"""
"""
法三:
transposed = []
for i in range(4):
transposed_row = []
for row in matrix:
transposed_row.append(row[i])
transposed.append(transposed_row)
print(transposed)
"""
print("=============== del 语句 :删除索引来删除值 ================")
"""
使用 del 语句可以从一个列表中依索引而不是值来删除一个元素。
这与使用 pop() 返回一个值不同。可以用 del 语句从列表中删除一个切割,
或清空整个列表(我们以前介绍的方法是给该切割赋一个空列表)。
"""
# a = [-1, 1, 66.25, 333, 333, 1234.5]
# del a[4]
# print(a)
# del a[2:4]
# print(a)
# del a[:]
# print(a)
print("=============== 元组和序列 ================")
# t = 12345, 54321, 'hello!'
# print(t[0])
# print(t)
# u = t, (1, 2, 3, 4, 5)
# print(u)
"""
元组在输出时总是有括号的,以便于正确表达嵌套结构。
在输入时可能有或没有括号, 不过括号通常是必须的(如果元组是更大的表达式的一部分)。
"""
print("=============== 集合 ================")
"""
可以用大括号({})创建集合。
注意:如果要创建一个空集合,你必须用 set() 而不是 {} ;
后者 {} 创建一个空的字典
"""
# basket = {'apple', 'orange','apple','pear','orange','banana'}
# print(basket)
# print('orange' in basket)
# print('crabgrass' in basket)
# a = set('abrabadabra')
# b = set('alacazam')
# print(a)
# print(b)
# print(a-b) # 仅在a
# print(a|b) # 或
# print(a&b) # 且
# print(a^b) # 异或
# print({x for x in a if x not in 'abc'})
print("=============== 字典 ================")
"""
序列是以连续的整数为索引,与此不同的是,字典以关键字为索引,
关键字可以是任意不可变类型,通常用字符串或数值。
理解字典的最佳方式是把它看做无序的键=>值对集合。
在同一个字典之内,关键字必须是互不相同。
一对大括号创建一个空的字典:{}。
"""
"""
tel = {'jack':4098, 'sape':4139}
tel['guido'] = 4127
print(tel)
print(tel['jack'])
del tel['sape']
tel['irv'] = 4127
print(tel)
print(list(tel.keys()))
print(list(tel.values()))
print(sorted(tel.keys()))
print('guido' in tel)
print('jack' not in tel)
"""
"""
# 构造函数 dict() 直接从键值对元组列表中构建字典。
# 如果有固定的模式,列表推导式指定特定的键值对
print(dict([('space',4139), ('guido',4127), ('jack',4098)]))
print(dict((('space',4139), ('guido',4127), ('jack',4098))))
print(dict({('space',4139), ('guido',4127), ('jack',4098)}))
# 此外,字典推导可以用来创建任意键和值的表达式词典
print({x : x**2 for x in (2,4,6)})
print({x : x*2 for x in (1,3,5,7,9,11,13,15,17,19)})
# 如果关键字只是简单的字符串,使用关键字参数指定键值对有时候更方便
print(dict(sape=4139, guido=4127, jack=4098))
print(dict(yuhaorong=1990,wuduoduo=1991,wuxiuwen=1995, lichang=1995, chenjialiang=1995,baokangkang=1996))
"""
print("=============== 遍历技巧 ================")
# 在字典中遍历时,关键字和对应的值可以使用 items() 方法同时解读出来
knights = {'gallahad':'the pure', 'robin':'the brave'}
for k, v in knights.items(): # print(knights['robin'])
print(k, v)
# 在序列中遍历时,索引位置和对应值可以使用 enumerate() 函数同时得到
for i, j in enumerate(['tic','tac','toe']):
print(i,j)
# 同时遍历两个或更多的序列,可以使用 zip() 组合
names = ['xwwu','changli','jialchen']
questions = ['sex','quest','favorite color']
answers = ['female','the holy grail','blue']
for n,q,a in zip(names,questions,answers):
print('Hi,{0}. What is your {1}? It is {2}.'.format(n,q,a))
# 要反向遍历一个序列,首先指定这个序列,然后调用 reversed() 函数
for i in reversed(range(1, 10, 2)):
print(i)
for j in reversed(range(1,100,2)):
print(j)
# 要按顺序遍历一个序列,使用sorted()函数返回一个已排序的序列,并不修改原值
basket = ['apple','orage','apple','pear','orange','banana']
for f in sorted(set(basket)): # set() 空集;{} 空字典;() 元组;[] 列表
print(f) |
496c14038cf08bdb986940afa273993e4d50f497 | chinweeee/Data-science-SCA-path-projects | /week3.py | 1,891 | 4.375 | 4 | # SCA PROJECT
# 3RD WEEK PROJECT
#Exercise 1: Write a Python program to get the largest and lowest numbers from a list
list1 = [21,43,24,555,12,859]
print(max(list1))
print(min(list1))
#Exercise 2: Create a dictionary with the names and birthdays of at least five people. write a program that displays a person's birthday if found in the dictionary, and if not found, it should update the dictionary and add the birthday and name of the person. , Concepts to keep in mind:, Input(), function, dictionary
birthdays_deets = {
"mzsusan" : {"Name": "Susan Onukogu", "Date": "3rd Dec"},
"nancy2" : {"Name": "Nancy Ale", "Date": "24th May"},
"amaka1" : {"Name": "Amaka Lea", "Date": "18th Sept"},
"oscar45" : {"Name": "Oscar Micheal", "Date": "24th May"},
}
username = input('Enter username: ')
if username in birthdays_deets:
print('Fullname:', birthdays_deets[username]['Name'], ', Birthday: ', birthdays_deets[username]['Date'])
else:
# collect full name
user_fullname = input('Enter full name: ')
# collect date of birth
user_dob = input('Enter date of birth: ')
# create new entry for user in dictionary, using data collected already.
birthdays_deets[username]= { 'Name': user_fullname, 'Date': user_dob }
# print user details
print('Fullname:', birthdays_deets[username]['Name'], ' Birthday: ', birthdays_deets[username]['Date'])
print('entire object')
print(birthdays_deets)
# print a thank you message
print('Thank you')
#Exercise 3: Write a program to update a tuple
ages = (20,23,35,46,12,61)
agesList = list(ages)
newage = [2 * item for item in agesList]
print(tuple(newage))
#Exercise 4: Write a Python program to create a union of sets
friends1 = {"Susan", "Nancy", "Amaka", "Oscar"}
friends2 = {"Joshh", "Martha", "Rita", "Susan"}
friends3 = {"Finn", "Sheila", "Fortune"}
new_friends = friends1.union(friends2,friends3)
print(new_friends) |
8ce1a63b196ccc14cf47b6e1c9b1ce62cf754a63 | jinnovation/JJinProjectEuler | /pe52.py | 375 | 3.59375 | 4 | def digits(n):
return sorted(set(map(int,str(n))))
def same_digits(n1,n2):
if digits(n1)==digits(n2):
return True
else:
return False
def trial(n): # problem-specific test case
return same_digits(n,2*n) and same_digits(n,3*n) and same_digits(n,4*n) and same_digits(n,5*n) and same_digits(n,6*n)
n = 1
while (not trial(n)):
n+=1
print n
|
27a1dfdda26c1d861aecb51339b54b33819caba7 | adx505602196/store | /day03/输入54321求执行结果.py | 117 | 3.84375 | 4 | num=int(input("请输入一个数:"))
while num != 0:
print(num % 10)
num=num//10
#'''
#1
#2
#3
#4
#5
#''' |
ba646f2068832e185fa87939106c5bd988016a1a | trashcluster/LeBezvoet | /TD20181012_STECIUK-Axel.py | 858 | 3.75 | 4 | #TD6
#Somme de 2 dés à n faces
from random import *
from math import *
def nfaces(n) :
return(int(n*random()+1))
nbfaces=int(input("Entrez le nombre de faces : "))
print(nfaces(nbfaces))
print(nfaces(nbfaces))
#Distances
#Demandes les coordonnés de 3 points à l'utilisateur et affiche la distance entre ces points
def distance(x1, y1, x2, y2) :
return(sqrt((x2-x1)**+(y2-y1)**))
Ax = int(input("Coordonnées point A en ordonnée : "))
Ay = int(input("Coordonnées point A en obscisse : "))
Bx = int(input("Coordonnées point B en ordonnée : "))
By = int(input("Coordonnées point B en abscisse : "))
Cx = int(input("Coordonnées point C en ordonnée : "))
Cy = int(input("Coordonnées point C en abscisse : "))
AB=distance(Ax, Ay, Bx, By)
BC=distance(Bx, By, Cx, Cy)
AC=distance(Ax, Ay, Cx, Cy)
print("AB",AB)
print("BC",BC)
print("AC",AC)
|
d29bde11eed907bb1990091c83215b5fda82063c | a13835614623/myPythonLearning | /01_python_basic/06_循环.py | 342 | 3.796875 | 4 | '''
Created on 2018年11月2日
循环
@author: zzk
'''
names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
# 计算1-100
# range()函数,生成一个整数序列
# range(5),生成的是[0,1,2,3,4]
sum=0
for x in range(101):
sum+=x
print(sum)
'''
while循环
'''
n=0
sum=0
while n<=100:
sum+=n
n+=1
print(sum) |
2a6fe015fdf99ddcdbc4841072fb564d91de5a12 | ArdaCet/Codewars-Repo | /Python_solutions/Replace With Alphabet Position.py | 591 | 3.859375 | 4 | def alphabet_position(text):
#alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
alphabet_string = string.ascii_lowercase
alphabet = list(alphabet_string)
alph_dict = {}
output = []
for values, keys in enumerate(alphabet):
alph_dict[keys] = values + 1
for letter in text.lower():
if letter in alph_dict.keys():
output.append(alph_dict[letter])
else:
continue
return str(output)[1:-1].replace(",","")
|
a49f52df00e0745de6de8a8e4134b75f41596a1c | giovannyCaluna/Amortizacion-Francesa | /calculator.py | 808 | 3.515625 | 4 |
class Bank:
def __init__ (self, name, anualRate,comision):
self.name = name
self.anualRate = anualRate
self.monthlyRate = (anualRate/100)/12
self.comision = comision
def feeCalculator (self, capital,n):
return round(capital*((self.monthlyRate*(1+self.monthlyRate)**n)/(((1+self.monthlyRate)**n)-1)),2)
def fullPayment(self,capital,fixedFee,month,n):
counter=0
interestTotal=0
residue = capital
while(counter<n):
counter+=1
interest=residue*self.monthlyRate
if(month>=counter):
interestTotal+=interest
amortization=fixedFee-interest
residue-=amortization
return round(capital+interestTotal+(capital*self.comision),2)
|
4afacfce8380392bb51f2aef067d53fd52e607e6 | Akashdeepsingh1/project | /LeetcodeRandom/3sum.py | 3,100 | 3.625 | 4 | def sum3(nums):
l = len(nums)
s= []
if l>2:
for i in range(l):
for j in range(i+1,l):
for k in range(j+1,l):
if nums[i]+nums[j]+nums[k] == 0:
temp = [nums[i],nums[j],nums[k]]
temp.sort()
if temp not in s:
s.append(temp)
temp = set(s)
return s
def threesum(nums):
l = []
for i in range(0, len(nums)-1):
ls = []
for j in range(i+1, len(nums)):
temp = nums[i] + nums[j]
if -temp in ls:
temp_ls = [nums[i],nums[j],-temp]
temp_ls.sort()
if temp_ls not in l:
l.append(temp_ls)
else:
ls.append(nums[j])
return l
def threesum2(nums):
dic = {}
def twosum(nums):
for i in range(0,len(nums)-1):
for j in range(i+1, len(nums)):
temp = nums[i]+nums[j]
if temp not in dic:
if nums[i]< nums[j]:
dic[nums[i] + nums[j]] = [[nums[i],nums[j]]]
else:
dic[nums[i] + nums[j]] = [[nums[j], nums[i]]]
else:
temp_l =[]
temp_l = dic[nums[i]+nums[j]]
temp_l.append([nums[i],nums[j]])
dic[nums[i]+nums[j]] = temp_l
twosum(nums)
l = []
for i in range(0, len(nums)):
if -nums[i] in dic:
le = len(dic[-nums[i]])
while le >=1:
val0, val1 = dic[-nums[i]][le]
if i != val0 and i != val1:
temp = -nums[i]
temp1 = []
if nums[val0] <= nums[val1] and nums[val0] <= -temp:
if nums[val1] <= -temp:
temp1.append([val0,val1,-temp])
elif nums[val1] <= nums[val0] and nums[val1] <= -temp:
if nums[val0] <= -temp:
temp1.append([val1,val0,-temp])
else:
if nums[val1]< nums[val0]:
temp1.append([-temp,val1,val0])
else:
temp1.append([-temp,val0,val1])
if len(temp1)>2 and temp1 not in l:
l.append(temp1)
le-=1
# def threeSum (self, nums: List[int]) -> List[List[int]]:
# l = len (nums)
# nums.sort ()
# ls = []
#
# for i in range (l):
# s = i + 1
# lst = l - 1
# while s < lst:
# temp = nums[i] + nums[s] + nums[lst]
# if temp == 0:
# ls.append (nums[i] + nums[s] + nums[lst])
# s += 1
# lst -= 1
#
# elif temp < 0:
# s += 1
# else:
# lst -= 1
# return ls
#l=sum3([-1, 0, 1, 2, -1, -4])
print(threesum2([-1,0,1,2,-1,-4]))
|
7735a1f53fe4cbe68a6a5608247d2762f9151e06 | likhi-23/DSA-Algorithms | /Searching/linear_search.py | 208 | 3.796875 | 4 | #Linear Search
a = list(map(int,input().split()))
val = int(input("Enter the search value:"))
i = 0
while(i<len(a)):
if a[i] == val:
print(i)
break
i+=1
if i >= len(a):
print("Value not found")
|
98712f1cf0721d179462b3b3713d223e72ade214 | tkp75/studyNotes | /learn-python-from-scratch/function8.py | 223 | 4.28125 | 4 | #!/usr/bin/env python3
num = 20
def multiply_by_10(n):
n *= 10
num = n # Changing the value inside the function
print (num)
return n
multiply_by_10(num)
print (num) # The original value remains unchanged
|
f7978623646fc96d7620b3b598a94c60d6dc54ee | LennonHG/ATMClicks.py | /source_code.py | 705 | 3.5 | 4 | # ATM by Lennon
class ATM:
def __init__(self, name, password, saveword):
self.name = name
self.password = password
self.saveword = saveword
def get_password(self):
return self.password
def get_saveword(self):
return self.saveword
print("Welcome to ATMClicks")
print("If you are a new user please press 1 to sign up")
print("If you are an existing user press 2 to sign in")
answer = input()
if answer == "1":
print("Welcome New user")
print("Please enter your name, password and saveword below")
user1 = ATM(input("Name:"), input("Password: "), input("saveword: "))
print(user1.get_saveword())
|
3a54f5a884746c02b28fc6128898966077f5f4e3 | VAR-solutions/Algorithms | /Sorting/Insertion Sort/Python/insertion_sort_recursively.py | 525 | 3.96875 | 4 | # Author Shubham Bindal
def insertion_sort(array,n):
# base case
if n<=1:
return
insertion_sort(array,n-1)
last = array[n-1]
j = n-2
while (j>=0 and array[j]>last):
array[j+1] = array[j]
j = j-1
array[j+1]=last
def print_arrayay(array,n):
for i in range(n):
print (array[i] , end=' ')
array = list(map(int,input("Enter the numbers to be sorted\n").split()))
n = len(array)
insertion_sort(array, n)
print_arrayay(array, n)
|
90e08ac5bbe1a160c09497abfb2b67231dc50c68 | priyankaparikh/recursion-dynamicprogramming | /add_two_numbers.py | 1,376 | 3.953125 | 4 | # You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
#
# You may assume the two numbers do not contain any leading zero, except the number 0 itself.
#
# Example
#
# Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
# Output: 7 -> 0 -> 8
# Explanation: 342 + 465 = 807.
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, value=0, nxt=None):
self.val = value
self.next = nxt
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res = ListNode()
p1 = l1
p2 = l2
# pointer to traverse the resulting list
curr = res
carry = 0
while p1 is not None or p2 is not None or carry != 0:
temp_sum = carry
if p1:
temp_sum += p1.val
p1 = p1.next
if p2:
temp_sum += p2.val
p2 = p2.next
curr.val = temp_sum % 10
carry = temp_sum // 10
if p1 is not None or p2 is not None or carry != 0:
curr.next = ListNode()
curr = curr.next
return res
|
ac8abb168d5e4cda5ac7678ac50f602fd2c4f8c9 | Kane4299/PIR | /justeprix.py | 2,408 | 3.8125 | 4 | import random
import time
import tkinter as tk
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\n")
time.sleep(1)
t = t - 1
return t
#Set the game's rule
def game(event=None):
global game_answer, player_answer, tries_left, tries_print, status, catch
p_answer = player_answer.get()
answer = int(p_answer)
if tries_left == 0:
status.set("Vous avez perdu ...")
return 0
if game_answer == answer:
status.set("Bonne réponse")
main_color="green"
window.config(bg="green")
frame.config(bg="green")
phrase.config(bg="green")
stat.config(bg="green")
tries_print_txt.config(bg="green")
return 0
if answer < game_answer:
status.set("Your price is too low")
tries_left = tries_left - 1
if answer > game_answer:
status.set("Your price is too high")
tries_left= tries_left - 1
tries_print.set(f"{tries_left} Tries left")
#Creates window
main_color = "#f5aa42"
window = tk.Tk()
window.geometry("700x300")
window.title("The price is right")
window.resizable(width=False, height=False)
window.config(bg=main_color)
#Frame 1
frame=tk.Frame(window)
frame.pack()
frame.config(bg=main_color)
frame.place(x=50, y=100)
#Set Tries Number
tries_left = 10
#Defines_answer
game_answer = random.randint(1, 100)
#Print catchphrase
catch = tk.StringVar()
catch.set("hello welcome to the Price is Right game, you need to guess the right price in 5 tries, the answer is between 0 and 100")
phrase = tk.Label(frame, textvariable=catch, bg=main_color, fg="blue")
phrase.pack()
#Player Answer
player_answer = tk.Entry(frame)
player_answer.bind('<Return>', game)
player_answer.pack()
#Create_Button
bouton = tk.Button(frame, text="Submit")
bouton.pack()
#Print status of answer
status = tk.StringVar()
status.set("Good luck have fun")
stat = tk.Label(frame, textvariable=status, bg=main_color, fg="blue")
stat.pack()
#Print remaining tries
tries_print = tk.StringVar()
tries_print.set("10 Tries left")
tries_print_txt = tk.Label(window, textvariable=tries_print, bg=main_color, fg="blue")
tries_print_txt.place(x=620, y=10)
window.mainloop()
|
d7d462ff5de9012c32f0612107ede4047eea3c2c | yuju13488/pyworkspace | /m5_str/method_is.py | 890 | 3.796875 | 4 | s1='yoyo'
s2='0413'
s3='yoyo0413'
print(s1.isalnum()) #判斷是否由字串或數字組成
print(s2.isalnum())
print(s3.isalnum())
print(s1.isalpha()) #判斷是否由純字串組成
print(s2.isalpha())
print(s3.isalpha())
print(s1.isdigit()) #判斷是否由純數字組成
print(s2.isdigit())
print(s3.isdigit())
print("--------------------")
#判斷識別字(須為字母、數字、底線,不可數字開頭,需區分大小寫,不限長度)
print(s1.isidentifier(),s2.isidentifier(),s3.isidentifier(),sep='\n')
print("--------------------")
print('yoyo'.islower()) #需全部小寫為Ture
print('Yoyo'.islower())
print('YOYO'.isupper()) #需全部大寫為Ture
print('Yoyo'.isupper())
print("--------------------")
#空白字元:空白、換行、跳格
print(' '.isspace())
print('\n'.isspace())
print('\t'.isspace())
print('\\'.isspace())
print("--------------------") |
f86996d1e48f47fcf65695bf912c560e51ee4350 | zietzm/xswap | /xswap/network_formats.py | 2,883 | 3.765625 | 4 | from typing import List, Tuple, TypeVar
import numpy
import scipy.sparse
def matrix_to_edges(matrix: numpy.ndarray, include_reverse_edges: bool=True):
"""
Convert (bi)adjacency matrix to an edge list. Inverse of `edges_to_matrix`.
Parameters
----------
matrix : numpy.ndarray
Adjacency matrix or biadjacency matrix of a network
include_reverse_edges : bool
Whether to return edges that are the inverse of existing edges. For
example, if returning [(0, 1), (1, 0)] is desired or not. If False,
then only edges where source <= target are returned. This parameter
should be `True` when passing a biadjacency matrix, as matrix positions
indicate separate nodes.
Returns
-------
edge_list : List[Tuple[int, int]]
Edge list with node ids as the corresponding matrix indices. For example,
if `matrix` has `matrix[0, 2] == 1`, then `(0, 2)` will be among the
returned edges.
"""
sparse = scipy.sparse.coo_matrix(matrix)
edges = zip(sparse.row, sparse.col)
if not include_reverse_edges:
edges = filter(lambda edge: edge[0] <= edge[1], edges)
return list(edges)
def edges_to_matrix(edge_list: List[Tuple[int, int]], add_reverse_edges: bool,
shape: Tuple[int, int], dtype: TypeVar=bool, sparse: bool=True):
"""
Convert edge list to (bi)adjacency matrix. Inverse of `matrix_to_edges`.
Parameters
----------
edge_list : List[Tuple[int, int]]
An edge list mapped such that node ids correspond to desired matrix
positions. For example, (0, 0) will mean that the resulting matrix has
a positive value of type `dtype` in that position.
add_reverse_edges : bool
Whether to include the reverse of edges in the matrix. For example,
if `edge_list = [(1, 0)]` and `add_reverse_edge = True`, then the
returned matrix has `matrix[1, 0]` = `matrix[0, 1]` = 1. Else, the matrix
only has `matrix[1, 0]` = 1. If a biadjacency matrix is desired, then
set `add_reverse_edges = False`.
shape : Tuple[int, int]
Shape of the matrix to be returned. Allows edges to be converted to
a matrix even when there are nodes without edges.
dtype : data-type
Dtype of the returned matrix. For example, `int`, `bool`, `float`, etc.
sparse : bool
Whether a sparse matrix should be returned. If `False`, returns a dense
numpy.ndarray
Returns
-------
matrix : scipy.sparse.csc_matrix or numpy.ndarray
"""
matrix = scipy.sparse.csc_matrix(
(numpy.ones(len(edge_list)), zip(*edge_list)), dtype=dtype, shape=shape,
)
if add_reverse_edges:
matrix = (matrix + matrix.T) > 0
matrix = matrix.astype(dtype)
if not sparse:
matrix = matrix.toarray()
return matrix
|
efafb58f3554342658e325eb46c6dd27203acf46 | hansleo/TopicModel_test | /doc_similarity/fileio.py | 352 | 3.640625 | 4 |
def read_file(path):
file = open(path, 'r', encoding = 'utf-8')
contents = ''
while True:
line = file.readline()
if (not line):
break
contents += line
return contents
def write_file(path, dict):
file = open(path, 'w', encoding = 'utf-8')
for k, v in dict.items():
text = str(k) + ',' + str(v) + '\n'
file.write(text)
file.close()
|
3db8b4c7b8b29af6ef71bbd537b8dc9fb80bb07a | yecong14/shiyan | /matrix.py | 629 | 3.65625 | 4 | #!/usr/bin/env python3
import numpy as np
def file2matrix(filename):
fr = open(filename)
array = fr.readlines()
numberoflines = len(array)
matrix = np.zeros((numberoflines,3))
label = []
index = 0
for i in array:
line = i.strip()
list = line.split()
matrix[index,:] = list[0:3]
label.append(int(list[-1]))
index += 1
return matrix,label
def norm(matrix):
minvals = matrix.min(0)
maxvals = matrix.max(0)
ranges = maxvals - minvals
m = matrix.shape[0]
norm = np.zeros(np.shape(matrix))
norm = matrix - np.tile(minvals,(m,1))
norm = norm/np.tile(ranges,(m,1))
return norm,ranges,minvals
|
ce4b05993f30b73700d090ad7aec97410d158d6f | khollbach/euler | /1_50/24/euler.py | 740 | 3.734375 | 4 | #!/usr/bin/python3
from utils import *
import math
def main():
print(nth_perm(999999, list(range(10))))
def nth_perm(n, l):
'''
n starts from 0.
'''
print(n, l)
if n < 0:
print('n < 0')
return None
if n >= math.factorial(len(l)):
print('n too large')
return None
if n == 0:
return l
fact = math.factorial(len(l) - 1)
# Find the largest number N s.t. N*fact <= n
for N in range(len(l)):
if N*fact > n:
N -= 1
break
assert N*fact <= n
# Pull the N'th number to the front and recurse on the rest.
return [l.pop(N)] + nth_perm(n - N*fact, l)
if __name__ == '__main__':
import sys
sys.exit(main())
|
0e6259fbc955f7a27bd10bd7fe492efc6e22450a | ChangedNameTo/AdventOfCode2019 | /2/opcode.py | 2,749 | 3.671875 | 4 | from tests import test_cases
def read_frame(index, program):
opcode = program[index]
# Halt
if opcode == 99:
return False
position_1 = program[index + 1]
position_2 = program[index + 2]
position_3 = program[index + 3]
# Add
if opcode == 1:
program[position_3] = program[position_1] + program[position_2]
return True
# Multiply
elif opcode == 2:
program[position_3] = program[position_1] * program[position_2]
return True
else:
print("!!!Error!!!")
return False
def output_sentence(program):
print('======')
print('('+str(program[1])+','+str(program[2])+')')
print(program[0])
passed = True
for case in test_cases:
program = case[0]
asert = case[1]
running = True
index = 0
while running:
running = read_frame(index, program)
index += 4
if(program != asert):
passed = False
print("Test failed")
print(program)
print(asert)
break
# Part 1
# if passed:
if False:
print("Tests Passed")
print("==============")
program = [1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,6,1,19,1,19,5,23,2,9,23,27,1,5,27,31,1,5,31,35,1,35,13,39,1,39,9,43,1,5,43,47,1,47,6,51,1,51,13,55,1,55,9,59,1,59,13,63,2,63,13,67,1,67,10,71,1,71,6,75,2,10,75,79,2,10,79,83,1,5,83,87,2,6,87,91,1,91,6,95,1,95,13,99,2,99,13,103,1,103,9,107,1,10,107,111,2,111,13,115,1,10,115,119,1,10,119,123,2,13,123,127,2,6,127,131,1,13,131,135,1,135,2,139,1,139,6,0,99,2,0,14,0]
program[1] = 12
program[2] = 2
running = True
pointer = 0
while running:
running = read_frame(index, program)
index += 4
print(program[0])
print(program)
# Part 2
if passed:
print("Tests Passed")
print("==============")
for i in range(0, 100):
for j in range(0, 100):
program = [1,i,j,3,1,1,2,3,1,3,4,3,1,5,0,3,2,6,1,19,1,19,5,23,2,9,23,27,1,5,27,31,1,5,31,35,1,35,13,39,1,39,9,43,1,5,43,47,1,47,6,51,1,51,13,55,1,55,9,59,1,59,13,63,2,63,13,67,1,67,10,71,1,71,6,75,2,10,75,79,2,10,79,83,1,5,83,87,2,6,87,91,1,91,6,95,1,95,13,99,2,99,13,103,1,103,9,107,1,10,107,111,2,111,13,115,1,10,115,119,1,10,119,123,2,13,123,127,2,6,127,131,1,13,131,135,1,135,2,139,1,139,6,0,99,2,0,14,0]
running = True
index = 0
while running:
running = read_frame(index, program)
index += 4
# output_sentence(program)
if(program[0] == 19690720):
print('Value Found')
print('---------')
print(program[1])
print(program[2])
print((100 * program[1]) + program[2])
break |
c0cdbc44d6c51d7e4d4c22e4fd95bbc0123e1bb1 | jabbalaci/Bash-Utils | /here.py | 633 | 3.75 | 4 | #!/usr/bin/env python3
"""
Laszlo Szathmary, 2014 (jabba.laci@gmail.com)
Print just the name of the current directory.
For instance, if you are in "/home/students/solo",
then this script will print just "solo".
The output is also copied to the clipboard.
Usage: here
Last update: 2017-01-08 (yyyy-mm-dd)
"""
import os
import sys
from lib.clipboard import text_to_clipboards
def main():
text = os.path.split(os.getcwd())[1]
print('# copied to the clipboard', file=sys.stderr)
print(text)
text_to_clipboards(text)
##############################################################################
if __name__ == "__main__":
main()
|
13bc50aad56a3fee8fcf72b72a7f06b4fed0ef12 | RyanKHawkins/Account_Manager | /main.py | 4,694 | 4.28125 | 4 | """
Create a login program that I can use to add and verify
usernames and passwords.
A dictionary seems like the appropriate item to store
this information.
"""
accounts = {"ryanhawkins": "beastmode", "testname": "testpass"}
class Account:
def __init__(self, username, password):
self.username = username
self.password = password
def user_status():
print()
print("[1] Sign in (current user)")
print("[2] Sign up (new user)")
user_status = input("Choose selection: ")
if user_status == "1":
Account.sign_in()
# Account.verify_username()
# Account.verify_password()
elif user_status == "2":
Account.sign_up()
else:
user_status()
def sign_up():
print("\nWe're glad to have you join us.")
new_username = Account.approve_new_username()
new_password = Account.approve_new_password()
accounts[new_username] = new_password
def approve_new_username():
accepted_name = False
while not accepted_name:
print("\nYour username must be between 7 and 11 characters long.")
new_username = input("Choose a username: ")
if len(new_username) < 7 or len(new_username) > 11:
print(
"Your username must be between 7 and 11 characters long.")
pass
elif new_username in accounts.keys():
print(f"'{new_username}' is already used.")
pass
else:
accepted_name = True
print(f"The username '{new_username}' was accepted.")
return new_username
def approve_new_password():
accepted_password = False
# numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# letters = []
new_password_tries = 0
while not accepted_password:
new_password = input("Select a password: ")
if len(new_password) > 5 and len(new_password) < 15:
accepted_password = True
return new_password
else:
print(
"Your password must be between 6 and 14 characters long.")
new_password_tries += 1
if new_password_tries >= 3:
password_help = input(
"Would you like an approved password generated for you? "
).lower()
new_password_tries = 0
if password_help in ["y", "yes", "yeah"]:
pass
if password_help in ["n", "no"]:
Account.approve_new_password()
# def sign_in():
# Account.verify_username()
# Account.verify_password()
# def verify_username():
# return_username = input("\nEnter your username: ")
# if return_username in accounts.keys():
# username = return_username
# return username
# Account.verify_password()
# else:
# print(f"'{return_username}' is not recognized.")
# print("Please, try again.")
# Account.user_status
# def verify_password():
# password = input("Enter password: ")
# if password in accounts.values(username):
# print("Access Granted.")
def sign_in():
username_verified = False
while not username_verified:
username = input("\nEnter your username: ")
if username in accounts.keys():
username_verified = True
else:
print(f"{username} is not recognized.")
print("Please, try again.")
password_verified = False
while not password_verified:
password = input("Enter your password: ")
if password == accounts[username]:
print("Access Granted")
else:
print("Access Denied")
# if password in accounts.values(username):
# print("Access Granted")
# else:
# print("The password and username do not match.")
# Account.sign_in()
def change_password():
pass
def main():
intro()
Account.user_status()
def intro():
intro_message = "Welcome to Hawkins Online."
print()
print(intro_message)
print("-" * len(intro_message))
if __name__ == "__main__":
main()
### Verification of New Account ###
# print()
# for key, value in accounts.items():
# print(key, value)
|
23fec4266c6a158041989472eb7cbe11c704fb6a | Justas327/Skaitiniai-Algoritmai | /LD-3/task3.py | 722 | 3.546875 | 4 | import matplotlib.pyplot as plt
from ast import literal_eval
import numpy as np
from interpolation import parametric_interpolation, hermite_interpolation_spline
from task3_data import x_range, y_range
n = 305 # Number of interpolation points
step = 0.1 # Graph's precision
# Reducing interpolation points to selected
t = range(n + 1)
x_range = x_range[::(306 // n)]
y_range = y_range[::(306 // n)]
ff = hermite_interpolation_spline(t, x_range)
ff2 = hermite_interpolation_spline(t, y_range)
xx, yy = parametric_interpolation(ff, ff2, np.arange(0, n, step))
plt.plot(xx, yy, 'r', label="Country's border")
plt.scatter(x_range, y_range, label=f"{n} Interpolation points")
plt.title('Cyprus')
plt.legend()
plt.show()
|
cdd06c5d4ae2e8c0c72942bd343c889491f0073b | hnguyen0907008/Nguyen_H_InClass_Python | /RPSGame.py | 2,062 | 4.0625 | 4 | from random import randint
choices=['Rock','Paper','Scissor']
player = False
player_lives = 5
computer_lives = 5
computer = choices[randint(0,2)]
#define win or lose function
def winorlose(status):
print("Called win or lose function")
print("**************************************")
print("You", status,"! Would you like to play again?")
choice = input("Y/N?")
#reset the lives
if (choice == "Y" or choice == "y"):
#change global variables
global computer_lives
global player_lives
global player
global computer
player = False
player_lives = 5
computer_lives = 5
computer = choices[randint(0,2)]
elif (choice == "N" or choice == "n"):
print("You chose to quit!")
print("**************************************")
exit()
while player is False:
print("============================================")
print("Player lives:", player_lives, "/5")
print("Computer lives:", computer_lives, "/5")
print ("Choose your weapon!\n")
player = str(input("Rock, Paper or Scissor?\n"))
print("Player chooses", player)
if (player == computer):
print("Tie! You live to shoot another day")
elif (player == "Rock"):
if (computer == "Paper"):
player_lives = player_lives - 1
print("You lose!", computer, "covers", player)
else:
computer_lives = computer_lives - 1
print("You win!", player, "smashes", computer)
elif (player == "Paper"):
if (computer == "Scissor"):
player_lives = player_lives - 1
print("You lose!", computer, "cuts", player)
else:
computer_lives = computer_lives - 1
print("You win!", player, "covers", computer)
elif (player == "Scissor"):
if (computer == "Rock"):
player_lives = player_lives - 1
print("You lose!", computer, "smashes", player)
else:
computer_lives = computer_lives - 1
print("You win!", player, "cuts", computer)
elif (player == "Quit"):
exit()
else:
print("Invalid option")
#check for win or lose
if player_lives is 0:
winorlose("lose")
if computer_lives is 0:
winorlose("lose")
player = False
computer = choices[randint(0,2)] |
f40e150a33aff6a25dc3716ac6ef00d99dc61567 | sayyedsy/sayyed-saber | /while.loop.multi.py | 118 | 3.625 | 4 | table=2
while table<=20:
mul=1
while mul<=10:
print(table,"×",mul,table*mul)
mul=mul+1
print()
table=table+1 |
f3373dc49d85cebfb79fba6154bac766c7673bfa | sugataach/al-gore-rhythms | /arden/test_q5.py | 2,543 | 3.734375 | 4 | '''
Given a linkedlist of integers and an integer value, delete every node of the linkedlist containing that value.
Approach A:
iterate through linkedlist, keeping a pointer to the current and prev nodes
when curr.val == integer, prev.next = curr.next, curr = prev.next
'''
import pytest
class Node:
def __init__(self, value, next_node=None):
self.value = value
self.next = next_node
class LinkedList:
def __init__(self, node_value=None):
if node_value == None:
self.head = self.tail = None
else:
self.head = Node(node_value)
self.tail = self.head
def add(self, value):
self.tail.next = self.tail = Node(value)
def remove(self, remove_value):
curr_node = self.head
prev_pointer = None
while curr_node:
if curr_node.value == remove_value:
if prev_pointer == None:
self.head = curr_node.next
prev_pointer = curr_node
else:
prev_pointer.next = curr_node.next
curr_node = curr_node.next
else:
prev_pointer = curr_node
curr_node = curr_node.next
def get_list(self):
if self.head == None:
return []
result = []
curr_node = self.head
while curr_node:
result.append(curr_node.value)
curr_node = curr_node.next
return result
def test_remove_node():
# standard case
linked_list = LinkedList(1)
linked_list.add(2)
linked_list.add(3)
linked_list.add(3)
linked_list.add(4)
linked_list.remove(3)
assert linked_list.get_list() == [1,2,4]
# delete from head
linked_list = LinkedList(1)
linked_list.add(2)
linked_list.remove(1)
assert linked_list.get_list() == [2]
# delete from tail
linked_list = LinkedList(1)
linked_list.add(2)
linked_list.remove(2)
assert linked_list.get_list() == [1]
# one node case
linked_list = LinkedList(1)
linked_list.remove(1)
assert linked_list.get_list() == []
# empty case
linked_list = LinkedList()
assert linked_list.get_list() == []
# empty remove case
linked_list = LinkedList()
linked_list.remove(4)
assert linked_list.get_list() == []
# missing case
linked_list = LinkedList(1)
linked_list.add(2)
linked_list.add(3)
linked_list.add(3)
linked_list.remove(4)
assert linked_list.get_list() == [1,2,3,3]
|
499742df4c23381236545ba1ef3677a89b2b6cfe | Keshav1506/competitive_programming | /Linked_List/012_leetcode_P_021_MergeTwoSortedLists/Solution.py | 8,761 | 3.546875 | 4 | #
# Time : O(N+M) ; Only one traversal of the loop is needed.
# Space: O(1) ; There is no additional space required.
# @tag : Linked List
# @by : Shaikat Majumdar
# @date: Aug 27, 2020
# **************************************************************************
# LeetCode - Problem 20: Merge Two Sorted Lists
#
# Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing
# together the nodes of the first two lists.
#
# Example:
#
# Input: 1->2->4, 1->3->4
# Output: 1->1->2->3->4->4
#
# **************************************************************************
# Source: https://leetcode.com/problems/merge-two-sorted-lists/ (LeetCode - Problem 20 - Merge Two Sorted Lists)
# https://practice.geeksforgeeks.org/problems/merge-two-sorted-linked-lists/1 (GeeksForGeeks - Merge two sorted linked lists)
#
# Youtube video: https://www.youtube.com/watch?v=3O_f_sk3mFc - Linked Lists with Dummy Nodes
# https://www.youtube.com/watch?v=GfRQvf7MB3k - Merge 2 Sorted Lists - A Fundamental Merge Sort Subroutine ("Merge Two Sorted Lists" on LeetCode)
# **************************************************************************
# Solution Explanation
# **************************************************************************
# Linkedlists can be confusing especially if you've recently started to code but (I think)
# once you understand it fully, it should not be that difficult.
#
# For this problem, I'm going to explain several ways of solving it BUT I want to make something clear.
# Something that you've seen a lot of times in the posts on this website but probably haven't
# fully understood. dummy variable!
#
# It has been used significantly in the solutions of this problem and not well explained for a newbie level coder!
# The idea is we're dealing with pointers that point to a memory location! Think of it this way!
# You want to find gold that is hidden somewhere. Someone has put a set of clues in a sequence!
# Meaning, if you find the first clue and solve the problem hidden in the clue, you will get to the second clue!
# Solving the hidden problem of second clue will get you to the thrid clue, and so on!
# If you keep solving, you'll get to the gold! dummy helps you to find the first clue!!!!
#
# Throughout the solution below, you'll be asking yourself why dummy is not changing and
# we eventually return dummy.next????
#
# It doesn't make sense, right?
#
# However, if you think that dummy is pointing to the start and there is another variable (temp)
# that makes the links from node to node, you'll have a better feeling !
# Similar to the gold example if I tell you the first clue is at location X, then, you can solve clues
# sequentially (because of course you're smart) and bingo! you find the gold!
# Watch this ==> ( https://www.youtube.com/watch?v=3O_f_sk3mFc - Linked Lists with Dummy Nodes )
#
# This video shows why we need the dummy! Since we're traversing using temp but once temp gets to the tail
# of the sorted merged linkedlist, there's no way back to the start of the list to return as a result!
# So dummy to the rescue! it does not get changed throughout the list traversals temp is doing!
# So, dummy makes sure we don't loose the head of the thread (result list).
# Does this make sense? Alright! Enough with dummy!
#
# I think if you get this, the first solution feels natural!
# Now, watch this. ==> [ https://www.youtube.com/watch?v=GfRQvf7MB3k - Merge 2 Sorted Lists - A Fundamental Merge Sort Subroutine ("Merge Two Sorted Lists" on LeetCode) ]
# You got the idea?? Nice!
#
# First you initialize dummy and temp. One is sitting at the start of the linkedlist and the other (temp)
# is going to move forward find which value should be added to the list.
# Note that it's initialized with a value 0 but it can be anything! You initialize it with your value of choice!
# Doesn't matter since we're going to finally return dummy.next which disregards 0 that we used to start the linkedlist.
# Line #1 makes sure none of the l1 and l2 are empty! If one of them is empty, we should return the other!
# If both are nonempty, we check val of each of them to add the smaller one to the result linkedlist!
# In line #2, l1.val is smaller and we want to add it to the list. How?
# We use temp POINTER (it's pointer, remember that!).
# Since we initialized temp to have value 0 at first node, we use temp.next to point 0 to the next value we're going
# to add to the list l1.val (line #3). Once we do that, we update l1 to go to the next node of l1.
# If the if statement of line #2 doesn't work, we do similar stuff with l2. And finally, if the length of l1 and l2
# are not the same, we're going to the end of one of them at some point! Line #5 adds whatever left from
# whatever linkedlist to the temp.next (check the above video for a great explanation of this part).
# Note that both linkedlists were sorted initially. Also, this line takes care of when one of the linkedlists are empty.
# Finally, we return dummy.next since dummy is pointing to 0 and next to zero is what we've added throughout the process.
#
import unittest
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __eq__(self, other):
if not self.equal(other):
# print("List1 != List2 where")
# print("List1:")
# print(str(self))
# print("List2:")
# print(str(other))
# print("\n")
return False
else:
return True
def equal(self, other):
if other is not None:
return self.val == other.val and self.next == other.next
else:
return False
def __repr__(self):
lst = []
p = self
while p:
lst.append(str(p.val))
p = p.next
return "List: [{}].".format(",".join(lst))
def initList(self, nums):
if not nums:
return None
head = None
current = None
for n in nums:
if not head:
head = ListNode(n)
current = head
else:
node = ListNode(n)
current.next = node
current = node
return head
def printList(self, head):
string = ""
if not head:
return string
while head.next:
if head.val is None:
string += "%s->" % str(head.val)
else:
string += "%d->" % head.val
head = head.next
if head.val is None:
string += "%s->" % str(head.val)
else:
string += "%d" % head.val
return string
# length of linked list => recursive function
def length(self, head):
if head is None:
return 0
else:
return 1 + self.length(head.next)
# length of linked list => iterative function
# def length(self, head):
# temp = head
# count = 0
# while(temp):
# count += 1
# temp = temp.next
# return count
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if None in (l1, l2):
return l1 or l2
dummy = temp = ListNode(0)
# while l1 != None and l2 != None: # 1
while l1 and l2: # 1
if l1.val < l2.val: # 2
temp.next = l1 # 3
l1 = l1.next # 4
else:
temp.next = l2
l2 = l2.next
temp = temp.next
temp.next = l1 or l2 # 5
return dummy.next # 6
class Test(unittest.TestCase):
def setUp(self) -> None:
pass
def tearDown(self) -> None:
pass
def test_mergeTwoLists(self) -> None:
listNode = ListNode()
s = Solution()
for l1, l2, solution in (
[
listNode.initList([1, 2, 4]),
listNode.initList([1, 3, 4]),
listNode.initList([1, 1, 2, 3, 4, 4]),
],
[
listNode.initList([5, 10, 15, 40]),
listNode.initList([2, 3, 20]),
listNode.initList([2, 3, 5, 10, 15, 20, 40]),
],
[
listNode.initList([1, 1]),
listNode.initList([2, 4]),
listNode.initList([1, 1, 2, 4]),
],
):
self.assertEqual(
solution,
s.mergeTwoLists(l1, l2),
"Should merge two sorted linked lists and return it as a new sorted list",
)
if __name__ == "__main__":
unittest.main()
|
e0cd03c32ea1ed15704192bb2e6f9cb9aa0d6b0b | francisco-igor/ifpi-ads-algoritmos2020 | /Fabio01_Parte02/f1_p2_q2_m_para_km.py | 289 | 3.875 | 4 | # Leia um número inteiro de metros, calcule e escreva quantos Km e quantos metros ele corresponde.
# ENTRADA
metros = int(input('Leia um valor em m: '))
# PROCESSAMENTO
km = metros // 1000
m = metros % 1000
# SAÍDA
print(f'O valor {metros}m corresponde a {km}km e {m}m.')
|
a13928ae5356e79f0b108011bd0c1f7c354e19e1 | gastonciara86/PYTHON_2.7-GUIA_2 | /EJE4G2.py | 114 | 3.59375 | 4 | c=0
for n in range (10) :
nro=int (raw_input ("Ingrese Nro:"))
if nro>23:
c=c+1
print "Nros>23:",c |
fc894120e935b388886a6be1fcc78f1ce0e14084 | ayingxp/PythonDataStructure | /datastructure/ch03_sort/bubbleSort.py | 619 | 3.84375 | 4 | """
所有的排序算法
"""
import random
# 冒泡排序
def bubbleSort(lyst):
"""
每次迭代时都会产生一个最大的值
:param lyst:
:return:
"""
for i in range(len(lyst)): # 控制迭代的轮次
for j in range(1, len(lyst) - i): # 进行一次具体的排序, 每次排序完成之后会产生一个(最大值)的固定位置
if lyst[j] < lyst[j-1]:
lyst[j-1], lyst[j] = lyst[j], lyst[j-1]
if __name__ == "__main__":
a = [5, 3, 1, 2, 4]
a = [random.randint(0, 100) for _ in range(20)]
print(a)
bubbleSort(a)
print(a) |
ec1721d3164a0f9f267211468f1372cf497bfeee | tormobr/Project-euler | /038/p38.py | 369 | 3.515625 | 4 | def solve():
res = 0
for i in range(1,10000):
pan = ""
j = 1
print(i)
while len(pan) < 9:
pan += str(i * j)
j += 1
if is_pandigital(pan) and int(pan) > res:
res = int(pan)
return res
def is_pandigital(n):
return sorted(str(n)) == [str(i) for i in range(1,10)]
print(solve())
|
f8360a1278f2426fa0acc71926f7ad281b199791 | harababurel/homework | /sem1/fop/lab7/models/Faculty.py | 2,563 | 3.9375 | 4 | """
Module implements the Faculty class.
"""
from models.Student import *
from models.Assignment import *
class Faculty:
"""
Class that models a generation of students (faculty) as an object.
Each faculty is described by:
- students - <list of Student()>
- assignments - <list of Assignment()>
"""
def __init__(self, students=None, assignments=None):
"""
If no parameters are provided, empty lists are used.
"""
self.students = [] if students is None else students
self.assignments = [] if assignments is None else assignments
def __repr__(self):
message = ''
for student in self.students:
message += "%r\n" % student
for assignment in self.assignments:
message += "%r\n" % assignment
return message
# SET STUFF
def setStudents(self, students):
"""
Method sets the students of the current faculty.
"""
self.students = students
def setAssignments(self, assignments):
"""
Method sets the assignments of the current faculty.
"""
self.assignments = assignments
def addStudent(self, student):
"""
Method adds a new student to the current faculty.
"""
self.students.append(student)
def addAssignment(self, assignment):
"""
Method adds a new assignment to the current faculty.
"""
self.assignments.append(assignment)
# GET STUFF
def getStudents(self):
"""
Method returns the list of students contained in the
current faculty.
"""
return self.students
def getAssignments(self):
"""
Method returns the list of assignments contained in the
current faculty.
"""
return self.assignments
def removeStudent(self, studentID):
"""
Method removes a student (identified by their studentID)
from the list of students. If not found, nothing happens.
"""
self.students = [x for x in self.students if x.studentID != studentID]
def removeAssignment(self, assignmentID):
"""
Method removes an assignment (identified by its position
in the list of assignments). If something goes wrong
(position does not exist, or such), nothing happens.
"""
try:
del self.assignments[assignmentID]
except:
pass
|
34f1196cd7908b2b7f4b42247a0f57115c3245bd | mag389/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 233 | 4.125 | 4 | #!/usr/bin/python3
""" write to file appends mode"""
def append_write(filename="", text=""):
""" write to file, appends if it exists """
with open(filename, 'a') as f:
num_chars = f.write(text)
return num_chars
|
35b2b50217a25d362edba790fbb92bd054f858ba | UW-ParksidePhysics/python-functions-and-branching-lucca001 | /f2c.py | 156 | 4 | 4 | #F = float(input("Input temopreratue (degrees F):"))
def C(F):
return (5.0/9.0) * (F - 32)
#print(f"Yor input is equal to {C(F):.2f} degrees Celcius") |
9e5cb9374c708735df771881ae3b402c94499257 | tizzle-b-rizzle/shakespeare_text_adventure | /text-adventure.py | 6,888 | 4.28125 | 4 | name = input(
"Hello! what is your name?\nplease type your name and then hit 'enter'\n")
# note, choices are defined by the naming convention "choice_[first choice]_[second choice]..." so if the player chooses 1, 2, and then 1, that function will be named "choice_1_2_1"
def choice_1_invalid():
choice_1()
def choice_1_3_2_i():
choice_1_3_2()
def choice_1_3_i(): # for some god-foresaken reason, any other choice_n_invalid doesn't work, I have to use i instead of invalid
choice_1_3()
def choice_1_3_4(): # for some god-foresaken reason, any other choice_n_invalid doesn't work, I have to use i instead of invalid
choice_1_4_i()
def start_the_game():
begin_the_game = input("Great to meet you, " + name +
"! Are you ready to begin?\nplease hit 'y' or 'n' and then hit enter\n")
if begin_the_game == "y":
print("Great!\nOnce upon a Tuesday, you're walking down a nice forest path when-\nOH NO! It's the reanimated corpse of William Shakespeare coming towards you!\nWhat do you do?")
choice_1()
elif begin_the_game == "n":
print("Well...bye then I guess?")
else:
print("invalid response")
repeat = input("press 'r' to go retry\nany other key will exit game\n")
if repeat == "r":
start_the_game()
else:
exit()
def start_over(): # function to start from the "Great to meet you, name..." part
start_over = input(
"If you would like to try again, please hit 'r' and then 'enter', hit any other key and 'enter' to end the program\n")
if start_over == "r":
start_the_game()
else:
exit()
def choice_1_3_2():
choice_1_3_2 = input(
"Bill isn't scared of your blade, and charges at you!\nWhat do you do?\n1.Swing low with your katana\n2.Swing high with your katana\n3.Charge at him\n4.Run away screaming\nYou know the drill when it comes to the buttons\n")
if choice_1_3_2 == "1":
print("He jumps over your blade and literally kicks your head off your body\n")
start_over()
elif choice_1_3_2 == "2":
print("He combat rolls under your blade and delivers a swift uppercut, knocking your head off your body\n")
start_over()
elif choice_1_3_2 == "3":
print("When you two meet, your blade crumples against his iron-clad pecs and he crashes into you with the force of a thousand suns. You never had a chance.\n")
start_over()
elif choice_1_3_2 == "4":
print("You trip over a branch and fall on your face. Your katana goes flying through the air and somehow lands blade-first on Shakespeare's bald spot, his one weakness!\nHe cries out in anguish 'Aaah, if only I used Regain Extra Strength Foam available for £40.99!\nHe's dead.\nYou win!")
start_over()
else:
print("invalid response")
choice_1_3_2_invalid = input(
"press 'r' and then 'enter' to retry\nany other key will exit game\n")
if choice_1_3_2_invalid == "r":
choice_1_3_2_i()
else:
exit()
def choice_1_3_3():
print(
"Shakespeare halts.\n'y-you can't be serious?' he asks.\nYou are.\n'Kaaa...'\n'...meeeh.\nkaaaa\nmeeeeh.\nAAAAAAH\nShakespeare is obliterated.")
start_over()
def choice_1_3():
choice_1_3 = input("Shakespeare breaths in deep and flexes his biceps, which grow to at least 24\", bruh I need his routine.\nWhat will you do?\n1.Run away screaming\n2.Pull out your katana that does +2 against any undead foes\n3.Plant your feet, and start charging up a kamehameha wave\nPress '1', '2', or '3', and then hit 'enter'\n")
if choice_1_3 == "1":
print("You trip over a branch and fall on your face. He effortlessly picks you up, says 'I was wondering what would break first, you spirit, or your body!' and snaps your spine over his knee. Before you die you have time to think 'Was that a Bane quote? How does Shakespeare know that Bane quote. Mad'")
start_over = input(
"If you would like to try again, please hit 'r' and then 'enter', hit any other key and 'enter' to end the program\n")
if start_over == "r":
start_the_game()
else:
exit()
if choice_1_3 == "2":
choice_1_3_2()
if choice_1_3 == "3":
choice_1_3_3()
else:
print("invalid response")
choice_1_3_invalid = input(
"press 'r' and then 'enter' to retry\nany other key will exit game\n")
if choice_1_3_invalid == "r":
choice_1_3_i()
else:
exit()
def choice_1_4():
choice_1_4 == input(
"World-renowned authour and playwright William Shakespeare has tears and snot running down his face.\n'I-I'm way better then that hack author!'\nHow do you want to address the mess in front of you?\n1.Say 'Oh no, wait! You're the guy who wrote Harry Potter!'\n2.Laugh at him\n3.Back slowly away\n4.Say 'Sorry man, I didn't mean it, I love your work!\n")
if choice_1_4 == "1":
print("William's head explodes from stress\n")
start_over()
elif choice_1_4 == "2":
print("'S-s-stop laughing at me!' he squeals. You laugh even more and walk away.")
start_over()
elif choice_1_4 == "3":
print(
"'You get back here right no-' and slips on his own tears. His neck snaps. F.")
start_over()
elif choice_1_4 == "4":
print("He looks up with hope in his eyes. 'R-really?;\nYou smile down at him, lean in, and whisper, 'no'.\nYou walk away.s")
else
print("invalid response")
choice_1_4_invalid = input(
"press 'r' and then 'enter' to retry\nany other key will exit game\n")
if choice_1_4_invalid == "r":
choice_1_4_i()
else:
exit()
def choice_1():
choice_1 = input("1.Run away screaming\n2.Walk up to him and give him a firm handshake\n3.Challenge him to a fight\n4.Say 'I loved your book, The Shining!'\npress '1', '2', '3', '4', and then hit 'enter'\n")
if choice_1 == "1":
print("You trip over a branch, fall onto your face, and are promptly devoured")
start_over()
elif choice_1 == "2":
print("He's impressed by your 'can do!' attitude, and immediately offers you a job. Great work, champ!")
start_over()
elif choice_1 == "3":
choice_1_3()
elif choice_1 == "4":
print("William... bursts into tears?")
choice_1_4()
else:
print("invalid response")
choice_1_invalid = input(
"press 'r' and then 'enter' to retry\nany other key will exit game\n")
if choice_1_invalid == "r":
choice_1_invalid()
else:
exit()
start_the_game()
|
66304a07fbbd57151bf8a61a4d236daf7f006ea4 | lchan20/COMP_1510_Lab_01 | /room_painter.py | 683 | 3.96875 | 4 | COVERAGE = 400
length = float(input("Enter the length of the room in feet: "))
width = float(input("Enter the width of the room in feet: "))
height = float(input("Enter the height of the room in feet: "))
coats = float(input("Enter the number of coats of paint: "))
surface_area = (length*width) + (2*length*height) +(2*width*height)
coverage_needed = surface_area*coats
cans_of_paint_required = coverage_needed/COVERAGE
print("Amount of paint needed is " + str(cans_of_paint_required))
if float(cans_of_paint_required) - int(cans_of_paint_required) != 0:
cans_to_buy = int(cans_of_paint_required) + 1
print("The number of cans needed to paint this room is " + str(cans_to_buy))
|
7e99f467e109c0d07a0276ddfc5d5bd7355ec4c1 | rk2100994/python_basics | /polymorphism.py | 269 | 3.59375 | 4 | class Animal:
def __init__(self):
print("I'm in animal")
class Dog(Animal):
def talk(self):
print("I talk in barking fashion")
class Lion(Animal):
def talk(self):
print("I talk in roaring way")
an1 = Lion()
an2 = Dog()
an1.talk()
an2.talk()
|
e92489f6aa63134420aacfc88adcca85bc9e6311 | christine-le/algorithms | /one_edit_apart.py | 1,358 | 3.84375 | 4 | class Solution(object):
def oneEditApart(self, word1, word2):
if len(word1) > len(word2):
longerWord, shorterWord = word1, word2
else:
longerWord, shorterWord = word2, word1
lengthDiff = len(longerWord) - len(shorterWord)
if lengthDiff > 1:
return False
elif lengthDiff == 1:
for i in range(0, len(longerWord)):
if i == len(longerWord)-1 or longerWord[i] != shorterWord[i]:
longerWord = longerWord[:i] + longerWord[i+1:]
if longerWord == shorterWord:
return True
else:
return False
else:
oneDiff = 0;
for i in range(0, len(longerWord)):
if longerWord[i] != shorterWord[i]:
oneDiff = oneDiff + 1
if oneDiff > 1:
return False
return True
solution = Solution()
print solution.oneEditApart("cat", "dog") # false
print solution.oneEditApart("cat", "cats") #true
print solution.oneEditApart("cat", "cut") # true
print solution.oneEditApart("cat", "cast") # true
print solution.oneEditApart("cat", "at") # true
print solution.oneEditApart("cata", "aact") # false
# Pseudocode
# if lengthDiff > 1:
# return
# if lengthDiff == 1:
# remove the character from larger string
# if lengthDiff == 0:
# loop through word1 and compare against word2
|
ba449a87d42e75c00ea94fd231e1b4b3382e3abf | braeden-smith/Chapter-3 | /Chapter 3 Excercise 2.py | 842 | 4.1875 | 4 | #Braeden Smith Chapter 3 Excericse 2
'''
Exercise 2: Rewrite your pay program using try and except so that your program handles non-numeric input gracefully by printing a message and exiting the program. The following shows two executions of the program:
Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input
Enter Hours: forty
Error, please enter numeric input
'''
try:
hours = float(input('Enter how many hours have you worked:' ))
float(hours)>=0
except:
print ('Please type in numerals only.')
hours = float(input('Enter how many hours have you worked:' ))
rate = float(input('Enter how much your hourly wage is:' ))
if hours > 40:
extra = float(hours) - 40
else:
extra = 0
extra_pay = 0.5 * float(rate) * extra
pay = float(hours) * float(rate) + extra_pay
print ('Pay: '),
print pay
|
40547b15e1f77f7b078558f202f87ee6b9c3db69 | romitpatel/learn_python | /Ch10_Tuples/exercise_2.py | 725 | 3.796875 | 4 | fname = input('Please enter a valid file name: ')
try:
fhand = open(fname)
except:
print('Please enter an existing file name')
exit()
counts = dict()
for line in fhand:
line = line.rstrip()
words = line.split()
if not line.startswith('From ') or len(words) < 1: continue
for word in words:
if word.find(':') == -1:continue
hour, min, sec = word.split(':')
if hour not in counts:
counts[hour] = 1
else:
counts[hour] += 1
t = counts.items()
dl = list()
check = sorted(t)
# This approach uses the sorted method instead of using a list of tuples and the sort method used by list to sort the items.
for key,val in check:
print(key,val)
|
103496b50aae26cc6f8313771d0fbaa6bd6ff827 | steveedegbo/learning_python | /Functions/functions.py | 4,512 | 4.125 | 4 | # # # # # #TAKES NAME & GENDER INPUT AND GREETS ACCORDINGLY
# # # # # def greet(name, gender, age):
# # # # # if gender == "male" and age >= 18:
# # # # # print(f'Hello Mr {name}..!')
# # # # # elif gender == "male" and age < 18:
# # # # # print(f'Hello Mst {name}..!')
# # # # # elif gender == "female" and age >= 18:
# # # # # print(f'Hello Mrs {name}..!')
# # # # # else:
# # # # # print(f'Hello Ms {name}..!')
# # # # # # greet("Ade", "female")
# # # # # people = [("bolu", "male", 23), ("ade", "female", 15), ("sholu", "female", 45), ("manny", "male", 33)]
# # # # # for name,gender,age in people:
# # # # # greet(name,gender,age)
# # # # # for name,gender in people:
# # # # # greet(name,gender)
# # # # #DEFINING YOUR OWN PYTHOIN FUNCTION REAL PYTHON READ UP
# # # # #HANGMAN WITH FUNCTIONS IN IT
# # # # name = input("Please enter your name : ")
# # # # print(f"Hi {name}, welcome to Hangman")
# # # # turns = 5
# # # # word = "stephen"
# # # # word_guess = ""
# # # # while turns > 0:
# # # # failed = 0
# # # # for char in word:
# # # # if char in word_guess:
# # # # print(char)
# # # # else:
# # # # print("_")
# # # # failed += 1
# # # # if failed == 0:
# # # # print("You guessed right!")
# # # # break
# # # # guess = input("Please enter your guess : ")
# # # # word_guess += guess
# # # # if guess not in word:
# # # # turns -= 1
# # # # print("You have", turns, "more guesses")
# # # # if turns == 0:
# # # # print("You lost")
# # # # def say_hello(name):
# # # # """THIS FUNCTION IS NICE and this is a docstring"""
# # # # print(f"Hello {name}")
# # # # say_hello('bola')
# # # # def sqrt(number1,number2,power):
# # # # answer = (number1 ** 2 + number2 ** 2) ** (1/power)
# # # # print(answer)
# # # # sqrt(3,4,2)
# # # def sqrt(number):
# # # answer = number ** (1/2)
# # # return answer
# # # def square(number):
# # # answer2 = number ** 2
# # # return answer2
# # # sdf = sqrt(square(5) + square(7))
# # # print(sdf)
# # import datetime
# # # time_now = datetime.datetime.now()
# # # # print(time_now)
# # # # print(time_now.weekday()) #GIVES WEEKDAY IN NUMERALS
# # # print(time_now.strfttime("%a:%H:%M")) #GIVES A FORMATTED STRING REPRESENTATION OF TIME
# # # time_stamp = (time_now.strfttime("%a %H:%M"))
# # def get_timestamp():
# # time_now = datetime.datetime.now()
# # time_stamp = time_now.strftime("%b %d %Y %a %H %M.")
# # print(time_stamp)
# # return time_stamp
# # def number_words(text):
# # count = len(text)
# # print(count)
# # return count
# # def store_memory(memory, time_stamp, count):
# # file = open(f"functions/{time_stamp},{count}.txt", "w")
# # file.write(memory)
# # file.close()
# # return True
# # text = input("Please enter text : ")
# # time_stamp = get_timestamp()
# # count = number_words(text)
# # store_memory(text, time_stamp, count)
# # #OPEN NEW FILE AND WRITE TO IT
# # # file = open("functions/note.txt", "w")
# # # text = input("Please enter text : ")
# # # file.write(text)
# # * is a tuple unpacker * variable positional argument
# ## ** is a dictionary unpacker *variable keyworrd argument
# # def sum_nums(*args):
# # print(args)
# # sum_nums(2,32,3,4,7,8,9,0,4,5)
# def sum_nums(**kwargs):
# print(kwargs)
# sum_nums(x=2,y=3,z=4,q=6,h=23)
#LAMBDA FUNCTION
# numbers = list("12345678")
# mini2 = lambda x: "A" + str(x)
# mapped_result2 = map(mini2, numbers)
# print(list(mapped_result2))
#RECURSION
# def factorial(n):
# if n <= 1:
# return n
# else:
# val = n + factorial(n-1)
# print(val)
# return val
# factorial(3)
# def count_down(num):
# if num == 0:
# return num
# print(num)
# return count_down(num-1)
# count_down(10)
# previous_number = 0
# numbers = 20,60,90,103,109,120
# for i in numbers:
# print(i - previous_number)
# previous_number = i
#with recursion
# previous_number = 0
# numbers = [20,60,90,103,109,120]
# def moving_difference(vals):
# if len(vals) == 1:
# return 0
# else:
# previous = vals.pop(0)
# print(vals[0] - previous)
# return moving_difference(vals)
# moving_difference(numbers) |
7b833e07e872f68d03cdb5195f55ab2c58de70cd | IamConstantine/LeetCodeFiddle | /python/PascalTriangle.py | 376 | 3.5 | 4 | from typing import List
def generate(numRows: int) -> List[List[int]]:
result = [[1]]
for row in range(2, numRows + 1):
curr = [1] * row
i = 1
j = (1 + row) // 2
while i < j:
last = result[-1]
curr[i] = curr[row - 1 - i] = last[i - 1] + last[i]
i += 1
result.append(curr)
return result
|
cc6d293b05462b11f0258877e26770fc5fcefa08 | riturajkush/Geeks-for-geeks-DSA-in-python | /bit magic/prog2.py | 1,050 | 3.5625 | 4 | #{
#Driver Code Starts
#Initial Template for Python 3
import math
def getRightMostSetBit(n):
return math.log2(n&-n)+1
# } Driver Code Ends
#User function Template for python3
##Complete this function
def posOfRightMostDiffBit(m,n):
m = int(bin(m).replace("0b",""),2)
n = int(bin(n).replace("0b",""),2)
res = bin(m^n).replace("0b","")
flag =0
for i in range(0,len(res)):
val = bin(1<<i).replace("0b","")
print(val, (int(res,2) & int(val,2)))
if((int(res,2) & int(val,2))!=0):
flag =1
return (i+1)
if(flag==0):
return -1
#{
#Driver Code Starts.
def main():
T=int(input())
while(T>0):
mn=[int(x) for x in input().strip().split()]
m=mn[0]
n=mn[1]
print(math.floor(posOfRightMostDiffBit(m,n)))
T-=1
if __name__=="__main__":
main()
#} Driver Code Ends
|
8b8792961a959e0b9646f24669b4c0a2d4b15bd9 | Cowcoder21/Hangman | /Hangman.py | 1,515 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[84]:
def guess():
target = input("The word the others have to guess is: " )
letters = 'abcdefghijklmnopqrstuvwxyz'
max_attempts = 3
counter = 0
previous_guesses = []
while True:
guess = input ("Guess a letter in the target word: ")
if guess not in letters:
print("Chose another character which is a letter")
continue
elif guess in previous_guesses:
print("You have already guessed this letter, try another ")
continue
elif guess not in target:
counter += 1
print("thats a strike! Only " + str(max_attempts - counter) + " guesses left! keep going")
print (counter)
previous_guesses.append(guess)
if counter == max_attempts:
print("You are out of guesses!")
break
elif guess in target:
print("You got a correct guess! keep going")
target = target.replace(guess, "")
# print(target)
previous_guesses.append(guess)
if target == "":
print("You have guessed the word! you win!")
break
else:
continue
elif guess in previous_guesses:
print("You have already guessed this letter ")
continue
print (guess())
# In[ ]:
# In[ ]:
# In[ ]:
|
b7b12b5c836ee574b11b7cfbddbdb37af7385436 | Matt-Robinson-byte/DigitalCrafts-classes | /python102/only-odds.py | 148 | 3.984375 | 4 | def is_even(number):
if number%2 == 0:
return True
else:
return False
def is_odd():
return not is_even()
def only- |
7321a8c0ec9cc9435bea1b3bdae8e9f5e94a2e5f | deepaksharma36/Artificial_Intelligence | /Project2_MLP_Classification/src/trainMLP.py | 13,689 | 3.90625 | 4 | """
File: trainMLP.py
Language: Python 3.5.1
Author: Karan Jariwala( kkj1811@rit.edu )
Aravindh Kuppusamy ( axk8776@rit.edu )
Deepak Sharma ( ds5930@rit.edu )
Description: It takes a file containing training data as input and trained
neural network weights after some epochs. It uses batch
gradient descent to trained neural network weights.
"""
__author__ = "Karan Jariwala, Aravindh Kuppusamy, and Deepak Sharma"
# Importing python module
import numpy as np
import matplotlib.pyplot as plt
import random
import os, sys
# Global Constants
DATA_File = 'train_data.csv'
DATA_FILE_TEST = "test_data.csv"
WEIGHTS_FILE='weights'
numNeuronsOutputLayer= 4
numNeuronsHiddenLayer = 5
CLASSES = 4
# EPOCHS = 1000
NUM_LAYER = 2
LEARNING_RATE = 0.1
class neuron:
"""
Represents a neuron unit in network
"""
__slots__= ( 'num_inputs','num_outputs','weights','input','activation' )
def __init__(self,inputs,outputs):
"""
Initializing parameters
:param inputs: Number of Inward connections
:param outputs: Number of outward connection
:return: None
"""
self.num_inputs=inputs
self.num_outputs=outputs
self.weights=self.__inti_weight__(self.num_inputs)
self.input=None
self.activation=None
def __inti_weight__(self,num_input):
"""
Initializing neuron weights with small random number
:param num_input: number of weight units for incoming connections
:return: random weights
"""
weights=[]
for counter in range(num_input):
weights.append(random.uniform(-1, 1))
weights=np.array(weights)
return weights
def __sigmoid__(self,input):
"""
Implementation of activation function
:param input: sum(Weights*inputs)
:return: activation of neuron
"""
return 1/(1+np.exp(-1*input))
def __activation__(self,inputs):
"""
Produce activation for a given input
:param inputs: inputs to neuron
:return: activation
"""
activation=0
for counter in range(self.num_inputs):
activation+=self.weights[counter]*inputs[counter]
return self.__sigmoid__(activation)
def response(self,inputs):
"""
Method for finding activation for a given output
record the state of the neuron for back propagation
:param inputs: (list) inputs to the neurons
:return: activation
"""
self.input=inputs
activation=self.__activation__(inputs)
self.activation=activation
return activation
def get_weights(self):
"""
Return weights of the the neuron
:return: Weight np array
"""
return self.weights
def set_weights(self,weights):
"""
Set weights of the neuron
:param weights: Np array of size num_input
:return: None
"""
self.weights=weights
class layer:
"""
Represents a layer in MLP, can contain multiple neurons
Assumption: each input to the layer is connected to each neuron of the layer
"""
__slots__= ( 'num_inputs','num_outputs','num_neurons','neurons' )
def __init__(self,num_inputs=1,num_outputs=1,num_neuron=1):
"""
Initializing the layer
:param num_inputs: number of inputs reaching to layer
:param num_outputs: number of output requires from layer
:param num_neuron: number of neuron in layer
"""
self.num_inputs=num_inputs
self.num_outputs=num_outputs
self.num_neurons=num_neuron
self.neurons=self.__init_neurons(num_neuron,num_inputs,num_outputs)
def __init_neurons(self,num_neurons,inputs,outputs):
"""
Creating required number of neurons for the layer
:param num_neurons: required number of neurons(int)
:param inputs: List of values
:param outputs: List of output values for the next layer
:return: list of neurons
"""
neurons=[]
for _ in range(num_neurons):
neurons.append(neuron(inputs,outputs))
return neurons
def response(self,inputs):
"""
Generating response of the layer by collecting activation of each
neuron of the layer
:param inputs: input list containing activation of previous/input layer
:return: list containing response of each neuron of the layer for
the provided inputs
"""
response=[]
for neuron in self.neurons:
response.append(neuron.response(inputs))
return response
def get_neurons(self):
"""
Getter method to return a list of neuron objects
:return: return a list of neuron objects
"""
return self.neurons
def get_num_neurons(self):
"""
Getter method to return number of neuron in a layer
:return: return number of neuron in a layer
"""
return self.num_neurons
class MLP:
"""
Representation of a neural network. It contain neuron layers.
"""
__slot__= ( 'network' )
def __init__(self,num_input,num_output):
"""
Creating a MLP with number of input and output channels
:param num_input:=Number of inputs to MLP
:param num_output:=Number of outputs from MLP
:return: None
"""
a_hidden_layer = layer(num_input, numNeuronsHiddenLayer + 1, numNeuronsHiddenLayer)
a_Output_layer = layer(numNeuronsHiddenLayer + 1, num_output, numNeuronsOutputLayer)
self.network=list([a_hidden_layer,a_Output_layer])
def forward_prop(self,input):
"""
Generating the activation of the MLP
:param input: input to the MLP
:return: return prediction/activation
"""
activation=input
for layer in range(NUM_LAYER):
activation=self.network[layer].response(activation)
if layer == 0:
activation.insert(0,1)
return activation
def network_update(self,weights):
"""
Assign weights of the MLP
:param weights: list(layer) of list(neuron) of np arrays(weights)
:param network: MLP (list of layer)
:return: None
"""
for layer_counter in range(len(self.network)):
neurons=self.network[layer_counter].get_neurons()
for neuron_counter in range(len(neurons)):
neurons[neuron_counter].set_weights(weights[layer_counter][neuron_counter])
def get_netWork_weights(self):
"""
It returns the network weights
:param network: MLP (list of layer)
:return: list(layer) of list(neuron) of np arrays(weights)
"""
weights=[]
for layer in self.network:
weights.append([])
for neuron in layer.get_neurons():
weights[-1].append(neuron.get_weights())
return weights
def configure_network_weight(self,weight_file):
"""
Assign weights to the MLP's neurons provided in text file
:param weight_file:
:return:
"""
file = open(weight_file, "r")
for line in file:
pass
lastline=line
weight_vector=lastline.strip().split(",")
weight_counter=0
for layer in self.network:
neurons=layer.get_neurons()
for neuron in neurons:
weight=[]
for counter in range(neuron.num_inputs):
weight.append(float(weight_vector[weight_counter]))
weight_counter+=1
neuron.set_weights(np.array(weight))
def back_prop(mlp, old_weight,error):
"""
Implementation of back propagation
:param old_weight: list(size=layer_count) of list(size=neuron_count) of np arrays(weights)
:param sample: input
:param error: list of true_lable-[output layer activation]
:param prediction: activation of last layer a list
:param network: MLP
:return: updated weight
"""
net_output_layer=mlp.network[-1] # 1 output layer
output_neurons=net_output_layer.get_neurons()
previous_delta=[]
for neuron_counter in range(len(output_neurons)): #
activation=output_neurons[neuron_counter].activation
input=output_neurons[neuron_counter].input #list
dsigmoid = activation*(1-activation)#[ acti * (1 - acti) for acti in activation] # 2 sigmoid
delta = error[neuron_counter]*dsigmoid#[ err * dsig for err, dsig in zip(error, dsigmoid)] # 2 delta
dw = [ LEARNING_RATE * delta* inp for inp in input] # will be a dot product in future
old_weight[-1][neuron_counter]+=dw #temperary
previous_delta.append(delta)
net_hidden_layer = mlp.network[-2] # 2nd layer
hidden_neurons = net_hidden_layer.get_neurons() # 3 neuron
output_weights = []
for neu in output_neurons:
output_weights.append( neu.get_weights() ) # 2 list of 4 element each
hidden_delta = []
for neuron_counter in range(len(hidden_neurons)): # 3 neurons
acti = hidden_neurons[neuron_counter].activation # 1 activation
input = hidden_neurons[neuron_counter].input # 3 elements
delta = 0
for delta_counter in range(len(previous_delta)):
delta += previous_delta[delta_counter] * \
output_weights[delta_counter][neuron_counter + 1]
hidden_delta.append(delta * acti * (1 - acti))
dw = [LEARNING_RATE * hidden_delta[neuron_counter] * inp for inp in
input]
old_weight[-2][neuron_counter] += dw # temperary
return old_weight
def load_dataset(file_name):
"""
Read data line wise from the input file
create attribute array with appending 1 (for bias implementation)
looks like =[x1, x2, 1]
:param file_name:
:return: np array of attribute and labels
"""
data=[]
with open(file_name) as data_file:
for line in data_file:
line_list=line.strip().split(",")
data.append([])
data[-1].append(float(1))
data[-1].append(float(line_list[0]))
data[-1].append(float(line_list[1]))
if float(line_list[2]) == 1.0:
data[-1].extend([float(1),float(0),float(0),float(0)])
if float(line_list[2]) == 2.0:
data[-1].extend([float(0),float(1),float(0),float(0)])
if float(line_list[2]) == 3.0:
data[-1].extend([float(0),float(0),float(1),float(0)])
if float(line_list[2]) == 4.0:
data[-1].extend([float(0),float(0),float(0),float(1)])
data=np.array(data)
label = data[:, 3:7]
attributes = data[:, 0:3]
return attributes,label
def gradient_decent(network, data_file):
"""
Implementation of Batch gradient decent algorithm
:return: None
"""
#loading data
attributes,label=load_dataset(data_file)
#initalizing sum of square error
SSE_History=[] #list for storing sse after each epoch
num_samples=attributes.shape[0]
epochs = int(sys.argv[2])
wt_file = WEIGHTS_FILE + "_" + str(epochs) + ".csv"
if os.path.isfile(wt_file):
os.remove(wt_file)
for epoch in range(epochs):
SSE = 0
new_weight=network.get_netWork_weights()
for sample in range(num_samples):
prediction=network.forward_prop(attributes[sample])
error=[]
for bit_counter in range(len(label[sample])):
error.append(label[sample][bit_counter] - prediction[bit_counter])
for bit_error in error:
SSE+=(bit_error)**2
new_weight=\
back_prop(network, new_weight,error)
network.network_update(new_weight)
#storing the Sum of squre error after each epoch
SSE_History.append(SSE)
write_csv(network)
print("After epoch "+str(epoch+1)+ " SSE: "+str(SSE ))
# write_csv(network)
return network, SSE_History
def write_csv(network):
"""
It writes the weights in a CSV file
:param network: A neuron network
:return: None
"""
weight_line=""
epochs = int(sys.argv[2])
weights=network.get_netWork_weights()
for layer_counter in range(len(weights)):
for neuron_counter in range(len(weights[layer_counter])):
for weight in weights[layer_counter][neuron_counter]:
weight_line+=str(weight)+","
weight_line=weight_line[0:len(weight_line)-1]
myStr = WEIGHTS_FILE + "_" + str(epochs) + ".csv"
fp = open(myStr, "a+")
fp.write(weight_line+"\n")
fp.close()
def SSE_vs_epoch_curve(figure, loss_matrix):
"""
It generate a plot of SSE vs epoch curve
:param figure: A matplotlib object
:param loss_matrix: A matrix loss
:return: None
"""
loss__curve = figure.add_subplot(111)
loss__curve.plot(loss_matrix, label='Training')
loss__curve.set_title("SSE vs Epochs")
loss__curve.set_xlabel("Epochs count")
loss__curve.set_ylabel("SSE")
loss__curve.legend()
def main():
"""
Main method
return: None
"""
if len(sys.argv) != 3:
print("FAILED: Please provide the proper python command line arguments")
print("Usage: python3 trainMLP <file> <N>")
print("<file> = train csv file")
print("<N> = Number of epochs")
sys.exit(1)
network = MLP(3, 4)
trained_network,SSE_History = gradient_decent(network, sys.argv[1])
figure = plt.figure()
SSE_vs_epoch_curve(figure, SSE_History)
figure.show()
plt.show()
if __name__=="__main__":
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.