blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
399608502371ffab488a84b475910e2b1cd342cc
sotomaque/Python-Coding-Interview-Questions
/intersection.py
1,420
4.28125
4
''' if you have two sorted arrays, find the common elements of the arrays ''' def intersection(givenArray1, givenArray2): common = [] x = y = maxLength = 0 if (len(givenArray1) >= len(givenArray2)): maxLength = len(givenArray1) else: maxLength = len(givenArray2) for i in range(maxLength): print('x', x) print('y', y) if (givenArray1[x] == givenArray2[y]): common.append(givenArray1[x]) x += 1 y += 1 elif (givenArray1[x] < givenArray2[y]): x += 1 else: y += 1 if len(common) == 0: print('no common elements found') return else: print(len(common), ' common elements found') return common def bubbleSort(list): # Swap the elements to arrange in order for iter_num in range(len(list)-1,0,-1): for idx in range(iter_num): if list[idx]>list[idx+1]: temp = list[idx] list[idx] = list[idx+1] list[idx+1] = temp def main(): #description print("This program takes in a series of arrays and returns the common elements between them") #input array1 = raw_input("enter the first array: ") array2 = raw_input("enter the second array: ") x = [] y = [] #put stirngs into array form for i in array1: x.append(int(i)) for i in array2: y.append(int(i)) #sort arrays bubbleSort(x) bubbleSort(y) print('x: ', x) print('y: ', y) #return common elements print(intersection(x, y)) main()
5a0dd1454539783f7f14d49ef47f07ad2830bed1
godaipl/python3study
/2python基础/2字符串和编码/Python的字符串.py
544
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 在最新的Python 3版本中,字符串是以Unicode编码的,也就是说,Python的字符串支持多语言 print('我是中国人') print(ord("我")) print(chr(ord("我"))) # print(bytes(b'我')) #会报异常 print("我".encode("UTF-8")) # print("我".encode("ascii")) print("我".encode("UTF-8").decode("UTF-8")) # 格式化 print('HELLO %s' % '波波') print('HELLO NO is %d' % 1) print('HELLO Salary is %f' % 1.0) print('HELLO %s , No is %d , Salary is %f' % ('波波', 1, 1.0))
ece9551a5922f844dc267a0fb2724a42ea49a086
Emily1988/mantis
/bugs2018/date.py
1,663
3.8125
4
import datetime #给定日期,返回对应当年第几周 def week_date(year,month,day): year = int(year) month = int(month) day = int(day) date = datetime.date(year,month,day).isocalendar() return date def dateRange(beginDate, endDate): dates = [] dt = datetime.datetime.strptime(beginDate, "%Y-%m-%d") date = beginDate[:] while date <= endDate: dates.append(date) dt = dt + datetime.timedelta(1) date = dt.strftime("%Y-%m-%d") return dates def weekRang(beginDate, endDate): week = set() for date in dateRange(beginDate, endDate): week.add(datetime.date(int(date[0:4]), int(date[5:7]), int(date[8:10])).isocalendar()[0:2]) wk_l = [] for wl in sorted(list(week)): wk_l.append(str(wl[0]) + '#' + str(wl[1])) return wk_l def dateRange(beginDate, endDate): dates = [] dt = datetime.datetime.strptime(beginDate, "%Y-%m-%d") date = beginDate[:] while date <= endDate: dates.append(date) dt = dt + datetime.timedelta(1) date = dt.strftime("%Y-%m-%d") return dates if __name__ == '__main__': # .strftime('%Y,%m,%d') # print(datetime.datetime.now()) # t = datetime.datetime.now().isocalendar() # print(t) # # # print(time.strftime('%W')) #返回当前时间对应的周序号 # print(datetime.date(2018,8,30).strftime('%W')) # # week_date(2017,2,7) # for week in weekRang('2017-01-08', '2018-01-01'): # print(week) t1 = datetime.date(2016,1,1).isocalendar() print(t1) # for date in dateRange('2017-01-01', '2017-12-31'): # print(date)
ed2ba9f41e32620d40b79c802e5106bc95fcaefd
CamA-JCU/cp1404practicals
/prac_02/files.py
1,020
4.15625
4
# 1. Write code that asks the user for their name, # then opens a file called "name.txt" and writes that name to it. open_file = open("name.txt", 'w') name = str(input("Name: ")) print(name, file=open_file) open_file.close() # 2. Write code that opens "name.txt" and reads the name (as above) then prints, # "Your name is Bob" (or whatever the name is in the file). open_file = open("name.txt", 'r') name = open_file.read().strip() print("Your name is", name) # 3. Write code that opens "numbers.txt", reads only the first two numbers and adds them together # then prints the result, which should be... 59. open_file = open("numbers.txt", 'r') number1 = int(open_file.readline()) number2 = int(open_file.readline()) print(number1 + number2) open_file.close() # 4. Now write a fourth block of code that prints the total for # all lines in numbers.txt or a file with any number of numbers. total = 0 open_file = open("numbers.txt", 'r') for line in open_file: number = int(line) total += number print(total)
9d0837ea18774ea2674a89c2299508ea55b87c1d
AnnapoorniRavi/Udacity_Nanodegree
/Exploring Weather Trends.py
1,378
3.6875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: ## Calling Libraries: import numpy as np import pandas as pd # for loading data into the notebook from matplotlib import pyplot as plt #for making line chart # In[16]: ## Importing the extracted Data Set: data = pd.read_excel (r'C:\Users\Sahi\Desktop\Nanodegree\Results.xlsx') print (data) # In[17]: ## Moving Averages: def moving_avg(mA_range, data_input): # with local variables output = data_input.rolling(window = mA_range, center = False, on = "ctemp").mean().dropna() return output ## Function Calling with the range of Moving Average: mA_value = 150 chart_moving_avg = moving_avg(mA_value, data) # with global variables ##Drawing the graph: Global Temperature plt.plot(chart_moving_avg['year'], chart_moving_avg['gtemp'], label='Global') plt.legend() plt.xlabel("Years") plt.ylabel("Temperature (°C)") plt.title("Global Average Temperature") plt.show() # In[18]: ## Drawing the graph:Austin and Global Temperature: plt.plot(chart_moving_avg['year'], chart_moving_avg['ctemp'], label='Austin') plt.plot(chart_moving_avg['year'], chart_moving_avg['gtemp'], label='Global') plt.legend() plt.xlabel("Years") plt.ylabel("Temperature (°C)") plt.title("Austin Vs Global Average Temperature") plt.show() # In[19]: data.tail(10) # In[20]: data.head(10) # In[ ]:
c46532a64303538bf1cf67c7a49b71d6b66e74d7
bimri/learning-python
/chapter_4/files.py
718
3.921875
4
''' File objects are Python code’s main interface to external files on your computer ''' # Opening & Writing to a file store to your CWD f = open('data.txt', 'w') # Make a new file in output mode('w' is write) print(f.write('Hello bimri, here we meet again\n')) # Write string of characters to it print(f.write('This time round - let nothing pass you by with files\n')) f.close() # Reading contents of your file f = open('data.txt') text = f.read() print(text) print(text.split()) # Best way to read a file is to not read it at all # Files provide an iterator that automatically reads # line by line in for loops and other contexts. for line in open('data.txt'): print(line)
995395737719142be9a6f293aa9b2800d1a37b4b
yangboyubyron/DS_Recipes
/zSnips_SQLite/CreateDBfromPythonDF.py
2,280
4
4
#---------------------------------------------------------- # EXAMPLE 1 import pandas as pd import sqlite3 import pandas.io.sql # reads files in dfcust=pd.read_csv('cust.csv', delimiter=',', header='infer', low_memory=False) dfmail=pd.read_csv('mail.csv', delimiter=',', header='infer', low_memory=False) dfitem=pd.read_csv('item.csv', delimiter=',', header='infer', low_memory=False) # creates connection named xzyconn and creates database named xyz.db # sets c an an object for sqlite cursor within the xyzconn connection # sends dfcust dataframe to the xyzconn (connection to the xyz db) and # names the file 'customer' xyzconn=sqlite3.connect('xyz.db') c=xyzconn.cursor() dfcust.to_sql('customer',xyzconn) # view the contents of the mail file that was just transferred to the db with xyzconn: c=xyzconn.cursor() # object for sqlite cursor within the xyzconn connection c.execute('SELECT * FROM customer') # selects from from customer tablein db # fectchmany allows to select the number of rows you want to view: # 5 in this example (can use fetchall() and fetchone()) rowcust=c.fetchmany(2) for row in rowcust: print row[:5] # only view 5 columns # view the contents of the mail file that was just transferred to the db c.execute('SELECT * FROM mail') rowmail=c.fetchmany(5) for row in rowmail: # specifies num of rows print row c.execute('SELECT * FROM item') # selects from the customer table in xyz db rowitem=c.fetchmany(5) # select 5 rows for row in rowitem: print row #---------------------------------------------------------- # EXAMPLE 2 import pandas as pd import sqlite3 import pandas.io.sql table_name = 'my_table_2' # sets object for table to be queried id_column = 'my_1st_column' # sets object for id_column column_2 = 'my_2nd_column' # sets object for column_2 column_3 = 'my_3rd_column' # sets object for column_3 # limits selection to 10 rows that meet a certain criteria # (in this example, when the result is "Hi World" c.execute('SELECT * FROM {tn} WHERE {cn}="Hi World" LIMIT 10'.\ format(tn=table_name, cn=column_2)) # sets 'ten_rows' object to fetch all that was selected # (which is only 10 due to limit in first line ten_rows = c.fetchall() print('4):', ten_rows)
75c521ac2d894998e55f64a408177f32d9ef1222
sforrester23/SlitherIntoPython
/chapter8/Question1.py
200
3.65625
4
my_words = input("Input some words to make a list: ").split() num = int(input("Number please: ")) i = 0 while i < len(my_words): if len(my_words[i]) >= num: print(my_words[i]) i += 1
646e1b340a784f91f537bdb9ac2e806745bf785a
jacksonkohls/Snakify
/4; Loops/Sum of N.py
78
3.609375
4
n=int(input()) y=0 for i in range(n): x = int(input()) y= y+x print(y)
e7b2a86607d79801c30d5e63de7277f731e70209
jinjuleekr/hackerrank_algorithms
/SimpleArraySum.py
394
3.609375
4
''' Title : Simple Array Sum Domain : Python Created : 01 OCT 2018 ''' get_number = int(input()) get_array = input('Input' + str(get_number) + 'numbers with space') get_list = get_array.split(' ') #print(get_number) #print(get_list) total = 0 while get_number > 0 : number = int(get_list[get_number-1]) total = total + number get_number = get_number - 1 print(total)
a7e2f348e6f22fbd667fb6837b048e4f4c2be04d
HussainPythonista/Data-Structure
/linkedList/Circular.py
2,386
3.796875
4
from linkedList import * #Load the data circular=linkedList() def createCircularLinkedList(head): #Create circular linkedlist forRemember=head circular.last.nextReference=head pointer=head while pointer!=None: print(pointer.data) if pointer.nextReference==forRemember: pointer.nextReference=None pointer=pointer.nextReference head=circular.head #createCircularLinkedList(circular.head) #Circular Linked List by Recursion needToStop=0 def byRecursion(head,p): global needToStop if needToStop==0 or p!=head: needToStop=1 print(p.data) #p=p.nextReference byRecursion(circular.head,p.nextReference) needToStop=0 def countNum(head): count=0 pointer=head while pointer: count+=1 pointer=pointer.nextReference return count-1 #print(countNum(circular.head)) def delete(head,index): if index-1==0: temp=head.nextReference head.nextReference=None circular.head=temp else: pointer=head count=0 while pointer: count+=1 #print(pointer.data) if count+1==index: temp=pointer.nextReference #print(temp.nextReference.data) #print(temp.data) pointer.nextReference=temp.nextReference pointer=pointer.nextReference createCircularLinkedList(circular.head) def insertValueInCircular(head,index,value): if index==0: temp=head node=Node(value) node.nextReference=temp head=node elif index==countNum(circular.head): node=Node(value) node.nextReference=head circular.last=node #print(circular.last.nextReference.data) #print(node.nextReference.data) pointer=head count=0 while pointer: count+=1 if count==index: node=Node(value) node.nextReference=pointer.nextReference pointer.nextReference=node break pointer=pointer.nextReference #print(head.nextReference.nextReference.nextReference.nextReference.nextReference.nextReference.nextReference.nextReference.nextReference.data) #circular.printElements(head) #createCircularLinkedList(head) index=1 delete(circular.head,index)
31bad158227177fe165a5bd9043125c8b9677c70
danveb/python-data-structure-practice
/36_find_the_duplicate/find_the_duplicate.py
1,080
4.09375
4
def find_the_duplicate(nums): """Find duplicate number in nums. Given a list of nums with, at most, one duplicate, return the duplicate. If there is no duplicate, return None >>> find_the_duplicate([1, 2, 1, 4, 3, 12]) 1 >>> find_the_duplicate([6, 1, 9, 5, 3, 4, 9]) 9 >>> find_the_duplicate([2, 1, 3, 4]) is None True """ # # initialize empty list for duplicate_list # duplicate_list = [] # # initialize a counter to count on number of duplicates # counter = 0 # # iterate for each_element in nums list # # if nums.count(each_element) # initialize counter at 0 counter = 0 # num = nums[0] num = nums[0] # iterate val in nums for val in nums: # current_freq will be equal to nums.count(val) current_freq = nums.count(val) # if current_freq is > counter if current_freq > counter: # counter is equal to current_freq counter = current_freq # num = i num = val # return num return num
87ab9eed4ef5a3cfe087cae8de85f7fda0b961a1
Crasti/Homework
/Lesson5/Task5.4.py
993
3.734375
4
""" Создать (не программно) текстовый файл со следующим содержимым: One — 1 Two — 2 Three — 3 Four — 4 Необходимо написать программу, открывающую файл на чтение и считывающую построчно данные. При этом английские числительные должны заменяться на русские. Новый блок строк должен записываться в новый текстовый файл. """ try: with open("Task4.txt", "r+") as task_4: repl_dict = {"One": "Один", "Two": "Два", "Three": "Три", "Four": "Четыре"} for line in task_4.readlines(): with open("Task4_new.txt", "a") as task4_new: print((line.replace(line.split()[0], str(repl_dict.get(line.split()[0])))), file=task4_new, end="") except Exception as ex: print(f"{ex} omg, something wrong!")
7ae12d15668d03c85609965aecaa38d7d0d180f8
Aadhya-Solution/PythonExample
/list_compranstion/lambda_map.py
387
4.3125
4
''' map map() applies the function func to all the elements of the sequence seq. It returns a new list with the elements changed by func map(func,seq) ''' def fahrenheit(T): return ((float(9)/5)*T + 32) def celsius(T): return (float(5)/9)*(T-32) temp = (36.5, 37, 37.5,39) F = map(fahrenheit, temp) C = map(celsius, F) print "Celsius:",C
1e92c886f6220c9c65b5f978703209f9f4eb38b0
kapppa-joe/leetcode-practice
/daily/20201202-random-node.py
1,116
3.734375
4
from random import randint # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def __init__(self, head: ListNode): """ @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. """ self.head = head self.pool = [] while head: self.pool.append(head.val) head = head.next def getRandom(self) -> int: idx = randint(0, len(self.pool) - 1) return self.pool[idx] def getRandom_rs(self) -> int: """ Returns a random node's value. Use reservoir sampling """ result = self.head.val i = 1 node = self.head while node: if randint(1, i) == 1: result = node.val node = node.next i += 1 return result # Your Solution object will be instantiated and called as such: # obj = Solution(head) # param_1 = obj.getRandom()
655ebc39613806f031d45bc7969c765f665c5ecd
SymmetricChaos/MyOtherMathStuff
/GEB/Chapter8TNT/StripSplit.py
3,124
3.640625
4
import re from Utils.StringManip import left_string # CANNOT IMPORT FROM PROPERTIES # Functions for splitting strings to be used for checking well formedness def split(x,left,right): L,lo,hi = left_string(x,left,right,inner=True,warn=False) R = x[hi+2:-1] return L,R def split_add_mul(x): return split(x,"(","⋅+") def split_logical(x): return split(x,"<","∧∨⊃") def split_eq(x): return x.split("=",maxsplit=1) # Functions for removing certain symbols def strip_neg(x): while x != "" and x[0] == "~": x = x[1:] return x def strip_succ(x): while x != "" and x[0] == "S": x = x[1:] return x # Removes quantifiers and also strips out negatives in the chain def strip_neg_qaunt(x): x = strip_neg(x) m = re.match("^[∀∃][a-z]\'*:",x) while m: span = m.span() x = x[span[1]:] x = strip_neg(x) m = re.match("^[∀∃][a-z]\'*:",x) return x # Need this because ordinary replacement will replace the a in a' def replace_var(x,pattern,replacement): if pattern not in x: raise Exception(f"Replacement Error: {pattern} not in {x}") left = "" pattern = re.escape(pattern) f = re.search(pattern,x) # While a possible match is found in x while f != None: # Get the upper and lower limits of the match lo,hi = f.span() # If the upper is not the end of the string if hi != len(x): # If the character immediately after the match is ' (meaning we only have part of a variable) # Then store the left half half and continue working with the right half if x[hi] == "'": left += x[:hi] x = x[hi:] # Otherwise append the the replacement to the left half, ignoring the matched section # and continue working with the right half else: left += x[:lo] + replacement x = x[hi:] # If we did reach the end of the string, ignoring the matched section # and continue working with the right half else: left += x[:lo] + replacement x = x[hi:] f = re.search(pattern,x) return left+x def replace_var_nth(x,pattern,replacement,n): if pattern not in x: raise Exception(f"Replacement Error: {pattern} not in {x}") left = "" pattern_esc = re.escape(pattern) f = re.search(pattern_esc,x) ctr = 1 while f != None: lo,hi = f.span() if ctr == n: if hi != len(x): if x[hi] == "'": left += x[:hi] x = x[hi:] else: left += x[:lo] + replacement x = x[hi:] else: left += x[:lo] + replacement x = x[hi:] return left+x else: left += x[:hi] x = x[hi:] f = re.search(pattern_esc,x) ctr += 1 raise Exception(f"Replacement Error: {pattern} does not appear {n} times in {x}")
d19b0f9fa19615bc50e85c27049b6c4fc4ab3889
greymliu/Compsci_final_proj
/attempt_3.py
1,952
4.03125
4
class Trillium: name = "Trillium" color = "white" size = "ground cover" properties = "xxx" petal_shape = "rounded" latin_binom = "xxx" petal_num = 3 additional_info = "xxxx" class LadySlipper: name = "Lady Slipper" color = "white" size = "knee height" petal_shape = "cup-like" class BloodRoot: name = "Blood Root" color = "white" size = "ground cover" petal_num = 8 class RueAnemone: name = "Rue Anemone" color = "white" size = "ground cover" properties = "xxx" petal_num = 5 class Yarrow: name = "Yarrow" color = "white" size = "knee height" class SolomonsSeal: name = "Solomon's Seal" color = "yellow" size = "small" class CommonMullien: name = "Common Mullien" color = "yellow" size = "waist height to tall" class CommonStJohnsWort: name = "Common St Johns Wort" color = "yellow" size = "knee height" flw_colors = ["white", "yellow","orange", "blue/violet", "red/pink"] flw_sizes = ["ground cover", "small", "knee height", "waist height to tall"] while True: flw_color = input(f"What color is you're flower? Options: {flw_colors}") if flw_color == "white": if flw_size == "ground cover": flw_petal_num = input(f"How many petals does you're flower have?") if flw_petal_num == "8": print("You're flower is Blood Root") break if flw_petal_num == "5": print("You're flower is a Rue Anenome") break if flw_petal_num =="3": print("You're flower is a Trillium") break flw_size = input(f"What size is you're flower? Options: {flw_sizes}") if flw_size == "small": print("We don't have a large enough database to find this flower") break if flw_size == "knee height": print("You're flower is a Lady Slipper") break
3105ca8d77fa1f0b31162c8335c18614e5222094
ravalrupalj/BrainTeasers
/Edabit/Day 7.6.py
735
3.5
4
#Hitting the Jackpot #Create a function that takes a list (slot machine outcome) and returns True if all elements in the list are identical, and False otherwise. The list will contain 4 elements. #test_jackpot(["@", "@", "@", "@"]) ➞ True #test_jackpot(["abc", "abc", "abc", "abc"]) ➞ True #test_jackpot(["SS", "SS", "SS", "SS"]) ➞ True #test_jackpot(["&&", "&", "&&&", "&&&&"]) ➞ False #test_jackpot(["SS", "SS", "SS", "Ss"]) ➞ False def test_jackpot(result): return len(set(result)) == 1 print(test_jackpot(["@", "@", "@", "@"])) print(test_jackpot(["abc", "abc", "abc", "abc"])) print(test_jackpot(["SS", "SS", "SS", "SS"])) print(test_jackpot(["&&", "&", "&&&", "&&&&"])) print(test_jackpot(["SS", "SS", "SS", "Ss"]))
e161efadb7dd79b98168f1111123507463d9fdbe
svkirillov/cryptopals-python3
/cryptopals/set1/challenge03.py
556
3.578125
4
#!/usr/bin/env python3 from functions.xor import bruteforce_xor_single_byte_key, xor_byte_arrays CIPHER_TEXT = bytes.fromhex( "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736" ) RESULT = b"Cooking MC's like a pound of bacon" def challenge03(cipher: bytes) -> bytes: key = bruteforce_xor_single_byte_key(cipher) msg = xor_byte_arrays(cipher, key) return msg if __name__ == "__main__": res = challenge03(CIPHER_TEXT) assert res == RESULT, "The result does not match the expected value" print("Ok")
0e5efedd53841f8799b8b3319d420f092512e92f
anjalikrishna98/lab
/fibonacci.py
282
3.953125
4
n=int(input("enter the number of terms:")) f1,f2=0,1 f3=f1+f2 if n<=0: print("please enter a positive integer") else: print("fionacci series of first",n,"terms") print(f1) print(f2) for i in range (3,n+1): print(f3) f1=f2 f2=f3 f3=f1+f2
eeb588fd3dea17d5a6e9f6aec0e826474603288c
Tjcooper4/Visual_sorting
/main.py
466
4.1875
4
from algorithms import bubbleSort import random import time #def setSpeed(speed): #speed = input((float("Enter a number between 0 and 1")) speed = float(input("Enter a number between 0 and 1: ")) # Test array arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] random.shuffle(arr) print(arr) time.sleep(2) bubbleSort(arr, speed) print ('Sorted array is:') for i in range (len(arr)): print("%d" %arr[i]),
0e5411ef07aed838e1571b5e77883d6eaa11ae77
stefan-gherman/pair_programming_ex
/passwordgen/passwordgen_module.py
600
3.515625
4
import string import random as rd def passwordgen(): all_possible_chars = list(string.printable[:-6]) len_passw = 0 passw = "" while len_passw <= 20: passw += all_possible_chars[rd.randint(0,len(all_possible_chars)-1)] len_passw += 1 return passw def main(): in1 = input("Password Strenght w for weak, s for strong:") if in1 == 'w': weak_passwd = ['passwd', 'user', 'admin' , 'root'] print(weak_passwd[rd.randint(0,len(weak_passwd)-1)]) elif in1 == 's': print(passwordgen()) return if __name__ == '__main__': main()
a94aecd43a814191d901a3d309f960eaff56b554
jadhavmayur/innomatics_internship_APR_21
/Task4(python programming/Capitalize!.py
356
3.5
4
def solve(s): first,last=s.split() c_name='' c_last='' for i in range(len(s)): if first[0].islower()==True: c_name=first[0].upper()+first[1:] if last[0].islower()==True: c_last=last[0].upper()+last[1:] return print(c_name+' '+c_last) n='mayur jadhav' solve(n)
0e027b5f1212b8e21a1e74b95339ac5382ba041c
ivanbjarni/PokeDevs
/Deck.py
1,385
3.859375
4
from Card import * import random class Deck(object): cards = [] #Card[] List of cards in the deck name = "" #String a name to identify the deck in presets def __init__(self): self.cards = [] def __str__(self): s = "" for c in self.cards: s = s + str(c) return s # Usage: deck.shuffle() # Before: nothing # After: deck has been shuffled def shuffle(self): random.shuffle(self.cards) # Usage: card = deck.draw() # Before: deck not empty # After: card is the top card of the deck which has been removed def draw(self): return self.cards.pop() # Usage: card = deck.remove() # Before: index is a valid index in deck.cards # After: card is the card with the given index which has been removed from the deck def remove(self, index): return self.cards.pop(index) # Usage: deck.add(card) # Before: Nothing # After: Card has been added to the deck def add(self, card): self.cards.append(card) # Usage: i=deck.getIndexOf(name) # Before: Nothing # After: i is the index of name if name is not in the deck then i=-1 def getIndexOf(self,name): for i in range(0,len(self.cards)): if(self.cards[i].name == name): return i return -1 # Usage: bool=deck.isEmpty() # Before: Nothing # After: bool is true if deck is empty else false def isEmpty(self): return not self.cards def setCards(self, cards): self.cards = cards
bfdef10ab6c8cdd2ec8872512fe4b24d94a3020b
jmcuy/CMSC123
/#LabExercise1/liststack/__init__.py
630
3.9375
4
from linkedlist import LinkedList class Stack: def __init__(self): self.items = LinkedList() def push(self, item): self.items.append(item) def pop(self): current = self.items.head if current is not None: return self.items.remove(self.peek()).value else: return None def peek(self): current = self.items.head if current: while current.next is not None: current = current.next return current.value else: return None def size(self): return self.items.size()
9069a87aa657cfeac2deee75275b585f0bae2a12
Aasthaengg/IBMdataset
/Python_codes/p03729/s710890288.py
115
3.53125
4
a, b, c = input().split() f = lambda x, y, z : x[-1] == y[0] and y[-1] == z[0] print("YES" if f(a, b, c) else "NO")
7898b87600089a13ed23e4c8d4715cbc24b867dc
pulengmoru/string_calculator
/test/string_calculator.py
799
4.03125
4
import re # Creating the add function def add(num_string): num_string = r'{}'.format(num_string) extracted_numbers = re.findall(r"-?\d+", num_string) negatives = getAllNegatives(extracted_numbers) total_sum = 0 # check if there are negative numbers and throw a relevant exception if len(negatives) > 0: error_msg = 'ERROR: negatives not allowed ' for i in range(len(negatives)): if i != len(negatives)-1: error_msg += str(negatives[i]) + ',' else: error_msg += str(negatives[i]) raise Exception (error_msg) else: for num in extracted_numbers: if int(num) < 1000: total_sum += int(num) return total_sum def getAllNegatives(nums): negs = [] for num in nums: if int(num) < 0: negs.append(int(num)) return negs total_sum = add("-1") print(total_sum)
f5874baff3fb0087cdec2b0591f356f3724f6476
8563a236e65cede7b14220e65c70ad5718144a3/python3-standard-library-solutions
/Chapter01/0033_re_groups.py
906
4.53125
5
""" Dissecting Matches with Groups Searching for pattern matches is the basis of the powerful capabilities provided by regular expressions. Adding groups to a pattern isolates parts of the matching text, expanding those capabilities to create a parser. Groups are defined by enclosing patterns in parentheses. Any complete regular expression can be converted to a group and nested within a larger expression. All the repetition modifiers can be applied to the group as a whole, requiring the entire group pattern to repeat. """ from re_test_patterns import test_patterns def main(): test_patterns( "abbaaabbbbaaaaa", [ (r"a(ab)", "a followed by literal ab"), (r"a(a*b*)", "a followed by 0-n a and 0-n b"), (r"a(ab)*", "a followed by 0-n ab"), ("a(ab)+", "a followed by 1-n ab") ] ) if __name__ == "__main__": main()
eaddd475e1197ce8d3ff4cd051a6938f3e340ca5
usuaero/PyProp
/pyprop/electronics.py
10,622
3.890625
4
"""Classes defining electronic components for the propulsion unit.""" import os import numpy as np import sqlite3 as sql from random import randint class Battery: """Defines a battery. Parameters ---------- name : str, optional Name of the battery to be used. manufacturer : str, optional Manufacturer of the battery. capacity : float, optional Capacity of the battery in mAh. resistance : float, optional Internal resistance of the battery in Ohms. voltage : float Nominal voltage of the battery in Volts. weight : float Weight of the battery in ounces. I_max : float Maximum current draw of the battery in Amps. Defaults to infinity. chemistry : str Chemistry type of the battery. cell_arrangement : tuple The number of series and parallel cells in the battery. The first element should be the number of series cells and the second element should be the number of parallel cells. Defaults to (0, 0). """ def __init__(self, **kwargs): # Get parameters from kwargs self.capacity = kwargs.get("capacity") self.R = kwargs.get("resistance") self.V0 = kwargs.get("voltage") self.weight = kwargs.get("weight") self.name = kwargs.get("name", "Generic Battery") self.manufacturer = kwargs.get("manufacturer", "PyProp") self.I_max = kwargs.get("I_max", np.inf) self.chemistry = kwargs.get("chemistry", "NULL") self.S, self.P = kwargs.get("cell_arrangement", (0, 0)) def __str__(self): string = "Battery: {0}".format(self.name) string += "\n\tManufacturer: {0}".format(self.manufacturer) string += "\n\tCapacity: {0} mAh".format(self.capacity) string += "\n\tCells: {0}S{1}P".format(self.S, self.P) string += "\n\tVoltage: {0} V".format(self.V0) string += "\n\tWeight: {0} oz".format(self.weight) return string def write_to_database(self): """Saves this component's information to the user database. Doing this allows the component to be used in optimization schemes that query the database. This function will replace duplicate components (i.e. same name). The database is stored in your Python site-packages folder. The name is ```user_components.db```. """ # Locate database file db_file = os.path.join(os.path.dirname(__file__), "user_components.db") # Connect to database connection = sql.connect(db_file) cursor = connection.cursor() # Check if the table has been created try: cursor.execute("select * from Batteries") except: cursor.execute("""create table Batteries (id INTEGER PRIMARY KEY, Name VARCHAR(40), manufacturer VARCHAR, Imax FLOAT, Capacity FLOAT, Weight FLOAT, Ri FLOAT, Volt FLOAT, Chem VARCHAR, S INTEGER default 0, P INTEGER default 0);""") # Check for duplicate cursor.execute("delete from Batteries where Name = '{0}';".format(self.name)) # Store component command = """insert into Batteries (Name, manufacturer, Imax, Capacity, Weight, Ri, Volt, Chem, S, P) values ("{0}", "{1}", {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9});""".format(self.name, self.manufacturer.replace(" ", "_"), self.I_max/self.P, self.capacity/self.P, self.weight/(self.S*self.P), self.R*self.P/self.S, self.V0/self.S, self.chemistry, self.S, self.P) cursor.execute(command) cursor.close() connection.commit() connection.close() class ESC: """Defines an electronic speed controller (ESC). Parameters ---------- name : str, optional Name of the ESC to be used. manufacturer : str, optional Manufacturer of the ESC. resistance : float, optional Equivalent "on" resistance of the ESC in Ohms. I_max : float Maximum current that can be sourced by the ESC in amps. Defaults to infinity. weight : float Weight of the ESC in ounces. """ def __init__(self, **kwargs): # Set params self.R = kwargs.get("resistance") self.name = kwargs.get("name", "Generic ESC") self.manufacturer = kwargs.get("manufacturer", "PyProp") self.I_max = kwargs.get("I_max", np.inf) self.weight = kwargs.get("weight") def __str__(self): string = "ESC: {0}".format(self.name) string += "\n\tManufacturer: {0}".format(self.manufacturer) string += "\n\tMax Current: {0} A".format(self.I_max) string += "\n\tWeight: {0} oz".format(self.weight) return string def write_to_database(self): """Saves this component's information to the user database. Doing this allows the component to be used in optimization schemes that query the database. This function will replace duplicate components (i.e. same name). The database is stored in your Python site-packages folder. The name is ```user_components.db```. """ # Locate database file db_file = os.path.join(os.path.dirname(__file__), "user_components.db") # Connect to database connection = sql.connect(db_file) cursor = connection.cursor() # Check if the table has been created try: cursor.execute("select * from ESCs") except: cursor.execute("""create table ESCs (id INTEGER PRIMARY KEY, Name VARCHAR(40), manufacturer VARCHAR, Imax FLOAT, Ipeak FLOAT, Weight FLOAT, Ri FLOAT);""") # Check for duplicate cursor.execute("delete from ESCs where Name = '{0}';".format(self.name)) # Store component command = """insert into ESCs (Name, manufacturer, Imax, Ipeak, Weight, Ri) values ("{0}", "{1}", {2}, {3}, {4}, {5});""".format(self.name, self.manufacturer.replace(" ", "_"), self.I_max, self.I_max, self.weight, self.R) cursor.execute(command) cursor.close() connection.commit() connection.close() class Motor: """Defines an electric motor. Parameters ---------- name : str, optional Name of the motor to be used. manufacturer : str, optional Manufacturer of the motor. Kv : float, optional Kv rating (also called the speed constant) of the motor. resistance : float, optional DC resistance of the motor in Ohms. I_no_load : float No-load current of the motor in amps. Defaults to 0.0 I_max : float Maximum current that can be handled by the motor in amps. Defaults to infinity. gear_ratio : float, optional Gear ratio of the motor. A value greater than unity will correspond to the output shaft of the motor turning slower than the motor itself. Defaults to 1.0. weight : float Weight of the motor in ounces. """ def __init__(self, **kwargs): # Set params self.Kv = kwargs.get("Kv") self.Gr = kwargs.get("gear_ratio", 1.0) self.I0 = kwargs.get("I_no_load", 0.0) self.I_max = kwargs.get("I_max", np.inf) self.R = kwargs.get("resistance") self.name = kwargs.get("name", "Generic Motor") self.manufacturer = kwargs.get("manufacturer", "PyProp") self.weight = kwargs.get("weight") # Determine torque constant self.Kt = 7.0432/self.Kv # Converts to ft*lb/A def __str__(self): string = "Motor: {0}".format(self.name) string += "\n\tManufacturer: {0}".format(self.manufacturer) string += "\n\tKv: {0}".format(self.Kv) string += "\n\tWeight: {0} oz".format(self.weight) return string def write_to_database(self): """Saves this component's information to the user database. Doing this allows the component to be used in optimization schemes that query the database. This function will replace duplicate components (i.e. same name). The database is stored in your Python site-packages folder. The name is ```user_components.db```. """ # Locate database file db_file = os.path.join(os.path.dirname(__file__), "user_components.db") # Connect to database connection = sql.connect(db_file) cursor = connection.cursor() # Check if the table has been created try: cursor.execute("select * from Motors") except: cursor.execute("""create table Motors (id INTEGER PRIMARY KEY, Name VARCHAR(40), manufacturer VARCHAR, kv FLOAT, gear_ratio FLOAT default 1.0, no_load_current FLOAT, weight FLOAT, resistance FLOAT);""") # Check for duplicate cursor.execute("delete from Motors where Name = '{0}';".format(self.name)) # Store component command = """insert into Motors (Name, manufacturer, kv, gear_ratio, no_load_current, weight, resistance) values ("{0}", "{1}", {2}, {3}, {4}, {5}, {6});""".format(self.name, self.manufacturer.replace(" ", "_"), self.Kv, self.Gr, self.I0, self.weight, self.R) cursor.execute(command) cursor.close() connection.commit() connection.close()
ad790b0794a14247df5ea4bf1b99266eadee25b1
Lorthevan/MyLeetcode
/easy/Valid Parentheses.py
459
3.71875
4
class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ if s == '': return True mapping = {")": "(", "}": "{", "]": "["} s = s.replace(' ','') if s == '': return False for i in range(len(s)//2+1): s = s.replace('()','') s = s.replace('[]','') s = s.replace('{}','') return False if s != '' else True
7c64196f59a44d7ab789650e21379eea885f49c9
ruirodriguessjr/Python
/ManipulandoArquivos/ManipulaçãoDeArquivos.py
3,726
4.65625
5
""""r"- Ler - Valor padrão. Abre um arquivo para leitura, erro se o arquivo não existir "a" - Anexar - Abre um arquivo para anexar, cria o arquivo se ele não existir "w" - Write - Abre um arquivo para gravação, cria o arquivo se ele não existir "x" - Criar - Cria o arquivo especificado, retorna um erro se o arquivo existir""" #Para abrir um arquivo para leitura basta especificar o nome do arquivo: f = open("ManipulacaoArquivos.txt") print(f) #O código acima é o mesmo que: a = open("ManipulacaoArquivos.txt", "rt") #Como "r"para leitura e "t"para texto são os valores padrão, você não precisa especificá-los. #Para abrir o arquivo, use a open()função interna. #A open()função retorna um objeto de arquivo, #que possui um read()método para ler o conteúdo do arquivo: f = open("ManipulacaoArquivos.txt", "r") print(f.read()) print("===============================") #Por padrão, o read()método retorna todo o texto # mas você também pode especificar quantos caracteres deseja retornar: f = open("ManipulacaoArquivos.txt", "r") print(f.read(6)) print(f.read(8).strip()) print("===============================") #Você pode retornar uma linha usando o readline()método: f = open("ManipulacaoArquivos.txt", "r") print(f.readline()) print("===============================") #Ao ligar readline()duas vezes, você pode ler as duas primeiras linhas: f = open("ManipulacaoArquivos.txt", "r") print(f.readline()) print(f.readline()) print("===============================") #Ao percorrer as linhas do arquivo, você pode ler o arquivo inteiro, linha por linha: f = open("ManipulacaoArquivos.txt", "r") for x in f: print(x) print("=================================") #É uma boa prática sempre fechar o arquivo quando você terminar com ele. f = open("ManipulacaoArquivos.txt", "r") print(f.readline()) f.close() print("=================================") """Para gravar em um arquivo existente, você deve adicionar um parâmetro à open()função: "a" - Anexar - será anexado ao final do arquivo "w" - Escrever - substituirá qualquer conteúdo existente""" #Abra o arquivo "ManipulacaoArquivos1.txt" e anexe o conteúdo ao arquivo: f = open("ManipulacaoArquivos1.txt", "a") f.write("Now the file has more content!") f.close() #open and read the file after the appending: f = open("ManipulacaoArquivos1.txt", "r") print(f.read()) print("=======================================") #Abra o arquivo "ManipulacaoArquivos2.txt" e sobrescreva o conteúdo: f = open("ManipulacaoArquivos2.txt", "w") f.write("Woops! I have deleted the content!") f.close() #open and read the file after the appending: f = open("ManipulacaoArquivos2.txt", "r") print(f.read()) print('======================================') """Crie um novo arquivo Para criar um novo arquivo no Python, use o open()método com um dos seguintes parâmetros: "x" - Create - criará um arquivo, retornará um erro se o arquivo existir "a" - Anexar - criará um arquivo se o arquivo especificado não existir "w" - Write - criará um arquivo se o arquivo especificado não existir""" #Crie um arquivo chamado "myfile.txt": z = open("myfile.txt", "x") #Crie um novo arquivo, se ele não existir: c = open("myfile.txt", "w") """Para excluir um arquivo, você deve importar o módulo do sistema operacional e executar sua os.remove()função: Exemplo Remova o arquivo "demofile.txt":""" import os os.remove("myfile.txt") #Para evitar um erro,você pode querer verificar se #o arquivo existe antes de tentar excluí-lo: import os if os.path.exists("demofile.txt"): os.remove("myfile.txt") else: print("The file does not exist") #Para excluir uma pasta inteira, use o os.rmdir()método: import os os.rmdir("myfolder")
e74f483ec431b74a3658a2f9eb061838faed45df
easmah/topstu
/variables_strings.py
992
4.09375
4
message = "Hello Python world!" print(message) message = "Hello Python Crash Course world!" print(message) # Strings # title() converts the first character to upper case AND any uppercase in a word to lower name = "ada LoveLace money" print(name.title()) print(name.lower()) print(name.upper()) # Concatenating Strings first_name = "James" last_name = "manstrong" full_name = first_name + " " + last_name print(full_name) print("Hello " + full_name.title() + "!") message = "Hello " + full_name.title() + "!" print(message) print("Languages: \n\tPython\n\tJava\n\tJavascript") # Stripping extra white spaces on the left lstrip()or right rstrip() favourite_language = "python " favourite_language = favourite_language.rstrip() print(favourite_language) favourite_language = " JavaScript" favourite_language = favourite_language.lstrip() print(favourite_language) favourite_language = " nodejs " favourite_language = favourite_language.strip() print("Stripped: " + favourite_language)
214139f20e4e985006912192e1c9b9bcf00f8bb5
Haveon/TeachPython
/2 - Functions and OOP/fib.py
322
3.859375
4
def fib(n): if n <= 2: return [1]*n # list times int is the same as list+list+...+list (n times) else: fibList = [1,1] for i in range(n-2): # We need to substract since we already have the first two numbers fibList.append(fibList[-2] + fibList[-1]) return fibList
fbad29ad49b63317ed450ff2a66c3709680ac6b5
xiaoxiaojiangshang/LeetCode
/leetcode_python/Binary_Tree_Inorder_Traversal_94.py
2,512
3.96875
4
#-*-coding:utf-8-*- # 作者:jgz # 创建日期:2018/11/24 15:55 # IDE:PyCharm import numpy as np # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution1(object): def recursive(self,root,inorder_traversal): if root.left: self.recursive(root.left,inorder_traversal) inorder_traversal.append(root.val) if root.right: self.recursive(root.right,inorder_traversal) def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ inorder_traversal = [] if root: self.recursive(root,inorder_traversal) return inorder_traversal class Solution2(object):# use stack def inorderTraversal(self, root): inorder_traversal = [] stack = [] dict_flag = {} if root: stack.append(root) dict_flag[root] = False while stack : father= stack.pop() if dict_flag[father]: inorder_traversal.append(father.val) else: # stack is oppsite if father.right : stack.append(father.right) dict_flag[father.right] = False stack.append(father) dict_flag[father] = True if father.left: stack.append(father.left) dict_flag[father.left] = False return inorder_traversal class Solution3(object): # use stack def inorderTraversal(self, root): result, stack = [], [(root, False)] while stack: cur, visited = stack.pop() if cur: if visited: result.append(cur.val) else: stack.append((cur.right, False)) stack.append((cur, True)) stack.append((cur.left, False)) return result if __name__ == "__main__": input_data = [1, 2, 3, 4] list_node = [] for data in input_data: list_node.append(TreeNode(data)) list_node[0].left = list_node[1] list_node[0].right = list_node[2] list_node[2].left = list_node[3] inorder_traversal = Solution1().inorderTraversal(list_node[0]) print(inorder_traversal) inorder_traversal = Solution2().inorderTraversal(list_node[0]) print(inorder_traversal)
2b2efcc9a8f602efb9ba5d23d95c6193f7997068
JosephEmmanuel/python_files
/sharkinfo.py
788
4.03125
4
# This is a program to display shark data from data in list. # # Developed by : Joseph Emmanuel # Date : May 2019 sharkNameList=["Blacktip", "Silvertip", "Whitetip", "Megamouth","WhaleShark", "DwarfLantern", "Hammerhead","Bonnethead"] sharkLengthList=[1.5, 2.25, 1.8, 4.5, 12.6, 0.2, 6, 1.5] #in meters sharkWeightList=[123, 162, 18, 750, 21500, 0.1, 580, 50 ] #in Kg sharkInput=input("Enter Only a shark Name:") foundFlag=False for index in range(len(sharkNameList)): if sharkNameList[index]==sharkInput: print("shark Name=",sharkNameList[index]) print("shark Weight=",sharkWeightList[index], " Kg") print("shark Lenght=",sharkLengthList[index], " meters") foundFlag=True if foundFlag==False : print ("Error: Shark name not found in the List")
be6bede8a9004f5ff4203bca841708bb265f5976
TonyBoy22/gittest
/Python/optimization/scipy_minimize.py
2,492
3.671875
4
''' Script to use minimize to solve most common optimization problems LP QCQP result object: result.fun: result of the function to optimize at the value of result.x result.x: minimal value found by optimization result.success: Boolean to indicate that optimization process went well ''' from scipy.optimize import minimize import numpy as np import matplotlib.pyplot as plt ''' First problem is from stochastic model predictive control for lane change decision of automated Driving Vehicles J = [l_1(x - s_ttc,k)**2 + l_2*np.absolute(x - s_dist,k) + l_3*(x - s_CP,k)**2] s_min < s < s_max for k = 1,...,Np help from this tutorial https://www.youtube.com/watch?v=G0yP_TM-oag ''' def fun(x): # constants J = 2*(x - 2.0)**2 + 1.5*np.absolute(x - 7.0) + 3*(x - 3.8)**2 return J # Starting guess x_0 = np.array([5.0]) x_0_test = [[5.0]] print('length initial guess: ', len(x_0), len(x_0_test)) # bounds. Can be tuple for memory size # As a tip about bounds lenght error: # https://stackoverflow.com/questions/29150064/python-scipy-indexerror-the-length-of-bounds-is-not-compatible-with-that-of-x0 bnds = ((0.0, 100.0),) # optimization ''' To give a variable, we need to define a function and we give the callable to scipy.optimize.minimize() It avoids defining symbolic or other ways to declare arbitrary variables ''' # First, let's plot the function to get an intuition x = np.linspace(0, 10.0, 50) # fig1, ax1 = plt.subplots() # ax1.plot(x, fun(x)) # plt.show() result = minimize(fun, x_0, method='SLSQP', bounds=bnds) if result.success: print('result: ', result.x) else: print('optimization failed. result = ', result.fun) ################################################################### # Case 2: Several arguments in the function to minimize # Other Arguments. First, outside of a tuple, then inside a = 5 b = 8 c = -4 tpl = ((a, b, c),) def fun_with_args(x, tpl): ''' Let's try with same cost function J = [l_1(x - s_ttc,k)**2 + l_2*np.absolute(x - s_dist,k) + l_3*(x - s_CP,k)**2] ''' a, b, c = tpl d = a+b+c J = 2 * (x - 2.0) ** 2 + d * np.absolute(x - 7.0) + 3 * (x - 3.8) ** 2 return J def make_constraints(args_in_tuple): constraints = { 'args': args_in_tuple } return constraints cstr = make_constraints(tpl) res = minimize(fun_with_args, x0=np.array([5]), \ method='SLSQP', args=tpl, bounds=bnds) if res.success: print('result: ', res.x) else: print('opt. failed')
cd2375f33affe6ba582ae8b9635a935880dc262e
mnabywan/Kompilatory-lab4
/ast_new.py
3,454
3.609375
4
class Node(object): def __init__(self): self.line = 0 self.column = 0 def accept(self, visitor): return visitor.visit(self) class Program(Node): def __init__(self, instructions): self.instructions = instructions class Instructions(Node): def __init__(self, instructions = []): self.instructions = instructions class IntNum(Node): def __init__(self, value): self.value = value class FloatNum(Node): def __init__(self, value): self.value = value class String(Node): def __init__(self, value): self.value = value class Variable(Node): def __init__(self, name): self.name = name class Ref(Node): def __init__(self, variable, indexes): self.variable = variable self.indexes = indexes class BinExpr(Node): def __init__(self, op, left, right): self.op = op self.left = left self.right = right class Assignment(Node): def __init__(self, left, right): self.left = left self.right = right class AssignmentAndExpr(Node): def __init__(self, op, left, right): self.op = op self.left = left self.right = right class RelExpr(Node): def __init__(self, op, left, right): self.op = op self.left = left self.right = right class UnaryExpr(Node): def __init__(self, op, arg): self.op = op self.arg = arg class For(Node): def __init__(self, variable, range1, instruction): self.variable = variable self.range1 = range1 self.instruction = instruction class While(Node): def __init__(self, condition, instruction): self.condition = condition self.instruction = instruction class If(Node): def __init__(self, condition, instruction, else_instruction=None): self.condition = condition self.instruction = instruction self.else_instruction = else_instruction class Range(Node): def __init__(self, start, end): self.start = start self.end = end class Print(Node): def __init__(self, expressions): self.expressions = expressions class Continue(Node): def __init__(self): pass class Break(Node): def __init__(self): pass class Return(Node): def __init__(self, value=None): self.value = value class Vector(Node): def __init__(self, coordinates): self.coordinates = coordinates def int_dims(self): result = (len(self.coordinates), ) if isinstance(self.coordinates[0], Vector): result += self.coordinates[0].int_dims() return result class MatrixInit(Node): def __init__(self, dim_1, dim_2=None): self.dim_1 = dim_1 self.dim_2 = dim_2 def int_dims(self): if isinstance(self.dim_1, IntNum) and (not self.dim_2 or isinstance(self.dim_2, IntNum)): dim1 = self.dim_1.value if self.dim_2: dim2 = self.dim_2.value else: dim2 = self.dim_1.value return (dim1, dim2) else: return None class Eye(MatrixInit): pass class Zeros(MatrixInit): pass class Ones(MatrixInit): pass class Error(Node): def __init__(self): pass
18d7175cd9bd6f6c6377755ad2b8584220e0c294
Sherin1998/3-assignment-3
/3ass3.py
913
3.921875
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: #1 a=int(input("enter no ")) if(a>0): print("positive") elif(a<0): print("negative") else: print("zero") # In[1]: #2 a=int(input("enter no ")) if(a%2==0): print("even") else: print("odd") # In[2]: #3 a=int(input("enter year ")) if(a%4==0 and a%100!=0): print("leap year") elif(a%100!=0 ): print("not leap year") elif(a%400==0): print("leap year") else: print("not leap year") # In[44]: #4 a=int(input("enter no ")) count=0 if(a>1): for i in range(2,a): if(a%1==0): print("Not prime") break else: print("prime") else: print("Not prime") # In[ ]: #5 for i in range(1,10001): if(i>1): for j in range(2,i): if(i%j==0): break else: print(i) # # 81 # In[ ]:
6271d4621d98e8be412659fbcf61df5f16fcf363
wellington16/BSI-UFRPE
/2016.1/Exércicio LAB DE PROGRAMAÇÃO/Exercício 2016.1/Exercícios/E11/E11.py
6,600
3.8125
4
#coding:utf-8 import sys #Autor Wellington Luiz ''' UNIVERSIDADE FEDERAL RURAL DE PERNAMBUCO - UFRPE Curso: Bacharelado em Sistemas de Informação Disciplina: Laboratório de Programação - 2016.1 Professor: Rodrigo Soares Exercício 11 - Laboratório de Programação título: Juvenal se perdeu. Executado em python 3.5 ''' class No: #def __init__(self,chave,dado): def __init__(self,chave): #self._dado = dado self._filhoesq = None self._filhodir = None self._pai = None self._chave = chave def getChave(self): return self._chave def setChave(self,k): self._chave = k #def getDado(self): #return self._dado #def setDado(self,dado): #self._dado = dado def getFilhoEsq(self): return self._filhoesq def setFilhoEsq(self,filho): self._filhoesq=filho def getFilhoDir(self): return self._filhodir def setFilhoDir(self,filho): self._filhodir=filho def getPai(self): return self._pai def setPai(self,pai): self._pai=pai def __str__(self): return str("Nó: "+str(self.getChave())) #+" "+ self.getDado()) class ArvoreBB: def __init__(self): self._raiz = None def getRaiz(self): return self._raiz def setRaiz(self, no): self._raiz=no def percorrerEmOrdem(self,x, lista): if x != None: self.percorrerEmOrdem(x.getFilhoEsq(), lista) #PERCORRER SUB ARVORE ESQUERDA print("O nó é esse: "+str(x)) #VISITA lista.append(str(x.getChave())) self.percorrerEmOrdem(x.getFilhoDir(), lista) #PERCORRER SUB ARVORE DIREITA return lista def percorrerEmPreOrdem(self, x, lista): if x != None: print("O nó é esse: "+str(x)) #visitando lista.append(str(x.getChave())) self.percorrerEmOrdem(x.getFilhoEsq(), lista)#PercorrendoArvorePelaEsquerda self.percorrerEmOrdem(x.getFilhoDir(), lista)#PercorrendoArvorePelaDireita return lista def percorrerEmPosOrdem(self,x, lista): if x != None: self.percorrerEmOrdem(x.getFilhoEsq(), lista)#PercorrendoArvorePelaEsquerda self.percorrerEmOrdem(x.getFilhoDir(), lista)#PercorrendoArvorePelaDireita lista.append(str(x.getChave())) print("O no é esse: "+str(x)) #visitando return lista def buscar(self,x,k): if x == None or x.getChave() == k: return x if k < x.getChave(): return self.buscar(x.getFilhoEsq(),k) else: return self.buscar(x.getFilhoDir(),k) def minimo(self,x): while x.getFilhoEsq() != None: x = x.getFilhoEsq() return x def maximo(self,x): while x.getFilhoDir() != None: x = x.getFilhoDir() return x def sucessor(self,x): if x.getFilhoDir() != None: return self.minimo(x.getFilhoDir()) y = x.getPai() while y != None and x is y.getFilhoDir(): x = y y = y.getPai() return y def antecessor(self,x): try: if x.getFilhoEsq() != None: return self.maximo(x.getFilhoEsq()) y = x.getPai() while y != None and x == y.getFilhoEsq(): x = y y = y.getPai() return y except: return 0 def inserir(self,z): y=None x = self.getRaiz() while x != None: y=x if z.getChave() <= x.getChave(): x = x.getFilhoEsq() else: x = x.getFilhoDir() z.setPai(y) if y == None: self.setRaiz(z) else: if z.getChave() < y.getChave(): y.setFilhoEsq(z) else: y.setFilhoDir(z) def remover(self,z): if z.getFilhoEsq() == None or z.getFilhoDir() == None: y = z else: y = self.sucessor(z) if y.getFilhoEsq() != None: x = y.getFilhoEsq() else: x = y.getFilhoDir() if x != None: x.setPai(y.getPai()) if y.getPai() == None: self.setRaiz(x) else: if y == y.getPai().getFilhoEsq(): y.getPai().setFilhoEsq(x) else: y.getPai().setFilhoDir(x) if y != z: z.setChave(y.getChave()) z.setDado(y.getDado()) import sys tree = ArvoreBB() #ent=open("e11.txt") #out=open('e11s.txt',"w") ent=open(sys.argv[1]) out=open(sys.argv[2],"w") linha=None caso=1 text="" while True: linha = ent.readline() if linha == '': break tree.setRaiz(None) n=int(linha) text="Caso "+ str(caso) +":\n" for i in range(n): linha=ent.readline() if linha.startswith("A"): l=linha.split(" ") x=int(l[1]) tree.inserir(No(x)) elif linha.startswith("B"): l=linha.split(" ") x=int(l[1]) tree.remover(tree.buscar(tree.getRaiz(), x)) elif linha.startswith("C"): linha.split(" ") x=int(l[1]) node=tree.buscar(tree.getRaiz(), x) try: e = tree.antecessor(node) while e.getChave()== x: e = tree.antecessor(e) text+=str(e.getChave())+"\n" except: text+=str(tree.antecessor(node))+"\n" elif "PRE" in linha: lista=[] lista=tree.percorrerEmPreOrdem(tree.getRaiz(),lista) if len(lista)>0: for i in lista: text+=i+" " text=text[:-1]+"\n" else: text+="0\n" elif "IN" in linha: lista=[] lista=tree.percorrerEmOrdem(tree.getRaiz(),lista) if len(lista)>0: for i in lista: text+=i+" " text=text[:-1]+"\n" else: text+="0\n" elif "POST" in linha: lista=[] lista=tree.percorrerEmPosOrdem(tree.getRaiz(),lista) if len(lista)>0: for i in lista: text+=i+" " text=text[:-1]+"\n" else: text+="0\n" caso += 1 out.write(text) text="" out.close()
e58cca47181af187db75c67f35678762657c6d9d
ferdlgr/Compilers19
/PARSER_A01366101/lexer.py
2,473
3.59375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This program is expected to pass throug its function the variables received throught the script and file reading to the global variables, making use of the globalTypes program, its values and tools, print each token found in the iput file and its definition previously found in gloobalTypes, in order to execute the program look at the file 'scripting.py' . This program was coded as part of the Compiler's design class for the period Aug-Dec 2019 ITESM. A01366101 Ma. Fernanda Delgado Radillo """ #variables y definiciones #from globalTypes import lexical #objeto from ply import * #tokens keywords = { 'int': 'INT', 'void': 'VOID', 'while': 'WHILE', 'if': 'IF', 'else': 'ELSE', 'return': 'RETURN' } # symbols tokens = [ 'PLUS','MINUS', 'TIMES','DIVIDE', 'LT','LE', 'GREATER','LESS', 'COMPARE','NE', 'EQUAL','SEMICOLON', 'COMMA','LPAREN', 'RPAREN', 'LBRACKET', 'RBRACKET','LBLOCK', 'RBLOCK','COMMENTS', 'ID', 'NUMBER','ENDFILE' ] + list(keywords.values()) # Define regular expressions t_PLUS = r'\+' t_MINUS = r'-' t_TIMES = r'\*' t_DIVIDE = r'/' t_COMMA = r'\,' t_LPAREN = r'\(' t_RPAREN = r'\)' t_LBRACKET = r'\[' t_RBRACKET = r'\]' t_LBLOCK = r'\{' t_RBLOCK = r'\}' t_LESS = r'<' t_GREATER = r'>' t_LE = r'<=' t_LT = r'>=' t_COMPARE = r'==' t_NE = r'!=' t_EQUAL = r'=' t_SEMICOLON = r';' t_ENDFILE = r'\$' t_ignore = ' \t' from enum import Enum class TokenType(Enum): ENDFILE = '$' literals = ['*','/','+','-'] def t_ID(t): r'[a-zA-Z][a-zA-Z]*' t.type = keywords.get(t.value, 'ID') return t def t_newline(t): r'\n+' t.lexer.lineno += len(t.value) def t_COMMENT(t): # Regex to identify comment block, do nothing r'\/\*(\*(?!\/)|[^*])*\*\/' t.lexer.lineno += t.value.count('\n') pass def t_NUMBER(t): r'\d+' # ID that starts with numbers if t.lexer.lexdata[t.lexpos + len(t.value)].isalpha(): t_error(t) t.value = int(t.value) return t def t_error(t): errorline = t.lexer.lineno line = t.lexer.lexdata.split('\n')[errorline - 1] tabPos = line.find(t.lexer.lexdata[t.lexer.lexpos]) print("Error de Sintaxis en " + str(errorline) + ":" + str(tabPos)) print(line) print(' ' * tabPos + '^') t.lexer.skip(1) lexer = lex.lex()
6519f77fff9130d644a0d161a4bc6f792d477480
malluri/python
/23.py
176
3.9375
4
#23. Write a program to findout big of two numbers num1=input("enter the num1:") num2=input("enter the num2:") big=0 if(num1>num2): big=num1 else: big=num2 print(big)
e7d2d969242fd3f5593bc491f6eb50b2acafd530
giveseul-23/give_Today_I_Learn
/80_pythonProject/mss06.py
112
3.71875
4
for i in range(1, 6, 1): # print() for j in range(0, i, 1): print("🌹", end=" ") print()
420f1ca50e7c9f031673083b61c91bda706aa0b3
muru4a/python
/Leetcode/removeDuplicates.py
475
4.0625
4
def removeDuplicates(s: str) -> str: """ use the stack check the element equal to last element in stack and pop the element current string character not equal to last element in stack and add the element in stack """ result = [] for row in s: if result and row == result[-1]: result.pop() else: result.append(row) return ''.join(result) if __name__ == "__main__": print(removeDuplicates("abbaca"))
1d8760a431ea943c6b87b47d445921aa962d8b7b
theodormunteanu/bond_and_swap
/bond_prices.py
5,159
3.6875
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 24 19:33:23 2018 @author: theod """ def bond_price(FV, c, T, rate, freq=4, t=0, freq2=0, **opt): r""" Returns the price of a bond given the zero-rates or a yield Parameters ---------- `FV` : face value of the bond (float/int). `c` : coupon rate (expressed in numbers between 0 and 1) `T` : time to maturity (expressed in years) `rate` : can be a single float number or a tuple containing maturities and zero rates `rate` can be of the following types: 1. `int` or `float`: a single discounted rate 2. `tuple` of two elements: the first element is a list of maturities while the second component is a list of interest rates (spot rates) `freq` : frequency of payments per year. By default it is set to 4, quarterly payments. `t` : time when the bond is evaluated `freq2` : compounding frequency (by default is set to 0, which means continuous discounting) \ `option` : contains the option of clean price or dirty price: \ For the clean price it substracts the accrued coupon from the dirty price Examples -------- 1. Compute the price of a 2-year bond with a single yield rate of 6.76%, semi-annual coupons with annual coupon rate of 6%. Source: John Hull, Options, Futures and Other Derivatives (8th edition), section 4.4: Bond prices --> Bond yield >>> bond_price(100,0.06,2,0.676,2) Result: 98.38 2. Compute the price of a 2-year bond with treasury rates 5%, 5.8%, 6.4% and 6.8% corresponding to 6M, 12M, 18M and 24M if the coupon is 6% per year and the payment frequency is twice/year. Source: the same but the intro section of Bond pricing instead >>> bond_price(100,0.06,2,([0.5,1,1.5,2],[0.05,0.058,0.064,0.068]),2) Result: 98.38 """ if isinstance(rate,tuple) and isinstance(rate[0],list) and isinstance(rate[1],list): if opt.get("option") in {"dirty price",None}: return bond_price2(FV,c,T,rate,freq,t,freq2) elif opt.get("option") == "clean price": return bond_price2(FV,c,T,rate,freq,t,freq2)-accrued_coupon(FV,c,t,T,freq) elif isinstance(rate, (int, float)): if opt.get("option") in {"dirty price", None}: return bond_price1(FV, c, T, rate, freq, t, freq2) elif opt.get("option")=="clean price": return bond_price1(FV,c,T,rate, freq, t, freq2)-accrued_coupon(FV,c,t,T,freq) def bond_price1(FV, c, T, r, freq=4, t=0, freq2=0): def times(t,T,freq = 4): r"""The above function gives the times of cash-flows posterior to time t""" import numpy as np if freq*(T-t)==int(freq*(T-t)): k = int(freq*(T-t)) return np.linspace(T-(k-1)/freq,T,k,endpoint = True) else: k = int(freq*(T-t))+1 return np.linspace(T-(k-1)/freq,T,k,endpoint = True) import numpy as np if t==T: return FV + (c/freq+1)*FV elif t>T or t<0: raise TypeError('the time when you want to evaluate the bond surpasses\ the lifetime of the bond or it is negative') else: time_points = times(t,T,freq) k = len(time_points) if freq2==0: disc_rates = [np.exp(-r*(time_points[i]-t)) for i in range(k)] else: disc_rates = [1/(1+r/freq2)**(freq2*(time_points[i]-t)) for i in range(k)] cash_flows = [c/freq*FV]*k cash_flows[-1]=cash_flows[-1]+FV return np.dot(disc_rates,np.array(cash_flows)) def bond_price2(FV,c,T,rates,freq=4,t=0,freq2 = 0): import numpy as np def times(t,T,freq = 4): if freq*(T-t)==int(freq*(T-t)): k = freq*(T-t)-1 else: k = int(freq*(T-t)) return np.linspace(T-k/freq,T,(k+1),endpoint = True) if t==T: return FV + (c/freq+1)*FV elif t>T or t<0: raise TypeError('the time when you want to evaluate the bond surpasses\ the lifetime of the bond or it is negative') else: time_points = times(t,T,freq) k = len(time_points) app_rates = [np.interp(time_points[i],rates[0],rates[1])\ for i in range(k)] if freq2==0: disc_rates = [np.exp(-app_rates[i]*(time_points[i]-t)) for i in range(k)] else: disc_rates = [1/(1+app_rates[i]/freq2)**(freq2*(time_points[i]-t)) for i in range(k)] cash_flows = [c/freq*FV]*k cash_flows[-1]=cash_flows[-1]+FV return np.dot(disc_rates,np.array(cash_flows)) def accrued_coupon(FV,c,t,T,freq=4): def last_time(t,T,freq = 4): if freq*(T-t)==int(freq*(T-t)): k = freq*(T-t)-1 else: k = int(freq*(T-t)) return T-(k+1)/freq return FV*c/freq * (t-last_time(t,T,freq))
03af04dc18cc77b611d748331e67226bb92f1776
minhd2/time2code
/sort_by_date/sort_by_date.py
592
3.796875
4
import re from datetime import datetime def sort_by_date(file): file_date_dict = {} pattern = r"\w* \d+, \d{4}" with open(file, 'r') as file: for line in file: columns = line.split() date = re.search(pattern, line) print(line) file_date_dict[columns[-1]] = file_date_dict.get(columns[3], date.group(0)) sorted_by_date_dict = sorted(file_date_dict.items(), key = lambda x:datetime.strptime(x[1], '%B %d, %Y'), reverse=True) return sorted_by_date_dict #below to print each one line by line. #for pair in sorted_by_date_dict: #print(pair) sort_by_date('data.txt')
db84345e8acb1882fdaecfec8a7536ec5920ba38
mprotti/CursoPhyton
/examen04.py
799
3.78125
4
def romano_a_numero(numero_romano): resultado = 0 valores = { 'M' : 1000, 'D' : 500, 'C' : 100, 'L' : 50, 'X' : 10, 'V' : 5, 'I' : 1 } if len(numero_romano) > 0: valor_anterior = 0 for letra in numero_romano: if letra in valores: valor_actual = valores[letra] else: print ('Valor invalido:' + letra) return 'NaN' if valor_anterior >= valor_actual: resultado += valor_actual else: resultado += valor_actual - (2 * valor_anterior) valor_anterior = valor_actual return resultado numero_romano = input("Ingrese el Numero Romano a evaluar: ").upper() print ("Numero : " + str(romano_a_numero(numero_romano)))
f018e1f0412108c3756ffb441ff0eec4dea8c93b
rahuldbhadange/Python
/Python/__File handling/files/6 readlines/readlines.py
274
4.125
4
#readlines() f=open("hello.txt") x=f.readlines() # reads all the lines and stores in a list x print(x) # printing the list x #printing each line seperately for p in x: print(p) f.close() # whenever we close a file, it will be used by #another person
7f2995d3eeeb9dd1468bf326943f496709e958e3
mennatarek204/GPA-calculator
/GPA Calculator.py
1,458
4.125
4
# new dictionary to save keys with their right values score_map = { 'A+' : 4, 'A' : 3.83, 'A-' : 3.66, 'B+' : 3.33, 'B' : 3, 'B-' : 2.66, 'C+' : 2.33, 'C' : 2, 'C-' : 1.66, 'D+' : 1.33, 'D' : 1, 'F' : 0, } #lists of needed data grades = [] CreditHours = [] #function to collect and calculate user inputs def collect(): t = int(input("enter number of terms: ")) c = int(input("enter number of courses: ")) overall_GPA =0 for i in range(t): print("\nenter courses of term %d " % (i+1)) for j in range(c): course_name = input("\nenter course name %d: " % (j+1)) grade_letters = input("enter grade letters %d: " % (j+1)) grades.append(grade_letters) credit = int(input("enter credit hour %d: " % (j+1))) CreditHours.append(credit) GPA = sum(score_map[grade_letters]*credit for grade_letters in grades) / sum(CreditHours) overall_GPA+=GPA print("GPA of term %d = " % (i+1), GPA) overall_GPA =overall_GPA/t print("The overall GPA = ", overall_GPA) if 3.6<=overall_GPA<=4: print("The Final Grade is Excellent") elif 3<=overall_GPA<=3.6: print("The Final Grade is Very Good") elif 2.6<=overall_GPA<=3: print("The Final Grade is Good") else: print("The Final Grade is Pass") print(collect())
000b65a98ba01cf22a91dcc4fcd274528d5f7d2f
hamil168/Data-Science-Misc
/Misc Learning/HackerRank 30 Days of Code/Additional Practice Problems/CountDiv.py
1,904
3.75
4
"""CountDiv Practice Problem by Codility Solution by B Hamilton 7/24/2018 given three integers A, B and K, return the number of integers within the range [A..B] that are divisible by K, i.e.: { i : A ≤ i ≤ B, i mod K = 0 } For example, for A = 6, B = 11 and K = 2, function should return 3, because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10. Assume that: A and B are integers within the range [0..2,000,000,000]; K is an integer within the range [1..2,000,000,000]; A ≤ B. Complexity: expected worst-case time complexity is O(1); expected worst-case space complexity is O(1). """ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A, B, K): # write your code in Python 3.6 # This is in the "prefix sum" section # But I don't think we need a prefix sum # We just need the values and # Intuition return ( (B - A)// K + 1) """ RESULT: 50% of Task Score 75% of Performance 25% of Correctess Having difficulty with this one. Will need to research further! Failed on: A=B in {0,1}, K = 11 for A=B=1 got 1 expected 0 - A=10, B = 10, K in {5, 7, 20} for 5 and 20 (got 1 expected 0 ) Failed o A=101, B = 123M, K = 10K (Got 12346 expected 12345) """ def solution2(A, B, K): # write your code in Python 3.6 # B is inclusive.... so 0 to 10k is 10k+1 # Floor returns the integer part of the division result # e.g. 9 // 2 = 4 # Modulo returns remainder part of the division result # e.g. 9 % 2 = 1 # edge cases: A, B small (1)... # edge case A,B same # edge case: B >> A (0 to 10k, 1) # edge case B > A, Large K # the max(A%K,2) is saying it will take the highest # max(A%K,K) means "give the remainder of A%K, # but count 0 as a full K instead of 0 return ( ((B-A) + max(A%K, K)) // K) """RESULT: Exactly the same. """
53fa6cb89a3723b11d2a2f542fcc887f81d3b1e2
ssarangi/algorithms
/hackerrank/strings/morgan_and_a_string.py
1,015
3.671875
4
__author__ = 'sarangis' """ Jack and Daniel are friends. Both of them like letters, especially upper-case ones. They are cutting upper-case letters from newspapers, and each one of them has their collection of letters stored in separate stacks. One beautiful day, Morgan visited Jack and Daniel. He saw their collections. Morgan wondered what is the lexicographically minimal string, made of that two collections. He can take a letter from a collection when it is on the top of the stack. Also, Morgan wants to use all the letters in the boys' collections. Input Format The first line contains the number of test cases, T. Every next two lines have such format: the first line contains string A, and the second line contains string B. Constraints 1≤T≤5 1≤|A|≤105 1≤|B|≤105 A and B contain upper-case letters only. Output Format Output the lexicographically minimal string S for each test case in new line. Sample Input 2 JACK DANIEL ABACABA ABACABA Sample Output DAJACKNIEL AABABACABACABA """
3f27e150d659df7b73892fed64173fc543d7559b
eanshuk/Python-Assignment
/Python Assignment/Exercise6.py
1,624
3.6875
4
import random class Aircraft: x=0 y=0 acceleration=1 def __init__(self, obj_no, new_x=0, new_y=0): print "Aircraft # ",obj_no self.flight_number = obj_no self.x=new_x self.y=new_y class Boeing_747(Aircraft): destination_x=0 destination_y=0 def __init__(self, obj_no=0): Aircraft.__init__(self,obj_no, new_x=0, new_y=0) self.x=random.randint(1,101) self.y=random.randint(1,101) self.destination_x=random.randint(1,101) self.destination_y=random.randint(1,101) def flight_path(self, x_path): m=float(self.destination_x - self.x) / float(self.destination_y - self.y) b= self.y - (m * self.x) return float((m*x_path)+ b) def Aircraft_acceleration(self): return self.acceleration anurag_airlines= [] for i in range(0,5): anurag_airlines.append(Boeing_747(i+1)) end=anurag_airlines[i].destination_x start = anurag_airlines[i].x if(anurag_airlines[i].x > anurag_airlines[i].destination_x): start=anurag_airlines[i].destination_x end =anurag_airlines[i].x print "Sarting from: (",start,",",anurag_airlines[i].flight_path(start) ,")" print "Headed to: (",end,",", anurag_airlines[i].y,")" else: print "Sarting from: (",start,",",anurag_airlines[i].y ,")" print "Headed to: (",end,",",anurag_airlines[i].flight_path(end) ,")" for j in range(start, end+1): print j,", ",anurag_airlines[i].flight_path(j) print "We have arrived!" print "Acceleration constant:",anurag_airlines[i].Aircraft_acceleration()
a63cb23be4f85f4726f45a3e21ef2354ac9f9940
YazanAhmad18/data-structures-and-algorithms-python
/data_structures/hash_table/hash_table/linked_list.py
1,471
4.03125
4
class Node: def __init__(self,value): self.value= value self.next= None class Linkedlist: def __init__(self): self.head = None def insert(self, value): node = Node(value) if self.head == None: self.head = node return self.head.value else: current = self.head self.head = node self.head.next = current return self.head.value def includes(self,value): if self.head: current =self.head while current: if current.value == value: return True current = current.next return False else: raise Exception("Sorry, this list is empty , so plz insert a value") def __str__(self): if self.head: data_str = '' current = self.head while current: data_str += '{'+str(current.value)+'}-> ' current = current.next data_str += 'NULL' return data_str else: data_str = 'NULL' return data_str def append(self, value): new_node = Node(value) if self.head == None: self.head = new_node else: current = self.head while current.next: current = current.next current.next = Node(value)
5af707aea2edc11a15856fc247d0b0ca1c2816e0
spradeepv/dive-into-python
/hackerrank/contests/accel/balanced_string.py
2,037
3.875
4
""" A balanced string is a string having the following properties: Both the left and right halves contain the same characters. Both the left and right halves contain unique characters. For example, abbaabba is balanced because the left half (abab) and the right half (baba) both contain the same unique characters. Xavier has NN unique characters in unlimited supply and wants to use them to make balanced strings. Help him determine PP, the number of possible balanced strings of length NN. Input Format The first line contains an integer, TT, the number of test cases. The TT subsequent lines each contain a single integer, NN, the number of characters Xavier can use to form his balanced strings for that test case. Constraints N will always be evenN will always be even Xavier's balanced strings must be of length NXavier's balanced strings must be of length N Output Format For each test case, print the result of P % (109+7)P % (109+7) on a new line. Constraints 1<=T<=100000 2<=N<=10^6 Sample Input 1 2 Sample Output 2 Explanation N=2 Xavier has two characters we'll refer to as 1 and 2. He must use these characters to form balanced strings of length 22. The possible strings are "11", "12", "21", and "22". Of those 44 strings, only 22 are balanced (i.e.: "11" and "22"), so we print the result of 2 % (10^9+7)2 on a new line. Editorial --------- N is even number so to make string balance right half and left half both having N/2 characters should contains equal and same set of characters. For right half Xrange have N unique characters so there will be N*(N-1)*( N-2)*......(N/2+1) possible strings that can be formed with N unique characters. For each right half string there will be (N/2)! possible left half strings. So the answer will be N*(N-1)*(N-2)*....(N/2+1)*((N/2)!) that will be equal to N! """ mod = int(1e9) + 7 fact = [1, 1] def facto(): for i in range(2, 1000001): fact.append((fact[-1]*i) % mod) facto() for _ in range(int(raw_input())): n = int(raw_input()) print fact[n]
6f62b109afb9bf94716e6b91d592969d6dfd11dd
Pruthvi77/Cent
/ML/Exception_Handling.py
304
3.59375
4
#1 try: val = 5/0 except : print("Error : incorrect mathmatical expression") #2 subjects=["Americans ","Indians "] verbs=["play ","watch "] objects=["Baseball","Cricket"] FinalList = [sub+ ver+ obj for sub in subjects for ver in verbs for obj in objects] for item in FinalList: print(item)
a8be3bdafb0b75bdd14e52fd6d1f3d2cec1bf94c
Phyopyosan/Exercises
/Variable.py
773
3.609375
4
#27.12.2019 + _ * / % ** >>> 2 + 2 4 >>> 50 - 5 * 6 20 >>> (50 -5 * 6) / 4 5.0 >>> round(5.0) 5 >>> 5.123456 5.123456 >>> round(5.123456,2) 5.12 >>> 17 / 3 5.6666666667 >>> 17 // 3 5 >>> 18 // 4 4 >>> 20 // 5 4 >>> 17 % 3 2 >>> 17 * 4 % 3 2 a = 1 a (variable) = (assign) 1 (value) weight = 20 height = 5 * 9 vol = weight * height vol sale = 300000 tax = 5/100 total_tax = sale * tax total_tax total_price = sale + total_tax total_price print('spam eggs') print('don\'t') print("doesn't") print('"Yes"') print("\'Yes, \" They said.") print('"Isn\'t, " They said') s = 'First Line.\nSecond Line.' print(s) print("""\ Usage: thingy -a -b -c """ ) """...""" or """...""" 3 * 'A' 2 * 'BC' + 'DE' 10 * 'GH' + 3 >>> List
9d1804617c28fa2f8de8a9323163ea8027a4cc6d
USER0721/AE401-20200720
/random.py
264
3.65625
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 3 17:30:50 2020 @author: user """ import random thm = random.randint(1,10) n = input("猜一個數字:") n = int(n) if thm == n: print("yes") else: print("no")
eecb5dc89c55a0a71342e9775495a73be2f4d46c
joanwanjiku/marvel-comics
/tests/test_character.py
291
3.515625
4
import unittest from app.models import Character class CharacterTest(unittest.TestCase): def setUp(self): self.new_character = Character(1, 'thor', 'he is amazing', '/hsfhdhgd') def test_instance(self) self.assertTrue(isinstance(self.new_character, Character))
3fe0e5c3fd08074abc2d7b60f5b799b5b0acb538
kunal-singh786/basic-python
/loop hackerrank.py
176
4.09375
4
'''Task Read an integer . For all non-negative integers , print . See the sample for details''' if __name__ == '__main__': n = int(input()) for i in range(n): print(i**2)
3d943455fc233dd6ac9ba3f714d366077aea9129
greeshma0601/Python-Language
/Dictionary/Set in Python - II.py
2,557
4.40625
4
''' Set in Python - II This is the last practice question of Python Set. You are familiar with working on set in Python. Now, let's move on to work on two sets using some inbuilt functions which are used widely. They are: union(): Used to find union() between two sets. This is performed using '|' operator. intersection(): Used to find intersection() between two sets. This is performed using '&' operator. difference(): Difference of A and B (A - B) is a set of elements that are only in A but not in B. Similarly for B-A holds same. Now, Given some elements in two sets, the task is to find the elements common in two sets, elements in both the sets, elements which are only in set B, not in A. Input: First line of input contains number of testcases T. For each testcase, first line of input contains elements of first set and next line contains elements of another set. Output: For each testcase, print the elements in the set after each operation. Constraints: 1 <= T <= 100 1 <= S[i] <= 104 User Task: To complete the function all_in_set(), common_in_set() and diff() to perform union, intersection and difference between two sets. Example: Input: 1 1 2 3 4 5 6 7 8 2 3 Output: 1 2 3 4 5 6 7 8 2 3 1 4 5 ''' #Initial Template for Python 3 //Position this line where user code will be pasted. # Driver code def main(): testcase = int(input()) # looping through all testcases while testcase > 0: # taking input of set a = {int(x) for x in input().split()} b = {int(x) for x in input().split()} for x in all_in_set(a, b): print (x, end = ' ') print () for x in common_in_set(a, b): print (x, end = ' ') print () for x in diff(a, b): print (x, end = ' ') print () testcase -= 1 if __name__ == '__main__': main() } ''' Please note that it's Function problem i.e. you need to write your solution in the form of Function(s) only. Driver Code to call/invoke your function is mentioned above. ''' #User function Template for python3 # Function to find common elements in sets # should return the intersection of sets def common_in_set(a, b): # Your code here return a&b # Function to find difference in sets # Should return the difference in sets def diff(a, b): return a-b# Your code here # Function to find union of sets # Should return the union of sets def all_in_set(a, b): # Your code here return a|b
6538b5231fe4b7d5af5c6a605dc98ecf976433a9
jxhangithub/lintcode
/Easy/141. Sqrt(x)/Solution.py
532
4
4
class Solution: """ @param x: An integer @return: The sqrt of x """ def sqrt(self, x): # write your code here if (x == 0): return x start, end = 1, x while (start + 1 < end): mid = (end - start) // 2 + start if (mid ** 2 == x): return mid elif (mid ** 2 > x): end = mid else: start = mid if (start ** 2 <= x): return start else: return end
941c08d45bcaaf8ba13ffff395b5a2596ec45aa9
anshuman2197/Python-Internshala
/prob32.py
634
3.953125
4
class Polygon: def __init__(self,sides): self.sides= sides def display_info(self): print("A polygon is a two dimensional shape with straight lines") def get_perimeter(self): perimeter=sum(self.sides) return perimeter class Triangle(Polygon): def display_info(self): print("A triangle is a ploygon with 3 edges") super().display_info() class Quadrilateral(Polygon): def display_info(self): print("A quadrilateral is a polygon with a 4 edges") t1=Triangle([5,6,7]) perimeter=t1.get_perimeter() print(perimeter) t1.display_info()
1323be42087cfd794ba2b544f5024abd370d879a
notconfusing/tulsa-early-warning-system
/tulsa/learn/splits.py
6,416
3.65625
4
import pandas as pd import numpy as np from sklearn.cross_validation import train_test_split def make_splits(split_strategy, stuterm_df, label_feature_df, engine): """ Makes a list of (X_test, X_train, y_test, y_train) splits :param split_strategy: refers to type of split used :param stuterm_label_feature_df: studentid, year, season, label, feature data :param engine: a db engine to use :type split_strategy: str :type stuterm_label_feature_df: pandas DataFrame :type engine: sqlalchemy engine :returns: list of four pandas DataFrames -- X_ dfs have features, y_ dfs have labels """ if split_strategy == '80/20': X = label_feature_df.iloc[:,1:].as_matrix() y = label_feature_df.iloc[:,0].as_matrix() return [train_test_split(X, y, test_size=0.2, random_state=0)] elif split_strategy == 'cohort': return make_cohort_test_train_split(stuterm_df,label_feature_df, engine) elif split_strategy == 'predict_new': return make_second_grade_train_predict_split(stuterm_df,label_feature_df, engine) else: # no such split strategy raise NotImplementedError def make_cohort_test_train_split(stuterm_df, label_feature_df, engine): """ Makes a list of (X_test, X_train, y_test, y_train) splits based on cohort splitting strategy :param stuterm_label_feature_df: studentid, year, season, label, feature data :param engine: a db engine to use :type stuterm_label_feature_df: pandas DataFrame :type engine: sqlalchemy engine :returns: list of four pandas DataFrames -- X_ dfs have features, y_ dfs have labels """ stuterm_df['grade'] = make_grade_column(stuterm_df, engine) splits = {} grade2_years = ['13_14', '14_15'] for test_year in grade2_years: train_years = [year for year in grade2_years if year != test_year] train_ids = stuterm_df.loc[(stuterm_df['measured_year'].isin(train_years))&(stuterm_df['grade']==2), 'studentid'] test_ids = stuterm_df.loc[(stuterm_df['measured_year']==test_year)&(stuterm_df['grade']==2), 'studentid'] train_stuterm = stuterm_df[stuterm_df['studentid'].isin(train_ids)] test_stuterm = stuterm_df[stuterm_df['studentid'].isin(test_ids)] train_indexes = train_stuterm.index test_indexes = test_stuterm.index X_train = label_feature_df.iloc[train_indexes, 1:] X_test = label_feature_df.iloc[test_indexes, 1:] y_train = label_feature_df.iloc[train_indexes, 0] y_test = label_feature_df.iloc[test_indexes, 0] splits[test_year] = {'X_train': X_train, 'X_test': X_test, 'y_train': y_train, 'y_test': y_test, 'train_stuterm': train_stuterm, 'test_stuterm': test_stuterm} return splits def make_second_grade_train_predict_split(stuterm_df, label_feature_df, engine): """ Makes a list of (X_test, X_train, y_test, y_train) splits based on splitting strategy where all training set is all students who have completed grade 3 and test set is those who have not completed to be predicted NOTE: returns y_test but this is superfluous :param stuterm_label_feature_df: studentid, year, season, label, feature data :param engine: a db engine to use :type stuterm_label_feature_df: pandas DataFrame :type engine: sqlalchemy engine :returns: list of four pandas DataFrames -- X_ dfs have features, y_ dfs have labels """ stuterm_df['grade'] = make_grade_column(stuterm_df, engine) grade2_years = ['13_14', '14_15'] test_year = '15_16' train_years = [year for year in grade2_years if year != test_year] train_ids = stuterm_df.loc[(stuterm_df['measured_year'].isin(train_years))&(stuterm_df['grade']==2), 'studentid'] test_ids = stuterm_df.loc[(stuterm_df['measured_year']==test_year)&(stuterm_df['grade']==2), 'studentid'] train_stuterm = stuterm_df[stuterm_df['studentid'].isin(train_ids)] test_stuterm = stuterm_df[stuterm_df['studentid'].isin(test_ids)] train_indexes = train_stuterm.index test_indexes = test_stuterm.index X_train = label_feature_df.iloc[train_indexes, 1:] X_test = label_feature_df.iloc[test_indexes, 1:] y_train = label_feature_df.iloc[train_indexes, 0] y_test = label_feature_df.iloc[test_indexes, 0] splits = {} splits[test_year] = {'X_train': X_train, 'X_test': X_test, 'y_train': y_train, 'y_test': y_test, 'train_stuterm': train_stuterm, 'test_stuterm': test_stuterm} return splits def make_grade_column(stuterm_df, engine): """ Appends a column indicate which grade a student belongs to. :param stuterm_label_feature_df: studentid, year, season, label, feature data :param engine: a db engine to use :type stuterm_label_feature_df: pandas DataFrame :type engine: sqlalchemy engine :returns: pandas DataFrame """ dem_query = """ SELECT student_number, grade_level, measured_year FROM clean_data.demographics """ dem = pd.read_sql_query(dem_query, engine) #join stuterm_df with grades df = stuterm_df.merge(dem, how = 'left', left_on = ['studentid', 'measured_year'], right_on = ['student_number', 'measured_year']) # Need to fill in NA grades # but only if NA year is less than grade 3 year sid_na = list(set(df.loc[np.isnan(df['grade_level']), 'studentid'])) for sid in sid_na: gr3_year = df.loc[(df['studentid']==sid) & (df['grade_level']==3), 'measured_year'].tail(1) if len(gr3_year)==0: pass else: na_year = df.loc[(df['studentid']==sid) & (np.isnan(df['grade_level'])), 'measured_year'].head(1) if int(str.split(gr3_year.iloc[0,], "_")[0]) > int(str.split(na_year.iloc[0,], "_")[0]): imp_grade = 3 - (int(str.split(gr3_year.iloc[0,], "_")[0]) - int(str.split(na_year.iloc[0,], "_")[0])) df.loc[(df['studentid']==sid)&(np.isnan(df['student_number'])), 'grade_level'] = imp_grade else: pass return df['grade_level']
1e300bc0dabebd7e2845f6633e6981d12ff574c1
nagesh-animineni/Helloworld
/list_test.py
83
3.640625
4
list1=[2,3,4,56,6] #for var in list: print(",".join( repr(e) for e in list1))
25e8093fe936ba70c51830c9a6ccba8a10d14184
luizhuaman/platzi_python
/practica.py
559
4
4
#AREA DE UN TRIANGULO base=int(input("Ingresar base\n")) altura=int(input("Ingresar altura\n")) print("El area del triangulo es:",int(base*altura/2)) #dolares a soles dolares=float(input("Ingresar los dolares a cambiar\n")) # print("Su cambio en soles es ",(dolares*3.52)) #otra forma print(f'Cambio: ${float(dolares * 3.52)}') #comparar edades var1=int(input("Ingrese edad 1:\n")) var2=int(input("Ingrese edad 2:\n")) # igual_is = var1 is var2 # print("Las edades son iguales?\nrpta:",igual_is) #Otra forma print(f"Tienen la misma edad?: {var1 is var2}")
4a357fa110d38c62a3dd3ee46b3301328b225d4b
airlay/test
/isInterleaving.py
1,084
4.34375
4
def isInterleaving(str1, str2, str3): ''' str3 is interleaving of str1 and str2 if it can be form by interleaving the characters of str1 and str2 in a way that maintains the left to right order of the characters from each string e.g. aabx, bbax, aabbxax -> true, aabx, bbax, axabbbx -> false ''' str1len = len(str1) str2len = len(str2) str3len = len(str3) # if str3 is not sum of str1 and str2, False if str1len + str2len != str3len: return False # if all strings are empty, return True if str1len == str2len == str3len == 0: return True i = 0 j = 0 k = 0 while k < str3len: if str3[k] == str1[i]: # check against first string i += 1 elif str3[k] == str2[j]: # check against second string j += 1 else: # none of them match return False k += 1 if i == str1len and j == str2len and k == str3len: return True else: return False if __name__ == '__main__': print(isInterleaving('XXYM', 'XXZT', 'XXXZXYTM'))
b765508ec890622681d48ca9a45a929064f9992a
jimmykobe1171/leetcode
/linked_list/linked_list_cycle_2.py
728
3.859375
4
# Linked List Cycle II # tortoise and hare algorithm # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a list node def detectCycle(self, head): faster_node = head slower_node = head while slower_node and faster_node and faster_node.next: slower_node = slower_node.next faster_node = faster_node.next.next if faster_node == slower_node: while head != slower_node: head = head.next slower_node = slower_node.next return head return None
230fd3cbf46e262852dc09e1ebfbcdeb8f049dfd
res0nat0r/exercism
/python/diffie-hellman/diffie_hellman.py
826
3.84375
4
""" Alice and Bob use Diffie-Hellman key exchange to share secrets. They start with prime numbers, pick private keys, generate and share public keys, and then generate a shared secret key. """ from random import randint def private_key(p): """ Return the private key :param int p: private key :return: private key """ return randint(1, p - 1) def public_key(p, g, private): """ Return the public key :param int p: public key :param int g: power :param int private: private key :return: public key """ return pow(g, private) % p def secret(p, public, private): """ Return the secret key :param int p: public key :param int public: public key :param int private: private key :return: secret """ return pow(public, private) % p
257984583d2a8bb07bcb36f9656436b2912aadb9
1633376/NUR-Assigment-2
/Code/mathlib/statistics.py
8,395
3.6875
4
import numpy as np import mathlib.sorting as sorting def kstest(x, cdf): """ Perform the Kolmogorov-Smirnov test for goodness of fit and return the p-value. In: param: x -- An array with value's who's CDF is expected to be the same as the provided CDF. Must be atleast size 4 param: cdf -- A function that is the expected cdf under the null hypothesis. Out: return: The p-value obtained by performing the KS-test. """ # Amount of values in the input array. x_size = len(x) # Sort the values and evaluate the cdf. x_sorted = sorting.merge_sort(x) x_sorted_cdf = cdf(x_sorted) # Maximum distance. max_dist = 0 # Value of the emperical cdf at step i-1. x_cdf_emperical_previous = 0 # Find the maximum distance. for idx in range(0,x_size): # Calculate the emperical cdf. x_cdf_emperical = (idx+1)/x_size # The true cdf evaluation at the given point. x_cdf_true = x_sorted_cdf[idx] # Find the distance. The emperical # CDF is a step function so there are two distances # that need to be checked at each step. # Calculate the two distances distance_one = abs(x_cdf_emperical - x_cdf_true) distance_two = abs(x_cdf_emperical_previous - x_cdf_true) # Find the maximum of those two distances and # check if it is larger than the current know maximum distance. max_dist = max(max_dist, max(distance_one, distance_two)) # Save the current value of the emperical cdf. x_cdf_emperical_previous = x_cdf_emperical # Calculate the p-value with the help of the CDF. sqrt_elemens = np.sqrt(x_size) cdf = _ks_statistic_cdf((sqrt_elemens + 0.12+0.11/sqrt_elemens)*max_dist) return 1 - cdf def kstest2(x1, x2, x2_sorted = None): """ Perform the Kolmogorov-Smirnov test for goodness of fit and return the p-value. In: param: x1 -- An array with value's who's CDF is expected to be the same as the CDF of the proviced values. Must be atleast size 4. param: x2 -- A discretized pdf of the expected distribution under the null hypothesis. Out: return: The p-value obtained by performing the KS-test """ # Amount of values in the input distributions. x1_size = len(x1) x2_size = len(x2) # Sort both arrays. x1 = sorting.merge_sort(x1) x2 = sorting.merge_sort(x2) if type(x2_sorted) is not None else x2_sorted # The maximum distance max_dist = 0 # The iteration values used to determine # the emperical pdf's and the max distance. x1_i, x2_j = 0,0 # Find the maximum distance by updating the emperical CDFs. while x1_i < x1_size and x2_j < x2_size: # Update the indices used for the emperical CDF's. if x1[x1_i] < x2[x2_j]: x1_i += 1 else: x2_j += 1 # Find the max distance max_dist = max(abs(x1_i/x1_size-x2_j/x2_size), max_dist) sqrt_factor = np.sqrt((x1_size*x2_size)/(x1_size+x2_size)) cdf = _ks_statistic_cdf((sqrt_factor + 0.12+0.11/sqrt_factor)*max_dist) return 1 - cdf def kuiper_test(x, cdf): """ Perform the Kuiper test for goodness of fit and return the p-value. In: param: x -- An array with value's who's CDF is expected to be the same as the provided CDF. Must be atleast size 4 param: cdf -- A function that is the expected cdf under the null hypothesis. Out: return: The p-value obtained by performing the kuiper-test """ # Sort the data in ascending order, calculate the # cdf and the emperical cdf for the sorted values and # save the total amount of elements we have. x_sorted = sorting.merge_sort(x) x_sorted_cdf = cdf(x_sorted) x_elements = len(x) # Find the maximum distance above and below # the true cdf. max_dist_above = 0 max_dist_below = 0 # Value of the cdf at step i-1. x_cdf_emperical_previous = 0 for idx, x in enumerate(x_sorted): # Calculate the emperical cdf. x_cdf_emperical = (idx+1)/x_elements # Calculate the true cdf. x_cdf_true = x_sorted_cdf[idx] # Find the maximum distance above and below max_dist_above = max(x_cdf_emperical - x_cdf_true, max_dist_above) max_dist_below = max(x_cdf_true - x_cdf_emperical_previous, max_dist_below) # Update previous cdf x_cdf_emperical_previous = x_cdf_emperical sqrt_elem = np.sqrt(x_elements) v = max_dist_above + max_dist_below cdf = _kuiper_statistic_cdf((sqrt_elem + 0.155+0.24/sqrt_elem)*v) return 1 - cdf def _ks_statistic_cdf(z): """ An approximation for the cdf of the Kolmogorov-Smirnov (KS) test staistic. In: param: z -- The value to calculate the cdf at. Out: return: An approximation of the cdf for the given value. print(max_dist_above + max_dist_below) """ # Numerical approximation taken from: # Numerical methods - The art of scientific computation. # Third edition. if z < 1.18: exponent = np.exp(-np.pi**2/(8*z**2)) pre_factor = np.sqrt(2*np.pi)/z return pre_factor*exponent*(1+ exponent**8)*(1+exponent**16) else: exponent = np.exp(-2*z**2) return 1-2*exponent*(1-exponent**3)*(1-exponent**6) def _kuiper_statistic_cdf(z): """ An approximation for the cdf of the Kuiper test statistic In: param: z -- The value to calculate the cdf at. Out: return: An approximation of the cdf for the given value. """ # Value of z is to small, sum will be 1 up to 7 digits if z < 0.4: return 1 # Approximateed value of the sum by performing 100 iterations # The value to return ret = 0 # A term often needed in the sum. z_squared = z**2 # Evaluate the first 100 terms in the sum. for j in range(1, 100): power = j**2 * z_squared ret += (4 * power -1)*np.exp(-2*power) return 1- 2*ret def normal_cdf(x, mean = 0, sigma = 1): """ Evaluate the cummulative normal distribution for the given parameters In: param: x -- The point to evaluate the cdf at or an array of points to evaluate it for. param: mean -- The mean of the normal distribution. param: sigma -- The square root of the variance for the normal distribution. Out: return: The cummulative normal distribution evaluated at. """ # Calculate the CDF using the erf function (defined below). return 0.5 + 0.5*erf((x-mean)/(np.sqrt(2)*sigma)) def normal(x, mean = 0, sigma = 1): """ Evaluate the normal distrbution for the given parameters. In: param: x -- The point to evaulte the distribution at. param: mean -- The mean of the distribution. param: sigma -- The square root of the variance for the distribution. Out: return: The value of the parameterized distribution evaluated at the given point. """ return 1/((np.sqrt(2*np.pi)*sigma))*np.exp(-0.5*((x - mean)/sigma)**2) def erf(x): """ Evaluate the erf function for a value of x. In: param: x -- The value to evaluate the erf function for. Out: return: The erf function evaluated for the given value of x. """ # Numerical approximation taken from Abramowits and Stegun. # Constants for the numerical approximation p = 0.3275911 a1 = 0.254829592 a2 = -0.284496736 a3 = 1.421413741 a4 = -1.453152027 a5 = 1.061405429 # Array in which the result is stored ret = np.zeros(len(x)) # The approximation functions erf_func_t_val = lambda x: 1/(1+ p*x) erf_func_approx = lambda t, x : 1 - t*(a1 + t*(a2 + t*(a3 + t*(a4 + t*a5))))*np.exp(-x**2) # Evaluate for both positive and negative neg_mask = x < 0 neg_x = x[neg_mask] pos_mask = x >= 0 pos_x = x[pos_mask] ret[neg_mask] = -erf_func_approx(erf_func_t_val(-neg_x), -neg_x) ret[pos_mask] = erf_func_approx(erf_func_t_val(pos_x), pos_x) return ret
f40b6ed9480827f1b8b90a68b3f0e37f9925fd6d
anatcruz/FEUP-MNUM
/Exames/2010/P5.py
756
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 12 16:03:03 2020 @author: ANA """ def z(x,y): return 6*x**2 - x*y + 12*y + y**2 - 8*x def dzx(x,y): return 12*x - y - 8 def dzy(x,y): return -x + 12 + 2*y def gradient(x, y, h, numItr): xn = 0 yn = 0 print("x: ",x) print("y: ",y) print("z(x,y): ",z(x,y)) print("gradiente: ",dzx(x,y),";",dzy(x,y)) print("") for i in range(numItr): xn = x - h * dzx(x, y) yn = y - h * dzy(x, y) if z(xn, yn) < z(x, y): h *= 2 y = yn x = xn if z(xn, yn) > z(x, y): h /= 2 print("x: ",x) print("y: ",y) print("z(x,y): ",z(x,y)) print("") print(gradient(0,0,0.25,1))
ee0d952387016dc6cbd9bf848f2be041cc12acf8
mikio1998/LeetCode
/leetcode/twosum.py
3,517
3.875
4
""" TWO SUM return indexes of two digits in array that add up to target. ex. Inputs: [2, 7, 11, 15], 9 Output: [0, 1] """ def twoSum(array, target): sortedArray = sorted(array) sums = [] for i in sortedArray: if i > target: return sums else: if target - i in array: found = [] found.append(i) found.append(target-i) found = sorted(found) if not found in sums: sums.append(found) continue continue return sums a = [2,7,11,15,6,3] b = 9 #print(twoSum(a, b)) ''' If next is left 1x > 2x 1y = 2y if next is right 1x < 2x 1y = 2y if next is up 1x = 2x 1y < 2y if next is down 1x = 2x 1y > 2y ''' def minimumTime(points): def nextIsHigher(a, b): if a[0] > b[0]: return True return False def nextIsRight(a, b): if a[1] > b[1]: return True return False def verticallyEqual(a, b): if a == b: return True return False def horisontallyEqual(a, b): if a == b: return True return False x = points steps = 0 coordinate = x[0] print(coordinate) for i in x[1:]: print(x[1:]) while coordinate != i: print("ok") if nextIsRight(coordinate, i): #if the next is right print("ok") if nextIsHigher(coordinate, i): #if the next is higher & right coordinate[0] += 1 coordinate[1] += 1 #move coordinate NorthEast steps+=1 continue elif horisontallyEqual(coordinate[1],i[1]): # if next is Right and Vertically equal coordinate[0] += 1 coordinate[1] += 0 steps += 1 continue else: #if the next is lower & right coordinate[0] += 1 coordinate[1] -= 1 steps += 1 continue elif coordinate[0] == i[0]: # if vertically alligned if nextIsHigher(coordinate, i): #if next is higher coordinate[0] += 0 coordinate[1] += 1 steps += 1 continue else: coordinate[0] += 0 coordinate[1] -= 1 steps += 1 continue else: #if the next is left if nextIsHigher(coordinate, i): #if the next is higher and left coordinate[0] -= 1 coordinate[1] += 1 #move coordinate NorthWest steps += 1 continue elif horisontallyEqual(coordinate[1],i[1]): # if next is Right and Vertically equal coordinate[0] -= 1 coordinate[1] += 0 steps += 1 continue else: #if the next is lower and left coordinate[0] -= 1 coordinate[1] -= 1 steps += 1 continue return steps points = [[1,1],[3,4],[-1,0]] print(minimumTime(points)) # xi = [0, 0] # zi = [0, 3] # xi[0] += 1 # print(xi) # if xi != zi: # print("nah")
0459b5a50b24fd834c1a21ebc3f092811c62e5ab
AmitAps/learn-python
/oops_python/coordinate_ex.py
633
4.125
4
class Coordinate(object): def __init__(self, x, y): self.x = x self.y = y def distance(self, other): x_diff_sq = (self.x-other.x)**2 y_diff_sq = (self.y-other.y)**2 return(x_diff_sq + y_diff_sq) ** 0.5 def __str__(self): return "<" + str(self.x)+","+str(self.y)+">" #conventional way c = Coordinate(3,4) zero = Coordinate(0,0) print(c,zero) print(c.distance(zero)) print(type(c)) #use isinstance() to check if an object is a Coordinate print(isinstance(c, Coordinate)) #equivalent to # c = Coordinate(3,4) # zero = Coordinate(0,0) # print(Coordinate.distance(c,zero))
d15a83404db316ae47e7c61e7ffda77c5f0a2dc4
rgov/sqlite_protobuf
/example/create_database.py
1,323
3.546875
4
#!/usr/bin/env python import random import sqlite3 from AddressBook_pb2 import Person # Create the database db = sqlite3.connect('addressbook.db') db.execute('CREATE TABLE IF NOT EXISTS people (protobuf BLOB)') # Populate it with some random people names = ''' Kaila Dutton Collin Felps Lou Ohearn Hilde Charters Raymond Mangione Kasandra La Anette Poore Gilberte Strzelecki Lilli Glassman Lakiesha Peavy Billye Boelter Joan Claire Monika Seo Vicki Campoverde Destiny Eilers Alfonzo Hotz Daine Wyllie Yu Leer Shanel Yip Emiko Morvant Joe Esses Nathaniel Malcolm Cherry Robidoux Beulah Harshaw Alvina Granier Gerald Faries Lorri Elsass Janella Spray Shantelle Enger Chia Leite ''' for name in names.splitlines(): name = name.strip() if not name: continue # Generate a new person with a few phone numbers person = Person() person.name = name count = random.randint(1, len(Person.PhoneType.items())) for k, v in random.sample(Person.PhoneType.items(), count): area_code = random.randint(200, 999) exchange = random.randint(200, 999) line_number = random.randint(0, 9999) number = person.phones.add() number.type = v number.number = '({}) {}-{:04d}'.format(area_code, exchange, line_number) # Add them to the database data = person.SerializeToString() db.execute('INSERT INTO people VALUES (?)', (data,)) print('Inserted', name) db.commit() db.close()
1cf6d84616905cfbdb871a71617a81781d2f4732
hakubishin3/nlp_100_knocks_2020
/ch01/07.py
351
3.734375
4
""" 07. テンプレートによる文生成 引数x, y, zを受け取り「x時のyはz」という文字列を返す関数を実装せよ.さらに,x=12, y=”気温”, z=22.4として,実行結果を確認せよ. """ def temp(x, y, z): return f"{x}時の{y}は{z}" x = 12 y = "気温" z = 22.4 answer = temp(x, y, z) print(answer)
287ca8d5497e8817af93fdfaa5cc1e70a8833884
iayushguptaaa/Open-Algorithms
/Python/kosaraju_algorithm.py
2,696
3.78125
4
# Kosaraju's algorithm # ======================== # Given one direct graph, the algorithm finds his SCC( strongly connected components ) V = ['A','B','C','D','E','F','G','H','I'] T = { 'A':['B'], 'B':['C','D','F'], 'C':['A'], 'D':['E'], 'E':['F', 'G'], 'F':['D', 'H'], 'G':['F'], 'H':['I'], 'I':['H'], } ''' ================== KOSARAJU's ALGORYTHM ================== 1) Create an empty stack 'S', do DFS on a graph, on the road, insert the vertices on top of this stack. 2) Obtain the Transpose Graph, just reverse the graph 3) One by one pop each vertex from S while S is not empty. 4) Let popped vertex be 'v', so it will be the source, do DFS on it. The DFS starting from 'v' will denote the strongly connected components (SCC) of 'v', one by one popped from stack. ''' class Graph: def __init__(self, vertices = {}, graph= {}): self.vertices = vertices self.graph = graph self.S = [] self.SCC = [] visited = {} for v in vertices: visited[v] = False self.visited = visited def doDFS(self, graph = None): if not graph: graph = self.graph for u in self.vertices: if self.visited[u] == False: self.visited[u] = True # Mark u as visited for v in graph[u]: self.doDFS() self.S.insert(0, u) def getSCC(self, vertix, graph = {}): if self.visited[vertix] == True: self.visited[vertix] = False ve = [vertix] if graph[vertix] is not None: for v in graph[vertix]: a = self.getSCC(v, graph) if a is not None: ve += a return ve # Transpose the given Graph def reverseGraph(self, graph = {}): rGraph = {} for v in graph.keys(): for dest in graph[v]: rGraph[dest] = [v] if rGraph.get(dest) == None else rGraph[dest] + [v] return rGraph # Constructs new graph from SCC def newGraph(self): newGraph = {} for ind in range(len(self.SCC) - 1): newGraph[self.SCC[ind][0]] = [self.SCC[ind + 1][0]] newGraph[self.SCC[len(self.SCC) - 1][0]] = [] print(">> Simplified Graph by SCC: ", newGraph) # Returns the Strongly Connected Components from a Graph def doKosaraju(self): # 1) Inserting in S the components self.doDFS() # 2) Obtaining the reverse graph rGraph = self.reverseGraph(self.graph) # 3) Popping and searching for SCC print("-"*30, "STRONGLY CONNECTED COMPONENTS", "-"*30) while len(self.S) > 0: v = self.S.pop(0) scc = self.getSCC(v, rGraph) if scc is not None: self.SCC.append(scc) print(" > Component",scc[0], " >> ",scc) print("-"*91, "\n") newGraph = self.newGraph() return self.SCC if __name__ == '__main__': g = Graph(V,T) print('='*150) print(">> Directed graph:",g.graph, "\n") g.doKosaraju() print('='*150)
250ddb97f42ab196f193ef55478a09ecd921256c
green-fox-academy/ZaitzeV16
/python_solutions/week-01/day-4/mile_to_km_converter.py
202
4.3125
4
# Write a program that asks for a double that is a distance in miles, # then it converts that value to kilometers and prints it mile = float(input("mile: ")) print("in km: {}".format(mile * 1.609344))
ccfaa8fae09aea086ec858f197f4e222268be92f
AdamZhouSE/pythonHomework
/Code/CodeRecords/2902/60825/263366.py
326
3.78125
4
def printSandD(numS, numD): for i in range(numS/2): print('*', end='') for i in range(numD): print('D', end='') for i in range(numS/2): print('*', end='') print() N=int(input()) for i in range(1, N+1, 2): printSandD(N-i, i) for i in range(N-2, 0, -2): printSandD(N-i, i)
98f25a7d72f2c0d3b47ad75b27c4028a7232dd79
patnir/TronBotAI
/mySim/direction.py
928
3.890625
4
class direction: def __init__(self, x, y, width): self.x = x self.y = y self.width = width def moveRight(self, board): if self.x + 1 >= self.width or board[self.y][self.x + 1] != 0: print("cannot move right!") return False self.x += 1 return True def moveLeft(self, board): if self.x - 1 <= 0 or board[self.y][self.x - 1] != 0: print("cannot move right!") return False self.x -= 1 return True def moveDown(self, board): if self.y + 1 >= self.width or board[self.y + 1][self.x] != 0: print("cannot move down!") return False self.y += 1 return True def moveUp(self, board): if self.y - 1 <= 0 or board[self.y - 1][self.x] != 0: print("cannot move up!") return False self.y -= 1 return True
942c99431e31b9b24b777c6fa024928f4e1645ad
robert75RG/python_bootcamp
/zjazd1/podstawy_zad06.py
172
3.5
4
liczba = int(input('Podaj liczbę całkowitą: ')) print(f'Większa od 10 {liczba > 10}') print(f'Mniejsze od 15 {liczba <= 15}') print(f'Podzielne przez 2 {liczba%2==0}')
d471954e93951279159992754a3f2e54d29e4bc0
newcombh5629/CTI110
/P2HW2_MealTip_HoiNewcomb.py
610
4.3125
4
# Creat a program that calculates the amount of the tip percentages. # 2/12/2019 # CTI-110 P2HW2 - Meal Tip Calculator # Hoi Newcomb # Pseudocode # 1. Give the meal charge # 2. tip 15% = meal charge times 0.15 # 3. tip 18% = meal charge times 0.18 # 4. tip 20% = meal charge times 0.20 # 5. display the different tips amount meal_charge = float(input('Enter the total cost of meal $: ')) t15 = meal_charge * 0.15 t18 = meal_charge * 0.18 t20 = meal_charge * 0.20 print('Tip 15% is $: ', format(t15, '.2f')) print('Tip 18% is $: ', format(t18, '.2f')) print('Tip 20% is $: ', format(t20, '.2f'))
11f1aeab884210daf9ceb8d6f7cfa7107409ac56
NikilReddyM/python-codes
/itertools.combinations_with_replacement().py
249
3.5
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 17 13:58:39 2017 @author: HP """ from itertools import combinations_with_replacement a = input().split() for i in combinations_with_replacement(sorted(a[0]),int(a[1])): print(''.join(i))
22f00d095bd4cf8c6ccbf3c8b6eca2303ab5c862
yummy1221/data_science
/1_intro_to_ds_in_python/week2/assignment.py
2,709
3.59375
4
import pandas as pd df = pd.read_csv('olympics.csv', index_col=0, skiprows=1) for col in df.columns: if col[:2]=='01': df.rename(columns={col:'Gold'+col[4:]}, inplace=True) if col[:2]=='02': df.rename(columns={col:'Silver'+col[4:]}, inplace=True) if col[:2]=='03': df.rename(columns={col:'Bronze'+col[4:]}, inplace=True) if col[:1]=='№': df.rename(columns={col:'#'+col[1:]}, inplace=True) names_ids = df.index.str.split('\s\(') # split the index by '(' df.index = names_ids.str[0] # the [0] element is the country name (new index) df['ID'] = names_ids.str[1].str[:3] # the [1] element is the abbreviation or ID (take first 3 characters from that) df = df.drop('Totals') df.head() ###### Part One def answer_zero(): return df.iloc[0] answer_zero() def answer_one(): return df[df['Gold']==max(df['Gold'])].index[0] def answer_two(): diff = abs(df['Gold'] - df['Gold.1']) return diff.sort_values(ascending=False).index[0] def answer_three(): tmp = df[['Gold', 'Gold.1', 'Gold.2']].dropna() tmp = tmp[(tmp['Gold'] != 0) & (tmp['Gold.1'] != 0)] ratio = (tmp['Gold'] - tmp['Gold.1'])/tmp['Gold.2'] return ratio.sort_values(ascending=False).index[0] def answer_four(): points = df['Gold.2'] * 3 + df['Silver.2'] * 2 + df['Bronze.2'] return points ###### Part Two import pandas as pd census_df = pd.read_csv('census.csv') #census_df.head() def answer_five(): st_cty = census_df[['STNAME','CTYNAME']] st_cty = st_cty.groupby('STNAME').nunique() return st_cty.sort_values(ascending=False, by='CTYNAME').index[0] # very import: SUMLEV = 40, total of all 50, on state level, 40, on county level def answer_six(): pop = census_df[['STNAME','CENSUS2010POP']] pop = pop[census_df['SUMLEV']==50] pop = pop.set_index('STNAME') grouped = pop.groupby(pop.index) top3 = grouped.apply(lambda x: x.sort_values('CENSUS2010POP', ascending=False)[:3].sum()) return list(top3.sort_values('CENSUS2010POP', ascending=False)[:3].index) def answer_seven(): pop = census_df[['CTYNAME', 'POPESTIMATE2010', 'POPESTIMATE2011', 'POPESTIMATE2012', 'POPESTIMATE2013', 'POPESTIMATE2014', 'POPESTIMATE2015']] pop = pop[census_df['SUMLEV']==50] pop = pop.set_index('CTYNAME') pop['diff'] = pop.max(axis = 1) - pop.min(axis=1) pop.sort_values('diff', ascending=False, inplace=True) return pop.iloc[0].name def answer_eight(): rst = census_df[['STNAME', 'CTYNAME']] boolean_mask = (census_df['REGION'] == 1) | (census_df['REGION'] == 2) boolean_mask = boolean_mask & census_df['CTYNAME'].str.startswith('Washington') boolean_mask = boolean_mask & (census_df['POPESTIMATE2015'] > census_df['POPESTIMATE2014']) return rst[boolean_mask]
9aca5975f136ec7a9820b7a03e5d6dd5762e2739
greenfox-velox/oregzoltan
/week-05/day-3/project/todo.py
3,821
3.609375
4
import sys import csv def main(): todo = TodoApp() if len(sys.argv) > 1: todo.menu(sys.argv) else: print(todo.usage()) class TodoApp(): def __init__(self): self.name = 'todo.csv' def menu(self, arg): self.arg = arg if self.arg[1] == '-l': print(self.list_task()) elif self.arg[1] == '-a': self.add_new_task() else: self.argument_error_handling() def argument_error_handling(self): if self.arg[1] == '-r': if len(self.arg) == 2: print('Unable to remove: No index is provided') elif self.arg[2] == '0': print('Unable to remove: Index is out of bound') else: self.remove_task() elif self.arg[1] == '-c': if len(self.arg) == 2: print('Unable to check: No index is provided') elif self.arg[2] == '0': print('Unable to check: Index is out of bound') else: self.complete_task() else: print('Unsupported argument') print(self.usage()) def usage(self): text = 'Python Todo application\n=======================\n\nCommand line arguments:\n -l Lists all the tasks\n -a Adds a new task\n -r Removes an task\n -c Completes an task\n' return text def checked(self, x): if x == 'True': return '[x] ' else: return '[ ] ' def list_task(self): self.try_to_open_file() text = csv.reader(self.f, delimiter=';') line_number = 1 text_read = '' for i in text: text_read = text_read + str(line_number) + ' - ' + self.checked(i[0]) + i[1] + '\n' line_number += 1 if len(text_read) <= 0: return('No todos for today!') self.f.close() return(text_read) def add_new_task(self): if len(self.arg) == 2: print('Unable to add: No task is provided') else: try: f = open(self.name, 'a') except: self.create_file_if_missing() f = open(self.name) f.write('False;'+self.arg[2]+'\n') f.close() def remove_task(self): self.try_to_open_file() try: text = self.f.readlines() del text[int(self.arg[2])-1] self.f.close() self.f = open(self.name, 'w') for i in text: self.f.write(i) self.f.close() except IndexError: print('Unable to remove: Index is out of bound') except ValueError: print('Unable to check: Index is not a number') def create_file_if_missing(self): self.f = open(self.name, 'w') def try_to_open_file(self): try: self.f = open(self.name) except: self.create_file_if_missing() self.f = open(self.name) def complete_task(self): self.try_to_open_file() try: text = csv.reader(self.f, delimiter=';') text_to_write = [] for i in text: text_to_write.append(i) if text_to_write[int(self.arg[2])-1][0] == 'True': print('It is already checked') else: text_to_write[int(self.arg[2])-1][0] = 'True' self.f.close() self.f = open(self.name, 'w') for i in text_to_write: self.f.write(i[0] + ';' + i[1] + '\n') self.f.close() except IndexError: print('Unable to check: Index is out of bound') except ValueError: print('Unable to check: Index is not a number') main()
6618df064156113921057af50bcf99556a80d528
stgodussaillant/P0
/Entrega 4/Laplaciana.py
377
3.59375
4
# -*- coding: utf-8 -*- from numpy import zeros def laplaciana(N, dtype): #En clases se usa un archivo distinto, y se llama al archivo A = zeros((N,N), dtype=dtype) for i in range (N): A[i,i] = 2 for j in range (max(0,i-2),i): if abs(i-j)==1: A[i,j] = -1 A[j,i] = -1 return (A)
8d024274e7592e6ca0e02eeafac6fbe1ae1fb703
Deaseyy/algorithm
/数组系列/leetcode 75 颜色分类(排序).py
838
3.8125
4
# -*- coding: utf-8 -*- """ 1. 问题描述: 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 注意: 不能使用代码库中的排序函数来解决这道题。 示例1: 输入: [2,0,2,1,1,0] 输出: [0,0,1,1,2,2] [2,0,2,1,1,0] [0,2,2,1,1,0] """ def sortColors(nums: list) -> list: p = 1 while p < len(nums): i = p while i > 0: if nums[i] < nums[i-1]: nums[i], nums[i-1] = nums[i-1], nums[i] i -= 1 else: break p += 1 return nums if __name__ == '__main__': print(sortColors([2,0,2,1,1,0]))
f520c308b356ebb21d39694d40f86b8b94065471
Aasthaengg/IBMdataset
/Python_codes/p02717/s024835056.py
101
3.578125
4
x,y,z=map(int,input().split()) temp=x x=y y=temp temp=x x=z z=temp print("{0} {1} {2}".format(x,y,z))
77f56d6013eff7bd9e988e2ab47ec6e3fb1eaaf2
PrihanNimsara/python-variables
/Project/src/code/HelloPython.py
394
4.03125
4
variable1 = variable2 = variable3 = 100; print(variable1) print(variable2) print(variable3) variable1,variable2,variable3 = 10,20,30 print(variable1) print(variable2) print(variable3) tuple = (1,"prihan") print(tuple[0]) tuple2 = (2,"nimsara") print(tuple2[0]) print(tuple2) print(tuple + tuple2) dictionary = {1:'prihan','ab':'nimsara'} print(dictionary.keys()) print(dictionary.values())
c2c7836739ffe353861741376730b868a5a267ef
AyratTatlybaev/LearnPython_lesson1
/test.py
179
3.765625
4
def summ_str(x,y): return str(x) + str(y) first_var = input('Enter first variable: ') second_var = input('Enter second variable: ') print(summ_str(first_var,second_var).upper())
216169d01fd5b805bf8db41b167d8c1967a96ed7
thesharpshooter/codeforce
/day11/game.py
118
3.65625
4
temp = map(int,raw_input().split(" ")) n1 = temp[0] n2 = temp[1] if n2<n1: print "First" else: print "Second"
4e3efcdedf46fbea4f32071343c3faf8cb3f3820
zjohnson5455/fileFormatter
/addColumn.py
748
3.5625
4
import csv linkMap = { "1": "form1@cognito.com", "2": "form2@cognito.com", "3": "form3@cognito.com", "4": "form4@cognito.com" } def editFile(): with open("testData1.csv", mode= 'r') as file: csvFile = csv.reader(file) firstLine = True listOfLists = [] for line in csvFile: if (firstLine): line.append('Link') firstLine = False listOfLists.append(",".join(line)) else: link = linkMap[line[2]] line.append(link) listOfLists.append(",".join(line)) with open("testData1.csv", mode= 'w') as editedFile: new_file_contents = "\n".join(listOfLists) editedFile.write(new_file_contents) editFile()
fc0519c9b50de3639c8b93997d4af960cca70068
caoxiang104/-offer
/10.py
712
3.859375
4
# -*- coding:utf-8 -*- """ 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。 请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形, 总共有多少种方法 i*1 铺i*n f(n) = f(n-1) + f(n-i) """ class Solution: def __init__(self): self.times = [1, 2] def rectCover(self, number): # write code here if number == 0: return 0 elif number == 1: return 1 elif number == 2: return 2 else: for i in range(2, number + 1): self.times.append(self.times[i - 1] + self.times[i - 2]) return self.times[number - 1] s = Solution() print(s.rectCover(7))
1f1a074db424fff62638645e7968353e144db344
Wonderpol/Python-mini-projects
/expenses-tracker.py
2,370
4.375
4
expenses = [] months = { 1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December" } def show_menu(menu: dict): for key in menu.keys(): print(f"{key}. {menu[key]}") def show_expenses(month: int): for expense_amount, expense_type, expense_month in expenses: if expense_month == month: print(f"{months[month]}: {expense_amount} USD - {expense_type} ") def add_expense(month: int): expense_amount = int(input("Enter amount in [USD]: ")) expense_type = input("Enter type of the expense e.g food, house etc.: ") expense = (expense_amount, expense_type, month) expenses.append(expense) def show_stats(month: int): total_expenses_in_this_month = sum(expense_amount for expense_amount, _, expense_month in expenses if expense_month == month) number_of_expenses_this_month = sum(1 for _, _, expense_month in expenses if expense_month == month) total_expenses_all_months = sum(expense_amount for expense_amount, _, _ in expenses) average_expense_this_month = total_expenses_in_this_month / number_of_expenses_this_month average_expense_all = total_expenses_all_months / len(expenses) print("\n Statistics in this mount [USD]: \n") print(total_expenses_in_this_month) print("\n Average expense in this mount [USD]: \n") print(average_expense_this_month) print("\n Overall statistics [USD]: \n") print(total_expenses_all_months) print("\n Average expense in this year [USD]: \n") print(average_expense_all) if __name__ == "__main__": menu_options = { 0: "Change month", 1: "Show all expenses", 2: "Add expense", 3: "Statistics" } while True: month = int(input("Enter a month from 1-12: ")) if month == 0: break while True: show_menu(menu_options) choice = int(input("Enter a number from 1-3 to perform an action: ")) if choice == 0: break elif choice == 1: show_expenses(month) elif choice == 2: add_expense(month) elif choice == 3: show_stats(month) else: exit(-1)
9a38e546a6b1ce8ac37c2917d4657949434a250b
VictorStankov/Python_Crash_Course
/Try it Yourself/Chapter 8/Album.py
327
3.671875
4
def make_album(artist, title, n_tracks=""): output = {"artist name": artist, "album title": title} if n_tracks: output['tracks'] = n_tracks return output print(make_album('idk', 'any albums', str(3))) print(make_album('how tf', 'should I know')) print(make_album('the point is', "I'm doing it", str(50)))
20dda1f1e1870930c37424df70eb4a54bc17e937
kobohuong/data_wrangling_exercises-1
/chapter_5_examples/standalone_files/MTA_turnstiles_data_download.py
2,399
3.609375
4
# include the requests library in order to get data from the web import requests # the built-in `operating system` or `os` Python library will let us create # a new folder in which to store our downloaded data files import os # the built-in `time` Python library will let us `pause` our script for 2 # seconds between data requests, so that we don't overload the MTA server with # too many requests in too short a time period import time # open the file where we stored our list of links mta_data_links = open("MTA_data_index.csv","r") # create a folder name so that we can keep the data organized folder_name = "turnstile_data" # since we're *not* using an API, the website owner will have no way to identify # us unless we provide some additional information. headers = { 'User-Agent': 'Mozilla/5.0 (X11; CrOS x86_64 13597.66.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.109 Safari/537.36', 'From': 'YOUR NAME HERE - youremailaddress@emailprovider.som' } # the built-in `readlines()` function reads one line of data from our file # at a time, and makes them into a list mta_links_list = mta_data_links.readlines() # as we did when working with PDFs, we want to confirm that no folder with # our chosen name exists before creating it; otherwise we'll get an error if os.path.isdir(folder_name) == False: # create a new folder with that name target_folder = os.mkdir(folder_name) # we only need four files, so we should only download that many for i in range(0,4): # we use the built-in `strip()` recipe to remove the newline `\n` character # at the end of each row data_url = (mta_links_list[i]).strip() # we split the url on slashes, and take the item from the resulting list # which is the `.txt` filename. This is the filename we'll use to save # our local copy of the data data_filename = data_url.split("/")[-1] # make our request for the data turnstile_data_file = requests.get(data_url, headers=headers) # open a new, writable file inside our target folder, using the appropriate # filename local_data_file = open(os.path.join(folder_name,data_filename), "w") # save the contents of the downloaded file to that new file local_data_file.write(turnstile_data_file.text) # close the local file local_data_file.close() # "sleep" for two seconds before moving on to the next item in the loop time.sleep(2)
a8b20fc1fd2faf31cae75c4efaa115843f86c84a
yuyi-7/python
/base_code/条件.py
417
3.9375
4
# -*- coding: utf-8 -*- weight=float(input('请输入你的体重(/kg):')) high=float(input('请输入你的身高(/m):')) bmi=weight/(high**2) print('你的BMI指数是:%.1f'%bmi) if bmi<18.5: print('你的体重过轻') elif bmi<25: print('你的体重正常') elif bmi<28: print("你的体重过重") elif bmi<32: print('你属于肥胖') else: print('你属于严重肥胖')
6b9abd6d6e90d2925809fe38fb95cf571b12da00
yeqingyan/CCI_code
/Chapter2/q2_7.py
440
3.8125
4
""" Question 2.7 """ from LinkedList import * def intersection(a, b): """ Determine if two linked list intersect, return the intersecting node """ a_nodes = [] while a: a_nodes.append(a) a = a.next while b: if b in a_nodes: return b b = b.next return None a = LinkedList.list_to_link_list([1, 2, 3, 4, 5, 6, 7]) b = a.get_node(5) assert intersection(a.head, b) == b
83448b18b8b7fad07a799f99b937c79d74b0f8c9
BCookies222/Python-Codes
/Longevity.py
1,497
3.875
4
# Longevity : Secret to lIve a Long Life from Tkinter import * class Application(Frame): # Frame is Super Class of Application def __init__(self, master): # CONSTRUCTOR Frame.__init__(self, master) # master =root (Window) self.grid() self.ans="" self.create_widgets() def create_widgets(self): # Creating Labels for Heading and Password self.L=Label(self,text="Enter the password for the secret of Longevity") self.L.grid(row=0,column=0,columnspan=2,sticky=W) self.P=Label(self, text="Password") self.P.grid(row=1,column=0,sticky=W) # Create an Entry widget: User input , SINGLE LINE ENTRY self.E=Entry(self) self.E.grid(row=1,column=1, sticky=W) # Create a Button Widget" SUBMIT and attach it to the event handler self.B=Button(self,text="SUBMIT", command=self.reveal) self.B.grid(row=2,column=0,sticky=W) # Create a Text (space) widget to write multilines into self.T=Text(self,width=60, height=5,wrap=WORD) self.T.grid(row=3,column=0, columnspan=2,sticky=W) # Event Handler def reveal(self): ans=self.E.get() if ans=="secret" or ans=="Secret": message="Here's the secret to live long! Live to 99 then be very careful!" else: message="Incorrect Password" # Delete old text and insert new text self.T.delete(0.0,END) # Delete previously held text in T self.T.insert(0.20,message) # Insert New Text # main root=Tk() root.title("Longevity") root.geometry("500x300") app=Application(root) root.mainloop()
d2b299b44f8224042bb70a6401bffad120332f52
mikebpedersen/python_med_gerth
/uge_3/opgave3_1.py
1,379
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 1 15:20:46 2020 @author: JensTrolle """ from math import pi print("A string: '%s'" % "Hello World") # prints the string and inserts "Hello World" as a string inside ''. print("An integer: %s" % 27) # prints the string and inserts 27 as a string. print("A float: %s" % 27.0) # prints the string and inserts 27.0 as a string. print("A float: %s" % pi) # prints the string and inserts pi as a string. print("A float: %s " % pi*2) # prints the string twice and inserts pi as a string. print("A float: %s " % (pi*2)) # prints the string and inserts (2 times pi) as a string. print("A float: %.2f " % pi) # prints the string and inserts pi as a float with 2 decimals. print("A float: [%5.2f] " % pi) # prints the string, inserts pi to 2 decimal places # and reserves a length of 5 characters. print("A float: [%+6.2f] " % pi) # prints the string, inserts pi to 2 decimal places and adds a + sign, in front # of pi, and reserves the last space. print("A float: [%+.2f] " % pi) # prints the string, inserts pi to 2 decimal places and adds a + sign. print("A float: [%08.2f] " % pi) # prints the string, inserts pi to 2 decimal places and adds 0's where # there is space in the reserved 8 chars. print("An integer: [%08d] " % 42) # prints the string and inserts 0's until a length of 8 has been reached.
f13ed725396710fcda3a5b7197272520a0d69299
sana9056/HomeWork
/HomeWork1_2.py
1,607
3.5625
4
my_list = [] for i in range(1, 1000, 2): my_list.append(i ** 3) sum_counter = 0 sum_of_number = 0 print("Список, состоящий из кубов нечётных чисел от 0 до 1000:") print(my_list) #Выполнение условия А второй задачи for i in range(0, len(my_list), 1): count = my_list[i] while my_list[i] > 0: sum_of_number += my_list[i] % 10 my_list[i] = my_list[i] // 10 if sum_of_number % 7 == 0: sum_counter += count my_list[i] = count + 17 #Выполнение условия С второй задачи sum_of_number = 0 print("Число, которое получается в сумме чисел, сумма цифр которых делится нацело на 7 равна:") print(sum_counter) # my_list.clear() # for i in range(1, 1000, 2): # my_list.append((i ** 3) + 17) print("Если к первоначальному виду списка чисел прибавить 17, выйдет следующий список чисел:") print(my_list) #Выполнение условия B второй задачи for i in range(0, len(my_list), 1): count = my_list[i] while my_list[i] > 0: sum_of_number += my_list[i] % 10 my_list[i] = my_list[i] // 10 if sum_of_number % 7 == 0: sum_counter += count sum_of_number = 0 print("Число, которое получается в сумме чисел, сумма цифр которых делится нацело на 7 равна:") print(sum_counter)
8af2a3f7566b619a966a354aef468cf5f0328a90
TJ021/QueryLanguageEngine
/reading.py
1,490
3.8125
4
import glob from database import * def read_table(table_file): '''(str) -> Table Given a file name without the extension, the function will read the table and return it. REQ: table_file must have proper format. ''' if (".csv" not in table_file): table_file = table_file + ".csv" # Opens the file for reading. table_handle = open(table_file, 'r') # Ceates a table object. object_table = Table() # Calls a function withing database.py to create a table. object_table = object_table.get_read_table(table_handle) # Returns a table return object_table def read_database(): '''() -> Database The function returns a database with the keys being the file name and they're mapped to the table within them. ''' # Reads all the file names in the directory. database_headers = glob.glob('*.csv') # Creates a new dictionary. file_data = [] # Creates a list filled with tables from each file in the directory. for counter in range(len(database_headers)): file_data.append(read_table(database_headers[counter])) # Creates a new database object. object_database = Database() # Calls a function within database.py to create a database. object_database = object_database.get_read_database(database_headers, file_data) # Returns a database. return object_database
c215e8238f21a9acedfc13e0e7bb15aa0854c263
alisonjo315/pythonclass-playtime
/lesson2/lesson02_states_alison.py
2,601
4.59375
5
# Difficulty Level: Intermediate # Goal: Create a program that prints out an HTML drop down menu for all 50 states # Step 1: Define your list of states # These should all be strings, since they're names of places # Instead of having to type them all out, I really like liststates.com -- you can even customize the format it gives you the states in to make it super easy to copy/paste into your code here # Step 2: Create your loop # Essentially, you're telling Python: for each state in my list: print this HTML code # A good place to start is by printing the name of the state in the loop; after that you can add the HTML around it # Step 3: Add the HTML # A drop-down menu in HTML looks like this: # <select> # <option value="state_abbreviation">Full state name</option> # </select> # At line 14, we create the drop-down menu # At line 15, we create one drop-down item. Each additional <option> that we add will add another item to our drop-down menu # At line 16, we tell HTML that we're done with the drop-down menu # Step 4: Test it! # Have Python print out the HTML code. Copy / paste it into a file, save that file as "states.html" and open that file in a web browser. # Later, when we learn file handling, we can skip the copy/paste step. # File handling can also let us create a file with the state names and abbreviations in it so we don't have to add it to our code. # Your finished project should look something like: https://github.com/codelikeagirlcny/python-lessons-cny/blob/master/code-exercises-etc/section_05_(loops)/states.html ##################################### state_names = """Alabama,Alaska,Arizona,Arkansas,California,Colorado,Connecticut,Delaware,District Of Columbia,Florida,Georgia,Hawaii,Idaho,Illinois,Indiana,Iowa,Kansas,Kentucky,Louisiana,Maine,Maryland,Massachusetts,Michigan,Minnesota,Mississippi,Missouri,Montana,Nebraska,Nevada,New Hampshire,New Jersey,New Mexico,New York,North Carolina,North Dakota,Ohio,Oklahoma,Oregon,Pennsylvania,Rhode Island,South Carolina,South Dakota,Tennessee,Texas,Utah,Vermont,Virginia,Washington,West Virginia,Wisconsin,Wyoming""" state_abbrs = """AL,AK,AZ,AR,CA,CO,CT,DE,DC,FL,GA,HI,ID,IL,IN,IA,KS,KY,LA,ME,MD,MA,MI,MN,MS,MO,MT,NE,NV,NH,NJ,NM,NY,NC,ND,OH,OK,OR,PA,RI,SC,SD,TN,TX,UT,VT,VA,WA,WV,WI,WY""" state_abbrs_list = state_abbrs.split(',') #print state_abbrs_list state_names_list = state_names.split(',') output = """<select>""" for abbr,name in zip(state_abbrs_list, state_names_list): output += """ <option value="{0}">{1}</option>""".format(abbr, name) output += """ </select>""" print output