blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
1b601202676058620ac2074468c4130d2260c80d
nato4ka1987/lesson2
/4.py
540
4.03125
4
''' Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки. Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове. ''' my_str = input("Enter string: ") a = my_str.split(' ') for i, el in enumerate(a, 1): if len(el) > 10: el = el[0:10] print(f"{i}. - {el}")
9161708731404df8a8d2e943b97efefb3d4a72db
benjaminwilson/word2vec-norm-experiments
/modify_corpus_word_freq_experiment.py
1,141
3.5
4
""" Modifies an input text for the word frequency experiment according to the parameters defined in parameters.py Reads from stdin, writes to stdout. Requires sufficient diskspace to write out the modified text at intermediate steps. """ import os import sys from parameters import * from functions import * wf_experiment_words = read_words(sys.argv[1]) counts = read_word_counts(sys.argv[2]) total_words = sum(counts.values()) # intersperse the meaningless token throughout the corpus intermediate_file = 'delete.me.word_freq_experiment' with open(intermediate_file, 'w') as f_out: intersperse_words({meaningless_token: meaningless_token_frequency}, sys.stdin, f_out) wf_experiment_words.append(meaningless_token) # perform the replacement procedure word_samplers = {} distn = lambda i: truncated_geometric_proba(word_freq_experiment_ratio, i, word_freq_experiment_power_max) for word in wf_experiment_words: word_samplers[word] = distribution_to_sampling_function(word, distn, word_freq_experiment_power_max) with open(intermediate_file) as f_in: replace_words(word_samplers, f_in, sys.stdout) os.remove(intermediate_file)
e4e58672f121baae0fbe3f9ba7fac94d072073cc
ObukhovVladislav/python-adv
/homeworks/210125/tast_1_example_4.py
1,042
4.0625
4
# def is_palindrome(num): # if num // 10 == 0: # return False # temp = num # reversed_num = 0 # # while temp != 0: # reversed_num = reversed_num * 10 + temp % 10 # temp = temp // 10 # # if num == reversed_num: # return True # else: # return False # def infinite_palindromes(): # num = 0 # while True: # if is_palindrome(num): # i = (yield num) # if i is not None: # num = i # num += 1 # pal_gen = infinite_palindromes() # for i in pal_gen: # digits = len(str(i)) # pal_gen.send(10 ** (digits)) # pal_gen = infinite_palindromes() # for i in pal_gen: # print(i) # digits = len(str(i)) # if digits == 5: # pal_gen.throw(ValueError("We don't like large palindromes")) # pal_gen.send(10 ** (digits)) # pal_gen = infinite_palindromes() # for i in pal_gen: # print(i) # digits = len(str(i)) # if digits == 5: # pal_gen.close() # pal_gen.send(10 ** (digits))
95413238babbc337a678c4ec2267e7f23e7547ba
jaiswalIT02/pythonprograms
/Chapter-3 Loop/untitled0.py
261
3.734375
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 3 14:21:13 2020 1,-2,3,-4.... 7@author: Tarun Jaiswal """ n=int(input("Enter the no=")) x=range(11,1,-1) print(x) for item in x: if item % 2==0: print(n*item) else: print(item*n)
7bb24992e011787e8ab538ed3cd9a133367fa1a6
jaiswalIT02/pythonprograms
/GUI Applications/calculator2.py
875
3.515625
4
from tkinter import * root=Tk() root.geometry("500x500") root.resizable(0,0) x=IntVar() y=IntVar() z=IntVar() e1=Entry(root,font=("Arial",25),textvariable=x) e1.pack() e2=Entry(root,font=("Arial",25),textvariable=y) e2.pack() # Sum of two integer def show(op): a=x.get() b=y.get() if(op==1): c=a+b z.set(c) if(op==2): c=a-b z.set(c) if(op==3): c=a*b z.set(c) if(op==4): c=a/b z.set(c) b1=Button(root,text="Sum",font=("Arial",25),command=lambda:show(1)) b1.pack() b2=Button(root,text="Sub",font=("Arial",25),command=lambda:show(2)) b2.pack() b3=Button(root,text="Multiply",font=("Arial",25),command=lambda:show(3)) b3.pack() b4=Button(root,text="Div",font=("Arial",25),command=lambda:show(4)) b4.pack() e3=Entry(root,font=("Arial",25),textvariable=z) e3.pack() root.mainloop()
8213167d8b5da70eea22723295f51802b2bb85e5
jaiswalIT02/pythonprograms
/Preparation/leftrotate.py
482
3.921875
4
def leftrotate(str): l=list(str) n=len(l) t=l[n-1] for i in range(n-1,0,-1): l[i]=l[i-1] l[0]=t result="".join(l) return result str="TIGER" str=leftrotate(str) print(str) # left rotate def leftrotate(str): l=list(str) n=len(l) t=l[n-1] for i in range(n-1,0,-1): l[i]=l[i-1] l[0]=t result="".join(l) return result str="ABC" print("original word=",str) str=leftrotate(str) print("rotate word=",str)
e2dbfd38a74c82a59c3600939f61ecd1f7bd683e
jaiswalIT02/pythonprograms
/Chapter-3 Loop/Series_Pattern/fibbonacy no.py
164
3.765625
4
n=int(input("N=")) a=0 b=1 sum=0 count=1 print("Fibbonaci series=",end=" ") while (count<=n): print(sum,end=" ") count+=1 a=b b=sum sum=a+b
aaff1f7f2e02e1fba60af4e0f426762f07ad211b
jaiswalIT02/pythonprograms
/Chapter-5 Functions/c_to_f function.py
125
3.6875
4
def c_to_f(c): Farhenheite=(c*9/5)+32 return Farhenheite n=int(input("Celcius=")) f=c_to_f(n) print(f,"'F")
3e0b50298a6ec8476a4a6999431ad630d91cb9a0
jaiswalIT02/pythonprograms
/Chapter-3 Loop/oddno.py
67
3.84375
4
x=range(1,10,2) print (x) for item in x: print(item,end=",")
bd9bfbad1ab769c34652f888c40cf20b672db239
jaiswalIT02/pythonprograms
/Preparation/+_-_n.py
206
3.546875
4
l=[-9,-86,56,-9,88] positive=[] negative=[] for i in l: if i >= 0: positive=positive+[i] if i <= 0: negative=negative+[i] print("positive list=",positive,"\nNegative List=",negative)
570e15d6d3b0868329b5bf43f91b1ae898fe30fb
jaiswalIT02/pythonprograms
/Chapter-3 Loop/prime.py
212
3.96875
4
a=int(input("A= ")) limit=a**.5 limit=int(limit) isprime=True for i in range(2,limit+1): if a % i==0: isprime=False break if isprime: print("Prime") else: print("NotPrime")
f4cb92fdc77320fe94f6aa51e466ef65d328ac93
jaiswalIT02/pythonprograms
/Preparation/noduplicate.py
168
3.53125
4
l=[1,3,4,4,1,5,5,6,7] l.sort() print(l) n=len(l) nonduplicatelist=[] prev=l[0] for i in range(1,n): curr=l[i] if curr==prev: print(curr)
68ce7ccdaa5bd03c6b9b7df2734337d61d8f243a
jaiswalIT02/pythonprograms
/Preparation/Basic_Python Program/split.py
185
3.734375
4
word="boy" print(word) reverse=[] l=list(word) for i in l: reverse=[i]+reverse reverse="".join(reverse) print(reverse) l=[1,2,3,4] print(l) r=[] for i in l: r=[i]+r print(r)
a2c5a0d70841b6f946b7a9c2ef5d0a2fb79292de
jaiswalIT02/pythonprograms
/Chapter-2 Conditional/Result.py
468
3.71875
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 2 17:09:46 2020 @author: Tarun Jaiswal """ p=int(input("Physics=")) c=int(input("Chemistry=")) m=int(input("Mathematics=")) if p<40 or c<40 or m<40: print("Result=Fail") else: print("Result=Pass") Total= p+c+m print("Total={0}".format(Total)) per=round(Total/3,2) print("Per={0}".format(per)) if per<50: print("3rd") elif per<60: print("2nd") else: print("1st")
9999ffcec508d80c632832af3106ac14e50ca149
jaiswalIT02/pythonprograms
/Preparation/positive_list.py
177
3.671875
4
#find the positive no from list l1= [10, -21, -4, -45, -66, 93] positive=[] for item in l1: if item >= 0: positive=positive+[item] print("positive list=",positive)
b7d668fbb96eb76401def55fdfcece6c435a6569
jaiswalIT02/pythonprograms
/Chapter-3 Loop/nestedpyramidloop.py
377
3.5625
4
''' n=0 r=4 for m in range(1,r+1): for gap in range(1,(r-m)+1): print(end=" ") while n!=(2*m-1): print("0",end=" ") n=n+1 n=0 print() ''' n=int(input("Enter the n=")) k=(2*n)-2 for i in range(1,n): for j in range(1,k): print(end=" ") k=k-1 for n in range(1,i+1): print("0",end=" ") print(" ")
09ceb85b032927f8481fae86450d4995f6501ce2
jaiswalIT02/pythonprograms
/Chapter-9 Regression/market.py
615
3.5
4
import pandas as pd #from sklearn import linear_model #from sklearn import tree from sklearn.tree import DecisionTreeClassifier #import pandas as pd def readexcel(excel): df=pd.read_excel(excel) return df df = readexcel("F:\\Excel2\\Market.xlsx") #print(df) x = df[['phy','chem' ]] y = df['division'] print(x) print(y) dtree = DecisionTreeClassifier() print(dtree) dtree = dtree.fit(x, y) print(dtree) result=dtree.predict([[80,75]]) print(result) result=dtree.predict([[39,45]]) print(result) """ result=dtree.predict([[250,2500]]) print(result) result=dtree.predict([[50,50]]) print(result) """
234ccf83fdd88ba514fd6290c3d2f3b4894f2eec
jaiswalIT02/pythonprograms
/Chapter-3 Loop/Triangle_Pattern/reverseabcpattern.py
156
3.5625
4
n=5 x=1 for i in range(1,n+1,1): for j in range(i,0,-1): ch=chr(ord('A')+j-1) print(ch,end="") x=x+1 print()
422097e0e6295618159d1ed54dcb6575a1975647
jaiswalIT02/pythonprograms
/Chapter-3 Loop/Forloop.py
334
4.0625
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 3 10:06:06 2020 @author: Tarun Jaiswal """ x1=range(10) print(x1) x2=range(2,10) print(x2) x3=range(2,10,3) print(x3) print("X1=",end="") for item in x1: print(item,end=",") print("X2=") for item in x2: print(item,end=",") print("X3=",end="") for item in x3: print(item,end=",")
f5d819cc1ab5956c324329169dace5be9525f826
jaiswalIT02/pythonprograms
/Chapter-2 Conditional/Many Min.py
354
3.78125
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 2 12:29:09 2020 @author: Tarun Jaiswal """ a=int(input("A= ")) b=int(input("B= ")) c=int(input("C= ")) d=int(input("D= ")) min=a variablename="b= " if b<min: variablename="b= " min=b if c<min: variablename="c= " min=c if d<min: variablename="d= " min=d print(variablename, min)
18f396d6cab808f43723e80981b90fef011898bd
jaiswalIT02/pythonprograms
/Chapter-3 Loop/series.py
125
3.703125
4
x1=range(1,11) print (x1) for item in x1: if item % 2==0: print(item) else: print(-item)
6de8cc6eff5d84304b883dd0990c56aa761ebfd3
lavindiuss/OnicaAssignment
/orm.py
3,280
3.984375
4
import sqlite3 as sq # this function create a database with all required tables and pass if its already exist """ database for : database connection database_cursor for : the cursor that controls the structure that enables traversal over the records in the database """ database = sq.connect("Books.db") database_cursor = database.cursor() def DatabaseCreation(): database_cursor.execute( "CREATE TABLE IF NOT EXISTS Book(id INTEGER PRIMARY KEY AUTOINCREMENT,title VARCHAR(200),author VARCHAR(255),description VARCHAR(500))" ) DatabaseCreation() # this function loads and return a list of db books """ books_list for : list of books that shows the output of books query """ def LoadDatabaseBooks(): try: books_list = database_cursor.execute("SELECT * FROM Book").fetchall() print("--" + str(len(books_list)) + " BOOKS LOADED INTO THE LIBRARY--\n") return books_list except Exception as e: print(str(e)) # this function list the ids and the titles of each book , and also returns a book details if it got a book id """ list_of_ids_and_titles for : list contains all ids and titles of books book_details for : tuple contains particular book data """ def UserBooksView(book_id=None,is_edit=False): list_of_ids_and_titles = database_cursor.execute( "SELECT id,title FROM Book" ).fetchall() if book_id != None: book_details = database_cursor.execute( "SELECT * FROM Book WHERE id = {}".format(book_id) ).fetchone() if not is_edit: print("ID:{}\n Title:{} \n Author:{} \n Description:{}".format(book_details[0],book_details[1],book_details[2],book_details[3])) else: return book_details else: for book in list_of_ids_and_titles: #TODO print("[{}] {}".format(book[0],book[1])) # this function takes the id of a book and partial update its attributes """ data_to_edit for : list contains all book data we can edit """ def EditBook(book_id=None, title=None, author=None, description=None): data_to_edit = [title, author, description, book_id] database_cursor.execute( "UPDATE Book SET title= ?,author= ?,description= ? WHERE id= ?", data_to_edit ) database.commit() print("--Book edited successfully--") # this function takes new book required attributes and save it to database """ data_to_save for : list of data that contains new book details """ def SaveNewBookToDatabase(title=None, author=None, description=None): data_to_save = [title, author, description] database_cursor.execute( "INSERT INTO Book(title,author,description) VALUES (?,?,?)", data_to_save ) database.commit() print("--Book saved successfully--") # this function takes keyword from user and search in database within it """ result for : attribute contains search resutl """ def SearchForBook(keyword=None): result = database_cursor.execute( "SELECT * FROM Book WHERE title like '%{}%'".format(keyword) ).fetchall() print("The following books matched your query. Enter the book ID to see more details, or <Enter> to return.") for book in result: print("[{}] {} ".format(book[0],book[1])) UserBooksView(2)
1dfb56c8d3698deca428411bc6c5774a739d5241
beccadsouza/System-Programming-and-Compiler-Construction
/ICG/infix.py
1,441
3.703125
4
infix = input("Enter infix expression : ").replace(' ','') result = input("Enter resultant variable : ") temp,string,operators = {},[],['+','-','*','/'] count,cp = 1,0 for i in range(len(infix)): if infix[i] in operators: string.append(infix[cp:i]) string.append(infix[i]) cp = i+1 string.append(infix[cp:]) for i in range(len(string)): if '[' in string[i]: temp['t'+str(count)] = ('*',string[i][string[i].index('[')+1],'8') count += 1 temp['t'+str(count)] = ('[]',string[i][:string[i].index('[')],'t'+str(count-1)) string[i] = 't'+str(count) count += 1 while len(string)!=1: temp['t'+str(count)] = (string[1],string[0],string[2]) string = string[3:] string = ['t'+str(count)] + string count += 1 print('\n','THREE ADDRESS CODES'.center(15,' ')) for k,v in temp.items(): if v[0]!='[]': print(k.center(3,' '),'='.center(3,' '),v[1].center(3,' '),v[0].center(3,' '),v[2]) else : print(k.center(3,' '),'='.center(3,' '),v[1].center(3,' '),'['+v[2]+']') print(result.center(3,' '), '='.center(3,' '), 't{0}'.format(count-1).center(3,' ')) temp[result] = ('=','t'+str(count-1),'---') print("\n","QUADRUPLE TABLE".center(20,' ')) print('op'.center(3,' '),'arg1'.center(5,' '),'arg2'.center(5,' '),'result'.center(7,' ')) for k,v in temp.items(): print(v[0].center(3,' '),v[1].center(5,' '),v[2].center(5,' '),k.center(7,' '))
d135bef0e2867c43ac4b429033e6f06d6c43d2a8
mvondracek/VUT-FIT-POVa-2018-Pedestrian-Tracking
/camera.py
1,426
3.546875
4
""" Pedestrian Tracking 2018 POVa - Computer Vision FIT - Faculty of Information Technology BUT - Brno University of Technology """ from typing import Tuple import numpy as np class Camera: def __init__(self, name: str, focal_length: float, position: Tuple[int, int, int], orientation: Tuple[int, int, int]): """ :param name: camera name used in user interface :param focal_length: focal length of camera, see `Camera.calibrate_focal_length` :param position: 3D coordinates of the camera position :param orientation: 3D vector of the camera's view orientation """ self.name = name self.focal_length = focal_length self.position = position self.orientation = orientation / np.linalg.norm(orientation) # convert to unit vector @staticmethod def calibrate_focal_length(real_distance: int, real_size: int, pixel_size: int) -> float: """ Calibrate focal length of the camera based on measurement of known object and its image representation. :param real_distance: real distance of known object from camera in millimeters :param real_size: real size size of known object in millimeters, :param pixel_size: size of known object measured in pixels in image obtained from the camera :return: focal length """ return (pixel_size * real_distance) / real_size
013ecfc959125154250731c0d5df74f2a7849548
ianmunoznunezudg/Particula
/mainclass.py
451
3.546875
4
from particula import Particula class MainClass: def __init__(self): self.__particulas = [] def agregar_inicio(self, particula: Particula): self.__particulas.insert(0, particula) def agregar_final(self, particula: Particula): self.__particulas.append(particula) def imprimir(self): for particula in self.__particulas: print(particula) print("----------------------------------")
386696a7e854e5ca447e3032dacea9e7686d0485
rbuhler/codigobasico
/Codigo_Python/e_par.py
224
3.578125
4
def e_par(valor): resultado = True resto = valor % 2 if resto > 0: resultado = False else: resultado = True return resultado if e_par( 3 ): print("E par") else: print("E Impar")
c37d12eab7ccf6dd8caa974bc22e47f98ec5cc36
shaman2527/Practicando-DNI
/js/python3/practica.py
358
3.96875
4
# n = int (input ("Enter an integer:")) # sum = n * (n + 1) / 2 # print ("The sum of the first interger from 1 to" + str (n) + " is" + str (sum) ) # print(type(sum)) #Modulo Horas de Trabajos y Paga hours = float (input("Horas de Trabajo:")) cost = float (input("Introduce lo que cobras por hora:")) pay = hours * cost print("Tu Pago" , pay)
436e5365c686922f6cc775cb441d6cb014a6103c
naveen882/mysample-programs
/last_day_quarter.py
473
3.59375
4
import datetime as dt import calendar month_quarter = [3,6,9,12] user_date = dt.datetime.strptime('2017-12-31', "%Y-%m-%d").date() if user_date.month in month_quarter: last_day = calendar.monthrange(user_date.year,user_date.month)[1] actual_date = dt.date(user_date.year,user_date.month, last_day) if user_date == actual_date: print "Matching" else: print "Select last day of the Quarter" else: print "Select last day of the Quarter"
335f5f0a83fb2c433d706e2b4640d408752508cf
naveen882/mysample-programs
/#longest_substring_in_a_given_string.py
379
3.71875
4
#longest substring in a given string def longSubstring(s): charSet = [] l=0 li = [] ss = '' for r in range(len(s)): if s[r] not in ss: ss+= s[r] else: li.append(ss) ss = '' return li ret = longSubstring('abcdbabcbb') print(ret) #print(max(ret,key=len))
1deb78c1b1af35d46bf3fef07643a25ba7a1c5f1
naveen882/mysample-programs
/classandstaticmethod.py
2,569
4.75
5
""" Suppose we have a class called Math then nobody will want to create object of class Math and then invoke methods like ceil and floor and fabs on it.( >> Math.floor(3.14)) So we make them static. One would use @classmethod when he/she would want to change the behaviour of the method based on which subclass is calling the method. remember we have a reference to the calling class in a class method. While using static you would want the behaviour to remain unchanged across subclasses http://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner/31503491#31503491 Example: """ class Hero: @staticmethod def say_hello(): print("Helllo...") @classmethod def say_class_hello(cls): if(cls.__name__=="HeroSon"): print("Hi Kido") elif(cls.__name__=="HeroDaughter"): print("Hi Princess") class HeroSon(Hero): def say_son_hello(self): print("test hello") class HeroDaughter(Hero): def say_daughter_hello(self): print("test hello daughter") testson = HeroSon() testson.say_class_hello() testson.say_hello() testdaughter = HeroDaughter() testdaughter.say_class_hello() testdaughter.say_hello() print "============================================================================" """ static methods are best used when you want to call the class functions without creating the class object """ class A(object): @staticmethod def r1(): print "In r1" print A.r1() #In r1 a=A() a.r1() #In r1 class A(object): def r1(self): print "In r1" """ print A.r1() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method r1() must be called with A instance as first argument (got nothing instead) """ print "============================================================================" class dynamo(): @staticmethod def all_return_same(): print "static method" @classmethod def all_return_different(cls): print cls if cls.__name__ == 'A': print "1" elif cls.__name__ == 'B': print "2" else: print "3" class A(dynamo): pass class B(dynamo): pass d=dynamo() d.all_return_same() d.all_return_different() dynamo().all_return_same() dynamo().all_return_different() print "======" a=A() a.all_return_same() a.all_return_different() A.all_return_same() A.all_return_different() print "======" b=B() b.all_return_same() b.all_return_different() B.all_return_same() B.all_return_different() print "============================================================================"
9bee868b22f8f2077bdcc3e13e3edb333e0a6ab4
CHemaxi/python
/001-python-core-language/005_tuples.py
3,322
3.859375
4
## >--- ## >YamlDesc: CONTENT-ARTICLE ## >Title: python tuples ## >MetaDescription: python tuples creating tuple, retrive elements, Operators example code, tutorials ## >MetaKeywords: python tuples creating tuple, retrive elements, Operators example code, tutorials tuple Methods,find,index example code, tutorials ## >Author: Hemaxi ## >ContentName: tuples ## >--- ## ># PYTHON Tuples ## >* Tuple is a immutable(Cannot be changed) group of elements. ## >* New elements CANNOT be added to a Tuple or Existing ELEMENTS CANNOT ## > be changed in a Tuple. ## >* Tuple declaration is in curly brackets t = ('data') ## >* Tuple is a compound and versatile type. ## >* Tuples can have elements (values) of mixed data types or same data type ## >* Tuple index starts from ZERO ## >* Tuples support conditional and iterative operations ## >* Tuples have built-in functions and methods similar to strings ## >* Tuples can have elements (values) of mixed data types or same data type ## >* Tuples index starts from ZERO ## >* Tuples Lists support conditional and iterative operations for reading ## >* Tuples have built-in functions and methods similar to strings ## >## Crearing, Reading and Deleting Tuples ## >* Tuples are immutable and cannot be changed ## >* We cannot change individual elements of tuple ## >* tuple1[0]=99 # This will result in an error as TUPLES are immutable ## >* we can overwrite a tuple though ## >``` # CREATE TUPLE tuple1 = (1, 2, 3, 4) tuple2 = ('A', 'b', 1, 2) # PRINT TUPLE print(tuple1) print(tuple2) tuple1 = (1, 2, 3, 4, 5) print(tuple1) # UPDATE TUPLES # Easier option for updating parts of tuple are creating # new tuples with parts of existing ones # Create a Tuple with elements 2,3,4 from tuple1 tuple3=tuple1[1:4] print(tuple3) # DELETING TUPLES del tuple3 # print(tuple3) # This will throw an error, as this TUPLE doesnt exist # TUPLES OPERATORS # creating a new tuple with appending tuples or concatenating tuples tuple33 = tuple1 + tuple2 print('tuple33: ', tuple33) #OUTPUT: tuple33: (1, 2, 3, 4, 5, 'A', 'b', 1, 2) tuple34 = (1,2,3) + ('a','b','c') print('tuple34: ', tuple34) #OUTPUT: tuple34: (1, 2, 3, 'a', 'b', 'c') # Check if element exists print(1 in tuple34) #OUTPUT: True for LOOP_COUNTER in (1, 2, 3): print(LOOP_COUNTER) # OUTPUT: 1 # 2 # 3 # Multiplication of the tuple values, duplication (multiple times) print(tuple1*3) # OUTPUT: (1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5) ## >``` ## >## Slicing Tuples ## >``` tuple99 = (11, 22, 33, 44, 55, 66) print('tuple99: ', tuple99) #OUTPUT: tuple99: (11, 22, 33, 44, 55, 66) # SLice from Index 1 to ONE element before Index 3 print(tuple99[1:3]) # OUTPUT: (22, 33) # Negative numbers in Index counts from reverse (-1 is last element) print(tuple99[-1]) # OUTPUT: 66 # Slice [n:] with no upper bound prints from nth index to end of index(last element) print(tuple99[2:]) # OUTPUT: (33, 44, 55, 66) ## >``` ## >## Tuples Built-in methods ## >``` tuple99 = (11, 22, 33, 44, 55, 66) # COUNT method counts the occurrences of an element in the tuple print((1,1,2,3).count(1)) # OUTPUT: 2 # MIN and MAX element of the TUPLE print(min(tuple99), max(tuple99)) # OUTPUT: 11 66 # LENGTH of tuple print(len(tuple99)) # SUM of all ELEMENTS print(sum(tuple99)) # OUTPUT: 231 ## >```
fc8bde15b9c00120cb4d5b19920a58e288100686
CHemaxi/python
/003-python-modules/008-python-regexp.py
2,984
4.34375
4
""" MARKDOWN --- Title: python iterators and generators MetaDescription: python regular, expressions, code, tutorials Author: Hemaxi ContentName: python-regular-expressions --- MARKDOWN """ """ MARKDOWN # PYTHON REGULAR EXPRESSIONS BASICS * Regular Expressions are string patterns to search in other strings * PYTHON Regular Expressions, functionality is provided by the "re" MODULE * The "re" Module provides all the functions required to enable PYTHONs regular expressions * Regular expressions is all about matching a "pattern" in a "string" * **search()** function, returns true or false for the string found / not found * **findall()** function, returns a TUPLE of all occurrences of the pattern * **sub()** function, This is used to replace parts of strings, with a pattern * **split()** function, seperates a string by space or any dilimeter. MARKDOWN """ # MARKDOWN ``` ####################### # 1) search Function ####################### import re # Create a test string with repeating letters words test_string = "The Test string 123 121212 learnpython LEARNPYTHON a1b2c3" #Search for pattern: learnpython (in SMALL LETTERS) match = re.search(r'learnpython',test_string) if match: print("The word 'learnpython' is found in the string:", "\n", test_string) else: print("The word 'learnpython' is NOT found in the string:", "\n", test_string) # Search for more complicated patterns, search for 12*, where * # is wildcard character, match everything else after the pattern "12" match = re.search(r'12*',test_string) if match: print("The word '12*' is found in the string:", "\n", test_string) else: print("The word '12*' is NOT found in the string:", "\n", test_string) ######################## # 2) findall Function ######################## import re # Prints all the WORDS with a SMALL "t" in the test-string # The options are: # word with a "t" in between \w+t\w+, # OR indicated by the PIPE symbol | # word with a "t" as the last character \w+t, # OR indicated by the PIPE symbol | # word with a "t" as the first character t\w+, # Create a test string with repeating letters words test_string = "The Test string 123 121212 learnpython LEARNPYTHON a1b2c3" all_t = re.findall(r'\w+t\w+|\w+t|t\w+',test_string) # The re.findall returns a TUPLE and we print all the elements looping # through the tuple for lpr in all_t: print(lpr) ######################## # 3) sub Function ######################## import re # This is used to replace parts of strings, with a pattern string = "Learnpython good python examples" # Replace "good" with "great" new_string = re.sub("good", "great", string) print(string) print(new_string) ######################## # 4) split Function ######################## # The split Function splits a string by spaces import re words2list = re.split(r's','Learnpython good python examples') print(words2list) # Split a Comma Seperated String csv2list = re.split(r',','1,AAA,2000') print(csv2list) # MARKDOWN ```
5b4b6d7602f2161ba8c400a6452067a729029f08
CHemaxi/python
/001-python-core-language/003_strings.py
7,001
3.859375
4
## >--- ## >YamlDesc: CONTENT-ARTICLE ## >Title: python strings ## >MetaDescription: python string, Strings as arrays,Slicing Strings,String Methods,find,index example code, tutorials ## >MetaKeywords: python string, Strings as arrays,Slicing Strings,String Methods,find,index example code, tutorials ## >Author: Hemaxi ## >ContentName: strings ## >--- ## ># Python String handling ## >* In python Strings are sequence of characters in single or double quotes ## >* Multi-line strings are enclosed in Triple quotes """<Multi Line text>""" ## > or '''<Multi Line text>''' ## >* Working with String character index(position of a character in a string) ## >* Strings are immutable, meaning they cant be changed once assogned ## > * Slicing strings with INDEX ## > * String built-in methods ## > * String text Case conversion ## > * String Checking methods ## > * String Manipulation ## >### Strings Basics ## >``` # sample string using DOUBLE QUOTES var_string_1 = "DOUBLE QUOTES STRING:Welcome to python tutorials by learnpython.com" # sample string using SINGLE QUOTES var_string_2 = 'SINGLE QUOTES STRING: Welcome to python tutorials by learnpython.com' # Multi line string using THREE DOUBLE QUOTES var_string_3 = """THREE DOUBLE QUOTES MULTI LINE STRING: Welcome to python tutorials by learnpython.com,This is a multi line string as you can see""" # print the sthe above strings print(var_string_1) print(var_string_2) print(var_string_3) ## >``` ## >### Strings as arrays [Using strings as arrays in other languages] ## >``` # Using python strings as STRING ARRAYs var_test_string = "Python is cool" # Index starts from 0, # This prints the first character of the string print('First character of variable var_test_string: ', var_test_string[0]); # Index of the last character is -1 print('Last character of variable var_test_string: ',var_test_string[-1]); # Print forth character from the end print('Fourth character from the end of variable var_test_string: ' ,var_test_string[-4]); ## >``` ## >### Slicing Strings[ working with string indexes(character positions in the string)] ## >``` var_test_string = "Python is cool" # Slicing part of the string using [number:] # prints string from specified index position to end of string print(var_test_string[6:]) # prints string from specified index position to end of string print(var_test_string[-4:]) # prints a part of the string between the specified index position print(var_test_string[4:10]) # OUT oF range indexes # when specifing indexes that dont exist is a string # single index usage fails var_my_string = "four" # print(var_my_string[5]) # this is raise an error # Slicing will not raise error, rather will not print anything print(var_my_string[5:7]) # Doesnt print anything ## >``` ## >### String Methods - Text Case conversion ## >``` # Testing String var_string_case_test = "learn PYTHON" # upper case conversion print(var_string_case_test.upper()) # OUTPUT: LEARN PYTHON # lower case conversion print(var_string_case_test.lower()) # OUTPUT: learn python # title case conversion print(var_string_case_test.title()) # OUTPUT: Learn Python # swap case conversion, swaps upper to lower and vice versa print(var_string_case_test.swapcase()) # OUTPUT: LEARN python # capitalize case conversion, UPPERs the first letter of the string print(var_string_case_test.capitalize()) # OUTPUT: Learn python ## >``` ## >### String Methods - Checking methods ## >``` # The Checking methods print true or false (Boolean) # Checking if the string is UpperCase print ('PYTHON'.isupper()) # prints true # Checking if the string is lowerCase print ('PYTHON'.islower()) # prints false # Checking if the string is alphabets only print ('PYTHON01'.islower()) # prints false # Checking if the string is alphnumeric (alphabets/digits) print ('PYTHON01'.isalnum()) # prints true # Checking if the string is alphnumeric (alphabets/digits/special characters) print ('1000'.isnumeric()) # prints true # Checking if the string is white space (space/tab) print (' '.isspace()) # prints true ## >``` ## >### String Methods - String Manipulation ## >``` # remove parts of string # and return the changed string # strip() Removes the white spaces before and after the string print (' This is a test '.strip()) # OUTPUT: This is a test print ('This is a test'.strip('t')) # removes the last occurrence of 't' # OUTPUT: This is a tes print ('This is a test'.strip('T')) # removes the last occurrence of 'T' # OUTPUT: his is a tes print ('This is a test'.lstrip('This')) # removes the last occurrence of 'This' # OUTPUT: is a test # lstrip() Removes the leading characters or white spaces by default # white spaces, of a string # Removes the white spaces before and after the string print (' This is a test '.lstrip()) # OUTPUT: This is a test print ('This is a test '.lstrip('This')) # OUTPUT: is a test # rstrip() Removes the trailing characters or white spaces by default # white spaces, of a string # Removes the white spaces before and after the string print ('This is a test '.rstrip(' test')) # OUTPUT: This is a ## >``` ## >### String alignment justify ## >``` # ljust, center, rjust # justify methods that add white spaces by default to # align the string, and pad the string to the length mentioned print ('test'.ljust(10,'+')) # OUTPUT: test++++++ print ('test'.rjust(10,'+')) # OUTPUT: ++++++test print ('test'.center(10,'+')) # OUTPUT: +++test+++ ## >``` ## >### Work with portions of string ## >``` # find()/index(): displays the position index of a given substring and # its occurrence number print ('test'.find('t',2)) # print the index of the second occurrence of 't' # OUTPUT: 3 print ('test'.index('t')) # print the index of the first occurrence of 't' # OUTPUT: 0 # find() doesnot raise error, it returns -1 when not found print ('test'.find('z')) # print the index of the second occurrence of 't' # OUTPUT: -1 # index(), raises an error when not found # print ('test'.index('z')) # print the index of the second occurrence of 't' # ERROR: ValueError: substring not found #rfind(), prints the highest index and -1 when not found print ('test'.rfind('z')) # OUTPUT: -1 print ('test'.rfind('t')) # OUTPUT: 3 #rindex(), prints the highest index and errors out when not found print ('test'.rindex('t')) # OUTPUT: 3 #replace(); replace the characters with the specified characters print ('test'.replace('t','i')) # OUTPUT: iesi #split(), This converts a string into a list based on a separator, #default is whitespace print('This is a test'.split()) # prints a LIST, seperated by a whitespace print('This|is|a|test'.split('|')) # prints a LIST, seperated by a pipe | print('This,is,a,test'.split(',')) # prints a LIST, seperated by a comma , #splitlines(), Converts multi-line strings to a list # Test varaible with multi-line string testString = """Line 1 Line 2 Line 3 """ print(testString.splitlines()) # OUTPUT: ['Line 1', 'Line 2', 'Line 3'] ## >```
85b893d3d8e664dd898e615e77adbcafc7a46938
CHemaxi/python
/003-python-modules/016-python-json-files.py
1,701
3.8125
4
""" MARKDOWN --- Title: Python JSON Tags: Python JSON, Read Json, write Json, Nested json Author: Hemaxi | www.github.com/learnpython ContentName: python-json --- MARKDOWN """ """ MARKDOWN # Python JSON Module * JSON is a data format widely used in REST web services, It stands for javascript Object Notation. * Here we demonstrate the following * Read Simple JSON, nested JSON * Create JSON from Python * Convert JSON to Dictionary, Lists ## Python Read JSON * Here we demonstrate python program reading a String in JSON format * **LOADS** Function parses JSON MARKDOWN """ # MARKDOWN```python import json # some JSON: bill_json = """{ "BillNumber":1245 ,"BillTotal":3000 ,"StoreLocation":"New York" ,"BillDetails":[ { "Product":"Soda" ,"Quantity":10 ,"UnitPrice":2 ,"LineItemPrice": 20} ,{ "Product":"Chips" ,"Quantity":5 ,"UnitPrice":3 ,"LineItemPrice":15 } ,{ "Product":"cookies" ,"Quantity":4 ,"UnitPrice":5 ,"LineItemPrice":20 } ] }""" # Parse JSON using "loads" Method y = json.loads(bill_json) # Get Subset of JSON print(y["BillDetails"]) # JSON Nested value, Get First Product print(y["BillDetails"][0]["Product"]) # JSON Get All Products for restaurant in y["BillDetails"]: print(restaurant["Product"]) # MARKDOWN```
e6516fb6c875b55303f5098988eb876d1749c739
lucifersasi/pythondemo
/TELUSKO/selectionsort(min).py
345
3.90625
4
def sort(nums): for i in range(5): minpos=i for j in range(i,6): if nums[j]<nums[minpos]: minpos=j temp=nums[i] nums[i]=nums[minpos] nums[minpos]=temp print(nums) #to see the sorting process step by step nums=[5,3,8,6,7,2] sort(nums) print(nums) # final output
6c82a4dd7590e0faac8b65e9011f621e44a01486
lucifersasi/pythondemo
/AndreiNeagoi/testing/game_test/guess_game_test.py
649
3.578125
4
import unittest from unittest import result import guess_game class TestMain(unittest.TestCase): def test_guess_val(self): answer = 1 guess = 1 result = guess_game.guess_run(guess, answer) self.assertTrue(result) def test_guess_wrongguess(self): result = guess_game.guess_run(0, 5) self.assertFalse(result) def test_guess_wrongnum(self): result = guess_game.guess_run(11, 5) self.assertFalse(result) def test_guess_wrongtype(self): result = guess_game.guess_run("d", 3) self.assertFalse(result) if __name__ == '__main__': unittest.main()
2ab350c02e54f7a4677eaa5b9b20b82a0fb1ec41
garciazapiain/euler
/euler 5.py
297
3.703125
4
i=1 counter=1 x=300000000 divisible=0 while (counter<x): while (i<21): if counter%i==0: divisible=divisible+0 else: divisible=1 break i=i+1 if divisible==0: print ("Number divisible by",counter) counter=counter+1 divisible=0 i=1
b530137226c3edb0245d2ccb10564baa0f4a78fa
peterbekins/MIT_OCW_6.00SC-Introduction-to-Computer-Science-and-Programming
/PS11/shortest_path.py
11,174
4
4
# PS 11: Graph optimization, Finding shortest paths through MIT buildings # # Name: Peter Bekins # Date: 5/12/20 # import string from graph import * # # Problem 2: Building up the Campus Map # # Write a couple of sentences describing how you will model the # problem as a graph) # def load_map(mapFilename): """ Parses the map file and constructs a directed graph Parameters: mapFilename : name of the map file Assumes: Each entry in the map file consists of the following four positive integers, separated by a blank space: From To TotalDistance DistanceOutdoors e.g. 32 76 54 23 This entry would become an edge from 32 to 76. Returns: a directed graph representing the map """ print "Loading map from file..." dataFile = open(mapFilename, 'r') map = mapGraph() nodes = [] for line in dataFile: if len(line) == 0 or line[0] == '#': continue dataLine = string.split(line) src = dataLine[0] dest = dataLine[1] # If src or dst are not already nodes, create them if not src in nodes: nodes.append(src) map.addNode(Node(src)) if not dest in nodes: nodes.append(dest) map.addNode(Node(dest)) source = map.getNode(src) destination = map.getNode(dest) weight = (int(dataLine[2]), int(dataLine[3])) map.addEdge(mapEdge(source, destination, weight)) return map # # Problem 3: Finding the Shortest Path using Brute Force Search # # State the optimization problem as a function to minimize # and the constraints # def allPaths(graph, start, end, maxTotalDist, maxDistOutdoors, path = []): """ This function walks every possible path between start and end. If the path meets the constraints (total and outdoor dist) it is added to the list. Returns list of all paths that meet constraints. """ path = path + [start] if start == end: totLength, outLength = pathLength(graph, path) if (totLength <= maxTotalDist) and (outLength <= maxDistOutdoors): return [path] if not (graph.hasNode(start)): return [] paths = [] for node in graph.childrenOf(start): if node[0] not in path: #print "current path " + str(path) extended_paths = allPaths(graph, node[0], end, maxTotalDist, maxDistOutdoors, path) for p in extended_paths: paths.append(p) return paths def pathLength(graph, path): totLength = 0 outLength = 0 for i in range(len(path)-1): for node in graph.childrenOf(path[i]): if node[0] == path[i+1]: totLength += node[1][0] outLength += node[1][1] return totLength, outLength def bruteForceSearch(digraph, start, end, maxTotalDist, maxDistOutdoors): """ Finds the shortest path from start to end using brute-force approach. The total distance travelled on the path must not exceed maxTotalDist, and the distance spent outdoor on this path must not exceed maxDisOutdoors. Parameters: digraph: instance of class Digraph or its subclass start, end: start & end building numbers (strings) maxTotalDist : maximum total distance on a path (integer) maxDistOutdoors: maximum distance spent outdoors on a path (integer) Assumes: start and end are numbers for existing buildings in graph Returns: The shortest-path from start to end, represented by a list of building numbers (in strings), [n_1, n_2, ..., n_k], where there exists an edge from n_i to n_(i+1) in digraph, for all 1 <= i < k. If there exists no path that satisfies maxTotalDist and maxDistOutdoors constraints, then raises a ValueError. """ start_node = digraph.getNode(start) end_node = digraph.getNode(end) paths = allPaths(digraph, start_node, end_node, maxTotalDist, maxDistOutdoors) # 2. Select shortest path under constraints shortPath = None shortLength = None # print "Brute force found " + str(len(paths)) + " paths" for path in paths: totLength, outLength = pathLength(digraph, path) if (shortLength == None) and (totLength <= maxTotalDist) and (outLength <= maxDistOutdoors): shortLength = totLength shortPath = path elif (totLength < shortLength) and (totLength <= maxTotalDist) and (outLength <= maxDistOutdoors): shortLength = totLength shortPath = path if shortPath == None: raise ValueError else: return shortPath # # Problem 4: Finding the Shortest Path using Optimized Search Method # def dfSearch(graph, start, end, maxTotalDist, maxDistOutdoors, path = [], shortPath = None): """ This walks each possible path between start and end. MaxTotalDist is the initial value for shortest path length. If any partial path hits the current shortest length, it gives up and backtracks to the next option. If any partial path hits maxDistOutdoors, it gives up and backtracks to the next option. returns best path as list of nodes """ path = path + [start] if start == end: return path for node in graph.childrenOf(start): if node[0] not in path: newPath = dfSearch(graph, node[0], end, maxTotalDist, maxDistOutdoors, path, shortPath) if newPath is not None: total, outdoors = pathLength(graph, newPath) if total <= maxTotalDist and outdoors <= maxDistOutdoors: shortPath = newPath maxTotalDist = total return shortPath def directedDFS(digraph, start, end, maxTotalDist, maxDistOutdoors): """ Finds the shortest path from start to end using directed depth-first. search approach. The total distance travelled on the path must not exceed maxTotalDist, and the distance spent outdoor on this path must not exceed maxDisOutdoors. Parameters: digraph: instance of class Digraph or its subclass start, end: start & end building numbers (strings) maxTotalDist : maximum total distance on a path (integer) maxDistOutdoors: maximum distance spent outdoors on a path (integer) Assumes: start and end are numbers for existing buildings in graph Returns: The shortest-path from start to end, represented by a list of building numbers (in strings), [n_1, n_2, ..., n_k], where there exists an edge from n_i to n_(i+1) in digraph, for all 1 <= i < k. If there exists no path that satisfies maxTotalDist and maxDistOutdoors constraints, then raises a ValueError. """ start_node = digraph.getNode(start) end_node = digraph.getNode(end) shortPath = dfSearch(digraph, start_node, end_node, maxTotalDist, maxDistOutdoors) if shortPath == None: raise ValueError else: return shortPath # Uncomment below when ready to test if __name__ == '__main__': # Test cases digraph = load_map("mit_map.txt") LARGE_DIST = 1000000 # Test case 1 print "---------------" print "Test case 1:" print "Find the shortest-path from Building 32 to 56" expectedPath1 = ['32', '56'] brutePath1 = bruteForceSearch(digraph, '32', '56', LARGE_DIST, LARGE_DIST) dfsPath1 = directedDFS(digraph, '32', '56', LARGE_DIST, LARGE_DIST) print "Expected: ", expectedPath1 print "Brute-force: ", brutePath1 print "DFS: ", dfsPath1 # Test case 2 print "---------------" print "Test case 2:" print "Find the shortest-path from Building 32 to 56 without going outdoors" expectedPath2 = ['32', '36', '26', '16', '56'] brutePath2 = bruteForceSearch(digraph, '32', '56', LARGE_DIST, 0) dfsPath2 = directedDFS(digraph, '32', '56', LARGE_DIST, 0) print "Expected: ", expectedPath2 print "Brute-force: ", brutePath2 print "DFS: ", dfsPath2 # Test case 3 print "---------------" print "Test case 3:" print "Find the shortest-path from Building 2 to 9" expectedPath3 = ['2', '3', '7', '9'] brutePath3 = bruteForceSearch(digraph, '2', '9', LARGE_DIST, LARGE_DIST) dfsPath3 = directedDFS(digraph, '2', '9', LARGE_DIST, LARGE_DIST) print "Expected: ", expectedPath3 print "Brute-force: ", brutePath3 print "DFS: ", dfsPath3 # Test case 4 print "---------------" print "Test case 4:" print "Find the shortest-path from Building 2 to 9 without going outdoors" expectedPath4 = ['2', '4', '10', '13', '9'] brutePath4 = bruteForceSearch(digraph, '2', '9', LARGE_DIST, 0) dfsPath4 = directedDFS(digraph, '2', '9', LARGE_DIST, 0) print "Expected: ", expectedPath4 print "Brute-force: ", brutePath4 print "DFS: ", dfsPath4 # Test case 5 print "---------------" print "Test case 5:" print "Find the shortest-path from Building 1 to 32" expectedPath5 = ['1', '4', '12', '32'] brutePath5 = bruteForceSearch(digraph, '1', '32', LARGE_DIST, LARGE_DIST) dfsPath5 = directedDFS(digraph, '1', '32', LARGE_DIST, LARGE_DIST) print "Expected: ", expectedPath5 print "Brute-force: ", brutePath5 print "DFS: ", dfsPath5 # Test case 6 print "---------------" print "Test case 6:" print "Find the shortest-path from Building 1 to 32 without going outdoors" expectedPath6 = ['1', '3', '10', '4', '12', '24', '34', '36', '32'] brutePath6 = bruteForceSearch(digraph, '1', '32', LARGE_DIST, 0) dfsPath6 = directedDFS(digraph, '1', '32', LARGE_DIST, 0) print "Expected: ", expectedPath6 print "Brute-force: ", brutePath6 print "DFS: ", dfsPath6 # Test case 7 print "---------------" print "Test case 7:" print "Find the shortest-path from Building 8 to 50 without going outdoors" bruteRaisedErr = 'No' dfsRaisedErr = 'No' try: bruteForceSearch(digraph, '8', '50', LARGE_DIST, 0) except ValueError: bruteRaisedErr = 'Yes' try: directedDFS(digraph, '8', '50', LARGE_DIST, 0) except ValueError: dfsRaisedErr = 'Yes' print "Expected: No such path! Should throw a value error." print "Did brute force search raise an error?", bruteRaisedErr print "Did DFS search raise an error?", dfsRaisedErr # Test case 8 print "---------------" print "Test case 8:" print "Find the shortest-path from Building 10 to 32 without walking" print "more than 100 meters in total" bruteRaisedErr = 'No' dfsRaisedErr = 'No' try: bruteForceSearch(digraph, '10', '32', 100, LARGE_DIST) except ValueError: bruteRaisedErr = 'Yes' try: directedDFS(digraph, '10', '32', 100, LARGE_DIST) except ValueError: dfsRaisedErr = 'Yes' print "Expected: No such path! Should throw a value error." print "Did brute force search raise an error?", bruteRaisedErr print "Did DFS search raise an error?", dfsRaisedErr
128d708db97a5073cd55a968fd83a78c7149d89f
denisdenisenko/Python_proj_1
/Project_1/Q1.py
668
3.6875
4
import re def number_of_messages_in_inbox(given_file): """ Counting the number of messages in the inbox :param given_file: .txt :return: void """ file_to_handle = None try: file_to_handle = open(given_file) except: print('File cannot be opened:', given_file) exit() simple_counter = 0 # Iterating over each line and if there "From " in the line -> increase counter for line in file_to_handle: line = line.rstrip() if re.search('^From:', line): # print(line) simple_counter += 1 continue print("Number of messages in inbox: ", simple_counter)
91f1b436f1ef43d14ace8e53cabec0ab202c1b45
hussein343455/Code-wars
/kyu 6/Split Strings.py
612
4.09375
4
# Complete the solution so that it splits the string into pairs of two characters. # If the string contains an odd number of characters then it should replace # the missing second character of the final pair with an underscore ('_'). # Examples: # solution('abc') # should return ['ab', 'c_'] # solution('abcdef') # should return ['ab', 'cd', 'ef'] def solution(s): re=[] i,j=0,2 if not s:return [] while j<len(s): re.append(s[i:j]) i+=2 j+=2 if len(s)%2==0: re.append(s[-2]+s[-1]) return re re.append(s[-1]+"_") return re
1ea08b041a6b98de6c0a5c55e9ffb411bdd6d3bc
hussein343455/Code-wars
/kyu 5/Best travel.py
2,218
4.03125
4
# John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns. ls = [50, 55, 57, 58, 60]. John is tired of driving and he says to Mary that he doesn't want to drive more than t = 174 miles and he will visit only 3 towns. # # Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John? # # Example: # With list ls and 3 towns to visit they can make a choice between: [50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]. # # The sums of distances are then: 162, 163, 165, 165, 167, 168, 170, 172, 173, 175. # # The biggest possible sum taking a limit of 174 into account is then 173 and the distances of the 3 corresponding towns is [55, 58, 60]. # # The function chooseBestSum (or choose_best_sum or ... depending on the language) will take as parameters t (maximum sum of distances, integer >= 0), k (number of towns to visit, k >= 1) and ls (list of distances, all distances are positive or null integers and this list has at least one element). The function returns the "best" sum ie the biggest possible sum of k distances less than or equal to the given limit t, if that sum exists, or otherwise nil, null, None, Nothing, depending on the language. # # With C++, C, Rust, Swift, Go, Kotlin, Dart return -1. # # Examples: # ts = [50, 55, 56, 57, 58] choose_best_sum(163, 3, ts) -> 163 # # xs = [50] choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go) # # ys = [91, 74, 73, 85, 73, 81, 87] choose_best_sum(230, 3, ys) -> 228 def choose_best_sum(t, k, ls): top= [] c=0 stop = 0 pointers = [] ls = sorted(ls) ls.reverse() while True: for ind, i in enumerate(ls): if ind <= c: continue if i + sum(top) > t: continue top.insert(len(top), i) pointers.insert(len(pointers), ind) stop += 1 if stop == k: return sum(top) stop -= 1 if not top: return None top.pop() c = pointers.pop()
bcd7c3ee14dd3af063a6fea74089b02bade44a1c
hussein343455/Code-wars
/kyu 6/Uncollapse Digits.py
729
4.125
4
# ask # You will be given a string of English digits "stuck" together, like this: # "zeronineoneoneeighttwoseventhreesixfourtwofive" # Your task is to split the string into separate digits: # "zero nine one one eight two seven three six four two five" # Examples # "three" --> "three" # "eightsix" --> "eight six" # "fivefourseven" --> "five four seven" # "ninethreesixthree" --> "nine three six three" # "fivethreefivesixthreenineonesevenoneeight" --> "five three def uncollapse(digits): x=["zero","one","two","three","four","five","six","seven","eight","nine"] for ind,i in enumerate(x): digits=digits.replace(i,str(ind)) return " ".join([x[int(i)] for i in digits])
e73d1193b1cb911c3681103d0ce3db4f44340176
hussein343455/Code-wars
/kyu 4/Roman Numerals Helper.py
2,229
3.796875
4
# Create a RomanNumerals class that can convert a roman numeral to and # from an integer value. It should follow the API demonstrated in the examples below. # Multiple roman numeral values will be tested for each helper method. # # Modern Roman numerals are written by expressing each digit separately # starting with the left most digit and skipping any digit with a value of zero. # In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. # 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: # MDCLXVI. # # Examples # RomanNumerals.to_roman(1000) # should return 'M' # RomanNumerals.from_roman('M') # should return 1000 # Help # | Symbol | Value | # |----------------| # | I | 1 | # | V | 5 | # | X | 10 | # | L | 50 | # | C | 100 | # | D | 500 | # | M | 1000 | class RomanNumerals(): def to_roman(number): number = str(number) while len(number) < 4: number = "0" + number re = '' dec = {1: 'I', 5: 'V', 10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M', 400: 'CD', 600: 'DC', 700: 'DCC', 800: 'DCCC', 900: 'CM', 40: 'XL', 60: 'LX', 70: 'LXX', 80: 'LXXX', 90: 'XC', 4: 'IV', 6: 'VI', 7: 'VII', 8: 'VIII', 9: 'IX', } re = re + "M" * int(number[0]) k = int(number[1] + "00") if k <= 300: re = re + 'C' * int(k / 100) else: re = re + dec[k] k = int(number[2] + "0") if k <= 30: re = re + 'X' * int(k / 10) else: re = re + dec[k] k = int(number[3]) if k <= 3: re = re + 'I' * k else: re = re + dec[k] return re def from_roman(Roman): pos = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} re = 0 for ind, i in enumerate(Roman): if ind == len(Roman) - 1: re += pos[i] elif pos[i] < pos[Roman[ind + 1]]: re -= pos[i] else: re += pos[i] return re
d9684a8c4fcdc5d846fb8e83ba8a9d9adf6c79e9
hussein343455/Code-wars
/kyu 7/Holiday III - Fire on the boat.py
373
3.5
4
# njoying your holiday, you head out on a scuba diving trip! # Disaster!! The boat has caught fire!! # You will be provided a string that lists many boat related items. If any of these items are "Fire" you must spring into action. Change any instance of "Fire" into "~~". Then return the string. # Go to work! def fire_fight(s): return s.replace("Fire","~~")
7d688699d912214c003e718f918a530d2acb637b
hussein343455/Code-wars
/kyu 7/Simple letter removal.py
913
3.828125
4
# In this Kata, you will be given a lower case string and your task will be to remove k characters from that string using the following rule: # # - first remove all letter 'a', followed by letter 'b', then 'c', etc... # - remove the leftmost character first. # For example: # solve('abracadabra', 1) = 'bracadabra' # remove the leftmost 'a'. # solve('abracadabra', 2) = 'brcadabra' # remove 2 'a' from the left. # solve('abracadabra', 6) = 'rcdbr' # remove 5 'a', remove 1 'b' # solve('abracadabra', 8) = 'rdr' # solve('abracadabra',50) = '' # More examples in the test cases. Good luck! def solve(st,k): st=st+"." for i in range(97,123): s=st.count(chr(i)) if s<k: st= st.replace(chr(i),"",s) k=k-s if st==".": return '' elif s>=k: st= st.replace(chr(i),"",k) return st[:-1]
fc6a2e2351529daf107a2996b8fc8052fe4a4384
colson1111/Other-Python-Code
/Random-Code/bubble_sort.py
446
3.640625
4
import numpy as np import time lst = np.random.randint(low = 1, high = 100, size = 10000).tolist() lst1 = lst # bubble sort def bubble_sort(lst): for i in range(len(lst)-1,0,-1): for j in range(i): if lst[j] > lst[j + 1]: c = lst[j] lst[j] = lst[j + 1] lst[j + 1] = c return lst a = time.time() bubble_sort(lst1) bubble_time = time.time() - a
967970e8265ab10e4677188c1a5fb54a3007faf2
pchegancas/slabwork
/MySlabs.py
875
3.578125
4
""" Classes for slab reinforcement calculations """ class Slab(): """ Model of a slab """ def __init__ (self, name: str, thk: float, concrete: float): self.name = name self.thk = thk self.concrete = concrete def __repr__ (self): print(f'Slab({self.name}, {self.thk}, {self.concrete})') class Band(): """ Model of a band """ def __init__(self, slab: Slab, width: float, strip_type): self.slab = slab self.width = width self.strip_type = strip_type def __repr__ (self): print(f'Band({self.slab}, {self.width}, {self.strip_type})') def get_min_reinforcement(self): return self.width * self.slab.thk * 0.002 class Project(): """ """ def __init__(self, name: str, number: str, date): self.name = name self.number = number self.date = date def __repr__ (self): print(f'Project({self.name}, {self.number}, {self.date})')
ab31c3e1a33bbe9ec2eb8ef5235b2206c022a8d7
kritikhullar/Python_Training
/day1/factorial.py
288
4.25
4
#Fibonacci print("-----FIBONACCI-----") a= int(input("Enter no of terms : ")) def fibonacci (num): if num<=1: return num else: return (fibonacci(num-1)+fibonacci(num-2)) if a<=0: print("Enter positive") else: for i in range(a): print (fibonacci(i), end = "\t")
097662ada6fcf8db91c68ee4d6e44a883ec3662e
kritikhullar/Python_Training
/day1/fibonacci.py
364
4.0625
4
#Factorial print("-----FACTORIAL-----") a= int(input("Enter range lower limit : ")) b= int(input("Enter range upper limit : ")) fact=1 def factorial (number): if number==0: return 1 if number==1: return number if number!=0: return number*factorial(number-1) for i in range(a,b+1,1): print ("Factorial of ", i, " = ", factorial(i))
77ceb0bc9596aa7d367d99a57e0ccb1552bdbfc6
kngavl/my-first-blog
/python_intro.py
274
4.0625
4
#this is a comment print("Hello, Django girls") if -2>2: print("Eat dirt") elif 2>1: print("hooman") else: print("y9o") def hi(name): print("hello " + name) print("hi") hi("frank") girls = ["shelly", "anja", "terry"] for name in girls: print(name)
a32357b7aabf7fd28844f10ed46e4c2517e94006
ningmengmumuzhi/ningmengzhi
/练习/1.py
113
3.8125
4
num=123.456 print(num) num='hello' print('who do you think i am') you=input() print('oh yes! i am a' )(you)
77cbc21b55152a47401ca785f411064581fa6225
ladsmund/msp_group_project
/koshka/scales/pythag_modes.py
1,384
3.515625
4
#!/usr/bin/python from pythag_series import PythagSeries class PythagMode: def __init__(self, mode, frequency): self.name = mode.lower() self.freq = frequency # An empty string does not transform to a different mode if self.name == "": self.tonic = 1 self.name = "ionian" elif self.name == "dorian": self.tonic = 2 elif self.name == "phrygian": self.tonic = 3 elif self.name == "lydian": self.tonic = 4 elif self.name == "mixolydian": self.tonic = 5 elif self.name == "aeolian": self.tonic = 6 elif self.name == "locrian": self.tonic = 7 elif self.name == "ionian": self.tonic = 8 else: print("Invalid mode chosen.") exit(1) mode_freqs = PythagSeries(self.freq).get_natural_scale() # Modify the frequency list to the mode for which a string was given # Basically, "roll up" to the appropriate mode by multiplying the tonic by 2 i = self.tonic while i > 1: mode_freqs.pop(0) mode_freqs.append(mode_freqs[0] * 2) i = i - 1 self.freqs = mode_freqs mode_freqs_alt = PythagSeries(mode_freqs[0]).get_natural_scale() self.freqs_alt = mode_freqs_alt
64e73cb395d25b53a166a6e491e70a7834c96aee
sajjadm624/Bongo_Python_Code_Test_Solutions
/Bongo_Python_Code_Test_Q_3.py
2,330
4.1875
4
# Data structure to store a Binary Tree node class Node: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right # Function to check if given node is present in binary tree or not def isNodePresent(root, node): # base case 1 if root is None: return False # base case 2 # if node is found, return true if root == node: return True # return true if node is found in the left subtree or right subtree return isNodePresent(root.left, node) or isNodePresent(root.right, node) def preLCA(root, lca, x, y): # case 1: return false if tree is empty if root is None: return False, lca # case 2: return true if either x or y is found # with lca set to the current node if root == x or root == y: return True, root # check if x or y exists in the left subtree left, lca = preLCA(root.left, lca, x, y) # check if x or y exists in the right subtree right, lca = preLCA(root.right, lca, x, y) # if x is found in one subtree and y is found in other subtree, # update lca to current node if left and right: lca = root # return true if x or y is found in either left or right subtree return (left or right), lca # Function to find lowest common ancestor of nodes x and y def LCA(root, x, y): # lca stores lowest common ancestor lca = None # call LCA procedure only if both x and y are present in the tree if isNodePresent(root, y) and isNodePresent(root, x): lca = preLCA(root, lca, x, y)[1] # if LCA exists, print it if lca: print("LCA is ", lca.data) else: print("LCA do not exist") if __name__ == '__main__': """ Construct below tree 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 """ root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) root.left.left.left = Node(8) root.right.left.right = Node(9) LCA(root, root.right.left, root.right.right) LCA(root, root.right, root.right.right)
5c0555e29053979c65911d74f52aa7c39af15d37
bucho666/pyrl
/test/testdice.py
643
3.59375
4
import unittest from dice import Dice class TestDice(unittest.TestCase): def testRoll(self): self.rollTest(Dice('2d6'), 2, 12) self.rollTest(Dice('2d6+2'), 4, 14) self.rollTest(Dice('2d6-3'), -1, 9) def testString(self): self.stringTest('2d6') self.stringTest('2d6+2') self.stringTest('2d6-3') def rollTest(self, dice, low, high): result = [dice.roll() for c in range(255)] for r in range(low, high + 1): self.assertTrue(r in result) self.assertFalse(low - 1 in result) self.assertFalse(high + 1 in result) def stringTest(self, string): self.assertEqual(str(Dice(string)), string)
85749fe8ab6730a4505eaf14e2c5cbca7d92e655
CIick/Week9
/print(“Cost Calculation Program for Fibe.py
373
3.78125
4
import os costPerFoot = .87 print(" Cost Calculation Program for Fiber Optics") compName= input("Please enter the company name: ") feet = input("Please enter the feet of fiber optics to install: ") Val = (costPerFoot * int (feet)) print( "Cost calucation for the company", compName, "Fiber Optics per foot at", feet, "feet total is $", Val, ".") os.system("pause")
222798a5d6081bd5ef04addcc5e31e550c3f38f2
Jacob1225/cs50
/pset7/houses/import.py
1,175
3.9375
4
from sys import argv, exit import csv import cs50 # Verify user has passed in proper number of args if len(argv) != 2: print("Must provide one and only one file") exit(1) # Open file for SQLite db = cs50.SQL("sqlite:///students.db") # Open file and read it if argument check was passed with open(argv[1], "r") as file: reader = csv.DictReader(file) for row in reader: student = [] # Seperate the first, middle and last name of every student for i in row["name"].split(" "): student.append(i) student.append(row["house"]) student.append(row["birth"]) # Insert the student array into the students db # If student has a middle name if len(student) == 5: db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES (?, ?, ?, ?, ?)", student[0], student[1], student[2], student[3], student[4]) # If student has no middle name if len(student) == 4: db.execute("INSERT INTO students (first, last, house, birth) VALUES (?, ?, ?, ?)", student[0], student[1], student[2], student[3])
92156b23818ebacfa3138e3e451e0ed11c0dd343
brianspiering/project-euler
/python/problem_025.py
1,139
4.375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Solution to "1000-digit Fibonacci number", Problem 25 http://projecteuler.net/problem=25 The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the first term in the Fibonacci sequence to contain 1000 digits? """ num_digits = 1000 # 3 | 1000 def fib(): "A Fibonacci sequence generator." a, b = 0, 1 while True: a, b = b, a+b yield a def find_fib_term(num_digits): "Find the 1st fib term that has the given number of digits." f = fib() current_fib = f.next() counter = 1 while len(str(current_fib)) < num_digits: current_fib = f.next() counter += 1 return counter if __name__ == "__main__": print("The first term in the Fibonacci sequence to contain {} digits "\ "is the {}th term." .format(num_digits, find_fib_term(num_digits)))
2ce7fc6a3a166efdbb4f87ddb75c827d9c805dd7
brianspiering/project-euler
/python/problem_003.py
863
3.875
4
#!/usr/bin/env python """ Solution to "Largest prime factor", aka Problem 3 http://projecteuler.net/problem=3 The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ n = 600851475143 # 13195 | 600851475143 def find_factors(n): "My attempt" return [i for i in xrange(1,n+1) if n % i == 0] def is_prime(n): # XXX: Returns True for n = 1 (1 is not a prime number) return all(n % i for i in xrange(2, n)) def factors(n): "From StackOverflow" return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) def find_largest_prime_factor(n): return max(filter(is_prime, find_factors(n))) if __name__ == "__main__": print("The largest prime factor of {0} is {1}." .format(n, find_largest_prime_factor(n)))
5448d28db97a609cafd01e68c875affe1f97723c
brianspiering/project-euler
/python/problem_004.py
992
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Solution to "Largest palindrome product", aka Problem 4 http://projecteuler.net/problem=4 A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ low, high = 100, 999 # 10, 99 | 100, 999 def find_largest_palindrome(low, high): """(slightly) clever brute force method""" largest_palindrome = 0 for x in xrange(high,low-1,-1): for y in xrange(high,low-1,-1): if is_palindrome(x*y) and (x*y > largest_palindrome): largest_palindrome = x*y return largest_palindrome def is_palindrome(n): return str(n) == str(n)[::-1] if __name__ == "__main__": print("The largest palindrome made from the product of " + "two {0}-digit numbers is {1}." .format(len(str(low)), find_largest_palindrome(low, high)))
bd009da4e937a9cfc1c5f2e7940ca056c1969ae5
brianspiering/project-euler
/python/problem_024.py
1,489
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Solution to "Lexicographic permutations", Problem 24 http://projecteuler.net/problem=24 A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120 201 210 What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? """ from __future__ import print_function import itertools # {range_argument: {place_number, place_name}} perm_picker = { 3: (6, 'sixth'), 10: (1000000, "millionth")} range_argument = 10 # 3 = demo; 10 def find_permutation(range_argument, place): "Find the specific (place) lexicographic permutation for give range argument." perm_tuple = list(itertools.permutations(xrange(range_argument)))[place-1] perm_string = "".join([str(n) for n in perm_tuple]) return perm_string if __name__ == "__main__": digits = range(range_argument) print("The {} lexicographic permutation of the digits ".format(perm_picker[range_argument][1], end="")) for digit in digits[:-2]: print("{}".format(digit), end=", ") print("{}".format(digits[-2]), end=", and ") print("{}".format(digits[-1]), end=" ") print("is {}.".format(find_permutation(range_argument, perm_picker[range_argument][0])))
5e2ae02f6553cbe7c31995ba76abf564c596d346
serenechen/Py103
/ex6.py
767
4.28125
4
# Assign a string to x x = "There are %d types of people." % 10 # Assign a string to binary binary = "binary" # Assign a string to do_not do_not = "don't" # Assign a string to y y = "Those who knows %s and those who %s." % (binary, do_not) # Print x print x # Print y print y # Print a string + value of x print "I said: %r." % x # Print a string + value of y print "I also said: '%s'." % y # Assign False to hilarious hilarious = False # Assign a string to joke_evaluation joke_evaluation = "Isn't that joke so funny?! %r" # Print a string + the value of hilarious print joke_evaluation % hilarious # Assign a string to w w = "This is the left side of..." # Assign a string to e e = "a string with a right side." # print a string concating w and e print w , e
3a3717209ab762e0a98678a58553014a16e0ec3b
Allen-Maharjan/Assignment-II-Control-Statement
/No_10.py
741
4.03125
4
#changing camelcase to snake case and kebab case1 def transformer(sample,seperator): final_answer = '' if seperator == 1: for i in sample: if i.isupper() == True: final_answer += "_" final_answer += i.lower() print(f'Snakecase = {final_answer[1::]}') elif seperator == 2: for i in sample: if i.isupper() == True: final_answer += "-" final_answer += i.lower() print(f"keabab case= {final_answer[1::]}") text = input("Enter a CamelCase string= ") separator = int(input("Enter 1 for snakecase\nEnter 2 for kebab case: ")) if (separator == 1 or separator == 2): transformer(text,separator) else: print("Error")
bf98158d76a44a21dee04e7de1f54047b8b35184
Allen-Maharjan/Assignment-II-Control-Statement
/No_18.py
284
3.59375
4
import json class Person(): def __init__(self, name, age): self.name = name self.age = age person_string = '{"name": "Allen", "age": 21}' person_dict = json.loads(person_string) print(person_dict) person_object = Person(**person_dict) print(person_object.name)
690bffde0d59c3593879d1b7ea1bef2cd2c37301
Naminenisravani/guvi
/positive.py
133
4.15625
4
x=int(input('INPUT')) if x>0: print("x is positive") elif (x==0): print("x is equal to zero") else: print("x is neative")
23f9d9fc5134daddae2aa9bc7c15853370b464ae
EddyScript/Git-With-Eddy
/Calculator.py
1,092
4.28125
4
# Assignment 1--------------------------------------------- def calculator(): first_number = int(input("Enter a number: ")) operator = input("Enter an operator: ") ops = ["+","-","*","/"] if operator in ops: second_number = int(input("Enter another number: ")) else: print("Sorry," + "'" + operator + "'"+ " is not valid.") quit_prompt = input("Press Q to quit OR enter to try again: ") q_button = ["Q","q"] if quit_prompt in q_button: quit() print(calculator()) def sub(number1,number2): print(number1 + number2) if operator == "+": sub(first_number,second_number) def sub(number1,number2): print(number1 - number2) if operator == "-": sub(first_number,second_number) def multi(number1,number2): print(number1 * number2) if operator == "*": multi(first_number,second_number) def div(number1,number2): print(number1 / number2) if operator == "/": div(first_number,second_number) calculator()
87b1700a53f458dc06fd245bcb4d041f45d1d969
BronyPhysicist/BaseballSim
/player_pkg/bats_and_throws.py
803
3.59375
4
''' Created on Apr 03, 2017 @author: Brendan Hassler ''' from enum import Enum from random import random class Bats(Enum): LEFT = "Left" RIGHT = "Right" SWITCH = "Switch" def __str__(self): return str(self.value) class Throws(Enum): LEFT = "Left" RIGHT = "Right" def __str__(self): return str(self.value) def generate_bats_throws(): r_throws = random() r_bats = random() if r_bats < 0.41: if r_throws < 0.366: return Bats.LEFT, Throws.LEFT else: return Bats.LEFT, Throws.RIGHT elif r_bats >= 0.41 and r_bats < 0.96: if r_throws < 0.182: return Bats.RIGHT, Throws.LEFT else: return Bats.RIGHT, Throws.RIGHT else: if r_throws < 0.5: return Bats.SWITCH, Throws.LEFT else: return Bats.SWITCH, Throws.RIGHT
6d70d520f69c0a7e7109a14410f7eaca60e52e36
nhantrithong/Sandbox
/prac3 - scratch exer 2.py
482
4
4
def main(): score = get_score() while score < 0 or score > 100: print("Invalid score, please re-enter an appropriate value") score = float(input("Enter your score: ")) if score < 50: print("This is a bad score") elif score > 50 and score < 90: print("This is a passable score") else: print("This is an excellent score") main() def get_score(): score = float(input("Enter your score: ")) return score main()
bd91b70078d5e7ea12a584d83f9a16071806ed04
AaronShabanian/PythonPrograms
/friends.py
1,248
3.953125
4
file=open("people.txt",'r') while True: dict={} finalList=[] for line in file: line=line.rstrip("\n") list=line.split(",") name=list[0] del list[0] values=list values=set(values) dict.update({name:values}) for key in dict: print(key) while True: try: name1=input("Choose name one: ") set1=dict[name1] break except KeyError: print("That name doesn't exist") while True: try: name2=input("Choose name two: ") set2=dict[name2] break except KeyError: print("That name doesn't exist") print("What they have in commmon: ") print(" ".join((set1).intersection(set2))) print("What is unique to ",name1,": ") print(" ".join(set1.difference(set2))) print("What is unique to ",name2,": ") print(" ".join(set2.difference(set1))) print("All the interests they do not have in common: ") print(" ".join(set2.symmetric_difference(set1))) answer=input("Would you like to continue? (yes or no)") if answer=="yes": print(" ") elif answer=="no": break
eb1491b0d3efc61f2462d17e314244fe5c95a352
charliechoong/sudoku_solver
/CS3243_P2_Sudoku_25.py
10,478
3.546875
4
import sys import copy import time from Queue import PriorityQueue # Running script: given code can be run with the command: # python file.py, ./path/to/init_state.txt ./output/output.txt class Sudoku(object): def __init__(self, puzzle): self.puzzle = puzzle # all empty squares in input puzzle self.remaining_var_list, self.domains = self.get_variables_and_domains() # neighbours of each unassigned variable self.neighbours = self.init_neighbours() self.binary_constraints = self.init_binary_constraints() # for ac3 inference heuristic self.ans = copy.deepcopy(puzzle) def solve(self): start_time = time.time() complete_assignment = self.backtracking_search() end_time = time.time() print(end_time - start_time) self.add_to_puzzle(complete_assignment, self.ans) return self.ans def get_variables_and_domains(self): var_list = list() domains = list() for i in range(0, 9): row = list() for j in range(0, 9): row.append(list()) domains.append(row) for i in range(9): for j in range(9): if self.puzzle[i][j] == 0: var_list.append((i,j)) domains[i][j] = list(k for k in range(1, 10)) constraints = self.init_constraints() self.edit_domains(var_list, domains, constraints) return var_list, domains def init_constraints(self): constraints = list() for i in range(0, 27): new = list(k for k in range(1, 10)) constraints.append(new) for row in range(9): for col in range(9): if self.puzzle[row][col] != 0: constraints[row].remove(self.puzzle[row][col]) constraints[col+9].remove(self.puzzle[row][col]) if self.puzzle[row][col] in constraints[(row/3)*3+col/3+18]: constraints[(row/3)*3+col/3+18].remove(self.puzzle[row][col]) return constraints def edit_domains(self, var_list, domains, constraints): for var in var_list: x, y = var for val in reversed(domains[x][y]): if (val not in constraints[x]) or (val not in constraints[y+9]) or (val not in constraints[(x/3)*3+y/3+18]): domains[x][y].remove(val) def init_neighbours(self): neighbours = dict() for var in self.remaining_var_list: x, y = var neighbours[var] = list() var_box = (x/3)*3+y/3 for other_var in self.remaining_var_list: if other_var == var: continue other_x, other_y = other_var other_var_box = (other_x/3)*3+other_y/3 if other_x == x or other_y == y or var_box == other_var_box: neighbours[var].append(other_var) return neighbours # binary constraints: tuple for each pair of neighbour def init_binary_constraints(self): lst = list() for var in self.remaining_var_list: for neighbour in self.neighbours[var]: lst.append((var, neighbour)) return lst def add_to_puzzle(self, assignment, puzzle): for var, value in assignment.items(): x, y = var puzzle[x][y] = value # Wrapper function for backtracking algorithm def backtracking_search(self): return self.recursive_backtrack({}) def recursive_backtrack(self, assignment): if self.is_completed_assignment(): return assignment var = self.select_unassigned_var() #var = self.remaining_var_list[0] #use this to remove MRV domain = self.order_domain_val(var) #domain = self.domains[var[0]][var[1]] #use this to remove LCV for val in domain: assignment[var] = val self.remaining_var_list.remove(var) self.domains[var[0]][var[1]] = [] is_valid, inferences = self.ac3(var, val) #insert FC or AC-3 here if is_valid: result = self.recursive_backtrack(assignment) if result != -1: return result del assignment[var] self.remaining_var_list.append(var) self.revert_domains(inferences) self.domains[var[0]][var[1]] = copy.copy(domain) return -1 # variable ordering def select_unassigned_var(self): return self.minimum_remaining_values() ''' most_constrained_variables = sorted(self.minimum_remaining_values(), key=(lambda var: self.degree(var)), reverse=True) return most_constrained_variables[0] ''' # heuristic for choosing variable: minimum remaining values (MRV) def minimum_remaining_values(self): min_size = 100 variable = -1 variables = [] for var in self.remaining_var_list: domain_size = len(self.domains[var[0]][var[1]]) if domain_size != 0 and domain_size < min_size: min_size = domain_size variable = var return variable ''' variables = [var] elif domain_size != 0 and domain_size == min_size: variables.append(var) return variables ''' def degree(self, var): count = 0 for neighbour in self.neighbours[var]: if neighbour in self.remaining_var_list: count += 1 return count # order domain values for a variable def order_domain_val(self, var): return self.least_constraining_value(var) # heuristic for ordering domain values: least constraining value(LCV) def least_constraining_value(self, var): x, y = var if len(self.domains[x][y]) == 1: return self.domains[x][y] return sorted(self.domains[x][y], key=(lambda value: self.count_conflicts(var, value))) def count_conflicts(self, var, value): total = 0 for neighbour in self.neighbours[var]: if len(self.domains[neighbour[0]][neighbour[1]]) > 0 and value in self.domains[neighbour[0]][neighbour[1]]: total += 1 return total def revert_domains(self, inferences): for entry in inferences: var, val = entry self.domains[var[0]][var[1]].append(val) inferences = [] # To determine completed assignment, check if there are unassigned variables. def is_completed_assignment(self): if len(self.remaining_var_list) == 0: return True return False # Checks if a value of a variable is consistent with assignment def is_consistent(self, value, variable, assignment): for var, val in assignment.items(): if val == value and variable in self.neighbours[var]: return False return True # heuristic for inference: arc consistency 3 def ac3(self, variable, value): inferences = list() ''' #use FC as pre-processing to determine failure is_valid, inferences = self.forward_checking(variable, value) if is_valid == False: return False, inferences ''' queue = self.binary_constraints while queue: var1, var2 = queue.pop(0) if var1 not in self.remaining_var_list or var2 not in self.remaining_var_list: continue if self.revise(var1, var2, inferences): if self.domains[var1[0]][var1[1]] == []: return False, inferences for var in self.neighbours[var1]: if var != var2 and var in self.remaining_var_list: queue.append((var, var1)) return True, inferences def revise(self, var1, var2, inferences): revised = False for val in self.domains[var1[0]][var1[1]]: if not any(val != other_val for other_val in self.domains[var2[0]][var2[1]]): self.domains[var1[0]][var1[1]].remove(val) inferences.append(((var1[0],var1[1]),val)) revised = True return revised # heuristic for inference: forward checking def forward_checking(self, variable, value): inferences = list() for neighbour in self.neighbours[variable]: x, y = neighbour if neighbour in self.remaining_var_list and value in self.domains[x][y]: self.domains[x][y].remove(value) inferences.append(((x, y), value)) if self.domains[x][y] == []: return False, inferences return True, inferences if __name__ == "__main__": # STRICTLY do NOT modify the code in the main function here if len(sys.argv) != 3: print ("\nUsage: python CS3243_P2_Sudoku_XX.py input.txt output.txt\n") raise ValueError("Wrong number of arguments!") try: f = open(sys.argv[1], 'r') except IOError: print ("\nUsage: python CS3243_P2_Sudoku_XX.py input.txt output.txt\n") raise IOError("Input file not found!") puzzle = [[0 for i in range(9)] for j in range(9)] lines = f.readlines() i, j = 0, 0 for line in lines: for number in line: if '0' <= number <= '9': puzzle[i][j] = int(number) j += 1 if j == 9: i += 1 j = 0 sudoku = Sudoku(puzzle) ans = sudoku.solve() with open(sys.argv[2], 'a') as f: for i in range(9): for j in range(9): f.write(str(ans[i][j]) + " ") f.write("\n")
6dee0f8aff74d29aed5f6384ad958dae27ba3a52
ALaDyn/Smilei
/validation/easi/__init__.py
29,631
3.609375
4
class Display(object): """ Class that contains printing functions with adapted style """ def __init__(self): self.terminal_mode_ = True # terminal properties for custom display try: from os import get_terminal_size self.term_size_ = get_terminal_size() except: self.term_size_ = [0,0]; self.terminal_mode_ = False # Used in a terminal if self.terminal_mode_: self.seperator_length_ = self.term_size_[0]; self.error_header_ = "\033[1;31m" self.error_footer_ = "\033[0m\n" self.positive_header_ = "\033[1;32m" self.positive_footer_ = "\033[0m\n" self.tab_ = " " # Not used in a terminal else: self.seperator_length_ = 80; self.error_header_ = "" self.error_footer_ = "" self.positive_header_ = "" self.positive_footer_ = "" self.tab_ = " " # Seperator self.seperator_ = " " for i in range(self.seperator_length_-1): self.seperator_ += "-" def message(self,txt): print(self.tab_ + txt) def error(self,txt): print(self.error_header_ + self.tab_ + txt + self.error_footer_) def positive(self,txt): print(self.positive_header_ + self.tab_ + txt + self.positive_footer_) def seperator(self): print(self.seperator_) display = Display() class SmileiPath(object): def __init__(self): from os import environ, path, sep from inspect import stack if "self.smilei_path.root" in environ : self.root = environ["self.smilei_path.root"]+sep else: self.root = path.dirname(path.abspath(stack()[0][1]))+sep+".."+sep+".."+sep self.root = path.abspath(self.root)+sep self.benchmarks = self.root+"benchmarks"+sep self.scrips = self.root+"scripts"+sep self.validation = self.root+"validation"+sep self.references = self.validation+"references"+sep self.analyses = self.validation+"analyses"+sep self.workdirs = self.root+"validation"+sep+"workdirs"+sep self.SMILEI_TOOLS_W = self.workdirs+"smilei_tables" self.SMILEI_TOOLS_R = self.root+"smilei_tables" self.COMPILE_ERRORS = self.workdirs+'compilation_errors' self.COMPILE_OUT = self.workdirs+'compilation_out' self.exec_script = 'exec_script.sh' self.exec_script_output = 'exec_script.out' self.output_file = 'smilei_exe.out' class ValidationOptions(object): def __init__(self, **kwargs): # Get general parameters from kwargs self.verbose = kwargs.pop( "verbose" , False ) self.compile_only = kwargs.pop( "compile_only" , False ) self.bench = kwargs.pop( "bench" , "" ) self.omp = kwargs.pop( "omp" , 12 ) self.mpi = kwargs.pop( "mpi" , 4 ) self.nodes = kwargs.pop( "nodes" , 0 ) self.resource_file = kwargs.pop( "resource-file", "" ) self.generate = kwargs.pop( "generate" , False ) self.showdiff = kwargs.pop( "showdiff" , False ) self.nb_restarts = kwargs.pop( "nb_restarts" , 0 ) self.max_time = kwargs.pop( "max_time" , "00:30:00" ) self.compile_mode = kwargs.pop( "compile_mode" , "" ) self.log = kwargs.pop( "log" , "" ) self.partition = kwargs.pop( "partition" , "jollyjumper" ) self.account = kwargs.pop( "account" , "" ) if kwargs: raise Exception(diplay.error("Unknown options for validation: "+", ".join(kwargs))) from numpy import array, sum self.max_time_seconds = sum(array(self.max_time.split(":"),dtype=int)*array([3600,60,1])) def copy(self): v = ValidationOptions() v.__dict__ = self.__dict__.copy() return v def loadReference(references_path, bench_name): import pickle from sys import exit try: try: with open(references_path + bench_name + ".txt", 'rb') as f: return pickle.load(f, fix_imports=True, encoding='latin1') except: with open(references_path + bench_name + ".txt", 'r') as f: return pickle.load(f) except: display.error("Unable to find the reference data for "+bench_name) exit(1) def matchesWithReference(data, expected_data, data_name, precision, error_type="absolute_error"): from numpy import array, double, abs, unravel_index, argmax, all, flatnonzero, isnan # ok if exactly equal (including strings or lists of strings) try: if expected_data == data: return True except: pass # If numbers: try: double_data = array(double(data), ndmin=1) if precision is not None: error = abs( double_data-array(double(expected_data), ndmin=1) ) if error_type == "absolute_error": pass elif error_type == "relative_error": try: error /= double_data if isnan( error ).any(): raise except Exception as e: display.error( "Error in comparing with reference: division by zero (relative error)" ) return False else: print( "Unknown error_type = `"+error_type+"`" ) return False if type(precision) in [int, float]: max_error_location = unravel_index(argmax(error), error.shape) max_error = error[max_error_location] if max_error < precision: return True print("Reference quantity '"+data_name+"' does not match the data (required precision "+str(precision)+")") print("Max error = "+str(max_error)+" at index "+str(max_error_location)) else: try: precision = array(precision) if (error <= precision).all(): return True print("Reference quantity '"+data_name+"' does not match the data") print("Error = ") print(error) print("Precision = ") print(precision) print("Failure at indices "+", ".join([str(a) for a in flatnonzero(error > precision)])) except Exception as e: print( "Error with requested precision (of type %s). Cannot be compared to the data (of type %s)"%(type(precision), type(error)) ) return False else: if all(double_data == double(expected_data)): return True print("Reference quantity '"+data_name+"' does not match the data") except Exception as e: print("Reference quantity '"+data_name+"': unable to compare to data") print( e ) return False _dataNotMatching = False class Validation(object): def __init__(self, **kwargs): # Obtain options self.options = ValidationOptions(**kwargs) # Find smilei folders self.smilei_path = SmileiPath() # Get the current version of Smilei from os import environ from subprocess import check_output self.git_version = check_output( "cd "+self.smilei_path.root+" && echo `git log -n 1 --format=%h`-", shell=True ).decode()[:-1] if 'CI_COMMIT_BRANCH' in environ: self.git_version += environ['CI_COMMIT_BRANCH'] else: self.git_version += check_output("cd "+self.smilei_path.root+" && echo `git rev-parse --abbrev-ref HEAD`", shell=True ).decode()[:-1] # Get the benchmark-specific resources if specified in a file from json import load self.resources = {} if self.options.resource_file: with open(self.options.resource_file, 'r') as f: self.resources = load( f ) if self.options.verbose: print("Found resource file `"+self.options.resource_file+"` including cases:") for k in self.resources: print("\t"+k) print("") # Define commands depending on host from socket import gethostname from .machines import Machine, MachineLLR, MachinePoincare, MachineRuche, MachineIrene self.HOSTNAME = gethostname() if "llrlsi-gw" in self.HOSTNAME: self.machine_class = MachineLLR elif "poincare" in self.HOSTNAME: self.machine_class = MachinePoincare elif "ruche" in self.HOSTNAME: self.machine_class = MachineRuche elif "irene" in self.HOSTNAME: self.machine_class = MachineIrene else: self.machine_class = Machine self.machine = self.machine_class( self.smilei_path, self.options ) # Define sync() import os if hasattr(os, 'sync'): self.sync = os.sync else: import ctypes self.sync = ctypes.CDLL("libc.so.6").sync def compile(self): from sys import exit from os import chdir, sep, stat, remove, rename from os.path import exists from .tools import mkdir, date, date_string from shutil import copy2 from subprocess import CalledProcessError if self.options.verbose: display.seperator() print(" Compiling Smilei") display.seperator() SMILEI_W = self.smilei_path.workdirs + "smilei" SMILEI_R = self.smilei_path.root + "smilei" # Get state of smilei bin in root folder chdir(self.smilei_path.root) STAT_SMILEI_R_OLD = stat(SMILEI_R) if exists(SMILEI_R) else ' ' # CLEAN # If no smilei bin in the workdir, or it is older than the one in smilei directory, # clean to force compilation mkdir(self.smilei_path.workdirs) self.sync() if exists(SMILEI_R) and (not exists(SMILEI_W) or date(SMILEI_W)<date(SMILEI_R)): self.machine.clean() self.sync() def workdir_archiv() : # Creates an archives of the workdir directory exe_path = self.smilei_path.workdirs+"smilei" if exists(exe_path): ARCH_WORKDIR = self.smilei_path.validation+'workdir_'+date_string(exe_path) rename(self.smilei_path.workdirs, ARCH_WORKDIR) mkdir(self.smilei_path.workdirs) try: # Remove the compiling errors files if exists(self.smilei_path.COMPILE_ERRORS): remove(self.smilei_path.COMPILE_ERRORS) # Compile self.machine.compile( self.smilei_path.root ) self.sync() if STAT_SMILEI_R_OLD!=stat(SMILEI_R) or date(SMILEI_W)<date(SMILEI_R): # or date(SMILEI_TOOLS_W)<date(SMILEI_TOOLS_R) : # if new bin, archive the workdir (if it contains a smilei bin) # and create a new one with new smilei and compilation_out inside if exists(SMILEI_W): # and path.exists(SMILEI_TOOLS_W): workdir_archiv() copy2(SMILEI_R, SMILEI_W) #copy2(SMILEI_TOOLS_R,SMILEI_TOOLS_W) if self.options.verbose: print(" Smilei compilation succeed.") else: if self.options.verbose: print(" Smilei compilation not needed.") except CalledProcessError as e: # if compiling errors, archive the workdir (if it contains a smilei bin), # create a new one with compilation_errors inside and exit with error code workdir_archiv() if self.options.verbose: print(" Smilei compilation failed. " + str(e.returncode)) exit(3) if self.options.verbose: print("") def run_all(self): from sys import exit from os import sep, chdir, getcwd from os.path import basename, splitext, exists, isabs from shutil import rmtree from .tools import mkdir, execfile from .log import Log import re, sys # Load the happi module sys.path.insert(0, self.smilei_path.root) import happi self.sync() INITIAL_DIRECTORY = getcwd() global _dataNotMatching _dataNotMatching = False for BENCH in self.list_benchmarks(): SMILEI_BENCH = self.smilei_path.benchmarks + BENCH # Prepare specific resources if requested in a resource file if BENCH in self.resources: options = self.options.copy() for k,v in self.resources[BENCH].items(): setattr(options, k, v) machine = self.machine_class( self.smilei_path, options ) else: options = self.options machine = self.machine # Create the workdir path WORKDIR = self.smilei_path.workdirs + 'wd_'+basename(splitext(BENCH)[0]) + sep mkdir(WORKDIR) WORKDIR += str(options.mpi) + sep mkdir(WORKDIR) WORKDIR += str(options.omp) + sep mkdir(WORKDIR) # If there are restarts, prepare a Checkpoints block in the namelist RESTART_INFO = "" if options.nb_restarts > 0: # Load the namelist namelist = happi.openNamelist(SMILEI_BENCH) niter = namelist.Main.simulation_time / namelist.Main.timestep # If the simulation does not have enough timesteps, change the number of restarts if options.nb_restarts > niter - 4: options.nb_restarts = max(0, niter - 4) if options.verbose: print("Not enough timesteps for restarts. Changed to "+str(options.nb_restarts)+" restarts") if options.nb_restarts > 0: # Find out the optimal dump_step dump_step = int( (niter+3.) / (options.nb_restarts+1) ) # Prepare block if len(namelist.Checkpoints) > 0: RESTART_INFO = (" \"" + "Checkpoints.keep_n_dumps="+str(options.nb_restarts)+";" + "Checkpoints.dump_minutes=0.;" + "Checkpoints.dump_step="+str(dump_step)+";" + "Checkpoints.exit_after_dump=True;" + "Checkpoints.restart_dir=%s;" + "\"" ) else: RESTART_INFO = (" \"Checkpoints(" + " keep_n_dumps="+str(options.nb_restarts)+"," + " dump_minutes=0.," + " dump_step="+str(dump_step)+"," + " exit_after_dump=True," + " restart_dir=%s," + ")\"" ) del namelist # Prepare logging if options.log: log_dir = ("" if isabs(options.log) else INITIAL_DIRECTORY + sep) + options.log + sep log = Log(log_dir, log_dir + BENCH + ".log") # Loop restarts for irestart in range(options.nb_restarts+1): RESTART_WORKDIR = WORKDIR + "restart%03d"%irestart + sep execution = True if not exists(RESTART_WORKDIR): mkdir(RESTART_WORKDIR) elif options.generate: execution = False chdir(RESTART_WORKDIR) # Copy of the databases # For the cases that need a database # if BENCH in [ # "tst1d_09_rad_electron_laser_collision.py", # "tst1d_10_pair_electron_laser_collision.py", # "tst2d_08_synchrotron_chi1.py", # "tst2d_09_synchrotron_chi0.1.py", # "tst2d_v_09_synchrotron_chi0.1.py", # "tst2d_v_10_multiphoton_Breit_Wheeler.py", # "tst2d_10_multiphoton_Breit_Wheeler.py", # "tst2d_15_qed_cascade_particle_merging.py", # "tst3d_15_magnetic_shower_particle_merging.py" # ]: # try : # # Copy the database # check_call(['cp '+SMILEI_DATABASE+'/*.h5 '+RESTART_WORKDIR], shell=True) # except CalledProcessError: # if options.verbose : # print( "Execution failed to copy databases in ",RESTART_WORKDIR) # sys.exit(2) # If there are restarts, adds the Checkpoints block arguments = SMILEI_BENCH if options.nb_restarts > 0: if irestart == 0: RESTART_DIR = "None" else: RESTART_DIR = "'"+WORKDIR+("restart%03d"%(irestart-1))+sep+"'" arguments += RESTART_INFO % RESTART_DIR # Run smilei if execution: if options.verbose: print("") display.seperator() print(" Running " + BENCH + " on " + self.HOSTNAME) print(" Resources: " + str(options.mpi) + " MPI processes x " + str(options.omp) +" openMP threads on " + str(options.nodes) + " nodes" + ( " (overridden by --resource-file)" if BENCH in self.resources else "" )) if options.nb_restarts > 0: print(" Restart #" + str(irestart)) display.seperator() machine.run( arguments, RESTART_WORKDIR ) self.sync() # Check the output for errors errors = [] search_error = re.compile('error', re.IGNORECASE) with open(self.smilei_path.output_file,"r") as fout: errors = [line for line in fout if search_error.search(line)] if errors: if options.verbose: print("") display.error(" Errors appeared while running the simulation:") display.seperator() for error in errors: print(error) exit(2) # Scan some info for logging if options.log: log.scan(self.smilei_path.output_file) # Append info in log file if options.log: log.append(self.git_version) # Find the validation script for this bench validation_script = self.smilei_path.analyses + "validate_" + BENCH if options.verbose: print("") if not exists(validation_script): display.error(" Unable to find the validation script "+validation_script) exit(1) chdir(WORKDIR) # If required, generate the references if options.generate: if options.verbose: display.seperator() print( ' Generating reference for '+BENCH) display.seperator() Validate = self.CreateReference(self.smilei_path.references, BENCH) execfile(validation_script, {"Validate":Validate}) Validate.write() # Or plot differences with respect to existing references elif options.showdiff: if options.verbose: display.seperator() print( ' Viewing differences for '+BENCH) display.seperator() Validate = self.ShowDiffWithReference(self.smilei_path.references, BENCH) execfile(validation_script, {"Validate":Validate}) if _dataNotMatching: display.error(" Benchmark "+BENCH+" did NOT pass") # Otherwise, compare to the existing references else: if options.verbose: display.seperator() print( ' Validating '+BENCH) display.seperator() Validate = self.CompareToReference(self.smilei_path.references, BENCH) execfile(validation_script, {"Validate":Validate}) if _dataNotMatching: break # Clean workdirs, goes here only if succeeded chdir(self.smilei_path.workdirs) rmtree(WORKDIR, True) if options.verbose: print( "") chdir(INITIAL_DIRECTORY) if _dataNotMatching: display.error( "Errors detected") exit(1) else: display.positive( "Everything passed") def list_benchmarks(self): from os.path import basename from glob import glob # Build the list of the requested input files list_validation = [basename(b) for b in glob(self.smilei_path.analyses+"validate_tst*py")] if self.options.bench == "": benchmarks = [basename(b) for b in glob(self.smilei_path.benchmarks+"tst*py")] else: benchmarks = glob( self.smilei_path.benchmarks + self.options.bench ) benchmarks = [b.replace(self.smilei_path.benchmarks,'') for b in benchmarks] benchmarks = [b for b in benchmarks if "validate_"+b in list_validation] if not benchmarks: raise Exception(display.error("Input file(s) "+self.options.bench+" not found, or without validation file")) if self.options.verbose: print("") print(" The list of input files to be validated is:\n\t"+"\n\t".join(benchmarks)) print("") return benchmarks # DEFINE A CLASS TO CREATE A REFERENCE class CreateReference(object): def __init__(self, references_path, bench_name): self.reference_file = references_path+bench_name+".txt" self.data = {} def __call__(self, data_name, data, precision=None, error_type="absolute_error"): self.data[data_name] = data def write(self): import pickle from os.path import getsize from os import remove with open(self.reference_file, "wb") as f: pickle.dump(self.data, f) size = getsize(self.reference_file) if size > 1000000: print("Reference file is too large ("+str(size)+"B) - suppressing ...") remove(self.reference_file) print("Created reference file "+self.reference_file) # DEFINE A CLASS TO COMPARE A SIMULATION TO A REFERENCE class CompareToReference(object): def __init__(self, references_path, bench_name): self.ref_data = loadReference(references_path, bench_name) def __call__(self, data_name, data, precision=None, error_type="absolute_error"): global _dataNotMatching from sys import exit # verify the name is in the reference if data_name not in self.ref_data.keys(): print(" Reference quantity '"+data_name+"' not found") _dataNotMatching = True return expected_data = self.ref_data[data_name] if not matchesWithReference(data, expected_data, data_name, precision, error_type): print(" Reference data:") print(expected_data) print(" New data:") print(data) print("") _dataNotMatching = True # DEFINE A CLASS TO VIEW DIFFERENCES BETWEEN A SIMULATION AND A REFERENCE class ShowDiffWithReference(object): def __init__(self, references_path, bench_name): self.ref_data = loadReference(references_path, bench_name) def __call__(self, data_name, data, precision=None, error_type="absolute_error"): global _dataNotMatching import matplotlib.pyplot as plt from numpy import array plt.ion() print(" Showing differences about '"+data_name+"'") display.seperator() # verify the name is in the reference if data_name not in self.ref_data.keys(): print("\tReference quantity not found") expected_data = None else: expected_data = self.ref_data[data_name] print_data = False # First, check whether the data matches if not matchesWithReference(data, expected_data, data_name, precision, error_type): _dataNotMatching = True # try to convert to array try: data_float = array(data, dtype=float) expected_data_float = array(expected_data, dtype=float) # Otherwise, simply print the result except: print("\tQuantity cannot be plotted") print_data = True data_float = None # Manage array plotting if data_float is not None: if expected_data is not None and data_float.shape != expected_data_float.shape: print("\tReference and new data do not have the same shape: "+str(expected_data_float.shape)+" vs. "+str(data_float.shape)) if expected_data is not None and data_float.ndim != expected_data_float.ndim: print("\tReference and new data do not have the same dimension: "+str(expected_data_float.ndim)+" vs. "+str(data_float.ndim)) print_data = True elif data_float.size == 0: print("\t0D quantity cannot be plotted") print_data = True elif data_float.ndim == 1: nplots = 2 if expected_data is None or data_float.shape != expected_data_float.shape: nplots = 1 fig = plt.figure() fig.suptitle(data_name) print("\tPlotting in figure "+str(fig.number)) ax1 = fig.add_subplot(nplots,1,1) ax1.plot( data_float, label="new data" ) ax1.plot( expected_data_float, label="reference data" ) ax1.legend() if nplots == 2: ax2 = fig.add_subplot(nplots,1,2) ax2.plot( data_float-expected_data_float ) ax2.set_title("difference") elif data_float.ndim == 2: nplots = 3 if expected_data is None: nplots = 1 elif data_float.shape != expected_data_float.shape: nplots = 2 fig = plt.figure() fig.suptitle(data_name) print("\tPlotting in figure "+str(fig.number)) ax1 = fig.add_subplot(1,nplots,1) im = ax1.imshow( data_float ) ax1.set_title("new data") plt.colorbar(im) if nplots > 1: ax2 = fig.add_subplot(1,nplots,2) im = ax2.imshow( expected_data_float ) ax2.set_title("reference data") plt.colorbar( im ) if nplots > 2: ax3 = fig.add_subplot(1,nplots,nplots) im = ax3.imshow( data_float-expected_data_float ) ax3.set_title("difference") plt.colorbar( im ) plt.draw() plt.show() else: print("\t"+str(data_float.ndim)+"D quantity cannot be plotted") print_data = True # Print data if necessary if print_data: if expected_data is not None: print("\tReference data:") print(expected_data) print("\tNew data:") print(data)
272f71dcc72f166a4bf938c7d24c2fcfc156fef3
amshapriyaramadass/learnings
/Hackerrank/numpy/array.py
250
3.609375
4
import numpy as np def arrays(arr): # complete this function # use numpy.array a = np.array(arr,dtype='f') return(a[::-1]) if __name__ =="__main__": arr = input().strip().split(' ') result = arrays(arr) print(result)
14c8a6e8dbdb673d146e92f1d3812523ce1b556f
amshapriyaramadass/learnings
/Python/Exercise Files/Ch2/classes_start.py
565
3.96875
4
# # Example file for working with classes # class myWheels(): def wheel1(self): print("wheel is alloy") def wheel2(self,SomeString): print("this is steel rim" + SomeString) class myCar(myWheels): def wheel1(self): myWheels.wheel1(self) print("this is car wheel dia 30inch") def wheel2(self,someString): print("this is car wheel2 uses alloy rim") def main(): c = myWheels() c.wheel1() c.wheel2("this is back wheel") c1 =myCar() c1.wheel1() c1.wheel2("this is car wheel") if __name__ == "__main__": main()
dc66d84ad39fb2fe87895ca376652e9d95781326
amshapriyaramadass/learnings
/Hackerrank/Interviewkit/counting_valley.py
789
4.25
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'countingValleys' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER steps # 2. STRING path #Sample Input # #8 #UDDDUDUU #Sample Output #1 # def countingValleys(steps, path): sealevel = 0 valeylevel = 0 for path1 in path: if path1 == 'U': sealevel += 1 else: sealevel -= 1 if path1 == 'U' and sealevel == 0: valeylevel += 1 return valeylevel # Write your code here if __name__ == '__main__': steps = int(input().strip()) path = input() result = countingValleys(steps, path) print(result)
b003a3afa4758e8696090f05bdba608f5ea5f10b
mazalkov/Python-Principles-Solutions
/Online status.py
278
3.625
4
# https://pythonprinciples.com/challenges/Online-status/ def online_count(dictionary): number_online = 0 for i, (key, value) in enumerate(dictionary.items()): if value == 'online': number_online += 1 return number_online
d8fa7c098496d84e58e0a49577c7c866f1f60f2c
flyfish1029/pythontest
/studytext/while_mj.py
235
4
4
#-*- coding: UTF-8 -*- numbers = [12,37,5,42,8,3] event = [] odd = [] while len(numbers)>0: number = numbers.pop() if(number % 2 == 0): event.append(number) else: odd.append(number) print(event) print(odd)
de5d15d0b7c4c9c8e4113c2abaf3463af7a368af
andremourato/travian_bot
/utils.py
256
3.59375
4
from datetime import datetime, timedelta def add_seconds_to_datetime_now(seconds): """Add seconds to current timestamp and return it.""" future_date = datetime.now() + timedelta(seconds=seconds) return future_date.strftime('%H:%M %d-%m-%Y')
b51bed97a9cb40110ca0d7a897f4e2d27b1e1d5e
bobosod/From_0_learnPython
/chapter4_2.py
226
3.921875
4
list = ["apple", "banana", "grape", "orange", "grape"] print(list) print(list[2]) list.append("watermelon") list.insert(1,"grapefruit") print(list) list.remove("grape") print(list) print(range(len(list))) help(list)
e634301ac092a01c6cfc61fcd9215d66f65d4deb
tutorials-4newbies/testing101
/test_phone_validator.py
1,088
3.5625
4
import unittest from lib import CellPhoneValidator # This is the spec! class PhoneValidatorTestCase(unittest.TestCase): def test_phone_validator_regular_number(self): value = "0546734469" expected_true_result = CellPhoneValidator(value).is_valid() self.assertTrue(expected_true_result) false_value = "aaaaa" expected_false_result = CellPhoneValidator(false_value).is_valid() self.assertFalse(expected_false_result) def test_cell_phone_valid_prefix(self): value = "0554446666" expected_true_result = CellPhoneValidator(value).is_valid() self.assertTrue(expected_true_result) false_value = "0114446666" expected_false_result = CellPhoneValidator(false_value).is_valid() self.assertFalse(expected_false_result) def test_cell_phone_prefix_without_zero(self): pass def test_cell_phone_has_legal_number_of_numbers(self): pass def test_cell_phone_number_can_contain_spaces_and_dashes(self): pass if __name__ == '__main__': unittest.main()
543832a8bac0de76fc71f18de41e352d2893860f
basseld21-meet/meet2019y1lab3
/debugging.py
965
3.5
4
Python 3.6.8 (default, Jan 14 2019, 11:02:34) [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux Type "help", "copyright", "credits" or "license()" for more information. >>> ##In order complete this challenge you need to debug the following code. ##It may be easier to do so if you improve the code quality. ##copy and paste this code into a new file named “debugging.py” import tutle # imports the turtle library yp7 = turtle.clone() #this creates a new turtle and stores it in a variable t = 200 b = -200 #draw the letter ‘A’ turtle.hideturtle() # this hides the arrow of the turtle called turtle yp7.pendown() yp7.goto(-1000,0) yp7.penup() a,c = yp7.pos() yp7.goto(a,c) yp7.pendown() yp7.goto(a+100, c+300) yp7.goto(a+200, c) yp7.goto(a+30, c+100) yp7.goto(a+300, c+100) turtle.manloop() # all turtle commands must go before this line!!! SyntaxError: multiple statements found while compiling a single statement >>>
f834c6ebc4442b3e4c945003704b4ec15f353289
lin-compchem/qmmm_neuralnets
/qmmm_neuralnets/input/filter.py
3,268
3.53125
4
""" This file contains methods for selecting feature from input vectors """ import numpy as np def do_pca(bfs, n_components): """ This is the code from my PCA experiment. Should do again and report results in the manual Params ------ bfs: list of ndarrays The basis function arrays ncomponents: The number of principal components to keep Returns ------- pca_models: list List of scikit-learn PCA models, required for back transformation Notes ----- TODO: check this """ from sklearn.decomposition import PCA pca_models = [] for bf in bfs: pca = PCA(n_components=n_components, svd_solver='full') pca.fit(bf) pca_models.append(pca) return pca_models def arbitrary_from_full_bpsf(h_rad, o_rad, h_ang, o_ang, h_radg=None, o_radg=None, h_angg=None, o_angg=None): """ This method arbitrarily selects features from input vectors. The method is described in the example notebook: TODO This is kept here because it works well enough. The basis vectors must be the size of the tests in the FortBPSF package. Parameters ---------- h_rad: ndarray of Nx48 h_ang: ndarray of Nx36 o_rad: ndarray of Nx48 o_ang: ndarray of Nx54 Returns ------- hbf: ndarray obf: ndarray """ grads = False assert h_rad.shape[1] == 48 assert o_rad.shape[1] == 48 assert h_ang.shape[1] == 36 assert o_ang.shape[1] == 54 if h_radg or o_radg or h_angg or o_angg: assert h_radg != 0 assert o_radg != 0 assert h_angg != 0 assert o_angg != 0 grads = True h_rx = [0, 24, 2, 25] h_ax = [1, 3, 7, 9, 19, 21, 23, 25, 27, 29, 31, 33] o_rx = [24, 25, 26, 0, 1, 2] o_ax = [23, 27, 36, 37, 38, 39, 42, 43, 44, 45, 48, 49, 50] hbf = np.float32(np.concatenate((np.delete(h_rad, h_rx, axis=1), np.delete(h_ang, h_ax, axis=1)), axis=1)) obf = np.float32(np.concatenate((np.delete(o_rad, o_rx, axis=1), np.delete(o_ang, o_ax, axis=1)), axis=1)) if grads: hg = np.float32(np.concatenate( (np.delete(h_radg, h_rx, axis=1), np.delete(h_radg, h_ax, axis=1)), axis=1)) og = np.float32(np.concatenate( (np.delete(o_radg, o_rx, axis=1), np.delete(o_radg, o_ax, axis=1)), axis=1)) h_rx = np.concatenate((np.arange(11, 22, 1), np.arange(31, 44, 1), (45, 46, 49, 50, 59, 60, 61, 62, 63, 64,65, 66, 67))) hbf = np.delete(hbf, h_rx, axis=1) if grads: hg = np.delete(hg, h_rx, axis=1) h_rx = (22, 23, 26, 28, 27) hbf = np.delete(hbf, h_rx, axis=1) if grads: hg = np.delete(hg, h_rx, axis=1) o_rx = np.concatenate((np.arange(9,21), np.arange(28,42), np.arange(43, 60, 2), np.asarray((62, 63, 67, 71, 73, 76, 77, 78, 79, 80, 81, 82)))) obf = np.delete(obf, o_rx, axis=1) if grads: og = np.delete(og, o_rx, axis=1) o_rx = [17, 19, 20, 21, 22, 23, 24, 25,29,31] obf = np.delete(obf, o_rx, axis=1) if grads: og = np.delete(og, o_rx, axis=1) if grads: return hbf, obf, hg, og return hbf, obf
795d5db9f77b07f2680468da5694dfd8c37bf234
klinok9/learning_python
/Глава4.py
1,361
3.53125
4
# char = ['w', 'a', 's', 'i', 't', 'a', 'r'] # out = '' # length = len(char) # i = 0 # while (i< length): # out = out +char[i] # i= i+1 # length = length * -1 # i=-2 # while (i >= length): # out = out + char[i] # i = i-1 # print(out) # smothies = [1,2,3,4,5] # length = len(smothies) # for i in range(length): # print(i,smothies[i]) scores = [11, 20, 3, 4, 50, 20, 22, 60, 55, 22, 60] # создаю список costs = [.1, .20, .3, .4, .50, .20, .22, .60, .55, .22, .60] high_score = 0 # создаю пустую перемен best_sol = [] # создаю пустой список length = len(scores) # узнаю длину списка cost = 100.0 most_effective = 0 for i in range(length): # перебор списка print('раствор №', i, 'результат', scores[i]) if scores[i] > high_score: # определение наиб значения high_score = scores[i] for i in range(length): if high_score == scores[i]: best_sol.append(i) for i in range(length): if scores[i] == high_score and costs[i]<cost: most_effective = i cost = costs[i] print('всего тестов', length) print('макс значение', high_score) print('растворы с наиб результатом', best_sol) print('самый лучший раствор', most_effective)
ee3ec39130ee54a0cfa72eb81d158a027840f222
anuriq/parallels-fibonacci
/src/fibonacci.py
182
4.1875
4
def fibonacci_number(n): n = int(n) if n == 1 or n == 2: return 1 else: result = fibonacci_number(n - 1) + fibonacci_number(n - 2) return result
35775689bab1469a42bae842e38963842bf54016
scottherold/python_refresher_8
/ExceptionHandling/examples.py
731
4.21875
4
# practice with exceptions # user input for testing num = int(input("Please enter a number ")) # example of recursion error def factorial(n): # n! can also be defined as n * (n-1)! """ Calculates n! recursively """ if n <= 1: return 1 else: return n * factorial(n-1) # try/except (if you know the errortype) # it's best to be explicit about exceptions that you are handling and it # is good practice to have different try/except blocks for multiple # potential exceptions try: print(factorial(num)) # example of multiple exceptions handling simultaneously) except (RecursionError, OverflowError): print("This program cannot calculate factorials that large") print("Program terminating")
293770c85b55ca8be91305a5d6a005962dddee4a
CelvinBraun/human_life_py
/life_turtle.py
1,217
3.6875
4
from turtle import Turtle START_X_CORR = -450 START_Y_CORR = 220 STEPS = 8 SIZE = 0.3 class Life: def __init__(self, age, years): self.start_x = START_X_CORR self.start_y = START_Y_CORR self.steps = STEPS self.size = SIZE self.weeks = round(years * 52.1786) self.age = age self.week_list = [] self.create_weeks() self.fill_weeks() def create_weeks(self): x_cor = self.start_x y_cor = self.start_y for week in range(self.weeks): new_week = Turtle() new_week.hideturtle() new_week.speed("fastest") new_week.shapesize(self.size) new_week.shape("square") new_week.fillcolor("white") new_week.penup() y_cor -= self.steps if week % 55 == 0: y_cor = self.start_y x_cor += self.steps new_week.goto(x_cor, y_cor) new_week.showturtle() self.week_list.append(new_week) def fill_weeks(self): for week in range(self.age): self.week_list[week].fillcolor("black") self.week_list[self.age-1].fillcolor("red")
a4721adc85bf2e62d8cd37cf97f1dc2ef9e4ffff
inaju/thoughtsapi
/test_api.py
2,010
3.578125
4
import requests class TestApi: def __init__(self): self.user_url = "http://127.0.0.1:8000/auth/" self.user_profile_url = "http://127.0.0.1:8000/auth/users/" self.user_profile_data = "http://127.0.0.1:8000/api/accounts/" self.user_data = { 'username': 'ibrahim', 'password': 'adminmaster' } def create_user(self): "This is for creating the user" response = requests.post(self.user_url+"users/", data=self.user_data) return self.get_jwt_token(), print(response.json(), response.status_code, " Create User") def get_jwt_token(self): """This is the same as logging in, jwt creates a token for you, you send that token to self.check_user, this brings out the user's details that you can query that means, with those details you can only show that specific data to the user""" response = requests.post(self.user_url+"jwt/create/", data=self.user_data) return self.check_user(response.json()['access']), print(response.json(), response.status_code, "Get Token") def check_user(self, token): """ This brings out the data for the querying """ headers = { 'Authorization': "Bearer "+str(token) } response = requests.get(self.user_profile_url+"me/", headers=headers) return self.user_profile(str(response.json()['id']), headers), self.all_profiles(headers), print(response.json(), response.status_code, "check user") def user_profile(self, id, headers): response = requests.get(self.user_profile_data+"profile/"+str(1)+"/", headers=headers) return print(response.json(), response.status_code, "user profile") def all_profiles(self, headers): response = requests.get(self.user_profile_data+"all-profiles",headers=headers) return print(response.json(), response.status_code, "all profiles") testing = TestApi() testing.get_jwt_token()
5548acf94dcf476343655ef2947fb9b6d5e5968c
Philippe-Boddaert/Philippe-Boddaert.github.io
/premiere/bloc1/chapitre-06/corrige.py
6,984
3.8125
4
#!/usr/bin/env python3 # Author : Philippe BODDAERT # Date : 19/12/2020 # License : CC-BY-NC-SA from enquete import Enquete def est_anagramme(mot1, mot2): ''' Indique si 2 mots sont anagrammes l'un de l'autre ;param mot1: (str) un mot :param mot2: (str) un mot ;return: (bool) True si les 2 mots sont anagrammes, False sinon :doctest: >>> est_anagramme('set', 'tes') True >>> est_anagramme('se', 'te') False ''' return sorted(mot1) == sorted(mot2) def est_anaphrase(phrase): ''' Indique si une phrase est une anaphrase, i.e contenant des anagrammes :param phrase: (str) une phrase :return: (bool) True si la phrase contient au moins un anagramme, False sinon :doctest: >>> est_anaphrase('le catcheur charcute son adversaire') True >>> est_anaphrase('les problèmes de gnosie ça se soigne') True >>> est_anaphrase('Claudel, voilà une chose qui me fait bien prier') False ''' resultat = False mots = phrase.split(' ') for i in range(len(mots) - 1): for j in range(i + 1, len(mots)): if est_anagramme(mots[i], mots[j]): resultat = True return resultat def est_lipogramme(phrase, lettre): ''' Indique si le mot est un lipogramme,i.e la lettre est exclue du mot :param phrase: (str) un mot :param lettre: (str) une lettre :doctest: >>> est_lipogramme('Là où nous vivions jadis', 'e') True >>> est_lipogramme('Là où nous vivions jadis', 'a') False >>> est_lipogramme('Son cœur est encore exempt de trouble et nul homme ne lui semble mériter ni distinction ni préférence', 'a') True ''' return lettre not in phrase def est_pangramme(phrase): ''' Indique si la chaine est un pangramme,i.e contient toutes les letres de l'alphabet :param phrase: (str) une phrase :return: (bool) True si la phrase est un pangramme, False sinon :doctest: >>> est_pangramme("Portez ce vieux whisky au juge blond qui fume") True >>> est_pangramme("Voyez le brick géant que j'examine près du wharf") True >>> est_pangramme("cette phrase est-elle un pangramme ?") False ''' alphabet = 'abcdefghijklmnopqrstuvwxyz' lettres = set() for lettre in phrase: lettres.add(lettre.lower()) nombre = 0 for lettre in lettres: if lettre in alphabet: nombre += 1 return nombre == len(alphabet) def est_palindrome(phrase): ''' Indique si le mot est un palindrome, i.e peut se lire dans les 2 sens :param phrase: (str) une phrase :return: (bool) True si la phrase est un palindrome, False sinon ;doctest: >>> est_palindrome('lol') True >>> est_palindrome('kayak') True >>> est_palindrome('été') True >>> est_palindrome('Caserne, genre sac') True >>> est_palindrome('palindrome') False ''' minuscule = phrase.replace(' ', '').replace("'",'').replace(',','').lower() debut = 0 fin = len(minuscule) - 1 while debut < fin and minuscule[debut] == minuscule[fin]: debut += 1 fin -= 1 return debut >= fin def est_tautogramme(phrase): ''' Indique si la phrase est un tautogramme, i.e dont tous les mots commencent par la même lettre :param phrase: (str) une phrase :return: (bool) True si tous les mots de la phrase commencent par la même lettre, False sinon :doctest: >>> est_tautogramme('Veni vidi Vici') True >>> est_tautogramme('Bonjour ami lycéen') False ''' mots = phrase.lower().split(' ') premier_mot = mots[0] premiere_lettre = premier_mot[0] i = 1 while i < len(mots) and mots[i][0] == premiere_lettre: i += 1 return i == len(mots) def est_monoconsonnantisme(phrase, consonne): ''' Indique si la phrase est un monoconsonnantisme, i.e qu'elle utilise une seule consonne :param phrase: (str) une phrase :param consonne: (str) la consonne :return: (bool) True si une seule consonne est utilisée, False sinon :doctest: >>> est_monoconsonnantisme('Nian-nian', 'n') True >>> est_monoconsonnantisme('gnangnan', 'n') False >>> est_monoconsonnantisme('Gag gogo', 'g') True ''' consonnes = 'bcdfghjklmnpqrstvwxz' for lettre in phrase: minuscule = lettre.lower() if minuscule in consonnes and consonne != minuscule: return False return True def est_surdefinition(phrase, mot): ''' Indique si la phrase est une surdéfinition, i.e que la phrase contient le mot qu'elle définit :param phrase: (str) une phrase :param mot: (str) le mot défini :return: (bool) True si la phrase est une surdéfinition, False sinon :doctest: >>> est_surdefinition("un proche qui fait partie de la famille", 'ami') True >>> est_surdefinition("limite de l'infini", 'Fini') True >>> est_surdefinition("définition qui ne contient pas le mot", 'eRReur') False ''' return mot.lower() in phrase.lower() # Partie preuve print("La pièce 0 est un tautogramme : ", est_tautogramme(Enquete.obtenir_piece(0))) print("La pièce 1 est un tautogramme : ", est_tautogramme(Enquete.obtenir_piece(1))) print("La pièce 2 est un lipogramme en 'a' : ", est_lipogramme(Enquete.obtenir_piece(2), 'a')) print("La pièce 4 est un lipogramme en 'e' : ", est_lipogramme(Enquete.obtenir_piece(4), 'e')) print("La pièce 5 est un lipogramme en 'a' : ", est_lipogramme(Enquete.obtenir_piece(5), 'a')) print("La pièce 6 est un lipogramme en 'u' : ", est_lipogramme(Enquete.obtenir_piece(6), 'u')) print("La pièce 7 est un monoconsonnantisme en 'm' : ", est_monoconsonnantisme(Enquete.obtenir_piece(7), 'm')) print("La pièce 8 est un monoconsonnantisme en 't' : ", est_monoconsonnantisme(Enquete.obtenir_piece(8), 't')) print("La pièce 9 est une surdéfinition d'abri : ", est_surdefinition(Enquete.obtenir_piece(9), 'abri')) print("La pièce 10 est une surdéfinition d'émoi : ", est_surdefinition(Enquete.obtenir_piece(10), 'émoi')) print("La pièce 11 est une surdéfinition de leçon : ", est_surdefinition(Enquete.obtenir_piece(11), 'leçon')) print("La pièce 12 est un pangramme : ", est_pangramme(Enquete.obtenir_piece(12))) print("La pièce 13 est un pangramme : ", est_pangramme(Enquete.obtenir_piece(13))) print("La pièce 14 est un lipogramme en 'e' : ", est_lipogramme(Enquete.obtenir_piece(14), 'e')) print("La pièce 15 est un lipogramme en 'i' : ", est_lipogramme(Enquete.obtenir_piece(15), 'i')) print("La pièce 16 est un palindrome : ", est_palindrome(Enquete.obtenir_piece(16))) print("La pièce 17 est un palindrome : ", est_palindrome(Enquete.obtenir_piece(17))) if __name__ == '__main__': import doctest doctest.testmod()
5d11169ca662b27c93169fe9c48338b339ed9f33
Allykazam/algorithms_tools
/list_manip.py
678
4.03125
4
def oddNumbers(l, r): # Write your code here odd_arr = [] for num in range(l, r + 1): if num % 2 != 0: #even numbers would be == instead of != odd_arr.append(num) return odd_arr print(oddNumbers(0, 12)) def rotLeft(a, d): for _ in range (d): front_val = a.pop(0) a.append(front_val) return a array = [1, 2, 3, 4, 5] new_array = rotLeft(array, 2) print(new_array) def rotRight(a, d): print("I hve",a) for _ in range(d): back_val = a.pop() print(back_val) a.insert(0, back_val) return a new_array_2 = rotRight(array, 2) print(new_array_2) #should be back to the original array
7106bb0336835310ea40ecaf3cd4a29f1f231269
HemlockBane/simple-banking-system
/card_db.py
3,360
3.5
4
import sqlite3 as sq3 class Db: def __init__(self): self.table_name = "card" self.db_name = "card.s3db" self.connection = self.init_db() def init_db(self): create_table_query = f'''create table if not exists {self.table_name} ( id INTEGER PRIMARY KEY AUTOINCREMENT, number TEXT, pin TEXT, balance INTEGER DEFAULT 0 );''' db_connection = sq3.connect(self.db_name) db_cursor = db_connection.cursor() db_cursor.execute(create_table_query) return db_connection def get_all_card_details(self): select_all_query = f'''select * from {self.table_name};''' db_cursor = self.connection.cursor() db_cursor.execute(select_all_query) rows = db_cursor.fetchall() print(rows) def save_card_details(self, card_num, pin): insert_value_query = f''' insert into {self.table_name} (number, pin) values (?,?);''' db_cursor = self.connection.cursor() db_cursor.execute(insert_value_query, [card_num, pin]) self.connection.commit() return int(db_cursor.lastrowid) def get_card_details(self, card_num, pin): select_user_query = f'''select id from {self.table_name} where number = ? and pin = ?;''' db_cursor = self.connection.cursor() db_cursor.execute(select_user_query, [card_num, pin]) rows = db_cursor.fetchall() return rows def check_if_card_exists(self, card_num): select_user_query = f'''select id from {self.table_name} where number = ?;''' db_cursor = self.connection.cursor() db_cursor.execute(select_user_query, [card_num]) rows = db_cursor.fetchall() return rows def get_account_balance(self, card_id): select_user_balance_query = f'''select balance from {self.table_name} where id = ?;''' db_cursor = self.connection.cursor() db_cursor.execute(select_user_balance_query, [card_id]) rows = db_cursor.fetchall() return rows[0] if len(rows) != 0 else () def delete_card_details(self, card_id): delete_card_query = f'''delete from {self.table_name} where id = ?''' db_cursor = self.connection.cursor() db_cursor.execute(delete_card_query, [card_id]) self.connection.commit() def increase_account_balance(self, amount, card_id): update_value_query = f'''update {self.table_name} set balance = balance + ? where id = ?''' db_cursor = self.connection.cursor() db_cursor.execute(update_value_query, [amount, card_id]) self.connection.commit() def decrease_account_balance(self, amount, card_id): update_value_query = f'''update {self.table_name} set balance = balance - ? where id = ?''' db_cursor = self.connection.cursor() db_cursor.execute(update_value_query, [amount, card_id]) self.connection.commit() def close(self): self.connection.close()
52c84ab4101801d394c4c8ee1dc3621e54b8285c
Reyes2777/100_days_code
/python_class/exercise_1.py
515
4.15625
4
#Write a Python program to convert an integer to a roman numeral. class Numbers: def int_to_roman(self, number_i): value = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] roman_numbers = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] roman_num = [] for i in range(len(value)): count = int(number_i / value[i]) roman_num.append(roman_num[i]*count) number_i = number_i - count return ''.join(roman_num)
13578b6a7bdcfe4fede9f52f79b48f5044285299
Alessandro100/x-puzzle-solver
/xpuzzle.py
7,651
3.640625
4
class XPuzzle: #sample input: 1 0 3 7 5 2 6 4 def __init__(self, rows, cols, input): self.rows = rows self.cols = cols self.arr = [] # we keep track of the 0 position to increase the performance of our algorithm self.zero_position = (0,0) #row, column self.__initialize_data_strcuture(input) # takes the input and formats it to the wanted data structure def __initialize_data_strcuture(self, input): input_arr = input.split(" ") count = 0 for i in range(self.rows): row = [] for j in range(self.cols): value = input_arr[count] if(value == '0'): self.zero_position = (i,j) row.append(value) count += 1 self.arr.append(row) # prints the data structure in a nice format for the console def pretty_print_array(self): for row in self.arr: print(*row) def find_valid_moves(self): valid_moves = [] if (self.zero_position[0] != 0): valid_moves.append('up') if (self.zero_position[0] != self.rows - 1): valid_moves.append('down') if (self.zero_position[1] != 0): valid_moves.append('left') if (self.zero_position[1] != self.cols - 1): valid_moves.append('right') if (self.zero_position[0] == 0 and self.zero_position[1] == 0): valid_moves.append('top_left_wrap') valid_moves.append('top_left_diagonal_wrap') valid_moves.append('top_left_diagonal_adjacent') elif (self.zero_position[0] == 0 and self.zero_position[1] == (self.cols - 1)): valid_moves.append('top_right_wrap') valid_moves.append('top_right_diagonal_wrap') valid_moves.append('top_right_diagonal_adjacent') elif (self.zero_position[0] == (self.rows - 1) and self.zero_position[1] == 0): valid_moves.append('bottom_left_wrap') valid_moves.append('bottom_left_diagonal_wrap') valid_moves.append('bottom_left_diagonal_adjacent') elif (self.zero_position[0] == (self.rows - 1) and self.zero_position[1] == (self.cols - 1)): valid_moves.append('bottom_right_wrap') valid_moves.append('bottom_right_diagonal_wrap') valid_moves.append('bottom_right_diagonal_adjacent') return valid_moves # moves the empty tile: up, down, left, right and will print invalid if the move is not correct while returning -1 def regular_move(self, move_direction_of_empty_tile): zero_row = self.zero_position[0] zero_col = self.zero_position[1] is_up_move_valid = (move_direction_of_empty_tile == 'up' and self.zero_position[0] != 0) is_down_move_valid = (move_direction_of_empty_tile == 'down' and self.zero_position[0] != self.rows - 1) is_right_move_valid = (move_direction_of_empty_tile == 'right' and self.zero_position[1] != self.cols - 1) is_left_move_valid = (move_direction_of_empty_tile == 'left' and self.zero_position[1] != 0) if(is_up_move_valid): return self.__swap(zero_row - 1, zero_col) if(is_down_move_valid): return self.__swap(zero_row + 1, zero_col) if(is_right_move_valid): return self.__swap(zero_row, zero_col + 1) if(is_left_move_valid): return self.__swap(zero_row, zero_col - 1) return -1 # takes care of the swapping logic and handles new zero position def __swap(self, row_swap, col_swap): value_swap = self.arr[row_swap][col_swap] self.arr[self.zero_position[0]][self.zero_position[1]] = value_swap self.arr[row_swap][col_swap] = 0 self.zero_position = (row_swap, col_swap) return 0 # wrapping move will auto detect if possible and will do it if it is def wrapping_move(self, column = False): if(column and self.rows > 2): return self.__wrapping_move_with_column() diagonal_info = self.__corner_position_information() if(diagonal_info['is_zero_top_left']): return self.__swap(0, self.cols - 1) if(diagonal_info['is_zero_top_right']): return self.__swap(0, 0) if(diagonal_info['is_zero_bottom_left']): return self.__swap(self.rows - 1, self.cols - 1) if(diagonal_info['is_zero_bottom_right']): return self.__swap(self.rows - 1, 0) return -1 # This is only possible if requested and more than 2 rows def __wrapping_move_with_column(self): diagonal_info = self.__corner_position_information() if(diagonal_info['is_zero_top_left']): return self.__swap(self.rows - 1, 0) if(diagonal_info['is_zero_top_right']): return self.__swap(self.rows - 1, self.cols - 1) if(diagonal_info['is_zero_bottom_left']): return self.__swap(0, 0) if(diagonal_info['is_zero_bottom_right']): return self.__swap(0, self.cols - 1) return -1 def __corner_position_information(self): zero_row = self.zero_position[0] zero_col = self.zero_position[1] diagonal_info = { 'is_zero_top_left': (zero_row == 0 and zero_col == 0), 'is_zero_top_right': (zero_row == 0 and zero_col == self.cols - 1), 'is_zero_bottom_left': (zero_row == self.rows - 1 and zero_col == 0), 'is_zero_bottom_right': (zero_row == self.rows - 1 and zero_col == self.cols - 1) } return diagonal_info # if the 0 is in a corner, it can wrap and swap there, or it can move diagonally within def diagonal_move(self, is_move): diagonal_info = self.__corner_position_information() if(diagonal_info['is_zero_top_left']): if(is_move): return self.__swap(self.rows - 1, self.cols - 1) else: return self.__swap(1, 1) if(diagonal_info['is_zero_top_right']): if(is_move): return self.__swap(self.rows - 1, 0) else: return self.__swap(1, self.cols - 2) if(diagonal_info['is_zero_bottom_left']): if(is_move): return self.__swap(0, self.cols - 1) else: return self.__swap(self.rows - 2, 1) if(diagonal_info['is_zero_bottom_right']): if(is_move): return self.__swap(0, 0) else: return self.__swap(self.rows - 2, self.cols - 2) return -1 def is_goal_state(self): goal_string = '' for i in range((self.cols * self.rows) - 1): goal_string += str(i + 1) + ' ' goal_string += '0' return goal_string == self.current_state_to_string() def current_state_to_string(self): return ' '.join(map(str, [ y for x in self.arr for y in x])) # Examples #puzzle = XPuzzle(2, 4, '1 2 3 4 5 6 0 7') #puzzle.pretty_print_array() #puzzle.regular_move('down') #puzzle.regular_move('left') #puzzle.diagonal_move(False) #puzzle.diagonal_move(True) #puzzle.wrapping_move() #puzzle.regular_move('right') #puzzle.regular_move('left') #puzzle.regular_move('up') #puzzle.regular_move('down') #puzzle.pretty_print_array() #print('goal state? ' + str(puzzle.is_goal_state())) #puzzleGoal = XPuzzle(2, 4, '1 2 3 4 5 6 7 0') #puzzleGoal.is_goal_state() #puzzleBig = XPuzzle(3, 8, '1 2 3 4 0 6 7 8 9 10 11 12 13 14 15 16 17 5')
9aeb414b897c3948dfe4313d40b30bd7471a3d49
priyal-jain-84/Projects
/sudoku project.py
2,429
4.25
4
# Sudoku project using backtracking method # board=[ [7,3,0,9,5,0,0,0,0], [2,0,0,6,7,0,5,8,0], [0,0,5,0,1,0,4,0,0], [1,9,0,0,6,3,2,0,5], [0,4,0,0,0,0,6,0,0], [5,6,8,2,0,7,0,0,0], [0,2,0,0,8,1,3,0,0], [0,0,1,0,0,9,7,6,0], [0,7,0,5,2,0,8,0,9] ] # to print the board in a good and understandable manner def print_board(boa): for i in range (len(boa)): if i%3==0 and i!=0: print("-------------------------------") for j in range(len(boa)): if j%3 == 0 and j!= 0: print(" | ",end="") if j==8: print(boa[i][j]) else: print(str(boa[i][j]) + " ", end=" ") # to find all the empty elements in the board def find_empty(boa): for i in range (len(boa)): for j in range(len(boa)): if boa[i][j]==0: return (i,j) # to check if the value is valid for any position def valid(boa,pos,num): # to check whether the no. is appearing in the given row.. for i in range(len(boa)): if boa[pos[0]][i]== num: return False # to check whether the no. is appearing in the given column.. for i in range(len(boa)): if boa[i][pos[1]] == num: return False # to check whether the no. is appearing in the given square box.. x0 = (pos[1] // 3 ) * 3 y0 = (pos[0] // 3 ) * 3 for i in range (0,3): for j in range(0,3): if boa[y0+i][x0+j] == num: return False # if non of the condition is false then the value is valid so it will return True return True # fuction which uses all this function and return the final solution def solution(boa): find =find_empty(boa) if not find: return True else: row,column = find for i in range(0,10): if valid (boa,(row,column),i): boa[row][column] = i if solution(boa): return True boa[row][column]=0 return False print("Question Board\n____________________________\n") print_board(board) solution (board) print("\nSolution Board\n____________________________\n") print_board(board)
dd466737b8abb26679212eceabda0ae7114c2495
stevenbrand99/holbertonschool-higher_level_programming
/0x05-python-exceptions/3-safe_print_division.py
260
3.5625
4
#!/usr/bin/python3 def safe_print_division(a, b): try: inside_result = a / b except (ZeroDivisionError, TypeError): inside_result = None finally: print("Inside result: {}".format(inside_result)) return inside_result
8923477b47a2c2d283c5c4aba9ac797c589fbf7e
nobin50/Corey-Schafer
/video_6.py
1,548
4.15625
4
if True: print('Condition is true') if False: print('Condition is False') language = 'Python' if language == 'Python': print('It is true') language = 'Java' if language == 'Python': print('It is true') else: print('No Match') language = 'Java' if language == 'Python': print('It is Python') elif language == 'Java': print('It is Java') else: print('No Match') user = 'Admin' logged_in = True if user == 'Admin' and logged_in: print('Admin Page') else: print('Bad Creeds') user = 'Admin' logged_in = False if user == 'Admin' and logged_in: print('Admin Page') else: print('Bad Creeds') user = 'Admin' logged_in = False if user == 'Admin' or logged_in: print('Admin Page') else: print('Bad Creeds') user = 'Admin' logged_in = False if not logged_in: print('Please Log In') else: print('Welcome') a = [1, 2, 3] b = [1, 2, 3] print(id(a)) print(id(b)) print(a is b) a = [1, 2, 3] b = [1, 2, 3] b = a print(id(a)) print(id(b)) print(a is b) print(id(a) == id(b)) condition = False if condition: print('Evaluated to true') else: print('Evaluated to false') condition = None if condition: print('Evaluated to true') else: print('Evaluated to false') condition = 0 if condition: print('Evaluated to true') else: print('Evaluated to false') condition = "" if condition: print('Evaluated to true') else: print('Evaluated to false') condition = {} if condition: print('Evaluated to true') else: print('Evaluated to false')
645074e3b2e1274fb0380182c95124df18ce2a89
liamliwanagburke/ispeakregex
/politer.py
8,060
4
4
'''Provides a 'polite' iterator object which can be sent back values and which allows sequence operations to be performed on it. exported: Politer -- the eponymous generator/sequence class @polite -- decorator that makes a generator function return a Politer ''' import functools import itertools import collections import inspect def politer(iterable): '''Wraps an iterable in a Politer if it is not already wrapped.''' if isinstance(iterable, Politer): return iterable return Politer(iterable) def polite(func): '''Decorator function that wraps a generator function and makes it return a Politer object. ''' @functools.wraps(func) def wrapped(*args, **kwargs): return politer(func(*args, **kwargs)) return wrapped def polite_arg(argument): '''Decorator function that wraps an argument passed to the function.''' def make_polite(func): signature = inspect.signature(func) @functools.wraps(func) def wrapped(*args, **kwargs): bound = signature.bind(*args, **kwargs) bound.arguments[argument] = politer(bound.arguments[argument]) return func(*bound.args, **bound.kwargs) return wrapped return make_polite class Politer(collections.Iterator, collections.Sequence): ''' A 'polite' iterator object which provides many useful methods. While generators often provide a cleaner approach to problems, their indeterminate and temporal nature make some problems -- such as those that require looking ahead or knowing the length of a sequence -- more difficult. Politer is an attempt to provide methods for solving those problems, in two ways: 1) It allows you to send values back to the generator, which will put them on top of the 'stack'. As a convenience, it provides a prev() method for the common use case of rewinding the generator exactly one value. 2) It provides a 'lazy' implementation of the sequence protocol, allowing you to get the politer's length, index into it, etc. just like a list. The politer will internally unroll as much of the generator as necessary in order to perform the requested operation. It also provides some 'lazy' methods to avoid using the more exhaustive ones, such as at_least() and popped(). Note that pulling values off the politer using next() will change its length and the indices of the contained elements -- the politer is a 'list of uniterated values,' albeit with the ability to send values back. Politers use deques internally to hold their unrolled values. They should perform well for relatively short-range looks ahead during iteration, but if you intend to perform many sequence operations that target the 'far end' of the generator, you will probably do better just casting the generator to a list. ''' __slots__ = ['_generator', '_values', '_previous'] def __init__(self, iterable): '''Instantiates a Politer. 'iterable' is the object to wrap.''' self._generator = iter(iterable) self._values = collections.deque() self._previous = None def __next__(self): '''Gets the next value from the politer.''' if self._values: value = self._values.popleft() else: value = next(self._generator) self._previous = value return value def send(self, *values): '''Puts values 'on top' of the politer, last-in-first-out.''' self._values.extendleft(values) def prev(self): '''Rewinds the generator exactly one value. Not repeatable.''' if self._previous is None: raise StopIteration('politer.prev() is not repeatable') self._values.appendleft(self._previous) self._previous = None def at_least(self, length): '''Lazily evaluates len(self) >= length.''' return self._advance_until(lambda: len(self._values) >= length) def __len__(self): '''Gets the length of the politer, dumping the generator to do so.''' self._dump() return len(self._values) def __getitem__(self, index): '''Gets the value at a specific index, or gets a slice. Since deques can't be sliced, if a slice is requested we cast the internal deque to a list and slice that, with the attendant costs.''' if isinstance(index, slice): return self._getslice(index) elif isinstance(index, int): if not self._advance_until(lambda: len(self._values) > index): raise IndexError("politer index out of range") return self._values[index] else: raise TypeError("politer indices must be integers") def __contains__(self, value): '''Lazily tests membership.''' return self._advance_until(lambda: value in self._values) def count(self, value): '''Counts the occurrences of value in the politer. Dumps the generator. ''' self._dump() return self._values.count(value) def index(self, value, i=0, j=None): '''Finds the first occurrence of value in the politer. Always dumps the generator. (Doesn't technically have to, but doing it the right way was very complicated.) ''' self._dump() if j is None: j = len(self._values) return self._values.index(value, i, j) def close(self): '''Closes the generator and discards all values.''' self._generator.close() del self._values self._values = collections.deque() def pop(self): '''Dumps the generator, then removes and returns the last item.''' self._dump() return self._values.pop() def popped(self, n=1): '''Yields every item in the politer except the last n.''' yield from self.takewhile(lambda _: self.at_least(n)) def __nonzero__(self): '''Returns True if there are any remaining values.''' return self._advance_until(lambda: self._values) def takewhile(self, func): '''As itertools, but preserves the failing element.''' saved = None for item in itertools.takewhile(func, self): yield item saved = item if not func(self._previous): self.prev() if saved is not None: self._previous = saved def takeuntil(self, func): '''Opposite of takewhile.''' yield from self.takewhile(lambda x: not func(x)) def any(self, func): '''True if func(any contained item) is true.''' if any(filter(func, self._values)): return True elif not self._advance(): return False else: return self._advance_until(lambda: func(self._values[-1])) def all(self, func): '''True if func(item) is true for all contained items.''' return not self.any(lambda x: not func(x)) def _getslice(self, sliceobj): start = sliceobj.start if sliceobj.start is not None else 0 stop = sliceobj.stop if sliceobj.stop is not None else -1 # force dump if start < 0 or stop < 0: self._dump() else: self._advance_until(lambda: len(self._values) >= stop) return list(self._values)[sliceobj] def _advance(self): try: self._values.append(next(self._generator)) return True except StopIteration: return False def _advance_until(self, func): while not func(): if not self._advance(): return False return True def _dump(self): self._values.extend(self._generator)
6a22f2e3cd18309c2b74becebafa184467ce9b87
Piper-Rains/cp1404practicals
/prac_05/hex_colours.py
591
4.375
4
COLOUR_CODES = {"royalblue": "#4169e1", "skyblue": "#87ceeb", "slateblue": "#6a5acd", "slategray1": "#c6e2ff", "springgreen1": "#00ff7f", "thistle": "#d8bfd8", "tomato1": "#ff6347", "turquoise3": "#00c5cd", "violet": "#ee82ee", "black": "#000000"} print(COLOUR_CODES) colour_name = input("Enter colour name: ").lower() while colour_name != "": if colour_name in COLOUR_CODES: print(colour_name, "has code:", COLOUR_CODES[colour_name]) else: print("Invalid colour name entered") colour_name = input("Enter colour name: ").lower()
e8893f7e629dede4302b21efee92ff9030fe7db2
Piper-Rains/cp1404practicals
/prac_05/word_occurrences.py
468
4.25
4
word_to_frequency = {} text = input("Text: ") words = text.split() for word in words: frequency = word_to_frequency.get(word, 0) word_to_frequency[word] = frequency + 1 # for word, count in frequency_of_word.items(): # print("{0} : {1}".format(word, count)) words = list(word_to_frequency.keys()) words.sort() max_length = max((len(word) for word in words)) for word in words: print("{:{}} : {}".format(word, max_length, word_to_frequency[word]))
0f6e1b50046506c97b52e79e6108bef72b64aa9f
siva237/python_classes
/numpys.py
990
3.75
4
# Numpy is the core library for scientific computing in Python. # It provides a high-performance multidimensional array object, and tools for working with these arrays. import numpy # a=numpy.array([1,2,3]) # rank 1 array # print(a.shape) # (3,) # print(type(a)) # <class 'numpy.ndarray'> # b=numpy.array([[1,2,3],[4,5,6]]) # rank 2 array # print(b.shape) # (2, 3) # print(type(b)) # <class 'numpy.ndarray'> # # # (0,0) (0,1) (0,2) # print(b) # 0 [[1 2 3] # # 1 [4 5 6]] # # (1,0) (1,1) (1,2) # # print(b[0,0],b[0,2]) # 1 3 # Create an array of all zeros # a1=numpy.zeros((2,2),int) # print(a1) # Create a 2x2 identity matrix # b1=numpy.eye(2) # print(b1) # Create an array of all ones # c1=numpy.ones((2,2)) # print(c1) # Create a constant array # d1=numpy.full((3,3),8) # print(d1) # e = numpy.random.randint(200,300,(2,2)) # Create an array filled with random values # print(e)
93aff832710c79b6a88e20cdd1e6f8d0c50b1e81
siva237/python_classes
/copy_ex.py
343
3.6875
4
import copy # s={1,2,3,4} # s1=copy.deepcopy(s) # print(s1 is s) # s.add(10) # print(s) # print(s1) # s={1,2,3,4} # s1=copy.copy(s) # print(s1 is s) # s.add(10) # print(s) # print(s1) # l=[1,2,3,4] # l1=copy.copy(l) # print(l1 is l) # l.insert(1,22) # print(l) # print(l1) l=[1,2,3,4] l1=l print(l1 is l) l.insert(1,22) print(l) print(l1)
a7554b02548c913fcf50cb1a1b7c621a646cf06a
siva237/python_classes
/read_write_append/most_occuring_words.py
198
3.78125
4
# file = open("doc.txt", 'w') import collections words = open("doc.txt", 'r').read() list_of_words = str(words).split(" ") words1 = collections.Counter(list_of_words).most_common(10) print(words1)
6abf00b079ceab321244dbe606f05bac9a347be0
siva237/python_classes
/Decorators/func_without_args.py
1,331
4.28125
4
# Decorators: # ---------- # * Functions are first class objects in python. # * Decorators are Higher order Functions in python # * The function which accepts 'function' as an arguments and return a function itslef is called Decorator. # * Functions and classes are callables as the can be called explicitly. # def hello(a): # return a # hello(5) # ----------------------- # def hello(funct): # # # return funct # ---------------------- # # 1. Function Decorators with arguments # 2. Function Decorators without arguments # 3. Class Decorators with arguments # 4. Class Decorators without arguments. class Student: def __init__(self): pass def __new__(self): pass def __call__(self): pass obj = Student() # def validate(func): # def abc(x, y): # if x > 0 and y > 0: # print(func(x, y)) # else: # print("x and y values should be greater than 0") # return abc # @validate # def add(a, b): # return a + b # out = add(20, 20) # @validate # def sub(a, b): # return a - b # print(out) # out1 = sub(20, 10) # print(out1) def myDecor(func): def wrapper(*args, **kwargs): print('Modified function') func(*args, **kwargs) return wrapper @myDecor def myfunc(msg): print(msg) # calling myfunc() myfunc('Hey')