blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
4e7667591affc79bb488d29f6b8867eda5445470
lunarpearl/rosemary.py
/modified_pancakes.chef.py
1,103
3.5
4
from kitchen.ingredients.Collections import Collection, Mixture, Portion from kitchen.Rosemary import Rosemary from kitchen.utensils import Pan, Plate, Bowl from kitchen.ingredients import Egg, Salt, Flour, Milk, Butter #making a batter again but now as a mixture(class) batter=Mixture(name='batter to make pancakes') for i in range(2): egg=Egg.take() egg.crack() batter._add(item=egg) batter._mix() salt=Salt.take('a dash') batter._add(item=salt) batter._mix() for i in range(5): flour=Flour.take(grams=50) batter._add(item=flour) batter._mix() for i in range(2): milk=Milk.take(ml=250) batter._add(item=milk) batter._mix() #making a specific measurement of ingredients to scoop for a single pancake single_pancake=Portion(ingredient=batter,portion=1/8) #cooking pancakes in a pan pan=Pan.use(name='pancakes') plate=Plate.use() for i in range(8): pan.add(Butter.take(amount='a little')) pan.add(single_pancake) pan.cook(minutes=1) pan.flip() pan.cook(minutes=1) pan.flip() pancake=pan.take() plate.add(pancake) Rosemary.serve(plate)
0248ef6c07fe234921a6b5a64b5575b93f9a0bc9
shuaih7/Huawei_coding_interview
/HJ21.py
806
3.90625
4
# -*- coding: utf-8 -*- d={ "abc":2, "def":3, "ghi":4, "jkl":5, "mno":6, "pqrs":7, "tuv":8, "wxyz":9, } if __name__ == "__main__": while True: try: a,res=input(),"" for i in a: if i.isupper(): # check whether the character is upper case if i!="Z": res+=chr(ord(i.lower())+1) else: res+="a" elif i.islower(): # check whether the character is lower case for j in d.keys(): if i in j: res+=str(d[j]) break else: res+=i print(res) except: break
48f20510daa56b7d2488f92013ee2ea9b1b15543
thomastien/hackerrank
/euler/euler004.py
1,475
3.75
4
# Enter your code here. Read input from STDIN. Print output to STDOUT # Strategy # Given a #, (assume <=998001) # Need to verify # A: number is palindromic # B: number is product of 3-digit #s # brute-force could start from 998001, downwards # and divide by all #s 100-999, until modulous 0 # STRATEGY TWO (the one used) # iterate through all products 100-999 * 100-999, note this is 808201 combinations # store this in a dictionary, and just locate the largest one < N import pprint debug = 0 def isPalin(x): x = str(x) revx = x if revx[::-1] == x: return True else: return False # Doesn't need to be a dict, will use a list #allpalins ={} allpalins = [] for i in range(100,1000): for j in range(100,1000): product = i*j if isPalin(product): #allpalins[product] = product allpalins.append(product) if debug: allpalins.sort() pprint.pprint(allpalins) n = input() for i in range(1,n+1): # note input evaluates, raw_input keeps as is # so use raw_input if it can be a string. In this case it's unnecessary, but # just noted (plus done) as an exercise x = int(raw_input()) #print max(allpalins, key=lambda x: allpalins[i] < x) index = max(k for k in allpalins if k <=x) if debug: print "Highest palindronmic product less than %i was %i" % (x,index) else: print index #print allpalins[index]
b762a72e787332a90cd732f517a9cf908f832ac6
Cleber-Woheriton/Python-Mundo-1---2-
/desafioAula063.py
817
4
4
#(Desafio 63) Escreva um programa que leia um número n inteiro qualquer e mostre # na tela os n primeiros elementos de uma sequência de fibonacci. # Ex 0→ 1→ 1→ 2→ 3→ 5→ 8→ print(f'\033[1;30;43m{" Sequência de Fibonacci ":=^60}\033[m') valA = f = 0 valB = valC = cont = 1 print('Quantos números de sequência deseja ver?') nFb = int(input('Valor: ')) while valC != 0: while cont <= nFb: print(f'\033[33m{valA}\033[m', end='\033[31m→ \033[m') if cont < nFb: print(f'\033[33m{valB}\033[m', end='\033[31m→ \033[m') valA += valB valB += valA cont += 1 cont += 1 print('\nQuantos mais deseja ver?') valC = int(input('Valor: ')) nFb += valC print(f'\033[35m{" Obrigado por usar nosso sistema! ":~^60}\033[m')
edfc42971e705ba71444978089ef1023c51a34cc
devdiogofelipe/Introduction-to-python
/Módulo 1/Practice/if_elif_else.py
476
4.25
4
def num_to_letter_grade(grade): if grade >= 90: print ("YAAAAY DID U GET AN A!!!!!") elif grade >= 80: print("WOW DID U GET AN B!!!") elif grade >= 70: print("WELL DONE MATE, U GET A C!!") elif grade >= 60: print("WELL DONE MATE, AN D CAN MAKE U PASS THROUGH") else : print("HELL NO THIS TEACHER ARE A WAAY OUT OF HIS MIND") grade = input("Enter your numeric grade: ") grade = int(grade) num_to_letter_grade(grade)
ab36eaded604e4efbd1bf9f67fa8c5c477ecedec
Jalcivarg2/Trabajos-en-clase
/Sintaxis.py
1,722
3.625
4
# -*- coding: utf-8 -*- """ Created on Fri Jun 25 14:01:17 2021 @author: Jose Alcivar Garcia """ #num=20 #if type(num)==int: # print("respuesta: ", num*2) #else: # print("el dato no es numerico") #def mensaje(men): # print(men) #mensaje("mi primer progama ") #mensaje("mi segundo programa ") class sintaxis: instancias =0 # variable de clases(opcional) _init_ def _init_ (self, dato="inicializacion"): self.frase=dato #variable de instacia #sintaxis.instancia= sintaxis.instancia+1 def usoVariable(self): edad, peso= 50, 70.5 nombres= "Daniel Vera" tipo_sexo= "M" civil= True # tuplas=() son colecciones de datos de cualquier tipo inmutable usuario=() usuario= ('dchili', '1234', 'chiki@gmail.com', True) #usuario[3]="milagro" #listas=[] coleccione mutables materias=[] materias=['programacion web', 'PHP', 'POO'] materias[1]="Python" materias.append("Go") #diccionario ={} colecciones de objetos clave: valor tipo json docente{} docente={'nombre': 'Daniel', 'edad': 50, 'fac': 'faci'} docente['carrera']="CS" # presentacion con format #print("""Mi nombre es {}, tengo{} años""".format(nombres, edad)) #print(usuario, materia, docentes) #print(usuario, usuario[0], usuario[0:2], usuario[-1]) print (materia, materias[2:], materias[:3], materias[:],materias[-2:]) #print(docente, docente['nombre']) ejer1= sintaxis()#se crea un objeto que es una instancia de la clase y se ejecuta el constructor ejerc1.usoVariables()
4ec52e5bf20bb7d4d3d0f915c686c2aecb87777c
LorenzHW/Coding-Competitions
/code_jam/2018/round_1-c/2_problem/lollipop.py
1,563
3.5625
4
class Flavor: def __init__(self, id, sold=False, likes=1): self.id = id self.sold = sold self.likes = likes class ShopStatistic: def __init__(self): self.statistic = {} def update(self, prefs): for flav_id in prefs: flavor = self.statistic.get(flav_id, None) if flavor is not None: flavor.likes += 1 else: self.statistic[flav_id] = Flavor(flav_id) def sell_lollipops(prefs, shop_statistic): if prefs is None: print("-1") return shop_statistic.update(prefs) flav_id = sell_correct_lollipop(prefs, shop_statistic) print(flav_id) def sell_correct_lollipop(prefs, shop_statistic): customers_flavors = [] for flav_id in prefs: flavor = shop_statistic.statistic.get(flav_id) if not flavor.sold: customers_flavors.append(flavor) if customers_flavors: customers_flavors.sort(key=lambda flav: flav.likes) customers_flavors[0].sold = True return customers_flavors[0].id return "-1" number_of_test_cases = int(input()) for i in range(1, number_of_test_cases + 1): N = int(input()) shop_statistic = ShopStatistic() for _ in range(N): line = [int(i) for i in input().split()] if line == "-1": exit() D = line[0] if D != 0: flavors = line[1:] else: flavors = None sell_lollipops(flavors, shop_statistic) # print("Case #{}: {}".format(i, res))
d3de5aff87631180e43f78543a78c9890b3d548c
huyanhvn/hackerrank
/python/map_reduce.py
491
3.515625
4
# https://www.hackerrank.com/challenges/string-validators if __name__ == '__main__': s = raw_input() print reduce((lambda y,z : y or z), map(lambda x: x.isalnum(), list(s))) print reduce((lambda y,z : y or z), map(lambda x: x.isalpha(), list(s))) print reduce((lambda y,z : y or z), map(lambda x: x.isdigit(), list(s))) print reduce((lambda y,z : y or z), map(lambda x: x.islower(), list(s))) print reduce((lambda y,z : y or z), map(lambda x: x.isupper(), list(s)))
47de4a68d816026e027c53dec9bef2fee9484f08
knakajima3027/pycoder
/ABC210/main_B.py
287
3.515625
4
def solve(S: str) -> str: for i in range(len(S)): if S[i] == "1": if i % 2 == 0: return "Takahashi" else: return "Aoki" if __name__ == "__main__": n = int(input()) s = input() ans = solve(s) print(ans)
bd56678d4bace7df952543a1ab0b177c7acbb2fa
jaford/thissrocks
/Python_Class/py3intro3day 2/EXAMPLES/simple_class.py
372
3.515625
4
#!/usr/bin/env python class Simple(): # <1> def __init__(self, message_text): # <2> self._message_text = message_text # <3> def text(self): # <4> return self._message_text if __name__ == "__main__": msg1 = Simple('hello') # <5> print(msg1.text()) # <6> msg2 = Simple('hi there') # <7> print(msg2.text())
1d64ce4ae4feb45fdc8953d952e403daad63c4ef
leyvamn2/Learning-python
/p5.py
244
3.90625
4
#práctica if print("evaluacion de notas") notas=input("Introduce la nota del alumno: \n") def evaluacion (nota): valoracion="aprobado" if nota<5: valoracion="suspenso" return valoracion print(evaluacion (int(notas)))
276c1ed69713f649a25df2878abef8e6e8216e3d
LavanyaLahariRajaratnam/100-days-coding
/XOR in list.py
425
3.734375
4
''' given an integer n and an integer start. define an array nums where nums[i]=start +2*i(0-indexed) and n==nums.length. Return the bitwise XOR ("^") of all elements of nums. ''' #sir ''' n=int(input())#5 start=int(input())#0 for i in range(n): x^=s+(2*i) print(x) ''' n=int(input()) start=int(input()) l=[] xor=0 for i in range(n): l.append(start+2*i) for j in l: xor=xor^j print(xor)
bcc2e20e10d269f0ea04a5143ecbb51839c6c1e4
advecchia/leetcode
/top_interview_questions/13_roman_to_integer.py
1,748
3.859375
4
# https://leetcode.com/problems/roman-to-integer/ import unittest MINIMUM_WORD_LENGTH = 1 MAXIMUM_WORD_LENGTH = 15 class SolutionValidator(object): def validate_word_length(self, word: str) -> None: if MINIMUM_WORD_LENGTH > len(word) or len(word) > MAXIMUM_WORD_LENGTH: raise ValueError('Invalid word length') def validate_roman_char(self, char: str) -> None: if char not in ['I', 'V', 'X', 'L', 'C', 'D', 'M']: raise ValueError('Invalid Roman char') class Solution: def __init__(self): self.validator = SolutionValidator() self.roman_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} def romanToInt(self, s: str) -> int: # Basic validations self.validator.validate_word_length(s) total = 0 last = -2**32 for i in range(len(s) - 1, -1, -1): # Basic validations self.validator.validate_roman_char(s[i]) current = self.roman_map[s[i]] if last > current: total -= current else: total += current last = current return total def main(): tc = unittest.TestCase() sol = Solution() print('Example 1') tc.assertEqual(sol.romanToInt('III'), 3) print('Example 2') tc.assertEqual(sol.romanToInt('IV'), 4) print('Example 3') tc.assertEqual(sol.romanToInt('IX'), 9) print('Example 4') print('Explanation: L = 50, V= 5, III = 3.') tc.assertEqual(sol.romanToInt('LVIII'), 58) print('Example 5') print('Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.') tc.assertEqual(sol.romanToInt('MCMXCIV'), 1994) if __name__ == "__main__": main()
a685193b165b2871a5445f2e8181cf459bf5fd8b
algohell/ALGOHELL
/Sherlock_and_the_Valid_String/pgo.py
611
3.65625
4
#!/bin/python3 import math import os import random import re import sys from collections import Counter # Complete the isValid function below. def isValid(s): s_v = sorted(list(Counter(s).values())) #print(s_v) if s_v.count(s_v[0]) == len(s_v) or (s_v.count(s_v[0]) == len(s_v) - 1 and s_v[-1] - s_v[-2] == 1) or (s_v.count(s_v[-1]) == len(s_v) - 1 and s_v[0] == 1): return "YES" else: return "NO" if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = isValid(s) fptr.write(result + '\n') fptr.close()
e876ef49e1b9d3a9581105dde2ab807f5c054c98
cappuccinooo/python20210201
/1-7.py
213
3.84375
4
a=int(input('輸入數學成績')) b=int(input('輸入英文成績')) if a<60 and b <60: print('要處罰!') elif a>90 and b>=90: print('有獎品!') elif a<60 or b <60: print('再加油')
20d977800b807448ecf8581d9aa65d00b72f498b
dmc200/Python-Projects
/List_Touple_Sets.py
1,974
4.375
4
# List Examples ''' courses = ["History", "Math", "Physics", "ComSci"] courses_2 = ["Education", "Statistics"] courses.append("Art") courses.insert(0, courses_2) print(courses[0]) print(courses) courses.remove(courses_2) courses.extend(courses_2) print(courses) courses.remove("Math") print(courses) popped = courses.pop() print(popped) print(len(courses)) print(courses[2]) print(courses[-1]) ''' ''' courses = ["History", "Math", "Physics", "ComSci"] courses_2 = ["Education", "Statistics"] print(courses.index("History")) new_list = sorted(courses) print(new_list) print("Art" in courses) for course in courses: print(course) for index, course in enumerate(courses, start=1): print(index, course) ''' ''' courses = ["History", "Math", "Physics", "ComSci"] # change what seperates items in a list with .join() course_str = ' - '.join(courses) print(course_str) # turn back to a string course_str = course_str.split(" - ") print(course_str) ''' # Lists are Mutable. # Touples are Imutable. ''' touple_1 = ('history', 'english', 'math') touple_2 = touple_1 mtset = {"math", "math", "ComcSci", "English", "ComSci"} mtset2 = {"math", "History", "Art", "English", "Reddit"} print(mtset) mtset.intersection(mtset2) # touple_1[1] = 'art' print(touple_1) print(touple_2) print(mtset) print(mtset2) mtset = {"math", "math", "ComcSci", "English", "ComSci"} mtset2 = {"math", "History", "Art", "English", "Reddit"} ''' cs_courses = {'History', 'Math', 'Physics', 'ComSci', 'Math'} art_courses = {'History', 'Math', 'Art', 'Design', 'Math'} # Sets are optimized for boolean operations like this: print('Math' in cs_courses) print(cs_courses.intersection(art_courses)) print(cs_courses.difference(art_courses)) print(cs_courses.union(art_courses)) empty_list = [] empty_list = list() empty_tuple = () empty_tuple = tuple() empty_set = {} # incorrect, this will create a dictionary. empty_set = set() # correct way to start an empty set.
fe20050718cd1761464b07b48bc5daf4ef5e430e
danielcorroto/projecteuler
/problem016.py
311
4
4
''' Created on Mar 19, 2014 @author: Daniel Corroto 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? ''' def sumBiPower(x): y = 2 ** x temp = 0 while y > 0: temp += y % 10 y /= 10 return temp print sumBiPower(1000)
5b8a00092c5a64ce612cf178fe7ac5e22e1e9d9d
nishamadaan/learning_space
/fun1.py
224
3.671875
4
def changeMe(mylist): #mylist.append([1,2,3]) list1 = [1,2,3] print("Values inside the function: ",list1) return mylist = [10,20,30] changeMe(mylist) print("values outside the function: ",mylist)
9c969b0b96422cc028f3bc1de4917012892cfdb0
LauraBrogan/2021-Computational-Thinking-with-Algorithms-Project
/bubblesort.py
1,266
4.46875
4
#CTA Project 2021 #Bubble Sort #Resourse used: https://realpython.com/sorting-algorithms-python/#the-bubble-sort-algorithm-in-python def bubblesort(array): n = len(array) for i in range(n): # If there's nothing left to sort terminate the sort function already_sorted = True #Look at each item of the list one by one and compare it to the adjacent item. #Each iteration reduces the amount of the array that is looked at as the remaining itens are already sorted. for j in range(n - i - 1): if array[j] > array[j + 1]: #If the item you are looking at is larger than the adjacent value then they are swaped. array[j], array[j + 1] = array[j + 1], array[j] #As swaping two elements, mark already_sorted to false so the algorithm doesn't finish prematurely. already_sorted = False #If no swaps in the last iteration the array is already sorted and can be terminated. if already_sorted: break #return array #Sample array array = [54,26,93,17,77,31,44,55,20] #Run bubble sort on the sample array bubblesort(array) #Print array for testing to see results of running bubble sort. print(array) #Laura Brogan 11/04/2021
2c6bee348b180f1b3fca5c46bafee932aa6682a1
RuzhaK/pythonProject
/Fundamentals/FinalExamPreparation/Regex/EmojiDetector.py
587
3.796875
4
import re line=input() pattern_emojis=r"(\*{2}|:{2})([A-Z][a-z]{2,})\1" pattern_digits="\d" matches_emojis=re.finditer(pattern_emojis,line) matches=re.findall(pattern_digits,line) threshold = 1 for m in matches: threshold*=int(m) all_emojis=[m for m in matches_emojis] print(f"Cool threshold: {threshold}") print(f"{len(all_emojis)} emojis found in the text. The cool ones are:") for emoji in all_emojis: sum=0 a=emoji[2] for i in range(len(emoji[2])): if emoji[2][i].isalpha(): sum+=ord(emoji[2][i]) if sum>threshold: print(emoji[0])
59a3731fecb16ae9ae13386f4e60342dda020548
GuiltyD/PythonCookbook
/Chapter 8/8.16 在类中定义多个构造函数.py
353
3.65625
4
import time class Date: def __init__(self,year,month,day): self.year = year self.month = month self.day = day @classmethod def today(cls): t = time.localtime() return cls(t.tm_year,t.tm_mon,t.tm_mday) def __str__(self): return '{}/{}/{}'.format(self.year,self.month,self.day) a = Date(2019,7,11) b = Date.today() print(a) print(b)
b899c0f3010aabe43039c51f37d4a75eeb18700a
cjgarcia/diplomado_python
/exes/exe4.py
90
3.609375
4
def es_palindromo(p1, p2): return p1 == p2[::-1] print(es_palindromo('amor', 'roma'))
7ebc0562b63d5ded763f61552d5b88dba6d8adb5
kzarms/robot
/essun/remote.py
5,609
3.546875
4
#!/usr/bin/env python3 """This is the initial module to control the car.""" # import sys import time import pygame import serial from serial import Serial # Check number of the COM port after BT paring COMPORT = 'COM3' COMPORT = '/dev/rfcomm0' ser = serial.Serial('/dev/rfcomm0') # open serial port >>> print(ser.name) # check which port was really used >>> ser.write(b'hello') # write a string >>> ser.close() # close port # region functions def send_cmd(ser, cmd): """Send command to serial.""" ser.write(cmd.encode('ascii')) def small_test(comport): """Small test to run forward for 3 secs.""" local_ser = serial.Serial(comport) local_delay = 1.5 # Run the car send_cmd(local_ser, "1,1#") time.sleep(local_delay) send_cmd(local_ser, "3,4#") time.sleep(local_delay) send_cmd(local_ser, "-1,2#") time.sleep(local_delay) send_cmd(local_ser, "0,0#") # Close the com port local_ser.close() # endregion # small_test(COMPORT) # Open serial port on the COMPORT ser = serial.Serial(COMPORT) # Start the pygame pygame.init() display_width = 500 display_height = 500 black = (0, 0, 0) white = (255, 255, 255) red = (255, 0, 0) car_width = 73 car_height = 123 gameDisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('Remote control') clock = pygame.time.Clock() # Car definition # carImg = pygame.image.load('racecar.jpg') def things(thingx, thingy, thingw, thingh, color): pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh]) def car(x, y): """The car function.""" gameDisplay.blit(carImg, (x, y)) # Text display def text_objects(text, font): """The text function.""" textSurface = font.render(text, True, black) return textSurface, textSurface.get_rect() def message_display(text): """The test show function.""" largeText = pygame.font.Font('freesansbold.ttf', 14) TextSurf, TextRect = text_objects(text, largeText) TextRect.center = (30, 10) gameDisplay.blit(TextSurf, TextRect) pygame.display.update() time.sleep(2) game_loop() def crash(): """The crash function.""" message_display('You Crashed') def game_loop(): """The main game function.""" center_position = 0.45 x_change = 0 y_change = 0 border_a = 0.1 border_b = 0.9 set_timer = 60 x = (display_width * center_position) y = (display_height * center_position) car_x = 0 car_y = 0 gameExit = False while not gameExit: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() ############################ if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 car_y += 1 #if difference less than 4 make it if abs(car_x - car_y) < 4: car_x += -1 elif event.key == pygame.K_RIGHT: x_change = 5 car_x += 1 #if difference less than 4 make it if abs(car_x - car_y) < 4: car_y += -1 elif event.key == pygame.K_UP: y_change = -5 car_x += 1 car_y += 1 elif event.key == pygame.K_DOWN: car_x += -1 car_y += -1 y_change = 5 elif event.key == pygame.K_SPACE: x = (display_width * center_position) y = (display_height * center_position) car_x = 0 car_y = 0 #Set maximum to the sending, no more then 9 if car_x > 9: car_x = 9 if car_x < -9: car_x = -9 if car_y > 9: car_y = 9 if car_y < -9: car_y = -9 send_cmd(ser, (str(car_x) +',' + str(car_y) + '#')) if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or \ event.key == pygame.K_RIGHT or \ event.key == pygame.K_UP or \ event.key == pygame.K_DOWN: #send_cmd(ser, "0,0#") x_change = 0 y_change = 0 ############################ x += x_change y += y_change msg = "X: " + str(x) + " Y: " + str(y) if x > (display_width * border_b): x = (display_width * border_b) if x < (display_width * border_a): x = (display_width * border_a) if y > (display_height * border_b): y = (display_height * border_b) if y < (display_height * border_a): y = (display_height * border_a) gameDisplay.fill(white) things(x, y, 25, 25, black) #car(x, y) # crash() pygame.display.update() clock.tick(set_timer) game_loop() ser.close() pygame.quit() quit() """ def frwd(): print("Frwd") def bkwd(): print("Bkwd") def left(): print("Left") def rite(): print("Rite") def navigation(x): return { 'w': frwd, 's': bkwd, 'a': left, 'd': right }[x]() button = keyboard.read_key() switcher[button]() navigation('w') while True: if keyboard.is_pressed("p"): if keyboard.read_key() == "w": print("Forward") break """
2f7fc26bb98b65db0f59c9dd1c7a83b2a8790310
danieldfc/curso-em-video-python
/ex003.py
225
3.875
4
first_value = int(input('Digite um valor: ')) second_value = int(input('Digite um valor: ')) sum_total = (first_value + second_value) print('A soma entre {} e {} é igual a {}!'.format(first_value, second_value, sum_total))
dc962abbc09bb705c9440f9884724787804e92b4
Yixuan-Lee/LeetCode
/algorithms/src/Ex_78_subsets/solution_discussion_cascading.py
604
3.78125
4
""" Reference: https://leetcode.com/problems/subsets/solution/ Idea: start from an empty subset in output list, then at each step, one takes an new integer into consideration and generates new subsets from the existing ones. Time complexity: O(n * 2^n) Space complexity: O(n * 2^n) """ from typing import List class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: output = [[]] for num in nums: output += [curr + [num] for curr in output] return output if __name__ == '__main__': solu = Solution() print(solu.subsets([1, 2, 3]))
ae51b048888f89784b6fd387c90e2972fb159a2c
ampledata/sdk-samples
/modbus_simple_bridge/cp_lib/split_version.py
3,788
3.6875
4
def split_version_string(value, default=None): """ Given a string in the form X.Y.Z, split to three integers. :param str value: a string version such as "6.1.0" or "7.345.beta" :param str default: :return: major, minor, and patch as ints :rtype: int, int, int """ if value is None or value == "": if default is None: return None, None, None else: value = default if not isinstance(value, str): # we don't expect int or float or other types raise TypeError value = value.strip() # hope value is like "X.y" patch = 0 # default offset = value.find(".") if offset >= 0: # then we found a ".", assume major is first part - the "X" major = int(value[:offset]) # now test the Y part value = value[offset + 1:] offset = value.find(".") if offset >= 0: # assume was had an X.Y.Z, so just ignore/discard the Z + more minor = int(value[:offset]) # now test for a Z part offset = value.find(".") if offset >= 0: item = value[offset + 1:] patch = item if not item.isdigit() else int(item) else: # was just X.Y, so this is the Y part minor = int(value) else: # was just X, so force Y to be 0 major = int(value) minor = 0 return major, minor, patch SETS_NAME_MAJOR = 'major_version' SETS_NAME_MINOR = 'minor_version' SETS_NAME_PATCH = 'patch_version' def split_version_save_to_dict(value, sets, default=None, section=None): """ Given a string in the form X.Y.Z split to three integers and save as ['major_version'], and ['minor_version'], and ['patch_version'] in the [section] of sets. :param str value: a string version such as "6.1.0" or "7.345.beta" :param dict sets: the settings, as per normal SDK :param str default: :param str section: the sub-section in sets, like "application" or "fw_info"; if None, assume in base setts :return dict: """ major, minor, patch = split_version_string(value, default) if section is None: sets[SETS_NAME_MAJOR] = major sets[SETS_NAME_MINOR] = minor sets[SETS_NAME_PATCH] = patch else: if section not in sets: sets[section] = dict() sets[section][SETS_NAME_MAJOR] = major sets[section][SETS_NAME_MINOR] = minor sets[section][SETS_NAME_PATCH] = patch return sets def sets_version_to_str(sets, section=None): """ Given a dict() (the 'sets'), see if at least one of ['major_version'], and ['minor_version'], and ['patch_version'] exist, if so return a string formed as "major.minor.patch", with 0 being a default. If neither exist, then return None :param dict sets: the settings, as per normal SDK :param str section: the sub-section in sets, like "application" or "fw_info"; if None, assume in base setts :rtype str: """ if section is None: major = sets.get(SETS_NAME_MAJOR, None) minor = sets.get(SETS_NAME_MINOR, None) patch = sets.get(SETS_NAME_PATCH, None) else: major = sets[section].get(SETS_NAME_MAJOR, None) minor = sets[section].get(SETS_NAME_MINOR, None) patch = sets[section].get(SETS_NAME_PATCH, None) if major is None and minor is None: # then we've failed return None if major is None: major = 0 else: major = int(major) if minor is None: minor = 0 else: minor = int(minor) if patch is None: patch = 0 else: patch = patch return "%d.%d.%s" % (major, minor, str(patch))
742986271a880c28a43cb3947277c2f99f90038c
eselyavka/python
/leetcode/solution_40.py
1,191
3.65625
4
import unittest class Solution(object): def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ ans = [] local_ans = [] n = len(candidates) candidates.sort() def backtracking(pos): if sum(local_ans) > target: return if sum(local_ans) == target: ans.append(local_ans[:]) return prev = -1 for i in range(pos, n): if prev == candidates[i]: continue local_ans.append(candidates[i]) backtracking(i + 1) local_ans.pop() prev = candidates[i] backtracking(0) return ans class TestSolution(unittest.TestCase): def test_combinationSum2(self): solution = Solution() self.assertListEqual(sorted(solution.combinationSum2([10, 1, 2, 7, 6, 1, 5], 8)), sorted([ [1, 1, 6], [1, 2, 5], [1, 7], [2, 6] ])) if __name__ == '__main__': unittest.main()
fdc3d9bc53fd0fd6d70eab7e8f89e1871f1d1ddf
Candy-u/python
/序列化.py
1,078
3.875
4
#序列化 #在程序运行的过程中,所有的变量都是在内存中,比如,定义一个dict: #d = dict(name='Bob', age=20, score=88) '''可以随时修改变量,比如把name改成'Bill',但是一旦程序结束,变量所占用的内存就被操作系统全部回收。如果没有把修改后的'Bill'存储到磁盘上,下次重新运行程序,变量又被初始化为'Bob'。 我们把变量从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等,都是一个意思。 序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上。 反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。 Python提供了pickle模块来实现序列化。''' import pickle d = dict(name='Bob', age=20, score=88) pickle.dumps(d) #pickle.dumps()方法把任意对象序列化成一个bytes,然后,就可以把这个bytes写入文件。
b1cad027f8ed34286074b177d1046c420ec91630
jxhangithub/leetcode
/solutions/python3/290.py
496
3.71875
4
class Solution: def wordPattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ if len(str.split())!=len(pattern): return False dic={} for word in str.split(): if not pattern[0] in dic.values() and not word in dic: dic[word]=pattern[0] else: if not word in dic or dic[word]!=pattern[0]: return False pattern=pattern[1:] return True
f84833155703043c56f3649874af353ef8b2d8a4
MellamoTrung/PythonPractice
/Ex3-2.py
143
4.1875
4
length = float(input("Enter the lenth: ")) width = float(input("Enter the width: ")) print("The area of the room is {}".format(length*width))
ce1d9b04b9b42d85febf7cdf2d95739f9a9c1aaa
anantkaushik/Competitive_Programming
/Python/GeeksforGeeks/odd-even-level-difference.py
2,989
4.34375
4
""" Problem Link: https://practice.geeksforgeeks.org/problems/odd-even-level-difference/1 Given a a Binary Tree, your task is to complete the function getLevelDiff which returns the difference between the sum of nodes at odd level and the sum of nodes at even level . The function getLevelDiff takes only one argument ie the root of the binary tree . 2 / \ 3 5 For the above tree the odd level sum is 2 and even level sum is 8 thus the difference is 2-8=-6 Input: The task is to complete the method which takes one argument, root of Binary Tree. There are multiple test cases. For each test case, this method will be called individually. Output: The function should return an integer denoting the difference between the sum of nodes at odd level and the sum of nodes at even level Constraints: 1 <=T<= 30 1 <= Number of nodes<= 20 Example: Input 2 2 1 2 R 1 3 L 4 10 20 L 10 30 R 20 40 L 20 60 R Output -4 60 There are two test cases. First case represents a tree with 3 nodes and 2 edges where root is 1, left child of 1 is 3 and right child of 1 is 2. Second test case represents a tree with 4 edges and 5 nodes. """ class Node: def __init__(self, value): self.left = None self.data = value self.right = None class Tree: # Binary tree Class def createNode(self, data): return Node(data) def insert(self, node, data, ch): if node is None: return self.createNode(data) if (ch == 'L'): node.left = self.insert(node.left, data, ch) return node.left else: node.right = self.insert(node.right, data, ch) return node.right def search(self, lis, data): # if root is None or root is the search data. for i in lis: if i.data == data: return i def traverseInorder(self, root): if root is not None: self.traverseInorder(root.left) print(root.data, end=" ") self.traverseInorder(root.right) if __name__=='__main__': t=int(input()) for i in range(t): n=int(input()) arr = input().strip().split() tree = Tree() lis=[] root = None root = tree.insert(root, int(arr[0]), 'L') lis.append(root) k=0 for j in range(n): ptr = None ptr = tree.search(lis, int(arr[k])) lis.append(tree.insert(ptr, int(arr[k+1]), arr[k+2])) k+=3 # tree.traverseInorder(root) # print '' print(getLevelDiff(root)) ''' Please note that it's Function problem i.e. you need to write your solution in the form of Function(s) only. Driver Code to call/invoke your function is mentioned above. ''' # Your task is to complete this function # Function should return an integer def getLevelDiff(root): # Code here if not root: return 0 return (root.data - getLevelDiff(root.left) - getLevelDiff(root.right))
6cd7d926f04146ce263ca83633ba86046c6a014b
nickhand/cosmology
/cosmology/utils/functionator.py
7,836
3.640625
4
import scipy.interpolate import numpy as np class trapolator: """ The base class for the different extrapolating/interpolating classes. Parameters ---------- min_x : float, optional The minimum x value that the function is defined over. Default is ``None``, which is interpreted as min_x = -np.inf. max_x : float, optional The maximum x value that the function is defined over. Default is ``None``, which is interpreted as max_x = np.inf. """ def __init__(self, min_x=None, max_x=None): self.x_range = (min_x, max_x) def __call__(self, x): return self.get(x) def valid(self, x): """ Test whether the x value is within the domain specified by ``self.x_range`` """ x = np.asarray(x) if x.ndim == 0: return self.valid(np.array([x]))[0] ok = np.zeros(x.shape, 'bool') min_x, max_x = self.x_range if min_x is None: if max_x is None: # (-inf, inf) return np.ones(x.shape, 'bool') else: # (-inf, max) return x < max_x else: if max_x is None: # [min, inf) return x >= min_x else: # [min, max) return (x>=min_x)*(x<max_x) #endclass trapolator #------------------------------------------------------------------------------- class basicInterpolator(trapolator): """ Class to handle basic interpolation, with default interpolation of x, y(x) performed by scipy.interpolate.interp1d. Parameters ---------- x : array_like A 1-D array of monotonically increasing real values. y : array_like A 1-D array of real values, of len=len(x). min_x : float, optional The minimum x value that the function is defined over. Default is ``None``, which is interpreted as min_x = -np.inf. max_x : float, optional The maximum x value that the function is defined over. Default is ``None``, which is interpreted as max_x = np.inf. """ INTERP = scipy.interpolate.interp1d # use scipy.interpolate.interp1d YLOG = False # do x vs y(x) def __init__(self, x, y, min_x=None, max_x=None): if min_x is None: min_x = x.min() if max_x is None: max_x = x.max() trapolator.__init__(self, min_x, max_x) self.ylog = self.YLOG if self.ylog: y = np.log(y) self.interp = self.INTERP(x, y) def get(self, x): y = self.interp(x) if self.ylog: y = np.exp(y) return y #endclass basicInterpolator #------------------------------------------------------------------------------- # basicInterpolator does the interpolation in linear space linearInterpolator = basicInterpolator #------------------------------------------------------------------------------- class logInterpolator(basicInterpolator): """ Sub-class of ``basicInterpolator`` that uses scipy.interpolate.interp1d to interpolate x vs log(y(x)) """ YLOG = True #endclass logInterpolator #------------------------------------------------------------------------------- class splineInterpolator(basicInterpolator): """ Sub-class of ``basicInterpolator`` that uses scipy.interpolate.InterpolatedUnivariateSpline to interpolate x vs y(x) """ INTERP = scipy.interpolate.InterpolatedUnivariateSpline #endclass splineInterpolator #------------------------------------------------------------------------------- class splineLogInterpolator(splineInterpolator): """ Sub-class of ``splineInterpolator`` that uses scipy.interpolate.InterpolatedUnivariateSpline to interpolate x vs log(y(x)) """ YLOG = True #endclass splineLogInterpolator #------------------------------------------------------------------------------- class powerLawExtrapolator(trapolator): """ A class to perform power law extrapolations of a function. Parameters ---------- gamma : float, optional The power law index, such that ``y = A*x**gamma``. Default is 1. A : float, optional The amplitude of the power law fit, such that ``y = A*x**gamma``. Default is 1. min_x : float, optional The minimum x value that the function is defined over. Default is ``None``, which is interpreted as min_x = -np.inf. max_x : float, optional The maximum x value that the function is defined over. Default is ``None``, which is interpreted as max_x = np.inf. """ def __init__(self, gamma=1., A=1., min_x=None, max_x=None): trapolator.__init__(self, min_x=min_x, max_x=max_x) self.params = gamma, A def get(self, x): gamma, A = self.params return A*x**gamma #endclass powerLawExtrapolator #------------------------------------------------------------------------------- class exponentialExtrapolator(trapolator): """ A class to perform exponential extrapolations of a function. Parameters ---------- gamma : float, optional The exponential factor, such that ``y = A*exp(gamma*x)``. Default is 1. A : float, optional The amplitude of the fit, such that ``y = A*exp(gamma*x)``. Default is 1. min_x : float, optional The minimum x value that the function is defined over. Default is ``None``, which is interpreted as min_x = -np.inf. max_x : float, optional The maximum x value that the function is defined over. Default is ``None``, which is interpreted as max_x = np.inf. """ def __init__(self, gamma=-1., A=1., min_x=None, max_x=None): trapolator.__init__(self, min_x=min_x, max_x=max_x) self.params = gamma, A def get(self, x): gamma, A = self.params return A*np.exp(x*gamma) #endclass exponentialExtrapolator #------------------------------------------------------------------------------- class functionator(trapolator): """ A class to combine several different trapolators in order to model a full function. This is where the magic happens. Parameters ---------- min_x : float, optional The minimum x value that the function is defined over. Default is ``None``, which is interpreted as min_x = -np.inf. max_x : float, optional The maximum x value that the function is defined over. Default is ``None``, which is interpreted as max_x = np.inf. ops : array_like, optional List of the trapolator instances that will make up the function. """ def __init__(self, min_x=None, max_x=None, ops=[]): trapolator.__init__(self, min_x, max_x) self.ops = [] for op in ops: self.append(op) def append(self, op): self.ops.append(op) def get(self, x): x = np.asarray(x) if x.ndim == 0: return self.get(np.array([x]))[0] ok = np.zeros(x.shape, 'bool') y = np.zeros(x.shape, 'float') for op in self.ops: s = op.valid(x) if any(s): y[s] = op.get(x[s]) ok[s] = True if not all(ok): print 'Warning: functionator called out-of bounds' inds = (~ok).nonzero() print x[inds] return y def valid(self, x): x = np.asarray(x) if x.ndim == 0: return self.valid(array([x]))[0] ok = np.zeros(x.shape, 'bool') for op in self.ops: ok += op.valid(x) return ok #endclass functionator #-------------------------------------------------------------------------------
1b5d373e50f02ff16b614219cc212c126b1c3006
Mpprobst/Rumors
/source/objects/actor.py
26,516
3.65625
4
""" actor.py Purpose: Implements the data structures and mechanics of an actor """ import copy import sys import string from objects.relationship import Relationship from objects.area import Area from objects.rumor import Rumor import math import random class Actor(): # assumes it is given a .txt filename def __init__(self, filename=None, world=None): self.name = "You, the Player" self.shortname = "You" self.pronoun = "T" self.description = "" # a description of the character self.world = world self.eavsedropping = False self.starting_area = "" self.current_area = None self.rumors = [] self.action_log = [] self.relationships = [] # list of relationships the character has with all other characters. TODO: find where to initialize this list # dictionary of personality traits that influence the characters decisions. Always a value between 0 and 9 self.personality = { "trustworthy" : 5, # how likely others are to tell this character a rumor "talkative" : 5, # how likely the character is to tell a rumor "gullible" : 5, # how likely the character is to believe a rumor "nosy" : 5, # how likely the character is to seek out rumors from others "loyalty" : 5, # how likely a character is to tell a bad rumor about a character they like "fame" : 0, # how well known the character is "morality" : 5, # how 'good' the character is. this influences the likelihood to mutate a rumor. 0-3 is evil, 4-5 is neutral, 6-9 is good "memory" : 5, # how good a character is at retelling a rumor "perception" : 5, # how good a character is at understanding a rumor "opinion" : 5 # what characters generally think about this one } # initialize the character if filename != None: f = open(filename, "r") for line in f: line_array = line.split() item = line_array[0] value = " ".join(line_array[1:]) if item == "name": self.name = value names = value.split() if "the" in names: self.shortname = names[0] else: self.shortname = names[1] elif item == "pronoun": self.pronoun = value elif item == "area": self.starting_area = value elif item in self.personality: self.personality[item] = int(value) elif item == "description": self.description = value else: print(f'WARNING: trait {item} is not a valid trait') def start_relationship(self, char): self.relationships.append(Relationship(self, char)) def get_relationship(self, name): for r in self.relationships: if r.character.shortname == name: return r def hear_rumor(self, rumor, speaker=None, force_believe=False): #print(f'{self.shortname} hearing rumor {rumor.id}') if rumor == None: return existing_rumor = None unique_rumor = True r_idx = 0 for r in self.rumors: if r.exists(rumor): # I've heard this before rumor.id = r.id existing_rumor = r break r_idx += 1 if speaker == None: speaker = self rumor.listener = self #rumor.info(1) # TODO: now adjust relationships # find the action object in the rumor if isinstance(rumor.action, str): return #if rumor.action == None: # return action = rumor.action#self.world.find_action(rumor.action.name) # based on personality, choose how much to believe the rumor belief = 1 subj_rel = self.get_relationship(rumor.subject.shortname) obj_rels = [] for obj in rumor.objects: obj_rels.append(self.get_relationship(obj.shortname)) #if action == None: # return speaker_rel = self.get_relationship(rumor.speaker.shortname) s = "" if speaker_rel != None: s = f'1. Relationship of {self.shortname} and {speaker_rel.character.shortname}\n {speaker_rel.trust} {speaker_rel.admiration} {speaker_rel.love}' if not force_believe: trust_val = 0 admire_val = 0 love_val = 0 if subj_rel != None: trust_val = self.personality["gullible"] - (5 - int(subj_rel.trust/10)) admire_val = int(subj_rel.admiration/10) - (5 - self.personality["loyalty"]) love_val = int(subj_rel.love/10) if rumor.action.morality >= 5: belief += 1 if trust_val >= rumor.action.r_trust else 0 belief += 1 if admire_val >= rumor.action.r_admire else 0 belief += 1 if love_val >= rumor.action.r_love else 0 else: belief += 1 if trust_val < rumor.action.r_trust else 0 # gullible characters believe things belief += 1 if admire_val < rumor.action.r_admire else 0 # if low resepect and disloyal belief += 1 if love_val < rumor.action.r_love else 0 # if character hates other, believe it #belief += random.randint(0, 1) """print(f'ACTION: {action.name} is {"good" if rumor.action.morality > 5 else "bad"}\n'+ f'\ttrust: {trust_val} >= {action.r_trust}\n'+ f'\tadmire: {admire_val} >= {action.r_admire}\n'+ f'\tlove: {love_val} >= {action.r_love}\n'+ f'Belief: {belief}' ) print(f'{rumor.speaker.shortname} is telling {self.shortname} that {rumor.subject.shortname} {rumor.action.name} {rumor.objects[0].shortname}')#q belief: {belief}') """ if speaker_rel != None: if belief > 3: belief = 2 speaker_rel.Trust(5) speaker_rel.Love(3) #rumor.new_version(rumor.copy(), self.world) if existing_rumor == None: clone = rumor.copy() clone.versions.append(clone.copy()) self.rumors.append(clone) else: unique_rumor = existing_rumor.new_version(rumor, self.world) #print(f'{self.shortname} really believes it!\n') elif belief > 2: belief = 1 speaker_rel.Trust(2) #rumor.new_version(rumor.copy(), self.world) if existing_rumor == None: clone = rumor.copy() clone.versions.append(clone.copy()) self.rumors.append(clone) else: unique_rumor = existing_rumor.new_version(rumor, self.world) #print(f'{self.shortname} believes it.\n') elif belief > 1: belief = 0 speaker_rel.Trust(-3) #print(f'{self.shortname} doesn\'t believe it!\n') else: belief = 0 speaker_rel.Trust(-7) speaker_rel.Admiration(-4) #print(f'{self.shortname} doesn\'t believe it at all!\n') #print(s) #print(f'-->\n {speaker_rel.trust} {speaker_rel.admiration} {speaker_rel.love}') else: if speaker_rel != None: speaker_rel.Trust(2) #rumor.new_version(rumor.copy(), self.world) if existing_rumor == None: clone = rumor.copy() clone.versions.append(clone.copy()) self.rumors.append(clone) else: unique_rumor = existing_rumor.new_version(rumor, self.world) # relationship between the listener and the subject and objects need to change based on # their respective current relationships and the affectors of the action # ex: if someone the listener doesn't like does something intimate with someone # the listener does like, then the listener should like the person they like less. # if the listener loves the one character and hates the other, the listener should # hate the person they hate even more if the action between them is nefarious. # if the action between the subject and objects is a good action, the listener might # begin to like the character they hate. Special case is that there is nothing wrong with # love, but if the subject and object are in love and the listener loves one of them # then they can be jealous and begin to like them less. #print(f'2. Relationship of {self.shortname} and {subj_rel.character.shortname}\n {subj_rel.trust} {subj_rel.admiration} {subj_rel.love}') # listener should update their opinions on the characters invloved in the rumor # based on how they align with thier values # PRODUCE RESPONSE # morals_align = True if rumor.action.morality >= 5 and self.personality["morality"] < 5: morals_align = False if rumor.action.morality < 5 and self.personality["morality"] >= 5: morals_align = False like_ct = 0 for rel in obj_rels: if rel == None: continue if rel.likes(): like_ct += 1 likes_obj = like_ct >= len(rumor.objects) / 2 likes_sub = True if subj_rel != None: subj_rel.likes() response = f'{self.shortname}: ' if len(rumor.versions) > 0: response += f'Yeah I heard that from {rumor.versions[len(rumor.versions)-1].speaker.shortname}. ' if not unique_rumor else "" dont = "doesn\'t" if rumor.objects[0].pronoun != 'T' else "don\'t" if not morals_align: response += f'I\'m not surprised {rumor.subject.shortname} would do that.' if likes_sub else f'I can\'t believe {rumor.subject.get_pronoun1()} would do that!' response += f'But poor {rumor.objects[0].shortname}... {rumor.objects[0].get_pronoun1()} {dont} deserve that.' if likes_obj else f'{rumor.objects[0].shortname} got what they deserved!' belief *= -1 else: response += f'I\'m glad {rumor.subject.get_pronoun1()} did that!' if likes_sub else f'That\'s surprising!' response += f' {rumor.objects[0].shortname} deserved that!' if not likes_obj else f' Good for {rumor.objects[0].shortname}!' #elif abs(moral) >= 5: # someone with perfect morals (9) and a neutral action (5) shouln't think too differently # belief *= -1 if not unique_rumor: belief = 0 response += f' ({belief})' if subj_rel != None: subj_rel.Trust(int(action.subject_trust * belief / 2)) subj_rel.Admiration(int(action.subject_admire * belief / 2)) subj_rel.Love(int(action.subject_love * belief / 2)) for rel in obj_rels: if rel == None: continue rel.Trust(int(action.object_trust * belief / 2)) rel.Admiration(int(action.object_admire * belief / 2)) rel.Love(int(action.object_love * belief / 2)) if force_believe: print(response) return None #print(f'-->\n {subj_rel.trust} {subj_rel.admiration} {subj_rel.love}\n') def take_action(self): self.gossip() return None # choose wait, move, or gossip # probability array [p_wait, p_gossip, p_move, p_eavsedrop] p = [5, 5, 0, 0] # TODO: change p_move in final version when there are more characters # talkative people will want to tell a rumor p[1] += self.personality["talkative"] - 4 # if there are people in the area, nosy people are more likely to eavsedrop if len(self.current_area.occupants) >= 2: p[3] += self.personality["nosy"] - 4 else: # if the person is alone, don't gossip, but potentially move p[1] = 0 #p[2] += self.personality["nosy"]- 4 p[3] = 0 if len(self.rumors) == 0: p[1] = 0 if self.shortname == "Blair": p[2] = 0 #print(f'{self.name} action probs: {p}') total = sum(p) if total <= 0: total = 1 rand = random.randint(0, total) action = 0 for i in range(len(p)): if rand < p[i]: action = i break else: rand -= p[i] if action == 0: self.wait() elif action == 1: self.gossip() elif action == 2: self.move() elif action == 3: self.wait_to_eavsedrop() # do nothing def wait(self): #print(f'{self.name} waited') self.action_log.append("wait") # given an Area object def move(self, area=None): if area == None: area = random.choice(self.current_area.connections) if self.current_area != None: self.action_log.append("move") self.current_area.leave(self) #print(f'{self.name} moved from {self.current_area.name} to {area.name}') self.current_area = area area.enter(self) self.action_log.append(f'move to {self.current_area.name}') def select_listener(self, listeners): return random.choice(listeners) def mutate_character(self, og_char, likes): #print("mutate character") rels = self.relationships.copy() for r in rels: if likes and not r.likes(): rels.remove(r) elif not likes and r.likes(): rels.remove(r) if len(rels) > 0: rel = random.choice(rels) return rel.character return og_char def mutate_action(self, og_action, like_sub, like_obj): #print("mutate action") sub_thresh = og_action.sum_sub() obj_thresh = og_action.sum_obj() actions = self.world.actions.copy() for a in actions: sub_aff = a.sum_sub() obj_aff = a.sum_obj() # subject is liked, remove immoral or worse actions if like_sub and (a.morality < 4 or sub_thresh > sub_aff): actions.remove(a) # subject is hated, remove good or better actions elif not like_sub and (a.morality > 5 or sub_thresh < sub_aff): actions.remove(a) # object is liked, remove immoral or worse actions elif like_obj and (a.morality < 4 or obj_thresh > obj_aff): actions.remove(a) # object is hated, remove good or better actions elif not like_obj and (a.morality > 5 or obj_thresh < obj_aff): actions.remove(a) mutate_action = og_action if len(actions) > 0: mutate_action = random.choice(actions) return mutate_action def select_rumor(self, listener, about=None): # if listener is the player, tell them something about a specific character if specified rumors = [] if about != None: for rumor in self.world.rumors.copy(): object_names = [] for obj in rumor.objects: object_names.append(obj.shortname) if rumor.subject.shortname == about.shortname or about.shortname in object_names: rumors.append(rumor) # based on listener, select a rumor if listener != None: listener_rel = self.get_relationship(listener.shortname) if listener_rel == None: return None t_thresh = listener_rel.trust/10 # threshold for action trust a_thresh = listener_rel.admiration/10 # threshold for action admiration l_thresh = listener_rel.love/10 # threshold for action love # 2 or more thresholds must be exceeded to tell the rumor for rumor in rumors: thresh_ct = 0 if rumor.action.r_trust <= t_thresh: thresh_ct += 1 if rumor.action.r_admire <= a_thresh: thresh_ct += 1 if rumor.action.r_love <= l_thresh: thresh_ct += 1 thresh_ct += random.randint(0,1) if thresh_ct < 2: rumors.remove(rumor) ru = None if len(rumors) > 0: ru = random.choice(rumors) if listener.shortname == "You": return ru else: #print(f'{self.shortname} is making something up...') # make something up ru = Rumor(id=len(self.world.rumors)+1, speaker=self, listener=listener, location=random.choice(self.world.areas)) like_s = True if random.random() < 0.5 else False like_o = True if random.random() < 0.5 else False valid_actors = self.world.actors.copy() for a in valid_actors: if a.shortname == self.shortname or a.shortname == listener.shortname or a.shortname == "You": valid_actors.remove(a) ru.objects = list() rand_actor = random.choice(valid_actors) ru.objects.append(rand_actor) valid_actors.remove(rand_actor) rand_actor = random.choice(valid_actors) ru.subject = rand_actor ru.action = random.choice(self.world.actions) self.mutate_character(ru.objects[0], like_o) self.mutate_character(ru.subject, like_s) self.mutate_action(ru.action, like_s, like_o) ru.versions.append(ru.copy()) new_rumor = True for rumor in self.world.rumors: if rumor.exists(ru): new_rumor = False ru = rumor.copy() break if new_rumor: self.world.rumors.append(ru) #ru.info(1) #print("THAT WAS A LIE") sub_rel = self.get_relationship(ru.subject.shortname) obj_rels = [] if sub_rel == None: return ru like_ct = 0 for obj in ru.objects: rel = self.get_relationship(obj.shortname) if rel == None: continue obj_rels.append((rel, rel.likes())) if rel.likes(): like_ct += 1 likes_obj = like_ct >= len(ru.objects) / 2 likes_sub = sub_rel.likes() # if loyal: if self.personality["loyalty"] >= 5 and ru.action.morality <= 3: # if character likes a character that would be negatively affected, choose a better action if likes_sub: if self.personality["morality"] < 5: # change the character that is negatively affected with one they dont like. ru.subject = self.mutate_character(ru.subject, likes_sub) else: # choose action that has sum(newaction.affectors) > sum(oldaction.affectors) ru.action = self.mutate_action(ru.action, likes_sub, likes_obj) if likes_obj: if self.personality["morality"] < 5: # change the character that is negatively affected with one they dont like. for o in ru.objects: o = self.mutate_character(o, o.likes()) else: # choose action that has sum(newaction.affectors) > sum(oldaction.affectors) ru.action = self.mutate_action(ru.action, likes_sub, likes_obj) rand = random.randint(0, 9) twist = (9-self.personality["morality"]) if rand < twist: # if ill-moraled: ru.action = self.mutate_action(ru.action, likes_sub, likes_obj) """ if likes_obj and likes_sub: # if the character likes all characters involved in the rumor, they will want them to look good # choose an action where avg(affectors) > 1 and morality >= 5 ru.action = self.mutate_action(ru.action, likes_sub, likes_obj) elif likes_obj and not likes_sub: # if the character hates the subject and likes the objects, # twist action s.t. sum(subject_affectors) < sum(avg(object_affectors)) ru.action = self.mutate_action(ru.action, likes_sub, likes_obj) elif not likes_obj and likes_sub: # if the character likes the subject and hates the objects, # twist action s.t. sum(subject_affectors) > sum(avg(object_affectors)) ru.action = self.mutate_action(ru.action, likes_sub, likes_obj) else: # if the character hates all characters involved in the rumor, they will want them to all look bad. # choose action where avg(affectors) > 1 and morality < 5 ru.action = self.mutate_action(ru.action, likes_sub, likes_obj) """ # if the character doesn't like or respect the object or subject of the rumor, and are ill moraled, # then they are more likely to twist the rumor. But if they like the objects, # and are loyal, they will not intentionally twist the rumor return ru # tell another character a rumor. pick rumor from ones the agent knows def gossip(self): #print(f'{self.shortname} is gossiping') listeners = [] occupants = self.current_area.occupants.copy() for o in occupants: for a in self.world.available_actors: if a.shortname == o.shortname and a.shortname != "You" and a.shortname != self.shortname: listeners.append(o) #s="" #for a in listeners: # s += f'{a.shortname}, ' #print(f'{self.shortname} can interact with: {s}') if len(listeners) == 0: self.wait() return 0 listener = self.select_listener(listeners) #print(f'{self.shortname} interacted with {listener.shortname}') self.world.occupy_actor(listener) self.world.occupy_actor(self) #self.current_area.occupants.append(self) rumor = self.select_rumor(listener) if rumor == None: #print(f'no suitable rumor found') return rumor = rumor.copy() rumor.speaker = self listener.hear_rumor(rumor, self) self.action_log.append(f'tell {listener.shortname} a rumor') return def wait_to_eavsedrop(self): # wait until all other characeters have done their action, then find a rumor to hear self.eavsedropping = True self.action_log.append("eavsedrop") def eavsedrop(self): # find someone to listen to based on relationships self.eavsedropping = False #print(f'{self.name} eavsedrops') def ask(self, character, isRumor): if isRumor: """ # get a rumor rumors = [] # filter the rumors for rumor in self.rumors: names = [] for object in rumor.objects: names.append(object.shortname) names.append(rumor.subject.shortname) if character.shortname in names: rumors.append(rumor) if len(rumors) > 0: """ #return random.choice(rumors) return self.select_rumor(self.world.player_actor, character) else: return self.get_relationship(character.shortname) return None def get_pronoun1(self): if self.pronoun == "F": return "she" elif self.pronoun == "M": return "he" else: return "they" def get_pronoun2(self): if self.pronoun == "F": return "her" elif self.pronoun == "M": return "him" else: return "them" def introduce(self): if self.description == "": self.description = f'Hi, I\'m {self.shortname}, {self.get_pronoun1()}/{self.get_pronoun2()}' print(f'{self.shortname}: {self.description}') def info(self, options=[]): if len(options) == 0: options = ["p", "ru", "re"] print("+---------ACTOR---------+") print(f'Name: {self.name} ({self.get_pronoun1()}/{self.get_pronoun2()})') print(f'Current Location: {self.current_area.name}') if "p" in options: print(f'\nPERSONALITY:') for p in self.personality: num_tabs = 4 - math.floor((len(p)+3) / 4) if num_tabs == 1: num_tabs += 1 tabs = "" for t in range(num_tabs): tabs += "\t" print(f' {p}:{tabs}{self.personality[p]}') if "re" in options: print(f'\nRELATIONSHIPS') for i in range(len(self.relationships)): r = self.relationships[i] print(f'{i+1}. {r.character.shortname}') print(f' trust: {r.trust}\n' + f' admiration: {r.admiration}\n' + f' love: {r.love}' ) if "ru" in options: print(f'\nRUMORS:') for i in range(len(self.rumors)): rumor = self.rumors[i] if rumor != None: print(f'RUMOR: {i+1}') rumor.info(1) print("+-----------------------+\n")
231c893ab6b0d51d7490acdae93f6ce9c5ca459e
santiagoom/leetcode
/solution/python/129_SumRoottoLeafNumbers_1.py
890
3.5625
4
from typing import List from utils import * class Solution_129_SumRoottoLeafNumbers_1: def sumNumbers(self, root: TreeNode): root_to_leaf = 0 stack = [(root, 0) ] while stack: root, curr_number = stack.pop() if root is not None: curr_number = curr_number * 10 + root.val # if it's a leaf, update root-to-leaf sum if root.left is None and root.right is None: root_to_leaf += curr_number else: stack.append((root.right, curr_number)) stack.append((root.left, curr_number)) return root_to_leaf if __name__ == "__main__": nums = [2, 7, 11, 15] target = 26 s = "aa" arrays = [[1, 2, 3], [4, 5, 6]] print(arrays)
c6c473cde684ad25f6184fc0adf934984e1c4aa7
shigithub/buildscript2
/zipper.py
608
3.578125
4
import os, sys, zipfile from zipfile import ZipFile as zip def zipAll(zipName, outputDir): z = zip(zipName, 'w', zipfile.ZIP_DEFLATED) for root, dirs, files in os.walk(outputDir): for file in files: absPath = os.path.join(root, file) z.write(os.path.join(root, file), os.path.relpath(absPath, outputDir)) z.close() def unzipAll(zipName, outputDir): z = zip(zipName) z.extractall(outputDir) op = sys.argv[1] inputFile = sys.argv[2] outputDir = sys.argv[3] if op == 'zip': zipAll(inputFile, outputDir) elif op == 'unzip': unzipAll(inputFile, outputDir)
520cb94d14660c93b05511d36a91bc3f8d0ea3b6
imhyo/codejam
/kruskal.py
499
3.53125
4
from graph import Graph from union_find import UnionFind # Kruskal's minimum spanning tree algorithm def kruskal(graph): ret = 0 result = [] edges = [] for u in graph: for v, c in graph[u]: edges.append((u, v, c)) edges.sort(key=lambda x: x[2]) uf = UnionFind(len(graph.V)) for u, v, c in edges: if uf.find(u) == uf.find(v): continue uf.union(u, v) result.append((u, v)) ret += c return ret, result
1ce2b83586c1513dbab3e2f3c9e132bf1605489e
yzl232/code_training
/mianJing111111/geeksforgeeks/array/Find the smallest and second smallest element in an array_find the second largest element in an array.py
845
3.78125
4
# encoding=utf-8 ''' 如果是找2个,或者3个。都是类似解法。 Write an efficient C program to find smallest and second smallest element in an array. Difficulty Level: Rookie Algorithm: 1) Initialize both first and second smallest as INT_MAX first = second = INT_MAX 2) Loop through all the elements. a) If the current element is smaller than first, then update first and second. b) Else if the current element is smaller than second then update second ''' class Solution: def print2Smallest(self, arr): n =len(arr) if n<2: return first=second = float('inf') for i in range(n): if arr[i] <= first: second, first = first, arr[i] elif arr[i]<second: second = arr[i] if second==10**10: print 'only one element' print first, second
4ebeaac59bdcba607c5b31d89ce0f5fc6fbfc719
arieldunn/PyMeUpCharlie
/PyBank/main.py
2,327
4
4
import os # Module for reading CSV files import csv import statistics csvpath = os.path.join('Resources', 'budget_data.csv') # # Method 1: Plain Reading of CSV files # with open(csvpath, 'r') as file_handler: # lines = file_handler.read() # print(lines) # print(type(lines)) # Method 2: Improved Reading using CSV module # make empty buckets total = [] months = [] month_change = [] # make calculation for average def average (numbers): total = 0.0 for number in numbers: total += number find_average = total/len(numbers) return find_average with open(csvpath) as csvfile: # CSV reader specifies delimiter and variable that holds contents csvreader = csv.reader(csvfile, delimiter=',') print(csvreader) # Read the header row first (skip this step if there is now header) csv_header = next(csvreader) print(f"CSV Header: {csv_header}") # Read each row of data after the header # append rows for row in csvreader: months.append(row[0]) total.append(row[1]) month_change.append(int(row[1])) # find net amount profit and losses total_revenue = 0 for values in total: total_revenue += int(values) print(f'Total Profits/Losses: ${total_revenue}') net_revenue = [j-i for i,j in zip(month_change[:-1], month_change[1:])] print(f'Average Change: ${round(average(net_revenue),2)}') net_revenue.sort(reverse=True) print(f'Total Months: {len(months)}') print(f'The greatest increase in profits: ${net_revenue[0]}') print(f'The greatest decrease in profits: ${net_revenue[len(net_revenue)-1]}') # output output_path = 'Financial Analysis.txt' with open(output_path, 'w', newline ='') as csvfile: csvwriter = csv.writer(csvfile, delimiter=',') csvwriter.writerow(['Financial Analysis']) csvwriter.writerow(["------------------------------------------------------"]) csvwriter.writerow([f'Total Months: {len(months)}']) csvwriter.writerow([f'Total Profits/Losses: ${total_revenue}']) csvwriter.writerow([f'Average Change: ${round(average(net_revenue),2)}']) csvwriter.writerow([f'The greatest increase in profits: ${net_revenue[0]}']) csvwriter.writerow([f'The greatest decrease in profits: ${net_revenue[len(net_revenue)-1]}'])
23899a7dae4b0600416186cbc5ebc80fca5e3f9f
wonjongah/multicampus_IoT
/인터페이스 실습코드/workspace/workspace/01_python/chapter15/ex02.py
971
4.0625
4
class Stack: def __init__(self, size=5): self.data = [] self.size = size def push(self, push_value): if len(self.data) == self.size: # full print("스택이 가득 찼습니다. pop()을 통해 지워주세요") return else: self.data.append(push_value) print(push_value, "값 푸쉬") def pop(self): if len(self.data) == 0: # empty print("스택이 비어있습니다. push()를 통해 값을 채워넣을세요") return else: self.data.pop() print("pop!") def clear(self): self.data = [] print("클리어") def print_car(self): print(self.data) def __str__(self): return f"<Stack size:({self.size}), data:({self.data})>" def main(): s1 = Stack() s1.push(5) s1.push(2) print(s1) s1.pop() print(s1) s1.clear() s1.pop() main()
1042a1baabe1082977c5059f3cd1faa05cf4a6ef
MOIPA/MyPython
/practice/function_class/function.py
4,185
4.3125
4
''' 方法的参数问题:变长参数 ''' # default arguments import types def student(name, age, city='none', sex='m'): pass # enroll student('tr', 18) student('tr', 18, city='bj') # changable arguments def calc(*num): for n in num: print(n) calc(1) calc(1, 2) # changable arguments by ** def person(name, age, **arg): print(name) print(arg) person('tr', 18, city='333') # ***********************************note # 默认参数很有用,但使用不当,也会掉坑里。默认参数有个最大的坑,演示如下: # 先定义一个函数,传入一个list,添加一个END再返回: def add_end(L=[]): L.append('END') return L # 当你正常调用时,结果似乎不错: add_end([1, 2, 3]) [1, 2, 3, 'END'] add_end(['x', 'y', 'z']) ['x', 'y', 'z', 'END'] # 当你使用默认参数调用时,一开始结果也是对的: add_end() ['END'] # 但是,再次调用add_end()时,结果就不对了: add_end() ['END', 'END'] add_end() ['END', 'END', 'END'] # 很多初学者很疑惑,默认参数是[],但是函数似乎每次都“记住了”上次添加了'END'后的list。 # 原因解释如下: # Python函数在定义的时候,默认参数L的值就被计算出来了,即[],因为默认参数L也是一个变量,它指向对象[],每次调用该函数,如果改变了L的内容,则下次调用时,默认参数的内容就变了,不再是函数定义时的[]了。 # 所以,定义默认参数要牢记一点:默认参数必须指向不变对象! # 要修改上面的例子,我们可以用None这个不变对象来实现: def add_end_new(L=None): if L is None: L = [] L.append('END') return L # 现在,无论调用多少次,都不会有问题: # 可变参数调用calc( *nums) **************************** def calc(*num): for i in num: print("%d" % i) # calc(0,1) # 如果这时候是一个list怎么办 nums = [0, 1, 2, 3] calc(*nums) # 关键字参数×××××××××××××××××××××××××××××××××××××× # 可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。而关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict。 def person(name, age, **kwargs): print('name', name, 'age', age, 'kw', kwargs) # person('mic',18) # 这时候瞎传一些参数也可以,但是瞎传的参数要带上关键字,不然咋叫关键字参数 # 这些参数带关键字,那么肯定可以传入dict参数 person('mic', 18, sis=18, nickname='gg') # dict参数传入,但是参数前要使用** kw = {'kw1': 1, 'kw2': '2'} person('tr', 18, **kw) # ****************************** # 参数组合 # 在Python中定义函数,可以用必选参数、默认参数、可变参数和关键字参数,这4种参数都可以一起使用,或者只用其中某些,但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数和关键字参数。 # 比如定义一个函数,包含上述4种参数: def func(a, b, c=0, *args, **kw): print 'a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw # 在函数调用的时候,Python解释器自动按照参数位置和参数名把对应的参数传进去。 >> > func(1, 2) a = 1 b = 2 c = 0 args = () kw = {} >> > func(1, 2, c=3) a = 1 b = 2 c = 3 args = () kw = {} >> > func(1, 2, 3, 'a', 'b') a = 1 b = 2 c = 3 args = ('a', 'b') kw = {} >> > func(1, 2, 3, 'a', 'b', x=99) a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99} # 最神奇的是通过一个tuple和dict,你也可以调用该函数: >> > args = (1, 2, 3, 4) >> > kw = {'x': 99} >> > func(*args, **kw) a = 1 b = 2 c = 3 args = (4,) kw = {'x': 99} # 所以,对于任意函数,都可以通过类似func(*args, **kw)的形式调用它,无论它的参数是如何定义的。 ''' type 关键字 ''' type('123') = types.StringType type([]) = types.ListType ''' dir 函数查看所有属性 hasattr 函数 查看是否有某个属性 ''' info = dir('acd') hasattr('acd','upper')
bcc1c47a37645857067be3b40cf1e7a3076d779f
ryanthomasdonald/python
/week-1/homework/python101_RyanDonald.py
3,052
4.25
4
print("\r") print("***))) Exercise 1 (((***") # Prints fancy titles!!! print("\r") cost = float(input("What is the final total of your meal? $")) service = input("Was your service good, fair, or bad? ") if service.lower() == "good": tip = cost * 0.2 elif service.lower() == "fair": tip = cost * 0.15 elif service.lower() == "bad": tip = cost * 0.1 else: print("Please restart the calculator and provide valid answers.") exit() total = cost + tip print("Tip amount: $" + "%.2f" % tip) print("Total amount: $" + "%.2f" % total) print("\r") print("***))) Exercise 2 (((***") print("\r") cost = float(input("What is the final total of your meal? $")) service = input("Was your service good, fair, or bad? ") people = float(input("How many people are splitting the check? ")) if service.lower() == "good": tip = cost * 0.2 elif service.lower() == "fair": tip = cost * 0.15 elif service.lower() == "bad": tip = cost * 0.1 else: print("Please restart the calculator and provide valid answers.") exit() total = cost + tip split = total / people print("Tip amount: $" + "%.2f" % tip) print("Total amount: $" + "%.2f" % total) print("Amount per person: $" + "%.2f" % split) print("\r") print("***))) Exercise 3 (((***") print("\r") coins = 0 print(f"You have {coins} coins.") answer = input("Would you like a coin? Type 'yes' or 'no'. ") while answer.lower() == "yes": coins += 1 print(f"You have {coins} coins.") answer = input("Would you like another coin? Type 'yes' or 'no'. ") print(f"Don't spend all {coins} coins in one place!") print("\r") print("***))) Exercise 4 (((***") print("\r") # I modified this to insert some horizontal spaces into the box, just FYI. print("BOX TIME!!!") width = int(input("Width? ")) height = int(input("Height? ")) visible_height = height - 1 empty_space = (width - 2) * " " print("* " * width) while visible_height - 1 > 0: print(f"*{empty_space} *") visible_height -= 1 print("* " * width) print("\r") print("***))) Exercise 5 (((***") print("\r") space = " " star = "*" print(f"{space * 3}" + star) print(f"{space * 2}" + f"{star * 3}") print(f"{space}" + f"{star * 5}") print(f"{star * 7}") print("\r") print("***))) Exercise 6 (((***") print("\r") count = 1 while count <= 10: ans1 = (f"{count * 1}") print(str(count) + " X 1 = " + str(ans1)) ans2 = (f"{count * 2}") print(str(count) + " X 2 = " + str(ans2)) ans3 = (f"{count * 3}") print(str(count) + " X 3 = " + str(ans3)) ans4 = (f"{count * 4}") print(str(count) + " X 4 = " + str(ans4)) ans5 = (f"{count * 5}") print(str(count) + " X 5 = " + str(ans5)) ans6 = (f"{count * 6}") print(str(count) + " X 6 = " + str(ans6)) ans7 = (f"{count * 7}") print(str(count) + " X 7 = " + str(ans7)) ans8 = (f"{count * 8}") print(str(count) + " X 8 = " + str(ans8)) ans9 = (f"{count * 9}") print(str(count) + " X 9 = " + str(ans9)) ans10 = (f"{count * 10}") print(str(count) + " X 10 = " + str(ans10)) count += 1
98ff1ed9d4216df74093ace8866bd9fd3fd9c7a1
Sidheartt/py
/dog.py
362
4.1875
4
Create a basic function that returns True if the word 'dog' is contained in the input string. Don't worry about edge cases like a punctuation being attached to the word dog, but do account for capitalization def findDog(var): if 'dog' in var.lower().split(): return True else: return False findDog('Is there a dog here?')
2e1c6e4402cb9ffbebe2cad51f9b9d8044d246fc
arduino-monkey/6.0001-MIT-EDX-pset-solutions
/pset1/problem3.py
476
3.8125
4
temp = '' lis = [] orignal_word = s for i in range(len(s)): temp = '' for i in range(len(s)-1): if s[i] <= s[i+1]: temp += s[i] else: temp += s[i] lis.append(temp) s = s[i+1:] break longest = '' for i in lis: if len(i) > len(longest): longest = i if len(lis) == 0: longest = orignal_word print('Longest substring in alphabetical order is:',longest)
8ebcc827142bc94f4ace1344862e04f18d61cd76
artificiallifeform/asm
/dec_to_bin.py
488
3.609375
4
def dec_to_bin(num): divisor = num bits = [] if num > 0: while divisor != 1: temp = divisor % 2 bits.insert(0, str(temp)) divisor = int((divisor - temp) / 2) # pdb.set_trace() bits.insert(0, '1') for i in range(16 - len(bits)): bits.insert(0, '0') result = ''.join(bits) return result def hello(): print('Hello') # 10 / 2 0 # 5 / 2 1 # 2 / 2 0 # 1 / 2 1 # 10 ->> 1010
f125a0dba4b43b81211e588c7f91b64751866dde
Scott8440/490Project
/tests/line_test.py
3,871
3.53125
4
import unittest from py.CodeLine import CodeLine from py.LineTypes import LineTypes class TestLineMethods(unittest.TestCase): lineNumber = 7 # Dummy lineNumber indentation = 1 # Dummy indentation def testLineCreation(self): string = "this is a line" line = CodeLine(string, self.lineNumber, self.indentation) self.assertEqual(line.line, string) self.assertEqual(line.lineNumber, self.lineNumber) def testBasicVariableParsing(self): string = "var = 2" line = CodeLine(string, self.lineNumber, self.indentation) variables = line.extractVariables() self.assertEqual(len(variables), 1) self.assertEqual(variables[0], "var") def testComplicatedVariableParsing(self): string = "self.x = x" line = CodeLine(string, self.lineNumber, self.indentation) variables = line.extractVariables() self.assertEqual(len(variables), 1) self.assertEqual(variables[0], "self.x") def testNoParseVariableInStringType(self): string = "var = 2" # Assume this has been parsed as a part of a multiline string line = CodeLine(string, self.lineNumber, self.indentation, LineTypes.CONTINUES_MULTILINE_STRING) variables = line.extractVariables() self.assertEqual(len(variables), 0) def testRemoveSimpleString(self): string = "var = 'this is a string'" line = CodeLine(string, self.lineNumber, self.indentation) strippedLine = line.removeStrings() correctStrip = "var = " self.assertEqual(strippedLine, correctStrip) def testRemoveStringWithNoString(self): string = "var = x" line = CodeLine(string, self.lineNumber, self.indentation) stripped = line.removeStrings() self.assertEqual(line.line, stripped) def testRemoveStringWithEscapeChar(self): txtFile = open('escapeCharacterLine.txt', 'r') string = txtFile.readline().rstrip() txtFile.close() line = CodeLine(string, self.lineNumber, self.indentation) stripped = line.removeStrings() correctStrip = "var = " self.assertEqual(stripped, correctStrip) def testRemoveMultipleStrings(self): string = 'var1 = "hello", var2 = "goodbye"' line = CodeLine(string, self.lineNumber, self.indentation) stripped = line.removeStrings() correctStrip = 'var1 = , var2 = ' self.assertEqual(stripped, correctStrip) def testRemoveStringThatDoesntEnd(self): string = 'var1 = "hello\\\n' line = CodeLine(string, self.lineNumber, self.indentation) stripped = line.removeStrings() correctStrip = 'var1 = \n' self.assertEqual(stripped, correctStrip) def testGetsVariableInStringStartType(self): string = 'multiline = """ start of string' line = CodeLine(string, self.lineNumber, self.indentation, LineTypes.STARTS_DOUBLE_MULTILINE_STRING) variables = line.extractVariables() self.assertEqual(len(variables), 1) self.assertEqual(variables[0], 'multiline') def testIgnoresStringVariableInStringStartType(self): string = 'multiline = """ var = x' line = CodeLine(string, self.lineNumber, self.indentation, LineTypes.STARTS_DOUBLE_MULTILINE_STRING) variables = line.extractVariables() self.assertEqual(len(variables), 1) self.assertEqual(variables[0], 'multiline') def testHandlesCompleteMultilineOnOneLine(self): string = 'multiline = """ bad_var = x """, var = x' line = CodeLine(string, self.lineNumber, self.indentation) variables = line.extractVariables() self.assertEqual(len(variables), 2) self.assertEqual(variables[0], 'multiline') self.assertEqual(variables[1], 'var') if __name__ == '__main__': unittest.main()
2d9e0ddec477eae94658f7f377799db4d63f4b71
suddi/coding-challenges
/python/data_structures/stack.py
6,376
4.0625
4
class Stack(): def __init__(self, value=None): # O(1) if value is not None: # O(1) self.stack = [value] # O(1) self.length = 1 # O(1) else: # O(1) self.stack = [] # O(1) self.length = 0 # O(1) def get_length(self): # O(1) """ Returns the length of the Stack >>> Stack(42).insert(22).insert(12).insert(95).insert(1).get_length() 5 """ return self.length # O(1) def pretty_print(self): # O(N) """ Pretty prints Stack values sequentially >>> Stack(42).pretty_print() 42 """ string = '' # O(1) for count, value in enumerate(self.stack): # O(N) string += str(value) + ' ' # O(1) if count < self.length - 1: # O(1) string += '-> ' # O(1) if string: # O(1) print(string.strip()) # O(1) def access(self, position): # O(N) """ Accesses Stack at a given position >>> Stack(42).insert(31).insert(30).access(20) Traceback (most recent call last): Exception: Cannot find non-existent position 20 in Stack >>> Stack(42).insert(31).insert(30).access(-1) Traceback (most recent call last): Exception: Cannot find non-existent position -1 in Stack >>> Stack(42).insert(22).insert(12).insert(95).insert(1).access(3) 95 """ if position >= self.length or position < 0: raise Exception('Cannot find non-existent position ' \ + '%d in Stack' % position) # O(1) for count, stack_value in enumerate(self.stack): # O(N) if count == position: # O(1) return stack_value # O(1) return -1 # O(1) def search(self, value): # O(N) """ Searches for value in Stack and returns position >>> Stack(42).insert(31).insert(30).search(31) 1 >>> Stack(42).insert(22).insert(12).insert(95).insert(1).search(22) 1 >>> Stack(42).insert(22).insert(12).insert(95).insert(1).search(52) -1 """ for count, stack_value in enumerate(self.stack): # O(N) if stack_value == value: # O(1) return count # O(1) return -1 # O(1) def insert(self, value): # O(1) """ Inserts value into the Stack, only possible at the end Insert covers 1 case: 1) Insert at the end of the Stack # O(1) >>> Stack(42).insert(31).insert(30).pretty_print() 42 -> 31 -> 30 >>> Stack(42).insert(22).insert(12).insert(95).insert(1).pretty_print() 42 -> 22 -> 12 -> 95 -> 1 """ self.stack.append(value) # O(1) self.length += 1 # O(1) return self # O(1) def delete(self): # O(1) """ Deletes value in Stack, only possible at the end Delete covers 1 case: 1) Delete at the end of the Stack # O(1) >>> Stack(42).insert(31).insert(30).delete().delete().pretty_print() 42 >>> Stack(42).insert(22).insert(12).insert(95).insert(1) \ .delete().delete().delete().pretty_print() 42 -> 22 >>> Stack(42).insert(22).insert(12).insert(95).insert(1) \ .delete().delete().delete().delete().delete().delete().delete() \ .delete().pretty_print() """ if self.length: # O(1) self.stack.pop() # O(1) self.length -= 1 # O(1) return self # O(1) def push(self, value): # O(1) """ Push a value at the end of the stack to demonstrate LIFO capability of Stack >>> Stack(42).push(31).push(30).pretty_print() 42 -> 31 -> 30 >>> Stack(42).push(22).push(12).push(95).push(1).pretty_print() 42 -> 22 -> 12 -> 95 -> 1 """ self.stack.append(value) # O(1) self.length += 1 # O(1) return self # O(1) def pop(self): # O(1) """ Pop a value out at the of the stack to demonstrate LIFO capability of Stack >>> Stack(42).push(31).push(30).pop() 30 >>> Stack(42).push(22).push(12).push(95).push(1).pop() 1 >>> Stack().pop() """ if not self.length: # O(1) return None # O(1) value = self.stack.pop() # O(1) self.length -= 1 # O(1) return value # O(1) if __name__ == '__main__': import doctest doctest.testmod()
d2389fe830d1a70f160f41f1bb75cb1fb188eb96
bucho666/pyrl
/demo/consoledemo.py
1,101
3.53125
4
# -*- coding: utf-8 -*- import parentpath import random import coord from console import Console from console import Color class Walk(object): KeyMap = { "h": (-1, 0), "j": (0, 1), "k": (0, -1), "l": (1, 0), "y": (-1, -1), "u": (1, -1), "b": (-1, 1), "n": (1, 1) } def __init__(self): self._coord = (1, 1) self._console = Console().colorOn().nonBlocking() def run(self): self.render() interval = int(1000/30) while True: self.update() self._console.sleep(interval) def update(self): key = self._console.getKey() coord.sum(self._coord, Walk.KeyMap.get(key, (0, 0))) self.render() def render(self): self._console.clear() self._console.move((1, 2)).write("+", Color.LIGHT_YELLOW) self._console.move((3, 4)).write("T", Color.GREEN, Color.BLUE) self._console.move((5, 6)).write("*", Color.LIGHT_YELLOW, Color.GREEN) self._console.move((7, 8)).write("&", random.choice(list(Color.LIST))) self._console.move(self._coord).write("@", Color.LIGHT_YELLOW).move(self._coord) if __name__ == '__main__': Walk().run()
7f8043d4f32a9fc5619d8590fdad50e924eb0994
BhaveshChand/cs50-edx
/pset6/vigenere.py
690
3.84375
4
import cs50 import sys def main(): if len(sys.argv)!=2 or not str.isalpha(sys.argv[1]): print("Usage: python vigenere.py k") exit(1) key=str.upper(sys.argv[1]) ptext=cs50.get_string("plaintext: ") ctext=[] j=0 for c in ptext: if str.islower(c): ctext.append(chr(((ord(c)-ord('a')+ord(key[j%len(key)])-ord('A'))%26)+ord('a'))) j+=1 elif str.isupper(c): ctext.append(chr(((ord(c)-ord('A')+ord(key[j%len(key)])-ord('A'))%26)+ord('A'))) j+=1 else: ctext.append(c) ctext=''.join(ctext) print("ciphertext: "+ctext) exit(0) if __name__=="__main__": main()
368f13db6a7fecbc1e231f92fded0af15ac3ba30
sdvacap/Python--Spring2020
/average.py
960
4.34375
4
#average.py #Calculate average #Sarah Vaca #February 24,2020 #Part 1 #Using a for loop and range, calculate the mean of all the numbers between 1 and 20 (include number 1 to 20) #Calculation of sum #Print results #enter number to calculate sum 0 #ANSWER sum=0 for num in range(1,21): sum=sum+num #sum of 0 plus each number in the range(1,21) print("Sum of numbers is: ", sum) #Sum of numbers from 1 to 20 = TOTAL 210 ANSWER #Calculation of average #Print results sum = 0 for num in range(1,21): sum = sum+num; average = sum / 20 print("Average is: ", average) #Part 2 #Do the same thing without a loop with fewer lines of code(HINT: might have to use a command in a module) #Try to make your code clean #use the module "statistics" import statistics average=statistics.mean(range(1,21)) #for calculate the average of the number between 1 an 20 print(average)
bfa1036e61d3190c0cce234b5eab3e67099c2b14
viswambhar-yasa/AuToDiFf
/test_NN.py
5,278
3.71875
4
""" Author: Viswambhar Yasa Basically all the test cases below have same structure. Aim : To test the forward propagation of the Neural Network Expected : The calculations are done for a Neural Network with one hidden layer whose weights are set to 1. Obtained : The output of the Neural Network class Remarks: Each test case employs different set of inputs. """ import autodiff as ad import numpy as np from NN_architecture import * import pytest def Sigmoid(x): return 1/(1+np.exp(-x)) def test_sigmoid_is_true(): x = 0 y=0.5 yf = Sigmoid(x) flag = np.array_equal(y,yf) assert flag == True """ def test_NN1_forward_prop_ones_init_is_true1(): model = NeuralNetLSTM(2,0,2,1) wts = model.get_weights() model.set_weights([np.ones_like(i()) for i in wts]) X=np.array([[0.5,0.5]]) W = np.ones((2,2)) B = np.ones((1,2)) S = Sigmoid(np.dot(X,W) + B ) Z= Sigmoid(np.dot(X,W)+np.dot(S,W) + B) G = np.copy(Z) R = np.copy(G) H = Sigmoid(np.dot(X,W)+np.dot(S*R,W)+B) Snew = ((np.ones_like(G)-G)*H) + (Z*S) Wf = np.ones((2,1)) Bf = np.ones(1) output = np.dot(Snew,Wf) + Bf print(output) print(model.output(X)()) flag = np.array_equal(output,model.output(X)() ) assert flag==True """ def test_NN1_forward_prop_ones_init_is_true2(): model = NeuralNetLSTM(2,0,2,1) wts = model.get_weights() model.set_weights([np.ones_like(i()) for i in wts]) X=np.array([[0,0]]) W = np.ones((2,2)) B = np.ones((1,2)) S = Sigmoid(np.dot(X,W) + B ) Z= Sigmoid(np.dot(X,W)+np.dot(S,W) + B) G = np.copy(Z) R = np.copy(G) H = Sigmoid(np.dot(X,W)+np.dot(S*R,W)+B) Snew = ((np.ones_like(G)-G)*H) + (Z*S) Wf = np.ones((2,1)) Bf = np.ones(1) output = np.dot(Snew,Wf) + Bf flag = np.array_equal(output,model.output(X)() ) assert flag==True def test_NN1_forward_prop_ones_init_is_true4(): model = NeuralNetLSTM(2,0,2,1) wts = model.get_weights() model.set_weights([np.ones_like(i()) for i in wts]) X=np.array([[-100.1894,-100.54]]) W = np.ones((2,2)) B = np.ones((1,2)) S = Sigmoid(np.dot(X,W) + B ) Z= Sigmoid(np.dot(X,W)+np.dot(S,W) + B) G = np.copy(Z) R = np.copy(G) H = Sigmoid(np.dot(X,W)+np.dot(S*R,W)+B) Snew = ((np.ones_like(G)-G)*H) + (Z*S) Wf = np.ones((2,1)) Bf = np.ones(1) output = np.dot(Snew,Wf) + Bf flag = np.array_equal(output,model.output(X)() ) assert flag==True def test_layer_NN1_ones_init_is_true1(): X=np.array([[100,100]]) W = np.ones((2,2)) B = np.ones((1,2)) S = Sigmoid(np.dot(X,W) + B ) Z= Sigmoid(np.dot(X,W)+np.dot(S,W) + B) G = np.copy(Z) R = np.copy(G) H = Sigmoid(np.dot(X,W)+np.dot(S*R,W)+B) Snew = ((np.ones_like(G)-G)*H) + (Z*S) print(Snew) layer = lstm_layer(2,2) wts = layer.get_weights_layer() layer.set_params_layer([np.ones_like(i()) for i in wts]) S = ad.Variable(S,"S") X=ad.Variable(X,"X") output = layer.output_layer(S,X) print(output()) flag = np.array_equal(output(),Snew) assert flag == True def test_layer_NN1_ones_init_is_true2(): X=np.array([[-0.1548484,0.494]]) W = np.ones((2,2)) B = np.ones((1,2)) S = Sigmoid(np.dot(X,W) + B ) Z= Sigmoid(np.dot(X,W)+np.dot(S,W) + B) G = np.copy(Z) R = np.copy(G) H = Sigmoid(np.dot(X,W)+np.dot(S*R,W)+B) Snew = ((np.ones_like(G)-G)*H) + (Z*S) print(Snew) layer = lstm_layer(2,2) wts = layer.get_weights_layer() layer.set_params_layer([np.ones_like(i()) for i in wts]) S = ad.Variable(S,"S") X=ad.Variable(X,"X") output = layer.output_layer(S,X) print(output()) flag = np.array_equal(output(),Snew) assert flag == True def test_layer_NN1_ones_init_is_true3(): X=np.array([[10000,1000000]]) W = np.ones((2,2)) B = np.ones((1,2)) S = Sigmoid(np.dot(X,W) + B ) Z= Sigmoid(np.dot(X,W)+np.dot(S,W) + B) G = np.copy(Z) R = np.copy(G) H = Sigmoid(np.dot(X,W)+np.dot(S*R,W)+B) Snew = ((np.ones_like(G)-G)*H) + (Z*S) print(Snew) layer = lstm_layer(2,2) wts = layer.get_weights_layer() layer.set_params_layer([np.ones_like(i()) for i in wts]) S = ad.Variable(S,"S") X=ad.Variable(X,"X") output = layer.output_layer(S,X) print(output()) flag = np.array_equal(output(),Snew) assert flag == True def test_layer_NN1_ones_init_is_true4(): X=np.array([[616464516,45461616]]) W = np.ones((2,2)) B = np.ones((1,2)) S = Sigmoid(np.dot(X,W) + B ) Z= Sigmoid(np.dot(X,W)+np.dot(S,W) + B) G = np.copy(Z) R = np.copy(G) H = Sigmoid(np.dot(X,W)+np.dot(S*R,W)+B) Snew = ((np.ones_like(G)-G)*H) + (Z*S) print(Snew) layer = lstm_layer(2,2) wts = layer.get_weights_layer() layer.set_params_layer([np.ones_like(i()) for i in wts]) S = ad.Variable(S,"S") X=ad.Variable(X,"X") output = layer.output_layer(S,X) print(output()) flag = np.array_equal(output(),Snew) assert flag == True
7935f38e9bd6067322eec534d90b66d52888b0f3
amax14/Codewars-Katas
/kata5.py
766
3.890625
4
def find_short(s): l=0 sstr=[] sl = [] for w in s.split(): sstr.append(w) sl = sorted(sstr, key=len) l = len(sl[0]) return l # l: shortest word length def find_short1(s): s2=[] sl = [len(x) for x in s.split()] for x in s.split(): s2.append(len(x)) print(sl) print(s2) return min(sl) print(find_short1("bitcoin take over the world maybe who knows perhaps")) print(find_short("turns out random test cases are easier than writing out basic ones")) print(find_short("lets talk about javascript the best language")) print(find_short("i want to travel the world writing code one day")) print(find_short("Lets all go on holiday somewhere very cold"))
89be9747fd60ed15b137bd6092e537d5d299cfed
srihariprasad-r/workable-code
/Practice problems/foundation/recursion/printkeypadcombinations.py
500
3.515625
4
def printkeypadcombinations(str,ans): if len(str) == 0: print(ans) return ch = str[0] rest = str[1:] chr_from_dict = dict[int(ch)] for i in range(len(chr_from_dict)): printkeypadcombinations(rest, ans + chr_from_dict[i]) dict = { 1 : 'abc', 2 : 'def' , 3 : 'ghi', 4 : 'jkl', 5 : 'mnop', 6 : 'qrst', 7 : 'uv', 8 : 'wxyz', 9 : '.;' , 10 : '?!' } str = '573' print(printkeypadcombinations(str, ""))
3095a139671aee95620ba26faa21e57f242cf5fe
AyberkKilicaslan/Python-XML-CSV-JSON-Converter
/xmlToCsv.py
3,493
3.59375
4
import xml.etree.ElementTree as ET import csv def xmltocsv(input_file,output_file): ##parsing the xml file with ET xml_Parser = ET.XMLParser(encoding="utf-8") tree = ET.parse(input_file,parser=xml_Parser) root = tree.getroot() # open a file for writing csv_data = open(output_file, 'w', encoding="utf-8") ##variables for easy print will be used in for loop second = '' grant = '' period = '' spec = '' lastScore = '' field = '' quota_text = '' ##writing the first line of the csv manually csv_data.write("ÜNİVERSİTE_TÜRÜ;ÜNİVERSİTE;FAKÜLTE;PROGRAM_KODU;PROGRAM;DİL;ÖĞRENİM_TÜRÜ;BURS;ÖĞRENİM_SÜRESİ;PUAN_TÜRÜ;KONTENJAN;OKUL_BİRİNCİSİ_KONTENJANI;GEÇEN_YIL_MİN_SIRALAMA;GEÇEN_YIL_MİN_PUAN\n") ##reach the "university" members for member in root.findall('university'): for submemer in member: csv_data.write(member.get("uType") +";") csv_data.write(member.get("name")+";") csv_data.write(submemer.get("faculty")+";") csv_data.write(submemer.get("id")+";") for submember in submemer: ###department has to be here if submember.tag == "name": csv_data.write(submember.text+";") if submember.tag == "name": if submember.get("lang") == "en": ##change the strings for expected csv file format csv_data.write("İngilizce;") else : csv_data.write(";") ##replace the xml attributes to the expected original csv file format ##reaching the whole element tag's attributes with cheking if else for each subelement if submember.tag =="grant": if submember.text is None: grant = ';' else: grant = submember.text+";" if submember.tag == "period": if submember.get("period") != None: period = submember.get("period")+";" if submember.tag == "name": if submember.get("second") == "no": second = ";" else : second = "İkinci Öğretim;" if submember.tag =="field": if submember.text != None: field = submember.text+";" if submember.tag =="period": period = submember.text+";" if submember.tag == "quota": spec = submember.get("spec")+";" if submember.tag == "quota": quota_text = submember.text+";" if submember.tag =="last_min_score": if(submember.get("order") != None): if(submember.get("order") == '0'): lastScore = ";" else: lastScore = submember.get("order")+";" + submember.text ##easy print part with variables which we included before csv_data.write(second + grant + period + field + quota_text + spec + lastScore) csv_data.write("\n")
97057cce48e6a22c540d6c9d2a531a0002965696
IvanYukish/PycharmProjects
/Test/2.1.5.py
143
3.765625
4
A, B = (int(input() )for _ in range(2)) it = sums = 0 for _ in range(A, B+1): if _%3 == 0: sums += _ it += 1 print(sums/it)
553775fc705cd709de289fb498c5b72744aa88d8
mgcarbonell/30-Days-of-Python
/04_basic_py_collections.py
3,368
4.6875
5
# In python we have lists names = ["Jerry", "Elaine", "Kramer", "George"] # and we can spread them over multiple lines, or mix datatypes friend_details = ["Andy", 33, "big boss"] # we can access them like standard javascript notation print(friend_details[0]) # => Andy print(friend_details[1]) # => 33 print(friend_details[2]) # => big boss # we can also access them with negatives, that's like a len - 1 print(names[-1]) # => George # want to add something to the end of the list? .append() names.append('Newman') # or we can use the + operator names = names + ['Helen'] print(names[-1]) # Helen print(names[-2]) # Newman # we can also use insert() so if we have... numbers = [1, 2, 4, 5] # and we want to insert a 3 at index 2 we would numbers.insert(2, 3) # to remove items from a list we can remove names.remove('Newman') # removes Newman # we can also use del del numbers[0] # deletes index 0 in numbers (deletes 1) print(numbers) # we can also pop() to remove the last item and save it jerry_mom = names.pop() print(jerry_mom) # we can also clear the array with clear names.clear() print(names) # => [] # TUPLES the Devil's Datastructure (just kidding) # All we need to define a tuple is a series of comma separated values names = "Jerry", "Elaine", "George" # most often you'll see names = ("Jerry", "Elaine", "George") with the parens # We can also store tuples in a list! movies_example = [ ("Eternal Sunshine of the Spotless Mind", 2004), ("Memento", 2000), ("Requiem for a Dream", 2000) ] # ESSM & 2004 = a tuple # Like lists, we can access a value in a tuple with list notation. print(names[0]) # => Jerry print(movies_example[0]) # => ('Eternal Sunshine of the Spotless Mind', 2004) # we can even use double notation to return something specific print(movies_example[0][0]) # => Eternal Sunshine of the Spotless Mind # However, TUPLES ARE IMMUTABLE. We cannot change once defined! # Exercises # 1. Create a movies list containing a single tuple. The tuple should contain a movie title, the director’s name, the release year of the movie, and the movie’s budget. movies = [("Hackers", "Iain Softley", 1995, 20000000)] # 2. Use the input function to gather information about another movie. You need a title, director’s name, release year, and budget. user_movie_title = input("What's your favorite movie? ") user_movie_director = input(f"Who directed {user_movie_title}? ") user_movie_year = int(input(f"In what year was {user_movie_title} released? ")) user_movie_budget = int(input(f"What was the budget of {user_movie_title}? ")) # 3. Create a new tuple from the values you gathered using input. Make sure they’re in the same order as the tuple you wrote in the movies list. user_movie_tuple = (user_movie_title, user_movie_director, user_movie_year, user_movie_budget) print(user_movie_tuple) # 4. Use an f-string to print the movie name and release year by accessing your new movie tuple. print(f"{user_movie_tuple[0]} directed by {user_movie_tuple[1]} was released in {user_movie_tuple[2]} with a budget of {user_movie_tuple[3]}.") # 5. Add the new movie tuple to the movies collection using append. movies.append(user_movie_tuple) # 6. Print both movies in the movies collection. print(movies) # 7. Remove the first movie from movies. Use any method you like. movies.pop(0) print(movies)
ac5ca46acfa85bf9be4d4f2d3ea55b5273ebe483
lord3612/GB_Python
/lesson_7/task_7_4.py
1,353
3.5
4
""" Написать скрипт, который выводит статистику для заданной папки в виде словаря, в котором ключи — верхняя граница размера файла (пусть будет кратна 10), а значения — общее количество файлов (в том числе и в подпапках), размер которых не превышает этой границы, но больше предыдущей (начинаем с 0), например: { 100: 15, 1000: 3, 10000: 7, 100000: 2 } Тут 15 файлов размером не более 100 байт; 3 файла больше 100 и не больше 1000 байт... Подсказка: размер файла можно получить из атрибута .st_size объекта os.stat. """ import os all_files = [] for root, dirs, files in os.walk('../'): for file in files: all_files.append(os.path.getsize(os.path.join(root, file))) max_size = max(all_files) my_dict = {} i = 1 for x in range(len(str(max_size))): i *= 10 if i == 10: my_dict[int(i)] = len([file for file in all_files if i >= file >= 0]) else: my_dict[int(i)] = len([file for file in all_files if i >= file >= i / 10]) print(my_dict)
6d7faf3fddbe0290a6f2f352452e9ef00cbd22f1
knparikh/IK
/Sorting/nearest_neighbors.py
1,466
3.921875
4
import heapq import math #Given a point P and other N points in two dimensional space, find K points out # of N points which are nearest to P. class point(object): def __init__(self, tup, p): self.x = tup[0] self.y = tup[1] # Since python only has min heap, and we want max heap, negate the eucl distance and store. self.eucl = -1 * (((self.x ** 2) - (p[0] ** 2)) + ((self.y ** 2) - (p[1] ** 2))) # skip the sqrt for efficiency def __lt__(self, other): return self.eucl < other.eucl def nearest_neighbors(p, neighbors, k): if len(neighbors) < k: return neighbors heap = [point(neighbors[i], p) for i in range(k)] # First insert and heapify k elements heapq.heapify(heap) for i in range(k, len(neighbors)): # If this neighbor's distance is less than max in heap, pop the max from heap and insert this neighbor. neigh = point(neighbors[i], p) if neigh > heap[0]: # invert the check because its actually min_heap heapq.heappop(heap) heapq.heappush(heap, neigh) out = [] # Finally return the k nearest points for i in range(len(heap)): elem = heapq.heappop(heap) out.append((elem.x, elem.y)) return out if __name__ == "__main__": neighbors = [(1,2),(2,3),(4,6),(7,9)] # 1, 5, 44, p = (2,2) print 'nearest_neighbors = ', nearest_neighbors(p, neighbors, 2)
44242558c3c785ae0135952e6087d592d22bb517
Mamata720/hangaman
/hangman.py
7,616
3.609375
4
import string from words import choose_word from images import IMAGES # in this line meaning from images i am import IMAGES variable list. # End of helper code # ----------------------------------- def InValide(guess):# def is pree difine keyword invalide is a variable i pass the guess argument inside the paremeter. if len(guess) > 1:#len of guess is less then 1(because i have to take only one letter input from user) return False # then i it will return False. if not guess.isalpha():#if guess is not in string (isalpha() function returning the value in bool if guess is in string then iw will give True or else it will return False.) return False# then return False. return True# then return True def hint(secret_word, letters_guessed): import random#i import random libry index = 0 #index is started from 0 not_guessed_letters = []# not_guessed_letters in this variable i assign empty list. while index < len(secret_word): letter = secret_word[index]#i difine letter variable in that i assign secreat_word[index] value if letter not in letters_guessed: if letter not in not_guessed_letters: not_guessed_letters.append(letter)#append letter in not_guessed_letters empty list. index = index + 1#increment # print(not_guessed_letters) return random.choice(not_guessed_letters) def is_word_guessed(secret_word, letters_guessed): ''' secret_word: ek string word jo ki user ko guess karna hai letters_guessed: ek list hai, jisme wo letters hai jo ki user nai abhi tak guess kare hai returns: return True kare agar saare letters jo ki user ne guess kiye hai wo secret_word mai hai, warna no False otherwise ''' if secret_word in get_guessed_word(secret_word, letters_guessed):# replac of == we can use in return True# then print True . return False#or else return False. # Iss function ko test karne ke liye aap get_guessed_word("kindness", [k, n, d]) call kar sakte hai def get_guessed_word(secret_word, letters_guessed): ''' secret_word: ek string word jo ki user ko guess kar raha hai letters_guessed: ek list hai, jisme wo letters hai jo ki user nai abhi tak guess kare hai returns: ek string return karni hai jisme wo letters ho jo sahi guess huye ho and baki jagah underscore ho. eg agar secret_word = "kindness", letters_guessed = [k,n, s] to hum return karenge "k_n_n_ss" ''' index = 0 guessed_word = "" while (index < len(secret_word)): if secret_word[index] in letters_guessed: guessed_word += secret_word[index] else: guessed_word += "_" index += 1 return guessed_word def get_available_letters(letters_guessed): ''' letters_guessed: ek list hai, jisme wo letters hai jo ki user nai abhi tak guess kare hai returns: string, hame ye return karna hai ki kaun kaun se letters aapne nahi guess kare abhi tak eg agar letters_guessed = ['e', 'a'] hai to humme baki charecters return karne hai jo ki `bcdfghijklmnopqrstuvwxyz' ye hoga ''' import string all_letters = string.ascii_lowercase letters_left = " " i = 0 # i difine one variable in that i assigen 0 variable while i < len(all_letters):# i less then len of all_letters if all_letters[i] not in letters_guessed:# all_letters[i] value not in letters_guessed. letters_left += all_letters[i]# all_letters[i]value i add in leters_left sring variable. i = i + 1# increment of i . # for i in all_letters: # if i not in letters_guessed: # letters_left += i return letters_left def hangman(secret_word): ''' secret_word: string, the secret word to guess. Hangman game yeh start karta hai: * Game ki shuruaat mei hi, user ko bata dete hai ki secret_word mei kitne letters hai * Har round mei user se ek letter guess karne ko bolte hai * Har guess ke baad user ko feedback do ki woh guess uss word mei hai ya nahi * Har round ke baar, user ko uska guess kiya hua partial word display karo, aur underscore use kar kar woh letters bhi dikhao jo user ne abhi tak guess nahi kiye hai ''' print ("Welcome to the game, Hangman!") print ("I am thinking of a word that is " + str(len(secret_word)) + " letters long.") print( "") # print(secret_word) while True: lives = input("\n1)Easy\n2)Medium\n3)Hard\n Enter your level:-") if "Easy" in lives or "easy" in lives or "1" in lives: level = 8 index = 0 break elif "Medium" in lives or "medium" in lives or "2" in lives : level = 6 index = 2 break elif "Hard" in lives or "hard" in lives or "3" in lives: level = 4 index = 4 break else: print("Wrong Input Enter Again :)")# if we are enter wrong answer then it will iterate again. letters_guessed = [] remaining_lives = level # i assign level value in remainging lives. # remaining_lives = 8#i difine remaining_lives for giving 8 chance to user. guess_count = 1 image_index= index # i am difining image_index variable for counting the index of IMAGE List in that i assign index value. . while remaining_lives > 0: available_letters = get_available_letters(letters_guessed) print ("Available letters: " + available_letters)#, + print("Remember only ",4 - guess_count ," times you can use hint after thata it will not work") guess = input("Please guess a letter / use hint :- ")# guess is taking input from user . if guess == "hint" and guess_count < 4: # if guess is equal to equal to hint and guess_count less then 4 print("You use your",guess_count ,"chance .") letter = ( hint(secret_word, letters_guessed))# in letter variable i called hint function . # print(guess_count) guess_count = guess_count + 1 # increment of guess_count. else: letter = guess.lower()# it is converting guess. letter in lower case. if not InValide(letter):# call the InValide function continue# if letter is not valide then continue taking input if letter in secret_word:# if letter in secret_word letters_guessed.append(letter)# then letters_guessed.append letter. if letter in secret_word: letters_guessed.append(letter) print ("Good guess: " + get_guessed_word(secret_word, letters_guessed)) print ("") if is_word_guessed(secret_word, letters_guessed) == True: print (" * * Congratulations, you won! * * ") print ("") break else: print ("Oops! That letter is not in my word: " + get_guessed_word(secret_word, letters_guessed)) letters_guessed.append(letter) print ("") print(IMAGES[image_index])#IMAGES is list name image_index(value of image_index in IMAGES list) image_index+=1#increment of image_index remaining_lives -= 1# increment of remaining_lives if remaining_lives == 0:# if my remaining lives is 0 print("Your secret word is :- " ,secret_word)# then this line will execute. # Load the list of words into the variable wordlist # So that it can be accessed from anywhere in the program secret_word = choose_word() hangman(secret_word)
fcd44f0666acfb40ff4bad42ca0384997a87ceaf
bakker4444/Algorithms
/Python/leetcode_076_minimum_window_substring.py
5,937
4
4
## 76. Minimum Window Substring # # Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). # # Example: # # Input: S = "ADOBECODEBANC", T = "ABC" # Output: "BANC" # # Note: # # If there is no such window in S that covers all characters in T, return the empty string "". # If there is such window, you are guaranteed that there will always be only one unique minimum window in S. ## ## Approach 1: Sliding Window ## reference ## https://leetcode.com/problems/minimum-window-substring/solution/ """ Complexity Analysis Time Complexity: O(|S| + |T|) where |S| and |T| represent the lengths of strings S and T. In the worst case we might end up visiting every element of string S twice, once by left pointer and once by right pointer. |T| represents the length of string T. Space Complexity: O(|S| + |T|). |S| when the window size is equal to the entire string S. |T| when T has all unique characters. """ from collections import Counter class Solution1(object): def minWindow(self, s, t): """ :type s: str :type t: str :rtype: str """ if not t or not s: return "" # Dictionary which keeps a count of all the unique characters in t. dict_t = Counter(t) # Number of unique characters in t, which need to be present in the desired window. required = len(dict_t) # left and right pointer l, r = 0, 0 # formed is used to keep track of how many unique characters in t are present in the current window in its desired frequency. # e.g. if t is "AABC" then the window must have two A's, one B and one C. Thus formed would be = 3 when all these conditions are met. formed = 0 # Dictionary which keeps a count of all the unique characters in the current window. window_counts = {} # ans tuple of the form (window length, left, right) ans = float("inf"), None, None while r < len(s): # Add one character from the right to the window character = s[r] window_counts[character] = window_counts.get(character, 0) + 1 # If the frequency of the current character added equals to the desired count in t then increment the formed count by 1. if character in dict_t and window_counts[character] == dict_t[character]: formed += 1 # Try and contract the window till the point where it ceases to be 'desirable'. while l <= r and formed == required: character = s[l] # Save the smallest window until now. if r - l + 1 < ans[0]: ans = (r - l + 1, l, r) # The character at the position pointed by the `left` pointer is no longer a part of the window. window_counts[character] -= 1 if character in dict_t and window_counts[character] < dict_t[character]: formed -= 1 # Move the left pointer ahead, this would help to look for a new window. l += 1 # Keep expanding the window once we are done contracting. r += 1 return "" if ans[0] == float("inf") else s[ans[1] : ans[2] + 1] ## Approach 2: Optimized Sliding Window ## reference: ## https://leetcode.com/problems/minimum-window-substring/solution/ """ Complexity Analysis Time Complexity : O(|S| + |T|) where |S| and |T| represent the lengths of strings S and T. The complexity is same as the previous approach. But in certain cases where |filtered_S| <<< |S|, the complexity would reduce because the number of iterations would be 2*|filtered_S| + |S| + |T|. Space Complexity : O(|S| + |T|)O(∣S∣+∣T∣). """ class Solution2(object): def minWindow(self, s, t): """ :type s: str :type t: str :rtype: str """ if not t or not s: return "" dict_t = Counter(t) required = len(dict_t) # Filter all the characters from s into a new list along with their index. # The filtering criteria is that the character should be present in t. filtered_s = [] for i, char in enumerate(s): if char in dict_t: filtered_s.append((i, char)) l, r = 0, 0 formed = 0 window_counts = {} ans = float("inf"), None, None # Look for the characters only in the filtered list instead of entire s. This helps to reduce our search. # Hence, we follow the sliding window approach on as small list. while r < len(filtered_s): character = filtered_s[r][1] window_counts[character] = window_counts.get(character, 0) + 1 if window_counts[character] == dict_t[character]: formed += 1 # If the current window has all the characters in desired frequencies i.e. t is present in the window while l <= r and formed == required: character = filtered_s[l][1] # Save the smallest window until now. end = filtered_s[r][0] start = filtered_s[l][0] if end - start + 1 < ans[0]: ans = (end - start + 1, start, end) window_counts[character] -= 1 if window_counts[character] < dict_t[character]: formed -= 1 l += 1 r += 1 return "" if ans[0] == float("inf") else s[ans[1] : ans[2] + 1] if __name__ == "__main__": print(Solution1().minWindow("ADOBECODEBANC", "ABC")) print(Solution2().minWindow("ADOBECODEBANC", "ABC")) print(Solution1().minWindow("ADOBECODEBANCADOBECODEBANC", "ABCABC")) print(Solution2().minWindow("ADOBECODEBANCADOBECODEBANC", "ABCABC"))
a2a417faae9269b9cb7e8f4839ec85b21a90ec4f
cblumenf/bootcamp
/longest_common_substring.py
618
4.28125
4
def common_str_finder(str1, str2): """This function takes in two strings and finds the longest common substring.""" str1_list = list(str1) str2_list = list(str2) if len(str1) <= len(str2): shortlist = str1 longlist = str2 else: shortlist = str2 longlist = str1 print(len(shortlist)) print(len(longlist)) ###What I need to do: """I must find which is shorter and which is longer. Then I must search for the shorter in the longer. If I find a longest common subsequence I must print this sequence. If I do not, I must indicate it."""
668d408118d3343f0f705470b8ecc343ba06ca3f
IbraSuraya/Semester2
/py UAS_PSD/UASPSD_1.py
3,455
3.875
4
''' === NO.1 === UAS Praktikum Struktur Data 2021 Nama : Ibra Hasan Suraya Kelas : IF-B NIM : 2010511053 Jurusan : Informatika Dosen : Pak Jayanta Sumber : Ebook Data Structures and Algorithms with Python (Kent D Lee) Referen https://www.geeksforgeeks.org/find-paths-given-source-destination/ ''' # Tambahan, agar hapus terminal secara otomatis import os os.system('cls') # Memanggil tipe data dict yang valuenya berupa tipe data apapun from collections import defaultdict # Membuat Objek Graf class Graph: # Deklarasi graf def __init__(self, vertices): # Objek yang menampung vertex self.V = vertices # Dekalarasi Graf dengan tipe data dict bervalue list self.graph = defaultdict(list) # Deklarasi untuk menampung bobot tiap jalur self.bobot = {} # Proses pembuatan jalur def tambahEdge(self, dari, ke, w): self.graph[dari].append(ke) self.bobot[(dari,ke)] = w def cariJalur(self, u, akhir, visited, path): # Vertex awal diubah ke True visited[u]= True # Karena sudah true, di append ke dalam path path.append(u) # Jika sudah pada u vertex tujuan, maka mencetak jalur tersebut if u == akhir: print(path) else: # Menelusuri vertex yang terhubung pada u saat tertentu for i in self.graph[u]: # Jika vertex ini masih false if visited[i]== False: # Maka akan menjadi u yang baru saat pemanggialn fungsi CariJalur self.cariJalur(i, akhir, visited, path) # Menghapus vertex yang sudah dilewati dan vertex yang lebih dari 17 path.pop() # Jika sudah di append di path, maka status u akan di false kembali # Karena ada kemungkinan akan dilewati visited[u]= False # Fungsi Persiapan mencari jalur def jalur(self, awal, akhir): # Memberi tanda bahwa semua vertex yang dilalui masih false visited =[False]*(self.V) # Var penampung jalur yang ingin diketahui path = [] # Memanggil fungsi proses pencarian self.cariJalur(awal, akhir, visited, path) g = Graph(30) g.tambahEdge(0, 1, 2.02) g.tambahEdge(1, 4, 1.70) g.tambahEdge(2, 8, 4.64) g.tambahEdge(3, 0, 4.45) g.tambahEdge(3, 2, 5.53) g.tambahEdge(4, 5, 3.28) g.tambahEdge(5, 7, 4.28) g.tambahEdge(5, 12, 3.30) g.tambahEdge(6, 2, 3.41) g.tambahEdge(7, 22, 16.43) g.tambahEdge(8, 13, 8.45) g.tambahEdge(9, 3, 5.02) g.tambahEdge(9, 10, 2.32) g.tambahEdge(9, 17, 7.10) g.tambahEdge(10, 0, 6.20) g.tambahEdge(10, 1, 5.80) g.tambahEdge(10, 11, 1.67) g.tambahEdge(10, 17, 8.65) # g.tambahEdge(11, ) g.tambahEdge(12, 11, 2.16) g.tambahEdge(13, 14, 4.61) g.tambahEdge(13, 16, 7.32) g.tambahEdge(14, 15, 4.07) g.tambahEdge(14, 17, 13.47) g.tambahEdge(15, 16, 1.24) g.tambahEdge(15, 17, 8.81) g.tambahEdge(16, 17, 9.01) g.tambahEdge(17, 3, 10.81) g.tambahEdge(17, 6, 11.6) g.tambahEdge(17, 23, 11.76) g.tambahEdge(17, 24, 8.42) g.tambahEdge(18, 17, 4.07) g.tambahEdge(19, 18, 1.54) g.tambahEdge(20, 19, 1.53) g.tambahEdge(21, 20, 6.17) g.tambahEdge(21, 22, 4.66) # g.tambahEdge(22, ) g.tambahEdge(23, 24, 2.18) g.tambahEdge(24, 27, 4.67) g.tambahEdge(25, 18, 6.17) g.tambahEdge(25, 26, 1.86) g.tambahEdge(26, 19, 4.72) g.tambahEdge(27, 25, 3.51) g.tambahEdge(27, 29, 11.6) g.tambahEdge(28, 20, 9.32) g.tambahEdge(28, 21, 6.66) g.tambahEdge(28, 29, 4.24) # g.tambahEdge(29, ) awal = 9 ; akhir = 29 print("Berikut semua kemungkin jalur") print(f"Dari: {awal} Menuju: {akhir}") g.jalur(awal, akhir)
8cb2d1230348c080691c0785c5d1e22597aeed80
rajatgarg149/Daily_python_practice
/listlessthan.py
512
4.375
4
'''This file prints to list 1) List of numbers > N 2) List of numbers <= N ''' list_all =input('Give the list you want to divide\n') N = int(input('Type the pivot\n')) #covert list of strings to int list_all = [int(x) for x in list_all.split()] list_gt = [x for x in list_all if x > N] list_lt = [x for x in list_all if x <= N] print('Given List:\n%r\n' % list_all) print('List with numbers greater than %r\n%r' %(N, list_gt)) print('List with numbers less than or equal to %r\n%r' %(N, list_lt))
b5b56d93d1a5b1df537698ed16e1c4ba7978a8f9
michelegorgini/excersises
/TimeZone challenge.py
3,381
4.21875
4
# Create a program that allows a user to choose one of # up to 9 time zones from a menu. You can choose any # zones you want from the all_timezones list. # # The program will then display the time in that timezone, as # well as local time and UTC time. # # Entering 0 as the choice will quit the program. # # Display the dates and times in a format suitable for the # user of your program to understand, and include the # timezone name when displaying the chosen time. # My solution import datetime import pytz import random My_tuple =() for x in sorted(pytz.country_names): if x in pytz.country_timezones: for zone in sorted(pytz.country_timezones[x]): My_tuple += ([x,pytz.country_names[x],zone],)# My_tuple contains all the conbination code country, country, timezone else: continue rand_choise = random.sample(My_tuple, 9) # I choise random 9 of these key_choise = {} ind = 1 for item in rand_choise: # I create a key to do a choise after code, name, timezone = item key_choise.setdefault(ind, []).append(item) ind += 1 while True: for y in range(1,10): print(y,key_choise[y]) # I print all the 9 opportunities code = int(input("\nDigit the code about the timezone you want the time + Enter (0 to Exit) : ")) if code == 0: # Exit from the program break if code > 9: print("You digit a code out of range!\n") else: for code, name, timezone in key_choise[code]: my_timezone = timezone tz_to_disply = pytz.timezone(my_timezone) aware_local_time = datetime.datetime.now(tz=tz_to_disply) #local time in the timezone choised print("\nAware local time {}, time zone {} ".format(aware_local_time, tz_to_disply)) utc_time = datetime.datetime.utcnow() #UtC time aware_utc_time = pytz.utc.localize(utc_time)# UTC time with localisation print("Aware UTC {}, time zone {} \n\n".format(aware_utc_time, aware_utc_time.tzinfo)) # # Tim Buchalka solution: I prefer my solution a part the print out (strftime('%A %x %X %z')) I had to do this. # # import datetime # import pytz # # available_zones = {'1': "Africa/Tunis", # '2': "Asia/Kolkata", # '3': "Australia/Adelaide", # '4': "Europe/Brussels", # '5': "Europe/London", # '6': "Japan", # '7': "Pacific/Tahiti", # '8': "US/Hawaii", # '9': "Zulu"} # # print("Please choose a time zone (or 0 to quit):") # for place in sorted(available_zones): # print("\t{}. {}".format(place, available_zones[place])) # # while True: # choice = input() # # if choice == '0': # break # # if choice in available_zones.keys(): # tz_to_display = pytz.timezone(available_zones[choice]) # world_time = datetime.datetime.now(tz=tz_to_display) # print("The time in {} is {} {}".format(available_zones[choice], world_time.strftime('%A %x %X %z'),world_time.tzname())) # print("Local time is {}".format(datetime.datetime.now().strftime('%A %x %X'))) # print("UTC time is {}".format(datetime.datetime.utcnow().strftime('%A %x %X'))) # print()
a2ae4de18c17efae0e779499e5521ef049cf0ec2
eBLDR/Misc_Projects
/paint.py
3,251
3.625
4
import turtle import pickle """ Mapping functions so we can repeat previous drawings: 1 = increase_line_width() 2 = decrease_line_width() 3 = color() 4 = shape() 5 = stamp() (x, y) = goto() """ LIST = [] # Action sequence memory def goto(x, y): atlas.pendown() atlas.goto(x, y) LIST.append([x, y]) def clear_screen(): global i_WIDTH, i_COLORS, i_SHAPES i_WIDTH, i_COLORS, i_SHAPES = (0, 0, 0) atlas.reset() global SHAPES, LIST atlas.shape(SHAPES[i_SHAPES]) LIST = [] def exit_(): screen.bye() def increase_line_width(): global i_WIDTH, WIDTH if i_WIDTH < 11: i_WIDTH += 1 atlas.pensize(WIDTH[i_WIDTH]) LIST.append(1) def decrease_line_width(): global i_WIDTH, WIDTH if i_WIDTH > 0: i_WIDTH -= 1 atlas.pensize(WIDTH[i_WIDTH]) LIST.append(2) def color(): global i_COLORS, COLORS if i_COLORS < 7: i_COLORS += 1 else: i_COLORS = 0 atlas.color(COLORS[i_COLORS]) LIST.append(3) def shape(): global i_SHAPES, SHAPES if i_SHAPES < 5: i_SHAPES += 1 else: i_SHAPES = 0 atlas.shape(SHAPES[i_SHAPES]) LIST.append(4) def stamp(): atlas.stamp() LIST.append(5) def repeat(): global LIST LIST_BLOCKED = LIST[::] clear_screen() for action in LIST_BLOCKED: if isinstance(action, (tuple, list)): goto(action[0], action[1]) else: if action == 1: increase_line_width() elif action == 2: decrease_line_width() elif action == 3: color() elif action == 4: shape() elif action == 5: stamp() LIST = LIST_BLOCKED[::] # Deep copy of the list def save(): global LIST with open('myDraw.pkl', 'wb') as extr: pickle.dump(LIST, extr) def load(): with open('myDraw.pkl', 'rb') as intr: LIST_LOAD = pickle.load(intr) global LIST LIST = LIST_LOAD[::] repeat() # Constants WIDTH = [str(i) for i in range(1, 13)] i_WIDTH = 0 # Initial width COLORS = ['black', 'yellow', 'orange', 'red', 'green', 'darkgreen', 'blue', 'purple'] i_COLORS = 0 # Initial color SHAPES = ['arrow', 'turtle', 'circle', 'square', 'triangle', 'classic'] i_SHAPES = 0 # Initial shape # Window settings screen = turtle.Screen() screen.setup(650, 650) screen.title('Paint Version by eBLDR') # Turtle settings atlas = turtle.Turtle() atlas.pencolor(COLORS[i_COLORS]) atlas.pensize(WIDTH[i_WIDTH]) atlas.shape(SHAPES[i_SHAPES]) # Legend drawing legend = turtle.Turtle() legend.hideturtle() legend.penup() legend.goto(-315, -315) legend.write('Intro => new\nEsc => exit\n2/3 => width\n0 => color\n1 => shape\nSpace => stamp\nr => Repeat\ns => Save\no => Load', align='left') # Keys screen.onclick(goto, btn=1) screen.onkey(clear_screen, 'Return') screen.onkey(exit_, 'Escape') screen.onkey(increase_line_width, '2') screen.onkey(decrease_line_width, '3') screen.onkey(color, '0') screen.onkey(shape, '1') screen.onkey(stamp, 'space') screen.onkey(repeat, 'r') screen.onkey(save, 's') screen.onkey(load, 'o') screen.listen() screen.mainloop() print(LIST) # Only for control
6c5c9219ed4341f2e0502816541e924de61c03cf
salihenesbayhan/Homework-Assigment-6
/Assignment 6.py
1,188
4.03125
4
import math # returns True if n is prime number # returns False otherwise def is_prime(n): # n is less than 2 if n < 2: return False # compute square root + 1 sq = int(math.sqrt(n)) + 1 # check if divisible by any other number for i in range(2, sq): if n % i == 0: return False return True # returns a list of the first 20 primes def primes_list(): p = [] i = 2 while len(p) < 20: if is_prime(i): p.append(i) i += 1 # increment i return p # returns the list of first 19 fake primes def fake_primes_list(primes): fake_primes = [] for i in range(len(primes) - 1): fake_primes.append(primes[i] * primes[i + 1]) return fake_primes def fakePrimes(): print("done") primes = primes_list() fake_primes = fake_primes_list(primes) for i in range(len(primes) - 1): print(f'Fake prime in position { i + 1 } is { fake_primes[i] }. It is generated using { primes[i] } and { primes[i + 1] }.') fakePrimes()
04df4c568081ef5acf2a31dd07ba6f65d2076fa0
LouStafford/My-Work
/week02/hello2.py
156
4.03125
4
#Lab 2.2 continued - creating a new file that reads a persons name & outputs same #Author: Louise Stafford name = input ("Enter your name:") print ( 'Hello ' + name)
2a3a33b785e30c883160a8f87699565f16af6905
joellimrl/Practicals
/prac02/ascii_table.py
748
4.34375
4
LOWER = 33 UPPER = 127 """ char = input("Enter a character: ") print("The ASCII code for {} is {}".format(char,ord(char))) code = int(input("Enter a number between {} and {}: ".format(LOWER,UPPER))) while code < LOWER or code > UPPER: code = int(input("Please re-enter a number between {} and {}: ".format(LOWER,UPPER))) print("The character for {} is {}".format(code, chr(code))) """ columns = int(input("How many columns would you like: ")) split = 93 // columns count = 0 lower = LOWER while lower < split+LOWER+1: for i in range(lower,UPPER,split+1): print("{:>3} {:20}".format(i,chr(i)),end="") count += 1 if count == columns: count = 0 break lower += 1 count = 0 print()
6c8a4ee5b828e39393f54686aaa4135f81f2665a
grain111/Learn_CS
/Databases/Many_to_Many/main.py
2,006
3.640625
4
import sqlite3, json conn = sqlite3.connect('studentdb.sqlite') cur = conn.cursor() cur.executescript(""" DROP TABLE IF EXISTS Student; DROP TABLE IF EXISTS Course; DROP TABLE IF EXISTS Member; DROP TABLE IF EXISTS Funct; CREATE TABLE Student (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT UNIQUE); CREATE TABLE Course (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT UNIQUE); CREATE TABLE Funct (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT UNIQUE); CREATE TABLE Member (student_id INTEGER, course_id INTEGER, funct_id INTEGER, PRIMARY KEY (student_id, course_id)); INSERT INTO Funct (name) VALUES ("student"); INSERT INTO Funct (name) VALUES ("teacher"); """) with open("sample.json") as f: data = json.load(f) for val in data: student_name = val[0] course_name = val[1] role = val[2] cur.execute("INSERT OR IGNORE INTO Student (name) VALUES (?)", (student_name, )) student_id = cur.execute("SELECT id FROM Student WHERE name=?", (student_name, )).fetchone()[0] cur.execute("INSERT OR IGNORE INTO Course (name) VALUES (?)", (course_name, )) course_id = cur.execute("SELECT id FROM Course WHERE name=?", (course_name, )).fetchone()[0] cur.execute("""INSERT OR IGNORE INTO Member (student_id, course_id, funct_id) VALUES (?, ?, ?)""", (student_id, course_id, role + 1)) conn.commit() cur.execute("""SELECT Student.name, Course.name, Funct.name FROM Member JOIN Student JOIN Course JOIN Funct ON Student.id = Member.student_id AND Course.id = Member.course_id AND Member.funct_id = Funct.id """) for rec in cur.fetchall(): print(rec)
b857491af0df256c7eecb44920436c01a8490903
s1lya/secutiryScriptsMIPT
/4.2.py
1,888
3.859375
4
# coding: utf-8 # In[25]: def pow_h(base, degree, module): binary = "{0:b}".format(degree) # print("Возводим число %d в %d степень по модулю %d"%(base,degree,module)) if len(binary) != 8: binary = '0' * (8 - len(binary)) + binary # print("Двоичное представление степени - " + binary) s = 1 counter = 1 for i in binary: temp = (s ** 2) * (base ** int(i)) % module # print("S%d = (%d)^2 * %d^%d = %d" % (counter, s, base, int(i), temp)) counter += 1 s = temp # print("Ответ - %d"%s) return s # In[26]: def Miller(n, a): res = [] power = n-1 print('n - 1 = %d' %(power)) print('Пока n - 1 делится на 2^i мы считаем a ^((n-1)/2^i) где i=1..') i = 0 while power % 2 == 0: print("(n - 1)/ 2^%d = %d" %(i, power)) print("Найдем a ^ (n - 1)/ 2^%d" %(i)) var = pow_h(a, power, n) print("a ^ (n - 1)/ 2^%d = %d" %(i, var)) res.append(var) i += 1 power = power // 2 print("(n - 1)/ 2^%d = %d" %(i, power)) print("Найдем a ^ (n - 1)/ 2^%d" %(i)) var = pow_h(a, power, n) print("a ^ (n - 1)/ 2^%d = %d" %(i, var)) res.append(var) return res # In[27]: print("Введите свидетель и проверяемое число") print("x1 , n") a , n= list(map(int, input().split(' '))) res = Miller(n, a) print("-1 mod n = %d" %(-1 %n)) print("Если первое найденное число равно 1 и последнее найденное не равно %d и %d есть среди найденных чисел то a свидетель простоты n" % (-1%n , -1%n)) print("Наши результаты") print(res) print(res[0] == 1 and res[-1] != -1 % n and -1 % n in res)
3fb8d821638212a3a663fb3a54d33bcc705f3f63
jalondono/holbertonschool-machine_learning
/math/0x04-convolutions_and_pooling/0-convolve_grayscale_valid.py
885
3.78125
4
#!/usr/bin/env python3 """Valid Convolution""" import numpy as np def convolve_grayscale_valid(images, kernel): """ performs a valid convolution on grayscale images: :param images: is a numpy.ndarray with shape (m, h, w) containing multiple :param kernel: is a numpy.ndarray with shape (kh, kw) containing the kernel for the convolution :return: a numpy.ndarray containing the convolved image """ w = int(images.shape[2] - kernel.shape[1] + 1) h = int(images.shape[1] - kernel.shape[0] + 1) m = int(images.shape[0]) kw = kernel.shape[1] kh = kernel.shape[0] new_img = np.zeros((m, h, w)) for row in range(w): for colum in range(h): img = images[0:, colum: kh + colum, row: kw + row] pixel = np.sum(img * kernel, axis=(1, 2)) new_img[0:, colum, row] = pixel return new_img
7e26f8b329dd34f714512142a30ef411c3d77509
wulab/falling
/person.py
1,736
3.609375
4
import config from deck import * from table import * class Person(object): def __init__(self, name): self.name = name def join(self, table): self.table = table if config.debug: print self.name + ' joined ' + table.getName() class Player(Person): def __init__(self, name): Person.__init__(self, name) self.hand = Deck('Hand') self.riders = Deck('Riders') self.stacks = [Deck('Stack')] def getStacks(self): return self.stacks class Dealer(Person): def __init__(self, name): Person.__init__(self, name) self.currentPass = 0 def setupCards(self): ''' Before you deal, separate the Ground cards from the deck. Shuffle the rest of the cards, and put the Grounds at the bottom. Hold the deck face down, and deal from the top. The Grounds will be the last cards you deal. ''' self.deck = FallingDeck('The Deck') self.deck.shuffle() def dealCard(self): ''' Draw a card from the deck and deal it to the next player in line. If a player has more than one stack, you deal one card into each. If a player has no stacks at all, you start a new one. ''' players = self.table.getPlayers() nextPlayer = players[self.currentPass % len(players)] nextStacks = nextPlayer.getStacks() for stack in nextStacks: card = self.deck.drawCard() stack.addCard(card) if config.debug: print self.name + ' dealt ' + str(card) + ' to ' + nextPlayer.name self.currentPass += 1 def remainingCards(self): return self.deck.countCards()
84b0c18874f7790396455d29893489600828304f
DanielAShurmer/PythonBootcamp
/Day 5/FindLongestWordInFile.py
718
4.28125
4
def SplitWordsIntoList(String): OutList = [] CurrentWord = "" for Character in String: if Character == " ": OutList.append(CurrentWord) CurrentWord = "" else: if Character != "\n": CurrentWord += Character OutList.append(CurrentWord) print(OutList) return OutList FileToEdit = input("Enter the File Name of A File To Examine:") File_R = open(FileToEdit,"r") MaxFound = 0 WordFound = [] for Line in File_R: WordList = SplitWordsIntoList(Line) for Word in WordList: if len(Word) == MaxFound: WordFound.append(Word) if len(Word) > MaxFound: MaxFound = len(Word) WordFound = [Word] print("The Longest Word(s), With A Length Of",MaxFound,"Is:") for Word in WordFound: print(Word)
3b22a9f22afbbbdf6f42785c3a0c1497684b4cff
an-lam/python-class
/functions/printtext1a.py
498
3.8125
4
def print_hello(): print("Hello world!") return 2 def print_fruits(): width = 80 text = "apple and orange" left_margin = (width - len(text)) // 2 print(" " * left_margin, text) # Parameter: text def centre_text(text): text = str(text) left_margin = (80 - len(text)) // 2 print(" " * left_margin, text) print_hello() print(print_hello()) # call the function centre_text("") centre_text("apple") centre_text(12) centre_text("orange")
559288821a3b703c84a49a4ccdac618640155e47
Toruitas/Python
/Practice/Daily Programmer/DP13a.py
951
3.859375
4
__author__ = 'Stuart' import sys class DaysException(Exception): def __init__(self, day, month): self.day = day self.month = month def __str__(self): months = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') return "{0} is more than the number of days in a {1}".format(self.day, months[self.month-1]) class MonthException(Exception): def __init__(self, month): self.month = month def __str__(self): return "{0} does not correspond with a valid month".format(self.month) def days(day, month): months = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30) if month > 12 : raise MonthException(month) if day > months[month-1] : raise DaysException(day, month) return sum(months[:month-1]) + day try : print( days( int(sys.argv[1]), int(sys.argv[2]) ) ) except Exception as e: print(e)
786c5e96ee07446aa8f15acb1af79a6ab36aa945
djbinder/DojoAssignments
/Python/Python_Fundamentals/Dictionary Basics/dictionary_basics.py
334
3.75
4
def about_me(dictionary): print 'My name is', dictionary["Name"] print 'My age is', dictionary["Age"] print 'My country of birth is the', dictionary["Born"] print 'My favorite language is', dictionary["Language"] dictionary = {"Name" : "Dan", "Age" : "34", "Born" : "USA", "Language" : "Python"} about_me(dictionary)
d6c1d09ff1bb2218a66f03db4320f6391b39f804
kmankan/python_crash_course_exercises
/Chapter 11/test_cities.py
728
3.984375
4
import unittest from city_functions import city_info class CitiesTestCase(unittest.TestCase): """Tests for city_functions.py""" def test_city_country(self): """"Does it print a city and country?""" city_country = city_info('medellin', 'colombia') self.assertEqual(city_country,"Medellin, Colombia") def test_city_country_population(self): """Does it print city, country - population xxxx""" city_country_population = city_info('santiago', 'chile', population=500000) self.assertEqual(city_country_population, "Santiago, Chile - Population 500000") if __name__ == '__main__': unittest.main
35fb93c51e51e49db83925ba0913c95aab3fd311
rafaelperazzo/programacao-web
/moodledata/vpl_data/59/usersdata/159/44778/submittedfiles/testes.py
150
4
4
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO n=int(input('Digite n:')) i=n produto=1 while i>0: produto=produto*i i=i-1 print(produto)
33c1337a0e0f77bb5ce0bdb5ec2eb2bdd0e1fbc1
Tijauna/CSC180-Python-C
/dev_ttt_print_board.py
970
3.625
4
# coding: utf-8 # %load dev_ttt_print_board.py def printBoard (T): rowcounter = 0 smallcounter = 0 limit = 2 if (len(T) > 9): #for too many positions return False for i in range (0, 8, 1): #for invalid list values if ((T[i] != 0) and (T[i] != 1) and (T[i] != 2)): return False while (rowcounter <= 2):#big loop, 2 rows = 1 iteration print '', while(smallcounter <= limit): if (T[smallcounter] == 0): a = str(smallcounter) if (T[smallcounter] == 1): a = 'X' if (T[smallcounter] == 2): a = 'O' if (smallcounter != limit): print a, print '|', else: print a smallcounter = smallcounter + 1 if (rowcounter != 2): print "---|---|---" rowcounter = rowcounter +1 limit = limit + 3 return True
a59ab39c64f399b7cdf917d4fdb8bbcd0481d235
franzip/project-euler
/python/problem005.py
666
3.859375
4
from fractions import gcd def lcm(a, b): return a * (b / gcd(a, b)) def smallest_multiple(upper_limit): assert upper_limit >= 3 and type(upper_limit) == int # save the sequence as a list sequence = range(1, upper_limit + 1) def helper(sequence, accumulator): # use tail recursion and return the least common multiple # maximum recursion depth triggers for upper_limit > 961 if len(sequence) == 1: return accumulator else: return helper(sequence[:-1], lcm(accumulator, sequence.pop())) return helper(sequence, lcm(sequence.pop(), sequence.pop())) print smallest_multiple(20)
13629c3952eef13eb26e6f8c1ea97490271f5b73
wanghan2789/CPP_learning
/algorithm/Practice/链表环的入口.py
895
3.609375
4
# -*- coding:utf-8 -*- #OJ : newcoad class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def EntryNodeOfLoop(self, pHead): # write code here if pHead is None: return None current_quick = pHead current_slow = pHead while True: try: current_slow = current_slow.next current_quick = current_quick.next.next except: return None if current_quick is None or current_slow is None: return None if current_quick == current_slow: current_quick = pHead break while True: if current_quick == current_slow: return current_quick current_quick = current_quick.next current_slow = current_slow.next
cf717a25717a7b20128450adfcb46fa5bfabdf38
saddhu1005/Coursera-DataStructuresAlgorithms
/Algorithm-on-Graphs/10_paths_in_graphs_starter_files_2/shortest_paths/shortest_paths.py
2,016
3.546875
4
#Uses python3 import sys import queue def BellMan_Ford(adj,cost,distance,s,reachable): distance[s]=0 reachable[s]=1 for i in range(len(adj)-1): for u in range(len(adj)): for v,w in zip(adj[u],cost[u]): if distance[v]>distance[u]+w and distance[u]!=10**19: distance[v]=distance[u]+w reachable[v]=1 pass def shortet_paths(adj, cost, s, distance, reachable, shortest): BellMan_Ford(adj,cost,distance,s,reachable) ncycle=[] for u in range(len(adj)): for v,w in zip(adj[u],cost[u]): if distance[v]>distance[u]+w and distance[u]!=10**19: distance[v]=distance[u]+w ncycle.append(v) if ncycle: queue=[] visited=[False]*(len(adj)) while ncycle: s=ncycle.pop(0) if visited[s]==True: continue queue.append(s) visited[s]=True shortest[s]=0 while queue: t=queue.pop(0) for u in adj[t]: if visited[u]==False: visited[u]=True shortest[u]=0 queue.append(u) pass if __name__ == '__main__': input = sys.stdin.read() data = list(map(int, input.split())) n, m = data[0:2] data = data[2:] edges = list(zip(zip(data[0:(3 * m):3], data[1:(3 * m):3]), data[2:(3 * m):3])) data = data[3 * m:] adj = [[] for _ in range(n)] cost = [[] for _ in range(n)] for ((a, b), w) in edges: adj[a - 1].append(b - 1) cost[a - 1].append(w) s = data[0] s -= 1 distance = [10**19] * n reachable = [0] * n shortest = [1] * n shortet_paths(adj, cost, s, distance, reachable, shortest) for x in range(n): if reachable[x] == 0: print('*') elif shortest[x] == 0: print('-') else: print(distance[x])
e7cdc0630d3f3ad25ea208bbcdf2212feb2bb895
Vanguard90/automate-python
/Section 2/if_else_example.py
180
4.125
4
#If-else example name = 'Enes' age = 3000 if name == 'Alice': print('Hi Alice.') elif age < 12: print('You\'re not Alice.') elif age > 2000: print('Good try vampire!')
95348cae48187f48072b7b80172fe79ddfabddee
orez-/Hexcells-Solver
/hex_model.py
21,328
3.578125
4
import contextlib import enum import itertools import util class Color(enum.Enum): blue = (0x05, 0xa4, 0xeb) yellow = (0xff, 0xaf, 0x29) black = (0x3e, 0x3e, 0x3e) @classmethod def closest(cls, value): """ Return the enum element closest in color to the given color. `value` is a tuple of RGB values. """ return min(Color, key=lambda color: util.color_diff(color.value, value)) def coordinate(x=None, y=None, z=None): """ Standardize and validate a hex coordinate given at least two components. A standardized cubic hex coordinate is three axes - x, y, and z - where x + y + z = 0. Given two components, this function will calculate the third and return all three. Given three components, this function will validate that the invariant above is met and will raise a ValueError if it is not, otherwise returning all three. """ coords = x, y, z nones = sum(c is None for c in coords) if nones > 1: raise TypeError("At least two coordinate values must be provided.") if nones == 1: final_coord = -sum(c for c in coords if c is not None) coords = tuple(c if c is not None else final_coord for c in coords) elif sum(coords): raise ValueError("Coordinate values must sum to 0.") return coords def coordinate_by_key(key): """ Given a key, return a standardized coordinate. A key may be an iterable representing x, y, and optionally z. A key may also be a dictionary with at least two of x, y, and z. """ return coordinate(**key) if isinstance(key, dict) else coordinate(*key) def parse_clue(text): """ Parse the text of a clue. Returns (integer value, is_contiguous) If the clue indicates the values must be contiguous, `is_contiguous` is True. If the clue indicates the values must NOT be contiguous, `is_contiguous` is False. If the clue does not indicate whether the values must be contiguous or not, `is_contiguous` is None. """ if text == '-': return None, None if text.startswith('-'): return int(text[1:-1]), False if text.startswith('{'): return int(text[1:-1]), True try: return int(text), None except ValueError: return None, None def generate_hex_circle(distance): return ( (x, y, -x - y) for x in range(-distance, distance + 1) for y in range(max(-distance, -distance - x), min(distance, distance - x) + 1) ) class Hex: def __init__(self, text, color, image_box=None): self.value, self.is_contiguous = parse_clue(text) self.color = color self.image_box = image_box @property def text(self): if self.value is None: return '-' fmt = { None: '{}', True: '{{{}}}', False: '-{}-', }[self.is_contiguous] return fmt.format(self.value) def clone(self): return Hex(self.text, self.color, self.image_box) def __repr__(self): return '{}({!r}, Color.{})'.format(type(self).__name__, self.text, self.color.name) def _ordered_neighbors(x_y_z): """ Yield coordinates surrounding the given coordinate, in adjacent order. """ ROTATIONS = 6 x, y, z = x_y_z dx, dy, dz = 1, 0, -1 for _ in range(ROTATIONS): yield x + dx, y + dy, z + dz dx, dy, dz = -dy, -dz, -dx class AbstractContiguousConstraint: def __init__(self, contiguous_hexes, value, cycle=False): # List of lists of contiguous hexes, in order. self._contiguous_hexes = contiguous_hexes # Does the final element of the final list connect to the first element of the first list self._cycle = cycle self.value = value self._refactor_cycle() def solve(self, board): raise NotImplementedError def is_done(self, board): """ Find if all hexes this constraint acts upon are uncovered. """ return all( board[coord].color != Color.yellow for section in self._contiguous_hexes for coord in section ) @classmethod def ring(cls, board, center): center_hex = board[center] neighbors = list(_ordered_neighbors(center)) sections = list(cls._generate_sections(board, neighbors)) cycle = bool( sections and sections[0][0] == neighbors[0] and sections[-1][-1] == neighbors[-1] ) subcls = ContiguousConstraint if center_hex.is_contiguous else NonContiguousConstraint return subcls( contiguous_hexes=list(sections), value=center_hex.value, cycle=cycle, ) @staticmethod def _generate_sections(board, hexes): """ Given a list of coordinates, split into contiguous groups. """ def predicate(coord): hex_ = board.get(coord) return not hex_ or hex_.color == Color.black return util.split_iterable(hexes, predicate) def _refresh_sections(self, board): start = self._contiguous_hexes[0][0] end = self._contiguous_hexes[-1][-1] self._contiguous_hexes = sum( ( list(self._generate_sections(board, hexes)) for hexes in self._contiguous_hexes ), [] ) # Only keep `_cycle` if the start and end are unchanged. self._cycle = ( self._cycle and start == self._contiguous_hexes[0][0] and end == self._contiguous_hexes[-1][-1] ) self._refactor_cycle() def _refactor_cycle(self): """ Cycles are a pain to reason about - remove them when we get the chance. """ if len(self._contiguous_hexes) != 1 and self._cycle: end = self._contiguous_hexes.pop() self._contiguous_hexes[0] = end + self._contiguous_hexes[0] self._cycle = False class ContiguousConstraint(AbstractContiguousConstraint): # Helper methods may assume _contiguous_hexes is accurate, but if # they make changes they must clean up after themselves. def solve(self, board): functions = [ self._prune_sections, self._solve_section, ] self._refresh_sections(board) for fn in functions: yield from fn(board) def _set_sections(self, sections, color): """ Yield each coordinate in each of the given sections with a color solution. """ yield from ((coord, color) for section in sections for coord in section) def _prune_sections(self, board): """ Prune sections known to not contain blue hexes. """ if len(self._contiguous_hexes) <= 1: return # If we know any blue hexes, prune sections that are not connected. for i, section in enumerate(self._contiguous_hexes): if any(board[coord].color == Color.blue for coord in section): yield from self._set_sections(self._contiguous_hexes[:i], Color.black) yield from self._set_sections(self._contiguous_hexes[i + 1:], Color.black) self._contiguous_hexes = [section] return # Prune sections that are too small to accommodate our value. to_remove, self._contiguous_hexes = util.partition_if( self._contiguous_hexes, lambda section: len(section) < self.value ) yield from self._set_sections(to_remove, Color.black) def _solve_cyclic_section(self, board): section, = self._contiguous_hexes blues = [i for i, coord in enumerate(section) if board[coord].color == Color.blue] if not blues: return # If we know some blues, we might know the contiguous section wont reach the far side # 3: bbyyyy -> bbykky possible = set() for i, _ in enumerate(section): section_range = {j % len(section) for j in range(i, i + self.value)} if all(blue in section_range for blue in blues): possible |= section_range possible = {section[p] for p in possible} # Need to be careful with order here - if there's something to remove, # we're necessarily no longer cyclical (🙌), but we have to ensure # we repair the correct seam; in the following example, we would not # want to accidentally return [2, 1] after removing 0s: # 1 2 0 0 # 0 1 2 0 # 0 0 1 2 # 2 0 0 1 # We use `itertools.groupby` to identify up to three groups # (the contiguous sections in the examples above), from which # we separate to_keep from to_remove while keeping them grouped. to_keep = [] to_remove = [] for keep, subsection in itertools.groupby(section, lambda coord: coord in possible): (to_keep if keep else to_remove).append(list(subsection)) if to_remove: # The only case where we have more than one group to_keep # is where it straddles the seam. We reverse any groups # to ensure we repair the seam correctly. self._contiguous_hexes = [sum(reversed(to_keep), [])] self._cycle = False # 🙌 yield from self._set_sections(to_remove, Color.black) def _solve_noncyclic_section(self, board): section, = self._contiguous_hexes blues = [i for i, coord in enumerate(section) if board[coord].color == Color.blue] # If we know some blues, we might know the contiguous section wont reach the edges. # 3: yybbyy -> kybbyk if blues: max_left = max(0, blues[-1] - self.value + 1) min_right = blues[0] + self.value temp = list( self._set_sections([section[:max_left], section[min_right:]], Color.black) ) yield from temp section[:] = section[max_left:min_right] # If the area is small enough, we know the center is blue. # 4: yyyyy -> ybbby new_blues = [ coord for coord in section[-self.value:self.value] if board[coord].color == Color.yellow ] yield from self._set_sections([new_blues], Color.blue) # # Join non-contiguous blues # # 5: yybybyy -> # # XXX: i can't actually come up with an example of this # # that isn't covered by the above rules! # new_blues = [ # coord for coord in section[blues[0]:blues[-1]] # if board[coord].color == Color.yellow # ] # yield from self._set_sections([new_blues], Color.blue) def _solve_section(self, board): """ Once there's a single remaining section, analyze it for further solutions. """ if len(self._contiguous_hexes) != 1: return if self._cycle: yield from self._solve_cyclic_section(board) else: yield from self._solve_noncyclic_section(board) class NonContiguousConstraint(AbstractContiguousConstraint): def solve(self, board): self._refresh_sections(board) blue_sections = ( (i, section) for i, section in enumerate(self._contiguous_hexes) if any(board[coord].color == Color.blue for coord in section) ) blue_section_id = None current_blues = 0 with contextlib.suppress(StopIteration): blue_section_id, blue_section = next(blue_sections) current_blues = sum(board[coord].color == Color.blue for coord in blue_section) next(blue_sections) # If we have two blue sections we've already necessarily got # a non-contiguous setup - there's nothing else we can learn # from this. return # Check all options for the remaining spots, looking for spots # where there is only one option. remaining_blues = self.value - current_blues available_coords = [ (i, coord) for i, section in enumerate(self._contiguous_hexes) for coord in section if board[coord].color != Color.blue ] spot_options = { coord: set() for section in self._contiguous_hexes for coord in section if board[coord].color != Color.blue } for id_coords in itertools.combinations(available_coords, remaining_blues): section_ids, coords = zip(*id_coords) section_ids = set(section_ids) if blue_section_id is not None: section_ids.add(blue_section_id) # If we're only in one section we're in danger of being contiguous if len(section_ids) == 1: section_id, = section_ids blue_groups = ( blue for blue, _ in itertools.groupby( self._contiguous_hexes[section_id], key=lambda coord: board[coord].color == Color.blue or coord in coords ) if blue ) # Skip contiguous configurations try: next(blue_groups) next(blue_groups) except StopIteration: continue # This is a valid configuration - mark down which are blue # and which are black. for coord, options in spot_options.items(): options.add(Color.blue if coord in coords else Color.black) for coord, options in spot_options.items(): # If there's no options this is either an unsolvable board or we messed up. assert options, coord if len(options) == 1: color, = options yield coord, color class HexBoard: def __init__(self, remaining=None): self._board = {} self._clicked = {} self._regions = None self._contiguous_constraints = None self.remaining = remaining def get(self, key, default=None): try: return self[key] except KeyError: return default def __getitem__(self, key): coord = coordinate_by_key(key) clicked = self._clicked.get(coord) if clicked: return clicked return self._board[coord] def __setitem__(self, key, value): coord = coordinate_by_key(key) self._board[coord] = value self._clicked.pop(coord, None) def __contains__(self, key): coord = coordinate_by_key(key) return coord in self._board @property def is_solved(self): return all( self[coord].color != Color.yellow for coord in self._board ) @property def rows(self): """ Yield left-to-right rows of hexes from top-to-bottom, for display. A "row" represents a set of hexagons whose centers are at the same vertical position. For flat-topped hexagons, this means (perhaps unintuitively) that sequential entries in a row will be two x coordinates apart from one another and will share no edge or vertex. Each yield is composed of a "row number" and the row itself. The row number represents the row's vertical positioning relative to the other rows: sequential rows will have sequential row numbers. Each row is composed of its hex coordinate and the Hex object at that coordinate. """ def sort_key(x_y_z__value): (x, y, z), value = x_y_z__value return y - z, x def group_key(x_y_z__value): (x, y, z), value = x_y_z__value return y - z data = sorted(self._board.items(), key=sort_key) return itertools.groupby(data, group_key) @property def leftmost(self): """ The x value of the leftmost hex in the board. """ if not self._board: raise ValueError("empty board") return min(x for x, y, z in self._board) def _neighbors(self, coord, distance=1): """ Unordered set of neighbors to the given coordinate within the given distance. """ return { neighbor for neighbor in ( tuple(map(sum, zip(coord, delta))) for delta in generate_hex_circle(distance) if any(delta) # don't yield yourself ) if neighbor in self._board } def _get_simplified_region(self, hexes, value): filtered_hexes = set() for coord in hexes: color = self[coord].color if color == Color.yellow: filtered_hexes.add(coord) elif color == Color.blue: value -= 1 # do nothing with black. assert value >= 0, value assert value <= len(filtered_hexes), (value, len(filtered_hexes)) return frozenset(filtered_hexes), value def _populate_regions(self): """ Process information into generic regions with values. """ self._regions = {} self._contiguous_constraints = set() if self.remaining is not None: self._regions[frozenset( coord for coord, hex_ in self._board.items() if hex_.color == Color.yellow )] = self.remaining for coord, hex_ in self._board.items(): if hex_.value is None: continue if hex_.is_contiguous is not None: self._contiguous_constraints.add(AbstractContiguousConstraint.ring(self, coord)) distance = 1 if hex_.color == Color.black else 2 hexes, value = self._get_simplified_region(self._neighbors(coord, distance), hex_.value) self._regions[hexes] = value def _identify_solved_regions(self): solutions = set() new_regions = {} for hexes, value in self._regions.items(): hexes, value = self._get_simplified_region(hexes, value) if len(hexes) == value: solutions.update((hex_, Color.blue) for hex_ in hexes) elif value == 0: solutions.update((hex_, Color.black) for hex_ in hexes) else: new_regions[hexes] = value return solutions, new_regions def _subdivide_overlapping_regions(self): # examine overlapping regions new_regions = {} # compare each region to each other for (hexes1, value1), (hexes2, value2) in itertools.combinations(self._regions.items(), 2): overlap = frozenset(hexes1 & hexes2) if not overlap: continue hexes1_exclusive = frozenset(hexes1 - overlap) hexes2_exclusive = frozenset(hexes2 - overlap) # find the upper and lower bounds for each that can fit in the overlap. omax = min(len(overlap), value2, value1) omin = max( value2 - len(hexes2_exclusive), value1 - len(hexes1_exclusive), 0, ) if omin == omax: if overlap not in self._regions: new_regions[overlap] = omax if hexes1_exclusive not in self._regions: new_regions[hexes1_exclusive] = value1 - omax if hexes2_exclusive not in self._regions: new_regions[hexes2_exclusive] = value2 - omax new_regions.pop(frozenset(), 0) return new_regions def _click(self, coord, color): hex_ = self[coord].clone() assert hex_.color == Color.yellow, (coord, hex_, color) # We decrement `remaining` purely for display purposes if color == Color.blue and self.remaining is not None: self.remaining -= 1 hex_.color = color self._clicked[coord] = hex_ def solve(self): """ Yield new information that can be inferred from the board state. """ for coord, color in self._solve(): self._click(coord, color) yield coord, color def _solve(self): self._populate_regions() progress = True while progress: progress = False # Identify newly-solved regions solutions = True while solutions: solutions, self._regions = self._identify_solved_regions() yield from solutions new_regions = self._subdivide_overlapping_regions() progress = progress or bool(new_regions) self._regions.update(new_regions) for constraint in set(self._contiguous_constraints): solutions = list(constraint.solve(self)) progress = progress or bool(solutions) yield from solutions if constraint.is_done(self): self._contiguous_constraints.remove(constraint) def apply_clicked(self): for coord, hex_ in self._clicked.items(): self._board[coord].color = hex_.color self._clicked = {}
52fbd83641d5b9abf0d65f386476cf25af8e1c21
george-ognyanov-kolev/Learn-Python-Hard-Way
/18.ex18.py
601
3.515625
4
#this one is like argv and scripts def print_two(*args): arg1, arg2 = args print(f'arg1 is {arg1} and arg2 is {arg2}') #ok that *args is pointless we could have do this def print_two_again(arg1, arg2): print('using .format arg1 is {} and arg2 is {}'.format(arg1, arg2)) #this takes one argument def take_one(arg1): print(f'this is the one argument {arg1}') #this takes no arguments def take_none(): print('i have nothing in this func') print_two('Georgi', 'Kolev') print_two_again('Yoneli', "Kitten") take_one("Python for big data and hadoop") take_none()
30203f950ceda9d0d1f1a417ec75f84d191f1f02
rkhood/advent_of_code
/2019/day01.py
561
3.671875
4
def read_masses(filename='data/day01.txt'): with open(filename) as f: masses = f.read().strip().split('\n') return masses def fuel_required_by_mass(mass): return (mass // 3) - 2 def fuel_required_by_fuel(mass): fuel = fuel_required_by_mass(mass) if fuel <= 0: return 0 return fuel + fuel_required_by_fuel(fuel) if __name__ == '__main__': fuel_req_by_mass = sum(fuel_required_by_mass(int(mass)) for mass in read_masses()) fuel_req_by_fuel = sum(fuel_required_by_fuel(int(mass)) for mass in read_masses())
6d93126dae53cd41b90b094ff780ed99375dae57
sakshigarg22/python-projects
/fghj.py
378
3.640625
4
def f(number): return number print(f(5)) def func(message,num = 1): print(message*num) func('welcome') func('viewers',3) def func(x = 1,y = 2): x = x+y y += 1 print(x,y) func(y = 2,x = 1) num = 1 def func(): global num num = num+3 print(num) func() print(num) def test(x = 1,y = 2): x = x+y y += 1 print(x,y) test(y = 2,x = 1)
46a7242c9cc4de06b85cf6ef34f625e0c1b637fb
Brice808/Calculator
/calculator_2.py
13,826
3.828125
4
#!/usr/bin/env python3 from tkinter import * import math import parser import tkinter import tkinter.messagebox root=Tk() root.title("Scientific Calculator") root.configure(background="DarkOrange1") root.resizable(width=False, height=False) root.geometry("500x580+0+0") calc = Frame(root) calc.grid() class Calc(): def __init__(self): self.total = 0 self.current = "" self.input_value = True self.check_sum = False self.op = "" self.result = False def display(self, value): txtDisplay.delete(0, END) txtDisplay.insert(0, value) def numberEnter(self, num): #call numbers self.result = False firstnum = txtDisplay.get() secondnum = str(num) if self.input_value: self.current = secondnum self.input_value = False else: if secondnum == '.': if secondnum in firstnum: return self.current = firstnum + secondnum self.display(self.current) def sum_of_total(self): # equals function self.result = True self.current = float(self.current) if self.check_sum == True: self.valid_function() else: self.total = float(txtDisplay.get()) def operation(self, op): #operators self.current = float(self.current) if self.check_sum: self.valid_function() elif not self.result: self.total = self.current self.input_value = True self.check_sum = True self.op = op self.result = False def valid_function(self): #check operators "name of buttons" if self.op == "add": self.total += self.current if self.op == "sub": self.total -= self.current if self.op == "multi": self.total *= self.current if self.op == "divide": self.total /= self.current if self.op == "mod": self.total %= self.current self.input_value = True self.check_sum = False self.display(self.total) def Clear_Entry(self): self.result = False self.current = "0" self.display (0) self.input_value = True def all_Clear_Entry(self): self.Clear_Entry() self.total = 0 def mathsPM(self): #+- function self.result = False self.current = -(float(txtDisplay.get())) self.display(self.current) def squared(self): self.result = False self.current = math.sqrt(float(txtDisplay.get())) self.display(self.current) def cos(self): self.result self.current = math.cos(math.radians(float(txtDisplay.get()))) self.display(self.current) def cosh(self): self.result self.current = math.cosh(math.radians(float(txtDisplay.get()))) self.display(self.current) def tan(self): self.result = False self.current = math.tan(math.radians(float(txtDisplay.get()))) self.display(self.current) def tanh(self): self.result = False self.current = math.tanh(math.radians(float(txtDisplay.get()))) self.display(self.current) def sin(self): self.result = False self.current = math.sin(math.radians(float(txtDisplay.get()))) self.display(self.current) def sinh(self): self.result = False self.current = math.sinh(math.radians(float(txtDisplay.get()))) self.display(self.current) def acosh(self): self.result = False self.current = math.acosh(float(txtDisplay.get())) self.display(self.current) def asinh(self): self.result = False self.current = math.asinh(float(txtDisplay.get())) self.display(self.current) def pi(self): self.result = False self.current = math.pi self.display(self.current) def tau(self): #2pi function self.result = False self.current = math.tau self.display(self.current) def log(self): self.result = False self.current = math.log(float(txtDisplay.get())) self.display(self.current) def exp(self): self.result = False self.current = math.exp(float(txtDisplay.get())) self.display(self.current) def expm1(self): self.result = False self.current = math.expm1(float(txtDisplay.get())) self.display(self.current) def lgamma(self): self.result = False self.current = math.lgamma(float(txtDisplay.get())) self.display(self.current) def degrees(self): self.result = False self.current = math.degrees(float(txtDisplay.get())) self.display(self.current) def e(self): #2pi function self.result = False self.current = math.e self.display(self.current) def log(self): self.result = False self.current = math.log(float(txtDisplay.get())) self.display(self.current) def log2(self): self.result = False self.current = math.log2(float(txtDisplay.get())) self.display(self.current) def log10(self): self.result = False self.current = math.log10(float(txtDisplay.get())) self.display(self.current) def log1p(self): self.result = False self.current = math.log1p(float(txtDisplay.get())) self.display(self.current) added_value = Calc() txtDisplay = Entry(calc, font=('arial', 20, 'bold'), bg="DarkOrange1", bd=30, width=28, justify=RIGHT) txtDisplay.grid(row=0, column=0, columnspan=4, pady=1) txtDisplay.insert(0,"0") numberpad = "789456123" i=0 btn=[] for j in range(2,5): for k in range(3): btn.append(Button(calc, width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, text = numberpad[i])) btn[i].grid(row = j, column = k, pady = 1) btn[i]["command"] = lambda x = numberpad [i] : added_value.numberEnter(x) i+=1 #----------------Button standard----------------# btnClear = Button(calc, text = chr(67), width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.Clear_Entry).grid(row=1, column=0, pady=1) btnAllClear = Button(calc, text = chr(67) + chr(69), width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="red", command = added_value.all_Clear_Entry).grid(row=1, column=1, pady=1) btnSq = Button(calc, text = "√", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.squared).grid(row=1, column=2, pady=1) btnAdd = Button(calc, text = "+", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = lambda : added_value.operation("add")).grid(row=1, column=3, pady=1) btnSub = Button(calc, text = "-", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = lambda : added_value.operation("sub")).grid(row=2, column=3, pady=1) btnMult = Button(calc, text = "*", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = lambda : added_value.operation("multi")).grid(row=3, column=3, pady=1) btnDiv = Button(calc, text = chr(247), width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = lambda : added_value.operation("divide")).grid(row=4, column=3, pady=1) btnZero = Button(calc, text = "0", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = lambda : added_value.numberEnter(0)).grid(row=5, column=0, pady=1) btnDot = Button(calc, text = ".", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = lambda : added_value.numberEnter(".")).grid(row=5, column=1, pady=1) btnPM = Button(calc, text = chr(177), width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.mathsPM).grid(row=5, column=2, pady=1) btnEquals = Button(calc, text = "=", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.sum_of_total).grid(row=5, column=3, pady=1) #----------------scientific boring part----------------# btnPi = Button(calc, text = "π", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.pi).grid(row=1, column=4, pady=1) btnCos = Button(calc, text = "cos" + chr(69), width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.cos).grid(row=1, column=5, pady=1) btnTan = Button(calc, text = "tan", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.tan).grid(row=1, column=6, pady=1) btnSin = Button(calc, text = "sin", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.sin).grid(row=1, column=7, pady=1) btn2Pi = Button(calc, text = "2π", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.tau).grid(row=2, column=4, pady=1) btnCosh = Button(calc, text = "cosh", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.cosh).grid(row=2, column=5, pady=1) btnTanh = Button(calc, text = "tanh", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.tanh).grid(row=2, column=6, pady=1) btnSinh = Button(calc, text = "sinh", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.sinh).grid(row=2, column=7, pady=1) btnLog = Button(calc, text = "log", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.log).grid(row=3, column=4, pady=1) btnExp = Button(calc, text = "Exp", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.exp).grid(row=3, column=5, pady=1) btnMod = Button(calc, text = "Mod", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1",).grid(row=3, column=6, pady=1) btnE = Button(calc, text = "e", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.e).grid(row=3, column=7, pady=1) btnLog2 = Button(calc, text = "log2", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.log2).grid(row=4, column=4, pady=1) btndeg = Button(calc, text = "deg", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.degrees).grid(row=4, column=5, pady=1) btnAcosh = Button(calc, text = "acosh", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.acosh).grid(row=4, column=6, pady=1) btnAsinh = Button(calc, text = "asinh", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.asinh).grid(row=4, column=7, pady=1) btnLog10 = Button(calc, text = "log10", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.log10).grid(row=5, column=4, pady=1) btnLog1p = Button(calc, text = "log1p", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.log1p).grid(row=5, column=5, pady=1) btnExpm1 = Button(calc, text = "expm1", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.expm1).grid(row=5, column=6, pady=1) btnLgamma = Button(calc, text = "lgamma", width=6, height=2, font=('arial', 20, 'bold'), relief=GROOVE, bd = 4, bg="DarkOrange1", command = added_value.lgamma).grid(row=5, column=7, pady=1) lblDisplay = Label(calc, text="Scientific Calculator", font=('arial', 20, 'bold'), justify=CENTER) lblDisplay.grid(row = 0, column=4, columnspan = 4) #----------------Menu----------------# def iExit(): iExit = tkinter.messagebox.askyesno("Scientific Calculator", "Conirm you want to exit") if iExit > 0: root.destroy() return def Scientific(): root.resizable(width=False, height=False) root.geometry("990x580+0+0") def Standard(): root.resizable(width=False, height=False) root.geometry("500x580+0+0") menubar = Menu(calc) filemenu = Menu(menubar, tearoff=0) menubar.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Standard", command = Standard) filemenu.add_command(label="Scientific", command = Scientific) filemenu.add_separator() filemenu.add_command(label="Exit", command = iExit) root.config(menu=menubar) root.mainloop()
08ea5d2d8c137b3536eda3ea78ea2bd13385a382
junedsaleh/Python-Programs
/Programs/1city.py
153
3.9375
4
i = input("Enter Number") i = int(i) j = 0 cnm= [] for j in range(i): n=input("Enater City Name") cnm.append(n) cnm. print(cnm)
142376bb56fa6c4f988533bc181a423c482e5eeb
Ayu-99/python2
/session2(e).py
322
3.8125
4
# Identity and Membership operators n1 = 10 n2 = 10 print( n1 is n2) # identity operators print( n1 == n2 ) #print( n1 is not n2) #print( n1 != n2) rollNumbers = [1, 2, 3, 4, 5] print(4 in rollNumbers) # MemberShip operators print( 40 not in rollNumbers) # Explore Membership operators on Tuple, Set and Dictionary
d328a20420e46b690568e4a28a50740cf6a7094b
LouisHadrien/Big-data-algorithm
/join2_reducer.py
760
3.640625
4
#!/usr/bin/env python import sys # imput from the mapper are: show,number of view or show,ABC (name of Channel) show = None #initialize these variables prev_show= None count= 0 for line in sys.stdin: line = line.strip() #strip out carriage return key_value = line.split(' ') #split line, into key and value, returns a list show=key_value[0] # name of TV show value=key_value[1] # channel ABC or count of view #print(show,value) if show!= prev_show: count=int(value) prev_show=show else: if value.isdigit(): # check if it is ABC or number of view count+=int(value)3 # sum view for a same show prev_show=show else: if value=='ABC': print('{0} {1}'.format(show,count)) count=0 prev_show=show
725136709eeda01167ace6061b9d540ae6c98eca
ChangxingJiang/LeetCode
/1301-1400/1325/1325_Python_1.py
1,035
3.78125
4
from toolkit import TreeNode from toolkit import build_TreeNode class Solution: def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode: def dfs(node): if node.left and dfs(node.left): node.left = None if node.right and dfs(node.right): node.right = None return not node.left and not node.right and node.val == target dfs(root) if not root.left and not root.right and root.val == target: return None return root if __name__ == "__main__": # [1,null,3,null,4] print(Solution().removeLeafNodes(build_TreeNode([1, 2, 3, 2, None, 2, 4]), 2)) # [1,3,null,null,2] print(Solution().removeLeafNodes(build_TreeNode([1, 3, 3, 3, 2]), 3)) # [1] print(Solution().removeLeafNodes(build_TreeNode([1, 2, None, 2, None, 2]), 2)) # []] print(Solution().removeLeafNodes(build_TreeNode([1, 1, 1]), 1)) # [1,2,3] print(Solution().removeLeafNodes(build_TreeNode([1, 2, 3]), 1))
ccda3f49b30aa82a6115cfa1e2f08e173d704be9
ilailabs/python
/tutorials/linkedList.py
524
3.890625
4
class Node: def __init__(self, data = None): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def printList(self): temp = self.head while(temp): print(temp.data) temp = temp.next llist = LinkedList() llist.head = Node("mon") e2 = Node("tue") e3 = Node("wed") e4 = Node("thur") e5 = Node("fri") e6 = Node("sat") llist.head.next = e2 e2.next = e3 e3.next = e4 e4.next = e5 e5.next = e6 llist.printList()
d6f2929d44dbd5f1fe4d15354726518a8cf0ef5c
HEroKuma/leetcode
/1277-largest-multiple-of-three/largest-multiple-of-three.py
1,608
4.15625
4
# Given an integer array of digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. # # Since the answer may not fit in an integer data type, return the answer as a string. # # If there is no answer return an empty string. # #   # Example 1: # # # Input: digits = [8,1,9] # Output: "981" # # # Example 2: # # # Input: digits = [8,6,7,1,0] # Output: "8760" # # # Example 3: # # # Input: digits = [1] # Output: "" # # # Example 4: # # # Input: digits = [0,0,0,0,0,0] # Output: "0" # # #   # Constraints: # # # 1 <= digits.length <= 10^4 # 0 <= digits[i] <= 9 # The returning answer must not contain unnecessary leading zeros. # # class Solution: def largestMultipleOfThree(self, digits: List[int]) -> str: list0 = sorted([d for d in digits if d%3==0]) list1 = sorted([d for d in digits if d%3==1]) list2 = sorted([d for d in digits if d%3==2]) s = (len(list1) + len(list2)*2)%3 if s==1: if list1: list1=list1[1:] elif len(list2)>=2: list2=list2[2:] else: raise Exception("check logic") elif s==2: if list2: list2=list2[1:] elif len(list1)>=2: list1=list1[2:] else: raise Exception("check logic") #print(list0, list1, list2) final = sorted(list0+list1+list2, reverse=True) if final and final[0]==0: return "0" return "".join(str(n) for n in final)
e6e83f36fde9f3e3615c5a42eb6073fed9e0df43
MonteYang/do_leetcode
/code/14.最长公共前缀.py
1,017
3.59375
4
# # @lc app=leetcode.cn id=14 lang=python3 # # [14] 最长公共前缀 # # @lc code=start class Solution: def longestCommonPrefix(self, strs): """获得 list of string 的公共子串 Args: strs (list): a list of string Returns: str: 公共自创 """ if not strs: return "" commom = strs[0] for i in range(1, len(strs)): commom = self.getCommonPrefix(commom, strs[i]) if commom == "": return "" return commom def getCommonPrefix(self, str1, str2): """返回str1和str2的公共子串 Args: str1 (string): 第一个字符串 str2 (string): 第二个字符串 Returns: string: 公共字符串 """ i = 0 while i < min(len(str1), len(str2)): if str1[i] == str2[i]: i += 1 else: break return str1[:i] # @lc code=end
40da8ab73740dc3ccd54e7c88dfc56c8fbe411f9
woomin-Shim/Python
/car/car.py
355
3.75
4
class Car: def __init__(self): self._speed = 0 def get_speed(self): return self._speed def start(self): print("Engine Start.") self._speed = 10 def accelerate(self): print("가속합니다.") self._speed += 30 def stop(self): print("정지합니다.") self._speed = 0
831e5bb5428964879e6cf64ca8291cd1771db5dc
wenqiang0517/PythonWholeStack
/day23/01-内容回顾.py
1,619
3.609375
4
# 面向对象 # 类 对象/实例 实例化 # 类是具有相同属性和相似功能的一类事物 # 一个模子\大的范围\抽象 # ***************** # 你可以清楚的知道这一类事物有什么属性,有什么动作 # 但是你不能知道这些属性具体的值 # 对象===实例 # 给类中所有的属性填上具体的值就是一个对象或者实例 # 只有一个类,但是可以有多个对象都是这个类的对象 # 实例化 # 实例 = 类名() # 首先开辟空间,调用init方法,把开辟的空间地址传递给self参数 # init方法中一般完成 : 把属性的值存储在self的空间里 - 对象的初始化 # self这个地址会作为返回值,返回给"实例" # 方法 : 定义在类里的函数,并且还带有self参数 # 实例变量 : self.名字 # 类 : 这个类有什么属性 用什么方法 大致的样子 # 不能知道具体的属性对应的值 # 对象 :之前所有的属性值就都明确了 # 类型 :int float str dict list tuple set -- 类(内置的数据类型,内置的类) # 变量名 = xx数据类型对象 # a = 10 # b = 12.5 # l = [1,2,3] # d = {'k':'v'} # o = 函数 # q = 迭代器 # u = 生成器 # i = 类名 # python中一切皆对象,对象的类型就是类 # 所有的对象都有一个类型,class A实例化出来的对象的类型就是A类 # 123的类型是int/float # 'ajksfk'的类型是str # {}的类型是dict # alex = Person()的类型是Person # 小白 = Dog()的类型是Dog # def abc():pass # print(type(abc))
3ac4d1fdcb2de17dba638fa12c46bacac65901e6
tanmaybanga/Carleton-University
/COMP-1405/Assignment2/2a/a2q1b.py
1,206
4
4
#Imran Juma 101036672 #Assignment 2 #Question 1 Part 2 #Guess Who Goes to "No" Statement #-----------------------------------------------------------------------Citations-----------------------------------------------------------------------# #Book Citation: #Giddis, T. (2014) Starting Our With Python (Third Edditon). (pp 1-615) #Website Citation #Tutorial Citation #----------------------------------------------------------------------Program Begins-------------------------------------------------------------------------# #This Will Print My Introduction Statement #This Will Also Print The Skip A Line Function print ("\n") print ("Welcome To Imran's Guess Who Round 2!") print ("**First Letter Of The Answer Must Be Capital**") print ("\n") #This Will Print Out The Question Selection = input("Does Your Character Have a scar Yes Or No?\n") #User Responce If Captial Y if Selection == ("Yes"): print ("Try Again\n") #Question Goes Directly to else statement else: print ("Correct, None of the face options have scars") print ("\n") #----------------------------------------------------------------------Program Ends-------------------------------------------------------------------------#
b803f6654714023b99d3238084ce7fda3d16cd14
GitBulk/pyone
/p35/fs/PyFirst/PyFirst/text.py
614
3.734375
4
x = "There are %d types of people." % 10 print(x) binary = "binary" doNot = "don't" y = "Those who know %s and those who %s." % (binary, doNot) print(y) i = int(-5.7777) print(i) s = int("1231", 5) print(s) hello = None res1 = hello is None res2 = hello is not None print(res1) print(res2) print(bool(0)) print(bool(123)) print(bool(-22)) a = 10 b = 4 z = a // b print(z) z = a / b print(z) myString = "hello " "world " "of " "Python" print(myString) sizes = ["small", "medium", "large", "x-large"] for x in sizes: print(x) print("-----------") for i in range(len(sizes)): print(sizes[i])
41dd4b4d3c8cdeecb7145d0cb525b0665a3cf9e7
WilliamSimoni/Neural_Network_Simulator
/Test/test_loss.py
932
3.5
4
""" Module test_loss test the loss Module """ import unittest import numpy as np from loss import * class TestLoss(unittest.TestCase): """ TestLoss is an unittest Class to test the Loss module """ def test_euclidean_loss(self): """ Test the euclidean loss with valid values """ self.assertEqual(1, euclidean_loss(np.array([2]), np.array([3]))) self.assertEqual(3, euclidean_loss(np.array([[1, 3, 3]]), np.array([[0, 1, 1]]))) def test_invalid_euclidean_loss(self): """ Test the euclidean loss with invalid values in input """ try: self.assertRaises(ValueError, euclidean_loss(np.array([1]), [1])) self.assertRaises(ValueError, euclidean_loss([1], np.array([1]))) self.assertRaises(ValueError, euclidean_loss(np.array([1]), np.array([1]))) except: pass
b7a2a3be31c05c30b0a7681671aa8bb632a370f5
Maulikchhabra/Python
/LearningPython/sets.py
2,617
4.34375
4
#Syntax => set={val1,val2,val3} days={"Mon","Tue","Wed","Thurs","Fri","Sat","Sun"} print(type(days)) print(days) list=[1,2,3,4,5] setList=set(list) #convert any other data structure into sets print(setList) #Heterogenous set1={True,"abc",12} #with immutable elements print(set1) #set2={12,25,[1,2,3]} with mutable elements (GIVES ERROR) #Empty set creation set2={} #will create empty dictionary so incorrect set3=set() #will correct empty set #Duplicate elements set3={1,2,2,3,3,4} print(set3) #Insertion into set setList.add(6) #add() function inserts the element to the set print(setList) setList.update({7,8,9,10}) #update() function inserts more than one element to the set # update function requires argument as an iterable like list,set ,dictionary print(setList) #Deletion on set # discard() and remove() methods #if item to be deleted is not present in set ,discard() does nothing while remove() throws error. setList.discard(10) setList.discard(15) print(setList) setList.remove(9) #setList.remove(16) throws error as it is not in set print(setList) #pop() method can also be used which generally eliminates last element but do not work properly in case of unsorted sets. setList.pop() print(setList) setList2={2,1,5,3,7} #unsorted set setList2.pop() print(setList2) #clear() method entirely empties the set removing all element setList2.clear() print(setList2) #Set operations a={1,2,3,4} b={4,5,6} #Union of two sets (|) print(a|b) #union operation print(a.union(b)) #union() method #Intersection of two sets (&) print(a&b) #intersection operation print(a.intersection(b)) #intersection() method #Intersection-update => removes the items from original set that are not present in both sets c={1,2,3,4,5} d={4,5,6,7,8} c.intersection_update(d) #will delete all elements except 4 and 5 print(c) #Difference of two sets print(a-b) #difference operator print(a.difference(b)) #difference() method #Symmetric difference (^) => delete the common part of both the sets and merge the else print(a^b) #symmetric operator print(a.symmetric_difference(b)) #symmetric difference method() #Set comparisons e={1,2,3,4} f={2,4} print(e>f) print(e<f) print(e==f) #Frozen sets (cam't be altered by add or remove functions as these sets are immutable.) froze1=frozenset(a) #passing only iterables as arguments print(type(froze1)) print(froze1) #Some built-in functions #Isdisjoint(...) return true if two sets have null intersection #Issubset(...) report whether another set contains this set. #Issuperset(...) report whether this set contains another set. #symmetric_difference_update()