blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
1bab041dff3b647ca61edd9e2bc2beb4a279c2d1
vipulthakur07/Assignment14
/Assignment14.py
926
4.15625
4
#Que1-->Write a python script to create a databse of students named Students. import pymongo client=pymongo.MongoClient() database=client['Studentdb'] print("database created") collection=database['studenttbl'] print("table created") print() #Que2-->Take students name and marks(between 0-100) as input from user 10 times using loops. print('Enter Detail Of Student') for i in range (1,5): for i in range (1,11): fn=input('enter the name:') mrk=int(input('enter the marks:')) print() #Que3-->Add these values in two columns named "Name" and "Marks" with the appropriate data type. for i in range(1,5): collection.insert_one({'Name':fn,'Mark':mrk}) print('VALUES INSERTED IN TABLE') print() #Que4-->Print the names of all the students who scored more than 80 marks. print('MARKS GREATER THAN 80') data=collection.find({'Mark':{"$gt" : 80}}) for document in data: print(document) print()
true
b72a14183418fce98d72a72c29e63ef3561d12db
imgeekabhi/HackerRank
/data-structures/insert-a-node-into-a-sorted-doubly-linked-list.py
680
4.21875
4
""" Insert a node into a sorted doubly linked list head could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node return the head node of the updated list """ def SortedInsert(head, data): if head == None: return Node(data=data, next_node=None, prev_node=None) node = head while node.next != None and node.next.data <= data: node = node.next node.next = Node(data=data, next_node=node.next, prev_node=node) return head
true
b2149ffcc18045825f21ffeaf5c3673ba7206c0c
pemagrg1/tkinter-sample-code
/Python-Programming/primeOrNot.py
301
4.25
4
# Check if given number is prime or not. Ex Prime numbers: 2, 3, 5, 7, 13 i, temp = 0, 0 n = int(input("please give a number : ")) for i in range(2, n//2): if n % i == 0: temp = 1 break if temp == 1: print("given number is not prime") else: print("given number is prime")
true
fae4acdcadd4fd174f7e6abe32e44928847f008a
Daniel-Osei/global-code2019
/dev-globalcode/loops/while_loop.py
954
4.1875
4
#first trial print ("printing from 1 - 10 with while") i = 0 while(i < 10): i = i + 1 print (i) input("press enter to continue") #try printing numbers from 7 - 19 print ("print from 7 - 19") j = 6 while(j < 19): j = j + 1 print (j) input("press enter to continue") #print even numbers between 12 and 20 print ("print even numbers between 12 and 20 ") k = 12 while(k < 18): k = k + 2 print (k) input("press enter to continue") #take two numbers from user and give even numbers between them def even(): start = int(input("Enter the lower limit: ")) end = int(input("Enter the upper limit: ")) for num in range(start, end + 1): if num % 2 == 0: print (num) even() def reverse_even(): start = int(input("Enter the lower limit: ")) end = int(input("Enter the upper limit: ")) for num in range(end, start - 1, -1): if num % 2 == 0: print (num) reverse_even()
true
3b7a9e3f1d000c536ae1a9da7843810bef205565
Bitcents/python_algos
/sorting.py
2,563
4.15625
4
from typing import List from timeit import default_timer as timer import random # the simplest of sorting algorithms # these implementations were inspired by psuedocode found in wikipedia # for explanations, head to the corresponding wikipedia page def selection_sort(numbers: List[int]) -> None: for i in range(len(numbers)): for j in range(i, len(numbers)): if numbers[j] < numbers[i]: numbers[i], numbers[j] = numbers[j], numbers[i] def insertion_sort(numbers: List[int]) -> None: i = 1 n = len(numbers) while (i < n): j = i while j > 0 and numbers[j-1] > numbers[j]: numbers[j-1], numbers[j] = numbers[j], numbers[j-1] j -= 1 i += 1 def bubble_sort(numbers: List[int]) -> None: n = len(numbers) flag = True while(flag): newn = 0 for i in range(1, n): if numbers[i-1] > numbers[i]: numbers[i - 1], numbers[i] = numbers[i], numbers[i-1] newn = i n = newn flag = not newn <= 1 def quick_sort(numbers: List[int], low: int, high: int) -> None: if low < high: i = low pivot = numbers[high-1] for j in range(low, high): if numbers[j] < pivot: numbers[j], numbers[i] = numbers[i], numbers[j] i += 1 numbers[i], numbers[high-1] = numbers[high-1], numbers[i] # recursive call quick_sort(numbers,low, i) quick_sort(numbers, i + 1, high) # We need an easy way to make large lists of integers, for testing our sorting algorithms # This function helps us create such lists easily def create_random_integers(lower: int, upper: int, no_of_ints) -> List[int]: arr = [] for _ in range(no_of_ints): arr.append(random.randint(lower, upper)) return arr if __name__=='__main__': # Due to how Python works, we must make copies of the lists we create # With the copy method test_numbers = create_random_integers(0,50,1000) test_numbers_copy = test_numbers.copy() # Test algorithms s = timer() quick_sort(test_numbers, 0, len(test_numbers)) e = timer() difference1 = e - s #print(test_numbers) s = timer() insertion_sort(test_numbers_copy) e = timer() difference2 = e - s #print(test_numbers) print(f'quick_sort time: {difference1}, insertion_sort time = {difference2}')
true
35f05b94673ca7af9b2a43f87b457b619c861581
srisaipog/ICS4U-Classwork
/Assessments/Test - 13 December 2019 (Algorithms)/Recursion 1.py
831
4.28125
4
""" Given an array of ints, compute recursively if the array contains a 6. We'll use the convention of considering only the part of the array that begins at the given index. In this way, a recursive call can pass index+1 to move down the array. The initial call will pass in index as 0. contain_6([1, 6, 4], 0) → true contain_6([1, 4], 0) → false contain_6([6], 0) → true """ # lowercase true and false, lol from typing import List def contain_6(nums: List[int], index: int) -> bool: if len(nums) == index: return False if nums[index] == 6: return True else: return contain_6(nums, index + 1) nums = [1, 2, 3, 2, 5] import random for _ in range(10): temp = [] for _ in range(5): temp.append(random.randint(0, 10)) print(temp, contain_6(temp, 0))
true
8efc2148672500c8563559fbaee40cd8a90d24ac
srisaipog/ICS4U-Classwork
/Assessment Practice/Final Test Prep/array220.py
797
4.1875
4
""" Given an array of ints, compute recursively if the array contains somewhere a value followed in the array by that value times 10. We'll use the convention of considering only the part of the array that begins at the given index. In this way, a recursive call can pass index+1 to move down the array. The initial call will pass in index as 0. array220([1, 2, 20], 0) → true array220([3, 30], 0) → true array220([3], 0) → false """ from typing import List def array220(nums: List[int], index: int) -> bool: if index >= len(nums) - 1: return False if nums[index] * 10 == nums[index + 1]: return True else: return False or array220(nums, index + 1) print( array220([1, 2, 20], 0), array220([3, 30], 0), array220([3], 0), sep="\n" )
true
1fb13b606ce19f7ee8edd7786e6f2782e450e229
srisaipog/ICS4U-Classwork
/Learning/File RW/more_txt_files.py
651
4.46875
4
# Sridhar S # Multi-line exercises # Create a multi-line text file with one word on each line ## Exercises ''' 1. Open the text file and print out `f.read()`. What does it look like? 2. Use a for loop to print out each line individually. `for line in f:` 3. Print out only the words that start with "m", or some other specific letter. ''' ## Solutions ### 1 with open("some_file.txt", "r") as f: print(f.read()) ### 2 with open("some_file.txt", "r") as f: for line in f: print(line.strip()) ### 3 with open("some_file.txt", "r") as f: for line in f: if line.lower().startswith("m"): print(line.strip())
true
9ff896efee2e1737f89873547a47c88a2cc132aa
srisaipog/ICS4U-Classwork
/Learning/Recursion/allStar.py
510
4.15625
4
''' Given a string, compute recursively a new string where all the adjacent chars are now separated by a "*". allStar("hello") → "h*e*l*l*o" allStar("abc") → "a*b*c" allStar("ab") → "a*b" ''' def allStar(w: str, mode=-1) -> str: if len(w) == 1: return w + "*" else: bob = allStar(w[:-1], 0) + allStar(w[-1], 0) if mode == -1: return bob[:-1] else: return bob print( allStar("Jerry"), allStar("Beth"), allStar("meth"), sep = "\n" )
false
2eef04dca7ba39527cd11a9fd1a9381a2ed264e3
IwanderTx3/Daily-assignment
/day3/calculator.py
647
4.125
4
import calc_functions first_number = float(input("Enter the first numer: ")) operator = str(input("Enter the operator: ")) second_number = float(input("Enter the second numer: ")) result = 0.0 if operator == '*': result = calc_functions.multiply(first_number,second_number) elif operator == '/': result = calc_functions.divide(first_number,second_number) elif operator == '+': result = calc_functions.add(first_number,second_number) elif operator == '-': result = calc_functions.subtract(first_number,second_number) else: print("Invailid Operator") print(f"{first_number} {operator} {second_number} = {result}")
true
b5d0435e6a647054a237e9f664f3cba718943d82
xiluhua/python-demo
/demo/demo02_比较运算符.py
826
4.125
4
''' @note: https://www.runoob.com/python/python-operators.html @author: xilh @since: 20200124 ''' a = 21 b = 10 c = 0 f = 'abc' g = 'abc' h = 'efg' if f == g : print("1. f equals g") if f == h : print("2. f equals h") else : print("2. f !equals h") if a == b : print("3. a 等于 b") else: print("3. a 不等于 b") if a != b : print("4. a 不等于 b") else: print("4. a 等于 b") if a < b : print("5. a 小于 b") else: print("5. a 大于 b") if a > b : print("6. a 大于 b") else: print("6. a 小于 b") # 修改变量 a 和 b 的值 a = 5 b = 20 if a <= b : print("7. a 小于等于 b") else: print("7. a 大于 b") if b >= a : print("8. b 大于等于 a") else: print("8. b 小于 a")
false
c6088be81f9a457d2c75c46b8a8d4aebefe343c6
VVingerfly/LearnPython
/6.FunctionalProgramming/dictionary.py
1,385
4.40625
4
""" Dictionary are data structures used to map arbitrary keys to values. Each element in a dictionary is represented by a key:value pair. Mutable objects can't be used as keys to dictionaries, such as lists, dictionaries. """ print("_________________________ Test 1 _________________________") ages = {"Dave": 24, "Mary": 42, "John": 58} print(ages["Mary"]) print(ages["Dave"]) print("_________________________ Test 2 _________________________") primary = { "red": [255, 0, 0], "green": [0, 255, 0], "blue": [0, 0, 255], } print(primary["red"]) # print(primary["yellow"]) # return a KeyError print("_________________________ Test 3 _________________________") squares = {1: 1, 2: 4, 3: "error", 4: 16,} squares[8] = 64 squares[3] = 9 print(squares) print("_________________________ Test 4 _________________________") # use in and not in to determine whether a key is in a dictionary nums = { 1: "One", 2: "Two", 3: "Three", } print(1 in nums) print("Three" in nums) print(4 not in nums) print("_________________________ Test 5 _________________________") pairs = { 1: "apple", "orange": [2, 3, 4], True: False, None: "True", } print(pairs.get("orange")) print(pairs.get(7)) print(pairs.get(12345, "not in dictionary")) fib = {1: 1, 2: 1, 3: 2, 4: 3} print(fib.get(4, 0) + fib.get(7, 5)) print(fib.get(4, 5)) print(fib.get(8)) print(fib)
true
16510eceb0e5d226249da73f7fe110e49fc33f65
VVingerfly/LearnPython
/8.RegularExpression/group.py
2,014
4.8125
5
""" A group can be created by surrounding part of a regular expression with parentheses. This means that a group can be given as an argument to metacharacters such as * and ?. """ import re print("_________________________ Test 1 _________________________") pattern = r"egg(spam)*" if re.match(pattern, "egg"): print("match 1") if re.match(pattern, "eggspamspamspamegg"): print("match 2") if re.match(pattern, "spam"): print("match 3") if re.match(pattern, "egg2"): print("match 4") print("_________________________ Test 2 _________________________") # The content of groups in a match can be accessed using the group function. # group(0) or group() returns the whole match. # group(n) returns the nth group from the left(n>0) # groups() returns all groups up from 1 # pattern = r"a(bc)(de)(f(g)h)i" match = re.match(pattern, "abcdefghijklmnop") if match: print(match.group()) print(match.group(0)) print(match.group(1)) print(match.group(2)) print(match.groups()) print("_________________________ Test 3 _________________________") # named groups: have the format (?P<name>...), where name is the name of group and ... is the content. # They behave the same as normal groups, except they can be accessed by group(name) in addition to its number. # Non-capturing groups: have the format (?:...), they are not accessible by the group method, # so they can be added to an existing regular expression without breaking the numbering. pattern = r"(?P<first>abc)(?:def)(ghi)" match = re.match(pattern, "abcdefghi") if match: print(match.group("first")) print(match.groups()) print("_________________________ Test 3 _________________________") # Another important metacharacter is |, which means "or" # red|blue matches either "red" or "blue" pattern = r"gr(a|e)y" match = re.match(pattern, "gray") if match: print("Match 1") match = re.match(pattern, "grey") if match: print("Match 2") match = re.match(pattern, "griy") if match: print("Match 3")
true
0107f3771610fe83ddbaf32cd7e1b31d8ad67185
VVingerfly/LearnPython
/4.Exception-Files/files_open.py
457
4.1875
4
myfile = open("./files/file1.txt") myfile.close() # read mode (default) open("./files/file1.txt", "r") # write mode # when a file is opened in write mode, the file's existing content is deleted open("./files/file1.txt", "w") # append mode: add new content to the end of the file open("./files/file1.txt", "a") # binary write mode # binary mode is used for non-text files (such as images and sound files) open("./files/file1.txt", "wb") print("Done!")
true
83e7a3ff59e8aeba53a7fd991c4efc90cf8691d8
Smrity01/python_codes
/flatter_.py
1,269
4.3125
4
def flatter(mylist,newlist,position=0,index=0): ''' Objective: To flatter a nested list Input parameters: mylist: The original nested list entered by user newlist: The flattered list position: To track the list given by user index: to track the new list Return value: new flattered list is returned ''' #Approach: The type of elements of the list is compared #If it is list type then flatter function is called on that nested list #If it is int type the element copied in newlist #It repeats until the end of the list #Recursion is used if(position < len(mylist)): if(type(mylist[position]) == int): element = mylist[position] newlist.insert(index,element) return flatter(mylist,newlist,position+1,index+1) elif (type(mylist[position]) == list): length = len(mylist[position]) flatter(mylist[position],newlist,0,index) return flatter(mylist,newlist,position+1,index + length) else:return newlist mylist=[10,30,[20],45,[40,[19],[30,28],90],76] newlist=[] print(flatter(mylist,newlist))
true
994a950944da90cb0be61164d425d61585ffe058
Smrity01/python_codes
/merge2list.py
2,125
4.1875
4
def merge(mylist,mylist2,finallist): ''' objective: to merge 2 unsorted list input parameter: mylist: first unsorted list mylist2: Second unsorted list finallist: The new merged list return value: final merged list ''' #Approach: inserting the smallest element of the two list at position 'pos' in the new list pos = 0 if mylist != [] and mylist2 != []: if mylist[pos] < mylist2[pos]: el = mylist.pop(pos) appendlist(el,finallist) return merge(mylist,mylist2,finallist) elif mylist[pos]>mylist2[pos]: el = mylist2.pop(pos) appendlist(el,finallist) return merge(mylist,mylist2,finallist) else: el = mylist2.pop(pos) appendlist(el,finallist) el = mylist.pop(pos) appendlist(el,finallist) return merge(mylist,mylist2,finallist) elif mylist != []: el = mylist.pop(pos) appendlist(el,finallist) return merge(mylist,mylist2,finallist) elif mylist2 != []: el = mylist2.pop(pos) appendlist(el,finallist) return merge(mylist,mylist2,finallist) else: return finallist def appendlist(number,lst,position=0): ''' objective: to append a value in sorted list input parameter: lst: original sorted list number: the number which is inserted in the list position: to traverse the list return value: modified list ''' #approach: recursive call of the function if (finallist != []): if(number< lst[len(lst)-1]): if(number < lst[position]): lst.insert(position,number) return lst else: return appendlist(number,lst,position+1) else: lst.insert(len(lst),number) else: lst.insert(0,number) mylist=[6,8,9,12,23,65,43,16] mylist2=[6,7,5,4] finallist=[] merge(mylist,mylist2,finallist) print('The final merge list: ',finallist)
true
56eaf8c330a59cc1a04145550955860a19672097
Smrity01/python_codes
/binary_search.py
1,785
4.125
4
def binary_search(mylist,element): ''' Objective: To search a number in the list using binary search algorithm Input parameter: mylist: The list in which number is to be search element: A number which is to be search in the list ''' #Approach: Divide and conquer technique is used upper=len(mylist) lower=-1 find(mylist,element,lower,upper) def find(mylist,element,lower,upper): ''' Objective: To search a number in the list sequentially Input parameter: mylist: The list in which number is to be search element: A number which is to be search in the list upper: upper limit of the list lower: lower limit of the list Ouput: Print whether the number is found or not. If number is found then its index is also printed ''' #Approach: The list is divided into 2 parts: #The middle element is compared with the searched element #If middle element is greater than the searched element:- left half of the list is searched #Else the right half of the list is searched if upper > lower+1: mid = (lower+upper) // 2 if mylist[mid] == element: return print('Element found at: Index',mid) if mylist[mid] > element: return find(mylist,element,lower,mid) else:return find(mylist,element,mid,upper) else:print('Oops.......Element not found') mylist=[2,17,29,45,51,64,67,72,89,100] print('Your list is: ',mylist) element=int(input('Enter the element you want to search: ')) binary_search(mylist,element)
true
7c08fbff25080554577aa7235f51e69a3e433a9c
JoseALermaIII/python-tutorials
/pythontutorials/books/AutomateTheBoringStuff/Ch04/Projects/P2_charPicGrid.py
2,035
4.15625
4
"""Character Picture Grid This program converts a matrix to an image. Say you have a list of lists where each value in the inner lists is a one-character string, like this:: grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] You can think of `grid[x][y]` as being the character at the x- and y-coordinates of a “picture” drawn with text characters. The `(0, 0)` origin will be in the upper-left corner, the x-coordinates increase going right, and the y-coordinates increase going down. Copy the previous grid value, and write a function, :meth:`matrix_to_pic`, that uses it to print the image:: ..OO.OO.. .OOOOOOO. .OOOOOOO. ..OOOOO.. ...OOO... ....O.... """ def matrix_to_pic(matrix: list) -> None: """Matrix to picture Converts a matrix of lists with one-character values into `ASCII Art`_. Args: matrix: List with lists containing one-character elements. Returns: None. Prints the contents of the lists as `ASCII Art`_ .. _ASCII Art: https://en.wikipedia.org/wiki/ASCII_art """ new_matrix = zip(*matrix) #: Convert rows to columns in new matrix for item in new_matrix: print(''.join(item)) return None def main(): grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] matrix_to_pic(grid) if __name__ == "__main__": main()
true
0b083ca3e53dd11f29b252678011f4ece843dd8d
JoseALermaIII/python-tutorials
/pythontutorials/books/AutomateTheBoringStuff/Ch13/Projects/P1_encryptPDFparanoia.py
2,444
4.125
4
"""Encrypt PDF paranoia Using :func:`os.walk`, write a script that will go through every PDF in a folder (and its subfolders) and encrypt the PDFs using a password provided on the command line. Save each encrypted PDF with an _encrypted.pdf suffix added to the original filename. Before deleting the original file, have the program attempt to read and decrypt the file to ensure that it was encrypted correctly. Notes: * Default folder is parent directory. * Default suffix is '_encrypted.pdf'. * Running in debug mode, uncomment to delete original file. """ def main(): import PyPDF4, os from PyPDF4.utils import PdfReadError FOLDER = "../" SUFFIX = "_encrypted.pdf" # Get all PDF files in FOLDER files = [] for folderName, subfolders, filenames in os.walk(FOLDER): for filename in filenames: # If file is in subdirectory, append backslash to folderName if folderName.endswith('/'): filepath = folderName + filename else: filepath = folderName + '/' + filename if filename.lower().endswith(".pdf") and not PyPDF4.PdfFileReader(open(filepath, "rb")).isEncrypted: files.append(filepath) # Get password from user password = input("Please input encryption password:\n") # Encrypt list of PDF files with password for file in files: pdfFile = open(file, "rb") pdfReader = PyPDF4.PdfFileReader(pdfFile) pdfWriter = PyPDF4.PdfFileWriter() for pageNum in range(pdfReader.numPages): pdfWriter.addPage(pdfReader.getPage(pageNum)) pdfWriter.encrypt(password) # Append SUFFIX when saving encrypted file newfile = file[:-4] + SUFFIX resultPdf = open(newfile, "wb") pdfWriter.write(resultPdf) resultPdf.close() # Attempt to read and decrypt encrypted file pdfReader = PyPDF4.PdfFileReader(open(newfile, "rb")) pdfReader.decrypt(password) # If the first page cannot be read, print error and move to next file try: pdfReader.getPage(0) except PdfReadError as err: print("PdfReadError: %s" % err) print("Skipping: %s" % file) continue # Delete original file print("Deleting: %s" % file) # DEBUG #os.remove(file) # uncomment if sure if __name__ == '__main__': main()
true
8e6948a4bd7e3648669285b98d618b20b526abfe
JoseALermaIII/python-tutorials
/pythontutorials/books/CrackingCodes/Ch09/PracticeQuestions.py
986
4.375
4
"""Chapter 9 Practice Questions Answers Chapter 9 Practice Questions via Python code. """ def main(): # 1. If you ran the following program and it printed the number 8, what would # it print the next time you ran it? import random random.seed(9) print(random.randint(1, 10)) random.seed(9) print(random.randint(1, 10)) # 2. What does the following program print? spam = [1, 2, 3] eggs = spam ham = eggs ham[0] = 99 print(ham == spam) # 3. Which module contains the deepcopy() function? # Hint: Check page 122...or the next question # 4. What does the following program print? import copy # Don't do this, imports are supposed to be at the top of file spam = [1, 2, 3] eggs = copy.deepcopy(spam) ham = copy.deepcopy(eggs) ham[0] = 99 print(ham == spam) # If PracticeQuestions.py is run (instead of imported as a module), call # the main() function: if __name__ == '__main__': main()
true
fba737b12fbc4502df572df73ea97c82c72cd1e2
JoseALermaIII/python-tutorials
/pythontutorials/books/wikibook/Chapter 10/C10-1_WhatMonth.py
317
4.28125
4
#!/usr/bin/env python3 # ~*~ coding: utf-8 ~*~ which_one = int(input("What month (1-12)? ")) months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] if 1 <= which_one <= 12: print("The month is", months[which_one - 1])
false
1a79cb6a78f16f01a05787cfdce9e1450854abf7
JoseALermaIII/python-tutorials
/pythontutorials/books/AutomateTheBoringStuff/Ch05/Projects/P1_gameInventory.py
1,510
4.28125
4
"""Fantasy game inventory This program models a player's inventory from a fantasy game. You are creating a fantasy video game. The data structure to model the player’s inventory will be a :obj:`dictionary <dict>` where the keys are :obj:`string <str>` values describing the item in the inventory and the value is an :obj:`integer <int>` value detailing how many of that item the player has. For example, the dictionary value:: {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} means the player has 1 rope, 6 torches, 42 gold coins, and so on. Write a function named :meth:`displayInventory` that would take any possible “inventory” and display it like the following:: Inventory: 12 arrow 42 gold coin 1 rope 6 torch 1 dagger Total number of items: 62 Attributes: stuff (dict): Dictionary with item names as keys and their counts as values. """ stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} def displayInventory(inventory: dict) -> None: """Display inventory Displays each key in a given inventory dictionary. Args: inventory: Inventory dictionary to display. Returns: None. Prints out inventory. """ print("Inventory:") item_total = 0 for k, v in inventory.items(): item_total += v print(str(v) + " " + k) print("Total number of items: " + str(item_total)) def main(): displayInventory(stuff) if __name__ == '__main__': main()
true
50cb84981c643909aa313177e29448bed23593aa
JoseALermaIII/python-tutorials
/pythontutorials/Udacity/CS101/Lesson 22 - How to Have Infinite Power/Q10-Palindromes.py
599
4.34375
4
# Define a procedure is_palindrome, that takes as input a string, and returns a # Boolean indicating if the input string is a palindrome. # Base Case: '' => True # Recursive Case: if first and last characters don't match => False # if they do match, is the middle a palindrome? def is_palindrome(s): if s == '': return True else: if s[0] != s[-1]: return False return is_palindrome(s[1:-1]) print(is_palindrome('')) # >>> True print(is_palindrome('abab')) # >>> False print(is_palindrome('abba')) # >>> True print(is_palindrome('abaaba')) # >>> True
true
c29220cc90ab01805af5432b37dac99629f6dd77
JoseALermaIII/python-tutorials
/pythontutorials/books/AutomateTheBoringStuff/Ch04/P3_myPets.py
359
4.1875
4
"""My pets This program checks if a given pet's name is in a list of pet names. """ def main(): myPets = ['Zophie', 'Pooka', 'Fat-tail'] print('Enter a pet name:') name = input() if name not in myPets: print('I do not have a pet named ' + name) else: print(name + ' is my pet.') if __name__ == "__main__": main()
true
05705e8fd6e6b0a130647ff0143d0c4d2899351c
JoseALermaIII/python-tutorials
/pythontutorials/Udacity/CS101/Lesson 24 - Problem Set 6 Starred/Q2-Khayyam Triangle.py
1,652
4.125
4
# Double Gold Star # Khayyam Triangle # The French mathematician, Blaise Pascal, who built a mechanical computer in # the 17th century, studied a pattern of numbers now commonly known in parts of # the world as Pascal's Triangle (it was also previously studied by many Indian, # Chinese, and Persian mathematicians, and is known by different names in other # parts of the world). # The pattern is shown below: # 1 # 1 1 # 1 2 1 # 1 3 3 1 # 1 4 6 4 1 # ... # Each number is the sum of the number above it to the left and the number above # it to the right (any missing numbers are counted as 0). # Define a procedure, triangle(n), that takes a number n as its input, and # returns a list of the first n rows in the triangle. Each element of the # returned list should be a list of the numbers at the corresponding row in the # triangle. def triangle(n): trianglelist = [] # Initialize row 0 currentrow = [1] # Initialize row 1 for count in range(0, n): trianglelist.append(currentrow) nextrow = [] previouselement = 0 for element in currentrow: nextrow.append(element + previouselement) previouselement = element nextrow.append(previouselement) currentrow = nextrow return trianglelist # For example: print(triangle(0)) # >>> [] print(triangle(1)) # >>> [[1]] print(triangle(2)) # >>> [[1], [1, 1]] print(triangle(3)) # >>> [[1], [1, 1], [1, 2, 1]] print(triangle(6)) # >>> [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]
true
f4c3a144a69f0ed7ae7bfd003c25fdcb00694a0e
JoseALermaIII/python-tutorials
/pythontutorials/Udacity/CS101/Lesson 20 - Problem Set Optional/Q1-Shift a Letter.py
334
4.1875
4
# Write a procedure, shift, which takes as its input a lowercase letter, # a-z and returns the next letter in the alphabet after it, with 'a' # following 'z'. def shift(letter): if letter < 'z': return chr((ord(letter) + 1)) return 'a' print(shift('a')) # >>> b print(shift('n')) # >>> o print(shift('z')) # >>> a
true
637f70aa5742b06778a006baab53713a29348944
JoseALermaIII/python-tutorials
/pythontutorials/Udacity/CS101/Lesson 13 - Problem Set Optional/Q1-Exploring List Properties.py
330
4.21875
4
# Investigating adding and appending to lists # If you run the following four lines of codes, what are list1 and list2? list1 = [1,2,3,4] list2 = [1,2,3,4] list1 = list1 + [5, 6] list2.append([5, 6]) # to check, you can print them out using the print statements below. print "showing list1 and list2:" print list1 print list2
true
c5b14ce130c44c87f96865dc72d5f972c4bf6dcf
JoseALermaIII/python-tutorials
/pythontutorials/books/wikibook/Chapter 08/C8-2_Absolute_Value.py
284
4.375
4
#!/usr/bin/env python3 a = 23 b = -23 def absolute_value(n): if n < 0: n = -n return n if absolute_value(a) == absolute_value(b): print("The absolute values of", a, "and", b, "are equal.") else: print("The absolute values of", a, "and", b, "are different.")
true
4ed6c7a7ee4cfb9a6000cf552f94891235ff767f
JoseALermaIII/python-tutorials
/pythontutorials/books/wikibook/Chapter 05/C5-Exercise1-2.py
560
4.34375
4
#!/usr/bin/env python3 # Write a program that asks the user of a Login Name and Password. Then when # they type "lock", they need to type in their name and password to unlock the # program. name = input('Set name: ') password = input('Set password: ') while 1 == 1: nameguess="" passwordguess="" key="" while (nameguess != name) or (passwordguess != password): nameguess = input('Name? ') passwordguess = input('Password? ') print("Welcome,", name, ". Type lock to lock.") while key != "lock": key = input("")
true
17136d7fe4c2410316e4471f244fb68b9c93683e
JoseALermaIII/python-tutorials
/pythontutorials/books/wikibook/Chapter 10/C10-2_Demolist.py
1,027
4.34375
4
#!/usr/bin/env python3 # ~*~ coding: utf-8 ~*~ demolist = ["life", 42, "the universe", 6, "and", 9] print("demolist = ", demolist) demolist.append("everything") print("after 'everything' was appended demolist is now:") print(demolist) print("len(demolist) =", len(demolist)) print("demolist.index(42) =", demolist.index(42)) print("demolist[1] =", demolist[1]) # Next we will loop through the list for c in range(len(demolist)): print("demolist [", c, "] =", demolist[c]) # Better way to loop for c, x in enumerate(demolist): print("demolist [", c, "] =", x) del demolist[2] print("After 'the universe' was removed demolist is now: ") print(demolist) if "life" in demolist: print("'life' was found in demolist") else: print("'life' was not found in demolist") if "amoeba" in demolist: print("'amoeba' was found in demolist") if "amoeba" not in demolist: print("'amoeba' was not found in demolist") another_list = [42,7,0,123] another_list.sort() print("The sorted another_list is", another_list)
false
6d50253e1f8a63c050a822e93ef2a4e776751497
JoseALermaIII/python-tutorials
/pythontutorials/Udacity/CS101/Lesson 10 - How to Solve Problems/Q21-Define Simple nextDay.py
732
4.46875
4
### ### Define a simple nextDay procedure, that assumes ### every month has 30 days. ### ### For example: ### nextDay(1999, 12, 30) => (2000, 1, 1) ### nextDay(2013, 1, 30) => (2013, 2, 1) ### nextDay(2012, 12, 30) => (2013, 1, 1) (even though December really has 31 days) ### def nextDay(year, month, day): """ Returns the year, month, day of the next day. Simple version: assume every month has 30 days. """ # YOUR CODE HERE if month == 12 and day == 30: return (year + 1, 1, 1) elif day == 30: return (year, month + 1, 1) else: return (year, month, day + 1) # Test routines print(nextDay(1999, 12, 30)) print(nextDay(2013, 1, 30)) print(nextDay(2012, 12, 30))
true
8f5e99c0f03d6133347aae8844579c1a4560eb9c
JoseALermaIII/python-tutorials
/pythontutorials/books/CrackingCodes/Ch13/PracticeQuestions.py
1,251
4.21875
4
"""Chapter 13 Practice Questions Answers Chapter 13 Practice Questions via Python code. """ def main(): # 1. What do the following expressions evaluate to? print(17 % 1000) print(5 % 5) # 2. What is the GCD of 10 and 15? # Don't do this - imports should be at the top of the file from pythontutorials.books.CrackingCodes.Ch13.cryptomath import gcd print(gcd(10, 15)) # 3. What does spam contain after executing spam, eggs = 'hello', 'world'? spam, eggs = 'hello', 'world' print(spam) # 4. The GCD of 17 and 31 is 1. Are 17 and 31 relatively prime? if not gcd(17, 31) == 1: print("No") else: print("Yes") # 5. Why aren't 6 and 8 relatively prime? print(gcd(6, 8)) # 6. What is the formula for the modular inverse of A mod C? # Hint: check page 183 SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.' print("The modular inverse of %s mod %s is number %s such that (%s * %s) mod %s == %s" % (SYMBOLS[0], SYMBOLS[2], SYMBOLS[34], SYMBOLS[0], SYMBOLS[34], SYMBOLS[2], SYMBOLS[-14])) # If PracticeQuestions.py is run (instead of imported as a module), call # the main() function: if __name__ == '__main__': main()
true
146866a039f4f20b4b2dd02dbb8911093c2bf0ad
JoseALermaIII/python-tutorials
/pythontutorials/Udacity/CS101/Lesson 11 - How to Manage Data/Q05-Countries.py
358
4.1875
4
# Given the variable countries defined as: # Name Capital Populations (millions) countries = [['China','Beijing',1350], ['India','Delhi',1210], ['Romania','Bucharest',21], ['United States','Washington',307]] # Write code to print out the capital of India # by accessing the list print countries[1][1]
false
f9b4c4ef679915e4b6b4d78e2553a8cfe8a20962
JoseALermaIII/python-tutorials
/pythontutorials/books/CrackingCodes/Ch03/PracticeQuestions.py
1,205
4.53125
5
"""Chapter 3 Practice Questions Answers Chapter 3 Practice Questions via Python code. """ def main(): spam = "Cats" # 1. If you assign spam = "Cats", what do the following lines print? print(spam + spam + spam) print(spam * 3) # 2. What do the following lines print? print("Dear Alice, \nHow are you?\nSincerely,\nBob") print("Hello" + "Hello") spam = "Four score and seven years is eighty seven years." # 3. If you assign spam = "Four score and seven years is eighty seven years.", # what would each of the following lines print? print(spam[5]) print(spam[-3]) print(spam[0:4] + spam[5]) print(spam[-3:-1]) print(spam[:10]) print(spam[-5:]) print(spam[:]) # 4. Which window displays the >>> prompt, the interactive shell or the file editor? # Hint: Check page 30 answers = ["interactive shell", "file editor"] print("The window that displays the >>> prompt is the %s." % answers[-2 + 5 * 7 * 9 * 0]) # 5. What does the following line print? #print("Hello, world!") # If PracticeQuestions.py is run (instead of imported as a module), call # the main() function: if __name__ == '__main__': main()
true
5864bd1872bca887a08268f17c64e20b2fe799b2
NareshKurukuti/Python
/1_pythonBasics/2_list.py
1,215
4.5
4
#List: List are mutable and square bracket is used for Lists nums = [12,45, 35, 23, 34, 55] print(nums) print(nums[0]) print(nums[-1]) print(nums[1:2]) names = ["naresh", "nar", "kn", "nk"] print(names) values = [9.5, "naresh", 26] print(values) print("\n multiple lists in single lists") mil = [nums, names] print(mil) print("\n append") nums.append(77) print(nums) print("\n insert a value at the index of 2") nums.insert(2, 22) print(nums) print("\n remove the list value based on index") nums.remove(nums[0]) print(nums) print("\n remove the list value based on value") nums.remove(45) print(nums) print("\n remove the list value based on index using pop") nums.pop(1) print(nums) print("\n remove the last value in the list using pop") nums.pop() print(nums) print("\n delete or remove the multiple values in the list") del nums[2:] print(nums) print("\n add multiple values in list") nums.extend([12,44,35,79]) print(nums) print("\n in built functions in list like min()") print(min(nums)) print("\n in built functions in list like max()") print(max(nums)) print("\n in built functions in list like sort()") nums.sort() print(nums) print("\n clear() of the list") nums.clear() print(nums)
true
685ecd7c2a27dad831cc1f40cfe3b8358ab7a1dd
NareshKurukuti/Python
/tryAndExcept/tryAndExceptExample.py
475
4.15625
4
print("give two number i will divide them") print("enter e or exit to exit") while True: firstNumber = input('enter first number ') if firstNumber == "e" or firstNumber == "exit": break secondNumber = input('enter second number ') if secondNumber == "e" or secondNumber == "exit": break try: answer = int(firstNumber)/int(secondNumber) print(answer) except ZeroDivisionError: print('the answer is 0 or zero')
true
f2389aaa6557881320745ad393e0e15e39c38392
ilovejnote/PythonProgrammingTutorial
/Py_01_00_Function.py
704
4.1875
4
# -*- coding: utf-8 -*- # To understand why in math we use "S = π*r*r" ; And To calculate 1 to 100 we use "∑". in math call it abstract # In Python we call this math method named function. In this way we don't need to aways write 3.14 * x * x, just use area_of_circle(x),once # python surport function and inside python there already have lots functions. you can use these functions directly. # In pythone function is one of method of abstract. # For example use abs() we can check it first form command line of interactive "help(abs)" # >>> help(abs) #Help on built-in function abs in module builtins: # #abs(x, /) # Return the absolute value of the argument. #>>> print(abs(100), abs(-20))
true
178ef6ace05e09ff3ae083123f6ebf5167a930f3
camargo800/Python-projetos-PyCharm
/PythonExercicios/ex014.py
387
4.25
4
# Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit. c = float(input('informe a temperatura em celsius: ')) f = ((9*c)/5)+32 print('a temperatura em fahrenheit é igual a {:.1f}'.format(f)) f = float(input('informe a temperatura em fahrenheit: ')) c = ((f-32)*5)/9 print('a temperatura em celsius é igual a {:.1f}'.format(c))
false
1a9a07ee2f9b4f91d483f2b18c9fd77efde67627
camargo800/Python-projetos-PyCharm
/PythonExercicios/ex059.py
1,498
4.125
4
# Crie um programa que leia dois valores e mostre um menu na tela: # [ 1 ] somar # [ 2 ] multiplicar # [ 3 ] maior # [ 4 ] novos números # [ 5 ] sair do programa # Seu programa deverá realizar a operação solicitada em cada caso. from time import sleep n1 = int(input('Digite o primeiro valor: ')) n2 = int(input('Digite o segundo valor: ')) opcao = 0 while opcao != 5: sleep(1) print(''' [1] somar [2] multiplicar [3] maior [4] novos números [5] sair''') opcao = int(input('>>>>>Qual a sua opção: ')) if opcao == 1: soma = n1 + n2 print('\033[31m{} + {} =\033[m \033[32m{}\033[m'.format(n1, n2, soma)) elif opcao == 2: multiplicacao = n1 * n2 print('\033[31m{} x {} =\033[m \033[32m{}\033[m'.format(n1, n2, multiplicacao)) elif opcao == 3: if n1 > n2: maior = n1 print('O maior número é \033[32m{}\033[m.'.format(maior)) elif n2 > n1: maior = n2 print('O maior número é \033[32m{}\033[m.'.format(maior)) elif n1 == n2: print('\033[7mNão há maior entre eles porque os números são iguais.\033[m') elif opcao == 4: print('Informe os novos números.') n1 = int(input('Digite o primeiro valor: ')) n2 = int(input('Digite o segundo valor: ')) elif opcao == 5: print('Finalizando...') sleep(1) else: print('Opção inválida. Tente novamente.') print('Fim do programa.')
false
d88d37d2e5ecbe3c8ea3f5e82f2d549592cab776
RaiManish3/ProjectEulerCode
/problems41_60/pe57_square_root_convergents.py
1,092
4.125
4
import time start=time.time() ##################################################################################### # ===============================EXECUTION TIME: 0.01s=============================== """ THE IDEA ALTHOUGH SIMPLE, IS RATHER NON-TRIVIAL. FOR EACH ITERATION I PLANNED TO CALCULATE ( 2+ RECIPROCAL OF PREVIOUS FRACTION ) EXAMPLE: FIRST ITERATION: 2+ 1/2 = 5/2 | MAIN FRACTION IS OBTAINED BY ADDING RECIPROCAL OF THIS TO 1 = 7/5 SECOND ITERATION: 2+ 2/5=12/5 | MAIN FRACTION = 1+5/12=17/12 THIRD ITERATION: 2+5/12= 29/12 | MAIN FRACTION = 1+ 12/29 =41/29 AND SO ON... THE CODE CAN BE MADE EFFECTIVE FOR HIGHER ITERATIONS IF WE USE LISTS ADDITION. """ def main(no_of_iterations): num,denom=1,2 count=0 # lst=[] for x in xrange(1,no_of_iterations): tmp_num=2*denom+num tmp_denom=denom fraction_num=str(tmp_num+tmp_denom) fraction_denom=str(tmp_num) if len(fraction_num)>len(fraction_denom): count+=1 # lst.append([fraction_num,fraction_denom]) denom=tmp_num num=tmp_denom return count # print main(1000) # print time.time()-start
true
aa14e0eb73d54059f97d4afb70d1e04828e3ddcc
Ericlkl/Data-Manipulation-In-Bash
/data/csv2sqlite.py
2,790
4.28125
4
""" Convert delimiter separated files to SQLite3 databases Harry Scells March 2017 """ import argparse import csv import io import sqlite3 import sys def read_csv(input_file: io.IOBase, delim=',', quote='"') -> list: """ Take a delimiter separated file and return a list of tuples representing the rows. :param input_file: File to read :param delim: Delimiter of the file :param quote: :return: """ csv_reader = csv.reader(input_file, delimiter=delim, quotechar=quote) csv_rows = [] for row in csv_reader: current_row = [] for r in [str(x) for x in row]: if r.isdigit(): current_row.append(int(r)) elif r.replace('.', '', 1).isdigit(): current_row.append(float(r)) else: current_row.append(r) csv_rows.append(current_row) return csv_rows if __name__ == '__main__': argparser = argparse.ArgumentParser(description= 'Convert delimiter-separated files to SQLite3') argparser.add_argument('-d', '--delimiter', help='Delimiter used for separating columns', default=',', required=False, type=str) argparser.add_argument('-q', '--quote', help='Quote delimiter used for escaping columns', default='"') argparser.add_argument('--table-name', help='Name for the SQLite3 table', required=False, default='ex', type=str) argparser.add_argument('--contains-headers', help='Does this file have headers?', default=True, type=bool) argparser.add_argument('--input', help='Input delimiter-separated file', default=sys.stdin, required=False, type=argparse.FileType('r')) argparser.add_argument('--output', help='Output filename for SQLite3 file', required=True, type=str) args = argparser.parse_args() # open a connection to db conn = sqlite3.connect(args.output) # get the rows from the csv file rows = read_csv(args.input, args.delimiter, args.quote) # process header info headers = [] if args.contains_headers: # when we have headers, use them, and skip a row headers = ','.join(rows[0]) rows = rows[1:] else: # otherwise just use numbers headers = ','.join([str(x) for x in range(len(rows[0]))]) # create the table conn.execute('CREATE TABLE {} ({})'.format(args.table_name, headers)) # create the parameter substitutions params = ','.join(['?' for x in rows[0]]) # now finally insert the data! conn.executemany('INSERT INTO {} VALUES ({})'.format(args.table_name, params), rows) conn.commit() conn.close()
true
f10aad001730f89836c88723418d3f21f8cf5d0a
jaaron7/projects
/Scale Lookup v3.py
2,314
4.4375
4
# -*- coding: utf-8 -*- """ Created on Tue Nov 26 11:24:16 2019 @author: kraskjo """ # Simple program to lookup notes in a major scale #dictionary to convert user input into integers, used for ScaleLookup function below notes_to_numbers = { "A": 1, "Bb": 2, "B": 3, "C": 4, "Db": 5, "D": 6, "Eb": 7, "E": 8, "F": 9, "Gb": 10, "G": 11, "Ab": 12, } #dictionary to convert integers back into scale notes strings numbers_to_notes = {1: "A", 2: "Bb", 3: "B", 4: "C", 5: "Db", 6: "D", 7: "Eb", 8: "E", 9: "F", 10: "Gb", 11: "G", 12: "Ab",} minor_scale = [] def ScaleLookup(user_root): conversion = notes_to_numbers[user_root] note2 = conversion + 2 if note2 > 12: note2 = numbers_to_notes[(conversion + 2) - 12] else: note2 = numbers_to_notes[conversion + 2] note3 = conversion + 4 if note3 > 12: note3 = numbers_to_notes[(conversion + 4) - 12] else: note3 = numbers_to_notes[conversion + 4] note4 = conversion + 5 if note4 > 12: note4 = numbers_to_notes[(conversion + 5) - 12] else: note4 = numbers_to_notes[conversion + 5] note5 = conversion + 7 if note5 > 12: note5 = numbers_to_notes[(conversion + 7) - 12] else: note5 = numbers_to_notes[conversion + 7] note6 = conversion + 9 if note6 > 12: note6 = numbers_to_notes[(conversion + 9) - 12] else: note6 = numbers_to_notes[conversion + 9] note7 = conversion + 11 if note7 > 12: note7 = numbers_to_notes[(conversion + 11) - 12] else: note7 = numbers_to_notes[conversion + 11] for i in range(2,8): list_note = str('note'+str(i)) major_scale.append(list_note) #print("Here are the notes for the key of " + user_root + " major: " user_root + str(major_scale)) print(major_scale) #print("Here are the notes for the key of " + user_root + " major: " + user_root + note2 + note3 + note4 + note5 + note6 + note7) ScaleLookup((input("In what key are you playing? "))) #
true
5ebbebc5c949bc1ad16d10e974f525dc1ceb93d6
Ishaangg/python-projects
/display_current_tym.py
733
4.21875
4
import time #Import time currentTime = time.time() # use time() function to get current time in seconds(since midnight Jan 1 1970) total_seconds = int(currentTime) # Obtain total seconds (trunketing millisecond) current_second = total_seconds % 60 # Obtain current second using total_seconds total_minutes = total_seconds // 60 # Obtain total minutes till now by uing total_seconds current_minute = total_minutes % 60 # Obtain current minutes from total_minutes % 60 total_hours = total_minutes // 60 # Obtain current hours from total_minutes current_hour = total_hours % 24 # Obtain cuurent hour from total_minutes % 60 print(f"current tym is {current_hour} : {current_minute} : {current_second} GMT") #print current time
true
b5f981e61e9d5d6e625da423f5c0b122548818a1
nerdalertsyd/My-Own-Recursion
/My own recursion.py
1,098
4.15625
4
#------------------------------- # My Own Recursion # Sydney Loerzel # December 12, 19 #------------------------------- import turtle chim = turtle.Turtle() wn = turtle.Screen() wn.bgcolor("black") def tree(branch,chim): if branch > 1: #exit case, will keep calling while the branch length is longer than 1 chim.forward(branch) #go forward chim.right(20) #turn right tree(branch-10,chim) #makes a branch length of 10 units shorter of self chim.left(40) #turn left tree(branch-10,chim) #makes a branch length of 10 units short of calling self again chim.right(20) #turn right chim.backward(branch) #go backwards to the next branch def main(): chim.color("green") tree(60,chim) #call the first function chim.right(90) chim.color("white") tree(60,chim) #call the first function facing a different way chim.right(90) chim.color("blue") tree(60,chim) chim.right(90) chim.color("white") tree(60,chim) #repeated until a full circle is made wn.exitonclick() main()
true
8f5beca1ba1f0528bee091caa0d1aebb9d038c1d
LDavis21/Assignments.github.io
/assignment1/LPHW/LPHW.py
1,620
4.5
4
#Exercise 1 print("hello world!") print("hello again") print("i like typing this.") print("this is fun.") print("yay! printing.") print("i'd much rather you 'not'.") print('i "said" do not touch this.') #exercise 2 # a comment, this is so you can read your program later. # anything after the # is ignored by python. print("I could have code like this.") # you can also use a comment to "disable" or comment out code: # print("this won't run") print("this will run.") print("i will not count my chickens:") print("hens", 25 + 30 / 6) print("roosters", 100 - 25 * 3 % 4) #Exercise 3 print("now i will count my eggs:") print( 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) print("is it true that 3 + 2 < 5 - 7?") print(3 + 2 < 5 - 7) print("what is 3 + 2?", 3 + 2) print("what is 5 - 7?", 5 - 7) print("oh, that's why it's false.") print("how about some more.") print("is it greater?", 5 > -2) print("is it greater or equal?", 5 >= -2) print("is it less or equal?", 5 <= -2) #excercise 4 cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90 cars_not_driven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_car average_passengers_per_car = passengers / cars_driven print("there are", cars, "cars available.") print("there are only", drivers, "drivers available.") print("there will be", cars_not_driven, "empty cars today.") print("we can transport", carpool_capacity, "people today.") print("we have", passengers, "to carpool today.") print("we need to put about", average_passengers_per_car, "in each car.")
true
2106d0ba67f64329de3a24d0980484cfd6592ce1
HarshitGupta150/hacktoberfest2021-2
/Binary Tree/binarytree.py
2,651
4.125
4
#1. write python code for binary tree with traversal, insertion, deletion # and searching methods. class Node: def __init__(self, key): self.left = None self.right = None self.val = key def insert(root, key): if root is None: return Node(key) else: if root.val == key: return root elif root.val < key: root.right = insert(root.right, key) else: root.left = insert(root.left, key) return root def inorder(root): if root: inorder(root.left) print(root.val, end=" ") inorder(root.right) def preorder(root): if root: print(root.val,end=" ") preorder(root.left) preorder(root.right) def postorder(root): if root: postorder(root.left) postorder(root.right) print(root.val,end=" ") def search(root, key): if (root == None): return False if (root.val == key): return True res1 = search(root.left, key) if res1: return True res2 = search(root.right, key) return res2 def deleteDeepest(root,d_node): q = [] q.append(root) while(len(q)): temp = q.pop(0) if temp is d_node: temp = None return if temp.right: if temp.right is d_node: temp.right = None return else: q.append(temp.right) if temp.left: if temp.left is d_node: temp.left = None return else: q.append(temp.left) def deletion(root, key): if root == None : return None if root.left == None and root.right == None: if root.key == key : return None else : return root key_node = None q = [] q.append(root) temp = None while(len(q)): temp = q.pop(0) if temp.val == key: key_node = temp if temp.left: q.append(temp.left) if temp.right: q.append(temp.right) if key_node : x = temp.val deleteDeepest(root,temp) key_node.val = x return root r = Node(50) r = insert(r, 30) r = insert(r, 20) r = insert(r, 40) r = insert(r, 70) r = insert(r, 60) r = insert(r, 80) print("inorder:") inorder(r) print("\npreorder:") preorder(r) print("\npostoreder:") postorder(r) key=30 print("\nsearch {}:".format(key),end="") if (search(r, key)): print("found" ) else: print("not found") key = 70 root = deletion(r, key) print("The tree after the deletion:") inorder(root)
true
7137d9fa29d734c26d0f327a39cd217e493c75dd
gsGIS76234/OOSA_Week1
/taskFour.py
658
4.3125
4
#!/bin/env python3 # Purpose: use nested loops to print square coords and colours # Loop through x-coords for x in range(1,9): # Loop through y-coords for y in range(1,9): # Odd x and odd y coords are black if x%2 == 1 and y%2 == 1: sqVal = "Black" # Odd x and even y coords are white elif x%2 == 1 and y%2 == 0: sqVal = "White" # Even x and even y coords are black elif x%2 == 0 and y%2 == 0: sqVal = "Black" # Even x and odd y coords are white elif x%2 == 0 and y%2 == 1: sqVal = "White" print(f'Square ({x},{y}) is {sqVal}')
false
a42debfe0f14e54a35233b9c26e94105d8f1df68
abiryusuf/Data_Structures_And_Algorithms
/com/data_structures_algorithms/03_Sets_Maps/3.1.1_Sets_Abstract.py
1,677
4.15625
4
""" A set is a container that stores a collection of unique values over a given comparable domain in which the stored values have no particular ordering """ """ intersect(setB): Creates and returns a new set that is the intersection of this set and setB. The intersection of sets A and B contains only those elements that are in both A and B. Neither set A nor set B is modified by this operation. 􏰀 difference( setB ): Creates and returns a new set that is the difference of this set and setB. The set difference, A−B, contains only those elements that are in A but not in B. Neither set A nor set B is modified by this operation. """ abir = set() abir.add("Math-112") abir.add("HIST-121") abir.add("ECON-101") abir.add("CSCI-121") roberts = set() roberts.add("ECON-101") roberts.add("ANTH-230") roberts.add("CSCI-121") roberts.add("POL-101") """ Next, we determine if the two students are taking the exact same courses. If not, then we want to know if they are taking any of the same courses. We can do this by computing the intersection between the two sets. """ if abir == roberts: print("Taking same courses") else: sameCourses = abir.intersection(roberts) if sameCourses == 0: print("Abir and Roberts are taking any of " + "the same cour se.") else: print("They are taking some of the " + "same courses") for course in sameCourses: print("They are taking same courses: ", course) uniqueCourse = abir.difference(roberts) for course in uniqueCourse: print("They are taking difference courses: ", course) union = abir.union(roberts) for c in union: print(c)
true
bae806f4dcbc3109ca23e39d80c232d10a81e17a
vishalGit7/Practice
/test_circle.py
1,331
4.34375
4
import unittest from example1 import Circle class TestCircleCreation(unittest.TestCase): def test_creating_circle_with_numeric_radius(self): # Define a circle 'c1' with radius 2.5, and check if # the value of c1.radius is equal to 2.5 or not. c1=Circle(2.5) self.assertEqual(c1.radius,2.5) def test_creating_circle_with_negative_radius(self): # Define a circle 'c' with radius -2.5, and check # if it raises a ValueError with the message # "radius must be between 0 and 1000 inclusive". with self.assertRaises(ValueError): c1=Circle(-2.5) c1.radius def test_creating_circle_with_greaterthan_radius(self): # Define a circle 'c' with radius 1000.1, and check # if it raises a ValueError with the message # "radius must be between 0 and 1000 inclusive". with self.assertRaises(ValueError): c1=Circle(1000.1) c1.radius def test_creating_circle_with_nonnumeric_radius(self): # Define a circle 'c' with radius 'hello' and check # if it raises a TypeError with the message # "radius must be a number". with self.assertRaises(TypeError): c1=Circle("Hello") c1.radius
true
d338c7f020849c321a022e3df028590b89606691
dhumindesai/Problem-Solving
/educative/subsets/subsets.py
406
4.1875
4
''' Time : O(N*2^N) Space : O(N*2^N) ''' def find_subsets(nums): subsets = [[]] for num in nums: for i in range(len(subsets)): new_set = list(subsets[i]) new_set.append(num) subsets.append(new_set) return subsets def main(): print("Here is the list of subsets: " + str(find_subsets([1, 3]))) print("Here is the list of subsets: " + str(find_subsets([1, 5, 3]))) main()
true
7d41ac7e6ca1d825407b03976ab1f0bfda76058f
Aziine/learn_python
/gpa.py
899
4.46875
4
print "Welcome to the GPA Calculator." print "Enter all your grades, one per line" print "Enter a blank line to desighnate the end" points = {"A+": 4.0, "A":4.0, "A-": 3.67, "B+":3.33, "B":3.0, "B-":2.67, "C+":2.33, "C": 2.0, "C-": 1.67, "D+":1.33, "D":1.0, "F":0.0} #we set a dictionary of grades and points num_courses = 0 total_points = 0 done = False while not done: grade = raw_input(">") #readline from a user if grade == " ": #empty line was entered done = True elif grade not in points: #if unrecognized grade entered print "Unknown grade '{0}' being ignored".format(grade) else: num_courses += 1 # the same as num_courses = num_courses + 1 total_points += points[grade] # the same as total_points = total_points + points[grades] if num_courses > 0: print "Your GPA is {0:.3}".format(total_points/num_courses)
true
12f386b1a997d0aec3f6fe72d8a4635d9e738d23
Aziine/learn_python
/ex21.py
1,557
4.5625
5
def add(a, b):#Our function is called with two arguments: a and b. #You might say this as, "I add a and b then return them." print "ADDING %d + %d." % (a, b) # We print out what our function is doing, in this case "ADDING." return a + b # Then we tell Python to do something kind of backward: we return the addition of a + b. #Python adds the two numbers. # Then when the function ends, any line that runs it will be able to assign this a + b result to a variable. def substract(a,b): print 'Substracting %d - %d.' % (a, b) return a - b def multiply(a, b): print 'Multiplying %d * %d.' % (a, b) return a * b def divide(a, b): print 'Dividing %d/%d.' % (a, b) return a/b print "Let's do some math using just functions." age = add(30, 5) SAT = multiply(8, 100) height = substract (200, 28) weight = divide(120, 2) iq = multiply (70, 2) #print "Age: %d, SAT: %d, Height: %d, Weight: %d, iq: %d" % (age, SAT, height, weight, iq) print 'Here is the puzzle!' #what = add(age , substract(height, multiply(weight, divide(iq, 2)))) #print "That becomes: ", what, "Can you do it by hand?" #another_what = divide(height, multiply(weight, substract(iq, add(SAT, 1))))#I'm taking the return value of one #function and using it as the argument of another function. #I'm doing this in a chain so that I'm kind of creating a formula using the functions #print "This becomes: ", another_what, "Can you do it mentally?" result = divide(add(24.0,26.0), add(100.0,44.0)) print result
true
e79810ffda71f3b791284d6e022c7d7dbf9677db
inrahulsingh/PracticePrograms
/makesTwenty.py
289
4.1875
4
#MAKES TWENTY: Given two integers, return True if the sum of the integers is 20 or if one of the integers is 20. If not, return False def makes_twenty(n1,n2): if n1+n2==20 or n1==20 or n2==20: return True else: return False result=makes_twenty(2,20) print(result)
true
b8b33e2750696938ebb947066e1b3884ee71da09
inrahulsingh/PracticePrograms
/paperdoll.py
256
4.15625
4
#PAPER DOLL: Given a string, return a string where for every character in the original there are three characters def paperdoll(text): result='' for char in text: result +=char*3 return result presult=paperdoll('rahul') print(presult)
true
cf82a5d9c7b51f3bea2845a3ce28d19081f58676
edigiorgio/PythonCode
/mathTest.py
1,738
4.1875
4
#Eric DiGiorgio #COP 1000 #Professor Kodsey #February 17, 2018 import random #This program is a basic math test that uses the random function to create different problems #Defining our main function def main(): #Here we declare our variables counter = 0 studentName = "" averageRight = 0.0 right = 0 number1 = 0 number2 = 0 answer = 0.0 studentName = inputNames(studentName) #A loop to run the program again while counter < 10: number1, number2 = getNumber() answer = getAnswer(number1, number2, answer) right = checkAnswer(number1, number2, answer, right) counter = counter + 1 averageRight = results(right, averageRight) displayInfo(right, averageRight, studentName) def inputNames(studentName): studentName = input("Enter Student Name:") return studentName def getNumber(): number1 = random.randint(1,500) number2 = random.randint(1,500) return number1, number2 def getAnswer(number1, number2, answer): print("What is the answer to the following equation") print(number1) print("+") print(number2) answer = eval(input("What is the sum:")) return answer def checkAnswer(number1, number2, answer, right): if answer == number1 + number2: print("Right") right = right + 1 else: print("Wrong") return right def results(right, averageRight): averageRight = right / 10 return averageRight def displayInfo(right, averageRight, studentName): print("Information for student:", studentName) print("The number right:", right) print("The average right is:",averageRight) main()
true
342aa92fab545d90d85e5dbe67942f23a647065d
edigiorgio/PythonCode
/Chapter2_Exercise5.py
1,703
4.40625
4
#Distancetraveledcalculator.py #Eric DiGiorgio #Chapter 2 Exercise 5 #January 19, 2018 #This program is an input output game with 3 math questions #Each question only has one answer and will tell you if you get it right or wrong #This is my 4 variables being declared and initialized Distance1 = 300 Distance2 = 480 Distance3 = 720 Name = 0 def main(): #Display message welcoming you to my game print ("Welcome to my little math game") print ("Lets test your math skills") #First input question Name = input ("What is your name? ") print ("Thank you ", Name) #Response to input question 1 #The start of our math questions Distance1 = eval (input("""Question 1, if a car is traveling at 60 mph, how far will it travel in 5 hours? """)) if Distance1 == 300: #I used if statements to give different outcomes based on answers print ("That is correct, good job ", Name) else : #Else statements are for anything other than the correct answer print ("No ", Name, "The correct answer is 300") Distance2 = eval (input("""Question 2, if a car is traveling at 60 mph, how far will it travel in 8 hours? """)) if Distance2 == 480: print ("That is correct, good job ", Name) else : print ("No ",Name, "The correct answer is 480") Distance3 = eval (input("""Question 3, if a car is traveling at 60mph, how far will it travel in 12 hours? """)) if Distance3 == 720: print ("That is correct, good job ", Name) else : print ("No ",Name, "The correct answer is 720") #Just a little thank you message for playing print ("Well thank you for playing...")
true
3cc32b95130004b4b19d8669097b78642dd9243f
edigiorgio/PythonCode
/Lab 9.5 array.py
2,402
4.25
4
#Eric DiGiorgio #COP 1000 #Professor Kodsey #February 26, 2018 #This program calculates the savings on your energy bills spanning over 2 years #The main function def main(): #Our priming read to get the machine going endProgram = "no" #Our while loop to keep the program going while endProgram.lower() == "no": notGreenCost = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]#Initialize our arrays(aka lists) goneGreenCost = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] savings = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] #Call our functions getNotGreen(notGreenCost, months) getGoneGreen(goneGreenCost, months) energySaved(notGreenCost, goneGreenCost, savings, months) displayInfo(notGreenCost, goneGreenCost, savings, months) #Ask if we want to run the program again endProgram = input("Do you want to end the program? Yes or No") #Our functions def getNotGreen(notGreenCost, months): counter = 0 while counter < len(months):#This runs our functions until it reaches the end of the list for months notGreenCost[counter] = float(input("Enter NOT GREEN energy costs for " + str(months[counter]) + ":"))#This is asking the user for input counter += 1 return notGreenCost def getGoneGreen(goneGreenCost, months): counter = 0 while counter < len(months): goneGreenCost[counter] = float(input("Enter GONE GREEN costs for " + str(months[counter]) + ":")) counter += 1 return goneGreenCost def energySaved(notGreenCost, goneGreenCost, savings, months): counter = 0 while counter < len(months): savings[counter] = notGreenCost[counter] - goneGreenCost[counter] counter += 1 return savings def displayInfo(notGreenCost, goneGreenCost, savings, months): counter = 0 while counter < len(months): print("Information for " + months[counter]) print("Savings $" + str(savings[counter])) print("Not Green Costs $" + str(notGreenCost[counter])) print("Gone Green Costs $" + str(goneGreenCost[counter])) counter += 1 main()
true
175ab73e2f670c2951a83d33c78d64a62b85e784
giselacontreras/CSC110
/guess_the_number.py
1,293
4.125
4
# # Pearce Phanawong # guess_the_number.py # Description: This program will ask the user to input a number, then # ask again for another number. If the second is the # same as the first, the user wins. The user has two # attempts, and if both are failed, the user loses. # from os import _exit as exit n = input('Enter number to be guessed between 10 and 100, inclusive:\n') if n.isnumeric() == True: n = int(n) else: print(n,'is not 10-100, inclusive.') exit(0) if n < 10 or n > 100: print(n,'is not 10-100, inclusive.') exit(0) guess1 = input('First guess:\n') if guess1.isnumeric() == False: print('Guess is invalid.') exit(0) else: guess1 = int(guess1) if guess1 == n: print(guess1, 'is correct! Ending game.') elif guess1 != n: print(guess1, 'is incorrect.') guess2 = input('Second guess:\n') if guess2.isnumeric() == False: print('Guess is invalid.') exit(0) else: guess2 = int(guess2) if guess2 == n: print(guess2, 'is correct! Ending game.') elif guess2 != n: print(guess2, 'is incorrect.') print('You did not guess the number within 2 attempts.') print('The target number was', n) print('Your guesses were', guess1, 'and', guess2)
true
f2533b7676955b3a3735fce6962dc860d0ebc2c6
patruk91/doctests
/poker_hand.py
1,015
4.125
4
def poker_hand(numbers): """ Write a poker_hand function that will score a poker hand. The function will take an array 5 numbers and return a string based on what is inside. >>> poker_hand([1, 1, 1, 1, 1]) 'five' >>> poker_hand([2, 2, 2, 2, 3]) 'four' >>> poker_hand([1, 1, 1, 2, 3]) 'three' >>> poker_hand([2, 2, 3, 3, 4]) 'twopairs' >>> poker_hand([1, 2, 2, 3, 4]) 'pair' >>> poker_hand([1, 1, 2, 2, 2]) 'fullhouse' >>> poker_hand([1, 2, 3, 4, 6]) 'nothing' """ poker_values = [numbers.count(number) for number in set(numbers)] if 5 in poker_values: return 'five' elif 4 in poker_values: return 'four' elif 3 in poker_values and len(poker_values) == 3: return 'three' elif len(poker_values) == 5: return 'nothing' elif len(poker_values) == 4: return 'pair' elif len(poker_values) == 3: return 'twopairs' elif len(poker_values) == 2: return 'fullhouse'
false
1cc6d7f03e0fa61a91ec6259e010ba4f3d0c8baa
MehtapIsik/algebra
/algebra/operations.py
301
4.15625
4
def sum(num1, num2): """ This function takes the sum of two numbers. Paramaters ---------- num1, float A number. num2, float A number. """ return num1 + num2 def product(num1, num2): """ This function takes the product of two numbers. """ return num1 * num2
true
d77f2089349a361473671de7c05f9d09e1cb258d
SomGitHub2018/PythonCodes
/thinkpython_cartalk1.py
1,638
4.375
4
# -*- coding: utf-8 -*- from __future__ import print_function, division """This module contains a code example related to Think Python, 2nd Edition by Allen Downey http://thinkpython2.com Copyright 2015 Allen Downey License: http://creativecommons.org/licenses/by/4.0/ Give me a word with three consecutive double letters. I’ll give you a couple of wordsthat almost qualify, but don’t. For example, the word committee, c-o-m-m-i-t-t-e-e. It would be great except for the ‘i’ that sneaks in there. Or Mississippi: M-i-s-s-i-s-s-i-p-p-i. If you could take out those i’s it would work. But there is a word that has threeconsecutive pairs of letters and to the best of my knowledge this may be the only word.Of course there are probably 500 more but I can only think of one. What is the word? """ def is_triple_double(word): """Tests if a word contains three consecutive double letters. word: string returns: bool """ i = 0 count = 0 while i < len(word)-1: if word[i] == word[i+1]: count = count + 1 if count == 3: return True i = i + 2 else: count = 0 i = i + 1 return False def find_triple_double(): """Reads a word list and prints words with triple double letters.""" fin = open('C:/SomeshFolder/Studies/PGDBM/REVA/PhytonCodes/word.txt') for line in fin: word = line.strip() if is_triple_double(word): print(word) print('Here are all the words in the list that have') print('three consecutive double letters.') find_triple_double() print('')
true
306d3c5d043fa185c60c1687161036f7b4c53639
SomGitHub2018/PythonCodes
/Even Fibonacci numbers.py
1,087
4.15625
4
# -*- coding: utf-8 -*- """ Created on Sun Oct 7 20:33:19 2018 @author: Somesh """ # Find the sum of all the even-valued terms in the Fibonacci sequence which # do not exceed given limit. #Example #Input : limit = 400; #Output : 188. #Explanation : 2 + 8 + 34 + 144 = 188. # Returns sum of even Fibonacci numbers which # are less than or equal to given limit. def evenFibSum(limit) : if (limit < 2) : return 0 # Initialize first two even prime numbers # and their sum ef1 = 0 ef2 = 2 sm= ef1 + ef2 # calculating sum of even Fibonacci value while (ef2 <= limit) : # get next even value of Fibonacci # sequence ef3 = 4 * ef2 + ef1 # If we go beyond limit, we break loop if (ef3 > limit) : break # Move to next even number and update # sum ef1 = ef2 ef2 = ef3 sm = sm + ef2 return sm # Driver code # take input from the user limit = int(input("Enter a limit number: ")) print(evenFibSum(limit))
true
9bd9bc13d693fb8f63877c51ae7268f4e46e5f81
rabbibhumbla/python
/assignoperators.py
581
4.125
4
#!/usr/bin/python### print ('Sample code for all of the arthemetic operators') a=int(input('enter value of a:')) b=int(input('enter value of b:')) c=int(input('enter value of c:')) c+=b print ('Addition assignment- Value of c is',c) c-= b print ('Subtraction assignment- Value of c is',c) c*=b print ('Multiplication assignment- Value of c is',c) c/=b print ('Division assignment- value of c is',c) c%=b print ('Modulus assignment- value of c is',c) c**= b print ('Exponent assignment- value of c is',c) c//= b print ('Floor values assignment - value of c is',c)
true
b5444a32ab292a675357abe1f5a2b49fe4f4a901
renatotnk/UDESC
/4a Fase/PRA/Trabalho/Hashing/hashing_sort.py
2,441
4.125
4
# Código para hashing sort a partir do calculo baseado em endereço # Tamanho da tabela de endereços SIZE = 10 # Nó de fila encadeada simples class Node(object): def __init__(self, data = None): self.data = data self.nextNode = None # Fila encadeada class LinkedList(object): def __init__(self): self.head = None # Inserindo valores sem retirar a ordenação def insert(self, data): newNode = Node(data) if self.head == None or data < self.head.data: newNode.nextNode = self.head self.head = newNode else: current = self.head while current.nextNode != None and current.nextNode.data < data: current = current.nextNode newNode.nextNode = current.nextNode current.nextNode = newNode # Função que ordena uma lista usando Hashing para calculo de endereço def hashing_sort(lista_entrada): # Declarando uma lista de listas encadeadas lista_de_listas = [] for i in range(SIZE): lista_de_listas.append(LinkedList()) # Calculando valor máximo maximum = max(lista_entrada) # Encontrando o endereço de cada valor e inserindo na tabela de endereços for val in lista_entrada: endereco = funcao_hash(val, maximum) lista_de_listas[endereco].insert(val) # Após os valores serem encontrados, a tabela de endereços é impressa for i in range(SIZE): current = lista_de_listas[i].head print("endereco " + str(i), end = ": ") while current != None: print(current.data, end = " ") current = current.nextNode print() # Passando os valores ordenados para a lista passada como entrada index = 0 for i in range(SIZE): current = lista_de_listas[i].head while current != None: lista_entrada[index] = current.data index += 1 current = current.nextNode # Função de hash (espalhamento), que utiliza como base o tamanho da tabela e o maior valor def funcao_hash(num, maximum): # Escalando para que fique sempre entre 0 e 9 endereco = int((num * 1.0 / maximum) * (SIZE-1)) return endereco # Lista de entrada não ordenada lista_entrada = [29, 23, 14, 5, 15, 10, 3, 18, 1] # Imprimindo a lista não ordenada print("\nLista de entrada não ordenada: " + " ".join([str(x) for x in lista_entrada])) # Fazendo a ordenação hashing_sort(lista_entrada) # Imprimindo a lista já ordenada print("\nLista de entrada ordenada: " + " ".join([str(x) for x in lista_entrada]))
false
58bc93845731806de1c8741616d330ef4bb2048f
Tanyaregan/practices
/greater_than_five.py
485
4.15625
4
def adds_to_five(nums): """Returns a list of lists containing pairs of numbers that add up to 5.""" nums_that_sum_to_5 = [] summed = [] index = 0 for num in nums: for n in nums: if n + nums[index] == 5: summed.append(n) summed.append(nums[index]) nums_that_sum_to_5.append(summed) index += 1 return nums_that_sum_to_5 print adds_to_five([2, 7, 3, 4, 1, 6]) #[2,3], [4,1]]
true
22709c51fbfd3d8fb21844e8603850f9f6c771c8
fainaszar/pythonPrograms
/pythonOOPS/oop.py
1,281
4.15625
4
#Example on oops using Inheritance class Vehicle(object): base_sales_price = 0 def __init__(self,wheels,miles,make,model,year,sold_on): self.wheels = wheels self.miles = miles self.make = make self.model = model self.year = year self.sold_on = sold_on def sales_price(self): if self.sold_on is not None: return 0.0 return 5000.0 * self.wheels def purchase_price(self): if self.sold_on is not None: return 0.0 return self.base_sales_price - (.10 * self.miles) class Car(Vehicle): def __init__(self,wheels,miles,make,model,year,sold_on): self.wheels=wheels self.miles = miles self.make = make self.model = model self.year = year self.sold_on = sold_on self.base_sales_price = 8000 class Truck(Vehicle): def __init__(self,wheels,miles,make,model,year,sold_on): self.wheels=wheels self.miles = miles self.make = make self.model = model self.year = year self.sold_on = sold_on self.base_sales_price = 10000 maruti = Car(4,300,"800","Maruti",2008,None) tata = Truck(4,411,"991","TATA",2009,None) v = Vehicle(4,0,'Honda','Accord',2014,None) print maruti.sales_price() print tata.sales_price() print maruti.purchase_price() print tata.purchase_price() print v.sales_price() print v.purchase_price()
true
76cb0e909e239f63234292644dbf429b90e53e97
nouranHnouh/cartwheeling-kitten
/classes/customer_Class.py
1,047
4.34375
4
class Customer(): """A customer of TD Bank with an account. customers have the following properties: Attributes: name: A string of a customer name balamnce: a float of customer`s current balance """ #intialize constructor def __init__(self,name,balance=0.0): self.name=name self.balance=balance #withdraw method takes an amount as an input #and return the remaining balance after withdraw def withdraw(self,amount): if self.balance<amount: print "I cant give you that amount !" else: self.balance-=amount return self.balance #method deposit return the current balance after deposit def deposit(self,amount): self.balance+=amount return self.balance def print_info(self): print ("\n") print ("Welcome "+self.name) print ("your current balance is: "+str(self.balance)) print ("-------------------") #create an instances a=Customer(" Jhon",1000.0) a.print_info() print "your balance after withdrawal is: ",a.withdraw(200) print "your balance after deposit is: " , a.deposit(100)
true
9017c3e9ae26f2de81f564b0556c58de1eb87218
nouranHnouh/cartwheeling-kitten
/whileLoopinList.py
921
4.625
5
# Let's learn a little bit of Data Analysis and how we can use # loops and lists to create, aggregate, and summarize data # For the part 1, we'll learn a basic way of creating data using # Python's random number generator. # To create a random integer from 0 to 10, we first import the # "random" module import random # We then print a random integer using the random.randint(start, end) function print "Random number generated: " + str(random.randint(0,10)) # We now want to create a list filled with random numbers. The list should be # of length 20 random_list = [] #empty list list_length = 20 # a while loop that populate this list of random integers. count=0 while count<list_length: random_list.append(random.randint(0,10)) count+=1 # When we print this list, we should get a list of random integers such as: # [7, 5, 1, 6, 4, 1, 0, 6, 6, 8, 1, 1, 2, 7, 5, 10, 7, 8, 1, 3] print random_list
true
cb863796baaca20024d959ff29e83413d361dd5b
gorandp/practice
/Python/12a - while.py
966
4.59375
5
# The while loop requires relevant variables to be ready, # in this example we need to define an indexing variable, # i, which we set to 1. i = 1 while i < 6: print(i) i += 1 print() # With the break statement we can stop the loop even if the # while condition is true: print(">>>> Break statement <<<<") i = 1 while i < 6: print(i) if (i == 3): break i += 1 print() # NEW <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< # The continue statement # With the continue statement we can stop the current iteration, and continue with the next: print(">NEW>>> The continue statement <<<<") i = 0 while i < 6: i += 1 if i == 3: continue print(i) print("Skipped print(i) when i == 3\n") # The else statement # With the else statement we can run a block of code once when the condition no longer is true: print(">NEW>>> The else statement <<<<") i = 1 while i < 6: print(i) i += 1 else: print("i is no longer less than 6")
true
33eb23edd70738c4df0589fd0019b367959ea443
jklemm/curso-python
/pythonbrasil/lista_2_estrutura_de_decisao/ex_01_maior_numero.py
836
4.40625
4
""" Faça um Programa que peça dois números e imprima o maior deles. """ def pede_numero_ao_usuario(msg): return float(input(msg)) def obter_o_maior_numero(num_1, num_2): # este é o chamado if ternário, faz o if em apenas uma linha maior_numero = num_1 if num_1 >= num_2 else num_2 return maior_numero def imprime_maior_numero(): numero_1 = pede_numero_ao_usuario('Informe um número: ') numero_2 = pede_numero_ao_usuario('Informe mais um número: ') maior_numero = obter_o_maior_numero(numero_1, numero_2) print('O número {} é o maior número'.format(maior_numero)) if __name__ == '__main__': print('+---------------------------------------+') print('| Programa: Exibe maior de dois números |') print('+---------------------------------------+') imprime_maior_numero()
false
ccd68e68d945cc247df8a6d30cde192934833fba
jklemm/curso-python
/pythonbrasil/lista_2_estrutura_de_decisao/ex_07_mostrar_maior_e_menor_de_tres_numeros.py
1,388
4.4375
4
""" Faça um Programa que leia três números e mostre o maior e o menor deles. """ def obter_numero_inteiro(msg): return int(input(msg)) def obter_maior_numero(numero_1, numero_2, numero_3): if numero_1 >= numero_2 and numero_1 >= numero_3: return numero_1 elif numero_2 >= numero_1 and numero_2 >= numero_3: return numero_2 else: return numero_3 def obter_menor_numero(numero_1, numero_2, numero_3): if numero_1 <= numero_2 and numero_1 <= numero_3: return numero_1 elif numero_2 <= numero_1 and numero_2 <= numero_3: return numero_2 else: return numero_3 def verifica_maior_e_menor_de_tres_numeros(): numero_1 = obter_numero_inteiro('Informe o primeiro número: ') numero_2 = obter_numero_inteiro('Informe o segundo número: ') numero_3 = obter_numero_inteiro('Informe o terceiro número: ') maior_numero = obter_maior_numero(numero_1, numero_2, numero_3) menor_numero = obter_menor_numero(numero_1, numero_2, numero_3) print('O maior número é', maior_numero, 'e o menor número é', menor_numero) if __name__ == '__main__': print('+--------------------------------------------------+') print('| Programa: Verifica maior e menor de três números |') print('+--------------------------------------------------+') verifica_maior_e_menor_de_tres_numeros()
false
3fd1cc67833022ff718caa25d5ab6fc704aa9c36
jklemm/curso-python
/pythonbrasil/lista_1_estrutura_sequencial/ex_11_calculos_com_floats_e_inteiros.py
592
4.34375
4
print('Cálculos envolvendo números inteiros e reais') numero1 = int(input('Informe um número inteiro: ')) numero2 = int(input('Informe outro número inteiro: ')) numero3 = float(input('Informe um número real: ')) calculo1 = (numero1 * 2) * (numero2 / 2) calculo2 = (numero1 * 3) + numero3 calculo3 = numero3 * numero3 * numero3 # ou pow(numero3, 3) print('O produto do dobro do primeiro com metade do segundo = {:.2f}'.format(calculo1)) print('A soma do triplo do primeiro com o terceiro = {:.2f}'.format(calculo2)) print('O terceiro elevado ao cubo = {:.2f}'.format(calculo3))
false
67b2c364c240701fdf529cb80e3559e7a57b300d
jklemm/curso-python
/pythonbrasil/lista_2_estrutura_de_decisao/ex_02_positivo_ou_negativo.py
801
4.34375
4
""" Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo. """ def pede_numero_ao_usuario(msg): return float(input(msg)) def obter_positivo_ou_negativo(num): # este é o chamado if ternário, faz o if em apenas uma linha maior_numero = 'positivo' if num >= 0 else 'negativo' return maior_numero def imprime_positivo_ou_negativo(): numero = pede_numero_ao_usuario('Informe um número: ') sinal_do_numero = obter_positivo_ou_negativo(numero) print('O número {} é {}'.format(numero, sinal_do_numero)) if __name__ == '__main__': print('+---------------------------------------+') print('| Programa: Exibe positivo ou negativo |') print('+---------------------------------------+') imprime_positivo_ou_negativo()
false
f61fd62ddad63757108159961939257aa06ad02f
srnoglu1/python-study
/for-demo.py
742
4.21875
4
# 1)(?) Print each element in the list of numbers. numbers = [1,2,3,4,5,10,15] for n in numbers: print(n) # 2)(?) Which numbers in the list of numbers are a multiple of 5? for n in numbers: if (n %5 == 0): print(n) # 3)(?) What is the sum of the numbers in the list of numbers? total = 0 for n in numbers: total = total + n print(total) # 4)(?) Square the even numbers in the list of numbers. for n in numbers: if(n%2==0): print(n,n*n) # 5)(?) How many products are there with 'iphone' in the list of products? products = ['iphone 8','iphone 7','iphone X','iphone XR','samsung S10'] count = 0 for x in products: index = (x.find('iphone')) if (index >-1 ): count += 1 print(count)
true
c670b20c8ea934656c0dab6c6c5380d09a1879d4
ChiUgb/CIS2348-15664
/Homework 2/hw8.10.py
540
4.21875
4
# Chiamaka Ugbaja # 1772427 user_input = input() no_spaces = "" for i in user_input: # look through each letter and adds it to new variable, no_spaces if i != ' ': no_spaces += i backward = "" for i in no_spaces: # evaluates the phrase without space (no_spaces) to see if it match with backwards backward = i + backward if no_spaces == backward: # if everything matched print(user_input + " is a palindrome") else: # discrepancies will result in no palindrome print(user_input + " is not a palindrome")
true
47b7eb6c9988b5d4e8d5e303d148d1f513d02fff
Oscar-Oliveira/Python-3
/18_Exercises/B_Complementary/Solutions/Ex13.py
1,037
4.28125
4
""" Exercise 13 """ def remove_symbols1(string): symbols = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" newString = "" for c in string: if c not in symbols: newString += c return newString def remove_symbols2(string): return "".join(x for x in string if x not in "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") def reverse1(string): newString = "" for i in range(-1, -(len(string) + 1), -1): newString += string[i] return newString def reverse2(string): return string[::-1] def is_palindrome(string): s = string.upper() return s == reverse2(s) print(remove_symbols1("""Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea.""")) print(remove_symbols2("""Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea.""")) print(reverse1("Python")) print(reverse2("Python")) print(is_palindrome("Python")) print(is_palindrome("Level"))
true
bf5693df343abd09fbfc14beb2087b4b10446238
Oscar-Oliveira/Python-3
/2_Data_Types/1_Scalars/G_decimal.py
1,112
4.25
4
""" decimal - See: https://docs.python.org/3.6/library/decimal.html """ from decimal import Decimal, getcontext a = 0.1 b = 0.2 print(a, b, a + b) areEqual = (a + b) == 0.3 print(areEqual) a = Decimal('0.1') b = Decimal('0.2') print(a, b, a + b) areEqual = (a + b) == Decimal('0.3') print(areEqual) print() value = Decimal('3.14') print(value) value = Decimal(3.14) print(value) print() # arithmetic, differences between arithmetic on Decimal and on integers and floats. a = -7 b = 4 print("{} / {} - {}".format(a, b, a / b)) print("{} // {} - {}".format(a, b, a // b)) print("{} % {} - {}".format(a, b, a % b)) a = Decimal(str(a)) b = Decimal(str(b)) print("{} / {} - {}".format(a, b, a / b)) print("{} // {} - {}".format(a, b, a // b)) print("{} % {} - {}".format(a, b, a % b)) # Precision print() a = Decimal('1.1') b = Decimal('1.36') print(getcontext().prec, "-", a / b) getcontext().prec = 3 print(getcontext().prec, "-", a / b) getcontext().prec = 10 print(getcontext().prec, "-", a / b) getcontext().prec = 42 print(getcontext().prec, "-", a / b)
false
355336a0f932fc6b29d2a2eb51948cf8c349f1a5
gyan-krishna/python_assignment
/3. time.py
968
4.15625
4
# -*- coding: utf-8 -*- """ ----------Phenix Labs---------- Created on Sat Jan 23 22:59:04 2021 @author: Gyan Krishna Topic: """ class Time: def __init__(self, hr, mins): self.hr = hr self.mins = mins def addTime(t1, t2): hours = t1.hr + t2.hr minutes = t1.mins + t2.mins hours += int(minutes / 60) minutes %= 60 sumTime = Time(hours, minutes) return sumTime def subTime(t1, t2): hours = t1.hr - t2.hr minutes = t1.mins - t2.mins sumTime = Time(hours, minutes) return sumTime def dispTime(self): print("the time is {} hours and {} mins".format(self.hr, self.mins)) print("Time 1 ::") h1 = int(input("enter hours")) m1 = int(input("enter mins")) print("Time 2 ::") h2 = int(input("enter hours")) m2 = int(input("enter mins")) t1 = Time(h1,m1) t2 = Time(h2,m1) t3 = Time.addTime(t1, t2) t4 = Time.subTime(t1, t2) t3.dispTime() t4.dispTime()
false
d2e62d0b3e879a1e73a9a08e1d9e32484d86153a
evershinemj/python
/zip.py
276
4.375
4
#!/usr/bin/env python3 # encoding=utf-8 s1 = 'happy' s2 = 'funny' # zip(a, b) creates an iterator that produces a tuple (x, y) # each time, where x is from sequence a, and y from sequence b for i, j in zip(s1, s2): print(i, j) print() for i in zip(s1, s2): print(i)
true
5f8443defc8ed044062efd532c50daebd0fb9982
evershinemj/python
/Countdown.py
667
4.15625
4
#!/usr/bin/env python3 # encoding=utf-8 class Countdown: def __init__(self, start): self._start = start def __iter__(self): n = self._start while n > 0: yield n n -= 1 # def reverse_iter(self): def __reversed__(self): n = 1 while n <= self._start: yield n n += 1 if __name__ == '__main__': countdown = Countdown(10) print('calling __iter__') for i in countdown: print(i) # print('calling reverse_iter') print('calling reversed') # for i in countdown.reverse_iter(): for i in reversed(countdown): print(i)
false
d52b4f7bd5fea81bc9254f0a44d9c7a4386ed72c
Irian3x3/calc
/main.py
639
4.15625
4
def sum(n1: int, n2: int): return n1 + n2 def mult(n1: int, n2: int): return n1 * n2 def rest(n1: int, n2: int): return n1 - n2 def div(n1: int, n2: int): if n2 == 0: raise ZeroDivisionError return n1 / n2 num1 = int(input("Number 1: ")) num2 = int(input("Number 2: ")) operator = input("Operator (one of: 'sum' for sum, 'rest' for rest, 'mult' for multiply, 'div' for divide): ") res = None if operator == "sum": res = sum(num1, num2) elif operator == "rest": res = rest(num1, num2) elif operator == "mult": res = mult(num1, num2) elif operator == "div": res = div(num1, num2) print(res)
false
b7e8f566d4a2d5973ce4ced287db0c9548087053
nooromari/data-structures-and-algorithms
/python/challenges/multi_bracket_validation/multi_bracket_validation.py
777
4.25
4
def multi_bracket_validation(input): """ function should take a string as its only argument, and should return a boolean representing whether or not the brackets in the string are balanced. """ opening=['(','[','{'] closing=[')',']','}'] check_list = [] for i in input: if i in opening: check_list.append(i) elif i in closing: pos = closing.index(i) if ((len(check_list) > 0) and (opening[pos] == check_list[len(check_list)-1])): check_list.pop() else: return False if len(check_list) == 0: return True else: return False if __name__ == "__main__": print(multi_bracket_validation('[Extra Characters'))
true
07060e48f6e4f8d1de712de6a6504ed5a69c0c55
ricardo64/Over-100-Exercises-Python-and-Algorithms
/src/further_examples/bit_operations/swap_odd_even.py
695
4.1875
4
#!/usr/bin/python3 # mari von steinkirch @2013 # steinkirch at gmail ''' Swap odd and even bits in a smart way in a binary: 1) first for odds, take n and move the odd: (a) Mask all odd bits with 10101010 (0xAA) (b) shift by right by 1 2) do the same to ints with 01010101 3) merge >>> num = 0b11011101 >>> result = '0b1101110' >>> swap_odd_even(num) == result True ''' def swap_odd_even(num): mask_odd = 0xAA # 0b10101010 mask_even = 0x55 # 0b1010101 odd = num & mask_odd odd >>= 1 even = num & mask_even even >>= 1 return bin(odd | even) if __name__ == '__main__': import doctest doctest.testmod()
false
f97b4b6581238e906b4fc5408fa7d611881eb2d1
ricardo64/Over-100-Exercises-Python-and-Algorithms
/src/further_examples/arrays_and_strings/find_if_is_substr.py
772
4.125
4
#!/usr/bin/python3 # mari von steinkirch @2013 # steinkirch at gmail ''' Find if a s2 is a substring of a s1 >>> s1 = 'buffy is a vampire slayer' >>> s2 = 'vampire' >>> s3 = 'angel' >>> isSubstr(s1, s2) True >>> isSubstr(s1, s3) False >>> s4 = 'pirevam' >>> find_substr(s2, s4) True >>> find_substr(s1, s4) False ''' def isSubstr(s1, s2): if s1 in s2 or s2 in s1: return True return False def find_substr(s1, s2): if s1 == '' or s2 == '': return True #empty str is always substr for i, c in enumerate(s1): if c == s2[0]: test_s1 = s1[i:]+s1[:i] return isSubstr(s2, test_s1) return False if __name__ == '__main__': import doctest doctest.testmod()
false
2b0a28bac91ea98f0196614db140d7a0d2f9e5b6
ngungo16/csf
/hw1.py
1,133
4.25
4
# Name: Ngoc (Ann) Nguyen # Evergreen Login: ngungo16@evergreen.edu # Computer Science Foundations # Programming as a Way of Life # Homework 1 # You may do your work by editing this file, or by typing code at the # command line and copying it into the appropriate part of this file when # you are done. When you are done, running this file should compute and # print the answers to all the problems. import math # makes the math.sqrt function available ### ### Problem 1 ### print "Problem 1 solution follows:" b = -5.86 sum = (b**2) - 4*8.5408 # calculate the sum value inside the square root math.sqrt(sum) sol1 = ((0-b)+ math.sqrt(sum))/2 sol2 = ((0-b)- math.sqrt(sum))/2 print sol1 print sol2 ### ### Problem 2 ### print "Problem 2 solution follows:" import hw1_test list = hw1_test print list.a print list.b print list.c print list.d print list.e print list.f ### ### Problem 3 ### print "Problem 3 solution follows:" print str ((list.a and list.b) or (not list.c) and not (list.d or list.e or list.f)) ### ### Collaboration ### # ... List your collaborators here, as a comment (on a line starting with "#").
true
1ac84e9b76618b269c2c849507f31236b3a21a5e
Saipheddine/LearingPython
/passwordGenerator.py
1,377
4.21875
4
import random # programm to generate a secure passwords print("Welcome to the PyPassword generator!") num_letters = input("How many letters would you like in your password?") num_symbols = input("How many symbols would you like in your password?") num_digits = input("How many numbers would you like in your password?") num_digits = int(num_digits) num_letters = int(num_letters) num_symbols = int(num_symbols) password = "" password_len = int(num_digits) + int(num_letters) + int(num_symbols) list_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] list_digits = [1, 2, 3, 4, 5, 6, 7, 8, 9] list_symbols = ['*', ',', '.', '&', '%', '$', '"', '?', '='] # add random letters to the password for i in range(0, password_len): if (num_letters > 0): random_int = random.randint(0, len(list_letters) -1) num_letters -= 1 password += list_letters[random_int] if (num_symbols > 0): random_int = random.randint(0, len(list_symbols) -1) num_symbols -= 1 password += list_symbols[random_int] if (num_digits > 0): random_int = random.randint(0, len(list_digits) -1) num_digits -= 1 password += str(list_digits[random_int]) print("Here is your password {}".format(password))
false
ced9250560a2f311398385c9186d48d41c2e29f1
joshualan/Notes
/python_notes/iterators.py
1,389
4.5
4
# An iteration is taking one of something, one after the other. # An iterator is # a Python object that has a __next__ (Python 3) or a next # (Python 2) method. # An iterable is an object that returns an iterator with a __iter__ method or # defines a __getitem__ method that accepts valid indexes and raises an # IndexError if it's not valid. # # So in short, an iterable is something you can get an iterator from. Here's # an example of an iterator: # This class only returns the first, third, fifth, etc. element in the list # passed. class Odd: def __init__(self, data): self.data = data self.len = len(self.data) self.index = 0 def __iter__(self): return self def __next__(self): if self.index >= self.len: raise StopIteration self.index = self.index + 2 return self.data[self.index-2] odd = Odd([x for x in range(5)]) # So what iter does is it returns whatever the iterable's __iter__ method returns. it = iter(odd) # Should print 0, 2, 4 # I know, it's weird, but 0 is the first element in the sequence given so... for i in it: print(i) odd = Odd('abcdef') it = iter(odd) # Should print "a c e" for i in it: print(i) # This will be an error as you can't reset our Odd iterator! next(it) #Keep in mind when you do something like: it = iter([1,2,3,4,5]) # iter simply calls __iter__ of the list class :)
true
1cedb22faac73b2077b7a0d4aa699a3cb35301c6
joshualan/Notes
/python_notes/generators.py
2,372
4.625
5
# Note: Read iterators.py before this because you need to understand # iterables to truly understand generators. Or not because I'm not # the police. # So a generator is a function that returns an object that you can # call next on! Every call to next() returns a value and eventually, # a StopIteration exception will be raised to show that no more values # can be returned. # So functions usually use "return" but generators use yield. This is # the piece that turns a function into a generator. def foo(n): yield n % 2 yield n % 3 gen = foo(7) # Should print out "1 1" since 7 % 2 and 7 % 3 are both 1. for i in gen: print(i) # Generators are like iterators and cannot be restarted! gen = foo(8) # Should print out 0 print(next(gen)) # Should print out 2 print(next(gen)) # Should raise a StopIteration exception #print(next(gen)) # So in essence, a generator is an alternate, faster, and less memory- # intesive way of implementing the iterator protocol! # We can also do something called generator expressions! gen = (x*x for x in range(10)) # This prints the squares of the numbers 0 to 9 for i in gen: print(i) # Generator expressions can get pretty complex! def unique(iterable, key=lambda x: x): seen = set() for elem, ekey in ((e, key(e)) for e in iterable): if ekey not in seen: yield elem seen.add(ekey) # This function yields a set of unique values based on the elements # in the iterable passed with the function passed in applied to them. # We use a generator to iterate through the iterable as well! # Generators don't even have to necessarily end! # We can simply stop calling the function if we wanted! def get_primes(number): while True: if is_prime(number): yield number number += 1 # Another note is that we can call the send() function of a generator! # This allows us to both receive a value yielded from the generator and # also receive a value from it. This is kind of reminds me of multi- # threaded programming. We can yield nothing and also send None. def quick_example(): data = yield yield sum(data) # Readings: # # Generator Expressions Abstract: https://www.python.org/dev/peps/pep-0289/ # Yield and Generators Explained: https://www.jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/
true
08081232d75c8a635e9b345c00d48694e6cd7185
rom4ikrom/Assignment-1
/Task2.py
268
4.40625
4
#This is a simple program that allows user calculate an area and a length of a circle. import math radius = float(input("Radius:")) area = math.pi * math.pow(radius, 2) length = 2 * math.pi * radius print("\nArea is: \t", area) print("\nLength is: \t", length)
true
6d999868abf7c802479c63ac4c832966917bc74c
imbmjha/learning-python
/test.py
376
4.25
4
import string # find no of uppercase letter name = input("enter a string= ") upper_case = 0 lower_case = 0 for char in name: if char in string.ascii_uppercase: upper_case += 1 elif char in string.ascii_lowercase: lower_case += 1 print(f"no of uppercase letter in {name} is {upper_case}") print(f"no of lowercase letter in {name} is {lower_case}")
true
5fc642e8af5a41a038c287336bdd83305dbc6994
imbmjha/learning-python
/area-circle.py
591
4.5
4
# length,breadth & radius are input through keyboard. #calculate area & perimeter of rectangle & circle length = int(input("enter length= ")) breadth = int(input("enter breadth= ")) radius = int(input("enter radius= ")) area_of_rectangle = length * breadth area_of_circle = 3.14 * r * r circumference_of_circle = 2 * 22.7 * r perimeter_of_rectangle = (2 * (length+breadth)) print(f"area of rectangle = {area_of_rectangle}") print(f"area of circle = {area_of_circle}") print(f"circumference of circle = {circumference_of_circle}") print(f"perimeter of rectangle = {perimeter_of_rectangle}")
true
cdfb2a24029838516a6b40ac02b4b7a1d1df516a
ehizman/Python_Projects
/src/chapter_two/arithmetic_smallest_and_largest.py
472
4.15625
4
import sys list_of_inputs = list() counter: int = 0 while counter < 3: try: user_input: int = int(input(f"Enter a number {counter + 1}: ")) print("number added to list successfully!") except ValueError as e: print("Oops!", e.__class__, "occurred") print("please re- enter input!") else: list_of_inputs.append(user_input) counter = counter + 1 print(f"The maximum of {list_of_inputs} is {max(list_of_inputs)}")
true
a4be71644e483ff98c6daead1872cba67449886b
ehizman/Python_Projects
/src/chapter_two/car_pool_savings_calculator.py
863
4.15625
4
if __name__ == "__main__": total_miles_driven_per_day: float = float(input("Enter the total number of miles driven per day: ")) cost_per_gallon_of_gasoline = float(input("Enter the cost per gallon of gasoline: ")) average_miles_per_gallon: float = float(input("Enter the average miles covered per gallon of gasoline: ")) parking_fees_per_day: float = float(input("Enter the parking fees per day: ")) tolls_per_day: float = float(input("Enter the tolls per day: ")) average_number_of_gallons_of_gasoline_used_per_day: float = total_miles_driven_per_day / average_miles_per_gallon cost_per_day_of_driving_to_work: float = (average_number_of_gallons_of_gasoline_used_per_day * cost_per_gallon_of_gasoline) + parking_fees_per_day + tolls_per_day print("user's cost per day of driving to work: %.2f" % cost_per_day_of_driving_to_work)
true
ff5bbab09ae5c78dd6ccb9966c975a344b9baeec
ehizman/Python_Projects
/src/chapter_two/sort_in_ascending_order.py
348
4.40625
4
list_of_floats = list() i: int = 0 print("Enter three float point numbers") while i < 3: try: user_input = float(input(f"Enter number {i + 1}: ")) except Exception as error: print(error) else: list_of_floats.append(user_input) i = i + 1 print(f"The list is ascending order is {sorted(list_of_floats)}")
true
75675dbf124001eebee6ca755ef3a2c1408e7e95
rainbow-sunshine/Python-Algorithm
/01_10/09_1 两个队列实现栈.py
1,347
4.28125
4
""" 主要是在push的时候保证元素在list1的最前面 """ class MyStack(object): def __init__(self): """ Initialize your data structure here. """ self.list1 = [] self.list2 = [] def push(self, x): """ Push element x onto stack. :type x: int :rtype: None """ if len(self.list1) == 0: self.list1.append(x) else: while self.list1: self.list2.append(self.list1.pop(0)) self.list1.append(x) while self.list2: self.list1.append(self.list2.pop(0)) def pop(self): """ Removes the element on top of the stack and returns that element. :rtype: int """ if len(self.list1) != 0 : return self.list1.pop(0) def top(self): """ Get the top element. :rtype: int """ while self.list2: self.list1.append(self.list2.pop(0)) return self.list1[-1] def empty(self): """ Returns whether the stack is empty. :rtype: bool """ return len(self.list1)==0 # Your MyStack object will be instantiated and called as such: # obj = MyStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.empty()
true
219ffbd4426e8e96bc50bccbc591396497625bb1
ioggstream/py-crypttool
/cifra.py
2,245
4.3125
4
#!/usr/bin/python # -*- coding: utf-8 -*- # # This is a sample program for teaching # python and some criptography # related to the article http://www.babel.it/it/centro-risorse/2012/08/13/58-crittografia-e-integrazione-dei-sistemi-con-python.html # ## ## A simple byte swap encryption ## def shift(i, step=2): """Sposta gli indici pari di una stringa.""" if i > 7: raise Exception("Valore dell’indice non valido: %s" % i) if i % 2: return i return (i - step) % 8 def codifica(stringa): """Ritorna la sequenza di numeri associata a una stringa""" ord_a=ord("A") ret = "" for carattere in stringa: # anteponi lo zero ai numeri minori di 10 ret += "%02d" % (ord(carattere)-ord_a) return ret def cifra(stringa): ret = "" stringa_codificata = codifica(stringa) print "stringa_codificata: %s" % stringa_codificata # una stringa e’ un’array di caratteri for i in range(len(stringa_codificata)): ret += stringa_codificata[shift(i)] return ret def cifra_test(): test_list=[ ("CASA", "02000810") ] for (input,output) in test_list: cifra_input = cifra(input) assert cifra_input == output, "Valore inatteso per %s: ho %s, aspettavo %s" % (codifica(input), cifra_input, output) # esegui cifra_test() cifra_test() ## ## A simple implementation of the Diffie-Hellman ## encryption algorithm ## def find_pubkey(p,q): """Crea una chiave pubblica a partire da due numeri primi p e q""" from fractions import gcd ring_2 = (p-1)*(q-1) for pub_k in range(2, ring_2): if gcd(pub_k, ring_2) == 1: return pub_k def find_privkey(p,q,pub_key): """Crea una chiave privata a partire da due numeri primi e da una chiave pubblica""" ring_2 = (p-1)*(q-1) for prv_k in range(2, ring_2): if prv_k * pub_key % ring_2 == 1: return prv_k def genera_chiavi_test(): """Genera una coppia di chiavi""" (p,q) = (5,11) pub_key = find_pubkey(p,q) prv_key = find_privkey(p,q,pub_key) print "pub: %s, prv: %s, ring: %s, ring2: %s" % (pub_key, prv_key, p*q, (p-1) * (q-1)) genera_chiavi_test() ## ## Exercise: write an example encryption-decryption test using ## a couple of keys generated with the previous algorithm ##
false
2663abc0dff8b22a2c6d3c8524f0de86633cf57a
soji-opa/CS-Python
/src/classes.py
1,633
4.5
4
""" - When naming classes we capitalize the first letter of every word - An object is an instance of a class """ # class Point: # def move(self): # print("move") # def draw(self): # print("draw") # point1 = Point() # point1.x = 10 # point1.y = 20 # print(point1.x) # point1.draw() """ We can make it cleaner by utilizing constructors """ # class Point: # def __init__(self, x, y): # self.x = x # self.y = y # def move(self): # print("move") # def draw(self): # print("draw") # point = Point(10, 20) # # point.x = 11 # print(point.x) """ Exercise """ # class Person: # def __init__(self, name): # self.name = name # def talk(self): # print(f"{self.name} says hello") # Boy = Person("Bolu") # girl = Person("Lindsay") # Boy.talk() # girl.talk() """ Inheritance basics """ # class Mammals: # def walk(self): # print("walk") # class Dogs(Mammals): # def bark(self): # print("bark bark") # class Cats(Mammals): # pass # dog1= Dogs() # dog1.walk() # dog1.bark() class Parent: def __init__ (self, name, location, work): self.name = name self.location = location self.work = work def job(self): return (f"{self.name} is a {self.work}") mom = Parent ("Brittany", "CPT", "developer") print(mom.job()) # Inheritance class Child(Parent): def __init__(self, major): self.major = major def study(self): return(f"{self.name} is a {self.major}") # cindy = Child ("Comp sci") # print(cindy.study()) # print(cindy.job())
true
362b9558cf7a1a6adb87e224b5ba8610ba4c0c1e
soji-opa/CS-Python
/src/functions.py
1,069
4.59375
5
""" In this section we look at functions in python - A basic python program is written below """ # def greet_user(): # print("Hi there") # print("Welcome to functions in python") # print("start") # greet_user() # print("finished") """ With parameters, functions can receive information - Parameters - are place holders that we define in our function to receive information -Arguments are the actual pieces of information that we pass into our functions - For regular functions use positional arguments - However, when dealing functions that take numerical values use keyword arguments in your functions """ def greet_user(name): print(f"Hi {name}, its nice to meet you") print("start") greet_user("Tyronne") print("finished") """ Return Statements """ def emoji_converter(msg): words = message.split(' ') emojis = { "happy": "\U0001F973", "sad": "\U0001F628" } output="" for word in words: output += emojis.get(word, word) + " " return output message = input("> ") print(emoji_converter(message))
true
7a01261e4730c6319ce610bfb5280cb6a6a2c9e1
CurtLH/my_pkg
/my_pkg/my_pkg.py
639
4.1875
4
def add(x, y): """Add two numbers together. Parameters ---------- x : int The first number. y : int The second number. Returns ------- z : int The first number plus the second number Example ------- >>> add(2, 2) """ return x + y def subtract(x, y): """Subtract one number from another. Parameters ---------- x : int The first number. y : int The second number. Returns ------- z : int The first number minus the second number Example ------- >>> subtract(2, 1) """ return x - y
true
98c52f328715afa6792523854a7e68fa055eaac1
tejamallidi/Just-Python
/Generic/Tuples and Sets.py
1,512
4.46875
4
''' Tuples - Collection which is ordered and unchangeable. ''' # my_tuple = (1, 2, 3, 4, 5) # print(my_tuple[2]) # # Cannot remove or add elements # for x in my_tuple: # print(x) # print(len(my_tuple)) ''' Sets - collection similar to lists BUT UNORDERED Lists are faster than Sets to iterate over the values Sets are faster than Lists to search for an item - contains only unique values Used mostly to remove and duplicates and check if an item exists ''' my_set = {'apples', 'bananas', 'oranges', 'melons'} new_set = {'grapes', 'plums', 'apples'} # print(my_set) # can print it any random order # print('melonS' in my_set) # case sensitive # # Loop thorugh # for x in my_set: # print(x) # # Remove # my_set.remove('grapes') # throws KeyError if key doesn't exist # my_set.discard('grapes') # no response returned if key doesn't exist # my_set.clear() # # Return the difference of two or more sets as a new set. (i.e. all elements that are in this set but not the others.) # print(new_set.difference(my_set)) # returns {'grapes', 'plums'} and excludes 'apples' # # Remove all elements of another set from this set. # my_set.difference_update(new_set) # 'apples' got removed from my_set # print(my_set) # print(new_set) # # Union # set_one = {1, 3, 5, 7, 9} # set_two = {2, 4, 6, 8, 10} # all_set = set_one.union(set_two) # returns a combined set in asc order # print(all_set) # # Add # my_set.add('pears') # my_set.update(['mango', 'pumpkin']) # print(my_set) # print(len(my_set))
true