blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
c34ba6bcf12d428f6bb6ed4c785326e87873846e
vipulshah31120/PythonClassesByCM
/DailyClasses/01-03-2021/json_ex2.py
721
3.5
4
import json fruits = ["apple","banana"] person = {"fname":"Vipul", "lname":"Shah", "fruits":fruits} str = json.dumps(person) print(str) cars = ["BMW", "Pagani", "Konigsegg", "LaFerrari"] Myself = ["I have these cars :",cars] Mycars = json.dumps(Myself) print(Mycars) x = '{"name":"Niklaus", "age":"Immortal", "City":"New Orleans"}' y = json.loads(x) print(y["City"]) a = { "Name": "Marcel", "Age": "800 Years", "Married": True, "Divorced": False, "Friends" : ("Vincent", "Camille"), "Enemy" : "Niklaus", "Bikes" : [ {"Model":"Ford", "color":"Black"}, {"Model": "Chevrolet", "color":"Blue"} ] } print(json.dumps(a)) print(json.dumps(a, indent = 4, separators=(". ", " = ")))
c82719ea9e717605263a88170bcb1dfcea16b120
rseusebio/crypto
/4.2.py
526
3.5
4
from math import sqrt n = input() L = [3] L2 = [3] m = int(sqrt(n)) a = 3 + 2 while a < n: L.append(a) L2.append(a) a += 2 print L print m p = 3 j = 0 crivo = [] while p < m: i = L.index(p*p) print "{} {} {}".format(p, p*p, i) while i < len(L): crivo.append(L[i]) try: L2.remove(L[i]) except ValueError: pass i += p print crivo print L2 j += 1 p = L2[j] crivo = [] L2 = [2] + L2 print L2
7c496efda0dbe01aeb455f2feab33a391759e8db
Lemonade-up/Assignment-no.5
/Program no.1.py
3,288
4.09375
4
# Create a program that will ask for grade percentage. Display the equivalent Grade/Mark and Description # Example: # Input grade: 87.6 # Grade/Mark: 1.75 # Description: Very Good # grade/mark percentage description # 1.0 97-100 Excellent # 1.25 94-96 Excellent # 1.5 91-93 Very Good # 1.75 88-90 Very Good # 2.0 85-87 Good # 2.25 82-84 Good # 2.50 79-81 Satisfactory # 2.75 76-78 Satisfactory # 3.0 75 Passing # 5.0 65-74 Failure # Inc. Incomplete # W Withdrawn # D Dropeed #Steps #1 Ask for grade percentage def inputGrade(): percentGradeI = input('Grade Percentage(65-100): ') return percentGradeI #2 If else statements def ifElse(percentGradeC): # Incomplete if percentGradeC == 'Incomplete' or percentGradeC == 'Inc.': gradeMarkC = 'Inc.' descriptionC = 'Incomplete' # Withdrawn elif percentGradeC == 'Withdrawn' or percentGradeC == 'W': gradeMarkC = 'W' descriptionC = 'Withdrawn' # Dropped elif percentGradeC == 'Dropped' or percentGradeC == 'D': gradeMarkC = 'D' descriptionC = 'Dropped' else: percentGradeC = float(percentGradeC) #2.1 if percentGradeC >= 96.5 and percentGradeC <= 100: gradeMarkC = 1.0 descriptionC = 'Excellent' #2.2 elif percentGradeC >= 93.5 and percentGradeC <= 96.4: gradeMarkC = 1.25 descriptionC = 'Excellent' #2.3 elif percentGradeC >= 90.5 and percentGradeC <= 93.4: gradeMarkC = 1.5 descriptionC = 'Very Good' #2.4 elif percentGradeC >= 87.5 and percentGradeC <= 90.4: gradeMarkC = 1.75 descriptionC = 'Very Good' # 2.5 elif percentGradeC >= 84.5 and percentGradeC <= 87.4: gradeMarkC = 2.0 descriptionC = 'Good' # 2.6 elif percentGradeC >= 81.5 and percentGradeC <= 84.4: gradeMarkC = 2.25 descriptionC = 'Good' # 2.7 elif percentGradeC >= 78.5 and percentGradeC <= 81.4: gradeMarkC = 2.5 descriptionC = 'Satisfactory' # 2.8 elif percentGradeC >= 75.5 and percentGradeC <= 78.4: gradeMarkC = 2.75 descriptionC = 'Satisfactory' # 2.9 elif percentGradeC >= 74.5 and percentGradeC <= 75.4: gradeMarkC = 3.0 descriptionC = 'Passing' # 2.10 elif percentGradeC >= 64.5 and percentGradeC <= 74.4: gradeMarkC = 5.0 descriptionC = 'Failure' elif percentGradeC <= 64.4 or percentGradeC >100: print('You must enter a Valid Grade(65-100)') exit() return gradeMarkC, descriptionC #Print def output(percentGradeP, gradeMarkP, descriptionP): print(f'Input Grade: {percentGradeP}') print(f'Grade/Mark: {gradeMarkP}') print(f'Description: {descriptionP}') percentGrade = inputGrade() gradeMark, description = ifElse(percentGrade) output(percentGrade, gradeMark, description)
c3fb3d966c08f22c2288356dfc350c7d55ac8862
mayaragualberto/Introducao-CC-com-Python
/Parte1/Semana7/Tabuada.py
161
3.65625
4
linha=1 coluna=1 while linha<=10: while coluna<=10: print(linha*coluna, end="\t") coluna=coluna+1 linha=linha+1 print() coluna=1
52a6c923ef7f1ace154c7e4799739ffc006f9f26
shbaek/HackerRank.Python
/30 Day Challenge/day7.py
136
3.53125
4
''' Arrays! ''' import sys n = int(input().strip()) arr = map(int, input().strip().split(' ')) for i in reversed(arr): print(i),
84cfe3395c9e42bb0365ce202fbaadb0022971e3
DawnEve/learngit
/Python3/pythonCodeGit/day20-design-pattern/dp02_4_Decorator.py
634
4.3125
4
# http://stackoverflow.com/questions/3118929/implementing-the-decorator-pattern-in-python class foo(object): def f1(self): print("original f1") def f2(self, word=""): print("original f2"+word) class foo_decorator(object): def __init__(self, decoratee): self._decoratee = decoratee def f1(self): print("====>decorated f1: begin") self._decoratee.f1() print("====>decorated f1: end") def __getattr__(self, name): #不装饰的部分,原样输出 return getattr(self._decoratee, name) u = foo() v = foo_decorator(u) v.f1() v.f2() v.f2(": hello world!!")
fb18f5fb7b270c85aeba1c6ad1a109e67557a83d
pedalpath/pedalpath-genetic
/router/solvers/solver.py
1,064
3.96875
4
class Solver: def heuristic_cost_estimate(self, node1, node2): """computes the estimated (rough) distance between two random nodes, this method must be implemented in a subclass computes the 'direct' distance between two (x,y) tuples""" return node1.distance(node2) def distance_between(self, node1, node2): """gives the real distance between two adjacent nodes n1 and n2 (i.e n2 belongs to the list of n1's neighbors), this method must be implemented in a subclass this method always returns 1, as two 'neighbors' are always adajcent""" # This will use more complex aspects in the future return node1.distance(node2) def neighbors(self, node): """for a given node, returns (or yields) the list of its neighbors. this method must be implemented in a subclass for a given coordinate in the maze, returns up to 4 adjacent nodes that can be reached (=any adjacent coordinate that is not a wall) """ return [ neighbor.end for neighbor in node.neighbors ]
620feba4e98ff9589b799edea52bf1ce5827fc95
jaeyun95/Natural_Language_Processing
/basic_of_nlp/chapter02/manhattan.py
544
3.53125
4
''' Manhattan exampel code ''' from sentence_transformers import SentenceTransformer import numpy as np sent1 = "i am so sorry but i love you" sent2 = "i love you but i hate you" model = SentenceTransformer('paraphrase-distilroberta-base-v1') def manhattan(sent1, sent2): sentences = [sent1,sent2] sentence_embeddings = model.encode(sentences) return np.sqrt(np.sum(np.abs(sentence_embeddings[0]-sentence_embeddings[1]))) result = manhattan(sent1,sent2) print("Manhattan Similarity : ",result) ''' Manhattan Similarity : 9.857575 '''
dbf88166365f91a26416394ae092f02afd51a62d
ethancknott/CS61A
/Labs/Pre-MT1/Recursion.py
1,027
4.125
4
def sum(n): """Computes the sum of all integers between 1 and n, inclusive.""" if n == 1: return 1 return n + sum(n - 1) def sum_every_other(n): """Return sum of every other natural number up to n, inclusive.""" if n == 0: return 0 elif n == 1: return 1 else: return n + sum_every_other(n - 2) def fib(n): """Return nth fibonacci number.""" if n == 0: return 0 elif n == 1: return 1 else: return fib(n - 1) + fib(n - 2) def hailstone(n): """If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1. Repeat this process until n is 1.""" print(n) if n == 1: return 1 elif n % 2 == 0: return 1 + hailstone(n // 2) else: return 1 + hailstone(3 * n + 1) def paths(m, n): """Return the number of paths from one corner of an M by N grid to the opposite corner.""" if m == 1 or n == 1: return 1 else: return paths(m - 1, n) + paths(m, n - 1)
8609357b2001c8939c63c64fbb513edbc408bd3d
subreena10/dictinoary
/highest3key.py
269
3.984375
4
my_dict = { 'a':50, 'b':58, 'c': 56, 'd':40, 'e':100, 'f':20 } a=[] for i in range(3): max=0 for j in my_dict: if max<my_dict[j]: max=my_dict[j] b=j a.append(b) my_dict.pop(b) print(a)
7583fdfc3dd213e77dfdf90ffe4923e862e239ff
albastienex/TEST
/test13.py
102
3.65625
4
a=2 b=4 if a>b: print('a') else: print('b') i=1 while i<=10: print(i**2) i+=1
4a6982d55fe8089bfa4bf0318c86f9394ad517e7
jrog20/TripleKarel
/TripleKarel.py
979
3.734375
4
from karel.stanfordkarel import * """ File: TripleKarel.py -------------------- Karel will paint the exterior of three buildings in a given world. """ def main(): for i in range(2): paint_building() move_to_next() paint_building() # pre: Karel has a building on its left. # post: Karel has a building on its left; and is now facing the next building. def paint_building(): for i in range(2): while left_is_blocked(): paint_wall() turn_left() move() while left_is_blocked(): paint_wall() def paint_wall(): put_beeper() move() # pre: Karel just painted a building and is facing the next building. # post: Karel has the next building on its left. def move_to_next(): while front_is_clear(): move() turn_right() if front_is_blocked(): turn_right() def turn_right(): for i in range(3): turn_left() if __name__ == "__main__": run_karel_program()
79ae5532b55f852a0ece39cb622535d0131c5990
oyuchangit/Competitive_programming_exercises
/algorithm_practices/ABC/ABC_exercises/C134.py
368
3.53125
4
# https://atcoder.jp/contests/abc134/tasks/abc134_c N = int(input()) max_a = 0 max_i = 0 max_a_2 = 0 for i in range(N): A = int(input()) if A >= max_a: max_a_2 = max_a max_a = A max_i = i elif A >= max_a_2: max_a_2 = A for i in range(N): if i != max_i: print(max_a) else: print(max_a_2)
698974714ca71a0c1d8d4e0424265a4064b340aa
brendamora/CLASE-2
/cont.py
231
3.90625
4
""" num = int(raw_input("ingrese numero")) cont = 0 while true: print (cont) cont += 1 if cont > num: break """ num = int(raw_input("ingrese numero")) for i in range(num): print (i)
a414b0168b45d3647e3d37956e29ae771b7e14a3
FlaviaR/SimpleInterpreter
/python/genSpiral.py
539
4.15625
4
import math # Generate a list of points of a 3D spiral # x = cx + r * sin(a) # y = cy + r * cos(a) # where x,y is a resultant point in the circle's circumference # cx, cy is the center of the spiral # r is the radius of the circle # a is the current angle - vary from 0 to 360 or 0 to 2PI def generateSpiral(r, cx, cy): f= open("spiral.txt","w+") a = 0 z = 0 for a in range (0, 7): x = cx + r * math.cos(a) z = cx + r * math.sin(a) y = 0 # z += 10 # r += 5 f.write("%d, %d, %d\n" %(x,y,z)) generateSpiral(10, 0, 0)
2dfdda0aa1d1efe12741b87e5cde75a40785e00e
theArjun/bikeinfos
/tvs/tvs.py
628
3.5
4
from bs4 import BeautifulSoup import pandas as pd import re import requests site = input("Enter the url of the site that you want to scrape: ") page = requests.get(site) name = input("Enter the bike: ") soup = BeautifulSoup(page.content, 'html.parser') specs = soup.select('h5', {'class':'clearfix services__title'}) title = ['Price'] + [spec.get_text() for spec in specs] price = soup.select_one('h4[style="color: white;"]').text infos = soup.select('.services__text') spec = [price] + [info.get_text() for info in infos] bike = pd.DataFrame ( {'Specs': title, 'Infos': spec, }) bike.to_csv(name + '.csv')
6c1bf91c42c6a97ac3e91d46a846465c9d2fd837
henchhing-limbu/Daily-Coding-Problems
/problem5.py
584
4.1875
4
""" cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. Given this implementation of cons: def cons(a, b): def pair(f): return f(a, b) return pair Implement car and cdr. """ def cons(a, b): def pair(f): return f(a, b) return pair def car(fun): def first_element(a, b): return a return fun(first_element) def cdr(fun): def last_element(a, b): return b return fun(last_element) print(car(cons(3, 4))) print(cdr(cons(3, 4)))
5e647ce4b0b6edd773ac1528c24990b2468fba57
rolfrussell/ml_playground
/udacity-730/softmax.py
721
3.625
4
"""Softmax.""" import numpy as np # scores = [3.0, 1.0, 0.2] scores = [1.0, 2.0, 3.0] scores2 = np.array([[1, 2, 3, 6], [2, 4, 5, 6], [3, 8, 7, 6]]) scores3 = np.array([[1/10, 2/10, 3, 6], [2/10, 4/10, 5, 6], [3/10, 8/10, 7, 6]]) def softmax(x): return np.exp(x) / np.sum(np.exp(x), axis=0) print "softmax(scores2)" print softmax(scores2) print "\nsoftmax(scores3)" print softmax(scores3) # Plot softmax curves import matplotlib.pyplot as plt x = np.arange(-2.0, 6.0, 0.1) scores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)]) plt.plot(x, softmax(scores).T, linewidth=2) plt.ylabel('softmax') plt.xlabel('x') plt.show()
5f4832f93ac04a5cfd4cf12f80ba89e26456d885
rosittaj/Pet
/pets.py
4,446
3.640625
4
from random import randrange class Pet(object): boredom_threshold = 3 hunger_threshold = 10 sounds = ['moo'] boredom_reduce = 3 hunger_reduce = 2 def __init__(self, name): self.name = name self.hunger = randrange(self.hunger_threshold) self.boredom = randrange(self.boredom_threshold) self.sounds = self.sounds[:] def clock_tick(self): self.boredom += 1 self.hunger += 1 def mood_state(self): if self.hunger <= self.hunger_threshold and self.boredom <= self.boredom_threshold: return "happy" elif self.hunger > self.hunger_threshold: return "hungry" else: return "bored" def __str__(self): state = " I'm " + self.name + ". " state += " I feel " + self.mood_state() + ". " return state def reduce_boredom(self): self.boredom = max(0, self.boredom - self.boredom_reduce) def hi(self): print(self.sounds[randrange(len(self.sounds))]) self.reduce_boredom() def teach(self, word): self.sounds.append(word) self.reduce_boredom() def reduce_hunger(self): self.hunger = max(0, self.hunger - self.hunger_reduce) def feed(self): self.reduce_hunger() class Cat(Pet): sounds = ['Meow'] class Dog(Pet): sounds = ['Woof', 'Ruff'] def feed(self): Pet.feed(self) print("Arf! Thanks!") class Bird(Pet): sounds = ["chirp"] def hi(self): print(self.sounds[randrange(len(self.sounds))]) class Lab(Dog): def hi(self): print(self.sounds[randrange(len(self.sounds))]) def whichone(petlist, name): for pet in petlist: if pet.name == name: return pet return None pet_types = {'dog': Dog, 'lab': Lab,'cat': Cat, 'bird': Bird} def whichtype(adopt_type="general pet"): return pet_types.get(adopt_type.lower(), Pet) def play(): animals = [] base_prompt = """Adopt <pettype> - dog, cat, lab, poodle, bird, or another unknown pet type\nGreet <petname>\nTeach <petname> <word>\nFeed <petname>\nQuit\n\nEnter your Choice: """ feedback = "" while True: action = input(feedback + "\n" + base_prompt) feedback = "" words = action.split() if len(words) > 0: command = words[0] else: command = None if command == "Quit" or command=="quit" or command=="QUIT": print("Exiting...") return elif command == "Adopt" or command == "adopt" or command == "ADOPT" and len(words) > 1: try: if whichone(animals, words[1]): feedback += "You already have a pet with that name\n" else: if len(words) > 2: new_pet = whichtype(words[2]) else: new_pet = Pet animals.append(new_pet(words[1])) except: print("enter the details correctly. ") elif command == "Greet" or command == "greet" or command == "GREET" and len(words) > 1: try: pet = whichone(animals, words[1]) if not pet: feedback += "Didn't understand. Please try again.\n" print() else: pet.hi() except: print("enter the details correctly. ") elif command == "Teach" or command == "teach" or command == "TEACH" and len(words) > 2: try: pet = whichone(animals, words[1]) if not pet: feedback += "Didn't understand. Please try again." else: pet.teach(words[2]) except: print("enter the details correctly. ") elif command == "Feed" or command == "FEED" or command == "feed" and len(words) > 1: try: pet = whichone(animals, words[1]) if not pet: feedback += "Didn't understand. Please try again." else: pet.feed() except: print("enter the details correctly. ") else: feedback+= "Didn't understand. Please try again." for pet in animals: pet.clock_tick() feedback += "\n" + pet.__str__() play()
90b65e8f0fdcfd2073722f4dad8be89199652287
Yowks/mds_fernandes_alexandre_pythonTP
/tp18.py
123
3.6875
4
def calculeCarre (c1) : result = c1*c1 print(result) number1 = int(input('Entrez un nombre : ')) calculeCarre(number1)
2cc8038f9be3c9845814070ac4a250e5c9abb3d8
ChocolateMinds/pp2
/lesson7/function_returns.py
468
3.953125
4
# Fruitful function or a Void function def greet(name): print("Howdy, "+name) return name my_greet = greet("Simon") print(my_greet) # Write a function that calculates and return the area of a rectangle given len and width # and call it with 12, 13 as len and width def area_rectangle(len, width): area = len * width return area area = area_rectangle(12, 13) print(area) # Write a function for square of a number and call it with some samples
91011cfc1322f6157c92c8962037596ca6677da7
damosman/Kattis-Problems
/cooking_water.py
641
3.703125
4
def who_is_right(spans, min_span): for span in spans: if span[0] < min_span[0] and span[1] < min_span[0]: return 'edward is right' if span[0] > min_span[1] and span[1] > min_span[1]: return 'edward is right' return 'gunilla has a point' N = int(input()) min_span = [] spans = [] for _ in range(N): a, b = map(int, input().split()) spans.append([a, b]) if len(min_span) == 0: min_span.append(a) min_span.append(b) else: if min_span[1] - min_span[0] > b - a: min_span[0] = a min_span[1] = b print(who_is_right(spans, min_span))
c1e1dddb93c5c917c001e4ea1715d35698b9c502
MansouraD/Programmation-Python
/4.1 Puissance.py
214
3.671875
4
def main(): N = int(input("Merci d'entrer un réel: ")) x = int(input("Merci d'entrer un entier: ")) p = math.pow(N,x) print(N," à la puissance ",x," = ",p) if __name__ == '__main__': main()
47b5d607f42763f800c7f614fd5460377c180276
GabrielReira/Python-Exercises
/49 - Boletim escolar.py
1,127
3.84375
4
studants = list() while True: name = str(input('Nome: ')) score1 = float(input('Nota 1: ')) score2 = float(input('Nota 2: ')) average_score = (score1 + score2) / 2 studants.append([name, [score1, score2], average_score]) answer = ' ' while answer not in 'SN': answer = input('Quer continuar? [S/N] ').upper() if answer == 'N': break # Resultado para o usuário com o boletim formatado. print('\n', '=-='*4, 'BOLETIM', '=-='*4, '\n') print(f'{"ÍNDICE":<8}{"NOME":<15}{"MÉDIA":>10}') print('-' * 35) # Exibir na tela o índice do aluno, seu nome e sua média. for i in range(len(studants)): print(f'{i:<8}{studants[i][0]:<15}{studants[i][2]:>9}') # Perguntar ao usuário se ele gostaria de ver as notas 1 e 2 de algum aluno. while True: print('-' * 35) index = int(input(f'''Gostaria de ver as notas 1 e 2 de alguém? (999 para interromper) Digite o índice do respectivo aluno, de 0 à {len(studants) - 1}: ''')) if index == 999: break if index <= (len(studants) - 1): print(f'Notas de {studants[index][0]}: {studants[index][1]}')
e87a95ccbb14b83abd1af36412cbb39c663df6a0
hasangurbuz01/Yuz_Tanima_Calismalari
/UygulamalarHG/TkinterHG.py
579
3.9375
4
import tkinter as tk root = tk.Tk() v = tk.IntVar() v.set(1) languages = [ ("NewYork",1), ("Paris",2), ("Dubai",3), ("Sydney",4), ("Istanbul",5) ] def ShowChoice(): print(v.get()) tk.Label(root, text="""Select a city:""", justify = tk.LEFT, padx = 20).pack() for val, language in enumerate(languages): tk.Radiobutton(root, text=language, padx = 20, variable=v, command=ShowChoice, value=val).pack(anchor=tk.W) root.mainloop()
30825312d248254f2a98e244dc5564ad0cdb08b0
diegochav/Herramientas
/ventana.py
725
3.703125
4
import tkinter as tk from tkinter import ttk def on_click(): label1.configure(text="Te dije que no "+name.get()) label1.configure(foreground='red') label1.configure(background='gold') boton.configure(state='disable') pass win = tk.Tk() win.title("Hola GUI") win.resizable(0,0) #ttk.Label(win,text="Hola etiqueta").grid(row=0,column=0) #ttk.Label(win,text="Diego F. Chavarro Sanchez").grid(row=0,column=1) #ttk.Button(win,text="Click me",comman=on_click).grid(row=1,column=1) label1=ttk.Label(win,text="Hola Label") label1.grid(row=0,column=0) boton=ttk.Button(win,text="Don't click me",comman=on_click) boton.grid(row=1,column=1) name=tk.StringVar() txtentry=ttk.Entry(win,textvariable=name) txtentry.grid(row=1,column=0) win.mainloop()
abebdf4c726fdabc1d149e92d4fdc8bc8271cddb
xinjf/StudyNote
/PythonStudy/APIAuto_study/time/about_datetime.py
1,266
3.59375
4
import datetime """datetime.datetime模块用法""" # 用于获取时间、时间类型之间的转化 # 返回系统当前时间 today = datetime.datetime.now() print(today) # 返回当前时间的日期 data = datetime.datetime.now().date() print(today) # 返回当前时间的时分秒 time = datetime.datetime.now().time() print(time) # datetime.datetime 类型转化为str类型 str_time = datetime.datetime.ctime(today) print(str_time) # 时间格式转化成字符串 print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) # 字符串转化成时间格式 print(datetime.datetime.strptime('2018-11-09 14:42:36', '%Y-%m-%d %H:%M:%S')) """datetime.timedelta的用法""" # 计算两个datetime.datetime或者datetime.date类型之间的时间差 # 参数可选:days、seconds、microseconds、milliseconds、minutes、hours、weeks # 计算1天前的时间 now = datetime.datetime.now().date() print(now) delta = datetime.timedelta(days = 1) print(delta) print(now - delta) # 计算10天+1周前的时间(17天前) delta = datetime.timedelta(days = 10, weeks = 1) print(delta) print(now - delta) # 计算总天数和秒数 print(datetime.timedelta(days = 1, weeks = 2).days) print(datetime.timedelta(days = 1, hours = 1).total_seconds())
84ff336cef9b0a5c95839c9a783b8a1c3ba0d4a0
JonathanOnorato/ChemLP
/Bowman/Function1_2_3.py
6,124
3.640625
4
# %% #Function 1 of ChemLibre Texts reading program, takes in a url, path, and browser type and returns the html #Path location should be in the format ex. C:/Users/bowri/Anaconda3/chromedriver #If using Firefox, or not Chrome, simply enter "" for path location, requires having downloaded chromedriver first #See formatting below #Stuff to do: #1) throw more errors - check, still work on the try/except for selenium being present #2) getting rid of import functions - check #3) add docstrings to let user know which types of data are allowed - check #4) add default settings, eg. output = none; have output in, maybe more #5) document better from selenium import webdriver from selenium.webdriver.common.keys import Keys import json import pandas as pd from lxml import html import selenium from bs4 import BeautifulSoup as BS import random import time from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import StaleElementReferenceException as SERE def selenium_html_collector(url, browser, path_to_driver, webdriver): """"This function takes in three strings: 1) a url, 2) a browser, and 3) a path to your local chromedriver location, which is only need if you are using Chrome. It takes in 4) a webdriver module from Selenium as well. It returns an html of the given url and opens the browser to that site as well""" if browser == "Firefox": #try: drive = webdriver.Firefox() #except: # print("Did you import the webdriver module from Selenium?") elif browser == "Chrome": #try: drive = webdriver.Chrome(executable_path= (path_to_driver)) #except: # print("Did you import the webdriver module from Selenium?") elif browser != "Chrome" or "Firefox": print("this is the weird browser:", browser) raise Exception("Sorry, the function only utilizes Firefox and Chrome currently") drive.get(url) return drive def book_finder(url, driver): #SHOULD GET RID OF INITIALIZED LIST EVERY TIME PROGRAM RUN, ADD AS ARGUMENT book_urls = [] urls = [] driver.get(url) driver.implicitly_wait(random.randint(1,10)) #mt-sortable-listing-link mt-edit-section internal is the class name that gets all genres #can do something recursive, where if <h1 .text contains "Book:" stop sections = driver.find_elements_by_class_name("mt-sortable-listing-link mt-edit-section internal") print(type(sections)) print(sections) #if h1.text does not contain "Book:" header = str(driver.find_element_by_xpath("//*[@id='title']").text) print(header) #for section in sections: # book_finder(section, driver) print() for section in sections: urls.append(str(section.get_attribute("href").text)) print(urls) #else: #for section in sections: #book_url.append = href value(link) #return book_urls # %% #Function 3 of ChemLibreTexts reading program, takes in two lists: 1) chapter titles and 2) chapter #contents and 3) a filename, and exports them to a JSON file with the given filename #Creates a dictionary with the two lists, and writes and opens a json file #add additional arguments for default settings, eg output_state boolean, for printing vs writing def chapter_exporter(chapter_titles, chapter_contents, filename, export = True): """"This function takes in three variables, and has one default variable. The first two variables must be lists, which ultimately get combined into a dictionary. The third var is the string filename of your choice, and the final variable determines whether or not the program will print or export the dictionary to a json. By default it is set to true""" if isinstance(chapter_titles, list) and isinstance(chapter_contents, list) == True: titles_and_contents = dict(zip(chapter_titles, chapter_contents)) if export == True: with open(filename, "w") as outfile: json.dump(titles_and_contents, outfile) else: print(titles_and_contents) else: raise Exception("Variables passed in must be lists") # %% #import json #titles_list = ["chapter 1", "chapter 2", "chapter 3"] #chap_list = ["this is chapter 1", "this is chapter 2", "this is chapter 3"] #title = "chapter 1" #chapter_exporter(titles_list, chap_list, "test_chapter_writing", False) # %% def chapter_text_parser(driver): driver.implicitly_wait(random.randint(1,100)) chapter_title = driver.find_element(By.XPATH, '//*[@id="title"]').text.strip() subchap_link_title_container = driver.find_elements(By.CLASS_NAME, 'mt-listing-detailed-title') subchap_titles = [title.text.strip() for title in subchap_link_title_container ] subchap_links = [link.find_element_by_tag_name('a').get_attribute('href') for link in subchap_link_title_container] print('Name of chapter', chapter_title, '\n', 'Number of subchapter is', len(subchap_links)) subchap_overview_container = driver.find_elements(By.CLASS_NAME, 'mt-listing-detailed-overview') subchap_overviews = [overview.text.strip() for overview in subchap_overview_container] subchap_contents=[] data = {} for chap_link in subchap_links: driver.get(chap_link) driver.page_source chap_text_container = driver.find_elements(By.CLASS_NAME,'mt-content-container') for subchap in chap_text_container: subchap_contents.append(subchap.text.strip()) data = {'chap-title':subchap_titles, 'chap-overview': subchap_overviews, 'chap-content':subchap_contents} return data # %% def new_exporter(dictionary, filename, driver, printout = False): if printout == False: with open(filename, "w") as outfile: json.dump(dictionary, outfile) else: print(dictionary) return driver.close()
fb0fdb593d2eaab31b4ec84ef8350a9a2d7fc3c2
guoyu321/NLP-Interview-Notes
/main.py
158
3.59375
4
import pandas as pd data = {'0': [1, 0, 1, 0, 0], '1': [1, 1, 1, 1, 1], '2': [2, 2, 2, 2, 2]} df = pd.DataFrame(data) print(df.ix[:, (df != df.ix[0]).any()])
4325bb9e9fe8d6bdadd4c045a664ab929f8d9f03
keakaka/practice01
/prob08.py
191
3.78125
4
# 문자열을 입력 받아, 해당 문자열을 문자 순서를 뒤집어서 반환하는 함수 reverse(s)을 작성하세요. quest = input('입력 > ') print(''.join(reversed(quest)))
5dd7f51d8094564722be03281a735fd70d4b0e32
MonadWizard/python-basic
/basic/learnPythonByDoing/oop_4/2_magic_method.py
729
3.921875
4
class Student: def __init__(self, name): self.name = name movies = ['Matrix', 'Finding Nemo'] print(len(movies)) print(""" """) class Garage: def __init__(self): self.cars = [] def __len__(self): return len(self.cars) def __getitem__(self, i): return self.cars[i] # def __repr__(self): # use for print-out string # return f'<Garage {self.cars}>' def __str__(self): return f'Garage with {len(self)} cars.' ford = Garage() ford.cars.append('Fiesta') ford.cars.append('Focus') print(ford[0]) # Garage.__getitem__(ford, 0) for car in ford: print(car) print(ford)
5c94a0a7b83d60dc1fd12e1309ca637c3590678e
Aasthaengg/IBMdataset
/Python_codes/p02400/s043104389.py
152
4.09375
4
from math import pi r = float(input()) circle_squre = r * r * pi circle_length = (r*2) * pi print('{}'.format(circle_squre),'{}'.format(circle_length))
0c58b70a5b7b51690af760cec219fd9b9c1ccbdd
jqjjcp/leetcode-python-solutions
/ZigzagConversion.py
2,709
4.0625
4
'''Problems description: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string text, int nRows); convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR" /*n=numRows Δ=2n-2 1 2n-1 4n-3 Δ= 2 2n-2 2n 4n-4 4n-2 Δ= 3 2n-3 2n+1 4n-5 . Δ= . . . . . Δ= . n+2 . 3n . Δ= n-1 n+1 3n-3 3n-1 5n-5 Δ=2n-2 n 3n-2 5n-4 */ ''' class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ if numRows == 1 or numRows >= len(s): return s L = [''] * numRows index, step = 0, 1 for x in s: L[index] += x if index == 0: step = 1 elif index == numRows -1: step = -1 index += step return ''.join(L) #another solution: def convert(self, s, nRows): if nRows==1: return s period= 2*(nRows -1) lines=["" for i in range(nRows)] d={} # dict remainder:line for i in xrange(period): if i<nRows: d[i]=i else: d[i]=period-i for i in xrange(len(s)): lines[ d[i%period] ] +=s[i] return "".join(lines) '''The idea is to use the remainder (index%period) to determine which line the character at the given index will be. The period is calculated first based on nRows. A dictionary with remainder:line as key:value is then created (this can also be done with a list or a tuple). Once these are done, we simply go through s, assign each character to its new line, and then combine these lines to get the converted string. The code can be further shortened to 8 lines by using dict comprehension: d={i:i if i<nRows else (period-i) for i in xrange(period)} ''' def convert(self, s, nRows): if nRows==1: return s period= 2*(nRows -1) lines=["" for i in range(nRows)] d={i:i if i<nRows else (period-i) for i in xrange(period)} for i in xrange(len(s)): lines[ d[i%period] ] +=s[i] return "".join(lines)
a59f3e0a2b15a3568e91fc7257b41a6e05d47955
PushanPatel/Open-CV-for-python-
/opencv_tutorial/Tut11_Smoothening_images.py
2,212
3.953125
4
""" Tutorial 18: Smoothening of images Smoothing or blurring is used to remove noise from image using filters such as Homogeneous: most simple. each output pixel is mean of its kernel neighbours Gaussian Median bilateral etc Kernel,convultion matrix is a shape which can apply/convolve over image. Used for blurring, sharpening, embossing, edge detection etc """ import cv2 import numpy as np from matplotlib import pyplot as plt #img=cv2.imread('opencv-logo.png') img=cv2.imread('pic2.png') #img=cv2.imread('lena.jpg') img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)# as we are using matplotlib #for homogeneous, kernel K=1/(Kwidth*Kheight)*(matrix of 1s) Kh=5 Kw=5 kernel=np.ones((Kh,Kw),np.float32)/(Kh*Kw) dst=cv2.filter2D(img,-1,kernel)# this destination image #filter2D(source,depth of dest. image,kernel) filter2D is filter for homogeneous\ # it smooths the curves(noises there are removed) #For one Dimensional signals of Image- Low Pass Filter and High Pass filters are used #LPF helps in removing noises and blurring images #HPF helps in finding edges in image blur=cv2.blur(img,(5,5)) # uses averaging method to blur gauss=cv2.GaussianBlur(img,(5,5),sigmaX=0)# gaussian filter uses different weight kernel in both x and y direction # center has higher weight and edges have less weight # better than blur. better at removing high frequency noise med=cv2.medianBlur(img,5) # Median filter replaces each pixel value with median of its neighbouring pixels. # This method is great when dealing with 'salt and pepper' noise( black as well as white spots as noise) # kernel should be odd number and not 1 bf=cv2.bilateralFilter(img,9,75,75) #All above filters not only remove noise but also smoothen the edges. In order to preserve the edges(in some case where we require them)Use bilateral filter #bilateralFilter(source,diameter of each pixel neighbourhood used, sigma color, sigma space ) titles=['Image','2D convolution','Blur','Gaussian Blur','Median','Bilateral filter'] images=[img,dst,blur,gauss,med,bf] for i in range(6): plt.subplot(2,3,i+1),plt.imshow(images[i],'gray') plt.title(titles[i]) plt.xticks([]),plt.yticks([]) plt.show()
cbd046a64a6683f0268e9e943f156726513073f5
mbellezze/Homework-Projects-Python
/Functions and Methods Homework.py
3,840
4.40625
4
#Write a function that computes the volume of a sphere given its radius. #The volume of a sphere is given as $$\frac{4}{3} πr^3$$ def vol(rad): return (4/3)*(3.1416)*(rad**3) # Check print(vol(2)) #33.49333333333333 print("-----------------------------------------------------------------------------------------------") #Write a function that checks whether a number is in a given range (inclusive of high and low) def ran_check(num,low,high): if num in range(low, high): return f"{num} is in the range between {low} and {high}" else: return f"{num} is not in the range between {low} and {high}" # Check print(ran_check(5,2,7)) #5 is in the range between 2 and 7 #If you only wanted to return a boolean: def ran_bool(num,low,high): return ((low<=num) and (num<=high)) #Check print(ran_bool(3,1,10)) print("-----------------------------------------------------------------------------------------------") #Write a Python function that accepts a string and calculates the number of upper case letters #and lower case letters. #Sample String : 'Hello Mr. Rogers, how are you this fine Tuesday?' #Expected Output : #No. of Upper case characters : 4 #No. of Lower case Characters : 33 #HINT: Two string methods that might prove useful: .isupper() and .islower() #If you feel ambitious, explore the Collections module to solve this problem! def up_low(s): #cont1=0 #cont2=0 d={"upper":0, "lower":0} for word in s: if word.isupper(): #cont1 +=1 d["upper"] +=1 elif word.islower(): d["lower"] +=1 #cont2 +=1 print(f"No. of Upper case characters: {cont1}") print(f"No. of Lower case characters: {cont2}") s = 'Hello Mr. Rogers, how are you this fine Tuesday?' up_low(s) print("-----------------------------------------------------------------------------------------------") #Write a Python function that takes a list and returns a new list with unique elements of the first list. #Sample List : [1,1,1,1,2,2,3,3,3,3,4,5] #Unique List : [1, 2, 3, 4, 5] def unique_list(lst): return list(set(lst)) print(f"Unique List: {unique_list([1,1,1,1,2,2,3,3,3,3,4,5])}") #Out #[1, 2, 3, 4, 5] print("-----------------------------------------------------------------------------------------------") #Write a Python function to multiply all the numbers in a list. #Sample List : [1, 2, 3, -4] #Expected Output : -24 def multiply(numbers): mult=1 for num in numbers: mult *= num return mult print(multiply([1,2,3,-4])) #Out #-24 print("-----------------------------------------------------------------------------------------------") #Write a Python function that checks whether a passed in string is palindrome or not. #Note: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or #nurses run. def palindrome(s): return (s[::]==s[::-1]) print(palindrome('helleh')) #Out #True print("-----------------------------------------------------------------------------------------------") #Hard: #Write a Python function to check whether a string is pangram or not. #Note : Pangrams are words or sentences containing every letter of the alphabet at least once. #For example : "The quick brown fox jumps over the lazy dog" #Hint: Look at the string module import string def ispangram(str1, alphabet=string.ascii_lowercase): str2=set(alphabet) return str2<=set(str1.lower()) print(ispangram("The quick brown fox jumps over the lazy dog")) #Out #True print(string.ascii_lowercase) #Out #'abcdefghijklmnopqrstuvwxyz' #Great Job!
fbc0dc921e213c7bac85a95eb28ff4283baac9ce
Girrajgg/analysis
/day_from_given_date.py
264
4.0625
4
#!/usr/bin/env python # coding: utf-8 # In[20]: #prints day of a week like monday import datetime dt = '10/03/2019' day, month, year = (int(x) for x in dt.split('/')) ans = datetime.date(year, month, day) print(ans.strftime("%A")) # In[ ]: # In[ ]:
95702fe117cd08ca7ea1a0824f83c32e679bdaf8
LizaChelishev/homework0310
/homework_10_4.py
752
3.921875
4
# 170 countires are voting pro / con / abst / vetto. count the votes and break loop when vetto. total_number_of_countries = 170 num_of_countries = 0 count_pro = 0 count_con = 0 count_abst = 0 while num_of_countries < total_number_of_countries: vote = int(input('Input your vote')) # ( 1 / 2 / 3 / 4 ) if vote == 1: count_pro += 1 if vote == 2: count_con += 1 if vote == 3: count_abst += 1 if vote == 4: print('Country number ' + str(num_of_countries + 1) + ' voted vetto.') break num_of_countries += 1 if num_of_countries == total_number_of_countries: print('Pro votes = ' + str(pro_count)) print('Con votes = ' + str(con_count)) print('Abstention votes = ' + str(abst_count))
5ef3c657a472bbfc29af735f751acfe92ded5bdb
juliakimchung/my_python_ex
/if_statement.py
1,346
4.1875
4
should_continue = True if should_continue: print("hello") known_people = ['John', "anna", "mary"] person = input("enter the person you know") if person in known_people: print("you know {}!".format(person)) else: print ("you don't know{}!".format(person)) numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Modify the method below to make sure only even numbers are returned. def even_numbers(): evens = [] for num in numbers: if num%2 ==0: evens.append(num) return evens print(even_numbers()) # Modify the below method so that "Quit" is returned if the choice parameter is "q". # Don't remove the existing code def user_menu(choice): if choice == "a": return "Add" elif choice == "q": return "Quit" def who_do_you_know(): #ask the user for a list of people they know #split the string into a list #return the list peoples = input("enter names you know separated by commas: ") names = [nam.strip() for nam in peoples.split(",") ] return names def ask_user(): #ask user for a name #see if the name is in the list of people they know #print out that they know the person p = input("enter a name of someone you know: ") if p in who_do_you_know(): print("you know {}".format(p)) print(ask_user())
b558dd34c881e05256052459c6f56e318d540522
zjw199708/python-all-zjw
/bank/entity/bank.py
2,576
3.71875
4
import random # 银行库 bank = {} # username : {password,money......} bank_name = "中国工商银行昌平支行" bank_choice = {"1": "开户", "2": "存钱", "3": "取钱", "4": "转账", "5": "查询", "6": "Bye"} # 银行业务选项 # 开户成功的信息模板 myinfo = ''' \033[0;32;40m ------------账户信息------------ 账号:{account} 姓名:{username} 密码:{password} 地址: 国家:{country} 省份:{province} 街道:{street} 门牌号:{door} 账户余额:{money} 注册银行名:{bank_name} ------------------------------- \033[0m ''' # 欢迎模板 welcome = ''' *********************************** * 中国工商银行账户管理系统 * *********************************** * 选项 * ''' welcome_item = '''* {0}.{1} *''' def print_welcome(): print(welcome, end="") keys = bank_choice.keys() for i in keys: print(welcome_item.format(i, bank_choice[i])) print("**********************************") # 输入帮助方法:chose是打印选项 def inputHelp(chose, datatype="str"): while True: print("请输入", chose, ":") i = input(">>>:") if len(i) == 0: print("该项不能为空!请重新输入!") continue if datatype != "str": return int(i) else: return i # 判断是否存在该银行选项 def isExists(chose, data): if chose in data: return True return False # 获取随机码 def getRandom(): li = "0123456789qwertyuiopasdfghjklzxcvbnmZXCVBNMASDFGHJKLQWERTYUIOP" string = "" for i in range(8): string = string + li[int(random.random() * len(li))] return string # 通过账号获取账户信息 def findByAccount(account): for i in bank.keys(): if bank[i]["account"] == account: return i return None # 银行的开户方法 def bank_addUser(username, password, country, province, street, door, money): if len(bank) >= 100: return 3 elif username in bank: return 2 else: # 正常开户:存储到银行 bank[username] = { "account": getRandom(), "password": password, "country": country, "province": province, "street": street, "door": door, "money": money, "bank_name": bank_name } return 1
a8f57375d81a6e9cc8edc677fa1d6ca13f74ed88
odify/Python-Security
/2020-08-19/wordlistcreations.py
620
4.15625
4
word_list = ['xyz','Yxz','zyX'] #INPUT ARRAY text = '' #INPUT TEXT text = text.replace(',',' ') #these statements remove irrelevant punctuation text = text.replace('.','') text = text.lower() #this makes all the words lowercase, so that capitalization wont affecting for repeatedword in word_list: counter = 0 #counter starts at 0 for word in text.split(): if repeatedword.lower() == word: counter = counter + 1 #add 1 every time there is a match in the list print(repeatedword,':', counter) #prints the word from 'word_list' and its frequency
c74421b70b4dbb94853ef0784b1ebc0277630a16
1475963/302poignees
/data_processing.py
1,562
3.828125
4
## module with data processing functions """ data processing function, creates separation matrix throught the dictionary created from the input file, finds every paths then select lowest """ def do_separation_matrix(data :dict, dump :bool): if dump: print("degrés de séparation (maison):") guys = sorted(data.keys()) matrix = [] index = 0 nb = 0 while index < len(guys): matrix.append([]) sepguys = dict.fromkeys(guys, 0) find_em_all(data, guys, guys[index], sepguys, 0) sepguys[guys[index]] = 0 for key in sorted(sepguys.keys()): matrix[index].append(sepguys[key]) index += 1 return matrix """ data processing function, used by separation algo """ def find_em_all(data :dict, guys :list, index :str, sepguys :dict, count :int): for i in range(len(data[index])): if sepguys[data[index][i]] == 0 or sepguys[data[index][i]] > count: sepguys[data[index][i]] = count + 1 find_em_all(data, guys, data[index][i], sepguys, count + 1) """ data processing function, uses separation matrix to define the best connexion path between two guys """ def find_target(data, guys, index, target, matrix, count): for i, item in enumerate(matrix[guys.index(index)]): if count == 0: return elif item == 1 and matrix[i][guys.index(target)] == count - 1: print("{} est ami(e) avec {}".format(index, guys[i])) find_target(data, guys, guys[i], target, matrix, count - 1)
b3c0a7402b6c1044412fe8b4025b8b6a733b09e1
Meowse/IntroToPython
/Students/apklock/session05/keyword_lab.py
760
3.6875
4
def colour(fore_colour = 'gold', back_colour = 'black', link_colour = 'green', visited_colour = 'red'): print "The default foreground colour is:", fore_colour print "The default background colour is:", back_colour print "The default link colour is:", link_colour print "The default visited colour is:", visited_colour colour() fore = raw_input("Type a new foreground colour here -->") fore_colour = fore back = raw_input("Type a new background colour here -->") back_colour = back link = raw_input("Type a new link colour here -->") link_colour = link visited = raw_input("Type a new visited colour here -->") visited_colour = visited def new_colours(*args): print "This is the new colour scheme:", args new_colours(fore, back, link, visited)
2ef360d5443e093a4e0e365ae45cb15c8f3a48e1
wesleyjkolar/week1
/day4/dictionary.py
550
4.25
4
# first=(input("Please input your first name:")) # last=(input("Please input your last name:")) # user={"name":first,"lname":last} # print("My name is, " + user["lname"] + " " + user["name"]) #activity 2 first_name = "Wesley" last_name = "Kolar" home_address = {"street": "1200 Richmond Ave", "city": "Houston"} vacation_home_address = {"street": "5533 Stiener Ranch", "city": "Austin"} addresses = [home_address, vacation_home_address] user = {"first_name": first_name, "last_name": last_name, "addresses": addresses} print(user)
84b82215e6e0ef70780a7f0735a4db0389995642
Monoakuma/Conniving-Conjurations
/DataBug.py
2,033
3.734375
4
import math import sys import random #Data Bug Seed = "" def randomWord(len): chrs = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] word = "" for i in range(len): word+=random.choice(chrs) return(word) def SrandomWord(len): chrs = ['A','A','A','B','C','D','E','E','E','E','E','E','F','G','H','I','I','I','I','J','K','L','M','N','O','O','O','P','Q','R','S','T','U','U','U','V','W','X','Y','Z'] word = "" for i in range(len): word+=random.choice(chrs) return(word) def scatterWord(str): string = str newstring = "" cis = list(range(0,len(string))) random.shuffle(cis) for i in cis: newstring+=string[i] return(newstring) while Seed != "!STOP": print("Hello World, I am DATABUG, I generate Data from numbers and words,\nenter literally anything and I'll try to process it into way too much information. Enter !STOP to end session.") Seed = input(">>>") Orde = 0 for chr in list(Seed): Orde+=ord(chr) try: random.seed(int(Seed)) print("ord:"+str(Orde)) print("int:"+str(int(Seed))) print("abs:"+str(abs(Seed))) print("hlf:"+str(int(Seed)/2)) print("len:"+str(len(Seed))) print("rnt:"+str(random.randint(1,int(Seed)))) print("rnr:"+str(random.random())) print("rwd:"+str(randomWord(len(Seed)))) print("srw:"+str(SrandomWord(len(Seed)))) print("scw:"+scatterWord(Seed)) except: random.seed(Orde) print("ord:"+str(Orde)) print("int:"+str(int(Orde))) print("abs:"+str(abs(Orde))) print("hlf:"+str(Orde/2)) print("len:"+str(len(Seed))) print("rnt:"+str(random.randint(1,Orde))) print("rnr:"+str(random.random())) print("rwd:"+str(randomWord(len(Seed)))) print("srw:"+str(SrandomWord(len(Seed)))) print("scw:"+scatterWord(Seed))
de5f66c5a5ebf55d7b79d0709baaabf947aea373
sharepusher/leetcode-lintcode
/data_structures/linkedlist/reverse_linked_list.py
1,161
3.890625
4
## Reference # http://www.lintcode.com/en/problem/reverse-linked-list/# # 206 https://leetcode.com/problems/reverse-linked-list/#/description ## Tags - Easy; RED # Linked list; Uber; Facebook ## Description # Reverse a linked list. # Example: # For linked list 1->2->3, the reversed linked list is 3->2->1 ## Challenge # Reverse in-place and in one-pass. ## Analysis # 1) stack + traverse: O(N)time; O(N)space; two pass # 2) 3step reverse in-place, and in one pass ## Solutions # definition of listNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next class Solution(object): # stack + traverse def reverse(self, head): if not head: return head stack = [] while head: stack.append(head) head = head.next # pop head = stack.pop() tail = head while stack: tail.next = stack.pop() tail = tail.next tail.next = None return head # reverse in place and in one pass def reverse(self, head): if not head: return head newhead = None while head: tmp = head.next head.next = newhead newhead = head head = tmp return newhead
06e10d2235f8c02c39f2dc86178cc6126a987abe
lucasmsantini/lucasmsantini
/p1_aula5/27.py
147
3.65625
4
n = (input('Digite seu nome completo: ')).strip() nome = (n.split()) print (nome[0]) print ('Quantos blocos? ',len(nome)) print (nome[len(nome)-1])
d484c451c4c2a742d9ed2e8fa882045100cb2f5f
dnswrsrx/adventofcode2k20
/day21.py
4,694
4.15625
4
def occurences(food_list): ''' Get ingredient with allergen occurences, ingredient occurences, and allergen occurences. Both ingredient with allergen occurences and allergen occurences will be used to identify ingredients without allergens. Ingredient occurences will be used to sum number of times ingredients without allergens appear in any food. ''' ingredient_occurences = {} allergen_occurences = {} ingredient_allergen_occurences = {} for food in food_list: if '(' in food: ingredients, allergens = food.split(' (') allergens = allergens.replace('contains ', '').replace(')', '').split(', ') for a in allergens: allergen_occurences.setdefault(a, 0) allergen_occurences[a] += 1 else: ingredients, allergens = food, [] ingredients = ingredients.split(' ') for i in ingredients: allergen_count = ingredient_allergen_occurences.setdefault(i, {}) for a in allergens: allergen_count.setdefault(a, 0) allergen_count[a] += 1 ingredient_occurences.setdefault(i, 0) ingredient_occurences[i] += 1 return ingredient_allergen_occurences, ingredient_occurences, allergen_occurences def ingredients_without_allergens(ingredients_and_allergen, allergen_occurences): ''' For any tentative allergen per ingredient, if said allergen's occurence doesn't match the total allergen's occurences, said ingredient likely isn't an allergen. So we pop said allergen from said ingredient's tentative allergen occurence. Example: if ingredient 'asdasdasd' has {'dairy': 1} and allergen_occurences['dairy'] == 3, likely 'asdasdasd' isn't a dairy allergen. So we pop 'dairy' from the tentative allergen occurence of 'asdasdasd' If the ingredient ends up without any allergen occurences, append to no_allergens. ''' no_allergens = [] for i, a in ingredients_and_allergen.items(): for allergen, count in allergen_occurences.items(): if allergen in a and a[allergen] != count: a.pop(allergen) if not a: no_allergens.append(i) return no_allergens def sort_ingredients_by_allergen(ingredients_and_allergen, without_allergens): # Remove ingredients without allergens # from the original ingredients_and_allergen for i in no_allergens: ingredients_and_allergen.pop(i) # The allergen occurence isn't important, # so make it a list of allergens instead for i, a in ingredients_and_allergen.items(): ingredients_and_allergen[i] = list(a.keys()) # As per instruction, each allergen is only found in one ingredient # and ingredients have 0 or 1 allergen(s). # General concept: # Loop through each ingredient and get the allergens. # If only one allergen, remove said allergen from # the possible allergens in other ingredients. # Let's hope this works. while not all(len(a) == 1 for a in ingredients_and_allergen.values()): for i, a in ingredients_and_allergen.items(): if len(a) == 1: ingredient = a[0] for i2, a in ingredients_and_allergen.items(): if i != i2 and ingredient in a: a.remove(ingredient) return ','.join(sorted(ingredients_and_allergen.keys(), key=lambda i: ingredients_and_allergen[i][0])) if __name__ == '__main__': test = [ 'mxmxvkd kfcds sqjhc nhms (contains dairy, fish)', 'trh fvjkl sbzzf mxmxvkd (contains dairy)', 'sqjhc fvjkl (contains soy)', 'sqjhc mxmxvkd sbzzf (contains fish)' ] ingredients_and_allergen, ingredient_occurences, allergen_occurences = occurences(test) no_allergens = ingredients_without_allergens( ingredients_and_allergen, allergen_occurences ) assert sum(c for i, c in ingredient_occurences.items() if i in no_allergens) == 5 assert sort_ingredients_by_allergen(ingredients_and_allergen, no_allergens) == 'mxmxvkd,sqjhc,fvjkl' with open('inputs/day21.txt') as f: food_list = [l.strip() for l in f.readlines() if l.strip()] ingredients_and_allergen, ingredient_occurences, allergen_occurences = occurences(food_list) no_allergens = ingredients_without_allergens( ingredients_and_allergen, allergen_occurences ) assert sum(c for i, c in ingredient_occurences.items() if i in no_allergens) == 2075 assert sort_ingredients_by_allergen(ingredients_and_allergen, no_allergens) == 'zfcqk,mdtvbb,ggdbl,frpvd,mgczn,zsfzq,kdqls,kktsjbh'
fa1c91a7285c06f6005c96b75b781b167246f599
GemmyTheGeek/Geek-s-Python-Community
/Turtle Python.py
908
3.625
4
import turtle tao = turtle.Turtle() tao.shape('turtle') #tao.forward(100) #tao.left(90) tao.reset () #for i in range(4): #tao.forward(100) #tao.left(90) tao.reset () range(4) list(range(4)) #for i in range (5): #print (i) #for i in [10,50,90]: #print (i) tao.reset() #for i in range(10): #for i in range(8): #tao.forward(50) #tao.left(45) #tao.left(36) tao.reset() def rectangle (): for i in range(2): tao.forward(200) tao.left(90) tao.forward(100) tao.left(90) tao.left(135) rectangle()
1d85d92897ba7d5a1b08f4a05aa5103af1c9edbc
RaulCavalcante/Programacao1-UFRPE-2020.4
/Atividades/06 - Triangulo de Pascal.py
993
4.09375
4
''' O triângulo de Pascal é uma matriz triangular dos coeficientes binomiais. Escreva uma função que recebe um valor inteiro n como entrada e imprime as primeirasn linhas do triângulo de Pascal. A seguir estão as primeiras 6 linhas do Triângulo de Pascal. Entrada: Saida: 3 1 1 1 1 2 1 ''' def calculo(n,p): x = 0 if p == 0 : x = 1 elif p == 1 : x = n elif (p+1) == n: x = n elif n == p: x = 1 else: x = fatorial(n) / (fatorial(p) * fatorial(n-p)) return x def fatorial (x): num = x while x - 1 > 1 : num = num * (x - 1) x -= 1 return num linha = int(input()) n = 0 p = 0 i = 0 while n < linha : if n == 0: print(calculo(n,p)) else: while p <= i: print(int(calculo(n,p)),end=" ") p += 1 print() n += 1 i += 1 p = 0
13181b408c98386b4e6f6ae0380a7247ab391c55
yazeedalrubyli/DEND
/Data Modeling with Postgres/create_tables.py
1,855
3.53125
4
import psycopg2 from sql_queries import create_table_queries, drop_table_queries def create_database(): ''' Drop database (sparkifydb) if exists, create a new one. :returns: The cursor and connection for (sparkifydb). ''' # connect to default database conn = psycopg2.connect("host=127.0.0.1 dbname=studentdb user=student password=student") conn.set_session(autocommit=True) cur = conn.cursor() # create sparkify database with UTF8 encoding cur.execute("DROP DATABASE IF EXISTS sparkifydb") cur.execute("CREATE DATABASE sparkifydb WITH ENCODING 'utf8' TEMPLATE template0") # close connection to default database conn.close() # connect to sparkify database conn = psycopg2.connect("host=127.0.0.1 dbname=sparkifydb user=student password=student") cur = conn.cursor() return cur, conn def drop_tables(cur, conn): ''' Drop tables based on sql_queries.py. :param cur: A cursor to perform database operations. :param conn: Connection to an existing database. ''' for query in drop_table_queries: cur.execute(query) conn.commit() def create_tables(cur, conn): ''' Create tables based on sql_queries.py. :param cur: A cursor to perform database operations. :param conn: Connection to an existing database. ''' for query in create_table_queries: cur.execute(query) conn.commit() def main(): ''' Drop the database, create a new one then create the tables based on sql_queries.py. ''' cur, conn = create_database() # No need for droping all tables one by one, we already droping the whole database(sparkifydb) in previous function call line 21 #drop_tables(cur, conn) create_tables(cur, conn) conn.close() if __name__ == "__main__": main()
71ed508a1b0170902a4785baf4bcb45874f8c099
alexbukher94/Python-projects
/Sal's Shipping Costs.py
779
3.703125
4
def ground_shipping(weight): if weight <= 2: cost = 1.50 elif weight > 2 and weight <= 6: cost = 3.00 elif weight > 6 and weight <= 10: cost = 4.00 else: cost = 10.00 return weight * cost + 20.00 def drone_shipping(weight): if weight <= 2: cost = 4.50 elif weight > 2 and weight <= 6: cost = 9.00 elif weight > 6 and weight <= 10: cost = 12.00 else: cost = 14.25 return weight *cost + 0.00 def cheapest_method(weight): ground = ground_shipping(weight) drone = drone_shipping(weight) premium_shipping = 125.00 if ground < drone and ground < premium_shipping: return ground elif drone < ground and drone < premium_shipping: return drone else: return premium_shipping print(cheapest_method(4.8))
a1da1a68ef7f1b5f0456b6988aef4532e106938a
amu73/DataStructure
/stack_using_list.py
1,090
4.21875
4
stack = [] def push(): """Function for push opertion in Stack """ if len(stack) == n: print("Stack is full") else: item = input("Enter element to push:") stack.append(item) def pop(): """Function for pop operation in stack """ if not stack: print("Stack is empty.") else: item = stack.pop() print("Popped item is",item) def peek(): """Function to traverse the element """ if not stack: print("Stack is empty.") else: print(stack) if __name__ == "__main__": n = int(input("Enter the limit of stack : ")) while True: print("select operation : 1.Push 2.Pop 3.Peek 4.Quit") choice = int(input()) if choice == 1: push() elif choice == 2: pop() elif choice == 3: peek() elif choice == 4: break else: print("Enter correct option")
29c626d32ba2d58c7f5f2c51ba1e00ceb7b9a1f0
fsiddi/generic-tools
/other-exercises/sorting_2.py
1,524
4.1875
4
list_0 = [] list_1 = [3] list_2 = [35,1] list_3 = [7,1,2] list_4 = [1,1,1,4,4,5,6,2,3,0] list_5 = [11,4,6,10,1,9,3,30,22,2,7] list_6 = [33,2,4,5,5,5,1,1,2,5] lists_list = [] ## We append all this lists to another list for unit testing for r in range(7): lists_list.append(eval("list_" + str(r))) ## This is the function containing the sorting algorithm. At the ## moment it does not get rid of duplicated numbers. This should ## be maybe part of another function. def sortList(unsorted_list): print "Unsorted list:", unsorted_list if len(unsorted_list) > 3: small_list = [] big_list = [] main_counter = 0 i = 0 small = unsorted_list[i] big = unsorted_list[i+1] if small < big: pass else: big = unsorted_list[i] small = unsorted_list[i+1] i += 2 for n in range(len(unsorted_list)-2): number = unsorted_list[i] print number if number < small: small = number print "hello" elif number > big: big = number else: pass i += 1 print small, big small_list.append(small) big_list.append(big) unsorted_list.remove(small) unsorted_list.remove(big) big_list.reverse() #print unsorted_list #print small_list #print big_list small_list.extend(unsorted_list) small_list.extend(big_list) print "Sorted list:", small_list else: pass ## Running unit tests by making a loop that reads a list of lists ## created at the beginning for unsorted_list in lists_list: sortList(unsorted_list) print ""
ba7cc829a092a2d462d61a620936339284b320ac
ishaansharma/leetcode-3
/code/404_solution.py
582
3.859375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def sumOfLeftLeaves(self, root: TreeNode) -> int: total = 0 nodes = [(root, 0)] if root else [] while nodes: node, is_left = nodes.pop() if is_left and not (node.left or node.right): total += node.val if node.left: nodes.append((node.left, 1)) if node.right: nodes.append((node.right, 0)) return total
aff8107f6027da0e4722df51b0056e06bb47cf00
Suman205/week1
/circle.py
153
4.25
4
from math import pi R = float(input ("enter a radius")) print ( "for a circle with" + str(R) + "of radius") A = (pi*R*R) print("The area is :" + str(A))
19ea1ba909c36625169cdb0c3947b4a71a0749f8
bionic790/ML-LAB
/ID3 ALGO/code.py
4,917
3.6875
4
import pandas as pd df = pd.read_csv('PlayTennis.csv') print("\n Input Data Set is:\n", df) t = df.keys()[-1] print('Target Attribute is: ', t) # Get the attribute names from input dataset attribute_names = list(df.keys()) #Remove the target attribute from the attribute names list attribute_names.remove(t) print('Predicting Attributes: ', attribute_names) #Function to calculate the entropy of collection S import math def entropy(probs): return sum( [-prob*math.log(prob, 2) for prob in probs]) #Function to calulate the entropy of the given Data Sets/List with #respect to target attributes def entropy_of_list(ls,value): from collections import Counter cnt = Counter(x for x in ls)# Counter calculates the propotion of class print('Target attribute class count(Yes/No)=',dict(cnt)) total_instances = len(ls) print("Total no of instances/records associated with {0} is: {1}".format(value,total_instances )) probs = [x / total_instances for x in cnt.values()] # x means no of YES/NO print("Probability of Class {0} is: {1:.4f}".format(min(cnt),min(probs))) print("Probability of Class {0} is: {1:.4f}".format(max(cnt),max(probs))) return entropy(probs) # Call Entropy def information_gain(df, split_attribute, target_attribute,battr): print("\n\n-----Information Gain Calculation of ",split_attribute, " --------") df_split = df.groupby(split_attribute) # group the data based on attribute values glist=[] for gname,group in df_split: print('Grouped Attribute Values \n',group) glist.append(gname) glist.reverse() nobs = len(df.index) * 1.0 df_agg1=df_split.agg({target_attribute:lambda x:entropy_of_list(x, glist.pop())}) df_agg2=df_split.agg({target_attribute :lambda x:len(x)/nobs}) df_agg1.columns=['Entropy'] df_agg2.columns=['Proportion'] # Calculate Information Gain: new_entropy = sum( df_agg1['Entropy'] * df_agg2['Proportion']) if battr !='S': old_entropy = entropy_of_list(df[target_attribute],'S-'+df.iloc[0][df.columns.get_loc(battr)]) else: old_entropy = entropy_of_list(df[target_attribute],battr) return old_entropy - new_entropy def id3(df, target_attribute, attribute_names, default_class=None,default_attr='S'): from collections import Counter cnt = Counter(x for x in df[target_attribute])# class of YES /NO ## First check: Is this split of the dataset homogeneous? if len(cnt) == 1: return next(iter(cnt)) # next input data set, or raises StopIteration when EOF is hit. ## Second check: Is this split of the dataset empty? if yes, return a default value elif df.empty or (not attribute_names): return default_class # Return None for Empty Data Set ## Otherwise: This dataset is ready to be devied up! else: # Get Default Value for next recursive call of this function: default_class = max(cnt.keys()) #No of YES and NO Class # Compute the Information Gain of the attributes: gainz=[] for attr in attribute_names: ig= information_gain(df, attr, target_attribute,default_attr) gainz.append(ig) print('Information gain of ',attr,' is : ',ig) index_of_max = gainz.index(max(gainz)) # Index of Best Attribute best_attr = attribute_names[index_of_max] # Choose Best Attribute to split on print("\nAttribute with the maximum gain is: ", best_attr) # Create an empty tree, to be populated in a moment tree = {best_attr:{}} # Initiate the tree with best attribute as a node remaining_attribute_names =[i for i in attribute_names if i != best_attr] # Split dataset-On each split, recursively call this algorithm.Populate the empty tree with subtrees, which # are the result of the recursive call for attr_val, data_subset in df.groupby(best_attr): subtree = id3(data_subset,target_attribute, remaining_attribute_names,default_class,best_attr) tree[best_attr][attr_val] = subtree return tree from pprint import pprint tree = id3(df,t,attribute_names) print("\nThe Resultant Decision Tree is:") pprint(tree) def classify(instance, tree,default=None): # Instance of Play Tennis with Predicted attribute = next(iter(tree)) # Outlook/Humidity/Wind if instance[attribute] in tree[attribute].keys(): # Value of the attributs in set of Tree keys result = tree[attribute][instance[attribute]] if isinstance(result, dict): # this is a tree, delve deeper return classify(instance, result) else: return result # this is a label else: return default df_new=pd.read_csv('PlayTennisTest.csv') df_new['predicted'] = df_new.apply(classify, axis=1, args=(tree,'?')) print(df_new)
04bd17d9f71b64770130c475c383ecc633361843
parkerahall/dailycodingchallenge
/1-7-19.py
985
3.5625
4
class LinkedList: def __init__(self, value, nxt=None): self.value = value self.next = nxt def check_list(ll, l): ind = 0 while ll != None: assert ll.value == l[ind] ind += 1 ll = ll.next def rem_kth_last(linked_list, k): minus_one = None plus_one = None ind = 0 head = linked_list while linked_list != None: if ind == k + 1: minus_one = head plus_one = head.next.next elif ind > k + 1: minus_one = minus_one.next plus_one = plus_one.next ind += 1 last = linked_list linked_list = linked_list.next if minus_one == None: return head.next else: minus_one.next = plus_one return head for i in range(5): ll = LinkedList(1, nxt=LinkedList(2, nxt=LinkedList(3, nxt=LinkedList(4, nxt=LinkedList(5))))) ll = rem_kth_last(ll, i) check_list(ll, [j for j in range(1, 6) if j != 5 - i])
2959d66cfc12fb49116efb666657aa2354db2dec
AsafKaslassy/python-training2019
/archive/function_demo/variables_scope.py
1,554
3.890625
4
def spacing(): addSpace = "-----------\n" print(addSpace) class ScopeTesting: def toplevel(num): a = num # Global variable but inside function only def nested(): nonlocal a # Adds the non-local variable to this nested function, without this, variable 'a' un-accessible. tempA = a a += 2 print( f"toplevel, nested(), {tempA} + 2 = {a}") # tries to print local variable a but its created after this line so exception is raised a = 7 nested() print(f"toplevel, not nested() = {a}") def toplevel2(num): a = num # variable inside function only def nested(): a = 5 + 2 print( f"toplevel2, nested(), a + 2 = {a}") # tries to print local variable a but its created after this line so exception is raised print(f"toplevel2, not nested() = {a}") nested() def enclosedScope(num): number = num def outer(num): number = num + 1 # Inner scope def inner(num): number = num + 2 print(f"def inner(num):{number}") inner(number) # nested inner level print(f"def outer(num):{number}") outer(number) # nested outer level print(f"def enclosedScope(num):{number}") # function level """This is a functions initiation.""" spacing() ScopeTesting.toplevel(5) spacing() ScopeTesting.toplevel2(5) spacing() ScopeTesting.enclosedScope(5) spacing()
c2dd10e3dedfeaf32aa44a5f60bbfb6f0dd4f27f
soulorman/Python
/practice/practice_4/select_sort.py
517
3.8125
4
# encoding: utf-8 # 选择排序 时间复杂度O(n^2) 空间复杂度 O(1) 不稳定 def selection_sort(arr): """选择排序 :param arr:需要排序的列表 :return: 排序完成的列表 """ length = len(arr) for i in range(length - 1): minIndex = i for j in range(i + 1, length): if arr[j] < arr[minIndex]: minIndex = j arr[i], arr[minIndex] = arr[minIndex], arr[i] return arr lis = [1, 5, 2, 0, 3] print(selection_sort(lis))
20c82e238c74f00b37265f9a569b120a98b5c446
peter1314/Space-Trader
/app/py/enums.py
3,731
3.765625
4
"""File containing enums""" from enum import Enum from collections import namedtuple DifficultyLevel = namedtuple('DifficultyLevel', ['name', 'starting_credits', 'number']) class Difficulty(Enum): """Enum for storing the difficulty of the game""" @property def nanme(self): """Returns the name of a difficulty""" return self.value.name @property def starting_credits(self): """Returns the starting credits of a difficulty""" return self.value.starting_credits @property def number(self): """Returns the number of a difficulty""" return self.value.number EASY = DifficultyLevel("Easy", 10000, 1) MEDIUM = DifficultyLevel("Medium", 500, 2) HARD = DifficultyLevel("Hard", 250, 3) class TechLevel(Enum): """Enum for storing the techlevel of a region, market, or item""" Primitive = 1 Agricultural = 2 Industrial = 3 Modern = 4 Planetary = 5 Interstellar = 6 Galactic = 7 ShipType = namedtuple('ShipType', ['cargo_cap', 'fuel_cap', 'health_cap', 'speed']) class ShipTypes(Enum): """Enum for storing different types of ships""" @property def cargo_cap(self): """Returns the capacity of a ship type""" return self.value.cargo_cap @property def fuel_cap(self): """Returns the fuel capacity of a ship type""" return self.value.fuel_cap @property def health_cap(self): """Returns the health capacity of a ship type""" return self.value.health_cap @property def speed(self): """Returns the speed of a ship type""" return self.value.speed Wren = ShipType(500, 20, 8, 20) Sparrow = ShipType(150, 30, 10, 20) Robin = ShipType(200, 30, 15, 25) Crow = ShipType(200, 40, 25, 25) Hawk = ShipType(250, 35, 50, 40) Falcon = ShipType(300, 45, 60, 45) Eagle = ShipType(400, 50, 70, 50) Albatross = ShipType(1000, 100, 60, 30) ItemType = namedtuple('ItemType', ['name', 'slot', 'size', 'base_price', 'base_count', 'tech_level']) class ItemTypes(Enum): """Enum for storing different types of items""" @property def name(self): """Returns the name of an item type""" return self.value.name @property def slot(self): """Returns the slot number of an item type, items are numbered by their slot""" return self.value.slot @property def size(self): """Returns the size of an item type""" return self.value.size @property def price(self): """Returns the base price of an item type""" return self.value.base_price @property def count(self): """Returns the base count of an item type""" return self.value.base_count @property def tech_level(self): """Returns the tech level of an item type""" return self.value.tech_level Food = ItemType("Food", 0, 10, 10, 500, TechLevel.Primitive) Wood = ItemType("Wood", 1, 30, 25, 200, TechLevel.Primitive) Spices = ItemType("Spices", 2, 5, 50, 150, TechLevel.Agricultural) Gold = ItemType("Gold", 3, 5, 100, 50, TechLevel.Agricultural) Medicine = ItemType("Medicine", 4, 10, 100, 100, TechLevel.Industrial) Phone = ItemType("Phones", 5, 5, 200, 100, TechLevel.Industrial) Computer = ItemType("Computers", 6, 10, 500, 80, TechLevel.Modern) Ray_Gun = ItemType("Ray Guns", 7, 25, 1500, 50, TechLevel.Planetary) Nanobots = ItemType("Nanobots", 8, 10, 5000, 30, TechLevel.Interstellar) Dark_Matter = ItemType("Dark Matter", 9, 10, 10000, 20, TechLevel.Galactic) Special = ItemType("Special", 10, 100, 5, 0, TechLevel.Primitive)
913513321d29e68818b088be1c3c2c76961462b7
skyjan0428/WorkSpace
/test/targets/regex.py
288
3.890625
4
import re # pragma: no cover def regex(string): """This function returns at least one matching digit.""" pattern = re.compile(r"^(\d+)") # For brevity, this is the same as r"\d+" result = pattern.match(string) if result: return result.group() return None
cc5bfcd4a00c559712475d9925d95813f12d1f08
AnthonyBriggs/Python-101
/hello_python_source_py3/chapter 10/mud-2/player.py
6,077
3.765625
4
import random import shlex help_text = """ ------------------------ Welcome to Anthony's MUD ------------------------ This text is intended to help you play the game, such as it is right now. Most of the usual MUD-type commands should work, including: name: set your name describe: describe yourself n,s,e,w: move around! look: look at things! say: you can say things shout: you can shout stuff so that everyone can hear it. get/drop/inv: you can pick stuff up. There are two items in the game - whoever has the coin is the current winner. attack: you can attack pretty much any other mobile in the game. Watch out for the orc though, or anyone carrying a sword. If there are any major bugs, let me know at anthony.briggs@gmail.com. """.split('\n') class Player(object): def __init__(self, game, location): self.game = game self.name = "Player" self.description = "The Player" self.location = location self.location.here.append(self) self.playing = True self.hit_points = 3 self.inventory = [] self.events = [] self.input_list = [] self.result = [] def get_input(self): #return raw_input(self.name+">") if self.input_list: return self.input_list.pop() else: return '' def send_results(self): for line in self.result: self.connection.msg_me(line) for line in self.events: self.connection.msg_me(line) def find_handler(self, verb, noun): if verb == 'name': verb = 'name_' if verb == "'": verb = 'say' # Try and find the object if noun != "": object = [x for x in self.location.here + self.inventory if x is not self and x.name == noun and verb in x.actions] if len(object) > 0: return getattr(object[0], verb) # if that fails, look in location and self if verb.lower() in self.location.actions: return getattr(self.location, verb) elif verb.lower() in self.actions: return getattr(self, verb) def process_input(self, input): # print str(self) + " executing :" + input try: parts = shlex.split(input) except ValueError: parts = input.split() if len(parts) == 0: return [] if len(parts) == 1: parts.append("") # blank noun verb = parts[0] noun = ' '.join(parts[1:]) handler = self.find_handler(verb, noun) if handler is None: return [input+"? I don't know how to do that!"] if '__call__' not in dir(handler): return handler return handler(self, noun) def update(self): self.result = self.process_input(self.input) def die(self): self.playing = False self.input = "" self.name = "A dead " + self.name # drop all our stuff for item in self.inventory: self.location.here.append(item) item.location = self.location self.inventory = [] # disconnect self.connection.msg_me("You have died! Better luck next time!") self.connection.transport.loseConnection() actions = ['quit', 'inv', 'get', 'drop', 'attack', 'name_', 'describe', 'look', 'help', 'say', 'shout'] no_noun_verbs = ['quit', 'inv', 'name_', 'describe', 'help', 'say', 'shout'] def help(self, player, noun): return help_text def inv(self, player, noun): result = ["You have:"] if self.inventory: result += [x.name for x in self.inventory] else: result += ["nothing!"] return result def quit(self, player, noun): self.playing = False self.die() return ["bye bye!"] def get(self, player, noun): return [noun + "? I can't see that here."] def drop(self, player, noun): return [noun + "? I don't have that!"] def name_(self, player, noun): self.name = noun return ["You changed your name to '%s'" % self.name] def describe(self, player, noun): self.description = noun return ["You changed your description to '%s'" % self.description] def look(self, player, noun): return ["You see %s." % self.name, self.description] def say(self, player, noun): for object in self.location.here: if ('events' in dir(object) and object != self): object.events.append(self.name + " says: " + noun) return ["You say: " + noun] def shout(self, player, noun): noun = noun.upper() for location in self.game.caves: for object in location.here: if ('events' in dir(object) and object != self): object.events.append(self.name + " shouts: " + noun) return ["You shout: " + noun] def attack(self, player, noun): hit_chance = 2 has_sword = [i for i in player.inventory if i.name == 'sword'] if has_sword: hit_chance += 2 roll = random.choice([1,2,3,4,5,6]) if roll > hit_chance: self.events.append("The " + player.name + " misses you!") return ["You miss the " + self.name] self.hit_points -= 1 if self.hit_points <= 0: return_value = ["You kill the " + self.name] self.events.append("The " + player.name + " has killed you!") self.die() return return_value self.events.append("The " + player.name + " hits you!") return ["You hit the " + self.name]
6733dcfdb1159580f49c60a11a3e6c01170f8d9e
ashwinvidiyala/Python-Fundamentals
/multiplication_table.py
895
3.875
4
line1 = ["x"] line2 = [1] line3 = [2] line4 = [3] line5 = [4] line6 = [5] line7 = [6] line8 = [7] line9 = [8] line10 = [9] line11 = [10] line12 = [11] line13 = [12] for i in range(1, 13): line1.append(i) line2.append(i) line3.append(2 * i) line4.append(3 * i) line5.append(4 * i) line6.append(5 * i) line7.append(6 * i) line8.append(7 * i) line9.append(8 * i) line10.append(9 * i) line11.append(10 * i) line12.append(11 * i) line13.append(12 * i) def horizontal_print(list): for x in list: print x, print "" horizontal_print(line1) horizontal_print(line2) horizontal_print(line3) horizontal_print(line4) horizontal_print(line5) horizontal_print(line6) horizontal_print(line7) horizontal_print(line8) horizontal_print(line9) horizontal_print(line10) horizontal_print(line11) horizontal_print(line12) horizontal_print(line13)
3b9d4b1fb418029d28546ebdacfa992c04a37130
scarlet-chariot/CSCI107
/Fox.py
900
3.75
4
# -----------------------------------------+ # Shengnan Zhou, Alex Tseng | # CSCI 107, Assignment 4 | # Last Updated: February 16, 2018 | # -----------------------------------------| # Use loops to minimize repeated words and | # phrases to these lyrics of "The Fox". | # -----------------------------------------+ print("Dog goes woof, cat goes meow.") print("Bird goes tweet, and mouse goes squeak.") print("Cow goes moo. Frog goes croak, and the elephant goes toot.") a= "Ducks say quack and fish go blub, and the seal goes" for i in range(1,4): b= " OW"*i print(a+b+".") print("But there's one sound that no one knows...") print("WHAT DOES THE FOX SAY?") print() for i in range(2): for j in range(4): c= " ding"*j+" dingeringeding!" print("Ring"+c) print("Gering"+c) for i in range(3): for j in range(6): d= " pa"*j+" pow!" print("Wa"+d)
d6513a00ef8487bd4db72aeb139a36b43b73f565
ZahraRoushan/MachineLearning1
/Algorithm_Section/sorting_searching/bubble_sort.py
280
3.796875
4
def buuble_sort(arr: list) -> list: arr_size = len(arr) for i in range(arr_size): for j in range(arr_size - i - 1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr print(buuble_sort([5, 6, -2, 0, 98, 12]))
f1f5aa27f527d799cadaab82eede53ed76f91b0a
patri-carrasco/project-game
/src/functions.py
1,803
3.875
4
import random import os def clear(): os.system('clear') def is_letter(char): ''' This function checks if char is in alphabet arg: char return letter : True or False ''' alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" letter = False if char in alphabet: letter = True return (letter) def random_word(word): ''' This function returns a random word from a list arg: word return random word ''' random_w =random.choice(word) return (random_w) def pos_char(char,word): ''' This function looks for the character in the word and returns the positions where they appear args : char word return positions ''' pos = [] for i in enumerate(word): if i[1] == char: pos.append(i[0]) return (pos) def get_empty_word(size): arr = [] for i in range(size): arr += '-' return arr def print_game_status(wrong, right,board): print(hangman[len(wrong)]) print(board) print(f'Mistake char {wrong}') print(f'Right {right}') def get_char(): while True: char= input("Enter a char ").lower() if is_letter(char): return char print("Enter a correct char ") hangman = [ ''' +---+ | | | | | | | | -------- -------- ''', ''' +---+ | | | O | | | | | -------- -------- ''', ''' +---+ | | | O | | | | | | | -------- -------- ''', ''' +---+ | | | O | /| | | | | | -------- -------- ''', ''' +---+ | | | O | /|\\ | | | | | -------- -------- ''', ''' +---+ | | | O | /|\\ | | | / | | -------- -------- ''', ''' +---+ | | | O | /|\\ | | | / \\ | | -------- -------- ''' ]
ff52359edfbba309f27bdc9ce9f9eb8ff26c9e40
estraviz/codewars
/7_kyu/Random case/test_random_case.py
1,024
3.578125
4
from random_case import random_case def test_random_case(): v = [ "Lorem ipsum dolor sit amet, consectetur adipiscing elit", "Donec eleifend cursus lobortis", "THIS IS AN ALL CAPS STRING", "These guidelines are designed to be compatible with Joe Celko’s SQL Programming Style book", "much harder with a physical book.", "This guide is a little more opinionated in some areas and in others a little more relaxed", "—such as unnecessary quoting or parentheses or WHERE clauses that can otherwise be derived.", "Object oriented design principles should not be applied to SQL or database structures.", "collective name or, less ideally, a plural form. For example (in order of preference) staff and employees", "THIS IS AN ALL CAPS STRING", "this is an all lower string" ] for i in v: r = random_case(i) assert r.lower() == i.lower() assert r != i assert r != i.upper() assert r != i.lower()
f1d4a3bbd2c521a78070d49d609cd58a87b8d943
kalynbeach/Python-Projects
/Projects/WeatherAdvices.py
1,928
4.09375
4
# Weather Advices by Kalyn Beach # Advice which activity should be done given a temperature, then count # and average out all given temperatures with a pretest loop: def weatherPretest(): total = 0; counter = 0; temp = input("Enter temperature in Fahrenheit, -9999 to quit: "); while (temp != -9999): if (temp < 40): activity = "Get some sleep at home."; elif (temp < 60): activity = "Browse the Internet."; elif (temp < 75): activity = "Take a walk in the park."; elif (temp < 90): activity = "Sunbathe on the lawn."; else: activity = "Go to the beach."; print activity; total = total + temp; counter = counter + 1; temp = input("Enter temperature in Fahrenheit, -9999 to quit: "); print 'Temperatures processed:', counter; average = float(total) / counter; print 'Average Temperature:', average; # Advice which activity should be done given a temperature, then count # and average out all given temperatures with a interrupted loop: def weatherInterrupted(): total = 0; counter = 0; while(True): temp = input("Enter temperature in Fahrenheit, -9999 to quit: "); if (temp < 40): activity = "Get some sleep at home."; elif (temp < 60): activity = "Browse the Internet."; elif (temp < 75): activity = "Take a walk in the park."; elif (temp < 90): activity = "Sunbathe on the lawn."; else: activity = "Go to the beach."; print activity; if (temp == -9999): break; total = total + temp; counter = counter + 1; print 'Temperatures processed:', counter; average = float(total) / counter; print 'Average Temperature:', average;
5ed7207f4e28bbb911f288999a62f5a59dcf2276
chenxu0602/LeetCode
/1139.largest-1-bordered-square.py
1,517
3.515625
4
# # @lc app=leetcode id=1139 lang=python3 # # [1139] Largest 1-Bordered Square # # https://leetcode.com/problems/largest-1-bordered-square/description/ # # algorithms # Medium (47.34%) # Likes: 242 # Dislikes: 54 # Total Accepted: 11.2K # Total Submissions: 23.4K # Testcase Example: '[[1,1,1],[1,0,1],[1,1,1]]' # # Given a 2D grid of 0s and 1s, return the number of elements in the largest # square subgrid that has all 1s on its border, or 0 if such a subgrid doesn't # exist in the grid. # # # Example 1: # # # Input: grid = [[1,1,1],[1,0,1],[1,1,1]] # Output: 9 # # # Example 2: # # # Input: grid = [[1,1,0,0]] # Output: 1 # # # # Constraints: # # # 1 <= grid.length <= 100 # 1 <= grid[0].length <= 100 # grid[i][j] is 0 or 1 # # # @lc code=start class Solution: def largest1BorderedSquare(self, grid: List[List[int]]) -> int: m, n = map(len, (grid, grid[0])) biggest, dp = 0, [[(0, 0) for _ in range(n + 1)] for _ in range(m + 1)] for r in range(m)[::-1]: for c in range(n)[::-1]: if grid[r][c]: dp[r][c] = (1 + dp[r+1][c][0], 1 + dp[r][c+1][1]) if min(dp[r][c]) > biggest: for side in range(biggest, 1 + min(dp[r][c]))[::-1]: if side <= dp[r + side - 1][c][1] and side <= dp[r][c + side - 1][0]: biggest = side break return biggest ** 2 # @lc code=end
69e3e452f296a7a983478c49e749f9aa571b5ecd
gguillamon/PYTHON-BASICOS
/python_ejercicios basicos_III/varios/bucles II/Ejercicio3.py
961
4.25
4
# 3.- Programa que lee notas de los alumnos y dice cuántos están aprobados y cuál es la nota # media. El programa dejará de pedir notas, cuando se pulse la tecla ENTER. # Introduzca las notas, ENTER para terminar: # Nota del alumno 1: 5.60 # Nota del alumno 2: 4.20 # Nota del alumno 3: 8.35 # Nota del alumno 4: 7.23 # Nota del alumno 5: 5.01 # Nota del alumno 6: (pulsamos ENTER) # Número de alumnos: 5 # Aprobados: 4 # Suspensos: 1 # # Nota media: 6.08 #Gabriel Guillamon print('Introduzca las notas, ENTER para terminar') suma=0 aprobados = 0 suspensos = 0 i=0 salir = False while not salir: i+=1 nota = input(f'Nota del alumno {i}: ') if nota != '': notaInteger = float(nota) suma += notaInteger if notaInteger >= 5: aprobados += 1 else: suspensos += 1 else: salir = True print(f"Numero de alumnos:{i-1}\nAprobados:{aprobados}\nSuspensos:{suspensos}\nNota media:{(suma)/i}")
31adb85d1fa94efbc05babbde2eb4d27d9cefff5
mlin1025/pismart_ros
/scripts/pismart/weather.py
2,071
3.609375
4
from basic import _Basic_class import requests import json class Weather(object): """ get weather message from internet http://openweathermap.org/ """ city = None API_key = None url = None _city_name = 'N/A' _weather = 'N/A' _temp = 'N/A' _temp_min = 'N/A' _temp_max = 'N/A' _humidity = 'N/A' _pressure = 'N/A' _wind_speed = 'N/A' _wind_degree = 'N/A' def __init__(self, city, API_key): super(Weather, self).__init__() if city == None or API_key == None: raise ValueError ("city or API_key is None") else: self.city = city self.API_key = API_key self.url = 'http://api.openweathermap.org/data/2.5/weather?q=%s&APPID=%s'%(self.city, self.API_key) def reflash(self): jsonStr = requests.get(self.url).text data = json.loads(jsonStr) self._city_name = data["name"] self._weather = data["weather"][0]["description"] self._temp = float(data["main"]["temp"])-273.16 self._temp_min = float(data["main"]["temp_min"])-273.16 self._temp_max = float(data["main"]["temp_max"])-273.16 self._humidity = float(data["main"]["humidity"]) self._pressure = float(data["main"]["pressure"]) self._wind_speed = float(data["wind"]["speed"]) self._wind_degree = float(data["wind"]["deg"]) ''' print"++++++++++++++++++++++++++++++++++++" print"weather report:\n" print " city :", self._city print " weather:", self._weather print " temp:", self._temp print " temp_min:", self._temp_min print " temp_max:", self._temp_max print " humidity:", self._humidity print " pressure:", self._pressure print " wind speed:", self._wind_speed print " wind_degree:", self._wind_degree print "++++++++++++++++++++++++++++++++++++" ''' @property def weather(self): return self._weather @property def temperature(self): return self._temp @property def temp_min(self): return self._temp_min @property def temp_max(self): return self._temp_max @property def city(self): return self._city
46eed6d95cc2dc2a545cdb4fd2692e51c32d9fdc
siddharth424/Automate-the-boring-stuff-with-python
/Chapter-7/Date_Detection.py
720
3.921875
4
import re str=input() dateRegex = re.compile(r'(\d{2})/(\d{2})/(\d{4})') mo =dateRegex.search(str) if mo==None: print("Invalid format") else: date = int(mo.group(1)) month = int(mo.group(2)) year = int(mo.group(3)) if year%4==0: if year%100==0: if year%400==0: feb=29 else: feb=28 else: feb=29 else: feb=28 dmax=[31,feb,31,30,31,30,31,31,30,31,30,31] if date>dmax[month-1]: print("Invalid date") elif month>12: print("Invalid date") elif year>=3000 or year<1000: print("Invalid date") else: print("Valid date")
198424ba706a8748a47e21c657cdde466cd5ebae
jrbella/computer_science_icstars
/basic_functions/reverse.py
400
4.09375
4
# Write your reverse_string function here: def reverse_string(word): lst = "" for i in range(len(word)-1,-1,-1): print(word[i]) lst += (word[i]) return lst # Uncomment these function calls to test your function: print(reverse_string("Codecademy")) # should print ymedacedoC #print(reverse_string("Hello world!")) # should print !dlrow olleH #print(reverse_string("")) # should print
c1958a0ada14b0df5ec5f64041af225c8a701e41
Anomium/Quinto-Semestre
/Python/Ejercicios Python - Taller 2/Ejercicio 5.py
163
4
4
def orden(num): #y = sorted(num) num.sort() return num x=[] for i in range(3): x.append(input("Digite 3 valores enteros: ")) print(orden(x))
374409b672f557a082fd3b64393fb9a4bd51e3fc
CivilizedWork/Whisper-Jhin
/day15/Practice.py
1,802
4.0625
4
import math class Point: """Represents a point in 2-D space.""" print(Point) blank = Point() print(blank) blank.x = 3.0 blank.y = 4.0 print(blank.y) x = blank.x print(x) print('(%g, %g)' % (blank.x, blank.y)) distance = math.sqrt(blank.x**2 + blank.y**2) print(distance) def print_point(p): print('(%g, %g)' % (p.x, p.y)) print_point(blank) def distance_between_points(p1,p2): distance= math.sqrt((p1.x-p2.x)**2+(p1.y-p2.y)**2) return distance print(distance_between_points(blank,blank)) class Rectangle: """ Represents a rectangle. attributes: width, height, corner. """ box = Rectangle() box.width = 100.0 box.height = 200.0 box.corner = Point() box.corner.x = 0.0 box.corner.y = 0.0 def find_center(rect): p = Point() p.x = rect.corner.x + rect.width/2 p.y = rect.corner.y + rect.height/2 return p center = find_center(box) print_point(center) box.width = box.width + 50 box.height = box.height + 100 def grow_rectangle(rect, dwidth, dheight): rect.width += dwidth rect.height += dheight print(box.width,box.height) grow_rectangle(box, 50, 100) print(box.width, box.height) def move_rectangle(rect, dx, dy): rect.corner.x += dx rect.corner.y += dy p1 = Point() p1.x = 3.0 p1.y = 4.0 import copy p2 = copy.copy(p1) print_point(p1) print_point(p2) print(p1 is p2) print(p1 == p2) box2 = copy.copy(box) print(box2 is box) print(box2.corner is box.corner) box3 = copy.deepcopy(box) print(box3 is box) print(box3.corner is box.corner) def move_rectangle_new(rect,dx,dy): rect1 = copy.deepcopy(rect) rect1.corner.x += dx rect1.corner.y += dy p = Point() p.x = 3 p.y = 4 #print(p.z) print(type(p)) print(isinstance(p,Point)) print(hasattr(p, 'x')) print(hasattr(p, 'z')) try: x = p.x except AttributeError: x = 0
759325f50ac7ef2ecab7ebaa50649ab35b0e8af7
Marek-Python/infoshare
/próg procentowy/range.py
1,007
4.03125
4
zakres= range (3,10) for i in zakres: print(i) nazwisko = "Strzelecki" for litera in nazwisko[::2]: print(litera.upper()) litery = list(nazwisko) print(litery) moja_lista=[1,2,3,4,5,6,7,8,9] print(moja_lista) for cyfra in moja_lista: print(cyfra) lista_liter=['s','t','r','z','e','l','e','c','k','i'] string_z_listy="".join(lista_liter) print(string_z_listy) string_z_listy="_".join(lista_liter) print(string_z_listy) string_z_listy="*".join(lista_liter) print(string_z_listy) #lista zakupów = [1, "napis", "L",] lista_zakupow = ["jajko", "długopis", "kura"] #opcja 1: for for rzecz_do_kupienia in lista_zakupow: print(rzecz_do_kupienia) #opcja 2 co_kupic = ", ".join(lista_zakupow) print("chce kupić {}".format(co_kupic)) ### magic="abracadabra" for i in range(len(magic)): print(i, magic[i]) #### zakres=range(10) lista_z_zakresu = list(zakres) print(lista_z_zakresu) for i in zakres: print(i, end=", ") print() for i in lista_z_zakresu: print(i, end=", ")
9b8f7e9815acc6ea56733282b2cfca2eb052ad74
ManaliKulkarni30/Python_Practice_Programs
/Decorator.py
710
3.90625
4
#Inbuilt Function Model def Subtraction(no1,no2): print("3:Inside Subtraction") return no1-no2 def SubDecorator(func_name): print("7: Inside SubDecorator") def Updator(a,b): print("9:Inside Updator") if a < b: temp = a a = b b = temp return func_name(a,b) return Updator def main(): print("19:Inside main") sub = SubDecorator(Subtraction) no1 = int(input("Enter first number:")) no2 = int(input("Enter second number:")) ret = sub(no1,no2) print("Subtraction is:",ret) print("28:End of main") if __name__ == '__main__': print("32:Inside starter") main()
8e9bca2121377b3efdcd53034e9c093c0d544e45
tjy-cool/python_study
/day7/属性方法.py
1,004
4.125
4
#!/usr/bin/env python # Funtion: # Filename: import os class Dog(object): food = 'water' def __init__(self, name): # self 为对象,cls为类 self.name = name self.n = '123' self.__food = 'fish' # @staticmethod # 实际上跟类没什么关系了,只是需要利用类来调用而已 # @classmethod # 只能访问类的共有属性,不能访问普通属性(即成员变量) @property # attribute def eat(self): print("%s is eating %s" % (self.name, self.__food)) @eat.setter def eat(self, food): print('set to food:', food) self.__food = food @eat.deleter def eat(self): del self.__food print('self.food has been del') # # def talk(self): # print('%s is talking' %self.name) d1 = Dog('Bagong') d2 = Dog('haha') d1.eat d2.eat d1.eat = 'baozi' d1.eat # # print(d1.eat) # del d1.eat # d1.eat # print(d1.eat) # del d1.name # print(d1.name) # del d1.eat
c1072050795fdc43153c2f3cc5a255ef0d53acb2
asingh714/Sorting
/src/recursive_sorting/recursive_sorting.py
1,232
4.0625
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(left, right): merged_arr = [] left_i, right_i = 0, 0 while left_i < len(left) and right_i < len(right): if left[left_i] <= right[right_i]: merged_arr.append(left[left_i]) left_i += 1 else: merged_arr.append(right[right_i]) right_i += 1 if left_i < len(left): merged_arr.extend(left[left_i:]) if right_i < len(right): merged_arr.extend(right[right_i:]) return merged_arr # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort(arr): # TO-DO if len(arr) <= 1: return arr middle = len(arr) // 2 left = arr[:middle] right = arr[middle:] left = merge_sort(left) right = merge_sort(right) return list(merge(left, right)) # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): # TO-DO return arr def merge_sort_in_place(arr, l, r): # TO-DO return arr # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def timsort(arr): return arr
887d865a3786669a8c2b32eb7ce295d85fedcc6e
neoguri/supreme-funicular
/influence2.py
6,769
3.59375
4
# Submitter: bssoohoo(Soo Hoo, Brandon) # Partner : lgazzola(Gazzola, Luca) # We certify that we worked cooperatively on this programming # assignment, according to the rules for pair programming import prompt from goody import safe_open from math import ceil from collections import defaultdict #d has 2 friends #2 - something #something = ceil(2 / 2) def read_graph(open_file : open) -> {str:{str}}: friend_graph = {}; while True: line = open_file.readline() line = line.strip("\n") if line == "": break; line = line.split(";") key = friend_graph.keys() if len(line) > 1: if (line[0] in key): friend_graph[line[0]].add(line[1]) print(line[0], line[1]) else: friend_graph[line[0]] = set() friend_graph[line[0]].add(line[1]) if (line[1] in key): friend_graph[line[1]].add(line[0]) else: friend_graph[line[1]] = set() friend_graph[line[1]].add(line[0]) elif len(line) == 1: if (not line[0] in key): friend_graph[line[0]] = set() return friend_graph def graph_as_str(graph : {str:{str}}) -> str: ans = "" for key in sorted(list(graph)): ans += " " + key + " -> [" sorted_list = sorted(list(graph[key])) try: for index in range(len(sorted_list)): if index == 0: ans += "\'" + sorted_list[index] + "\'" else: ans += ", \'" + sorted_list[index] + "\'" except TypeError: break ans += "]\n" print(ans) return ans def find_influencers(graph : {str:{str}}, trace : bool = False) -> {str}: infl_dict = {} for key in graph: infl_dict[key] = [(len(graph[key]) - ceil(len(graph[key]) / 2)) if len(graph[key]) > 0 else -1, len(graph[key]), key] while True: #print(infl_dict) #print (graph) cand_list = [] for key in infl_dict: if infl_dict[key][0] >= 0: cand_list.append((infl_dict[key][0], infl_dict[key][1], infl_dict[key][2])) #print(infl_dict) if cand_list == []: return set(infl_dict.keys()) cand_list.sort(key = lambda x : x[2]) least = max(cand_list, key = lambda x : x[0])[0] letter_least_key = max(cand_list, key = lambda x : x[0])[2] least_friends = cand_list[0][1] for index in cand_list: if index[2] == letter_least_key: least_friends = index[1] for index in cand_list: if index[0] < least: least = index[0] letter_least_key = index[2] least_friends = index[1] elif index[0] == least: if least_friends > index[1]: least = index[0] letter_least_key = index[2] least_friends = index[1] #print(letter_least_key) #print(letter_least_key) #print(infl_dict) if trace: #prints for if trace is True print("influencer dictionary\t=", infl_dict) print("removal candidates\t=", cand_list) print((infl_dict[letter_least_key][0], infl_dict[letter_least_key][1], infl_dict[letter_least_key][2]), "is the smallest candidate") print("Removing", letter_least_key, "as key from influencer dictionary; decrementing friend's values here", end = "\n\n") infl_dict.pop(letter_least_key) #graph.pop(letter_least_key) #remove letter_least_key element in graph for key in infl_dict: #remove letter_least_key from each element of graph if letter_least_key in graph[key]: infl_dict[key][0] -= 1 infl_dict[key][1] -= 1 #print(cand_list) def all_influenced(graph : {str:{str}}, influencers : {str}) -> {str}: ans = set(influencers) #print(ans) while True: add_to_ans = False for key in graph: count = 0 for influenced in ans: if influenced in graph[key]: count += 1 if count >= ceil(len(graph[key]) / 2) and count > 0: if not key in ans: ans.add(key) add_to_ans = True if not add_to_ans: return ans if __name__ == '__main__': # Write script here file = safe_open ("Enter a file storing a friendship graph", mode="r", error_message="That don't work homie", default="") fileGraph = read_graph (file) dupe = str (fileGraph) file.close () originalFileLen = len (fileGraph) graph_as_str (fileGraph) influencers = find_influencers (eval (dupe), prompt.for_bool ("Trace the Algorithm", default=True, error_message="That don't work either homie")) print("influencers: ", influencers) while True: redflag = False userPrompt = str(prompt.for_string("Enter influencers set (or else quit)", default=influencers, error_message="Homie stop")) if userPrompt == "quit": break try: if type (eval (userPrompt)) == type (set ()): for user_key in eval (userPrompt): if user_key not in fileGraph.keys (): print (" Entry Error: ", userPrompt, ";", sep="") print (" Please enter a legal String\n") redflag = True break else: print ("That is not a valid entry. Please enter a valid entry\n") continue if redflag: continue if str(userPrompt) != "quit": if type(userPrompt) == str: influenced = all_influenced(fileGraph, eval (userPrompt)) print (influenced) print ("All Influenced ", "(", (len (influenced)/originalFileLen)*100, "%) = ", influenced, "\n", sep="") else: break except: print ("That is not a valid entry. Please enter a valid entry\n") # For running batch self-tests print() import driver driver.default_file_name = "bsc1.txt" #driver.default_show_traceback = True #driver.default_show_exception = True #driver.default_show_exception_message = True driver.driver()
0fbcc976ffaa190532b3aadaffd562d1e5a73c87
pauldiaz10/Programming-Paradigm---Python-Prolog-Scheme-
/HW1/Diaz_paul_HW2_CS152/pluto1.py
4,504
4.34375
4
# ----------------------------------------------------------------------------- # Name: pluto1 # Purpose: Recursive Descent Parser Demo # # Author: Rula Khayrallah # # ----------------------------------------------------------------------------- """ Recursive descent parser to recognize & evaluate simple arithmetic expressions Supports the following grammar: <command> ::= <arith_expr> <arith_expr> ::= <term> {ADD_OP <term>} <term> ::= <factor> {MULT_OP <factor>} <factor>::= LPAREN <arith_expr> RPAREN | FLOAT | INT """ import lex from operator import add, sub, mul, truediv # For the homework, uncomment the import below # from operator import lt, gt, eq, ne, le, ge # List of token names - required tokens = ('FLOAT', 'INT', 'ADD_OP', 'MULT_OP', 'LPAREN', 'RPAREN') # global variables token = None lexer = None parse_error = False # Regular expression rules for simple tokens # r indicates a raw string in Python - less backslashes t_ADD_OP = r'\+|-' t_MULT_OP = r'\*|/' t_LPAREN = r'\(' t_RPAREN = r'\)' # Regular expression rules with some action code # The order matters def t_FLOAT(t): r'\d*\.\d+|\d+\.\d*' t.value = float(t.value) # string must be converted to float return t def t_INT(t): r'\d+' t.value = int(t.value) # string must be converted to int return t # For the homework, you will add a function for boolean tokens # A string containing ignored characters (spaces and tabs) t_ignore = ' \t' # Lexical error handling rule def t_error(t): global parse_error parse_error = True print("ILLEGAL CHARACTER: {}".format(t.value[0])) t.lexer.skip(1) # For homework 2, add the comparison operators to this dictionary SUPPORTED_OPERATORS = {'+': add, '-': sub, '*': mul, '/': truediv} def command(): """ <command> ::= <arith_expr> """ result = arith_expr() if not parse_error: # no parsing error if token: # if there are more tokens error('END OF COMMAND OR OPERATOR') else: print(result) def arith_expr(): """ <arith_expr> ::= <term> { ADD_OP <term>} """ result = term() while token and token.type == 'ADD_OP': operation = SUPPORTED_OPERATORS[token.value] match() # match the operator operand = term() # evaluate the operand if not parse_error: result = operation(result, operand) return result def term(): """ <term> ::= <factor> {MULT_OP <factor>} """ result = factor() while token and token.type == 'MULT_OP': operation = SUPPORTED_OPERATORS[token.value] match() # match the operator operand = factor() # evaluate the operand if not parse_error: result = operation(result, operand) return result def factor(): """ <factor>::= LPAREN <arith_expr> RPAREN | FLOAT | INT """ if token and token.type == 'LPAREN': match() result = arith_expr() if token and token.type == 'RPAREN': match() return result else: error(')') elif token and (token.type == 'FLOAT' or token.type == 'INT'): result = token.value match() return result else: error('NUMBER') def match(): """ Get the next token """ global token token = lexer.token() def error(expected): """ Print an error message when an unexpected token is encountered, sets a global parse_error variable. :param expected: (string) '(' or 'NUMBER' or or ')' or anything else... :return: None """ global parse_error if not parse_error: parse_error = True print('Parser error') print("Expected:", expected) if token: print('Got: ', token.value) print('line', token.lineno, 'position', token.lexpos) def main(): global token global lexer global parse_error # Build the lexer lexer = lex.lex() # Prompt for a command more_input = True while more_input: input_command = input("Pluto 1.0>>>") if input_command == 'q': more_input = False print('Bye for now') elif input_command: parse_error = False # Send the command to the lexer lexer.input(input_command) token = lexer.token() # Get the first token in a global variable command() if __name__ == '__main__': main()
ba59550e2cf374954a1dec6e4d8eba3c1bc49b33
Pumacens/Competitive-Programming-Solutions
/CodeWars-excercises/Python/7_kyu/files/993. nova polynomial 1. add.py
643
3.609375
4
# return the sum of the two polynomials p1 and p2. def poly_add(p1, p2): p1 = p1[::] p2 = p2[::] if len(p1) >= len(p2): for indx, value in enumerate(p2): p1[indx] += value return p1 else: for indx, value in enumerate(p1): p2[indx] += value return p2 # from itertools import izip_longest # def poly_add(p1, p2): # return [a+b for a, b in izip_longest(p1, p2, fillvalue=0)] # def poly_add(p1,p2): # if p1 == []: # return p2 # if p2 == []: # return p1 # return [p1[0] + p2[0]] + poly_add(p1[1:], p2[1:])
4486e69123039fd7dc6a727b4751d19c7c33f9f0
Carloslee96/Indoor-Localization
/Data_Processing/calculate_loc_final.py
2,709
3.65625
4
''' By Zhenghang(Klaus) Zhong With data structure of samples X time_steps X features, and the time steps are created by sliding Window, which means there are a lot of repeating data in input as well as output, the data sample is like (if with one feature): [1 2 3 4 5 6 2 3 4 5 6 7 3 4 5 6 7 8 4 5 6 7 8 9] The output is similar, to get a better location coordination, we get location info of one point based on the mean of all its estimated state, that is its final location. For above example, we have input of 9 points' info. ''' import csv import os import numpy as np import pandas as pd #Adjust according to parameter setting time_step = 30 def mean_of_line(dataset, item, all_steps): #the points number that is smaller than length of dataset if item < len(dataset): # 20 is decided by the time steps if item >= time_step: number = time_step else: number = item + 1 row = len(dataset) length = len(dataset[0]) total = 0 j = 0 for i in range(number): total += dataset[item][j].astype('float') item -= 1 j +=1 mean = total / number all_steps.append(mean) if(item == 0): print('0:',mean) #Last several points (whos number equal to (time_step -1)) else: row_start = len(dataset)-1 total = 0 j = item - len(dataset)+1 #print('lengh:',time_step - (item - len(dataset)+1)) for i in range(time_step - (item - len(dataset)+1)): total += dataset[row_start][j].astype('float') row_start -= 1 j += 1 mean = total / (time_step - (item - len(dataset)+1)) all_steps.append(mean) # read the raw output data with open('yhat_loc_x.csv', 'r', newline='') as csvfile: reader = csv.reader(csvfile) dataset_x = np.array([row[1:] for row in reader]) print(dataset_x) with open('yhat_loc_y.csv', 'r', newline='') as csvfile: reader = csv.reader(csvfile) dataset_y = np.array([row[1:] for row in reader]) #get the final estimated location of all points with x and y coordinates all_steps_x = [] for x in range(len(dataset_x)+(time_step-1)): mean_of_line(dataset_x,x,all_steps_x) all_steps_x = pd.DataFrame(all_steps_x) all_steps_x.to_csv('all_steps_x.csv', mode='w', header=['Loc_x']) all_steps_y = [] for y in range(len(dataset_y)+(time_step-1)): mean_of_line(dataset_y,y,all_steps_y) #print(all_steps_y) all_steps_y = pd.DataFrame(all_steps_y) all_steps_y.to_csv('all_steps_y.csv', mode='w', header=['Loc_y']) all_steps_x= pd.read_csv(filepath_or_buffer = 'all_steps_x.csv', sep = ',',usecols = [1]) all_steps_y= pd.read_csv(filepath_or_buffer = 'all_steps_y.csv', sep = ',',usecols = [1]) all_steps = pd.concat([all_steps_x,all_steps_y],axis = 1) all_steps.to_csv('all_steps.csv', mode='w', header=['Loc_x','Loc_y'])
fb715313873f0cbfb979c0e6b900e983842b400c
MegaLoler/Magic-CPU
/player.py
765
3.515625
4
from memory import RAM from context import ExecutionContext class Player: ''' this is mainly just a dummy player class to demonstrate players having their own ram ''' def __init__(self): self.ram = RAM(bytearray(2**10*4)) # 2kb of ram, of course it can be however much you like! def run_program(self, program_memory, arguments, cpu, game): ''' make this player run a program using some cpu ''' # create the context for execution # the program memory is the provided program data # and the player is this player! # and the game is provided context = ExecutionContext(program_memory, self, game) # and tell the cpu to run indefinitely! return cpu.run(context, arguments)
bd65bf7e38c46ad51d2293ca18b7e79fe9ddcaab
phucle2411/LeetCode
/Python/n-ary-tree-level-order-traversal.py
677
3.78125
4
# https://leetcode.com/problems/n-ary-tree-level-order-traversal/ """ # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children """ class Solution(object): def levelOrder(self, root): """ :type root: Node :rtype: List[List[int]] """ def traverse(root, level): if not root: return while len(ret) <= level: ret.append([]) ret[level].append(root.val) for child in root.children: traverse(child, level + 1) ret = [] traverse(root, 0) return ret
8e390ece94c3cbdbce3953ddd1a53877fa953eff
smartycope/Nifty-Python-Programs
/monitorKeyboard-boilderplate.py
1,318
3.65625
4
from pynput import keyboard, mouse #* Keys def on_press(key): try: print('{0} pressed'.format(key.char)) except AttributeError: print('{0} pressed (Special Key)'.format(key)) def on_release(key): print('{0} released'.format(key)) if key == keyboard.Key.esc: # Stop listener return False def on_move(x, y): print('Pointer moved to {0}'.format( (x, y))) #* Mouse def on_click(x, y, button, pressed): print('{0} at {1}'.format( 'Pressed' if pressed else 'Released', (x, y))) if not pressed: # Stop listener return False def on_scroll(x, y, dx, dy): print('Scrolled {0} at {1}'.format( 'down' if dy < 0 else 'up', (x, y))) # Collect events until released # with mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener: # listener.join() # ...or, in a non-blocking fashion: mouseListener = mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) # Collect events until released # with keyboard.Listener(on_press=on_press, on_release=on_release) as listener: # listener.join() # ...or, in a non-blocking fashion: keyboardListener = keyboard.Listener(on_press=on_press, on_release=on_release) keyboardListener.start() mouseListener.start() #
fc8cec9268866ca099c5e24da079a5ecf30b5af3
giselacontreras/CSC110
/chess.py
5,497
3.953125
4
### ### Author: Pearce Phanawong ### Description: This program runs a game of 1D chess. It involves ### each player having 2 knights that can move two ### spaces in either direction and a king that moves ### until it reaches another piece or an end of the ### board. The game is played on a 1x9 board takes ### user input for which piece to be moved and which ### direction to move it. ### from graphics import graphics W_KNIGHT = 'WKn' W_KING = 'WKi' B_KNIGHT = 'BKn' B_KING = 'BKi' EMPTY = ' ' WHITE = 'White' BLACK = 'Black' LEFT = 'l' RIGHT = 'r' def is_valid_move(board, position, player): ''' This function checks if the player's move will be a valid one based on whether it is the player's piece and if it's in the correct spot. ''' if position <= 8 and position >= 0: if player == WHITE: if board[position] == W_KNIGHT or board[position] == W_KING: return True return False else: if board[position] == B_KNIGHT or board[position] == B_KING: return True return False def move_knight(board, position, direction): ''' This function will move the knight piece two spaces in either direction and will replace whatever piece or spot it lands on. The space it was previously at will become an empty space. ''' if direction == LEFT: if position >= 2: board[position - 2] = board[position] board[position] = EMPTY if direction == RIGHT: if position <= 6: board[position + 2] = board[position] board[position] = EMPTY def move_king(board, position, direction): ''' This function will move the king piece in one direction until it either hits another piece or reaches the end of one side of the board. It will replace whatever piece or spot it lands on. The space it was previously at will become an empty space. ''' if direction == LEFT: i = 0 king = board[position] board[position] = EMPTY while i == 0: if position != 0: position -= 1 if board[position] != EMPTY: board[position] = king i += 1 else: i += 1 board[position] = king if direction == RIGHT: i = 0 king = board[position] board[position] = EMPTY while i == 0: if position != 8: position += 1 if board[position] != EMPTY: board[position] = king i += 1 else: i += 1 board[position] = king def print_board(board): ''' This function will print out a "board" with the location of all the pieces still in the game ''' print('+-----------------------------------------------------+') for i in range(len(board)): print('| ' + board[i] + ' ', end = '') print('|') print('+-----------------------------------------------------+') def draw_board(board, gui): ''' This function will create a graphical image of the board while the game is played. ''' def is_game_over(board): ''' This function checks if the white or black king is still on the board, and if it is not, will print whether the white player or black player won. ''' if W_KING in board and B_KING in board: return False elif B_KING in board and not W_KING in board: print_board(board) print('Black wins!') return True else: print_board(board) print('White wins!') return True def move(board, position, direction): ''' This function checks whether the piece is a king or knight and then will call the appropriate function to move the piece. ''' if board[position] == W_KNIGHT or board[position] == B_KNIGHT: move_knight(board, position, direction) else: move_king(board, position, direction) def main(): # Create the canvas #gui = graphics(700, 200, '1 Dimensional Chess') # This is the starting board. # This board variable can and should be passed to other functions # and changed as moves are made. board = [W_KING, W_KNIGHT, W_KNIGHT, EMPTY, EMPTY, EMPTY, B_KNIGHT, B_KNIGHT, B_KING] # White typically starts in chess. # This will change between WHITE and BLACK as the turns progress. player = WHITE # This variable will be updated to be True if the game is over. # The game is over after one of the kings dies. is_game_won = False # This loop controls the repetitive nature of the turns of the game. while not is_game_won: print_board(board) # Draw the board #draw_board(board, gui) position = int(input(player + ' enter index:\n')) direction = input(player + ' enter direction (l or r):\n') # If the desired move is valid, then call the move function. # Also, change the player variable. if is_valid_move(board, position, player): if player == WHITE: move(board, position, direction) player = BLACK else: move(board, position, direction) player = WHITE is_game_won = is_game_over(board) main()
7ba5eb84406b46981cb3c60a828d8ba412d3ba00
Rijutajain/Python_projects
/Dicegame.py
1,244
3.765625
4
def count_wins(dice1, dice2): assert len(dice1) == 6 and len(dice2) == 6 dice1_wins, dice2_wins = 0, 0 for i in dice1: for j in dice2: if i>j: dice1_wins +=1 elif j>i: dice2_wins +=1 return (dice1_wins, dice2_wins) def find_the_best_dice(dices): assert all(len(dice) == 6 for dice in dices) for candidate_dice in range(len(dices)): count=0 for other_dice in range(len(dices)): (x,y)=count_wins(dices[candidate_dice],dices[other_dice]) if x>y or other_dice==candidate_dice: count=count+1 if count==len(dices): return candidate_dice return -1 def compute_strategy(dices): assert all(len(dice) == 6 for dice in dices) strategy = dict() if find_the_best_dice(dices)!=-1: strategy["choose_first"]=True strategy["first_dice"]=find_the_best_dice(dices) else: strategy["choose_first"]=False for candidate_dice in range(len(dices)): for other_dice in range(len(dices)): (x,y)=count_wins(dices[candidate_dice],dices[other_dice]) if y>=x and candidate_dice!=other_dice: strategy[candidate_dice]=other_dice return strategy
fbbde862c025550cd630dc75bca596c2bfe87ae9
fgoingtob/python
/add.py
87
3.578125
4
x = input( "enter first:" ) y = input( "enter second:" ) z = int(x) + int(y) print z
f897846bfbe129918271bf380be32dddbd199b2e
florisdobber/project-euler
/problem-14.py
444
3.6875
4
def main(): max_length = 0 num = -1 for i in range(1, 1000000+1): c_length = collatz_length(i) if c_length > max_length: max_length = c_length num = i print(num) def collatz_length(n): length = 1 while True: if n % 2 == 0: n = n / 2 else: n = (3 * n) + 1 length += 1 if n == 1: break return length main()
4f6ac4a480ca8e166c17d6d86e48beecc3ca37e6
zision/Sort-Python
/insert_sort.py
1,450
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # File : insert_sort.py # Author: ZhouZijian # Date : 2018/9/21 """插入排序(Insertion-Sort)的算法描述是一种简单直观的排序算法。 它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。 1、从第一个元素开始,该元素可以认为已经被排序; 2、取出下一个元素,在已经排序的元素序列中从后向前扫描; 3、如果该元素(已排序)大于新元素,将该元素移到下一位置; 4、重复步骤3,直到找到已排序的元素小于或者等于新元素的位置; 5、将新元素插入到该位置后; 6、重复步骤2~5。 """ import rdlist # 插入排序算法实现1 def insert_sort1(arr): for i in range(1, len(arr)): key = arr[i] for j in range(i - 1, -1, -1): if arr[j] > key: arr[j + 1] = arr[j] arr[j] = key return arr # 插入排序算法实现2 def insert_sort2(arr): for i in range(1, len(arr)): for j in range(i - 1, -1, -1): if arr[j] > arr[i]: arr[j], arr[i] = arr[i], arr[j] i -= 1 j -= 1 return arr # 检测 if __name__ == "__main__": print("排序后列表:", insert_sort1(rdlist.rdlist(int(input("输入待检测列表长度:")))))
3e1cd0060093af582cff79167eb3c06a44245da4
rileykeane/FIT2085
/Lab 6/tour.py
8,663
4.25
4
import unsorted_list_ADT as list_ADT def initialise_tour(n): """ Create a tour data type of size n @param n: the size of the tour n*n @return the tour data type @post the tour will initially be empty and can be populated using other tour functions @complexity best and worst case: O(n^2) where n is in input n """ tour = list_ADT.List(n*n) return tour def print_tour(tour): """ This will print a chess board representation of the tour @param tour: the tour data type @post the printed board will have non visited positions as 0, visited at * and the current as K @complexity best and worst: O(n^2) where n is the length of the tour """ n = int(list_ADT.size(tour)**0.5) # creating a chess board of size n*n board = list_ADT.List(n) # populating the board with 0s for _ in range(n): row = list_ADT.List(n) for _ in range(n): list_ADT.add_last(row, '.') list_ADT.add_last(board, row) # setting previous positions in board to '*'s n = list_ADT.length(tour) for i in range(n): pos = list_ADT.get_item(tour, i) # getting row and column of position pos_r = list_ADT.get_item(pos, 0) - 1 pos_c = list_ADT.get_item(pos, 1) - 1 # setting previous positions to a * and current to a K in board row = list_ADT.get_item(board, pos_r) if i == n-1: list_ADT.set_item(row, pos_c, 'K') else: list_ADT.set_item(row, pos_c, '*') # printing the tour print('\nCurrent Tour') n = list_ADT.length(board) col_numbers = '' for i in range(n, 0, -1): col_numbers = ' ' + str(i) + col_numbers row = list_ADT.get_item(board, i - 1) row_str = str(i) + ' ' for j in range(list_ADT.length(row)): row_elt = list_ADT.get_item(row, j) row_str += str(row_elt) + ' ' print(row_str) print('\n ' + col_numbers) def new_position(tour, row, col): """ This adds a new position to the tour @param tour: a tour data_type @param row: the row of the position as an integer @param col: the column of the position as an integer @return True if the tour has space left, otherwise False @pre row and col must be integers @pre the tour must not be full @pre the position must be within the size of the tour @post the new position will be added to the end of the tour and will be treated as current position for all other tour functions @complexity best and worst case: O(1) """ # checking the tour is not full if list_ADT.is_full(tour): raise Exception("The tour is complete. No more moves can be made") # checking row and col and integers try: int(row) int(col) except ValueError: raise ValueError('row and/or col must be integer values') # checking row and col fit into the tour n = int(list_ADT.size(tour)**0.5) if not (1 <= row <= n or 1 <= col <= n): raise IndexError('Row and/or col does not fit within the size of the tour') pos = list_ADT.List(2) list_ADT.add_last(pos, row) list_ADT.add_last(pos, col) list_ADT.add_last(tour, pos) if list_ADT.is_full(tour): return False else: return True def next_moves(tour): """ returns all the possible next moves for the tour @param tour: a tour data data @return a list of all possible next moves @pre the tour must have made at least one move @post only moves that have not already been made will be returned @post only moves that are within the size of the tour will be returned @complexity best and worst case: O(n) where n is the length of the tour """ # checking the tour has at least one move n = list_ADT.length(tour) if n == 0: raise Exception('The tour must have made at least one move') # getting current current_pos = list_ADT.length(tour) - 1 current = list_ADT.get_item(tour, current_pos) # calculating all the next moves moves = list_ADT.List(8) move = list_ADT.List(2) list_ADT.add_last(move, list_ADT.get_item(current, 0) + 2) list_ADT.add_last(move, list_ADT.get_item(current, 1) + 1) list_ADT.add_last(moves, move) move = list_ADT.List(2) list_ADT.add_last(move, list_ADT.get_item(current, 0) + 2) list_ADT.add_last(move, list_ADT.get_item(current, 1) - 1) list_ADT.add_last(moves, move) move = list_ADT.List(2) list_ADT.add_last(move, list_ADT.get_item(current, 0) - 2) list_ADT.add_last(move, list_ADT.get_item(current, 1) + 1) list_ADT.add_last(moves, move) move = list_ADT.List(2) list_ADT.add_last(move, list_ADT.get_item(current, 0) - 2) list_ADT.add_last(move, list_ADT.get_item(current, 1) - 1) list_ADT.add_last(moves, move) move = list_ADT.List(2) list_ADT.add_last(move, list_ADT.get_item(current, 0) + 1) list_ADT.add_last(move, list_ADT.get_item(current, 1) - 2) list_ADT.add_last(moves, move) move = list_ADT.List(2) list_ADT.add_last(move, list_ADT.get_item(current, 0) + 1) list_ADT.add_last(move, list_ADT.get_item(current, 1) + 2) list_ADT.add_last(moves, move) move = list_ADT.List(2) list_ADT.add_last(move, list_ADT.get_item(current, 0) - 1) list_ADT.add_last(move, list_ADT.get_item(current, 1) - 2) list_ADT.add_last(moves, move) move = list_ADT.List(2) list_ADT.add_last(move, list_ADT.get_item(current, 0) - 1) list_ADT.add_last(move, list_ADT.get_item(current, 1) + 2) list_ADT.add_last(moves, move) # checking moves are valid n_tour = list_ADT.length(tour) valid_moves = list_ADT.List(8) for j in range(8): move = list_ADT.get_item(moves, j) move_r = list_ADT.get_item(move, 0) move_c = list_ADT.get_item(move, 1) tour_size = int(list_ADT.size(tour)**0.5) # comparing move to previous moves previous_move = False i = 0 while not previous_move and i < n_tour: pos = list_ADT.get_item(tour, i) if move == pos: previous_move = True i += 1 # checking if move has not already been made and if the move fits within the tour if 1 <= move_r <= tour_size and 1 <= move_c <= tour_size and not previous_move: list_ADT.add_last(valid_moves, move) return valid_moves def undo_move(tour): """ undo the last move on the tour @param tour: a tour data type @pre the tour must have made at least one move. @post the previous move will become the current move of the tour @return True if the move is successfully deleted @complexity best and worst case: O(1) """ n = list_ADT.length(tour) if n > 0: list_ADT.delete_last(tour) return True else: raise Exception('The tour must have made at least one move') def check_position(tour, r, c): """ checks that the imputed position is a valid move for a knight @param tour: a tour data type @param r: the row of the position to be tested @param c: the column of the position to be tested @pre the tour must have made at least one move @post r and c must be integers complexity best and worst case: O(1) """ # handling errors from next_moves try: possible_moves = next_moves(tour) except Exception: print('The tour must have made at least one move') # checking row and col and integers try: int(r) int(c) except ValueError: raise ValueError('row and/or col must be integer values') # creating a list ADT for new move new = list_ADT.List(2) list_ADT.add_last(new, r) list_ADT.add_last(new, c) for i in range(list_ADT.length(possible_moves)): move = list_ADT.get_item(possible_moves, i) if new == move: return True return False def next_moves_str(moves): """ Returns next moves as a string @param moves: the next moves for the tour generated with next_moves @return a string containing all the moves in the form r1,c1; r2,c2;... @complexity best and worst case: O(1) """ moves_str = "" for i in range(list_ADT.length(moves)): move = list_ADT.get_item(moves, i) moves_str += str(list_ADT.get_item(move, 0)) + ',' + str(list_ADT.get_item(move, 1)) + '; ' return moves_str
5ac16a2ff9fcf92e3930bd99acfbba29f1ae2689
9838dev/coding
/arrays/combination_sum_2.py
350
3.765625
4
# given an array and a target # find all unique combination in an array where array number sum to target # solution must not contain duplicate combination ''' Given input array = [10,1,2,7,6,1,5] target = 8 Output: [ [1,1,6], [1,2,5], [1,7], [2,6 ] ''' arr = [10,1,2,7,6,1,5] target = 8 ans=[] find_combination(0,arr,target,ans,[])
21cc4ffb58097696f78cffd1ede88f1f132c17fa
yveega/Task-Generator-2.0
/Subjects/Алгебра/Обыкновенные дроби/gen.py
8,552
3.671875
4
# Обыкновенные дроби import pygame import random import math from fractions import Fraction import os import sys path = "Subjects".join(os.getcwd().split("Subjects")) sys.path.insert(0, path) # изменяем текущую директорию для импорта модулей from Interface import * # Импортируем: окно с параметрами, from Convert import convert # конвертер в LaTeX from Export import export # и окно экспорта drawer = Drawer("radi(Тип задания, 01, Сложение, Вычитание, Умножение, Деление, Преобразовать, Сложение/Вычитание, Умножение/Деление, Микс); numb(кол-во чисел, 02, 2); numb(кол-во заданий, 03, 1)") fracs = [] signs = [] sign = [" + ", " - ", " : ", " * "] def clear_all(): signs.clear() fracs.clear() def make_fraction(count): denominator = random.randint(2, 1 + max(3, 20 // max(1, (count-1)))) # знаменатель numerator = random.randint(1, denominator*3) # числитель if count == 1: denominator = random.randint(2, 20) # знаменатель numerator = random.randint(denominator, 99) if numerator % denominator == 0: numerator += 1 fr = Fraction(numerator, denominator) fracs.append(fr) def replacement(count): sum = 0 for i in range(1, count): sum += fracs[i] fracs[0] += max(0, math.ceil(sum - fracs[0])) def solve(count): elems = [] esigns = [] ress = fracs[0] for i in range(1, count): if signs[i-1] == " + " or signs[i-1] == " - ": elems.append(ress) esigns.append(signs[i-1]) ress = fracs[i] elif signs[i-1] == " : ": ress = ress / fracs[i] elif signs[i-1] == " * ": ress = ress * fracs[i] elems.append(ress) if len(elems) > 0: ress = elems[0] for i in range(1, len(elems)): if esigns[i - 1] == " + ": ress += elems[i] if esigns[i - 1] == " - ": ress -= elems[i] #print(elems) return ress def plus(count): task = "" for i in range(count): make_fraction(count) ans = Fraction(0, 1) for i in range(count): ints = math.floor(fracs[i]) if ints != 0: task += str(ints) + " " task += str(fracs[i] - ints) if i < count - 1: task += " + " signs.append(" + ") ans = solve(count) ans_txt = "" ints = math.floor(ans) if ints != 0: ans_txt += str(ints) + " " ans_txt += str(ans - ints) clear_all() return task, ans_txt def minus(count): task = "" for i in range(count): make_fraction(count) fracs.sort(reverse=True) replacement(count) for i in range(count): ints = math.floor(fracs[i]) if ints != 0: task += str(ints) + " " task += str(fracs[i] - ints) if i < count - 1: task += " - " signs.append(" - ") ans = solve(count) ans_txt = "" ints = math.floor(ans) if ints != 0: ans_txt += str(ints) + " " ans_txt += str(ans - ints) clear_all() return task, ans_txt def multiply(count): task = "" for i in range(count): make_fraction(count) for i in range(count): ints = math.floor(fracs[i]) if ints != 0: task += str(ints) + " " task += str(fracs[i] - ints) if i < count - 1: task += " * " signs.append(" * ") ans = solve(count) ans_txt = "" ints = math.floor(ans) if ints != 0: ans_txt += str(ints) + " " ans_txt += str(ans - ints) clear_all() return task, ans_txt def division(count): task = "" for i in range(count): make_fraction(count) for i in range(count): ints = math.floor(fracs[i]) if ints != 0: task += str(ints) + " " task += str(fracs[i] - ints) if i < count - 1: task += " : " signs.append(" : ") ans = solve(count) ans_txt = "" ints = math.floor(ans) if ints != 0: ans_txt += str(ints) + " " ans_txt += str(ans - ints) clear_all() return task, ans_txt def converts(count): task = "" make_fraction(count) task += str(fracs[0]) ans = fracs[0] ans_txt = "" ints = math.floor(ans) if ints != 0: ans_txt += str(ints) + " " ans_txt += str(ans - ints) clear_all() return task, ans_txt def mixed(count, fir, sec): task = "" for i in range(count): # генерируем дроби make_fraction(count) for i in range(count-1): # генерируем знаки signs.append(sign[random.randint(fir, sec)]) if " - " in signs: if " + " in signs: el = min(signs.index(" + "), signs.index(" - ")) else: el = signs.index(" - ") first = solve(el+1) #print(first) second = solve(count) - first if first + second < 0: mid = max(abs(second) // first + 1, abs(first) // second + 1) fracs[0] = fracs[0] * mid if fracs[0].numerator % fracs[0].denominator == 0: fracs[0] += Fraction(1, fracs[0].denominator + 1) ans = solve(count) for i in range(count): ints = math.floor(fracs[i]) if ints != 0: task += str(ints) + " " task += str(fracs[i] - ints) if i < count - 1: task += signs[i] #print(ans) ans_txt = "" ints = math.floor(ans) if ints != 0: ans_txt += str(ints) + " " ans_txt += str(ans - ints) clear_all() return task, ans_txt def generate(operation, count=2): """ Функция генерирует квадратные уравнение Входных параметров нет Вывод: 2 строки - уравнение и ответв формате упрощённой формулы Баги: неправильный формат вывода при нулевом корне """ count = int(count) #print(count) if operation == "Сложение": task, ans_txt = plus(count) if operation == "Вычитание": task, ans_txt = minus(count) if operation == "Умножение": task, ans_txt = multiply(count) if operation == "Деление": task, ans_txt = division(count) if operation == "Преобразовать": task, ans_txt = converts(1) if operation == "Сложение/Вычитание": task, ans_txt = mixed(count, 0, 1) if operation == "Умножение/Деление": task, ans_txt = mixed(count, 2, 3) if operation == "Микс": task, ans_txt = mixed(count, 0, 3) return task, ans_txt # eq, ans = generate() # print("Уравнение:", eq) # print("Ответ:", ans) kg = True # Условие основного цикла программы while kg: # ОЦП (Основной Цикл Программы) res = drawer.tick() # Обновление интерфейса и приём команд пользователя. Для пересоздания интерфейса используется функция reset("новый_ввод") # Обработка вывода интерфейса if res == 'stop': kg = False elif res is not None: print(res) #print("io", res.split(" : ")[2], "io") count = res.split("02 : ")[1].split(", 03 ")[0] operation = res.split("01 : ")[1].split(", 02 ")[0] ktasks = int(res.split("03 : ")[1]) tasks = "" for t in range(ktasks): task, answer = generate(operation, count) if '/' not in answer and " " in answer: answer = answer.split(" ")[0] tasks += "Task: " + task + "\n" tasks += "Answer: " + answer + "\n" #print("task: " + tasks) #print("answer: " + answer) # print(tasks) conv = convert(tasks) export(conv) # & Тут можно складывать, вычитать, умножать, делить и преобразовывать дроби # & А также можно задавать количество чисел, кроме преобразования # Выход из программы pygame.quit()
284a9fa90d88820e161ac7629d3d00391ff4e7f9
henrylin2008/Coding_Problems
/DailyCoding/longest_increasing_subsequence.py
2,400
4.125
4
# Daily Coding Problem #75 # Problem # This problem was asked by Microsoft. # # Given an array of numbers, find the length of the longest increasing subsequence in the array. The subsequence does not necessarily have to be contiguous. # # For example, given the array [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15], the longest increasing subsequence has length 6: it is 0, 2, 6, 9, 11, 15. # # Solution # This naive, brute force way to solve this is to generate each possible subsequence, testing each one for monotonicity and keeping track of the longest one. That would be prohibitively expensive: generating each subsequence already takes O(2^N)! # # Instead, let's try to tackle this problem using recursion and then optimize it with dynamic programming. # # Assume that we already have a function that gives us the length of the longest increasing subsequence. Then we'll try to feed some part of our input array back to it and try to extend the result. Our base cases are: the empty list, returning 0, and an array with one element, returning 1. # # Then, # # For every index i up until the second to last element, calculate longest_increasing_subsequence up to there. # We can only extend the result with the last element if our last element is greater than arr[i] (since otherwise, it's not increasing). # Keep track of the largest result. def longest_increasing_subsequence(arr): if not arr: return 0 if len(arr) == 1: return 1 max_ending_here = 0 for i in range(len(arr)): ending_at_i = longest_increasing_subsequence(arr[:i]) if arr[-1] > arr[i - 1] and ending_at_i + 1 > max_ending_here: max_ending_here = ending_at_i + 1 return max_ending_here # This is really slow due to repeated subcomputations (exponential in time). So, let's use dynamic programming to store values to recompute them for later. # # We'll keep an array A of length N, and A[i] will contain the length of the longest increasing subsequence ending at i. We can then use the same recurrence but look it up in the array instead: def longest_increasing_subsequence(arr): if not arr: return 0 cache = [1] * len(arr) for i in range(1, len(arr)): for j in range(i): if arr[i] > arr[j]: cache[i] = max(cache[i], cache[j] + 1) return max(cache) # This now runs in O(N^2) time and O(N) space.
dd8887dd012bf6e29f878ef9542e7f762c2ba200
eYSIP-2016/eYSIP-Raspberry_Pi_Development_Board
/Code/Motor control using PWM/PWM to DC motor through PCA9685 IC/DC_motor_PCA9685.py
2,104
3.6875
4
import Adafruit_PCA9685 import smbus import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) # to use Raspberry Pi board pin numbers GPIO.setup(11,GPIO.OUT) # to set board pin 11 as output GPIO.setup(13,GPIO.OUT) # to set board pin 13 as output GPIO.setwarnings(False) pwm = Adafruit_PCA9685.PCA9685() pwm.set_pwm_freq(60) # set the frequency of pwm to 60Hz # Function name :forward # Input : None # Logic : give pin 11 logic 1 connected to IN1 of L293D # and give pin 13 logic 0 connected to IN2 of L293D # to rotate the motor in clockwise direction. # Output : Motor moves in clockwise direction i.e.,forward # Example call: forward() def forward(): # for clockwise motion of motor GPIO.output(11,True) GPIO.output(13,False) return # Function name :backward # Input : None # Logic : give pin 11 logic 0 connected to IN1 of L293D # and give pin 13 logic 1 connected to IN2 of L293D # to rotate the motor in anticlockwise direction. # Output : Motor moves in anticlockwise direction i.e.,backward # Example call: backward() def backward(): #for anticlockwise motion of motor GPIO.output(11,False) GPIO.output(13,True) return try: while True: forward() for value in range (0,4095,409): pwm.set_pwm(0, 0, value) #motor rotates in forward direction time.sleep(2) #with increasing speed for value in range (0,4095,409): pwm.set_pwm(0, 0 ,4095-value)#motor rotates in backward direction time.sleep(2) # with decreasing speed backward() for value in range (0,4095,409): pwm.set_pwm(0,0,value) #motor rotates in backward direction time.sleep(2) #with increasing speed for value in range (0,4095,409): pwm.set_pwm(0,0,4095-value) #motor rotates in backward direction time.sleep(2) # with decreasing speed except KeyboardInterrupt: pass GPIO.cleanup() # clears GPIO pins which stalls the motor
11d80013e2373647d5238b85dfa8ac61181e0cd0
micaelatapia/python01
/Punto1Modulo2Ejercicio06.py
235
4.0625
4
nro = int(input("Ingresar numero: ")) raiz = nro ** (1 / 2) if nro > 0: print("La raiz del numero es: ", raiz) if nro < 0: print("El numero elevado es: ", nro ** 2) if nro == 0: print("Error. Ha ingresado un valor nulo")
172c379e2c62bad7adcfc94a0d5a2d0ff70dcd62
Fondamenti18/fondamenti-di-programmazione
/students/1804395/homework01/program02.py
1,181
3.546875
4
def conv(n): if n == 0: return '' elif n<=19: return('uno','due','tre','quattro','cinque','sei','sette','otto','nove', 'dieci','undici','dodici','tredici','quattordici','quindici','sedici', 'diciassette','diciotto','diciannove')[n-1] elif n<= 99: decina=('venti','trenta','quaranta','cinquanta','sessanta','settanta', 'ottanta','novanta')[int(n/10)-2] if n%10==1 or n%10==8 : decina= decina[:-1] return decina+conv(n%10) elif n<= 199 : return 'cento'+ conv(n%100) elif n<=999: l='cento' if int((n%100)/10)==8: l=l[:-1] return conv(int(n/100))+l+conv(n%100) elif n<=1999: return 'mille'+conv(n%1000) elif n<=999999: return conv(int(n/1000)) + 'mila' + conv(n%1000) elif n<= 1999999: return 'unmilione' + conv(n%1000000) elif n<= 999999999: return conv(int(n/1000000)) + 'milioni' + conv(n%1000000) elif n<= 1999999999: return 'unmiliardo' + conv(n%1000000000) else: return conv(int(n/1000000000)) + 'miliardi' + conv(n%1000000000)
d9b3c3730dd3382ec34b3d77fc5265430f1c68df
meganesu/twitter-members-from-list
/scrapeTwitterListMembers.py
2,016
3.640625
4
''' Uses the Tweepy library (http://www.tweepy.org/) to pull the name, screenname, and bio/url for all users in a list. Make sure you've installed Tweepy: $ pip install tweepy You will can generate a consumer key/secret and access token/secret by creating a Twitter app (https://apps.twitter.com/). ''' ''' API.list_members(owner, slug, cursor) Returns the members of the specified list. Parameters: owner – the screen name of the owner of the list slug – the slug name or numerical ID of the list cursor – Breaks the results into pages. Provide a value of -1 to begin paging. Provide values as returned to in the response body’s next_cursor and previous_cursor attributes to page back and forth in the list. Return type: list of User objects ''' import tweepy consumer_key = input("Enter consumer key: ") consumer_secret = input("Enter consumer secret: ") access_token = input("Enter access token: ") access_token_secret = input("Enter access token secret: ") owner = input("Enter screen name of the owner of the list: ") slug = input("Enter slug name or numerical ID of the list: ") filename = slug + '_members.csv' f = open(filename, 'w') auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) list_members = tweepy.Cursor(api.list_members, owner, slug, -1).items() for user in list_members: name = user.name screen_name = user.screen_name description = user.description url = user.url str = '' if name is not None: str = str + name + ',' else: str = str + ',' if screen_name is not None: str = str + screen_name + ',' else: str = str + ',' if description is not None: str = str + description + ',' else: str = str + ',' if url is not None: str = str + url + '\n' else: str = str + '\n' f.write(str) f.close() print("All done! Contents written to " + filename + ".")
d9fbc97f8f0aed336d81bf35395265cbd3dfea76
enigmavadali/Python-Basics
/TupleandSets.py
257
3.921875
4
# tuple t1 = (1,2,3,"hello","python") del t1 print(t1[0]) print(t1[2:4]) # has same list operations like min(), max(), len() etc #sets # removes duplicates a={1,2,3,4,5} l1 = ['python','c','Java','ruby','c++'] l1.append('c') print(l1) set(l1) sorted(l1)