blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
000bc463304a917b9db234a0a1d18ef4b5521c2e
mytram/learning-python
/projecteuler.net/problem_043.py
1,381
3.71875
4
# Sub-string divisibility # Problem 43 # The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. # Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: # d2d3d4=406 is divisible by 2 # d3d4d5=063 is divisible by 3 # d4d5d6=635 is divisible by 5 # d5d6d7=357 is divisible by 7 # d6d7d8=572 is divisible by 11 # d7d8d9=728 is divisible by 13 # d8d9d10=289 is divisible by 17 # Find the sum of all 0 to 9 pandigital numbers with this property. import itertools def gen_pandigital(): it = itertools.permutations(range(10)) while True: number = list(next(it)) if number[0] != 0: yield number # this turns out to be faster than functools.reduce def list_to_number(ds): number = 0 for d in ds: number = number * 10 + d return number def sub_string_divisible(digits, primes): for i in range(1, 8): sub_number = list_to_number(digits[i:i+3]) if sub_number % primes[i - 1] != 0: return False return True def solve(): primes = [2, 3, 5, 7, 11, 13, 17] return sum(list_to_number(pd) for pd in gen_pandigital() if sub_string_divisible(pd, primes)) if __name__ == '__main__': print(__file__ + ':', solve())
bcd5a99ff08a480f5738b908e4243816f73ece00
matheuslins/helltriangle
/utils.py
89
3.53125
4
def raw_input_triangle_size(): return input("""What the size of triangle? -->> """)
1968158f65e007b047094afb5b828520a6772726
him-mah10/Mario
/person.py
545
3.640625
4
class People: position=1 shape='' '''def __init__(self): self.position=1 #self.shape''' class Person(People): def __init__(self): #By default the mario is on the ground self.shape='m' #m=>Short Person and M=>Large Person self.position=1 self.height=0 player=Person() class Enemy: def __init__(self,start=68,end=0,osc=False): self.startPosition=start self.endPosition=end self.position=start self.oscillate=osc self.currDirection="RL"
ba656eb2151452f50d155b8ebb4827aa2f16d388
hcxgit/SwordOffer
/Leetcode/406.根据身高重建队列.py
828
3.53125
4
# # @lc app=leetcode.cn id=406 lang=python3 # # [406] 根据身高重建队列 # class Solution: def reconstructQueue(self, people): # 先对原数组按 h 降序、k 升序排序。然后遍历数组,根据元素的 k 值进行「插队操作」:直接把元素插入数组下标为 k 的位置。 # k 值表示排在这个人前面且身高大于或等于 h 的人数,按 h 降序排序可以方便确定身高更高者的人数 # 按 k 降序排序则先处理排在更前面的数,避免更多的元素交换操作 people = sorted(people, key=lambda x: (-x[0], x[1])) result = [] print(people) for each in people: result.insert(each[1], each) return result s = Solution().reconstructQueue([[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]])
04ef69161a22c31b9b2ce49abfabae3df7474134
prernagulati0/Hangman-Game
/hangman.py
4,401
3.6875
4
#main function def hangman(): global picked,right,n,entryy,wrong,x,temp,chances guess = inp.get() entry.delete(0,END) if(n>=1): if guess in picked: for i in range(len(picked)): while picked[i]==guess : right.pop(i) right.insert(i,guess) x=''.join(right) word.configure(text=x) if x==temp: result.configure(text='you won, congratulation!!') reset=messagebox.askyesno("Notification",' want to play again?') if reset==True: chooseword() photo3 = ImageTk.PhotoImage(Image.open("/Users/dell/Downloads/5.png")) label.configure(image = photo3) label.place(x=590,y=150) label.update(photo3) else: root.destroy() else: break else: n -= 1 guesses.configure(text='No. of guesses = {}'.format(n)) chng() while n==1: guesses.configure(text='No. of guesses = 0') result.configure(text='You lose the game!!') z.configure(text='I picked: {}'.format(picked)) photo3 = ImageTk.PhotoImage(Image.open("/Users/dell/Downloads/0.png")) label.configure(image = photo3) label.place(x=590,y=150) label.update(photo3) def jj(event): hangman() def b(): chooseword() photo3 = ImageTk.PhotoImage(Image.open("/Users/dell/Downloads/5.png")) label.configure(image = photo3) label.place(x=590,y=150) label.update(photo3) #import modules from tkinter import * from tkinter import messagebox from PIL import Image, ImageTk import random root = Tk() root.geometry('1200x670+90+15') root.configure(bg='#f0f0f0',padx=100) root.title('Hangman Game') words = ['titanic','cindrella','goodfellas','vertigo','alien','batman','joker','halloween','superman','aladin', 'bambi','shrek','inception','predator','matilda','memento','cocktail','parasite','fanaa','kahani','hungama', 'zero','deadpool','dangal','mowgli','baaghi','war','barfi','pk','raees','fashion','sanju,super30'] #labels f= Label(root,text='Guess the movie-',font=('oswal',17,'bold'),bg='#f0f0f0') f.place(x=120,y=200) intro = Label(root,text='Welcome to HAngman game',font=('oswal',20,'bold'),bg='#f0f0f0') intro.place(x=260,y=40) word = Label(root,text='- - - -',font=('oswal',20,'bold'),bg='#f0f0f0') word.place(x=220,y=270) guesses = Label(root,text='No. of guesses:',font=('oswal',12,'bold'),bg='#f0f0f0') guesses.place(x=160,y=340) enter=Label(root, text="Enter your guess :",bg='#f0f0f0',font=('oswal',14,'bold')) enter.place(x=82,y=393) result = Label(root,text='You won!!',font=('oswal',15,'bold'),bg='#f0f0f0') result.place(x=345,y=520) z= Label(root,text='',font=('oswal',12,'bold'),bg='#f0f0f0') z.place(x=365,y=550) #entry box inp = StringVar() entry = Entry(root,font=('oswal',25,'bold'),relief=RIDGE,bd=3,textvariable=inp, width=3) entry.focus_set() entry.place(x=180,y=450) #buttons bt1 = Button(root,text='Enter',font=('oswal',15,'bold'),width=7,bd=4,bg='black',relief=RIDGE ,fg='white',command=hangman) bt1.place(x=260,y=450) root.bind("<Return>",jj) bt2 = Button(root,text='Exit',font=('oswal',15,'bold'),width=7,bd=5,bg='black',relief=RIDGE ,fg='white',command=root.destroy) bt2.place(x=460,y=595) bt3 = Button(root,text='restart',font=('oswal',15,'bold'),width=7,bd=5,bg='black',relief=RIDGE ,fg='white',command=b) bt3.place(x=310,y=595) #photo image=Image.open("/Users/dell/Downloads/5.png") photo= ImageTk.PhotoImage(image) label=Label(image=photo) label.place(x=590,y=150) def chooseword(): global picked,right,n,temp picked= random.choice(words) right = ['-' for i in picked] n=5 guesses.configure(text='No. of guesses = {}'.format(n)) temp= picked word.configure(text=right) result.configure(text='') chooseword() def chng(): imagepaths=[0.png, 1.png, 2.png, 3.png, 4.png, 5.png] photo2 = ImageTk.PhotoImage(Image.open(imagepaths[n])) label.config(image = photo2) label.update(photo2) root.mainloop()
d846d690a30999d17f6e84c98dfb766439a6ba3c
Aleti-Prabhas/python-practice
/minion_game.py
714
3.515625
4
input_string=input() kevin=0 stuart=0 vowels=['a','e','i','o','u'] def sub_string(string): sub_string_set=[] for i in range(0,len(string)): for j in range(i,len(string)): sub=string[i:j] sub_string_set.append(sub) print(sub_string_set) return sub_string_set sub=sub_string(input_string) for i in range(0,len(sub)): if(str(str[i])!=""): if(str(sub[i]).startswith('a') or str(sub[i]).startswith('e') or str(sub[i]).startswith('i') or str(sub[i]).startswith('o') or str(sub[i]).startswith('u')): kevin=kevin+1 else: stuart=stuart+1 if kevin>stuart: print("kevin",kevin) else: print("stuart",stuart)
df49582c33967cf24ed986057a017f3da3257664
VinayakBagaria/Python-Programming
/New folder/t_server.py
687
3.96875
4
import socket """ socket.socket() creates a socket object """ s=socket.socket() host=socket.gethostname() print(host) port=12345 """ s.bind() - this method binds the address (hostname,port) to socket for knowing where to connect """ s.bind((host,port)) """ s.listen() sets up and starts TCP-IP listener """ s.listen() while True: """ this method passively accepts TCP-IP client connection, waiting until the connection arrives """ c,addr=s.accept() print('Got Connection from ',addr) c.send(b'Connected') print(c.recv(1024)) while True: c.send(str.encode(input())) print(c.recv(1024)) c.close()
3f106eb715c560fe890f061ed72809fe5f3fbabe
2tom/python_study
/shinyawy/04_hello.py
547
3.65625
4
# coding: UTF-8 # No.1 Python Study 2015/06/11 # 数値 # 整数、少数、複素数 # 演算子 + - * / // % ** # 50 print 10*5 # 3 print 10 // 3 # 1 print 10 % 3 # 8 print 2 ** 3 # 整数と小数の演算 → 小数 # 7.0 print 5 + 2.0 # 整数同士の割り算 → 切り捨ての整数 # 3 print 10 / 3 # 3.333333... print 10 / 3.0 # -4 OS依存で結果が変わる print -10 / 3 # -3.33333... print -10 / 3.0 # 1 print 10 / 7 # 1.428... print 10 / 7.0 # -2 OS依存で結果が変わる print -10 / 7 # -1.428 print -10 / 7.0
536c35801b5318ff79e8f6463fd7aa171ac5e98a
pk2609/Hazard_01
/displaying_graphs.py
2,036
3.515625
4
# -*- coding: utf-8 -*- """ In this module we will be displaying stats about which source is giving more fake news and in what proportion. """ from matplotlib import pyplot as plt a=87 b=90 c=67 d=75 e=91 f=69 g=83 h=71 i=77 labels=["IGN","Independent","Buzzfeed","CNBC","The Washington Post","GoogleNews","Techradar","ESPN","MTV"] #labels1=["Gaming","Education","Entertainment","Economy","World","Top News","Technology","Sports","Music"] data_source=[a,b,c,d,e,f,g,h,i] colors=['gold','red','blue','green','lightcoral','orange','yellowgreen','pink','brown'] plt.pie(data_source,labels=labels,colors=colors,autopct='%1.1f%%') plt.title("Sources with Reality Check") plt.axis('equal') #plt.pie(data_source1) plt.show() me="ESPN" if me=="IGN": ign=[a,100-a] plt.pie(ign,labels=["Truth","Fake"],autopct='%1.1f%%') plt.title("IGN") plt.show() elif me=="Independent": indepe=[b,100-b] plt.pie(ign,labels=["Truth","Fake"],autopct='%1.1f%%') plt.title("IGN") plt.show() elif me=="Buzzfeed": bf=[c,100-c] plt.pie(bf,labels=["Truth","Fake"],autopct='%1.1f%%') plt.title("Buzzfeed") plt.show() elif me=="CNBC": cnbc=[d,100-d] plt.pie(cnbc,labels=["Truth","Fake"],autopct='%1.1f%%') plt.title("CNBC") plt.show() elif me=="The Washington Post": twp=[e,100-e] plt.pie(twp,labels=["Truth","Fake"],autopct='%1.1f%%') plt.title("The Washington Post") plt.show() elif me=="GoogleNews": gn=[f,100-f] plt.pie(gn,labels=["Truth","Fake"],autopct='%1.1f%%') plt.title("GoogleNews") plt.show() elif me=="Techradar": tr=[g,100-g] plt.pie(tr,labels=["Truth","Fake"],autopct='%1.1f%%') plt.title("Techradar") plt.show() elif me=="ESPN": espn=[h,100-h] plt.pie(espn,labels=["Truth","Fake"],autopct='%1.1f%%') plt.title("ESPN") plt.show() elif me=="MTV": mtv=[i,100-i] plt.pie(mtv,labels=["Truth","Fake"],autopct='%1.1f%%') plt.title("MTV") plt.show()
5fa92113888104be877e04c6103f8fa7ab034823
EugeneZaharchenko/SoftServe
/elementary_tasks/task8fold/task8.py
2,685
4.25
4
""" Elementary Task 8 Fibonacci sequence for a certain range ---------------- The program outputs all Fibonacci numbers, which are in given range. The range is given with 2 arguments during the main class call. Fibonacci numbers are comma separated in output and sorted by asc. """ import sys from functools import lru_cache class Fibonacci: def __init__(self, start, stop): self.start, self.stop = self.validate(start, stop) @staticmethod def validate(start, stop): if stop > 0 and (stop < start): raise ValueError if stop < 0 and (stop > start): raise ValueError return start, stop @staticmethod # lru_cache used to cash previously calculated values @lru_cache(maxsize=128) def gen_fib(): """ Fibonacci sequence generator :return: Fibonacci sequence -> iterator """ a, b = 0, 1 yield a yield b while True: a, b = b, a + b yield b @staticmethod @lru_cache(maxsize=128) def gen_fib_neg(): """ Fibonacci sequence generator for negative numbers :return: Fibonacci sequence -> iterator """ a, b = 0, 1 yield a yield b while True: a, b = b, a - b yield b def fib_list(self): """ Func to form Fibonacci list :return: list of Fibonacci numbers -> list """ if self.stop < 0: g = self.gen_fib_neg() return [next(g) for _ in range(self.start, self.stop, -1)] g = self.gen_fib() return [next(g) for _ in range(self.stop)] def main(): if len(sys.argv) == 1: print(__doc__) try: # receive user's data start, stop = int(sys.argv[1]), int(sys.argv[2]) # creating instance of Fibonacci class in certain range which is given as arguments fib = Fibonacci(start, stop) except ValueError: print("Wrong arguments. Give start and stop values where stop is bigger (start < stop)") except IndexError: print("Wrong arguments. Must be 2 parameters: start, stop (start < stop)") else: fib_seq = fib.fib_list() if stop < 0: fib_str = ", ".join([str(s) for s in fib_seq if stop <= s <= start]) else: fib_str = ", ".join([str(s) for s in fib_seq if start <= s <= stop]) print("Fibonacci sequence for a given range {start} - {stop} is: {seq}".format(start=start, stop=stop, seq=fib_str)) if __name__ == "__main__": main()
51b6d4cda3beaa2592faacbd8becdfe36cedb6d0
Veridi/EE104Project3
/Hospital ER.py
5,430
3.703125
4
# -*- coding: utf-8 -*- """ Created on Thu Nov 12 10:28:48 2020 @author: Paul Payumo (011344905) and Mike Lin (011001445) """ from random import randint class Global: operatingRooms = 4 beds = 400 nurses = 200 doctors = 50 medicalEquipment = 100 medication = 200 patients = [] time = 5 waiting = 0 class Patient: def __init__(self, time): self.time = time self.waitingTime = 0 self.operatingRoom = False self.specialEquipment = False self.medication = False def checkCapacity(patient): if(Global.medication == 0): if(patient.medication == True): patient.waitingTime = minimumTime() + 2 if(Global.operatingRooms == 0): if(patient.operatingRoom == True): if(24 - Global.time > patient.waitingTime): patient.waitingTime = 24 - Global.time if(Global.medicalEquipment == 0): if(patient.specialEquipment == True): if(patient.waitingTime < minimumEquipmentTime()): patient.waitingTime = minimumEquipmentTime() if(Global.nurses == 0 or Global.beds == 0 or Global.doctors < (1/8)): if(patient.waitingTime < minimumTime()): patient.waitingTime = minimumTime() return patient.waitingTime def minimumTime(): minTime = 9 for i in range(len(Global.patients)): if(Global.patients[i].time < minTime): minTime = Global.patients[i].time return minTime def minimumEquipmentTime(): minTime = 9 equipment = [] for i in range(len(Global.patients)): if(Global.patients[i].specialEquipment == True): equipment.append(Global.patients[i]) for i in range(len(equipment)): if(equipment[i].time < minTime): minTime = equipment[i].time return minTime def addPatient(): p = Patient(randint(1,8)) if(input("Does the patient need surgery? 'Yes' or 'No' ") == "Yes"): p.operatingRoom = True if(input("Does the patient need special equipment? 'Yes' or 'No' " ) == "Yes"): p.specialEquipment = True if(input("Does the patient need medication? 'Yes' or 'No' ") == "Yes"): p.medication = True waitingTime = checkCapacity(p) if(waitingTime == 0): Global.beds += -1 Global.nurses += -0.25 Global.doctors += -1/8 if(p.operatingRoom == True): Global.operatingRooms += -1 if(p.specialEquipment == True): Global.medicalEquipment += -1 if(p.medication == True): Global.medication += -1 Global.patients.append(p) print("\nYou will be admitted now for", p.time, "hours.") else: if(p.operatingRoom == False and p.specialEquipment == False and p.medication == True and Global.medication == 0 and Global.beds > 0 and Global.nurses > 0 and Global.doctors > 0): print("\nYou will be admitted now for", p.time, "plus 2 additional hours due to lack of medication.") p.time += 2 Global.patients.append(p) Global.beds += -1 Global.nurses += -0.25 Global.doctors += -1/8 else: if(p.medication == True): waitingTime += -2 print("\n\nWaiting time is", waitingTime, "hours.\n") def wait(): newPatients = [] Global.time += 1 if(Global.time == 24): Global.time = 0 Global.operatingRooms = 4 Global.medication = 2 print("It is {}:00 in military time.".format(Global.time)) if(len(Global.patients) >= 1): for i in range(len(Global.patients)): Global.patients[i].time += -1 if(Global.patients[i].time == 0): Global.beds += 1 Global.nurses += 0.25 Global.doctors += 1/8 if(Global.patients[i].specialEquipment == True): Global.medicalEquipment += 1 for i in range(len(Global.patients)): if(not Global.patients[i].time == 0): newPatients.append(Global.patients[i]) Global.patients = newPatients def main(): print("It is {}:00 in military time.".format(Global.time)) while(1): action = int(input("\nWhat would you like to do?\n'1' for admit a patient\n'2' for wait one hour.\n'3' to check availability.\n'4' to see when the next patient is leaving.\n\n")) if(action == 1): addPatient() elif(action == 2): wait() elif(action == 3): print("\nNumber of operating rooms available: ", Global.operatingRooms) print("Number of beds available: ", Global.beds) print("Nurses can see", Global.nurses * 4, "patients") print("Doctors can see", Global.doctors * 8, "patients") print("Number of equipment available: ", Global.medicalEquipment) print("Number of medication available: ", Global.medication) elif(action == 4): if(len(Global.patients) == 0): print("\nThere are no patients.") else: print("\nThe next patient will be leaving in", minimumTime(), "hours.") else: print("\nInvalid command.") main()
24d18536e753b27d331dc7bbcd4428a832855c87
joaoribas35/distance_calculator
/app/services/log_services.py
1,100
3.59375
4
from os.path import exists import os from csv import DictReader, DictWriter FILENAME = 'log.csv' FIELDNAMES = ['id', 'address', 'distance'] def read_logs(): """ Will verify if a file named log.csv exists. If not, will create a log.csv file and write a header with the fieldnames. """ if not exists(FILENAME) or os.stat(FILENAME).st_size == 0: with open(FILENAME, 'w') as f: writer = DictWriter(f, fieldnames=FIELDNAMES) writer.writeheader() logs = [] with open(FILENAME, 'r') as f: reader = DictReader(f) for log in reader: logs.append(log) return logs def create_id(): """ Will create a numeric sequence to be used as IDs for the log.csv entries. """ id_list = [] logs = read_logs() for log in logs: id_list.append(int(log['id'])) return sorted(id_list)[-1] + 1 if id_list != [] else 1 def create_log(log): """ Will create add a new log to log.csv. """ with open(FILENAME, 'a') as f: writer = DictWriter(f, fieldnames=FIELDNAMES) writer.writerow(log)
2e5a33bb1682b5c6c01ab4798916fd929f3400c3
candyer/leetcode
/longestCommonPrefix.py
640
3.796875
4
# https://leetcode.com/problems/longest-common-prefix/description/ # 14. Longest Common Prefix # Write a function to find the longest common prefix string amongst an array of strings. def longestCommonPrefix(strs): """ :type strs: List[str] :rtype: str """ if not strs: return '' mini, maxi = min(strs), max(strs) for i, string in enumerate(mini): if string != maxi[i]: return mini[:i] return mini print longestCommonPrefix(["bzc", "azertyui", "aertiertyuio"]) == '' print longestCommonPrefix(["atcg", "ag", "cg"]) == '' print longestCommonPrefix(["abc", "abcd", "abcde"]) == 'abc' print longestCommonPrefix([]) == ''
b1ff8a58e0750ca520a4474cdb025cc535f892d9
Annabe-ll/scripts_python
/ejemplos_python/diccionario.py
482
3.625
4
peliculas = {"anabel" : "Rapido y furioso", "carli" : "la noche del demonio", "joaquin" : "cars" } print (peliculas["anabel"]) for nombre, peli in peliculas.items(): print("Nombre alumno: %s" % nombre) print("Nombre pelicula: %s" % peli) num = 24 * 10 nombre = "anabel" utiles = ["mochila","libreta","lapiz"] frutas = ["manazana","pera","uva"] dia_clases = {"nombre" : nombre, "utiles" : utiles, "frutas" : frutas, "num" : num} print (dia_clases["frutas"])
fa190bece1546e35fd97fcf2fc0f5c729d5c681c
jawang35/project-euler
/python/lib/problem45.py
1,059
3.90625
4
''' Problem 45 - Triangular, Pentagonal, Hexagonal Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: Triangle T_n=n(n+1)/2 1, 3, 6, 10, 15, ... Pentagonal P_n=n(3n−1)/2 1, 5, 12, 22, 35, ... Hexagonal H_n=n(2n−1) 1, 6, 15, 28, 45, ... It can be verified that T_285 = P_165 = H_143 = 40755. Find the next triangle number that is also pentagonal and hexagonal. ''' from functools import partial from lib.helpers.numbers import is_triangular, is_pentagonal from lib.helpers.runtime import print_answer_and_elapsed_time def next_hexagonal_pentagonal_triangular_number(previous_hexagonal_n): n = previous_hexagonal_n while True: n += 1 current_number = n * (2 * n - 1) if is_pentagonal(current_number) and is_triangular(current_number): return current_number answer = partial(next_hexagonal_pentagonal_triangular_number, previous_hexagonal_n=143) if __name__ == '__main__': print_answer_and_elapsed_time(answer)
63a7f547b5c384a77972a3a1d549eb5ecfb399ad
ziyun-li/Algorithms
/String_Pattern_Finder.py
3,156
3.8125
4
def solution(s): """ This function takes in a string s, and finds the maximum equal splits of s Example, s = abcabcabcab, pattern = abc, max_eqal_split = 3 s = aaaaaaaaaaaaaaabbbbbbaaaaaaaaaaaaaaabbbbbb, pattern = aaaaaaaaaaaaaaabbbbbb, max_equal_split = 2 """ #collect index positions of first unique letter of the pattern first_letter_position=[] #collect index positions of second unique letter of the pattern second_letter_position=[] #for loop iterates through each index in the string to find the index positions of the first unique letter and the second unique letter for i in range(len(s)): if s[i]==s[0]: first_letter_position.append(i) #adds second unique letter that occurs in string. Ignores any subsequent 3rd to nth unique letters. elif len(second_letter_position) == 0: second_letter_position.append(i) else: #collect all positions of the second unique letter, only if it is after an occurence of the first letter letter #Rationale: if first unique letter has not occurred again, pattern has NOT repeated lapsed_indexes_from_last = range(second_letter_position[-1],i) if set(lapsed_indexes_from_last)-set(first_letter_position)!=set(lapsed_indexes_from_last): if s[i] == s[second_letter_position[0]]: second_letter_position.append(i) # if second_letter_position is empty, there is only 1 unique letter in the entire string. The entire string will be a repetition of the first letter that appears. if len(second_letter_position) ==0: max_equal_part=len(s) # if len(second_letter_position) is at least 2, and the second unique letter only occurs once in the pattern, the pattern will repeat at least 2 times. The exception is if the pattern consists of multiple first and second letter positions, e.g. abaaaab, and this is handled using "except" elif len(second_letter_position) >=2: try: n=1 #length of pattern is given by difference in position of one of the second letter positions. len_pattern = second_letter_position[n] - second_letter_position[0] #We iterate through the indexes to handle exception cases where second letter position occurs more than once in a single pattern. while True: if s[:len_pattern] == s[len_pattern:len_pattern+len_pattern]: break else: n+=1 len_pattern = second_letter_position[n] - second_letter_position[0] max_equal_part=len(s)/len_pattern #Indexerror indicates all positions in second_letter_position has been input into while loop but no match in pattern is found. This means that all positions in second_letter_position are within the same pattern, the pattern does not repeat. except IndexError: max_equal_part=1 # If len(second_letter_position) == 1, the second unique letter only appears once. The pattern does not repeat. else: max_equal_part=1 return max_equal_part
4c3d94f81af357492a92938a26b4da13fd4c7bae
RayGonzalez/FormalAnalysis
/KNN/KNN.py
4,638
3.703125
4
__author__ = 'raymundogonzalez' import csv import matplotlib.pyplot as plt import random data_file = open('knn_data.csv') reader = csv.reader(data_file) my_DataList = [] #Create datalist from file for row in reader: my_DataList.append(row) #Create lists for x and y values and the labels (going to need this for the scatter plot) x=[] y=[] labels=[] for point in my_DataList: x.append(point[0]) y.append(point[1]) labels.append(point[2]) #Receives a list of points and a refernce point as input #Gives me a list of tuples with distances from the nth point and the labels of those points def my_distance(Points,n): dist_list = [] tuple_list =[] count=0 ref_point= (Points[n]) for i in Points: distanceX = (float(i[0])-float(ref_point[0]))**2 distanceY = (float(i[1])-float(ref_point[1]))**2 distance = (distanceX+distanceY)**0.5 dist_list.append(distance) #Make tuple list with distances and labels for x in dist_list: tuple_list.append((x, Points[count][2])) count+=1 return tuple_list #Need to define this because I'll use it on P_label def getKey(item): return item[0] #Input: list of points (Datalist), reference point, k value #Gets most frequent label for k nearest points to a point n (Predicted label) def P_label(Points,n,k): MagicList= my_distance(Points,n) MagicList.sort(key=getKey) #Makes sublist with the distances to the k nearest points to n and their neighbors NewList = MagicList[1:k+1] count0=0 count1=0 #looks for the most frequent label in the neighbors and returns it for x in NewList: if x[1]=='0': count0+=1 else: count1+=1 if count1<count0: return 0 elif count0<count1: return 1 #If there is a tie, lets consider one less neighboor, and repeat else: NewList = MagicList[1:k] for x in NewList: if x[1]=='0': count0+=1 else: count1+=1 if count1<count0: return 0 else: return 1 #Creates the scatterplot given the points and labels (I can give it either predicted labels or real labels) def DoPlot(x,y,labels): plt.scatter(x,y,c=labels,s=100) plt.show() #Input: K value, and a boolean to say either if I want a plot or not. #Gives me a list of predicted labels and actual labels, calculates percentage of accuracy #If plot=true, gives me a plot of the points and their predicted labels. def Magic(k,plot): Result_list=[] #variable for number/percentage of right predictions count=0 labels=[] for c in range(0,len(my_DataList)): l=P_label(my_DataList,c,k) labels.append(l) Result_list.append((l,int(my_DataList[c][2]))) for a in Result_list: if a[0]==a[1]: count+=1 if plot==True: DoPlot(x,y,labels) return count/600.0*100 #Gives the best k using brute force def BruteForce(): Klist=[] Score=0 BestK=0 #gets a list with the values of k and the number of correct results #Assumption: No need to look for k values bigger than 300 (half the total number of points) for k in range(1,300): Klist.append((k,Magic(k,False))) #OPTIMIZATION: I don't need to sort the whole list, I just need to find the greatest score. #This takes more lines of code than just sorting, but lest computational power for a in Klist: if Score<a[1]: Score=a[1] BestK=a[0] print BestK #Create plot with predicted labels Magic(BestK,True) print Score #print Klist #Greedy algorithm for getting the best k. What I am doing is simulated annealing def Greedy(): #Generate 2 random neighboring solutions and check for scores #No need to check for values of k higher than 300 k1=int(random.uniform(1,300)) count=0 score1=0 #Greedy way to get at least 90% accuracy while (score1<90 and count<50) : score1=Magic(k1,False) k2=int(random.uniform(k1-20,k1+20)) score2=Magic(k2,False) count+=1 #If second solution better than first one, move there if score2>score1: k1=k2 #sometimes move to a worse solution #But I don't want to move to a worse solution if I am about to finish elif (random.random()>.90): k1=k2 print "k=",k1 #I am doing this in order to show the plot of predicted labels print "accuracy:" ,Magic(k1,True) #Get plot with real labels DoPlot(x,y,labels) Greedy() BruteForce()
8a769a3c52598c3545a8db6f7b4e236275ecffd6
NestY73/Algorythms_Python_Course
/Lesson_2/turnover.py
690
3.515625
4
#------------------------------------------------------------------------------- # Name: turnover # Purpose: Homework_lesson2_Algorythms # # Author: Nesterovich Yury # # Created: 16.03.2019 # Copyright: (c) Nesterovich 2019 # Licence: <your licence> #------------------------------------------------------------------------------- # 1 способ n1 = input("Введите целое число: ") n2 = '' n2 = n1[::-1] print('"Обратное" ему число:',n2) # 2 способ n1 = int(input("Введите целое число: ")) n2 = 0 while n1 > 0: n2 = n2 * 10 + n1 % 10; n1 = n1 // 10 print('"Обратное" ему число:',n2)
346a9f4634f74626323027387540aebf49767cd3
thabbott/prisoners-dilemma
/SchizophrenicRetribution.py
996
3.578125
4
from random import random, choices from Prisoner import Prisoner """ SchizophrenicRetribution: an old Prisoner who usually copies their opponent's last choice, but forgets what to do as time goes on so they usually just cooperate with anyone and everyone. They won't stop telling you the same stories from their glory days as a TitForTat. """ class SchizophrenicRetribution(Prisoner): def __init__(self): self.round_number = 0 self.last_strategy = True def pick_strategy(self): r = random() # 0 < schizophrenic factor < 1 increases with round number # and maximum schizophrenia sets in after 100 rounds. sf = min(self.round_number / 100, 1) if r < (1 - 0.4*sf): return self.last_strategy else: return choices([True, False], weights=[4, 1]) def process_results(self, my_strategy, other_strategy): self.round_number = self.round_number + 1 self.last_strategy = other_strategy
1c42c564af105d39f03b5d3a96775179d4a39582
yiming1012/MyLeetCode
/LeetCode/栈/单调栈(Monotone Stack)/496. 下一个更大元素 I.py
2,435
4.1875
4
""" 给定两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。 nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1 。   示例 1: 输入: nums1 = [4,1,2], nums2 = [1,3,4,2]. 输出: [-1,3,-1] 解释: 对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。 对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。 对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。 示例 2: 输入: nums1 = [2,4], nums2 = [1,2,3,4]. 输出: [3,-1] 解释:   对于 num1 中的数字 2 ,第二个数组中的下一个较大数字是 3 。 对于 num1 中的数字 4 ,第二个数组中没有下一个更大的数字,因此输出 -1 。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/next-greater-element-i 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: """ 思路:暴力法 时间复杂度:O(N*N) """ res = [] for num in nums1: index = nums2.index(num) for i in range(index + 1, len(nums2)): if nums2[i] > num: res.append(nums2[i]) break else: res.append(-1) return res def nextGreaterElement2(self, nums1: List[int], nums2: List[int]) -> List[int]: """ 思路: """ dic = {} stack = [] for i, num in enumerate(nums2): while stack and num > nums2[stack[-1]]: index = stack.pop() dic[nums2[index]] = num stack.append(i) return [dic.get(x, -1) for x in nums1] if __name__ == '__main__': nums1 = [4, 1, 2] nums2 = [1, 3, 4, 2] Solution().nextGreaterElement(nums1,nums2) Solution().nextGreaterElement2(nums1,nums2) if __name__ == '__main__': nums1 = [4, 1, 2] nums2 = [1, 3, 4, 2] print(Solution().nextGreaterElement(nums1, nums2))
afda2c426dcca605f9677aca1f872c3f0d9f533e
denzow/practice-design-pattern
/04_factory/pizza_store/lib/ingredient_factory.py
1,669
3.515625
4
# coding: utf-8 from abc import ABC, abstractmethod from .ingredient import * class PizzaIngredientFactory(ABC): @abstractmethod def create_dough(self): pass @abstractmethod def create_sauce(self): pass @abstractmethod def create_cheese(self): pass @abstractmethod def create_veggies(self): pass @abstractmethod def create_pepperoni(self): pass @abstractmethod def create_clam(self): pass class NYPizzaIngredientFactory(PizzaIngredientFactory): """ NYスタイルのピザ食材ファクトリ """ def create_dough(self): return ThinCrustDough() def create_sauce(self): return MarinaraSauce() def create_cheese(self): return ReggianoCheese() def create_veggies(self): veggies = [ Garlic(), Onion(), Mushroom(), RedPepper(), ] return veggies def create_pepperoni(self): return SlicedPepperoni() def create_clam(self): return FreshClams() class ChicagoPizzaIngredientFactory(PizzaIngredientFactory): """ シカゴスタイル """ def create_dough(self): return ThickCrustDough() def create_sauce(self): return PlamTomatoSauce() def create_cheese(self): return Mozzarella() def create_veggies(self): veggies = [ EggPlant(), Spinach(), BlackOlives(), ] return veggies def create_pepperoni(self): return SlicedPepperoni() def create_clam(self): return FrozenClams()
f3de785aaf121ecb89bc70272210727208cbd51c
edersoncorbari/hackerrank
/python/dijkstras.py
1,160
3.5625
4
#!/usr/bin/python -tt import sys from heapq import * def read(fn): return tuple(fn(i) for i in sys.stdin.readline().split(' ')) def load_graph(N, M): graph = [dict() for i in range(0, N)] for i in range(0, M): (x, y, r) = read(int) x -= 1 y -= 1 r = r if y not in graph[x] else min(r, graph[x][y]) graph[x][y] = r graph[y][x] = r return graph def dijkstras(graph, source): q = [] heappush(q, (0, source)) distances = [-1] * len(graph) distances[source] = 0 while len(q) > 0: (distance, vertice) = heappop(q) if distances[vertice] > 0: continue distances[vertice] = distance for n in graph[vertice]: if distances[n] > -1: continue cost = distance + graph[vertice][n] heappush(q, (cost, n)) return distances def test(): (N, M) = read(int) graph = load_graph(N, M) S = read(int)[0] - 1 distances = dijkstras(graph, S) for i in range(0, N): if i != S: end = ' ' if i < N - 1 else '\n' print(distances[i], end=end) def main(): T = read(int)[0] for i in range(0, T): test() if __name__ == '__main__': main()
432b80f967e6dda0efc977bb217e1834b9bf0f67
ViniciusEduardoM/Enigma
/Enigmadl.py
7,836
3.625
4
# Importando as bibliotecas necessárioas # Nós precisamos da biblioteca ascii_lowercase para puxar uma lista com alfabeto ingles from string import ascii_lowercase class enigma: def __init__(self, plugboard = {" ":" "}, alpha=None, beta=None, gama=None): ''' Setando as configurações do enigma antes da encriptação ''' # Criando a lista do alfabeto self.alphabet = list(ascii_lowercase) ''' Plugboard é um sistema de soquetes que era usado conectando pares de letras que eram trocadas na entrada do primeiro rotor ''' self.plugboard = plugboard if alpha != None and beta != None and gama != None and plugboard != None: ''' Aqui testamos se os valores do plugboard são letras e setemos os valores dos rotores para aquilo que o construtor receber ''' if type(plugboard) is not dict: self.plugboard = {" " : " "} self.alpha = alpha self.beta = beta self.gama = gama # Aqui verificamos se a letra a ser encriptada está no plugboard, e assim duplicamos seu par for letter in list(self.plugboard.keys()): print(str(plugboard)) if letter in self.alphabet: self.plugboard.update({self.plugboard[letter]:letter}) print(str(plugboard)) '''Aqui setamos o refletor que pega uma letra, e reflete sua posição no alfabeto, como um a, invertido vira z e assim por diante''' self.reflector = [leter for leter in reversed(self.alphabet)] def shift(self, rotor): ''' Aqui criamos a primeira função do Enigma, essa função 'roda o alfabeto' dependendo das configuraçoes setadas nos rotores ''' shift_alphabet = ''.join(self.alphabet) shift_alphabet = list(shift_alphabet) for iter in range(rotor): shift_alphabet.insert(0, shift_alphabet[-1]) shift_alphabet.pop(-1) #print(self.alphabet) #print('Separa') #print(shift_alphabet) return shift_alphabet def shift_reverso(self, rotor): ''' Esta função tem a mesma lógica da função anterior, mas fazendo o caminho invertido para frente ''' shift_alphabet = ''.join(self.alphabet) shift_alphabet = list(shift_alphabet) for iter in range(rotor): shift_alphabet.append(shift_alphabet[0]) shift_alphabet.pop(0) #print(self.alphabet) #print(shift_alphabet) return shift_alphabet def encrypt_text(self, text): ''' Esta é a função principal da classe, ela chama todas as outras funcões de forma lógica para encriptar a mensagem ''' encrypted_text = [] # Processando o texto recebido text = text.lower() # Transformamos o texto totalmente em minusculo text.split() # 'Splitamos' o texto, ou seja, o cortamos, deixando cada letra ser um objeto numa lista # Aqui começa a encriptação letra por letra for letter in text: # Checamos se a letra está no plugboard if letter in self.plugboard: # Se a letra está, a encriptamos com seu par letter = self.plugboard[letter] print('Está no plugboard -> ' + letter) ''' Aqui testamos se o caracter é um espaço, se for, o adicionamos no final do texto final e seguimos para outra letra''' if letter == ' ': encrypted_text.append(' ') else: # Aqui temos a letra sendo ecriptada pelo primeiro rotor temp_letter = self.shift(self.alpha)[self.alphabet.index(letter)] print("alpha - {}".format(temp_letter)) # Aqui temos a letra sendo ecriptada pelo segundo rotor temp_letter = self.shift(self.beta)[self.alphabet.index(temp_letter)] print("beta - {}".format(temp_letter)) # Aqui temos a letra sendo ecriptada pelo terceiro rotor temp_letter = self.shift(self.gama)[self.alphabet.index(temp_letter)] print("gama - {}".format(temp_letter)) # Aqui chamamos o refletor, para refletir a letra encriptada no alfabeto print(temp_letter) temp_letter = self.reflector[self.alphabet.index(temp_letter)] print("reflector - > {}".format(temp_letter)) ''' Caminho de volta ''' # Aqui temos a letra sendo ecriptada pelo primeiro rotor reverso temp_letter = self.shift_reverso(self.gama)[self.alphabet.index(temp_letter)] #print('Reversed') print("gama - {}".format(temp_letter)) # Aqui temos a letra sendo ecriptada pelo segundo rotor reverso temp_letter = self.shift_reverso(self.beta)[self.alphabet.index(temp_letter)] #print('Reversed') print("beta - {}".format(temp_letter)) # Aqui temos a letra sendo ecriptada pelo terceiro rotor reverso temp_letter = self.shift_reverso(self.alpha)[self.alphabet.index(temp_letter)] #print('Reversed') print("alpha - {}".format(temp_letter)) print('Letra final codificada -> ' + temp_letter) if temp_letter in self.plugboard: temp_letter = self.plugboard[temp_letter] print('Está na saida plugboard, virou -> ' + temp_letter) encrypted_text.append(temp_letter) # Juntamos a letra temporaria ao texto encriptado e a printamos # Rodando os rotores * Explicado com detalhes na documentação * self.alpha += 1 if self.alpha % len(self.alphabet) == 0: self.beta += 1 self.alpha = 0 if self.beta % len(self.alphabet) == 0 and self.alpha % len(self.alphabet) != 0 and self.beta >= len( self.alphabet) - 1: self.gama += 1 self.beta = 1 print('Valor do rotor beta - {}'.format(self.beta)) # Setamos o novo valor de Beta print('Valor do rotor alpha - {}'.format(self.alpha))# Setamos o novo valor de Alpha print('Fim encriptação da letra') print('------------------------------------ \n') print('Mensagem encriptada/decriptada:\n') return ''.join(encrypted_text) # Depois de todo loop de encriptação feito, mostramos a mensagem alpha = int(input('Digite aqui o valor do Primeiro Rotor: ')) # Setando o valor do primeiro rotor beta = int(input('Digite aqui o valor do Segundo Rotor: ')) # Setando o valor do segundo rotor gama = int(input('Digite aqui o valor do Terceiro Rotor: ')) # Setando o valor do terceiro rotor crypttxt = input('Digite aqui a mensagem a ser encriptada: ') # Recebendo a mensagem para ser encriptada Enigma = enigma({'f':'g','d':'y','h':'b'}, alpha = alpha, beta = beta, gama = gama) print(Enigma.encrypt_text(crypttxt))
b6582881a59ad79ae2f96ebd9c02801ac2a120e1
Saeid-Nikbakht/Data_Analysis_UK_Crime
/UK_Crime_Statistics.py
9,435
3.71875
4
#!/usr/bin/env python # coding: utf-8 # # About this dataframe # ## Context # Recorded crime for the Police Force Areas of England and Wales. # The data are rolling 12-month totals, with points at the end of each financial year between year ending March 2003 to March 2007 and at the end of each quarter from June 2007. # # ## Content # The data are a single .csv file with comma-separated data. # It has the following attributes: # # 12 months ending: the end of the financial year. # # PFA: the Police Force Area. # # Region: the region that the criminal offence took place. # # Offence: the name of the criminal offence. # # Rolling year total number of offences: the number of occurrences of a given offence in the last year. # # ## Source: # https://www.kaggle.com/r3w0p4/recorded-crime-data-at-police-force-area-level # In[1]: import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import sklearn # # Reading the dataset # In[2]: df = pd.read_csv("rec-crime-pfa.csv") df.head() # # Change the Column names for convinience # In[3]: mapper = {"Rolling year total number of offences":"num_offence", "Offence":"type_offence", "12 months ending":"date"} df.rename(columns = mapper, inplace=True) # # General Overview of Dataset # In[4]: print("The number of Features: {}".format(df.shape[1])) print("The number of Observations: {}".format(df.shape[0])) # In[5]: df.info() # In[6]: df.describe() # ## There is no Null values in this Dataset # In[7]: df["date"] = pd.to_datetime(df["date"]) df.set_index("date", inplace = True) # # Unique Values # In[8]: df.index.unique() # In[9]: df.Region.unique() # In[10]: df.PFA.unique() # In[11]: df.type_offence.unique() # # We only consider the data after the year 2007 # In[12]: df = df.loc[df.index>"01-01-2007"] # In[13]: df.loc[df.index.month == 3, "season"] = "Winter" df.loc[df.index.month == 6, "season"] = "Summer" df.loc[df.index.month == 9, "season"] = "Spring" df.loc[df.index.month == 12, "season"] = "Fall" df["year"] = df.index.year # In[14]: df.head() # # Main Analysis # ## Seasonal Crimes Analysis # In[15]: df_ys = pd.crosstab(index = df.year, columns = df.season, values = df.num_offence, aggfunc = "mean", margins = True, margins_name = "mean") df_ys.head(15) # ## As is shown, The mean amount of crime in different seasons are almost the same. # In[16]: plt.figure(figsize = [12,8]) plt.plot(df_ys.drop(index = 'mean').index, df_ys.drop(index = 'mean').loc[:,"mean"]) # In[17]: df.groupby(["year","season"]).num_offence.mean().unstack(). plot(kind = "bar", figsize = [12,8]); # In[18]: hue_order = ["Winter", "Spring", "Summer", "Fall"] plt.figure(figsize = [12,8]) sns.barplot(data = df, x = 'year', y = "num_offence", hue = "season", dodge = True, hue_order = hue_order,); # ## As is shown, the average number of crimes during the years 2007 and 2018 sunk from nearly 6000 to 4600 in 2013 and it increases up to more than 6000 again in 2018. # # Regional Crime Analysis over the Years # In[19]: df_yr = pd.crosstab(index = df.year, columns = df.Region, values = df.num_offence, aggfunc = "mean", margins = True, margins_name = "mean") df_yr.head(15) # ## We should Ommit Three columns namely, Fraud: Action Fraud, Fraud: CIFAS, Fraud: UK Finance, Because these parts are related to the type of offence, not the region of the crime!! # In[20]: df_yr.drop(columns = ['Fraud: Action Fraud','Fraud: CIFAS', 'Fraud: UK Finance'], index = 'mean').plot(figsize = [12,8]) # ## Among all regions Action Fraud and CIFAS have been significantly rose during the years 2011 and 2018. The rest of regions saw a slight decrease and then increase. # ## Another fact about this plot is that the most criminal region in the whole analyzed area is London. The amount of crime in the other regions of UK is pretty much the same. # # Type of Offence Analysis Over the Years # In[21]: df_yt = pd.crosstab(index = df.year, columns = df.type_offence, values = df.num_offence, aggfunc = "mean", margins = True, margins_name = "mean") df_yt.head(15) # ## Since there are some Null Values in each column, we consider backward fill value method here. # ## Moreover, Three columns of Action Fraud, CIFAS and UK Finance are also seperated, since the amount of these crimes are much more than the rest and their analysis cannot be shown in the plot vividly. # In[22]: blocked_list = ["Action Fraud","CIFAS","UK Finance"] df_yt.fillna(method = "bfill").drop(columns = blocked_list, index = 'mean'). plot(figsize = [12,80], subplots = True,grid = True); # ## Most highlights during the years 2007 to 2018: # # 1) Bicycle Theft: has decreased from 2500 in 2007 to nearly 2000 in 2016. afterwards however, it increased up to 2200 in 2018 # # 2) Criminal Damage and Ason decreased from 25000 to 12500. This is nearly a 50% decrease. # # 3) Death or serious injury caused by illegal driving rose from 10 to 16. This amount is too little to be analyzed. # # 4) Domestic Burglury has decreased slightly from 6000 in 2007 to 4000 in 2016. This amount has fallen significantly to zero in 2018. This is strange, there must be missing values for this crime in our data set in the year 2018. # # 5) Drug offence rose to 5500 and decreased to lower than 3500 in 2018 # # 6) Homicide decreased from 17 in 2007 to 12 in 2014. then it increased to 16 in 2018. # # 7) Miscellaneous Crime against society decreased slightly from 1400 in 2007 to 1000 in 2013 and increased to 2200 in 2018. # # 8) Non domestic Burglury decreased steadily from 7000 in 2007 to nearly 4500 in 2016. Afterwards it decreased significantly to zero in 2018. # # 9) Between the years 2016 and 2018 however, the non residential burglury increased remarkably to nearly 3000. # # 10) Possession of weapons offences was nearly 900 in 2007. it saw a steady decrease and reached its minimum of below 500 in 2013 and it rose again up to more than 900 in 2018. # # 11)Public oreder offences showed a slight decrease from 5500 in 2007 to 3500 in 2013 and it increased to more than 9000 in 2018. # # 12)Robbery decreased from 2200 to 1200 in 2015 and it increased to 1800 in 2018. # # 13)Unfortunately, The sexual offences increased steadily during this period of time from lower than 1500 in 2007 to more than 3500 in 2018. Looking at this statistics from another perspective, during the past years, with the remarkable growth of social media, people are not affraid or ashamed of disclosing sexual abuses. Maybe this statistics can be reffered to the number of disclosures of this crime to the police, rather than the number of sexual herasments which actually were occured. Hope So! # # 14) The same thing could be true for Stalking and Herassments, which showed a great increase from lower than 2000 in 2007 to 8000 in 2018. # # 15)The theft from people fluctuated between 1800 and 2200 # # 16) Vehicle offences decreased from 16000 in 2007 to 8000 in 2015. Subsequently, it increased to 10000 in 2018. # # 17)Violence with injuries decreased from 11000 in 2007 to 7000 in 2013 and it increased to more than 12000 in 2018. # # 18) Violence without injuries however, increased significantly from lower than 6000 to more than 14000. # # # The Average incidence of crimes in all of the aforementioned areas decreased from 2007 to 2013. The years 2013 to 2015 showed a plateau of the minimum incidences and afterwards the average occurace of crimes again increased significantly. # # In[23]: selected_list = ["Action Fraud","CIFAS","UK Finance"] df_yt.fillna(method = "bfill").loc[:,selected_list].drop(index = 'mean'). plot(figsize = [12,10], subplots = True,grid = True); # ## Most highlights during the years 2007 to 2018: # # 1) Action Fraud increased from lower than 50,000 in 2011 to nearly 300,000 in 2018. # # 2) CIFAS showed a similar behavior and reached its maximum of 300,000 in years 2015 and 2016 and it fell slightly to 280,000 in 2018. # # 3) UK Finance however decreased from 120,000 in 2012 to 80,000 in 2018. This crime is an exceptional case and as opposed to all other crimes it fell during this period of time. # # Regional Analysis of Crimes based on the Type of Crime # In[24]: blocked_index = ["Fraud: Action Fraud","Fraud: CIFAS","Fraud: UK Finance"] blocked_columns = ["Action Fraud","CIFAS","UK Finance","mean"] df_rt = pd.crosstab(index = df.Region, columns = df.type_offence, values = df.num_offence, aggfunc = "mean", margins = True, margins_name = "mean").\ drop(index = blocked_index, columns = blocked_columns) df_rt.head(15) # In[25]: df_rt.T.plot(kind = 'barh', figsize = [12,150], subplots = True, grid = True, fontsize = 15, sharex = False, stacked = True); # ## Highlights: # # 1) The most common crimes in all regions are "Criminal Damage and Arson", "Violence with and without Injury", "Vehicle Offences" and "Shoplifting". # Almost all of the regions are showing these crimes to be the most common. # 2) The least common crimes are "Illegal Driving", "Possession of Weapon" and "Homocide".
6694b60e9a62468e9304591936d2078e613fae73
Jakamarinsek/Backend_python
/Pretvornik.py
264
4.0625
4
mile = 1.852 print("Hi. I can convert km to miles.") odgovor = "yes" while odgovor == "yes": number = int(raw_input("Enter km: ")) km = number / mile print km odgovor = raw_input("another coversion?: ").lower() if odgovor == "no": print ("bye")
e881c0247fd3c4a908d66386947acc5e153c759b
Palash51/Python-Programs
/oop prgm/All-OOP/inheritance/inheritance2.py
463
3.96875
4
## tutorial -- inheritance # -- inheritance is implicite ## -- issubclass(A,B) return boolean ### class Person(object) --> it is explicit but in python3 no need to define it like this (implicit) ### by default class is a subclass of object class class Person: pass class Employee(Person): pass def main(): print(issubclass(Employee, Person)) print(issubclass(Employee, object)) print(issubclass(Employee, object)) if __name__ == "__main__": main()
356ac29fd2271c864fe24b059dd9a3c82e7d3de1
cuekoo/python-demos
/interview-problem/interview-problem.py
1,315
3.84375
4
#! /usr/bin/python # This program demonstrates the solution to the problem in Quora. # # Suppose you are going to hire one person for a position. There are 100 # candidates. You interview one by one and should make the decision # immediately after the interview. There's no way to get back the candidates # who you already eliminated. Then what's the best strategy to get the best # candidate? import random import math from collections import Counter from matplotlib import pyplot as plt def try_max(num, base): data = range(0, num) random.shuffle(data) b = math.floor(1 * num / base) maxv = 0 for i in range(0, num): if i < b: if data[i-1] > maxv: maxv = data[i - 1] else: if data[i - 1] > maxv: maxv = data[i - 1] return maxv return data[num - 1] def exp(trynum, num, base): temp = [] for i in range(0, trynum): temp.append(try_max(num, base)) return temp def count(num, result): cnt = Counter(result) temp = [] for i in range(0, num): temp.append(cnt[i]) return temp num = 100 trynum = 1000 result_quora = exp(trynum, num, math.e) plt.title("histogram of guesses") plt.plot(range(0, num), count(num, result_quora), "bo-") plt.show()
407845504f44fc97568ac0bd70aa5eae5205593e
lvsazf/python_test
/variable.py
348
3.828125
4
# -*- coding: utf-8 -*- ''' Created on 2017年6月29日 @author: Administrator list:有序列表,可变 ''' classmates = ["Michael","Boy","Tracy"] print(classmates) #list长度 print(len(classmates)) ''' tuple 元组 一旦初始化完,就不能修改 ''' print("---------------tuple---------------------") t = (1,2) print(t)
148a2433f78ad0f419c3c415bff6f27b8538c48a
3esawe/Python-Linux
/Firecode/unique.py
324
3.6875
4
def unique_chars_in_string(input_string): unique = {} for i in input_string: unique[i] = unique.get(i, 0) + 1 maxval = max(unique.keys(), key=(lambda k: unique[k])) print(unique) if unique[maxval] > 1: return False else: return True print(unique_chars_in_string("Language"))
abafada0110b8cba9f6bd2bc7879e44c559c646a
SvetlanaBicanin/MATF-materijali
/3. godina/pp vezbe/cas03 - Funkcionalno programiranje (Python)/3.py
407
3.734375
4
# Marko, Petar i Pavle su polagali ispit iz predmeta # Programske Paradigme. Napisati program koji sa # standardnog ulaza ucitava ocene koji su dobili, # a potom ispisuje listu parova (student, ocena) na # standardni izlaz. imena = ['Marko', 'Petar', 'Pavle'] ocene = [int(input("Ocena za " + ime + ": ")) for ime in imena] print(zip(imena, ocene)) # adresa for par in zip(imena, ocene): print(par)
a49b79d5e2904914ec815365ccd49ee7dfed10b7
ameet-1997/Course_Assignments
/Machine_Learning/Programming_Assignments/CS15B001_PA1a/Code/q2/run.py
1,818
3.5
4
""" This file has been used to complete assignment parts 1,2,3 of PA1 Includes generation of synthetic data, learning Linear and KNN classifiers and getting the accuracy values Author: Ameet Deshpande RollNo: CS15B001 """ import os import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score # Load the data generated in question 1 after changing the working directory os.chdir("..") train = pd.read_csv("q1/DS1-train.csv", header=None) test = pd.read_csv("q1/DS1-test.csv", header=None) # Change back the working directory os.chdir(os.getcwd()+"/q2") # Subset the data and the labels train_data = train.iloc[:,0:20] train_labels = np.array(train.iloc[:,20]) test_data = test.iloc[:,0:20] test_labels = np.array(test.iloc[:,20]) # Train Linear Regression Model on the data lr = LinearRegression() lr.fit(train_data, train_labels) # Predict the values for testdata predicted_labels_linear = lr.predict(test_data) # Using threshold as 0.5 to check which class it belongs to predicted_labels_linear[predicted_labels_linear >= 0.5] = 1 predicted_labels_linear[predicted_labels_linear < 0.5] = 0 # Calculate the scores for the predicted labels lin_accuracy = accuracy_score(test_labels, predicted_labels_linear) lin_precision = precision_score(test_labels, predicted_labels_linear) # average='macro' lin_recall = recall_score(test_labels, predicted_labels_linear) lin_f = f1_score(test_labels, predicted_labels_linear) print("Accuracy: "+str(lin_accuracy)) print("Precision: "+str(lin_precision)) print("Recall: "+str(lin_recall)) print("F-Score: "+str(lin_f)) print("Coefficients Learnt: "+str(lr.coef_)) np.savetxt("coeffs.csv", lr.coef_,delimiter=',')
81126c7dbecb3c1d299601de32f6ddb877fc3d24
suman2826/Building_BLocks_of_Competitive
/Array/find_min.py
378
3.5625
4
def find_min(a,low,high): if high<low: return a[0] if high == low: return a[low] mid = (high+low)//2 if mid < high and a[mid+1] < a[mid]: return a[mid+1] if mid > low and a[mid] < a[mid-1]: return a[mid] if a[high]>a[mid]: return find_min(a,low,mid-1) return find_min(a,mid+1,high) a = [10,20,30,40,5,7] low = 0 high = len(a)-1 print(find_min(a,low,high))
c8ed4f0f1024091194fb7a91bbee1d5c1e683725
Mercy021/pythonclass
/dog.py
323
3.609375
4
class Dog: breed="Bulldog" color="grey" def __init__(self,breed,color): self.breed=breed self.color=color def bite(self): return f"Hello chew,my pet bites strangers {self.breed}" def bark(self): return f"Hello,my dog barks every morning {self.breed}"
a8ff0c36f7274aff0d820db1d35bc71dda4980ec
windy319/leetcode
/binary-tree-level-order-traversal-ii.py
1,016
3.8125
4
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of lists of integers def levelOrderBottom(self, root): if not root: return [] result = [] stack = [[],[]] cur,pre=0,1 stack[cur] = [root] while True: cur,pre = pre,cur if not stack[pre]: break path = [] for x in stack[pre]: path.append(x.val) result.append(path) stack[cur]=[] stack[pre].reverse() while stack[pre]: node = stack[pre].pop() if node.left: stack[cur].append(node.left) if node.right: stack[cur].append(node.right) result.reverse() return result
20bce1c1c43fedeed6448208bc8818507d0a8a29
climatom/BAMS
/Code/Misc/VapourTransport.py
2,309
3.578125
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Simple script to estimate moisture flux through the South Col. The principle here is to take the mean spechum and mean wind between South Col and Balcony and estimate the vapour flux in this corridoor. """ import pandas as pd, numpy as np import matplotlib.pyplot as plt g=9.81 # Gravitational acceleration def satVpTeten(tempC): """ Teten's formula to compute the saturation vapour pressure """ if np.min(tempC) >150: tempC-=273.15 vp=611.2*np.exp((17.67*tempC)/(tempC+243.5)) return vp def specHum(temp,rh,press): """ Simply computes the specific humidity (kg/kg) for given temp, relative humidity and air pressure Input: - temp (C or K) - rh (fraction): relative humidity - press: air pressure (hPa or Pa) """ rh=np.atleast_1d(rh) temp=np.atleast_1d(temp) press=np.atleast_1d(press) # Check for rh as frac and convert if in % if np.nanmax(rh)>1.5: _rh=rh/100. else: _rh = rh*1. # Check for Pa and convert if in hPa (note - no checking for other formats) if np.nanmax(press)<2000: _press=press*100. else: _press=press*1. # Note that satVp() checks if temp is in K... svp=satVpTeten(temp) Q=_rh*svp*0.622/_press return Q # Read in din="/home/lunet/gytm3/Everest2019/Research/BAMS/Data/AWS/" fs=["south_col_filled.csv","balcony_filled.csv"] col=pd.read_csv(din+fs[0],parse_dates=True,index_col=0) bal=pd.read_csv(din+fs[1],parse_dates=True,index_col=0) idx_col=col.index.isin(bal.index) idx_bal=bal.index.isin(col.index) # Compute specific humidity q1=specHum(col["T_HMP"],col["RH"],col["PRESS"]) q2=specHum(bal["T_HMP"],bal["RH"],bal["PRESS"]) # Mean spechum mu_q=1/2.*(q1[idx_col]+q2[idx_bal]) # Winds u1=(col["WS_AVG"].values[:]+col["WS_AVG_2"].values[:])/2. u2=(bal["WS_AVG_1"].values[:]+bal["WS_AVG_2"].values[:])/2. # Mean wind mu_u=1/2.*(u1[idx_col]+u2[idx_bal]) # Delta p (Pa) dp=(col.loc[idx_col]["PRESS"]-bal.loc[idx_bal]["PRESS"])*100. # Compute IVT ivt=1/g*dp*mu_q*mu_u ivt_total=np.sum(ivt)*60**2 ivt_total_m3=ivt_total/1000. # Compute precipitable water (mm) pw=1/(1000.*g)*mu_q*dp*1000. fig,ax=plt.subplots(1,1) ax.plot(dp.index,ivt)
d9296f0601e1a25b11091028231e1773c56befe5
yeeryan/programming-python
/Lessons/Lesson 5.py
137
3.875
4
# Lists odds = [1,3,5,7] print('odds are:',odds) # Exercise my_list = [] for char in 'hello': my_list.append(char) print(my_list)
cb5ecc6ce57739a80b9e5fa76b883abfbab10eaf
feleck/edX6001x
/lec5_problem6.py
352
3.9375
4
def lenIter(aStr): ''' aStr: a string returns: int, the length of aStr ''' # my solution: RECURSIVE!!!! - should be iterative ''' if aStr == '': return 0 else: return 1 + lenIter(aStr[:-1]) ''' length = 0 while aStr != '': aStr = aStr[:-1] length += 1 return length
4bf85a2ec403e3f667cf55ab090ac700b3a6cd11
dizethanbradberry/anandh-python
/chapter 2/pgm1-sum.py
289
3.890625
4
# Program to provide an implementation for built in function 'sum' def sum(l): sum=0 for i in l: sum=sum+i return sum n=raw_input("Enter the length of list:") l=[] for i in range(int(n)): l.append(int((raw_input("Enter the element %d:" % i)))) print 'list =',l print 'sum =',sum(l)
c8ab423a0dd38f02dbf42f1a436d52054c3258c2
andersonpablo/Exercicios_Python
/Aula08/avaliando-questao01.py
907
4.21875
4
# -*- coding: utf-8 -*- # 1. Faça um algoritmo que leia n valores e calcule a média aritmética desses valores. # Lê a quantidade de valores a serem digitados quantidade = input("Digite um número: ") # Criando a variável i para contar de 1 até o valor da variável quantidade i = 1 # Criando a variável que será usada para somar os valores digitados pelo usuário somatorio = 0 # Laço condicional para contar de 1 até o valor da variável quantidade while i <= quantidade: # Solicita que o usuário digite um valor valor = input("Digite o " + str(i) + "o. valor: ") # Soma o valor com o somatório dos valores digitados anteriormente somatorio = somatorio + valor # Incrementa o valor de i em 1 i = i + 1 # Calcula a média aritmética dos valores digitados media = somatorio / quantidade # Imprime o resultado print("A média dos valores digitados é " + str(media))
7447787a978481feab09108a81c49c01bcf9bbfb
NCRivera/COP1990-Introduction-to-Python-Programming
/Assignments/Weights - Lists.py
840
3.8125
4
# FIXME (1): Prompt for four weights. Add all weights to a list. Output list. weights = [] people = 4 for person in range(people): score = float(input("Enter weight %d:\n" % (person + 1))) weights.append(score) print('Weights:', weights) # FIXME (2): Output average of weights. averageWeight = sum(weights)/people print('\nAverage weight: %0.2f' % averageWeight) # FIXME (3): Output max weight from list. maxWeight = max(weights) print('Max weight: %0.2f\n' % maxWeight) # FIXME (4): Prompt the user for a list index and output that weight in pounds and kilograms. index = int(input('Enter a list index (1 - 4):\n')) print("Weight in pounds: %0.2f" % weights[index - 1]) print('Weight in kilograms: %0.2f\n' % ((weights[index - 1])/2.2)) # FIXME (5): Sort the list and output it. weights.sort() print('Sorted list:', weights)
c79e597d19e8dc91b674c2e63a048029297f43f6
khela123/exercises
/journalbirthdays.py
2,656
3.765625
4
import csv # import sys class Birthdays: # xRead from an input file # xAdd entry to journal # xView entries # xSearch entries # Edit entries # Delete entries # xExport def __init__(self): self.birthday_id = 1 self.entries = [] def read_input(self): with open('birthdays.csv') as csvfile: reader = csv.reader(csvfile, delimiter=',') next(reader) date = [] name = [] for row in reader: date = row[0] name = row[1] self.add_entry(name,date) # print(date) # print(name) def add_entry(self,name,date): self.entries.append({ 'date': date, 'name': name }) def view_entries(self): print(' Date | Name ') print('---' * 11) for entry in self.entries: date, name = entry.values() print(date, ',', name) def search_entry(self, query=''): searchinput = input("Input chuchu you want to search: ") matched_entries = [entry for entry in self.entries if searchinput in entry['name'].lower()] print(matched_entries) return matched_entries def edit_entry(self): # choice = input("Do you want to edit? y/n") inputindex = int (input("Input index that you want to edit: ")) inputelement = input("Input (n) for name and (d) for date: ") if inputelement in ("n", "N"): newname = input("New Name: ") self.entries[inputindex]['name'] = newname elif inputelement in ("d", "D"): newdate = input("New Date: ") self.entries[inputindex]["date"] = newdate else: print("Invalid input!") self.view_entries() def delete_entry(self): indextodel = int (input("Input index that you want to delete: ")) print("Deleted: ",self.entries[indextodel]) self.entries.pop(indextodel) self.view_entries() return self.entries def export_entries(self, file_name): with open(file_name, 'w') as f: f.writelines([ '{date},\t{name} \n'.format_map(entry) for entry in self.entries ]) def __str__(self): return 'Birthdays ' + str(self.birthday_id) birthdays = Birthdays() print(birthdays) birthdays.read_input() birthdays.view_entries() birthdays.search_entry(query ="") birthdays.edit_entry() birthdays.delete_entry() birthdays.export_entries(file_name='copy_birthdays.txt')
7d8a0270e5a2e56d239bbbb499dfbdec7bce235e
gewl/Exercisms
/python/pangram/pangram.py
358
3.890625
4
from string import ascii_lowercase def is_pangram(phrase): alphabet_dictionary = {letter:False for letter in ascii_lowercase} for letter in phrase: letter = letter.lower() if letter in alphabet_dictionary: alphabet_dictionary[letter] = True return all(letter == True for letter in alphabet_dictionary.itervalues())
faba3c76462321ba453f49646fde34404cc836e2
donsergioq/learn-homework-1
/4_while1.py
840
4.15625
4
""" Домашнее задание №1 Цикл while: hello_user * Напишите функцию hello_user(), которая с помощью функции input() спрашивает пользователя “Как дела?”, пока он не ответит “Хорошо” """ def hello_user(): answer = '' while answer != 'Хорошо': answer = input('Как дела? ') print('Рад за Вас') def hello_user2(): while True: if input('Как дела? ') == 'Хорошо': break print('Рад за Вас') def hello_user3(): while input('Как дела? ') != 'Хорошо': pass print('Рад за Вас') if __name__ == "__main__": hello_user3() # Вариант 3 мне нравится больше других
d91fa9fa82e5c5db73bc708f18cdadcbeeceaf13
reichlj/PythonBsp
/Schulung/py01_einführung/f060_input.py
214
4.25
4
name = input("Dog's name? ") if name == "Blanchefleur" or name == "Camille": print("Bonjour " + name) elif name == "Dolce" or name == "Valentino": print("Buongiorno " + name) else: print('Hi ' + name)
f70037f414c4d495354a92f88427b0a5c86e4dbf
todaybow/python_basic
/python_basic_jm_22.py
2,052
3.953125
4
''' 파이썬 데이터베이스 연동 (SQlite) 테이블 조회 ''' import sqlite3 # DB파일 조회(없으면 새로 생성) conn = sqlite3.connect('D:/Python/python_basic/resource/database.db') # 커서 바인딩 cursor = conn.cursor() # 데이터 조회 cursor.execute("SELECT * FROM users") # 커서 위치가 변경 # 1개 로우 선택 # print('One-> \n', cursor.fetchone()) # 지정 로우 선택 # print('Three-> \n', cursor.fetchmany(size=3)) # 나머지 전체 로우 선택 # print('All-> \n', cursor.fetchall()) # 커서위치 초과 되어 데이터가 없음 # print('All-> \n', cursor.fetchall(), end='\n\n') # 순회1 # rows = cursor.fetchall() # for row in rows: # print('retrieve1 > ', row) # 순회2 for row in cursor.fetchall(): print('retrieve2 > ', row) print() # 순회3 for row in cursor.execute("SELECT * FROM users ORDER BY id desc"): print('retrieve3 > ', row) print() # WHERE Retrieve1 param1 = (3,) cursor.execute("SELECT * FROM users WHERE id=?", param1) print('param1 : ', cursor.fetchall()) print() # WHERE Retrieve2 param2 = 4 cursor.execute("SELECT * FROM users WHERE id='%s'" % param2) print('param2 : ', cursor.fetchall()) print() # WHERE Retrieve3 cursor.execute("SELECT * FROM users WHERE id=:Id", {"Id":5}) print('param3 : ', cursor.fetchall()) print() # WHERE Retrieve4 param4 = (3,5) cursor.execute("SELECT * FROM users WHERE id IN(?,?)", param4) # IN은 합집합입니다. print('param4 : ', cursor.fetchall()) print() # WHERE Retrieve5 cursor.execute("SELECT * FROM users WHERE id IN('%d','%d')" % (3,4)) # IN은 합집합입니다. print('param5 : ', cursor.fetchall()) print() # WHERE Retrieve6 cursor.execute("SELECT * FROM users WHERE id=:id1 OR id=:id2", {"id1":1, "id2":2}) # IN은 합집합입니다. print('param6 : ', cursor.fetchall()) print() # Dump 출력 with conn: with open('D:/Python/python_basic/resource/dump.sql', 'w') as f : for line in conn.iterdump(): f.write('%s\n' % line) print('Dump print complete')
c742ae188533ee2a08faca9347dbae2869144ff4
Caio-Batista/coding-marathon-problems
/hackerrank/min_max_sum.py
466
3.53125
4
def miniMaxSum(arr): ordered = count_sort(arr) min_sum = sum(ordered[0:4]) max_sum = sum(ordered[1:]) print(f'{min_sum} {max_sum}') def count_sort(arr): temp = [0] * 100000 ordered = [] for e in arr: temp[e] += 1 for i in range(len(temp)): for _ in range(temp[i]): ordered.append(i) print(ordered) return ordered if __name__ == '__main__': arr = [7, 69, 2, 221, 8974] miniMaxSum(arr)
8d11169a869dbdbab4db192659e43f0f8b03489a
Remyaaadwik171017/mypythonprograms
/collections/list/nestedlist/list4.py
136
3.96875
4
t1=(1,2,4,6,3,6,8,12,34,22)#tuple t2=sorted(t1) #after sorting will return list not tuple print(t2) t3=sorted(t1,reverse=True) print(t3)
a02e2ae96b764d6a94b02fd5be8b6d1ceaef9413
mebinjohnson/Basic-Python-Programs
/Journal Testing/Q18 Mebz(Create data.txt).py
642
3.921875
4
read_file=open('data.txt','rb') string='' string=read_file.read() read_file.close() upper='' lower='' other='' print string for letter in string: #if letter.isalpha(): if letter.isupper(): upper+=letter elif letter.islower(): lower+=letter else: other+=letter print 'Upper=',upper print 'Lower=',lower print 'Other=',other upper_file=open("upper.txt",'wb') lower_file=open("lower.txt",'wb') other_file=open('other.txt','wb') upper_file.write(upper) lower_file.write(lower) other_file.write(other) upper_file.close() lower_file.close() other_file.close()
17544229d9f5c1a697ec95b67c0e9410f50d2b46
psukhomlyn/HillelEducation-Python
/Lesson2/HW-2-password_validator.py
985
4.5
4
""" password validation rules: 1. password should be 8 characters or more 2. password cannot contain spaces 3. password should include at least 1 digit and 1 special symbol (Shift+digit on keyboard) """ import string password: str = input('Enter password: ') is_digit_found = False is_symbol_found = False if len(password) < 8: print('Invalid password. Password should be at least 8 characters.') elif ' ' in password: print('Invalid password. Password cannot include spaces.') else: for char in password: if char in string.digits: is_digit_found = True elif char in {'!','@','#','$','%','^','&','*','(',')'}: is_symbol_found = True if is_digit_found and is_symbol_found: print('Password is valid') break if not is_digit_found: print('Invalid password. Password should include a digit.') if not is_symbol_found: print('Invalid password. Password should include a symbol.')
0a55cd4dac118fd9d72b1a9348c8433eeee13957
harshavachhani/python_intermediate_project
/q03_create_3d_array/build.py
186
3.84375
4
# Default Imports import numpy as np # Enter solution here def create_3d_array(): n=3*3*3 array_a = np.array(range(n)) array_a = array_a.reshape((3,3,3)) return array_a
3badd4865b7411d18df907d258f6ccf6a29cb0b8
luisalcantaralo/Tarea-02
/porcentajes.py
575
3.96875
4
#encoding: UTF-8 # Autor: tuNombreCompleto, tuMatricula # Descripcion: Texto que describe en pocas palabras el problema que estás resolviendo. # A partir de aquí escribe tu programa mujeres = int(input("Mujeres inscritas: ")) hombres = int(input("Hombres inscritos: ")) total = mujeres + hombres porcentajeMujeres = round((mujeres / total)* 100, 1) porcentajeHombres = round((hombres / total)* 100, 1) print("Total de inscritos: ", total) print("Porcentaje de mujeres: ", porcentajeMujeres, "%", sep="") print("Porcentaje de hombres: ", porcentajeHombres, "%", sep="")
3d9e57b9640d52849b8be5622bbc4a178658b9d1
snaveen1856/Test_project
/emp_open.py
968
3.671875
4
# Writing a file(Bonus.txt) with only one file (name) as input name=input('Enter file name bonus: ') b=open(name,'w') # first it will create file with user give name then take input as filename fname=input('Enter file name:') with open(fname) as f: data=f.readlines() # Here it will read data line by line for row in data: # Here it make loop to read and separate the data into feilds row=row.rstrip('\n') feilds=row.split(',') empid=feilds[0] job=feilds[2] salary=int(feilds[3]) if job=='Manager': bonus=round(0.25*12*salary) if job=='Salesman': bonus=round(0.20*12*salary) if job=='Clerk': bonus=round(0.15*12*salary) rec=empid+','+job+','+str(salary)+','+str(bonus)+'\n' b.write(rec) print(rec) opt=input('Write another record [y/n]: ') if opt in('n','N'): break
577f5aed445c5bf4e790d0174183f7481ebee6a8
SeanLeCornu/Coding-Notes
/4. Python - DataCamp/1. Intro to Python/1.4 NumPy Stats.py
436
3.65625
4
import numpy as np # numpy has lots of inbuilt mathematical functions such as mean and median np_2d = np.array([[1.7, 1.6, 1.8, 2], [65, 59, 88, 93]]) print("Mean:", np.mean(np_2d[1])) print("Median:", np.median(np_2d[0])) # other common functions include correlation coefficient, np.corrcoef and standard deviation np.std # as there is only one data type in the array these calculations are much quicker than they are in base python
f7e13e224c49e4d71fb286ee3b6aaf2efb42027a
daniel-reich/ubiquitous-fiesta
/Pjffmm9TTr7CxGDRn_3.py
784
3.78125
4
def is_ascending(s): def group_by_size(string, size): if len(string) == size: return [string] elif len(string) < size: return ['XX'] else: return [string[:size]] + group_by_size(string[size:], size) def ascending(group, index = 0, previous = None): if previous == None: previous = int(group[index]) return ascending(group, index+1, previous) else: if index == len(group): return True elif int(group[index]) != previous + 1: return False else: return ascending(group, index + 1, int(group[index])) poss_groups = [group_by_size(s,n) for n in range(1, len(s) // 2 + 1) if 'XX' not in group_by_size(s,n)] asc = [ascending(group) for group in poss_groups] return True in asc
c15ba12a1fe7b9f756395a3468008a8cbac8fa4e
navarrjl/scientific_computing_python_projects
/time_calculator/time.py
3,224
3.984375
4
import math def add_time(cur_time, time_add, day_of_week=" "): current_time, period = cur_time.split(' ') current_hour, current_minute = current_time.split(':') hour_to_add, minutes_to_add = time_add.split(':') day_of_week = day_of_week.lower() days_of_the_week = ["saturday", "sunday", 'monday', "tuesday", "wednesday", "thursday", "friday"] if period == "AM": periods = 0 elif period == "PM": periods = 1 # converting the hours into minutes and casting the minutes total_minutes_std_hour = (int(current_hour.strip()) * 60) total_minutes_add_hours = (int(hour_to_add.strip()) * 60) std_minutes = int(current_minute.strip()) add_minutes = int(minutes_to_add.strip()) # total of hours combined total_minutes = int(total_minutes_std_hour + total_minutes_add_hours + std_minutes + add_minutes) total_minutes_left = int ((total_minutes_std_hour + total_minutes_add_hours + std_minutes + add_minutes) % 60) total_hours = total_minutes / 60 periods += math.ceil(total_hours / 12) period_indicator = ' ' if periods % 2 != 0: period_indicator = "AM" else: period_indicator = "PM" # data that will be printed in the clock clock_minutes = total_minutes_left if clock_minutes < 10: clock_minutes = '0' + str(clock_minutes) clock_hour = total_hours days = periods / 2 day_message = 0 if clock_hour >= 12: clock_hour = clock_hour % 12 if (period_indicator == "PM" or period_indicator == "AM") and int(clock_hour) == 0: clock_hour = 12 if float(days) <= 1: day_message = "" elif float(days) > 1 and days <= 2: day_message = "(next day)" elif days > 2: day_message = f"({str(int(days))} days later)" if day_of_week not in days_of_the_week: if day_message == "": returning_data = f"{str(int(clock_hour))}:{str(clock_minutes)} {period_indicator}" else: returning_data = f"{str(int(clock_hour))}:{str(clock_minutes)} {period_indicator} {day_message}" else: days = math.ceil(days) if day_of_week == "monday": day = (1 + days) % 7 day_of_week = days_of_the_week[day].capitalize() elif day_of_week == "tuesday": day = (2 + days) % 7 day_of_week = days_of_the_week[day].capitalize() elif day_of_week == "wednesday": day = (3 + days) % 7 day_of_week = days_of_the_week[day].capitalize() elif day_of_week == "thursday": day = (4 + days) % 7 day_of_week = days_of_the_week[day].capitalize() elif day_of_week == "friday": day = (5 + days) % 7 day_of_week = days_of_the_week[day].capitalize() elif day_of_week == "saturday": day = (6 + days) % 7 day_of_week = days_of_the_week[day].capitalize() else: day = days % 7 day_of_week = days_of_the_week[day].capitalize() returning_data = f"{str(int(clock_hour))}:{str(clock_minutes)} {period_indicator}, {day_of_week} {day_message}" return returning_data
ae5aa91b9e74acea9a642444324a6f07f263f5a1
Usernam-kimyoonha/python
/12.py
338
3.9375
4
x = 3 y = 1 if x > y : # 3이 1보다 크면 print("x(3)는 y(1)보다 크다.") #출력이 된다. print("x가 y보다 크기(True)때문에 출력 된다.","\n") if x < y : # y가 x보다 크지 않다. print("x보다 y가 크다") # 출력이 안된다. print("y가 x보다 크지 않기(False)때문에 출력 안된다.","\n")
374c5ee25d60f2c91470f5e58e8f96b26b4dfdce
sounmind/problem-solving-programmers
/level_1/Pg_12825.py
367
3.75
4
# https://programmers.co.kr/learn/courses/30/lessons/12925 def solution(s): answer = 0 if s[0].isalpha(): if s[0] == "+": answer = int(s[1:]) else: answer = -int(s[1:]) else: answer = int(s) return answer print(solution("1234")) print(solution("-134")) print(solution("+124")) print(solution("234"))
5af1a8a0d5c5184c9a95ee3cd12ac22332db81f4
buwenzheng/Study
/python-study/python-basics/6-OdjectOrientedProgramming/5_getObjectMsg.py
5,531
3.78125
4
# !/user/bin/env python3 # -*- conding: utf-8 -*- # 获取对象信息 # type()获取对象的类型,基本类型都可以用type(),来判断 type(123) # 输出 <class 'init'> type(abs) # <class 'builtin_function_or_method'> # 但是type()函数返回的是什么类型?它返回对应的Class类型。如果我们要在if语句中判断,就需要比较两个变量的type类型是否相同 type(123)==type(456) # True type(123)==int # True type('abc')==type('123') # True type('abc')==str # True type('abc')==type(123) # False # 判断基本数据类型可以直接写int,str等,但是如果要判断一个对象是否是函数怎么办?可以使用types模块中定义的常量: import types def fn(): pass type(fn) == types.FunctionType # True type(abs) == types.BuiltinFunctionType # True type(lambda x: x)==types.LambdaType # True type((x for x in range(10)))==types.GeneratorType # True # 使用isinstance() # 对于class的继承关系来说,使用type()就很不方便。我们要判断class的类型,可以使用isinstance()函数 # isinstance()可以告诉我们,一个对象是否是某种类型。先创建3种类型的对象 class Animal(object): def run(self): print('Animal is running') class Dog(Animal): def run(self): print('Dog is running') class Cat(Dog): def run(self): print('Cat is running') a = Animal() d = Dog() c = Cat() print(isinstance(a, Animal)) # True print(isinstance(c, Dog)) # True print(isinstance(c, Animal)) # True # 能用type()判断的基本类型也可以用isinstance()判断 isinstance('234', str) # True # 并且还可以判断一个变量是否是某些类型中的一种,比如下面的代码就可以判断是否是list或者tuple isinstance(([1,2,3]), (list, tuple)) # True # 使用dir() dir('asd') # ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] # 类似__xxx__的属性和方法在Python中都是有特殊用途的,比如__len__方法返回长度。在Python中,如果你调用len()函数试图获取一个对象的长度,实际上,在len()函数内部,它自动去调用该对象的__len__()方法,所以,下面的代码是等价的 len('abc') # 3 'abc'.__len__ # 3 # 我们自己写的类,如果也想用len(myObj)的话,就自己写一个__len__()方法 class myDog(object): def __len__(self): return 12 dog = myDog() print(len(dog)) # 12 # 剩下的都是普通属性或方法,比如lower()返回小写的字符串 'ABC'.lower() # 'abc' # 仅仅把属性和方法列出来是不够的,配合getattr(),setattr(),hasattr(),可以直接操作一个对象的状态 class MyObject(object): def __init__(self): self.x = 6 def power(self): return self.x * self.x obj = MyObject() hasattr(obj, 'x') # 是否有属性'x' # True hasattr(obj, 'y') # 是否有'y' # False setattr(obj, 'y', 19) # 设置一个属性'y' hasattr(obj, 'y') # True obj.y # 此时设置了属性y # 19 # 如果试图获取不存在的属性,会抛出AttributeError的错误 getattr(obj, 'z') # 获取属性'z' # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # AttributeError: 'MyObject' object has no attribute 'z' # 可以传入一个default参数,如果属性不存在,就返回默认值 getattr(obj, 'z', 404) # 获取属性'z',如果不存在的话就返回404 # 也可以获取对象的方法 hasattr(obj, 'power') # 确认有无 getattr(obj, 'power') # 获取对象的power方法 # 小结 # 通过内置的一系列函数,我们可以对任意一个Python对象进行剖析,拿到其内部的数据。要注意的是,只有在不知道对象信息的时候,我们才会去获取对象信息。如果可以直接写: # sum = obj.x + obj.y # 就不要写: # sum = getattr(obj, 'x') + getattr(obj, 'y') # 一个正确的用法的例子如下: # def readImage(fp): # if hasattr(fp, 'read'): # return readData(fp) # return None # 假设我们希望从文件流fp中读取图像,我们首先要判断该fp对象是否存在read方法,如果存在,则该对象是一个流,如果不存在,则无法读取。hasattr()就派上了用场。 # 请注意,在Python这类动态语言中,根据鸭子类型,有read()方法,不代表该fp对象就是一个文件流,它也可能是网络流,也可能是内存中的一个字节流,但只要read()方法返回的是有效的图像数据,就不影响读取图像的功能
9649c5ed3408179b73b222d0a691598dfaf1699d
wasymshykh/ai-ml-course-practice
/artificial-intelligence-work/final-term-practice/csp/Variable.py
222
3.53125
4
class Variable: def __init__(self, name): self._name = name def get_name(self): return self._name def __eq__(self, other): other: Variable return self._name == other.get_name()
11d95f94377f889dae7675eaa47d55b7178c8b3c
fatima-a-khan/ITM200-IntroToProgramming
/poly1.py
581
3.578125
4
#poly.py #Author: Fatima Khan #Input s = input("Enter input such as a=10, b=5, c=1, x=1: \n"); s = s.lower(); #Parse operands i1 = s.find('a'); i2 = s.find(','); ai = s[i1+2:i2].strip(); a = float(ai); o1 = s.find('b'); o2 = s.find(',', i2+1); bo = s[o1+2:o2].strip(); b = float(bo); p1 = s.find('c'); p2 = s.find(',', o2+1); cp = s[p1+2:p2].strip(); c = float(cp); m1 = s.find('x'); xm = s[m1+2:].strip(); x = float(xm); #Calculate z using ax^2+bx+c z = ((a*(x**2)) + (b*x) + c); #Print output print("a: ", a); print("b: ", b); print("c: ", c); print("x: ", x); print("z: ", z);
6d31371a7564e22fa29c69cebe8896b117c8f073
zhuwhr/interview
/snippets/prim.py
1,779
3.890625
4
""" quite similar to dijkstra find shortest path from start node to all nodes prim vs dijkstra: 都是通过贪心的算法用BFS dijkstra找的是最短路径,在发现环的时候,要对比最短路径是不是有变化,然后更新 prim是发现环的时候就不管它,找的是从根开始到每个点的最小总和,并不一定是到每个点的最短路径 """ import heapq def prim(graph, costs, start): items = {} pq = [] for i in graph.keys(): if i == start: continue item = [float('inf'), i] items[i] = item pq.append(item) heapq.heapify(pq) start_item = [0, start] heapq.heappush(pq, start_item) pre = {start: None} visited = set() while pq: _, u = heapq.heappop(pq) visited.add(u) for v in graph[u]: if v not in visited and costs[u, v] < items[v][0]: items[v][0] = costs[u, v] pre[v] = u heapq._siftdown(pq, 0, pq.index(items[v])) return pre def make_undirected(cost): ucost = {} for k, w in cost.items(): ucost[k] = w ucost[(k[1],k[0])] = w return ucost if __name__=='__main__': # adjacent list graph = { 1: [2,3,6], 2: [1,3,4], 3: [1,2,4,6], 4: [2,3,5,7], 5: [4,6,7], 6: [1,3,5,7], 7: [4,5,6]} # edge costs cost = { (1,2):7, (1,3):9, (1,6):14, (2,3):10, (2,4):15, (3,4):11, (3,6):2, (4,5):6, (5,6):9, (4,7):2, (5,7):1, (6,7):12} cost = make_undirected(cost) s= 1 predecessors = prim(graph, cost, s) print(predecessors)
9ee96b1a3baec5dbfd3e4d0a020a26667353dc8a
dandubovoy/DPV
/chap1/modulo_expo.py
519
3.6875
4
from readint import readinput def modular_exp(x, y, N): """ given two n-bit integers x and N, an integer exponent y output: x^y mod N """ if y == 0: return 1 z = modular_exp(x, y//2, N) if y % 2 == 0: return (z*z) % N else: return (x*z*z) % N def main(): print ("X^Y % N") x = readinput("X") y = readinput("Y") N = readinput("N") ans = modular_exp(x, y, N) print ("(%d^%d) %% %d = %d" % (x, y, N, ans)) if __name__ == '__main__': main()
6a230e0e26e8b1992c6d2652b55a8860b75154b5
nivleM-ed/WIA2005_Algorithm_Assignment
/main.py
4,325
3.609375
4
import copy from time import sleep from Map import airports, dijkstra, getAirports, plotMap, getPossibleRoutes from Words import Analysis, plotAllWords, plotNegVPos, plotStopwords def compare(p, n): if p > n: print("The country have positive political situation.") elif p == n: print("The country has an average political situation.") else: print("The country have negative political situation.") def getBestFlight(shortest_path, distance, probability): best_flight = {} best_flight2 = {} last = distance[len(distance)-1] for x in range(len(shortest_path)): distance_score = ((float(last)-float(distance[x]))/float(last))*70 y = 0 while shortest_path[x][1] != probability[y]['name']: y+=1 if probability[y]['positive'] > probability[y]['negative'] or probability[y]['positive'] == probability[y]['negative']: positive_score = probability[y]['positive'] - probability[y]['negative'] else: positive_score = -(2*probability[y]['negative']) total_score = distance_score + positive_score best_flight2["path"] = shortest_path[x] best_flight2["distance"] = distance[x] best_flight2["positive"] = probability[y]['positive'] best_flight2["negative"] = probability[y]['negative'] best_flight2["score"] = int(total_score) best_flight[x] = copy.deepcopy(best_flight2) return arrangeBest(best_flight) def arrangeBest(best_flight): n = len(best_flight) gap = n//2 while gap > 0: for i in range(gap,n): # add a[i] to the elements that have been gap sorted # save a[i] in temp and make a hole at position i temp = best_flight[i] # shift earlier gap-sorted elements up until the correct # location for a[i] is found j = i while j >= gap and best_flight[j-gap]["score"] < temp["score"]: best_flight[j] = best_flight[j-gap] j -= gap # put temp (the original a[i]) in its correct location best_flight[j] = temp gap //= 2 return best_flight shortest_paths = {} shortest_paths_str = {} distance = {} latitude = {} longitude = {} print("Retrieving airports from database...") airport_array = getAirports() probability = Analysis() for x in range(len(airports)): print(x+1,". ",airports[x]) print("\nEnter airport according to number:") print("Origin: ", airports[0]) goal = input("Goal: ") print("You chose", airports[int(goal)-1]) print("Showing the 10 best routes of",getPossibleRoutes(),"possible routes\n") shortest_paths_str, shortest_paths, distance, latitude, longitude = dijkstra(airport_array, airports[0], airports[int(goal)-1]) # print(shortest_paths) # for x in range(len(shortest_paths_str)): # print("Route ",x+1,": ",shortest_paths_str[x]) # print("Distance: ", distance[x]),"\n" best_flight = getBestFlight(shortest_paths, distance, probability) for x in range(len(best_flight)): print("Route",x+1,":",best_flight[x]["path"]) print("Distance:", best_flight[x]["distance"],"\tPositive percentage: ", best_flight[x]["positive"],"\tNegative percentage: ", best_flight[x]["negative"]) compare(best_flight[x]["positive"],best_flight[x]["negative"]) print("\n") yesChoice = ['yes','y'] noChoice = ['no', 'n'] user_in = input("Would you like to view the routes before the best route algorithm:(y/n): ") if user_in in yesChoice: print("Getting routes...") for x in range(len(shortest_paths)): print(x,".",shortest_paths[x]) user_in = input("\nWould you like to view the map(y/n): ") if user_in in yesChoice: print("Plotting map with best routes...") plotMap(latitude, longitude) user_in = input("\nWould you like to view graph of negative and positive words:(y/n) ") if user_in in yesChoice: print("Plotting graph on plot.ly...") plotNegVPos() user_in = input("\nWould you like to view graph of all words:(y/n) ") if user_in in yesChoice: print("Plotting graph on plot.ly...") plotAllWords() user_in = input("\nWould you like to view graph of stopwords:(y/n) ") if user_in in yesChoice: print("Plotting graph on plot.ly...") plotStopwords()
34e1943fb795e8889cc1a61e50ad6cdfc219dcef
karchi/codewars_kata
/已完成/Find Maximum and Minimum Values of a List.py
1,570
4.03125
4
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' # Find Maximum and Minimum Values of a List题目地址:http://www.codewars.com/kata/577a98a6ae28071780000989/train/python ''' import unittest class TestCases(unittest.TestCase): def test1(self):self.assertEqual(min([-52, 56, 30, 29, -54, 0, -110]), -110) def test2(self):self.assertEqual(min([42, 54, 65, 87, 0]), 0) def test3(self):self.assertEqual(min([1, 2, 3, 4, 5, 10]), 1) def test4(self):self.assertEqual(min([-1, -2, -3, -4, -5, -10]), -10) def test5(self):self.assertEqual(max([-52, 56, 30, 29, -54, 0, -110]), 56) def test6(self):self.assertEqual(min([9]), 9) def test7(self):self.assertEqual(max([4,6,2,1,9,63,-134,566]), 566) def test8(self):self.assertEqual(max([5]), 5) def test9(self):self.assertEqual(max([534,43,2,1,3,4,5,5,443,443,555,555]), 555) def test10(self):self.assertEqual(max([9]), 9) def min(arr): # return min(arr) return sorted(arr)[0] def max(arr): # return max(arr) return sorted(arr)[-1] if __name__ == '__main__': unittest.main() ''' 参考解法: pass 解法2: class assert_equals(): def min(arr): return min(arr) def max(arr): return max(arr) 解法3: def max(arr): temp = __builtins__.max(arr) ##builtin used because naming conflict with func return temp def min(arr): temp = __builtins__.min(arr) return temp 解法4: import builtins def min(arr): return builtins.min(arr) def max(arr): return builtins.max(arr) '''
a731325eb1221231ccdd918e2fa620f7a07b2d1b
bikashkrgupta/Blockchain
/complete_blockchain.py
2,479
3.984375
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 26 13:12:15 2020 @author: Kiit1705576 """ blockchain=[] def get_last_value(): return(blockchain[-1]) def add_value(transaction_amount,last_transaction=blockchain[-1]): blockchain.append([[last_transaction],transaction_amount]) def get_transaction_value(): user_value=float(input('Enter your transaction Amount')) return user_value def get_user_choice(): user_input=input("Please give your choice here:") return user_input def print_block(): index=0 for block in blockchain: index=index+1 print("Printing Block Number:"+str(index)+",Value="+str(block)) print("Complete Blockchain is = ") print(blockchain) def verify_chain(): index = 0 valid=True for block in blockchain: if index==0: index+=1 continue elif block[0]==[blockchain[index-1]]: valid = True else: valid=False break index+=1 return valid while True: print("Choose an option") print('Chose 1 for adding a new transaction') print('Choose 2 for printing the blockchain') print('Choose 3 if you want to manipulate the data') print('Chose anything else if you want to quit') user_choice=int(get_user_choice()) print(user_choice) if user_choice==1: tx_amount=get_transaction_value() add_value(tx_amount,get_last_value()) elif user_choice==2: print_block() elif user_choice==3: if len(blockchain)>=1: #blockchain[0]='A' block_value=int(input('Enter Block Number for Manipulation')) transaction_value=float(input('Enter transaction amount for Manipulation')) #blockchain[1]=[12,34] blockchain_manipulate=[] print("Original blockchain="+str(blockchain(block_value))) blockchain_manipulate=blockchain[block_value] blockchain_manipulate[-1]=transaction_value print("Manipulated blockchain = "+str(blockchain_manipulate)) blockchain[block_value]=blockchain_manipulate print(blockchain) else: print("else") break if not verify_chain(): print(blockchain) print('Blockchain manipulate') break
7bc8926e6c79bc24e3fd752e27323bb4fa517caa
radkovskaya/Algorithms
/les2/1.py
1,945
3.953125
4
# 1.Написать программу, которая будет складывать, вычитать, умножать или делить два числа. Числа и знак операции вводятся пользователем. После выполнения вычисления программа не должна завершаться, а должна запрашивать новые данные для вычислений. Завершение программы должно выполняться при вводе символа '0' в качестве знака операции. Если пользователь вводит неверный знак (не '0', '+', '-', '*', '/'), то программа должна сообщать ему об ошибке и снова запрашивать знак операции. Также сообщать пользователю о невозможности деления на ноль, если он ввел 0 в качестве делителя. while True: a = int(input("Введите первое число ")) b = int(input("Введите второе число ")) i = input("Введите знак операции. Возможные варианты *, +, - , /. При введении 0 осуществляется выход из программы ") if i == "0": break elif i == "*": print(f"Произведение чисел равно {a*b}") elif i == "+": print(f"Сумма чисел равна {a+b}") elif i == "-": print(f"Разность чисел равна {a-b}") elif i == "/": if b == 0: print(f"Делить на 0 нелья") else: print(f"Результат деления первого числа на второе равен {a/b}") else: print("Неверный знак операции")
5453db4b25bd8232c31f364493709cff4dbbec8a
nnayrb/--Python--
/CeV - Exercises/Python/jogo advinhar v1.0.py
626
3.671875
4
from random import randint from time import sleep from termcolor import colored computador = randint(0, 3) print('\033[34;40m-=-\033[m' * 20) print('Vou pensar em um número entre 0 e 8. Tente advinhar...') print('\033[34;40m-=-\033[m' * 20) jogador = int(input('Em que número eu pensei??')) #Jogador tentar advinhar print('PROCESSANDO...') sleep(3) print(' Pensei no número {}'.format(computador))#faz o computador "pensar" if jogador == computador: #orientação print('Parabens !! você conseguiu advinhar e me venceu !!') else: print('Ganhei ! de você bobão, viu como sou um AI inteligente? :P ')
22f284e9a6b764263af8656e12dc81b37a263450
JnKesh/Hillel_HW_Python
/HW15/Peter's height.py
711
3.671875
4
while True: s = list(map(int, input('Enter pupils heights: ').split())) if max(s) > 200: # Проверка списка на максимальное значение print('Only numbers between 1 and 200 are accepted, try again.') if min(s) < 1: print('Only numbers between 1 and 200 are accepted, try again.') else: break while True: r = int(input("Enter Peter's height: ")) if not 1 <= r <= 200: # Проверка числа на максимальное значение print('Only numbers between 1 and 200 are accepted, try again') else: break count = 0 for i in range(len(s)): if r <= s[i]: count += 1 print(count + 1)
f558b9da2bc8ce26578899af4e15349b63c82e78
Sly143/Criptografia
/1 Unidade/transp_linhas.py
1,844
3.765625
4
# encoding: utf-8 def railfence_id(tam, key): ''' Retorna um lista de inteiros com a posicao da linha que o caracter do texto ira ocupar, variando de 0 ate key - 1. ''' j = int(0) inc = int(0) idx = [] for i in range(tam): if j == key - 1: inc = -1 elif j == 0: inc = 1 idx.append(j) j += inc return idx def encrypt(texto, key): ''' Retorna o texto plano cifrado na cifra rail fence com a chave key. ''' texto = texto.replace(' ', '') tam = len(texto) idx = railfence_id(tam, key) cifrado = '' for i in range(key): for z in range(tam): if idx[z] == i: cifrado += texto[z] return cifrado.upper() def decrypt(texto, key): ''' Retorna o texto plano para um texto cifrado com a cifra rail fence com a chave key. ''' texto = texto.replace(' ', '') tam = len(texto) idx = railfence_id(tam, key) idx_sorted = sorted(idx) texto_plano = '' for i in range(tam): for j in range(tam): if idx[i] == idx_sorted[j] and idx[i] > -1: texto_plano += texto[j] idx[i] = -1 idx_sorted[j] = -1 return texto_plano.lower() def main(): op = int(input("Transposição de Linhas!\nDigite:\n1 - Criptografar Mensagem\n2 - Descriptografar Mensagem\n")) if op == 1: print("[Criptografar]") mensagem = input('Digite a mensagem:\n') key = int(input("Quantidade de Linhas\n")) print(encrypt(mensagem,key)) elif op == 2: print("[Descriptografar]") mensagem = input('Digite a mensagem:\n') key = int(input("Quantidade de Linhas\n")) print(decrypt(mensagem,key)) else: print('Opção Inválida!')
d2d3394728f06090dfc37375d2312652d9f32710
mtariquekhan11/PycharmProjects
/welcome Projects/factor_factorial.py
1,072
4.21875
4
# Author: Mohd Tarique Khan # Date: 14/10/2019 # Purpose: To find the factors and factorials condition = "True" def factor(n): print("The factors of ", n, "are: ") for i in range(1, n + 1): if n % i == 0: print(i) i = i + 1 def factorial(n): factorial = 1 if n == 0: print("Factorial for", n, "is 1") elif n < 0: print("Factorial for", n, "does not exist") else: for i in range(1, n + 1): factorial = factorial * i print("Factorial for", n, "is", factorial) while condition is "True": choice = int(input("Enter the your choice \n '1' for Factor, '2' for Factorial: ")) if choice == 1: num = int(input("Enter the number: ")) factor(num) elif choice == 2: num = int(input("Enter the number: ")) factorial(num) else: print("Invalid Input") break condition1 = input("Do you want to check more, Press Y or y: ") if condition1 == "y" or condition1 == "Y": condition = "True" else: break
522afa119c64845ae6e1e09af595ef88635dcfe8
JanZahalka/ii20
/ii20/data/ImageFinder.py
3,064
3.546875
4
""" ImageFinder.py Author: Jan Zahalka ([email protected]) Finds all images in specified directory (recursively) and establishes image ordering. """ import os import PIL class ImageFinder: @classmethod def find_all_images(cls, traversed_dir, image_list=[], relative_dir_path=""): """ Constructs a list of paths to images within the traversed directory (recursive, subdirectories are also searched). The paths are relative to the master directory. When calling the function from other code, explicitly setting the optional image_list and relative_dir_path parameters is strongly discouraged. They are there to ensure proper recursive functionality, so set them explicitly only if you are really sure what you are doing. Parameters ---------- traversed_dir : str (valid directory path) The directory to be traversed. image_list : list The list where the image paths are to be recorded. The default is an empty list, should not need to be set explicitly by code elsewhere. relative_dir_path : str The relative path of the current directory to the master directory. The default is "", should not need to be set explicitly by code elsewhere. """ # Establish the list of files in the directory try: file_list = os.listdir(traversed_dir) # If the list cannot be established, raise an error except OSError: err = ("ERROR: Cannot traverse the '%s' directory and find images." % traversed_dir) raise ImageFinderError(err) # Iterate over the files in the file list for file_name in file_list: # Establish the full path of the file file_path = os.path.join(traversed_dir, file_name) # If the file is a directory, traverse it if os.path.isdir(file_path): relative_subdir_path = os.path.join(relative_dir_path, file_name) image_list = cls.find_all_images(file_path, image_list, relative_subdir_path) # Else, test whether the file is an image (try opening it with # Pillow). If so, add it to the list else: try: im = PIL.Image.open(file_path) im.verify() except (OSError, ValueError, PIL.UnidentifiedImageError): continue else: im.close() relative_image_path = os.path.join(relative_dir_path, file_name) image_list.append(relative_image_path) return image_list class ImageFinderError(Exception): """ Raised whenever an error with any of the ImageFinder methods is encountered """ pass
3bffd95baafb7581cae575744256028bb4971142
salahlotfi/Python-Scripts
/CDC - Overall DeathCount.py
1,499
3.875
4
# This script is created to count the number of deaths # given diseases in a given year reported by CDC database. # The disease codes are obtained from ICDO dictionary, so you need to put # the icd_nodot script as well as database file in the same folder. The final file is a .CSV file. import icd_nodot def main() : dictionary = {} # This dictionary holds cause of death as keys and counts as values. infile = open("Mort99us.dat","r") # This is a sample CDC file, correspondeath_causes.gn to 1999. for line in infile: death_causes= line[161:301] # Character 161:301 will read the causes of death. cause_list = death_causes.split() # to split the causes with space for cause in cause_list : # for each cause a = cause[2:] # Slice and grab any character after 2. dictionary[a] = dictionary.get(a,0) + 1 # append all cauases to the dictionary. infile.close() icddictionary = icd_nodot.ICD_dictionary() # This function uses ICD dictionary with dots removed from codes to find diseases name and write it. outfile = open("CDC_out.csv","w") for key in dictionary: if (key in icddictionary): # These two lines write disease name if the code is known. Otherwise, write only the key. print(dictionary[key],",",icddictionary[key].replace(",",""),file=outfile) else: print(dictionary[key],",",key,file=outfile) outfile.close() main()
a8883f4ca635181e7d52ef488473d3808d46be23
Schnei1811/PythonScripts
/CLRS Algorithms/Class2/tkinterHeuristicTSP.py
5,480
4.09375
4
from tkinter import * from random import * from math import sqrt points = [] size = 550 def click(event): draw_point(event.x, event.y) points.append((event.x, event.y)) def draw_point(x, y): c.create_oval(x, y, x+1, y+1, fill="black", tags = "point") def draw_points(): c.delete("point", "line"); map(lambda point: draw_point(point[0], point[1]), points) def draw_line(): c.delete("line") c.create_line(points, tags="line") def clear(): global points points = [] c.delete("point", "line"); def randomise(): global points points = [] for i in range(100): points.append((randint(1,size), randint(1,size))) print(points) draw_points() def nearest_neighbour_algorithm(points): if len(points) == 0: return [] #current = choice(points) current = points[0] nnpoints = [current] points.remove(current) while len(points) > 0: next = points[0] for point in points: if dist(current, point) < dist(current, next): next = point nnpoints.append(next) points.remove(next) current = next return nnpoints def two_opt(points): for i in range(len(points) - 1): for j in range(i + 2, len(points) - 1): if dist(points[i], points[i+1]) + dist(points[j], points[j+1]) > dist(points[i], points[j]) + dist(points[i+1], points[j+1]): points[i+1:j+1] = reversed(points[i+1:j+1]) return points def three_opt(points): for i in range(len(points) - 1): for j in range(i + 2, len(points) - 1): for k in range(j + 2, len(points) - 1): way = 0 current = dist(points[i], points[i+1]) + dist(points[j], points[j+1]) + dist(points[k], points[k+1]) if current > dist(points[i], points[i+1]) + dist(points[j], points[k]) + dist(points[j+1], points[k+1]): current = dist(points[i], points[i+1]) + dist(points[j], points[k]) + dist(points[j+1], points[k+1]) way = 1 if current > dist(points[i], points[j]) + dist(points[i+1], points[j+1]) + dist(points[k], points[k+1]): current = dist(points[i], points[j]) + dist(points[i+1], points[j+1]) + dist(points[k], points[k+1]) way = 2 if current > dist(points[i], points[j]) + dist(points[i+1], points[k]) + dist(points[j+1], points[k+1]): current = dist(points[i], points[j]) + dist(points[i+1], points[k]) + dist(points[j+1], points[k+1]) way = 3 if current > dist(points[i], points[j+1]) + dist(points[k], points[i+1]) + dist(points[j], points[k+1]): current = dist(points[i], points[j+1]) + dist(points[k], points[i+1]) + dist(points[j], points[k+1]) way = 4 if current > dist(points[i], points[j+1]) + dist(points[k], points[j]) + dist(points[i+1], points[k+1]): current = dist(points[i], points[j+1]) + dist(points[k], points[j]) + dist(points[i+1], points[k+1]) way = 5 if current > dist(points[i], points[k]) + dist(points[j+1], points[i+1]) + dist(points[j], points[k+1]): current = dist(points[i], points[k]) + dist(points[k], points[i+1]) + dist(points[j], points[k+1]) way = 6 if current > dist(points[i], points[k]) + dist(points[j+1], points[j]) + dist(points[i+1], points[k+1]): current = dist(points[i], points[k]) + dist(points[j+1], points[j]) + dist(points[i+1], points[k+1]) way = 7 if way == 1: points[j+1:k+1] = reversed(points[j+1:k+1]) elif way == 2: points[i+1:j+1]= reversed(points[i+1:j+1]) elif way == 3: points[i+1:j+1],points[j+1:k+1] = reversed(points[i+1:j+1]),reversed(points[j+1:k+1]) elif way == 4: points = points[:i+1] + points[j+1:k+1] + points[i+1:j+1] + points[k+1:] elif way == 5: temp = points[:i+1] + points[j+1:k+1] temp += reversed(points[i+1:j+1]) temp += points[k+1:] points = temp elif way == 6: temp = points[:i+1] temp += reversed(points[j+1:k+1]) temp += points[i+1:j+1] temp += points[k+1:] points = temp elif way == 7: temp = points[:i+1] temp += reversed(points[j+1:k+1]) temp += reversed(points[i+1:j+1]) temp += points[k+1:] points = temp return points def dist(a, b): return sqrt(pow(a[0] - b[0], 2) + pow(a[1] - b[1], 2)) def distance(points): if len(points) == 0: return 0 distance = 0 for i in range(len(points) - 1): distance += dist(points[i], points[i + 1]) return distance def optimisation_click(algorithm): global points points = algorithm(points) draw_line() v.set(int(distance(points))) root = Tk() root.title("TSP - Visualizer [Nemanja Trifunovic br. ind.:346/2010]") root.resizable(0,0) c = Canvas(root, bg="white", width = size, height = size) c.configure(cursor="crosshair") c.pack() c.bind("<Button-1>", click) Button(root, text = "Clear", command = clear).pack(side = LEFT) Button(root, text = "Randomise", command = randomise).pack(side = LEFT) Button(root, text = "Nearest Neighbour", command = lambda : optimisation_click(nearest_neighbour_algorithm)).pack(side = LEFT) Button(root, text = "2-OPT", command = lambda : optimisation_click(two_opt)).pack(side = LEFT) Button(root, text = "3-OPT", command = lambda : optimisation_click(three_opt)).pack(side = LEFT) v = IntVar() Label(root, textvariable = v).pack(side = RIGHT) Label(root, text = "dist:").pack(side = RIGHT) root.mainloop()
97c41771bfc591b6ec7af42a2e3fce0e6473de32
jhirniak/pizza-for-students
/data_engine/geometry.py
1,909
3.84375
4
class Point: def __init__(self, x, y): self.x, self.y = float(x), float(y) def distance(self, other): return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5 def add(self, other): return Point(self.x + other.x, self.y + other.y) def midpoint(self, other): return Point((self.x + other.x) / 2.0, (self.y + other.y) / 2.0) def in_radius_distance(self, centre, radius): return self.distance(centre) <= radius def location(self): return Point(self.x, self.y) class Square: def __init__(self, p0, p1): self.xmin = min([p0.x, p1.x]) self.xmax = max([p0.x, p1.x]) self.ymin = min([p0.y, p1.y]) self.ymax = max([p0.y, p1.y]) def contains(self, point): return self.xmin <= point.x and point.x <= self.xmax \ and self.ymin <= point.y and point.y <= self.ymax class Circle: def __init__(self, centre, radius): self.centre = centre self.radius = radius def contains(self, point): return self.centre.distance(point) <= self.radius class Infinity: def __init__(self): pass def contains(self, point): return True class Area: def __init__(self, convex): self.convex = convex def centre(self): common = [self.convex[i].x * self.convex[i+1].y \ - self.convex[i+1] * self.convex[i].y \ for i in range(len(self.convex))] area = 0.5 * sum(common) x = 1.0 / 6.0 / area * sum([ (self.convex[i].x + self.convex[i+1].x) * common[i] \ for i in range(len(self.convex)) ]) y = 1.0 / 6.0 / area * sum([ (self.convex[i].y + self.convex[i+1].y) * common[i] \ for i in range(len(self.convex)) ]) return Point(x, y) def contains(self, point): pass
20cda797e60043083dbff471c9bbdb3e8cdbdb86
prateekvishnu/Numpy_practice
/Basic Operations.py
1,288
3.875
4
import numpy as np a = np.array([20, 50, 70, 40]) b = np.arange(10, 50, 10) c = a-b print c # power of each element print c**2 #sin fuction print 10*np.sin(c) #Returns a bool type array - returns True if value less tha n25 else returns False print c<25 # Element-wise and Matrix Multiplication A = np.array( [[1,1], [0,1]] ) B = np.array( [[2,0], [3,4]] ) print "Element wise Multiplication" print A*B print #Matix Multiplication print "Method 1" print A.dot(B) print print "Method 2" print np.dot(A,B) # operations like += and *= a = np.ones((2,3), dtype=int) b = np.random.random((2,3)) print "b" print b a *= 3 b += a #a+=b won't work as a is of interger type to do such operations use different variable name eg: c = a+b # Sum, Min and Max Functions print print "sum" print b.sum() print "min" print b.min() print "max" print b.max() #axis parameter print print "axis parameter" c = np.arange(12).reshape(3,4) print "axis=0 => Coloumn" print c.sum(axis=0) print "axis=1 => Row" print c.min(axis=1) #cumulative sum print "Cumulative Sum" print c.cumsum(axis=1) # Universal Fuctions d=np.arange(3) print "exp value of each element" print np.exp(d) # Similar functions - exp, sqrt, sin, cos, add e = np.array([2., -1., 4.]) print "Adding two arrays" print np.add(d,e)
22d35a0bc6494d700c653d17caf9d087c83a73f7
shu6h4m/Python_Assignments
/A3_Control Constructs.py
2,946
4.21875
4
''' Assignment_3 Program to perform following tasks: 1) Takes input from user and save it to n 2) Print Prime Numbers and their count between 1 and n. 3) Print Even And Odd Numbers between 1 to n. Submitted by Subham Sharma IDE Used:- https://www.onlinegdb.com/ :) ''' def printp(n): #Defining function to print prime numbers ''' Purpose : To print prime numbers between 1 and n Input: n : Takes an integer value as an input. Output: Print prime numbers between 1 And n and there count. ''' count = 0 #Declare variable count to keep track of total no.of prime numbers between 1 and n print("Prime numbers between 1 and ",n, " are :- ",end=""); for i in range(2, n + 1): # Skip 1 as it is neither prime nor composite # Declare flag variable to tell if i is prime number or not flag = 1; #Run for loop from j = 2 to half of i and then divide i by j and if remainder is 0 then i is not prime. for j in range(2, ((i // 2) + 1), 1): if (i % j == 0): # Division to check for not prime flag = 0;# Set flag variable to 0 to tell that i is not prime break; # Loop is terminated using the break statement # flag = 1 means i is prime and flag = 0 means i is not prime if (flag == 1): print(i, end = " "); # Prints the prime number i count = count + 1 #Increment count by 1 when i is prime print() # Move control to next line print("Total Prime numbers between 1 and ",n, " are :- ",count); print(''' --------------------------- ''') # Defining function to print even and odd numbers def print_e_o(n): ''' Purpose : This function is designed to print even and odd numbers between 1 and n Input: n : Takes an integer value as an input. Output: Prints even and odd numbers. ''' # Print display message print("Even numbers between 1 and ",n, " are :> ",end=""); for i in range(1, n + 1): #Traversing each number from 1 to n with the help of for loop if (i % 2 == 0): # Division to check for number i is even number print(i, end = " "); # Prints the even number i print() # Move control to next line # Print display message print("Odd numbers between 1 and ",n, " are :> ",end=""); for i in range(1, n + 1): #Traversing each number from 1 to n with the help of for loop if (i % 2 != 0): # Division to check for number i is odd number print(i, end = " "); # Prints the odd number i # Defining main function def main(): n = int(input("Enter Any Number n :")) # Taking user input printp(n) # Calling function to print prime numbers print_e_o(n) # Calling function to print even and odd numbers # Calling main function if __name__ == "__main__": main()
40e8b918ea19f3b7e7c82eb6ddaaef59c5aa8a78
Pa1245/Coding_Practice
/Python/ProjectEuler/PrimeNumbers/sum_of_primes.py
894
3.796875
4
import math import timeit def isPrime(number): if number == 1: return False elif number<4: return True elif number%2 == 0: return False elif number < 9: return True elif number%3 == 0: return False else: limit = math.sqrt(number) i = 5 while i <= limit: if number%i == 0: return False if number%(i+2) == 0: return False i = i+6 return True def main(): start_time = timeit.default_timer() total = 5 limit = 2000000 i = 5 while i <= limit: if isPrime(i): total = total + i i = i+2 if i <= limit and isPrime(i): total = total+i i = i+4 elapsed = timeit.default_timer() - start_time print total print elapsed if __name__ == '__main__': main()
32dc69bc9381b24568227fb5b08ad8a01d35c098
jonborg/IASD
/uninformed.py
878
3.9375
4
from uninformed2 import * # trying to implement uniform cost, this way we can garantee optimality with # a resonable complexity def choose_next_node(open_list, closed_list): """Apply Uniform cost algorithm to choose next node/step in tree""" selected_node = open_list[0] minimum_cost = selected_node.gx for node in open_list: # select the node with the minimum cost if node.gx < minimum_cost: minimum_cost = node.gx selected_node = node # send nodes with the same state but with higher cost to closed list for node in open_list: if ( (node.state_space[:2] == selected_node.state_space[:2]) and (node != selected_node) ): closed_list.append(node) # just doing refular BFS for debugging selected_node = open_list[0] open_list.remove(selected_node) return selected_node
1d0b78af74837cb98625fc3c3f0370a97bb33958
danieka/grupdat
/3/longest.py
269
4.09375
4
def longest(s): words = s.split() longest_word = "" for word in words: if len(word) > len(longest_word): longest_word = word return longest_word with open("/home/daniel/Code/grupdat/3/dikt.txt") as f: s = f.read() print(longest(s)) print("Nu filer stängd")
7de5999f1a7faa2fd0d869266bb88a69c17da302
Rookiee/Python
/Python2.7/mile_trans_kilomettet.py
317
3.671875
4
def MileTransKilo(): input_str = raw_input("Input mile or kilo: ") if input_str[-1] in ['K','k']: m = eval(input_str[0:-1]) / 0.62 print ("The result is %f miles." %m) elif input_str[-1] in['M','m']: k = eval(input_str[0:-1]) * 0.62 print (" %f kilo ." %k) else: print "Input error" MileTransKilo()
d06b425e784066c68ff4f82bcafdf5603c24c576
9hafidz6/self-projects
/hacker rank/newyearchaos.py
1,730
3.84375
4
#!/bin/python3 # did not manage to pass all test cases import math import os import random import re import sys # # Complete the 'minimumBribes' function below. # # The function accepts INTEGER_ARRAY q as parameter. # def swap(index1,index2,elem,res): # check if can swap ie, 2 positions max # use remove and insert # index1 is the original # index2 is the final swapNum = index1 - index2 temp = elem[index1] elem.remove(elem[index1]) # print(elem) elem.insert(index2,temp) # print(elem) res += swapNum return elem,res def minimumBribes(q): # Write your code here # assuming initial queue is ordered ie. 1 2 3 4 5 etc res = 0 elem = [] for i in range(len(q)): elem.append(i+1) # fill the elem list with initial ordered numbers # can start comparing with ordered with final pattern for j in range(len(q)): if elem[j] != q[j]: # means there is a swap, can only swap to front # give the index of supposed and current index index1 = elem.index(q[j]) index2 = elem.index(elem[j]) # print(f"interation {i}, index 1:{index1} index 2:{index2}") if (index1-index2) > 2: print("Too chaotic") return 0 else: elem,res = swap(index1,index2,elem,res) # num1 = elem[i] # num2 = q[i] # elem = swap(num1,num2,elem) else: continue print(res) if __name__ == '__main__': t = int(input().strip()) for t_itr in range(t): n = int(input().strip()) q = list(map(int, input().rstrip().split())) minimumBribes(q)
8467c79b2da6ec9b0381450db8caf0e4f78e3502
SMMend/PythonLab
/slicing.py
1,400
4.0625
4
text = "My GitHub handle is @shannonturner and my Twitter handle is @svt827" # Let's extract the GitHub handle using str.find() and slicing. snail_index = text.find('@') print text[snail_index:snail_index + 14] # So the first slicing index is given by the variable, but we're still relying on knowing the exact number of characters (14). We can improve this. space_after_first_snail_index = text[snail_index:].find(' ') # Note that we're using slicing here to say start the .find() after the first snail is found. print text[snail_index:snail_index + space_after_first_snail_index] # Why do we need to add snail_index to the second slicing index? Take a look: print "snail_index is: ", snail_index print "space_after_first_snail_index is: ", space_after_first_snail_index print "So this is essentially saying text[20:34], see? --> ", text[20:34] # Instead of creating a separate variable, you can just add the str.find() that gives the number you want right into the slice, like this: print text[text.find('@'):text.find('@')+text[text.find('@'):].find(' ')] # But as you can see, it's not the most readable, especially compared to above. # Still, it's a fairly common syntax / notation, so it's worth being familiar with it and knowing what it looks like in case you run into it. print "Can you use slicing and string methods like str.find() to extract the Twitter handle from text?"
97e551318a5d4175393e2ae253fccb9935adbdf5
AP-MI-2021/lab-3-AlexandruGirlea01
/main.py
7,339
4.0625
4
def tipareste_meniu(): print("1. Citire date") print("2. Cea mai lunga secventa in care toate elementele sunt patrate perfecte") print("3. Cea mai lunga secventa in care toate elementele au acelasi numar de biti de 1 in reprezentarea binara") print("4. Cea mai lunga secventa in care toate elementele sunt pare") print("5. Iesire") def citeste_lista(lista: list) -> list[int]: """ Citeste de la tastatura elementele unei liste :param lista: lista care trebuie citita de la tastatura :return: lista cu elemente citite de la tastatura """ numar_elemente = int(input("Dati numarul de elemente ale liste: ")) for i in range(numar_elemente): lista.append(int(input("Lista["+str(i)+"]= "))) return lista def is_perfect_square(n: int) -> bool: """ Verifica daca un numar este patrat perfect sau nu :param n: Numarul care trebuie verificat :return: True daca numarul este patrat perfect sau False in caz contrar """ for i in range(1, n+1): if i*i == n: return True elif i*i > n: return False def test_is_perfect_square(): assert(is_perfect_square(16)) is True assert(is_perfect_square(10)) is False assert (is_perfect_square(100)) is True def toate_elementele_patrate_perfecte(lista: list) -> bool: """ Verifica daca toate elementele unei liste sunt patrate perfecte :param lista: Lista asupra careia se face verificarea :return: True daca toate elementele sunt patrate perfecte sau False in caz contrar """ for x in lista: if is_perfect_square(x) is False: return False return True def test_toate_elementele_patrate_perfecte(): assert(toate_elementele_patrate_perfecte([16, 9, 36])) is True assert (toate_elementele_patrate_perfecte([15, 9, 36])) is False assert (toate_elementele_patrate_perfecte([16, 9, 36, 64, 100])) is True def get_longest_all_perfect_squares(lista: list) -> list[int]: """ Determina cea mai lunga secventa de patrate perfecte dintr-o lista :param lista: Lista asupra careia se face verificarea :return: Se returneaza elementele celei mai lungi subsecvente de patrate perfecte """ subsecventa_max = [] for i in range(len(lista)): for j in range(i, len(lista)): if toate_elementele_patrate_perfecte(lista[i:j + 1]) and len(subsecventa_max) < len(lista[i:j + 1]): subsecventa_max = lista[i:j + 1] return subsecventa_max def test_get_longest_all_perfect_squares(): assert(get_longest_all_perfect_squares([16, 9, 1, 5, 36, 49])) == [16, 9, 1] assert (get_longest_all_perfect_squares([101, 10, 12, 5, 6, 50])) == [] assert (get_longest_all_perfect_squares([9, 1, 5, 36, 49, 12, 16, 25, 100])) == [16, 25, 100] def get_number_of_bits_equal_to_one(x: int) -> int: """ Determina cati biti sunt egali cu 1 in reprezentarea binara a unui numar dat :param x: Numarul al carui numar de biti este calculat :return: Returneaza numarul de biti egali cu 1 """ numar_biti = 0 while x != 0: if x % 2 == 1: numar_biti += 1 x = x//2 return numar_biti def test_get_number_of_bits_equal_to_one(): assert(get_number_of_bits_equal_to_one(12)) == 2 assert (get_number_of_bits_equal_to_one(19)) == 3 assert (get_number_of_bits_equal_to_one(55)) == 5 def toate_elementele_au_numar_egal_de_biti(lista: list) -> bool: """ Verifica daca toate elementele unei liste au acelasi numar de biti egali cu 1 :param lista: Lista asupra careia se efectueaza verificarea :return: True daca toate elementele listei au acelasi numar de biti egal cu 1 sau False in caz contrar """ numar_biti = get_number_of_bits_equal_to_one(lista[0]) for x in lista[:len(lista)]: if get_number_of_bits_equal_to_one(x) != numar_biti: return False return True def test_toate_elementele_au_numar_egal_de_biti(): assert(toate_elementele_au_numar_egal_de_biti([12, 15, 17])) is False assert (toate_elementele_au_numar_egal_de_biti([12, 17, 18])) is True assert (toate_elementele_au_numar_egal_de_biti([12, 18, 24])) is True def get_longest_same_bit_counts(lista: list) -> list[int]: """ Determina cea mai lunga secventa de numere ce au acelasi numar de biti egali cu 1 in reprezentarea binara :param lista: Lista asupra careia se efectueaza operatia :return: Returneaza cea mai lunga subsecventa ce indeplineste conditia """ subsecventa_max = [] for i in range(len(lista)): for j in range(i, len(lista)): if toate_elementele_au_numar_egal_de_biti(lista[i:j + 1]) and len(subsecventa_max) < len(lista[i:j + 1]): subsecventa_max = lista[i:j + 1] return subsecventa_max def test_get_longest_same_bit_counts(): assert(get_longest_same_bit_counts([12, 17, 15, 21, 22, 25])) == [21, 22, 25] assert (get_longest_same_bit_counts([11, 12, 15, 27])) == [15, 27] assert (get_longest_same_bit_counts([14, 19, 21, 30, 31])) == [14, 19, 21] def toate_elementele_pare(lista: list) -> bool: """ Verifica daca toate elementele unei liste sunt pare :param lista: Lista asupra careia se efectueaza verificarea :return: Returneaza True daca toate elementele listei sunt pare sau False in caz contrar """ for x in lista: if x % 2 == 1: return False return True def test_toate_elementele_pare(): assert(toate_elementele_pare([2, 4, 18, 66])) is True assert(toate_elementele_pare([6, 12, 15, 18])) is False assert (toate_elementele_pare([])) is True def get_longest_all_even(lista: list) -> list[int]: """ Determina cea mai lunga subsecventa de numere pare dintr-o lista :param lista: Lista asupra careia se efectueaza determinarea :return: Cea mai lunga subsecventa care contine doar numere pare """ subsecventa_max = [] for i in range(len(lista)): for j in range(i, len(lista)): if toate_elementele_pare(lista[i:j + 1]) and len(subsecventa_max) < len(lista[i:j + 1]): subsecventa_max = lista[i:j + 1] return subsecventa_max def test_get_longest_all_even(): assert(get_longest_all_even([5, 4, 6, 8, 9, 16, 12, ])) == [4, 6, 8] assert (get_longest_all_even([50, 48, 25, 16, 32, 36])) == [16, 32, 36] assert (get_longest_all_even([10, 12, 14, 15, 25])) == [10, 12, 14] def main(): test_is_perfect_square() test_toate_elementele_patrate_perfecte() test_get_longest_all_perfect_squares() test_get_number_of_bits_equal_to_one() test_toate_elementele_au_numar_egal_de_biti() test_get_longest_same_bit_counts() test_toate_elementele_pare() test_get_longest_all_even() while True: tipareste_meniu() optiune = input("Introduceti optiunea: ") if optiune == "1": lista = [] citeste_lista(lista) elif optiune == "2": print(get_longest_all_perfect_squares(lista)) elif optiune == "3": print(get_longest_same_bit_counts(lista)) elif optiune == "4": print(get_longest_all_even(lista)) elif optiune == "5": break else: print("Optiune gresita, incercati din nou!") main()
39c82b00fa2f9d1a053859052be9e0c573540dc3
kaitoukito/PythonADT
/7. LinkedListADT/PositionList.py
889
3.59375
4
import DoublyLinkedBase class PositionList(DoublyLinkedBase._DoublyLinkedBase): # -------------------- nested Position class -------------------- class Position: """An abstract representing the location of a single element.""" def __init__(self, container, node): """Constructor should not be invoked by user.""" self._container = container self._node = node def element(self): """Return the element stored at this Position.""" return self._node._element def __eq__(self, other): """Return True if other Position represents the same location.""" return type(other) is type(self) and other._node is self._node def __ne__(self, other): """Return True if other does not represents the same location.""" return not (self == other)
57de694b14db9a8b2ed7ec3f61c4759f4348c61c
sunho-park/Notebook
/textbook/14.dataframe/list14_27.py
270
3.875
4
import pandas as pd from pandas import DataFrame dupli_data = DataFrame({"col1":[1, 1, 2, 3, 4, 4, 6, 6], "col2":["a", "b", "b", "b", "c", "c", "b", "b"]}) print(dupli_data) print(dupli_data.duplicated()) print(dupli_data.drop_duplicates())
5ce4aeab8b28262f9ca3e8b60952be27200d9db4
svenenri/python-csv-transform
/handler.py
6,190
3.734375
4
""" Module used for performing transformations to a csv file that are needed to prepare the csv file for ETL process """ from collections import defaultdict import re import csv import boto3 import botocore def extract_nums(code_list): """ Method to remove numbers from the Project Code and Project Series. Args: code_list: List based of the column passed in from the csv file. Returns: code_list: List with numbers removed from column information. """ for idx, code in enumerate(code_list): if re.match(r'[0-9]', code[-1:]): new_code = code[:-1] code_list[idx] = new_code return code_list def download_s3_file(bucket_name, key, file_name): """ Method for downloading csv file to be transformed. Args: bucket_name: Name of S3 bucket where the file is located. key: Key associated with file in the S3 Bucket. file_name: Name of file to be downloaded from the S3 bucket. Returns: Tuple outlining the result. A successful download will return a tuple containing a True boolean and the String 'Success'. An unsuccessful download will return a tuple containing a False boolean and the error response. Raises: Error associated with failed download of the file from the S3 bucket. """ try: print 'Getting ' + key + ' from the ' + bucket_name + ' bucket...' data_file = s3.meta.client.download_file(bucket_name, key, '/tmp/' + file_name) return (True, 'Success') except botocore.exceptions.ClientError as error: if error.response['Error']['Code'] == '404': data_file = s3.meta.client.download_file(bucket_name, key, '/tmp/' + file_name) return (False, data_file) else: raise # Perform data transformations def transform(file_name): """ Method to complete required data transformations Args: file_name: Name of file to be read for transformations Returns: Zipped object containing data to be written to the csv file """ columns = defaultdict(list) with open(file_name, 'rb') as csv_file: reader = csv.DictReader(csv_file) for row in reader: for (key, val) in row.items(): columns[key].append(val) all_data = columns project_code = columns['Project External System Code'] project_code.insert(0, 'PROJECT Code') all_data['PROJECT Code'] = all_data.pop('Project External System Code') project_series = columns['Project Description'] project_series.insert(0, 'PROJECT Series') all_data['PROJECT Series'] = all_data.pop('Project Description') project_code = extract_nums(project_code) project_series = extract_nums(project_series) rows = zip( columns['Person Account'].insert(0, 'Person Account'), columns['Person Code'].insert(0, 'Person Account'), columns['Person First Name'].insert(0, 'Person Code'), columns['Person First Name'].insert(0, 'Person First Name'), columns['Person Last Name'].insert(0, 'Person Last Name'), columns['Project Code'].insert(0, 'Project Code'), columns['Project Title'].insert(0, 'Project Title'), columns['Project End Date'].insert(0, 'Project End Date') ) return rows # Write to CSV def csv_file_write(file_name, rows): """ Method for writing transformed data to csv file Args: file_name: Name of file to be created rows: Zipped object containing data to be written to the csv file Returns: Created file """ name_items = file_name.split('.') new_file_name = '/tmp/' + name_items[0] + '_updated.csv' with open(new_file_name, 'wb') as csv_write: writer = csv.writer(csv_write) for row in rows: writer.writerow(row) return new_file_name def upload_to_s3(bucket_name, key, file_name): """ Method for uploading transformed csv file back to the specified S3 bucket Args: bucket_name: Bucket to upload transformed csv file key: Key to associate file in the S3 Bucket file_name: Name of file to upload to S3 """ key_list = key.split('/') new_key = 'reports/' + key_list[-1] try: print 'Uploading ' + key + ' to the ' + bucket_name + ' bucket...' s3.meta.client.upload_file(file_name, bucket_name, new_key) print 'Uploaded' except botocore.exceptions.ClientError as error: if error.response['Error']['Code'] == '404': print 'The object does not exist.' else: raise s3 = boto3.resource('s3') # Execute def handler(event, context): """ Handler to execute csv transformations when invoked in AWS Lambda. Args: event: context: Returns: event_tup: Tuple containing the outcome of the Lambda execuction. A successful execution returns the String 'Success', the name of the transformed file, and the name of the bucket the transformed file was uploaded to. An unsuccessful execution returns the String 'There was an issue', the name of the transformed file, and the bucket that the module attempted to upload the transformed file to. """ bucket_name = event['Records'][0]['s3']['bucket']['name'] key = event['Records'][0]['s3']['object']['key'] key_list = key.split('/') file_name = key_list[-1] download = download_s3_file(bucket_name, key, file_name) # execute = 1 if download[0]: new_file = transform('/tmp/' + file_name) write_file = csv_file_write(file_name, new_file) new_key_list = write_file.split('/') new_key = new_key_list[-1] upload_to_s3(bucket_name, '/tmp/' + new_key, write_file) event_tup = ('Success', new_key, bucket_name) return event_tup event_tup = ('There was an issue', new_key, bucket_name) return event_tup
e88fa6b8801496e80b69b89c08b5129d91c2cd6d
L273/Cryptology-
/古典密码/古典密码项目文件/hill加密(弹性)/hill.py
11,546
3.765625
4
def menu(): li = { 1:en_file, 2:de_file } choose=True while(choose): try: print("1、加密文件") print("2、解密文件") choose = eval(input("请输入选择:")) if(choose==2 or choose ==1): break choose=True except: choose=True switch = li.get(choose) switch() def en_file(): print("将要加密文件") m=get_code('1.txt') if len(m)==0 or len(m)==1: print("字符串太短,不足以进行操作。") return ; m=en_code(m) m=to_str(m) print("加密后的字符串为:"+m) set_code('1.txt',m) def de_file(): print("将要解密文件") m=get_code('1.txt') if len(m)==0 or len(m)==1: print("字符串太短,不足以进行操作。") return ; m=de_code(m) m=to_str(m) print("解密后的字符串为:"+m) set_code('1.txt',m) def get_code(text): print(text) fp=open(text,'r') dd=fp.read() fp.close() print("\n得到要操作的字符串(非字母均会过滤掉)") m=[] print("\n文件内的字符串为:",end="") for a in dd: if ord(a)<91 and ord(a)>64: print(a,end="") temp = ord(a)-64+26 elif ord(a)<123 and ord(a)>96: print(a,end="") temp = ord(a)-96 else: continue m.append(temp) ''' a-z 1->26 A-Z 27->52 ''' print("\n") return m def set_code(text,connect): print("\n将把操作的数据写入文件") print(text) try: fp=open(text,'w') dd=fp.write(connect) fp.close() print("\n写入成功!") except: print("\n写入失败。") def mul_2(a,b): c=[[]for i in range(2)] try: c[0].append((a[0][0]*b[0][0]+a[0][1]*b[1][0])%52) except: pass try: c[0].append((a[0][0]*b[0][1]+a[0][1]*b[1][1])%52) except: pass try: c[1].append((a[1][0]*b[0][0]+a[1][1]*b[1][0])%52) except: pass try: c[1].append((a[1][0]*b[0][1]+a[1][1]*b[1][1])%52) except: pass return c def mul_3(a,b): c=[[]for i in range(3)] try: c[0].append((a[0][0]*b[0][0]+a[0][1]*b[1][0]+a[0][2]*b[2][0])%52) except: pass try: c[0].append((a[0][0]*b[0][1]+a[0][1]*b[1][1]+a[0][2]*b[2][1])%52) except: pass try: c[0].append((a[0][0]*b[0][2]+a[0][1]*b[1][2]+a[0][2]*b[2][2])%52) except: pass try: c[1].append((a[1][0]*b[0][0] +a[1][1]*b[1][0] +a[1][2]*b[2][0])%52) except: pass try: c[1].append((a[1][0]*b[0][1] +a[1][1]*b[1][1] +a[1][2]*b[2][1])%52) except: pass try: c[1].append((a[1][0]*b[0][2] +a[1][1]*b[1][2] +a[1][2]*b[2][2])%52) except: pass try: c[2].append((a[2][0]*b[0][0]+a[2][1]*b[1][0]+a[2][2]*b[2][0])%52) except: pass try: c[2].append((a[2][0]*b[0][1]+a[2][1]*b[1][1]+a[2][2]*b[2][1])%52) except: pass try: c[2].append((a[2][0]*b[0][2]+a[2][1]*b[1][2]+a[2][2]*b[2][2])%52) except: pass return c def en_code(m): k2_en=[[51, 13], [43, 20]] k3_en=[[22, 30, 19], [23, 41, 6], [2, 35, 10]] if(len(m)%5==0): c=[[]for i in range((int)(len(m)/5))] for i in range(len(c)): c[i].append(mul_2(k2_en,[[m[5*i]],[m[5*i+1]]])[0][0]) c[i].append(mul_2(k2_en,[[m[5*i]],[m[5*i+1]]])[1][0]) c[i].append(mul_3(k3_en,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[0][0]) c[i].append(mul_3(k3_en,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[1][0]) c[i].append(mul_3(k3_en,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[2][0]) #2323.....23 2323 elif(len(m)%5==4): c=[[]for i in range((int)(len(m)/5)+2)] try: for i in range(len(c)-2): c[i].append(mul_2(k2_en,[[m[5*i]],[m[5*i+1]]])[0][0]) c[i].append(mul_2(k2_en,[[m[5*i]],[m[5*i+1]]])[1][0]) c[i].append(mul_3(k3_en,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[0][0]) c[i].append(mul_3(k3_en,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[1][0]) c[i].append(mul_3(k3_en,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[2][0]) except: pass c[-2].append(mul_2(k2_en,[[m[-4]],[m[-3]]])[0][0]) c[-2].append(mul_2(k2_en,[[m[-4]],[m[-3]]])[1][0]) c[-1].append(mul_2(k2_en,[[m[-2]],[m[-1]]])[0][0]) c[-1].append(mul_2(k2_en,[[m[-2]],[m[-1]]])[1][0]) #2323.....23 2322 elif(len(m)%5==3): c=[[]for i in range((int)(len(m)/5)+1)] try: for i in range(len(c)-1): c[i].append(mul_2(k2_en,[[m[5*i]],[m[5*i+1]]])[0][0]) c[i].append(mul_2(k2_en,[[m[5*i]],[m[5*i+1]]])[1][0]) c[i].append(mul_3(k3_en,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[0][0]) c[i].append(mul_3(k3_en,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[1][0]) c[i].append(mul_3(k3_en,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[2][0]) except: pass c[-1].append(mul_3(k3_en,[[m[-3]],[m[-2]],[m[-1]]])[0][0]) c[-1].append(mul_3(k3_en,[[m[-3]],[m[-2]],[m[-1]]])[1][0]) c[-1].append(mul_3(k3_en,[[m[-3]],[m[-2]],[m[-1]]])[2][0]) #2323.....23 233 elif(len(m)%5==2): c=[[]for i in range((int)(len(m)/5)+1)] try: for i in range(len(c)-1): c[i].append(mul_2(k2_en,[[m[5*i]],[m[5*i+1]]])[0][0]) c[i].append(mul_2(k2_en,[[m[5*i]],[m[5*i+1]]])[1][0]) c[i].append(mul_3(k3_en,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[0][0]) c[i].append(mul_3(k3_en,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[1][0]) c[i].append(mul_3(k3_en,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[2][0]) except: pass c[-1].append(mul_2(k2_en,[[m[-2]],[m[-1]]])[0][0]) c[-1].append(mul_2(k2_en,[[m[-2]],[m[-1]]])[1][0]) #2323.....23 232 elif(len(m)%5==1): c=[[]for i in range((int)(len(m)/5)+2)] try: for i in range(len(c)-3): c[i].append(mul_2(k2_en,[[m[5*i]],[m[5*i+1]]])[0][0]) c[i].append(mul_2(k2_en,[[m[5*i]],[m[5*i+1]]])[1][0]) c[i].append(mul_3(k3_en,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[0][0]) c[i].append(mul_3(k3_en,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[1][0]) c[i].append(mul_3(k3_en,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[2][0]) except: pass c[-3].append(mul_2(k2_en,[[m[-6]],[m[-5]]])[0][0]) c[-3].append(mul_2(k2_en,[[m[-6]],[m[-5]]])[1][0]) c[-2].append(mul_2(k2_en,[[m[-4]],[m[-3]]])[0][0]) c[-2].append(mul_2(k2_en,[[m[-4]],[m[-3]]])[1][0]) c[-1].append(mul_2(k2_en,[[m[-2]],[m[-1]]])[0][0]) c[-1].append(mul_2(k2_en,[[m[-2]],[m[-1]]])[1][0]) #2323.....23 222 return c def de_code(m): k2_de=[[12, 39], [21, 15]] k3_de=[[44, 1, 25], [42,26, 45], [47, 18, 4]] if(len(m)%5==0): c=[[]for i in range((int)(len(m)/5))] for i in range(len(c)): c[i].append(mul_2(k2_de,[[m[5*i]],[m[5*i+1]]])[0][0]) c[i].append(mul_2(k2_de,[[m[5*i]],[m[5*i+1]]])[1][0]) c[i].append(mul_3(k3_de,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[0][0]) c[i].append(mul_3(k3_de,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[1][0]) c[i].append(mul_3(k3_de,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[2][0]) #2323.....23 2323 elif(len(m)%5==4): c=[[]for i in range((int)(len(m)/5)+2)] try: for i in range(len(c)-2): c[i].append(mul_2(k2_de,[[m[5*i]],[m[5*i+1]]])[0][0]) c[i].append(mul_2(k2_de,[[m[5*i]],[m[5*i+1]]])[1][0]) c[i].append(mul_3(k3_de,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[0][0]) c[i].append(mul_3(k3_de,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[1][0]) c[i].append(mul_3(k3_de,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[2][0]) except: pass c[-2].append(mul_2(k2_de,[[m[-4]],[m[-3]]])[0][0]) c[-2].append(mul_2(k2_de,[[m[-4]],[m[-3]]])[1][0]) c[-1].append(mul_2(k2_de,[[m[-2]],[m[-1]]])[0][0]) c[-1].append(mul_2(k2_de,[[m[-2]],[m[-1]]])[1][0]) #2323.....23 2322 elif(len(m)%5==3): c=[[]for i in range((int)(len(m)/5)+1)] try: for i in range(len(c)-1): c[i].append(mul_2(k2_de,[[m[5*i]],[m[5*i+1]]])[0][0]) c[i].append(mul_2(k2_de,[[m[5*i]],[m[5*i+1]]])[1][0]) c[i].append(mul_3(k3_de,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[0][0]) c[i].append(mul_3(k3_de,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[1][0]) c[i].append(mul_3(k3_de,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[2][0]) except: pass c[-1].append(mul_3(k3_de,[[m[-3]],[m[-2]],[m[-1]]])[0][0]) c[-1].append(mul_3(k3_de,[[m[-3]],[m[-2]],[m[-1]]])[1][0]) c[-1].append(mul_3(k3_de,[[m[-3]],[m[-2]],[m[-1]]])[2][0]) #2323.....23 233 elif(len(m)%5==2): c=[[]for i in range((int)(len(m)/5)+1)] try: for i in range(len(c)-1): c[i].append(mul_2(k2_de,[[m[5*i]],[m[5*i+1]]])[0][0]) c[i].append(mul_2(k2_de,[[m[5*i]],[m[5*i+1]]])[1][0]) c[i].append(mul_3(k3_de,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[0][0]) c[i].append(mul_3(k3_de,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[1][0]) c[i].append(mul_3(k3_de,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[2][0]) except: pass c[-1].append(mul_2(k2_de,[[m[-2]],[m[-1]]])[0][0]) c[-1].append(mul_2(k2_de,[[m[-2]],[m[-1]]])[1][0]) #2323.....23 232 elif(len(m)%5==1): c=[[]for i in range((int)(len(m)/5)+2)] try: for i in range(len(c)-3): c[i].append(mul_2(k2_de,[[m[5*i]],[m[5*i+1]]])[0][0]) c[i].append(mul_2(k2_de,[[m[5*i]],[m[5*i+1]]])[1][0]) c[i].append(mul_3(k3_de,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[0][0]) c[i].append(mul_3(k3_de,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[1][0]) c[i].append(mul_3(k3_de,[[m[5*i+2]],[m[5*i+3]],[m[5*i+4]]])[2][0]) except: pass c[-3].append(mul_2(k2_de,[[m[-6]],[m[-5]]])[0][0]) c[-3].append(mul_2(k2_de,[[m[-6]],[m[-5]]])[1][0]) c[-2].append(mul_2(k2_de,[[m[-4]],[m[-3]]])[0][0]) c[-2].append(mul_2(k2_de,[[m[-4]],[m[-3]]])[1][0]) c[-1].append(mul_2(k2_de,[[m[-2]],[m[-1]]])[0][0]) c[-1].append(mul_2(k2_de,[[m[-2]],[m[-1]]])[1][0]) #2323.....23 222 return c def to_str(list): list_str="" for i in list: for j in i: if j<27: list_str += chr(j+96) elif j<53: list_str += chr(j+38) return list_str def main(): menu() if __name__=='__main__': main() ''' #a-z 1->26 #A-Z 27->52 '''
2cd8c34beaa70ec4a8b9076fb85187839c82297d
chphuynh/CMPM146
/P3/mcts_vanill.py
3,598
3.578125
4
from mcts_node import MCTSNode from random import choice from math import sqrt, log num_nodes = 1000 explore_faction = 2. def traverse_nodes(node, state, identity): """ Traverses the tree until the end criterion are met. Args: node: A tree node from which the search is traversing. state: The state of the game. identity: The bot's identity, either 'red' or 'blue'. Returns: A node from which the next stage of the search can proceed. """ if not node.child_nodes: node.visits = node.visits + 1 return node bound = None selected_child = None #selected_child_state = None for child in node.child_nodes: child = node.child_nodes[child] child_bound = child.wins + explore_faction * (sqrt(2*log(node.visits) / (child.visits))) if bound is None or child_bound < bound: bound = child_bound selected_child = child #selected_child_state = state.copy() state.apply_move(selected_child.parent_action) return traverse_nodes(selected_child, state, state.player_turn) # Hint: return leaf_node def expand_leaf(node, state): """ Adds a new leaf to the tree by creating a new child node for the given node. Args: node: The node for which a child will be added. state: The state of the game. Returns: The added child node. """ new_state = state.copy() new_move = choice(node.untried_actions) new_state.apply_move(new_move) new_node = MCTSNode(parent=node, parent_action=new_move, action_list=new_state.legal_moves) return new_node # Hint: return new_node def rollout(state): """ Given the state of the game, the rollout plays out the remainder randomly. Args: state: The state of the game. """ while(state.legal_moves): state.apply_move(choice(state.legal_moves)) def backpropagate(node, won): """ Navigates the tree from a leaf node to the root, updating the win and visit count of each node along the path. Args: node: A leaf node. won: An indicator of whether the bot won or lost the game. """ if node.parent == None: return if won: node.wins = node.wins + 1 node.visits = node.visits + 1 backpropagate(node.parent, won) def think(state): """ Performs MCTS by sampling games and calling the appropriate functions to construct the game tree. Args: state: The state of the game. Returns: The action to be taken. """ identity_of_bot = state.player_turn root_node = MCTSNode(parent=None, parent_action=None, action_list=state.legal_moves) for step in range(num_nodes): # Copy the game for sampling a playthrough sampled_game = state.copy() # Start at root node = root_node # Do MCTS - This is all you! node = traverse_nodes(node, sampled_game, identity_of_bot) node = expand_leaf(node, sampled_game) rollout(sampled_game) backpropagate(node, sampled_game.winner == identity_of_bot) highscore=-1 bestAction = None for child in root_node.child_nodes: child = root_node.child_nodes[child] if child.wins/child.visits > highscore: highscore = child.wins/child.visits bestAction = child.parent_action return bestAction # Return an action, typically the most frequently used action (from the root) or the action with the best # estimated win rate.
eea8a43a6c18386e98a34dd44e6fc385cd6fc338
kathleentully/process_haz_waste
/find_clusters.py
805
3.53125
4
#import simplejson as json import json, urllib, csv key = json.loads(open('key.json').read())['key'] VAR_LIMIT = 50 def find_points(year,num): data = json.loads(open('20'+year+'-hazwaste.json').read()) point_list = [] for point in data: if len(point['areaAroundPoint']['points']) >= num: point_list.append(point['point_id']) return point_list if __name__ == '__main__': while True: try: num = int(raw_input('Find all clusters larger than what number? ').strip()) break except: print 'Please enter an integer. Try again' points = find_points('01',num) if len(points) == 0: print 'No points found for 2001' else: print '2001:',', '.join(points) points = find_points('11',num) if len(points) == 0: print 'No points found for 2011' else: print '2011:',', '.join(points)
a10cf95e53cfac5f7f34b305b70c79f2b90a299d
Voronit/Python
/Основы Python/6.Работа с файлами/Задача 1.py
1,889
3.5625
4
def main (_file): file = open(_file) cook_book = {} i = True for lines in file: dish = "" if i == True: for line in lines: if line != "\n": dish += line else: cook_book.update({dish: support1(_file, lines)}) i = False elif lines == "\n": i = True file.close() return cook_book def support1 (_file, line): file = open(_file) sup = [] q = 0 i = False for lines in file: if lines == line: i = True if i == True: if q < 2: q += 1 elif lines != "\n": sup.append(support2(_file, lines)) elif lines == "\n": q = 0 i = False file.close() return sup def support2 (_file, line): file = open (_file) sup = {} ind = "ingredient_name" for lines in file: ign = "" qua = "" mea = "" if lines == line: for line in lines: if ind == "ingredient_name": if line != "|" and line != " ": ign += line elif line == "|": sup.update({ind: ign}) ind = "quantity" elif ind == "quantity": if line != "|" and line != " ": qua += line elif line == "|": sup.update({ind: qua}) ind = "measure" elif ind == "measure": if line != "\n" and line != " ": mea += line if line == lines[-1] and mea != "": sup.update({ind: mea}) file.close() return sup print (main ("text.txt"))
56b31a245e622cad125c8f4fcc9a434cb9b7e1b3
lidongdongbuaa/leetcode2.0
/链表/链表排序与划分/148. Sort List (linked list).py
10,842
4.1875
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2019/11/13 9:14 # @Author : LI Dongdong # @FileName: 148. Sort List (linked list).py '''''' ''' 题目分析 1.要求:Sort a linked list in O(n log n) time using constant space complexity. Input: 4->2->1->3 Output: 1->2->3->4 Input: -1->5->3->4->0 Output: -1->0->3->4->5 2.理解:用堆/快速/归并 三种nlongn的排序方法在原链表上进行排序,使得space complexity 为constant,即为常数 3.类型:链表排序 4.方法及方法分析: Bottom-up Merge sort method; Merge sort method; list storage-rebuild method time complexity order: Bottom-up Merge sort method O(NlogN) = Merge sort method O(NlogN) = list storage-rebuild method O(NlogN) space complexity order: Bottom-up Merge sort method O(1) < Merge sort method O(N) = list storage-rebuild method O(N) ''' ''' Bottom-up Merge sort method (iterative) idea:use bottom-up merge sort method edge case: input:None? Y only one? Y repeat? N sorted? N range ? N output:None / the sorted linked list head method: compare the value of the adjacent node groups having one element, by calculating linklist length, using while, for loop, moving head to cut the groups compare the value of the adjacent node groups have two elements Then repeat doing it, until there is only one group time complex: O(NlogN) space complex: O(1) 易错点: 在求第二段的头尾时,第二段的长度可能会小于gap的长度,故需要使用if head: s_end = head, head = head.next避免head.next报错 ''' 'leetcode 超时。' \ '原因:interval for循环中,重复性寻找每段的头和尾' \ '解决方案:舍弃掉for循环,用while head和interval' class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def sortList(self, head: ListNode) -> ListNode: # sort linklist if not head: # corner case return None if not head.next: return head length = self.findL(head) # calculate length gap = 1 cur = head dummy = ListNode(0) dummy.next = head while gap < length: # do bottom-up merge for i in range(0, length - gap, gap * 2): dummy = self.merge(dummy, i, gap) gap = gap * 2 return dummy.next def findL(self, head): # calculate lenght if not head: # corner case return 0 numb = 0 while head: # accumlate length head = head.next numb += 1 return numb def merge(self, dummy, i, gap): # merge sort first gap nodes with second gap nodes head = dummy for _ in range(i + 1): b = head # before-head of first gap nodes head = head.next f = head # head of first gap nodes for _ in range(gap): f_end = head # tail of first gap nodes head = head.next s = head # head of second gap nodes for _ in range(gap): if head: # 易错点 s_end = head # tail of second gap nodes head = head.next next = head # head of next part(except sort nodes) b.next = None f_end.next = None s_end.next = None newH, newT = self.submerge(f, s) b.next = newH newT.next = next return dummy def submerge(self, fH, sH): # merge two sorted linked list fH and sH, output head and tail if not sH: head = fH while head.next: head = head.next return fH, head if not fH: head = sH while head.next: head = head.next return sH, head dummy = cur = ListNode(0) while fH and sH: # or 可以吗 if fH.val < sH.val: cur.next = fH cur = cur.next fH = fH.next else: cur.next = sH cur = cur.next sH = sH.next if fH: cur.next = fH if sH: cur.next = sH while cur.next: cur = cur.next return dummy.next, cur 'optimized code' ''' 关键点: 1. 用while head 替换 for 2. 每轮 merge之前,每次更新fake_tail和head 3. 每轮 merge中,先cut,后merge,再链接merged linklist,最后更新fake_tail和head 易错点:新group的head,tail,与前group,后group的连接 ''' class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def sortList(self, head: ListNode) -> ListNode: # sort linklist if not head: # corner case return None if not head.next: return head length = self.findL(head) # calculate length interval = 1 dummy = ListNode(0) dummy.next = head while interval < length: # do bottom-up merge fake_tail = dummy # fake_tail is tail of last part, 初始化 head = dummy.next while head: nextH = self.cut(head, interval) leftH = self.cut(nextH, interval) mergeHead, mergeTail = self.merge(head, nextH) fake_tail.next = mergeHead # connect the merged part to original linklist mergeTail.next = leftH fake_tail = mergeTail # renew the tail which is before the merge sort part head = leftH # renew the head interval = 2 * interval return dummy.next def findL(self, head): # calculate lenght if not head: # corner case return 0 numb = 0 while head: # accumlate length head = head.next numb += 1 return numb def cut(self, head, interval): # from head to cut interval nodes, return next part head if not head: # corner case return None for _ in range(interval): if not head: # corner case: interval > length of linklist break tail = head head = head.next tail.next = None return head def merge(self, head1, head2): # merge sort two sorted linklist. return this part head and tail if not head1: cur = head2 while cur.next: cur = cur.next return head2, cur if not head2: cur = head1 while cur.next: cur = cur.next return head1, cur dummy = cur = ListNode(0) while head1 and head2: if head1.val < head2.val: cur.next = head1 cur = cur.next head1 = head1.next else: cur.next = head2 cur = cur.next head2 = head2.next if head1: cur.next = head1 if head2: cur.next = head2 while cur.next: cur = cur.next return dummy.next, cur A1 = ListNode(-1) A2 = ListNode(5) A3 = ListNode(3) A4 = ListNode(4) A5 = ListNode(0) A1.next = A2 A2.next = A3 A3.next = A4 A4.next = A5 X = Solution() X.sortList(A1) ''' Merge sort method (recursion) idea:use merge sort method edge case: input:None? Y only one? Y repeat?N value range? infinite output:None/linked list head method: divide the linked list into pairs compare the node value of the pair, move the smaller val node left to the bigger one(by changing next to) compare elements of the two leftmost pairs, and move the smaller val node to the left. (by changing next to) repeat it until these is only one pair left time complex: O(NlogN) space complex: O(N) 易错点:L,R划定以后,尾部要及时中止,即L,R变成单独的 ''' class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def sortList(self, head: ListNode) -> ListNode: # sort linklist if head is None: # edge case return None if head.next is None: # edge case return head length = self.len_linklist(head) mid = length // 2 L = R = head # L is head of first part, R is head of later part for _ in range(mid): # cut separated L group and R group R = R.next L_cur = L for _ in range(mid - 1): # L_cur is first part's tail L_cur = L_cur.next L_cur.next = None sub_L = self.sortList(L) sub_R = self.sortList(R) return self.sortSubList(sub_L, sub_R) # merge sub_L and sub_R def sortSubList(self, head1, head2): # sort two sorted list if head1 is None: # edge case return head2 if head2 is None: return head1 dummy = new_head = ListNode(0) while head1 and head2: # merge two list if head1.val < head2.val: dummy.next = head1 dummy = dummy.next head1 = head1.next else: dummy.next = head2 dummy = dummy.next head2 = head2.next if head1: dummy.next = head1 else: dummy.next = head2 return new_head.next def len_linklist(self, head): # calculate length of linked list if head is None: # edge case return 0 length = 0 curr = head while curr: # accumulate length length += 1 curr = curr.next return length ''' list storage-rebuild method idea:save node val in list -> sort list -> rebuild node/change val of linkedlist edge case:head is None method: traverse linkedlist to save node val in node_list #tO(N), sO(N) sort list #tO(NlogN) traverse node_list to rebuild the linkedlist #tO(N), sO(N)/sO(1) time complex: O(NlogN) space complex: O(N) 易错点:因为pre = new_head = ListNode(0),故最后需要返回new_head.next,而不是new_head ''' class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def sortList(self, head: ListNode) -> ListNode: # edge case if head is None: return None # save linklist in a list node_list = [] curr = head while curr: node_list.append(curr.val) curr = curr.next # sort list node_list.sort() # rebuild the linklist pre = new_head = ListNode(0) for elem in node_list: new_node = ListNode(elem) pre.next = new_node pre = pre.next return new_head.next ''' test case '''
d6a303fb8a6bde2a8e0d8cbf06111b2d8b8b4d43
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4029/codes/1749_3089.py
212
4.03125
4
n = int(input("Digite um numero: ")) s = 0 while ( n != 0): s = s + n n = n + 1 if (n > 1): msg = "Direita" else: msg = "Esquerda" else: n = int(input("Digite um numero: ")) print(n) print(msg)
9062b9544dba86ffcb31d6d19bb435022107aa41
cloudenjr/Calvert-Loudens-GitHub
/Self_Study/Python_MC/Py_Prog/Using_DB_inPython/createDB/contacts2.py
1,969
4.3125
4
# ********************************************************************************************************************* # Notes: # - in Python, when you want to just iterate over the resulting dataset, Python allows you to execute queries using the # connection w/o having to create a cursor # - you really should commit the changes after performing the update # - use the cursor to commit the changes rather than the connection: cursor objects themselves don't have a 'commit' # method, but they do have a 'connection' property that we can use to get a reference to the connection that the # cursor's using. # # ********************************************************************************************************************* import sqlite3 db = sqlite3.connect("contacts.sqlite") # this line will create the contacts.sqlite DB if it doesnt already exist, # otherwise it'll just open it. new_email = "[email protected]" phone = input("Please enter the phone number ") # update_sql = "UPDATE contacts SET email = '{}' WHERE phone = {}".format(new_email, phone) update_sql = "UPDATE contacts SET email = ? WHERE phone = ?" print(update_sql) update_cursor = db.cursor() update_cursor.execute(update_sql, (new_email, phone)) # update_cursor.executescript(update_sql) # '.executescript' function allows Python to execute multiple statements print("{} rows updated".format(update_cursor.rowcount)) print() print("Are the connections the same: {}".format(update_cursor.connection == db)) print() update_cursor.connection.commit() update_cursor.close() for name, phone, email in db.execute("SELECT * FROM contacts"): # upacking the tuple method syntax print(name) print(phone) print(email) print('_' * 20) # for row in db.execute("SELECT * FROM contacts"): # displays each row in the DB as a list containing values based on # print(row) # column data types db.close()
85b6513ca460043e6d02a8b7a3a9774d7128a7ab
tashakim/code-catalog-python
/catalog/suggested/graphs/topological_sort.py
824
3.671875
4
def topological_sort(self): """ Determines the priority of vertices to be visited. """ STATUS_STARTED = 1 STATUS_FINISHED = 2 order = [] statuses = {} assert (not self.contains_cycle()) for vertex in self.get_vertex(): to_visit = [vertex] while to_visit: v = to_visit.pop() if v in statuses: if statuses[v] == STATUS_STARTED: statuses[v] = STATUS_FINISHED order.append(v) else: statuses[v] = STATUS_STARTED to_visit.append(v) # add to stack again to signal vertex has finished DFS for u in self.get_neighbor(v): if u not in statuses: to_visit.append(u) order.reverse() return order
47b090e88a2e00fe69fa6039c1b715433ab1e2fd
raissaazaria/pythonexcercise-1and2
/python exercise 2 no 4.py
1,059
3.71875
4
qty = eval(input("Enter the number of packages purchased:")) retails_price = qty * 99 if qty >= 10 and qty <=19: result1 = (10*retails_price/100) result_1 = retails_price - result1 print("Discount amount @10:$", format(result1)) print("Total amount: $", format(result_1, ".2f")) elif qty >= 20 and qty <=49: result2 =(20*retails_price/100) result_2 = retails_price - result2 print("Discount amount @20%:$", format(result2)) print("Total amount: $", format(result_2, ".2f")) elif qty >= 50 and qty <=99: result3 = (50 * retails_prices/100) result_3 = retails_price - result3 print("Discount amount @30%:$", format(result3)) print("Total amount: $", format(result_3, ".2f")) elif qty >= 100 : result4 = (40*retails_price/100) result_4 = retails_price - result4 print("Discount amount @40%:$", format(result4)) print("Total amount: $", format(result_4, ".2f")) else: print("Discount amount @ 0%: $0.00") print("Total amount:$" , format(retails_price, ".2f"))
549556d660759df46ffa9387402059552d0bd4ba
CodingDojoDallas/python_oct_2017
/staci_rodriquez/OOP/callcenter.py
2,306
3.71875
4
class CallCenter(object): def __init__(self): self.calls = [] self.queue_size = 0 #adds a call to the end of the queue def add(self, call): self.calls.append(call) self.queue_size+=1 return self #removes a call by phone number def remove_by_number(self, number): for call in self.calls: if call.number == number: self.calls.remove(call) self.queue_size -= 1 return self else: print("call does not exist") return self #sorts the queue by caller time def sort_queue(self): if len(self.calls) > 1: for pointer in range(len(self.calls)): earliest = 0 for index in range(pointer,len(self.calls)): if self.calls[index].compare(self.calls[earliest]) == 1: earliest = index temp = self.calls[pointer] self.calls[pointer] = self.calls[earliest] self.calls[earliest] = temp return self #removes calls from index 0 of the queue def remove(self): if self.queue_size != 0: self.calls.pop(0) self.queue_size -= 1 else: print("no calls in queue") return self # prints call center info def info(self): print("The Queue Length is {} \nCalls:".format(self.queue_size)) for call in self.calls: call.display() print() class Call(object): unique_id = 0 def __init__(self, name, number, time, reason): Call.unique_id+=1 self.id = self.unique_id self.name = name self.number = number self.time = time self.reason = reason def display(self): print("id: {}\nName: {} \nNumber: {} \nTime: {} \nReason: {}".format(self.id, self.name, self.number, self.time,self.reason)) def compare(self, other): split_time1 = self.time.split(":") split_time2 = other.time.split(":") if split_time1[0] > split_time2[0]: return -1 elif split_time1[0] < split_time2[0]: return 1 else: if split_time1[1] > split_time2[1]: return -1 elif split_time1[1] < split_time2[1]: return 1 return 0 call1 = Call("Mom", 2145552326, "23:51", "You are out past curfue") call1.display() print("---------") cc = CallCenter() call2 = Call("Mom", 2145552326, "23:50", "You are out past curfue") cc.add(call2) cc.add(call1).add(Call("Dad", 9725554321, "3:20", "where are you?")).info() print("---------") cc.sort_queue().info() print("---------") cc.remove_by_number(4695551234).info()
27d2f39716e8a6c8d69cb9448584ebd539a2843f
Faturrahman025/faturrahman
/kelasDemo.py
947
3.984375
4
class Demo(object): def __init__(self, m,p,a): self.mahasiswa = m self.pelajar = p self.aparat = a def hitungJumlah(self): return self.mahasiswa + self.pelajar + self.aparat def cetakData(self): print("mahasiswa\t: ",self.mahasiswa) print("pelajar\t: ",self.pelajar) print("aparat\t: ",self.aparat) def cetakJumlah(self): print("Jumlah Massa\t: ", self.hitungJumlah()) class DemoDpr(Demo): def __init__(self, m,p,a,d): self.mahasiswa = m self.pelajar = p self.aparat = a self.dpr = d def cetakData(self): print("mahasiswa\t: ",self.mahasiswa) print("pelajar\t: ",self.pelajar) print("aparat\t: ",self.aparat) print("dpr\t: ",self.dpr) def main(): DemoDpr1 = DemoDpr(1000,500,400,"Tolak KUHP") DemoDpr1.cetakData() DemoDpr1.cetakJumlah() if __name__ == "__main__" : main()
7f64ec931e7823f036f286b23c272551309c5afb
DCHuTJU/blockchain2021
/graduation/2018级/hudengcheng/code/code/storage_allocation_code/normalization/normalization.py
488
3.53125
4
import numpy as np # 使用 sigmod 归一化函数 def normalization(number_set): for i in range(len(number_set)): number_set[i] = 1.0 / (1 + np.exp(-float(number_set[i]))) return number_set def normalization_with_number(num): return 1.0 / (1 + np.exp(-float(num))) def mapminmax(data, MIN, MAX): d_min = np.min(data) d_max = np.max(data) return MIN + (MAX-MIN) / (d_max - d_min) * (data - d_min) # print(mapminmax([74, 232, 233, 231, 132], 0.1, 1))
3b197763dd054afef7e3a4aafb5f2c5b07cef08d
UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018
/students/RoyC/lesson01/comprehensions.py
321
3.96875
4
#!/usr/bin/env python3 # Lesson 01, Comprehensions import pandas as pd music = pd.read_csv("featuresdf.csv") toptracks = sorted([x for x in zip(music.danceability, music.loudness, music.artists, music.name) if x[0] > 0.8 and x[1] < -5], reverse=True) for track in toptracks[:5]: print(track[3] + " by " + track[2])
3b0fa1960d6b5281a087b45d0f50f5fbc8978bc8
darkraven92/CodeAbbey
/Python/Problem #4 Minimum of Two/problem4.py
196
3.53125
4
c = [] data = int(input("data:\n")) for i in range(data): x,y = input().split() if int(x) < int(y): c.append(x) else: c.append(y) for u in c: print(u, end =" ")