blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
d8a9530663b133d3350bbeccf3988c2a8f738d16
jvkus/PyGame-SkEtch
/main.py
1,987
3.59375
4
# Author: Joanna Kus import pygame as pg from time import sleep r = int(input("Pick a red value.")) g = int(input("Pick a green value.")) b = int(input("Pick a blue value.")) bgColor = (r, g, b) White = (255, 255, 255) (width, height) = (700, 700) coords = [350, 350] oldCoords = [350, 350] drawBool = True cursorBool = True pg.init() pg.mouse.set_cursor(*pg.cursors.diamond) #Creates the screen. screen = pg.display.set_mode((width, height)) pg.display.set_caption('Etch-A-Sketch') screen.fill(bgColor) #Updates the screen. pg.display.flip() running = True while running: #Stops the game from running when you click the X button. for event in pg.event.get(): if event.type == pg.QUIT: running = False #I - Up. K - Down. J - Left. L - Right. if pg.key.get_pressed()[pg.K_i]: if coords[1] >= 1: coords[1] -= 1 if pg.key.get_pressed()[pg.K_k]: if coords[1] < 699: coords[1] += 1 if pg.key.get_pressed()[pg.K_j]: if coords[0] >= 0: coords[0] -= 1 if pg.key.get_pressed()[pg.K_l]: if coords[0] <= 698: coords[0] += 1 if pg.key.get_pressed()[pg.K_p] and drawBool: drawBool = False elif pg.key.get_pressed()[pg.K_p] and not drawBool: drawBool = True #Locks the cursor on the window. if pg.key.get_pressed()[pg.K_ESCAPE] and cursorBool: cursorBool = False elif pg.key.get_pressed()[pg.K_ESCAPE] and not cursorBool: cursorBool = True #Clears the screen. if pg.key.get_pressed()[pg.K_y]: screen.fill(bgColor) #Keeps it from drawing too fast. sleep(0.015) #Draws a white line on the screen from 0,0 to 50,30, 5px wide. if drawBool: pg.draw.line(screen, White, oldCoords, coords, 2) if cursorBool: pg.mouse.set_pos(coords) pg.display.flip() #Helps draw the lines. oldCoords = coords #This actually closes the window. pg.quit()
d6d119a01d844faaa2330167e9e29246835bafe6
Annisotropy/Python
/HW6/Task2.py
327
3.59375
4
class Road: def __init__(self, length, width): self._length = length self._width = width self.mass1sm = 10 self.height = 5 def mass(self): bitumen_mass = self._length * self._width * self.mass1sm * self.height return bitumen_mass road = Road(1, 2) print(road.mass())
6699bddd388f902c2380297f669f178190998fe2
Annisotropy/Python
/HW4/Task2.py
174
3.65625
4
my_numbers = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55] new_list = [my_numbers[i] for i in range(1, len(my_numbers)) if my_numbers[i] > my_numbers[i-1]] print(new_list)
2e3c62a0757ae2f8f9cf4bbed7733bd74d9bb482
Annisotropy/Python
/HW2/Task3.py
594
3.90625
4
#1 month1 = input('Введите любой месяц цифрой от 1 до 12: ') my_dict = {'1': 'winter', '2': 'winter', '3': 'spring', '4': 'spring', '5': 'spring', '6': 'summer', '7': 'summer', '8': 'summer', '9': 'autumn', '10': 'autumn', '11': 'autumn', '12': 'winter'} print(my_dict[month1]) #2 month2 = input('Введите любой месяц цифрой от 1 до 12: ') my_dict = {'winter': ['1', '2', '12'], 'spring': ['3', '4', '5'], 'summer': ['6', '7', '8'], 'autumn': ['9', '10', '11']} for k, v in my_dict.items(): if month2 in v: print(k)
abbab3f0997e611484012c1616af259d44fe6176
alex-code4okc/advent-of-code2020
/Day2/day2_part2.py
855
3.734375
4
def result() -> int: result = None with open("input_day2.txt", "rt") as file: lines = file.readlines() # remove new lines lines = [l.strip() for l in lines] acceptable = [] for line in lines: condition, password = line.split(":") min_max, character = condition.split(" ") pos1, pos2 = min_max.split("-") pos1 = int(pos1) - 1 pos2 = int(pos2) - 1 password = password.strip() condition1 = password[pos1] == character condition2 = password[pos2] == character if (condition1 and not condition2) or (not condition1 and condition2): acceptable.append(True) else: acceptable.append(False) result = acceptable.count(True) return result result()
7c9879abac0149b1c072961e66d7364716410962
kim-hwi/Python
/softeer/8단미션.py
210
4.03125
4
import sys arr = [int(i) for i in input().split()] # print(arr) if arr == [1, 2, 3, 4, 5, 6, 7, 8]: print("ascending") elif arr == [8, 7, 6, 5, 4, 3, 2, 1]: print("descending") else: print("mixed")
e304f219f92cde59c80352cdcd554fe77579db1f
kim-hwi/Python
/Heap/이중우선순위큐.py
868
3.59375
4
import heapq def solution(operations): print(operations) heap1 = [] for i in operations: if i[0] == 'I': heapq.heappush(heap1, int(i[2:])) if i[0] == 'D': if len(heap1) == 0: continue if i[2:] == '-1': heapq.heappop(heap1) if i[2:] == '1': temp = [] while len(heap1) > 1: heapq.heappush(temp, heapq.heappop(heap1)) heap1 = temp.copy() answer = [0, 0] if len(heap1) == 0: answer = [0, 0] elif len(heap1) == 1: answer[0] = heapq.heappop(heap1) answer[1] = answer[0] elif len(heap1) > 1: answer[1] = heapq.heappop(heap1) while len(heap1) > 1: heapq.heappop(heap1) answer[0] = heapq.heappop(heap1) return answer
844d2367e9bd785b7a4757b42cac052ef66f8fac
kim-hwi/Python
/basictest/나이순 정렬.py
244
3.578125
4
num = int(input()) arr = [[0,0,'']for i in range(num)] for i in range(num): arr[i][0] = i arr[i][1],arr[i][2] = map(str,input().split()) arr.sort(key = lambda x:(int(x[1]),int(x[0]))) for i in range(num): print(arr[i][1],arr[i][2])
f3aa094a2bca69fd9aa554f3959a924477d3fe7d
kim-hwi/Python
/basictest/영화감독 숌.py
155
3.5
4
testcase = int(input()) count = 0 num = 665 while testcase > count: num += 1 temp = str(num) if "666" in temp: count+=1 print(num)
ff0ae3aeab1e651665b7f47bc292c8d8718879aa
todixon/practice
/recursive.py
175
4.03125
4
def recursive(input): if input <= 0: return input else: output = recursive(input - 1) print(output) return output print(recursive(2))
70a5488de69e2f96eba33b2c152ef6d9d2886722
todixon/practice
/hello.py
504
4.09375
4
# This program says hello and asks for my name print('Hello world!') print('What is your name?') # ask for their name myName = input() print('It is good to meet you, ' + myName) print('the length of your name is:') print(len(myName)) print('What is your age?') myAge = int(input()) print('You will be ' + str(int(myAge) + 1) + ' in a year.') if myName == 'Alice': print('Hi Alice') elif myAge < 12: print('You are not Alice, kiddo') else: print('You are neither Alice nor a little kid')
d133c88ca79b8e137ba209e36ddfb28ceb4cf042
prtha112/math-lab
/set_intersection.py
235
4
4
def intersection(set1, set2): inter = list(set(set1) & set(set2)) return inter set_1 = [1,1,2] set_2 = [3,1,2,4,5] print(intersection(set_1, set_2)) set_1 = ['A','B','C'] set_2 = ['C','E', 1] print(intersection(set_1, set_2))
b463b7ae82416f4e22ccbf1b08656edba195f529
mariellefoster/learning
/number_theory/abundant.py
242
3.84375
4
def abundant(): for i in range(2, 1000): if i < sum_divisors(i): print "abundant: " + str(i) if i%2 == 1: print "ODD" def sum_divisors(n): summ = 0 for i in range(1, n/2+1): if n%i == 0: summ += i return summ abundant()
065126994ccd96ae78bd147762f3ce193c089138
Davidzuluagag/PROGRAMATION
/Talleres y tareas/Taller-prequiz1.py
766
3.984375
4
#-----------MENSAJES---------------# MENSAJE_BIENVENIDO = "Bienvenido" PREGUNTA_PACIENTES = "Ingrese numero de pacientes" MENSAJE_BAJO = "Riesgo bajo" MENSAJE_MEDIO = "Riesgo medio" MENSAJE_ALTO = "Riesgo alto" PREGUNTA_UCI = "Ingrese numero de pacientes en UCI" #-----------ENTRADAS------------# _numeroPacientes = " " _numeroUCI = " " #-----------CODIGO-------------# print(MENSAJE_BIENVENIDO) _numeroPacientes = int(input (PREGUNTA_PACIENTES)) if ((_numeroPacientes > 0) and (_numeroPacientes <= 1000)): print (MENSAJE_BAJO) elif ((_numeroPacientes >= 1000) and (_numeroPacientes < 5000)): _numeroUCI = int(input(PREGUNTA_UCI)) if (_numeroUCI >=1000): print (MENSAJE_ALTO) else: print(MENSAJE_MEDIO) else: print (MENSAJE_ALTO)
3e5efb7bdfe7d2d4f3438ab28c8b070dd0b836ef
Davidzuluagag/PROGRAMATION
/Examenes/Quiz 1.py
1,122
4
4
#-----------MENSAJES---------------# PREGUNTA_TEMPERATURA = "Igrese temperatura corporal (en °C) del usuario" PREGUTA_PROCEDENCIA = "Ingrese procedencia del usuario" MENSAJE_HIPOTERMIA = "Hipotermia" MENSAJE_SALUDABLE = "Saludable" MENSAJE_ALERTA = "Alerta" MENSAJE_PELIGRO = "Peligro" MENSAJE_OBSERVACIÓN = "En observación" MENSAJE_DESPEDIDA = "Siguiente" #-----------ENTRADAS------------# _temperturaUsuario = 0.0 _procedenciaUsuario = " " CHINA = "china" ITALIA ="italia" IRAN = "iran" #-----------CODIGO-------------# _temperturaUsuario = float(input (PREGUNTA_TEMPERATURA)) if (_temperturaUsuario < 36): print (MENSAJE_HIPOTERMIA) elif ((_temperturaUsuario >= 36) and (_temperturaUsuario < 38.5)): print(MENSAJE_SALUDABLE) elif ((_temperturaUsuario >= 38.5) and (_temperturaUsuario < 40)): print(MENSAJE_ALERTA) else: print(MENSAJE_PELIGRO) _procedenciaUsuario = (input(PREGUTA_PROCEDENCIA)) if ((_procedenciaUsuario == CHINA) or (_procedenciaUsuario == ITALIA) or (_procedenciaUsuario == IRAN)): print (MENSAJE_OBSERVACIÓN) print (MENSAJE_DESPEDIDA) else: print (MENSAJE_DESPEDIDA)
9682bdce76206453617d5b26c2c219becb5d4001
yougov/tortilla
/tortilla/formatters.py
444
4.125
4
# -*- coding: utf-8 -*- def hyphenate(path): """Replaces underscores with hyphens""" return path.replace('_', '-') def mixedcase(path): """Removes underscores and capitalizes the neighbouring character""" words = path.split('_') return words[0] + ''.join(word.title() for word in words[1:]) def camelcase(path): """Applies mixedcase and capitalizes the first character""" return mixedcase('_{0}'.format(path))
ec23e639c78ecc7b4134ae5361e0d3acb00fb787
davidcmm/campinaPulse
/scripts/analise/dadosSet17/usuario/fixnames.py
727
3.5
4
# coding=utf-8 # This script receives a file with street names, qscores and lat/long and replaces street names whitespaces with _ import sys if __name__ == "__main__": if len(sys.argv) < 2: print "Uso: <arquivo com ruas, qscore e lat/long>" sys.exit(1) data_file = open(sys.argv[1], "r") lines = data_file.readlines() data_file.close() output_file = open(sys.argv[1], "w") for line in lines: data = line.split("+") question = data[0].strip(" \t") street = data[1].strip(" \t") qscore = data[2].strip(" \t") lat = data[3].strip(" \t") lon = data[4].strip(" \t") street_name = street.replace(" ", "_") output_file.write(question+"+"+street_name+"+"+qscore+"+"+lat+"+"+lon) output_file.close()
bcfc6b454ca877ba7650b1ea12be892b1e978b04
abhishekshahane/username
/func.py
1,007
3.890625
4
""" DO NOT MODIFY THE CODE BELOW THIS LINE. """ import sqlite3 #Getting the sqlite connection conn = sqlite3.connect('example.db') #Creating a object out of that connection. cursor = conn.cursor() #Creating the table here sql ='''CREATE TABLE USERNAME( USERNAME CHAR(100) NOT NULL, WEBSITE CHAR(1000) )''' #If there are two tables, drop one here. cursor.execute("DROP TABLE IF EXISTS USERNAME") cursor.execute(sql) # Execute code if finished. print("Finished loading all tables......") print("Now commiting.........") #Function decs. def putin(username, website): b = cursor.execute("INSERT INTO USERNAME(USERNAME, WEBSITE) VALUES(?, ?)", (username, website)) conn.commit() print("Record inserted.......") def displayout(website): cursor.execute("SELECT USERNAME FROM USERNAME WHERE WEBSITE=?", (website,)) a = str(cursor.fetchone()) a=a.replace("(","") a=a.replace(")","") a=a.replace(",","") print("The username for the website {} is: {}".format(website,a))
62a8b8245b4877f2e8f1599dfea13fc520e06032
vinay59530/spy-chat
/spydetails.py
1,045
3.75
4
spy_is_online=False spy_name = raw_input("Enter your Name") spy_salutation= raw_input("Are You Mr. or Ms. ?") spy_password=raw_input("Create your password") print("you have created a password") spy_age = raw_input("Enter your age") spy_rate=raw_input("Enter your rating (out of 5)") if len(spy_name)>0 and spy_age>="18" and spy_age<="45" and spy_rate>="3.0" and spy_rate<="5.0": print"Congratulations " +spy_salutation +spy_name, print"! \nYou have successfully created your account" spy_is_online=True else: print"Sorry!could not proceed\neither you have entered wrong input or your details doesn't fulfil our requirements" friends = [ { 'name': 'Nitesh', 'saultation': 'Mr.', 'rating': 4.5, 'age': 25, 'chats': [] }, { 'name': 'Shreya', 'saultation': 'Ms.', 'rating': 4.4, 'age': 21, 'chats': [] }, { 'name': 'abhilash', 'saultation': 'Mr.', 'rating': 4, 'age': 19, 'chats': [] } ]
63252875d59ce1d4ed17864e6d85a96ce555198e
kaiocp/uri-challenges
/python/1042.py
177
3.71875
4
a, b, c = map(int, input().split()) _list = [a, b, c] sorted_list = sorted(_list) for number in sorted_list: print(number) print() for number in _list: print(number)
bba37baa003b4b07bb31c1b5bfac36bb9f9c1afa
kaiocp/uri-challenges
/python/1066.py
516
3.75
4
# storing values _list = [] for num in range(5): num = int(input()) _list.append(num) # counting evens and odds evens, odds = 0, 0 for num in _list: if num % 2 == 0: evens += 1 else: odds += 1 # counting positives and negatives pos, neg = 0, 0 for num in _list: if num > 0: pos += 1 elif num < 0: neg += 1 print(f"{evens} valor(es) par(es)\n" f"{odds} valor(es) impar(es)\n" f"{pos} valor(es) positivo(s)\n" f"{neg} valor(es) negativo(s)")
4664d11d11dcfdd9a52868c6f9afaaee7721f3bd
kaiocp/uri-challenges
/python/1037.py
322
3.765625
4
ent = float(input()) if ((ent >= 0) and (ent <= 25)): print("Intervalo [0,25]") elif ((ent > 25) and (ent <= 50)): print("Intervalo (25,50]") elif ((ent > 50) and (ent <= 75)): print("Intervalo (50,75]") elif ((ent > 75) and (ent <= 100)): print("Intervalo (75,100]") else: print("Fora de intervalo")
e7e059b9395b1e22d4932f005031b549a59b3825
kaiocp/uri-challenges
/python/1060.py
231
3.90625
4
number_list = [] for number in range(0, 6): number = float(input()) number_list.append(number) pos_values = 0 for number in number_list: if number > 0: pos_values += 1 print(f"{pos_values} valores positivos")
e1f7afb9801174f5380cb56e563b09f2f6ee95f0
mdribera/project-euler
/p001.py
432
4.09375
4
# PROBLEM ONE # https://projecteuler.net/problem=1 # If we list all the natural numbers below 10 that are multiples of 3 or 5, # we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. def find_sum_of_multiples(max): total = 0 for x in range(1, max): if not(x % 3) or not(x % 5): total += x return total print find_sum_of_multiples(1000)
5531520bb4582e1fdb0c439a4aabe1de078de97e
Satomin2864/math_adventure
/chap_3/number_game.py
591
3.734375
4
from random import randint def numberGame(): number = randint(1, 100) print("number当てゲームです。") print("1~100までの数字を当ててください。") guess = int(input("いくつかと思いますか?")) while True: if number == guess: print("正解です") break elif number > guess: print("不正解です。もっと大きいです。") else: print("不正解です。もっと小さいです。") guess = int(input("いくつかと思いますか?")) numberGame()
c835f716667d2854b6658f16c45112e845376c28
baydingv/pyBase
/ex_2_6.py
991
3.984375
4
# -*- coding: utf-8 -*- #В программе генерируется случайное целое число от 0 до 100. # Пользователь должен его отгадать не более чем за 10 попыток. # После каждой неудачной попытки должно сообщаться # больше или меньше введенное пользователем число, чем то, что загадано. # Если за 10 попыток число не отгадано, то вывести загаданное число. import random m = random.randint(0,100) print('число m загадано') for i in range(10): n = int(input('введи n: ')) if n>m: print('[попытка {}] n>m'.format(i+1)) elif n<m: print('[попытка {}] n<m'.format(i+1)) else: print('угадал, это: {}'.format(m)); break; if i==9: print('не угадал, это: {}'.format(m)); break;
64accf0a27b0e44dd3cea95f2fd3b89b7f0cad56
NazeliGalsytyan/homework_python
/3_home.py
1,759
3.8125
4
#Task_1 class Circle: def __init__ (self, radius): self.radius = input("Enter circle radius value!\n") def area(self): print("The area of the circle equals:") print(int(self.radius) **2 * 3.14) def perimeter(self): print("The perimeter of the circle equals:") print(int(self.radius) *2 * 3.14) circle_area = Circle(1) circle_area.area() circle_area.perimeter() #Task_2 # class PairIndices: # def __init__(self, array, target): # self.array = array # self.target = target # def pairing(self): # set_array = set() # for i in self.array: # num_1 = self.target - i # if num_1 in set_array: # print([num_1],array[i]) # else: # set_array.add(array[i]) # #the_array = ([10,20,10,40,50,60,70]) # indices = PairIndices(([10,20,10,40,50,60,70]), 50) # indices.pairing() #Task_3 class Person: def __init__(self,name, surname, age): self.name = name self.surname = surname self.age = age class Student(Person): def __init__(self,name, surname, age, university, faculty, course): Person.__init__(self,name, surname, age) self.university = university self.faculty = faculty self.course = course class Worker(Person): def __init__(self,name, surname, age, profession, experience): Person.__init__(self,name,surname, age) self.profession = profession self.experience = experience student_1 = Student("Armen","Petrosyan",22, "YSMU", "Farmacology", 5 ) worker_1 = Worker("Alice","Shelunc", 40, "Manager", "15 years") print(student_1.name, student_1.surname, student_1.age, student_1.university, student_1.faculty, student_1.course) print(student_1.__dict__) print(worker_1.name, worker_1.surname, worker_1.age, worker_1.profession, worker_1.experience) print(worker_1.__dict__)
1242dfb0fe79c5b10a512eea2ef543bb4068c4f4
NazeliGalsytyan/homework_python
/4_home.py
1,979
4
4
class Country: def __init__(self, continent,name_country): self.continent = continent self.name_country = name_country def country_presemtation(self): country_return = F"This prodact is made in {self.continent} in {self.name_country}." return country_return class Brand: def __init__(self,name_brand,start_date): self.name_brand = name_brand self.start_date = start_date def brand_presentation(self): brand_return = F"The brand is {self.name_brand}, which has been founded on {self.start_date}." return brand_return class Season: def __init__(self,name_season, average_temp): self.name_season = name_season self.average_temp = average_temp def season_presentation(self): season_return = F"In {self.name_season} the averege temperature is {self.average_temp} celcius." return season_return class Product(Country,Brand,Season): def __init__(self, name,type_,quantity,price,continent,name_country,name_brand, start_date,name_season,average_temp): self.name = name self.type_ = type_ self.quantity = quantity self.price = price Country.__init__(self,continent,name_country) Brand.__init__(self,name_brand, start_date) Season.__init__(self,name_season, average_temp) def product_presentation(self): print(F"{self.name} is a type of {self.type_}.\nThe price for {self.quantity} is {self.price} Euro") print(self.country_presemtation()) print(self.brand_presentation()) print(self.season_presentation()) def discount(self,percent,quantity,price): self.percent = percent self.quantity = quantity self.price = int(quantity * price * (percent / 100)) print(f"This clothing is the perfect purchase. \n\n\t And guess what? \n\nYes, we have a discount!!! \nGet {self.quantity} for {self.percent}% off, in total for {self.price} Euro.") prodact = Product("T-shirt", "clothing",1,100,"Europe","Italy","Prada",1913, "Spring", 24 ) prodact.product_presentation() prodact.discount(50,2, 100)
87c72440ec6362b1a9f1da1506c2b2c7c1d73098
NazeliGalsytyan/homework_python
/python_classes/2_homework.py
948
3.734375
4
#homwork_2 # Task_1 celsius = float(input("Temperature in celsius")) f = (celsius * 9/5) + 32 print("Temperature in fahrenheit", f) #OR # c = 25 # number = 32 # f = (c * 1.8) + 32 # print(f) # # #Task_2 # # #1 # a = 5 # b = 6 # c = 7 # z = (a+ b+ c)/3 # print(z) # #2 # z = a**c + b**c # print(z) # #3 # z = (a + b)**c # print(z) # #4 # print(str(a) + str(b) + str(c), '+', str(a) + '*' + str(b) + '*' + str(c)) # z = str (a) + str(b) + str(c) # print("Which equals", int(z) + a* b * c) # #Task_3 # #1 # x = 5 # y = x + 3 # y = int(str(y) + "2") # print(y) # #2 # x = 7 # x *=2 # num = 25 # print(num % x) # num //= 4 # print(num + x) # #3 # from movies import movie_name, movie_genre, movie_director, initial_release # print(movie_name, movie_genre, movie_director, initial_release, sep = "\n") # #4 # my_boolean = True # print(my_boolean) # print(11 > 6) # print(7 < 7) # print(8 <= 8) # print("\n\tThank you \n\t\tfor your time")
fe57a8e2f21221e250e56e7f319d448ce80533ed
NazeliGalsytyan/homework_python
/python_classes/5_homework.py
1,581
4.03125
4
#Task_1 year = int(input("Enter a year and I\'l tell you if it\'s a leap year or not. \n")) if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print("{0} is a leap year!".format(year)) else: print("{0} is not a leap year!".format(year)) else: print("{0} is a leap year!".format(year)) else: print("{0} is not a leap year!".format(year)) #Task_2 number = int(input("Enter a number and I\'ll tell you if it\'s divisible by 5 or 11 or not.\n")) if number % 5 == 0: if number % 11 == 0: print("{0} is divisible both by 5 and 11!". format(number)) else: print("{0} is divisible by 5!". format(number)) elif number % 11 == 0: print("{0} is divisible by 11!". format(number)) else: print("{0} isn\'t divisible by 5 or 11!". format(number)) #Task_3 number = int(input("Enter a number and I\'ll tell you if it\'s divisible by 3 or 5 or both, otherwise I\'ll return your number.' \n")) if number % 3 == 0: if number % 5 == 0: print("FizzBuzz") else: print("Fizz") elif number % 5 == 0: print("Buzz") else: print(number) #Task_4 def not_poor(string): s_not = string.find('not') s_poor = string.find('poor') if s_poor > s_not and s_poor > 0 and s_not > 0: string = string.replace(string[s_not:(s_poor+4)], "good") return string else: return string print(not_poor("The lyrics is not that poor!")) print(not_poor("The lyrics is poor!")) #Task_5 string = "restart" save = string[0] string = string.replace(save, '$') string = save + string[1:] print(string)
d74fa5642ef8bb8660fcf38a6466d91cef78b7e5
christopherhui/geeksforgeeks
/graphs/adjlistcol.py
481
3.765625
4
from collections import defaultdict class Graph: def __init__(self, vertices): self.graph = defaultdict(list) self.vertices = vertices def addEdge(self, u, v): if u > self.vertices or v > self.vertices: raise ValueError("Value of u or v is greater than number of vertices.") self.graph[u].append(v) a = Graph(5) a.addEdge(0, 1) a.addEdge(2, 3) a.addEdge(0, 2) a.addEdge(1, 2) a.addEdge(3, 4) a.addEdge(4, 2) a.addEdge(4, 1)
d817d8f491e23137fd24c3184d6e594f1d8381b0
GaneshManal/TestCodes
/python/practice/syncronous_1.py
945
4.15625
4
""" example_1.py Just a short example showing synchronous running of 'tasks' """ from multiprocessing import Queue def task(name, work_queue): if work_queue.empty(): print('Task %s nothing to do', name) else: while not work_queue.empty(): count = work_queue.get() total = 0 for x in range(count): print('Task %s running' % name) total += 1 print('Task %s total: %s' %(name, str(total))) def main(): """ This is the main entry point for the program """ # create the queue of 'work' work_queue = Queue() # put some 'work' in the queue for work in [15, 10, 5, 2]: work_queue.put(work) # create some tasks tasks = [ (task, 'One', work_queue), (task, 'Two', work_queue) ] # run the tasks for t, n, q in tasks: t(n, q) if __name__ == '__main__': main()
68a9fa74fcc26279e1e184eb9281e458c86b3937
GaneshManal/TestCodes
/python/practice/sqaure_generator.py
510
4.15625
4
# Generator Function for generating square of numbers def square_numbers(nums): for num in nums: yield num*num numbers = range(1, 6) gen_x = square_numbers(numbers) print "Generator Object : ", gen_x print "Generator Mem : ", dir(gen_x) """" 'print '--->', gen_x.next() print '--->', gen_x.next() print '--->', gen_x.next() print '--->', gen_x.next() print '--->', gen_x.next() # print '--->', gen_x.next() # StopIteration Exception. """ # print list(gen_x) for num in gen_x: print num,
efc7eb5facd34819df189af40bff4725e9016aca
FuzzyLogick/ChooseYourOwnAdventure-1
/pg73.py
590
3.765625
4
def text(): print("") print("") #print("[From part 81]") print("") print("Standing in line will take too long. Perhaps this man is the only way to get a message to the pharoah. But you can't say anything about the potion. You tell the man that you want to meet the pharaoh in a grove of trees by the river. You tell him it is urgent.") print("") print("As you wait by the river, you wonder when the pharaoh will arive. He never does, but the Priests of Amun-Ra do.") print("") print("") print("+ The End.") print("") print("") return
220f392ef8c5174db1f915aa8b5209a69061d715
FuzzyLogick/ChooseYourOwnAdventure-1
/pg22.py
1,456
3.90625
4
def text(): print("") print("") #print("[From part 7]") print("") print("You take the slow geology cruiser and hope for the best. You fly low over the forests and lakes of Andromeda. It works. You pass across the other side of the planet undetected by the Voxons. After you land, you are led inside the rebel stronghold. The three of you are introduced to the rebel leader, Alf Gan-Rosh.") print('"To defeat Lord Snag, we need the Stone of Narvelin," says Gan-Rosh. "But the Stone is guarded by the Mangons."') print("") print('"What are Mangons?" you ask.') print('"Monsters with a keen sense of taste and smell," says Gan-Rosh. "They vaporize anyone they do not like. We have never known them to like anyone. We must act fast. Time is running out for Andromeda."') print("") print("You, Nisko and vleet discuss the problem. Vleet reminds you that they have collected many unusual minerals from different worlds. Perhaps one of them will be useful to you now. you check the ship's computer. There are three elements which may help.") print("") print("") print("[Element 40, Zenium - Brings Invisibility]") print("") print("[Element 50, Meerang - Brings the Force of Lasers]") print("") print("[Element 53, Argonix - Brings Loss of Odor]") print("") print("") print("+ Enter the element you wish to take with you to continue.") print("") print("") return
aa93a7a6ec7b84e8166bd117306902a246328a4c
FuzzyLogick/ChooseYourOwnAdventure-1
/pg28.py
1,639
4.09375
4
def text(): print("") print("") #print("[From part 27]") print("") print('"Today is the birthday of Lord Snag," says Milo, "and I am baking him a cake."') print("") print('"A poison cake, I hope," says Vleet.') print("") print('"No," says Milo. "Snag has his slaves taste the food first. The cake cannot be poisoned, but it will change Snag forever. No one will notice until it is too late. The cake will be ready in a minute. all we have to do is take it to the main kitchen and replace the real cake with ours."') print("") print('"There is only one problem wiht this plan," says Nisko. "Which of us will take the cake into the kitchen?"') print("") print('"Of course, I would be glad to," says Milo, "but I really do not feel so well. Would one of you please take it instead? It is our only chance to save Andromeda."') print("") print("You, Nisko and Vleet draw straws...") print("") print("You choose the short one.") print("") print("") print('Proud Milo gives you his cake. "Go down the hall, take the second door on the right. Just replace the old cake with this one. They will look exactly alike. All the cooks are on their break now, so the kitchen will be empty. Then just come back here and hide with us. Here - wear my old chef hat as a convincing disguise, just in case you meet any of the cooks in the hall. They will think you are one of the slave workers brought here from other worlds. Now go, before the cooks return."') print("") print("") print("+ Press Enter to continue.") print("") print("") return
c3b18a7e7f9f59926167e38351ad28e96fafbf99
FuzzyLogick/ChooseYourOwnAdventure-1
/pg92.py
999
3.65625
4
def text(): print("") print("") #print("From part 66") print("") print("Your first task is to find Dr. Walker. Whatever is shiny on top of the hill may be a clue, so you walk up there as carefully as you can. At the crest of the hill, you see something amazing: a large spaceship with its hatch open. Small grey aliens with large black eyes are walking about, working with a ray gun. Beside the aliens stand a woolly mammoth, frozen solid.") print("") print("As a bird flies overhead, an alien shoots it with the ray gun, freezes it, and drops silently from the sky. A solid thud sound was felt when it hit the ground. Then you notice a frozen saber-toothed tiger, several more birds, and a woman in a white coat. It can only be Dr. Margaret Walker!") print("") print("") print("+ If you want to approach the aliens, enter 72 to continue.") print("") print("+ If you want to remain hidden, enter 76 to continue.") print("") print("") return
e0e75e87f998f503ddcad6ee8a8fedf140a7eaa0
FuzzyLogick/ChooseYourOwnAdventure-1
/pg74.py
552
3.75
4
def text(): print("") print("") #print("[From part 21]") print("") print("The Hall of Dinosaurs is a big room, but for some reason, all the exits are blocked. The seven people now have you trapped. Giant dinosaur skeletons loom above you.") print("") print('"Give us the bottle," says the leader.') print("") print("") print("+ If you want to give them the bottle, enter 83 to continue.") print("") print("+ If you want to drink the potion, enter 89 to continue.") print("") print("") return
32642819cef74b507c4f7751c00f5840997ec062
FuzzyLogick/ChooseYourOwnAdventure-1
/pg6.py
1,312
4.0625
4
def text(): print("") print("") #print("[From part 41]") print("") print("") print("The liquid smells so good that you take just a tiny sip. It tastes wonderful, too, like honey and cinnamon. You take another sip. The planetarium speaker is saying something about the night sky in August, but the voice sounds like it is coming from underwater. You hear a gentle hum. Then all grows dark around you.") print("") print("The next thing you see is a camel, walking across the desert. you are sitting beneath a palm tree. It is very early in the morning, and the sun is just about to rise. But all around you, men, women, and children are walking to a marketplace. A huge pyramid is under construction nearby.") print("") print("The words you hear are a foreign language, yet you can somehow understand every word. you pinch yourself, but you are not dreaming. The liquid must have carried you back in time to the land of ancient Egypt!") print("") print('Suddenly three men with swords and golden armbands walk up to you and ask, "Who are you, and why are you wearing such a strange costume? Answer well, or we will send you to the galleys."') print("") print("") print("+ Press Enter to continue.") print("") print("") return
ab976a8b4180302c15e164781a2b467ade29abd4
FuzzyLogick/ChooseYourOwnAdventure-1
/pg85.py
640
3.75
4
def text(): print("") print("") #print("[From part 51 / part 65]") print("") print("You sneak away to the hidden spot where you can be alone. Opening the bottle, you recognize the familiar scent of honey and cinnamon.") print("") print("After you take a little sip, you feel warmth in your stomach. But when you look down, you see your feet have turned into the talons of a bird.") print("") print("") print("+ If you want to drink more of the liquid, enter 58 to continue.") print("") print("+ If you don't want to drink more, enter 71 to continue.") print("") print("") return
49bb7190d717037a7cd9f1518b74dcdedd99f6ed
FuzzyLogick/ChooseYourOwnAdventure-1
/pg34.py
539
3.5625
4
def text(): print("") print("") #print("[From part 23]") print("") print("") print('You call to the guard, "There is something crawling around in here. Please put is un another room."') print("") print('"The only thing crawling around will be you three spies," says the guard, "in the Mines of Pluto."') print("") print("You do not hear the tapping noise any longer. The next day you are shipped ot the Mines of Pluto.") print("") print("+ The End.") print("") print("") return
2bea88c289e7f417b5433f18af27137aed4a467d
FuzzyLogick/ChooseYourOwnAdventure-1
/pg94.py
1,152
4.03125
4
def text(): print("") print("") #print("From part 89") print("") print("You throw stones and sticks to destract the dinosaurs from the aliens. Your plan works. The dinsaurs go away. After the animals have left, you approach the aliens.") print("") print('"Thank you, Earthling," they say. "But we are dying anyway."') print("") print('"No, you are not. Not if I can help it," you say. You rush to get them water. Your quick thinking saves their lives') print("") print('Now they can begin to rebuild their spacecraft. "We are from the twenty-third century," they explain. To thank you, they bring you back to your won time, to your own home.') print("") print("In their time travels, the aliens have been to ancient Rome, Greece, and Egypt. Tonight, in your room, they happily tell you everything they discovered about these civilizations. By morning you are ready to hand in a wondertful term paper. You can't wait till their next visit. They have promised to take you along on their next trip.") print("") print("") print("+ The End") print("") print("") return
5a9161c4f8f15e0056fd425a5eee58de16ec45bf
beb777/Python-3
/003.py
417
4.28125
4
#factorial n! = n*(n-1)(n-2)..........*1 number = int(input("Enter a number to find factorial: ")) factorial = 1; if number < 0: print("Factorial does not defined for negative integer"); elif (number == 0): print("The factorial of 0 is 1"); else: while (number > 0): factorial = factorial * number number = number - 1 print("factorial of the given number is: ") print(factorial)
c7237a147182067b9f46e1f106fd946adf4849e2
haleyxu/PyPractice
/filedeal.py
794
3.921875
4
#打开文件 with open("pi_data.txt") as file_object: contents = file_object.read() print(contents) print('-' * 20) #打开文件,按行输出 file_name = "pi_data.txt" with open(file_name) as file_object: for line in file_object: print(line.rstrip()) print('-' * 20) #with代码段外使用文件内容 with open(file_name) as file_object: outfile = file_object.read() print(outfile) #写入文件 py只能写入字符串 w:写入 a:追加 r:读取(默认) r+:读取和写入 write_file_name = "write.txt" with open(write_file_name, 'w') as write_file: write_file.write("python example\n") write_file.write("3.1415926535\n") with open(write_file_name, 'a') as append_file: append_file.write("new line\n") append_file.write("Oh cool")
d692009f8dcc413c01f6621ca2dd4ce862ec117f
ankush4144/File-Handling-Questions
/question-5.py
538
3.90625
4
#Q.5- Write a Python program to write 10 random numbers into a file. #Read the file and then sort the numbers and then store it to another file. import random file1=open('d.txt','w') for i in range(1,11): file1.writelines(str(random.randrange(1,100))+'\n') file1.close() file1=open('d.txt','r') file_content=file1.readlines() file1.close() file1=open('d.txt','w') sorting=[] for i in file_content: sorting.append(int(i.strip())) sorting.sort() sorting=[str(i) for i in sorting] file1.writelines('\n'.join(sorting)) file1.close()
e4b485f80b9649d0f7bb3b9b5dbf4358a1172d84
kbm1422/New_Framework
/Sam_Test_Code/Python_Challenge_4.py
546
3.828125
4
#!/usr/bin/python # -*- coding: utf-8 -*- import urllib import re url = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=" number = "12345" R = re.compile("(\d+)$") D = re.compile("Divide") while True: source = urllib.urlopen(url + number).read() match = re.search(R, source) divide = re.search(D, source) if match: number = match.group() print number elif divide: number = str(int(number) / 2) else: break #print "the url is: %s" % url + str(int(number) / 2) print source
1c922b07b6b1f011b91bc75d68ece9b8e2958576
Leah36/Homework
/python-challenge/PyPoll/Resources/PyPoll.py
2,168
4.15625
4
import os import csv #Create CSV file election_data = os.path.join("election_data.csv") #The list to capture the names of candidates candidates = [] #A list to capture the number of votes each candidates receives num_votes = [] #The list to capture the number of votes each candidates gather percent_votes = [] #The counter for the total number of votes total_votes = 0 with open(election_data, newline = "") as csvfile: csvreader = csv.reader(csvfile, delimiter = ",") csv_header = next(csvreader) for row in csvreader: #Add to our vote-countr total_votes += 1 #If the candidate is not on our list, add his/her name to our list, along with #a vote in his/her name. #If he/she is already on our list, we will simply add a vote in his/her name. if row[2] not in candidates: candidates.append(row[2]) index = candidates.index(row[2]) num_votes.append(1) else: index = candidates.index(row[2]) num_votes[index] += 1 #Add to percent_votes list for votes in num_votes: percentage = (votes/total_votes) * 100 percentage = round(percentage) percentage = "%.3f%%" % percentage percent_votes.append(percentage) #Find the winning candidate winner = max(num_votes) index = num_votes.index(winner) winning_candidate = candidates[index] #Display the results print("Election Results") print("------------") print(f"Total Votes:{str(total_votes)}") print("------------") for i in range(len(candidates)): print(f"{candidates[1]}: {str[percent_votes[i])} ({str(num_votes[i])})") print("-----------") print(f"Winner: {winning_candidate}") print("----------") #Print to a text file output = open("output.txt", "w") line1 = "Election Results" line2 = "----------" line3 = str(f"Total Votes: {str(total_votes)}") line4 = str("----------") output.write('{}\n{}\n{}\n{}\n'.formate(line1, line2, line3, line4)) for i in range(len(candidates)): line = str(f"{candidate[i]}: {str(percent_votes[i])} ({str(num_votes[i])})") output.write('{}\n'.format(line)) line5 = "-----------" line6 = str(f"Winner: {winning_candidate}") line7 = "-----------" output.write('{}\n{}\n{}\n'.format(line5, line6,line7))
eae5cf109c9e7f40267156b4f96b8f6e6266f538
Ivoah/InteractiveFiction
/demo.py
1,755
3.859375
4
from InteractiveFiction import * world = World() @world.room('Bedroom', True) class Bedroom(Room): '''Your bedroom. There is a bathroom to the north and a living room to the south.''' south = 'Living room' north = 'Bathroom' @world.room('Living room') class LivingRoom(Room): '''A modern looking living room.''' north = 'Bedroom' class Toothbrush(Item): '''An average looking toothbrush, the bristles are visibly worn.''' def see(self): if self.world.location.name == 'Bathroom': world.print('You see a toothbrush lying on the counter.') else: world.print('You see a toothbrush lying on the ground') class Teeth(Item): '''The only set of teeth you'll get, take care of them''' shown = False def drop(self): world.print('You try to pull your teeth out of your skull, but they\'re firmly rooted') return False world.player.inventory.append(Teeth(world, 'teeth')) @world.room('Bathroom') class Bathroom(Room): '''A small bathroom. There's a tiny shower nestled in the corner next to a toilet and sink.''' items = [Toothbrush(world, 'toothbrush')] south = 'Bedroom' @world.verb('brush') def brush(world, *args): if not any(isinstance(item, Toothbrush) for item in world.player.inventory): world.print('You need a toothbrush to brush your teeth.') elif world.location.name != 'Bathroom': world.print('You look for a sink to brush your teeth but can\'t find any.') else: world.print('After two minutes of vigorous brushing, your teeth are sparkly white again.') world.tests['toothbrush'] = ['n', 'take toothbrush', 's', 'drop toothbrush', 'brush', 'take toothbrush', 'brush', 'n', 'brush'] world.run()
5797e49efd3cfc42d3e8f85b7567a4590da72f12
AndreDegel/blackjack
/PlayMain.py
554
3.9375
4
__author__ = 'Andre' """ Main method to start a blackjack game. Main in version 1.0, could use shaping up by using a loop to restart the game and create every time a new Blackjack object. from blackjack import Blackjack """ game = Blackjack() """game2 = Blackjack() """ def main(): start = input("Would you like to play a round of blackjack?[y/n] ") if start == "y": game.play() reround = input("Would you like to play another round of blackjack?[y/n] ") if reround == "y": game2 = Blackjack() game2.play() main()
ac35daa52a1319932e505b76e0a8e9bbae90889b
principia12/Algorithm-Lickers
/mcjung/remove-invalid-parentheses.py
1,857
3.546875
4
# problem link: https://leetcode.com/problems/remove-invalid-parentheses import itertools pas = ['(', ')'] class Solution: def removeInvalidParentheses(self, s: str) -> List[str]: result = set() remove_list = [] basic = self.parsing_parentheses(s) result.add(basic) pa_list = [] for i, ch in enumerate(s): if ch in pas: pa_list.append(i) diff = len(s) - len(basic) remove_list = itertools.combinations(pa_list, diff) for r_list in remove_list: tmp_l = list(s) for i in reversed(r_list): tmp_l.pop(i) if self.parsing_parentheses(tmp_l, True): tmp_s = ''.join(tmp_l) result.add(tmp_s) return list(result) def parsing_parentheses(self, s, check_valid=False): stack = list() result = list() removed = 0 for i, ch in enumerate(s): if ch == '(': stack.append([ch, i - removed]) result.append(ch) elif ch == ')': if len(stack) > 0 and stack[-1][0] == '(': stack.pop() result.append(ch) else: if check_valid: return False else: removed += 1 else: result.append(ch) for remain in stack[::-1]: if remain[0] == '(': if check_valid: return False else: result.pop(remain[1]) if check_valid: return True else: return ''.join(result)
a55dc8ef112a7043d5ab3843f618265a4103e14c
whisperity/dotfiles-framework
/dotfiles/lazy_dict.py
1,089
3.75
4
class LazyDict(dict): """ A version of dict where a user-supplied factory method can be used to provide None-marked elements. :note: Why doesn't collections.defaultdict support this... :( """ def __init__(self, factory, initial_keys=None): """ Create a new dict and register the element factory in it. :param initial_keys: (Optional) if a collection, set the given keys in the dict to None. """ super().__init__() self.factory = factory for key in initial_keys if initial_keys else []: self.__setitem__(key, None) def __getitem__(self, key): """ Returns the element for the given key, as if D[key] was called, but if the element was None, performs construction with the set factory method. If `key` isn't part of the dict, raises the same `KeyError` as a normal dict would. """ it = super().__getitem__(key) if it is None: it = self.factory(key) self[key] = it return it
71000dd86b84710b89b78315df1859d1d12d9259
pavlee/rsa
/rsa_enc.py
1,256
3.515625
4
import sys BLOK_CIFRE = 300 BLOK_KARAKTERI = BLOK_CIFRE // 3 plaintext = "" sifrovani_text = "" def encrypt(plaintext, key): ascii_plaintext = bytes(plaintext, "ASCII") # Tekst se lomi na blokove duzine najvise BLOK_KARAKTERI chara # Svaki char je predstavljen pomocu trocifrenog broja blokovi = [] for i, chars in enumerate(ascii_plaintext[::BLOK_KARAKTERI]): start = BLOK_KARAKTERI * i end = BLOK_KARAKTERI * (i + 1) blokovi.append(ascii_plaintext[start:end]) enkriptovani_blokovi = [] for blok in blokovi: broj_plaintext = 0 for i, char in enumerate(list(blok)[::-1]): # lista se reversuje i pocinjemo od nizih cifara broj_plaintext += (char * 10**(i*3)) enkriptovani_blokovi.append(pow(broj_plaintext, key[0], key[1])) # Pad each block to BLOK_CIFRE sifrovani_text = "" for blok in enkriptovani_blokovi: sifrovani_text += str(blok).rjust(BLOK_CIFRE, "0") return sifrovani_text if __name__ == "__main__": if len(sys.argv) != 4: print("Validni argumenti programa su x, N, e") quit() xprim = encrypt(str(sys.argv[1]), (int(sys.argv[3]), int(sys.argv[2]))) print("\nRezultat: \n\n{}".format(xprim))
faaf4b222a3b9e120d0197c218bcd6e25c3422a4
bwblock/Udacity
/CS101/quiz-median.py
621
4.21875
4
#! /usr/bin/env python # Define a procedure, median, that takes three # numbers as its inputs, and returns the median # of the three numbers. # Make sure your procedure has a return statement. def bigger(a,b): if a > b: return a else: return b def biggest(a,b,c): return bigger(a,bigger(b,c)) def median(a,b,c): big1 = bigger(a,b) big2 = bigger(b,c) big3 = bigger(a,c) max = biggest(a,b,c) if big1 == big2: return big3 if max == big1: return big2 else: return big1 print(median(1,3,2)) #>>> 2 print(median(9,3,6)) #>>> 6 print(median(7,8,7)) #>>> 7
01bdad6c1614a2db3d954735b3546c3b1445d452
seanluciotolentino/SimpactPurple
/simpactpurple/Operators.py
10,291
3.59375
4
""" Module for all of the default operators. """ import Queue import numpy as np import numpy.random as random class RelationshipOperator(): """ Controls the formation and dissolution of relationships between agents. At initialization, the relationship operator creates the grid queues it will need to hold agent, and starts their functioning in seperate processes. Each time step, the relationship operator does three things: 1. Dissolve relationships that have exceeded their duration 2. Recruit from the grid queues into the main queue 3. Iterate through main queue, attempting to match each suitor ` at the top of the queue. """ def __init__(self, master): self.master = master self.max_weeks = (master.MAX_AGE*52)+1 # for efficiently knowing setting the end time of relationships def step(self): """ Take a single time step in the simulation. """ #1. Recruit for i in range(self.master.recruit): self.recruit() #2. Match while not self.master.main_queue.empty(): self.match() def recruit(self): """ Pick a random grid queue and send a request for a recruit. Recruited individuals are then added to the main_queue (self.master.main_queue). """ gq = self.master.grid_queues.keys()[random.randint(len(self.master.grid_queues))] #gq = random.choice(self.master.grid_queues.keys()) self.master.pipes[gq].send("recruit") agent_name = self.master.pipes[gq].recv() if agent_name is not None: agent = self.master.agents[agent_name] self.master.main_queue.push(gq, agent) def match(self): """ Pop a suitor off the main queue and try to match him or her. """ #1. Send enquiry suitor = self.match_enquire() if not suitor: return #2. Receive replies matches = self.match_recv() #3. Process matches self.match_process(suitor, matches) def match_enquire(self): """ 1. Get next suitor in the main_queue and send request for matches for him/her from grid queues. Note that if a suitor was already matched the method will return None and not send an enquiry message. """ #1.1 Get next suitor suitor = self.master.main_queue.pop()[1] #1.2 Return if matched if self.master.network.degree(suitor) >= suitor.dnp: return #1.3 In parallel, send enquiries via pipe for pipe in self.master.pipes.values(): pipe.send("enquire") pipe.send(suitor) return suitor def match_recv(self): """ 2. Receive match messages from pipes and process them into agents. """ names = [pipe.recv() for pipe in self.master.pipes.values()] matches = [self.master.agents[n] for n in names if n is not None] return matches def match_process(self, suitor, matches): """ 3. After receiving matches allow suitor to choose. """ #3.1 Suitor flips coins with potential matches if not matches: # no matches return pq = Queue.PriorityQueue() while(matches): match = matches.pop() #calc probability (checking for pre-exisiting edge) probability = int(not self.master.network.has_edge(suitor, match))\ *self.master.probability(suitor, match) r = random.random() decision = int(r < probability) pq.put((-decision, match)) #3.2 Verify acceptance and form the relationship accept, match = pq.get() if accept: self.form_relationship(suitor, match) if self.master.network.degree(suitor) >= suitor.dnp: self.master.pipes[suitor.grid_queue].send("remove") self.master.pipes[suitor.grid_queue].send(suitor.name) if self.master.network.degree(match) >= match.dnp: self.master.pipes[match.grid_queue].send("remove") self.master.pipes[match.grid_queue].send(match.name) def form_relationship(self, agent1, agent2): """ Forms a relationship between agent1 and agent2. """ d = np.max((1, self.master.DURATIONS(agent1, agent2))) # relationships must be at least 1 week #cache the ending time for easier access end_time = int(np.min((self.master.time + d, self.master.NUMBER_OF_YEARS*52, self.max_weeks+agent1.born, self.max_weeks+agent2.born))) self.master.relationships_ending_at[end_time].append((agent1,agent2)) #add the relationship to data structures self.master.relationships.append((agent1, agent2, self.master.time, end_time)) self.master.network.add_edge(agent1, agent2, {"start":self.master.time, "end": end_time,}) #print " ++ forming relationship:", agent1.name, "and", agent2.name, "(",agent1.grid_queue,",",agent2.grid_queue,")" def dissolve_relationship(self, agent1, agent2): """ Dissolves a relationship between agent1 and agent2. """ #print " -- dissolving relationship:", agent1.name, "and", agent2.name, "(",agent1.grid_queue,",",agent2.grid_queue,")" self.master.network.remove_edge(agent1, agent2) #add agents into appropriate grid queues self.master.add_to_grid_queue(agent1) self.master.add_to_grid_queue(agent2) class TimeOperator(): """ Controls the progression of time in the simulation. In particular, the time operator updates the clocks of the queues, dissolves relationships that are past their duration, and removes agents that are beyond the maximum age. """ def __init__(self, master): self.master = master self.oldest_queues = self.master.grid_queues.keys()[:2] # needs to be generalized... def step(self): """ Take a single step in the simulation. """ #1.1 Update the clocks of the GridQueues (processes AND originals) pipes = self.master.pipes.values() for pipe in pipes: pipe.send("time") pipe.send(self.master.time) for gq in self.master.grid_queues.values(): # kinda hacky gq.time = self.master.time #1.2 Update relationships for r in self.master.relationships_ending_at[self.master.time]: self.master.relationship_operator.dissolve_relationship(r[0], r[1]) #2.1 Make a new grid queue if necessary if self.master.time%(self.master.BIN_SIZE*52)==0: self.master.make_n_queues(self.master.SEXES) #2.2 Grab oldest agents from oldest grid queues for queue in self.oldest_queues: self.master.pipes[queue].send("oldest") for queue in self.oldest_queues: msg = self.master.pipes[queue].recv() while msg != 'done': agent = self.master.agents[msg] self.remove(agent) self.replace(agent) msg = self.master.pipes[queue].recv() #2.3 Terminate old grid queue if necessary if self.master.time%(self.master.BIN_SIZE*52)==0: for queue in self.oldest_queues: self.master.pipes[queue].send("terminate") del self.master.grid_queues[queue] del self.master.pipes[queue] self.oldest_queues = self.master.grid_queues.keys()[:2] def remove(self, agent): """ Function for removing agents from the simulation. """ agent.grid_queue = None self.master.network.remove_node(agent) agent.attributes["TIME_REMOVED"] = self.master.time if agent.time_of_infection < np.inf: self.master.infection_operator.infected_agents.remove(agent) def replace(self, agent): """ Function to replace *agent*. """ self.master.make_population(1) class InfectionOperator(): """ Controls the progression of the sexually transmitted disease. """ def __init__(self, master): self.master = master self.infected_agents = [] def step(self): """ Take a single step in the simulation: Go through relationships, if relationship is serodiscordant, infect the uninfected partner with probablity this is relative to infectivity. """ #Go through edges and flip coin for infections now = self.master.time for agent in self.infected_agents: relationships = self.master.network.edges(agent) for r in relationships: if(r[0].time_of_infection < now and r[1].time_of_infection > now and random.random() < self.master.INFECTIVITY): r[1].time_of_infection = now self.infected_agents.append(r[1]) continue if(r[1].time_of_infection < now and r[0].time_of_infection > now and random.random() < self.master.INFECTIVITY): r[0].time_of_infection = now self.infected_agents.append(r[0]) def perform_initial_infections(self, initial_prevalence, seed_time): """ Seeds the population with *initial_prevalence* at *seed_time*. """ infections = int(initial_prevalence*self.master.INITIAL_POPULATION) agent = self.master.agents[random.randint(0, len(self.master.agents) - 1)] for i in range(infections): while agent in self.infected_agents: agent = self.master.agents[random.randint(0, len(self.master.agents) - 1)] #agent = random.choice(self.master.agents.values()) agent.time_of_infection = seed_time self.infected_agents.append(agent)
852b7503b5a6cba6f532058d664c3c2cd36de376
hanigue/CTU-codes
/RPH/testiky/strings.py
632
3.828125
4
from collections import Counter from os.path import splitext def count_chars_in_string(arg): cnt = Counter() for s in range(len(arg)): cnt[arg[s]] += 1 cnt.pop("\n") return cnt.most_common(len(cnt)) def count_chars_in_file(arg): with open(arg, 'r', encoding="utf-8") as f: read = f.read() cnt = count_chars_in_string(read) filename = splitext(arg)[0] with open(filename + ".freq", 'w', encoding="utf-8") as f: for key, freq in cnt: f.write(str(key + " " + str(freq) + "\n")) if __name__ == "__main__": count_chars_in_file("in.txt")
c95fe818b4b1336e49416a45e9eb8304780bbfbc
vijayboopathy-zz/learn-python
/ex5.py
485
3.90625
4
my_name = 'Vijayboopatny Elangovan' my_age = 26 my_height = 74 my_weight = 75 my_eyes = 'Black' my_teeth = 'White' my_hair = 'Black' print(f"Let's talk about {my_name}.") print(f"He's {my_height} inches tall.") print(f"He's {my_weight} pounds heavy.") print(f"Actually that's not too heavy.") print(f"He's got {my_eyes} eyes and {my_hair} hair.") print(f"His teeth are usually {my_teeth}.") total = my_age + my_height + my_weight print(f"If I add {my_age}, {my_height} and {my_weight} I get {total}")
4177affcacfc12c25bddd614f54eaa4ef31cab82
LuffySir/Python-learning
/tkinter_gui/tkinter_gui_event.py
3,669
3.640625
4
# -*- coding:utf-8 -*- import tkinter # 事件响应 # bind(seq,func,add) # bind_class(class,seq,func,add) 类绑定 # bind_all(seq,func,add) 所有组件事件绑定到事件响应函数 # seq为绑定的事件,以<>包围的字符串,如<Button-1>左键按下,<KeyPress-A>按下A键等 class MyButton: def __init__(self, root, canvas, label, type): self.root = root self.canvas = canvas self.label = label # 根据类型创建按钮 if type == 0: button = tkinter.Button(root, text='DrawLine', command=self.DrawLine) elif type == 1: button = tkinter.Button(root, text='DrawArc', command=self.DrawArc) elif type == 2: button = tkinter.Button(root, text='DrawRec', command=self.DrawRec) else: button = tkinter.Button(root, text='DrawOval', command=self.DrawOval) button.pack(side='left') def DrawLine(self): self.label.text.set('Draw Line') self.canvas.SetStatus(0) def DrawArc(self): self.label.text.set('Draw Arc') self.canvas.SetStatus(1) def DrawRec(self): self.label.text.set('Draw Rec') self.canvas.SetStatus(2) def DrawOval(self): self.label.text.set('Draw Oval') self.canvas.SetStatus(3) class MyCanvas: def __init__(self, root): self.status = 0 self.draw = 0 self.root = root self.canvas = tkinter.Canvas(root, bg='white', width=600, height=480) self.canvas.pack() # 绑定事件到左键 self.canvas.bind('<ButtonRelease-1>', self.Draw) # 绑定事件到中键 self.canvas.bind('<Button-2>', self.Exit) # 绑定事件到右键 self.canvas.bind('<Button-3>', self.Del) # 绑定事件到delete键 self.canvas.bind_all('<Delete>', self.Del) self.canvas.bind_all('<KeyPress-d>', self.Del) self.canvas.bind_all('<KeyPress-e>', self.Exit) def Draw(self, event): if self.draw == 0: self.x = event.x self.y = event.y self.draw = 1 else: if self.status == 0: self.canvas.create_line(self.x, self.y, event.x, event.y) self.draw = 0 elif self.status == 1: self.canvas.create_arc(self.x, self.y, event.x, event.y) self.draw = 0 elif self.status == 2: self.canvas.create_rectangle(self.x, self.y, event.x, event.y) self.draw = 0 else: self.canvas.create_oval(self.x, self.y, event.x, event.y) self.draw = 0 # 按下右键或d键删除图形 def Del(self, event): items = self.canvas.find_all() # for item in items: # self.canvas.delete(item) i = len(items) while i > 0: self.canvas.delete(items[i - 1]) i -= 1 # 按下中键或e键退出 def Exit(self, event): self.root.quit() # 设置绘制的图形 def SetStatus(self, status): self.status = status class MyLabel: def __init__(self, root): self.root = root self.canvas = canvas self.text = tkinter.StringVar() self.text.set('Draw Line') self.label = tkinter.Label(root, textvariable=self.text, fg='red', width=50) self.label.pack(side='left') root = tkinter.Tk() canvas = MyCanvas(root) label = MyLabel(root) MyButton(root, canvas, label, 0) MyButton(root, canvas, label, 1) MyButton(root, canvas, label, 2) MyButton(root, canvas, label, 3) root.mainloop()
d45809da871238ef94c6ebf82a09104ca9915c86
ignovak/my_sandbox
/chess.py
5,439
3.71875
4
#!/usr/bin/env python #-*- coding: utf-8 -*- from pprint import pprint from time import sleep class Board(): def __init__(self, chars=[]): self.SIZE = 8 self.board = [[0 for i in range(self.SIZE)] for i in range(self.SIZE)] # self.OLD_CHARS = { # 'queen': ['Q', self.__queen], # 'king': ['K', self.__king], # 'rook': ['R', self.__rook], # 'bishop': ['B', self.__bishop], # 'knight': ['H', self.__knight] # } self.CHARS = { 'Q': self.__queen, 'K': self.__king, 'R': self.__rook, 'B': self.__bishop, 'H': self.__knight } for char in chars: self.applyChar(char[0], char[1], char[2]) def applyChar(self, name, x, y): x -= 1 y -= 1 if not(-1 < x < self.SIZE and -1 < y < self.SIZE): print name + ': invalid coordinate' return if type(self.board[self.SIZE - 1 - y][x]).__name__ == 'str': print name + ': coordinate collision' return self.board[self.SIZE - 1 - y][x] = name self.CHARS[name](x, y) def printBoard(self): print '\n' board = map(lambda x: map(lambda y: str(y), x), self.board) print '\n'.join(map(lambda x: ' '.join(x), board)) print '\n' def getMax(self): m, x, y = 0, 0, 0 for i in range(self.SIZE): for j in range(self.SIZE): if m < self.board[i][j] < 10: m, x, y = self.board[i][j], j + 1, self.SIZE - i return m, x, y def getQuickMax(self): return max( map( lambda a: max(filter(lambda x: x < 10, a)), self.board ) ) def __incrCell(self, x, y): y = self.SIZE - 1 - y if -1 < x < self.SIZE and -1 < y < self.SIZE: if type(self.board[y][x]).__name__ == 'str': return self.board[y][x] self.board[y][x] += 1 def __getChar(self, x, y): y = self.SIZE - 1 - y if -1 < x < self.SIZE and -1 < y < self.SIZE: return self.board[y][x] def __getRanges(self, x, y, name, direct): def getRange(_x, _y): def getDoubleBlockedRange(x, _x, y, _y): # For cases when queen-bishop or queen-rook are on one line. if _x != x: return range(min(_x, x), max(_x, x)) else: return range(min(_y, y), max(_y, y)) def getSingleBlockedRange(x, _x, y, _y): # For cases when queen-king or queen-knight are on one line. if _x > x: return range(0, _x) elif _x < x: return range(_x, self.SIZE) else: if _y > y: return range(0, _y) elif _y < y: return range(_y, self.SIZE) char = self.__getChar(_x, _y) if type(char).__name__ == 'str' and char != name: # print char, _x + 1, _y + 1 if direct == 'diag' and char in ['B', 'Q'] \ or direct == 'line' and char in ['R', 'Q']: return getDoubleBlockedRange(x, _x, y, _y) else: return getSingleBlockedRange(x, _x, y, _y) rangeX = rangeY = range(0, self.SIZE) for i in range(0, self.SIZE): if direct == 'diag': rangeX = getRange(i, i - x + y) or rangeX rangeY = getRange(i, -i + x + y) or rangeY elif direct == 'line': rangeX = getRange(x, i) or rangeX rangeY = getRange(i, y) or rangeY return (rangeX, rangeY) def __rook(self, x, y, name='R'): rangeX = rangeY = range(0, self.SIZE) rangeX, rangeY = self.__getRanges(x, y, name, direct='line') for i in rangeX: self.__incrCell(x, i) for i in rangeY: self.__incrCell(i, y) def __bishop(self, x, y, name='B'): rangeX, rangeY = self.__getRanges(x, y, name, direct='diag') for i in rangeX: self.__incrCell(i, i - x + y) for i in rangeY: self.__incrCell(i, -i + x + y) def __queen(self, x, y): self.__rook(x, y, 'Q') self.__bishop(x, y, 'Q') def __king(self, x, y): for i in range(x - 1, x + 2): for j in range(y - 1, y + 2): self.__incrCell(i, j) def __knight(self, x, y): for i in range(-2, 3): for j in range(-2, 3): if abs(i) + abs(j) == 3: self.__incrCell(x - i, y - j) # b.applyChar('queen', 5, 3) CONSECUENCE = ('K', 'H', 'B', 'R', 'Q') points = [ (1, 2), (4, 1), (4, 4), (2, 5), (3, 7), ] chars = zip(CONSECUENCE, [i[0] for i in points], [i[1] for i in points]) b = Board(chars) b.printBoard() print b.getMax() print b.getQuickMax() print ''.join(CONSECUENCE) sugg = { 'max': 0, 'cons': '', 'x': 0, 'y': 0 } count = [0] cache = {} def mix(a): count[0] += 1 if len(a) < 2: return [a] else: s = ''.join(map(str, a)) if cache.get(s): return cache[s] else: res = [] for k, v in enumerate(a): res += map(lambda x: [v] + x, mix(a[:k] + a[k + 1:])) cache[s] = res return res chars = mix(list(CONSECUENCE)) for i in range(len(chars)): cons = chars[i] b = Board(zip(CONSECUENCE, [i[0] for i in points], [i[1] for i in points])) print '\n', i b.printBoard() m = b.getQuickMax() if m > sugg['max']: sugg['max'] = m sugg['cons'] = cons m = b.getMax() sugg['x'] = m[1] sugg['y'] = m[2] # TODO: generate keys
a759beda8dd1ef2309a0c200c3442bed4228f455
naotube/Project-Euler
/euler7.py
616
4.21875
4
#! /usr/bin/env python # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, # we can see that the 6th prime is 13. # What is the 10001st prime number? primes = [2,3] def is_prime(num): """if num is a prime number, returns True, else returms False""" for i in primes: if num % i == 0: return False return True def next_prime(num): """returns a first prime number larger than num""" while 1: num = num + 1 if is_prime(num): return num i = 2 while len(primes) < 10002: i = next_prime(i) primes.append(i) print(primes[10000])
cfab23035d6d8755c6b7a631380ea3add940263c
naotube/Project-Euler
/euler44.py
832
3.53125
4
class Pentagonal: def __init__(self, start=1, maximum=2100000000): self.start = start self.maximum = maximum def __iter__(self): self.number = self.start return self def __next__(self): pentagonal = int(self.number * (3 * self.number - 1) / 2) if pentagonal > self.maximum: raise StopIteration self.number += 1 return pentagonal if __name__ == "__main__": pentagonal_numbers = [] pen = Pentagonal() answer = 0 for i in pen: pentagonal_numbers.append(i) penta = Pentagonal(maximum=i) for n in penta: if (i-n) in pentagonal_numbers and (n - (i-n)) in pentagonal_numbers: answer = n - (i-n) if not answer == 0: break print("answer:{0}".format(answer))
b050c56f19cb7f9ab011f0c519db652a13369955
naotube/Project-Euler
/euler145.py
262
3.84375
4
LIMIT = 10 ** 9 reversible = 0 for i in range(1, LIMIT): if not i % 10 == 0 and all(not int(d) % 2 == 0 for d in str(i + int(str(i)[::-1]))): reversible += 1 print(i) print("{0} reversible numbers exist below {1}".format(reversible, LIMIT))
09c439bf39db140df5d094265ff57823679bd7b2
naotube/Project-Euler
/euler43.py
441
3.671875
4
import itertools if __name__ == "__main__": primes = [2,3,5,7,11,13,17] digits = ['0','1','2','3','4','5','6','7','8','9'] pandigital_numbers = itertools.permutations(digits) pandigital_numbers = ["".join(n) for n in pandigital_numbers if not n[0] == '0'] interesting_numbers = [int(n) for n in pandigital_numbers if all(int(n[i+1:i+4]) % primes[i] == 0 for i in range(len(n) - 3))] print(sum(interesting_numbers))
80663cac907a117527ed74eed69f3138c87ef98a
naotube/Project-Euler
/euler142.py
426
3.546875
4
from itertools import count def main(): squares = set() for x in count(3,1): squares.add(x ** 2) for y in range(x-1, 0, -1): if x+y in squares and x-y in squares: for z in range(y-1, 0, -1): p = (x+z, x-z, y+z, y-z) if all(n in squares for n in p): return(x+y+z) if __name__ == "__main__": print(main())
66d4fcfa07aed59ff5befc78a6139b11b5fb4b8c
SorenKremer/Boiler_board_hack
/Color_Game.py
2,497
3.984375
4
"""start up code needed here""" print("Hello World") """Main starts here""" wrong_press = 0 number_of_trials = 1 while number_of_trials < 16: random_number = 0 user_input = 0 import random for x in range(1): random_number = (random.randint(0, 9)) if random_number == 0: print("UP") if random_number == 1: print("RIGHT") if random_number == 2: print("DOWN") if random_number == 3: print("LEFT") if random_number == 4: print("Red") if random_number == 5: print("B") if random_number == 6: print("A") if random_number == 7: print("Orange") if random_number == 8: print("Green") if random_number == 9: print("Blue") user_input = 0 """Need the users input = user_input""" """Now we check for validity""" if random_number == 0: if user_input == 0: """do nothing""" else: wrong_press = wrong_press + 1 if random_number == 1: if user_input == 1: """do nothing""" else: wrong_press = wrong_press + 1 if random_number == 2: if user_input == 2: """do nothing""" else: wrong_press = wrong_press + 1 if random_number == 3: if user_input == 3: """do nothing""" else: wrong_press = wrong_press + 1 if random_number == 4: if user_input == 5: """do nothing""" else: wrong_press = wrong_press + 1 if random_number == 5: if user_input == 5: """do nothing""" else: wrong_press = wrong_press + 1 if random_number == 6: if user_input == 6: """do nothing""" else: wrong_press = wrong_press + 1 if random_number == 7: if user_input == 0 or 2: """do nothing""" else: wrong_press = wrong_press + 1 if random_number == 8: if user_input == 6: """do nothing""" else: wrong_press = wrong_press + 1 if random_number == 9: if user_input == 1 or 3: """do nothing""" else: wrong_press = wrong_press + 1 """blank""" """\/This goes at the very end of the loop \/""" print(number_of_trials) number_of_trials = number_of_trials + 1 print("Your score is ", (15-wrong_press), " out of 15")
3afe6d679ce437fc4466278143cff4c97b75a21b
cdrinconm/Cursos-Virtuales
/Coursera/Algorithmic Toolbox/week3_greedy_algorithms/7_maximum_salary/largest_number.py
425
3.640625
4
def largestNumber(): total = 0 i = 1 while total < n: if (total + i) == n: arreglo.append(i) return len(arreglo) if (total + i) < n: total = total + i arreglo.append(i) else: arreglo.append(i) total = total + i exc = total - n arreglo.remove(exc) return len(arreglo) i = i + 1 n = int(input()) arreglo = [] result = largestNumber()
eab7d94b1926d280f96e261156e32f16b796e1e3
cdrinconm/Cursos-Virtuales
/Coursera/Algorithmic Toolbox/week1_programming_challenges/1_sum_of_two_digits/APlusB.py
239
3.984375
4
# python3 def sum_of_two_digits(first_digit, second_digit): return first_digit + second_digit entrada = input() entrada = entrada.split() number1 = int(entrada[0]) number2 = int(entrada[1]) print (sum_of_two_digits(number1,number2))
4e59686cfdb9ff9c6835c17ee66b0b9ce1956f69
bgitego/DSP_WITH_PYTHON
/DSP_BOOK/func_fft.py
5,066
3.796875
4
import matplotlib.pyplot as plt import numpy as np import cmath as cm print('DSP Tutorial Implementation of The Discrete fourier transform') N = 128 # Number of Sample N_MINUS_1 = N-1 # Used to Define Array access 0 Index Max Value N_OVER_2 = int((N/2)) # Used to Define Array Acccess 0 Index Max Value N_OVER_2_P_1 = N_OVER_2 + 1 # Number of Frequency Samples PI = np.pi # Definition of the PI Constant XX = np.zeros(N) #XX[] Hold The Time Domain Signal REX = np.zeros(N_OVER_2_P_1) #REX[] Hold the Real Part of the Frequency Domain IMX = np.zeros(N_OVER_2_P_1) #IMX[] Hold the Imaginary part of the frequency domain MAG = np.zeros(N_OVER_2_P_1) PHASE = np.zeros(N_OVER_2_P_1) F_XX = np.zeros(N) #XX[] Hold The Time Domain Signal F_REX = np.zeros(N_OVER_2_P_1) #REX[] Hold the Real Part of the Frequency Domain F_IMX = np.zeros(N_OVER_2_P_1) #IMX[] Hold the Imaginary part of the frequency domain #Creating Simple Sine Wave #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ t = np.linspace(0,2*np.pi,N, endpoint=True) #print(len(t)) #print 'number of samples', t f_hz1 = 1.0 #Frequency In Hz f_hz2 = 10 f_hz3 = 100 A = 1 #Amplitude B = 5 C = 2.5 s = (A * np.sin(f_hz1*t)) #+ (B * np.cos(f_hz2*t)) #+ (C*np.sin(f_hz3*t)) #Signal #print 'Length of Time Domain Signal: ',len(s) #Windowing hamm = np.hamming(len(t)) #s = s*hamm #Find the discrete fourier transform of the sine wave Y = np.fft.rfft(s) #print np.array(Y).real #print np.array(Y).imag #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #Assign the real and Imaginary part of the frequency response to REX and IMX REX = np.array(Y).real IMX = np.array(Y).imag #Assign the time domain signal to F_XX[] F_XX = s #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #INVERSE DFT Function in Rectangular def INV_DFT(REX,IMX,F_RANGE,SAMPLE_SIZE): for K in range(0,F_RANGE,1): REX[K] = REX[K]/(SAMPLE_SIZE/2) IMX[K] = -IMX[K]/(SAMPLE_SIZE/2) REX[0] = REX[0]/2 REX[(F_RANGE-1)] = REX[(F_RANGE-1)]/2 for K in range(0,F_RANGE,1): for I in range(0,SAMPLE_SIZE): XX[I] = XX[I] + REX[K]*np.cos(2*PI*K*I/N) + IMX[K]*np.sin(2*PI*K*I/N) return XX #Calculating the Inverst FFT #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #Calculating the DFT of a sign signal def DFT(F_XX,F_RANGE,SAMPLE_SIZE): for K in range(0,(F_RANGE),1): for I in range(0,SAMPLE_SIZE,1): F_REX[K] = F_REX[K] + F_XX[I]*np.cos(2*PI*K*I/N) F_IMX[K] = F_IMX[K] - F_XX[I]*np.sin(2*PI*K*I/N) return {'F_REX':F_REX,'F_IMX':F_IMX} def REC_2_POL(REX,IMX,F_RANGE): for K in range(0,F_RANGE,1): MAG[K] = np.sqrt(np.square(REX[K]) + np.square(IMX[K])) if (REX[K] == 0): REX[K] = 1E-20 PHASE[K] = np.arctan(IMX[K]/REX[K]) if (REX[K] < 0 and IMX[K] < 0): PHASE[K] = PHASE[K] - PI if (REX[K] < 0 and IMX[K] >= 0): PHASE[K] = PHASE[K] + PI return {'MAG':MAG,'PHASE':PHASE} XX = INV_DFT(REX,IMX,N_OVER_2_P_1,N) F_FRQ = DFT(F_XX,N_OVER_2_P_1,N) POL = REC_2_POL(F_FRQ['F_REX'],F_FRQ['F_IMX'],N_OVER_2_P_1) #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #Calculation of the FFT #FFT Constant CREX = np.zeros(N) #REX[] Hold the Complex Real Part of the Frequency Domain CIMX = np.zeros(N) #IMX[] Hold the Complex Imaginary part of the frequency domain CMAG = np.zeros(N) CPHASE = np.zeros(N) CF_XX = np.zeros(N) #XX[] Derived From Complex FFT: The Time Domain Signal CF_REX = np.zeros(N_OVER_2_P_1) #REX[] Derived From Complex FFT: Hold Real Part of the Complex Frequency Domain CF_IMX = np.zeros(N_OVER_2_P_1) #IMX[] Derived From Complex FFT: Hold Imaginary part of the Complex Frequency Domain #Negative Frequency Generation For Inverse FFT def NEG_HZ_GEN(REAL_HZ,IMG_HZ,SAMPLE_SIZE): COMPLEX_RHZ = np.zeros(SAMPLE_SIZE) #Create Temporary Complex Frequency Domain COMPLEX_RHZ[0:(int((SAMPLE_SIZE/2)+1))] = REAL_HZ #Copy Real data into Compex Frequency Domain COMPLEX_IHZ = np.zeros(SAMPLE_SIZE) COMPLEX_IHZ[0:(int((SAMPLE_SIZE/2)+1))] = IMG_HZ for K in range((int((SAMPLE_SIZE/2)+1)),SAMPLE_SIZE,1): COMPLEX_RHZ[K] = COMPLEX_RHZ[SAMPLE_SIZE-K] COMPLEX_IHZ[K] = -COMPLEX_IHZ[SAMPLE_SIZE-K] return COMPLEX_RHZ,COMPLEX_IHZ CREX,CIMX = NEG_HZ_GEN(REX,IMX,N) print (REX) print (IMX) print (CREX) print (CIMX) plt.figure(1) plt.subplot(411) plt.plot(REX) plt.xlabel('Real Frequency') plt.ylabel('Frequency') plt.title('Magnitude') plt.grid(1) plt.subplot(412) plt.plot(IMX) plt.title('Imaginary Frequency') plt.xlabel('Frequency') plt.ylabel('Magnitude') plt.grid(1) plt.subplot(413) plt.plot(CREX) plt.title('Complex Real Hz') plt.xlabel('Frequency') plt.ylabel('Phase(Radians)') plt.grid(1) plt.subplot(414) plt.plot(CIMX) plt.title('Complex Imaginary Hz') plt.xlabel('Frequency') plt.ylabel('Magnitude') plt.grid(1) plt.show()
f9a5045cb8eb1da9e717ce37487162fcf8335602
sweakpl/connect-four
/test/connectfour_test.py
4,634
3.515625
4
# This Python file uses the following encoding: utf-8 #python -m unittest test.connectfour_test import unittest from gamemodel.connectfour import ConnectFourClassic from gamemodel.wrongmoveexception import WrongMoveException class ConnectFourTest(unittest.TestCase): '''TestCase class for testing the ConnectFourClassic functionalities''' def setUp(self): self.game = ConnectFourClassic() def test_should_board_contain_two_coins_when_two_drops(self): '''After two moves the board contains two coins''' # given # when self.game.drop_move(0) self.game.change_turns() self.game.drop_move(1) expected_board = [[0 for i in range(7)] for i in range(6)] expected_board[0][0] = 1 expected_board[0][1] = 2 # then self.assertEqual(self.game.board, expected_board) def test_should_return_true_when_vertical_win_line(self): '''is_winning(1) returns True when the player 1 assembles vertical winning line''' # given self.game.board = [[1, 2, 0, 0, 0, 0, 0], [1, 2, 0, 0, 0, 0, 0], [1, 2, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] # when self.game.drop_move(0) is_player_one_winning = self.game.is_winning(1) # then self.assertTrue(is_player_one_winning) def test_should_return_true_when_horizontal_win_line(self): '''is_winning(1) returns True when the player 1 assembles horizontal winning line''' # given self.game.board = [[1, 1, 1, 0, 0, 0, 0], [2, 2, 2, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] # when self.game.drop_move(3) is_player_one_winning = self.game.is_winning(1) # then self.assertTrue(is_player_one_winning) def test_should_return_true_when_diagonal_win_line(self): '''is_winning(1) returns True when the player 1 assembles diagonal winning line''' # given self.game.board = [[1, 2, 1, 2, 0, 0, 0], [0, 1, 2, 2, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] # when self.game.drop_move(3) is_player_one_winning = self.game.is_winning(1) # then self.assertTrue(is_player_one_winning) def test_should_return_true_when_board_tied(self): '''is_board_full() returns True if there is no more free space on the board''' # given self.game.board = [[2, 2, 2, 1, 2, 2, 2], [1, 1, 1, 2, 1, 1, 1], [2, 2, 2, 1, 2, 2, 2], [1, 1, 1, 2, 1, 1, 1], [2, 2, 2, 1, 2, 2, 2], [1, 1, 1, 2, 1, 1, 1]] # when is_game_tied = self.game.is_board_full() # then self.assertTrue(is_game_tied) def test_should_return_true_when_longer_than_four_win_line(self): '''is_winning(1) returns True when the player 1 assembles winning line longer than four coins''' # given self.game.board = [[1, 1, 1, 0, 1, 1, 1], [2, 2, 2, 0, 2, 2, 2], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] # when self.game.drop_move(3) is_player_one_winning = self.game.is_winning(1) # then self.assertTrue(is_player_one_winning) def test_should_throw_wrong_move_exception_when_wrong_drop(self): '''drop_move(0) raises WrongMoveException when the column 0 is full''' # given self.game.board = [[2, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0]] # when # then self.assertRaises(WrongMoveException, self.game.drop_move, 0) if __name__ == "__main__": unittest.main()
f9980a6aed23237637945f961672875d962240f1
muke101/AdventOfCode
/2-1.py
341
3.796875
4
import sys strings = sys.stdin.read() double = 0 tripple = 0 for string in strings.splitlines(): characters={} for character in string: if character in characters: characters[character]+=1 else: characters[character] = 1 if 3 in characters.values(): tripple+=1 if 2 in characters.values(): double+=1 print(double*tripple)
c1640acb6098ab4e8d87c5684dfb88e73a71fb89
cjcruzrivera/swapps_test_2
/method.py
989
3.65625
4
""" This file can be imported as a module and contains the following function: * getFourLenSubStringRepeated - returns how many substrings of 4 characters appear more than once along a main string """ def getFourLenSubStringRepeated(mainString): """ Method that identifies how many substrings of 4 characters appear more than once along the main string. Parameters ---------- mainString : str String to be analyzed Returns ------- dict a dict with the next format, with a line from each substring: { "key" : value, } key: substring found value: how many time the substring appear """ result = {} length = len(mainString) for index in range(0, length): if index <= (length-4): substring = mainString[index:(index+4)] count = mainString.count(substring) if(count > 1): result[substring] = count return result
5887e5004eb41259e28e4f9c908ac8064fa3e703
Vijay-FSD/Currency-converter
/desktopapp.py
773
3.96875
4
from tkinter import * window = Tk() def conversion(): indianrupees = (float(dollars.get())*75) t1.delete("1.0", END) t1.insert(END, indianrupees) canadian = (float(dollars.get())*1.3) t2.delete("1.0", END) t2.insert(END, canadian) euros = (float(dollars.get())*0.84) t3.delete("1.0", END) t3.insert(END, euros) b1 = Button(window, text="Convert", command=conversion) b1.grid(row=0, column=0) dollars = StringVar() e1 = Entry(window, textvariable=dollars) e1.grid(row=0, column=1) t1 = Text(window, height=1, width=10) t1.grid(row=1, column=0) t2 = Text(window, height=1, width=10) t2.grid(row=1, column=1) t3 = Text(window, height=1, width=10) t3.grid(row=1, column=2) window.mainloop()
9a8afb90a8f875ebb495f1cf54c50612a28613fd
ubaidahmadceh/python_beginner_to_expert
/tables_by_while_loop.py
209
3.96875
4
number = int(input("enter number : ")) start = int(input("enter start point : ")) limit = int(input("enter limit : ")) while start <= limit: print(f"{number} x {start} = {number*start}") start += 1
250b0995a4454e028efc181c0fd8e2a3970a02e6
ubaidahmadceh/python_beginner_to_expert
/ordered_dictionaries_in_collections.py
171
3.703125
4
from collections import OrderedDict my_dictionary = OrderedDict() my_dictionary[1] = "Apple" my_dictionary[2] = "Mango" my_dictionary[3] = "Orange" print(my_dictionary)
32867cc63387d79bf31da4ef7395c4713d5b1599
ubaidahmadceh/python_beginner_to_expert
/deque_in_collection.py
158
3.65625
4
from collections import deque my_list = ['pakistan', 'india', 'nepal'] deque_of_my_list = deque(my_list) deque_of_my_list.popleft() print(deque_of_my_list)
cd9902d851dd5f7d4527d6bb80fa8abf13ef59c7
ubaidahmadceh/python_beginner_to_expert
/isdigit_function.py
218
4.25
4
number = input("Enter your number : ") if number.isdigit(): print("this is numeric (0-9)") elif number.isalpha(): print("this is string !!") else: print("This is not numeric , this is symbol or alphabet")
244ef98e42b8538bd4d780203a2cc27956a3f871
dolandJake/Cs114
/Cs114/magic8ball.py
791
3.859375
4
print("Ask any question. about the future.") life = input() import random def getanswer(answernumber): if answernumber == 1: return "What do you think?" elif answernumber == 2: return "It might be." elif answernumber == 3: return "totes mcgoats" elif answernumber == 4: return "I have no idea bro" elif answernumber == 5: return "Leave me alone, I don't work for you" elif answernumber == 6: return "ask the question better" elif answernumber == 7: return "oh snap, lookin bad" elif answernumber == 8: return "nope. no. no way. not at all. never." elif answernumber == 9: return "yeah probably not" random_int = random.randint(1,9) fortune = getanswer(random_int) print(fortune)
06a27040c7d5d372c5a4b69aa53ed6ead2b6949f
Deepika200012/Guvi
/task/firstlast.py
203
3.71875
4
def firstDigit(n) : while n >= 10: n = n / 10; return int(n) def lastDigit(n) : return (n % 10) n = 98562; print(firstDigit(n), end = " ") print(lastDigit(n))
217e90f00ca3e57f29be4bce036367b3201f2380
Deepika200012/Guvi
/task/numguess.py
159
3.609375
4
import random a=int(input("enter the number")) print(a) r=random.randint(1,99) print(r) if(a==r): print("success") else: print("not success")
629c32b051677e577aaa63a269a6cef608432126
ethanweber/SGD-Loss-Landscape
/generate_dataset.py
3,078
3.59375
4
"""Generate synthetic datasets. """ import argparse import pprint from sklearn.datasets import make_regression, make_classification from sklearn.preprocessing import MinMaxScaler import os import numpy as np parser = argparse.ArgumentParser(description="") parser.add_argument('--n', type=int, default=1000, help="number of data points") parser.add_argument('--d', type=int, default=100, help="feature dimension") parser.add_argument('--dataset_name', type=str, default="example_dataset", help="dataset name") parser.add_argument('--percent_splits', type=str, default="0.6, 0.2, 0.2", help="percent splits") if __name__ == "__main__": args = parser.parse_args() print("Generating dataset with args:") pprint.pprint(args) # TODO(ethan): what to do with n_informative? dataset = make_regression(n_samples=args.n, n_features=args.d, n_informative=10, # max(args.d // 10, 10), # effective_rank=args.d, # effective_rank=10, noise=100.0, random_state=2) # dataset = make_classification(n_samples=args.n, n_features=args.d, n_classes=2) # TODO(ethan): add correlation and Gaussian noise params X, Y = dataset X = np.resize(X, (X.shape[0], args.d)).astype(np.float32) Y = np.resize(Y, (Y.shape[0], 1)).astype(np.float32) # normalize dataset # scaler = MinMaxScaler() # scaler.fit(Y) # X = scaler.transform(X) # Y = (scaler.transform(Y) * 2.0) - 1.0 # [0, 1] X = X - X.min() X /= (X.max() - X.min()) # [-1, 1] Y = Y - Y.min() Y /= (Y.max() - Y.min()) scalar = 1.0 Y = (scalar * 2 * Y) - scalar # print(X.shape) # print(Y.shape) # shuffle # arr = np.arange(len(X)) # np.random.shuffle(arr) # X = X[arr] # Y = Y[arr] # add noise here # TODO: decide if this is accurate # Y[Y == 0.0] = -1.0 # so we have labels {-1, 1} dataset_path = os.path.join("datasets", args.dataset_name) # make folder if it doesn't exist if not os.path.exists(dataset_path): os.makedirs(dataset_path) percent_splits = [float(x) for x in args.percent_splits.split(",")] # get split indices split_indices = [0] end_perc = 0 for perc in percent_splits: end_perc += perc split_indices.append(int(len(X) * end_perc)) print("Splitting at indices:", split_indices) # save files np.save(os.path.join(dataset_path, "trainX.npy"), X[split_indices[0]:split_indices[1]]) np.save(os.path.join(dataset_path, "trainY.npy"), Y[split_indices[0]:split_indices[1]]) np.save(os.path.join(dataset_path, "valX.npy"), X[split_indices[1]:split_indices[2]]) np.save(os.path.join(dataset_path, "valY.npy"), Y[split_indices[1]:split_indices[2]]) np.save(os.path.join(dataset_path, "testX.npy"), X[split_indices[2]:split_indices[3]]) np.save(os.path.join(dataset_path, "testY.npy"), Y[split_indices[2]:split_indices[3]])
fe0051ff89d919948011a5cf94a99a282c6e9228
mglcampos/trader
/htr/helpers/welford.py
1,389
3.625
4
import numpy as np class Welford(object): """Calculate the moving standard deviation using Welford's Algorithm.""" def __init__(self, window_size): """Create object with a given window size. Size can be -1, infinite size or > 1 meaning static size.""" self.window_size = window_size if not (self.window_size == -1 or self.window_size > 1): raise Exception("size must be -1 or > 1") self._window = [] self.n = 0.0 self.mean = 0.0 self._s = 0.0 @property def std(self): """Returns the standard deviation.""" if self.n == 1: return 0.0 return np.sqrt(self._s / (self.n - 1)) def update(self, value): """Updates the standard deviation with a new value and removes the old one if n > window_size.""" self.n += 1.0 diff = (value - self.mean) self.mean += diff / self.n self._s += diff * (value - self.mean) if self.n > self.window_size: old = self._window.pop(0) oldM = (self.n * self.mean - old) / (self.n - 1) self._s -= (old - self.mean) * (old - oldM) self.mean = oldM self.n -= 1 self._window.append(value) def update_and_return(self, vector): for value in vector: self.update(value) return self.std
5244b2220f9a582cc780a374a52ecf7b7cc79c47
SimmyZhong/leetCode
/179_MaxNum.py
1,660
3.84375
4
""" https://leetcode-cn.com/problems/largest-number/ 给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。 示例 1: 输入: [10,2] 输出: 210 示例 2: 输入: [3,30,34,5,9] 输出: 9534330 说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。 """ class Solution: def largestNumber(self, numList): sortList = self.__mergeSort(numList) result = ''.join([str(each) for each in sortList]) # 防止"00"这种情况存在 return "0" if result.startswith('0') else result def __mergeSort(self, numList): """ 采用归并法排序 """ if len(numList) <= 1: return numList middle = len(numList) // 2 leftList, rightList = numList[:middle], numList[middle:] return self.mergeList(self.__mergeSort(leftList), self.__mergeSort(rightList)) def mergeList(self, leftList, rightList): """ 合并列表 """ result = [] while (leftList and rightList): if self.__compare(leftList[0], rightList[0]): result.append(rightList.pop(0)) else: result.append(leftList.pop(0)) result.extend(leftList) if leftList else result.extend(rightList) return result def __compare(self, num1, num2): """ 两数对比,按最高位对比 """ n1, n2 = int(''.join([str(num1), str(num2)])), int(''.join([str(num2), str(num1)])) return True if n1 < n2 else False def testCase(): assert("0" == Solution().largestNumber([0, 0])) assert("34312121" == Solution().largestNumber([12, 121, 343])) assert("856574545343321211" == Solution().largestNumber([5657, 121, 343, 32, 1, 8, 4545])) print("Test OK") if __name__ == '__main__': testCase()
e78a1c15c7e86aaeec34c7da1b8a00479ca594b3
sparksmp/Programming_Tools_and_File_Management
/ArticleLetterCount.py
1,575
3.921875
4
""" We want to use Python and an HTML parser called BeautifulSoup to visit websites (UIC News) and extract their article dates, titles, article url and the article text. """ from bs4 import BeautifulSoup import urllib3 my_word = "the" def TheCount(article): for word in alpha: D[c] = 0 for c in article: if c in alpha: D[c] += 1 return D def GetArticleText(art_url): http = urllib3.PoolManager() requested = http.request('GET', art_url) B = BeautifulSoup(requested.data.decode('utf-8'), 'lxml') Btmp = B.find('div', {'class': 'pf-content'}) art_text = Btmp.get_text().replace("\n", "") return art_text def ScrapeUICNews(): #this only gets the FIRST srticle on the site - firstArticle funct http = urllib3.PoolManager() uic_news_url = "https://today.uic.edu/uicnews/section/uic-news/" requested = http.request('GET', uic_news_url) B = BeautifulSoup(requested.data.decode('utf-8'), 'lxml') #print(B) # for a basic HTML content #print(B.prettify()) # for a better/neater display of the HTML content Articles = B.find_all('div', attrs = {'class' : 'news-release-info clearfix'}) firstArticle = Articles[0] # only consider the first article title = firstArticle.find('a').string # extracts the title of the article inside the <a > hyperlink/anchor art_url = firstArticle.find('a')['href'] # extracts the url of the article article = GetArticleText(art_url) D = ArticleLetterCount(article) print(D) def main(): ScrapeUICNews() main()
62064319c0e14653d0903ba033bab6d0a58df3bf
sparksmp/Programming_Tools_and_File_Management
/Lecture30.py
1,474
3.90625
4
""" We want to use Python and an HTML parser called BeautifulSoup to visit websites (UIC News) and extract their article dates, titles, article url and the article text. """ from bs4 import BeautifulSoup import urllib3 #2 def GetArticleText(art_url): http = urllib3.PoolManager() requested = http.request('GET', art_url) B = BeautifulSoup(requested.data.decode('utf-8'), 'lxml') Btmp = B.find('div', {'class': 'pf-content'}) art_text = Btmp.get_text().replace("\n", "") return art_text #1 def ScrapeUICNews(): http = urllib3.PoolManager() uic_news_url = "https://today.uic.edu/uicnews/section/uic-news/" requested = http.request('GET', uic_news_url) B = BeautifulSoup(requested.data.decode('utf-8'), 'lxml') #print(B) # for a basic HTML content #print(B.prettify()) # for a better/neater display of the HTML content Articles = B.find_all('div', attrs = {'class' : 'news-release-info clearfix'}) for meta_art in Articles: date = meta_art.find('p').getText() # finds the first paragraph occurrence and returns its text component title = meta_art.find('a').string # extracts the title from the url anchor art_url = meta_art.find('a')['href'] # extracts the url of the article print(date) print(title) print(art_url) article = GetArticleText(art_url) print(article) print("--------------") def main(): ScrapeUICNews() main()
aa51c3ac081bdc54fdae83035e9d9bca83c36f31
pykili/py-204-hw1-tpeyrolnik
/task_3/solution_3_2.py
201
3.9375
4
string = input() alphabet = "" for i in string: if i not in alphabet: alphabet+=i for s in range (1, 9): string = input() for k in string: if k not in alphabet: alphabet+=k print (alphabet)
8ec44fa264f7d8c6006002d7f96478b2dec81788
GUOliver/COMP2041-Tutor
/wk12/flask/quick.py
102
3.75
4
#!/usr/local/bin/python3 def s(a, b): return a + b number = dict(a=5, b=10) print(s(**number))
a04df7c374427b78bc7711661ada1adbd7b4086d
GUOliver/COMP2041-Tutor
/wk12/flask/sort.py
131
3.765625
4
#!/usr/local/bin/python3 s = dict() s['a'] = 10 s['b'] = 3 s['c'] = 17 s['d'] = 0 letters = sorted(s, key=s.get) print(letters)
5920e52626ee1c337ddb30f7c3657d62c8012882
jf115/python-lesson
/Clase 4/condicionales.py
1,024
3.96875
4
# edad = int(input('Ingrese la edad: ')) # if edad >= 18: # print('Es mayor de edad') # else: # print('Es menor de edad') #edad = int(input('Ingrese la edad: ')) # if edad < 10: # print('Muy joven') # elif edad >=10 and edad < 14: # print ('Es categoria infantil') # elif edad >=14 and edad < 17: # print ('Es categoria juvenil') # elif edad >=18 and edad < 20: # print ('Es categoria sub 20') # elif edad >=20: # print ('Es categoria profesional') # edad1 = int(input('Ingrese edad 1: ')) Esto sobra porque ya definí la variable edades, entonces es mejor poner edades (a, b, c, d) # edad2 = int(input('Ingrese edad 2: ')) # edad3 = int(input('Ingrese edad 3: ')) # edad4 = int(input('Ingrese edad 4: ')) def edades (edad1, edad2, edad3, edad4): if edad1 > edad2 > edad3 > edad4: print (edad1) elif edad2 > edad3 > edad4: print (edad2) elif edad3 > edad4: print (edad3) else: print (edad4) edades(1,2,3,4) edades(4,5,3,1) edades(8,7,6,5)
55d554785a728b28f90d235233fcd0d13db0601a
Mahmoud-Arafaa/GenaticsAlgorithms
/assignment_1GenaticAlgorithmsKnapsack/genaticAlgorithmsKnapsack.py
4,153
3.5625
4
import random input = open(r"DataFile.txt") test_case_num = int(input.readline()) candidates = 0 maxWeight = 0 weight = [] value = [] pop = [] fitness = [] fitnessSum = 0 GEERATION_NUM = 20000 POP_SIZE = 100 print("Test cases: ", test_case_num) def generatePOP(): population = [] for i in range(POP_SIZE): chromosom = "" for j in range(candidates): r = random.randint(0,1) chromosom = chromosom + str(r) population.append(chromosom) return population def calcFitness(population): fitness = [] for j in range(POP_SIZE): idx = 0 sumValues = 0 sumWeight = 0 for x in population[j]: if (x == "1"): sumValues = value[idx] + sumValues sumWeight = weight[idx] + sumWeight idx = idx + 1 if sumWeight > maxWeight: fitness.append(1 / sumValues) else: fitness.append(sumValues) return fitness def fitnessSum(fitness): index = 0 fitnessSum = 0 for i in fitness: fitnessSum = fitnessSum + i for i in fitness: fitness[index] = float(i / fitnessSum) index = index + 1 return fitness def roulettWheel(): individuals = [] while len(individuals) < 2: idx = 0 ran = random.random() * 1 partial_sum = 0 for i in fitness: partial_sum = partial_sum + i if partial_sum > ran: if pop[idx] in individuals: break individuals.append(pop[idx]) break idx = idx + 1 return individuals def bestOfCandidates(fitness): best = -99 idx = -1 for i in range(len(fitness)): if fitness[i] > best: idx = i best = fitness[i] return idx def worstOfCandidates(fitness): worst = 99999999999 idx = -1 for i in range(len(fitness)): if fitness[i] < worst: idx = i best = fitness[i] return idx def cross_over(individuals): point = random.randint(1, candidates-1) temp1 = individuals[0][0:point] temp2 = individuals[1][0:point] temp1 = temp1 + individuals[1][point:candidates] temp2 = temp2 + individuals[0][point:candidates] individuals[0] = temp1 individuals[1] = temp2 return individuals def mutaion(generation): idx = -1 for i in generation: idx = idx + 1 for j in range(len(i)): rand = random.uniform(0, 1) if rand > 0.6: temp = list(generation[idx]) if temp[j] == '0': temp[j] = '1' else: temp[j] = '0' generation[idx] = "".join(temp) return generation for i in range(test_case_num): string = input.readline() if "\n" is string: string = input.readline() candidates = int(string) string = input.readline() if "\n" is string: string = input.readline() maxWeight = int(string) value = [] weight = [] for j in range(candidates): string = input.readline() if "\n" is string: string = input.readline() s = string.split(" ") value.append(int(s[1])) weight.append(int(s[0])) input.readline() pop = generatePOP() for x in range(GEERATION_NUM): fitness = calcFitness(pop) best = pop[bestOfCandidates(fitness)] fitnessSummation = fitnessSum(fitness) new_generation = [] for z in range(int(POP_SIZE/2)): individuals = roulettWheel() new_generation.append(cross_over(individuals)[0]) new_generation.append(cross_over(individuals)[1]) new_generation = mutaion(new_generation) fit = calcFitness(new_generation) new_generation.remove(new_generation[worstOfCandidates(fit)]) new_generation.append(best) pop = new_generation fit = calcFitness(pop) best = bestOfCandidates(fit) print("case", i+1, ": ", fit[best]," / ", pop[best])
971cad6e99ec5cd69824289f011ee12c5142947a
Miyayx/LeetCode
/python/103_binary_tree_zigzag_level_order_traversal.py
854
3.8125
4
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of lists of integers def zigzagLevelOrder(self, root): def add_to_list(l, d, p): #l:list, d:deep if len(l) <= d: l.append([]) l[d].append(p.val) if p.left: add_to_list(l, d+1, p.left) if p.right: add_to_list(l, d+1, p.right) if not root: return [] l=[] add_to_list(l,0,root) for i in range(len(l)): if i%2==1: l[i].reverse() return l #Note: reverse list in even level based on the result of 102
a5dbba04a03a87aea4eed1853168eaa1784f73aa
fac33/CS0008-f2016
/f2016_cs8_fac33_fp/f2016_cs8_fac33_fp.py
7,649
3.765625
4
# Template for code submission # name: Fanyang Cheng # email: fac33@pitt.edu # date: 12/10/2016 # class: CS0008-f2016 # instructor: Max Novelli (man8@pitt.edu) # # Description # description of this file goes here # Starting with Python, final projet # notes # The program should provide output on the screen similar to the following: #Number of Input files read : xx #Total number of lines read : xx #total distance run : xxxx.xxxxx #max distance run : xxxx.xxxxx # by participant : participant name #min distance run : xxxx.xxxxx # by participant : participant name #Total number of participants : xx #Number of participants # with multiple records : xx #The program should also create an output file reporting name of the participant, how many times their #name appears in the input files and the total distance run. Each row should be as follows: #Max,3,124.23 #Barbara,2,65.00 #Luka,1,12.87 #first we need to read in all the names of the file we need to read filename = input("pls input the file with all the files' name you want me to deal with.") # open the data file K = open(filename,'r') # read info in it line by line, without \n . name = K.readlines()# read the file names in a list # MN: you need to close the file K.close() # remove '\n' n = 0 #this n is a recorder which will help us to record the position where the file name is in the list "name". for line in name: line = line.rstrip('\n') name[n] = line # here is where I use the n to reassign the file name without "/n" to the list "name". n+=1 # here add 1 to n # then ,we read all of the contant in to a list of list, "contant" contant = [] append = [] contant0 = [] # this one will be the vary basic list contain the basic data. for item in name: P = open(item,'r') # open the file append = P.readlines() contant.extend(append) P.close() # MN: you need to close each file that you open. # this close needs to be moved inside the loop #P.close() totaldistance = 0 for data in contant: data = data.rstrip('\n') data = data.split(',') if not "distance" in data: contant0.append({'name': data[0].strip(' '), 'distance':float(data[1])}) totaldistance += float(data[1]) #now it is time for us to define the class of participation. class participant: """ participant class""" # properties # name of the participant name = "unknown" # total distance run by the participant distance = 0 # total number of runs by the participant runs = 0 # methods # initializer methods def __init__(self, name, distance=0): # set name self.name = name # set distance if non zero if distance > 0: # set distance self.distance = distance # set number of runs accordingly self.runs = 1 # end if # end def __init__ # addDistance method def addDistance(self, distance): if distance > 0: self.distance += distance self.runs += 1 # end if # end def addDistance # addDistances method def addDistances(self, distances): # loops over list for distance in distances: if distance > 0: self.distance += distance self.runs += 1 # end if # end for # end def addDistance # return the name of the participant def getName(self): return self.name # end def getName # return the total distance run computed def getDistance(self): return self.distance # end def getDistance # return the number of runs def getRuns(self): return self.runs # end def getRuns # stringify the object def __str__(self): return \ "Name : " + format(self.name, '>20s') + \ ". Distance run : " + format(self.distance, '9.4f') + \ ". Runs : " + format(self.runs, '4d') # end def __init__ # convert to csv def tocsv(self): return ','.join([self.name, str(self.runs), str(self.distance)]) # end def tocsv # ok, now we have finished all the def class work and we need to move on to how to assign the datas in files to class. # then we get how many files we need to deal with. NumberofFile = len(name) # and Totaline is the total line of all three files of datas. Totalline = len(contant0) print(Totalline) #then I decided to find all the participants using a dictionary. participants = {} for item in contant0: if not item['name'] in participants.keys(): participants[item['name']] = participant(item['name']) # insert distance in the list for this participant participants[item['name']].addDistance(item['distance']) minDistance = { 'name' : None, 'distance': None } # maximum distance run with name maxDistance = { 'name' : None, 'distance': None } # appearences dictionary apparences = {} for name, object in participants.items(): # get the total distance run by this participant distance = object.getDistance() # check if we need to update min # if this is the first iteration or if the current participant distance is lower than the current min if minDistance['name'] is None or minDistance['distance'] > distance: minDistance['name'] = name minDistance['distance'] = distance # end if # check if we need to update max # if this is the first iteration or if the current participant distance is lower than the current min if maxDistance['name'] is None or maxDistance['distance'] < distance: maxDistance['name'] = name maxDistance['distance'] = distance # end if # # get number of runs, aka apparences from participant object participantAppearences = object.getRuns() # # check if we need to initialize this entry if not participantAppearences in apparences.keys(): apparences[participantAppearences] = [] apparences[participantAppearences].append(name) # end for # # compute total number of participant # this is equivalent to the length of the participantDistances totalparticipant = len(participants); # # compute total number of participants with more than one record # extract all the participants that have 2 or more runs # and count th enumber of elements in the list with len() totalNumberOfParticipantWithMultipleRecords = len([1 for item in participants.values() if item.getRuns() > 1]) # set format strings INTEGER = '10d' FLOAT = '12.5f' STRING = '20s' # provide requested output print(" Number of Input files read : " + format(NumberofFile,INTEGER)) print(" Total number of lines read : " + format(Totalline,INTEGER)) print(" Total distance run : " + format(totaldistance,FLOAT)) print(" Max distance run : " + format(maxDistance['distance'],FLOAT)) print(" by participant : " + format(maxDistance['name'],STRING)) print(" Min distance run : " + format(minDistance['distance'],FLOAT)) print(" by participant : " + format(minDistance['name'],STRING)) print(" Total number of participants : " + format(totalparticipant,INTEGER)) print(" Number of participants") print(" with multiple records : " + format(totalNumberOfParticipantWithMultipleRecords,FLOAT)) # # create output file outputFile = "f2016_cs8_fac33_a3.output.csv" # open file for writing fh = open(outputFile,'w') # write header in file fh.write('name,records,distance\n') # loop on all the participants for name, object in participants.items(): # write line in file fh.write(object.tocsv() + '\n') #end for # close files fh.close()
fe806d525ec60e6eb789350136b62132c979a08d
luizsousasuper/circuitoseletricos
/rlc_paralelo.py
2,332
3.65625
4
"""" 09/2021 - Código da resposta de um circuito RLC paralelo, todos os casos são contemplados. """ import matplotlib.pyplot as plt import numpy as np import math R = float(input('Valor de R [ohm]: ')) #80 L = float(input('Valor de L [H]: ')) #200 * 10 ** -3 C = float(input('Valor de C [F]: ')) #5 * 10 ** -6 vc0 = float(input('Tensão armazenada no capacitor [V]: ')) #10 il0 = float(input('Corrente armazenada no indutor [A]: ')) #-0.6 ts = float(input('Tempo de simulação [s]: ')) #0.05 # Fator de amortecimento. a = 1/(2*R*C) # Frequência natural não amortecida. w = 1/math.sqrt(L*C) # Lista cujos elementos serão os segundos. t = np.arange(start=0, stop=ts, step=ts/1000) # Lista vazia cujos elementos serão os valores de tensão a cada segundo. v = [] # A função range gerará uma lista iterável com intervalo entre os tempos constante e igual a 1. # O equacionamento de vc1 e vc2 fica a cargo do usuário for i in range(len(t)): if a > w: # Raízes do sistema s1 = -a + math.sqrt(a**2 - w**2) s2 = -a - math.sqrt(a**2 - w**2) # Condições iniciais ic0 = -(vc0/R) - il0 dvc0 = ic0/C # Coeficientes da equação de comportamento A1 = ((vc0*s2)-dvc0)/(s2-s1) A2 = (dvc0-(vc0*s1))/(s2-s1) vt = A1*math.e**(s1*t[i]) + A2*math.e**(s2*t[i]) v.append(vt) elif a == w: s1 = -a s2 = -a ic0 = -(vc0/R) - il0 dvc0 = ic0/C B1 = vc0 B2 = dvc0 - (s1*B1) vt = B1*math.e**(s1*t[i]) + B2*t[i]*math.e**(s2*t[i]) v.append(vt) elif a < w: s1 = complex(-a, math.sqrt(-(a**2 - w**2))) s2 = complex(-a, -math.sqrt(-(a**2 - w**2))) wd = s1.imag ic03 = -(vc0/R) - il0 dvc03 = ic03/C C1 = vc0 C2 = (dvc03+(-s1.real*C1))/wd vt = (C1*math.cos(wd*t[i]) + C2*math.sin(wd*t[i])) * math.e**(s1.real*t[i]) v.append(vt) # A função x.append(y) preencherá uma lista x previamente criada com os valores da variável y. # Formatação do plot gerado. plt.style.use('seaborn-dark') plt.xlabel('\nt, s') plt.ylabel('Vc(t), V\n') plt.title('Tensão Vc(t)\n') plt.plot(t, v) plt.grid(True) plt.tight_layout() plt.show()
95a17e11a79f68563c393524c22b6f45b0365599
rob256/adventofcode2017
/python3/day_2/day_2_part_1.py
977
4.15625
4
from typing import List def checksum_line(numbers_list: iter) -> int: """ Given a list of numbers, return the value of the maximum - minimum values """ min_number = max_number = numbers_list[0] for number in numbers_list[1:]: min_number = min(min_number, number) max_number = max(max_number, number) return max_number - min_number def get_number_list_from_line(number_list_string: str) -> List[int]: return list(map(int, number_list_string.split())) def checksum_spreadsheet(spreadsheet_string: str) -> int: total_checksum = 0 for number_list_string in spreadsheet_string.split('\n'): number_list = get_number_list_from_line(number_list_string) total_checksum += checksum_line(number_list) return total_checksum def main(): with open('input.txt') as input_file: input_text = input_file.read().rstrip() print(checksum_spreadsheet(input_text)) if __name__ == '__main__': main()
90bd3d19039903b6001e349e42999f6c41339567
ramjoshi/phonepad-trie
/suggester.py
1,598
3.5625
4
from trie import patricia KEYMAP = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz' } ptrie = patricia() def keysearch(seq): suggestions = {} if len(seq) == 3: for ci in KEYMAP[seq[0]]: for cj in KEYMAP[seq[1]]: for ck in KEYMAP[seq[2]]: word = ''.join([ci,cj,ck]) results = search(word) if results: suggestions.update(results) return suggestions def search(word): data = ptrie.search(word) popular = {} if data: popularity(word, data, popular) return popular def popularity(word, data, popular): w = data[0] if w is not '': word += w node = data[1] for n in node: if n == 'count': if not word in popular: popular[word] = 0 popular[word] += node['count'] elif n == '': if not word in popular: popular[word] = 0 popular[word] += node[''][1]['count'] else: popularity(word+n, node[n], popular) def train(file): with open(file) as source: for l in source.readlines(): for word in l.split(' '): word = omit_chars(word) ptrie.addWord(word.lower()) def omit_chars(text, chars=None): if chars is None: chars = '\n\r,.:;!?()"\'' for c in chars: text = text.replace(c, '').rstrip('-') return text
88fba8cb95b7e3512ad5a1105182f2238462f69e
waltaskew/book-to-music-converter
/bemusic/words.py
1,109
3.875
4
"""Extract words and useful word features from a text.""" import nltk import nltk.tokenize as tokenize from nltk.corpus import stopwords from nltk.corpus import wordnet NOUN_TAG = 'N' STOP_WORDS = set(stopwords.words('english')) def iter_nouns(text): """Given a text, return an iterator yielding all of the nouns' synsets in the text. """ for sentence in tokenize.sent_tokenize(text): for tagged_word in nltk.pos_tag(tokenize.word_tokenize(sentence)): word, pos = tagged_word if pos.startswith(NOUN_TAG) and word not in STOP_WORDS: synset = get_synset(word) if synset is not None: yield synset def get_synset(word): """Get the most likely synset for the given noun.""" synsets = wordnet.synsets(word, pos=wordnet.NOUN) if not synsets: morphs = wordnet.morphy(word, wordnet.NOUN) if not morphs: return None else: synsets = wordnet.synsets(morphs[0], pos=wordnet.NOUN) if synsets: return synsets[0] else: return None
8a133240dad352f45daeb2e44b08f2a13cdccb42
jvitorn/python_init
/ex05.py
445
4.0625
4
prova1 = int(input('Digite uma nota: ')) prova2 = int(input('Digite uma nota: ')) prova3 = int(input('Digite uma nota: ')) media = (prova1+prova2+prova3)/3 if(media >=7): print('Você foi aprovado') else: print('Você Não foi aprovado e terá que fazer o exame final') exame = int(input('Digite sua nota no exame: ')) final = (media + exame)/2 if(final >= 5): print('Aprovado') else: print('Reprovado')
f114f3109b41762c0a9fde9b61f77d6aaaed3e85
sindhu819/DP-3
/Problem-23.py
1,313
3.578125
4
#minimum falling path -931 #Time complexity =O(N^2) #space complexity =O(N^2) #passed all test cases #Approach- DP first row remains the same. Subsequent rows takes the minimum value from above rows and add the value in current row column value. for 1 and last columns it's different and middle columns it's different. class Solution(object): def minFallingPathSum(self, A): """ :type A: List[List[int]] :rtype: int """ r=len(A) dp=[[0]*r for _ in range(r)] n=len(dp) # first row remains the same for i in range(n): dp[0][i]=A[0][i] for i in range(1,n): for j in range(0,n): #first column if (j==0): dp[i][j]=min(dp[i-1][j],dp[i-1][j+1])+A[i][j] #last column elif (j==n-1): dp[i][j]=min(dp[i-1][j],dp[i-1][j-1])+A[i][j] #middle cloumns from 1 to n-1 else: dp[i][j]=min(dp[i-1][j-1],min(dp[i-1][j],dp[i-1][j+1]))+A[i][j] min_val = float("inf") for i in range(n): min_val=min(min_val,dp[n-1][i]) return min_val
3405556565db382761660e3ce2db8fc1d2188c92
chrishowes55/rock_paper_scissors
/RockPaperScissorsTwentyFive.py
3,117
4.03125
4
from random import randint import time playing = True main_array = ['gun', 'dynamite', 'nuke', 'lightning', 'devil', 'dragon', 'alien', 'water', 'bowl', 'air', 'moon', 'paper', 'sponge', 'wolf', 'cockroach', 'tree', 'man', 'woman', 'monkey', 'snake', 'axe', 'scissors', 'fire', 'sun', 'rock'] def switch_replacement(x): # populates dictionary from array result_dict = {} for i in range(0, len(main_array)): result_dict[main_array[i]] = i return result_dict[x] if x in result_dict else len(main_array) def back(x): return main_array[x] while playing: wantRules = input('Would you like the rules (Y/N)') if wantRules == 'Y': print('WARNING: Lots of text coming your way (~300 lines, so get ready to scroll!)') time.sleep(2) # give them adequate warning rulesFile = open('rules.txt') rulesArray = rulesFile.readlines(); rules = ''.join(rulesArray) print(rules) print('Prepare yourself! We are going to play three rounds of rock, paper, scissors (The 25 version). Can you beat me, a computer?') userScore = 0 computerScore = 0 for i in range(0, 3): draw = True while draw: computerChoice = randint(0, len(main_array)) userChoice = switch_replacement(input('Gun, dynamite, nuke, lightning, devil, dragon, alien, water, bowl, air, moon, paper, ' 'sponge, wolf, cockroach, tree, man, woman, monkey, snake, axe, scissors, fire, ' 'sun or rock?').lower()) # convert to number if userChoice == len(main_array): print("Invalid Input") #invalid input was given print("Computer won by default :-(") computerScore += 1 break print('Computer chose ' + back(computerChoice)) # The following logic works because of the order of the array: If computerChoice is more than twelve before the userChoice, # it beats the userChoice. This is better illustrated if you look in rules.txt. if computerChoice == userChoice: print('DRAW!') draw = True else: total = 0 for i in range(1, 13): if back(computerChoice) == back(userChoice - i): print("USER WINS!") userScore += 1 draw = False else: total += 1 if total == 12: print("COMPUTER WINS!") computerScore += 1 draw = False if userScore > computerScore: print('User wins by ' + str(userScore - computerScore)) else: print('Computer wins by ' + str(computerScore - userScore)) userReplay = input('Would you like to play again? (Y/N)') if userReplay == 'N': playing = False break
15c1912330e73e8f067beb37d0b1fe8561c80072
sunnyfriend/blog
/blog6/test_zhuangshi.py
300
3.609375
4
import time def timer(n): def wrap1(func): def wrap2(*args,**kwargs): time1 = time.time() for i in range(n): result = func(*args,**kwargs) time2 = time.time() print(time2-time1) return result return wrap2 return wrap1 @timer(10000000) def foo(x,y): return x ** y foo(9,3)
e6886af2f0373dea4fac1f974cfca7574bca353b
daniel-cretney/PythonProjects
/primality_functions.py
481
4.4375
4
# this file will take a number and report whether it is prime or not def is_primary(): number = int(input("Insert a number.\n")) if number <= 3: return True else: divisor = 2 counter = 0 for i in range(number): if number % divisor == 0: counter += 1 if counter > 0: return False else: return True if __name__ == "__main__": print(is_primary())
ec0481ed09ec5b592cbffaddbf9b58844f40ec92
jamesjakeies/python-api-tesing
/python_crash_tutorial/examples/examples/InText/list.py
227
3.875
4
# list.py # in-text examples items = [10, 3, -1, 8, 24] print(items[1]) print(items[-1]) print(items[2:4]) print() items = [-2, 5, 3, -8, 7] items[0] = 10 print(items) items = [-2, 5, 3, -8, 7] items[1:3] = [0] print(items)