blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
66b8c6815a588d9c9c1bfac47ce0e22d3ebb20f0
cytoly/data_structures
/implementations/LinkedList.py
2,755
4.125
4
from typing import Union class Node: def __init__(self, data=None): self.data = data self.next: Union[Node, ()] = None def has_next(self) -> bool: return self.next is not None class LinkedList: def __init__(self): self.head: Union[Node, ()] = None self.length = 0 def __len__(self) -> int: # current_node = self.head # count = 0 # while current_node is not None: # count += 1 # current_node = current_node.next # return count return self.length def prepend(self, data) -> (): new_node = Node(data) if self.length == 0: self.head = new_node else: new_node.next = self.head self.head = new_node self.length += 1 def append(self, data) -> (): current_node = self.head while current_node.has_next(): current_node = current_node.next new_node = Node(data) current_node.next = new_node self.length += 1 def all(self) -> Union[list, str]: if self.length == 0: return "empty" current_node = self.head output = [] while current_node: output.append(current_node.data) current_node = current_node.next return output def pop_start(self): if self.length == 0: return print("empty") self.head = self.head.next self.length -= 1 def pop(self): current_node = self.head if self.length <= 1: self.pop_start() return while current_node.next.has_next(): current_node = current_node.next current_node.next = None self.length -= 1 def insret(self, index: int, data) -> (): if self.length < index or index < 0: return print("are you dumb?") if index == 0: self.prepend(data) return if index == self.length: self.append(data) return new_node = Node(data) count = 0 current = self.head while count < index-1: count += 1 current = current.next new_node.next = current.next current.next = new_node self.length += 1 def clear(self): self.head = None self.length = 0 class test(LinkedList): def pop(self): ... if __name__ == "__main__": ll = LinkedList() ll.prepend(69) ll.append(420) print(len(ll)) print(ll.all()) ll.pop() ll.pop_start() print(ll.all()) ll.insret(0, "hello world") ll.insret(1, "testing") ll.insret(2, "nerd") print(ll.all()) ll.clear() print(ll.all())
8d600e3a5ca852a4f986c929b7a9b538237361cd
yeo040294/cz1003
/FunctionList.py
3,623
3.71875
4
from tkinter import * def tick(): import time time1 = '' time2 = time.strftime('%a, %d %b %y %H:%M:%S') # get the current local time from the PC if time2 != time1: # if time string has changed, update it time1 = time2 clock.config(text=time2) # calls itself every 200 milliseconds # to update the time display as needed # could use >200 ms, but display gets jerky clock.after(200, tick) def StallList(index): #Returns all unique values in .csv (e.g. Stall List or Weekdays) import csv listof = set() #set() is a method to help identify unique values with open("Menu.csv") as file_pointer: csv_pointer = csv.reader(file_pointer) for row in csv_pointer: listof.add(row[index]) return list(listof) def getStallListByDay(day): import csv listof = set() with open("Menu.csv") as file_pointer: csv_pointer = csv.reader(file_pointer) for row in csv_pointer: if row[0] == day: listof.add(row[1]) return list(listof) def MenuTypeByHour(hour): from datetime import datetime time = int(hour) menutype = ["Breakfast", "Lunch & Dinner"] if time >= 9 and time < 12: return menutype[0] elif time >= 12 and time < 20: return menutype[1] else: return def MenuType(): from datetime import datetime time = int(datetime.now().strftime("%H")) menutype = ["Breakfast", "Lunch & Dinner"] if time > 9 and time < 12: return menutype[0] elif time >= 12 and time < 20: return menutype[1] else: return def getMenu(menutype , day , stall): print('at getMenu') print(menutype) print(day) print(stall) import csv from datetime import datetime from collections import defaultdict with open("Menu.csv") as file_pointer: csv_pointer = csv.reader(file_pointer) for row in csv_pointer: print(row[0]) print(row[1]) if row[0] == day and row[1] == stall: if menutype == "Breakfast": return row[2] elif menutype == "Lunch & Dinner": return row[3] def Menu(menutype, day, stall): #Find breakfast or lunch menu based on day and stall name import csv from datetime import datetime from collections import defaultdict with open("Menu.csv") as file_pointer: csv_pointer = csv.reader(file_pointer) #menutype = MenuType() newdict = {} if menutype == "Breakfast": for each in csv_pointer: newdict.setdefault(each[0], {})[each[1]] = each[2] elif menutype == "Lunch & Dinner": for each in csv_pointer: newdict.setdefault(each[0], {})[each[1]] = each[3] else: return query = newdict[day][stall] return query def DisplayMenu(window , menutype, day, stall): #To display all food and prices for a particular stall itemlist = getMenu(menutype, day, stall) print(itemlist) if itemlist == None: label = Label(window, text="Closed", font=("arial 10")).pack() else: itemlist = itemlist.split(", ") food = [i.split(" / ")[0] for i in itemlist] price = [float(i.split(" / ")[1]) for i in itemlist] count = 1 for index, item in enumerate(food): display = str(count) + ". {:<10s} ${:.2f}".format(item, price[index]) label = Label(window, text=display, font=("arial 10")).pack() count += 1 return label
522385d08ccd855e401d141f9f4e8ccf1535f926
purwokang/learn-python-the-hard-way
/ex6.py
971
4.15625
4
# creating variable x that contains format character x = "There are %d types of people." % 10 # creating variable binary binary = "binary" # creating variable do_not do_not = "don't" # creating variable y, contains format character y = "Those who know %s and those who %s." % (binary, do_not) # printing content of variable x print(x) # printing content of variable y print(y) # printing the content of variable x print("I said: %r." % x) # printing the content of variable y print("I also said: '%s'." % y) # creating variable with boolean content hilarious = True # creating variable, contains format character joke_evaluation = "Isn't that joke so funny?! %r" # printing combination of two variables print(joke_evaluation % hilarious) # creating variable w with string content w = "This is the left side of..." # variable e, the content is string as well e = "a string with a right side." # printing both variable w and e, consist of strings print(w + e)
73fde459583226d6bdd2dc97c3bb7be80d5bd206
patidarrohit/us-state-guess-game
/main.py
931
3.828125
4
import turtle import pandas as pd screen = turtle.Screen() screen.title('U.S. States Game') image = "blank_states_img.gif" turtle.addshape(image) turtle.shape(image) guessed_state = [] data = pd.read_csv("50_states.csv") states = data.state.to_list() while len(guessed_state) < 50: answer = turtle.textinput(title=f"{len(guessed_state)}/50 states Correct", prompt="What's the another state name?").title() if answer == 'Exit': missing_states = [state for state in states if state not in guessed_state] pd.DataFrame(missing_states).to_csv("states_to_learn.csv") break if answer in states and answer not in guessed_state: guessed_state.append(answer) t = turtle.Turtle() t.penup() t.hideturtle() state_data = data[data.state == answer] t.goto(int(state_data.x), int(state_data.y)) t.write(state_data.state.item()) #screen.exitonclick()
5211bb145600460c72b911168a3917b2d2086e56
cyberandrei/time_tailored_string_exercise
/calculate_total_minutes_in.py
3,457
3.859375
4
import re from math import ceil from decimal import Decimal import unittest string_example="all I did today; i 20m, 35m, 2.5h, 2h40m v 40m 35m 1.2h e 30, 60m " class MinutesTest(unittest.TestCase): def test_calculate_total_minutes_in(self): self.assertEqual(calculate_total_minutes_in(), 602) # check seprators (a comma, a space, a comma followed by spaces) to be handled properly: self.assertEqual(calculate_total_minutes_in("all I did today; ,,,, i 20m , , 35m,2.5h,2h , 40m v 40m,35m, 1.2h e 30,, 60m , "), 602) # input string that does not contain ';' character: self.assertEqual(calculate_total_minutes_in("all I did today"), 0) # input string is empty: self.assertEqual(calculate_total_minutes_in(""), 0) # input string contains a lot of not meaningful charscters: self.assertEqual(calculate_total_minutes_in("all I did today;r i y 20m, g 35m, 2.5h, 2hu40m v 40m 35m r1.2h e 30, 60m i pp"), 602) # input string contains floats: self.assertEqual(calculate_total_minutes_in("all I did today; 2.5854589999999999h"), 156) self.assertEqual(calculate_total_minutes_in("all I did today; 1.00000000000000000000001"), 2) self.assertEqual(calculate_total_minutes_in("all I did today; 2.55465456456456h 60.6546456456564m "), 214) self.assertEqual(calculate_total_minutes_in("all I did today; 2.55465456456456h60.6546456456564m 0.0000000001 "), 214) # input string does not contain any time enties, just not meaningful charscters including "h" and "m": self.assertEqual(calculate_total_minutes_in("all I did today; f d t h g e t y m l"), 0) # just some random test cases: self.assertEqual(calculate_total_minutes_in("all I did today"), 0) self.assertEqual(calculate_total_minutes_in("all I did today;1 1 1 1 1 1 1"), 7) self.assertEqual(calculate_total_minutes_in("all I did today;1m 1m 1m 1m 1m 1m 1h 1m"), 67) self.assertEqual(calculate_total_minutes_in("all I did today;1m 1m 1m 1m 1m 1m 1m1h 10m0h"), 77) self.assertEqual(calculate_total_minutes_in("all I did today;1m 1m 1m 1m 1m 1m 1m1h 10m000000000000000001h"), 137) self.assertEqual(calculate_total_minutes_in("all I did today; i 20m, 35m, 2.5h, 3h40m v"), 425) def calculate_total_minutes_in(time_tailored_string=string_example): total_minutes = 0 if ';' not in time_tailored_string: return total_minutes else: tokens = re.split(',\s*|[,\s]', time_tailored_string.split(";")[1]) tokens_with_numbers = [x for x in tokens if any(c.isdigit() for c in x)] for token in tokens_with_numbers: if ('h'in token) or ('m'in token): matched_hours = re.search(r'[\d.]+($|(?=[h]))', token) if matched_hours is not None: hours = matched_hours.group(0) else: hours = 0 matched_minutes = re.search(r'[\d.]+($|(?=[m]))', token) if matched_minutes is not None: minutes = matched_minutes.group(0) else: minutes = 0 else: minutes = re.search(r'[0-9]*\.?[0-9]*', token).group(0) hours = 0 total_minutes += Decimal(hours)*60 + Decimal(minutes) return ceil(total_minutes) if __name__ == "__main__": unittest.main()
ea1e981b9a899e15fddce5b28d20ea97c05b5ccd
lovingstudy/Molecule-process
/point2Plane.py
1,296
4.15625
4
#--------------------------------------------------------------------------------------------------- # Name: point2Plane.py # Author: Yolanda # Instruction: To calculate the distance of a point to a plane, which is defined by 3 other points, # user should input the coordinates of 3 points in the plane into (x1,y1,z1)(x2,y2,z2)(x3,y3,z3), # also input the coordinates of the point out of the plane into (x0,y0,z0). This program will # print the distance. # Application: Measure the distance of a atom to a benzene ring. #--------------------------------------------------------------------------------------------------- import numpy as np from scipy import linalg # 3 points to define a plane. For example, 3 atoms in a benzene ring. x1, y1, z1 = 0.421, 9.340, 10.017 x2, y2, z2 = -0.042, 8.673, 8.866 x3, y3, z3 = 0.785, 8.316, 7.853 # Train the equation of the plane. Equation: Ax + By + Cz + 1 = 0 A = np.array([[x1,y1,z1],[x2,y2,z2],[x3,y3,z3]]) b = np.array([[-1],[-1],[-1]]) pr = list(linalg.inv(A).dot(b).flat) + [1] # pr == [A, B, C, 1] # The point out of the plane. x0, y0, z0 = 2.691, 11.980, 9.187 # Calculte the distance of the point to the plane. d = np.abs(sum([p*x for p,x in zip(pr, [x0,y0,z0,1])])) / np.sqrt(sum([a**2 for a in pr[:3]])) print "Distance: ", d
19e10f2d86501c35eacca1775d2717e4c27a52a1
chrisadbr/Python-Tutorial
/employee.py
665
3.953125
4
class Employee: emp_count = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.emp_count += 1 """def display_count(self): print(f"Total number of employees: {Employee.emp_count}")""" def display_employee(self): print("Name: ", self.name, "\nSalary: ", self.salary, "\n") emp1 = Employee('Juma Adonis', 5500) emp2 = Employee('Christian Brown', 78500) emp3 = Employee('Daniel Mbando', 70000) emp1.salary = 804500 emp1.display_employee() emp2.display_employee() emp3.display_employee() del emp1.salary print(hasattr(emp1, 'salary')) print(f"Total number of employees: {Employee.emp_count}")
eaf7562051ed60068967a4d5e5f0cdf2fb0f428f
liu-yuxin98/Python
/chapter3/3.8.py
134
3.65625
4
import math number=(input("input a number:")) number_new=number[::-1] number_result=int(number_new.lstrip("0")) print(number_result)
849b8d7b506850e4c17a06336311474482d0304e
liu-yuxin98/Python
/myOwnfunc/isPalindrom.py
141
3.53125
4
from myOwnfunc import Reverse def isPalindrom(number): if number==Reverse.reverse(number): return 1 else: return 0
8322a7426daf57e6aa802952ca4a7680db6531b2
liu-yuxin98/Python
/myOwnfunc/IsLeapYear.py
1,373
3.796875
4
def IsLeapYear(year): if year%4==0 and year%100!=0: return 1 elif year%400==0: return 1 else: return 0 monthLeap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def NumberOfDaysOftheMonth(year,month): if IsLeapYear(year): return monthLeap[month-1] else: return month[month-1] #1800 year 1.1 is Wednesday def DayInWeek(year,month,day): # return the day in a week sum=0 for i in range(1800,year): if IsLeapYear(i): sum+=366 else: sum+=365 if IsLeapYear(year): for j in range(0,month): sum+=monthLeap[j] else: for j in range(0,month): sum+=month[j] sum+=day-1 day=sum%7 return day def GetMonth(n): if n==1: print("Jan",end=" ") elif n==2: print("Feb",end=" ") elif n==3: print("Mar",end=" ") elif n==4: print("April",end=" ") elif n==5: print("May",end=" ") elif n==6: print("June",end=" ") elif n==7: print("July",end=" ") elif n==8: print('Aug',end=" ") elif n==9: print("Sept",end=" ") elif n==10: print("Oct",end=" ") elif n==11: print("Nov",end=" ") else: print("Dec",end=" ")
3cafe63251f472829b0defa73519a2ec9e3a5aee
liu-yuxin98/Python
/chapter13/13-1.py
1,042
3.546875
4
# -*- coding: utf-8 -*- # 2020-02-19 # author Liu,Yuxin # check whether President.txt exists ''' import os.path if os.path.isfile('President.txt'): print("President.txt exists") ''' outfile = open("President.txt","w") outfile.write('Bill Clinton\n') outfile.write("George Bush\n") outfile.write('Barack Obama\n') outfile.write('Donlord Trump') outfile.close() ''' infile = open("President.txt", "r") # open file for input print(infile.read()) infile.close() print('------------------------') # second method infile = open("President.txt", "r") s1 = infile.read(10) print(s1) infile.close() print('------------------------') # third method infile = open("President.txt", "r") line1 = infile.readline() line2 = infile.readline() print(line1) print(line2) infile.close() print('------------------------') # fourth method infile = open("President.txt", "r") z = infile.readlines() print(infile.readlines()) infile.close() print('------------------------') ''' infile = open("President.txt", "r") z = infile.readlines() for i in range(4): print(z[i])
f2b1f3bd3c6fc0dbfbd1ec1174374dba2ed53c31
liu-yuxin98/Python
/PythonClass/week6/lab-6.py
1,775
3.5625
4
# -*- coding: utf-8 -*- # 2020-04-01 # author Liu,Yuxin print(chr(1)) ''' def containsDuplicate(lst): s = set(lst) # without set if len(s)==len(lst): print('NO') return 0 else: print('YES') return 1 n = int(input()) lst = input().split() lst = [ int(x) for x in lst] containsDuplicate(lst) ''' ''' n = int(input()) lst = input().split() lst = [ int(x) for x in lst] lst.sort() lst = lst[::-1] print(*lst) ''' ''' n = int(input()) lst = input().split() lst = [ int(x) for x in lst] pen = dict() for num in lst: pen[num] = pen.get(num, 0)+1 for key in pen: if pen[key] == 1: print(key) ''' ''' dict1 = dict() for num in lst: # create dict1 dict1[num] = dict1.get(num, 0)+1 # print(dict1) ''' ''' # 方法一 n = int(input()) lst = input().split() lst = [ int(x) for x in lst] subset = set(lst) newset = set() for i in range(0, len(lst)): newset.add(lst[i]) if newset == subset: print(i) break # 方法二 n = int(input()) lst = input().split() lst = [ int(x) for x in lst] subset = set(lst) subsetlst = list(subset) p = lst.index((subsetlst[0])) for i in range(0, len(subsetlst)): if lst.index(subsetlst[i]) >= p: p = lst.index(subsetlst[i]) # 方法三 n = int(input()) lst = input().split() lst = [ int(x) for x in lst] subset = set(lst) subsetlst = list(subset) p = [] for i in range(0, len(subsetlst)): p.append(lst.index(subsetlst[i])) # 找到每个元素第一次出现的下标 print(max(p)) # 方法四 n = int(input()) lst = input().split() lst = [ int(x) for x in lst] dict1 = dict() p = [] for i in range(0, len(lst)): dict1[lst[i]] = dict1.get(lst[i], 0)+1 if dict1[lst[i]] == 1: p.append(i) print(max(p)) '''
d1556d9eacb878908fc9ebb2393ee47a09b93022
liu-yuxin98/Python
/myOwnfunc/Reverse.py
411
3.875
4
def reverse(number): rnumber=0 if number<0: number=-1*number while number != 0: rnumber = 10 * rnumber + number % 10 number = (number - number % 10) / 10 rnumber=-1*rnumber else: while number != 0: rnumber = 10 * rnumber + number % 10 number = (number - number % 10) / 10 rnumber=rnumber return(rnumber)
193cb4ae9de57fdd0f44e672e6d7884aae0af1a0
liu-yuxin98/Python
/PythonClass/week5/5-7-4.py
324
3.703125
4
# -*- coding: utf-8 -*- # 2020-03-23 # author Liu,Yuxin def f(n): sum = 1 if n == 0: return 1 elif n ==1: return 1 else: for i in range(1,n+1): sum *= i return sum n = int(input()) lst = [ f(i) for i in range(1,n+1,2)] s = sum(lst) print('n='+str(n)+',s='+str(s))
b3e654fb7d302437c7d13d06d3abc6b7c83a28ef
liu-yuxin98/Python
/PythonClass/week5/5-7-1.py
329
3.65625
4
# -*- coding: utf-8 -*- # 2020-03-23 # author Liu,Yuxin def f(n): sum = 1 if n == 0: return 1 elif n ==1: return 1 else: for i in range(1,n+1): sum *= i return sum n = int(input()) lst = [1/f(i) for i in range(0,n+1)] result = sum(lst) print("{:.8f}".format(result) )
8f06c97a2061ed6cdd62c6230d8bf5857210ea84
liu-yuxin98/Python
/chapter7/shape.py
1,033
4.125
4
#-*- coding=utf-8-*- import math class Circle: def __init__(self,radius=1): self.radius=radius def getPerimeter(self): return self.radius*2*math.pi def getArea(self): return self.radius*self.radius*math.pi def setRadius(self,radius): self.radius=radius class Rectangular: def __init__(self,length=2,width=1): self.width=width self.length=length def setLength(self, length): self.length=length def setWidth(self, width): self.width=width def getArea(self): return self.width*self.length def getPerimeter(self): return 2*(self.width+self.length) class Coordinate: def __init__(self,x=0,y=0): self.x=x self.y=y def setVaule(self,x,y): self.x=x self.y=y def getX(self): return self.x def getY(self): return self.y ''' c1=Circle()# c1.radius=1 print(c1.radius) r1=Rectangular(5,3) print(r1.getArea()) p1=Coordinate(5,6) print(p1.x) print(p1.getX()) '''
913a343cf8aeeba68780700d8529c4cc3ebc82ad
liu-yuxin98/Python
/chapter5/5.1.py
229
3.890625
4
num = eval(input(" enter a number, except 0:")) sum=num count=0 while num!=0: num = eval(input(" enter a number, except 0:")) sum+=num count+=1 print("sum={}".format(sum/count,"5.2f")) print(format(sum/count,"5.2f"))#
571dd80f1fd7f2a70f1e7dbb9245829cc4b6eb6b
liu-yuxin98/Python
/chapter3/3.6.py
97
3.75
4
ch=input("enter a letter:") print(ord(ch)) nu=eval(input("enter an ascii code:")) print( chr(nu))
7d7d941bdfd9d5daf281f20613f6a975e9c6748a
liu-yuxin98/Python
/PythonClass/week4/4-7-1.py
375
3.59375
4
# -*- coding: utf-8 -*- # 2020-03-16 # author Liu,Yuxin n = int(input()) if n == 0: print('average = '+str(0.0)) print('count = ' + str(0)) else: gradelst = list(map(int, input().split())) avg = sum(gradelst) / n avg = round(avg, 1) count = len([k for k in gradelst if k >= 60]) print('average = ' + str(avg)) print('count = ' + str(count))
7d38432729304ddf772e5bcdb0f9e52ab8aa40ad
liu-yuxin98/Python
/myOwnfunc/isReversePrime.py
273
3.65625
4
from myOwnfunc import IsPrime from myOwnfunc import Reverse def isReversePrime(number): if number<10: return 0 else: if IsPrime.IsPrime(number) and IsPrime.IsPrime(Reverse.reverse(number)): return 1 else: return 0
728b4d353e7f9413c02c942701be5a63b89b3687
liu-yuxin98/Python
/PythonClass/week3/3-lab.py
1,871
3.53125
4
# -*- coding: utf-8 -*- # 2020-03-11 # author Liu,Yuxin ''' def sumlst(n): if n == 1: lst = [1] elif n == 2: lst = [1,-2/3] else: lst = [-i/(2*i-1) if i%2==0 else i/(2*i-1) for i in range(2, n+1)] lst.insert(0,1) return sum(lst) n = eval(input()) print("{:.3f}".format( sumlst(n) )) ''' ''' def creatlsta(a, n ): if n == 1: lst = [a] else: lst = [ a * i for i in range(1, n+1)] lst = [ eval(t) for t in lst ] return sum(lst) s = input().split() a = s[0] n = eval(s[1]) print('s = ',end='') print(creatlsta(a,n)) ''' ''' def createlstab(a,b): if a == b: lst = [a] else: lst = [i for i in range(a, b+1)] return lst s = input().split() a = eval(s[0]) b = eval(s[1]) lst = createlstab(a, b) for i in range(len(lst)): if i>4 and i%5 == 0: print('') print("{:>5d}".format(lst[i]), end='') print('') print('Sum = ', end='') print(sum(lst)) ''' ''' def createlstm(m): lst = [i for i in range(11,m+1)] return lst m = eval(input()) print('sum =', end=' ') print(sum(createlstm(m))) ''' ''' import math def IsPrime(x): if x == 1: return 0 elif x == 2: return 1 else: i = 2 while i < math.sqrt(x): if x % i == 0: return 0 i = i + 1 if i > math.sqrt(x): return 1 number = eval(input()) if IsPrime(number): print(str(number)+' is a prime number.') else: print(str(number)+' is not a prime number.') ''' ''' index = s.find('is') index2 = s.find('is', index) index3 = s.find('is', index2) # indexi = s.find('is', index(i-1)) ''' s = 'is is is is' number = s.count('is') index = s.find('is') indexlst = [index] for i in range(number-1): index = s.find('is', index+1,len(s)) indexlst.append(index)
fae798cbf978a8219c737399647ff1dbc8309772
liu-yuxin98/Python
/chapter9/9-11.py
1,512
3.796875
4
# -*- coding: utf-8 -*- # 2020-02-04 # author Liu,Yuxin from tkinter import * import math class LoacCalculator: def __init__(self): # window and two frame window = Tk() window.title('Loan Calculator') # left 5 labels Label(window, text='Annual Interest Rate:').grid(row=1, column=1) Label(window, text='Number of years:').grid(row=2, column=1) Label(window, text='Loan Amount').grid(row=3, column=1) Label(window, text='Monthly payment').grid(row=4, column=1) Label(window, text='Total Payment').grid(row=5, column=1) # three Entry: self.AnnualIR = IntVar() self.NumberOY = IntVar() self.LoanA = IntVar() Entry(window, textvariable=self.AnnualIR).grid(row=1, column=2) Entry(window, textvariable=self.NumberOY).grid(row=2, column=2) Entry(window, textvariable=self.LoanA).grid(row=3, column=2) # two Label self.labelMp = Label(window, text=0) self.labelMp.grid(row=4, column=2) self.labelTp = Label(window, text=0) self.labelTp.grid(row=5, column=2) # one button Button(window, text='Calculate', command=self.Calculate).grid(row=6, column=2) window.mainloop() def Calculate(self): tp = self.LoanA.get()*math.pow((1+self.AnnualIR.get()/100), self.NumberOY.get()) mp = tp/(12*self.NumberOY.get()) self.labelMp['text'] = round(mp) self.labelTp['text'] = round(tp) LoacCalculator()
e5719292794e7507606d3c952730bd9d02352656
tushushu/artificial-intelligence
/bfs and dfs.py
5,198
4.21875
4
# -*- coding: utf-8 -*- """ @Author: liu @Date: 2018-05-07 20:40:47 @Last Modified by: liu @Last Modified time: 2018-05-07 20:40:47 """ class Node(): def __init__(self): self.next = set() self.color = "white" class graph(object): def __init__(self): """[summary] e.g. If there are three egdes: 0→1, 0→2, 2→3 then the dictionary of graph will be like this: Node(0).next {Node(1), Node(2)} Node(1).next: {Node(0)} Node(2).next: {Node(0), Node(3) Node(3).next: {Node(2)} """ self.nodes = {} def add_edge(self, start, end): """[summary] Add an edge into the graph Arguments: start {int} -- start node number of the edge end {int} -- end node number of the edge """ nodes = self.nodes # {start node number: end node} if nodes.get(start): nodes[start].next.add(end) else: nodes[start] = Node() nodes[start].next = set([end]) # {end node number: start node} if nodes.get(end): nodes[end].next.add(start) else: nodes[end] = Node() nodes[end].next = set([start]) def reset_color(self): """[summary] Reset the colors of all nodes """ for node in self.nodes.values(): node.color = "white" def bfs(self, start, target): """[summary] Search the nearest path from start to target Arguments: start {int} -- start node number target {int} -- target node number Returns: list -- the nearest path from start to target """ nodes = self.nodes # Terminate earlier if start not in nodes or target not in nodes: return None # Record paths, 2D list que = [[start]] # Search the graph while que: # Visit the child nodes of the first node in the que current_node_num = que[0][-1] child_node_nums = nodes[current_node_num].next for child_node_num in child_node_nums: # Append them together if the child node's not explored if nodes[child_node_num].color == "white": que.append(que[0] + [child_node_num]) # Target found if child_node_num == target: self.reset_color() return que[-1] # Pop first node in the que and marked as explored nodes[current_node_num].color = "black" que.pop(0) # Not found self.reset_color() return None def dfs(self, start, target): """[summary] Search the one path from start to target Arguments: start {int} -- start node number target {int} -- target node number Returns: list -- one path from start to target """ nodes = self.nodes # Terminate earlier if start not in nodes or target not in nodes: return None # Record paths, 1D list stack = [start] nodes[start].color = "gray" # Search the graph while stack: # Visit the child node of the last node in the stack current_node_num = stack[-1] # get its child child_node_nums = nodes[current_node_num].next # set up a flag to check if there is any while child has_while_child = False for child_node_num in child_node_nums: # Append while child to path if nodes[child_node_num].color == "white": has_while_child = True stack.append(child_node_num) # Mark child node as explored nodes[child_node_num].color = "gray" break # Mark current node as fully explored if not has_while_child: nodes[child_node_num].color == "black" stack.pop() # Target found if child_node_num == target: self.reset_color() return stack # Not found self.reset_color() return None if __name__ == '__main__': # Build graph edges = [ [0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [0, 7], [2, 7], [6, 9], [7, 8], [8, 9], [7, 10], [8, 11], [9, 11], [10, 13], [11, 13], [13, 14], [13, 17], [12, 15], [15, 16], [16, 17], [17, 18], [18, 19], ] rome_graph = graph() for edge in edges: rome_graph.add_edge(*edge) # Search path start, target = 2, 13 print("The bfs path from {start} to {target} is:".format( start=start, target=target), rome_graph.bfs(start, target)) print("The dfs path from {start} to {target} is:".format( start=start, target=target), rome_graph.dfs(start, target))
ad50e57b62467400f9ff978a0bbc5135033b3200
kutoga/learning2cluster
/core/nn/misc/uncertainity.py
1,251
4.09375
4
import numpy as np def uncertainity_measure(dist): """ The uncertainity measure is just the normalized entropy of the input distribution. If the value is 0, then one single value is selected. If the value is 1 then the distribution is uniform This measure may be used for a neural network softmax output: If it is 0, then the network is quite sure about its selection. On the other side, if the value is 1, then the network is absolutely not sure about the selection. :param dist: :return: """ num_classes = np.prod(dist.shape) # Simple case: 1 class => the (normalized) entropy is always 0 if num_classes == 1: return 0. # Calculate the entropy non_zero_dist = dist[dist != 0.] entropy = -np.sum(non_zero_dist * np.log2(non_zero_dist)) # Normalize it norm_entropy = entropy / np.log2(num_classes) return norm_entropy def average_uncertainity_measure(dists): return np.mean(list(map(uncertainity_measure, dists))) if __name__ == '__main__': print(uncertainity_measure(np.asarray([0.2, 0.6, 0.2]))) print(uncertainity_measure(np.asarray([0.5, 0.5]))) print(uncertainity_measure(np.asarray([1.0])))
93c378525593aef72ea35ed3a740b1988ea22bf6
kutoga/learning2cluster
/playground/creepy_network.py
4,449
3.78125
4
# This test is independent of the MT;-) # This code is really just to play around. It is a try to implement some neural network like thing that only operates # on boolean values (which is much faster than working with floats). import numpy as np np.random.seed(1) # The complete network only works with 1d data. Currently we only use {0, 1} data input_size = 2 hidden_layer_sizes = [100] output_size = 1 # We need to generate some data. et us program an xor-software x = [ [0, 0], [0, 1], [1, 0], [1, 1] ] y = [ 0, 1, 1, 0 ] # That's it for now:) # First make numpy arrays: x = np.asarray(x) y = np.asarray(y) # The output layer is just another "hidden layer" hidden_layer_sizes.append(output_size) # Create the required weights: Every layer contains for each input neuron a weight -1, 0 or 1 and also a bias b (b may be any natural number) weights = [] for i in range(len(hidden_layer_sizes)): # Get the number of inputs for the current layer if i == 0: input_count = input_size else: input_count = hidden_layer_sizes[i - 1] # Create a weight matrix (input_count, output_count) and a bias matrix # The weights are random initialized (-1, 0, 1), except for the bias: It is 0 w = np.random.randint(-3, 4, (input_count, hidden_layer_sizes[i])) b = np.zeros((hidden_layer_sizes[i],), dtype=np.int32) weights.append((w, b)) def get_rand_value(p): if p == 0: return 0 r = np.random.uniform() result = 0 if p < 0: if r < (-p): result = -1 else: if r < p: result = 1 return result def get_binary_delta_weights(arr): arr = np.copy(arr) arr = np.minimum(arr, 1) arr = np.maximum(arr, -1) if len(arr.shape) == 1: for i in range(arr.shape[0]): arr[i] = get_rand_value(arr[i]) elif len(arr.shape) == 2: for i in range(arr.shape[0]): for j in range(arr.shape[1]): arr[i, j] = get_rand_value(arr[i, j]) return arr.astype(np.int32) # Train (we train currently record by record) temperature = 0.5 for i in range(100): wrong = 0 w, b = weights[-1] w_d = np.zeros_like(w, dtype=np.float32) b_d = np.zeros_like(b, dtype=np.float32) for i in range(x.shape[0]): x_i = x[i] y_i = y[i] # Do the forward pass curr_v = x_i for j in range(len(hidden_layer_sizes)): (w_j, b_j) = weights[j] curr_v = np.dot(curr_v, w_j) + b_j # Execute the activation: curr_v[curr_v >= 0] = 1 curr_v[curr_v < 0] = 0 curr_y = curr_v # Compare x_i and y_i and backpropagate the error d0 = y_i - curr_y # For each y value that is excat we backpropagate nothing; for each which is too high we try to decrease the input # weights with a probability of temperature and we also try to decrease the bias (by 1) with the same probability. # The abs(bias) is equal to (the number of input neurons + 1). layer_temperature = temperature # Store the probability to increase a value from a previous layer: increase_w_p = np.zeros((hidden_layer_sizes[-1],), dtype=np.float32) increase_b_p = np.zeros(()) if np.sum(np.abs(d0)) > 0: wrong += 1 print("temperature={}".format(temperature)) for j in range(d0.shape[0]): dj = d0[j] # Try to increase the current weights w_d[:, j] += d0[j] * w[:, j] * layer_temperature # Try to increase the current bias b_d[j] += d0[j] * layer_temperature # Backpropagate the error # Create a mask for the input weights # increase_w_p += d0[j] * w[:, j] bdw = get_binary_delta_weights(w_d) w += bdw w = np.minimum(w, 3) w = np.maximum(w, -3) bdb = get_binary_delta_weights(b_d) b += bdb b_max = hidden_layer_sizes[-1] + 1 b = np.minimum(b, b_max) b = np.maximum(b, -b_max) print("sum(bdw)={}, sum(bdb)={}".format(np.sum(np.abs(bdw)), np.sum(np.abs(bdb)))) weights[-1] = (w, b) temperature *= 0.95 if temperature < .5: temperature = .5 print("Error: {}".format(wrong / x.shape[0])) print()
bda693f3f07c052185858531f01c619432908c7a
igorgbr/intro-python-CDD
/curso_python_coisadedev/aula01.py
378
3.53125
4
# Variaveis # Crie um programa que receba pelo menos 3 variaveis # (nome, idade e sobrenome) # Leia essas variaveis e imprima na tela uma frase # mostrando quantos anos o usuario tera daqui 20 anos # "Olá Usuario daqui 20 anos voce ter x anos." nome = 'Carlos' sobrenome = 'Alberto' idade = 45 print(f'Olá {nome} {sobrenome} daqui 20 anos você terá {idade + 20} anos')
dc3e1ef98f938de7f58315adb99b398394fc93ad
niektuytel/Machine_Learning
/Deep_Learning/_deprecated/network/_scratch.py
5,918
3.75
4
# https://github.com/pangolulu/rnn-from-scratch import numpy as np import matplotlib.pyplot as plt import sys, os, keras from network.LSTM import LSTM sys.path.insert(1, os.getcwd() + "/../") import data class Model: def __init__(self, seq_length, seq_step, chars, char2idx, idx2char, n_neurons=100): """ Implementation of simple character-level LSTM using Numpy """ self.seq_length = seq_length # no. of time steps, also size of mini batch self.seq_step = seq_step # no. size of each time step self.vocab_size = len(chars) # no. of unique characters in the training data self.char2idx = char2idx # characters to indices mapping self.idx2char = idx2char # indices to characters mapping self.n_neurons = n_neurons # no. of units in the hidden layer self.unit = LSTM(self.n_neurons, self.vocab_size) self.smooth_loss = -np.log(1.0 / self.vocab_size) * self.seq_length def sample(self, h_prev, c_prev, sample_size): """ Outputs a sample sequence from the model """ x = np.zeros((self.vocab_size, 1)) h = h_prev c = c_prev sample_string = "" for t in range(sample_size): y_hat, _, h, _, c, _, _, _, _ = self.unit.forward(x, h, c) # get a random index within the probability distribution of y_hat(ravel()) idx = np.random.choice(range(self.vocab_size), p=y_hat.ravel()) x = np.zeros((self.vocab_size, 1)) x[idx] = 1 # find the char with the sampled index and concat to the output string char = self.idx2char[idx] sample_string += char return sample_string def forward_backward(self, x_batch, y_batch, h_prev, c_prev): """ Implements the forward and backward propagation for one batch """ x, z = {}, {} f, i, c_bar, c, o = {}, {}, {}, {}, {} y_hat, v, h = {}, {}, {} # Values at t= - 1 h[-1] = h_prev c[-1] = c_prev loss = 0 for t in range(self.seq_length): x[t] = np.zeros((self.vocab_size, 1)) x[t][x_batch[t]] = 1 y_hat[t], v[t], h[t], o[t], c[t], c_bar[t], i[t], f[t], z[t] = self.unit.forward(x[t], h[t - 1], c[t - 1]) loss += -np.log(y_hat[t][y_batch[t], 0]) self.unit.reset_gradients(0) dh_next = np.zeros_like(h[0]) dc_next = np.zeros_like(c[0]) for t in reversed(range(self.seq_length)): dh_next, dc_next = self.unit.backward(y_batch[t], y_hat[t], dh_next, dc_next, c[t - 1], z[t], f[t], i[t], c_bar[t], c[t], o[t], h[t]) return loss, h[self.seq_length - 1], c[self.seq_length - 1] def train(self, X, y, epochs=10, learning_rate=0.01, beta1=0.9, beta2=0.999, verbose=True): """ Main method of the LSTM class where training takes place """ losses = [] # return history losses for epoch in range(epochs): h_prev = np.zeros((self.n_neurons, 1)) c_prev = np.zeros((self.n_neurons, 1)) for i in range(len(X)): x_batch = X[i] y_batch = np.concatenate([ x_batch[1:], [y[i]] ]) # Forward Pass loss, h_prev, c_prev = self.forward_backward(x_batch, y_batch, h_prev, c_prev) # smooth out loss and store in list self.smooth_loss = self.smooth_loss * 0.999 + loss * 0.001 # keep loss history losses.append(self.smooth_loss) # overflowding protection # self.unit.limit_gradients(5) batch_num = epoch * epochs + i / self.seq_length + 1 self.unit.optimization(batch_num, learning_rate, beta1, beta2) # print out loss and sample string if verbose: if i % 100 == 0: prediction = self.sample(h_prev, c_prev, sample_size=250) print("-" * 100) print(f"Epoch:[{epoch}] Loss:{round(self.smooth_loss[0], 2)} Index:[{i}/{len(X)}]") print("-" * 88 + " prediction:") print(prediction + "\n") return losses if __name__ == "__main__": """ Implementation of simple character-level LSTM using Numpy """ # get data x, y = data.vectorization() print(f'data has {len(data.text)} characters, {data.chars} are unique') # define model model = Model(data.seq_length, data.sequences_step, data.chars, data.char2idx, data.idx2char) # train model losses = model.train(x, y) # display history losses plt.plot([i for i in range(len(losses))], losses) plt.xlabel("#training iterations") plt.ylabel("training loss") plt.show() # Print: # ---------------------------------------------------------------------------------------------------- # Epoch:[0] Loss:461.54 Index:[0/14266] # ---------------------------------------------------------------------------------------- prediction: # vEкmS‘0.NJUTбђгyShsјOVTгф.uгTrAs?Cv(aKrXjCvfтN(јaђsowpCyRAT?вuCTrir5E2FђгH~FTSiveSLCN4CfтAycfTI31~gX9”%AzјnypуpбHTв4ELt"tSOу””rNZгf?CZhDqt # ...... # ---------------------------------------------------------------------------------------------------- # Epoch:[4] Loss:279.69 Index:[5700/14266] # ---------------------------------------------------------------------------------------- prediction: # a’no’r no ctu eunst. I tox gsga lrrntt s fy I’s oorsy, tegoe tam o euesools wr’mo ieoicos, bg auo I, slsm osooinnuetr’t guutom o m souuoand htth ii g uy o imoo goty’goo i tavrcamnuet y”ott tig uog uxctiuo sd ouru, taan H tQub teivwel “geeEuorss te “r # but, it is a little to slow :)
eb8330a70b7872267bb928151ee6b5ec969311db
niektuytel/Machine_Learning
/Unsupervised_Learning(UL)/Clustering/Gaussian_Mixture/gaussian_mixture_scratch.py
5,139
3.703125
4
import numpy as np # for the math import pandas as pd # for read csv file import matplotlib.pyplot as plt # for visualizing data import math # for math class GaussianMixture(): """ Parameters: ----------- k: int The number of clusters the algorithm will form. max_iterations: int The number of iterations the algorithm will run for if it does not converge before that. tolerance: float If the difference of the results from one iteration to the next is smaller than this value we will say that the algorithm has converged. """ def __init__(self, n_components=5, max_iterations=2000, tolerance=8):# 1e-8 self.k = n_components self.max_iterations = max_iterations self.tolerance = tolerance self.parameters = [] self.responsibilities = [] self.sample_assignments = None self.responsibility = None def _init_random_gaussians(self, X): """ Initialize gaussian randomly """ n_samples = np.shape(X)[0] self.priors = (1 / self.k) * np.ones(self.k) for i in range(self.k): params = {} params["mean"] = X[np.random.choice(range(n_samples))] params["cov"] = np.cov(X, rowvar=False) self.parameters.append(params) def multivariate_gaussian(self, X, params): """ Likelihood """ n_features = np.shape(X)[1] mean = params["mean"] covar = params["cov"] determinant = np.linalg.det(covar) likelihoods = np.zeros(np.shape(X)[0]) for i, sample in enumerate(X): d = n_features # dimension coeff = (1.0 / (pow((2.0 * math.pi), d / 2) * np.sqrt(determinant))) exponent = np.exp(-0.5 * (sample - mean).T.dot(np.linalg.pinv(covar)).dot((sample - mean))) likelihoods[i] = coeff * exponent return likelihoods def _get_likelihoods(self, X): """ Calculate the likelihood over all samples """ n_samples = np.shape(X)[0] likelihoods = np.zeros((n_samples, self.k)) for i in range(self.k): likelihoods[:, i] = self.multivariate_gaussian(X, self.parameters[i]) return likelihoods def _expectation(self, X): """ Calculate the responsibility """ # Calculate probabilities of X belonging to the different clusters weighted_likelihoods = self._get_likelihoods(X) * self.priors sum_likelihoods = np.expand_dims( np.sum(weighted_likelihoods, axis=1) , axis=1 ) # Determine responsibility as P(X|y)*P(y)/P(X) self.responsibility = weighted_likelihoods / sum_likelihoods # Assign samples to cluster that has largest probability self.sample_assignments = self.responsibility.argmax(axis=1) # Save value for convergence check self.responsibilities.append(np.max(self.responsibility, axis=1)) def _maximization(self, X): """ Update the parameters and priors """ # Iterate through clusters and recalculate mean and covariance for i in range(self.k): resp = np.expand_dims(self.responsibility[:, i], axis=1) mean = (resp * X).sum(axis=0) / resp.sum() covariance = (X - mean).T.dot((X - mean) * resp) / resp.sum() self.parameters[i]["mean"], self.parameters[i]["cov"] = mean, covariance # Update weights n_samples = np.shape(X)[0] self.priors = self.responsibility.sum(axis=0) / n_samples def _converged(self, X): """ Covergence if || likehood - last_likelihood || < tolerance """ if len(self.responsibilities) < 2: return False diff = np.linalg.norm( self.responsibilities[-1] - self.responsibilities[-2]) # print ("Likelihood update: %s (tol: %s)" % (diff, self.tolerance)) return diff <= self.tolerance def fit_predict(self, X): """ Run GMM and return the cluster indices """ # Initialize the gaussians randomly self._init_random_gaussians(X) # Run EM until convergence or for max iterations for _ in range(self.max_iterations): self._expectation(X) # E-step self._maximization(X) # M-step # Check convergence if self._converged(X): break # Make new assignments and return them self._expectation(X) return self.sample_assignments if __name__ == "__main__": # Loading data dataset = pd.read_csv("../../../_EXTRA/data/Mall_Customers.csv") X = dataset.iloc[:, [3, 4]].values # define the model model = GaussianMixture(n_components=5) # assign a cluster to each example yhat = model.fit_predict(X) # retrieve unique clusters clusters = np.unique(yhat) # create scatter plot for samples from each cluster for cluster in clusters: # get row indexes for samples with this cluster row_ix = np.where(yhat == cluster) # create scatter of these samples plt.scatter(X[row_ix, 0], X[row_ix, 1]) # show the plot plt.show()
215e07a4c2197dac235dca63f0b3bdcf5f0e1a32
Ayseguldeniz/python--project
/assignment-primenumbers.py
189
3.65625
4
p = [] n = 100 for i in range(2,n+1): prime = True for j in range(2,i) : if i % j == 0: prime = False if prime: p.append(i) print("Prime list = ", p)
3fbe66368cb280a796554f56110e25a893122f23
shobithkalal/Data_Structures
/Recursion (Linked List) /LinkedList.py
5,288
4.3125
4
""" PROJECT 2 - Linked List Recursion Name: PID: """ class LinkedNode: # DO NOT MODIFY THIS CLASS # __slots__ = 'value', 'next' def __init__(self, value, next=None): """ DO NOT EDIT Initialize a node :param value: value of the node :param next: pointer to the next node in the LinkedList, default is None """ self.value = value # element at the node self.next = next # reference to next node in the LinkedList def __repr__(self): """ DO NOT EDIT String representation of a node :return: string of value """ return str(self.value) __str__ = __repr__ # IMPLEMENT THESE FUNCTIONS - DO NOT MODIFY FUNCTION SIGNATURES # def insert(value, node=None): ''' Inserts a given node of a value to the front of a linked list :param value: value to insert into linked list :param node: node passed into to connect to or create new node :return: head node of list ''' if node is None: return LinkedNode(value) else: node.next = insert(value, node.next) return node def to_string(node): ''' convert linked list to string :param node: linked list to print :return: linked list converted to string ''' try: if node.next is not None: return str(node.value) + ", " + to_string(node.next) else: return str(node.value) except: return "" def remove(value, node): ''' removes a node of a given value :param value: value of node to delete :param node: list passed in :return: returns head node ''' if node is None: return node elif node.value == value: return node.next else: node.next = remove(value, node.next) return node def remove_all(value, node): ''' removes all instances of a value :param value: value to delete :param node: linked list passed in :return: returns head node ''' if node is None: return node if node.value == value: return remove_all(value , node.next) else: node.next = remove_all(value, node.next) return node def search(value, node): ''' sees if a value is in a linked list :param value: value to search for :param node: linked list passed in :return: returns true or false if value is located ''' if node is None: return False elif node.value == value: return True else: return search(value, node.next) def length(node): ''' finds the length of a linked list :param node: head node of a linked list :return: length of the linked list ''' if node is None: return 0 if node.next is None: return 1 else: return 1 + length(node.next) def sum_list(node): ''' sums all values of nodes in a linked list :param node: head of linked list :return: returns sum of all nodes in linked list ''' if node is None: return 0 if node.next is None: return node.value else: return node.value + sum_list(node.next) def count(value, node): ''' counts how many nodes of a value are presents in a linked list :param value: value to look for :param node: head node of linked list :return: returns the num of times a value occurs in a linked list ''' if node is None: return 0 if node.value == value: return 1 + count(value, node.next) else: return count(value, node.next) def reverse(node): ''' reverses order of a linked list :param node: head node of a linked list :return: returns the new head node of reversed linked list ''' if node is None: return node if node.next is None: return node else: nextNode = node.next headNode = reverse(node.next) nextNode.next = node node.next = None return headNode def remove_fake_requests(head): ''' remove all non unique items within a linked list :param head: head of linked list :return: returns linked list of all unique items ''' if head is None or head.next is None: return head if head.value == head.next.value: return remove_fake_requests(remove_all(head.value, head)) else: head.next = remove_fake_requests(head.next) return head #only had this working for first test case, this was the attempt to make O(n) instead of O(n^2) # if head is None: # return head # if head.value == head.next.value: # while head.value == head.next.value: # head.next = head.next.next # head = head.next # return remove_fake_requests(head.next) # else: # head.next = remove_fake_requests(head.next) # return head if __name__ == "__main__": requests = insert(170144) insert(567384, requests) insert(604853, requests) insert(783456, requests) insert(783456, requests) insert(903421, requests) real_requests = remove_fake_requests(requests) for i in [170144, 567384, 604853, 903421]: assert real_requests.value == i real_requests = real_requests.next
d846912ba458d7a7620fdb44776c396d65075450
pkdism/misc-programs
/missing-number.py
250
3.953125
4
def missing_number(array): n = len(array) + 1 total_sum = n * (n + 1) // 2 array_sum = sum(array) missing_value = total_sum - array_sum return missing_value print(missing_number([1, 2, 4])) print(missing_number([1, 2, 3, 4, 6]))
ec7fc736bea025f1ebb21c4d47a4d290925152f8
jmarin4777/algos
/python/uniqueBST.py
850
3.96875
4
# Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? # Example: # Input: 3 # Output: 5 # Explanation: # Given n = 3, there are a total of 5 unique BST's: # 1 3 3 2 1 # \ / / / \ \ # 3 2 1 1 3 2 # / / \ \ # 2 1 2 3 class Solution: def __init__(self): self.mem = {} def numTrees(self, n: int) -> int: if(n == 1 or n == 0): return 1 if(n in self.mem): return self.mem[n] count = 0 for i in range(1,n+1): count += self.numTrees(i-1) * self.numTrees(n-i) self.mem[n] = count return self.mem[n] func = Solution() print(func.numTrees(3)) # -> 5 print(func.numTrees(5)) # -> 42
2303e2f97cbfd56e99aea1ad1b2adcabd3dc0618
Vetrix/obstacle_avoidance
/source/sudoku.py
4,543
4.375
4
#!/usr/bin/env python ''' SELEKSI CALON KRU PROGRAMMING DAGOZILLA 2018 Take Home Test File name: sudoku.py Problem 2: Code Comprehension ''' import sys import numpy as np def read_from_file(filename, board): with open(filename) as f: data = f.readlines() for i in range(9): for j in range(9): if data[i][j] == '-': board[i][j] = int(0) else: board[i][j] = int(data[i][j]) # What does this function do? # This function prints what's in table board[i][j], to the screen. def print_board(board): for i in range(9): for j in range(9): if board[i][j] == 0: print '-', else: print board[i][j], print('') def save_board(filename, board): np.savetxt(filename, board, delimiter=' ', fmt='%i') # What does this function do? # Find int 0 in the board, and returning boolean value def find_empty_location(board, l): for row in range(9): for col in range(9): # What happens inside the 'if' section? # Cheking the board[row][col] is 0, if it is, returns value True if(board[row][col]==0): l[0]=row l[1]=col return True return False # Why does this function return a boolean value? # Because it will be used as a condition in conditional statement def used_in_row(board, row, num): for i in range(9): if(board[row][i] == num): return True return False def used_in_col(board, col, num): for i in range(9): if(board[i][col] == num): return True return False def used_in_block(board, row, col, num): for i in range(3): for j in range(3): if(board[i+row][j+col] == num): return True return False def is_valid(board, row, col, num): return not used_in_row(board, row, num) \ and not used_in_col(board,col,num) \ and not used_in_block(board,row - row%3,col - col%3,num) # What makes this function return True (what makes it valid for a number in a given location)? # It will returns True if the sudoku solved with valid answers # all in a row consist of 1 to 9, all of in a col cons. 1 to 9, and all of in 3x3 box const. of 1 to 9 # Explain the algorithm in this function! # Initialize l as [0,0], then find form empty location, then start filling it with numbers, backtracking until sudoku valid. def solve_sudoku(board): # 'l' is a list that stores rows and cols in find_empty_location Function l=[0,0] # What does this 'if' block check? # check is there any empty location on the board, if it is, then proceed # What will happen if the program enters the following 'if' block? # It will check for int 0, and return if(not find_empty_location(board, l)): # In what way does this True value affect the program? # If theres no empty location, it's finished return True # Assigning list values to row and col that we got from the above Function row=l[0] col=l[1] # What does this block do? # filling empty location with int 1 to 9 for num in range(1,10): if is_valid(board, row, col, num): board[row][col]=num # What does this 'if' section check? # return if the board completed if solve_sudoku(board): return True # Else it fails, undo board[row][col] = 0 # What is this False value for? Will this function always return False? # False mean sudoku have to backtrack return False # Driver main function to test above functions if __name__=="__main__": # What is this 'if' for? # Check the module name,and checking errors # Is there any other way to check and handle error like this without using 'if else'? # Using exceptions # What does the value of len(sys.argv) represent? # Number of command line arguments if len(sys.argv) < 3: print "Error: ..." else: board = [[0 for i in range(9)] for j in range(9)] # What is sys.argv[1]? # List created from command line argument read_from_file(sys.argv[1], board) print "Your board:" print_board(board) print "-----------------" if solve_sudoku(board): print "Solution:" print_board(board) save_board(sys.argv[2], board) else: print "No solution found"
10d9e5f8376e60f0d9cbc4144662e7b03f43a460
drunkinlove/data-structures
/binary-search-tree.py
8,884
4.4375
4
class Node: """ The node class, which we will spawn the tree with. The key principle of binary trees is that, at any given moment, the right child of a node is larger than it, and the left child is always smaller. (This is only true if tree's order relation is a total order. Which it is, because the tree is constructed that way by the program, and not provided in advance by some jerk who just had to screw it up.) If we want to perform an algorithm on the whole tree, we should invoke the method on the root. """ def __init__(self, value): """ Node constructor. Each node instance contains three attributes: link to its left and right children, and its value. """ self.left = None self.right = None self.value = value def insert(self, value): """ Insert a new node with specified value. """ if self.value: if value < self.value: if self.left is None: self.left = Node(value) else: self.left.insert(value) elif value > self.value: if self.right is None: self.right = Node(value) else: self.right.insert(value) else: self.value = value def search(self, value): """ Iterative search in the (sub)tree for the node with specified value, from the self node to the bottom of the tree. """ current_node = self while current_node != None: if value == current_node.value: return current_node elif value < current_node.value: current_node = current_node.left else: current_node = current_node.right return None def childrencount(self, value): """ Returns the number of children of the node with specified value. """ cnt = 0 node = self.search(value) if node.left: # if it exists cnt += 1 if node.right: cnt += 1 return cnt def findmin(self): """ Returns node with smallest value in the (sub)tree. """ current_node = self while current_node.left: #while it exists current_node = current_node.left return current_node def lookforparent(self, value, parent=None): """ Iterative search, with a slightly different output. """ if value < self.value: if self.left is None: return None return self.left.lookforparent(value, self) # We enter the cycle again, but now we have moved one element # down our tree. And there must be a parent now, # so we cyclically set the parent variable to the node that we # just passed by. # Note that if the node we invoke the method on had the same # value as the one we were searching for, the parent=None # attribute would've played its role and we naturally # would have gotten None as the output. elif value > self.value: if self.right is None: return None return self.right.lookforparent(value, self) else: return parent def delete(self, value): """ Delete node in the (sub)tree containing specified value. """ node, parent = self.search(value), self.lookforparent(value) if node is not None: if self.childrencount(node.value) == 0: # if node has no children, just remove it if parent: if parent.left is node: parent.left = None else: parent.right = None del node else: self.value = None elif self.childrencount(node.value) == 1: # if node has 1 child, replace node with its child if node.left: n = node.left else: n = node.right if parent: if parent.left is node: parent.left = n else: parent.right = n del node else: self.left = n.left self.right = n.right self.value = n.value else: # if node has 2 children, replace it with the next bigger node # look to the right first, then pick the leftmost node parent = node successor = node.right while successor.left: parent = successor successor = successor.left # found it. now replace node value with its successor's value node.value = successor.value # fix the old node that we have now moved if parent.left == successor: # if there actually was a node to the left of the one to # the right to the one we're removing... parent.left = successor.right else: # else, if we could not find any nodes to the left of the # one to the right to the one we're removing... # meaning, the child of the node being removed only has # children to the right. # THEN, we replace the removed node with the one to the # right, essentially moving the branch up by an element. parent.right = successor.right def traverse(self): """ Print tree contents in order. Due to the arranged structure of the tree, the algorithm for this is quite simple. """ if self.left: # if there's anything to the left self.left.traverse() print(self.value) if self.right: self.right.traverse() def searchRecursively(self, value): """ Recursive search for the node with specified value. """ if self is None or self.value == value: # if there is no (sub)tree, or we have found the node, stop this madness return self if value < self.value: return self.left.searchRecursively(value) else: return self.right.searchRecursively(value) def __str__(self): """ A private method for printing info about a node. """ if self.childrencount(self.value) == 0: return("A node with value %s." % str(self.value)) if self.left != None and self.right != None: return("A node with value %s. Its left child is a node with value" " %s, and the right child is a node with value %s." % (str(self.value), str(self.left.value), str(self.right.value))) elif self.left == None: return("A node with value %s. Its right child is a node with" " value %s." % (str(self.value), str(self.right.value))) else: return("A node with value %s. Its left child is a node with value" " %s." % (str(self.value), str(self.left.value))) root = Node(int(input("First, let's create the tree. Enter the root:\n"))) root.insert(int(input("Another one:\n"))) root.insert(int(input("One more:\n"))) root.insert(int(input("Final one:\n"))) print("\nThis is what our binary tree currently contains:") root.traverse() print("\nNow, let's look up info about an element.") inf = int(input("Enter a value that corresponds to a node: \n")) print(root.search(inf)) print("\nIts parent is: \n" + str(root.lookforparent(inf))) todelete = root.search(int(input("Now, let's delete a node. Input the " "corresponding value:\n"))) print("\nBye-bye, " + str(todelete.value) + "!\n") children = root.childrencount(todelete.value) root.delete(todelete.value) if children != 0: print("Its place was taken by one of its children.") else: print("It's gone for good!") input("\nNow press Enter to see what's left.\n") print("These are the elements left in the tree:") root.traverse() input() input("Whew.\n") print("Alright, that's enough playing with binary trees. Please" " return to your daily duties. Thank you for attention!")
3c1219e7c7c57db39fc61e7551c9e3e8808fadb7
league-python-student/level1-module2-ezgi-b
/_01_writing_classes/_b_intro_to_writing_classes.py
2,725
4.3125
4
""" Introduction to writing classes """ import unittest # TODO Create a class called student with the member variables and # methods used in the test class below to make all the tests pass class Student: def __init__(self, name, grade): self.name = name self.grade = grade self.homework_done = False def do_homework(self): self.homework_done = True def go_to_school(self, start = "7 am"): return self.name + " is leaving for school at " + start # ================== DO NOT MODIFY THE CODE BELOW ============================ class WriteClassesTests(unittest.TestCase): student_1 = Student(name='Zeeshan', grade=7) student_2 = Student(name='Amelia', grade=8) student_3 = Student(name='Penelope', grade=9) def test_student_objects_created(self): self.assertIsNotNone(WriteClassesTests.student_1, msg='student 1 not created!') self.assertIsNotNone(WriteClassesTests.student_2, msg='student 2 not created!') self.assertIsNotNone(WriteClassesTests.student_3, msg='student 3 not created!') def test_names(self): self.assertTrue(WriteClassesTests.student_1.name == 'Zeeshan') self.assertTrue(WriteClassesTests.student_2.name == 'Amelia') self.assertTrue(WriteClassesTests.student_3.name == 'Penelope') def test_grades(self): self.assertTrue(WriteClassesTests.student_1.grade == 7) self.assertTrue(WriteClassesTests.student_2.grade == 8) self.assertTrue(WriteClassesTests.student_3.grade == 9) def test_student_methods(self): self.assertEquals(False, WriteClassesTests.student_1.homework_done) self.assertEquals(False, WriteClassesTests.student_2.homework_done) self.assertEquals(False, WriteClassesTests.student_3.homework_done) WriteClassesTests.student_1.do_homework() WriteClassesTests.student_2.do_homework() WriteClassesTests.student_3.do_homework() self.assertEquals(True, WriteClassesTests.student_1.homework_done) self.assertEquals(True, WriteClassesTests.student_2.homework_done) self.assertEquals(True, WriteClassesTests.student_3.homework_done) def test_going_to_school(self): leave_str = WriteClassesTests.student_1.go_to_school(start='6 am') self.assertEqual('Zeeshan is leaving for school at 6 am', leave_str) leave_str = WriteClassesTests.student_2.go_to_school(start='6:30 am') self.assertEqual('Amelia is leaving for school at 6:30 am', leave_str) leave_str = WriteClassesTests.student_3.go_to_school() self.assertEqual('Penelope is leaving for school at 7 am', leave_str) if __name__ == '__main__': unittest.main()
86d62162df8024d7a2fe9891eb9dcb719a6744c6
kudiXPR/6_password_strength
/password_strength.py
2,392
3.546875
4
import string import os def check_pass_is_date_or_digits(password): return not set(password).difference(set(string.digits), set(string.punctuation)) def check_pass_is_letters(password): return not set(password).difference(set(string.ascii_letters)) def check_pass_is_punctuation(password): return not set(password).difference(set(string.punctuation)) def check_pass_in_blacklist(password, path_to_blacklist): with open(path_to_blacklist) as blacklist: for passw in blacklist: if password == passw.rstrip(): return True return False def check_pass_contains_lower_and_upper_case(password): lowercase_letters = set(string.ascii_lowercase) uppercase_letters = set(string.ascii_uppercase) return bool(set(password).intersection(lowercase_letters)) and bool(set(password).intersection(uppercase_letters)) def check_pass_contains_punctuation(password): return bool(set(password).intersection(string.punctuation)) def check_pass_contains_digits(password): return bool(set(password).intersection(string.digits)) def get_password_strength(password, path_to_blacklist): strength = 1 if check_pass_is_date_or_digits(password): return strength if check_pass_is_letters(password): return strength if check_pass_is_punctuation(password): return strength if check_pass_in_blacklist(password, path_to_blacklist): return strength if len(password) < 8: return strength if len(password) >= 8: strength += 1 if len(password) >= 14: strength += 1 if len(password) >= 20: strength += 1 if check_pass_contains_lower_and_upper_case(password): strength += 2 if check_pass_contains_punctuation(password): strength += 2 if check_pass_contains_digits(password): strength += 2 return strength if __name__ == '__main__': path_to_blacklist = '10_million_password_list_top_1000000.txt' if not os.path.exists(path_to_blacklist): os.system('wget https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/10_million_password_list_top_1000000.txt') while True: password = input('Enter the password: ') if not password: break print('Password strength: {}'.format(str(get_password_strength(password, path_to_blacklist))))
e392968fe946f5627af9e3caa28c7a3bed3c0ae6
0t3b2017/CursoemVideo1
/desafio #019.py
451
4.03125
4
""" desafio #019 Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo o nome deles e escrevendo o nome do escolhido """ from random import choice n1=str(input("Primeiro aluno: ")) n2=str(input("Segundo aluno: ")) n3=str(input("Terceiro aluno: ")) n4=str(input("Quarto aluno: ")) alunos=[n1,n2,n3,n4] nome=choice(alunos) print("O aluno escolhido para apagar o quadro é: {}.".format(nome))
10b98f23aed7717f9648ea95aa78e7ab2790cb52
0t3b2017/CursoemVideo1
/aula06b.py
477
4.3125
4
""" Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis sobre ele. """ x=input("Digite algo: ") print("O tipo do valor é {}".format(type(x))) print("O valor digitado é decimal? ",x.isdecimal()) print("O valor digitado é alfanum? ",x.isalnum()) print("O valor digitado é alfa? ",x.isalpha()) print("O valor digitado é printable? ",x.isprintable()) print("O valor digitado é maiuculo? ",x.isupper())
4bfba7c91923794a62b17e796ea043d8f8afa543
0t3b2017/CursoemVideo1
/desafio #037.py
2,039
4.125
4
""" desafio #037 Escreva um programa que leia um número inteiro (em decimal) e peça para o usuário escolher qual será a base de conversão: 1 para binário 2 para octal 3 para hexadecimal """ """ num = int(input("Digite um número: ")) opc = int(input(\"""Selecione uma das base de conversão desejada: 1 => binário 2 => octal 3 => hexadecimal digite: \""")) if opc == 1: base = 2 rest = [] divisor = num while divisor >= 1: rest.append(divisor % base) divisor = divisor // base rest.reverse() print("\nO valor {} em binário é ".format(num), *rest, sep='') elif opc == 2: base = 8 rest = [] divisor = num while divisor >= 1: rest.append(divisor % base) divisor = divisor // base rest.reverse() print("\nO valor {} em binário é ".format(num), *rest, sep='') elif opc == 3: base = 16 rest = [] divisor = num while divisor >= 1: rest.append(divisor % base) divisor = divisor // base rest.reverse() print("\nO valor {} em binário é ".format(num), *rest, sep='') else: print("\n\033[31mOpção inválida\033[m") """ ## Guanabara num = int(input("Digite um número inteiro: ")) while True: print('''Escolha uma das bases para conversão: [ 1 ] converter para BINÁRIO [ 2 ] converter para OCTAL [ 3 ] converter para HEXADECIMAL''') opcao = int(input('\nSua opção: ')) print('') if opcao == 1: print('{} convertido para binário é igual a \033[34m{}\033[m'.format(num, bin(num)[2:])) break elif opcao == 2: print('{} convertido para octal é igual a \033[34m{}\033[m'.format(num, oct(num)[2:])) break elif opcao == 3: print('{} convertido para hexadecimal é igual a \033[34m{}\033[m'.format(num, hex(num)[2:])) break else: print('\033[31mOpção inválida. Favor selecionar uma das opções disponíveis.\033[m\n')
35f07132ed792e76da0ca01799f2679206571ad7
0t3b2017/CursoemVideo1
/desafio #012.py
355
3.734375
4
""" desafio #012 Faça um algoritmo que leia o preço de um produto e mostre seu novo preço com 5% de desconto. """ preco=float(input("Qual o preço original? R$ ")) desc=float(input("Qual o desconto a ser aplicado em porcentagem? ")) new_preco=(preco - ((preco * desc) / 100)) print("O valor com desconto de {}% é R$ {:.2f}".format(desc, new_preco))
d219c316c3a67a940a8d0c369a2cdec1cb882d36
0t3b2017/CursoemVideo1
/desafio #041.py
749
4.09375
4
""" desafio #041 A confederação nacional de natação precisa de um programa que leia o ano de nascimento de um atleta e mostre sua categoria, de acordo com a idade: - Até 9 anos: Mirim - Até 14 anos: Infantil - Até 19 anos: Junior - Até 25 anos: Senior - Acima: Master """ from datetime import date ano_nasc = int(input("Digite o seu ano de nascimento com 4 dígitos: ")) ano_atual = date.today().year idade = ano_atual - ano_nasc print("O atleta tem {} anos.".format(idade)) if idade <= 9: print("Sua categoria é Mirim") elif idade <= 14: print("Sua categoria é Infantil") elif idade <= 19: print("Sua categoria é Junior") elif idade <= 25: print("Sua categoria é Senior") else: print("Sua categoria é Master")
1866eaa566cf7da42fad880204300044ed994fa4
0t3b2017/CursoemVideo1
/desafio #022.py
1,004
4.375
4
""" Crie um programa que leia o nome completo de uma pessoa e mostre: - O nome com todas as letras maiúsculas - O nome com todas as letras minusculas - Quantas letras ao todo (sem considerar espaços) - Quantas letras tem o primeiro nome. """ name = str(input("Type your name: ")).strip() print("Seu nome em letras maiúsculas é {}.".format(name.upper())) print("Seu nome em letras minúsculas é {}.".format(name.lower())) # print(name.strip()) # print(name.capitalize()) # print(name.title()) # Minha ideia print("Seu nome ao todo tem {} letras.".format(len(''.join(name.split())))) # Guanabara ideia print("Seu nome ao todo tem {} letras.".format(len(name) - name.count(' '))) # Minha ideia # Split the name in a list and then verify the lenght of the first name. print("Seu primeiro nome tem {} letras.".format(len(name.split()[0]))) # Guanabara ideia # Find de first space position. As the index starts with 0, the count matches. print("Seu primeiro nome tem {} letras.".format(name.find(' ')))
30cd643809fbb92f2842d5cc1bc5f2b3206dd494
LydiaZhou/LeetCode
/P1-300/P2.py
1,617
3.875
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addNumberCarry(self, l: ListNode, carry: int) -> ListNode: result = ListNode(-1) ptr = result while l != None: ptr.next = ListNode((carry + l.val)%10) carry = (carry + l.val) // 10 ptr = ptr.next l = l.next if carry != 0: ptr.next = ListNode(carry) return result def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: carry = 0 start = 1 while l1 != None and l2 != None: if start == 1: pointer = ListNode((l1.val + l2.val)%10) result = pointer start = 0 else: pointer.next = ListNode((l1.val + l2.val + carry)%10) pointer = pointer.next carry = (l1.val + l2.val + carry)//10 l1 = l1.next l2 = l2.next ## One of the linked list end remaining = ListNode(-1) if l1 != None: remaining = self.addNumberCarry(l1, carry) elif l2 != None: remaining = self.addNumberCarry(l2, carry) elif carry != 0: remaining.next = ListNode(carry) pointer.next = remaining.next return result def main(self): a = ListNode(3) a.next = ListNode(7) b = ListNode(9) b.next = ListNode(2) print(self.addTwoNumbers(a, b)) if __name__ == '__main__': a = Solution() a.main()
3b29d593b0f91621cd38e616b833f1c4a5ec7b46
LydiaZhou/LeetCode
/P601-/P981.py
1,320
3.6875
4
import collections class TimeMap(object): def __init__(self): """ Initialize your data structure here. """ self.dict = collections.defaultdict(list) def set(self, key, value, timestamp): """ :type key: str :type value: str :type timestamp: int :rtype: None """ self.dict[key].append((timestamp, value)) def get(self, key, timestamp): """ :type key: str :type timestamp: int :rtype: str """ if key not in self.dict: return "" list = self.dict[key] left = 0 right = len(list) if list[0][0] > timestamp: return "" elif list[right - 1][0] <= timestamp: return list[right - 1][1] # binary search while left < right - 1: mid = left + right // 2 if list[mid][0] > timestamp: right = mid else: left = mid return list[left][1] # Your TimeMap object will be instantiated and called as such: if __name__ == '__main__': kv = TimeMap() kv.set("foo", "bar", 1) print(kv.get("foo", 1)) print(kv.get("foo", 3)) kv.set("foo", "bar2", 4) print(kv.get("foo", 4)) print(kv.get("foo", 5))
f8224e641379496e2a79e71426bb23a09f3ef3dd
LydiaZhou/LeetCode
/P301-P600/P314.py
2,771
3.875
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def verticalOrder(self, root): if not root: return [] newDict = {} curPos = 0 queue = [(root, curPos)] # dfs while queue: (root, curPos) = queue.pop(0) if curPos in newDict: newDict[curPos].append(root.val) else: newDict[curPos] = [root.val] if root.left: queue.append((root.left, curPos - 1)) if root.right: queue.append((root.right, curPos + 1)) return [newDict[i] for i in sorted(newDict)] # def verticalOrder(self, root): # """ # :type root: TreeNode # :rtype: List[List[int]] # """ # return self.helper(root)[0] # # def helper(self, root): # if not root: # return ([], -1) # (leftList, leftIndex) = self.helper(root.left) # (rightList, rightIndex) = self.helper(root.right) # rightStart = leftIndex + 1 - rightIndex + 1 # # conbime two lists # if leftIndex != -1: # newArray = leftList.copy() # if leftIndex + 1 < len(newArray): # newArray[leftIndex + 1].insert(0, root.val) # else: # newArray.append([root.val]) # for i in range(len(rightList)): # if i + rightStart < len(newArray) and i + rightStart > 0: # newArray[i + rightStart] += rightList[i] # else: # newArray.append(rightList[i]) # else: # newArray = rightList.copy() # if rightIndex - 1 < len(newArray) and rightIndex - 1 > 0: # newArray[rightIndex - 1].insert(0, root.val) # elif rightIndex - 1 < 0: # newArray.insert(0, [root.val]) # else: # newArray.append([root.val]) # return (newArray, leftIndex + 1) if __name__ == '__main__': obj = Solution() root = TreeNode(3) root.left = TreeNode(9) root.right = TreeNode(8) root.right.left = TreeNode(1) root.right.right = TreeNode(7) root.left.left = TreeNode(4) root.left.right = TreeNode(0) root.left.right.right = TreeNode(2) root.right.left.left = TreeNode(5) print(obj.verticalOrder(root)) root2 = TreeNode(1) root2.right = TreeNode(6) root2.right.left = TreeNode(5) root2.right.left.left = TreeNode(3) root2.right.left.left.left = TreeNode(2) root2.right.left.left.right = TreeNode(4) # print(obj.verticalOrder(root2))
d2463ea58310ac43303cc67962199cf0c693cca0
LydiaZhou/LeetCode
/P1-300/P5.py
1,230
3.6875
4
class Solution(object): def __init__(self): self.data = None def longestPalindrome(self, s): """ :type s: str :rtype: str """ self.data = s palindrome = "" for i in range(len(s)): # Even situation currentVal = self.helper(s, i, i) if len(currentVal) > len(palindrome): palindrome = currentVal # Odd situation currentVal = self.helper(s, i, i+1) if len(currentVal) > len(palindrome): palindrome = currentVal return palindrome def helper1(self, left, right): if left < 0: return self.s[0:right] if right >= len(self.s): return self.s[left+1:] if self.s[left] == self.s[right]: left -= 1 right += 1 return self.helper(self.s, left, right) else: return self.s[left+1:right] def helper(self, s, left, right): while left>=0 and right<len(s) and s[left] == s[right]: left -=1 right +=1 return s[left+1:right] if __name__ == '__main__': obj = Solution() print(obj.longestPalindrome("cbbd"))
f3a8be529229afb1dc8aae55029cc6c62186acc9
LydiaZhou/LeetCode
/P1-300/P62.py
573
3.671875
4
class Solution(object): def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ if m == 1 or n == 1: return 1 if n > m: return self.fractorial(n, m + n - 1) // self.fractorial(1, m) else: return self.fractorial(m, m + n - 1) // self.fractorial(1, n) def fractorial(self, m, n): res = 1 for i in range(m, n): res *= i return res if __name__ == '__main__': obj = Solution() print(obj.uniquePaths(7, 3))
fc1bb8f29a9dc8a85f6e88784a66e432149866da
LydiaZhou/LeetCode
/P1-300/P21.py
929
3.96875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ new = ListNode(-1) ptr = new while l1 and l2: if l1.val <= l2.val: ptr.next = l1 l1 = l1.next else: ptr.next = l2 l2 = l2.next ptr = ptr.next if l1: ptr.next = l1 if l2: ptr.next = l2 return new.next if __name__ == '__main__': l1 = ListNode(1) l1.next = ListNode(2) l1.next.next = ListNode(4) l2 = ListNode(1) l2.next = ListNode(3) l2.next.next = ListNode(4) obj = Solution() a = obj.mergeTwoLists(l1, l2) print("hello")
e83f86e15aecd6eb0009ea838026ebb57c85d06a
wesleyramos/Chatbot
/PatternMatching/main1.py
470
4.0625
4
""" In this example only content starting with hi or hello or hey with 0 or more spaces and letters will be matched """ import re r = "(hi|hello|hey)[ ]*([a-z]*)" print(re.match(r, 'Hello Rosa', flags=re.IGNORECASE)) print(re.match(r, "ho ho, hi ho, it's off to work ...", flags=re.IGNORECASE)) print(re.match(r, "hey, what's up", flags=re.IGNORECASE)) r = ".*(hi|hello|hey)[ ]*([a-z]*)" print(re.match(r, "ho ho, hi ho, it's off to work ...", flags=re.IGNORECASE))
3fac10e5c9ccf3814be608c7e6fe35db55759d6f
willian-pessoa/My-codes-in-CS-learning-journey
/Intro CS/Mit 6.0001/ps1b.py
944
3.9375
4
# -*- coding: utf-8 -*- """ Created on Sat Aug 21 19:17:51 2021 @author: willi """ portion_down_payment = 0.25 current_saving = 0.0 r = 0.04 annual_salary = float(input("Enter your annual salary:")) portion_saved = float(input("Enter the percent of your salary to save, as a decimal:")) total_cost = float(input("Enter the cost of your dream home:")) semi_annual_raise = float(input("Enter the semi-­annual raise, as a decimal:")) monthly_salary = annual_salary / 12 # increase the saving to count the months months = 1 while current_saving < total_cost * portion_down_payment: # update salary if months % 6 == 0: annual_salary += annual_salary * semi_annual_raise monthly_salary = annual_salary / 12 current_saving += monthly_salary * portion_saved current_saving += current_saving * r / 12 # return months += 1 print("Number of months:", months )
098749d838c1a502871f3e98afb6c69de278cb0d
rtaguma01/Python_Exercises
/list.py
393
4.0625
4
#Practice List list = ["apple", "banana", "pear", "orange", "strawberry"] length = len(list) print length print ("\n") list.append("grapes") print list list.insert(2,"cantaloupe") print list list.remove("orange") print list list2 = ["peas", "carrots", "lettuce", "beets"] list.extend(list2) print list del list[2] print list print sorted(list) print list
65dd73e46b023df5c03a32f0a7b10459e8b076c7
rtaguma01/Python_Exercises
/range.py
218
3.796875
4
#Practice Range a = range(1, 10) for i in a: print i print ("\n") for b in range(0,28, 2): print b print ("\n") for c in range (40, 0, -4): print c print ("\n") for d in range(20): print d
45d5f2d08f9b31aee0ae71aead411e1d3f9e6fdd
NihalAnand/Python6B
/wm.py
477
3.578125
4
def weighted_mean(values: list, weights: list) -> float: sum_weighted_values = 0 sum_weights = 0 for i in range(len(values)): for j in range(len(weights)): value = values[i] weight = weights[i] sum_weighted_values += value * weight sum_weights += weight result = sum_weighted_values / sum_weights return result n=int(input()) x=list(map(int,input().strip().split())) w=list(map(int,input().strip().split())) print(round(weighted_mean(x,w),1))
ee2be7243780a0c8c35d7d680a7e98b6ad011a4f
JacobMason83/my_atm
/my_machine.py
20,594
3.734375
4
import tkinter as tk # importing tkinter as the gui for the app from tkinter import font as tkfont #importing all the tkinter functionality from tkinter import * account_balance = 1000 class My_Atm(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title_font = tkfont.Font(family='Comic Sans Serif', size=18, weight="bold") self.shared_data = {'Balance':tk.IntVar()} # the container is where we'll stack a bunch of frames # on top of each other, then the one we want visible # will be raised above the others container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) # This is the page loop for all the pages in the project self.frames = {} for F in (Start_Page, Menu_Page, Withdraw_Page, Deposit_Page, Balance_Page): page_name = F.__name__ frame = F(parent=container, controller=self) self.frames[page_name] = frame # put all of the pages in the same location; # the one on the top of the stacking order # will be the one that is visible. frame.grid(row=0, column=0, sticky="nsew") self.show_frame("Start_Page") def show_frame(self, page_name): #this function shows a page name for the given page, and brings it up frame = self.frames[page_name] frame.tkraise() class Start_Page(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent,bg="#5203fc") self.controller = controller self.controller.title('Mason Family Bank') self.controller.state('zoomed') heading_label1 = tk.Label(self, text='Mason Family Bank ATM', font=('Comic Sans Serif', 50, 'bold'), fg='white', bg='#5203fc') heading_label1.pack() space_in_between = tk.Label(self, height=4, bg='#5203fc') space_in_between.pack() sign_in_label = tk.Label(self, text='Enter Your Password', font=('Comic Sans Serif', 15, 'bold'), fg='white', bg='#5203fc') sign_in_label.pack() my_password = tk.IntVar() password_entry_box = tk.Entry(self, text="Enter Your Pin", textvariable=my_password, font=('sans serif',13), width=24) password_entry_box.pack(ipady=8) def password_check(): if my_password.get() == 123: my_password.set('') controller.show_frame('Menu_Page') else: incorrect_password_label["text"]= 'Incorrect Password' space_between_input_box = tk.Label(self, height=4, bg='#5203fc') space_between_input_box.pack check_the_password_button = tk.Button(self, text='Enter', command=password_check, relief='raised', borderwidth=10, width=15, height=2) check_the_password_button.pack() incorrect_password_label = tk.Label(self, text="", font=('Comic Sans Serif', 12), fg='white', bg='#5203fc', relief='groove', borderwidth=4, height=4, anchor='n') # adding the anchor n which means north so that when the user clicks the enter # #button if incorrect is true it will run this incorrect_password_label.pack(fill='both', expand=True) #trying to create a background image on the pages # cool_image = tk.PhotoImage(file='icons\images\cool_image.jpg') # background_img_label= Label(parent, image=cool_image) # background_img_label.place() bottom_frame = tk.Frame(self,relief='raised',borderwidth=3) bottom_frame.pack(fill='x',side='bottom') # self.background_img_label = background_img_label #starting of the menu page which is created on the tkinter frame setup above class Menu_Page(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent, bg='#5203fc') self.controller = controller # label = tk.Label(self, text="Mason Family Bank", font=controller.title_font) # label.pack(side="top", fill="x", pady=10) #setting the heading labels for the menu page heading_label1 = tk.Label(self, text='Mason Family Banks ATM', font=('Comic Sans Serif', 50, 'bold'), fg='white', bg='#5203fc') heading_label1.pack() # making the main menu text main_menu_label = tk.Label(self, text='Main Menu', font=('Comic Sans Serif', 20), fg='white', bg='#5203fc') main_menu_label.pack() #adding this make a selection to make it seem more interactive with the user make_a_selection = tk.Label(self, text="What can we help you with today?", font=('Comic Sans Serif', 13, 'bold'), fg='white', bg='#5203fc') make_a_selection.pack(pady=25, fill='x') button_frame = tk.Frame(self,bg='#4c4d4b') button_frame.pack(fill='both',expand=True) #adding the function for tkinter to click to the withdraw window on clik def withdraw(): controller.show_frame('Withdraw_Page') withdraw_button = tk.Button(button_frame, text='Withdraw', command=withdraw, relief='raised', borderwidth=10, width=25, height=3) withdraw_button.grid(column=0, columnspan=2, row=0, padx=5, pady=5) #adding the function for tkinter to click to the deposit window on clik def deposit(): controller.show_frame('Deposit_Page') # this button is taking in the frame i made above and using it as a grid to make the button and # is placing it in the grid at column 0 row 2 with a column span of 2 deposit_button = tk.Button(button_frame, text='Deposit', command=deposit, relief='raised', borderwidth=10, width=25, height=3) deposit_button.grid(column=0,columnspan=2,row=2, padx=5, pady=5) #adding the function for tkinter to click to the balance window on clik def balance(): controller.show_frame('Balance_Page') balance_button = tk.Button(button_frame, text='Balance', command=balance, relief='raised', borderwidth=10, width=25, height=3) balance_button.grid(column=0,columnspan=2,row=4) #giving the exit button on the menu page access to the start page so that it will go there on click def exit(): controller.show_frame('Start_Page') exit_button = tk.Button(button_frame, text='Exit', command=exit, relief='raised', borderwidth=10, width=25, height=3) exit_button.grid(column=0,columnspan=2,row=6,) bottom_frame = tk.Frame(self,relief='raised',borderwidth=3) bottom_frame.pack(fill='x',side='bottom') #making the withdraw page class so that when the button is clicked # it goes to the withdraw page class Withdraw_Page(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent, bg='#5203fc') self.controller = controller #adding the standard heading to the page heading_label1 = tk.Label(self, text='Mason Family Bank ATM', font=('Comic Sans Serif', 50, 'bold'), fg='white', bg='#5203fc') heading_label1.pack() # need to ask how much they want to withdraw amount_to_take_label = tk.Label(self, text='How much do you want to withdraw today?', font=('Comic Sans Serif', 15, 'bold'), fg='white', bg='#5203fc') amount_to_take_label.pack(side='top', padx=20, pady=20) #putting in the frame for the withdraw page, so that the buttons are easier to grid button_frame = tk.Frame(self,bg='#4c4d4b') button_frame.pack(fill='both',expand=True) #adding a balance label to the top global account_balance #bringing in the global variable so it can be updated, and user can see # this is allowing the data to be shared across the pages controller.shared_data['Balance'].set(account_balance) #adding a label to be put on the page to be able to be seen when withdrawing balance_label = tk.Label(self, textvariable= controller.shared_data['Balance'], font=('Comic Sans Serif', 50), fg='white', bg='#5203fc', anchor='w') balance_label.pack(fill='x') #making the function for the withdraw method def withdraw(amount): global account_balance #setting the global balance so that it can be updated account_balance -= amount controller.shared_data['Balance'].set(account_balance) # adding the button grid of 20 40 60 80 100 other twenty_button = tk.Button(button_frame, text='$20', command=lambda: withdraw(20), relief='raised', borderwidth=10, width=25, height=3) twenty_button.grid(row=0, column=0, columnspan=2) #40 button fourty_button = tk.Button(button_frame, text='$40', command=lambda: withdraw(40), relief='raised', borderwidth=10, width=25, height=3) fourty_button.grid(row=1, column=0, columnspan=4) #60 button sixty_button = tk.Button(button_frame, text='$60', command=lambda: withdraw(60), relief='raised', borderwidth=10, width=25, height=3) sixty_button.grid(row=2, column=0, columnspan=2) #80 button eighty_button = tk.Button(button_frame, text='$80', command=lambda: withdraw(80), relief='raised', borderwidth=10, width=25, height=3) eighty_button.grid(row=3, column=0, columnspan=2) #100 button one_hundred_button = tk.Button(button_frame, text='$100', command=lambda: withdraw(100), relief='raised', borderwidth=10, width=25, height=3) one_hundred_button.grid(row=4, column=0, columnspan=2) # making the back to menu button # other_button = tk.Button(button_frame, # text='other', # command=lambda:withdraw(input('Please enter the amount you want to withdraw')), # relief='raised', # borderwidth=10, # width=25, # height=3) # other_button.grid(row=5, column=0, columnspan=2) #adding a go back button to the page def go_back(): controller.show_frame('Menu_Page') # adding the button to go back to menu page back_to_menu_button = tk.Button(self, text='Back to Menu', command=lambda: go_back(), fg='white', bg='#5203fc') back_to_menu_button.pack() bottom_frame = tk.Frame(self,relief='raised',borderwidth=3) bottom_frame.pack(fill='x',side='bottom') #making the deposit page class so that when the button is clicked # it goes to the deposit page class Deposit_Page(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent, bg='#5203fc') self.controller = controller #adding the heading label to the deposit page heading_label1 = tk.Label(self, text='Mason Family Bank ATM', font=('Comic Sans Serif', 50, 'bold'), fg='white', bg='#5203fc') heading_label1.pack() #need to add a label to ask how much you want to deposit need_to_deposit_label = tk.Label(self, text='How much would you like to deposit?', font=('Comic Sans Serif', 15, 'bold'), fg='white', bg='#5203fc') need_to_deposit_label.pack(padx=20, pady=20) #need to add the button frame so that it looks like the other pages #adding the balance to the page to be seen when depositing global account_balance #bringing in the global variable so it can be updated, and user can see # this is allowing the data to be shared across the pages controller.shared_data['Balance'].set(account_balance) balance_label = tk.Label(self, textvariable=controller.shared_data['Balance'], font=('Comic Sans Serif', 50), fg='white', bg='#5203fc', anchor='w') balance_label.pack(fill='x') #adding the function for depositing to the bank cash = tk.StringVar() deposit_entry = tk.Entry(self, textvariable=cash, font=('Comic Sans Serif', 13), width=25) deposit_entry.pack(ipady=5) def deposit_cash(cash): global account_balance account_balance += int(cash.get()) controller.shared_data['Balance'].set(account_balance) cash.set('') controller.show_frame('MenuPage') deposit_enter_button = tk.Button(self, text="Enter Your Deposit", command=lambda: deposit_cash(cash), relief='raised', borderwidth=10, width=15, height=3) deposit_enter_button.pack(ipadx=5, ipady=5) #adding a seperation bar to help with the look # adding a back to menu button on the page def go_back(): controller.show_frame('Menu_Page') back_to_menu_button = tk.Button(self, text='Back to Menu', command=lambda: go_back(), fg='white', bg='#5203fc') back_to_menu_button.pack() two_tone_label = tk.Label(self,bg='#4c4d4b') two_tone_label.pack(fill='both',expand=True) #bottom frame of the page to help with seperation bottom_frame = tk.Frame(self,relief='raised',borderwidth=3) bottom_frame.pack(fill='x',side='bottom') #making the balance page, so that when the balance button is clicked it goes to the balance page class Balance_Page(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent, bg='#5203fc') self.controller = controller #adding the heading label to the page heading_label1 = tk.Label(self, text='Mason Family Bank ATM', font=('Comic Sans Serif', 50, 'bold'), fg='white', bg='#5203fc') heading_label1.pack() #adding the balance function, button and page details global account_balance #bringing in the global variable so it can be updated, and user can see # this is allowing the data to be shared across the pages controller.shared_data['Balance'].set(account_balance) over_balance_label = tk.Label(self, text='Balance', fg='white',bg='#5203fc',font=('Comic Sans Serif', 30,'bold'),anchor='w') over_balance_label.pack() balance_label = tk.Label(self, textvariable=controller.shared_data['Balance'], font=('Comic Sans Serif', 50), fg='white', bg='#5203fc' ) balance_label.pack(fill='x', side='top') # the function to allow me to go back to the menu page def go_back(): controller.show_frame('Menu_Page') # bottom frame styles button_frame = tk.Frame(self, bg='darkblue') button_frame.pack(fill='both',expand=True) back_to_menu_button = tk.Button(button_frame, text='Back to Menu', command=lambda: go_back(), fg='white', bg='#5203fc') back_to_menu_button.pack() if __name__ == "__main__": app = My_Atm() app.mainloop()
4cb649d8a71138ca487b0e6a7eda8edfe1245a83
jmnunezd/NaiveBayes
/nb.py
4,417
4.09375
4
import numpy as np import operator def suit(book): """ suit cleans the 'words' that are found in a book, this helps to count every single word just once. e.g. 'kiss,' and 'kiss' content actually the same word, so we remove the ',' and makes everything simple. :param book: it's the book we want to clean. :return: a list that contains every valid word that appears on the book. Notice that in here words may be repeated. """ text = open(f'books/{book}', 'r') text = text.read().lower() words = text.split() words = [words[i].replace('.', '').replace(',', '').replace('.', '').replace('"', '').replace("'", '') .replace('?', '').replace(';', '').replace(':', '').replace('-', '').replace('!', '') .replace('…', '').replace('“', '').replace('”', '').replace('—', '').replace('(', '') .replace(')', '').replace('/', '').replace('–', '').replace('’', '').replace('‘', '') .replace('*', '').replace('%', '').replace('#', '').replace('=', '').replace('+', '') .replace('1', '').replace('2', '').replace('3', '').replace('4', '').replace('5', '') .replace('6', '').replace('7', '').replace('8', '').replace('9', '').replace('0', '') for i in range(len(words))] return words def frequencies(book): """ For a given book, this function clean the words in the book using the suit function and returns a dictionary, that contains every word that appear on the book as a key and it's frequencies of occurrence as a value. :param book: it's the book we want to know it's words frequencies. :return: a dict that contains every word and it's count. """ words = suit(book) book_dict = {} for word in words: if word in book_dict.keys(): pass else: book_dict[word] = words.count(word) return book_dict def train(*books): """ this function saves the dict of frequencies of every book input, this will be useful when we wan't to test a future book that is not in the list. This creates a sort of a model. :param books: a list of book's names that we want our model to be feed of. :return: a dictionary that may become handy when using a test function. """ train_dict = {} for book in books: bock_dict = frequencies(book) total_words = sum(bock_dict.values()) train_dict[book] = [bock_dict, total_words] return train_dict def test(trained_dict, book_to_predict, n_sample): """ given a model, a book we want to predict it's author and a sample size number we obtain the most probable author comparing the frequencies of the words in the model and in a sample of words of the current book. :param trained_dict: a model, it's the output of the train function. :param book_to_predict: the name of the book we want to predict the author. :param n_sample: an integer. :return: a print that shows what is the most likely author of the book_to_predict. """ f = frequencies(book_to_predict) sample = np.random.choice(list(f.keys()), n_sample) print('the sample of words taken from', book_to_predict, 'is: ') print(sample) print() max_words_in_book = 1 for key in trained_dict.keys(): max_words_in_book = max(trained_dict[key][1], max_words_in_book) posteriori = {} for key in trained_dict.keys(): book_dict = trained_dict[key][0] total_words = trained_dict[key][1] prob = [] for word in sample: if word in book_dict: fi = book_dict[word] / total_words prob.append(fi) else: prob.append(1 / max_words_in_book) posteriori[key] = np.prod(prob) add = sum(posteriori.values()) for key in posteriori.keys(): posteriori[key] = posteriori[key] / (add + 0.00000001) max_prob_element = max(posteriori.items(), key=operator.itemgetter(1))[0] print('the author of ', book_to_predict, 'is more likely to be the author of', max_prob_element) print() print(posteriori) print() if __name__ == '__main__': model = train(*['hp1.txt', 'cn1.txt', 'lr1.txt']) test(model, 'hp2.txt', 10) test(model, 'cn2.txt', 10) test(model, 'lr2.txt', 10) test(model, 'cb.txt', 10)
1c2e9a4f7d93dfcce5b74087ed6e6cbd51337f27
Highstaker/Dropbox-Photo-Uploader
/tests/thread_with_lock_test001.py
836
3.6875
4
#!/usr/bin/python3 -u # -*- coding: utf-8 -*- import threading from time import sleep class A(object): """docstring for A""" def __init__(self): super(A, self).__init__() self.mutex = threading.Lock() def func(self,a,Sleep=False): print(a + " called func()") with self.mutex: print(a + " entered mutex") if Sleep: print("="*20) sleep(3) print(a + " finished") class B(object): """docstring for B""" def __init__(self): super(B, self).__init__() self.insA = A() t = threading.Thread(target=self.test_thread) t.start() t = threading.Thread(target=self.test_thread) t.start() self.insA.func("main",Sleep=True) t = threading.Thread(target=self.test_thread) t.start() def test_thread(self): self.insA.func("thread",Sleep=True) def main(): b = B() if __name__ == '__main__': main()
aee5132cf7fdd9e2c4bfbacdf5362de64c50882e
ivanulb/luracoin-python
/luracoin/helpers.py
1,351
3.796875
4
import binascii import hashlib from typing import Union def sha256d(s: Union[str, bytes]) -> str: """A double SHA-256 hash.""" if not isinstance(s, bytes): s = s.encode() return hashlib.sha256(hashlib.sha256(s).digest()).hexdigest() def little_endian(num_bytes: int, data: int) -> str: return data.to_bytes(num_bytes, byteorder="little", signed=False).hex() def little_endian_to_int(little_endian_bytes: str) -> int: return int.from_bytes( binascii.unhexlify(little_endian_bytes), byteorder="little" ) def var_int(num: int) -> str: """ A VarInt (variable integer) is a field used in serialized data to indicate the number of upcoming fields, or the length of an upcoming field. """ if num <= 252: result = little_endian(num_bytes=1, data=num) elif num <= 65535: result = "fd" + little_endian(num_bytes=2, data=num) elif num <= 4_294_967_295: result = "fe" + little_endian(num_bytes=4, data=num) else: result = "ff" + little_endian(num_bytes=8, data=num) return result def var_int_to_bytes(two_first_bytes: str) -> int: if two_first_bytes == "ff": return 8 elif two_first_bytes == "fe": return 4 elif two_first_bytes == "fd": return 2 return 1 def mining_reward() -> int: return 50
b5cf2fc7f42367eb826ba6e59021f5465b040bcd
sorokotyaha/TicTacToe_simulation_using_binary_trees
/game_tree.py
4,366
4.03125
4
from board import Board from linked_binary_tree import LinkedBinaryTree import random class GameSimulator: """ This class represents a tic tac toe game simulator, where computer plays with 0 and the player plays with X """ MAXSTEPS = 9 WON = 0 LAST_PLAYER = None def __init__(self): """ Constructing GameSimulator""" self._board = Board(3, 3) self._mycell = 0 def getUserStep(self): """ This method gets the coordinates of the next step for player :return: list(int, int) """ print("Type the row number and the column number of your next step:") line = input() return list(map(int, line.strip().split())) def board(self): """ Returns the current state of a board :return: Board """ return self._board def set_board(self, board): """ Sets self._board to board :param board: Board """ self._board = board @staticmethod def generate_step(board): """ Generates a random step out of free. If there is no free cells, returns None :return: tuple """ free = board.get_free_cells() if not free: return None step = random.choice(free) return step @staticmethod def make_step(board, row, col, value): """ Sets the cell at row and col to a value :param row: int :param col: int :param value: int """ if value == 0: board.set_zero_cell(row, col) else: board.set_cross_cell(row, col) GameSimulator.LAST_PLAYER = value def get_numVictories(self): """ Returns the number of victories for the game simulation :return: float """ return GameSimulator.WON / 2 def clear_victories(self): """ Sets number of victories to 0 """ GameSimulator.WON = 0 def fill_board(self, board_node, tree): """ This method takes a tree of boards and a node to work with. If the node contains a board with a winning combination of 0 or the board is full, returns tree. If there is still space left, generates two new steps out of available for the next player. Then creates two new Board objects and configures them with the new set of cross and zero cells. Then adds as children to board_node. :param board_node: LinkedBinaryTree :param tree: LinkedBinaryTree :return: LinkedBinaryTree """ board = board_node.key cross = board.get_cross_cells() zeros = board.get_zero_cells() # check if board is full or 0 won if board.check_for_win_combos(): GameSimulator.WON += 1 return tree elif len(cross) + len(zeros) == GameSimulator.MAXSTEPS: return tree # if it's Cross turn elif len(cross) == len(zeros): GameSimulator.LAST_PLAYER = Board.CROSS_CELL # if it's Zeros turn else: GameSimulator.LAST_PLAYER = Board.ZERO_CELL fill_cell = GameSimulator.LAST_PLAYER # add child left step1 = self.generate_step(board) new_board1 = Board(3, 3) new_board1 = new_board1.configure(cross, Board.CROSS_CELL).configure( zeros, Board.ZERO_CELL) self.make_step(new_board1, step1[0], step1[1], fill_cell) board_node.insert_left(new_board1) # add child right step2 = self.generate_step(new_board1) # if there was only 1 cell left for next step if not step2: step2 = step1 new_board2 = Board(3, 3) new_board2.configure(cross, Board.CROSS_CELL) new_board2.configure(zeros, Board.ZERO_CELL) self.make_step(new_board2, step2[0], step2[1], fill_cell) board_node.insert_right(new_board2) return self.fill_board(board_node.get_right_child(), tree), self.fill_board( board_node.get_left_child(), tree)
36a04e409a3ea79e336b56ca7989aaa91c55f9b3
Mohamed-Taha-Essa/AI_algorithms_by_python
/algorithms_ai/BFS.py
1,114
3.828125
4
#!/usr/bin/env python # coding: utf-8 # In[8]: #creating by "Mohamed Abdallah " from queue import Queue adj_list = {"A" :["B" , "D"] , "B" : ["C" ,"A"], "C" :["B" ] , "D" : ["B","F" ,"A"], "E" : ["D","F" ,"G"], "F" :["D","E" ,"H" ] , "G" : ["E","H" ], "H" : ["F" ,"G"] } # In[40]: visited = {} level = {} #dic distanse parent = {} bfs_traversal_output = [] queue = Queue() for node in adj_list.keys() : visited[node] =False level[node] = None parent[node] = -1 print(visited) print(level) print(parent) start ="A" visited[start] = True level[start] = 0 queue.put(start) while not queue.empty(): templet = queue.get() bfs_traversal_output.append(templet) for value in adj_list[templet]: if not visited[value]: visited[value] = True parent[value] = templet level[value] = level[templet]+1 queue.put(value) print(visited) print(level) print(parent) print(bfs_traversal_output) # In[ ]: # In[ ]:
0da29fef733652c8a03c4aabecb1fef8374ee1dd
HUSSAMFAEZALTARAJI/Python
/open function.py
556
3.71875
4
# def name(first_name, Last_name): # return f"Hi {first_name} {Last_name} welcom with us in our lesson" # print(name(str(input("Enter your first name :")),str(input("Enter your Last name :")))) # message=name(str(input("Enter your first name :")),str(input("Enter your Last name :"))) # file = open('C:/Users/hussa/OneDrive/Desktop/New Text Document (2).txt', 'w') # file.write(message) # f = open(r'C:/Users/hussa/OneDrive/Desktop/youtube chanel/New Text Document (4).txt','r') # if f.mode == 'r': # hh = f.read() # print(hh)
8deeb1d4276520dbea5b0014bce480d58ec45861
Prabhjyot2/workshop-python
/L2/P4.py
131
3.5
4
#wapp to convert fare to degree n = float(input("Enter ")) r = (n - 32) * 5 / 9 print("%.2f \u0046 --> %.2f \u0043" %(n , r))
6a793cfc990f511cce72216830fd7c443e9e04c6
Prabhjyot2/workshop-python
/L4/p5.py
683
3.640625
4
# wamdpp for queue implementation import array queue = array.array('i',[]) while True: op = int(input("1.insert, 2.remove, 3.peek, 4.display and 5.exit ")) if op == 1: ele = int(input("enter the element to insert ")) queue.append(ele) print(ele, "is inserted in queue ") elif op == 2: if len(queue) == 0: print("queue is empty ") else: ele = queue.pop(0) print("removed element is", ele) elif op == 3: if len(queue) == 0: print("queue is empty ") else: ele = queue[0] print("peeked element ", ele) elif op == 4: if len(queue) == 0: print("queue is empty ") else: print(queue) elif op == 5: break else: print("invalid option")
f742a6010866badbb9f77203c6f6b4e69cd6c56f
Prabhjyot2/workshop-python
/L3/p4.py
196
3.765625
4
# wapp to generate num = int(input("enter the number ")) if num < 0: print("b +ve") else: n = 0 for i in range(1 , num+1): for j in range(1, i+1): print(n, end="") n = n + 1 print()
3d18f0eb26f85178c2f3c6b6f009e6f00b94c3af
Prabhjyot2/workshop-python
/L9/p5.py
149
4
4
# wapp to o/p yess if user enters integer else else o/p no try: num = int(input("enter an integers")) print("yes") execpt ValueError: print("no")
cf3c05d28b1c3fbdb58d966e308f6b0a1d0a64df
Prabhjyot2/workshop-python
/L2/p8.py
254
3.84375
4
#wapp to read marks & find the grades mark = int(input("enter the marks ")) if (mark>=70): g="dist." elif(mark>=60): g="FIRST CLASS" elif(mark>=50): g="SECOND CLASS" elif(mark>=40): g="PASS" else: g="fail" print("marks =", mark,"GRADES = ",g)
d2181a4d79b5f40ce98e852f429bc7881cda34aa
Prabhjyot2/workshop-python
/L5/p6.py
288
3.953125
4
''' wapp tp read a sentence and sort every word of sentence i/p Kamal sir rocks o/p aaklm irs ckors''' def mysort(s): ls = sorted(s) ns = ''.join(ls) return ns s1= input("enter a string ") l1= s1.split(" ") ns1 =" " for m in l1: m = mysort(m) ns1 = ns1 + " " + m print("", ns1)
e897af19e5fdf1f6ab3568b14ae124c5971a2a57
Prabhjyot2/workshop-python
/L2/P2.py
235
4.40625
4
#wapp to read radius of circle & find the area & circumference r = float(input("Enter the radius ")) pi = 3.14 area = pi * r** 2 print("area=%.2f" %area) cir = 2 * pi * r print("cir=%.4f" %cir) print("area=", area, "cir=", cir )
b794e6fa42a47d23f44792945a330e57b2f45412
Prabhjyot2/workshop-python
/L2/p7.py
223
4
4
# wapp to read year & find if its a leap year year = int(input("Enter the year")) b1 = (year%100 == 0) and (year%400 == 0) b2 = (year%100 != 0) and (year%4 == 0) if b1 or b2: print("yessssssss") else: print("naaaaaaa")
63896d5b332d30ed57338c3277fd9dc4cfaf8bfb
prabhugs/scripts
/duplicate.py
297
3.75
4
a = [1,1,2,2,2,3,4,5] c=[] d=[] for entry in a: if entry not in c: c.append(entry) d.append(entry) print "----" print c print d print "----" pass if entry in c and entry in d: print d d.remove(entry) print c print d
51dc7d36233782cfb7481e5a29b6061d99983669
alexcarlos06/CEV_Python
/Mundo 2/Desafio 036.py
2,886
3.921875
4
# Escreva um programa para aprovar o empréstimo bancário para comprar uma casa. # O programa vai perguntar o valor da casa, o salário do comprador e em quantos anos ele vai pagar. # Calcule o valor da prestação mensal sabendo que ele nao pode exceder 30% do salário ou então o empréstimo será negado. # Importando o método sleep dentro da bibliotéca time e o método randint dentro da bibliotéca random from time import sleep from random import randint # Montando a paleta de cores cores = {'azul' : '\033[1;34m', 'amarelo' : '\033[1;33m', 'preto' : '\033[7;30m', 'vermelho' : '\033[1;31m', 'verde' : '\033[1;32m', 'limpa' : '\033[m', 'negrito' : '\033[1m'} # Mensagem inicial do Programa print('{}xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.format(cores['amarelo'])) print('{} *Aprovador de Emprestimo Imobiliário*'.format(cores['azul'])) print('{}xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx{}{}' .format(cores['amarelo'] , cores['limpa'] , cores['negrito'])) # Colhendo os inputs valor = float(input('Informe qual valor do imóvel a ser financiado: R$ ')) período = float(input('Informe em quantos anos o comprador deseja pagar: ')) salário = float(input('Informe o salário atual do comprador: R$ ')) # Definindo variáveis para facilitar a elaboração das condições e possíveis manutenções nas condições. percentual = 30 / 100 # Está variável é reponsável pela porcentagem aceita para emprestimo limite = salário*percentual # O limite é a quantidade maxíma em reais que o usuário pode fazer a parcela respeitando o percentual estabelecido na variável percentual. parcela = período * 12 # O período é a quantiade de anos que usuário deseja pagar o emprestimo. prestação = valor / parcela print('\n{}Sua solicitação está sendo processada em nosso banco de dados.\n\nAguarde alguns segundos................{}'.format(cores['azul'] , cores['negrito'])) sleep(3) # Montando a condição para informar se o emprestimo sera permitido ou não if prestação > limite: print('{}Você está sem margem para realizar o emprestimo. \nSolicite um valor mais baixo ou aumente o número de parcelas.{}'.format(cores['vermelho'] , cores['negrito'])) else: print('{}Parabéns, o seu emprestimo foi aceito,' '\nSão {: .0f} parcelas de R${: .2f} .' '\nEntre em contato com os nossos corretores e informe o número de acesso "{}"{}'.format(cores['verde'] , parcela , prestação ,randint(10000,99999) , cores['negrito'])) print('\nObrigado por utilizar o nosso sistema de financiamento imobiliário.') #Desafio Concluído
44f9c71e161a2fddd66975520ca4b0444be0fefa
alexcarlos06/CEV_Python
/Mundo 2/Desafio 069.py
2,095
4.15625
4
'''Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, o programa deverá perguntar se o usuário quer ou nao continuar. No final, mostre: a) Quantas pessoas tem mais de 18 anos. b) Qantos homens foram cadastrados. c)Quantas mulheres tem mais de 20 anos .''' print('\n{:^100}\n'.format(' \033[1;4mCadastro de Pessoas \033[m')) c = '' maior = homens = mulheres = 0 while c != 'N': print('{}\n'.format('-' * 100)) s = str(input('Informe o sexo [M / F]: ')).upper().strip()[0] while s not in 'F,M': s = str(input('Informe "M" para Masculino e "F" para Feminino: ')).upper().strip()[0] i = int(input('Informe a idade: ')) while i not in range(1, 1000): i = int(input('Informe a idade entre 1 e 999: ')) if i > 18: maior += 1 if s == 'M': homens +=1 if s == 'F' and i > 20: mulheres += 1 c = str(input('Deseja cadastrar mais [S / N]: ')).upper().strip()[0] while c not in 'S,N': c = str(input('Deseja cadastrar mais [S / N]: ')).upper().strip()[0] if c == 'N': print('~' * 100, '\033[1;32m') break if maior == 0: print('\nNão foi Cadastrado nenhuma pessoa com idade superior a 18 anos.') elif maior == 1: print('\nFoi cadastrada uma pessoa com idade superior a 18 anos.') else: print(f'\nforam cadastradas {maior} pesoas com idade superior a 18 anos.') if homens == 0: print('Não foi cadastrado nenhuma pessoa do sexo masculino.') elif homens == 1: print('Foi cadastro uma pessoa do sexo masculo.') else: print(f'Foram cadastradas {homens} pessoas do sexo masculino.') if mulheres == 0: print('Não foi cadastrada nenhuma pessoa do sexo femino com idade superior a 20 anos.') elif mulheres == 1: print('Foi cadastrada uma pessoa do sexo feminino com idade superior a 20.') else: print(f'Foram cadastradas {mulheres} pessoas com sexo feminino e idade superior a 20 anos.') print('\n\n\n\033[m{:=^110}'.format(' \033[1;4mObrigado por utilizar o sistema de cadastro ACSistemas\033[m ')) # Desafio Concluído.
ab830dfe0aa7c1006ddc12c332194fe546dc8724
alexcarlos06/CEV_Python
/Mundo 1/Desafio 013.py
352
3.890625
4
#Faça um algoritimo que leia o salário de um funcionário e mostre seu novo salario com almento de 15% # Fazendo a leitura do salario atual s = float(input('Iinforme o salário atual: ')) #Informando na tela o valor obtido através da soma do salario atual mais 15% print('O novo salário será {} reais '.format(s+(s*0.15))) # Desafio concluído
c748ec48187e940398cda28db426de3c0ce6c219
alexcarlos06/CEV_Python
/Mundo 1/Desafio 011.py
1,085
3.9375
4
#Faça um programa que leia a largura e a altura de uma parede em metros e cacule sua área e a quantidade de tinta necessária para pinta-la. sabendo que cada litro de tinta pinta uma área de 2m² # Lendo o rendimento da embalagem de tinta a ser comprada rend = int(input('Informe o rendimento da embalagem de tinta: ')) # Lendo o valor do preço de uma embalagem de tinta rs = float(input('Informe quanto custa a tinta desejada ')) # Lendo as medidas da parede h = int(input('Informe a altura da parede ')) b = int(input('informe a largura da parede ')) # Calculando a área da parede a = b*h # Definindo variáveis para mostrar a necessidade e o preço gasto para pitar a parede neces = a/rend vl = neces*rs # Mostrando na tela os valores , desta vez para maior entendimento do código foram criadas as variáveis fora do método .format, desta forma fica mais facíl o entendimento do código. print('O tamanho da parede é {} m²\nPara pintar toda a parede serão necessários {:.2f} latas de tinta e o valor pago será {} reais. '.format(a,neces, vl)) #Desafio concluído
337341d300ebe5397368e6ca19dcf2ae8c895d3e
alexcarlos06/CEV_Python
/Mundo 2/Desafio 071.py
2,201
4.15625
4
'''Crie um programa que simule o funcionamento de um caixa eletônico. No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues. OBS: Considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1''' print('\n{}{:^^100}{}\n'.format('\033[1;4;34m', '\033[1;31m Caixa Eletrônico ACSistemas \033[1;4;34m', '\033[m')) import os saque = int(input('Informe o valor do saque: ')) print('') c = 100 valor = saque cont = 0 while True: if valor >= c: while valor >= c: valor -= c cont += 1 total = cont * c print(f'Serão {cont} notas de R${c:.2f} ==> O total das notas de {c} será R${total: .2f} \n') if valor >= 50: c = 50 cont = 0 while valor >= c: valor -= c cont += 1 total = cont * c print(f'Serão {cont} notas de R${c:.2f} ==> O total das notas de {c} será R${total: .2f} \n') elif valor >= 20: c = 20 cont = 0 while valor >= c: valor -= c cont += 1 total = cont * c print(f'Serão {cont} notas de R${c:.2f} ==> O total das notas de {c} será R${total: .2f}\n') elif valor >= 10: c = 10 cont = 0 while valor >= c: valor -= c cont += 1 total = cont * c print(f'Serão {cont} notas de R${c:.2f} ==> O total das notas de {c} será R${total: .2f}\n') elif valor >= 1: c = 1 cont = 0 while valor >= c: valor -= c cont += 1 total = cont * c print(f'Serão {cont} notas de R${c:.2f} ==> O total das notas de {c} será R${total: .2f}\n') else: print('-' * 85) print('') if saque == 0: break else: saque = int(input('Informe um novo valor do saque ou 0 para sair: ')) print('') c = 100 valor = saque cont = 0 print('\033[1;33m{:~^100}'.format(' \033[1;4;34mObrigado por utilizar o nosso sistema de Caixa eletrônico\033[1;33m ')) # Desafio Concluído
2bd2b887faf5433b01e8f743c54186d801442691
alexcarlos06/CEV_Python
/Mundo 2/Desafio 058.py
2,752
4
4
'''Melhore o jogo do desafio 028 onde o computador vai "pensar" em um número entre 0 e 10. só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer. ''' from random import randint ''' Paleta de cores''' cores = {'azul' : '\033[34m', 'amarelo' : '\033[33m', 'vermelho' : '\033[31m', 'limpa' : '\033[m', 'roxo' : '\033[35m', 'verde' : '\033[32m', 'nverde' : '\033[1;32m', 'namarelo' : '\033[1;33m', 'nvermelho' : '\033[1;31m', 'negativo' : '\033[7;30m'} print('{}{:=^50}{}'.format(cores['amarelo'],' Jogo da Adivinhação ', cores['limpa'])) print('''{} Vou pensar em um número inteiro entre 1 e 10, Será que vc consegue adivinhar???? Boa sorte!!!!!{} {}{}{}'''.format(cores['roxo'], cores['limpa'], cores['amarelo'], '*' * 50,cores['limpa'])) ncomp = randint(1, 10) palpite = 0 contagem = 0 while palpite != ncomp: if contagem == 0: palpite = int(input('' '\nQual seu palpite? ')) contagem += 1 print('') else: palpite = int(input('{}Errou...' '\n' '\n{}Qual seu novo palpite? '.format(cores['vermelho'], cores['limpa']))) contagem += 1 print('') if contagem == 1: print('{0}Parabéns!!!!' '\n{1}Você acerou de primeira. ' '\n{0}A SORTE ESTA AO SEU LADO....{2}'.format(cores['nverde'], cores['verde'], cores['limpa'])) elif contagem <=3: print('{}Você acertou!!!' '\n{}Foram necessárias {}{}{} tentátias.' '\n{}Seu nível de sorte está em {}%'.format( cores['verde'], cores['limpa'],cores['verde'], contagem, cores['limpa'], cores['nverde'], (10 - contagem) * 10)) elif contagem <=5: print('{}Você acertou!!!' '\n{}Foram necessárias {}{}{} tentativas.' '\n{}ATENÇÃO seu nivel de sorte está em {}%'.format(cores['verde'], cores['limpa'], cores['verde'], contagem, cores['limpa'], cores['namarelo'], (10 - contagem) * 10)) elif contagem <=9: print('{0}Você acertou!!!' '\n{1}Foram necessárias {0}{2}{1} tentativas.' '\n{3}CUIDADO seu nível de sorte está em {4}%'.format(cores['verde'], cores['limpa'], contagem, cores['namarelo'], (10 - contagem) * 10)) else: print('{0}Eram apenas 10 possibilidades e você acertou em {2} {1}' '\n{0} Você entendeu o jogo?? {1}' '\n{0} Tente novamente.... {1}'.format(cores['negativo'], cores['limpa'],contagem)) # Desafio Concluído.
7adc48dd7da8cea5d02cbdc83ea6524f924fc037
alexcarlos06/CEV_Python
/Mundo 1/desafio 008.py
341
4.21875
4
#Escreva um programa que leia um valor em metros e o exiba convertido em centimentros e milimetros m=int(input('Informe a quantidade de metros que desja converter: ')) mm=int(1000) cm=int(100) mmconverte=m*mm cmconverte=m*cm print(' Em {} metros existem {} centimetros e {} milimetros.'.format(m, cmconverte, mmconverte)) #Desafio concluído
7366faebfd176414ff1bf491adaefe7030557187
alexcarlos06/CEV_Python
/Mundo 2/Desafio 038.py
577
3.9375
4
#Escreva um programa que leia dois números inteiros e compare-os, mostrando na tela uma mensagem: #O primeiro valor é maior, O segundo valor é menor , Não existe valor maior, os dois são iguais. # Fazendo a leitura de dois números n1 = float(input('Digite o primeiro valor: ')) n2 = float(input('Digite o segundo valor: ')) print('') # Montando a estrutura de condição if n1 == n2: print('Não existe valor maior, pois os dois são iguais.') elif n1 > n2: print('O primeiro valor o maior. ') else: print('O segundo valor é o maior. ') #Desafio Concluído
02fc4d0883508b8ed4ef03cc15856e5308538050
alexcarlos06/CEV_Python
/Mundo 2/Desafio 070.py
1,743
4.09375
4
'''Crie um programa que leia o nome e o peço de vários produtos. O programa deverá perguntar se o usuário vai continuar. No final, mostre: a) Qual é o total gasto na compra. b) Quantos produtos custam mais de R$ 1000. c) Qual é o nome do produto mais barato. ''' print('\n\033[1;32m{:~^100}\033[m'.format(' \033[1;4;33mRegistrador de Compras\033[1;32m ')) total = valor = acima = menor = contador = 0 produto = barato = '' while True: print('\n{}'.format('~' * 84)) produto = str(input('\nInforme o nome do produto: ')).strip() valor = float(input('Informe o preço do produto: ')) print('') print('~' * 84) valida = str(input('Deseja continuar [S / N]: ')).upper().strip() total += valor contador += 1 if valor > 1000: acima += 1 if contador <= 1: menor = valor barato = produto elif menor > valor: menor = valor barato = produto while valida not in 'SN': valida = str(input('Deseja continuar "S" para SIM ou "N" NÃO: ')).upper().strip() if valida == 'N': print('~' * 84) print('') break print('\033[1;32m{:=^97}\033[1m\n'.format(' \033[1;4mResumo das compras \033[1;32m')) print(f'O total das compras foi R${total: .2f} .') if acima == 0: print('Você não comprou nenhum produto acima de R$1000,00 .') elif acima == 1: print('Você comprou um produto acima de R$1000,00 .') else: print(f'Você comprou {acima} produtos com valor acima de R$ 1000,00 .') print(f'O produto mais barato comprado foi {barato} que custou R${menor: .2f} .') print('\n\033[1;32m{:~^100}'.format('\033[1;4;33m Obrigado por utilizar o Gerenciador de Compras ACSistemas\033[1;32m ')) # Desafio Concluído
1d8edc6e0ad9f240115c16793e369cf63b73cefb
alexcarlos06/CEV_Python
/Mundo 1/Desafio 032.py
846
3.96875
4
#Faça um programa que leia um ano qualquer e mostre se ele é BISSEXTO. # Mensagem inicial do programa print('xxxxxX Verificador de Ano Bissexto Xxxxxx') print('========'*10) #Colhendo a informação do ano consultado ano = int(input('Informe qual ano deseja verificar: ')) #Montando a condição, se o resto da divisão por 400 do ano for 0 então o ano é bissexto, se o resto da divisão por 100 for 0 então ano não é bissexto por fim se o resto da divisão #por 4 for igual a zero então o ano sera um ano bissexto . if ano % 400 == 0: print('O ano {} é um ano bissexto.'.format(ano)) elif ano % 100 == 0: print('O ano {} não é um ano bissexto.'.format(ano)) elif ano % 4 == 0: print('O ano {} é um ano bissexto.'.format(ano)) else: print('O ano {} não é um ano bissexto.'.format(ano)) # Desafio concluído
d4888e3a514d852c58b30b04a38a3066a12fb6ab
alexcarlos06/CEV_Python
/Mundo 2/Desafio 042.py
2,293
4
4
#Refaça o desafio 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado. #Equilátero: todos os lados iguais ; Isóceles: dois lados iguais ; Escaleno: todos os lados diferentes. #Se os 3 seguimentos de retas formarem o triângulo o programa precisa responder qual o tipo de triangulo montado. # montando a paleta de cores cores = {'azul' : '\033[1;34m', 'amarelo' : '\033[1;33m', 'verde' : '\033[1;32m', 'vermelho' : '\033[1;31m', 'limpa' : '\033[1;m'} # Mensagem ínicial do programa print('{1}{0} Validador de possibilidade e Conferência do tipo do Triângulo {0}{2}'.format('*' * 20, cores['azul'],cores['limpa'] )) print('') a = int(input('Informe o primeiro seguimento de reta: ')) b = int(input('Informe o segundo seguimento de reta: ')) c = int(input('Informe o terceiro seguimento de reta: ')) print('') print('{}{}{}'.format(cores['azul'], '*' *80, cores['limpa'])) print( '{}Triângulo Isósceles. Tem dois lados iguais e um diferente. ' '\nTriângulo Equilátero. Todos os lados são iguais.' '\nTriângulo Escaleno. Nenhum dos lados é igual.{}'.format(cores['amarelo'], cores['limpa'])) print('{}{}{}'.format(cores['azul'], '*' * 80, cores['limpa'])) print('') # Montando a estrura de condição para validar se é possível montar um triangulo retângulo e qual o tipo de triângulo montado if abs(c - b) < a < (c + b) and abs(a - c) < b < (a + c) and abs(a - b) < c < (a + b): if a == b == c: print('{0}É possível montar um Triângulo do {2}tipo Equilátero{0} com os seguimentos de reta que foram informados{1}'.format(cores['verde'], cores['limpa'], cores['vermelho'])) elif a == b or b == c or a == c: print('{0}É possível montar um Triângulo do {2}tipo Isóceles{0} com os seguimentos de reta que foram informados{1}'.format(cores['verde'],cores['limpa'], cores['vermelho'])) else: print('{0}É possível montar um Triângulo do {2}tipo Escaleno{0} com os seguimentos de reta que foram informados{1}'.format(cores['verde'], cores['limpa'], cores['vermelho'])) else: print('{}Não é possível montar um Triângulo com os seguimentos de reta apresentados{}'.format(cores['vermelho'],cores['limpa'])) # Desafio Concluído
532793eb6901f35e2184ab5b510aea233c5a484b
Sher-Chowdhury/CentOS7-Python
/files/python_by_examples/loops/iterations/p02_generator.py
845
4.34375
4
# functions can return multiple values by using the: # return var1,var2....etc # syntax. # you can also do a similar thing using the 'yield' keyword. fruits = ['apple', 'oranges', 'banana', 'plum'] fruits_iterator = iter(fruits) # we now use the 'next' builtin function # https://docs.python.org/3.3/library/functions.html # a genarotor is simply a functions that contains one or more 'yield' lines. def fruits(): print("about to print apple") yield 'apple' print("about to print oranges") yield 'oranges' print("about to print banana") yield 'banana' print("about to print plum") yield 'plum' fruit = fruits() print(type(fruit)) print(next(fruit)) print(next(fruit)) print(next(fruit)) print(next(fruit)) # the yield command effectively pauses the function until the next 'next' command is executed.
51ef16e584f74ddbfa5d23412847e88fd8f4cf27
rodrigocms/python
/Scripting_ErrorsAndExceptions.py
509
3.609375
4
#Errors And Exceptions #Syntax errors occur when Python can’t interpret our code, since we didn’t follow the correct syntax # for Python. These are errors you’re likely to get when you make a typo, or you’re first starting # to learn Python. # Exceptions occur when unexpected things happen during execution of a program, even if the code is # syntactically correct. There are different types of built-in exceptions in Python, and you can see # which exception is thrown in the error message.
8ee8bfee53f3b666a3cddd35bb85ddae2c52e6b8
tntterri615/Pdx-Code-Guild
/Python/lab10unitconverter.py
587
4.125
4
''' convert feet to meters ''' x = int(input('What distance do you want to convert?')) y = input('What are the input units?') z = input('What are the output units?') if y == 'ft': output = x * 0.3048 elif y == 'km': output = x * 1000 elif y == 'mi': output = x * 1609.34 elif y == 'yd': output = x * 0.9144 elif y == 'in': output = x * 0.0254 if z == 'ft': output /= 0.3048 elif z == 'km': output /= 1000 elif z == 'mi': output /= 1609.34 elif z == 'yd': output /= 0.9144 elif z == 'in': output /= 0.0254 print(f'{x} {y} is {output} {z}')
f1497ee3c556984b0c9034b07687c2353046edb5
tntterri615/Pdx-Code-Guild
/Python/lab31atm.py
1,398
4.125
4
''' atm lab ''' class Atm: transaction_list = [] def __init__(self, balance = 0, interest_rate = 0.1): self.balance = balance self.interest_rate = interest_rate def check_balance(self): return self.balance def deposit(self, amount): self.balance += amount self.transaction_list.append(f'You deposited ${amount}') return self.balance def check_withdrawl(self, amount): return (self.balance - amount) > 0 def withdraw(self, amount): self.balance -= amount self.transaction_list.append(f'You withdrew ${amount}') return self.balance def calc_interest(self, interest): self.balance *= interest return self.balance def print_transactions(self): for i in self.transaction_list: print(i) account = Atm(0, 0) while True: command = input('What would you like to do (deposit, withdraw, check balance, history)? ').strip() if command == 'deposit': deposit_amount = input('Enter amount to deposit: ') account.deposit(int(deposit_amount)) elif command == 'withdraw': withdraw_amount = input('Enter amount to withdraw: ') account.withdraw(int(withdraw_amount)) elif command == 'check balance': print(account.check_balance()) elif command == 'history': account.print_transactions()
59802ababfc3db1657ac9227b618e583df6aac14
tntterri615/Pdx-Code-Guild
/Python/lab25countwords.py
2,382
3.75
4
# unicode count words punctuation = ";,.?!'\"-()*:[]$#" other_punctuation = '":;#*()[]\'/$#,-\n' word_count = {} # Version 1 # with open('leviathan.txt', 'r') as f: # contents = f.read() # contents = contents.lower() # for char in punctuation: # contents = contents.replace(char, "") # contents = contents.split() # # for word in contents: # for key in dict # if word not in word_count: # word_count[word] = 1 # else: # word_count[word] += 1 # # print(word_count) # # words = list(word_count.items()) # list of tuples # words.sort(key=lambda tup: tup[1], reverse=True) # sort largest to smallest, based on count # for i in range(min(10, len(words))): # print the top 10 words, or all of them, whichever is smaller # print(words[i]) # Version 2 with open('leviathan.txt', 'r') as f: contents = f.read() contents = contents.replace('?', '.') # split into sentences by changing all punctuation to '.' contents = contents.replace('!', '.') contents = contents.lower() for punctuation in other_punctuation: contents = contents.replace(punctuation, '') sentences = contents.split('.') words = contents.split(' ') print(len(words)) print(len(sentences)) # for word in words: # print(word) #print(sentences) for i in range(len(words)-1): # for key in dict if words[i].strip() == '' or words[i+1].strip() == '': continue pair = words[i] + ' ' + words[i + 1] if pair not in word_count: word_count[pair] = 1 else: word_count[pair] += 1 words = list(word_count.items()) # list of tuples words.sort(key=lambda tup: tup[1], reverse=True) # sort largest to smallest, based on count for i in range(min(20, len(words))): # print the top 20 words, or all of them, whichever is smaller print(words[i]) # Version 3 # Nick walked me through the concept of how this would work; create a dictionary inside a dictionary # pair_counts = { # 'to': { # 'from': 3, # 'there': 5, # }, # 'there': { # 'and': 4, # 'word': 5 # } # } # # word1 = 'to' # word2 = 'from' # # if word1 not in pair_counts: # pair_counts[word1] = {} # # if word2 not in pair_counts[word1]: # pair_counts[word1][word2] = 1 # else: # pair_counts[word1][word2] += 1
bae3bd82fed925785023d6270207ad175da884b1
tntterri615/Pdx-Code-Guild
/Python/lab09makechange.py
816
4.03125
4
''' making change out of a dollar amount ''' # get input(dollar amount) from user x = int(input("Let's convert your money from dollars into change. How much money do you have, without using the decimal point?")) # determine how many quarters can be used quarters = float(x//25) # get remainder q_remainder = x%25 # determine how many dimes can be used dimes = float(q_remainder//10) d_remainder = q_remainder%10 # determine how many nickles can be used nickles = float(d_remainder//5) n_remainder = d_remainder%5 #determine how many pennies can be used pennies = n_remainder print(f'{quarters} quarters, {dimes} dimes, {nickles} nickles, {pennies} pennies') y = float(input("Now enter a dollar amount with the decimal point:")) amount_in_pennies = y * 100 print(f'You have {amount_in_pennies} pennies.')
a6bbf085e34878cf47623fef38c77da3b7ef8d4c
djamrozik/CS411-VegeCheck
/scripts/cheating_detection/detect_utils_copy.py
2,766
3.546875
4
from fetch_score import score_data import re from collections import defaultdict def split_answers(input): groups = re.match(r"(\d*):[\d],(\d*):[\d],(\d*):[\d],(\d*):[\d],(\d*):[\d],", input) return (groups.group(1), groups.group(2), groups.group(3), groups.group(4), groups.group(5)) """ a and b should both be percentages of type (float or decimal)""" def percentage_trigger(a, b, threshhold): if (abs(a - b) <= 20): return True else: return False """ a and b should both be storeIDs of type (int)""" def storeID_trigger(a, b): if a == b: return True else: return False """ a and b should both be timeFinished of type (datetime)""" def date_trigger(a, b): if a.date() == b.date(): return True else: return False """a and b should both be a list of answers of type (list)""" def compare_answers(answer1, answer2, threshhold): count = 0 for i in answer1: for j in answer2: if i == j: count = count + 1 if count >= threshhold: return True else: return False def is_suspicious(person1, person2, percent_threshhold, answer_threshhold): storeID1 = int(person1[1]) employeeID1 = int(person1[2]) percentage1 = float(person1[3]) timeFinished1 = person1[4] answers1 = split_answers(person1[5]) storeID2 = int(person2[1]) employeeID2 = int(person2[2]) percentage2 = float(person2[3]) timeFinished2 = person2[4] answers2 = split_answers(person2[5]) test1 = percentage_trigger(percentage1, percentage2, percent_threshhold) test2 = storeID_trigger(storeID1, storeID2) test3 = date_trigger(timeFinished1, timeFinished2) test4 = compare_answers(answers1, answers2, answer_threshhold) if (test1 and test2 and test3 and test4): return True else: return False # print type(storeID1), type(employeeID1), type(percentage1), type(timeFinished1), type(answers1) def exists(input, a, b): for i in input[a]: if i == b: return True return False def suspicious_employees(data): suspect_dict = defaultdict(list) percentage_threshhold = .2 answer_threshhold = 3 for i in range(len(data)): person_of_interest = data[i] for j in range(len(data)): person_to_compare = data[j] employeeID1 = int(person_of_interest[2]) employeeID2 = int(person_to_compare[2]) if ((employeeID1 != employeeID2) and is_suspicious(person_of_interest, person_to_compare, percentage_threshhold, answer_threshhold) and not exists(suspect_dict, employeeID1, employeeID2)): suspect_dict[employeeID1].append(employeeID2) return suspect_dict
4faf66595614f1e6342d12d115b62b927a503030
sunjuyoung/coding-test
/ch06/6-5.py
181
3.796875
4
array = [5,7,9,0,3,1,6,2,4,8] def quick_sort(array): pivot = array[0] tail = array[1:] # 피벗을 제외한 리스트 left_side = [x for x in tail if x<= pivot]
b6dbb2ce166a364aba1d21cef86ce8e16211eff4
lyjeff/Machine-Learning-Class
/hw1-Perceptron/hw1-1.py
1,593
3.71875
4
import numpy as np from utils import ( PLA, build_data, verification, plt_proc ) def PLA_3_times_with_30_data(m, b, num, times): # build 2D data x, y = build_data(m, b, num) #initial weight w = (0, 0, 0) w = np.zeros([1,3]) # count the iteration total numbers iteration_count = 0 # initial the figure plt_fig = plt_proc(x, num, title="HW1-1: PLA with 30 2D data samples") # plot the sample line equation plt_fig.add_line( w=None, m=m, b=b, num=num, iteration=None, label=f"Benchmark", txt="" ) for i in range(times): # run PLA algorithm w_result, iteration = PLA(x, y, w, num) # verify the line equation verification(x, y, w_result, num, iteration, show=True) # count the total number of iterations iteration_count += iteration # plot the line equation plt_fig.add_line( w=w_result, m=None, b=None, num=num, iteration=iteration, label=f"{i}", txt=f", iteration = {iteration}" ) print(f"Avg. Iteration = {iteration_count/3:.3f}") # save and show the figure plt_fig.save_and_show( itr_avg=iteration_count / 3, filename='hw1-1.png', avg_show=True ) if __name__ == '__main__': # y = m * x + b m = 1 b = 2 # default number of data = 30 num = 30 # set the running times of PLA times = 3 PLA_3_times_with_30_data(m, b, num, times)
042aea68e1f50e022a82004118433c410336b7be
YEJINLONGxy/shiyanlou-code
/investment.py
715
4
4
#!/usr/bin/env python3 # #amount = float(input('Enter amount: ')) #输入数额 #inrate = float(input('Enter Interest rate: ')) #输入利率 #period = int(input('Enter period: ')) #输入期限 #value = 0 #year = 1 def investment(): amount = float(input('Enter amount: ')) #输入数额 inrate = float(input('Enter Interest rate: ')) #输入利率 period = int(input('Enter period: ')) #输入期限 value = 0 year = 1 while year <= period: value = amount + (inrate * amount) #计算投资总得 #print("Year {} Rs. {:.2f}".format(year, value)) amount = value year += 1 return year-1, amount investment = investment() print('Year {} Rs. {:.2f}'.format(investment[0], investment[1]))
9cae7dd953a102a146fe23105b85c64746c2f834
YEJINLONGxy/shiyanlou-code
/matrixmul.py
1,735
4.25
4
#!/usr/bin/env python3 #这个例子里我们计算两个矩阵的 Hadamard 乘积。 #要求输入矩阵的行/列数(在这里假设我们使用的是 n × n 的矩阵)。 n = int(input("Enter the value of n: ")) print("Enter value for the Matrix A") a = [] for i in range(n): a.append([int(x) for x in input().split()]) #print(a) print("Enter value for the Matrix B") b = [] for i in range(n): b.append([int(x) for x in input().split()]) #print(b) c = [] for i in range(n): c.append([a[i][j] * b[i][j] for j in range(n)]) #print(c) print("after matrix multiplication") print("-" * 7 * n) for x in c: for y in x: print(str(y).rjust(5), end=" ") print() print("-" * 7 * n) #+++++++++++++++++++++++++++++++++++++++++++++++++++ #运行如下 #[root@dev1 python_code]# ./matrixmul.py #Enter the value of n: 4 #Enter value for the Matrix A #1 2 3 4 #5 6 7 8 #9 10 11 12 #13 14 15 16 #[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] #Enter value for the Matrix B #16 15 14 13 #12 11 10 9 #8 7 6 5 #4 3 2 1 #[[16, 15, 14, 13], [12, 11, 10, 9], [8, 7, 6, 5], [4, 3, 2, 1]] #[[16, 30, 42, 52], [60, 66, 70, 72], [72, 70, 66, 60], [52, 42, 30, 16]] #after matrix multiplication #---------------------------- # 16 30 42 52 # 60 66 70 72 # 72 70 66 60 # 52 42 30 16 #---------------------------- #这里我们使用了几次列表推导式: #[int(x) for x in input().split()] 首先通过 input() 获得用户输入的字符串 #再使用 split() 分割字符串得到一系列的数字字符串,然后用 int() 从每个数字字符串创建对应的整数值 #我们也使用了 [a[i][j] * b[i][j] for j in range(n)] 来得到矩阵乘积的每一行数据
f6cf5dd18f276acb2e83a3f7b2fb701a3b4528f3
YEJINLONGxy/shiyanlou-code
/palindrome_check.py
668
4.25
4
#!/usr/bin/env python3 #回文检查 #回文是一种无论从左还是从右读都一样的字符序列。比如 “madam” #在这个例子中,我们检查用户输入的字符串是否是回文,并输出结果 s = input("Please enter a string: ") z = s[::-1] #把输入的字符串 s 进行倒叙处理形成新的字符串 z if s == z: print("The string is a palindrome") else: print("The string is not a palindrome") #运行程序 #[root@dev1 python_code]# ./palindrome_check.py #Please enter a string: madam1 #The string is not a palindrome #[root@dev1 python_code]# ./palindrome_check.py #Please enter a string: madam #The string is a palindrome
7693472e4e9e0e294f95e89eca7ee7df6bb8acf7
rajiv786/turtle-library-in-python
/4.py
293
3.625
4
import turtle t = turtle.Turtle() turtle.title("Heart Shape") w = turtle.Screen() w.bgcolor("black") t.color("red") t.begin_fill() t.fillcolor("red") t.left(140) t.forward(180) t.circle(-90, 200) t.setheading(60) t.circle(-90, 200) t.forward(180) t.end_fill() t.hideturtle()
25e5e995ce64c0953a463eb92ba9b294e909f67c
soukalli/jetbrain-accademy
/Topics/Nested lists/Word list/main.py
360
3.796875
4
text = [["Glitch", "is", "a", "minor", "problem", "that", "causes", "a", "temporary", "setback"], ["Ephemeral", "lasts", "one", "day", "only"], ["Accolade", "is", "an", "expression", "of", "praise"]] length = int(input()) print([word for word in [word_in_sentence for sentence in text for word_in_sentence in sentence] if len(word) <= length])
0f7add96fea2633342d15e577bd3363a614385e6
soukalli/jetbrain-accademy
/Topics/Algorithms in Python/Last index of max/main.py
199
3.890625
4
def last_indexof_max(numbers): # write the modified algorithm here index = 0 for i in range(len(numbers)): if numbers[i] >= numbers[index]: index = i return index
72ded11a309eb690440c7f9c3e7a8e02c12d316f
davruk/mojevje-be-
/guess the secret number.py
217
4.0625
4
secret = "22" guess = int(input("Guess the secret number (between 1 and 30): ")) if guess == 22: print("You got it - It is the number 22") else: print("Sorry, your guess is not correct")
2ddb1a6ff62f577e06a8102ca42dd46710f22cbd
BigFav/Project-Euler
/p_33.py
1,046
3.65625
4
from fractions import Fraction from operator import mul """ Find the denominator for the product of digit cancelling fractions. """ digit_cancel_fracs = [] for numerator in xrange(10, 99): if numerator % 10 == 0 or numerator % 11 == 0: # trivial cases continue for denominator in xrange(numerator + 1, 100): real_frac = Fraction(numerator, denominator) # check if numbers share digits num_digits = list(`numerator`) den_digits = list(`denominator`) if den_digits[0] in num_digits: num_digits.remove(den_digits[0]) del den_digits[0] elif den_digits[1] in num_digits: num_digits.remove(den_digits[1]) del den_digits[1] else: continue if int(den_digits[0]) != 0 and real_frac == Fraction(int(num_digits[0]), int(den_digits[0])): digit_cancel_fracs.append(real_frac) if len(digit_cancel_fracs) == 4: break print reduce(mul, digit_cancel_fracs, 1)
b265460fc33d63e632d20275ca7b56137ad961c9
BigFav/Project-Euler
/p_56.py
240
3.84375
4
''' For a^b, where a, b < 100, what is the maximum digital sum? ''' def sum_digits(n): r = 0 while n: r, n = r + n % 10, n / 10 return r print max(max(sum_digits(a**b) for b in xrange(1, 100)) for a in xrange(1, 100))
52f91fbb66db692a1136d6fc61b11c1e40cab9e5
UPstartDeveloper/zip_file_maker
/zip_test.py
559
3.859375
4
import os import zipfile def zipdir(path, ziph): """ziph is zipfile handle""" for root, dirs, files in os.walk(path): for file in files: ziph.write(os.path.join(root, file)) if __name__ == '__main__': file_name = input("Enter a name for your new ZIP folder " + "(include extension): ") path = input("Enter the path to the directory you would like the ZIP " + "to save to: ") zipf = zipfile.ZipFile(file_name, 'w', zipfile.ZIP_DEFLATED) zipdir(path, zipf) zipf.close()
b7104c88bf95201fb455f5dd1f0a918b78a682b0
ankush1717/2048
/gui2048.py
3,712
4.125
4
from class2048 import * from tkinter import * class Square: '''Objects of this class represent a square on a tkinter canvas.''' def __init__(self, canvas, center, size, color, order, value): (x, y) = center x1 = x - size / 2 y1 = y - size/2 x2 = x + size/2 y2 = y + size/2 self.handle = \ canvas.create_rectangle(x1, y1, x2, y2, fill=color, outline=color) self.canvas = canvas self.center = center self.size = size self.color = color self.order = order self.value = value canvas.create_text(center, text=value, font="Times 20") def setColor(self, color): '''Changes this object's color to 'color'.''' self.canvas.itemconfig(self.handle, fill=color, outline=color) self.color = color def move(self, x, y): '''Move this square by (x, y).''' self.canvas.move(self.handle, x, y) (cx, cy) = self.center self.center = (cx + x, cy + y) def moveTo(self, x, y): '''Move this square to the location (x, y) on its canvas.''' (cx, cy) = self.center dx = x - cx dy = y - cy self.move(dx, dy) def changeValue(self, value): c.create_text(self.center, text=value, font="Times 20 bold", ) self.value = value def make_GUI_board(board): squares = [] x = -75 order = 0 for i in range(4): x += 150 y = -75 c.create_line(x+75, 0, x+75, 600, fill='blue', width=3) for j in range(4): y += 150 order += 1 if i == 1: c.create_line(0, y+75, 600, y+75, fill='blue', width=3) squares.append(Square(c,(x,y),144, 'peach puff', order-1, '')) for value in board: place = value[0] + (4 * value[1]) for item in squares: if item.order == place: item.changeValue(board[value]) for item in squares: if item.value == 2: item.setColor('lavender') if item.value == 4: item.setColor('cornflower blue') if item.value == 8: item.setColor('pale goldenrod') if item.value == 16: item.setColor('dark seagreen') if item.value == 32: item.setColor('seagreen') if item.value == 64: item.setColor('yellow') if item.value == 128: item.setColor('orange') if item.value == 256: item.setColor('orange red') if item.value == 512: item.setColor('hot pink') if item.value == 1024: item.setColor('light sea green') if item.value == 2048: item.setColor('sandy brown') if item.value == 4096: item.setColor('snow') if item.value == 8192: item.setColor('violet') def update_GUI(board, event): update(board, event) make_GUI_board(board) def buttonPressed(event): letter = event.char update_GUI(b, event.char) def erase_board(board): board = {} def new_game(board): board = make_board() print(board) print('button pressed') make_GUI_board(board) if __name__ == '__main__': root = Tk() root.geometry('600x600') c = Canvas(root, width=600, height=600) c.pack() b = make_board() make_GUI_board(b) root.bind('<w>', buttonPressed) root.bind('<a>', buttonPressed) root.bind('<d>', buttonPressed) root.bind('<s>', buttonPressed) root.mainloop()