blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
908d5750b2bbb33fb78bd7b5037b15193ce1d4ec
codyduong/OPS-IncomeVis
/csvCreator/dataHandler.py
1,245
3.625
4
import json import csv #For the curious, the JSON is formatted such that each employee is given their own unique key-name for easier accessing of specific employees. def writeToJson(e, filename): """ Converts {employee: [Location, Position],...} to JSON """ with open(filename, "w") as f: content = json.dumps(e, indent=4) f.write(content) #YML below # s = 'employees:\n\n' # for person in e: # s += '- name: %s\n location: %s\n position: %s\n\n' % (person, e[person][0], e[person][1]) # f.write(s) #handles the funky way I store json to CSV, rather than standardized json def writeWeirdJSONtoCSV(weirdJSON, filename): fields = ['name', 'location', 'position', 'category', 'income'] rows = [] #--> [[Name, Location, Position, Income], ...] for name in weirdJSON: nD = weirdJSON[name] #nameDumped, because for some reason it thinks name == string. idk java explicit typecasting better smh rows.append([name, nD['location'], nD['position'], nD['category'], nD['income']]) with open(filename, 'w', newline='') as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow(fields) csvwriter.writerows(rows)
27131fa53a7c1f1ec3336b515dcf68b87aeff8ea
travisobregon/itt-big-data-ca
/mapper.py
283
3.671875
4
#!/usr/bin/python # Format of each line is: # Job Title, Total Pay, Gender import sys for line in sys.stdin: data = line.strip().split("\t") if len(data) == 3: job_title, total_pay, gender = data print "{0}\t{1},{2}".format(job_title, total_pay, gender)
f13b94ea8ee9284aebfacc1631cd852586380dd1
fatihaydnn/Python
/Kumanda.py
2,854
3.90625
4
# Televizyon Kumandası Uygulaması: """ İşlemler: 1. Televizyonu Aç - tv durumu = "Açık" 2. Televizyonu Kapat - tv durumu = "Kapalı" 3. Televizyon Bilgileri - o anki kanal, ses durumu, tüm kanallar. 4. Kanal Ekle - kanal listesine kanalı ekle 5. Rastgele Kanal Aç - random bir kanalı açar 6. Sesi Azalt Arttır - ses arttır/azalt """ from random import randint as r class Kumanda: def __init__(self, tv_durum="Kapalı", tv_ses=0, kanal_listesi=["Trt"], kanal="Trt"): print("Kumanda Oluşturuluyor") self.tv_sesi = tv_ses self.tv_durumu = tv_durum self.kanal_listesi = kanal_listesi self.kanal = kanal def ses_azalt_arttir(self): while True: karakter = input("Ses Azaltmak için '<', arttırmak için '>' , Çıkış için 'q' ya basınız..") if karakter == '<': if self.tv_sesi != 0: self.tv_sesi -= 1 print("Ses : {}".format(self.tv_sesi)) elif karakter == '>': if self.tv_sesi != 15: self.tv_sesi += 1 print("Ses : {}".format(self.tv_sesi)) elif karakter == 'q': print("Ses : {}".format(self.tv_sesi)) break def tv_kapat(self): print("TV Kapatılıyor..") self.tv_durumu = "Kapalı" def tv_ac(self): print("TV Açılıyor...") self.tv_durumu = "Açık" def __str__(self): return "TV Durumu {}\nSes: {}\nŞu Anki Kanal:{}\n".format(self.tv_durumu,self.tv_sesi,self.kanal) def rastgele_kanal(self): rastgele = r(0, len(self.kanal_listesi)-1) self.kanal = self.kanal_listesi[rastgele] print("Şu an açık olan kanal",self.kanal) def kanal_ekle(self, kanal): print("Kanal Eklendi", kanal) self.kanal_listesi.append(kanal) kumanda = Kumanda() print(""" İşlemler: 1. Televizyonu Aç 2. Televizyonu Kapat 3. Televizyon Bilgileri 4. Kanal Ekle 5. Rastgele Kanal Aç 6. Sesi Azalt Arttır """) while True: islem = input("İslem Seçiniz") if islem == 'q': print("Programdan çıkılıyor") break elif islem == "1": kumanda.tv_ac() elif islem == "2": kumanda.tv_kapat() elif islem == "3": print(kumanda) elif islem == "4": kanallar = input("Eklemek istediğiniz kanalları ',' ile ayırarak giriniz") eklenecekler = kanallar.split(",") for x in eklenecekler: kumanda.kanal_ekle(x) print("Kanal Ekleme Başarılı") elif islem == "5": kumanda.rastgele_kanal() elif islem == "6": kumanda.ses_azalt_arttir() else: print("Geçersiz İşlem")
c5c77da3e67eacdc6c02fa2f052ae89c508cd743
FalseG0d/PythonGUIDev
/Sample.py
236
4.125
4
from tkinter import * root=Tk() #To create a Window label=Label(root,text="Hello World") #To create text on label and connect it to root label.pack() #to put it on root root.mainloop() #To avoid closing until close button is clicked
63e41a1d3d91e5f40b158189589022d36a55256c
FalseG0d/PythonGUIDev
/MessageBox.py
714
3.703125
4
from tkinter import * from tkinter import messagebox def call_me(): messagebox.showinfo("Success","Hello World") #messagebox.showerror("Success","Hello World") #messagebox.showwarning("Success","Hello World") def ask_question(): #answer=messagebox.yesnocancel("Exit","Are you sure?") #print(answer) #returns True False None answer=messagebox.askquestion("Exit","Are you sure?") #print(answer) if answer=='yes': root.quit() root=Tk() b1=Button(root,text="Message",command=call_me) b1.pack() b2=Button(root,text="Exit",command=ask_question) b2.pack() root.geometry("300x150+120+120") #width x height+(distance from x axis)+(distance from y axis) root.mainloop()
41aeac28dcbfd65a68bcda38b7b5ba602a1c23b1
PaulJoshi/hospital_management_system
/core/patients.py
3,773
3.5
4
import pickle import datetime class Patient : def __init__(self): self.name = "" self.age = None self.gender = "" def create_user(self,age,gender) : ''' Adds a new patient to "/database/patients.pkl" in database ''' self.age = age self.gender = gender patient = [self.name, self.age, self.gender] with open("database/patients.pkl", "rb") as file: all_patients = pickle.load(file) all_patients.append(patient) with open("database/patients.pkl", "wb") as file: pickle.dump(all_patients, file) def patient_exists(self) : ''' Returns 1 if patient already exists, else, returns 0 ''' with open("database/patients.pkl", "rb") as file: all_patients = pickle.load(file) for patient in all_patients: if patient[0].lower() == self.name.lower(): return 1 return 0 def get_doctors(self, specialization) : ''' Returns list of doctors with specified specialization ''' doctors = [] with open("database/doctors.pkl", "rb") as file : all_doctors = pickle.load(file) for doctor in all_doctors: if doctor[1].lower() == specialization.lower() : doctors.append(doctor) if len(doctors) == 0: return 0 return doctors def make_appointment(self, doctor, date) : ''' Adds an appointment to "/database/appointments.pkl" in database ''' if date == 1: a = datetime.datetime.today() current_date = a.day, a.month, a.year appointment = [doctor, self.name, current_date] elif date == 2: b = datetime.datetime.today() next_date = b.day + 1, b.month, b.year appointment = [doctor, self.name, next_date] elif date == 3: c = datetime.datetime.today() next_next_date = c.day + 2, c.month, c.year appointment = [doctor, self.name, next_next_date] else: return 0 with open("database/appointments.pkl", "rb") as file : appointments=pickle.load(file) with open("database/appointments.pkl", "wb") as file : appointments.append(appointment) pickle.dump(appointments, file) return 1 def update_user(self,name, age) : ''' Changes the details of given user in "/database/patients.pkl" in database ''' with open("database/patients.pkl", "rb") as file: patients = pickle.load(file) for patient in patients: if patient[0].lower() == self.name.lower(): patient[0] = name patient[1] = age with open("database/patients.pkl", "wb") as file: pickle.dump(patients,file) with open("database/appointments.pkl", "rb") as file: appointments = pickle.load(file) for appointment in appointments: if appointment[1].lower() == self.name.lower(): appointment[1] = name with open("database/appointments.pkl", "wb") as file: pickle.dump(appointments, file) self.name = name self.age = age def get_appointments(self) : ''' Get all appointments of given patient name ''' appointments = [] with open("database/appointments.pkl", "rb") as file: all_appointments = pickle.load(file) for appointment in all_appointments: if appointment[1].lower() == self.name.lower(): appointments.append(appointment) return appointments
3766ef11f0b53fea8ad5349b1f5e975830b74b28
brainmentorspvtltd/rd_python_iot
/SecondDay.py
16,527
3.890625
4
''' New Question Take input of 2 strings Print true if they're anagrams, otherwise false. Google anagrams if you don't know about them. ''' Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license()" for more information. >>> a = 10 >>> type(a) <class 'int'> >>> a = 10.2 >>> type(a) <class 'float'> >>> a = "hello" >>> type(a) <class 'str'> >>> a = true Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> a = true NameError: name 'true' is not defined >>> a = "true" >>> type(a) <class 'str'> >>> a = True >>> type(a) <class 'bool'> >>> #I18N - Internationalization >>> a = "राम " >>> a 'राम ' >>> a.encode() b'\xe0\xa4\xb0\xe0\xa4\xbe\xe0\xa4\xae ' >>> b = "hello" >>> b 'hello' >>> a = "राम ram" >>> a.encode() b'\xe0\xa4\xb0\xe0\xa4\xbe\xe0\xa4\xae ram' >>> encodedForm = a.encode() >>> type(encodedForm) <class 'bytes'> >>> encodedForm.decode() 'राम ram' >>> a=10 >>> float(a) 10.0 >>> #Student obj = new Student(); >>> str(a) '10' >>> bool(a) True >>> bool(0) False >>> bool(-10) True >>> a = 10.2 >>> int(a) 10 >>> str(a) '10.2' >>> bool(a) True >>> a = "python" >>> int(a) Traceback (most recent call last): File "<pyshell#34>", line 1, in <module> int(a) ValueError: invalid literal for int() with base 10: 'python' >>> int('a') Traceback (most recent call last): File "<pyshell#35>", line 1, in <module> int('a') ValueError: invalid literal for int() with base 10: 'a' >>> ord('a') 97 >>> ord(' ') 32 >>> ord('abc') Traceback (most recent call last): File "<pyshell#38>", line 1, in <module> ord('abc') TypeError: ord() expected a character, but string of length 3 found >>> #ordinal value -> ascii value >>> chr(97) 'a' >>> chr(32) ' ' >>> chr(65) 'A' >>> bin(65) '0b1000001' >>> id(a) 4342198376 >>> hex(id(a)) '0x102d0b068' >>> oct(123) '0o173' >>> bool("python") True >>> bool(" ") True >>> bool("") False >>> bool(None) False >>> int(0b1000001) 65 >>> bin(0x102d0b068) '0b100000010110100001011000001101000' >>> bin(102d0b068) SyntaxError: invalid syntax >>> bin("102d0b068") Traceback (most recent call last): File "<pyshell#54>", line 1, in <module> bin("102d0b068") TypeError: 'str' object cannot be interpreted as an integer >>> bin(1020068) '0b11111001000010100100' >>> #to see directory of fns a particular object has got use dir() >>> type(a) <class 'str'> >>> dir(str) ['__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', 'isascii', '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'] >>> str.__doc__ "str(object='') -> str\nstr(bytes_or_buffer[, encoding[, errors]]) -> str\n\nCreate a new string object from the given object. If encoding or\nerrors is specified, then the object must expose a data buffer\nthat will be decoded using the given encoding and error handler.\nOtherwise, returns the result of object.__str__() (if defined)\nor repr(object).\nencoding defaults to sys.getdefaultencoding().\nerrors defaults to 'strict'." >>> print(str.__doc__) str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'. >>> 10/20 0.5 >>> 10 // 20 0 >>> 22 / 7 3.142857142857143 >>> 22 // 7 3 >>> #/ -> classic division >>> # // -> floor division >>> >>> 2 * 3 6 >>> 2 ** 3 8 >>> 3 ** 2 9 >>> 3^2 1 >>> 100 ^ 23 115 >>> 123 ^ 90 33 >>> 12.3 ^ 90.9 Traceback (most recent call last): File "<pyshell#74>", line 1, in <module> 12.3 ^ 90.9 TypeError: unsupported operand type(s) for ^: 'float' and 'float' >>> 12.3 ^ 90 Traceback (most recent call last): File "<pyshell#75>", line 1, in <module> 12.3 ^ 90 TypeError: unsupported operand type(s) for ^: 'float' and 'int' >>> bin(10.2) Traceback (most recent call last): File "<pyshell#76>", line 1, in <module> bin(10.2) TypeError: 'float' object cannot be interpreted as an integer >>> a=0 >>> a+=66 >>> 22 = 66 SyntaxError: can't assign to literal >>> "22".isidentifier() False >>> "a22".isidentifier() True ] >>> oct = 10 >>> oct(10) Traceback (most recent call last): File "<pyshell#83>", line 1, in <module> oct(10) TypeError: 'int' object is not callable >>> oct1 = 10 >>> True = 10 SyntaxError: can't assign to keyword >>> a = 10 >>> a++ SyntaxError: invalid syntax >>> a + 1 11 >>> a 10 >>> a = a + 1 >>> a 11 >>> a += 1 >>> a = 09 SyntaxError: invalid token >>> a = 0x9 >>> z += 1 Traceback (most recent call last): File "<pyshell#95>", line 1, in <module> z += 1 NameError: name 'z' is not defined >>> z = 10 >>> z += 1 >>> z 11 >>> # a*=1 -> a = a * 1 >>> # a **= 1 >>> a **= 3 >>> a 729 >>> === RESTART: /Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py === Traceback (most recent call last): File "/Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py", line 4, in <module> print("A is " + a) TypeError: can only concatenate str (not "int") to str >>> === RESTART: /Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py === A is10 A is 10 Sum of 10 and 20 is 30 Sum of 10 and 20 is 30 >>> === RESTART: /Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py === A is10b is20 A is 10 b is 20 A is 10 Sum of 10 and 20 is 30 Sum of 10 and 20 is 30 >>> === RESTART: /Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py === Traceback (most recent call last): File "/Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py", line 8, in <module> print("Sum of %d and %d is %d"%(a,b,"10")) TypeError: %d format: a number is required, not str >>> === RESTART: /Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py === Sum of 10 and 20 is 10 >>> === RESTART: /Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py === Sum of 10 and 20 is 10 Sum of 10 and 20 is 30 >>> === RESTART: /Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py === Sum of 10 and 20 is 10 Traceback (most recent call last): File "/Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py", line 10, in <module> print("Sum of {} and {} is {}. Total result is {}".format(a,b,c)) IndexError: tuple index out of range >>> === RESTART: /Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py === Sum of 10 and 20 is 10 Traceback (most recent call last): File "/Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py", line 10, in <module> print("Sum of {} and {} is {2}. Total result is {2}".format(a,b,c)) ValueError: cannot switch from automatic field numbering to manual field specification >>> === RESTART: /Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py === Sum of 10 and 20 is 10 Sum of 10 and 20 is 30. Total result is 30 >>> === RESTART: /Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py === Sum of 10 and 20 is 10 Sum of 10 and 20 is 30. Total result is 30 Sum of 10 and 20 is 30. Total result is 30 >>> === RESTART: /Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py === Sum of 10 and 20 is 10 Sum of 10 and 20 is 30. Total result is 30 Sum of 10 and 20 is 30. Total result is 30 Enter your name : Ram Name is Ram >>> === RESTART: /Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py === Sum of 10 and 20 is 10 Sum of 10 and 20 is 30. Total result is 30 Sum of 10 and 20 is 30. Total result is 30 Enter your name : nmk Name is nmk Name is {name} >>> === RESTART: /Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py === Sum of 10 and 20 is 10 Sum of 10 and 20 is 30. Total result is 30 Sum of 10 and 20 is 30. Total result is 30 Enter your name : Ram Name is Ram Name is Ram >>> === RESTART: /Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py === Sum of 10 and 20 is 10 Sum of 10 and 20 is 30. Total result is 30 Sum of 10 and 20 is 30. Total result is 30 Enter your name : Ram Name is Ram Name is Ram Ram >>> === RESTART: /Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py === Sum of 10 and 20 is 10 Sum of 10 and 20 is 30. Total result is 30 Traceback (most recent call last): File "/Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py", line 12, in <module> print("Sum of {num} and {1} is {2}. Total result is {2}".format(a,b,c)) KeyError: 'num' >>> === RESTART: /Users/anmolrajarora/Documents/rd_college_python_iot/Demo.py === Sum of 10 and 20 is 10 Sum of 10 and 20 is 30. Total result is 30 Sum of 10 and 20 is 30. Total result is 30 Enter your name : Ram Name is Ram Name is Ram Ram First element is 1 >>> 0.1 0.1 >>> 0.2 0.2 >>> 0.1 + 0.2 0.30000000000000004 >>> 0.1000000001 + 0.200000000000003 0.300000000100003 >>> 0.1 + 0.3 0.4 >>> list1 = [1,2,3,4,5] >>> list1 [1, 2, 3, 4, 5] >>> list1[0] 1 >>> list1[1] 2 >>> list1[2] 3 >>> list1 = [1,2,3,4,5,"six"] >>> import numpy >>> arr1 = [1,2,3,4,5,"six"] >>> arr1 = np.array(arr1) Traceback (most recent call last): File "<pyshell#117>", line 1, in <module> arr1 = np.array(arr1) NameError: name 'np' is not defined >>> arr1 = numpy.array(arr1) >>> arr1 array(['1', '2', '3', '4', '5', 'six'], dtype='<U21') >>> arr1 = numpy.array([1,2,3,4,5]) >>> arr1 array([1, 2, 3, 4, 5]) >>> list1= [1,2,3,4,5,"six"] >>> list1 [1, 2, 3, 4, 5, 'six'] >>> list1.append(10) >>> list1 [1, 2, 3, 4, 5, 'six', 10] >>> list1.pop() 10 >>> tuple1 = [1, 2, 3, 4, 5, 'six'] >>> tuple1 [1, 2, 3, 4, 5, 'six'] >>> tuple1 = (1, 2, 3, 4, 5, 'six') >>> tuple1 (1, 2, 3, 4, 5, 'six') >>> dir(tuple) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index'] >>> list1 [1, 2, 3, 4, 5, 'six'] >>> del list1[5] >>> list1 [1, 2, 3, 4, 5] >>> del tuple1[0] Traceback (most recent call last): File "<pyshell#135>", line 1, in <module> del tuple1[0] TypeError: 'tuple' object doesn't support item deletion >>> tuple1 = (1,2,3,4,5, [11,22,33,44,55]) >>> del tuple1[0] Traceback (most recent call last): File "<pyshell#137>", line 1, in <module> del tuple1[0] TypeError: 'tuple' object doesn't support item deletion >>> tuple1[5] [11, 22, 33, 44, 55] >>> tuple1[5].append(66) >>> tuple1 (1, 2, 3, 4, 5, [11, 22, 33, 44, 55, 66]) >>> tuple1[5] = [1,2,3,4,5] Traceback (most recent call last): File "<pyshell#141>", line 1, in <module> tuple1[5] = [1,2,3,4,5] TypeError: 'tuple' object does not support item assignment >>> list1 [1, 2, 3, 4, 5] >>> list1 = [1, 2, 3, 4, 5, [1,2,3,4,5]] >>> list1 [1, 2, 3, 4, 5, [1, 2, 3, 4, 5]] >>> list2 = list1 >>> list2 [1, 2, 3, 4, 5, [1, 2, 3, 4, 5]] >>> del list1[0] >>> list1 [2, 3, 4, 5, [1, 2, 3, 4, 5]] >>> list2 [2, 3, 4, 5, [1, 2, 3, 4, 5]] >>> list3 = list1.copy() >>> id(list1) == id(list2) True >>> id(list1) == id(list3) False >>> list1.append(100) >>> list1 [2, 3, 4, 5, [1, 2, 3, 4, 5], 100] >>> list2 [2, 3, 4, 5, [1, 2, 3, 4, 5], 100] >>> list3 [2, 3, 4, 5, [1, 2, 3, 4, 5]] >>> list1[4].append(200) >>> list1 [2, 3, 4, 5, [1, 2, 3, 4, 5, 200], 100] >>> list2 [2, 3, 4, 5, [1, 2, 3, 4, 5, 200], 100] >>> list3 [2, 3, 4, 5, [1, 2, 3, 4, 5, 200]] >>> import deepcopy Traceback (most recent call last): File "<pyshell#161>", line 1, in <module> import deepcopy ModuleNotFoundError: No module named 'deepcopy' >>> import copy >>> list4 = copy.deepcopy(list1) >>> id(list1) == id(list4) False >>> id(list1[4]) == id(list4[4]) False >>> id(list1[4]) == id(list3[4]) True >>> list1[4].append(1000) >>> list1 [2, 3, 4, 5, [1, 2, 3, 4, 5, 200, 1000], 100] >>> list2 [2, 3, 4, 5, [1, 2, 3, 4, 5, 200, 1000], 100] >>> list3 [2, 3, 4, 5, [1, 2, 3, 4, 5, 200, 1000]] >>> list4 [2, 3, 4, 5, [1, 2, 3, 4, 5, 200], 100] >>> a = 10 >>> b = 20 >>> a,b = 10,20 >>> a,b = b,a >>> a 20 >>> b 10 >>> a = 10,20 >>> a (10, 20) >>> name = "Ram" >>> print("Welcome",name) Welcome Ram >>> msg = "Welcome",name >>> msg ('Welcome', 'Ram') >>> msg = "Welcome " + name >>> msg 'Welcome Ram' >>> id("Welcome") 4403113688 >>> id(name) 4403113800 >>> id(msg) 4402019696 >>> >>> >>> >>> >>> >>> >>> >>> >>> str1 = "python programming is easy" >>> str1[0] 'p' >>> str1[1] 'y' >>> str1[len(str1) - 1] 'y' >>> str1[-1] 'y' >>> str1[0:5] 'pytho' >>> str1[0:6] 'python' >>> len(str1) 26 >>> str1[0:25] 'python programming is eas' >>> str1[0:26] 'python programming is easy' >>> str1[-1] 'y' >>> str1[-len(str1)] 'p' >>> str1[-1:-5] '' >>> str1[0:26:1] 'python programming is easy' >>> str1[0:26:2] 'pto rgamn ses' >>> str1[0:26:3] 'ph oai s' >>> str1[0:26:5] 'pngisy' >>> str1[-1:-5:-1] 'ysae' >>> str1[-5:-1] ' eas' >>> str1[-5:0] '' >>> str1[-5:] ' easy' >>> str1[:] 'python programming is easy' >>> str1[26:0:-1] 'ysae si gnimmargorp nohty' >>> str1[26:-1:-1] '' >>> str1[26::-1] 'ysae si gnimmargorp nohtyp' >>> str1[::-1] 'ysae si gnimmargorp nohtyp' >>> dir(str) ['__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', 'isascii', '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'] >>> print("Welcome user!") Welcome user! >>> print("Welcome user!".center(100)) Welcome user! >>> print("Welcome user!".center(110)) Welcome user! >>> "Welcome user!".center(110) ' Welcome user! ' >>> "Welcome user!".center(110,"*") '************************************************Welcome user!*************************************************' >>> msg 'Welcome Ram' >>> msg.endswith('Ram') True >>> msg.count("a") 1 >>> msg.count("Ram") 1 >>> msg = 'Welcome RamRam' >>> msg.count("Ram") 2 >>> msg 'Welcome RamRam' >>> msg.index("a") 9 >>> msg.rindex("a") 12 >>> msg = 'Welcome RamRamRam' >>> msg.index("a") 9 >>> msg.rindex("a") 15 >>> msg.index("a", 10) 12 >>> msg.index("a", msg.index("a")) 9 >>> msg.index("a", msg.index("a") + 1) 12 >>> msg 'Welcome RamRamRam' >>> msg.split('a') ['Welcome R', 'mR', 'mR', 'm'] >>> msg = 'Welcome RamRamRaam' >>> msg.split('a') ['Welcome R', 'mR', 'mR', '', 'm'] >>> msg.partition('a') ('Welcome R', 'a', 'mRamRaam') >>> msg.replace("a","x") 'Welcome RxmRxmRxxm' >>> msg.replace("a","") 'Welcome RmRmRm' >>> msg.replace("a"," ") 'Welcome R mR mR m' >>> msg.split("a") ['Welcome R', 'mR', 'mR', '', 'm'] >>> tokens = msg.split("a") >>> tokens ['Welcome R', 'mR', 'mR', '', 'm'] >>> 'a'.join(tokens) 'Welcome RamRamRaam' >>>
99d7231dc880871ffc6a23324fd8e72bb1b7b628
arpit0891/Project-Euler
/p265.py
1,591
3.703125
4
# In this problem we look at 2^n-digit binary strings and the n-digit substrings of these. # We are given that n = 5, so we are looking at windows of 5 bits in 32-bit strings. # # There are of course 32 possible cyclic windows in a 32-bit string. # We want each of these windows to be a unique 5-bit string. There are exactly 2^5 = 32 # possible 5-bit strings, hence the 32 windows must cover the 5-bit space exactly once. # # The result requires the substring of all zeros to be in the most significant bits. # We argue that the top n bits must be all zeros, because this is one of the cyclic windows # and the value 00...00 must occur once. Furthermore the next and previous bit must be 1 - # because if they're not, then at least one of the adjacent windows are also zero, which # violates the uniqueness requirement. # # With n = 5, this means every candidate string must start with 000001 and end with 1. # In other words, they are of the form 000001xxxxxxxxxxxxxxxxxxxxxxxxx1. # The middle 25 bits still need to be determined, and we simply search by brute force. def compute(): N = 5 # Must be at least 1 TWO_POW_N = 2**N MASK = TWO_POW_N - 1 # Equal to n 1's in binary, i.e. 0b11111 def check_arrangement(digits): seen = set() digits |= digits << TWO_POW_N # Make second copy for i in range(TWO_POW_N): seen.add((digits >> i) & MASK) return len(seen) == TWO_POW_N start = 2**(TWO_POW_N - N - 1) + 1 end = 2**(TWO_POW_N - N) ans = sum(i for i in range(start, end, 2) if check_arrangement(i)) return str(ans) if __name__ == "__main__": print(compute())
968460d960e69e40a3dd73190e39bc3e9f6812ff
arpit0891/Project-Euler
/p029.py
296
3.96875
4
# We generate all the possible powers in the given range, put each value # into a set, and let the set count the number of unique values present. def compute(): seen = set(a**b for a in range(2, 101) for b in range(2, 101)) return str(len(seen)) if __name__ == "__main__": print(compute())
1684a3c6ac6cb0069166ecdc9884b3eae1e7962b
arpit0891/Project-Euler
/p065.py
341
3.578125
4
def compute(): numer = 1 denom = 0 for i in reversed(range(100)): numer, denom = e_contfrac_term(i) * numer + denom, numer ans = sum(int(c) for c in str(numer)) return str(ans) def e_contfrac_term(i): if i == 0: return 2 elif i % 3 == 2: return i // 3 * 2 + 2 else: return 1 if __name__ == "__main__": print(compute())
a6bd48ccdb050035229962628efefc35d9955cb7
arpit0891/Project-Euler
/p119.py
1,201
3.828125
4
import itertools # Candidates have the form n^k, where n >= 2, k >= 2, n^k >= 10, and isDigitSumPower(n^k) == true. # We also impose n^k < limit. If there are at least 30 candidates under 'limit', # then the 30th smallest candidate is the answer. Otherwise we raise the limit and search again. # # We only need to try the exponents k until 2^k exceeds the limit. # We only need to try the bases n until the power of the digit sum is too small to match n^k. # The power of the digit sum is digitSum(n^k)^k, which is at most (9 * digitLength(n^k))^k. def compute(): INDEX = 30 # 1-based limit = 1 while True: candidates = set() k = 2 while (1 << k) < limit: for n in itertools.count(2): pow = n**k if pow >= limit and len(str(pow)) * 9 < n: break if pow >= 10 and is_digit_sum_power(pow): candidates.add(pow) k += 1 if len(candidates) >= INDEX: return str(sorted(candidates)[INDEX - 1]) limit <<= 8 def is_digit_sum_power(x): digitsum = sum(int(c) for c in str(x)) if digitsum == 1: # Powers of 10 are never a power of 1 return False pow = digitsum while pow < x: pow *= digitsum return pow == x if __name__ == "__main__": print(compute())
1c5096a00eac1ca44c9efaee7d333ec4b3a74b53
arpit0891/Project-Euler
/p122.py
4,115
4.15625
4
import itertools # This problem uses the concepts of https://en.wikipedia.org/wiki/Addition_chain # and https://en.wikipedia.org/wiki/Addition-chain_exponentiation . # # Definition: An addition chain is a finite sequence of integers {a_i} such that: # - a_0 = 1 (i.e. the head element is 1). # - For each index i (with 0 < i < length), there exists indices j and k such that 0 <= j <= k < i # and a_i = a_j + a_k (i.e. each subsequent element is the sum of some two elements that come before it). # - The number of operations in an addition chain is equal to the length of the chain minus one. # # Example: {1, 2, 3, 6, 9, 11} is an addition chain because # 2 = 1 + 1, 3 = 1 + 2, 6 = 3 + 3, 9 = 3 + 6, 11 = 2 + 9. # This chain has length 6, and uses 5 addition operations. # # Note: A star chain or Brauer chain is an addition chain with the stronger condition that for each i > 0, # there exists an index j such that 0 <= j < i and a_i = a_{i-1} + a_j. However, a minimum-length star chain # might be longer than the minimum-length general addition chain. A counterexample is known for 12509; # the shortest addition chain that produces 12509 is shorter than the shortest star chain that produces it. # This is unfortunate because searching star chains is much faster than searching general addition chains. # # The overall strategy of this solution is to explore all addition chains by brute force using depth-first search. # We start with the base chain of {1}, progressively add elements that are the sum of some two earlier elements, # and backtrack at each stage. No memoization or breadth-first search is performed because the search space is large. # # An important detail is that we perform depth-limited search of the full search space, with depth = 1, 2, 3, etc. # This gives us the benefit of breadth-first search without its high memory usage - namely, the first time # we visit a sum of n, we can be sure that it has been reached with the smallest possible chain length. # # A crucial algorithmic optimization is that we only consider addition chains that are strictly increasing. # Clearly there is no benefit to producing a certain term twice within the same sequence (e.g. 2 + 2 = 4 and 1 + 3 = 4). # As for the increasing order, we argue that for every addition chain that isn't strictly increasing, it can be # reordered to one that is strictly increasing. For example, the chain {1, 2, 4, 3} can be reordered to {1, 2, 3, 4}. # This is because if a_i > a_{i+1}, then a_{i+1} can't possibly use a_i as an addend (which are all positive), # and it must have used two terms that are strictly in front of index i. Therefore, exploring only strictly increasing # addition chains will still give us full coverage of the search space. def compute(): # Set up initial array of known/unknown minimum operation counts LIMIT = 200 minoperations = [0, 0] + [None] * (LIMIT - 1) numunknown = [LIMIT - 1] # Use list instead of scalar to work around Python 2's broken scoping # Recursively builds up chains and compares them to chain lengths already found. def explore_chains(chain, maxops): # Depth-based termination or early exit if len(chain) > maxops or numunknown[0] == 0: return # Try all unordered pairs of values in the current chain max = chain[-1] # Peek at top for i in reversed(range(len(chain))): for j in reversed(range(i + 1)): x = chain[i] + chain[j] if x <= max: break # Early exit due to ascending order if x <= LIMIT: # Append x to the current chain and recurse chain.append(x) if minoperations[x] is None: # For each unique value of x, we set minoperations[x] only once # because we do progressive deepening in the depth-first search minoperations[x] = len(chain) - 1 numunknown[0] -= 1 explore_chains(chain, maxops) chain.pop() # Perform bounded depth-first search with incrementing depth for ops in itertools.count(1): if numunknown[0] == 0: # Add up the results return str(sum(minoperations)) explore_chains([1], ops) if __name__ == "__main__": print(compute())
2c611be54a9022133cfe5a5de20ac4c8b45c289d
arpit0891/Project-Euler
/p103.py
13,035
4.09375
4
import itertools # We start with three pedantic lemmas to constrain the nature of possible solutions. # # No-zero lemma: # A special sum set (SSS) should not contain the value 0. The problem statement # doesn't say this explicitly, but it is implied in the numerical examples. # Proof: # - For size n = 0, {} technically qualifies as an SSS, and is trivially optimum. # But the problem statement does not mention the n = 0 case at all. # - For size n = 1, {0} has sum 0, which is better than the SSS {1} given in the # problem statement, yet this violates no properties. Even though the subsets # {} and {0} have the same sum of 0, the properties only apply to non-empty subsets. # - For size n = 2, {0,1} has sum 1, which is better than the SSS {1,2} given in # the problem statement, yet this still violates no properties. There is exactly # one possible pair of non-empty disjoint subsets, namely {0} vs. {1}, and # this pair satisfies both properties. # - For sizes n >= 3, having 0 in the set would violate property (ii) for the pair of # subsets {0,a} and {b}, where 0 and a and b are distinct elements of the set and a < b. # Hence for 0 <= n <= 2, allowing 0 would produce a more optimum solution than the # examples given in the problem statement, and for n >= 3 an SSS can never contain 0. # # As for negative numbers, the intent of the problem statement readily suggests that elements # are never negative. Furthermore, having negative numbers in a set would either affect the # sum by only a small amount or violate property (ii), making the problem uninteresting. # # Upper bound lemma: # For each natural number n >= 0, there exists a special sum set # whose size is n and whose sum is (n + 1) * 2^n - 1. # Proof: # - For each index i (counting from 0), let element i equal 2^n + 2^i. # - The sum of all the elements is (2^n + 2^0) + (2^n + 2^1) + ... + (2^n + 2^(n-1)) # = n * 2^n + (2^0 + 2^1 + ... + 2^(n-1)) = n * 2^n + 2^n - 1 = (n + 1) * 2^n - 1. # - For example with n = 4, the elements expressed in binary are {10001, # 10010, 10100, 11000}. Their sum is 1001111 (binary) = 79 (decimal). # - Notice that when summing a subset of (distinct) elements, the bottom n bits # never produce a carry. This means the bottom n bits behave like a set union, # and the activity in the bottom n bits never affect the 2^n term or above. # - Property (i) is satisfied because for any subset B, the bottommost n bits of S(B) # encode which elements are present. Thus any two unequal subsets will have unequal sums. # - Property (ii) is satisfied because for any subset B, the value floor(S(B) / 2^n) # (i.e. dropping the bottommost n bits) encodes the size of B. # Corollaries: # - For any given upper bound, there are a finite number of {{sets of positive integers} # whose sum doesn't exceed the upper bound}. Thus once we find an SSS with a certain sum, # we can argue by finite search that there must exist an optimum SSS whose sum is # less than or equal to the aforementioned sum. # - For size 7, we know there exists an SSS of sum exactly (7 + 1) * 2^7 - 1 = 1023. # Hence we don't need to search any larger sums. # # Lower bound lemma: # For each n >= 3, each special sum set of size n must have sum at least 2^n. # Proof: # - A set of size n has exactly 2^n - 1 non-empty subsets # (the kind relevant to the problem statement). # - Because all elements are positive integers, the lowest possible # subset sum is 1, and the highest sum is the sum of all elements. # - To satisfy property (i) and give each non-empty subset a unique sum, the # set of sums with the smallest maximum value is {1, 2, 3, ..., 2^n - 1}. # - To achieve the aforementioned set of subset sums using positive elements, # the one and only solution is the set {1, 2, 4, 8, ..., 2^(n-1)}. # - But for n >= 3, the pair of subsets {1,2} and {4} violates property (ii). # - Hence the set cannot have sum 2^n - 1. It must have a sum of at least 2^n. # Corollary: # We can begin searching for an optimum SSS with the initial maximum sum set to 2^n. def compute(): TARGET_SIZE = 7 # At the top level, we try larger and smaller values of s until we find the smallest value # of s such that there exists a special sum set with sum at most s. As long as no solution # exists when the sum is at most s - 1, it means that the optimum set's sum is exactly s. # First we try maxsum = 1, 2, 4, 8, ..., doubling the maximum sum until we find a solution. maxsum = 1 while SpecialSumSet.make_set(TARGET_SIZE, maxsum) is None: maxsum *= 2 # Now we know that there must be a special sum set whose sum is at most # maxsum, and also that no solution exists for maxsum / 2. # Perform a kind of binary search to decrease maxsum to the optimal value. # For example, if maxsum = 256, then we know that a solution exists for # maxsum = 256 but no solution exists for maxsum = 128. We don't know if # maxsum = 129, 130, ..., 255 will yield solutions. We first try maxsum # = 256 - 64, and depending on whether a solution exists, we eliminate # either the bottom half of the search range or the top half. Then we # try smaller steps, and stop after handling a step size of 1. i = maxsum // 4 while i > 0: maxsum -= i if SpecialSumSet.make_set(TARGET_SIZE, maxsum) is None: maxsum += i i //= 2 set = SpecialSumSet.make_set(TARGET_SIZE, maxsum) # Must be not None return "".join(map(str, set.values)) # This helper class represents a finite sequence of distinct positive integers # that satisfies properties (i) and (ii) given in the problem statement. # Objects of the class are immutable. Objects also keep track of extra data to # make it easier to check if adding a new element would violate the properties, # without explicitly checking every non-empty disjoint subset pair by brute force. class SpecialSumSet(object): # Returns the lexicographically lowest special sum set with the given size # and with a sum of at most maximumsum, or None if no such set exists. @staticmethod def make_set(targetsize, maximumsum): return SpecialSumSet._make_set(SpecialSumSet([], [True], [0], [0]), targetsize, maximumsum, 1) # Returns the lexicographically lowest special sum set by adding exactly sizeremain elements # to the given set, such that the sum of the additional elements is at most sumremain, # and the next element to be added is at least startval. Returns None if no such set exists. @staticmethod def _make_set(set, sizeremain, sumremain, startval): # In summary, this procedure takes a partial answer (prefix) and some parameters, # and tries to extend the answer by performing depth-first search through recursion. if sizeremain == 0: # Base case - success return set # Optimization: If we still need to add at least 2 elements, then the next element # will be at least startval, the one after will be at least startval + 1, # thereafter is at least startval + 2, et cetera. The sum of the elements # to be added is strictly greater than startval * sizeremain, which we can # check against sumremain and bail out early if a solution is impossible. if sizeremain >= 2 and startval * sizeremain >= sumremain: return None endval = sumremain # Optimization: If the partial set has at least two elements a and b, then by the # property (ii), S({a, b}) = a + b must be greater than any single element of the set. # We use the foremost two elements, which have the smallest values - this makes # endval as small and restrictive as possible compared to other choices of elements. if len(set.values) >= 2: endval = min(set.values[0] + set.values[1] - 1, endval) # Consider each possible value for the next element for val in range(startval, endval + 1): # Try adding the value and see if any property is violated temp = set.add(val) if temp is None: continue # Recurse and see if a solution is found down the call tree temp = SpecialSumSet._make_set(temp, sizeremain - 1, sumremain - val, val + 1) if temp is not None: return temp return None # No solution for the given current state # Internal constructor. The contents of the given list objects must not change. def __init__(self, vals, sumposb, minsum, maxsum): # Note: All fields are conceptually immutable # Positive numbers in strict ascending order. Length 0 or more. self.values = vals # For indexes i from 0 to sum(values) inclusive, sumpossible[i] # is true iff there exists a subset of 'values' whose sum is i. self.sumpossible = sumposb # For i from 0 to len(values) (inclusive), minimumsum[i] is the minimum sum # among all possible subsets of 'values' of size i, and likewise for maximumsum[i]. self.minimumsum = minsum self.maximumsum = maxsum # Attempts to add the given value to this set, returning a new set # if successful. Otherwise returns None if any property is violated. def add(self, val): # Simple checks on the value if val <= 0: raise ValueError("Value must be positive") size = len(self.values) if size >= 1 and val <= self.values[-1]: raise ValueError("Must add values in ascending order") # Check if adding val to any subset of this set would create a duplicate sum posb = self.sumpossible if any((posb[i] and posb[i - val]) for i in range(val, len(posb))): return None # Compute minimum and maximum sums for each subset size, with help from old data. # The idea is that by introducing the new value val, each subset of the new set # either contains val or doesn't. All old subsets are still possible, so we copy # the old tables of minima and maxima. Each new subset contains val plus an old subset # (possibly empty). Hence we look at the existing minima and maxima, add val to the sum, # add 1 to the size, and merge the values into the table of minima and maxima. newsize = size + 1 minsum = self.minimumsum maxsum = self.maximumsum newmin = [0] + [min(minsum[i], minsum[i - 1] + val) for i in range(1, newsize)] + [minsum[size] + val] newmax = [0] + [max(maxsum[i], maxsum[i - 1] + val) for i in range(1, newsize)] + [maxsum[size] + val] # Check iff property (ii) '|B| > |C| implies S(B) > S(C)' is violated if any((newmax[i] >= newmin[i + 1]) for i in range(newsize)): return None # Compute all possible new subset sums, with help from old data. This is the # classic table-based algorithm for solving the subset sum or knapsack problem. newposb = posb + [False] * val for i in reversed(range(val, len(newposb))): newposb[i] |= newposb[i - val] # Append given value to the new set return SpecialSumSet(self.values + [val], newposb, newmin, newmax) # An illustrative example for SpecialSumSet and add(): # # Suppose our current set is {3, 5, 6}. All its subsets and their sums are: # - S({}) = 0. # - S({3}) = 3. # - S({5}) = 5. # - S({6}) = 6. # - S({3, 5}) = 8. # - S({3, 6}) = 9. # - S({5, 6}) = 11. # - S({3, 5, 6}) = 14. # # Therefore, the data arrays have the following values: # - sumpossible = [T, F, F, T, F, T, T, F, T, T, F, T, F, F, T]. # (Sum legend: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14) # - minimumsums = [0, 3, 8, 14]. # - maximumsums = [0, 6, 11, 14]. # - (Size legend: 0 1 2 3) # # Now suppose we want to add the value 7 to the set. Here is what happens: # - First we check that in sumpossible, no pair of 'true' elements are # separated by a distance of 7. This ensures that if we take any particular # subset and add 7 to it, its sum won't equal another existing subset sum. # - Let the new set S' = S union {7} = {3, 5, 6, 7}. What are # the minimum and maximum subset sums for each subset size k? # - If k = 0, the min and max are both clearly 0. # - If k = |S| = 4, then min and max are the sum of all elements, thus 21. # - Otherwise with k > 0, consider an arbitrary subset A of S' where |A| = k. # - If A does not contain 7, then A is a subset of S, so A's # minimum sum is minimumsums[k] and A's maximum sum is maximumsums[k]. # - Otherwise split A = {7} union B, where B does not contain 7. # B is a subset of S, and |B| = k - 1. So A's minimum sum is # 7 + minimumsums[k - 1], and A's maximum sum is 7 + maximumsums[k - 1]. # Hence newminimumsums[k] = min(minimumsums[k], 7 + minimumsums[k - 1]), # and newmaximumsums[k] = max(maximumsums[k], 7 + maximumsums[k - 1]). # For each size k that is not out of bounds, if maximumsums[k] >= minimumsums[k + 1], # then there exists some set of size k with some set of size k + 1 fails property (ii). # Otherwise property (ii) is upheld in all subset pairs (including empty subsets). # - Finally, we compute the new sumpossible table (which is guaranteed to # have no conflicts), and finish creating the new set with the added element. if __name__ == "__main__": print(compute())
61ceabf03505c5291a06720e53adf674b6af92e8
arpit0891/Project-Euler
/p425.py
2,634
3.75
4
import eulerlib, heapq # Finding all the relatives of 2 can be seen as a single-source shortest path problem, # which we solve here using Dijkstra's algorithm. The key insight is that at each node (prime number), # we consider the connection path from 2 to it, and store the maximum path number at the node. # It is amenable to dynamic programming because it's always best to minimize the maximum path number. # # For example, 2 is connected to 103 because 2 <-> 3 <-> 13 <-> 113 <-> 103. # The maximum number along this path is 113, and among all paths # this is the minimum possible maximum, so 103 is not a relative of 2. def compute(): LIMIT = 10**7 isprime = eulerlib.list_primality(LIMIT) # pathmax[i] = None if i is not prime or i is not connected to 2. # Otherwise, considering all connection paths from 2 to i and for each path computing # the maximum number, pathmax[i] is the minimum number among all these maxima. pathmax = [None] * len(isprime) # Process paths in increasing order of maximum number queue = [(2, 2)] while len(queue) > 0: pmax, n = heapq.heappop(queue) if pathmax[n] is not None and pmax >= pathmax[n]: # This happens if at the time this update was queued, a better # or equally good update was queued ahead but not processed yet continue # Update the target node and explore neighbors pathmax[n] = pmax # Try all replacements of a single digit, including the leading zero. # This generates exactly all (no more, no less) the ways that a number m is connected to n. digits = to_digits(n) tempdigits = list(digits) for i in range(len(tempdigits)): # For each digit position for j in range(10): # For each digit value tempdigits[i] = j m = to_number(tempdigits) nextpmax = max(m, pmax) if m < len(isprime) and isprime[m] and (pathmax[m] is None or nextpmax < pathmax[m]): heapq.heappush(queue, (nextpmax, m)) tempdigits[i] = digits[i] # Restore the digit ans = sum(i for i in range(len(isprime)) if isprime[i] and (pathmax[i] is None or pathmax[i] > i)) return str(ans) # Returns the given non-negative integer as an array of digits, in big endian, with an extra leading zero. # e.g. 0 -> [0,0]; 1 -> [0,1]; 8 -> [0,8]; 42 -> [0,4,2]; 596 -> [0,5,9,6]. def to_digits(n): if n < 0: raise ValueError() # Extract base-10 digits in little endian temp = [] while True: temp.append(n % 10) n //= 10 if n == 0: break temp.append(0) temp.reverse() return temp def to_number(digits): result = 0 for x in digits: result = result * 10 + x return result if __name__ == "__main__": print(compute())
7098bd17195206fcddee8505e4d0ec80eab6f7b8
Martsyalis/python-practice
/set.py
194
3.671875
4
def get_count(input_str): return sum(1 for c in input_str if c in 'aeou') print(get_count('aeousssssss')) def friend(x): return sum([1 for f in x if f in 'ad']) print(friend('abcd'))
ecf81505386eb8b1fde34224ad2eefb3e94074a9
adrianw-eecs/Twitter_Streaming_Analysis
/Part 2 - Sentimental Analysis of Tweets with Visualiztion/sentiment_analysis.py
2,736
3.640625
4
import sys, csv, re import operator import nltk from nltk.corpus import stopwordds from nltk.classify import SklearnClassifier from string import punctuation def clean_input(input): # this function will clean the input by removing unnecessary punctuation # input must be of type string if type(input) != str: raise TypeError("input not a string type") # first, lets remove any words that are encapsulated by brackets # since we're looking at song lyrics, this will most likely be words like # (chorus) or (repeat). Since these aren't actual words in the song we can get rid of them temp = re.sub(r'(\(\w*\s*\))', '', input) # Remove the word chorus since its not an actual lyric temp = temp.replace("chorus", "") # next, the input must be stripped of punctuation # this is done by replacing them with whitespace # apostrophes are left in for now temp = re.sub(r'[^\w\s\']', ' ', temp) # now, any contractions are collapsed by removing the apostrophes temp = re.sub(r'[\']', '', temp) # any numbers will also be removed since they hold very little meaning later on temp = re.sub(r'[\d]', '', temp) # replace all whitespace with the space character, this joins all the text into one scenetence temp = re.sub(r'[\s]', ' ', temp) # Eliminates all stopwords and punctuation # All stopwords are in english lib stop_words = set(stopwords.words('english')) # Replace apostrophes with "" so important words are not separated and contraction words are taken as separate words tokened_text = temp.split(); stopword_text = "" for t in tokened_text: if len(t) > 1 and t not in stop_words: if t not in punctuation: stopword_text += " " + t return stopword_text def sentiment_analysis(text, positive_words, negative_words): p_score = 0 n_score = 0 cleaned_text = clean_input(text) for word in cleaned_text.split(" "): for wordp in positive_words: wordp = wordp.replace("\n","") if word == wordp: p_score = p_score + 1 for wordn in negative_words: wordn = wordn.replace("\n", "") if word == wordn: n_score = n_score + 1 print(p_score) print(n_score) if p_score > 1.25 * n_score: return 1 elif n_score > 1.25 * p_score: return -1 else: return 0 def main(): test_text = "I am having a good day" positive_words = open("./positive.txt").readlines() negative_words = open("./negative.txt").readlines() print("Result =", sentiment_analysis(test_text, positive_words, negative_words)) if __name__ == "__main__": main()
f573d91df21116b83c6acdcb9abe7c9250f00cbd
wamalik786/Waqas_Ahmad_PIAIC_154908
/PIAIC_154908_ Waqas Ahmad_ assignment_2.py
1,811
3.515625
4
#!/usr/bin/env python # coding: utf-8 # In[75]: import numpy as np # In[3]: x = np.arange(1,13).reshape((6,2)) print(x) # In[9]: x = np.arange(10,37, dtype = np.float64). reshape((3,3,3)) x # In[81]: a =np.arange(1,100*10+1).reshape((100,10)) x = a [(a % 7 == 0) & (a % 5 ==0)] print(x) # In[41]: print("original matrix") arr = np.arange(9).reshape(3,3) print(arr) print("swaped matrix") arr[:,[0,1]] = arr[:,[1,0]] arr # In[44]: z= np.zeros((4,5), dtype=int) z # In[82]: arr = np.zeros(10, dtype=int) print(arr) print("\n Update fifth and eighth value") arr[4] = 10 arr[7] = 20 print(arr) # In[46]: x = np.zeros(4, dtype=np.int64) x # In[58]: x = np.full((2, 5), 6, dtype=np.uint32) x # In[60]: a=np.arange(2,101,2) print("\nArray of all the even integers from 2 to 100") a # In[85]: arr = np.array([[3,3,3,],[4,4,4],[5,5,5]]) brr = np.array([1,2,3]) sub = arr[0]-brr[0], arr[1]-brr[1], arr[2]-brr[2] sub # In[2]: arr = np.array([0,1,2,3,4,5,6,7,8,9]) arr[arr%2==1] = -1 arr # In[7]: arr = np.array([1,2,3]) arr1 = np.repeat(arr,3) ans = np.hstack((arr1,arr,arr,arr)) ans # In[ ]: # In[43]: a = np.array([2,6,1,9,10,3,27]) print("Original array:") print(a) ind_pos = np.where(np.logical_and(a>5, a<10)) print("values in a range 5 to 10:") arr[ind_pos] # In[51]: print("Creating 8X3 array using numpy.arange") arr = np.arange(10,34,1) arr = arr.reshape(8,3) print (arr) print("Dividing 8X3 array into 4 sub array\n") ans = np.split(sampleArray, 4) print(ans) # In[66]: arr = np.array([[8,2,-2],[-4,1,7],[6,3,9]]) arr ans = arr[np.argsort(arr[:,1])] ans # In[82]: x = np.array([[1],[2],[3]]) y = np.array([[2],[3],[4]]) ans = np.dstack((x, y)) print (ans) # In[111]: arr = np.arange(1,10*10+1).reshape(10,10) arr # In[ ]:
17105410cf77c2d37bd2e5caf5eb8dde88dbeb62
chanthony/Oregon-112
/Diseases.py
2,854
3.828125
4
#diseases.txt def generateDiseases(data): diseaseList = []#keep the diseases as a list diseaseList.append(Disease("performed a ritual sacrifice to the 112 gods", "grade",10))#generate each disease and store it diseaseList.append(Disease("forgot to backup their work and lost it", "grade",-10)) diseaseList.append(Disease("angered the great Kosbie","grade",-20)) diseaseList.append(Disease("""forgot a parentheses in their code and spent 15 hours looking for it""","grade",-5)) diseaseList.append(Disease("""watched a Youtube video that had the word programming in the title""","grade",5)) diseaseList.append(Disease("caught dysentery","energy",-50)) diseaseList.append(Disease("got dumped","energy",-30)) diseaseList.append(Disease("hung out with their friends","energy",20)) diseaseList.append(Disease("told a funny joke","energy",10)) diseaseList.append(Disease("had their interp class cancelled","energy",40)) data.diseaseList = diseaseList#store the list class Disease(object):#the various effects def __init__(self,name,effect,amount): self.name = name#not the name but what the disease is self.effect = effect#what the disease effects self.amount = amount#the size of the impact if self.amount < 0:#if negative self.change = "lost"#whether we lost or gained amount else:#positive self.change = "gained" def takeEffect(self,char,player): if self.effect == "energy":#if the energy is hurt player.energy += self.amount#change the energy if player.energy < 0:#if at negative energy player.energy = 0#set us back at 0 elif player.energy >= 100:#cap energy to 100 player.energy = 100 elif self.effect == "grade": if self.amount > 0: char.increaseGrade(self.amount) else: char.reduceGrade(self.amount) else: #we clearly havent' coded this yet so let me know raise NameError("This disease effect has not been coded yet!") def showDisease(self,char):#shows the disease dialogue if self.effect == "energy": line = "%s %s.\n" % (char.name,self.name) #ex. You forgot your homework line += "Your group %s %d energy." % (self.change,abs(self.amount)) else:#if it's something other than energy line = "%s %s. \n" % (char.name , self.name) #ex. Jimmy forgot to close his parentheses line += "%s %s %d %s points" % (char.name,self.change, abs(self.amount),self.effect) #ex. Jimmy gained 15 energy return line
18c9cc619d5e44504665132e9fad5315a8b44799
pjkellysf/Python-Examples
/backwards.py
960
4.78125
5
#!/usr/local/bin/python3 # Patrick Kelly # September 29, 2015 # Write a program that prints out its own command line arguments, but in reverse order. # Note: The arguments passed in through the CLI (Command Line Interface) are stored in sys.argv. # Assumption: The first item argument in sys.argv is the filename and should NOT be included in the output. # Import the sys module import sys # Subtract one from the length of sys.argv to access the last index and store the result in the variable argumentIndex. argumentIndex = len(sys.argv) - 1 # Iterate through sys.argv starting with the last argument at index argumentIndex. for argument in sys.argv: # Exclude the filename which is the first argument in sys.argv at index 0. if argumentIndex > 0: # Print out the indexed argument from sys.argv print (sys.argv[argumentIndex]) # Decrement argumentIndex to access the previous argument in the next loop argumentIndex -= 1
8707d6834569e841a2a4dd597664eaab15ba9d11
OXDBXKXO/energy-data-hack
/keysolver/post_treatment/key_filtering.py
7,906
3.734375
4
__SLIDING_WINDOW = 80 __SHIFT_RADIUS = 50 class KeyPress: """ Represent a key presses. Instances of this class are immutable. Attributes: key: A tring representing the key (e.g. "A", "SHIFT" or "NOKEY") count: The number of consecuting repetitions. has_shift: True if the SHIFT modifier is applied. """ def __init__(self, key, count=1, has_shift=False): self.__key = key self.__count = count self.__has_shift = has_shift @property def key(self): return self.__key @property def count(self): return self.__count @property def has_shift(self): return self.__has_shift def __detect_modifiers(keys, radius): """ Try to detect keys with a SHIFT modifier. Args: keys: A list of KeyPress. radius: How far back and ahead the algorithm will look for SHIFT frames. Returns: The "key" array is modified in place and returned. """ # for each key : a greater score means more SHIFT frames in the neighborhood, # a smaller score means more NOKEY frames. score = [0] * len(keys) for i in range(len(keys)): # will the score be increased or decreased in this neighborhood? mod = 0 if keys[i].key == "NOKEY": mod = -1 elif keys[i].key == "SHIFT": mod = 1 else: continue # applying the score neighborhood_begin = max(0, i - radius) neighborhood_end = min(len(keys), i + radius) for j in range(neighborhood_begin, i): score[j] += mod for j in range(i, neighborhood_end): score[j] += mod # applying the SHIFT modifier where the score is strictly positive for i in range(len(keys)): if score[i] > 0: keys[i] = KeyPress(keys[i].key, keys[i].count, True) return keys def __has_mostly_shift(keys): """ Detect whether a list of keys contains more keys with or without the SHIFT modifier. Args: keys: A list of KeyPress. Returns: True if there are more key presses with the SHIFT modifier, False otherwise. """ return sum([(1 if key.has_shift else -1) for key in keys]) > 0 def __get_histo(keys): """ Compute the frequency of every key in a set of key presses. Args: keys: A list of KeyPress. Returns: A dictionary whose keys are key strings, and whose elements are occurence counts. """ histo = dict() for key in keys: if key.key in histo: histo[key.key] += key.count else: histo[key.key] = key.count return histo def __get_most_frequent(keys): """ Get the key with the most occurences in a list. Args: keys: A list of KeyPress. Returns: A KeyPress corresponding to the most represented key. """ histo = __get_histo(keys) most_frequent = "" max_count = 0 for element, count in histo.items(): if count > max_count: most_frequent = element max_count = count return KeyPress(most_frequent, 1, __has_mostly_shift(keys)) def __sliding_most(keys, window_size): """ Computes, using a sliding window, the most represented key in each window. Args: keys: A list of KeyPress. Returns: A list of KeyPress, corresponding to the "keys" argument but keeping only maximum values. """ result = [] window = keys[0:window_size] for key in keys[window_size - 1:]: window = window[1:] + [key] most_frequent = __get_most_frequent(window) result.append(most_frequent) return result def __dedup(keys): """ Merge duplicate adjacent keys. Args: keys: A list of KeyPress. Returns: A list of KeyPress, corresponding to the "keys" argument but with duplicate adjacent keys merged. """ len_keys = len(keys) if len_keys == 0: return [] result = [keys[0]] for i in range(1, len_keys): key = keys[i] last_key_press = result[-1] if last_key_press.key == key.key: # for simplicity, the SHIFT modifier always win result[-1] = KeyPress(key.key, last_key_press.count + key.count, key.has_shift or last_key_press.has_shift) else: result.append(key) return result def __filter(keys): """ Remove isolated key occurences. Args: keys: A list of KeyPress. Returns: A list of KeyPress, corresponding to the "keys" argument but with non-repeated keys removed. """ return __dedup([ key for key in keys if key.count > 1 ]) def __split_keys(keys): """ Split a list of keys according to actual key strokes. Args: keys: A list of KeyPress. Returns: A list of keys. Every key is itself represented by a list of KeyPress, which are candidates for the actual key. """ result = [] buff = [] for key in keys: if key.key == "NOKEY": result.append(buff) buff = [] else: buff.append(key) result.append(buff) # returning only non-empty parts return [part for part in result if len(part) != 0] def __get_sorted_histo(keys): """ Compute the frequency of every key in a set of key presses. Args: keys: A list of KeyPress. Returns: A list of (KeyPress, occurence count) pairs. The list is sorted by descending occurence count. """ # the shift modifier is applied uniformly to every element has_shift = __has_mostly_shift(keys) items = sorted(__get_histo(keys).items(), key = lambda e : e[1]) return [(KeyPress(item[0], 1, has_shift), item[1]) for item in items] def filter_keys(keys): """ Turn a raw list of tagged frames into a list of key presses. Args: keys: A list representing, for each frame, the detected key as a string. Returns: A list of key presses, in chronological order. Each key press is represented by an array of key strings, sorted from the most likely to the least likely. The "SHIFT" modifier is represented as a standalone key, just before the affected key press. Examples: >>> filter_keys(keys) [ ['0', 'SUPPR', 'CTRL'], ['SHIFT'], ['D'], ['SHIFT'], ['T'], ['SHIFT'], ['A'], ['SHIFT'], ['M'], ['SHIFT'], ['I'], ['H', 'U'], ['A', 'W'], ['C'], ['K'], ['A', 'W'], ['T'], ['O'], ['N'], ['2'], ['0'], ['2'], ['2', '3', '4'], ['ENTER'] ] """ prob_keys = [] # applying filters key_presses = [KeyPress(key) for key in keys] key_presses = __detect_modifiers(key_presses, __SHIFT_RADIUS) key_presses = [(key if key.key != "SHIFT" else KeyPress("NOKEY", key.count, True)) for key in key_presses] key_presses = __sliding_most(key_presses, __SLIDING_WINDOW) key_presses = __dedup(key_presses) key_presses = __filter(key_presses) processed = __split_keys(key_presses) # building the resulting list for part in processed: sorted_histo = __get_sorted_histo(part) sorted_part = [e[0] for e in sorted_histo if e[1] > 0] # representing the SHIFT modifier as a standalone key if __has_mostly_shift(sorted_part): prob_keys.append(["SHIFT"]) prob_keys.append([key.key for key in sorted_part]) return prob_keys
3c064008c882c067c144eedc5312c6b7ad329ac0
Alistrandarious/ETL-LifeExpectancy
/code.py
1,892
3.921875
4
import time average = 0 student_list = ["Alfred", "Matthew", "Simon", "Amy", "Mary"] Selection = False Average = False scores = { "Alfred": { "Maths": 74, "Science": 78, "English": 68, "History": 52 }, "Matthew": { "Maths": 64, "Science": 82, "English": 70, "History": 65, "Psychology": 87 }, "Simon": { "Maths": 61, "Science": 63, "English": 71, "History": 56 }, "Amy": { "Maths": 91, "Science": 89, "English": 69, "History": 71 }, "Mary": { "Maths": 53, "Science": 74, "English": 90, "History": 85, "Psychology": 75 }, } print("Hi, welcome to the Student Averagator v1.") time.sleep(1) while Selection is False: print("Please choose from the following students: \n") time.sleep(1) print("Alfred, \n" "Amy, \n" "Mary, \n" "Matthew, \n" "Simon \n") Student = input("SELECT YOUR STUDENT: \n").capitalize() if Student in student_list: Selection = True else: print("Please type in a current student.") while Selection is True: for name in scores: print(Student + "scores:") print(scores[Student]) Selection = False while average is False: average = input("Would you like the average:\n") if average == ["y", "yes"]: for Student in scores: print(scores[Student]) for subject in scores: for marks in scores: print(sum(marks) / 5) average = True if average == ["n", "no"]: print("Thanks for using Student Averagator. Goodbye") time.sleep(1) exit() else: print("Please type yes or no.") while average is True: print("Thanks for using Student Averagtor. Goodbye")
828c2e1ca9d4ef07d3298e03d15d494d4b229f44
paigekm/Marsden_Pizzas
/testing_file_sprint2.py
4,058
4.1875
4
"""A program to manage customers' pizza orders.""" import math def stars(): """Prints a line of * to separate information and make the output easy to understand.""" print("*" * 60) def dotted(): """Prints a line of . to separate information and make the output easy to understand.""" print("." * 60) def get_string(m): """Ask for user input as a string. :param m: list :return: string """ my_string = str(input(m)) return my_string def get_integer(m): """Ask for user input as an integer. :param m: list :return: string """ my_integer = int(input(m)) return my_integer def single_loop_print(p): """Print the list. :param L: list :return: None Print the list in a nice format and only once. """ output = "{: ^10} {:^15} {:^15} {:^15}".format("INDEX", "PRICE", "PIZZAS", "DESCRIPTION") print(output) stars() for i in range(0, len(p)): output = "{}: {: ^25} --- {:<10} --- {:<10}".format(i, p[i][0], p[i][1], p[i][2]) print(output) def add_to_order(mo,p): """Add pizza to order. :param L: list :return: None The required list must be two-dimensional, and the sub list must be of the form [str, int], requests user input for index and quantity, adds new pizza and quantity to the list, prints confirmation. """ dotted() print("Start to fill out order") dotted() pizza_choice_index = get_integer("Enter pizza index number:") chosen_pizza = p[pizza_choice_index][1] quantity = get_integer("How many {} pizzas would you like?".format(chosen_pizza)) dotted() temp_list = [chosen_pizza, quantity] mo.append(temp_list) def review_order(mo): print("Here is your order so far:") for i in range(0, len(mo)): order = ("{: ^10} --- {:<10} ".format(mo[i][0], mo[i][1])) print(order) def quit_or_menu(): """Choose to either quit or view menu. :param: None :return: None """ # this list is a list of the customer's ordered pizzas my_order = [] price_of_regular = 18.5 price_of_gourmet = price_of_regular + 7 pizzas = [ (price_of_regular, "USA", "A tasty meat lovers pizza"), (price_of_regular, "Australia", "Pineapple, shrimp and BBQ sauce"), (price_of_gourmet, "Russia", "Mockba four fish pizza with sardines, tuna, mackerel and salmon"), (price_of_gourmet, "India", "Pickled ginger and paneer") ] option_menu = [ ("V", "View pizza menu"), ("O", "Start order"), ("R", "Review order so far"), ("Q", "Quit") ] confirm_quit = [ ("Y", "Continue quit"), ("N", "Go back to menu page") ] run = True while run == True: for i in range(0, len(option_menu)): print("{:3} : {}".format(option_menu[i][0], option_menu[i][1])) option_choice = get_string("What would you like to do? -> ").upper() dotted() if option_choice == "V": single_loop_print(pizzas) dotted() elif option_choice == "O": single_loop_print(pizzas) add_to_order(my_order, pizzas) elif option_choice == "R": review_order(my_order) dotted() elif option_choice == "Q": for i in range(0, len(confirm_quit)): print("{:3} : {}".format(confirm_quit[i][0], confirm_quit[i][1])) ask_quit_confirmation = get_string("Are you sure you want to quit?").upper() dotted() if ask_quit_confirmation == "Y": print("Thank you for visiting Marsden Pizzas. Hope to see you again!") run = False elif ask_quit_confirmation == "N": run = True else: print("You have requested an invalid choice.") else: print("You have requested an invalid choice.") quit_or_menu()
c2ed5c9f07d0c48a3342758fd474a8949662efc6
LeonidasRex/Project_Euler
/Solutions/Euler Prob 7.py
230
3.546875
4
''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10,001st prime number? ''' #Yes, this is sympy, how may I help you? :) import sympy as sy print(sy.prime(10001))
a7e60a422b39726dd76eb1e913e3236967a09502
simpx/elo
/elo.py
1,056
3.625
4
#!/usr/bin/env python # -*- coding: utf8 -*- import sys ''' 计算A对B的胜率期望值 公式里的常数默认取10和400 ''' def E(rankA, rankB, base = 10, power = 400): return 1 / ( 1 + pow(base, (1.0 * (rankB - rankA) / power))) ''' 计算A对阵B后,新的rank分数 ''' def R(oldRankA, oldRankB, scoreA, k = 32, base = 10, power = 400): if (scoreA not in [0, 0.5, 1]): raise ValueError("Invalid score!", scoreA) e = E(oldRankA, oldRankB, base, power) return oldRankA + k * (scoreA - e) if __name__ == "__main__": if len(sys.argv) < 4: print "usage: %s rankA rankB scoreA" % sys.argv[0] else: rankA = float(sys.argv[1]) rankB = float(sys.argv[2]) scoreA = float(sys.argv[3]) scoreB = 1 - scoreA newRankA = R(rankA, rankB, scoreA) newRankB = R(rankB, rankA, scoreB) print "Ea %.2f, Eb %.2f" % (E(rankA, rankB), E(rankB, rankA)) print "A rank: %.2f -> %.2f" % (rankA, newRankA) print "B rank: %.2f -> %.2f" % (rankB, newRankB)
5bfe3fa926c2f2f34299874688692f7d1fbb1c80
maha139/python_practice
/whatsyourname.py
267
3.96875
4
#Task4 # Get firstname and last name and see if less than 10 characters firstname = input("enter first name") lastname = input("enter last name") print(firstname) print(lastname) print ("Hello {} {} You just delved into Python".format(firstname,lastname))
e8a9965c15b7ef985908e4a04807eccdc3d7a5c8
MukundiCode/alex
/Q_gridpoint.py
6,342
3.609375
4
#Tinashe Mukundi Chitamba #The gridpoint class encapsulates the variables and methods used in the value iteration algorithm import numpy as np class gridPoint: # Variables # x - x coordinate # y - y coordinate # int value - value of that grid point # boolean isTerminal - true if it is terminal point # policies [] - list of valid moves for this object #constructor def __init__(self,x,y,value,endx,endy,gamma): self.x = x self.y = y self.value = value self.gamma = gamma self.isTerminal = False self.endx = endx self.endy = endy self.isEnd = False def makePolicy(self): self.policies = [] top = self.x -1 bottom = self.x + 1 left = self.y -1 right = self.y +1 if (top >= 0): self.policies.append([self.x-1,self.y]) else: self.policies.append(None) if (bottom <= self.endx): self.policies.append([self.x + 1,self.y]) else: self.policies.append(None) if (left >= 0): self.policies.append([self.x,self.y -1]) else: self.policies.append(None) if (right <= self.endy): self.policies.append([self.x,self.y+1]) else: self.policies.append(None) #gets the value of the next state, right now not including the reward of making the move def getNextStateValue(self,nextState): return (self.gamma*nextState.value) def getOptimal(self,optimal,grid,qtable): if self.isEnd == True: #optimal.append([self.x,self.y]) return True else: nextAction = np.argmax(qtable[self.x,self.y]) #print(nextAction,self.policies) #print(qtable[self.x,self.y]) nextMove = self.policies[nextAction] if nextMove == None: return for move in optimal: if move == nextMove : print("No optimal route found") print(move,optimal) return #print(grid[nextMove[0]][nextMove[1]].value,next,sep=' ,') optimal.append(nextMove) return grid[nextMove[0]][nextMove[1]].getOptimal(optimal,grid,qtable) #cyclic route found #print("No possible route to end point") #return def getOptimal_2(self,optimal,grid): if self.isEnd == True: #optimal.append([self.x,self.y]) return else: #optimal.append([self.x,self.y]) nextValues = [] #finding the next optimal value for next in self.policies: if next != None: nextValues.append(grid[next[0]][next[1]].value) maxValue = max(nextValues) for next in self.policies: if next != None: if grid[next[0]][next[1]].value == maxValue: print(grid[next[0]][next[1]].value,next,sep=' ,') optimal.append(next) return grid[next[0]][next[1]].getOptimal(optimal,grid) #cyclic route found print("No possible route to end point") return def Q_getNextStateValue(self,nextState): return (self.gamma*nextState.value) def getNextAction(self,epsilon,grid,qtable): number = np.random.random() if number < epsilon: nextAction = np.argmax(qtable[self.x,self.y]) #print(nextAction,self.policies) #print(qtable[self.x,self.y]) nextMove = self.policies[nextAction] if nextMove == None: return -1 if self.isEnd == False: self.value = self.Q_getNextStateValue(grid[nextMove[0]][nextMove[1]]) else: return -1 #print(self.value) return [nextMove[0],nextMove[1],nextAction] else: rand = np.random.randint(len(self.policies)) if not self.policies[rand] == None: if not grid[self.policies[rand][0]][self.policies[rand][0]].isTerminal: if self.isEnd == False: self.value = self.Q_getNextStateValue(grid[self.policies[rand][0]][self.policies[rand][0]]) #print(self.value) return [self.policies[rand][0],self.policies[rand][0],rand] else: self.value = self.Q_getNextStateValue(grid[self.policies[rand][0]][self.policies[rand][0]]) return -1 #getting the positions of the else: return -1 def getNextAction2(self,epsilon,grid,qtable): number = np.random.random() if number < epsilon: nextAction = np.argmax(qtable[self.x,self.y]) nextMove = self.policies[nextAction] self.value = self.Q_getNextStateValue(grid[nextMove[0]][nextMove[1]]) counter = 0 maxValue = -1000 action = 0 for next in self.policies: if self.Q_getNextStateValue(grid[next[0]][next[1]]) > maxValue: maxValue = self.Q_getNextStateValue(grid[next[0]][next[1]]) action = counter nextMove = next counter = counter + 1 if self.isEnd == False: self.value = maxValue else: return -1 #print(self.value) return [nextMove[0],nextMove[1],action] else: rand = np.random.randint(len(self.policies)) if not grid[self.policies[rand][0]][self.policies[rand][0]].isTerminal: if self.isEnd == False: self.value = self.Q_getNextStateValue(grid[self.policies[rand][0]][self.policies[rand][0]]) #print(self.value) return [self.policies[rand][0],self.policies[rand][0],rand] else: #self.value = self.Q_getNextStateValue(grid[self.policies[rand][0]][self.policies[rand][0]]) return -1 #getting the positions of the def __str__(self) -> str: return str(self.x) + ":" + str(self.y)
0c0115b670926748b7df837e063d0953a16199b1
Bryanx/exercises
/Python/Fibonacci copy.py
289
4.15625
4
def fibonacci(x): x -= 2 f = [0, 1] if x < 0: return[0] elif x < 1: return f else: for i in range(x): f.append(f[len(f) - 2] + f[len(f) - 1]) return f print(fibonacci(int(input("Enter the amount of Fibonacci numbers:\n"))))
b112929c1836af29d6fe388e1fc749a47695c84e
arpine58/python_homework
/homework3/Palindrome numbers.py
320
3.84375
4
a = int(input()) b = int(input()) def palindrome(x): temp = x rev = 0 while x > 0: dig = x % 10 rev = rev*10+dig x = x//10 if temp == rev: return True else: return False for i in range(a, b): if palindrome(i) is True: print(i)
9d1ed42cd4a586df38bb7f2a122db69fbece314a
aidank18/PythonProjects
/montyhall/MontyHall.py
1,052
3.78125
4
from random import random def game(stay): doors = makeDoors() choice = int(random() * 3) for i in range(0, 2): if (i != choice) and doors[i] == "g": doors[i] = "r" break if stay: return doors[choice] else: doors[choice] = "r" for door in doors: if door != "r": return door def makeDoors(): doors = ["g", "g", "c"] for i in range(0, 10): val1 = int(random() * 3) val2 = int(random() * 3) temp = doors[val1] doors[val1] = doors[val2] doors[val2] = temp return doors def tests(stay): cars = 0 for i in range(0, 10000): if game(stay) == "c": cars += 1 probability = cars/10000 if stay: print() print("The probability of picking the car by staying with the same door is", probability) print() else: print() print("The probability of picking the car by switching doors is", probability) print() tests(False)
c8a2b5153663184e1ae0c23e29d8b4309b5df5bd
aidank18/PythonProjects
/linkedList/LinkedList.py
4,359
3.9375
4
from Node import * class LinkedList: def __init__(self, aStart = None): self.__start = aStart if self.__start == None: self.__size = 0 else: self.__size = self.__traverseList(self.__start, False) def __str__(self): list = "[" + self.__traverseList(self.__start) if not self.isEmpty(): list = list[:-2] list += "]" return list def __len__(self): return self.__size def __traverseList(self, curr, string = True): if curr == None: if string: return "" return 0 if string: #print(curr.value, curr.next) return str(curr.value) + ", " + self.__traverseList(curr.next) return 1 + self.__traverseList(curr.next, False) def appendItem(self, node = None, number = None): if node != None: #print(node.value, node.next) if self.__start == None: self.__start = node self.__size += self.__traverseList(node, False) return self.__addNode(self.__start, node) self.__size += 1 elif number != None: if self.__start == None: self.__start = Node(number, None) self.__size += 1 return self.__addNumber(self.__start, number) self.__size += 1 def __addNode(self, curr, node): if curr.next == None: curr.next = node return self.__addNode(curr.next, node) def __addNumber(self, curr, number): if curr.next == None: curr.next = Node(number, None) return self.__addNumber(curr.next, number) def prependItem(self, node = None, number = None): if number != None: node = Node(number, None) curr = node while curr.next != None: curr = curr.next curr.next = self.__start self.__start = node self.__size = self.__traverseList(node, False) def removeHead(self): if self.__start == None: return None self.__size -= 1 temp = self.__start self.__start = self.__start.next return temp def removeTail(self): if self.__size == 0 or self.__size == 1: return self.removeHead() curr = self.__start while curr.next.next != None: curr = curr.next temp = curr.next curr.next = None self.__size -= 1 return temp #counts the number of nodes with the specified item def count(self, item): if self.__size == 0: return 0 counter = 0 curr = self.__start while curr.next != None: if curr.value == item: counter += 1 curr = curr.next return counter #returns the first index of the given item def index(self, item): if self.__size == 0: return None curr = self.__start ind = 0 while curr != None: if curr.value == item: return ind curr = curr.next ind += 1 return None def insert(self, index, item): if index > self.__size: return elif index == 0: self.prependItem(item) elif index == self.__size: self.appendItem(item) else: curr = self.__start i = 0 while i + 1 != index: curr = curr.next i += 1 curr.next = Node(item, curr.next) self.__size += 1 def isEmpty(self): if self.__size == 0: return True return False def size(self): return self.__size def clear(self): self.__size = 0 self.__start = None def first(self): return self.__start def last(self): if self.__size == 0: return None curr = self.__start while(curr.next != None): curr = curr.next return curr def elemAt(self, index): if index < 0 or index >= self.__size: return None curr = self.__start for i in range(0, index): curr = curr.next return curr
c745c673b6a345386bdd51981e7cdca0e2e76a7e
netager1007/Python_Cookbook_3rd
/2-Strings_and_Text.py
15,795
4.34375
4
# 2.1 Splitting Strings on Any of Multiple Delimiters line = 'asdf fjdk; afed, fjek,asdf, foo' import re print(re.split(r'[;,\s]\s*', line)) # \s : white space fields = re.split(r'(;|,|\s)\s*', line) print(fields) values = fields[::2] delimiters = fields[1::2]+[''] print('values: ', values) print('delimiters: ', delimiters) print(''.join(v+d for v, d in zip(values, delimiters))) print(re.split(r'(?:,|;|\s)\s*', line)) # 2.2 Matching Text at the Start or End of a String # str.startswith() or str.endswith() filename = 'spam.txt' print(filename.endswith('.txt')) print(filename.startswith('file:')) print(filename.startswith('sp')) url = 'http://www.python.org' print(url.startswith('http:')) import os filenames = os.listdir('.') print(filenames) print([name for name in filenames if name.endswith(('.c', '.h', '.py'))]) print(any(name.endswith('.py') for name in filenames)) from urllib.request import urlopen def read_data(name): if name.startswith(('http:', 'https:', 'ftp:')): return urlopen(anme).read() else: with open(name) as f: return f.read() choices = ['http:', 'ftp:'] url = 'http://www.python.org' url.startswith(tuple(choices)) # startswith() 와 endswith() 함수는 str or tuple로 넘겨야 함 filename = 'spam.txt' print(filename[-4:] == '.txt') url = 'http://www.python.org' print(url[:5] == 'http:' or url[:6] == 'https' or url[:4] == 'ftp:') import re url = 'http://www.python.org' print(re.match('http:|https:|ftp:', url)) # Useful endswith() import os dirname = '.' if any(name.endswith(('.c', '.h')) for name in os.listdir(dirname)): print(name) else: print('No File exists') # 2.3 Matching Strings Using Shell Wildcard Patterns # fnmatch() and fnmatchcase() from fnmatch import fnmatch, fnmatchcase print(fnmatch('foo.txt', '*.txt')) print(fnmatch('foo.txt', '*.TXT')) # fnmatch()는 대소문자 구분하지 않음 print(fnmatch('foo.txt', '?oo.txt')) print(fnmatch('Dat45.csv', 'Dat[0-9]*')) names = ['Dat1.csv', 'Dat2.csv', 'config.ini', 'foo.py'] print([name for name in names if fnmatch(name, 'Dat*.csv')]) print(fnmatchcase('foo.txt', '*.TXT')) # fnmatchcase() 대소문자 구분 addresses = [ '5412 N CLARK ST', '1060 W ADDISON ST', '1039 W GRANVILLE AVE', '2122 N CLARK ST', '4802 N BROADWAY', ] from fnmatch import fnmatchcase print([addr for addr in addresses if fnmatchcase(addr, '* ST')]) print([addr for addr in addresses if fnmatchcase(addr, '54[0-9][0-9] *CLARK*')]) # 2.4 Matching and Searching for Text Patterns text = 'yeah, but no, but yeah, but no, but yeah' print(text == 'yeah') # Exact match print(text.startswith('yeah')) # Match at start or end print(text.endswith('no')) # Match at start or end print(text.find('no')) # Search for the location of the first occurrence print(text.find('lee')) text1 = '11/27/2012' text2 = 'Nov 27, 2012' import re if re.match(r'\d+/\d+/\d+', text1): print('yes') else: print('no') if re.match(r'\d+/\d+/\d+', text2): print('yes') else: print('no') # Precompile the regular expression pattern datepat = re.compile(r'\d+/\d+/\d+') if datepat.match(text1): print('yes') else: print('no') if datepat.match(text2): print('yes') else: print('no') text = 'Today is 11/27/2012. PyCon starts 3/13/2013.' print(datepat.findall(text)) # Capture groups by enclosing parts of the pattern in parentheses. # Capture groups often simplify subsequent processing of the matched text. datepat = re.compile(r'(\d+)/(\d+)/(\d+)') m = datepat.match('11/27/2012') print(m) print(m[0], m[1], m[2], m[3], m.groups()) month, day, year = m.groups() print(month, day, year) text = 'Today is 11/27/2012. PyCon starts 3/13/2013.' print(datepat.findall(text)) # Find all matches (notice splitting into tuples) for month, day, year in datepat.findall(text): print('{}-{}-{}'.format(year, month, day)) # findall() method searches the text and finds all matches, retruning them as a list. # If you want to find matches iteratively, use the finditer() method instead. for m in datepat.finditer(text): print(m.groups()) datepat = re.compile(r'(\d+)/(\d+)/(\d+)$') print(datepat.match('11/27/2012abcdef')) print(datepat.match('11/27/2012')) # Simple text matching/searching operation, you can often skip the compilation step. print(re.findall(r'(\d+)/(\d+)/(\d+)', text)) # 2.5 Searching and Replacing Text # str.replace() text = 'yeah, but no, but yeah, but no, but yeah' print(text.replace('yeah', 'yep')) print(text) # No change origin text # re.sub() # In second argument, backslashed digits such as \3 refer to capture group number # in the pattern. text = 'Today is 11/27/2012. PyCon starts 3/13/2013.' import re print(re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text)) import re datepat = re.compile(r'(\d+)/(\d+)/(\d+)') print(datepat.sub(r'\3-\1-\2', text)) # For more complicated substitutions from calendar import month_abbr import re #TODO: Dont' understand datepat = re.compile(r'(\d+)/(\d+)/(\d+)') def change_date(m): print(type(m)) print(m) mon_name = month_abbr[int(m.group(1))] return '{} {} {}'.format(m.group(2), mon_name, m.group(3)) print(datepat.sub(change_date, text)) # How many substitutions were made in addition to getting the replacement text, # use re.subn() instead. text = 'Today is 11/27/2012. PyCon starts 3/13/2013.' datepat = re.compile(r'(\d+)/(\d+)/(\d+)') newtext, n = datepat.subn(r'\3-\2-/2', text) print('n: ', n, 'newtext: ', newtext) # 2.6 Searching and Replacing Case-Insensitive Text # use re module and re.IGNORECASE flag text = 'UPPER PYTHON, lower python, Mixed Python' print(re.findall('python', text)) print(re.findall('python', text, flags=re.IGNORECASE)) print(re.sub('python', 'snake', text, flags=re.IGNORECASE)) #TODO: It's very difficult ~ Where is m from? def matchcase(word): def replace(m): print('type(m): ', type(m)) text = m.group() print('replace.text: ', text) if text.isupper(): return word.upper() elif text.islower(): return word.lower() elif text[0].isupper(): return word.capitalize() else: return word return replace print(re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE)) # 2.7 Specifying a Regular Expression for the Shortest Match # TODO: It's very difficult str_pat = re.compile(r'\"(.*)\"') text1 = 'Computer says "no."' print(str_pat.findall(text1)) text2 = 'Computer says "no." Phone says "yes."' print(str_pat.findall(text2)) str_pat = re.compile(r'\"(.*?)\"') text2 = 'Computer says "no." Phone says "yes."' print(str_pat.findall(text2)) # 2.8 Writing a Regular Expression for Multiline Patterns comment = re.compile(r'/\*(.*?)\*/') text1 = '/* this is a comment */' text2 = '''/* this is a multiline comment */''' print(comment.findall(text1)) print(comment.findall(text2)) # When multiline, can't find comment = re.compile(r'/\*((?:.|\n)*?)\*/') print(comment.findall(text2)) # Use re.DOTALL flag comment = re.compile(r'/\*(.*?)\*/', re.DOTALL) print(comment.findall(text2)) # 2.9 Normalizing Unicode Text to a Standard Representation s1 = 'Spicy Jalape\u00f1o' s2 = 'Spicy Jalapen\u0303o' print(s1) print(s2) print(s1 == s2) print('len(s1): ', len(s1), 'len(s2): ', len(s2)) import unicodedata t1 = unicodedata.normalize('NFC', s1) t2 = unicodedata.normalize('NFC', s2) print(t1 == t2) print(ascii(t1)) t3 = unicodedata.normalize('NFD', s1) t4 = unicodedata.normalize('NFD', s2) print(t3 == t4) print(ascii(t3)) s = '\ufb01' print(s) print(unicodedata.normalize('NFD', s)) print(unicodedata.normalize('NFKD', s)) print(unicodedata.normalize('NFKC', s)) s1 = 'Spicy Jalape\u00f1o' t1 = unicodedata.normalize('NFD', s1) print(t1) print(''.join(c for c in t1 if not unicodedata.combining(c))) # 2.10 Working with Unicode Characters in Regular Expression import re num = re.compile('\d+') m = num.match('123') # ASCII digits print(m.group()) print(num.match('\u0661\u0662\u0663')) m1 = num.match('\u0661\u0662\u0663') print(m1.group()) arabic = re.compile('[\u0600-\u06ff\u0750-\u077f\u08a0-\u08ff]+') pat = re.compile('stra\u00dfe', re.IGNORECASE) s = 'straße' s1 = pat.match(s) print(s1.group()) pat.match(s.upper()) print(s.upper()) # 2.11 Stripping Unwanted Characters from Strings # strip() # Whitespace stripping s = ' hello world \n' print(s.strip()) print(s.lstrip()) print(s.rstrip()) t = '------hello=====' print(t.lstrip('-')) print(t.strip('-=')) s = ' hello world \n' s = s.strip() print(s) print(s.replace(' ','')) import re a = re.sub('\s+', ' ', s) print('a: ', ascii(a)) # Reading lines of data from a file data = 'abcd efg HIJ KLMN OPqrs' fout = open('test.txt', 'wt') fout.write(data) fout.close() with open('test.txt') as f: lines = (line.strip() for line in f) for line in lines: print(line) # 2.12 Sanitizing and Cleaning Up Text # str.translate() s = 'pýtĥöñ\fis\tawesome\r\n' print(s) remap = { ord('\t') : ' ', ord('\f') : ' ', ord('\r') : None # Deleted } a = s.translate(remap) print(a) # Remove all combining characters # A dictionary mapping every Unicode combining character to None is created # using the dict.fromkeys() #TODO : It is very difficult import unicodedata import sys cmb_chrs = dict.fromkeys(c for c in range(sys.maxunicode) if unicodedata.combining(chr(c))) print(cmb_chrs) b = unicodedata.normalize('NFD', a) print(b) print(b.translate(cmb_chrs)) print(a.translate(cmb_chrs)) # Translation table that maps all Unicode decimal digit characters to their equivalent in ASCII digitmap = {c: ord('0') + unicodedata.digit(chr(c)) for c in range(sys.maxunicode) if unicodedata.category(chr(c)) == 'Nd'} print(len(digitmap)) x = '\u0661\u0662\u0663' print(x.translate(digitmap)) a = 'pýtĥöñ\fis\tawesome\r\n' b = unicodedata.normalize('NFD', a) c = b.encode('ascii', 'ignore').decode('ascii') print(a) print(b) print(c) # 2.13 Aligning Text Strings # ljust(), rjust(), center() text = 'Hello World' print(text.ljust(20)) print(text.rjust(20)) print(text.center(20)) print(text.rjust(20, '=')) print(text.center(20, '*')) print(format(text, '>20')) print(format(text, '<20')) print(format(text, '^20')) print(format(text, '=>20')) print(format(text, '-<20')) print(format(text, '*^20')) print('{:>10s} {:>10s}'.format('Hello', 'World')) x = 1.2345 print(format(x, '>10')) print(format(x, '*^10')) # 2.14 Combining and Concatenating Strings parts = ['Is', 'Chicago', 'Not', 'Chicago?'] print(' '.join(parts)) print(''.join(parts)) print(','.join(parts)) a = 'Is Chicago' b = 'Not Chicago?' print(a + ' ' + b) print('{} {}'.format(a, b)) a = 'Hello' 'world' print(a) parts = ['Is', 'Chicago', 'Not', 'Chicago?'] s = '' for p in parts: s += p print(s) data = ['ACME', 50, 91.1] print(','.join(str(d) for d in data)) print(a + ':' + ':' +c) # ugly print(':'.join([a, b, c])) # Still ugly print(a, b, c, sep=':') # Better # TODO: don't know ''' source = 'abcd efgh hijklmn' def combine(source, maxsize): parts = [] size = 0 for part in source: parts.append(part) size += len(part) if size > maxsize: yield ''.join(parts) parts = [] size = 0 yield ''.join(parts) f = open('combin.txt', 'wt') for part in combine(sample(), 32768): f.write(part) f.close() ''' # 2.15 Interplating Variables in Strings s = '{name} has {n} message.' print(s.format(name='Guido', n=37)) # format_map() and vars() name = 'Guido' n = 37 print(s.format_map(vars())) # Work with instances class Info: def __init__(self, name, n): self.name = name self.n = n a = Info('Guido', 37) print(s.format_map(vars(a))) # They do not deal gracefully with missing values. try: s.format(name='Guido') # Error Occure except KeyError as e: print('Error: ', e) # Way to avoid this is to define an alternative dictionary class # with a __missing__() method. class safesub(dict): def __missing__(self, key): return '{' + key + '}' del n # Make sure n is undefined print(s.format_map(safesub(vars()))) # frame hack import sys def sub(text): return text.format_map(safesub(sys._getframe(1).f_locals)) name = 'Guido' n = 37 print(sub('Hello {name}')) print(sub('You have {n} messages.')) print(sub('Your favorite color is {color}')) # 2.16 Reformating Text to a Fixed Number of Columns # textwrap module s = "Look into my eyes, look into my eyes, the eyes, the eyes, \ the eyes, not around the eyes, don't look around the eyes, \ look into my eyes, you're under." import textwrap print(textwrap.fill(s, 70)) print(textwrap.fill(s, 40)) print(textwrap.fill(s, 40, initial_indent=' ')) print(textwrap.fill(s, 40, subsequent_indent=' ')) # os.get_terminal_size() #import os #os.get_terminal_size() # Error Occured # 2.17 Handling HTML and XML Entities in Text # html.escape() s = 'Elements are written as "<tag>text</tag>".' import html print(s) print(html.escape(s)) print(html.escape(s, quote=False)) # Disable escaping of quotes s = 'Spicy Jalapeño' print(s.encode('ascii', errors='xmlcharrefreplace')) print(s) s = 'Spicy &quot;Jalape&#241;o&quot.' from html.parser import HTMLParser import html p = HTMLParser() print(html.unescape(s)) t = 'The prompt is &gt;&gt;&gt;' from xml.sax.saxutils import unescape print(unescape(t)) # 2.18 Tokenizing Text text = 'foo = 23 + 42 * 10' tokens = [('NAME', 'foo'), ('EQ','='), ('NUM', '23'), ('PLUS','+'), ('NUM', '42'), ('TIMES', '*'), ('NUM', '10')] import re NAME = r'(?P<NAME>[a-zA-Z_][a-zA-Z_0-9]*)' NUM = r'(?P<NUM>\d+)' PLUS = r'(?P<PLUS>\+)' TIMES = r'(?P<TIMES>\*)' EQ = r'(?P<EQ>=)' WS = r'(?P<WS>\s+)' ''' master_pat = re.compile('|'.join([NAME, NUM, PLUS, TIMES, EQ, WS])) scanner = master_pat.scanner('foo = 42') print(scanner.match()) print(_.lastgroup, _.group()) ''' from collections import namedtuple master_pat = re.compile('|'.join([NAME, NUM, PLUS, TIMES, EQ, WS])) Token = namedtuple('Token', ['type', 'value']) def generate_tokens(pat, text): scanner = pat.scanner(text) for m in iter(scanner.match, None): yield Token(m.lastgroup, m.group()) for tok in generate_tokens(master_pat, 'foo = 42'): print(tok) tokens = (tok for tok in generate_tokens(master_pat, text) if tok.type != 'WS') for tok in tokens: print(tok) # TODO: Skip, because i can't understand # 2.19 Writing a Simple Recursive Descent Parser # 2.20 Performing Text Operations on Byte Strings # Perform common text operations(stripping, searching, replacement) on byte strings. data = b'Hello World' print(data[0:5]) print(data.startswith(b'Hello')) print(data.split()) print(data.replace(b'Hello', b'Hello Cruel')) # In Byte arrays data = bytearray(b'Hello World') print(data[0:5]) print(data.startswith(b'Hello')) print(data.split()) print(data.replace(b'Hello', b'Hello Cruel')) data = b'FOO:BAR,SPAM' import re # re.split('[:,]', data) # Error Occured print(re.split(b'[:,]', data)) a = 'Hello World' # Text string print(a[0]) print(a[1]) b = b'Hello World' # Byte string print(b[0]) print(b[1]) s = b'Hello World' print(s) print(s.decode('ascii')) print(b'%10s %10d %10.2f' % (b'ACME', 100, 490.1)) # print(b'{} {} {}'.format(b'ACME', 100, 490.1)) # Error Occured print('{:10s} {:10d} {:10.2f}'.format('ACME', 100, 490.1).encode('ascii')) # Write a UTF-8 filename with open('jalape\xf1o.txt', 'w') as f: f.write('spicy') # Get a directory listing import os print(os.listdir('.')) # Text string (names are decoded) print(os.listdir(b'.')) # Byte string (names left as bytes)
3a94506be1a06ff57ad47e7eed4df8fb7fb4b253
AGRamirezz94/COGS-202
/regex_test.py
917
3.53125
4
import re import random import sys # Get the text for the constitution #page = requests.get('https://www.usconstitution.net/const.txt', verify=True) with open("const.txt") as myfile: const_text = myfile.read() #print const_text # A useful construct I'm leaving in, commented out constitution_lines = const_text.split('\n') # for line in constitution_lines: # print "-->",line # Define the regular expression and use it to find matches regex = r"(Amendment) " matches = re.findall(regex, const_text) # Do something with the matches phrases = ["A M E N D M E N T", " Unconstitutional", ":::::::::<[]>:::::::::::"] for match in matches: print random.choice(phrases) if random.choice(phrases) == " Unconstitutional": print " I plead the fifth :(" # Do a replace. Uncomment to see it working #backwards = re.sub(regex, r"--==>>\2 is the \1 in question<<==--", const_text) #print backwards
243bc53d352c7b539dc0856aba22db34c34c787b
afergadis/keras-nlp
/keras_nlp/preprocessing/segment.py
4,609
3.6875
4
import re def sent_tokenize( text, subst="\n", regex="(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s" ): """ A simple sentence tokenizer based on regular expressions to find the sentence boundaries. Parameters ---------- text : str The text to tokenize. subst : str The substitution character that defines a sentence boundary. regex : str The regular expresion to use in order to find sentence boundaries. Returns ------- list A list with the sentences of the text. See Also -------- `https://stackoverflow.com/a/25736082/1143894`_ Examples -------- >>> doc = "MI patients had 18% higher plasma levels of MAp44 "\ "(IQR 11-25%) as compared to the healthy control group (p < 0.001). "\ "However, neither salvage index (Spearman rho -0.1, p = 0.28) " \ "nor final infarct size (Spearman rho 0.02, p = 0.83) correlated "\ "with plasma levels of MAp44." >>> sents = sent_tokenize(doc) >>> print(len(sents)) 2 """ substitutions = re.sub(regex, subst, text, 0, re.MULTILINE) return list(substitutions.split(subst)) def word_tokenize(text, regex="\W+|\t|\n"): """ A simple word tokenizer to tokenize text on the giver regular expression. Parameters ---------- text : str The text to tokenize. regex : str The regular expresion to use in order to split the `text`. Returns ------- list A list with the words in the text. Separators are trimmed. Examples -------- >>> sentence = 'A sentence\\tto\\nbe tokenized\\n' >>> word_tokenize(sentence) ['A', 'sentence', 'to', 'be', 'tokenized'] """ tokens = re.split(regex, text) if len(tokens[-1]) == 0: tokens.pop() return tokens class SentenceSplitter: """ Splitting sentences using some heuristics that help to prevent wrong segmentation especially in scientific papers. Examples -------- >>> doc = "MI patients had 18% higher plasma levels of MAp44 "\ "(IQR 11-25%) as compared to the healthy control group (p < 0.001). "\ "However, neither salvage index (Spearman rho -0.1, p = 0.28) " \ "nor final infarct size (Spearman rho 0.02, p = 0.83) correlated "\ "with plasma levels of MAp44." >>> ss = SentenceSplitter() # Use the module's sent_tokenize function. >>> print(len(ss.tokenize(doc))) 2 """ def __init__(self, tokenizer=None): if tokenizer is None: self.tokenizer = sent_tokenize else: self.tokenizer = tokenizer @staticmethod def _first_alpha_is_upper(sent): for c in sent: if c.isalpha(): if c.isupper(): return True return False @staticmethod def _ends_with_special(sent): sent = sent.lower() ind = [ item.end() for item in re.finditer( r'[\W\s]sp.|[\W\s]nos.|[\W\s]figs.|[\W\s]sp.[\W\s]no.|' r'[\W\s][vols.|[\W\s]cv.|[\W\s]fig.|[\W\s]e..|' r'[\W\s]et[\W\s]al.|[\W\s]i.e.|[\W\s]p.p.m.|[\W\s]cf.|' r'[\W\s]n.a.', sent) ] if len(ind) == 0: return False else: ind = max(ind) if len(sent) == ind: return True else: return False def _split_sentences(self, text): sents = [l.strip() for l in self.tokenizer(text)] ret = [] i = 0 while i < len(sents): sent = sents[i] while (i + 1) < len(sents) and ( self._ends_with_special(sent) or not self._first_alpha_is_upper(sents[i + 1])): sent += ' ' + sents[i + 1] i += 1 ret.append(sent.replace('\n', ' ').strip()) i += 1 return ret def tokenize(self, text: str): """ Tokenize a text to its sentences. Parameters ---------- text : str The text to tokenize. Returns ------- list A list of sentences. """ sents = [] subtext = re.sub(r'\s+', ' ', text.replace('\n', ' ')).strip() if len(subtext) > 0: ss = self._split_sentences(subtext) sents.extend([s for s in ss if (len(s.strip()) > 0)]) if len(sents[-1]) == 0: sents = sents[:-1] return sents if __name__ == '__main__': import doctest doctest.testmod()
d8f1f90bcf7d84a8a52a5055ab3f4850de1d4a77
lykketrolle/Noroff_NIS2016
/TAP 4/TAP04-sets[4].py
2,083
4.75
5
#!/usr/bin/python """ Name: Kjell Chr. Larsen Date: 24.05.2017 Make two different set with fruits, copy the one set in to the other and compare the two sets for equality and difference. """ print("This program will have two sets of fruits. One will then be copied,\n" "into the other, then a comparison of the two sets for difference and equality \n" "is done to show the operators used and the result produced.\n") print("A set is an unordered collection with no duplicate elements. Curly braces or the \n" "set() function can be used to create sets. Note: to create an empty set, we use the \n" "set() and not {} - curly braces, where the latter creates an empty dictionary.\n") print("Here is a demonstration. A set with duplicate elements: ") print(""" "basket = {'Banana', 'Apple', 'Banana', 'Apple', 'Pear', 'Orange'}" Here we see there are duplicate elements, lets see how the printout will be. """) test_basket = {'Banana', 'Apple', 'Banana', 'Apple', 'Pear', 'Orange'} print(test_basket) print("\nAs we can see, the printout only prints out one of the duplicate elements.\n") # Here is the sets related to the assignment. Both sets have different and equal values set1 = {'Grapes', 'Apples', 'Oranges', 'Pear', 'Peaches'} set2 = {'Blueberry', 'Apricot', 'Avocado', 'Apples', 'Bilberry'} print("SET1:", set1, "\nSET2:", set2) print("") """ Now I will copy the content from set2 into set1. I do this by using the | operator. """ # Here I copy set2 into set1 and then print out the result cp_set = set1 | set2 print("Here is the result of copying set2 into set1 using ' | ':\n", cp_set) print("") # Now I will use the ' - ' operator to check the difference between set1 and set2 diff_set = set1 - set2 print("The difference between set1 and set2: ", diff_set) print("Now to test difference between the sets. First I test to see if every\n" "element is in set1 and set2 by using the ' set.difference() 'operator.\n") print(set1.difference(set2)) print("This is the difference in the two sets.")
ada51e6ff846c136f10eadc00f10e0b0ffb38d59
georgiedignan/she_codes_python
/Session4/functions.py
445
3.953125
4
# def ask_name(): # name = input("What is your name? ") # return name # georgie_name = ask_name() # print(georgie_name) # mimi_name = ask_name() # print(mimi_name) # def create_greeting(name): # greeting = f"Hello {name}" # return greeting # print(create_greeting("georgie")) #Create function that takes an integer as a parameter #Returns the integer multiplied by 3 def integer(int): return int*3 print(integer(3))
9454731a5b8163df69c66fd9a7a27ce4f6195257
georgiedignan/she_codes_python
/Session5_dictionaries/Exercises/Q3.py
402
3.609375
4
names = ["Maddy", "Bel", "Elnaz", "Gia", "Izzy","Joy", "Katie", "Maddie", "Tash", "Nic","Rachael", "Bec", "Bec", "Tabitha", "Teagen","Viv", "Anna", "Catherine", "Catherine", "Debby","Gab", "Megan", "Michelle", "Nic", "Roxy","Samara", "Sasha", "Sophie", "Teagen", "Viv"] # list_names = list(set(names)) names_dict = {}.fromkeys(names,0) for name in names: names_dict[name] += 1 print(names_dict)
82386828e06a85350e834c807cd003896a97446e
georgiedignan/she_codes_python
/Session2/conditionals_exercises.py
747
3.9375
4
#Exercise 1 # moths_in_house = bool(input("Are there moths in the hosue? ")) # if moths_in_house == True: # print("Get the moths") # else: # print("No threats detected") #Exercise 2 # light_color = "red" # if light_color is "red": # print("correct") #Exercise 3 #Exercise 4 # height = 164 # if height > 120: # print("Hop on!") # else: # print("Not today.") #Exercise 5 # username = "georgie" # password = "dignan" # input_username = input("Username: ") # input_password = input("Password: ") # if input_username == username and input_password == password: # print("Correct!") # else: # print("Incorrect") #Exercise 6 # email = "georgiedignan@gmail.com" # if "@" in email: # print("Valid email address.")
9fb5404d86596e822da14852d181caedd240edf2
georgiedignan/she_codes_python
/Session3/Exercises/while_loops.py
947
4.21875
4
#Exerise 1 # number = input("Please guess any number: ") # while number != "": # number = input("Please guess any number: ") #Exercise 2 number = int(input("Please enter a number: ")) #using a for loop # for num in range(1,number+1): # if num%2!=0: # print(num) #try using a while loop i=1 while (i<=number): if i%2 != 0: print(i) i+=1 # N = int(input("Enter a number: ")) # i = 1 # while(i <= N): # if (i % 2) == 0: # print('EVEN') # else: # print('ODD') # i += 1 #Exercise 3 # number = 43 # guess = int(input("Guess my number: ")) # if guess > number: # print("Guess is too high!") # else: # print("Guess is too low!") # while guess != number: # guess = int(input("Guess my number: ")) # if guess > number: # print("Guess is too high!") # elif guess < number: # print("Guess is too low!") # else: # print("That is correct!")
85213ae0071b9f2d5caf92488a5eea6a4e2bb444
jbrudvik/sublime-sum
/sum.py
2,191
3.59375
4
# -*- coding: utf-8 -*- import re try: import sublime import sublime_plugin class SumCommand(sublime_plugin.TextCommand): def run(self, edit): # Create new buffer that never reports dirty status sum_view = self.view.window().new_file() sum_view.set_name('Sum') sum_view.set_scratch(True) # Insert sum of numbers from original buffer into new buffer file_text = self.view.substr(sublime.Region(0, self.view.size())) file_sum = sum_of_numbers_in_string(file_text) sum_view.insert(edit, 0, str(file_sum)) # Make new buffer read-only sum_view.set_read_only(True) except ImportError: pass def is_float(s): """Return boolean indicating whether a string can be parsed to an float.""" try: float(s) return True except ValueError: return False def number_from_string(s): """ Parse and return number from string. Return float only if number is not an int. Assume number can be parsed from string. """ try: return int(s) except ValueError: return float(s) def words_in_string(s): """ Return a list of words aggressively split from the string. Split on whitespace and some punctuation. """ return [word for word in re.split('[\s,[\](){}]', s) if word] def string_without_currency(s): """ Return a string without leading or trailing currency symbols. Strip leading and trailing currency symbols, and currency symbols at position 1 if first character is + or - """ currency_symbols = '$€£¥¢' s = s.strip(currency_symbols) if len(s) > 2 and s[0] in '+-' and s[1] in currency_symbols: s = s[0] + s[2:] return s def sum_of_numbers_in_string(s): """ Return sum of numbers in string. Make a best guess at what are summable numbers given unknown format. Strip some punctuation and currency symbols. """ words = [string_without_currency(word) for word in words_in_string(s)] numbers = [number_from_string(word) for word in words if is_float(word)] return sum(numbers)
aeb8a3648da51cead7ac4eae29f809ab02a1f0b6
nknavkal/project-euler
/largestpalindromeproduct.py
823
3.8125
4
def reverseIt(n): a = [] b = len(str(n)) if n%10 != 0: for i in range(b): a.append(n%10) n = int((n-a[-1])/10) a.reverse() for i in range(b): n = 10*n + a.pop() return n def palindromeFinder(): print("For this problem, we're going to find the largest palindromic number that is the product of two n-digit numbers") n = int(input("choose that n: ")) allofthem = [] for i in range (10**(2*(n-1)), 10**(2*n)): if i == reverseIt(i): allofthem.append(i) allofthem.reverse() for i in allofthem: for j in range(10**(n-1),10**n): if i%j == 0: if j < 1000 and j > 100 and int(i/j) < 1000 and int(i/j) > 100: print(i, j, int(i/j)) palindromeFinder()
810a9ba68bf4e22c888a6b530265e7be8fbc457d
Amantini1997/FromUbuntu
/Sem 2/MLE/Week 2 - Decision Tree & Boosting/regression.py
1,658
4.375
4
# regression.py # parsons/2017-2-05 # # A simple example using regression. # # This illustrates both using the linear regression implmentation that is # built into scikit-learn and the function to create a regression problem. # # Code is based on: # # http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html # http://scikit-learn.org/stable/auto_examples/linear_model/plot_ransac.html import math import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model from sklearn.datasets import make_regression from sklearn.model_selection import train_test_split # # Generate a regression problem: # # The main parameters of make-regression are the number of samples, the number # of features (how many dimensions the problem has), and the amount of noise. X, y = make_regression(n_samples=100, n_features=1, noise = 2) # Split the data into training and test set X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=0) # # Solve the problem using the built-in regresson model # regr = linear_model.LinearRegression() # A regression model object regr.fit(X_train, y_train) # Train the regression model # # Evaluate the model # # Data on how good the model is: print("Mean squared error: %.2f" % np.mean((regr.predict(X_test) - y_test) ** 2)) # Explained variance score: 1 is perfect prediction print('Variance score: %.2f' % regr.score(X_test, y_test)) # Plotting training data, test data, and results. plt.scatter(X_train, y_train, color="black") plt.scatter(X_test, y_test, color="red") plt.scatter(X_test, regr.predict(X_test), color="blue") plt.show()
fe463b29379ec7121b135c448b206be9f11123ff
Amantini1997/FromUbuntu
/Sem 2/MLE/Week 2 - Decision Tree & Boosting/Error_function.py
438
3.5
4
import matplotlib.pyplot as plt a = 3 errors = [] X_train = [1] y_train = [1] def predict_arr(X): return X def plot_model_and_input(): ## DATA PLOT plt.figure() plt.plot(X_train, y_train, "b.") plt.plot(X_train, predict_arr(X_train), "r.") plt.show() plt.close() ## ERROR PLOT plt.figure() plt.plot(range(len(errors)), errors) plt.show() plt.close() plot_model_and_input() b = 3
98a0b26efc09b461a8ac2e815e8785d866cf7707
greatwallgoogle/Learnings
/other/learn_python_the_hard_way/ex34.py
883
4.4375
4
# ex34 : 访问列表元素 # 常用函数 # 声明列表:[] # 索引法访问元素: list[index] # 删除某个元素:del(list[index]) # 列表元素反向:list.reverse() # 追加元素:list.append(ele) animals = ['dog','pig','tiger','bear',3,4,5,6] print("animals :",animals) # 索引法访问列表中的值 dog = animals[0] print("animals first ele:", dog) # 使用方括号的形式截取列表 list2 = animals[1:5] #从索引为1的地方开始,读取(5-1)个元素 print("animals[1:5]:",list2) # 追加元素 animals.append("chicken") print("animals :",animals) # 删除元素 print("---list2-----orign:" , list2) del(list2[0]) print("---list2-----new : " ,list2) # 反向元素 print("---reverse-----orign:" , list2) list2.reverse() print("---reverse-----new:" , list2) # 移除列表中的某个元素 list2.pop() print("---pop-----new:" , list2)
e310bdad449d5b03b18cdfc4d16a6ce25cc676a4
greatwallgoogle/Learnings
/other/learn_python_the_hard_way/ex12.py
413
3.640625
4
# 提示别人,即给input函数指定参数用于提示 # 重写ex11.py的内容 y = input("Name? ") print(y) # ------ print("----------") age = input("How old are you ?") height = input("How tall are you ?") weight = input("How much do you weight?") print("So,you are %r old, %r tall and %r heavy." % (age,height,weight)) # 在终端输入pydoc input,查看此函数的API简介 # 然后输入q退出pydoc
4ed2d4ef6171647b08629409ec77b488d059bc6f
greatwallgoogle/Learnings
/other/learn_python_the_hard_way/ex9.py
975
4.21875
4
# 打印,打印,打印 days = "Mon Tue Wed Thu Fri Sat Sun" # 第一中方法:将一个字符串扩展成多行 months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJuly\nAug" print("Here are the days :",days) # 等价于 print("Here are the days : %s" % days) print("Here are the months : ", months) #等价于 print("Here are the months : %s" % months) # 第二种方法:使用三引号输出任意行的字符串 print(""" There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or6. """) # for example tabby_cat = "\tI'm tabbed in." print("tabby_cat:",tabby_cat) persian_cat = "I'm split\non a line." print("persian_cat:",persian_cat) backslash_cat = "I'm \\ a \\ cat." print("backslash_cat:",backslash_cat) fat_cat = ''' I'll do a list: \t* Cat food \t* Fishied \t* Catnit\n\t* Grass ''' print(fat_cat) # # while True: # for i in ["/","-","|","\\","|"]: # print("%s\r" % i)
6e08f46015d7af78c93569e722ad4dc04ffc0f28
greatwallgoogle/Learnings
/other/learn_python_the_hard_way/ex_class1.py
2,178
3.671875
4
# self 代表类的实例,self 在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数。 # 类函数的第一个参数必须是self # 类变量定义: # _foo:单下划线开头的表示是protected类型的变量 # __foo:双下划线开头的表示是private类型的变量 # __foo__:表示定义的是特殊方法,一般是系统定义名字 class Map(object): """docstring for Map""" def __init__(self, arg): super(Map, self).__init__() self.arg = arg print("Map arg:",arg) print(self) print(self.__class__) # 析构函数,当对象不再被使用时,__del__方法运行 def __del__(self): print("Map Del") def nextScene(self,sceneName): pass def openingScene(self): pass class Engine(object): """docstring for Engine""" def __init__(self, arg): super(Engine, self).__init__() self.arg = arg # 类的文档字符串 print(self.__doc__) def play(self): pass class Scene(object): """docstring for Scene""" def __init__(self, arg): super(Scene, self).__init__() self.arg = arg print(self.__doc__) def enter(self): pass # 表示继承自Scene class Death(Scene): """docstring for Death""" def __init__(self, arg): super(Death, self).__init__() self.arg = arg def enter(self): pass # 表示继承自Scene class CenterlCorridor(Scene): """docstring for CenterlCorridor""" def __init__(self, arg): super(CenterlCorridor, self).__init__() self.arg = arg def enter(self): pass # 表示继承自Scene class LaserWeaponArmory(Scene): """docstring for LaserWeaponArmory""" def __init__(self, arg): super(LaserWeaponArmory, self).__init__() self.arg = arg def enter(self): pass # 表示继承自Scene class TheBridge(Scene): """docstring for TheBridge""" def __init__(self, arg): super(TheBridge, self).__init__() self.arg = arg def enter(self): pass # 表示继承自Scene class EscapePod(Scene): """docstring for EscapePod""" def __init__(self, arg): super(EscapePod, self).__init__() self.arg = arg def enter(self): pass # 创建实例 aMap = Map("CenterlCorridor") aGame = Engine(aMap) aGame.play()
a73adc9082e54df28f0db2a9b93496e2f1bcd5ff
thekayode/area_of_shapes
/area_of_triangle _assignment.py
993
4.40625
4
''' This programme is too calculate the area of a triangle. ''' base = float(input('Enter the base of the triangle\n')) height = float(input('Enter the height of the the triangle\n')) area = 1/2 * (base * height) print('area', '=', area) ''' This programme is too calculate the area of a square. ''' length = float(input('Enter the length of the square\n')) area = length**2 print('area', '=', area) ''' This programme is too calculate the area of a cylinder. ''' radius = float(input('Enter the radius of cylinder: ')) pi = 3.142 height = float(input('Enter the heigth of cylinder: ')) area = (2 * pi * radius**2) + (2 * pi * radius * height) print('Enter the area', (round(area,2))) ''' This programme is too calculate the area of a trapezoid. ''' a = float(input('Enter base 1 of trapezoid: ')) b = float(input('Enter base 2 of trapezoid: ')) height = float(input('Enter the height of trapezoid: ')) area = 1/2 * (a + b) * height print('area', '=', area)
3a60055f2ac29c71ecc7991bf69e89cd1750d475
carolinemeng/RecommendSystem
/RecommendSystem/simpleRecommender/simple.py
2,164
3.59375
4
# Simple Recommendation Based Only On Popularity and Ratings import pandas as pd import numpy as np import matplotlib.pyplot as plt #column headers for the dataset data_cols = ['user id', 'movie id', 'rating', 'timestamp'] item_cols = ['movie id', 'movie title', 'release date', 'video release date', 'IMDb URL', 'unknown', 'Action', 'Adventure', 'Animation', 'Childrens', 'Comedy', 'Crime', 'Documentary', 'Drama', 'Fantasy', 'Film-Noir', 'Horror', 'Musical', 'Mystery', 'Romance ', 'Sci-Fi', 'Thriller', 'War', 'Western'] user_cols = ['user id', 'age', 'gender', 'occupation', 'zip code'] #importing the data files onto dataframes users = pd.read_csv('/Users/carolinemeng/Desktop/ml-100k/u.user', sep='|', names=user_cols, encoding='latin-1') item = pd.read_csv('/Users/carolinemeng/Desktop/ml-100k/u.item', sep='|', names=item_cols, encoding='latin-1') data = pd.read_csv('/Users/carolinemeng/Desktop/ml-100k/u.data', sep='\t', names=data_cols, encoding='latin-1') #printing the head of these dataframes() print("Users Head") print(users.head()) print("\nItems Head") print(item.head()) print("\nData Head") print(data.head()) #printing the details of these dataframes() print('\n',users.info()) print('\n',item.info()) print('\n',data.info()) print ('\n') #Using Pandas to manipulate the data #Create one data frame from the three print('The Merged Dataset') print ('***************************************************************\n') dataset = pd.merge(pd.merge(item, data),users) print(dataset.head()) #Create dataframes with mean rating and total number of ratings ratings_total = dataset.groupby('movie title').size() rt = (dataset.groupby('movie title'))['movie title','rating'] ratings_mean = (rt.mean()) #modify those dataframes so that we can merge the two ratings_total = pd.DataFrame({'movie title':ratings_total.index, 'total ratings': ratings_total.values}) ratings_mean['movie title'] = ratings_mean.index final = pd.merge(ratings_mean, ratings_total).sort_values(by = 'total ratings', ascending= False) print(final.head()) print(final.describe()) final = final[:300].sort_values(by = 'rating', ascending = False) print(final.head())
b1869818de65a93e61f1fc9cf4320396c09ca8bc
oct0f1sh/cs-diagnostic-duncan-macdonald
/functions.py
760
4.21875
4
# Solution for problem 8 def fibonacci_iterative(num = 10): previous = 1 precedingPrevious = 0 for number in range(0,num): fibonacci = (previous + precedingPrevious) print(fibonacci) precedingPrevious = previous previous = fibonacci # Solution for problem 9 # I don't know how to call stuff from the terminal and my python # installation is really screwed up so I'm using PyCharm to run these # and i'm just going to set an input arg = int(input("Enter a number: ")) fibonacci_iterative(arg) print() # Solution for problem 10 def factorial_recursive(num): solution = num while num != 0: solution = solution * (num - 1) print(solution) num = num - 1 factorial_recursive(6)
bc3433cbcf10bc908f4ee18af182a489bbb403d3
ISEexchange/Python-Bootcamp
/intermediate_class/session_3/hw.py
3,026
3.96875
4
################################# # In Class Assignment and Homework ################################# # 1. Write a function that takes in any number of un-named and named parameters. # 2. Loop through the list of un-named parameters and print the values. # 3. Loop through the dictionary of named parameters and print out the # parameter name and value. # Let's update the Thermostat class from session 2. You can update your own # class or use the provided one in the homework solutions. # 4. Add a class variable to the Thermostat class called MAX_BTU and give it some # default value. This class variable is a representation of how large of an # AC each thermostat can handle (measured in BTUs). All of the thermostats in # your system are the same so they can all share this one constant. # 5. Add a class method that can allow an administrator to change this max # constant. The function definition should look like: # def update_max_btu(cls, admin_pasword) # Only if the correct admin password is provided can the class variable # then be updated. # 6. Add a static method that wlil return the MAX_BTU value. # Let's practice inheritance! # 7. We now need to store more information about the individual AC and heater # components. # Create three new classes: # 1. TemperatureChanger # 2. AirConditioner (inherits from TemperatureChanger) # 3. HeatingUnit (inherits from TemperatureChanger) # 8. TemperatureChanger contains: # an instance variable for on/off # an instance variable for fanspeed # instance methods for setting on/off and fanspeed # 9. AirConditioner contains: # an instance variable for BTU # 10. HeatingUnit contains: # an instance variable for watts # 11. Update the Thermostat class so that it contains a list or dictionary of # TemperatureChanger objects instead of whatever you had before for tracking # the ACs and heaters. # Comprehensions! # Think about what these are going to produce before running it! # 12. Whats the value of A in: # A = [i for i in range(10, 100, 5)] # 13. Whats the value of B in: # B = [i for i in range(10, 100, 3) if str(i)[0] in ('3','4','5')] # 14. Whats the value of C in: # C = {i for i in [(1,2),(3,4),(5,6),(2,1),'a','b','c']} # 15. Whats the value of D in: # import string # D = {i:i.lower() for i in string.letters.upper()} # 16. Whats the value of E in: # E = [i for i in A for j in B if i == j] # 17. Change the following function so a list comprehension is used # # from string import lowercase, digits # str_to_process = 'O329u@T4Gs5-HH643.hf838' # allowed_chars = lowercase + digits # # def checker(str_to_process): # for c in str_to_process: # if c not in allowed_chars: # return False # return True # 18. If its not already, update checker() from above so that the body # is only one line of code
d9cd91c8a4efb8c0da7fe18fc4d3ff83e24eed8d
jfudge/python-flask
/app.py
4,360
4.0625
4
from flask import Flask, render_template import datetime app = Flask(__name__) site_title = "Python and Flask" year = datetime.datetime.now().strftime("%Y") pythons_list = [ { "answer": "Python is a programming language used for building object oriented interactive interfaces that need a programmable interface. It is used to build everything from applications to robots.", "question": "What is Python and what is it used for?" }, { "answer": "A class is used by creating a class statement which is a particular object type. An Object is a collection of methods and data. An class is a blueprint for that object.", "question": "What is a class and what is an object in Python?" }, { "answer": "@property is used in python to create getters and setters in object oriented programming. Attributes are used to create access controls to classes.", "question": "What are properties/attributes in Python and in what way(s) do they differ from variables?" }, { "answer": "When invoked functions stored in class dictionaries get turned into methods. Methods only differ from regular functions in that the object instance is prepended to the other arguments. By convention, the instance is called self but could be called this or any other variable name.", "question": "What are methods in Python and in what way(s) do they differ from functions?" }, { "answer": "There are many types of magic methods. They automatically perform special actions. They are name with two underscores before and after the function. Descriptors are used to bind functions to methods. The constructor method is a method called __init__() in Python which is called when a new instance of the class is created by using the class name as a function. ", "question": "What are magic methods, what is the constructor method specifically, and how do they differ from normal methods?" }, { "answer": "Private class variable names are class variable names which are only accessible from inside of the class they are defined in and its methods and which can therefore only be altered using the methods inside of that class. Private name mangling is used to keep the code object-oriented by keeping the data encapsulated inside of the object and to keep the processing of that data abstracted from the user.", "question": "What is private name mangling and why is it used?" }, { "answer": "The 4 priniples of object-oriented programming are Encapsulation; the inclusion of one thing within another thing so that the included thing is not apparent, Abstraction; is used for efficiency purposes when the developer hides certain part to make it less complex, Inheritance; when sublcasses inherit definitions of one or more classes and Polymorphism; when objects can do different things depending on the context without changing the core interface.", "question": "Identify and define the four principles of object-oriented programming and explain in what way(s), each is used in Python." }, { "answer": "PIP stands for PIP Installs Packages. It is used for installing thrid party libraries and packages for Python. ", "question": "What is PIP, what is a wheel and what are they used for?" }, { "answer": "Flask is a framework for creating applications in python. Flask is used to provide a router and server and connect a thirty party HTML templating engine Jinja", "question": "What is Flask, what is Jinja and what are they used for?" }, { "answer": "SQL is a programming language used to manage relational databases. MySQL and MariaDB are relational database systems where you can create, update and administer a relational database. MySQL Connector is a library to connect and manage MySQL or MariaDB in python.", "question": "What is SQL/ MySQL/MariaDB, what is MySQL Connector and what are they used for?" }, ] @app.route("/") def index(): return render_template( "index.html.j2", site_title = site_title, page_title = site_title + " - Home", year = year, pythons_list = pythons_list ) if __name__ == "__main__": app.run(debug = True)
18db5e61c29a777be3bd163202dce195042b6878
dianamorenosa/Python_Fall2019
/ATcontent.py
487
4.125
4
#!/usr/bin/python #1.- Asign the sequence to a variable #2.- Count how many A's are in the sequence #3.- Count how many T's are in the sequence #4.- Sum the number of A's and the number of T's #5.- Print the sum of A's and T's seq1= ("ACTGATCGATTACGTATAGTATTTGCTATCATACATATATATCGATGCGTTCAT") #Asign the sequence to the variable seq1 ATcount= seq1.count ("A") + seq1.count("T") #Use count method for A and T, the + symbol will sum the number of A's and the number of T's print(ATcount)
a3037b8de00a8552d355fb5e45a15c6dc0743b77
rsingla92/advent_of_code_2017
/day_3/part_1.py
2,422
4.15625
4
''' You come across an experimental new kind of memory stored on an infinite two-dimensional grid. Each square on the grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while spiraling outward. For example, the first few squares are allocated like this: 17 16 15 14 13 18 5 4 3 12 19 6 1 2 11 20 7 8 9 10 21 22 23---> ... While this is very space-efficient (no squares are skipped), requested data must be carried back to square 1 (the location of the only access port for this memory system) by programs that can only move up, down, left, or right. They always take the shortest path: the Manhattan Distance between the location of the data and square 1. For example: Data from square 1 is carried 0 steps, since it's at the access port. Data from square 12 is carried 3 steps, such as: down, left, left. Data from square 23 is carried only 2 steps: up twice. Data from square 1024 must be carried 31 steps. How many steps are required to carry the data from the square identified in your puzzle input all the way to the access port? ''' from math import sqrt, floor, fabs def calculate_spiral_coords(n): # Determine the radius of the spiral 'n' is in. # If the spiral length is u, then the last element is at u^2. # The next spiral is u^2 + 1 right, continuing u up, then u+1 # leftwards, u+1 downwards, and u+2 right. # Calculate u u = floor(sqrt(n)) if u % 2 == 0: u -= 1 radius = (u - 1) // 2 n -= u ** 2 if n == 0: return radius, radius n -= 1 if n < u: return radius+1, radius-n n -= u if n < u + 1: return radius + 1 - n, radius - u n -= u+1 if n < u + 1: return radius - u, radius - u + n n -= u + 1 if n < u + 2: return radius - u + n, radius + 1 def calculate_steps(n): x, y = calculate_spiral_coords(n) print 'x: ' + str(x) + ' y: ' + str(y) return fabs(x)+fabs(y) if __name__ == '__main__': test_1 = 1 print 'Test 1 result is ' + str(calculate_steps(test_1)) test_2 = 12 print 'Test 2 result is ' + str(calculate_steps(test_2)) test_3 = 23 print 'Test 3 result is ' + str(calculate_steps(test_3)) test_4 = 1024 print 'Test 4 result is ' + str(calculate_steps(test_4)) my_input = 347991 print 'My result is ' + str(calculate_steps(my_input))
a11169561d2f55ae809039b34052a60fe630462b
PQuix/pythonCrashCourse
/python_work/testing/employee_class.py
530
4.09375
4
class Employee(): """Creates an employee.""" def __init__(self, first, last, salary): """Defines the employee by name and salary.""" self.first = first self.last = last self.salary = salary def get_full_name(self): """Returns the employee's full name.""" self.full_name = self.first + " " + self.last return self.full_name.title() def give_raise(self, increase='50000'): """Increases the employee's salary by the specified amount.""" self.salary = int(self.salary) + int(increase) return self.salary
791650496e801ade14b6d4c86c5f53a4e53fc026
PQuix/pythonCrashCourse
/python_work/admin.py
611
4.0625
4
from user_class import User class Admin(User): """Defines an admin, child of the User-class, and its properties.""" def __init__(self, first_name, last_name, username): """Initializes the admin and the required information.""" super().__init__(first_name, last_name, username) self.privileges = Privileges( "Can add posts", "Can delete posts", "Can ban users" ) class Privileges(): """Defines a list of privileges for a user.""" def __init__(self, *privileges): self.privileges = privileges def show_privileges(self): for privilege in self.privileges: print(privilege)
513f6897b84fd22d38742167cd47bcf6ea3ac4f1
PQuix/pythonCrashCourse
/python_work/aliens.py
254
3.71875
4
alien_color = "grey" if(alien_color == "green"): print("1 shot! 5 points for you!") elif(alien_color == "yellow"): print("2 hits! 10 points for you!") elif(alien_color == "red"): print("You killed it! 15 points for you!") else: print("You missed!")
9a1255f7af057c5305f5c44b291f6a01c5f435ca
PQuix/pythonCrashCourse
/python_work/restaurant.py
1,008
3.953125
4
class Restaurant(): """A class that represents a restaurant.""" def __init__(self, restaurant_name, cuisine_type): """Initialize name of restaurant and type of cuisine served.""" self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): """Describes the restaurant.""" print(self.restaurant_name.title() + " is a restaurant that serves " + self.cuisine_type.title()) def open_restaurant(self): """Stating the opening of the restaurant.""" print(self.restaurant_name.title() + " is now open!") #restaurant = Restaurant("giornos", "italian") #print("Restaurant: " + restaurant.restaurant_name.title()) #print("Cuisine: " + restaurant.cuisine_type.title()) #restaurant.describe_restaurant() #restaurant.open_restaurant() first = Restaurant("Jennifers", "German") second = Restaurant("Seconds", "Mystery Food") third = Restaurant("Freddy Fuego", "Burritos") first.describe_restaurant() second.describe_restaurant() third.describe_restaurant()
95e77e7734ad56da50c4c68a62f14ce3e0b63671
PQuix/pythonCrashCourse
/python_work/names.py
213
3.640625
4
names = ["Jennifer", "Eirik", "Håvard"] print(names[0]) print(names[1]) print(names[2]) print("Good evening, " + names[0] + "!") print("Good evening, " + names[1] + "!") print("Good evening, " + names[2] + "!")
f2ebecc1ae4ecf33bdafff1a64e324685db1d23a
PQuix/pythonCrashCourse
/python_work/hello_admin.py
353
3.71875
4
usernames = ["pquix", "thirdrevolt", "admin", "ymentradonsax", "snowowl15"] if usernames: for user in usernames: if(user == "admin"): print("Greetings, " + user.title() + ", would you like to see a status report?") else: print("Hello, " + user.title() + ", thank you for logging in.") else: print("Sorry, there are no users registered...")
aa77d85d283be3f9d1e812f2ec9890507a08ccdc
harrider/AoC2019
/Dec_4/SecurityModule/PasswordRule_NDigitPassword.py
568
3.59375
4
class PasswordRule_NDigitPassword: def __init__(self, requiredPasswordLength): if isinstance(requiredPasswordLength, int) == False: raise TypeError('ERROR :: "requiredPasswordLength" must be of type "int"!') if requiredPasswordLength < 0: raise ValueError('ERROR :: "requiredPasswordLength" must be a POSITIVE number!') self.requiredPasswordLength = requiredPasswordLength def Validate(self, password): passwordStr = str(password) return len(passwordStr) == self.requiredPasswordLength
96160a9731bb41f035c3f7dcabeb56719215b6fd
A01377436/Mision-02
/miInfo.py
580
3.515625
4
# Autor: David Alejandro Nicols Palos, A01377436 # Descripcion: Elaboracin de un programa que muestre en pantalla mi informacin # Escribe tu programa después de esta línea. print("Nombre:") print("David Alejandro Nicols Palos") print("Matricula:") print("A01377436") print("Escuela de Procedencia:") print("Prepa Tec Multicultural") print("Carrera:") print("ISDR") print("Quien soy?") print("Me gusta Jugar videojuegos, la msica y la tecnologa, me considero hbil con las computadoras y en las matemticas, mi deporte preferido Es el Futbol y mi libro preferido es el Principito, el primero que le.")
3ce91e12f94f3389775bb3815e925dd6387da366
Woo-Dong/pre-education
/quiz/pre_python_08.py
294
3.609375
4
"""8. 정수를 입력했을 때 짝수인지 홀수인지 핀별하는 코드를 작성하시오 예시 <입력> 정수를 입력하세요 : 14 <출력> 짝수입니다. """ print("짝수입니다." if int(input("정수를 입력하세요 :")) %2 == 0 else "홀수입니다." )
b9e4ce86a0401768957ffa91c60ebc32e55e0184
legend1412/Recommend
/Chapter08/8-2.py
681
3.59375
4
import math import matplotlib.pyplot as plt def sigmoid(x1): return 1 / (1 + math.exp(-x1)) # python2中range生成的是一个数组,python3中生成的是一个迭代器,可以使用list进行转换 x = list(range(-10, 10)) y = list(map(sigmoid, x)) fig = plt.figure(figsize=(4, 4)) ax = fig.add_subplot(111) # 隐藏上边和右边 ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') # 移动另外两个轴 ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data', 0)) ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data', 0.5)) ax.plot(x, y) plt.savefig("data/{}".format("sigmoid.png")) plt.show()
a43e10b5e0adc8002c2865d241aa343a1f67baae
Algorant/HackerRank
/Python/whats_your_name/name.py
311
4.0625
4
# Given input of first name and last name, return the statement # with the persons name in it. def print_full_name(a, b): print("Hello {} {}! You just delved into python.".format(a, b)) if __name__ == '__main__': first_name = input() last_name = input() print_full_name(first_name, last_name)
23241e4ba4dadda493f44610e334ff1dfa533d82
Algorant/HackerRank
/Python/string_validators/string_validators.py
586
4.125
4
# You are given a string . Your task is to find out if the string contains: # alphanumeric characters, alphabetical characters, digits, lowercase # and uppercase characters. if __name__ == '__main__': s = input() # any() checks for anything true, will iterate through all tests # Check for alphanumerics print(any(c.isalnum() for c in s)) # Check for alphabet characters print(any(c.isalpha() for c in s)) # Check for digits print(any(c.isdigit() for c in s)) # Check for lowercase print(any(c.islower() for c in s)) # Check for uppercase print(any(c.isupper() for c in s))
49624d546ad4b998440f082ac43f75168f7431a7
Algorant/HackerRank
/Interview_Prep_Kit/Warm-up_Challenges/Sales_By_Match/sales.py
738
3.65625
4
''' Given some starter code, complete the function such that n number of socks within an array ar are paired to each other. Return the total number of matching pairs of sucks that can be sold. ''' import math import os import random import re import sys # Complete the sockMerchant function below. def sockMerchant(n, ar): pairs = 0 d = {} for i in range(n): if ar[i] in d: d.pop(ar[i]) pairs += 1 else: d[ar[i]] = 1 return pairs if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) ar = list(map(int, input().rstrip().split())) result = sockMerchant(n, ar) fptr.write(str(result) + '\n') fptr.close()
aa361a509b9cb245ecbf9448f4df5279cfc078c6
Algorant/HackerRank
/Python/reduce/reduce.py
557
4.25
4
''' Given list of n pairs of rational numbers, use reduce to return the product of each pair of numbers as numerator/denominator fraction by every fraction in list n. ''' # some of this code is supplied to user from fractions import Fraction from functools import reduce def product(fracs): t = reduce(lambda x, y: x * y, fracs) return t.numerator, t.denominator if __name__ == '__main__': fracs = [] for _ in range(int(input())): fracs.append(Fraction(*map(int, input().split()))) result = product(fracs) print(*result)
f6b7564f728de2663ab87128b71fd4280236772a
Algorant/HackerRank
/Python/set_add/set_add.py
204
4.25
4
''' Given an integer and a list of items as input, use set.add function to count the number of unique items in the set. ''' n = int(input()) s = set() for i in range(n): s.add(input()) print(len(s))
e22b8fd8640989a5bde9647dfc5cf28296f5ad06
Algorant/HackerRank
/Python/groups/group.py
198
3.84375
4
''' Given a string S find the occurrences of alphanumeric characters in S that have consecutive repetitions. ''' import re m = re.search(r"([a-z0-9])\1+", input()) print(m.group(1) if m else -1)
11e269dfec9b5dd946037da3766f0dcab3fec30c
Algorant/HackerRank
/Python/regex_substitution/resub.py
328
3.96875
4
''' Given a text of N lines, which contain && and || symbols, modify the symbols to be && > and and || > or. Both && and || should have a space "" on both sides. ''' import re for _ in range(int(input())): print(re.sub(r'(?<= )(\&\&|\|\|)(?= )', (lambda m: 'and' \ if m.group(1) == '&&' \ else 'or'), input()))
1a4370f022cd378a550949fc439910c195d8fb58
Algorant/HackerRank
/Python/default_arguments/default.py
1,072
3.6875
4
''' Debug the given code so that it successfully executes all provided test files. ''' # In line 28, def print_from_stream has an issue in it, the default argument # called stream=EvenStream() is only called once, and should be called every # time. Therefore we add the init line in 29 to make it do this. class EvenStream(object): def __init__(self): self.current = 0 def get_next(self): to_return = self.current self.current += 2 return to_return class OddStream(object): def __init__(self): self.current = 1 def get_next(self): to_return = self.current self.current += 2 return to_return def print_from_stream(n, stream=EvenStream()): stream.__init__() #alternatively can do if statement here for stream=None for _ in range(n): print(stream.get_next()) queries = int(input()) for _ in range(queries): stream_name, n = input().split() n = int(n) if stream_name == "even": print_from_stream(n) else: print_from_stream(n, OddStream())
91df05bb5905d70cc260c414ec0f4ba2bcaf3d88
Algorant/HackerRank
/30_days_of_code/d25_running_time_and_complexity/running_time.py
1,020
4.1875
4
''' Given list of integers of length T, separated by /n, check if that number is prime and return "Prime" or "Not Prime" for that integer. ''' # This was first attempt. Naive approach that works but fails 2 test cases # due to timeout! (Too slow) # def ptest(T): # # Make sure greater than 1 # if T > 1: # # Check if its even or has any other factors # for i in range(2, T): # if (T % i) == 0: # print("Not Prime") # break # can end if it finds any # else: # print("Prime") # no factors other than 1 and self # # else: # print("Not Prime") # any other case not prime # # # ptest(31) # ptest(12) # ptest(33) # Attempt 2 def prime(num): if num == 1: return False else: return all((num % r) for r in range(2, round(num ** 0.5) + 1)) T = int(input()) for i in range(1, T+1): num = int(input()) if prime(num)==True: print("Not prime") else: print("Prime")
c4af13b7fe312442dff6566b0f57e102a66f5f97
Algorant/HackerRank
/Python/zipped/zipped.py
239
3.75
4
''' Given grades for N students in X subjects, find the average scores of each student. ''' x, y = map(int, input().split()) scores = [map(float, input().split()) for _ in range(y)] [print(sum(student) / y) for student in zip(*scores)]
8fd0b127421d3c4627f55dcab5b4a0db3ced41bb
Algorant/HackerRank
/Python/swap_case/swap.py
113
3.921875
4
# return the swap case for a given input s = str(input()) def swap(s): return s.swapcase() print(swap(s))
66be396f989fb7be287af6978ec2f7cbe638df13
Algorant/HackerRank
/30_days_of_code/d08_dictionaries/dictionaries.py
510
3.765625
4
if __name__ == '__main__': phone_book = {} n = int(input()) # Populate phone book dict for _ in range( n ): name, phone_number = input().split(' ') phone_book[name] = int(phone_number) # Use try/except to query dict for values for _ in range(n): try: lookup_name = input() if lookup_name in phone_book: print('{}={}'.format(lookup_name, phone_book[lookup_name])) else: print("Not found") except EOFError: break
996bb5aa753930626a1a6a45d930437dd015c850
Algorant/HackerRank
/Python/findall_finditer/find.py
482
4.21875
4
''' Given a string S, consisting of alphanumeric characters, spaces, and symbols, find all the substrings of S that contain 2 or more vowels. The substrings should lie between 2 consonants and should contain vowels only. ''' import re vowels = 'aeiou' consonants = 'bcdfghjklmnpqrstvwxyz' regex = '(?<=[' + consonants + '])([' + vowels + ']{2,})[' + consonants + ']' match = re.findall(regex, input(), re.IGNORECASE) if match: print(*match, sep='\n') else: print('-1')
aeee95faea31ee7bf131aca23c338051773e6587
Algorant/HackerRank
/Python/find_the_score/find_score.py
591
3.875
4
''' Given an xml file of length N, find the score of the file, which is adding up all the tags and attributes in the file. ''' import xml.etree.ElementTree as etree tree = etree.ElementTree(etree.fromstring(xml)) # xml = ''.join(input() for _ in xrange(input())) def get_attr_number(node): return sum(len(child.attrib) for child in node.iter()) # This code is given in problem: # if __name__ == '__main__': # sys.stdin.readline() # xml = sys.stdin.read() # tree = etree.ElementTree(etree.fromstring(xml)) # root = tree.getroot() # print(get_attr_number(root))
48329f8e8f38992d5facada2ee70b92d13d76dc6
simonxu14/LeetCode_Simon
/103.Binary Tree Zigzag Level Order Traversal/Solution.py
1,170
3.75
4
__author__ = 'Simon' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if root is None: return [] stack1 = [] stack2 = [] result = [] current = [] stack1.append(root) current.append(root.val) result.append(current[:]) while stack1: while stack1: node = stack1.pop(0) if node.left: stack2.append(node.left) if node.right: stack2.append(node.right) if len(stack2) != 0: current = [] for i in range(len(stack2)): current.append(stack2[i].val) result.append(current[:]) stack1 = stack2 stack2 = [] for i in range(len(result)): if i%2 == 1: result[i].reverse() return result
c60aea537e0f4df6b46d54ece8e3b7e90cf93efc
simonxu14/LeetCode_Simon
/49.Group Anagrams/Solution.py
1,207
3.5625
4
__author__ = 'Simon' class Solution(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ if len(strs) == 0 or strs[0] == "": return [] dict = {} result = [] for item in strs: item_ele = tuple(sorted(item)) if item_ele not in dict.keys(): dict[item_ele] = [item] else: dict[item_ele].append(item) for key in dict: item_array = dict[key] result.append(item_array) return result # class Solution(object): # def groupAnagrams(self, strs): # """ # :type strs: List[str] # :rtype: List[List[str]] # """ # mydict = dict() # results = [] # for item in strs: # item_ele = tuple(sorted(item)) # if not item_ele in mydict: # mydict[item_ele] = [item] # else: # mydict[item_ele].append(item) # for key in mydict: # item_array = mydict[key] # item_array.sort() # results.append(item_array) # return results
4cfb935205c712ecfc202390bf1e746855401275
simonxu14/LeetCode_Simon
/36.Valid Sudoku/Solution.py
2,102
3.734375
4
__author__ = 'Simon' class Solution(object): def check(self, board, start, choice): numbers = [] for i in range (0, len(board)): num = board[start][i] if (choice== 'col'): num = board[i][start] if num != '.': num = int(num) if num < 0 or num > 9 or num in numbers: return False numbers.append(num) return True def check_row(self, board, start): return self.check(board, start, 'row') def check_col(self, board, start): return self.check(board, start, 'col') def check_square(self, board, row, col): numbers = [] for i in range(row, row+3): for j in range (col, col+3): print i, j num = board[i][j] if num != '.': num = int(num) if num < 0 or num > 9 or num in numbers: return False numbers.append(num) return True def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ result = True for i in range (0, 9): result = result and self.check_row(board, i) result = result and self.check_col(board, i) if i % 3 == 0: for j in range (0, 9): if j % 3 == 0: result = result and self.check_square(board, i, j) return result # def isValidSudoku(self, board): # """ # :type board: List[List[str]] # :rtype: bool # """ # big = set() # for i in xrange(0,9): # for j in xrange(0,9): # if board[i][j]!='.': # cur = board[i][j] # if (i,cur) in big or (cur,j) in big or (i/3,j/3,cur) in big: # return False # big.add((i,cur)) # big.add((cur,j)) # big.add((i/3,j/3,cur)) # return True
ced8ce5046c20c5aabf47fd1731b4b0a86c1debe
simonxu14/LeetCode_Simon
/125.Valid Palindrome/Solution.py
962
3.609375
4
__author__ = 'Simon' class Solution(object): # def isPalindrome(self, s): # """ # :type s: str # :rtype: bool # """ # s.lower() # i = 0 # j = len(s) - 1 # while i < j: # while not s[i].isalpha(): # i += 1 # if i >= j: # return True # while not s[j].isalpha(): # j -= 1 # if i >= j: # return True # if s[i] != s[j]: # return False # return True def isPalindrome(self, s): if not s: return True s=s.lower() s1=[] for x in range(len(s)): if s[x].isalpha() or s[x].isdigit(): s1.append(s[x]) #Get s1 with letters and digits only for i in range(int(len(s1)/2)): if not s1[i]==s1[-i-1]: return False return True
a14935149e0a38f89aa39780a60bdcbc6a345f46
simonxu14/LeetCode_Simon
/82.Remove Duplicates from Sorted List II/Solution.py
2,198
3.8125
4
__author__ = 'Simon' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ # if head is None: # return head # if head.next is None: # return head # node = head # pre = None # next = head.next # current = node.val # while next: # if next.val == current: # if node == head: # head = next.next # pre = None # if head is None: # return head # else: # next = head.next # else: # pre.next = next.next # node = next.next # if node is None: # return head # else: # next = node.next # else: # pre = node # node = next # next = next.next # current = node.val # return head # if head is None: return head if head.next is None: return head node = head pre = None while node.next: if node.next.val == node.val: while node.next.val == node.val: node = node.next if node.next is None: break if node.next is None: if pre == None: return None else: pre.next = None return head else: if pre == None: head = node.next node = node.next else: pre.next = node.next node = node.next else: pre = node node = node.next return head
ebd6910d093a12719e8ade1d893f44d11ba867f6
simonxu14/LeetCode_Simon
/78.Subsets/Solution.py
512
3.578125
4
__author__ = 'Simon' class Solution(object): def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] res.append([]) nums.sort() self.dfs(nums, 0, [], res) return res def dfs(self, nums, index, path, res): for i in range(index, len(nums)): res.append(path+[nums[i]]) # print path+[nums[i]] # print index self.dfs(nums, i+1, path+[nums[i]], res)
9a7552099fc493844fc68edd8b43535b050026cb
kigaita/EulersSolutions
/prob25.py
524
3.890625
4
#! usr/bin/python #Digit Counter def digits(n): n=[int(i) for i in str(n)] if len(n)==1000: return True return False #Fibonnaci Generator def fib(): a, b = 0, 1 while 1: yield a a, b = b, a + b def main(): stop = False a = fib() i=-1 #Stop when N is a length of 1000 while stop!=True: i+=1 #Use I to track where in the sequence we are n=a.next() stop=digits(n) print(i) if __name__ == '__main__': main()
8fe50d117de92d388d4d46f2e173553de3b0a4f5
cvnguye2/python_examples
/prime.py
1,144
3.734375
4
#find prime numbers from start to end def Primes(start,end): prime=[] for i in range(start, end+1): for j in range(1,(i+1)): if(i%j==0 and i!=j and j!=1): break elif (i%j==0 and i==j): prime.append(i) else: continue return prime #find prime pairs that are seperated by cup def Primes_sets(start,end,cup): primeset=[] prime=Primes(start,end) for i in range(len(prime)): if(i>(len(prime)-1)): break elif (prime[i]-prime[i-1]==cup): primeset.append([prime[i-1],prime[i]]) else: continue return primeset #find the first n Primes def NumOfPrimes(n): wprime=[] i=0 k=0 while k<n: i+=1 for j in range (1,(i+1)): if(i%j==0 and i!=j and j!=1): break elif(i%j==0 and i==j): wprime.append(i) k+=1 break else: continue return wprime #find the prime numbers of n and it's multiples of those primes def Prime_B(n): temp=[1] multi=[] i=2 while i<=n: if(n%i==0): n/=i if(max(temp)!=i): temp.append(i) else: multi.append(i) else: i+=1 return temp, multi print(Prime_B(400)) print(NumOfPrimes(10)) print(Primes_sets(0,37,2)) print(Primes(10,37))
73e35bdbc746c7e13c94465536823b4d21bfbac5
Delfinoln/Python_Study
/100DaysOfCode-TheCompletePythonProBootcampFor2021-Course/Day25-Project/US_States_Game_Project/main.py
1,798
4.03125
4
import turtle import pandas as pd exists = False screen = turtle.Screen() screen.title("U.S. States Game") # Setting up screen screen.setup(width=730, height=510) screen.tracer(0) # Adding image to the screen image = "blank_states_img.gif" screen.addshape(image) turtle.shape(image) screen.update() # Reading csv file with pandas data_frame = pd.read_csv("50_states.csv") # Creating a writer Turtle writer = turtle.Turtle() writer.penup() writer.hideturtle() game_is_on = True STATES = 50 correct_states = [] while game_is_on and len(correct_states) < 50: # Asking user answer_state = screen.textinput(title=f"{len(correct_states)}/{STATES} States Correct", prompt="What's another state's name?") answer_state = answer_state.title() # Check if user's answer exists in the data frame if answer_state in data_frame["state"].to_list(): exists = True if answer_state == "Exit": break # Write on screen the name of the state if exists and answer_state not in correct_states: correct_states.append(answer_state) state_x = data_frame[data_frame["state"] == answer_state]["x"] state_y = data_frame[data_frame["state"] == answer_state]["y"] writer.goto(int(state_x), int(state_y)) writer.write(answer_state, align="center", font=("Courier", 8, "normal")) exists = False if len(correct_states) == 50: print("You got all 50 states!") else: # Check what stats were missing states_missing = [] for state in data_frame["state"].to_list(): if state not in correct_states: states_missing.append(state) # Create a csv file to study later states_missing_csv = pd.DataFrame(states_missing) states_missing_csv.to_csv("states_to_learn.csv") screen.exitonclick()
9acd75e8fad98aac14db19683ee8f65a978daf3f
Delfinoln/Python_Study
/100DaysOfCode-TheCompletePythonProBootcampFor2021-Course/Day23-Project/The-Turtle-Crossing-Game/main.py
1,074
3.671875
4
import turtle import character import car import time import scoreboard # Creating a screen object screen = turtle.Screen() # Setting up screen atributes screen.setup(width=600, height=600) screen.tracer(0) screen.title("Turtle Crossing") # Creating a Character player = character.Character() # Creating a screen listener screen.listen() screen.onkey(player.move, "Up") screen.onkey(player.move_down, "Down") # Creating scoreboard objet scoreboard = scoreboard.Scoreboard() is_game_on = True counter = 0 cars = car.Car() cars.cars_list.append(cars) while is_game_on: screen.update() cars.move() time.sleep(cars.pace) counter += 1 if counter == 6: counter = 0 (cars.cars_list.append(car.Car())) if player.ycor() == 280: cars.pace *= 0.8 scoreboard.level += 1 scoreboard.rewrite() player.reset() for one_car in cars.cars_list: if player.distance(one_car) < 20: is_game_on = False scoreboard.game_over() # In order to not close the window screen.exitonclick()
0bd110e04ddf20c86d0c252368798a111568913c
Opimenov/Tetris
/shapes.py
2,725
3.5625
4
from graphics import Point from shape import Shape class I_shape(Shape): def __init__(self, center): coords = [Point(center.x - 2, center.y), Point(center.x - 1, center.y), Point(center.x, center.y), Point(center.x + 1, center.y)] Shape.__init__(self, coords, 'blue') self.shift_rotation_dir = True self.center_block = self.blocks[2] class J_shape(Shape): def __init__(self, center): coords = [Point(center.x - 1, center.y), Point(center.x, center.y), Point(center.x + 1, center.y), Point(center.x + 1, center.y + 1)] Shape.__init__(self, coords, 'orange') self.center_block = self.blocks[1] class L_shape(Shape): def __init__(self, center): coords = [Point(center.x - 1, center.y), Point(center.x, center.y), Point(center.x + 1, center.y), Point(center.x - 1, center.y + 1)] Shape.__init__(self, coords, 'cyan') self.center_block = self.blocks[1] class O_shape(Shape): def __init__(self, center): coords = [Point(center.x, center.y), Point(center.x - 1, center.y), Point(center.x, center.y + 1), Point(center.x - 1, center.y + 1)] Shape.__init__(self, coords, 'red') self.center_block = self.blocks[0] def rotate(self, board): # Override Shape's rotate method since O_Shape does not rotate return class S_shape(Shape): def __init__(self, center): coords = [Point(center.x, center.y), Point(center.x, center.y + 1), Point(center.x + 1, center.y), Point(center.x - 1, center.y + 1)] Shape.__init__(self, coords, 'green') self.center_block = self.blocks[0] self.shift_rotation_dir = True self.rotation_dir = -1 class T_shape(Shape): def __init__(self, center): coords = [Point(center.x - 1, center.y), Point(center.x, center.y), Point(center.x + 1, center.y), Point(center.x, center.y + 1)] Shape.__init__(self, coords, 'yellow') self.center_block = self.blocks[1] class Z_shape(Shape): def __init__(self, center): coords = [Point(center.x - 1, center.y), Point(center.x, center.y), Point(center.x, center.y + 1), Point(center.x + 1, center.y + 1)] Shape.__init__(self, coords, 'magenta') self.center_block = self.blocks[1] self.shift_rotation_dir = True self.rotation_dir = -1
48fc9819df0e53db026d6c3d4032a114c52eba0c
xyp8023/LeetCode_Python
/786_Repeated_String_Match.py
915
3.53125
4
import math class Solution: def repeatedStringMatch(self, A: str, B: str) -> int: if B in A: return 1 x = (len(B) // len(A)) x = math.ceil(len(B) / len(A)) A_new = A * x if B in A_new: return x else: if B in A_new + A: return x + 1 return -1 def re(self, A, B): if B in A: return 1 if (set(B) - set(A))!=set(): return -1 A_list = [] for j in range(1, len(A)+len(B)): A_list.append(A*j) for item in A_list: if B in item: return A_list.index(item)+1 return -1 # A="aaaaaaaaaaaaaaaaaaaaaab" # B="ba" # res = Solution().repeatedStringMatch(A, B) # res1 = Solution().re(A, B) # # print(res) # print(res1) A = 'abcd' B='cdabcdab' res1 = Solution().repeatedStringMatch(A, B) print(res1)
e1857ba1bca8d77225879626030c0bd424645de2
xyp8023/LeetCode_Python
/461_HammingDistance.py
2,657
3.640625
4
# class Solution: # def hammingDistance(self, x, y): # """ # :type x: int # :type y: int # :rtype: int # """ # x_binary = bin(x).replace('0b','') # y_binary = bin(y).replace('0b', '') # x_len = len(x_binary) # y_len = len(y_binary) # # res = 0 # max_len = max(x_len, y_len) # if x_len==y_len: # x_new = x_binary # y_new = y_binary # else: # # dif_len = abs(x_len - y_len) # if x_len==max_len: # x longer than y # y_new = '' # for i in range(dif_len): # y_new+='0' # for i in y_binary: # y_new+=i # x_new = x_binary # else: # y longer than x # x_new = '' # for i in range(dif_len): # x_new = x_new + '0' # for i in x_binary: # x_new = x_new + i # y_new = y_binary # for i in range(max_len): # res+=int(x_new[i])^int(y_new[i]) # return res # # other solutions # # 1. # class Solution: # def hammingDistance(self, x, y): # """ # :type x: int # :type y: int # :rtype: int # """ # x_binary = bin(x)[2:] # y_binary = bin(y)[2:] # x_len = len(x_binary) # y_len = len(y_binary) # dif_len = abs(x_len-y_len) # res=0 # # make sure x_bianry always longer # if x_len<y_len: # x_binary,y_binary = y_binary,x_binary # x_len = len(x_binary) # y_new = '' # y_new = '0' * dif_len # y_new += y_binary # for i in range(x_len): # if x_binary[i]!=y_new[i]: # res+=1 # return res # 2. class Solution: def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ x_binary = bin(x)[2:] y_binary = bin(y)[2:] x_len = len(x_binary) y_len = len(y_binary) res = 0 # make sure x_bianry always longer if x_len < y_len: x_binary, y_binary = y_binary, x_binary x_len = len(x_binary) y_len = len(y_binary) if x_len != y_len: dif_len = x_len - y_len y_new = '0' * dif_len y_binary = y_new + y_binary for i in range(x_len): if x_binary[i] != y_binary[i]: res += 1 return res x=1 y=4 sol = Solution() res = sol.hammingDistance(x, y) print(res)
38cb82c498644f5189a0520458ec5d9c03770332
ZckFreedom/Mathworks
/Finite_fields&Signal_design/fundamental_tools/same_data_structures_methods.py
11,003
3.65625
4
class Assoc: def __init__(self, key, value): self.key = key self.value = value # def __lt__(self, other): # 有时可能会需要关键码的排序 # return self.key < other.key # def __le__(self, other): # return self.key < other.key or self.key == other.key def __str__(self): return 'Assoc({0},{1})'.format(self.key, self.value) class DictList: def __init__(self): self._elems = [] def is_empty(self): return not self._elems def num(self): return len(self._elems) def search(self, key1): n = self.num() for i in range(n): if self._elems[i].key == key1: return self._elems[i].value return False def insert(self, key1, value1): # n = self.num() # for i in range(n): # if self._elems[i].key == key1: # self._elems[i].value = value1 # return self._elems.append(Assoc(key1, value1)) def delete(self, key1): n = self.num() for i in range(n): if self._elems[i].key == key1: self._elems.pop(i) return def value(self): n = self.num() for i in range(n): yield self._elems[i].value def entries(self): n = self.num() for i in range(n): yield self._elems[i].key, self._elems[i].value def change(self, key1, vaule1): n = self.num() for i in range(n): if self._elems[i].key == key1: self._elems[i].value = vaule1 class StackUnderflow(ValueError): pass class SStack: """ 用顺序表实现栈,在python中因为有list的定义,所以可以直接使用list来实现栈 由于python中list采用动态顺序表技术,所以栈采用的也是动态顺序表技术 栈是list的一个真子集,对于list来说正常的操作对于栈都是非法的,所以不能用list直接表示栈 但是可以将栈看做一个类,这个类具有一个list属性,这样可以对这个属性进行限制和定义比较严格的栈的操作 这种看法即用list函数来实现栈 """ def __init__(self): self._elems = [] def is_empty(self): # 判空 return self._elems == [] def top(self): # 访问最上面的数据,也就是最后进入的数据 if len(self._elems) == 0: raise StackUnderflow('in SStack top{}') return self._elems[-1] def push(self, elem): # 存入数据,存入在结构的最上面 self._elems.append(elem) def pop(self): # 弹出数据,根据后进先出,弹出最后进入的数据 if len(self._elems) == 0: raise StackUnderflow('in SStack pop{}') return self._elems.pop() class LNode: # 使用链表就要定义结点 def __init__(self, elem, next_=None): self._elem = elem self._next = next_ class LStack: """ 使用链表来实现栈类,因为单链表对表头的操作最简单,所以把表头看做是栈的最上面 每次存入数据,删除数据或者访问数据就可以直接对表头进行操作 这种方法是用链表实现栈 """ def __init__(self): self._top = None def is_empty(self): # 判空 return self._top is None def top(self): # 访问最上面数据 if self._top is None: raise StackUnderflow('in LStack top{}') return self._top.elem def push(self, elem): # 存入数据 self._top = LNode(elem, self._top) def pop(self): # 删除数据 if self._top is None: raise StackUnderflow('in LStack pop{}') p = self._top self._top = p.next return p.elem class QueueUnderflow(ValueError): pass class SQueue: """ 通过列表表示队列 """ def __init__(self, init_len=8): self._len = init_len self._elems = [0] * init_len self._head = 0 # 队首的索引,相关的加减法都要取模 self._num = 0 def is_empty(self): return self._num == 0 def peek(self): if self._num == 0: raise QueueUnderflow return self._elems[self._head] def dequeue(self): if self._num == 0: raise QueueUnderflow e = self._elems[self._head] # 不需要更改self._elems[self._head]的值是因为这个位置储存区直接可以被无视 self._elems[self._head] = 0 self._head = (self._head + 1) % self._len self._num -= 1 return e def enqueue(self, e): if self._num == self._len: self.__extend() self._elems[(self._head + self._num) % self._len] = e # 因为采用的是循环列表的形式 self._num += 1 def __extend(self): # 进行存储空间的扩张 old_len = self._len self._len *= 2 # 直接将长度扩大二倍 new_elems = [0] * self._len # 新建一个列表,然后通过列表复制的方式进行扩建 for i in range(old_len): # 扩建之后self._head从零开始记值 new_elems[i] = self._elems[(self._head + i) % old_len] self._elems = new_elems self._head = 0 def dequeue_2(self): if self._num == 0: raise QueueUnderflow e = self._elems[(self._head + self._num - 1) % self._len] self._elems[(self._head + self._num - 1) % self._len] = 0 self._num -= 1 return e def enqueue_2(self, e): if self._num == self._len: self.__extend() self._elems[(self._head - 1) % self._len] = e self._head = (self._head - 1) % self._len self._num += 1 ''' 优先队列,与栈和队列作用一样,是一个缓存结构,但是其中的每一个数据有具有一个优先级的值 基于对二叉树的应用,可以高效地实现这种数据结构 一般来讲,为了实现高效,在对于相同优先级的数据处理时,应当采取随机处理某一个数据 可以基于5.1中二叉树基于线性表的实现来实现优先队列,也可以用链表,更方便 ''' class PrioQueueError(ValueError): pass class PrioQue: def __init__(self, elist=None): if elist is None: elist = [] self._elems = list(elist) self._elems.sort(reverse=True) # 用列表的排序方法进行排序,基于小数优先级高,也可反过来 def enqueue(self, e): # 基于优先级相同的数据先进先出,可以更改小于等于使其变为后进先出 i = len(self._elems) - 1 while i >= 0: if self._elems[i] <= e: # 因为是反序,所以要找到最小的比e大的数 i -= 1 else: break self._elems.insert(i + 1, e) # insert不会引发错误,如果i+1大于元列表的最大索引则等于进行append def is_empty(self): return not self._elems def peek(self): # 访问优先级最高的一组数据中最先进入的那个数据 if self.is_empty(): raise PrioQueueError return self._elems[-1] def dequeue(self): if self.is_empty(): raise PrioQueueError return self._elems.pop() ''' 堆:采用树形结构实现优先队列的一种有效技术,堆就是每个结点都存储数据的完全二叉树 堆序:每个结点的数据优先级小于等于其父结点,大于等于其子结点(每个结点只与其父结点和子结点比较) 由于完全二叉树与连续表同构,所以一般也可以用连续表实现堆 在堆上删除根元素或最后一个元素生成的结构仍是堆(一个或两个),加入新元素未必是堆(不一定满足堆序) 用堆可以优化在5.1中优先队列的插入或者删除操作,能够把O(n)时间的算法优化为O(logn)时间的算法 基于list可以实现堆 ''' class PrioQueue: def __init__(self, elist=None): if elist is None: elist = [] self._elems = list(elist) if elist: self.buildheap() # 建立一个堆 def is_empty(self): return not self._elems def peek(self): if self.is_empty(): raise PrioQueueError return self._elems[0] def enqueue(self, e): self._elems.append(None) # 加入一个空结点 self.siftup(e, len(self._elems) - 1) def siftup(self, e, last): """ 向上筛选法:在堆的最后添加一个包含e的结点,然后这个结点与其父结点比较,如果e的优先级更大,则交换位置 重复上面比较交换操作直到e不动,由堆的性质可以得到所有操作完成之后得到的仍然是一个堆 其中,因为初始的根结点在列表中的位置是0,所以求每个结点的父结点要取下整 """ i, j = last, (last - 1) // 2 # 取下整,得到其父结点的索引 while i > 0 and e < self._elems[j]: # 不需要交换,将所有下面的值调整好之后,上面直接赋e,可以省略交换的过程 self._elems[i] = self._elems[j] i, j = j, (j - 1) // 2 self._elems[i] = e def dequeue(self): # 弹出根结点 if self.is_empty(): raise PrioQueueError elems = self._elems e0 = elems[0] e = elems.pop() if len(elems) > 0: self.siftdown(e, 0, len(elems)) return e0 def siftdown(self, e, begin, end): """ 向下筛选法:指针指向某一个父结点,e与其两个子结点进行比较,让优先级最高的值的结点作为这一个父结点 如果是e,则结束,否则指针指向优先级最高的那个子结点,使其作为下一轮的父结点 这样e的比较路径总是沿着优先级最高的向下筛选 同shiftup的思路类似,在比较过程中不需要实际的交换,而是给每个元素找合适的位置,找到了之后直接赋值 """ elems, i, j = self._elems, begin, begin * 2 + 1 # 乘2加1可以保证j总是i的子结点中的左子结点 while j < end: if j + 1 < end and elems[j + 1] < elems[j]: j += 1 # elems[j+1]更小的情况,则与e比较的使命交给elems[j+1] if e < elems[j]: # 此时e是三者中最小的,这个时候已经给e找好了位置,就是i break elems[i] = elems[j] # 否则,如果e不是最小的,那么就让e往下继续比较 i, j = j, j * 2 + 1 elems[i] = e # 最后赋值 def buildheap(self): end = len(self._elems) for i in range(end // 2, -1, -1): # 到零为止 self.siftdown(self._elems[i], i, end) def another_way(self): """ 不节省空间实现优先队列排序的方法 """ a = [] while self._elems: a.append(self.dequeue()) return a class BinTNode: """ 使用递归调用结点的方式定义二叉树,先定义结点类 """ def __init__(self, dat, left=None, right=None): self.data = dat self.left = left self.right = right class BinTree: """ 真正的二叉树类 """ def __init__(self): self._root = None def is_empty(self): return self._root is None def root(self): return self._root def leftchild(self): return self._root.left def rightchild(self): return self._root.right def set_root(self, rootnode): if not isinstance(rootnode, BinTNode): raise ValueError('this root is not a BinTNode') self._root = rootnode def set_left(self, leftchild): if not isinstance(leftchild, BinTNode): raise ValueError('this root is not a BinTNode') self._root.left = leftchild def set_right(self, rightchild): if not isinstance(rightchild, BinTNode): raise ValueError('this root is not a BinTNode') self._root.right = rightchild def preorder_elements(self): # 前根序生成器 t, s = self._root, SStack() while t is not None or not s.is_empty(): while t is not None: s.push(t.right) # 右子结点入栈 yield t.data t = t.left t = s.pop()
16b2508ae7b7acf90c93aacd8c76c3ba6727326b
Shurtugall/Metodos_Numericos
/T1/5.py
374
3.75
4
""" @author: Gabriel Righi @matricula: 201612819 """ #Questão 5 #duvida import math def main(): a = 7 x_ant = 0.1 for i in range(10): x = (x_ant + a/x_ant)/2 x_ant = x print("X", i+1, ":", x) erro_absoluto = math.sqrt(7.0) - x print("Erro absoluto: ", math.fabs(erro_absoluto)) main()
9c0f362c726440f6abbf2f21d442f9a56015a479
thofiqming/python_basics
/conditions.py
201
3.84375
4
# conditions value = 15 if 10 < value < 20: print("value greater than 10 and less than 20") elif value > 20: print("value greater than 20") else: print("none of the condition satisfied")
b6088f0209437e9b04158cae3be064b907dab776
samturton2/Python_fizz_buzz_task
/main.py
840
3.96875
4
# import the fizz buzz class from FizzBuzz_class import FizzBuzz # make function that requests fizz number def request_fizz(): return int(input("Please enter number for Fizz to replace\n=>")) # make function that requests buzz number def request_buzz(): return int(input("Please enter number for Buzz to replace\n=>")) # make function that loops through a list printing each number def print_list(my_list): for item in my_list: print(item) # Run main if ran from this file if __name__ == "__main__": # run functions to request fizz and buzz fizz_number = request_fizz() buzz_number = request_buzz() # create object from fizzbuzz class fizz_buzz_object = FizzBuzz(fizz_number, buzz_number) # print final output using print_list function made print_list(fizz_buzz_object.fizz_buzz_list())
fdc6657bb80dc04c9fa2709da30589be0cea2dd3
CharonAndy/scikit-fda
/examples/plot_kernel_smoothing.py
3,897
3.59375
4
""" Kernel Smoothing ================ This example uses different kernel smoothing methods over the phoneme data set and shows how cross validations scores vary over a range of different parameters used in the smoothing methods. It also show examples of undersmoothing and oversmoothing. """ # Author: Miguel Carbajo Berrocal # License: MIT import skfda import skfda.preprocessing.smoothing.kernel_smoothers as ks import skfda.preprocessing.smoothing.validation as val import matplotlib.pylab as plt import numpy as np ############################################################################### # # For this example, we will use the # :func:`phoneme <skfda.datasets.fetch_phoneme>` dataset. This dataset # contains the log-periodograms of several phoneme pronunciations. The phoneme # curves are very irregular and noisy, so we usually will want to smooth them # as a preprocessing step. # # As an example, we will smooth the first 300 curves only. In the following # plot, the first five curves are shown. dataset = skfda.datasets.fetch_phoneme() fd = dataset['data'][:300] fd[0:5].plot() ############################################################################### # Here we show the general cross validation scores for different values of the # parameters given to the different smoothing methods. param_values = np.linspace(start=2, stop=25, num=24) # Local linear regression kernel smoothing. llr = val.minimise(fd, param_values, smoothing_method=ks.local_linear_regression) # Nadaraya-Watson kernel smoothing. nw = skfda.preprocessing.smoothing.validation.minimise( fd, param_values, smoothing_method=ks.nw) # K-nearest neighbours kernel smoothing. knn = skfda.preprocessing.smoothing.validation.minimise( fd, param_values, smoothing_method=ks.knn) plt.plot(param_values, knn['scores']) plt.plot(param_values, llr['scores']) plt.plot(param_values, nw['scores']) ax = plt.gca() ax.set_xlabel('Smoothing method parameter') ax.set_ylabel('GCV score') ax.set_title('Scores through GCV for different smoothing methods') ax.legend(['k-nearest neighbours', 'local linear regression', 'Nadaraya-Watson'], title='Smoothing method') ############################################################################### # We can plot the smoothed curves corresponding to the 11th element of the data # set (this is a random choice) for the three different smoothing methods. fd[10].plot() knn['fdatagrid'][10].plot() llr['fdatagrid'][10].plot() nw['fdatagrid'][10].plot() ax = plt.gca() ax.legend(['original data', 'k-nearest neighbours', 'local linear regression', 'Nadaraya-Watson'], title='Smoothing method') ############################################################################### # We can compare the curve before and after the smoothing. # Not smoothed fd[10].plot() # Smoothed plt.figure() fd[10].scatter(s=0.5) nw['fdatagrid'][10].plot(c='g') ############################################################################### # Now, we can see the effects of a proper smoothing. We can plot the same 5 # samples from the beginning using the Nadaraya-Watson kernel smoother with # the best choice of parameter. plt.figure(4) nw['fdatagrid'][0:5].plot() ############################################################################### # We can also appreciate the effects of undersmoothing and oversmoothing in # the following plots. fd_us = skfda.FDataGrid( ks.nw(fd.sample_points, h=2).dot(fd.data_matrix[10, ..., 0]), fd.sample_points, fd.sample_range, fd.dataset_label, fd.axes_labels) fd_os = skfda.FDataGrid( ks.nw(fd.sample_points, h=15).dot(fd.data_matrix[10, ..., 0]), fd.sample_points, fd.sample_range, fd.dataset_label, fd.axes_labels) # Under-smoothed fd[10].scatter(s=0.5) fd_us.plot(c='sandybrown') # Over-smoothed plt.figure() fd[10].scatter(s=0.5) fd_os.plot(c='r')
4015375a4cc30b561b61b97ea0bd6a317ed0b8b4
slougn/PythonWF
/PythonCrashCourse/ch4/ex4.py
346
3.796875
4
alien_color = 'green' if alien_color=='green': print('player get 5 points') if alien_color!='red': print('not pass!') age = 30 if age < 2: print('婴儿') elif age < 4: print("蹒跚学步") elif age <13: print('儿童') elif age < 20: print('青少年') elif age <65: print('成年人') else: print('老年人')
64fbdf74d3c3c31e36ca9886c223192d6d18eb69
slougn/PythonWF
/PythonCrashCourse/ch11/test_cities.py
325
3.5
4
import unittest from city_functions import city_functions # print(city_functions('handan','china')) class CityTestCase(unittest.TestCase): """测试city_function的功能""" def test_cities(self): formatted = city_functions('handan','china') self.assertEqual(formatted,'Handan China') unittest.main
c9b16d36134a1ffc3a7e2460c384b6b9c48d679d
slougn/PythonWF
/PythonCrashCourse/ch7/ex3.py
667
3.8125
4
bread_order = ['白面馒头','麦馒头','南瓜馒头','叉烧包','蛋黄包'] finished_bread = [] while bread_order: bread = bread_order.pop() print(bread+'已经做好了!') finished_bread.append(bread) print('做好的订单有:') for bread in finished_bread: print(bread) bread_order = ['白面馒头','五香牛肉包子','麦馒头','五香牛肉包子','南瓜馒头','叉烧包','五香牛肉包子','蛋黄包'] print(bread_order) print('五香牛肉包子已经售罄!!') while '五香牛肉包子' in bread_order: bread_order.remove('五香牛肉包子') print('确认订单:') for bread in bread_order: print(bread)
f28f9d5304d565e29fb27f7f5715f7e9a7940abe
rbalaji07/balaji
/bala23.py
115
3.734375
4
abc=int(input()) for i in range(2,abc): if(abc%i==0): print("no") break else: print("yes")
982a6225a1aab61116069568225265bc27d73923
cemathey/aoc_2020
/day21/day21.py
3,469
3.765625
4
import sys from typing import NamedTuple, Tuple, List, Dict, Set class Food(NamedTuple): ingredients: Tuple[str, ...] allergens: Tuple[str, ...] def parse_food(line: str) -> Food: """Return a valid Food from the given line.""" left, right = line.strip().split(" (contains ") foods: List[str] = [food for food in left.split(" ")] # Slice off everything except the ending parentheses allergens: List[str] = [allergen for allergen in right[:-1].split(", ")] return Food(tuple(foods), tuple(allergens)) def collect_foods_allergen(foods: Tuple[Food, ...], allergen: str) -> Tuple[Food, ...]: """Return a tuple of all foods that contain the given allergen.""" return tuple(food for food in foods if allergen in food.allergens) def collect_foods_ingredient( foods: Tuple[Food, ...], ingredient: str ) -> Tuple[Food, ...]: """Return a tuple of all foods that contain the given ingredient.""" return tuple(food for food in foods if ingredient in food.ingredients) def collect_unknown_ingredients( decoded_allergens: Dict[str, str], foods: Tuple[Food, ...], allergen: str ): """Collect all of the unknown ingredients for each food that contains the given allergen.""" unique_ingredients: List[List[str]] = [] for food in foods: filtered_ingredients: List[str] = [] for ingredient in food.ingredients: if ( allergen in food.allergens and ingredient not in decoded_allergens.values() ): filtered_ingredients.append(ingredient) # No empty lists if filtered_ingredients: unique_ingredients.append(filtered_ingredients) return unique_ingredients def decode_allergens(foods: Tuple[Food, ...]) -> Dict[str, str]: """Populate our decoded allergens by searching for foods that contain an allergen and exactly 1 unknown ingredient.""" allergens: Set[str] = set(allergen for food in foods for allergen in food.allergens) decoded_allergens: Dict[str, str] = {} # To decode our allergens, iterate through the allergens until we can find a set intersection of ingredients for that allergen that has exactly one commonality while len(decoded_allergens) < len(allergens): for allergen in allergens: unknown_ingredients: List[List[str]] = collect_unknown_ingredients( decoded_allergens, foods, allergen ) # Can't pass a generator expression, make a tuple of sets and then explode it intersecting_ingredients = set.intersection( *tuple(set(ingredients) for ingredients in unknown_ingredients) ) if len(intersecting_ingredients) == 1: decoded_allergens[allergen] = intersecting_ingredients.pop() return decoded_allergens if __name__ == "__main__": filename = sys.argv[1] contents = open(filename).readlines() foods: Tuple[Food, ...] = tuple(parse_food(line) for line in contents) decoded_allergens: Dict[str, str] = decode_allergens(foods) answer: int = sum( 1 for food in foods for ingredient in food.ingredients if ingredient not in decoded_allergens.values() ) dangerous_ingredients: str = ",".join( v for k, v in sorted(decoded_allergens.items()) ) print(f"Part 1: answer= {answer}") print(f"Part 2: dangerous_ingredients= {dangerous_ingredients}")