blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
fade8fcd236ccbf30038d4ca49cd11dd18dae898
isaolmez/core_python_programming
/com/isa/python/chapter6/ShallowCopy.py
1,228
4.28125
4
## SHALLOW COPY person = ["name", ["savings", 100.00]] print id(person), id(person[:]) print "---- Slice copy" husband = person[:] print id(person), id(person[:]) print id(person), id(husband) # They both refer to the same string "name" as their first element and so on. print "id() of names:", id(person[0]), id(husband[0]) print "id() of savings:", id(person[1]), id(husband[1]) husband[0] = "isa" print person, "\n", husband print "---- Factory function copy" wife = list(person) wife[0] = "hilal" # Assign new object, so one change cannot effect other. No magic print id(person), id(person[:]) print id(person), id(wife) print "---- All three\n", id(person), id(husband), id(wife) print person, "\n", husband, "\n", wife ## Notes till now: # We have shallow copies. Only references are copied for the inner objects, not the object itself. # The object copied itself is new, but the contents are not. # Lets see what this means. husband[1][1] = 50.00 # Assign new value to the state of aliased object. This is state modification for aliased object, not a new object assignment. print person, "\n", husband, "\n", wife # This line has changed inner list in all 3 objects. All are mutated.
true
0c2c06e78b487259157082a78e21bdcf951a457b
Supython/SuVi
/+or-or0.py
287
4.5
4
#To Check whether the given number is positive or negative S=int(input("Enter a number: ")) if S>0: print("Given number {0} is positive number".format(S)) elif S<0: print("Given number {0} is negative number".format(S)) else: print("Given number {0} s Zero".format(S))
true
d4c1b4e64302f1f0a851ed7fa7061142b687320d
chisoftltd/PythonFilesOperations
/PythonWriteFile.py
1,443
4.375
4
# Write to an Existing File import os f = open("demofile2.txt", "a") f.write("Now the file has more content! TXT files are useful for storing information in plain text with no special formatting beyond basic fonts and font styles.") f.close() myfile = open("Tutorial2.txt", "w") myfile.write("Python Programming Tutorials \n") myfile.write("Coding Challenge \n") myfile.write("Java Programming Tutorial") myfile.close() #open and read the file after the appending: f = open("demofile2.txt", "r") print(f.read()) f = open("demofile.txt", "w") f.write("Woops! I have deleted the content! The file is commonly used for recording notes, directions, and other similar documents that do not need to appear a certain way. If you are looking to create a document with more formatting capabilities, such as a report, newsletter, or resume, you should look to the .DOCX file, which is used by the popular Microsoft Word program.") f.close() #open and read the file after the appending: f = open("demofile.txt", "r") print(f.read()) # Create a New File if os.path.exists("myfile5.txt") or os.path.exists("myfile4.txt"): os.remove("myfile4.txt") os.remove("myfile5.txt") else: print("The file does not exist") f = open("myfile4.txt", "x") f = open("myfile5.txt", "w") # The mkdir() Method os.mkdir("myfiles") # The getcwd() Method() os.getcwd() # The chdir() Method # os.chdir("C:/data") # The rmdir() Method os.rmdir("myfiles")
true
8c2035389bee962cd81c58f710e21d5f5e15d5cd
artorious/simple_scripts_tdd
/test_longer_string.py
998
4.15625
4
#!/usr/bin/env python3 """ Tests for longer_string.py """ import unittest from longer_string import longer_string class TestLongerString(unittest.TestCase): """ Test cases for longer_string() """ def test_invalid_input(self): """ Tests both arguments are strings """ self.assertRaises( TypeError, longer_string, ('art', 1), 'Expected strings' ) self.assertRaises( TypeError, longer_string, (11, 1), 'Expected strings' ) def test_different_lengths(self): """ Test function prints the longer of the two strings provided """ self.assertEqual(longer_string('art', 'arthur'), 'arthur') self.assertEqual(longer_string('arthur', 'arthr'), 'arthur') def test_same_lengths(self): """ Test function prints both strings if they are of the same length """ self.assertEqual(longer_string('arthur', 'ngondo'), 'arthur\nngondo') if __name__ == '__main__': unittest.main()
true
e4a9b2f2f3c847ea444f2380217eca63adf7ffd3
JessBrunker/euler
/euler23/euler23.py
2,576
4.125
4
#!/usr/bin/python3 ''' A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1+2+4+7+14=28, which means 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if the sum exceed n. As 12 is the smallest abundant number, 1+2+3+4+6=16, the smallest number that can be written as the sum of two abundant numbers is 24. By By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. ''' import time import math start = time.time() summed_divisors = {1:0, 2:0, 3:0, 5:0, 7:0, 11:0, 13:0, 17:0, 19:0} ''' def sum_divisors(num): if num in summed_divisors: return summed_divisors[num] top = int(num/2) while top > 1: if num % top == 0: div = int(num / top) factor = sum_divisors(top) summed_divisors[num] = 1 + top + factor if div not in summed_divisors: summed_divisors[num] += div return summed_divisors[num] top -= 1 summed_divisors[num] = 0 return 0 ''' def sum_divisors(num): if num == 1: return 1 top = int(math.sqrt(num)) + 1 total = 1 divisor = 2 while divisor < top: if num % divisor == 0: total += divisor total += int(num/divisor) divisor += 1 return total # test if number is abundant def is_abundant(num): return sum_divisors(num) > num def test_abundant(num): total = 0 for i in range(1, int(num/2)+1): if num % i == 0: total += i return total > num if __name__ == '__main__': UPPER_LIMIT = 28124 #UPPER_LIMIT = 2000 abundants = [] for i in range(2,UPPER_LIMIT, 2): if is_abundant(i): abundants.append(i) sums = set() top = 0 for i in abundants: for j in abundants: total = i + j top = max(top, total) sums.add(total) total = 0 for i in range(top): if i not in sums: total += i print(total) end = time.time() print('{}s'.format(end-start))
true
8ffa90066929fb6ada2524fedba217edd785c2e4
jorge-jauregui/guess-the-number-game
/guess the number.py
587
4.125
4
print("Welcome to Jorge's 'guess the number' game!") print("I have in mind a number between 1 and 100. Can you guess what it is?") import random random.randrange(1, 101) number_guess = random.randrange(1, 101) chances = 0 while chances < 100000: user_guess = int(input("Type your guess: ")) if user_guess == number_guess: print("You smart cookie! Sorry, I don't have anything to give you.") break elif user_guess > number_guess: print("Are you trying to pull my leg? Guess lower.") else: print("The number I have in mind is higher.")
true
316688cfd723a90690b103add5d1b582ca75bbf9
akshay-1993/Python-HackerRank
/Staircase.py
574
4.40625
4
# Problem # Consider a staircase of size : n = 4 # # # # ## # ### # #### # 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. #!/bin/python3 import math import os import random import re import sys # Complete the staircase function below. def staircase(n): for i in range(1, n+1): print(' '*(n-i)+"#"*i) if __name__ == '__main__': n = int(input()) staircase(n)
true
36d0406ea682acc2c1847191849ac889a75d75c9
dagamargit/absg_exercises
/04_changing_the_line_spacing_of_a_text_file.py
1,063
4.125
4
#!/usr/bin/python # Write a script that reads each line of a target file, then writes the line back to stdout, #+but with an extra blank line following. This has the effect of double-spacing the file. # # Include all necessary code to check whether the script gets the necessary command-line argument (a filename), #+and whether the specified file exists. # # When the script runs correctly, modify it to triple-space the target file. # Finally, write a script to remove all blank lines from the target file, single-spacing it. import sys import os err_wrong_args = 65 if len(sys.argv) == 1 or not os.path.isfile(sys.argv[1]): print "Usage: " + os.path.basename(sys.argv[0]) + " file" sys.exit(err_wrong_args) text_file = sys.argv[1] with open(text_file) as fl: for line in fl.readlines(): if len(line) > 1: print line, # For now, script remove all blank lines from file. # For double-spacing: uncomment two lines below. # For triple-spacing: uncomment three lines below. # print # print # print
true
e267a34267b31cae25ca650817d9f6ec23097ccc
jeremy-techson/PythonBasics
/tuples.py
621
4.375
4
# Tuples are immutable list numbers = (1, 2, 3, 4, 5) print(numbers) # Operations available to tuples are almost the same with list print(numbers[0:3]) print("Length: ", len(numbers)) numbers = numbers + (6, 7) print(numbers) print("7 in tuple?", 7 in numbers) for num in numbers: print(num, end=", ") print("") # Convert list to tuple strawhat_crew = ["Luffy", "Zorro", "Nami", "Sanji", "Usopp", "Chopper", "Robin", "Franky", "Brook", "Jimbei"] strawhat_crew = tuple(strawhat_crew) print(strawhat_crew) # Convert tuple to list print(list(strawhat_crew)) print(min(strawhat_crew)) print(max(strawhat_crew))
true
2500df19b972bec81642da911c1ee72101bf0ee8
tjguk/kelston_mu_code
/20181124/primes.py
635
4.21875
4
"""A simple function which will indicate whether a number is a prime or not """ def is_prime(n): # # Check every number up to half of the number # we're checking since if we're over half way # we must have hit all the factors already # for factor in range(2, 1 + (n // 2)): if n % factor == 0: # # Bail out as soon as we've found a factor # return False # # If we haven't found anything, it's a prime # return True while True: candidate = int(input("Enter a number: ")) print("Prime" if is_prime(candidate) else "Not Prime")
true
316e325d6eb23a574569332c4796dc70118847bc
ardenzhan/dojo-python
/arden_zhan/Python/Python Fundamentals/string_list.py
862
4.125
4
''' String and List Practice .find() .replace() min() max() .sort() len() ''' print "Find and Replace" words = "It's thanksgiving day. It's my birthday, too!" print "Position of first instance of day:", words.find("day") print words.replace("day", "month", 1) print "" print "Min and Max" x = [2,54,-2,7,12,98] print "List:", x print "Min value of list:", min(x) print "Max value of list:", max(x) print "" print "First and Last" x = ["hello",2,54,-2,7,12,98,"world"] print "List:", x newList = [x[0], x[len(x) - 1]] print "List of first and last element:", newList print "" print "New List" x = [19,2,54,-2,7,12,98,32,10,-3,6] print x x.sort() print "Sorted List", x half = len(x) / 2 firstHalf = x[:half] secondHalf = x[half:len(x)] print "First Half:", firstHalf print "Second Half:", secondHalf secondHalf.insert(0, firstHalf) print "Output:", secondHalf
true
4d79f25d46800b34809bfa18691f99567f91ce20
ardenzhan/dojo-python
/arden_zhan/Python/Python Fundamentals/scores_and_grades.py
800
4.34375
4
'''Scores and Grades''' # generates ten scores between 60 and 100. Each time score generated, displays what grade is for particular score. ''' Grade Table Score: 60-79; Grade - D Score: 70-79; Grade - C Score: 80-89; Grade - B Score: 90-100; Grade - A ''' # import random # #random_num = random.random() # #random function returns float - 0.0 <= random_num < 1.0 # random_num = random.randint(60, 100) import random def scoreGrade(quantity, min, max): for x in range(quantity): random_num = random.randint(min, max) grade = "" if random_num >= 90: grade += "A" elif random_num >= 80: grade += "B" elif random_num >= 70: grade += "C" else: grade += "D" print "Score: {}; Your grade is {}".format(random_num, grade) scoreGrade(10, 60, 100)
true
c63063ed71536d139b127cc48d2aae18a915e8ba
muhammad-masood-ur-rehman/Skillrack
/Python Programs/adam-number.py
665
4.375
4
Adam number A number is said to be an Adam number if the reverse of the square of the number is equal to the square of the reverse of the number.  For example, 12 is an Adam number because the reverse of the square of 12 is the reverse of 144, which is 441, and the square of the reverse of 12 is the square of 21, which is also 441. Write an Algorithm and the subsequent Python code to check whether the given number  is an Adam number or not. Write a function to reverse a number def rev(n): return(int(str(n)[::-1])) def adam(num): if(rev(num)**2==rev(num**2)): print('Adam number') else: print('Not an Adam number') n=int(input()) adam(n)
true
7451ad703a6c8c56d0976ef8e6d481ef3e7feae0
muhammad-masood-ur-rehman/Skillrack
/Python Programs/sum-unit-digit-3-or-6.py
667
4.34375
4
Sum - Unit Digit 3 or 6 The program must accept N integers as the input. The program must print the sum of integers having the unit digit as 3 or 6 as the output. If there is no such integer then the program must print -1 as the output. Boundary Condition(s): 1 <= N <= 100 1 <= Each integer value <= 10^5 Example Input/Output 1: Input: 5 12 43 30 606 7337 Output: 649 Example Input/Output 2: Input: 4 52 84 365 134 Output: -1 N = int(input()) numList = [int(val) for val in input().split()] sumVal, printed = 0, False for val in numList: if val % 10 == 3 or val % 10 == 6: sumVal += val printed = True print('-1' if sumVal == 0 else sumVal)
true
1c96e07d40bd8283d1b28ac27fe4c5d8af4d31e4
muhammad-masood-ur-rehman/Skillrack
/Python Programs/replace-border-with-string.py
907
4.3125
4
Replace Border with String The program must accept a character matrix of size RxC and a string S as the input. The program must replace the characters in the border of the matrix with the characters in the string S in the clockwise direction. Then the program must print the modified matrix as the output. Example Input/Output 1: Input: 4 5 @ b c d E e f 5 h i b c d e q k 9 o l 2 queenbee Output: q u e e n e f 5 h b b c d e e k 9 o l e Example Input/Output 2: Input: 3 3 A b c d * f g h i d@$zling Output: d @ $ g * z n i l R,C=map(int,input().split()) matrix=[list(map(str,input().split())) for ctr in range(R)] S=input().strip() row,col=0,0 for ch in S: matrix[row][col]=ch if row==0 and col<C-1: col+=1 elif row==R-1 and col>0: col-=1 elif col==C-1 and row<R-1: row+=1 elif col==0 and row>0: row-=1 for val in matrix: print(*val)
true
ada01c186d7844f188d4231a43681cedd802029c
muhammad-masood-ur-rehman/Skillrack
/Python Programs/product-of-current-and-next-elements.py
1,369
4.125
4
Product of Current and Next Elements Given an array of integers of size N as input, the program must print the product of current element and next element if the current element is greater than the next element. Else the program must print the current element without any modification. Boundary Condition(s): 1 <= N <= 100 Input Format: The first line contains the value of N. The second line contains N integers separated by space(s). Output Format: The first line contains N integers separated by space(s). Example Input/Output 1: Input: 6 5 4 6 5 7 2 Output: 20 4 30 5 14 2 Explanation: For 1st element, 5>4 so the output is 5*4=20 For 2nd element, 4<6 so the output is 4 For 3rd element, 6>5 so the output is 6*5=30 For 4th element, 5<7 so the output is 5 For 5th element, 7>2 so the output is 14 For 6th element there is no next element, so the output is 2 Example Input/Output 2: Input: 5 22 21 30 2 5 Output: 462 21 60 2 5 Explanation: For 1st element, 22>21 so the output is 22*21=462 For 2nd element, 21<30 so the output is 21 For 3rd element, 30>2 so the output is 30*2=60 For 4th element, 2<5 so the output is 2 For 5th element there is no next element, so  the output is 5 n=int(input()) l=list(map(int,input().split())) for i in range(n-1): if(l[i]>l[i+1]): print(l[i]*l[i+1],end=" ") else: print(l[i],end=" ") print(l[n-1])
true
5c30823a56d59cc5c51b764f4781fed4b1ba1997
muhammad-masood-ur-rehman/Skillrack
/Python Programs/find-duplicates-in-folder.py
1,562
4.1875
4
Find Duplicates In Folder The directory structure of a file system is given in N lines. Each line contains the parent folder name and child file/folder name. If a folder has two files/folders with the same name then it is a duplicate. Print all the duplicate file/folders names sorted in ascending order. If there is no duplicate print -1. Boundary Condition(s): 1 <= N <= 100 2 <= Length of file/folder name <= 100 Input Format: The first line contains N. The next N lines contain parent and child file/folder name separated by space. Output Format: Print the duplicate file/folder names sorted in ascending order. If there is no duplicate print -1. Example Input/Output 1: Input: 5 videos trailer.mp4 documents word.doc documents animal.jpg test trailer.mp4 documents word.doc Output: word.doc Example Input/Output 2: Input: 7 src style.css videos HD.mp4 documents sheet.xls documents animal.jpg test animal.jpg documents sheet.xls src style.css Output: sheet.xls style.css a=int(input()) d={} e=[];f=[] for i in range(a): b,c=map(str,input().split()) e.append(b) f.append(c) x=0 for i in f: d.setdefault(i,[]).append(e[x]) x+=1 ans=[] for i in d.keys(): s=list(set(d[i])) if(len(d[i])>1): if(len(s)!=len(d[i])): ans.append(i) ans=sorted(ans) if(ans==[]): print(-1) else: print(*ans, sep="\n") d=[] c=[] for i in range(int(input())): k=input().split() if k not in d: d.append(k) elif k[1] not in c: c.append(k[1]) if not c: print(-1) for i in sorted(c): print(i)
true
63f9c82f95090e789395286b4f977b74ac621a4b
muhammad-masood-ur-rehman/Skillrack
/Python Programs/matching-word-replace.py
1,307
4.3125
4
Matching Word - Replace ? The program must accept two string values P and S as input. The string P represents a pattern. The string S represents a set of words. The character '?' in P matches any single character. The program must print the word in S that matches the given pattern P as the output. If two or more words match the pattern P, then the program must print the first occurring word as the output. Note: At least one word in S is always matched with P. Boundary Condition(s): 1 <= Length of P <= 100 1 <= Length of S <= 1000 Input Format: The first line contains P. The second line contains S. Output Format: The first line contains a string representing the word in S that matches the pattern P. Example Input/Output 1: Input: ?i?n LION crane lion breath kiln Output: lion Explanation: Here P = "?i?n" and S = "LION crane lion breath kiln". There are two words in S that match the pattern P. lion klin So the first occurring word lion is printed as the output. Example Input/Output 2: Input: BR??E? BRIGHT BEST BRAVE BROKEN Output: BROKEN s=input().strip() k=s;p=[];m=0 l=input().strip().split() for i in l: m=0 if len(i)==len(s): for j in range(len(i)): if s[j]!='?' and s[j]!=i[j]: m=1 if m==0: p.append(i) print(p[0])
true
5de0252734c9525ea7956e7cd76d14401e1b3d7d
muhammad-masood-ur-rehman/Skillrack
/Python Programs/python-program-for-interlace-odd-even-from-a-to-b.py
1,509
4.4375
4
Python Program for Interlace odd / even from A to B Two numbers A and B are passed as input. The program must print the odd numbers from A to B (inclusive of A and B) interlaced with the even numbers from B to A. Input Format: The first line denotes the value of A. The second line denotes the value of B. Output Format: The odd and even numbers interlaced, each separated by a space. Boundary Conditions: 1 <= A <= 9999999 A <  B <= 9999999 Example Input/Output 1: Input: 5 11 Output: 5 10 7 8 9 6 11 Explanation: The odd numbers from 5 to 11 are 5 7 9 11 The even numbers from 11 to 5 (that is in reverse direction) are 10 8 6 So these numbers are interlaced to produce 5 10 7 8 9 6 11 Example Input/Output 2: Input: 4 14 Output: 14 5 12 7 10 9 8 11 6 13 4 Explanation: The odd numbers from 4 to 14 are 5 7 9 11 13 The even numbers from 14 to 4 (that is in reverse direction) are 14 12 10 8 6 4 So these numbers are interlaced to produce 14 5 12 7 10 9 8 11 6 13 4 (Here as the even numbers count are more than the odd numbers count we start with the even number in the output) Example Input/Output 3: Input: 3 12 Output: 3 12 5 10 7 8 9 6 11 4 Explanation: The odd numbers from 3 to 12 are 3 5 7 9 11 The even numbers from 12 to 3 (that is in reverse direction) are 12 10 8 6 4 So these numbers are interlaced to produce 3 12 5 10 7 8 9 6 11 4 a=int(input()) b=int(input()) i=a;j=b while(i<=b and j>=a): if i%2!=0: print(i,end=" ") i+=1 if j%2==0: print(j,end=" ") j-=1
true
c2b2db90bec32dd87464306cbc8a57b91b3d0243
muhammad-masood-ur-rehman/Skillrack
/Python Programs/odd-even-row-pattern-printing.py
940
4.59375
5
Odd Even Row - Pattern Printing Given a value of N, where N is the number of rows, the program must print the character '*' from left or right depending on whether the row is an odd row or an even row. - If it is an odd row, the '*' must start from left. - If it is an even row, the '*' must start from right. After the asterisk '*' the numbers from 1 to the row count must be printed. Input Format: The first line will contain the value of N Output Format: N lines will contain '*' forming the pattern as described. Constraints: 2 <= N <= 25 Example Input/Output 1: Input: 3 Output: *1 21* *123 Example Input/Output 2: Input: 5 Output: *1 21* *123 4321* *12345 n=int(input()) for i in range(1,n+1): if(i%2!=0): print("*",end="") for j in range(1,i+1): print(j,end="") print() elif(i%2==0): for j in range(i,0,-1): print(j,end="") print("*",end="") print()
true
25e72d166e88791aaac58cdd83ed552c38b3867f
muhammad-masood-ur-rehman/Skillrack
/Python Programs/check-sorted-order.py
1,127
4.125
4
Check Sorted Order The program must accept N integers which are sorted in ascending order except one integer. But if that single integer R is reversed, the entire array will be in sorted order. The program must print the first integer that must be reversed so that the entire array will be sorted in ascending order. Boundary Condition(s): 2 <= N <= 20 Input Format: The first line contains N. The second line contains N integer values separated by a space. Output Format: The first line contains the integer value R. Example Input/Output 1: Input: 5 10 71 20 30 33 Output: 71 Explanation: When 71 is reversed the array becomes sorted as below. 10 17 20 30 33 Example Input/Output 2: Input: 6 10 20 30 33 64 58 Output: 64 Example Input/Output 3: Input: 6 10 20 30 33 67 58 Output: 58 def rev(n): reve=0 while(n>0): r=n%10 reve=reve*10+r n=n//10 return reve n=int(input()) l=list(map(int,input().split()));ind=0 while(True): number=l[ind] r=rev(number) l[ind]=r if l==sorted(l): print(number) break else: l[ind]=number ind+=1
true
a8d6708bf1f9958cd05214bf00e43a3cf3dcdfe0
muhammad-masood-ur-rehman/Skillrack
/Python Programs/count-overlapping-string-pattern.py
1,039
4.1875
4
Count Overlapping String Pattern Two string values S and P representing a string and pattern are passed as the input to the program. The program must print the number of overlapping occurrences of pattern P in the string S as the output. Note: The string S and pattern P contains only lowercase alphabets. Boundary Condition(s): 1 <= Length of S <= 2000000 1 <= Length of P <= 10 Input Format: The first line contains S. The second line contains P. Output Format: The first line contains the number of overlapping occurrences of P in S. Example Input/Output 1: Input: precondition on Output: 2 Explanation: The pattern on occurs two times in precondition so 2 is printed. Example Input/Output 2: Input: tetetetmtey tet Output: 3 def overlap(string,substring): c=0;s=0 while s<len(string): pos=string.find(substring,s) if pos!=-1: s=pos+1 c+=1 else: break return c string=input().strip() substring=input().strip() print(overlap(string,substring))
true
6ee5cd6a8e090682bf699c788e467ccb8cfb975c
muhammad-masood-ur-rehman/Skillrack
/Python Programs/first-m-multiples-of-n.py
558
4.46875
4
First M multiples of N The number N is passed as input. The program must print the first M multiples of the number Input Format: The first line denotes the value of N. The second line denotes the value of M. Output Format: The first line contains the M multiples of N separated by a space. Boundary Conditions: 1 <= N <= 999999 Example Input/Output 1: Input: 5 7 Output: 5 10 15 20 25 30 35 Example Input/Output 2: Input: 50 11 Output: 50 100 150 200 250 300 350 400 450 500 550 a=int(input()) b=int(input()) for i in range(1,b+1): print(a*i,end=" ")
true
15125f1513e68e317ad5bc79e4f09f7c6dbb4dbd
muhammad-masood-ur-rehman/Skillrack
/Python Programs/direction-minimum-shift.py
2,093
4.3125
4
Direction & Minimum Shift The program must accept two string values S1 and S2 as the input. The string S2 represents the rotated version of the string S1. The program must find the minimum number of characters M that must be shifted (Left or Right) in S1 to convert S1 to S2. Then the program must print the direction (L-Left or R-Right or A-Any direction) in which the characters in the string S1 are shifted and the value of M as the output. The direction A represents that the string S1 can be converted to S2 in both directions with the same value M. Boundary Condition(s): 2 <= Length of S1, S2 <= 100 Input Format: The first line contains S1. The second line contains S2. Output Format: The first line contains a character (L or R or A) and M. Example Input/Output 1: Input: hello llohe Output: L2 Explanation: Here S1 = hello and S2 = llohe. If 3 characters in S1 are shifted to the right, it becomes llohe. If 2 characters in S1 are shifted to the left, it becomes llohe. Here the minimum is 2, so L2 is printed as the output. Example Input/Output 2: Input: IcecrEAm EAmIcecr Output: R3 Explanation: Here S1 = IcecrEAm and S2 = EAmIcecr. If 3 characters in S1 are shifted to the right, it becomes EAmIcecr. If 5 characters in S1 are shifted to the left, it becomes EAmIcecr. Here the minimum is 3, so R3 is printed as the output. Example Input/Output 3: Input: ROBOTICS TICSROBO Output: A4 Explanation: Here S1 = ROBOTICS and S2 = TICSROBO. If 4 characters in S1 are shifted to the right, it becomes TICSROBO. If 4 characters in S1 are shifted to the left, it becomes TICSROBO. Here both directions give the minimum is 4, so A4 is printed as the output. n=input().strip() m=input().strip() if n==m: print("A0") else: l,r=n,n for i in range(1,len(n)+1): l=l[1:]+l[0] r=r[-1]+r[:-1] if l==m and r==m: print("A{}".format(i)) break elif l==m: print("L{}".format(i)) break elif r==m: print("R{}".format(i)) break
true
c88a8f7c2ef64b308a95bd5b040b5f98df2f40b1
muhammad-masood-ur-rehman/Skillrack
/Python Programs/remove-characters-from-left.py
1,445
4.28125
4
Remove Characters from Left Remove Characters from Left: The program must accept two string values S1 and S2 as the input. The program must print the minimum number of characters M to be removed from the left side of the given string values so that the revised string values become equal (ignoring the case). If it is not possible, then the program must print -1 as the output. Boundary Condition(s): 1 <= Length of S1, S2 <= 1000 Input Format: The first line contains S1. The second line contains S2. Output Format: The first line contains M. Example Input/Output 1: Input: Cream JAM Output: 4 Explanation: After removing the first 3 characters from the string Cream, the string becomes am. After removing the first character from the string JAM, the string becomes AM. The revised string values am and AM are equal by ignoring the case. The minimum number of characters to be removed from the left side of the given string values is 4 (3 + 1). So 4 is printed as the output. Example Input/Output 2: Input: corn Corn Output: 0 Example Input/Output 3: Input: 123@abc 123@XYZ Output: -1 S1=input().strip().lower() S2=input().strip().lower() L1=S1[::-1] L2=S2[::-1] temp='' for ele in range(min(len(L1),len(L2))): if L1[ele]==L2[ele]: temp+=L1[ele] else: break flag=len(temp) var1=len(S1)-len(temp) var2=len(S2)-len(temp) if flag==0: print(-1) elif S1==S2: print(0) else: print(var1+var2)
true
aa6ea506e424f5b0a50f4537652395b31a901596
muhammad-masood-ur-rehman/Skillrack
/Python Programs/rotate-matrix-pattern.py
1,377
4.46875
4
Rotate Matrix Pattern The program must accept an integer matrix of size N*N as the input. The program must rotate the matrix by 45 degrees in the clockwise direction. Then the program must print the rotated matrix and print asterisks instead of empty places as the output. Boundary Condition(s): 3 <= N <= 100 Input Format: The first line contains N. The next N lines, each contains N integers separated by a space. Output Format: The first (2*N)-1 lines containing the rotated matrix. Example Input/Output 1: Input: 3 1 2 3 4 5 6 7 8 9 Output: **1 *4 2 7 5 3 *8 6 **9  Explanation: After rotating the matrix by 45 degrees in the clockwise direction, the matrix becomes   1  4 2 7 5 3  8 6   9 So the rotated matrix is printed and the asterisks are printed instead of empty places. Example Input/Output 2: Input: 4 13 21 36 49 55 65 57 80 17 32 63 44 56 60 78 98 Output: ***13 **55 21 *17 65 36 56 32 57 49 *60 63 80 **78 44 ***98 n=int(input()) arr=[] for i in range(n): a=[] for j in range(n): a.append(int(input())) arr.append(a) s1,s2=0,0 stars=n-1 for i in range(1, (2*n)): i1=s1 i2=s2 for j in range(1,n+1): if(j<=stars): print("*",end=' ') else: print(arr[i1][i2],end=" ") i1-=1 i2+=1 if(i>n-1): s2+=1 stars+=1 else: stars-=1 s1+=1 print("")
true
8ec84a6f4492aa2fc49b4fee6a9e6a9ca41083f6
muhammad-masood-ur-rehman/Skillrack
/Python Programs/sum-of-digits-is-even-or-odd.py
690
4.125
4
Sum of Digits is Even or Odd Sum of Digits is Even or Odd: Given an integer N as input, the program must print Yes if the sum of digits in a given number is even. Else it must print No. Boundary Condition(s): 1 <= N <= 99999999 Input Format: The first line contains the value of N. Output Format: The first line contains Yes or No. Example Input/Output 1: Input: 123 Output: Yes Explanation: The sum of digits in a given number is 1+2+3 = 6. Hence the output is Yes. Example Input/Output 2: Input: 1233 Output: No Explanation: The sum of digits in  a given number is 1+2+3+3 = 9. Hence the output is No. n=input() s=0 for i in n: s+=int(i) print('Yes' if s%2==0 else print('No')
true
1321a5a0862b67f2f4568189562a86f3444a201e
muhammad-masood-ur-rehman/Skillrack
/Python Programs/batsman-score.py
844
4.125
4
Batsman Score Batsman Score: Given an integer R as input, the program must print Double Century if the given integer R is greater than or equal to 200. Else if the program must print Century if the given integer R is greater than or equal to 100. Else if the program must print Half Century if the given integer R is greater than or equal to 50. Else the program must print Normal Score. Boundary Condition(s): 1 <= R <= 999 Input Format: The first line contains the value of R. Output Format: The first line contains Double Century or Century or Half Century or Normal Score. Example Input/Output 1: Input: 65 Output: Half Century Example Input/Output 2: Input: 158 Output: Century r=int(input()) print('Double Century') if r>=200 else print('Century') if r>=100 else print('Half Century') if r>=50 else print('Normal Score')
true
dc3805fb23ea3f2f06c3263183c16edd3967deed
muhammad-masood-ur-rehman/Skillrack
/Python Programs/toggle-case.py
617
4.3125
4
Toggle Case Simon wishes to convert lower case alphabets to upper case and vice versa. Help Simon by writing a program which will accept a string value S as input and toggle the case of the alphabets. Numbers and special characters remain unchanged.  Input Format: First line will contain the string value S  Output Format: First line will contain the string value with the case of the alphabets toggled.  Constraints: Length of S is from 2 to 100  SampleInput/Output: Example 1: Input: GooD mORniNg12_3  Output: gOOd MorNInG12_3  Example 2: Input:R@1nBow  Output:r@1NbOW n=input() print(n.swapcase())
true
cd8de721b5a119f128606b24071ed7a2c4aafed0
muhammad-masood-ur-rehman/Skillrack
/Python Programs/top-left-to-bottom-right-diagonals-program-in-python.py
1,296
4.28125
4
Top-left to Bottom-Right Diagonals Program In Python The program must accept an integer matrix of size RxC as the input. The program must print the integers in the top-left to bottom-right diagonals from the top-right corner of the matrix. Boundary Condition(s): 2 <= R, C <= 50 1 <= Matrix element value <= 1000 Input Format: The first line contains R and C separated by a space. The next R lines, each contains C integers separated by a space. Output Format: The first (R+C)-1 lines, each contains the integer value(s) separated by a space. Example Input/Output 1: Input: 3 3 9 4 5 9 5 3 7 7 5 Output: 5 4 3 9 5 5 9 7 7 Explanation: In the given 3x3 matrix, the integers in the top-left to bottom-right diagonals from the top-right corner of the matrix are given below. 5 4 3 9 5 5 9 7 7 Example Input/Output 2: Input: 7 5 17 88 27 71 57 28 96 59 99 56 52 69 80 86 57 85 56 48 59 47 61 85 58 86 36 63 23 14 70 60 28 50 17 24 13 Output: 57 71 56 27 99 57 88 59 86 47 17 96 80 59 36 28 69 48 86 60 52 56 58 70 13 85 85 14 24 61 23 17 63 50 28 r,c=map(int,input().split()) m=[list(map(int,input().split())) for row in range(r)] for i in range(1-c,r): for row in range(r): for col in range(c): if row-col==i: print(m[row][col],end=" ") print()
true
6c7286a208f6e7c8152d488ceb97ebb1df8c7bbf
muhammad-masood-ur-rehman/Skillrack
/Python Programs/unique-alphabet-count.py
596
4.3125
4
Unique Alphabet Count A string S is passed as input to the program which has only alphabets (all alphabets in lower case). The program must print the unique count of alphabets in the string. Input Format: - The first line will contain value of string S+ Boundary Conditions: 1 <= Length of S <= 100 Output Format: The integer value representing the unique count of alphabets in the string S. Example Input/Output 1: Input: level Output: 3 Explanation: The unique alphabets are l,e,v. Hence 3 is the output. Example Input/Output 2: Input: manager Output: 6 print(len(set(input().strip())))
true
5ae44003eed074094a44f7b9f3edf268e48f022f
muhammad-masood-ur-rehman/Skillrack
/Python Programs/python-program-to-print-fibonacci-sequence.py
575
4.5625
5
Python Program To Print Fibonacci Sequence An integer value N is passed as the input. The program must print the first N terms in the Fibonacci sequence. Input Format: The first line denotes the value of N. Output Format: The first N terms in the Fibonacci sequence (with each term separated by a space) Boundary Conditions: 3 <= N <= 50 Example Input/Output 1: Input: 5 Output: 0 1 1 2 3 Example Input/Output 2: Input: 10 Output: 0 1 1 2 3 5 8 13 21 34 n=int(input()) n1,n2=0,1 count=0 while count<n: print(n1,end=" ") nth=n1+n2 n1=n2 n2=nth count+=1
true
10e61b1d76df5b45f241b64dc305f9420d297a2e
muhammad-masood-ur-rehman/Skillrack
/Python Programs/print-numbers-frequency-based.py
1,045
4.46875
4
Print Numbers - Frequency Based An array of N positive integers is passed as input. The program must print the numbers in the array based on the frequency of their occurrence. The highest frequency numbers appear first in the output. Note: If two numbers have the same frequency of occurrence (repetition) print the smaller number first. Input Format: The first line contains N The second line contains the N positive integers, each separated by a space. Output Format: The first line contains the numbers ordered by the frequency of their occurrence as described above. Boundary Conditions: 1 <= N <= 1000 Example Input/Output 1: Input: 10 1 3 4 4 5 5 1 1 2 1 Output: 1 4 5 2 3 Example Input/Output 2: Input: 12 7 1 9 12 13 9 7 22 21 13 22 100 Output: 7 9 13 22 1 12 21 100 Example Input/Output 3: Input: 5 11 11 11 11 11 Output: 11 Python: import operator n=int(input()) l=[int(i) for i in input().split()] s={} for i in l: s[i]=l.count(i) d=sorted(s.items(),key=operator.itemgetter(1),reverse=True) for i in d: print(i[0],end=' ')
true
1370e5de23f56dad4a80ed2d09096913b7899778
muhammad-masood-ur-rehman/Skillrack
/Python Programs/sparse-matrix.py
706
4.34375
4
Sparse Matrix Write an algorithm and the subsequent Python program to check whether the given matrix is sparse or not. A matrix is said to be a “Sparse” if the number  of zero entries  in the matrix,  is greater than or equal to the number  of non-zero entries. Otherwise it is  “Not sparse”. Check for boundary conditions and print 'Invalid input' when not satisfied. r=int(input()) #number of rows in matrix c=int(input()) #number of columns in matrix if(r<=0 or c<=0): print('Invalid input') exit else: vals=[] flag=0 for i in range(r*c): vals.append(int(input())) zero_entries=vals.count(0) if(zero_entries>=r*c-zero_entries): print('Sparse') else: print('Not sparse')
true
82212ae4feda9fea0df5846fdc235aee5d457ddf
muhammad-masood-ur-rehman/Skillrack
/Python Programs/all-digits-pairs-count.py
1,119
4.21875
4
All Digits - Pairs Count The program must accept N integers as the input. The program must print the number of pairs X where the concatenation of the two integers in the pair consists of all the digits from 0 to 9 in any order at least once. Boundary Condition(s): 2 <= N <= 100 1 <= Each integer value <= 10^8 Input Format: The first line contains N. The second line contains N integers separated by a space. Output Format: The first line contains X. Example Input/Output 1: Input: 6 38479 74180 967132 1584604 726510 6512160 Output: 3 Explanation: The 3 possible pairs are given below. (38479, 726510) -> 38479726510 (38479, 6512160) -> 384796512160 (967132, 1584604) -> 9671321584604 The concatenation of the two integers in each pair contains all the digits from 0 to 9 at least once. Example Input/Output 2: Input: 4 2670589 243106 3145987 5789 Output: 4 Python: num=int(input()) list_arr=list(map(str,input().split())) count=0 for i in range(len(list_arr)): for j in range(i+1,len(list_arr)): temp=list_arr[i]+list_arr[j] if len(set(temp))==10: count+=1 print(count)
true
27381d83b8d936ffeff2ef2e10665d913a7a166b
alexandroid1/PytonStarter_Lesson1_PC
/calculator.py
370
4.1875
4
x = float(input("First number: ")) y = float(input("Second number: ")) operation = input("Operation") result = None if operation == '+': result = x + y elif operation == '-': result = x-y elif operation == '*': result = x*y elif operation == '/': result = x/y else: print('Unsupported operation') if result is not None: print('Result:', result)
true
fc8f710a881f74f7bf2cfc65a6c00ecccd939dfe
urstkj/Python
/thread/thread.py
1,484
4.125
4
#!/usr/local/bin/python #-*- coding: utf-8 -*- import _thread import threading import time # Define a function for the thread def print_time(threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print("%s: %s" % (threadName, time.ctime(time.time()))) # Create two threads as follows try: _thread.start_new_thread(print_time, ( "Thread-1", 2, )) _thread.start_new_thread(print_time, ( "Thread-2", 4, )) except: print("Error: unable to start thread") exitFlag = 0 class myThread(threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print("Starting " + self.name) print_time(self.name, 5, self.counter) print("Exiting " + self.name) def print_time(threadName, counter, delay): while counter: if exitFlag: threadName.exit() time.sleep(delay) print("%s: %s" % (threadName, time.ctime(time.time()))) counter -= 1 # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() print("Exiting Main Thread") print("done.")
true
38aa843a83904894f86e1c447fcdb138b281a370
luckeyme74/tuples
/tuples_practice.py
2,274
4.40625
4
# 12.1 # Create a tuple filled with 5 numbers assign it to the variable n n = ('2', '4', '6', '8', '10') # the ( ) are optional # Create a tuple named tup using the tuple function tup = tuple() # Create a tuple named first and pass it your first name first = tuple('Jenny',) # print the first letter of the first tuple by using an index print first[0] # print the last two letters of the first tuple by using the slice operator (remember last letters means use # a negative number) print first[3:] # 12.2 # Given the following code, swap the variables then print the variables var1 = tuple("hey") var2 = tuple("you") var1, var2 = var2, var1 print var1 print var2 # Split the following into month, day, year, then print the month, day and year date = 'Jan 15 2016' month, day, year = date.split(' ') print month print day print year # 12.3 # pass the function divmod two values and store the result in the var answer, print answer answer = divmod(9, 2) print answer # 12.4 # create a tuple t4 that has the values 7 and 5 in it, then use the scatter parameter to pass # t4 into divmod and print the results t4 = (7, 5) result = divmod(*t4) print result # 12.5 # zip together your first and last names and store in the variable zipped # print the result first = "Jenny" last = "Murphy" zipped = zip(first, last) print zipped # 12.6 # Store a list of tuples in pairs for six months and their order (name the var months): [('Jan', 1), ('Feb', 2), etc months = [('October', 10), ('January', 1), ('March', 3), ('May', 5), ('July', 7), ('December', 12)] # create a dictionary from months, name the dictionary month_dict then print it month_dict = dict(months) print month_dict # 12.7 # From your book: def sort_by_length(words): t = [] for word in words: t.append((len(word), word)) t.sort(reverse=True) res = [] for length, word in t: res.append(word) return res # Create a list of words named my_words that includes at least 5 words and test the code above # Print your result my_words = ('hacienda', 'empathetic', 'harmonious', 'allegorical', 'totalitarianism', 'harpsichord', 'embellishment', 'lassitude', 'mysticism') print sort_by_length(my_words)
true
abe6186dcccda09293dd055eb09cbb0c24de9a93
saidaHF/InitiationToPython
/exercises/converter2.py
1,031
4.15625
4
#!/usr/bin/env python # solution by cpascual@cells.es """ Exercise: converter2 --------------------- Same as exercise converter1 but this time you need to parse the header to obtain the values for the gain and the offset from there. Also, you cannot assume that the header has just 3 lines or that the order of the items in the header is always the same. In summary: you know that the "gain" is the number just after the word "GAIN" and the offset is the number after word "OFFSET". You also know that the word "DATA" marks the end of the header and that after it it comes the channels data. If possible, try not to use `for i in len(range(...))`. Use "enumerate" and "zip" instead. Note: call the output of this program "converter2.dat", and compare it (visually) with "converted1.dat" Important: do not import modules. Do it with the basic python built-in functions. Tips: - see tips of exercise converter1 and also - note that you can find elements in a list using the .index() method of a list """ # Write your solution here
true
e1be8a6391e8d69d9906b8712357a171952493c4
mauricejenkins-00/Python-Challenge
/pypoll/main2.py
2,486
4.34375
4
#Import libraries os, and Csv import os import csv #Give canidates a variable to add the canidates and vote count to candidates = {} #election_csv is a variable that calls for the election data file in the resources folder election_csv = os.path.join('.','Resources','election_data.csv') #With statement opens the election_csv variable as csvfile and is set to read mode with open(election_csv, 'r') as csvfile: #csvreader is a variable set to opening the csv file and reading each row of data csvreader = csv.reader(csvfile, delimiter=',') header = next(csvreader) #The header variable is set to equal the next object in each column #For loop is used to input data into spots in the dictionary we started earlier in the program called candidates for row in csvreader: if row[2] in candidates.keys(): candidates[row[2]]+=1 else: #If no value is returned then it sets the value to default candidates[row[2]] = 1 #Sets the total candidates value equal to total so we can call for it later total = candidates.values() #Sets the variable total_votes equal to the sum of candidates value total_votes = sum(total) #List_candidates is just the dictionary keywords list_candidates = candidates.keys() #Here a variable is set equal to the equation used to calculate the votes per candidate votes_per = [f'{(x/total_votes)*100:.3f}%' for x in candidates.values()] #Winner is a variable set equal to whoever has the highest amount of votes saved to the dictionary and prints it winner = list(candidates.keys())[list(candidates.values()).index(max(candidates.values()))] winner #Prints the final results to the terminal #Extra print statements are used to space out the output in the terminal print("Election results") print("--------------------------------") print(f" Total votes: {int(total_votes)}") print("---------------------------------") i = 0 #For loop runs for candidate votes and goes for the length of all the candidate items #Prints the candidate name, the vote count, and the vote percentage they received for candidate, vote in candidates.items(): print(f'{candidate}, {vote} , {votes_per[i]}') i+=1 #Prints the final result of who won the election print("------------------------------") print(f" Winner: {winner}") print("------------------------------")
true
1c4c1304afa4fb8619848032eafba93110c4eb19
jackmar31/week_2
/parkingGarage/# Best Case: O(n) - Linear.py
901
4.28125
4
# Best Case: O(n) - Linear def swap(i,j, array): array[i],array[j] = array[j],array[i] def bubbleSort(array): # initially define isSorted as False so we can # execute the while loop isSorted = False # while the list is not sorted, repeat the following: while not isSorted: # assume the list is sorted isSorted = True # crawl along the list from the beginning to the end for num in range(len(array) - 1): # if the item on the left is greater # than the item on the right if array[num] > array[num + 1]: # swap them so the greater item goes on the right swap(num, num + 1, array) # because we had to make the swap, # the list must not have been sorted isSorted = False return array bubbleSort([22,55,88,44,1,100,34,66])
true
06ea29eec33fe7ef9b2254a7b3fcd28b33bd6a60
simgroenewald/StringDataType
/Manipulation.py
869
4.34375
4
# Compulsory Task 3 strManip = input("Please enter a sentence:")#Declaring the variable StrLength = len(strManip)#Storing the length of the sentence as a variable print(StrLength)# Printing the length of the sentence LastLetter = strManip[StrLength-1:StrLength] #Storing the last letter of the lentence as a variable print(strManip.replace(LastLetter,"@"))#Replacing all of the letters that are the same as last letter with the @ symbol print(strManip[StrLength:StrLength-4:-1])#Printing the last 3 letter using the length of the string as the letters positions print(strManip[0:3]+ strManip[StrLength-2:StrLength]) #Slicing the string and concatenating the sliced pieces together print(strManip.replace(" ","\n"))#Replacing all of the spaces with the backslash (there is no backslash on my keyboard so I had to copy it - please help)n to put in new lines
true
3695661c954293f8c27fd7f1ea75e22e4003c377
ulicqeldroma/MLPython
/basic_slicing.py
696
4.15625
4
import numpy as np x = np.array([5, 6, 7, 8, 9]) print x[1:7:2] """Negative k makes stepping go toward smaller indices. Negative i and j are interpreted as n + i and n + j where n is the number of elements in the corresponding dimension.""" print x[-2:5] print x[-1:1:-1] """If n is the number of items in the dimension being sliced. Then if i is not given then it defaults to 0 for k > 0 and n - 1 for k < 0. If j is not given it defaults to n for k > 0 and -1 for k < 0. If k is not given it defaults to 1. Note that :: is the same as : and means select all indices along this axis.""" print x[4:] """(root) G:\MachineLearning\Python\book>python basic_slicing.py [6 8] [8 9] [9 8 7] [9]"""
true
da2a27e14b2e98b13c25310fea2ea62af5f9e07c
JIANG09/LearnPythonTheHardWay
/ex33practice.py
354
4.125
4
def while_function(x, j): i = 0 numbers = [] while i < j: print(f"At the top i is {i}") numbers.append(i) i = i + x print("Numbers now: ", numbers) print(f"At the bottom i is {i}") return numbers numbers_1 = while_function(7, 10) print("The numbers: ") for num in numbers_1: print(num)
true
620a67cbe340ace45f2db953d28b110f9fb0ac3d
timwilson/base30
/base30/base30.py
2,528
4.4375
4
#!/usr/bin/env python3 """ This module provides two functions: dec_to_b30 and b30_to_dec The purpose of those functions is to convert between regular decimal numbers and a version of a base30 system that excludes vowels and other letters than may be mistaken for numerals. This is useful for encoding large numbers in a more compact format while reducing the likelihood of errors while typing the base30-encoded version. The base30 digits include 0-9 and the letters BCDFGHJKLMNPQRSTVWXZ """ class Error(Exception): """Base class for other exceptions""" pass class NumberInputError(Error): """Raised when the input value is a float""" pass class ImproperBase30FormatError(Error): """Raised when the input value contains letters that aren't allowed in the base30 specification""" pass values = "0123456789BCDFGHJKLMNPQRSTVWXZ" digit_value_dict = { "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "B": 10, "C": 11, "D": 12, "F": 13, "G": 14, "H": 15, "J": 16, "K": 17, "L": 18, "M": 19, "N": 20, "P": 21, "Q": 22, "R": 23, "S": 24, "T": 25, "V": 26, "W": 27, "X": 28, "Z": 29, } def dec_to_b30(num): """Given a decimal number, return the base30-encoded equivalent.""" base_num = "" # Make sure the function received an integer as input try: if isinstance(num, float): raise NumberInputError num = int(num) except (ValueError, NumberInputError): print("Must provide an integer to convert.") else: while num > 0: digit = int(num % 30) if digit < 10: base_num += str(digit) else: base_num += values[digit] num //= 30 base_num = base_num[::-1] return base_num def b30_to_dec(num): """Given a base30-encoded number, return the decimal equivalent.""" # Make sure the function received a base30 number that doesn't include any illegal characters try: num = str(num) for c in num: if c not in values: raise ImproperBase30FormatError except ImproperBase30FormatError: print(f"Invalid base30 format. My only contain {values}.") else: dec_num = 0 rev_num = num[::-1] for i in range(len(rev_num)): dec_num += digit_value_dict[rev_num[i]] * (30 ** i) return dec_num
true
400b14f32ee96af63ee8fbf4c750443ec51c1532
hamk-webdev-intip19x6/petrikuittinen_assignments
/lesson_python_basics/side_effect.py
629
4.375
4
# WARNING! DO NOT PROGRAM LIKE THIS # THE FOLLOWING FUNCTION HAS AN UNDOCUMENTED SIDE EFFECT def mymax(a): """Return the item of list a, which has the highest value""" a.sort() # sort in ascending order return a[-1] # return the last item a = [1, 10, 5, -3, 7] print(mymax(a)) print(a) # a is sorted as well! # This version does NOT have a side effect def mymax2(a): """Return the item of list a, which has the highest value""" b = a.copy() b.sort() # sort in ascending order return b[-1] # return the last item a = [1, 10, 5, -3, 7] print(mymax2(a)) print(a) # a is still in original order
true
047fe4c0903be5318f414cff2ce4fbb295768f58
hamk-webdev-intip19x6/petrikuittinen_assignments
/lesson_python_file_and_web/ask_float_safely.py
533
4.15625
4
def ask_float(question): """display the question string and wait for standard input keep asking the question until user provides a valid floating point number. Return the number""" while True: try: return float(input(question)) except ValueError: print("Please give a valid floating point number") def lbs_to_kg(lbs): """Convert pounds (lbs) to kilograms (kg)""" return lbs * 0.45359237 lbs = ask_float("How many pounds (lbs) ?") print(f"{lbs_to_kg(lbs):.2f} kg")
true
8b3498cef391bc920ca5d9db2966bd3cbe71bcfd
hamk-webdev-intip19x6/petrikuittinen_assignments
/lesson_python_basics/closure.py
322
4.21875
4
# Example of a closure def make_multiplier(x): # outer / enclosing function def multiplier(y): # inner / nested function return x*y return multiplier mul10 = make_multiplier(10) # mul is the closure function print(mul10(5)) # 50 print(mul10(10)) #100 mul2 = make_multiplier(2) print(mul2(10)) # 20
true
f162f9720be4566474fcd6e09731c5f43a727059
sterlingb1204/EOC2
/HW4.py
998
4.5
4
#-- Part 2: Python and SQLite (25 Points) #-- #-- Take your Homework 1, Part 1 module and re-write #-- it to so that it queries against the sqlite3 #-- babynames database instead. #-- #-- The beauty of this approach is that, because #-- your original code was in a module, you can #-- change how the module fulfills the `get_frequency()` #-- function request, and all of the scripts that you #-- wrote that use your module will benefit from #-- the improvements! #-- #-- You can test your module by running your Homework #-- 1, parts 2 and 3 scripts, and see if you observe #-- an improvement in the speed of the scripts! #------------------------------------------------ import babynames1 print("The Fantastic Four!") print("-" * 19) names = {name: sum(babynames1.get_frequency(name).values()) for name in ["Reed", "Susan", "Ben", "Johnny"]} for name, count in names.items(): print(f"{name:>7}: {count:>9,}") print("pynames") print(f"\n{max(names, key=names.get)} is the most popular!")
true
e37de75b4b15d71da1d709b52889d49cbef78bd8
volodiny71299/Right-Angled-Triangle
/02_number_checker.py
1,010
4.3125
4
# number checker # check for valid numbers in a certain range of values # allow float def num_check(question, error, low, high, num_type): valid = False while not valid: try: response = num_type(input(question)) if low < response < high: return response else: print(error) except ValueError: print(error) # main routine goes here get_angle = num_check("What is the value of the angle ", "Enter a value between 0 and 90\n", 0, 90, float) # get the length of a side (used the float('inf') to represent an infinite integer, doesn't have a max restriction) get_length = num_check("What is the length of one side ", "Enter a value greater than 0\n", 0, float('inf'), float) # calculate the second angle (can be used for overall data for end results) angle_two = 90 - get_angle print() # prints results of input print("Angle one: {:.3f}".format(get_angle)) print("Angle two: {:.3f}".format(angle_two))
true
2571fb011cab5aed53fa2d7a10bb66470982bbf9
volodiny71299/Right-Angled-Triangle
/01_ask_what_calculate.py
962
4.40625
4
# ask user what they are trying to calculate (right angled triangle) valid_calculations = [ ["angle", "an"], ["short side", "ss"], ["hypotenuse", "h"], ["area", "ar"], ["perimeter", "p"] ] calculation_ok = "" calculation = "" for item in range(0,3): # ask user for what they are trying to calculate what_to_calculate = input("What do you want to calculate? ".lower()) for var_list in valid_calculations: # if the calculation is in list if what_to_calculate in var_list: # get full name of what is needed to be calculated calculation = var_list[0].title() calculation_ok = "yes" break # # if the chosen calculation is not valid ask again else: calculation_ok = "no" # print option again if calculation_ok == "yes": print("You want to calculate '{}'".format(calculation)) else: print("Invalid choice")
true
8f24a35c4ff8b1ebbb4e476e7ac6dd74d4a652dc
pjarcher913/python-challenges
/src/fibonacci/module.py
1,020
4.15625
4
# Created by Patrick Archer on 29 July 2019 at 9:00 AM. # Copyright to the above author. All rights reserved. """ @file asks the user how many Fibonacci numbers to generate and then generates them """ """========== IMPORTS ==========""" """========== GLOBAL VARS ==========""" """========== MAIN() ==========""" def fib(): print("\nThis app generates a sequence of Fibonacci numbers for a specified range.\n") seqLength = input("How many numbers would you like to generate?\n") print("\nResulting sequence:") print(str(fibGen(int(seqLength)))) """========== ADDITIONAL FUNCTIONS ==========""" def fibGen(seqLength): fibSeq = [] for index in range(0, seqLength): if index == 0: fibSeq.append(0) elif index == 1: fibSeq.append(1) else: fibSeq.append(fibSeq[index - 2] + fibSeq[index - 1]) return fibSeq """========== \/ SCOPE \/ ==========""" if __name__ == '__fib__': fib() """========== \/ @file END \/ =========="""
true
c4cccf258eab393d27882e0e80b006df10784546
phu-n-tran/LeetCode
/monthlyChallenge/2020-05(mayChallenge)/5_02_jewelsAndStones.py
1,349
4.15625
4
# -------------------------------------------------------------------------- # Name: Jewels and Stones # Author(s): Phu Tran # -------------------------------------------------------------------------- """ You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A". Example 1: Input: J = "aA", S = "aAAbbbb" Output: 3 Example 2: Input: J = "z", S = "ZZ" Output: 0 Note: S and J will consist of letters and have length at most 50. The characters in J are distinct. Hint: For each stone, check if it is a jewel. """ class Solution(object): def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ sum_jewel = 0 for each_jewel in J: sum_jewel += S.count(each_jewel) return sum_jewel '''###alternate solution### setJ = set(J) return sum(s in setJ for s in S) '''
true
0482288b53ef2ee63980d4d388ae8dc7d9b6ae7f
phu-n-tran/LeetCode
/monthlyChallenge/2020-06(juneChallenge)/6_29_UniquePaths.py
2,214
4.5
4
# -------------------------------------------------------------------------- # Name: Unique Paths # Author(s): Phu Tran # -------------------------------------------------------------------------- """ A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? (see 6_29_illustration.png) Above is a 7 x 3 grid. How many possible unique paths are there? Example 1: Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right Example 2: Input: m = 7, n = 3 Output: 28 Constraints: 1. 1 <= m, n <= 100 2. It's guaranteed that the answer will be less than or equal to 2 * 10 ^ 9. """ class Solution(object): def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ # each block represent the current coordinate and its value represent the number of ways to move from origin to the current coordinate dp = [[1] * n for _ in range(m)] for i in range(1, m): for j in range(1, n): dp[i][j] = dp[i-1][j] + dp[i][j-1] return dp[-1][-1] '''other faster methods (from other submissions) ################################################## def binom(n, k): """n choose k, i.e. n! / (k! (n-k)!)""" result = 1 for i in range(k+1, n+1): result *= i for i in range(1, n-k+1): result /= i return result class Solution(object): def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ return binom((m-1)+(n-1), n-1) ################################################## '''
true
68cb6a414b42c04874e1a204a7bd2ffd16f3dba9
phu-n-tran/LeetCode
/monthlyChallenge/2020-07(julychallenge)/7_02_BTLevelOrderTraversal2.py
2,801
4.21875
4
# -------------------------------------------------------------------------- # Name: Binary Tree Level Order Traversal II # Author(s): Phu Tran # -------------------------------------------------------------------------- """ Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its bottom-up level order traversal as: [ [15,7], [9,20], [3] ] """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ def bottomUp(root, result, level): if root: if len(result) <= level: result.append([]) result[level] += [root.val] bottomUp(root.left, result, level+1) bottomUp(root.right, result, level+1) result = [] bottomUp(root, result, 0) return result[::-1] '''other faster methods (from other submissions) ################################################## def levelOrderBottom(self, root): if not root: return [] prev = [root] ret = [] while prev: ret.append([n.val for n in prev]) curr = [] for node in prev: if node.left: curr.append(node.left) if node.right: curr.append(node.right) prev = curr return list(reversed(ret)) ################################################## def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ res = [] if not root: return res queue = [root] level=0 while queue: node = [nod for nod in queue] temp =[] res.append([nod.val for nod in node]) for nod in node: if nod.left: temp.append(nod.left) if nod.right: temp.append(nod.right) queue = temp level+=1 return res[::-1] ################################################## '''
true
5b5cda38002926df07c4809361992ba67ed62c2a
phu-n-tran/LeetCode
/monthlyChallenge/2020-06(juneChallenge)/6_18_HIndex_V2.py
2,119
4.25
4
# -------------------------------------------------------------------------- # Name: H-Index II # Author(s): Phu Tran # -------------------------------------------------------------------------- """ Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each." Example: Input: citations = [0,1,3,5,6] Output: 3 Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, her h-index is 3. Note: If there are several possible values for h, the maximum one is taken as the h-index. Follow up: 1. This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order. 2. Could you solve it in logarithmic time complexity? """ class Solution(object): def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ l=len(citations) res=0 for i in range(l): if citations[l-i-1]>=(res+1):res+=1 else:return res return res '''other methods (from other submissions) ################################################## def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ n = len(citations) if n == 0: return 0 #citations.sort(reverse = True) for i in range(n): if citations[n - 1 - i] <= i: return i return n '''
true
862417cfb9e359619f04610c0a1ee27492e43ddc
phu-n-tran/LeetCode
/monthlyChallenge/2020-06(juneChallenge)/6_13_LargestDivisibleSubset.py
2,169
4.15625
4
# -------------------------------------------------------------------------- # Name: Largest Divisible Subset # Author(s): Phu Tran # -------------------------------------------------------------------------- """ Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0. If there are multiple solutions, return any subset is fine. Example 1: Input: [1,2,3] Output: [1,2] (of course, [1,3] will also be ok) Example 2: Input: [1,2,4,8] Output: [1,2,4,8] """ class Solution(object): def largestDivisibleSubset(self, nums): """ :type nums: List[int] :rtype: List[int] """ if nums: nums.sort() results = [[each_ele] for each_ele in nums] for i in range(len(nums)): for k in range(i): # 1st cond is to check if the current number divisible by all the small number # 2nd cond is to make sure the iterate number is also divisible by other numbers in the list if nums[i] % nums[k] == 0 and len(results[i]) <= len(results[k]): results[i] += [nums[k]] print(results) # return max(results, key=len) return max(results, key=lambda each_list: len(each_list)) '''other methods (from other submissions) ################################################## def largestDivisibleSubset(self, nums): """ :type nums: List[int] :rtype: List[int] """ if not nums: return [] dic = {} for i in sorted(nums): a = [(k,len(dic[k])) for k in dic if i%k==0] #print(dic) if a: dic[i]=dic[max(a,key=lambda x:x[1])[0]]+[i] else: dic[i]=[i] #print(dic) return max(dic.items(), key=lambda x:len(x[1]))[1] '''
true
890540caa1d454ce7c0d7dd0944d8fde13ed3193
aernesto24/Python-el-practices
/Basic/Python-university/Functions/ArithmeticTables/arithmeticTables.py
2,650
4.46875
4
"""This software shows the arithmetic tables based on the input the user provides, it can show: multiplication table, sum tablet, etc. """ #Function to provide the multiplication table from 0 to 10 def multiplicationTables(LIMIT, number): counter = 0 print("Tabla de multiplicar de " + str(number)) for i in range(LIMIT+1): result = number * counter print(str(number) + " * " + str(counter)+ " = " + str(result)) counter +=1 #Function to provide the division table from 1 to 10 def divisionTables(LIMIT, number): counter = 1 print("Tabla de dividir de " + str(number)) for i in range(LIMIT+1): result = round(number / counter, 2) print(str(number) + " / " + str(counter)+ " = " + str(result)) counter +=1 #Function to provide the sum table from 0 to 10 def sumTables(LIMIT, number): counter = 0 print("Tabla de sumar de " + str(number)) for i in range(LIMIT+1): result = number + counter print(str(number) + " + " + str(counter)+ " = " + str(result)) counter +=1 #Function to provide the substraction table from 0 to 10 def substrationTables(LIMIT, number): counter = 0 print("Tabla de restar de " + str(number)) for i in range(LIMIT+1): result = number - counter print(str(number) + " - " + str(counter)+ " = " + str(result)) counter +=1 #Run function, here are declared the LIMIT constant and request user input for the number and option def run(): print("***TABLAS DE SUMA | RESTA | MULTIPLICACION | DIVISION***") LIMIT = 10 number = int(input("Ingresa el numero para conocer su tabla: ")) option = input("""Selecciona la opcion que quieres: 1. Tabla de multiplicacion 2. Tabla de division 3. Tabla de suma 4. Tabla de resta 5. Mostrar todas las tablas : """) if option == '1': multiplicationTables(LIMIT, number) elif option == '2': divisionTables(LIMIT, number) elif option == '3': sumTables(LIMIT, number) elif option == '4': substrationTables(LIMIT, number) elif option == '5': multiplicationTables(LIMIT, number) print("") divisionTables(LIMIT, number) print("") multiplicationTables(LIMIT, number) print("") sumTables(LIMIT, number) print("") substrationTables(LIMIT, number) else: print("Opción invalida!!") if __name__ == '__main__': run()
true
15a69ecb35cec652121faaf582966f25ea7dad8b
gaoyangthu/leetcode-solutions
/004-median-of-two-sorted-arrays/median_of_two_sorted_arrays.py
1,815
4.28125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- """ There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5 """ class Solution(object): def find_kth(self, nums1, nums2, k): if not nums1: return nums2[k - 1] if not nums2: return nums1[k - 1] if k == 1: return min(nums1[0], nums2[0]) m = nums1[k / 2 - 1] if len(nums1) >= k / 2 else None n = nums2[k / 2 - 1] if len(nums2) >= k / 2 else None if n is None or (m is not None and m < n): return self.find_kth(nums1[k / 2:], nums2, k - k / 2) else: return self.find_kth(nums1, nums2[k / 2:], k - k / 2) def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ l = len(nums1) + len(nums2) if l % 2 == 1: return self.find_kth(nums1, nums2, l / 2 + 1) else: return (self.find_kth(nums1, nums2, l / 2) + self.find_kth(nums1, nums2, l / 2 + 1)) / 2.0 def test(): solution = Solution() print solution.findMedianSortedArrays([1, 2], [1, 2, 3]) print solution.findMedianSortedArrays([1, 2], [1, 2]) print solution.findMedianSortedArrays([1, 2], [3]) print solution.findMedianSortedArrays([1], [2, 3]) print solution.findMedianSortedArrays([4], [1, 2, 3, 5, 6]) print solution.findMedianSortedArrays([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22], [0, 6]) if __name__ == '__main__': test()
true
3153c6df49836cc64a8b4cf94a57c9bcf1b30927
dgibbs11a2b/Module-9-Lab-Assignment
/Problem2NumList10.py
711
4.1875
4
#---------------------------------------- #David Gibbs #March 10, 2020 # #This program will use a while loop to append the current #value of the current counter variable to the list and #then increase the counter by 1. The while loop then stops #once the counter value is greater than 10. #---------------------------------------- l = [0,1,2,3,4,5,6,7,8,9,10] counter_value = 0 #sets counter value counter_max = 10 #sets counter maximum while counter_value <= counter_max: l.append(counter_value) counter_value += 1 #while statement which appens incremented counter values to list "l" print('The updated list is: ', l) #Updated List #x = 0 #L = [] #while x < 11: # L.append(x) # x += 1 #print(L)
true
84cce619cee66ec68eb13425e3d6c11ef2cb6ec1
JonasKanuhsa/Python
/Survey/Survey.py
573
4.1875
4
''' Make a program that can take survey information. @author: Jonas Kanuhsa ''' question = "What is your name?" name = input("What is your name") print(name) response = "What is your favorite color?" color = input("What is your favorite color?") print(color) var = = "What city did you grow up in?" city = input("What city did you grow up in?") print(city) var1 = "What is your best friends name?" variable = input("What is your best friends name?") print(variable) var2 = "What color hair do you have?" hair = input("What color hair do you have?") print(hair)
true
f0345277450b059093e85d4a310eddb279d501ea
MistyLeo12/Learning
/Python/double_linked.py
1,967
4.21875
4
class Node(object): def __init__(self, data = None): self.data = data self.next = None self.prev = None class doublyLinkedList(object): def __init__(self): self.root = Node() self.size = 0 def get_size(self): current = self.root counter = 0 while current.next is not None: counter += 1 current = current.next return counter def push(self, data): #Inserts at head of the list new_node = Node(data) new_node.next = self.root new_node.prev = None if self.root is not None: self.root.prev = new_node self.root = new_node def insert(self, prev, data): if prev is None: #Checks if prev is NULL print("Node doesn't exist in the List") return new_node = Node(data) new_node.next = prev.next #point next of new node as next of previous node prev.next = new_node #next of previous as new node new_node.prev = prev #make previous as previous of new node if new_node.next is not Node: new_node.next.prev = new_node def append(self, data): new_node = Node(data) #traverses list until it reaches the last node current = self.root while current.next is not None: current = current.next current.next = new_node #changes the next of last new_node.prev = current #makes the last node the previous node def returnList(self, node): elements = [] while node is not None: elements.append(node.data) node = node.next return elements newList = doublyLinkedList() newList.append(8) newList.append(66) newList.append(77) print(newList.returnList(newList.root)) newList.push(133) print(newList.returnList(newList.root)) newList.insert(newList.root.next, 9) print(newList.returnList(newList.root))
true
da11b4c7fdf486d72914db90af4b471bb91709bf
ErickMwazonga/learn_python
/others/mothly_rate.py
1,097
4.1875
4
import locale # set the locale for use in currency formatting result = locale.setlocale(locale.LC_ALL, '') if result == 'C': locale.setlocale(locale.LC_ALL, 'en_US') # display a welcome message print("Welcome to the Future Value Calculator") # print() choice = 'Y' while choice.lower() == 'y': # get input from the user monthly_investment = float(input('Enter monthly investment:\t')) yearly_interest_rate = float(input('Enter yearly interest rate:\t')) years = int(input('Enter number of years"\t\t')) # convert yearly values to monthly values monthly_interest_rate = yearly_interest_rate/12/100 months = years * 12 # calculate the future value future_value = 0 for i in range(months): future_value = future_value + monthly_investment monthly_interest_amount = future_value * monthly_interest_rate future_value = future_value + monthly_interest_amount # format and display the result print('Future value:\t\t\t' + locale.currency( future_value, grouping=True)) print() # see if the user wants to continue choice = input('Continue? (y/n): ') print() print('Bye!')
true
85c7222686015f91f512afc68fa49a2d3689f67a
edithclaryn/march
/hobbies.py
251
4.28125
4
"""Create a for loop that prompts the user for a hobby 3 times, then appends each one to hobbies.""" hobbies = [] # Add your code below! for i in range(3): hobby = input("Enter your hobby: ") print (hobby) hobbies.append(hobby) i += 1
true
0a2280f39b0f3bcc6ed11af2df1001813cc342b9
edithclaryn/march
/battleship.py
945
4.21875
4
"""Create a 5 x 5 grid initialized to all 'O's and store it in board. Use range() to loop 5 times. Inside the loop, .append() a list containing 5 "O"s to board. Note that these are capital letter "O" and not zeros.""" board = [] for i in range(0,5): board.append(["O"]*5) print (board) #Use the print command to display the contents of the board list. """First, delete your existing print statement. Then, define a function named print_board with a single argument, board. Inside the function, write a for loop to iterates through each row in board and print it to the screen. Call your function with board to make sure it works.""" def print_board(board): for i in board: print (i) print_board(board) """to remove commas in the list: Inside your function, inside your for loop, use " " as the separator to .join the elements of each row.""" def print_board(board): for row in board: print (" ".join(row)) print_board(board)
true
291b9fcbb8a201634e37bc6ffded8ca809404b6e
nahymeee/comp110-21f-workspace
/exercises/ex05/utils.py
1,120
4.125
4
"""List utility functions part 2.""" __author__ = "730330561" def only_evens(first: list[int]) -> list[int]: """Gives back a list of only the even numbers.""" i: int = 0 evens: list[int] = [] while i < len(first): if first[i] % 2 == 0: evens.append(first[i]) i += 1 return evens def sub(lista: list[int], first: int, last: int) -> list[int]: """Makes a sub list from the original list provided.""" i: int = 0 new: list[int] = [] if len(lista) == 0 or first >= len(lista) or last <= 0: return new if last > len(lista): last = len(lista) if first <= 0: first = 0 while i < len(lista): while first != last: new.append(lista[first]) first += 1 i += 1 return new def concat(first: list[int], second: list[int]) -> list[int]: """Combines two lists together.""" i: int = 0 both: list[int] = [] while i < len(first): both.append(first[i]) i += 1 i = 0 while i < len(second): both.append(second[i]) i += 1 return both
true
1f23bfe9500c5f4405f3f1ad69e472dd5a755a05
NickPerez06/Python-miniProjects
/rpsls.py
1,802
4.34375
4
''' This mini project will create the game rock, paper, scissors, lizard, spock for your enjoyment. Author: Nicholas Perez ''' import random def name_to_number(name): '''converts string name to number for rpsls''' number = 0 if( name == "rock" ): number = 0 return number elif ( name == "Spock" ): number = 1 return number elif ( name == "paper" ): number = 2 return number elif ( name == "lizard" ): number = 3 return number elif ( name == "scissors" ): number = 4 return number else: return "This is not one of the choices!" def number_to_name(number): '''Converts number to srting name for rpsls game''' if ( number == 0 ): return "rock" elif ( number == 1 ): return "Spock" elif ( number == 2 ): return "paper" elif ( number == 3 ): return "lizard" elif ( number == 4 ): return "scissors" else: return "Error: you must pick a number between 0-4" def rpsls(player_choice): '''Main Fucntion for rpsls. Will use helper fucntions listed above''' print "" print "Player chooses " + player_choice player_number = name_to_number(player_choice) #Below will be the computers choice form 0-4 comp_number = random.randrange(0, 5) comp_choice = number_to_name(comp_number) print "Computer chooses " + comp_choice #Below will determind who wins or if there is a tie result = (player_number - comp_number) % 5 if ( result == 1 or result == 2 ): print "Player wins!" elif ( result == 3 or result == 4 ): print "Computer wins!" else: print "Player and Computer tie!" # testing code rpsls("rock") rpsls("Spock") rpsls("paper") rpsls("lizard") rpsls("scissors")
true
29bcc76645fbf2a3133fe36f2799a53ac5de279b
MicahJank/Intro-Python-I
/src/16_stretch.py
1,893
4.3125
4
# 3. Write a program to determine if a number, given on the command line, is prime. # 1. How can you optimize this program? # 2. Implement [The Sieve of # Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes), one # of the oldest algorithms known (ca. 200 BC). import sys import math # in order to check if a number is prime i need to find if it has any factors besides 1 and itself - if it does it is not a prime number # i only need to check the numbers up to the square root of the number being inputted # i should start my loop at 2 since 1 is not relevant # First i will need to get the number that the user is inputting into the command line # sys.args will give me everything that has been inputted on the command line # I will then need to find the square root of that number - this number will be the last number i need to check in the loop # I will need to loop starting at 2 all the way until i get to the square root of the number the user inputted # inside the loop i need to check if the current index in the loop is divisible by the number the user inputted - if it is - then that means the number is not prime # if i get to the end of the loop and none of the index numbers have been divisible by the number then there is a good chance it is a prime inputs = sys.argv number = 0 isPrime = False def run_program(num): num = int(num) print("Running") sqrt = int(math.sqrt(num)) for factor in range(2, sqrt): if num % factor == 0: return False return True try: number = inputs[1] except: print("No number inputted - please make sure you are inputting a number into the command line") else: print(f"Number inputted: {number}") isPrime = run_program(number) print(f"{number} is a prime number" if isPrime == True else f"{number} is not a prime number")
true
99bfc65a4a0cffca30b37ff18a129edd81b8b359
kom50/PythonProject
/Simple Code/Factorial.py
369
4.21875
4
# find factorial using loop def fact(num): # 1st function f = 1 for i in range(1, num + 1): f *= i return f # find factorial using recursive function def fact1(num): # 2nd function if num == 1: return 1 return num * fact1(num - 1) # 1st function print('Factorial : ', fact(4)) # 2nd function print('Factorial : ', fact1(4))
true
6aa47cd97da9f307b127f9ba7df2b81325f5674b
tlkoo1/Lok.Koo-Chatbot
/ChatBotTemplate.py
569
4.25
4
#open text document stop-words.txt file = open("stop-words.txt") stopwords = file.readlines() #function going through all stopwords def removeStopwords(firstWord): for word in stopwords: next = word.strip() firstWord = firstWord.replace(" " + next + " ", " " ) return firstWord #while input matches stop words, no display while True: input = raw_input("What is your name ? ") input = " " + input + " " filtered = removeStopwords(input); filtered = filtered.replace(" name "," ") print("Answer: " + filtered.strip())
true
ef6c8b1057839016de9dd2b51ffd879435043270
martinaobrien/pands-problem-sets
/sumupto.py
1,128
4.28125
4
# Martina O'Brien: 24 - 02 - 2019 # Problem Set Programming and Scripting Code 1 #Calculate the sum of all factorials of positive integer # Input variable needed for calculation # Int method returns an integer as per python programming # input "Enter Number" will be visible on the user interface # setting up variables to be used later in while loop start = int (input ('Please enter a positive number: ')) ans = 0 # ans = 0 and 0 is the value that the loop begins calculating i = 1 if start > 0: # i = 1 as the starting point while i <= start: ans = ans + i i = i + 1 print(ans) # Print is the funtion used to display the sum of all factorials of positive integer inputted # As print is not contained through indentation in the previous statement, it displays one figure as ans else: print('This is not a positive number') # ans will continue to increase by the value of i as it progresses through the while loop # i will increase by 1 each time it goes through while loop. # This will continue while the argument is true i.e: Until the i reaches the start number.
true
0debb74096cb6fb8c78922e17677242b87b884d9
rmaur012/GraphicalSequenceAlgorithm
/GraphicalSequenceAlgorithm.py
2,392
4.3125
4
#Setting up the sequence list try: sizeOfSeq = raw_input("How many vetices are there? ") sizeOfSeq = int(sizeOfSeq) index = 0 sequence = [None]*sizeOfSeq except ValueError: print 'A Non-Numerical Value Was Entered. Please Try Again And Enter With A Numerical Value.' quit() #The user inputs the degrees of the vertices, then sorts it in reverse. #It will also calculate sum of the sequence of degrees to then be evaluated in the second if statement after the loop seqSum = 0 while sizeOfSeq>0: try: sequence[index]=int(raw_input("Enter The Degree For A Vertex: ")) seqSum = seqSum + sequence[index] sizeOfSeq=sizeOfSeq-1 index=index+1 except ValueError: print 'A Non-Numerical Value Was Entered. Please Enter A Numerical Value.' sequence.sort(reverse = True) #Checks if a degree is bigger or equal to number of vertices, #then will check if the sum of the sequence = 2*(number of edges), which would make it not graphical if it does not equal, #then it proceeds with algorithm if it's not determined to be either of the first two if sequence[0]>=len(sequence): print 'The Sequence Is Not Graphical: Degree Is Higher Than The Number Of Vertices' elif seqSum%2 !=0: print 'The Sequence Is Not Graphical: The Sum Of The Degrees In The Sequence Is Not Divisible By 2' else: #Algorithm starts here seqIndex = 1 iteration = 0 negFound = False while iteration<len(sequence): num = sequence[0] sequence[0] = 0 while num>0: sequence[seqIndex]= sequence[seqIndex]-1 num = num -1 seqIndex = seqIndex + 1 sequence.sort(reverse=True) if sequence[len(sequence)-1]<0: negFound = True break seqIndex = 1 iteration = iteration + 1 if negFound == True: print 'The Sequence Is Not Graphical: A Term Of The Sequence Was Negative' else: print 'The Sequence Is Graphical!' #Prints The State Of The Sequence At The End Of The Algorithm print 'Algorithm Ended With Sequence As: {0}'.format(sequence)
true
adab3d9ccab42569ced54c6fd3551335a7b34969
hsrwrobotics/Robotics_club_lectures
/Week 2/Functions/func_echo.py
1,497
4.375
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 21 16:15:36 2019 HSRW Robotics @author: mtc-20 """ # A function definition starts with the keyword def followed the function # name which can be anything starting with an alphabet, preferably in # lowercase followed by a colon {:}. The body(the block of code to be reused) # starts in the subsequent line and is closed by the return statement # Below is a simple function that takes 0 arguments and returns nothing def echo(): shoutout = input("Shout out something: ") print(shoutout.upper()) print(shoutout) print(shoutout.lower()) for i in range(len(shoutout)): print(shoutout[:-i].lower()) return # To use the function, it can be called in different ways: echo() test_echo = echo() print ("\n", test_echo) # Pay attention to the variable explorer, is there anything stored? # What about the print statements from the different call? # Below is another way of writing the same function. Functions can also have # arguments that are passed in brackets {()}. Arguments are variables and a # function can have any number of arguments. # The below function takes 1 argument and returns True value always def echo2(shoutout): print(shoutout.upper()) print(shoutout) print(shoutout.lower()) for i in range(len(shoutout)): print(shoutout[:-i].lower()) return True # There are atleast 3 different ways to call this function, that's your task
true
0161be485ecedd4e17fd86e5049d4ef2bea9191d
liyouzhang/Algos_Interviews
/sum_of_two_values.py
1,254
4.375
4
def find_sum_of_two_one(A, val): ''' input - array of numbers; val - a number output - bool 1. native: - try all combinations of two numbers in array: 2 for loops - for each, test if == target ''' #1. naive approach for a in A: for b in A: if b != a: if a + b == val: return True return False #space - O(1) #running time - O^2 def find_sum_of_two_two(A, val): ''' approach 2. find if val-current_num is in the list create a set of found_values loop through the array, check if val-value is in the found_values, if yes, return true else, add to the set ''' found_values = set() for i in A: if val-i in found_values: return True found_values.add(i) return False #space - O(n) set #run time - O(n) 1 for loop def find_sum_of_two_three(A, val): ''' approach 3. use two indexes to avoid for loop 1. sort array 2. use two idx 3. sum, if sum < target, then move left +1 ; if > target, then move right -1 ''' i = 0 j = len(A) - 1 A.sort() if A[i] + A[j] < val: i += 1 if A[i] + A[j] > val: j -= 1 if A[i] + A[j] == val: return True return False
true
50b40bb9f10c8abbe769296dea8d895e517ee13e
liyouzhang/Algos_Interviews
/819_most_common_word.py
2,900
4.34375
4
''' Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique. Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase. Example: Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." banned = ["hit"] Output: "ball" Explanation: "hit" occurs 3 times, but it is a banned word. "ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. Note that words in the paragraph are not case sensitive, that punctuation is ignored (even if adjacent to words, such as "ball,"), and that "hit" isn't the answer even though it occurs more because it is banned. Note: 1 <= paragraph.length <= 1000. 0 <= banned.length <= 100. 1 <= banned[i].length <= 10. The answer is unique, and written in lowercase (even if its occurrences in paragraph may have uppercase symbols, and even if it is a proper noun.) paragraph only consists of letters, spaces, or the punctuation symbols !?',;. There are no hyphens or hyphenated words. Words only consist of letters, never apostrophes or other punctuation symbols. ''' # my try 20200502 # failed because sometimes words are not split by ' ' but by punctuation, so in solution it used regex def most_common_word (paragraph, banned): # input: para = string, banned = a list of strings # output: a string (word), lower case # split the string to a list of words # process every word into lower case # iterate through the list, to add the not_banned words into a new list # iterate through the filtered list: # if the word is found more than once, then counter += 1 # the counter is a dictionary # find out the max of the value, and return the key import string l1 = paragraph.split(' ') filtered_list = [] for i in l1: i_transformed = ''.join(ch for ch in i if ch not in set(string.punctuation)).lower() if i_transformed not in banned: filtered_list.append(i_transformed) counter = {} for i in filtered_list: if i in counter.keys(): counter[i] += 1 else: counter[i] = 1 l3 = list(counter.values()) l4 = list(counter.keys()) return l4[l3.index(max(l3))] # solution def most_common_word (paragraph, banned): import re word_list = re.split('\W+', paragraph.lower()) max_freq,max_word, freq, banned_set = 0, None, {}, set(banned) for word in word_list: if word not in banned_set: freq[word] = freq.get(word, 0) + 1 if freq[word] > max_freq: max_freq, max_word = freq[word], word return max_word
true
87ae2f7ef55554516cf8cdce8e1a57837533b3e8
doraithodla/py101
/learnpy3/word_freq_2.py
783
4.15625
4
# wordfreq2 - rewrite the wordfreq program to take the text from a file and count the words def word_freq1(str): """ takes a string and calculates the word frequency table :param str: string input :return: frequency dictionary """ frequency = {} for word in str.split(): if word in frequency: frequency[word] = frequency[word] + 1 else: frequency[word] = 1 return frequency def read(file_name): """ reads a file and returns the number of lines in the file :param file_name: name of the file to be read :return: number of lines in the file """ with open(file_name, "r") as f: text = f.read() return text file_text = read("something.txt") print(word_freq1(file_text))
true
16ba194d28de4bf38a2764f173606bce7cde982b
doraithodla/py101
/shapes.py
282
4.28125
4
from turtle import forward, right def shape(sides,length): for i in range(sides): forward(length) right(360/sides) ''' length = int(input("Length: ")) sides = int(input("Number of sides:")) ''' for sides in range(3,5): shape(sides, 100)
true
41b4bb8bda85667c76cc72387e98ef65fc4fd871
doraithodla/py101
/learnpy2/wordset.py
328
4.125
4
noise_words = {"if", "and", "or", "the", "add"} def wordset(string): """ converts a list of words to a set :param list: string input from the user :return: set object """ string_set = set(string.split()) print(string_set) print(noise_words) wordset("a is a test to check the test of sets ")
true
bea6d8a0680e3c04423bf50c4e89d162cdace2af
eternalseptember/CtCI
/04_trees_and_graphs/01_route_between_nodes/route_between_nodes.py
1,044
4.1875
4
""" Given a directed graph, design an algorithm to find out whether there is a route between two nodes. """ class Node(): def __init__(self, name=None, routes=None): self.name = name self.routes = [] if routes is not None: for item in routes: self.routes.append(item) def __str__(self): list_of_routes = [] for route in self.routes: list_of_routes.append(route.name) return 'name: {0}\t\troutes: {1}'.format(self.name, list_of_routes) def has_route_between_nodes(from_node, to_node): # return True if there is a route between the two # return False if there isn't a route if from_node == to_node: return True visited = [] queue = [from_node] if from_node == to_node: return True while len(queue) > 0: current_node = queue.pop(0) for route in current_node.routes: if route == to_node: return True else: if (route not in queue) and (route not in visited): queue.append(route) # record node as visited if there isn't a path visited.append(current_node) return False
true
275a53e865259a0d15f82cdacdc2a58a641b9343
eternalseptember/CtCI
/07_object-oriented_design/11_file_system/file_system.py
2,226
4.28125
4
""" Explain the data structures and algorithms that you would use to design an in-memory file system. Illustrate with an example in code where possible. """ # What is the relationship between files and directories? class Entry(): def __init__(self, name, parent_dir): self.name = name self.parent_dir = parent_dir # directory object # there should be error checking here. if parent_dir is not None: parent_dir.add_entry(self) def get_full_path(self): if self.parent_dir is None: return self.name else: return '{0}/{1}'.format(self.parent_dir.get_full_path(), self.name) def rename(self, new_name): self.name = new_name def __str__(self): return str(self.name) class File(Entry): def __init__(self, name, parent_dir): Entry.__init__(self, name, parent_dir) self.content = None self.size = 0 def set_content(self, content): self.content = content self.size = len(content) def get_content(self): return str(self.content) def get_size(self): return str(self.size) class Directory(Entry): def __init__(self, name, parent_dir): Entry.__init__(self, name, parent_dir) self.contents = [] # self.num_of_items = 0 def add_entry(self, item): item_type = type(item) item_name = item.name # Search through list. for folder_item in self.contents: if (folder_item.name == item_name) and (type(folder_item) == item_type): print('File with that name exists.') return False # Can add this item? self.contents.append(item) # self.num_of_items += 1 return True def delete_entry(self, item): # Delete an item in this folder. try: self.contents.remove(item) # self.num_of_items -= 1 except: print('File or folder does not exist.') def get_contents(self): content_str = '' for content in self.contents: if len(content_str) > 0: content_str += '\n' content_str += str(content) # content_str += '\n' print(content_str) def get_size(self): size = 0 for item in self.contents: if type(item) is File: size += item.size else: # Get the size of the contents within that folder. size += item.get_size() return size def get_num_of_items(self): return len(self.contents)
true
005103cb3b2736711e6dd9a194a19cb0db8bd420
jcs-lambda/cs-module-project-algorithms
/sliding_window_max/sliding_window_max.py
1,016
4.34375
4
''' Input: a List of integers as well as an integer `k` representing the size of the sliding window Returns: a List of integers ''' def sliding_window_max(nums, k): # initialize first window and max window = nums[:k] current_max = max(window) maxes = [current_max] # slide window for x in nums[k:]: # add newest value to window window.append(x) # remove oldest value from window, and, # if it equals the current max, # then recalculate the current max if window.pop(0) == current_max: current_max = max(window) # check if newest value is max elif x > current_max: current_max = x # store maximum for this window maxes.append(current_max) return maxes if __name__ == '__main__': # Use the main function here to test out your implementation arr = [1, 3, -1, -3, 5, 3, 6, 7] k = 3 print(f"Output of sliding_window_max function is: {sliding_window_max(arr, k)}")
true
f01f3cb9fdf5bd6c4167da2ff209ec7df0308681
subashchandarA/Python-Lab-Pgms-GE8151-
/11MostFrequentWord.py
660
4.34375
4
#Most Frequent word in a string #str="is program is to find the of the word in the string" filename=input("Enter the file name to find the most frequent word: ") fo=open(filename,'r') str=fo.read() print("The given string is :",str) wordlist = str.split(" ") d={} for s in wordlist: if( s in d.keys()): d[s]=d[s]+1 else: d[s]=1 #Frequency: each word as key and frequency is its value print("Dictionary containing word and its frequency:",d) m = max(d.values()) print(m) for key in d: if(d[key]==m): result=key print(" The most frequent word : ",result) print(" It is present ",m," times")
true
5dac50e3ef0821386d271fe18a353c279e69ea1e
subashchandarA/Python-Lab-Pgms-GE8151-
/6.1 selecion sort(python method).py
1,356
4.21875
4
def selectionsort(lt): "select the min value and insert into its position" for i in range(len(lt)-1): #min_pos=x #for x in range(i+1,len(lt)): # if(lt[min_pos]>lt[x]): # min_pos=x min_pos=lt[i:].index(min(lt[i:])) # FIND THE INDEX OF MINIMUM ELEMENT FROM i lt[min_pos+i],lt[i]=lt[i],lt[min_pos+i] # SWAP THE MINIMUM ELEMENT WITH ith ELEMENT print(lt) #Print the list to see the each step of selection sort n=int(input("Enter the number of values:")) lt = [] # creation of empty list #getting n values and store in a list i=30 while(i<n): number=int(input("Enter a value to store:")) lt.append(number) i=i+1 lt=[5,8,12,55,3,7,50] print("Before Selcection Sort : ",lt) selectionsort(lt) print("After Selcection Sort : ",lt) #OUTPUT 1 #Enter the number of values:6 #Enter a value to store:23 #Enter a value to store:80 #Enter a value to store:250 #Enter a value to store:10 #Enter a value to store:500 #Enter a value to store:50 #Before Selcection Sort : [23, 80, 250, 10, 500, 50] #[10, 80, 250, 23, 500, 50] #[10, 23, 250, 80, 500, 50] #[10, 23, 50, 80, 500, 250] #[10, 23, 50, 80, 500, 250] #[10, 23, 50, 80, 250, 500] #After Selcection Sort : [10, 23, 50, 80, 250, 500]
true
a7cd794a1ef6fc543980181f1cf7144b6dd6639f
ShreyaPriyanil/Sorting-in-Python
/insertionsort.py
514
4.21875
4
def insertionSort(alist): for index in range(1,len(alist)): print("TRAVERSAL #: ",index) position = index while position>0 and alist[position-1]>alist[position]: temp = alist[position] alist[position] = alist[position-1] alist[position-1] = temp position = position-1 print("ARRAY AFTER TRAVERSAL #:",index," ", alist) alist = [5,4,3,2,1] print("---------------------NEW---------------------") insertionSort(alist) print(alist)
true
df1eb693316cd623603e43fbee56746b8445b821
shivdazed/Python-Projects-
/Exceptionhandling.py
324
4.15625
4
try: a = int(input("Enter the number A:")) b = int(input("Enter the number B:")) c = a/b print(c) #except Exception as e: # print(e) except ZeroDivisionError: print("We can't divide by zero") except ValueError: print("Your entered value is wrong") finally: print("Sum = ",a+b)
true
08e7e22f6f39a02caca937e0fca7982fb33c901c
Poonam-Singh-Bagh/python-question
/Loop/multiplication.py
228
4.21875
4
''' Q.3 Write a program to print Multiplication of two numbers without using multiplication operator.''' i = 1 a = int(input("enter a no.")) b = int(input("enter a no.")) c = 0 while i <= b: c = c + a i = i + 1 print (c)
true
13cd95427f9fed8977a2b5de25abae5c22d361c6
ONJoseph/Python_exercises
/index game.py
1,013
4.375
4
import random def main(): # 1. Understand how to create a list and add values # A list is an ordered collection of values names = ['Julie', 'Mehran', 'Simba', 'Ayesha'] names.append('Karel') # 2. Understand how to loop over a list # This prints the list to the screen one value at a time for value in names: print(value) # 3. Understand how to look up the length of a list # Use randint to select a valid "index" max_index = len(names) - 1 index = random.randint(0, max_index) # 4. Understand how to get a value by its index # Get the item at the chosen index correct_answer = names[index] # This is just like in Khansole Academy... # Prompt user for an answer and check whether correct or not prompt = 'Who is in index...' + str(index) + '? ' answer = input(prompt) if answer == correct_answer: print('Good job') else: print('Correct answer was', correct_answer) if __name__ == '__main__': main()
true
ca67ed3630bf2bf15468aaacd138312cb1854ad8
shubhamjha25/FunWithPython
/coin_flipping_game/coinflipgame.py
635
4.21875
4
import random import time print("-------------------------- COIN FLIPPING GAME -----------------------------") choice = input("Make your choice~ (heads or tails): ") number = random.randint(1,2) if number == 1: result = "heads" elif number == 2: result = "tails" print("-------------------------------- DECIDING ----------------------------------") time.sleep(2) if choice == result: print("WOOOOO WELL DONE YOU WON!!!! The coin you flipped were", result) else: print("Awww man, you lose. But you can run the script again y'know, The coin you flipped were", result) print("Thanks for playing the coin flipping game!!!")
true
d1cee333a1147bc53c0040e732128b8a5d05abca
Anisha7/Tweet-Generator
/tasks1-5/rearrange.py
1,612
4.28125
4
# build a script that randomly rearranges a set of words provided as command-line arguments to the script. import sys import random # shuffles given list of words def rearrange(args): result = [] while (len(args) > 0) : i = random.randint(0, len(args)-1) result.append(args.pop(i)) return result # takes string word and reverses it def reverse_word(word): rev_word = "" for i in range(len(word)): rev_word += word[len(word) - 1 - i] return rev_word # takes in a string sentence and returns reversed string def reverse_sentence(sentence): l = sentence.split(" ") new = "" for i in range(len(l)): new += l[len(l) - 1 - i] + " " return new; def game(): option = input("Do you want to (A) rearrange, (B) reverse word, (C) reverse sentence? ") if (option == 'A' or option == 'a'): args = input("Give me a list of words: ") result = rearrange(args.split(" ")) print(" ".join(result)) elif (option == 'B' or option == 'b'): word = input("Give me a word to reverse: ") result = reverse_word(word) print(result) else : sentence = input("Give me a sentence to reverse: ") result = reverse_sentence(sentence) print(result) return; def run(): # args = sys.argv[1:] # result = rearrange(args) # print(" ".join(result)) gameState = input("Do you want to play (y/n)? ") while (gameState == 'y' or gameState == 'Y'): game(); gameState = input("Do you want to play again (y/n)? ") return; run()
true
bb8749c3abda670d006b2184f7b620449bb54f07
joseramirez270/pfl
/Assignment4/generate_model.py
1,180
4.1875
4
"""modify this by generating the most likely next word based on two previous words rather than one. Demonstrate how it works with a corresponding conditional frequency distribution""" import nltk """essentially, this function takes a conditional frequency distribution of bigrams and a word and makes a sentence. Each time, a loop prints the current word, then looks for the next word by finding the most frequent word that appears in texts after it. It then prints that word, and the process repeats again, generating the random sentence""" def generate_model(cfdist, word, num=15): for i in range(num): print(word, end = ' ') word = cfdist[word].max() def generate_model2(cfdist, bigram, num=15): for i in range(num): print(bigram[0], end = ' ') bigram = cfdist[bigram].max() text = nltk.corpus.genesis.words('english-kjv.txt') bigrams = nltk.bigrams(text) bigramsofbigrams = nltk.bigrams(bigrams) cfd = nltk.ConditionalFreqDist(bigramsofbigrams) bigrams = nltk.bigrams(text) cfd2 = nltk.ConditionalFreqDist(bigrams) generate_model(cfd2, 'in') print('\n') generate_model2(cfd, ('in', 'the')) #print(cfd[('in', 'the')].max())
true
0a93e0ded92ef09809aa22bd801667587171f6ed
jyoung2119/Class
/Class/demo_labs/PythonStuff/5_10_19Projects/dateClass.py
1,918
4.15625
4
#Class practice class Date: def __init__(self, m, d): self.__month = m self.__day = d #Returns the date's day def get_day(self): return self.__day #Returns the date's month def get_month(self): return self.__month #Returns number of days in this date's month def days_in_month(self): print() #Modifies date by 1 def next_day(self): print() def compare(self, mon, day): if mon > self.__month: return -1 elif mon == self.__month and day == self.__day: return 0 elif mon == self.__month and day < self.__day: return 1 elif mon == self.__month and day > self.__day: return -1 else: return 1 def main(): dayList = [31,30,31,30,31,30,31,31,30,31,30,31] try: month = int(input("Enter month #: ")) day = int(input("Enter the day #: ")) secMonth = int(input("Enter second month #: ")) secDay = int(input("Enter the second day #: ")) except ValueError: print("(ノಠ益ಠ)ノ彡┻━┻") else: if (month > 12 or month < 0) or dayList[month - 1] < day or day < 0: print("(ಥ ╭╮ಥ )") print("Check Your Dates...") elif (secMonth > 12 or secMonth < 0) or dayList[month - 1] < secDay or day < 0: print("ಡ _ಡ") print("Check Your Dates...") else: dateVar = Date(month, day) compRes = dateVar.compare(secMonth, secDay) if compRes == -1: print("First date comes before the second date.") elif compRes == 0: print("SAME DAY REEEEEE") else: print("Second date comes before the first date.") main()
true
ac1971b1544ccb491d9ed862258cc4bf3dbccae2
inbsarda/Ccoder
/Python_codes/linked_list.py
2,030
4.1875
4
################################################### # # Linked List # ################################################### class node: def __init__(self, data): self.data = data self.next = None def insertAtBegining(head,data): ''' Insert node at begining ''' newnode = node(data) newnode.next = head return newnode def insertAtEnd(head, newnode): ''' Insert node at the end ''' if head is None: head = newnode return while head.next != None: head = head.next head.next = newnode def insertInBetween(middlenode, newnode): ''' Insert node in between of the list ''' if middlenode is None: print("Node is absent") return newnode.next = middlenode.next middlenode.next = newnode def deleteNode(head, data): ''' Remove the node from linked list ''' if head.data == data: Head = head head = head.next Head = None return while head.data != data: prev = head head = head.next if head is None: break if head is None: print("node not found") return else: prev.next = head.next head = None def findMiddle(head): ''' Find middle of the linked list ''' node1 = node2 = head if head is None: print("Empty list") while node2 is not None and node2.next is not None: node1 = node1.next node2 = node2.next.next return node1 def printList(head): ''' Trverse and print the list ''' while head != None: print(head.data) head = head.next head = node("mon") e1 = node("Tue") e2 = node("wed") head.next = e1 e1.next = e2 e3 = node("thu") insertAtEnd(head, e3) e4 = node("fri") insertInBetween(head.next, e4) head = insertAtBegining(head, "sun") deleteNode(head, "fri") deleteNode(head, "sun") printList(head) middle = findMiddle(head) print(middle.data)
true
a4c58d8162dbb4317ec0cfced87e8e3c71860f74
inbsarda/Ccoder
/Python_codes/reverse_list.py
1,161
4.3125
4
################################################################## # # Reverse the linked list # ################################################################## class node: def __init__(self, data): self.data = data self.next = None class linkedlist: def __init__(self): self.head = None def insert(self, data): ptr = node(data) if self.head is None: self.head = ptr return temp = self.head while temp.next is not None: temp = temp.next temp.next = ptr def printlist(self): temp = self.head while temp is not None: print(temp.data) temp = temp.next def reverselist(self): temp = self.head prev = None fwd = None while temp is not None: #print(temp.data) fwd = temp.next temp.next = prev prev = temp temp = fwd self.head = prev llist = linkedlist() llist.insert("sun") llist.insert("mon") llist.insert("tue") llist.insert("wed") llist.printlist() llist.reverselist() llist.printlist()
true
a1593b01f3f3c09d1c392c63612e81506d90243a
doritger/she-codes-git-course-1
/ex2.py
1,049
4.28125
4
from datetime import datetime # imports current date and time def details(): first_name = input("Please enter your first name: ") surname = input("Please enter your surname: ") birth_year = input("Please enter the year of your birth: ") # asks the user to enter name, surname and year of birth print (first_name) print (surname) print (birth_year) # prints the name, surname and year of birth of the user currentYear = datetime.now().year # calcuates current year age = (int (currentYear)) - (int (birth_year)) # changes the strings 'currentYear' & 'birth_year' to intergals # and calcuates the user's age according to current year print ("Your initials are " + first_name[0].upper() +surname[0].upper() + " and you are " + str (age) + " years old.") # changes the intergal 'currentYear' to a string # and prints the user's initials (first letter of the name & surname) # and the user's age # .upper() to have the initials in uppercase letters details()
true
5fe884067f7af8df12f114e84a40953cab414d6e
abby-does-code/youtube_practice_intmd
/dictionaries!!.py
2,766
4.3125
4
# START ## Keep chugging away bb! # Dictionary: data type that is unordered and mutable ##Consists of key:value pairs; maps value to associated pair # Create a dictionary(30:00) mydict = {"name": "Max", "age": 28, "city": "New York"} print(mydict) # Dict method for creation # mydict2 = dict(name = "Mary", age = 27, city = "Boston") # print(mydict2) # Acessing values (31:35) value = mydict["name"] print(value) # Weird, i thought that created a value. value = mydict["age"] print(value) # Adding or changing values (32:18) ##Dictionaries are mutable! ###Fun note: name was moved to the back of the dictionary? mydict["email"] = "Max@xyz.com" print(mydict) """ # Deleting a method ###I commented this out so I can keep working without retyping code lol### del mydict["name"] print(mydict) mydict.pop("age") print(mydict) mydict.popitem() #removes the first item?? print(mydict) """ # Checking for value if "name" in mydict: print(mydict["name"]) ##Try and except method? (35:05) try: print(mydict["name"]) except: print("Error") try: print(mydict["lastname"]) except: print("Error! That's not in the dictionary silly goose.") # Iterating through a dictionary (36:00) # For loops: for key in mydict: print(key) # prints all keys for key in mydict.keys(): print(key) for value in mydict.values(): print(value) for key, value in mydict.items(): print(key, value) # Copyign a dictionary ##Be careful! mydict_copy = mydict print(mydict_copy) # Modifying the copy modifies the OG! commented out so the proper code works lol """ mydict_copy["email"] = "max@123.com" print(mydict_copy, mydict) """ # Notice, just like lists, this changes the OG as well. This is becuase you're referencing the same point in the memory. # Making a copy that's independent of your OG: mydict_copy = mydict.copy() print(mydict_copy) mydict_copy["email"] = "max@123.com" print(mydict_copy, mydict) # Updating a dictionary (39:15) my_dict = {"name": "Max", "age": 56, "email": "eww@eww.com"} my_otherdict = dict(name="Martha", age=102, city="Hotlanta") my_dict.update(my_otherdict) print(my_dict) # This is FASCINATING! All existing key pairs were overwritten; email was NOT becuase it was not an item in my_otherdict # Possible key types ##Can use any immutable type ###Can even use a tuple??? my_dict = {3: 9, 6: 36, 9: 81} print(my_dict) # value = my_dict[0] # Error! Zero isn't in our list and it's not an index. Use the actual key to access. value = my_dict[3] print(value) # This will return the value 9! # Use a tuple as a key mytuple = (8, 7) my_dict = {mytuple: 15} print(my_dict) # Tuples are possible, but a list would throw an exception # Lists are mutable and can be changed; so it's not hashable and can't be used as a key
true
18f75cc839f336f3a2f815a578eb5871ad2a7f5c
pranabsg/python-dsa
/get_fibonacci.py
381
4.28125
4
"""Implement a function recursively to get the desired Fibonacci sequence value. """ def get_fib(position: int) -> int: if position == 0 or position == 1: return position return get_fib(position - 1) + get_fib(position - 2) def main(): # Test cases print(get_fib(2)) print(get_fib(11)) print(get_fib(0)) if __name__ == '__main__': main()
true
f78a79c275e90a90394269b230cdef39dbc4d979
danecashion/python_example_programs
/first_largest.py
284
4.5625
5
""" Python program to find the largest element and its location. """ def largest_element(a): """ Return the largest element of a sequence a. """ return None if __name__ == "__main__": a = [1,2,3,2,1] print("Largest element is {:}".format(largest_element(a)))
true
8bf8929bbfe763af15cf61cdb294ca78b59bc057
annamwebley/PokerHand
/deck.py
2,626
4.15625
4
# Project 3b # Anna Markiewicz # May 12 # deck.py # Shuffle the Card objects in the deck import random from card import Card class Deck: """Card Deck, which takes self as input, and creates a deck of cards """ def __init__(self): self.cards = [ ] for suit in ['C', 'D', 'H', 'S']: for rank in range(2,15): # print(f"I am creating suit = {suit}, rank = {rank}") # create a new card with the specified rank # and suit and append it to the list. self.cards.append(Card(rank, suit)) def __str__(self): output = "" # Concatenate card to # the output variable for card in self.cards: output = output + str(card) + " " return output def __repr__(self): return str(self) def shuffle(self): # print("I am shuffling cards...") random.shuffle(self.cards) def deal_card(self): # # Remove the card from the top of the cards list and save it as the Card object c # print (len(self.cards)) # print("I am popping one card...") return self.cards.pop() def pop_card(self): # # Remove the card from the top of the cards list and save it as the Card object c # print (len(self.cards)) # print("I am popping one card...") return self.cards.pop() def count_cards(self): # print("I am counting cards...") return (len(self.cards)) def is_empty(self): if not self.cards: return True else: return False def add_to_top(self, rank, suit): # Create a new card with the specified rank and suit and append it to the cards in the deck c = Card(rank, suit) self.cards.append(c) return self.cards[-1] def add_to_bottom(self, rank, suit): # Insert the card c at the bottom of the deck (before the item with index 0) c = Card(rank, suit) self.cards.insert(0, c) return self.cards[0] if (__name__) == '__main__': deck = Deck() #print(f"deck.cards = {deck.cards[7]}") # for card in deck.cards: # print(card) deck.shuffle() print(deck) deck.deal_card() print(deck.deal_card()) deck.pop_card() print(deck.pop_card()) deck.count_cards() print(deck.count_cards()) deck.is_empty() print(deck.is_empty()) c = Card(10, "H") deck.add_to_top(10, "H") print(deck.add_to_top(10, "H")) c = Card(8, "C") deck.add_to_bottom(8, "C") print(deck.add_to_bottom(8, "C"))
true
492eddbeffe120a0ca71fc4767ce8e6523b04978
lshpaner/python-datascience-cornell
/Analyzing and Visualizing Data with Python/Importing and Preparing Data/LoadDataset.py
2,531
4.125
4
#!/usr/bin/env python # coding: utf-8 # ## Analyzing the World Happiness Data # # # ### Preparing the data for analysis # In this exercise, we will do some initial data imports and preprocessing to get the data ready for further analysis. We will repeat these same basic steps in subsequent exercises. Begin by executing the code cell below to import some necessary packages. Note that the last line in the code cell below is intended to instruct pandas to display floating point numbers to 2 decimal places (`.2f`). This is just one of many pandas display options that can be configured, as described [here](https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html). # In[1]: import pandas as pd import seaborn as sns import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') pd.options.display.float_format = '{:.2f}'.format # ### Step 1 # # Create a Pandas dataframe named ```dfraw``` by reading in the data in the worksheet named "Table2.1" from the spreadsheet "WHR2018Chapter2OnlineData.xls". # In[2]: dfraw = pd.read_excel('WHR2018Chapter2OnlineData.xls', sheet_name='Table2.1') # To facilitate working with the data, it will be useful to select a subset of the data from the full dataset and to rename the columns to make them less verbose. In the code cell below, the variable ```cols_to_include``` contains a list of column names to extract. # Execute the cell. # In[3]: cols_to_include = ['country', 'year', 'Life Ladder', 'Positive affect','Negative affect', 'Log GDP per capita', 'Social support', 'Healthy life expectancy at birth', 'Freedom to make life choices', 'Generosity', 'Perceptions of corruption'] # ### Step 2 # # Using the variables defined above, in the code cell below, write and evaluate an expression to create a new dataframe named `df` that includes the subset of data in `cols_to_include`. # ## Graded Cell # # This cell is worth 100% of the grade for this assignment. # In[4]: df = dfraw[cols_to_include] # ## Self-Check # # Run the cell below to test the correctness of your code above before submitting for grading. # In[5]: # Run this self-test cell to check your code; do not add code or delete code in this cell from jn import testDf try: print(testDf(df, dfraw)) except Exception as e: print("Error!\n" + str(e)) # ### Step 3. # # Take a peek at the head of the new dataframe. # In[6]: df.head()
true
28b512c74e3fd196b8ca592e9c81d72bfe1f9672
lshpaner/python-datascience-cornell
/Constructing Expressions in Python/Computing the Average (Mean) of a List of Numbers/exercise3.py
975
4.53125
5
""" Computing the Average (Mean) of a List of Numbers Author: Leon Shpaner Date: July 19, 2020 In exercise3.py in the code editor window, create a new list containing a mixture of letters and numbers: my_other_list = [1, 2.3, 'a', 4.7, 'd'], and write an expression computing its average value using a similar expression as the one you previously wrote, storing the result in my_other_list_average. """ my_other_list = [1, 2.3, 'a', 4.7, 'd'] # Set a running total for elements in the list, initialized to 0 total = 0 # Set a counter for the number of elements in the list, initialized to 0 num_elements = 0 # Loop over all the elements in the list for element in my_other_list: # Add the value of the current element to total total = total + element # Add 1 to our counter num_elements num_elements = num_elements + 1 # Compute the average by dividing the total by num_elements average = total / num_elements my_other_list_average= total/len(my_other_list)
true