blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
b37520ed33b2fef924c8ea17c96d34799b78cc37
TimKillingsworth/Codio-Assignments
/src/dictionaries/person_with_school.py
306
4.34375
4
#Create dictionary with person information. Assign the dictionary to the variable person person={'name':'Lisa', 'age':29} #Print out the contents of person print(person) #Add the school which Lisa attends person['school'] = 'SNHU' #Print out the contents of person after adding the school print(person)
true
47f7f996f21d85e5b7613aa14c1a6d2752faaa82
zaidjubapu/pythonjourney
/h5fileio.py
1,969
4.15625
4
# file io basic '''f = open("zaid.txt","rt") content=f.read(10) # it will read only first 10 character of file print(content) content=f.read(10) # it will read next 10 character of the file print(content f.close() # must close the file in every program''' '''f = open("zaid.txt","rt") content=f.read() # it will read all the files print(1,content) # print content with one content=f.read() print(2,content) # it will print only 2 because content are printed allready f.close()''' '''if we want to read the file in a loop with f = open("zaid.txt","rt") for line in f: print(line,end="")''' # if want to read character in line by line '''f = open("zaid.txt","rt") content=f.read() for c in content: print(c)''' #read line function '''f = open("zaid.txt","rt") print(f.readline()) # it wiil read a first line of the file print(f.readline()) # it will read next line of the file it will give a space because the new line wil already exist in that f.close()''' # readlines functon wil use to create a list of a file with 1 line as 1 index '''f = open("zaid.txt","rt") print(f.readlines())''' # writ functions '''f=open("zaid.txt","w") f.write("hello how are you") # replce the content with what we have written f.close()''' '''f=open("zaid1.txt","w") # the new file wil come with name zaid1 f.write("hello how are you") # the new file will created and the content will what we have written f.close()''' # append mode in write '''f=open("zaid2.txt","a") # the new file wil come with name zaid1 and will append the character at the end how much we run the program a=f.write("hello how are you\n") # the new file will created and the content will what we have written print(a) # it will display the no of character in the file f.close()''' #if want to use read and write function simultaneously f=open("zaid.txt","r+") #r+ is used for read and write print(f.read()) f.write("thankyou") f.write("zaid") f.close()
true
014987c11429d51e6d1462e3a6d0b7fb97b11822
zaidjubapu/pythonjourney
/enumeratefunction.py
592
4.59375
5
'''enumerate functions: use for to easy the method of for loop the with enumerate method we can find out index of the list ex: list=["a","b","c"] for index,i in enumerate(list): print(index,i) ''' ''' if ___name function : print("and the name is ",__name__)# it will give main if it is written before if __name__ == '__main__': # it is used for if we want to use function in other file print("hello my name is zaid")''' ''' join function: used to concatenat list in to string list=["a","b","c","d"] z=" and ".join(list) #used to concatenate the items of the sting print(z)'''
true
50e523c196fc0df4be3ce6acab607f623119f4e1
zaidjubapu/pythonjourney
/h23abstractbaseclassmethod.py
634
4.21875
4
# from abc import ABCMeta,abstractmethod # class shape(metaclass=ABCMeta): # or from abc import ABC,abstractmethod class shape(ABC): @abstractmethod def printarea(self): return 0 class Rectangle(shape): type= "Rectangle" sides=4 def __init__(self): self.length=6 self.b=7 # def printarea(self): # return self.length+self.b harry=Rectangle() # if we use abstract method before any function. then if we inherit the class then it gives an errr # untill that method is not created inside that class # now it wil give error # we cant create an object of abstract base class method
true
22773f2a2796ae9a493020885a6e3a987047e7f8
Pegasus-01/hackerrank-python-works
/02-division in python.py
454
4.125
4
##Task ##The provided code stub reads two integers, a and b, from STDIN. ##Add logic to print two lines. The first line should contain the result of integer division, a// b. ##The second line should contain the result of float division, a/ b. ##No rounding or formatting is necessary. if __name__ == '__main__': a = int(input()) b = int(input()) intdiv = a//b floatdiv = a/b print(intdiv) print(floatdiv)
true
5a4c0c930ea92260b88f0282297db9c9e5bffe3f
BarunBlog/Python-Files
/Learn Python3 the Hard Way by Zed Shaw/13_Function&Files_ex20.py
1,236
4.21875
4
from sys import argv script, input_file = argv def print_all(f): print(f.read()) def rewind(f): f.seek(0) ''' fp.seek(offset, from_what) where fp is the file pointer you're working with; offset means how many positions you will move; from_what defines your point of reference: 0: means your reference point is the beginning of the file 1: means your reference point is the current file position 2: means your reference point is the end of the file if omitted, from_what defaults to 0. ''' def print_a_line(line_count, f): print(line_count, f.readline()) ''' readline() reads one entire line from the file. fileObject.readline( size ); size − This is the number of bytes to be read from the file. The fle f is responsible for maintaining the current position in the fle after each readline() call ''' current_file = open(input_file) print("First let's print the whole file:\n") print_all(current_file) print("Now let's rewind, kind of like a tape.") rewind(current_file) print("Let's print three lines:") current_line = 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file)
true
b6fefcbd7ae15032f11a372c583c5b9d7b3199d9
BarunBlog/Python-Files
/02 String operation.py
993
4.21875
4
str1 = "Barun " str2 = "Hello "+"World" print(str1+" "+str2) ''' To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert. ''' str3 = 'I don\'t think so' print(str3) print('Source:D \Barun\Python files\first project.py') # raw string changed heres print(r'Source:D \Barun\Python files\first project.py') # r means rush string.. #raw string stays the way you wrote it str4 = str1+str2 print(str4) print(str1 * 5) x = ' ' print(str2.find('World'),x,str2.find('Word')) print(len(str2)) print(str2.replace('Hello','hello')) # replace returns string but don't replace parmanently print(str2,"\n") new_str2 = str2.replace('H','h') print(new_str2) print(str2) str5 = "Hello World!" print(str5) del str5 #print(str5) # it will give an error st1 = "Barun Bhattacharjee" st2 = "Hello World!" li = st2.split(" ") print(li) st3 = li[0] +' '+ st1 print(st3) st4 = st2.replace("World!", st1) print(st4)
true
6c727ec6706b42ea057f264ff97d6f39b7481338
AnkitAvi11/100-Days-of-Code
/Day 11 to 20/MoveAllnegative.py
798
4.59375
5
""" python program to move all the negative elements to one side of the array ------------------------------------------------------------------------- In this, the sequence of the array does not matter. Time complexity : O(n) space complexity : O(1) """ # function to move negatives to the right of the array def move_negative(arr : list) -> None : left = 0;right = len(arr) - 1 while left < right : if arr[left] < 0 : while arr[right] < 0 : right-=1 # swap the two ends of the array arr[left], arr[right] = arr[right], arr[left] left += 1 right -= 1 else : left += 1 # driver code if __name__ == "__main__": arr = [1,2,-1,3,5,-2,7,8] move_negative(arr) print(arr)
true
9f076e1b7465ff2d509b27296a2b963dd392a7f9
kishoreramesh84/python-75-hackathon
/filepy2.py
523
4.28125
4
print("Reading operation from a file") f2=open("newfile2.txt","w") f2.write(" Hi! there\n") f2.write("My python demo file\n") f2.write("Thank u") f2.close() f3=open("newfile2.txt","r+") print("Method 1:") for l in f3: #Method 1 reading file using loops print(l,end=" ") f3.seek(0) #seek is used to place a pointer to a specific location print("\nMethod 2:") print(f3.read(10))#Method 2 it reads 10 character from file f3.seek(0) print("Method 3:") print(f3.readlines())#Method 3 it prints the text in a list f3.close()
true
5bbce3aaa6c5a5d38b2a2848ce856322107a8c91
mirsadm82/pyneng-examples-exercises-en
/exercises/06_control_structures/answer_task_6_2a.py
1,788
4.34375
4
# -*- coding: utf-8 -*- """ Task 6.2a Make a copy of the code from the task 6.2. Add verification of the entered IP address. An IP address is considered correct if it: - consists of 4 numbers (not letters or other symbols) - numbers are separated by a dot - every number in the range from 0 to 255 If the IP address is incorrect, print the message: 'Invalid IP address' The message "Invalid IP address" should be printed only once, even if several points above are not met. Restriction: All tasks must be done using the topics covered in this and previous chapters. """ ip_address = input("Enter ip address: ") octets = ip_address.split(".") correct_ip = True if len(octets) != 4: correct_ip = False else: for octet in octets: if not (octet.isdigit() and int(octet) in range(256)): correct_ip = False break if not correct_ip: print("Invalid IP address") else: octets_num = [int(i) for i in octets] if octets_num[0] in range(1, 224): print("unicast") elif octets_num[0] in range(224, 240): print("multicast") elif ip_address == "255.255.255.255": print("local broadcast") elif ip_address == "0.0.0.0": print("unassigned") else: print("unused") # second version ip = input("Enter IP address") octets = ip.split(".") valid_ip = len(octets) == 4 for i in octets: valid_ip = i.isdigit() and 0 <= int(i) <= 255 and valid_ip if valid_ip: if 1 <= int(octets[0]) <= 223: print("unicast") elif 224 <= int(octets[0]) <= 239: print("multicast") elif ip == "255.255.255.255": print("local broadcast") elif ip == "0.0.0.0": print("unassigned") else: print("unused") else: print("Invalid IP address")
true
86fc4bc0e652ee494db883f657e918b2b056cf3e
mirsadm82/pyneng-examples-exercises-en
/exercises/04_data_structures/task_4_8.py
1,107
4.125
4
# -*- coding: utf-8 -*- """ Task 4.8 Convert the IP address in the ip variable to binary and print output in columns to stdout: - the first line must be decimal values - the second line is binary values The output should be ordered in the same way as in the example output below: - in columns - column width 10 characters (in binary you need to add two spaces between columns to separate octets among themselves) Example output for address 10.1.1.1: 10 1 1 1 00001010 00000001 00000001 00000001 Restriction: All tasks must be done using the topics covered in this and previous chapters. Warning: in section 4, the tests can be easily "tricked" into making the correct output without getting results from initial data using Python. This does not mean that the task was done correctly, it is just that at this stage it is difficult otherwise test the result. """ ip = "192.168.3.1" octets = ip.split(".") output = """ {0:<10}{1:<10}{2:<10}{3:<10} {0:08b} {1:08b} {2:08b} {3:08b}""" print(output.format(int(octets[0]), int(octets[1]), int(octets[2]), int(octets[3])))
true
b3cfe1ba6b28715f0f2bccff2599412d406fd342
n001ce/python-control-flow-lab
/exercise-5.py
670
4.40625
4
# exercise-05 Fibonacci sequence for first 50 terms # Write the code that: # 1. Calculates and prints the first 50 terms of the fibonacci sequence. # 2. Print each term and number as follows: # term: 0 / number: 0 # term: 1 / number: 1 # term: 2 / number: 1 # term: 3 / number: 2 # term: 4 / number: 3 # term: 5 / number: 5 # etc. # Hint: The next number is found by adding the two numbers before it # Program to display the Fibonacci sequence up to n-th term n1, n2 = 0, 1 count = 0 print("Fibonacci sequence:") while count < 50: print(f"term: {count} / number: {n1}") nth = n1 + n2 n1 = n2 n2 = nth count += 1
true
8d980ed029b0dc74e4dc6aa0e7785d6af0f95fa7
NiharikaSinghRazdan/PracticeGit_Python
/Code_Practice/list_exercise.py
512
4.21875
4
# Convert string into list mystring="This is the new change" mylist = [] for letter in mystring: mylist.append(letter) print(mylist) # Change string into list with different convert format and in one line mystring1="Hi There" mylist1 =[letter for letter in mystring1] print(mylist1) # Check other usage of this new one liner format to convert string into list #Check the odd no in list mylist2=[num for num in range(0,11) if num%2==0] print(mylist2) mylist2=[num**2 for num in range(0, 11)] print(mylist2)
true
bc76d2ae44f894254a3e24c0b53c61db5039f4ff
NiharikaSinghRazdan/PracticeGit_Python
/Code_Practice/arbitary_list.py
1,556
4.1875
4
#retrun the list where the passed arguments are even def myfunc(*args): mylist=[] for item in args: if item%2==0: mylist.append(item) else: continue print(mylist) print(myfunc(-2,4,3,5,7,8,10)) # return a string where every even letter is in uppercase and every odd letter is in lowercase def myfunct(*args): mylist1=[] for item in args: # find the index of the items index=args.index(item) if (item==item.upper() and index%2==0) or (item==item.lower() and index%2!=0): mylist1.append(item) print(mylist1) print(myfunct('A','B','C','D','e',"f")) # check the index of the list and verify that even is in uppercase and odd index is in lower case def myfunc1(*args): mystring=' ' mystring_t=args[0] print(len(mystring_t)) for item in range(len(mystring_t)): if (item%2==0): mystring=mystring+mystring_t[item].upper() else: mystring=mystring+mystring_t[item].lower() print(mystring) print(myfunc1("supercalifragilisticexpialidocious")) # print the argument in upper and lowercase alternate def myfunc2(*args): mystring_total=args[0] c_string=' ' for item in mystring_total: index1=mystring_total.index(item) if (index1%2==0): item=item.upper() c_string=c_string+item else: item=item.lower() c_string=c_string+item print(mystring_total) print(c_string) print(myfunc2("AbcdEFGHijKL"))
true
37b1dce3bcbe2da05065e677491797983588c285
dankolbman/NumericalAnalysis
/Homeworks/HW1/Problem1.py
520
4.21875
4
import math a = 25.0 print("Squaring a square-root:") while ( math.sqrt(a)**2 == a ): print('sqrt(a)^2 = ' + str(a) + ' = ' + str(math.sqrt(a)**2)) a *= 10 # There was a rounding error print('sqrt(a)^2 = ' + str(a) + ' != ' + str(math.sqrt(a)**2)) # Determine the exponent of the float expo = math.floor(math.log10(a))-1.0 # Reduce to only significant digits b = a/(10**expo) print("Ajusting decimal placement before taking the square-root:") print('sqrt(a)^2 = ' + str(a) + ' = ' + str((math.sqrt(b)**2)*10**expo))
true
bfc1710b45ac38465e6f545968f2e00cd535d2dc
Tarun-Rao00/Python-CodeWithHarry
/Chapter 4/03_list_methods.py
522
4.21875
4
l1 = [1, 8, 7, 2, 21, 15] print(l1) l1.sort() # sorts the list print("Sorted: ", l1) l1.reverse() #reverses the list print("Reversed: ",l1) l1.reverse() print("Reversed 2: ",l1) l1.append(45) # adds to the end of the list print ("Append", l1) l2 = [1,5, 4, 10] l1.append(l2) # l2 (list) will be added print("Append 2", l1) l1.insert(0, 100) # Inserts 100 at 0-(position) print("Inserted", l1) l1.pop(2) # removes item from position 2 print("Popped", l1) l1.remove(7) # removes 7 from the list print("Removed", l1)
true
0ab24f03f7919f96e74301d06dd9af5a377ff987
Tarun-Rao00/Python-CodeWithHarry
/Chapter 2/02_operators.py
548
4.125
4
a = 34 b = 4 # Arithimatic Operator print("the value of 3+4 is ", 3+4) print("the value of 3-4 is ", 3-4) print("the value of 3*4 is ", 3*4) print("the value of 3/4 is ", 3/4) # Assignment Operators a = 34 a += 2 print(a) # Comparision Operators b = (7>14) c = (7<14) d = (7==14) e = (7>=14) print(b) print(c) print(d) print(e) # Logical Operators boo1 = True bool2 = False print("The value of bool1 and bool2 is", (boo1 and bool2)) print("The value of bool1 and bool2 is", (boo1 or bool2)) print("The value of bool1 and bool2 is", (not bool2))
true
d31f727127690b2a4584755c941cd19c7452d9e4
Tarun-Rao00/Python-CodeWithHarry
/Chapter 6/11_pr_06.py
221
4.15625
4
text = input("Enter your text: ") text1 = text.capitalize() num1 = text1.find("Harry") num2 = text1.find("harry") if (num1==-1 and num2==-1): print("Not talking about Harry") else: print("Talking about Harry")
true
406ad197c1a6b2ee7529aaa7c6ea5a86e10114de
carrenolg/python-code
/Chapter12/optimize/main.py
896
4.25
4
from time import time, sleep from timeit import timeit, repeat # main def main(): """ # measure timing # example 1 t1 = time() num = 5 num *= 2 print(time() - t1) # example 2 t1 = time() sleep(1.0) print(time() - t1) # using timeit print(timeit('num = 5; num *= 2', number=1)) print(repeat('num = 5; num *= 2', number=1, repeat=3)) """ # Algorithms and Data Structures # build a list in different ways def make_list_1(): result = [] for value in range(1000): result.append(value) return result def make_list_2(): result = [value for value in range(1000)] return result print('make_list_1 takes', timeit(make_list_1, number=1000), 'seconds') print('make_list_2 takes', timeit(make_list_2, number=1000), 'seconds') if __name__ == '__main__': main()
true
c5333727d54b5cb7edff94608ffb009a29e6b5f4
nikita5119/python-experiments
/cw1/robot.py
1,125
4.625
5
# A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following: # UP 5 # DOWN 3 # LEFT 3 # RIGHT 2 # The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer. # Example: # If the following tuples are given as input to the program: # UP 5 # DOWN 3 # LEFT 3 # RIGHT 2 # Then, the output of the program should be: # 2 position=[0,0] while True: a= input("enter the direction and steps :") if not a: break direction, steps= a.split(' ') steps=int(steps) if (direction== "up"): position[0]= position[0]+steps elif (direction=="down"): position[0]=position[0]-steps if (direction=="right"): position[1]=position[1]+steps elif (direction=="left"): position[1]=position[1]-steps print(position) distance=(position[0]**2+position[1]**2)**(1/2) print(distance)
true
6e468bf7c8d0d37233ee7577645e1d8712b83474
TameImp/compound_interest_app
/test_calc.py
929
4.125
4
''' this programme test the compound interest calculator ''' from calc import monthly_compounding def test_tautology(): assert 3 == 3 #test that investing no money generates no returns def test_zeros(): #initialise some user inputs initial = 0 monthly = 0 years = 0 annual_rate = 0 #calculate a final sum final_sum = monthly_compounding(initial, monthly, years, annual_rate) #test out assert final_sum == 0 def test_cash(): initial = 1000 monthly = 100 years = 10 annual_rate = 0 #calculate a final sum final_sum = monthly_compounding(initial, monthly, years, annual_rate) #test out assert final_sum == 13000 def test_rate(): initial = 1000 monthly = 100 years = 2/12 annual_rate = 12 # calculate a final sum final_sum = monthly_compounding(initial, monthly, years, annual_rate) #test out assert final_sum == 1221.1
true
e0ee6d13b199a167c7cf72672876ff5d4b6e1b99
LuisPereda/Learning_Python
/Chapter03/excercise1.py
420
4.1875
4
# This program parses a url url = "http://www.flyingbear.co/our-story.html#:~:text=Flying%20Bear%20is%20a%20NYC,best%20rate%20in%20the%20city." url_list = url.split("/") # Parsing begins at character (/) domain_name = url_list[2] # Dictates at which character number parsing begins print (domain_name.replace("www.","")) # Deletes a specific character or string of characters and replaces them with desired input
true
9a915e306d84c786fd2290dc3180535c5773cafb
schase15/cs-module-project-iterative-sorting
/src/searching/searching.py
1,967
4.375
4
# Linear and Binary Search assignment def linear_search(arr, target): # Go through each value starting at the front # Check to see if it is equal to the target # Return index value if it is # Return -1 if not found in the array` for i in range(len(arr)): if arr[i] == target: return i return -1 # not found # Write an iterative implementation of Binary Search # If the target is in the array, return the index value # If the target is not in the array, return -1 def binary_search(arr, target): # Set first and last index values first = 0 last = len(arr) -1 # What is our looping criteria? What tells us to stop looping # If we see that the index position has gone past the end of the list we stop # If the value from the array is equal to the target, we stop while first <= last: # Compare the target element to the midpoint of the array # Calculate the index of the midpoint mid = (first + last) //2 # The double slash rounds down # If the midpoint element matches our target, return the midpoint index if target == arr[mid]: return mid # If the midpoint value is not equal to the target, decide to go higher or lower if target < arr[mid]: # If target is less than the midpoint, toss all values greater than the midpoint # Do this by moving the search boundary high point down to one below the midpoint last = mid -1 if target > arr[mid]: # If target is greater than the midpoint, toss all values less than the midpoint # Move the search boundary low point up to one above the midpoint first = mid + 1 # Repeat this loop unitl the end of the array has been reached # When the mid index has surpassed the length of the list # If target is not found in the list, return -1 return -1
true
996da01a75f050ffcdb755c5c5f2b16fb1ec8f1c
Shmuco/PY4E
/PY4E/ex_05_02/ex_05_02.py
839
4.15625
4
##### 5.2 Write a program that repeatedly prompts a user for integer numbers until #the user enters 'done'. Once 'done' is entered, print out the largest and #smallest of the numbers. If the user enters anything other than a valid number #catch it with a try/except and put out an appropriate message and ignore the #number. Enter 7, 2, bob, 10, and 4 and match the output below. largest = None smallest = None while True: num = input("Enter a number: ") if num == "done" : break try: fnum =float(num) except: print ("Invalid input") continue if largest is None: largest = fnum elif fnum > largest: largest = fnum if smallest is None: smallest = fnum elif smallest > fnum: smallest = fnum print("Maximum", largest, "Minumum", smallest)
true
48f85e68fcdd06ca468437c536ac7e27fd20ef77
endreujhelyi/zerda-exam-python
/first.py
431
4.28125
4
# Create a function that takes a list as a parameter, # and returns a new list with every second element from the original list. # It should raise an error if the parameter is not a list. # Example: with the input [1, 2, 3, 4, 5] it should return [2, 4]. def even_elements(input_list): if type(input_list) == list: return [input_list[i] for i in range(len(input_list)) if i % 2 == 1] else: raise TypeError
true
40eb347ec2a99811529a9af3aa536a16618d0ad3
DoranLyong/CSE-python-tutorial
/Coding-Test/CodeUp/Python/036_number.py
345
4.375
4
""" [ref] https://codeup.kr/problem.php?id=1036 Question: 1. take one English letter 2. print it out as the decimal value of the ASCII code table. """ letter = input() print(ord(letter)) """ Program to find the ASCII value of a character: https://beginnersbook.com/2019/03/python-program-to-find-ascii-value-of-a-character/ """
true
58dce475f4c94e14c6d58a4ee3c1836e34c82f21
DoranLyong/CSE-python-tutorial
/Coding-Test/CodeUp/Python/037_number.py
319
4.125
4
""" [ref] https://codeup.kr/problem.php?id=1037 Question: 1. take one decimal ineger 2. print it out in ASCII characters """ num = int(input()) print(chr(num)) """ Program to find the ASCII value of a character: https://beginnersbook.com/2019/03/python-program-to-find-ascii-value-of-a-character/ """
true
3442780fcf656417aa119190f13137e61db8d005
jamessandy/Pycon-Ng-Refactoring-
/refcator.py
527
4.21875
4
#Example 1 num1 = 4 num2 = 4 result = num1 + num2 print(result) #Example 2 num1 = int(input('enter the firExamst number:')) num2 = int(input('enter the second number:')) result = num1 + num2 print('your answer is:', result) #Example 3 num1 = int(input('Enter number 1:')) num2 = int(input('Enter number 2:')) result = num1 + num2 print(result) #Example 4 def add (x, y): return x + y num1 = int(input('Enter number 1:')) num2 = int(input('Enter number 2:')) result = add(num1, num2) print('your answer is:', result)
true
e130159211e4dc6092a9943fa6a1c9422d058f68
mclark116/techdegree-project
/guessing_game2.py
2,321
4.125
4
import random history = [] def welcome(): print( """ ____________________________________ Welcome to the Number Guessing Game! ____________________________________ """) def start_game(): another = "y" solution = random.randint(1,10) value = "Oh no! That's not a valid value. Please chose a number between 1 and 10." attempt = 0 while another == "y": try: prompt = int(input("Pick a number between 1 and 10: ")) except ValueError: print(value) else: if prompt > solution: if prompt > 10: print(value) else: print("It's lower!") attempt +=1 elif prompt < solution: if prompt < 1: print(value) else: print("It's higher!") attempt +=1 elif prompt == solution: attempt +=1 if attempt == 1: print("\nGot it! It took you {} try!".format(attempt)) else: print("\nGot it! It took you {} tries!".format(attempt)) print("Game Over!") history.append(attempt) solution = random.randint(1,10) attempt = 0 another = input("Would you like to play again? y/n ") if another.lower()=="y": print("\nHigh Score: {}".format(min(history))) elif another.lower()!="y": if another.lower()=="n": print("\nGame Over! Thanks for playing.") break else: while another.lower !="y" or "n": print("Please choose y or n") another = input("Would you like to play again? y/n ") if another.lower()=="y": print("\nHigh Score: {}".format(min(history))) break elif another.lower()!="y": if another.lower()=="n": break welcome() start_game()
true
cf7554340e039e9c317243a1aae5e5f9e52810f9
IraPara08/raspberrypi
/meghapalindrom.py
412
4.3125
4
#Ask user for word wordinput = input("Please Type In A Word: ") #Define reverse palindrome reverseword = '' #For loop for x in range(len(wordinput)-1, -1, -1): reverseword = reverseword + wordinput[x] #Print reverse word print(reverseword) #Compare if wordinput == reverseword: print("This is a palindrome!") else: print("This is not a palindrome:(") #TA-DA print("Ta-Da!")
true
fed78ccbb8a565e936cacbac817485c26ab84383
domlockett/pythoncourse2018
/day03/exercise03_dl.py
458
4.28125
4
## Write a function that counts how many vowels are in a word ## Raise a TypeError with an informative message if 'word' is passed as an integer ## When done, run the test file in the terminal and see your results. def count_vowels(word): vowels=('a','e','i','o','u') count= 0 for i in word: if type(word)!=str: raise TypeError, "Make sure your input is a string." if i in vowels: count+=1 return count
true
2074006981e41d2e7f0db760986ea31f6173d181
ladas74/pyneng-ver2
/exercises/06_control_structures/task_6_2a.py
1,282
4.40625
4
# -*- coding: utf-8 -*- """ Task 6.2a Make a copy of the code from the task 6.2. Add verification of the entered IP address. An IP address is considered correct if it: - consists of 4 numbers (not letters or other symbols) - numbers are separated by a dot - every number in the range from 0 to 255 If the IP address is incorrect, print the message: 'Invalid IP address' The message "Invalid IP address" should be printed only once, even if several points above are not met. Restriction: All tasks must be done using the topics covered in this and previous chapters. """ ip = input('Введите IP адрес: ') #ip = '10.1.16.50' ip_list = ip.split('.') correct_ip = False if len(ip_list) == 4: for oct in ip_list: if oct.isdigit() and 0 <= int(oct) <= 255: #in range(256) вместо 0 <= int(oct) <= 255 correct_ip = True else: correct_ip = False break if correct_ip: oct1 = ip_list[0] if 1 <= int(oct1) <= 223: print("unicast") elif 224 <= int(oct1) <= 239: print("multicast") elif ip == '255.255.255.255': print("local broadcast") elif ip == '0.0.0.0': print("unassigned") else: print("unused") else: print('Invalid IP address')
true
27cc3bbaffff82dfb22f83be1bcbd163ff4c77f1
ladas74/pyneng-ver2
/exercises/05_basic_scripts/task_5_1.py
1,340
4.3125
4
# -*- coding: utf-8 -*- """ Task 5.1 The task contains a dictionary with information about different devices. In the task you need: ask the user to enter the device name (r1, r2 or sw1). Print information about the corresponding device to standard output (information will be in the form of a dictionary). An example of script execution: $ python task_5_1.py Enter device name: r1 {'location': '21 New Globe Walk', 'vendor': 'Cisco', 'model': '4451', 'ios': '15.4', 'ip': '10.255.0.1'} Restriction: You cannot modify the london_co dictionary. All tasks must be completed using only the topics covered. That is, this task can be solved without using the if condition. """ name_switch = input('Введите имя устройства: ') london_co = { "r1": { "location": "21 New Globe Walk", "vendor": "Cisco", "model": "4451", "ios": "15.4", "ip": "10.255.0.1", }, "r2": { "location": "21 New Globe Walk", "vendor": "Cisco", "model": "4451", "ios": "15.4", "ip": "10.255.0.2", }, "sw1": { "location": "21 New Globe Walk", "vendor": "Cisco", "model": "3850", "ios": "3.6.XE", "ip": "10.255.0.101", "vlans": "10,20,30", "routing": True, }, } print(london_co[name_switch])
true
70e15b366634efea90e939c6c169181510818fdb
Sushantghorpade72/100-days-of-coding-with-python
/Day-03/Day3.4_PizzaOrderCalculator.py
881
4.15625
4
''' Project Name: Pizza Order Author: Sushant Tasks: 1. Ask customer for size of pizza 2. Do they want to add pepperoni? 3. Do they want extra cheese? Given data: Small piza: $15 Medium pizza: $20 Large pizza: $ 25 Pepperoni for Small Pizza: +$2 Pepperoni for medium & large pizza: +$3 Extra cheese for any size pizza: +$1 ''' print("Welcome to python pizza deliveries!!!") size = input("What size pizza do you want? S,M or L? ") add_pep = input("Do you want pepperoni? Y or N: ") extra_cheese = input("Do you want extra cheese? Y or N: ") #Price size wise: bill = 0 if size == "S": bill += 15 elif size == "M": bill += 20 else: bill += 25 if add_pep == "Y": if size == "S": bill += 2 else: bill += 3 if extra_cheese == "Y": bill += 1 print(f"Your final bill is ${bill}")
true
9b4a03cec322c2c28438a0c1df52d36f1dfce769
Long0Amateur/Self-learnPython
/Chapter 5 Miscellaneous/swapping.py
297
4.21875
4
# A program swaps the values of 3 variables # x gets value of y, y gets value of z, and z gets value of x x = 1 y = 2 z = 3 hold = x x = y y = hold hold = y y = z z = hold hold = z z = x z = hold print('Value of x =',x) print('Value of y =',y) print('Value of z =',z)
true
edfd81e4cbd96b77f1666534f7532b0886f8ec4e
himashugit/python_dsa
/func_with_Arg_returnvalues.py
617
4.15625
4
''' def addition(a,b): result = a+b return result # this value we're sending back to main func to print def main(): a = eval(input("Enter your number: ")) b = eval(input("Enter your 2ndnumber: ")) result = addition(a,b) # calling addition func & argument value and storing in result print(f' "the addition of {a} and {b} is {result}"') main() # calling main func ''' def multiply_num_10(value): #result = value*10 #return result return value*10 def main(): num=eval(input("Enter a number:")) result=multiply_num_10(num) print("The value is: ", result) main()
true
c9361ac9212e8bd0441b05a26940729dd6915861
itsMagondu/python-snippets
/fib.py
921
4.21875
4
#This checks if a certain number num is a number in the fibbonacci sequence. #It loops till the number is the sequence is either greater or equal to the number in the sequence. #Thus we validate if the number is in the fibonacci sequence. import sys tot = sys.stdin.readline().strip() try: tot = int(tot) except ValueError: pass def fibTest(f0,f1,f,num): f0 = f1 f1 = f f = f0+f1 if int(f) < int(num): f0,f1,f,num = fibTest(f0,f1,f,num) else: if f == int(num): print "IsFibo" else: print "IsNotFibo" return f0,f1,f,num def getFibnumber(f0,f1): return f0+f1 while tot: num = sys.stdin.readline().strip() f0 = 0 f1 = 1 f = getFibnumber(f0,f1) try: num = int(num) if num != 0 or num != 1: fibTest(f0,f1,f,num) tot -= 1 except ValueError: pass
true
5ebb8cf419dd497c64b1d7ac3b22980f0c33b790
sberk97/PythonCourse
/Week 2 - Mini Project Guess number game.py
2,289
4.21875
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import random import simplegui # helper function to start and restart the game def new_game(): # initialize global variables used in your code here global secret_number global times times = 7 print "You have 7 guesses" secret_number=random.randrange(0,99) # define event handlers for control panel def range100(): # button that changes the range to [0,100) and starts a new game global secret_number global times times = 7 print "You have 7 guesses" secret_number=random.randrange(0,99) print "Restarting the game, range now is[0,100)" def range1000(): # button that changes the range to [0,1000) and starts a new game global secret_number global times times = 10 print "You have 10 guesses" secret_number=random.randrange(0,999) print "Restarting the game, range now is[0,1000)" def input_guess(guess): # main game logic goes here guess=int(guess) print "Guess was %s" % (guess) if guess==secret_number: print "Correct" new_game() elif guess > secret_number: print "Lower" global times if times > 0: times -= 1 print "You have %s guesses left" % (times) else: print "You are out of guesses, the secret number was %s, new game begins" % (secret_number) new_game() elif guess < secret_number: print "Higher" if times > 0: times -= 1 print "You have %s guesses left" % (times) else: print "You are out of guesses, the secret number was %s, new game begins" % (secret_number) new_game() else: print "Error" # create frame frame=simplegui.create_frame("Guess game", 300, 300) input=frame.add_input("Input", input_guess, 50) # register event handlers for control elements and start frame button1=frame.add_button("Range is [0,100)", range100, 100) button2=frame.add_button("Range is [0,1000)", range1000, 100) frame.start() # call new_game new_game() # always remember to check your completed program against the grading rubric
true
5c4362ae8eea49bd105ae1f0ffced5d62aba12ed
ArnoldKevinDesouza/258327_Daily_Commits
/Dict_Unsolved02.py
209
4.5
4
# Write a Python program to convert a list into a nested dictionary of keys list = [1, 2, 3, 4] dictionary = current = {} for name in list: current[name] = {} current = current[name] print(dictionary)
true
3963dccc95056b06715cf81c7a8eab7091c682a5
ArnoldKevinDesouza/258327_Daily_Commits
/If_Else_Unsolved04.py
314
4.15625
4
# Write a program to get next day of a given date from datetime import date, timedelta import calendar year=int(input("Year:")) month=int(input("\nMonth:")) day=int(input("\nDay:")) try: date = date(year, month, day) except: print("\nPlease Enter a Valid Date\n") date += timedelta(days=1) print(date)
true
dd652b879fd1162d85c7e3454f8b724e577f5e7e
Einsamax/Dice-Roller-V2
/main.py
2,447
4.375
4
from time import sleep import random #Introduce user to the program if __name__ == "__main__": #This does a good thing print ("*" * 32) print("Welcome to the Dice Roller!".center(32)) print ("*" * 32) print() sleep(1) def roll_dice(diceamnt, diceint): #Defines function roll_dice dicetotal = 0 #Reset dicetotal for i in range(diceamnt): #Repeat for desired amount of dice rolled diceroll = random.randint(1, diceint) #Roll based on type of dice selected print(diceroll) #Print each roll as they are rolled sleep(1) dicetotal = dicetotal + diceroll #Add each dice roll to the total return dicetotal rolling=True while rolling: #Repeats the loop upon each roll unless exited by user choosing = True while choosing: #Prompt user to chose their dice type print("*" * 32) print("Which type of dice would you like to roll?") sleep(1) print("You may select from D2, D3, D4, D6, D8, D10, D12, D20, and D100!") sleep(1) print("You may also type 'exit' to leave the program.") dicetype = str(input()) # User enters the type of dice they wish to roll if dicetype == "exit": #User wishes to exit the program sleep(1) print("Thank you for rolling your luck!") sleep(2) rolling = False # exits the while loop elif dicetype == "D2" or dicetype == "D3" or dicetype == "D4" or dicetype == "D6" or dicetype == "D8" or dicetype == "D10" or dicetype == "D12" or dicetype == "D20" or dicetype == "D100": diceint = int(dicetype[1:]) #Extracts the dicetype as an integer choosing = False else: print("Uh oh! It looks like you entered an invalid dice type!") sleep(1) #exit() #Exits the program because exiting the loop wasn't working lmao sleep(1) print("How many", dicetype, "would you like to roll?") diceamnt = int(input()) # User enters number of dice to roll sleep(1) dicetotal = roll_dice(diceamnt, diceint) #Set the returned value to dicetotal print("You rolled a total of", dicetotal, "!") #Print the total in a clear statement sleep(2)
true
c6aadc50833356e4ce23f7f2a898634ff3efd4a7
dsimonjones/MIT6.00.1x---Introduction-to-Computer-Science-and-Programming-using-Python
/Week2- Simple Programs/Lecture4- Functions/Function isIn (Chap 4.1.1).py
611
4.1875
4
# -*- coding: utf-8 -*- """ @author: ali_shehzad """ """ Finger exercise 11: Write a function isIn that accepts two strings as arguments and returns True if either string occurs anywhere in the other, and False otherwise. Hint: you might want to use the built-in str operation in. """ def isIn(str1, str2): if len(str1) > len(str2): #We're comparing which string is longer and then checking to see if str2 in str1: #if the shorter string is present in the longer string return True else: if str1 in str2: return True return False
true
3bc103df43f3b4e607efa104b1e3a5a62caa1469
LaurenShepheard/VsCode
/Learningpython.py
1,227
4.375
4
for i in range(2): print("hello world") # I just learnt how to comment by putting the hash key at the start of a line. Also if I put a backslash after a command you can put the command on the next line. print\ ("""This is a long code, it spreads over multiple lines, because of the triple quotaions and brackets""") # A string is a sequence of one or more characters surrounded by quotes ' "", like above. It's data type is str. print('This is a String but if you are using numbers the data type is int and called integer') b = 100 print(b) print(2+2) # Numbers with a decimal are called a float and act like ints. True and false are bool data type called booleans. print(2/2) print("The number above is a constant as its value does not change whereas the b is a variable as I assigned it a value using the assignment operator =, doing this you can do math") a = 50 y = a + b print(y) a = a + 1 # The above is an example of incrementing a variable, you can decrement it by using - as well. You can also skip putting the a like below. a += 1 y = a + b print(y) print("Now the number changes because I incremented the variable.") Nick = "A really cool guy who is probably a jedi but who really knows" print(Nick)
true
20b609e21199215965d79601920124905c16ef2d
katesem/data-structures
/hash_table.py
884
4.25
4
''' In Python, the Dictionary data types represent the implementation of hash tables. The Keys in the dictionary satisfy the following requirements. The keys of the dictionary are hashable i.e. the are generated by hashing function which generates unique result for each unique value supplied to the hash function. The order of data elements in a dictionary is not fixed. So we see the implementation of hash table by using the dictionary data types ''' # accessing data with keys in hash table : hash_table = {1 :'one', 2 : 'two', 3 : 'three', 4 : 'four'} hash_table[1] # -> one hash_table[4] # -> four #adding items: hash_table[5] = 'five' # updating dictionary: hash_table[4] = 'FOUR' print(hash_table) #deleting items: del hash_table[1] # remove entry with key 'Name' hash_table.clear(); # remove all entries in dict del hash_table ; # delete entire dictionary
true
02aa151e60891f3c43b27a1091a35e4d75fe5f7d
mshalvagal/cmc_epfl2018
/Lab0/Python/1_Import.py
1,610
4.375
4
"""This script introduces you to the useage of Imports in Python. One of the most powerful tool of any programming langauge is to be able to resuse code. Python allows this by setting up modules. One can import existing libraries using the import function.""" ### IMPORTS ### from __future__ import print_function # Only necessary in Python 2 import biolog biolog.info(3*'\t' + 20*'#' + 'IMPORTS' + 20*'#' + 3*'\n') # A generic import of a default module named math import math # Now you have access to all the functionality availble # in the math module to be used in this function print('Square root of 25 computed from math module : {}'.format(math.sqrt(25))) # To import a specific function from a module from math import sqrt # Now you can avoid referencing that the sqrt function is from # math module and directly use it. print('Square root of 25 computed from math module by importing only sqrt function: ', sqrt(25)) # Import a user defined module # Here we import biolog : Module developed to display log messages for the exercise biolog.info('Module developed to display log messages for the exercies') biolog.warning("When you explicitly import functions from modules, it can lead to naming errors!!!""") # Importing multiple functions from the same module from math import sqrt, cos # Defining an alias : # Often having to reuse the actual name of module can be a pain. # We can assign aliases to module names to avoid this problem import datetime as dt biolog.info("Here we import the module datetime as dt.") # Getting to know the methods availble in a module biolog.info(dir(math))
true
42f37b58b8e3b4583208ea054d30bef34040a6ed
inshaal/cbse_cs-ch2
/lastquest_funcoverload_Q18_ncert.py
1,152
4.1875
4
"""FUNCTION OVERLOADING IS NOT POSSIBLE IN PYTHON""" """However, if it was possible, the following code would work.""" def volume(a): #For volume of cube vol=a**3 print vol, "is volume of cube" def volume(a,b,c): #volume of cuboid |b-height vol=a*b*c print vol, "is volume of cuboid" def volume(a,b): #volume of cylinder |a-radius|b-height from math import pi vol= pi*(a**2)*b print vol, "is volume of cylinder" a=raw_input("Enter dimension1: ") b=raw_input("Enter dimension2: ") c=raw_input("Enter dimension3: ") volume(a,b,c) ''' Notice Python takes the latest definition of that function. So if all three values are provided for a,b & c Python will give an error stating it takes only 2 arguments but 3 given. ''' ''' EXTRA PART FOR - (Not Required) ta=bool(a) tb=bool(b) tc=bool(c) if ta: a=float(a) if not (tb and tc): volume(a) elif tb and (not tc): b=float(b) volume(a,b) elif (tb and tc): b=float(b) c=float(c) volume(a,b,c) ''' """It's possible using module/s: https://pypi.python.org/pypi/overload"""
true
579a2fbc1f237e1207be37752963d17f2011b629
edenizk/python_ex
/ifstatement.py
866
4.15625
4
def main(): phone_balance = 10 bank_balance = 50 if phone_balance < 10: phone_balance += 10 bank_balance -= 10 print(phone_balance) print(bank_balance) number = 145 if number % 2 == 0: print("Number " + str(number) + " is even.") else: print("Number " + str(number) + " is odd.") age = 35 free_up_to_age = 4 child_up_to_age = 18 senior_from_age = 65 concession_ticket = 1.25 adult_ticket = 2.50 if age <= free_up_to_age: ticket_price = 0 elif age <= child_up_to_age: ticket_price = concession_ticket elif age >= senior_from_age: ticket_price = concession_ticket else: ticket_price = adult_ticket message = "Somebody who is {} years old will pay ${} to ride the bus.".format(age, ticket_price) print(message)
true
1fb7b06f3ed69f53268c4b1f6fc0a39702f8274c
mishra-atul5001/Python-Exercises
/Search.py
574
4.15625
4
Stringy = ''' Suyash: Why are you wearing your pajamas? Atul: [chuckles] These aren't pajamas! It's a warm-up suit. Suyash: What are you warming up for Bro..!!? Atul: Stuff. Suyash: What sort of stuff? Atul: Super-cool stuff you wouldn't understand. Suyash: Like sleeping? Atul: THEY ARE NOT PAJAMAS! ''' print(Stringy) def countWord(word,st): st = st.lower() count = st.count(word) return print(word + ' repeats ' + str(count) + ' times') print('What word do you want to search for?') userWord = input() countWord(userWord,Stringy) #Atul Mishra #SRM Univ.
true
cc8e5d5db27730063c43f01ef610dcea40ec77df
lacra-oloeriu/learn-python
/ex15.py
552
4.125
4
from sys import argv# That is a pakege from argv script, filename = argv#This is define the pakege txt= open(filename)#that line told at computer ...open the file print(f"Here's your file {filename}:")#print the text...and in {the name of file to open in extension txt} print ( txt.read()) print("Type the filename again:")#print the text.."Type the fil....again" file_again = input ( " > ")# the name of file txt_again = open ( file_again)#open file again print (txt_again.read())#printeaza continutul fisierului ...prin the cont of file again
true
af1191998cf3f8d5916e22b8b55da7766bead003
huynhirene/ICTPRG-Python
/q1.py
241
4.28125
4
# Write a program that counts from 0 to 25, outputting each number on a new line. num = 0 while num <= 26: print(num) num = num + 1 if num == 26: break # OR for numbers in range(0,26): print(numbers)
true
113cddca4472e40432caf9672fdc4ce22f25fb86
fjctp/find_prime_numbers
/python/libs/mylib.py
542
4.15625
4
def is_prime(value, know_primes=[]): ''' Given a list of prime numbers, check if a number is a prime number ''' if (max(know_primes)**2) > value: for prime in know_primes: if (value % prime) == 0: return False return True else: raise ValueError('List of known primes is too short for the given value') def find_all_primes(ceil): ''' find all prime numbers in a range, from 2 to "ceil" ''' known_primes = [2, ] for i in range(3, ceil+1): if is_prime(i, known_primes): known_primes.append(i) return known_primes
true
44cc5b20276024979f97fb31cd221b90ba78e351
Mahdee14/Python
/2.Kaggle-Functions and Help.py
2,989
4.40625
4
def maximum_difference(a, b, c) : #def stands for define """Returns the value with the maximum difference among diff1, diff2 and diff3""" diff1 = abs(a - b) diff2 = abs(b - c) diff3 = abs(a - c) return min(diff1, diff2, diff3) #If we don't include the 'return' keyword in a function that requires 'return', then we're going to get a special value #called 'Null' def least_dif(a ,b, c): """Docstring - Finds the minimum value with the least difference between numbers""" diff1 = a - b diff2 = b - c diff3 = a - c return min(diff1, diff2, diff3) print( least_dif(1, 10, 100), least_dif(1, 2, 3), least_dif(10, 20, 30) ) #help(least_dif) print(1, 2, 3, sep=" < ") #Seperate values in between printed arguments #By default sep is a single space ' ' #help(maximum_difference)^^^ #Adding optional arguments with default values to custom made functions >>>>>> def greet(who="Mahdee"): print("Hello ", who) print(who) greet() greet(who="Mahdee") greet("world") #Functions applied on functions def mult_by_five(x, y): return 5 * x + y def call(fn, *arg): """Call fn on arg""" return fn(*arg) print(call(mult_by_five, 1, 1) , "\n\n") example = call(mult_by_five, 1, 3) print(example) def squared_call(fn, a, b, ans): """Call fn on the result of calling fn on arg""" return fn(fn(a, b), ans) print( call(mult_by_five, 3, 6), squared_call(mult_by_five, 1, 1, 1), sep='\n', # '\n' is the newline character - it starts a new line ) def mod_5(x): """Return the remainder of x after dividing by 5""" return x % 5 print( 'Which number is biggest?', max(100, 51, 14), 'Which number is the biggest modulo 5?', max(100, 51, 14, key=mod_5), sep='\n', ) def my_function(): print("Hello From My Function!") my_function() def function_with_args(name, greeting): print("Hello, %s, this is an example for function with args, %s" % (name, greeting)) function_with_args("Mahdee", "Good Morning") def additioner(x, y): return x + y print(additioner(1, 3)) def list_benefits(): return "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to connect and share code together" def build_sentence(info): return "%s , is a benefit of functions" % info def name_the_benefits_of_functions(): list_of_benefits = list_benefits() for benefit in list_of_benefits: print(build_sentence(benefit)) name_the_benefits_of_functions() #Exercise def to_smash(total_candies, n_friends=3): """Return the number of leftover candies that must be smashed after distributing the given number of candies evenly between 3 friends. >>> to_smash(91) 1 """ return total_candies % n_friends print(to_smash(91)) x = -10 y = 5 # # Which of the two variables above has the smallest absolute value? smallest_abs = min(abs(x), abs(y)) def f(x): y = abs(x) return y print(f(0.00234))
true
d990ed78e1ecc5dd47c002e438d23400c72badba
mochadwi/mit-600sc
/unit_1/lec_4/ps1c.py
1,368
4.1875
4
# receive Input initialBalance = float(raw_input("Enter your balance: ")) interestRate = float(raw_input("Enter your annual interest: ")) balance = initialBalance monthlyInterestRate = interestRate / 12 lowerBoundPay = balance / 12 upperBoundPay = (balance * (1 + monthlyInterestRate) ** 12) / 12 while True: balance = initialBalance monthlyPayment = (lowerBoundPay + upperBoundPay) / 2 # bisection search for month in range(1,13): interest = round(balance * monthlyInterestRate, 2) balance += interest - monthlyPayment if balance <= 0: break if (upperBoundPay - lowerBoundPay < 0.005): # TOL (tolerance) # Print result print "RESULT" monthlyPayment = round(monthlyPayment + 0.004999, 2) print "Monthly Payment to pay (1 Year): $", round(monthlyPayment, 2) # recalculate balance = initialBalance for month in range(1,13): interest = round(balance * monthlyInterestRate, 2) balance += interest - monthlyPayment if balance <= 0: break print "Months needed: ", month print "Your balance: $", round(balance, 2) break elif balance < 0: # Paying too much upperBoundPay = monthlyPayment else: # Paying too little lowerBoundPay = monthlyPayment
true
fbaf789fbe6bfaede28d2b2d3a6a1673e229f57b
bledidalipaj/codefights
/challenges/python/holidaybreak.py
2,240
4.375
4
""" My kids very fond of winter breaks, and are curious about the length of their holidays including all the weekends. Each year the last day of study is usually December 22nd, and the first school day is January 2nd (which means that the break lasts from December 23rd to January 1st). With additional weekends at the beginning or at the end of the break (Saturdays and Sundays), this holiday can become quite long. The government issued two rules regarding the holidays: The kids' school week can't have less than 3 studying days. The holidays should thus be prolonged if the number of days the kids have to study before or after the break is too little. If January 1st turns out to fall on Sunday, the following day (January 2nd) should also be a holiday. Given the year, determine the number of days the kids will be on holidays taking into account all the rules and weekends. Example For year = 2016, the output should be holidayBreak(year) = 11. First day of the break: Friday December 23rd. Last day of the break: Monday January 2nd. Break length: 11 days. For year = 2019, the output should be holidayBreak(year) = 16. First day of the break: Saturday December 21st. Last day of the break: Sunday January 5th. Break length: 16 days. *** Due to complaints, I've added a hidden Test outside of the range. The Year now goes to 2199 *** [time limit] 4000ms (py) [input] integer year The year the break begins. Constraints: 2016 ≤ year ≤ 2199. [output] integer The number of days in the break. # Challenge's link: https://codefights.com/challenge/yBwcdkwQm5tAG2MJo # """ import calendar def holidayBreak(year): first_day = 23 last_day = 31 + 1 # first day of the break weekday = calendar.weekday(year, 12, 23) if weekday == 0: first_day -= 2 elif weekday == 1: first_day -= 3 elif weekday == 2: first_day -= 4 elif weekday == 6: first_day -= 1 # last day of the break weekday = calendar.weekday(year + 1, 1, 1) if weekday == 6 or weekday == 5: last_day += 1 elif weekday == 4: last_day += 2 elif weekday == 3: last_day += 3 elif weekday == 2: last_day += 4 return last_day - first_day + 1
true
0bad5a8a7ee86e45043ef0ddf38406a9ee4d1032
pmayd/python-complete
/code/exercises/solutions/words_solution.py
1,411
4.34375
4
"""Documentation strings, or docstrings, are standard ways of documenting modules, functions, methods, and classes""" from collections import Counter def words_occur(): """words_occur() - count the occurrences of words in a file.""" # Prompt user for the name of the file to use. file_name = input("Enter the name of the file: ") # Open the file, read it and store its words in a list. # read() returns a string containing all the characters in a file # and split() returns a list of the words of a string “split out” based on whitespace with open(file_name, 'r') as f: word_list = f.read().split() # Count the number of occurrences of each word in the file. word_counter = Counter(word_list) # Print out the results. print( f'File {file_name} has {len(word_list)} words ({len(word_counter)} are unique).\n' # f-strings dont need a \ character for multiline usage f'The 10 most common words are: {", ".join([w for w, _ in word_counter.most_common(10)])}.' ) return word_counter # this is a very important part of a module that will only be executed # if this file is calles via command line or the python interpreter. # This if statement allows the program to be run as a script by typing python words.py at a command line if __name__ == '__main__': words_occur()
true
95b308d6bdb204928c6b014c8339c2cc8693b7d7
pmayd/python-complete
/code/exercises/most_repeating_word.py
870
4.3125
4
import doctest def most_repeating_word(words: list) -> str: """ Write a function, most_repeating_word, that takes a sequence of strings as input. The function should return the string that contains the greatest number of repeated letters. In other words: for each word, find the letter that appears the most times find the word whose most-repeated letter appears more than any other Bonus: - make function robust (empty list, etc) - add parameter to count all leters, only vowels or only consonants Examples: >>> most_repeating_word(['aaa', 'abb', 'abc']) 'aaa' >>> most_repeating_word(['hello', 'wonderful', 'world']) 'hello' >>> words = ['this', 'is', 'an', 'elementary', 'test', 'example'] >>> most_repeating_word(words) 'elementary' """ pass if __name__ == "__main__": doctest.testmod()
true
111c536fba28296ec4f2a93ab466360e57d839d6
paul0920/leetcode
/question_leetcode/215_5.py
1,471
4.25
4
# Bucket sort algorithm # Average time complexity: O(n) # Best case: O(n) # Worst case: O(n^2) # Space complexity: O(nk), k: bucket count # Bucket sort is mainly useful when input is uniformly distributed over a range # Choose the bucket size & count, and put items in the corresponding bucket nums = [3, 2, 1, 5, 6, 4] # k = 2 # nums = [3, 2, 3, 1, 2, 4, 5, 5, 6] # k = 4 # nums = [2, 200, 6, 9, 10, 32, 32, 100, 101, 123] def bucket_sort(alist, bk_size): largest = max(alist) length = len(alist) size = bk_size # size = largest / length # if size < 1: # size = 1 print "bucket size:", size buckets = [[] for _ in range(length)] for i in range(length): j = int(alist[i] / size) print "i:", i, "j:", j, "length:", length if j < length: buckets[j].append(alist[i]) elif j >= length: buckets[length - 1].append(alist[i]) print buckets print "" # Use insertion sort to sort each bucket for i in range(length): insertion_sort(buckets[i]) result = [] for i in range(length): result += buckets[i] return result def insertion_sort(alist): for i in range(1, len(alist)): key = alist[i] j = i - 1 while j >= 0 and key < alist[j]: alist[j + 1] = alist[j] j = j - 1 alist[j + 1] = key arr = bucket_sort(nums, 3) print "" print "the sorted array:", arr
true
d94c3e993bd855c950dfe809dba92957b40c4a20
JimiofEden/PyMeth
/Week 1/TEST_roots_FalsePosition.py
470
4.25
4
import roots_FalsePosition import numpy ''' Adam Hollock 2/8/2013 This will calculate the roots of a given function in between two given points via the False Position method. ''' def f(x): return x**3+2*x**2-5*x-6 results = roots_FalsePosition.falsePosition(f,-3.8,-2.8,0.05) print results results = roots_FalsePosition.falsePosition(f,-1.3,-0.9,0.05) print results results = roots_FalsePosition.falsePosition(f,1.8,2.3,0.05) print results print numpy.roots([1, 2, -5, -6])
true
e579fadc31160475af8f2a8d42a20844575c95fa
mitalshivam1789/python
/oopfile4.py
940
4.21875
4
class A: classvar1= "I am a class variable in class A." def __init__(self): self.var1 = "I am in class A's constructor." self.classvar1 = "Instance variable of class A" self.special = "Special" class B(A): classvar1="I am in class B" classvar2 = "I am variable of class B" def __init__(self): #super().__init__()# as we call this then the values of var1 and classvar1 will change as per class A instance self.var1 = "I am in class B's constructor." self.classvar1 = "Instance variable of class B" # values of var1 and classvar1 will change again super().__init__() #as we call this then the values of var1 and classvar1 will change as per class A instance # if we comment 1st one then from here the values of var1 and classvar1 will not change a = A() b= B() print(b.classvar1) print(b.classvar2) print(b.special,b.var1)
true
4ecd4d3a20e875b9c0b5019531e8858f4722b632
victorbianchi/Toolbox-WordFrequency
/frequency.py
1,789
4.5
4
""" Analyzes the word frequencies in a book downloaded from Project Gutenberg """ import string def get_word_list(file_name): """ Reads the specified project Gutenberg book. Header comments, punctuation, and whitespace are stripped away. The function returns a list of the words used in the book as a list. All words are converted to lower case. """ #loading file and stripping away header comment f = open(file_name,'r') lines = f.readlines() curr_line = 0 while lines[curr_line].find('START OF THIS PROJECT GUTENBERG EBOOK') == -1: curr_line += 1 lines = lines[curr_line+1:] #remove excess for i in range(len(lines)): lines[i] = lines[i].strip().translate(string.punctuation).lower() while '' in lines: lines.remove('') words = [] for line in lines: line_words = line.split(' ') words = words + line_words return words def get_top_n_words(word_list, n): """ Takes a list of words as input and returns a list of the n most frequently occurring words ordered from most to least frequently occurring. word_list: a list of words (assumed to all be in lower case with no punctuation n: the number of words to return returns: a list of n most frequently occurring words ordered from most frequently to least frequentlyoccurring """ word_counts = {} for word in word_list: if word not in word_counts: word_counts[word] = 1 else: word_counts[word] += 1 ordered_by_frequency = sorted(word_counts, key=word_counts.get, reverse=True) return ordered_by_frequency[:n+1] if __name__ == "__main__": result = get_word_list('pg32325.txt') list = get_top_n_words(result, 100) print(list)
true
d2de097ee33f0060830681df81f87f600f5da69c
Scott-Dixon-Dev-Team-Organization/cs-guided-project-linked-lists
/src/demonstration_3.py
804
4.1875
4
""" Given a non-empty, singly linked list with a reference to the head node, return a middle node of linked list. If there are two middle nodes, return the second middle node. Example 1: Input: [1,2,3,4,5] Output: Node 3 from this list The returned node has value 3. Note that we returned a `ListNode` object `ans`, such that: `ans.val` = 3, `ans.next.val` = 4, `ans.next.next.val` = 5, and `ans.next.next.next` = NULL. Example 2: Input: [1,2,3,4,5,6] Output: Node 4 from this list Since the list has two middle nodes with values 3 and 4, we return the second one. *Note: The number of nodes in the given list will be between 1 and 100.* """ class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def middleNode(self, head): # Your code here
true
00ead084fe729599aeedba61cc88fc277e7726ad
menezesluiz/MITx_-_edX
/week1/exercise/exercise-for.py
442
4.34375
4
""" Exercise: for Finger Exercises due Aug 5, 2020 20:30 -03 Completed Bookmark this page Exercise: for exercise 1 5.0/5.0 points (graded) ESTIMATED TIME TO COMPLETE: 5 minutes In this problem you'll be given a chance to practice writing some for loops. 1. Convert the following code into code that uses a for loop. prints 2 prints 4 prints 6 prints 8 prints 10 prints Goodbye! """ for i in range(2, 12, 2): print(i) print("Goodbye!")
true
36e8464800601f9fc4553aacc2f48369940393df
menezesluiz/MITx_-_edX
/week1/exercise/exercise04.py
2,056
4.40625
4
""" Exercise 4 Finger Exercises due Aug 5, 2020 20:30 -03 Completed Bookmark this page Exercise 4 5/5 points (graded) ESTIMATED TIME TO COMPLETE: 8 minutes Below are some short Python programs. For each program, answer the associated question. Try to answer the questions without running the code. Check your answers, then run the code for the ones you get wrong. This question is going to ask you what some simple loops print out. If you're asked what code like this prints: """ # Exemplo num = 5 if num > 2: print(num) num -= 1 print(num) # write what it prints out, separating what appears on a new line by a comma # and a space. So the answer for the above code would be: # Resposta: 5, 4 """ If a given loop will not terminate, write the phrase 'infinite loop' (no quotes) in the box. Recall that you can stop an infinite loop in your program by typing CTRL+c in the console. Note: What does +=, -=, *=, /= stand for? a += b is equivalent to a = a + b a -= b is equivalent to a = a - b a *= b is equivalent to a = a * b a /= b is equivalent to a = a / b """ # 1 num = 0 while num <= 5: print(num) num += 1 print("Outside of loop") print(num) # Minha resposta: # 0, 1, 2, 3, 4, 5, Outside of loop, 5 ou 6 # 2 numberOfLoops = 0 numberOfApples = 2 while numberOfLoops < 10: numberOfApples *= 2 numberOfApples += numberOfLoops numberOfLoops -= 1 print("Number of apples: " + str(numberOfApples)) # Minha resposta: # Infinite Loop # 3 num = 10 while True: if num < 7: print("Breaking out of loop") break print(num) num -= 1 print("Outside of loop") """ Note: If the command break is executed within a loop, it halts evaluation of the loop at that point and passes control to the next expression. Test some break statements inside different loops if you don't understand this concept! """ # Minha resposta: # Breaking out of loop, 10, 9, Outside Of loop # 5 num = 100 while not False: if num < 0: break print('num is: ' + str(num)) # Minha resposta: # Infinit loop
true
8d6d347432112c3884102402bf0c269bcbd2ab89
Preet2fun/Cisco_Devnet
/Python_OOP/encapsulation_privateMethod.py
1,073
4.4375
4
""" Encapsulation = Abstraction + data hiding encapsulation means we are only going to show required part and rest will keep as private """ class Data: __speed = 0 #private variable __name = '' def __init__(self): self.a = 123 self._b = 456 # protected self.__c = 789 # private self.__updatesoftware() self.__speed = 200 self.__name = "I10" def __updatesoftware(self): print("Updating software") def updatespeed(self,speed): self.__speed = speed def drive(self): print("Max speed of car is : " + str(self.__speed)) num = Data() """print(num.a, num._b, num.__c) --> we can not directly acces __C as it is define as private for class and no object of that class has access to it""" print(num.a, num._b, num._Data__c) #print(num.__updatesoftware) --> not able to access as its proivate method print(num.drive()) print(num._Data__speed) num.__speed = 300 print(num.drive()) num.updatespeed(300) print(num.drive())
true
cd9c959a5bc604f523799d07470931d281d79698
paulc1600/Python-Problem-Solving
/H11_staircase.py
1,391
4.53125
5
#!/bin/python3 # ---------------------------------------------------------------------# # Source: HackerRank # Purpose: Consider a staircase of size n: # # # ## # ### # #### # # Observe that its base and height are both equal to n, and # the image is drawn using # symbols and spaces. The last # line is not preceded by any spaces. # # Write a program that prints a staircase of size n. # # Function Description # Complete the staircase function in the editor below. It # should print a staircase as described above. staircase has # the following parameter(s): # o n: an integer # # --------------------------------------------------------------------- # PPC | 08/26/2019 | Original code. # --------------------------------------------------------------------- import math import os import random import re import sys # Print a staircase where the image is drawn using # symbols and spaces. def staircase(MySteps): air_fill = ' ' for step in range(MySteps): step_len = step + 1 wood_step = step_len * '#' whole_step = wood_step.rjust(MySteps, air_fill) print(whole_step) if __name__ == '__main__': n = 15 result = staircase(n)
true
2cc6154799ccae67f873423a981c6688dc9fb2b5
paulc1600/Python-Problem-Solving
/H22_migratoryBirds_final.py
1,740
4.375
4
#!/bin/python3 # ---------------------------------------------------------------------# # Source: HackerRank # Purpose: You have been asked to help study the population of birds # migrating across the continent. Each type of bird you are # interested in will be identified by an integer value. Each # time a particular kind of bird is spotted, its id number # will be added to your array of sightings. You would like # to be able to find out which type of bird is most common # given a list of sightings. Your task is to print the type # number of that bird and if two or more types of birds are # equally common, choose the type with the smallest ID # number. # --------------------------------------------------------------------- # PPC | 09/02/2019 | Original code. # --------------------------------------------------------------------- import math import os import random import re import sys # migration def migratoryBirds(myArr): migStats = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} maxBird = 0 maxCount = 0 for birdType in myArr: migStats[birdType] = migStats[birdType] + 1 if migStats[birdType] > maxCount: maxBird = birdType maxCount = migStats[birdType] elif migStats[birdType] == maxCount and birdType < maxBird: maxBird = birdType return maxBird if __name__ == '__main__': n = 6 # ar = [1, 4, 4, 4, 5, 3] # result = migratoryBirds(ar) ar = [1, 2, 3, 4, 5, 4, 3, 2, 1, 3, 4] result = migratoryBirds(ar) # ar = [5, 5, 2, 2, 1, 1] # result = migratoryBirds(ar) print(result)
true
e955679387cd90ad3e5dfbbff7f941478063823d
Hajaraabibi/s2t1
/main.py
1,395
4.1875
4
myName = input("What is your name? ") print("Hi " + myName + ", you have chosen to book a horse riding lesson, press enter to continue") input("") print("please answer the following 2 questions to ensure that you will be prepared on the day of your lesson.") input("") QuestionOne = None while QuestionOne not in ("yes" , "no"): QuestionOne = str(input("have you got your own helmet? ")) if QuestionOne == "yes": print("great!") elif QuestionOne == "no": input("To rent a riding hat, you will have to pay a fee of £4 every lesson. Are you size small, medium or large? ") print("thank you") else: print("please enter yes or no") input("") QuestionTwo = None while QuestionTwo not in ("yes" , "no"): QuestionTwo = str(input("have you got your own riding shoes? ")) if QuestionTwo == "yes": print("great!") elif QuestionTwo == "no": print("To rent riding shoes, you will have to pay a fee of £5 every lesson.") else: print("please enter yes or no") input("") print("SUMMARY: For riding hat you chose: " + QuestionOne + " for riding shoes you chose: " + QuestionTwo + ".") Payment = input("To continue to payment, please type 'yes': ") if Payment == "yes": print("Thank you!") else: print("you have chosen not to go ahead with payment. see you again next time!")
true
0d0892bf443e39c3c5ef078f2cb846370b7852e9
JakobLybarger/Graph-Pathfinding-Algorithms
/dijkstras.py
1,297
4.15625
4
import math import heapq def dijkstras(graph, start): distances = {} # Dictionary to keep track of the shortest distance to each vertex in the graph # The distance to each vertex is not known so we will just assume each vertex is infinitely far away for vertex in graph: distances[vertex] = math.inf distances[start] = 0 # Distance from the first point to the first point is 0 vertices_to_explore = [(0, start)] # Continue while heap is not empty while vertices_to_explore: distance, vertex = heapq.heappop(vertices_to_explore) # Pop the minimum distance vertex off of the heap for neighbor, e_weight in graph[vertex]: new_distance = distance + e_weight # If the new distance is less than the current distance set the current distance as new distance if new_distance < distances[neighbor]: distances[neighbor] = new_distance heapq.heappush(vertices_to_explore, (new_distance, neighbor)) return distances # The dictionary of minimum distances from start to each vertex graph = { 'A': [('B', 10), ('C', 3)], 'C': [('D', 2)], 'D': [('E', 10)], 'E': [('A', 7)], 'B': [('C', 3), ('D', 2)] } print(dijkstras(graph, "A"))
true
026526ddd9c38e990d966a0e3259edcb2c438807
arlionn/readit
/readit/utilities/filelist.py
1,003
4.21875
4
import glob from itertools import chain def filelist(root: str, recursive: bool = True) -> [str]: """ Defines a function used to retrieve all of the file paths matching a directory string expression. :param root: The root directory/file to begin looking for files that will be read. :param recursive: Indicates whether or not glob should search for the file name string recursively :return: Returns a list of strings containing fully specified file paths that will be consumed and combined. """ listoffiles = [ glob.glob(filenm, recursive=recursive) for filenm in root ] return unfold(listoffiles) def unfold(filepaths: [str]) -> [str]: """ Defines a function that is used to convert a list of lists into a single flattened list. :param filepaths: An object containing a list of lists of file paths that should be flattened into a single list. :return: A single list containing all of the file paths. """ return list(chain(*filepaths))
true
0d012a23dfd3e68024f560287226171040c2ca67
EthanReeceBarrett/CP1404Practicals
/prac_03/password_check.py
941
4.4375
4
"""Password check Program checks user input length and and print * password if valid, BUT with functions""" minimum_length = 3 def main(): password = get_password(minimum_length) convert_password(password) def convert_password(password): """converts password input to an equal length "*" output""" for char in password: print("*", end="") def get_password(minimum_length): """takes a users input and checks that it is greater than the minimum length if not, repeats till valid then returns the password""" valid = False while not valid: password = input("Please enter password greater than 3 characters long: ") password_count = 0 for char in password: password_count += 1 if password_count <= minimum_length: print("invalid password") else: print("valid password") valid = True return password main()
true
262d7b72a9b8c8715c1169b9385dd1017cb2632b
EthanReeceBarrett/CP1404Practicals
/prac_06/programming_language.py
800
4.25
4
"""Intermediate Exercise 1, making a simple class.""" class ProgrammingLanguage: """class to store the information of a programing language.""" def __init__(self, field="", typing="", reflection="", year=""): """initialise a programming language instance.""" self.field = field self.typing = typing self.reflection = reflection self.year = year def __str__(self): """returns output for printing""" return "{}, {} typing, reflection = {}, First appeared in 1991".format(self.field, self.typing, self.reflection, self.year) def is_dynamic(self): if self.typing == "Dynamic": return True else: return False
true
8aa1cf81834abd2a7cb368ffdb9510ae7f0039e4
nobleoxford/Simulation1
/testbubblesort.py
1,315
4.46875
4
# Python program for implementation of Bubble Sort def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in place for j in range(0, n-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] # Driver code to test above arr1 = [64, 34, 25, 12, 22, 11, 90] arr2 = [64, 34, 25, 12, 22, 11] arr3 = [-64, 34, 25] arr4 = [] bubbleSort(arr1) bubbleSort(arr2) bubbleSort(arr3) bubbleSort(arr4) print ("Sorted array1 is:") print(arr1) print ("Sorted array2 is:") print(arr2) print ("Sorted array3 is:") print(arr3) print ("Sorted array4 is:") print(arr4) cards = ['5♣', '8♠', '4♠', '9♣', 'K♣', '6♣', '5♥', '3♣', '8♥', 'A♥', 'K♥', 'K♦', '10♣', 'Q♣', '7♦', 'Q♦', 'K♠', 'Q♠', 'J♣', '5♦', '9♥', '6♦', '2♣', '7♠', '10♠', '5♠', '4♣', '8♣', '9♠', '6♥', '9♦', '3♥', '3♠', '6♠', '2♥', '10♦', '10♥', 'A♠', 'A♣', 'J♥', '7♣', '4♥', '2♦', '3♦', '2♠', 'Q♥', 'A♦', '7♥', '8♦', 'J♠', 'J♦', '4♦'] bubbleSort(cards) print("Sorted cards:" ) print(cards)
true
b29b3de7434393fca62ea01898df1015e7a8871f
iamkarantalwar/tkinter
/GUI Sixth/canvas.py
1,080
4.21875
4
#tkinter program to make screen a the center of window from tkinter import * class Main: def __init__(self): self.tk = Tk() #these are the window height and width height = self.tk.winfo_screenheight() width = self.tk.winfo_screenwidth() #we find out the center co ordinates y = (height - 600)//2 x = (width - 600)//2 #place the window at the center co ordinate self.tk.geometry('600x600+'+str(x)+'+'+str(y)+'') #these lines of code are for placing picture as background self.can = Canvas(self.tk,height=600,width=600,bg="red") self.can.pack() self.img = PhotoImage(file='./images/obama.gif') self.can.create_image(0,0,image=self.img,anchor=NW) self.fr = Frame(self.tk,height=200,width=200) #we make resizable false to restrict user from resizing the window self.fr.place(x=200,y=200) self.tk.resizable(height=False,width=False) self.tk.mainloop() d = Main()
true
5765384a784ac51407757564c0cbafa06cedb83b
divyaprabha123/programming
/arrays/set matrix zeroes.py
1,059
4.125
4
'''Set Matrix Zeroes 1. Time complexity O(m * n) 2. Inplace ''' def setZeroes(matrix): """ Do not return anything, modify matrix in-place instead. """ #go through all the rows alone then is_col = False nrows = len(matrix) ncols = len(matrix[0]) for r in range(nrows): if matrix[r][0] == 0: is_col = True for c in range(1,ncols): if matrix[r][c] == 0: matrix[0][c] = 0 matrix[r][0] = 0 for r in range(1, nrows): for c in range(1, ncols): if not matrix[r][0] or not matrix[0][c]: matrix[r][c] = 0 if matrix[0][0] == 0: for c in range(ncols): matrix[0][c] = 0 if is_col: for r in range(nrows): matrix[r][0] = 0 return matrix
true
9a3b9864abada3b264eeed335f6977e61b934cd2
willzhang100/learn-python-the-hard-way
/ex32.py
572
4.25
4
the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] #first for loop goes through a list for number in the_count: print "This is count %d" % number #same for fruit in fruits: print "A fruit of type: %s" % fruit #mixed list use %r for i in change: print "I got %r" % i #built lists, start with empty elements = [] """ for i in range(0,6): print "Adding %d to the list." % i #append elements.append(i) """ elements = range(0,6) #print for i in elements: print "Element was: %d." % i
true
d6c2b9f271797e580226702c6ec843e00eea3508
SMinTexas/work_or_sleep
/work_or_sleep_in.py
428
4.34375
4
#The user will enter a number between 0 and 6 inclusive and given #this number, will make a decision as to whether to sleep in or #go to work depending on the day of the week. Day = 0 - 4 go to work #Day = 5-6 sleep in day = int(input('Day (0-6)? ')) if day >= 5 and day < 7: print('Sleep in') elif day >= 0 and day <= 4: print('Go to work') else: print('You are outside the range of available days of the week!')
true
d0db003c65b5b4bb5d08db8d23f49b29d15a2d9b
mariaKozlovtseva/Algorithms
/monotonic_check.py
798
4.3125
4
def monotonic(arr, if_true_false=False): """ Check whether array is monotonic or not :param arr: array of different numbers :return: string "Monotonic" / "Not monotonic" or if True / False """ decreasing = False increasing = False idx = 0 while not increasing and idx < len(arr)-1: # use abs() as we may have negative values if abs(arr[idx]) > abs(arr[idx+1]): increasing = True else: decreasing = True idx += 1 if if_true_false: return True if (decreasing and not increasing) else False return "Monotonic" if (decreasing and not increasing) else "Not monotonic" if __name__ == '__main__': print(monotonic([1,-2,-4,-10,-100])) print(monotonic([0,-1,-2,1,4], if_true_false=True))
true
41c3f5039e71c2ea562a61ddb37987b3e80ad0fc
grgoswami/Python_202011
/source/reg17.py
465
4.28125
4
def Fibonacci0(num): """ The following is called the docstring of the function. Parameters ---------- num : int The number of elements from the Fibonacci sequence. Returns ------- None. It prints the numbers. """ a = 1 print(a) b = 1 print(b) for i in range(2, num): c = a + b print(c) a = b b = c Fibonacci0(3) Fibonacci0(5) Fibonacci0(10) Fibonacci0(100)
true
8a0fcd96d2e7a22e2ef1d45af7dd914f4492d856
vamsikrishnar161137/DSP-Laboratory-Programs
/arrayoperations.py
1,774
4.28125
4
#SOME OF THE ARRAY OPERATIONS import numpy as np a=np.array([(1,4,2,6,5),(2,5,6,7,9)])#defining the array. print '1.The predifined first array is::',a b=np.size(a)#finding size of a array. print '2.Size of the array is::',b c=np.shape(a)#finding shape of an array print '3.Shape of the array is::',c d=np.ndim(a) print '4.Dimension of the array is::',d e=a.reshape(5,2) print '5.Reshaping of an array is::\n',e #Slicing(getting a specific digit from digit::) f=a[0,3] print '6.The digit is::',f g=np.linspace(1,3,5) print '7.The result is::',g h=np.max(a) print '8.Max of the array::',h i=np.min(a) print '9.Min of the array::',i j=np.sum(a)#sum of the digits in a array. print '10.The sum of the digits in the array is::',j k=np.sqrt(a)#finding square roots of the digits in the array. print '11.The square roots of the digits in an array is::\n',k l=np.std(a)#finding standard deviation for digits in the array. print '12.The standard deviation of the array::',l #doing sum,sub,mul,div to two arraya with their respective elements. m=np.array([(1,2,3,4,5),(4,5,6,7,8)]) n=a+m print '13.The sum of the two arrays is::\n',n o=a-m print '14.The subtraction of the two arrays is::\n',o p=a*m print '15.The multiplication of the two arrays is::\n',p q=a/m print '16.The division of the two arrays is::\n',q #placing second array in the first array.(called as stacking processes) r=np.vstack((a,m))#vertical stacking print '17.The concatenation of the two arrays is::\n',r s=np.hstack((a,m))#horizontal stacking print '18.The concatenation of the two arrays is::\n',s #converting all in one column t=a.ravel() print '19.The result is::',t u=m.ravel() print '20.The result is::',u #finding data type of the array. print '21.The data type of the array is::' print (a.dtype)
true
bc16a054e3eee1730211763fe3d0b71be4d41019
shevdan/programming-group-209
/D_bug_generate_grid.py
2,259
4.375
4
""" This module contains functions that implements generation of the game grid. Function level_of_dif determines the range (which is the representation of the level of difficulty which that will be increased thorough the test) from which the numbers will be taken. Function generate_grid generates grid, with a one specific number of needed type and 9 more random numbers. """ from random import sample, randint, shuffle from typing import List from D_bug_number_type import user_number_type as check def level_of_dif(num_of_iterations): """ This functions determines the range from which the numbers will be taken. 0 - 3 iterations : easy level of game: range of numbers [0, 20] 4 - 6 iterations : medium level of game: range of numbers [20, 50] 7 - 9 iterations : hard level of game: range of numbers [50, 100] >>> level_of_dif(0) [10, 20] >>> level_of_dif(4) [20, 50] >>> level_of_dif(6) [20, 50] >>> level_of_dif(9) [50, 100] """ range_of_nums = [] if -1 < num_of_iterations < 4: range_of_nums = [10, 20] if 3 < num_of_iterations < 7: range_of_nums = [20, 50] if 6 < num_of_iterations < 10: range_of_nums = [50, 100] return range_of_nums def generate_grid(range_of_nums: List[int], num_type: str) -> List[int]: """ This function generates the game grid, which consist of 10 numbers. Args : range_of_nums: a list of two ints, which represent the level of difficulty, which increases thorough the test. num_type: a string, which represents what type of num has to be present in the game grid. Returns: a list of 10 positive ints, which represents the game grid. Args are given by the other functions, therefore no exceptions should be rose. """ right_num = randint(range_of_nums[0], range_of_nums[1]) # checks whether a num of desired type will be present in the grid. while not check(right_num, num_type): right_num = randint(range_of_nums[0], range_of_nums[1]) range_of_generation = [i for i in range(range_of_nums[0], range_of_nums[1])] grid = sample(range_of_generation, 9) grid.append(right_num) shuffle(grid) return grid
true
3da0639a03ae3f87446ad57a859b97af60384bc4
blafuente/SelfTaughtProgram_PartFour
/list_comprehension.py
2,397
4.65625
5
# List Comprehensions # Allows you to create lists based on criteria applied to existing lists. # You can create a list comprehension with one line of code that examins every character in the original string # Selects digigts from a string and puts them in a list. # Or selects the right-most digit from the list. # Example: # return [c for c in input_string if c.isdigigt()][-1] input_string = "Buy 1 get 2 free" # A simple use of list comprehension is to create a new list from a string new_list = [c for c in input_string] # Basically says to loop through each character in input_string to create a new list print(new_list) # [c for c in input_string if c.isdigit()] # You can also add a conditional statement to the list comprehension # The 'if' clause only allows digits to go into the new list # The output will be a list containing only digits from the input_string # You can tack on a negative index to select only the last digit from the new list. # [c for c in input_string if c.isdigit()][-1] # new_list = [expression(i) for i in input_list if filter(i)] # The general syntax for a list comprehension contains a flexible collection of tools that can be applied to lists # Expression(i) is based on the variable used for each elelment in the input_string # You can simply step through each item using an expression such as "c for c" or you can manipulate # those items mathematically or character wise. # For example, the expression price*3 for price would step through each value of price at the # same time multiplying each price by three. # The word[0] for word would step through a list of words, taking the first letter of each # in input_list # This part of the list comprehension specifies the input string or list the last part of the # list comprehension # if filter(i) # The last part of the list comprehension allows you to add a conditional statement to filter out list items that match # specified critera such as being a digit ,if c.isdigit(), or being an even number (if n%2 == 0) # recap # List comprehension create lists based on criteria that iterate, processes, or filters an existing list # The general syntax for a list comprehension statement can contain an expression for stepping through an input list # based on a for loop and then expression to use as a filter to select specific items from the input_list to be added # to the new_list
true
d2f172a112ec5a30ab4daff10f08c5c4c5bc95a1
AAKASH707/PYTHON
/binary search tree from given postorder traversal.py
2,332
4.21875
4
# Python program to construct binary search tree from given postorder traversal # importing sys module import sys # class for creating tree nodes class Node: def __init__(self, data): self.data = data self.left = None self.right = None # initializing MIN and MAX MIN = -sys.maxsize - 1 MAX = sys.maxsize # recurrsive function for creating binary search tree from postorder def constructBST(postorder, postIndex, key, min, max, size): # base case if postIndex[0] < 0: return None root = None # If current element of postorder is in range(min to max), then only it is part # of current subtree if key > min and key < max: # creating a new node and assigning it to root, decrementing postIndex[0] by 1 root = Node(key) postIndex[0] -= 1 if (postIndex[0] >= 0): # all the nodes in the range(key to max) will be in the right subtree, # and first such node will be the root of the right subtree. root.right = constructBST(postorder, postIndex, postorder[postIndex[0]], key, max, size) # all the nodes in the range(min to key) will be in the left subtree, # and first such node will be the root of the left subtree. root.left = constructBST(postorder, postIndex, postorder[postIndex[0]], min, key, size) return root # function for printing the inorder traversal of the binary search tree def printInorder(root): if (root == None): return printInorder(root.left) print(root.data, end=" ") printInorder(root.right) # Driver code def main(): # asking the user for postorder sequence postorder = list(map(int, input('Enter the postorder traversal: ').split())) size = len(postorder) # postIndex is used to keep track of index in postorder postIndex = [size - 1] # calling function constructBST root = constructBST(postorder, postIndex, postorder[postIndex[0]], MIN, MAX, size) print("The inorder traversal of the constructed binary search tree: ") # calling function printInorder printInorder(root) if __name__ == "__main__": main()
true
a079327ad1c4c1fcc01c22dc9e1e8f335f119958
AAKASH707/PYTHON
/Print Square Number Pattern.py
234
4.25
4
# Python Program to Print Square Number Pattern side = int(input("Please Enter any Side of a Square : ")) print("Square Number Pattern") for i in range(side): for i in range(side): print('1', end = ' ') print()
true
5b90a261a667a86387e49463f49a8855b477174c
AAKASH707/PYTHON
/Count Words in a String using Dictionary Example.py
639
4.34375
4
# Python Program to Count words in a String using Dictionary string = input("Please enter any String : ") words = [] words = string.split() frequency = [words.count(i) for i in words] myDict = dict(zip(words, frequency)) print("Dictionary Items : ", myDict) *********************************************************************************************** # Python Program to Count words in a String using Dictionary 2 string = input("Please enter any String : ") words = [] words = string.split() # or string.lower().split() myDict = {} for key in words: myDict[key] = words.count(key) print("Dictionary Items : ", myDict)
true
5d464a64a9d8ef963da82b64fba52c598bc2b56c
josh-folsom/exercises-in-python
/file_io_ex2.py
402
4.4375
4
# Exercise 2 Write a program that prompts the user to enter a file name, then # prompts the user to enter the contents of the file, and then saves the # content to the file. file_name = input("Enter name of file you would like to write: ") def writer(file_name): file_handle = open(file_name, 'w') file_handle.write(file_name) file_handle.close() print(file_name) writer(file_name)
true
f36220a4caae8212e34ff5070b9a203f4b5814f8
josh-folsom/exercises-in-python
/python_object_ex_1.py
2,486
4.375
4
# Write code to: # 1 Instantiate an instance object of Person with name of 'Sonny', email of # 'sonny@hotmail.com', and phone of '483-485-4948', store it in the variable sonny. # 2 Instantiate another person with the name of 'Jordan', email of 'jordan@aol.com', # and phone of '495-586-3456', store it in the variable 'jordan'. # 3 Have sonny greet jordan using the greet method. # 4 Have jordan greet sonny using the greet method. # 5 Write a print statement to print the contact info (email and phone) of Sonny. # 6 Write another print statement to print the contact info of Jordan. class Person(): greeting_count = 0 def __init__(self, name, email, phone): self.name = name self.email = email self.phone = phone self.friends = [] self.num_unique_people_greeted = 0 self.uniquecounter = [] def greet(self, other_person): print ('Hello {}, I am {}!'.format(other_person, self.name)) self.greeting_count += 1 # for other_person in list1: if other_person not in self.uniquecounter: self.uniquecounter.append(other_person) self.num_unique_people_greeted += 1 def print_contact_info(self): print("{}'s email: {} , {}'s phone number: {}".format(self.name, self.email, self.name, self.phone)) def add_friend(self, other): self.friends.append(other) def __str__(self): return"Contact info for {} : email - {} | phone - {}".format(self.name, self.email, self.phone) # print('Person: {} {} {}'.format(self.name, self.email, self.phone)) # def greeting_count(self, greeting_count): # newcount = [] # if self.name.greet() == True: # newcount = count + 1 # print(newcount) sonny = Person('Sonny', 'sonny@hotmail.com', '483-485-4948') jordan = Person('Jordan', 'jordan@aol.com', '495-586-3456') print(jordan.greeting_count) print(sonny.greeting_count) sonny.greet('Jordan') sonny.greet('Jordan') #jordan.greet('Sonny') #sonny.print_contact_info() #jordan.print_contact_info() #print(sonny.email, sonny.phone) #print(jordan.email, jordan.phone) #jordan.friends.append(sonny) #sonny.friends.append(jordan) #print(len(jordan.friends)) #print(len(sonny.friends)) #print(sonny.friends) #print(jordan.friends) #jordan.add_friend(sonny) #print(len(jordan.friends)) #print(len(sonny.friends)) #print(jordan.greeting_count) #print(sonny.greeting_count) #print(jordan) print(sonny.num_unique_people_greeted) #jordan.__str__()
true
26f2d3651294e73420ff40ed603baf1ac2abb269
Rohitjoshiii/bank1
/read example.py
439
4.21875
4
# STEP1-OPEN THE FILE file=open("abc.txt","r") #STEP2-READ THE FILE #result=file.read(2) # read(2) means ir reads teo characters only #result=file.readline() #readline() it print one line only #result=file.readlines() #readlines() print all lines into list line=file.readlines() # for loop used when we dont want our text into list form for result in line: print(result) #STEP3-CLOSE THE FILE file.close()
true
db3c248cd270dad58a6386c4c9b6dc67e6ae4fab
AK-1121/code_extraction
/python/python_20317.py
208
4.1875
4
# Why mutable not working when expression is changed in python ? y += [1,3] # Means append to y list [1,3], object stays same y = y+[1,3] # Means create new list equals y + [1,3] and write link to it in y
true
6f2581f4fafe6f3511327d5365f045ba579a46b1
CdavisL-coder/automateTheBoringStuff
/plusOne.py
372
4.21875
4
#adds one to a number #if number % 3 or 4 = 0, double number #this function takes in a parameter def plus_one(num): num = num + 1 #if parameter is divided by 2 and equal zero, the number is doubled if num % 2 == 0: num2 = (num + 1) * 2 print(num2) #else print the number else: print(num) plus_one(4) plus_one(80) plus_one(33)
true
17e5dcdb6b83c5023ea428db1e93cc494d6fe405
Parashar7/Introduction_to_Python
/Celsius_to_farenheight.py
217
4.25
4
print("This isa program to convert temprature in celcius to farenheight") temp_cel=float(input("Enter the temprature in Celsius:")) temp_faren= (temp_cel*1.8) +32 print("Temprature in Farenheight is:", temp_faren)
true
ebefd9d3d3d7139e0e40489bb4f3a022ee790c19
vatasescu-predi-andrei/lab2-Python
/Lab 2 Task 2.3.py
215
4.28125
4
#task2.3 from math import sqrt a=float(input("Enter the length of side a:")) b=float(input("Enter the length of side b:")) h= sqrt(a**2 + b**2) newh=round(h, 2) print("The length of the hypotenuse is", newh)
true
f235e7b36ac48915e7e0750af1fb6621a971f227
yadavpratik/python-programs
/for_loops_programs.py
1,901
4.28125
4
# normal number print with for and range function '''n=int(input("enter the number : ")) print("normal number print with for and range function") for i in range(n): print(i) # ============================================================================================================================= # print number with space print("print horizontal with spaces :") for i in range(n): print(i,end=" ") # ============================================================================================================================= #print number with increment 2 print("\nprint with increment 2 :") for i in range(0,n,2): print(i,end=" ") # ============================================================================================================================= #print number with decrement 2 print("\nprint with decrement 2 :") for i in range(n,0,-2): print(i,end=" ") print() # ============================================================================================================================= name = "pratik" #by for loop print vertical string for i in name: print(i) #by for loop print horizontal string for i in name: print(i,end=" ") list1=list(name) print("\n",list1) for i in list1: print(i,end=" ")''' # ============================================================================================================================= # n=int(input("enter the number of rows :")) '''for i in range(5): #Represnts row for j in range(5): #Represents columns if i<j: print(j,end=" ") print()''' # ============================================================================================================================= '''for i in range(1,n+1): for j in range(1,n+1): print(n+1-i,end=" ") print()'''
true
a1ee1c5cfa1a83dfa4c2ca2dc2ec204b201ed1f2
NatalieBeee/PythonWithMaggie
/algorithms/printing_patterns.py
1,218
4.28125
4
''' #rows for i in range(0,5): #columns for j in range(0,i+1): print ('*', end ='') print ('\r') ''' # half_pyramid() is a function that takes in the number of rows def half_pyramid(num_r): #for each row -vertical for i in range(0,num_r): #for each column -horizontal for j in range(0,i+1): print ('*', end ='') print ('\r') def tree_log(log_length,log_width): #for each row -vertical for i in range(0,log_length): #for each column -horizontal for j in range(0,log_width): print ('*',end ='') print ('\r') half_pyramid(6) half_pyramid(8) half_pyramid(15) half_pyramid(19) tree_log(6,8) ''' Extra fun! 1) Add a base to the tree - DONE! tree_log() * ** *** * ** *** **** ***** * * 2) Add "|" to the top of the tree | * ** *** * ** *** **** 3) Add a star to the top of the tree * ** * * ** *** **** ***** * ** *** 4) Get the user to input the number of rows instead (hint: input()) 5) Instead of a Christmas tree, let's make a ball instead * ** *** ** * 6) Let's make a snow man * ** * * ** *** **** ***** **** *** ** * 7) Use "/" and "\" instead of "*" - let's get creative! 8) Free style! '''
true
754cd0a9c3159b2eb91350df0f5d2907c543a6ad
sbishop7/DojoAssignments
/Python/pythonAssignments/funWithFunctions.py
639
4.21875
4
#Odd/Even def odd_even(): for count in range(1,2001): if count % 2 == 1: print "Number is ", count, ". This is an odd number." else: print "Number is ", count, ". This is an even number." #Multiply def multiply(arr, x): newList = [] for i in arr: newList.append(i*x) return newList #Hacker Challenge def layered_multiples(arr): new_array = [] for i in arr: count = 0 x=[] while count < i: x.append(1) count += 1 new_array.append(x) return new_array x = layered_multiples(multiply([2,4,5],3)) print x
true
9535c83847a12174fc9d6002e19f70c163876af5
LdeWaardt/Codecademy
/Python/1_Python_Syntax/09_Two_Types_of_Division.py
1,640
4.59375
5
# In Python 2, when we divide two integers, we get an integer as a result. When the quotient is a whole number, this works fine # However, if the numbers do not divide evenly, the result of the division is truncated into an integer. In other words, the quotient is rounded down to a whole number. This can be surprising when you expect to receive a decimal and you receive a rounded-down integer To yield a float as the result instead, programmers often change either the numerator or the denominator (or both) to be a float quotient1 = 7./2 # the value of quotient1 is 3.5 quotient2 = 7/2. # the value of quotient2 is 3.5 quotient3 = 7./2. # the value of quotient3 is 3.5 # An alternative way is to use the float() method: quotient1 = float(7)/2 # the value of quotient1 is 3.5 # PROBLEM : You have come home from the grocery store with 100 cucumbers to split amongst yourself and your 5 roommates (6 people total). Create a variable cucumbers that holds 100 and num_people that holds 6. Create a variable called whole_cucumbers_per_person that is the integer result of dividing cucumbers by num_people. Print whole_cucumbers_per_person to the console. You realize that the numbers don't divide evenly and you don't want to throw out the remaining cucumbers. Create a variable called float_cucumbers_per_person that holds the float result of dividing cucumbers by num_people. Print float_cucumbers_per_person to the console. cucumbers = 100 num_people = 6 whole_cucumbers_per_person = cucumbers / num_people print whole_cucumbers_per_person float_cucumbers_per_person = float(cucumbers)/num_people print float_cucumbers_per_person
true
ea14d5de2d43b1f19eb612dea929a612ebfed717
Ottermad/PythonNextSteps
/myMagic8BallHello.py
819
4.15625
4
# My Magic 8 Ball import random # put answers in a tuple answers = ( "Go for it" "No way, Jose!" "I'm not sure. Ask me again." "Fear of the unkown is what imprisons us." "It would be madness to do that." "Only you can save mankind!" "Makes no difference to me, do or don't - whatever" "Yes, I think on balance that is the right choice" ) print("Welcome to MyMagic8Ball.") name = input("What is your name?") # get the user's question question = input("Ask me for advice, " + name + " then press ENTER to shake me.\n") print("shaking ...\n" * 4) # use the randint function to select the correct answer choice = random.randint(0,7) # print the answer to the screen print(answers[choice]) # exit nicely input("\n\nThanks for playing, " + name + ". Press the RETURN key to finish.")
true
9f4a1f9c1e212efe17186287746b7b4004ac037a
Col-R/python_fundamentals
/fundamentals/Cole_Robinson_hello_world.py
762
4.21875
4
# 1. TASK: print "Hello World" print('Hello World!') # 2. print "Hello Noelle!" with the name in a variable name = "Col-R" print('Hello', name) # with a comma print('Hello ' + name) # with a + # # 3. print "Hello 42!" with the number in a variable number = 24 print('Hello', number) # with a comma print('Hello '+ str(number)) # with a + -- this one should give us an error! # # 4. print "I love to eat sushi and pizza." with the foods in variables fave_food1 = "ramen" fave_food2 = "cake" print("I love to eat {} and {}".format(fave_food1, fave_food2)) # with .format() print(f'I love to eat {fave_food1} and {fave_food2}') # with an f string eats = (f'I love to eat {fave_food1} and {fave_food2}') print (len(eats)) print (eats.upper()) print (eats.title())
true
768d5acc06bf952cb396c18ceea1c6f558634f6f
Col-R/python_fundamentals
/fundamentals/strings.py
1,874
4.4375
4
#string literals print('this is a sample string') #concatenation - The print() function inserts a space between elements separated by a comma. name = "Zen" print("My name is", name) #The second is by concatenating the contents into a new string, with the help of +. name = "Zen" print("My name is " + name) number = 5 print('My number is', number) # print('My number is'+ number) throws an error # Type Casting or Explicit Type Conversion # print("Hello" + 42) # output: TypeError print("Hello" + str(42)) # output: Hello 42 total = 35 user_val = "26" # total = total + user_val output: TypeError total = total + int(user_val) # total will be 61 # f-strings: Python 3.6 introduced f-strings for string interpolation. To construct a f-string, place an f right before the opening quotation. Then within the string, place any variables within curly brackets. first_name = "Zen" last_name = "Coder" age = 27 print(f"My name is {first_name} {last_name} and I am {age} years old.") # string.format() Prior to f-strings, string interpolation was accomplished with the .format() method. first_name = "Zen" last_name = "Coder" age = 27 print("My name is {} {} and I am {} years old.".format(first_name, last_name, age)) # output: My name is Zen Coder and I am 27 years old. print("My name is {} {} and I am {} years old.".format(age, first_name, last_name)) # output: My name is 27 Zen and I am Coder years old. # %-formatting - an even older method, the % symbol is used to indicate a placeholder, a %s for a string and %d for a number. hw = "Hello %s" % "world" # with literal values py = "I love Python %d" % 3 print(hw, py) # output: Hello world I love Python 3 name = "Zen" age = 27 print("My name is %s and I'm %d" % (name, age)) # or with variables # output: My name is Zen and I'm 27 # Built in methods x = "hello world" print(x.title()) # output: "Hello World"
true
7ddac6a6f3770cacd02645e29e1058d885e871f2
dburr698/week1-assignments
/todo_list.py
1,924
4.46875
4
# Create a todo list app. tasks = [] # Add Task: # Ask the user for the 'title' and 'priority' of the task. Priority can be high, medium and low. def add_task(tasks): name = input("\nEnter the name of your task: ") priority = input("\nEnter priority of task: ") task = {"Task": name, "Priority": priority} tasks.append(task) return tasks # Delete Task: # Show user all the tasks along with the index number of each task. User can then enter the index number of the task to delete the task. def delete_task(tasks): for index in range(len(tasks)): print(f"{index + 1} - {tasks[index]['Task']} - {tasks[index]['Priority']}") num = int(input("\nEnter the number of the task you would like to delete: ")) for index in range(len(tasks)): if tasks[index] == tasks[num - 1]: print(f"\nThe task {tasks[num -1]['Task']} has been deleted from your To-Do list.") del tasks[index] break return tasks # View all tasks: # Allow the user to view all the tasks in the following format: def view_tasks(tasks): if len(tasks) == 0: print("\nYou have no tasks.") for index in range(len(tasks)): print(f"{index + 1} - {tasks[index]['Task']} - {tasks[index]['Priority']}") # When the app starts it should present user with the following menu: # Press 1 to add task # Press 2 to delete task # Press 3 to view all tasks # Press q to quit # The user should only be allowed to quit when they press 'q'. while True: choice = input( "\nPress 1 to add task \nPress 2 to delete task \nPress 3 to view all tasks \nPress q to quit \n" ) if choice == "q": print("\nGoodbye\n") break elif choice == "1": add_task(tasks) elif choice == "2": delete_task(tasks) elif choice == "3": view_tasks(tasks) else: print("\nInvalid option\n")
true
7d6aef42709ca67f79beed472b3b1049efd73513
chriklev/INF3331
/assignment6/_build/html/_sources/temperature_CO2_plotter.py.txt
2,237
4.1875
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt def plot_temperature(months, time_bounds=None, y_bounds=None): """Plots the temperatures of given months vs years Args: months (string): The month for witch temperature values to plot. Can also be list of strings with several month names. time_bounds (tuple or list): Optional argument with minimum and maximum for the years to plot. Must be tuple or list, of integers or floats on the form: (minimum, maximum) y_bounds (tuple or list): Optional argument with minimum and maximum for the y-axis. Must be tuple or list, of integers or floats on the form: (minimum, maximum) """ temperatures = pd.read_csv( "temperature.csv", usecols=["Year"].append(months)) if time_bounds: bounds = temperatures["Year"].map( lambda x: x >= time_bounds[0] and x <= time_bounds[1]) temperatures = temperatures[bounds] temperatures.plot("Year", months, ylim=y_bounds) plt.title("Temperature vs. year for given months") plt.xlabel("time [years]") plt.ylabel("temperature [celsius]") def plot_CO2(time_bounds=None, y_bounds=None): """Plots global carbon emmissions vs years Args: time_bounds (tuple or list): Optional argument with minimum and maximum for the years to plot. Must be tuple or list, of integers or floats on the form: (minimum, maximum) y_bounds (tuple or list): Optional argument with minimum and maximum for the y-axis. Must be tuple or list, of integers or floats on the form: (minimum, maximum) """ co2 = pd.read_csv("co2.csv") if time_bounds: bounds = co2["Year"].map( lambda x: x >= time_bounds[0] and x <= time_bounds[1]) co2 = co2[bounds] co2.plot("Year", "Carbon", ylim=y_bounds, legend=False) plt.title("Global carbon emmissions vs. year") plt.xlabel("time [years]") plt.ylabel("carbon emmissions [million metric tons]") if __name__ == "__main__": plot_CO2() plt.show() plot_temperature( ["January", "February", "March"]) plt.show()
true