blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
bf4fb0bb615781cd26ea4c7fde9ee78f21c5dff0
archana-nagaraj/experiments
/Udacity_Python/Excercises/testingConcepts.py
890
4.21875
4
def vehicle(number_of_tyres, name, color): print(number_of_tyres) print(name) print(color) vehicle(4, "Mazda", "blue") # Trying Lists courses = ['Math', 'Science', 'CompSci'] print(courses) print(len(courses)) print(courses[1]) print(courses[-1]) #Lists slicing print(courses[0:2]) print(courses[:2]) print(courses[2:]) print(courses[1:-1]) # Lists methods #courses.append('Art') print(courses) #courses.insert(0,'Art') print(courses) #Lists within a list courses_2 = ['Zoology', 'Writing'] #courses.insert(0,courses_2) print(courses) print(courses[0]) # extend a list courses_3 = ['Education', 'Photography'] #courses.extend(courses_3) print(courses) #remove some items from list courses.remove('Math') print(courses) #popped = courses.pop() print(courses) #print(popped) #reverse a list courses.reverse() print(courses) #sorting a list courses.sort() print(courses)
true
8ce320224914c3dbbc166d7c59c43588bfbea60e
archana-nagaraj/experiments
/Udacity_Python/Excercises/secret_message.py
617
4.125
4
import os def rename_files(): #(1)get file names from a folder file_list = os.listdir(r"/Users/archananagaraja/Desktop/AN_Personal/Udacity_Python/alphabet") print(file_list) current_dir = os.getcwd() print("My current directory is: "+current_dir) os.chdir(r"/Users/archananagaraja/Desktop/AN_Personal/Udacity_Python/prank") #(2) for each file rename filename for file_name in file_list: print("Old File Name: " +file_name) os.rename(file_name, file_name.translate(None, "0123456789")) print("New File Name:" +file_name) os.chdir(current_dir) rename_files()
false
9a2a1d2058cc7a2b6345d837173e109f20b39ed5
jeb26/Python-Scripts
/highestScore.py
622
4.21875
4
##Write a prog that prompts for a number of students. then each name and score and ##then displays the name of student with highest score. scoreAcc = 0 nameAcc = None currentScore = 0 currentName = None numRuns = int(input("Please enter the number of students: ")) for i in range(numRuns): currentName = str(input("Please enter the name of the current student: ")) currentScore = int(input("Pleae enter the score the current student: ")) if currentScore > scoreAcc: scoreAcc = currentScore nameAcc = currentName print("The highest scoring student is: ",nameAcc)
true
fdb5d39c2ed2c61416aeffb1e4dbc491241ce316
sonht113/PythonExercise
/HoTrongSon_50150_chapter5/Chapter5/Exercise_page_145/Exercise_04_page_145.py
338
4.1875
4
""" Author: Ho Trong Son Date: 18/08/2021 Program: Exercise_04_page_145.py Problem: 4. What is a mutator method? Explain why mutator methods usually return the value None. Solution: Display result: 58 """ #code here: data = [2, 5, 24, 2, 15, 10] sum = 0 for value in data: sum += value print(sum)
true
d713c91065792ffb55927b59ab859b791b85b3b6
sonht113/PythonExercise
/HoTrongSon_50150_chapter3/Chapter3/Exercise_page_70/exercise_01_page_70.py
793
4.25
4
""" Author: Ho Trong Son Date: 23/07/2021 Program: exercise_01_page_70.py PROBLEM: 1. Write the outputs of the following loops: a. for count in range(5): print(count + 1, end = " ") b. for count in range(1, 4): print(count, end = " ") c. for count in range(1, 6, 2): print(count, end = " ") d. for count in range(6, 1, –1): print(count, end = " ") SOLUTION: """ # Code here: # 1 for count in range(5): print(count + 1, end=" ") # 2 print() for count in range(1, 8): print(count, end=" ") # 3 print() for count in range(1, 6, 2): print(count, end=" ") # 4 print() for count in range(5, 1, -2): print(count, end=" ") # Result: # a) 1 2 3 4 5 # b) 1 2 3 4 5 6 7 # c) 1 3 5 # d) 5 3
false
25a467d72816cf35cf0b5ef9b94503dd40376c2a
sonht113/PythonExercise
/HoTrongSon_50150_chapter2/Chapter2/exercise_page_46/exercise_04_page_46.py
624
4.125
4
""" Author: Ho Trong Son Date: 11/07/2021 Program: exercise_04_page_46.py PROBLEM: 4) What happens when the print function prints a string literal with embedded newline characters? SOLUTION: 4) => The print function denoted print() in a computer programming language such as Python is a function that prints values assigned to its parameter. When assigned a string literal("I'm not going" for example) and break line statements/new line characters(\n), it prints the value such as "I'm not going\n" and starts a new line where a break line is indicated in the instruction(after "going" in the example) """
true
7d4ed044ec86306dff4cb4752b0d6d9202fad492
sonht113/PythonExercise
/HoTrongSon_50150_Chapter4/Chapter4/Project_page_132-133/project_12_page_133.py
1,421
4.15625
4
""" Author: Ho Trong Son Date: 5/08/2021 Program: Project_12_page_133.py Problem: 12. The Payroll Department keeps a list of employee information for each pay period in a text file. The format of each line of the file is the following: <last name> <hourly wage> <hours worked> Write a program that inputs a filename from the user and prints to the terminal a report of the wages paid to the employees for the given period. The report should be in tabular format with the appropriate header. Each line should contain an employee�s name, the hours worked, and the wages paid for that period. Solution: Display result Enter the file name: ../textFile/project12.txt Name Hours Work Total Pay Ho 10 135.0 Dang 15 123.75 Tran 7 86.8 """ fileName = input("Enter the file name: ") inputFileName = open(fileName, 'r') print("%-20s%10s%20s" % ("Name", "Hours Work", "Total Pay")) for line in inputFileName: dataList = line.split() name = dataList[0] hoursWork = int(dataList[1]) moneyPriceOneHour = float(dataList[2]) totalPay = hoursWork * moneyPriceOneHour print("%-20s%10s%20s" % (name, hoursWork, totalPay))
true
805f1755caf35c97cf3c31dfe3436ffc407ccb01
sonht113/PythonExercise
/HoTrongSon_50150_chapter5/Chapter5/Exercise_page_149/Exercise_04_page_149.py
522
4.125
4
""" Author: Ho Trong Son Date: 18/08/2021 Program: Exercise_04_page_149.py Problem: 4. Define a function named summation. This function expects two numbers, named low and high, as arguments. The function computes and returns the sum of the numbers between low and high, inclusive. Solution: Display result: 5 """ def summation(low, high): result = 0 for index in range(low, high): result += index return result low = 2 high = 4 print(summation(low, high))
true
ca59990c60f302bcb8521710ad34a14d493224f4
sonht113/PythonExercise
/HoTrongSon_50150_chapter3/Chapter3/Exercise_page_70/exercise_02_page_70.py
364
4.1875
4
""" Author: Ho Trong Son Date: 23/07/2021 Program: exercise_02_page_70.py PROBLEM: 2. Write a loop that prints your name 100 times. Each output should begin on a new line. SOLUTION: """ # Code here: name = "Ho Trong Son" for i in range(100): print(name, "(" + str(i+1) + ")") # Result: # Ho Trong Son (1) # ... # ... # ... # Ho Trong Son (100)
true
e8e4d0c2a84f2bf905a9a4c3721e132249cfd403
sonht113/PythonExercise
/HoTrongSon_50150_Chapter4/Chapter4/Project_page_132-133/project_05_page_132.py
1,139
4.5625
5
""" Author: Ho Trong Son Date: 5/08/2021 Program: Project_05_page_132.py Problem: 5. A bit shift is a procedure whereby the bits in a bit string are moved to the left or to the right. For example, we can shift the bits in the string 1011 two places to the left to produce the string 1110. Note that the leftmost two bits are wrapped around to the right side of the string in this operation. Define two scripts, shiftLeft.py and shiftRight.py, that expect a bit string as an input. The script shiftLeft shifts the bits in its input one place to the left, wrapping the leftmost bit to the rightmost position. The script shiftRight performs the inverse operation. Each script prints the resulting string Solution: Display result Enter a string of bits: 1101 1011 1110 """ def left(bit): if len(bit) > 1: bit = bit[1:] + bit[0] return bit def right(bit): if len(bit) > 1: bit = bit[-1] + bit[:-1] return bit # main bitInput = input("Enter a string of bits: ") print(left(bitInput)) print(right(bitInput))
true
1e23187a25a230abed4a21b60cdda3e90ae27930
sonht113/PythonExercise
/HoTrongSon_50150_Chapter4/Chapter4/Exercise_page_118/Exercise_01_page_118.py
805
4.25
4
""" Author: Ho Trong Son Date: 5/08/2021 Program: Exercise_01_page_118.py Problem: 1. Assume that the variable data refers to the string "Python rules!". Use a string method from Table 4-2 to perform the following tasks: a. Obtain a list of the words in the string. b. Convert the string to uppercase. c. Locate the position of the string "rules". d. Replace the exclamation point with a question mark. Solution: Display result: a) ['P', 'y', 't', 'h', 'o', 'n', ' ', 'r', 'u', 'l', 'e', 's', '!'] b) PYTHON RULES! c) 7 d) Python rules? """ string = 'Python rules!' print('a)', list(string)) print('b)', string.upper()) print('c)', string.index('rules')) print('d)', string.replace('!', '?'))
true
a6971bf97f895b2eafc8af4aba0a631b0bc3dfbe
sonht113/PythonExercise
/HoTrongSon_50150_Chapter4/Chapter4/Exercise_page_125/Exercise_03_page_125.py
682
4.3125
4
""" Author: Ho Trong Son Date: 5/08/2021 Program: Exercise_03_page_125.py Problem: 3. Assume that a file contains integers separated by newlines. Write a code segment that opens the file and prints the average value of the integers. Solution: Display result: Average: 5.0 """ #Code here: textFile = open("../textFile/myfile.txt", 'w', encoding='utf-8') for index in range(1, 50): textFile.write(str(index) + '\n') textFile = open("../textFile/myfile.txt", 'r', encoding='utf-8') sum = 0 count = 0 for line in textFile: sum += int(line.strip()) count += 1 print(sum) average = sum/count print("Average =>", average)
true
8fe5c46bdf8a1c42a910d3135d1a8f0dde4fee4f
sonht113/PythonExercise
/HoTrongSon_50150_chapter6/Chapter6/Exercise_page_182/Exercise_04_page_182.py
522
4.125
4
""" Author: Ho Trong Son Date: 01/09/2021 Program: Exercise_04_page_182.py Problem: 4. Explain what happens when the following recursive function is called with the value 4 as an argument: def example(n): if n > 0: print(n) example(n - 1) Solution: Result: - Print to the screen the numbers from 10 to 1 """ def example(n): if n > 0: print(n) example(n - 1) def main(): example(10) main()
true
4ba7d4715f7716794594ae54630d63a3ad3e3745
sonht113/PythonExercise
/HoTrongSon_50150_chapter3/Chapter3/Project_page_99-101/project_07_page_100.py
1,986
4.1875
4
""" Author: Ho Trong Son Date: 24/07/2021 Program: project_07_page_100.py Problem: 7. Teachers in most school districts are paid on a schedule that provides a salary based on their number of years of teaching experience. For example, a beginning teacher in the Lexington School District might be paid $30,000 the first year. For each year of experience after this first year, up to 10 years, the teacher receives a 2% increase over the preceding value. Write a program that displays a salary schedule, in tabular format, for teachers in a school district. The inputs are the starting salary, the percentage increase, and the number of years in the schedule. Each row in the schedule should contain the year number and the salary for that year. Solution: """ # Code here: def checkYear(year): while not 0 < year < 11: year = float(input("Enter years of service: ")) # input salary = float(input("Enter starting salary: $ ")) rate = float(input("Enter salary increase rate: ")) year = int(input("Enter years of service: ")) checkYear(year) print("\n%10s %20s %25s %18s" % ("Year", "Starting salary", "Salary increase rate", "Ending salary")) for i in range(1, year+1): endSalary = salary + (salary * rate/100) print("%9s %18s %17s %26s" % (i, "$ " + str(round(salary, 1)), str(round(rate))+"%", "$ " + str(round(endSalary, 1)))) salary = endSalary # Result here: # Enter starting salary: $ 2000 # Enter salary increase rate: 3 # Enter years of service: 5 # # Year Starting salary Salary increase rate Ending salary # 1 $ 2000.0 3% $ 2060.0 # 2 $ 2060.0 3% $ 2121.8 # 3 $ 2121.8 3% $ 2185.5 # 4 $ 2185.5 3% $ 2251.0 # 5 $ 2251.0 3% $ 2318.5
true
9ddbfa493304a945a607310e245ba8265ebd8a26
AAM77/Daily_Code_Challenges
/codewars/6_kyu/python3/who_likes_it.py
2,339
4.28125
4
# Name: Who Likes It # Source: CodeWars # Difficulty: 6 kyu # # URL: https://www.codewars.com/kata/who-likes-it/train/ruby # # # Attempted by: # 1. Adeel - 03/06/2019 # # ################## # # # Instructions # # # ################## # # # You probably know the "like" system from Facebook and other pages. People can # "like" blog posts, pictures or other items. We want to create the text that # should be displayed next to such an item. # # Implement a function likes :: [String] -> String, which must take in input # array, containing the names of people who like an item. It must return the # display text as shown in the examples: # # likes [] // must be "no one likes this" # likes ["Peter"] // must be "Peter likes this" # likes ["Jacob", "Alex"] // must be "Jacob and Alex like this" # likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this" # likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this" # For 4 or more names, the number in and 2 others simply increases. ################# # PseudoCode: # ################# # Five scenarios: # (1) Empty => no one likes this # (2) One => 1 likes this # (3) Two => 0 & 1 like this # (4) Three => 0, 1 & 2 like this # (5) Four => 0, 1, & # others like this # if empty: # return 'no one likes this' # elsif length == 1: # return 'name1 likes this' # elsif length == 2: # return 'name1 and name2 like this' # elsif length == 3: # return 'name1, name2, and name3 like this' # else: # return 'name1, name2, & remaining # others like this' # end #################### # PYTHON SOLUTIONS # #################### #*******************# # Adeel’s Attempt 1 # #*******************# # This is the attempt I made after the session def likes(names): if len(names) == 0: return 'no one likes this' elif len(names) == 1: return "{names[0]} likes this".format(names=names) elif len(names) == 2: return "{names[0]} and {names[1]} like this".format(names=names) elif len(names) == 3: return "{names[0]}, {names[1]} and {names[2]} like this".format(names=names) else: return "{names[0]}, {names[1]} and {remaining} others like this".format(names=names, remaining = len(names)-2)
true
fca476b8dd0f39eacd82ee137010acc742dfb1c3
keshopan-uoit/CSCI2072U
/Assignment One/steffensen.py
1,470
4.28125
4
# Keshopan Arunthavachelvan # 100694939 # January 21, 2020 # Assignment One Part Two def steffensen(f, df, x, epsilon, iterations): ''' Description: Calculates solution of iterations using Newton's method with using recursion Parameters f: function that is being used for iteration (residual) df: derivative of the function f x: initial point epsilon: lower bound for when the iteration should terminate (estimated error) iterations: maximum number of iterations ''' # Iterates through the Steffensen's iteration for i in range(0, iterations): # Variable Instantiation y1 = x # Performs Newton's step and stores values y2 = x - float(f(y1))/float(df(y1)) y3 = x - float(f(y2))/float(df(y2)) # Using the previously saves values from Newton's Steps, perform an iteration with Steffensen's iterations x = y1 - ((y2 - y1) ** 2 / (y3 - (2 * y2) + y1)) # If current solution is less than the estimated error or residual, then print converged and break the loop print('The solution at the ' + str(i) + 'th iteration is ' + str(f(x)) + '.') if (f(x) < epsilon): print "Converged" return x # If current iteration exceeds maximum number of iterations, print the current solution and return null print('Next iteration exceeds maximum number of iterations. Current solution is ' + str(f(x)) + ". \nDoes not Converge.") return None
true
eae0607b690abe39fd59214c1d018ac0ddc24d13
fhorrobin/CSCA20
/triangle.py
290
4.125
4
def triangle_area(base, height): """(number, number) -> float This function takes in two numbers for the base and height of a triangle and returns the area. REQ: base, height >= 0 >>> triangle_area(10, 2) 10.0 """ return float(base * height * 0.5)
true
42467a9b02e36935f5c34815dc53081841a156fb
tsung0116/modenPython
/program02-input.py
479
4.125
4
user_name = input("Enter your name:") print("Hello, {name}".format(name=user_name)) principal = input("Enter Loan Amount:") principal = float(principal) interest = 12.99 periods = 4 n_years = 2 final_cost = principal * (1+interest/100.0/periods)**n_years print(final_cost) print("{cost:0.02f}".format(cost=final_cost)) print("Total Interest Paid: {interest:0.02f}".format(interest=final_cost-principal)) print("Monthly Payments: {payment:0.02f}".format(payment=final_cost/24))
true
b64bed1f594bd9703b82659dc96c2313b05fc621
mateusrmoreira/Curso-EM-Video
/desafios/desafio24.py
280
4.1875
4
""" 16/03/2020 jan Mesu Crie uma programa que peça o nome de uma cidade e diga se a cidade começa ou não com a palavra SANTO """ cidade = str(input('Escreva o nome da sua cidade :> ')).strip().upper() santo = cidade[:6] print(f'Tem santo no nome da cidade? {"SANTO " in santo}')
false
e28f61aba7d0d793a4ceac0b89a24ac245c0d06e
DanaAbbadi/data-structures-and-algorithms-python
/tests/stacks_and_queues/test_queues.py
1,822
4.125
4
from data_structures_and_algorithms.stacks_and_queues_challenges.queue import (Queue, Node) def test_create_empty_Queue(): nums = Queue() assert nums.front == None def test_enqueue_one_value(): nums = Queue() nums.enqueue(1) assert nums.front.value == 1 def test_enqueue_multiple_values(): nums = Queue() nums.enqueue(1,3,5,9) assert nums.front.value == 1 assert nums.__str__() == 'front->1->3->5->9-> rear' def test_dequeue(): # Stand Alone testing: nums = Queue() node = Node(1) nums.rear = node nums.front = node actual = nums.dequeue() expected = 1 assert actual == expected # Using methods from Queue class: nums.enqueue(100,13) actual = nums.dequeue() expected = 100 assert actual == expected def test_dequeue_from_empty_Queue(): nums = Queue() actual = nums.dequeue() expected = 'Queue is empty' assert actual == expected def test_emptying_queue_with_multi_dequeue(): nums = Queue() # Stand Alone testing: node = Node(1) nums.rear = node nums.front = node temp = nums.rear nums.rear = Node(13) temp.next = nums.rear nums.dequeue() nums.dequeue() actual = nums.dequeue() expected = 'Queue is empty' assert actual == expected # Using methods from Queue class: nums.enqueue(100,13) nums.dequeue() nums.dequeue() actual = nums.dequeue() expected = 'Queue is empty' assert actual == expected def test_peek(): nums = Queue() node = Node(13) nums.rear = node nums.front = node actual = nums.peek() expected = 13 assert actual == expected def test_peek_on_empty_Queue(): nums = Queue() actual = nums.peek() expected = 'Queue is empty' assert actual == expected
false
0e034002296b0cf3d7c0486907d571802341606d
DanaAbbadi/data-structures-and-algorithms-python
/data_structures_and_algorithms/stacks_and_queues_challenges/stacks.py
1,922
4.28125
4
from data_structures_and_algorithms.stacks_and_queues_challenges.node import Node # from node import Node class Stack(Node): def __init__(self): self.top = None def push(self, *args): """ Takes a single or multiple values as an argument and adds the new nodes with that value to the front of the stack. Arguments: *args -- list of values with variable length """ for i in args: new_node = Node(i) temp = self.top self.top = new_node new_node.next = temp def pop(self): """ * Removes the node from the front of the queue, and returns the node’s value. * Will raise an exception if the queue is empty. """ try: value = self.top.value self.top = self.top.next return value except AttributeError as error: return 'Stack is empty' def peek(self): """ * Returns the value of the node located in the front of the queue, without removing it from the queue. * Will raise an exception if the queue is empty """ try: return self.top.value except AttributeError as error: return 'Stack is empty' def isEmpty(self): """ Checks whether or not the Queue is empty. """ return False if self.top else True def __str__(self): current = self.top output = 'top->' while current: output += f"{current.value}->" current = current.next output+=" NULL" return output if __name__ == "__main__": adjectives = Stack() adjectives.push('smart','unique') adjectives.push('fluffy') print(adjectives) print(adjectives.pop()) print(adjectives.peek()) print(adjectives.isEmpty())
true
ddb6bb1bc35904275e44ba87e46cf1efe7983c0f
DanaAbbadi/data-structures-and-algorithms-python
/data_structures_and_algorithms/challenges/binary_tree/breadth_first.py
1,541
4.1875
4
class Node: def __init__(self,value): self.value = value self.left = None self.right = None class BinaryTree: """ This class is responsible of creating and traversing the Binary Search Tree. """ def __init__(self): self.root = None def breadth_first(self, root): """ Traverse the tree using Breadth First approach where the Node Values at each level of the Tree are traversed before going to next level. """ try: queue = [] breadth = [] if not root: return 'Tree is empty' else: if root: queue.append(root) while queue: current = queue.pop(0) breadth.append(current.value) if current.left: queue.append(current.left) if current.right: queue.append(current.right) return breadth except Exception as e: return f'An error occured, {e}' if __name__ == "__main__": bt = BinaryTree() bt.root = Node(2) bt.root.left = Node(7) bt.root.right = Node(5) bt.root.left.left = Node(2) bt.root.left.right = Node(6) bt.root.left.right.left = Node(5) bt.root.left.right.right = Node(11) bt.root.right.right = Node(9) bt.root.right.right.left = Node(4) # 2 7 5 2 6 9 5 11 4 print(bt.breadth_first(bt.root))
true
30b58144b16e936bea70ff6d1bb79c56db04947c
avikchandra/python
/Python Assignment/centredAverage.py
574
4.28125
4
#!/usr/bin/env python3 ''' "centered" average of an array of integers ''' # Declare the list num_list=[-10, -4, -2, -4, -2, 0] # Find length list_len=len(num_list) # Check if length is odd or even if list_len%2 == 0: # For even length, find average of two centred numbers mean_result=(num_list[list_len//2 -1] + num_list[list_len//2]) // 2 else: # For odd length, find the centred number mean_result=num_list[list_len//2] # Print value print("The given list is: \n", num_list) print("Centered mean value is: ", mean_result)
true
8d812c5251edda45c2a531b9bf28ed4b138e233c
avikchandra/python
/Python Assignment/wordOccurence.py
1,459
4.125
4
#!/usr/bin/env python3 ''' highest occurences of words in file "sample.txt" ''' def main(): # Declare dict word_dict={} punct_list=[',','.','\'',':','?','-'] # list of punctuations # Create file object from file file_obj=open("sample.txt", 'r') word_list=[] # Read line from file object for line in file_obj: # Strip the punctuations from line for punct in punct_list: line=line.replace(punct,'') # Get words from line for word in line.split(): # Append to list word_list.append(word.lower()) word_dict=updateDict(word_list, word_dict) print("Top five word occurences: ") for num in range(5): print(findHighest(word_dict)) # Close the file file_obj.close() def updateDict(word_list, word_dict): # Update dictionary with word count for word in word_list: word_dict[word]=word_list.count(word) return word_dict def findHighest(word_dict): # Check for occurences from dictionary highest_num=0 for entry in word_dict: curr_count=int(word_dict[entry]) if curr_count > highest_num: highest_num=curr_count highest_word=entry # Remove the word from dict word_dict.pop(highest_word) # Return the highest occurence return (highest_word, highest_num) if __name__ == '__main__': main()
true
fbb14a7e554803b8d3e42998a545bd399ab9c795
avikchandra/python
/Python Advanced/sentenceReverse.py
303
4.4375
4
#!/usr/bin/env python3 ''' Reverse words in sentence ''' # Take input from user orig_string=input("Enter the string: ") str_list=orig_string.split() # Option1 #str_list.reverse() #print(' '.join(str_list)) # Option2 reversed_list=list(str_list[::-1]) print(' '.join(reversed_list))
true
2f6421bb1c3a27757237ea75657e5e1e62ad9d3d
danlunin/dictionaries
/Dict_list.py
1,208
4.125
4
#!/usr/bin/env python3 class Dictionary: def __init__(self, dict_list=None): if dict_list: self.dict_list = dict_list else: self.dict_list = [] def __str__(self): return str(self.dict_list) def __repr__(self): return str(self.dict_list) def __getitem__(self, item): for e in self.dict_list: if e[0] == item: return e[1] raise KeyError def __setitem__(self, key, value): for e in self.dict_list: if e[0] == key: self.dict_list.remove(e) self.dict_list.append((key, value)) return self.dict_list.append((key, value)) def __delitem__(self, key): for e in self.dict_list: if e[0] == key: self.dict_list.remove(e) return raise KeyError def size(self): return len(self.dict_list) def main(): a = Dictionary() a[1] = 'Ok' a[2] = 'q' a[1] = 0 a[7] = 'p' a[10] = 1 a[0] = 5 a[3] = 2 print(a.size()) print(a) print(a[7]) b = Dictionary() print(b) if __name__ == '__main__': main()
false
ee1aeab37fc4b91f7f8f65b50aba287b8e9c1801
Joldiazch/holbertonschool-higher_level_programming
/0x06-python-classes/2-square.py
460
4.375
4
#!/usr/bin/python3 class Square: """class Square that defines a square by: (based on 0-square.py) Attributes: size_of_square (int): Description of `attr1`. """ def __init__(self, size_of_square=0): if type(size_of_square) is not int: raise TypeError('size must be an integer') elif size_of_square < 0: raise ValueError('size must be >= 0') else: self.__size = size_of_square
true
54c574df0d191bcd3e68f076859588c74827b1ef
beckam25/ComputerScience1
/selectionsort.py
2,652
4.375
4
""" file: selectionsort.py language: python3 author: bre5933@rit.edu Brian R Eckam description: This program takes a list of numbers from a file and sorts the list without creating a new list. Answers to questions: 1) Insertion sort works better than selection sort in a case where you have a very long list that you wish to be sorted. 2)Selection sort is worse in this case because it would search the list for the lowest(or highest) index remaining in the list THEN put it at the end of the sorted list. Insertion sort would take the next unsorted index and insert it where it belonged in the sorted part of the list. """ def swap(lst, x, y): """ Swap two indexes in a list :param lst: The list to be swapped in :param x: first index to swap :param y: second index to swap :return: list with x and y swapped """ temporary = lst[x] lst[x] = lst[y] lst[y] = temporary def find_min(lst): """ Find the minimum index in a list :param lst: THe list to look in :return: the minimum in the list """ if len(lst) > 0: minimum = lst[0] for index in range(1, len(lst)): if lst[index] < minimum: minimum = lst[index] return minimum def search_in_list(lst, number): """ Finding the index of a number. In this case the minimum. :param lst: The list to look in. :param number: The number to look for. :return: The index where the number is located in the list """ for index in range(len(lst)): if number == lst[index]: return index return None def selection_sort(lst): """ Sorting function that will sort integers in a list from lowest to highest :param lst: The list to be sorted :return: A sorted version of the list from low to high """ x = 0 while x < len(lst): minimum = find_min(lst[x:]) found = search_in_list(lst[x:], minimum) + x # add x to account for all indexes before the slice swap(lst, found, x) x = x + 1 print("The sorted list:") print(lst) def main(): """ The main function which imports a user input list and sends that list to the sorting function. :return: The sorted list """ filename = input("filename: ") text = open(filename) lst = [] count = 0 for line in text: lst = lst + line.split() new_lst = [] for char in lst: new_lst.append(char) print("The original list:") print(new_lst) selection_sort(new_lst) main()
true
079ac76649cfff4b61345dd077e68178de0ffc52
joseluismendozal10/test
/DATA ANALYTICS BOOTCAMP/June 19/Python/2/quick check up .py
266
4.125
4
print("Hello user") name = input("what is your name?") print ("Hello" + name) age = int(input("whats your age?")) if age >= 21: print("Ah, a well traveled soul you are ye") else: print("aww.. you're just a baby!")
true
ebca2a200c8e7b27ae234835003b6d15e0d6a3cd
JaiberS/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
372
4.21875
4
#!/usr/bin/python3 """ >>> add_integer(2, 3) 5 """ def add_integer(a, b=98): """ >>> c = add_integer(2, 3) """ if type(a) is not int: if type(a) is not float: raise TypeError('a must be an integer') if type(b) is not int: if type(b) is not float: raise TypeError('b must be an integer') return int(a + b)
false
25f5ba74734da7afb773999499cca4c79685c717
r0hansharma/pYth0n
/prime number.py
319
4.125
4
no=int(input('enter the no to check\n')) if(no>1): for i in range(2 , no): if(no%i==0): print(no,'is not a prime number') else: print( no,"is a prime number") elif(no==1): print("1 is neither a prime nor a compposite number") else: print("enter a number greater than 1")
true
27908d6450779964609a859a83c29decd4e67d3e
bnsh/coursera-IoT
/class5/week4/leddimmer.py
605
4.25
4
#! /usr/bin/env python3 """This is week 4 of the Coursera Interfacing with the Raspberry Pi class. It simply dims/brightens the LED that I've attached at pin 12 back and forth.""" import math import time import RPi.GPIO as GPIO def main(): GPIO.setmode(GPIO.BOARD) GPIO.setup(12, GPIO.OUT) pwm = GPIO.PWM(12, 50) pwm.start(0) # So, let's make a sine wave. try: while True: for theta in range(0, 360): rate = 100.0 * (1.0 + math.sin(theta * math.pi / 180.0)) / 2.0 pwm.ChangeDutyCycle(rate) time.sleep(2.0/360.0) finally: GPIO.cleanup() if __name__ == "__main__": main()
true
e2fda25298068dda88406226945b707a7514a200
JesNatTer/python_fibonacci
/fibonacci.py
464
4.1875
4
numbers = 20 # amount of numbers to be displayed def fibonacci(n): # function for fibonacci sequence if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2) # function formula for fibonacci if numbers <= 0: print("Please enter positive value") # amount of numbers cannot be less than 1 else: for i in range(numbers): # amount of numbers is 1 or more, so sequence is printed print(fibonacci(i), end= " ")
true
15cfa3ed4506417d5eb879b43e1ac0a6f3d9b5bc
Moiseser/pythontutorial
/ex15.py
719
4.375
4
#This allows your script to ask you on the terminal for an input from sys import argv #this command asks you what the name of your text file you want to read is script,filename = argv #this opens the file and then assigns the opened file to a variable txt = open(filename) #here we print the name of the file print 'Heres your file %s' % filename #here the contents of the file are printed onto the terminal print txt.read() #text is printed on the terminal print 'Type the filename again' #here we again manually input into script whht the name of the of the file is file_again = raw_input('>') #the opened file again is assigned to this variable txt_again = open(file_again) #contents printed print txt_again.read()
true
98442c545f269213e63e8a6f966c01db056c21f5
Moiseser/pythontutorial
/ex3.py
562
4.375
4
print "I will now count my chickens:" print 'Hens' , 25+30/6 print 'Roosters', 100-25 * 3 % 4 print 'What is 4 % 3' , 4 % 3 print 'Now I will count my eggs:' print 3 + 2 +1 -5 +4 % 2 -1 /4 + 6 print '1 divide by 4' , 1/4 print '1.0 dive by 4.0' , 1.0/4.0 print 'It is 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, thats 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
true
1f13b414cb94ff7e57a9a2a41ac470e41dfd52ba
dongjulongpy/hackerrank_python
/Strings/find_a_string.py
385
4.1875
4
def count_substring(string, sub_string): string_list = list() length = len(sub_string) for i in range(len(string)-length+1): string_list.append(string[i:i+length]) return string_list.count(sub_string) if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count)
true
76265670bce143a07b85821de09bab6355a40e92
LisaLen/code-challenge
/interview_cake_chals/find_rotation_point.py
1,661
4.125
4
'''I opened up a dictionary to a page in the middle and started flipping through, looking for words I didn't know. I put each word I didn't know at increasing indices in a huge list I created in memory. When I reached the end of the dictionary, I started from the beginning and did the same thing until I reached the page I started at. Now I have a list of words that are mostly alphabetical, except they start somewhere in the middle of the alphabet, reach the end, and then start from the beginning of the alphabet. In other words, this is an alphabetically ordered list that has been "rotated." For example: >>> find_rotation_point(['ptolemaic', 'retrograde', 'supplant', 'undulate', 'xenoepist', 'asymptote', 'babka', 'banoffee', 'engender', 'karpatka', 'othellolagkage']) 5 Write a function for finding the index of the "rotation point," which is where I started working from the beginning of the dictionary. This list is huge (there are lots of words I don't know) so we want to be efficient here.''' def find_rotation_point(lst): '''return index of rotation point''' if not lst: return floor_indx = 0 ceiling_indx = len(lst) - 1 while (ceiling_indx - floor_indx) > 1: middle_indx = (ceiling_indx - floor_indx) // 2 + floor_indx if lst[middle_indx] < lst[ceiling_indx]: ceiling_indx = middle_indx else: floor_indx = middle_indx if lst[floor_indx] < lst[ceiling_indx]: return floor_indx return ceiling_indx if __name__ =='__main__': import doctest if doctest.testmod().failed == 0: print('\n***PASSED***\n')
true
0b98b66200151b0dc6bd322824f2d53b37e2329c
LisaLen/code-challenge
/primes/primes.py
927
4.28125
4
"""Return count number of prime numbers, starting at 2. For example:: >>> is_prime(3) True >>> is_prime(24) False >>> primes(0) [] >>> primes(1) [2] >>> primes(5) [2, 3, 5, 7, 11] """ def is_prime(number): assert number >= 0 if number < 2: return False if number == 2: return True if number % 2 == 0: return False n = 3 while n*n < number: if number % n == 0: return False n += 2 return True def primes(count): """Return count number of prime numbers, starting at 2.""" numbers = [] i = 2 j = 0 while j < count: if is_prime(i): numbers.append(i) j += 1 i += 1 return numbers if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print("\n*** ALL TESTS PASSED. GREAT WORK!\n")
true
1c627ef942bc3401647b955fda0cd4a9139e6e57
iliakur/python-experiments
/test_strformat.py
1,311
4.125
4
"""12/08/2016 my colleague Leela reported getting a weird error. She was trying to perform an equivalent of the following string interpolation: `" a {0}, b {1}".format(some_dict["key"], ["key2"])` She had forgotten to type `some_dict` for the second argument of `format`. However the error she got was unrelated to that. She was namely told that list indices must be integers, not strings. At the time I was pretty certain Unfortunately I didn't get a chance to check her Python interpreter version, so I have to test this in both 3 and 2. """ import pytest def test_format_insert_list(): """I think what Leela was indexing as a dictionary was in fact a list. This test clearly demonstrates that .format can handle raw lists as arguments. """ tpl = "a {0}, b {1}" d = {4: 3} assert tpl.format(d[4], [3]) == 'a 3, b [3]' assert tpl.format(d[4], ["3"]) == "a 3, b ['3']" def test_format_insert_list_str_indx(): """Confirming that we should get the error Leela and I saw if we in fact index a list as if it were a dictionary. """ tpl = "a {0}, b {1}" l = [2, 3] with pytest.raises(TypeError) as exc_info: assert tpl.format(l["4"], ["5"]) == 'a 3, b ["5"]' assert str(exc_info.value) == "list indices must be integers or slices, not str"
true
e50d72ab79c96789a88454a52ceb0c54985130e9
Lusarom/progAvanzada
/ejercicio38.py
825
4.5
4
#Exercise 38: Month Name to Number of Days #The length of a month varies from 28 to 31 days. In this exercise you will create #a program that reads the name of a month from the user as a string. Then your #program should display the number of days in that month. Display “28 or 29 days” #for February so that leap years are addressed. print('List of months: January, February, March, April, May, June, July, August, September, October, November, December') month_name = input("Input the name of Month: ") if month_name == 'February': print('No. of days: 28/29 days') elif month_name in ('April', 'June', 'September', 'November'): print('No. of days: 30 days') elif month_name in ('January', 'March', 'May', 'July', 'August', 'October', 'December'): print('No. of days: 31 day') else: print('Error month name')
true
beeea37473e0c78c74d28ca618548df2fab1cf0b
Lusarom/progAvanzada
/ejercicio40.py
766
4.5
4
#Exercise 40: Name that Triangle #A triangle can be classified based on the lengths of its sides as equilateral, isosceles #or scalene. All 3 sides of an equilateral triangle have the same length. An isosceles #triangle has two sides that are the same length, and a third side that is a different #length. If all of the sides have different lengths then the triangle is scalene. #Write a program that reads the lengths of 3 sides of a triangle from the user. #Display a message indicating the type of the triang print("Input lengths of the triangle sides: ") x = int(input("x: ")) y = int(input("y: ")) z = int(input("z: ")) if x == y == z: print("Equilateral triangle") elif x==y or y==z or z==x: print("isosceles triangle") else: print('Scalene triangle")
true
b2c18894797ee2043d24a28316aa7e6884bcfeb3
Lusarom/progAvanzada
/ejercicio41.py
796
4.3125
4
#Exercise 41: Note To Frequency #The following table lists an octave of music notes, beginning with middle C, along #with their frequencies (Hz) #Note Frequency # C4 261.63 # D4 293.66 # E4 329.63 # F4 349.23 # G4 392.00 # A4 440.00 # B4 493.88 nombre = input('Inserta el nombre de la nota:') nota = nombre[0].upper() octave = int(nombre[1]) frequencia = -1 if nota == "C": frequencia = 261.63 elif nota == "D": frequencia = 293.66 elif nota == "E": frequencia = 329.63 elif nota == "F": frequencia = 349.23 elif nota == "G": frequencia = 392.00 elif nota == "A": frequencia = 440.00 elif nota == "B": frequencia = 493.88 frequencia /= 2 ** (4 - octave) print('La nota es:' ,nota, 'frequencia es ',(frequencia), 'Hz')
false
79b32bf67300146e872698d4b3ad2779c0914829
mmeitesDIM/USMB-BachelorDIM-Algo--PUBLIC
/assignments/Session1/S1remove_whiteSpace.py
1,261
4.3125
4
# -*- coding: utf-8 -*- """ brief : remove whitespace caracter in a string Args : # @input_string : the string to remove whitespace # @return the string without whitespace raise : """ def remove_whitespace(input_string): if len(input_string)==0: print('aucune chaîne de caractère en entrée') tmp_char ="" list_index = [] #list_index[0] = 0 result_string="" tmpElt = 0 # search whitespace caracter index in input_string for index in range (len(input_string)): tmp_char = input_string[index] if tmp_char ==" " : list_index.append(index); # delete whitespace caracter for index in range (len(input_string)): for elt in list_index: if index == elt: if result_string=="": result_string = input_string[:elt] else: result_string += input_string[tmpElt:elt] tmpElt = elt+1 result_string += input_string[tmpElt:] return result_string # Test script test_string = 'il en faut peu pour etre heureux'#↨ create a fake tab result_string = remove_whitespace(test_string) print(result_string)
false
32799865345f5c901d665edadf4cc0904cbaff3d
DJBlom/Python
/CS1101/Unit_7/Discussion.py
1,141
4.65625
5
""" This is a program to demonstrate how tuples can be usefull loops over lists and dictionaries. """ def listZip(): st = 'Code' li = [0, 1, 2, 3] print('Zip function demo.') t = zip(li, st) for i, j in t: print(i, j) """ The zip function is used to iterate over two or more collections/lists in a parrallel way. Furthermore, the tuple collection it returns can be very useful to navigate the list """ def listEnum(): print('\nEnumerate function demo.') for i, j in enumerate('Code'): print(i, j) """ The enumerate function will iterate over list items and it's indices. """ def listItem(): d = {0 : 'I', 1 : 'love', 2 : 'to', 3 : 'code', 4 : 'CodeForTheWin'} print('\nItem functions demo.') for i, j in d.items(): print(i, j) """ The items function will return a list of tuples/sequence of tuples that are mapped together with a key to the value of that key. """ def main(): listZip() listEnum() listItem() main()
true
4a2455564ea6478e6ea519a97befc90cc8a3aed2
nimkha/IN4110
/assignment3/wc.py
1,391
4.46875
4
#!/usr/bin/env python import sys def count_words(file_name): """ Takes file name and calculates number of words in file :param file_name: :return: number of words in file """ file = open(file_name) number_of_words = 0 for word in file.read().split(): number_of_words += 1 return number_of_words def count_lines(file_name): """ Takes file name and calculates number of lines in file :param file_name: :return: number of lines in file """ number_of_lines = len(open(file_name).readlines()) return number_of_lines def count_characters(file_name): """ Takes file name and calculates number characters in a file. This version excludes white spaces :param file_name: :return: number of characters in file excluding white spaces """ file = open(file_name) data = file.read().replace(" ", "") counter = len(data) return counter def main(): """ Main function, runs the program :return: no return value """ arguments = sys.argv[1:] for file in arguments: number_of_words = count_words(file) number_of_lines = count_lines(file) number_of_characters = count_characters(file) print(f"#characters -> {str(number_of_characters)}, #words -> {str(number_of_words)}, #lines -> {str(number_of_lines)}, file name -> {file}") main()
true
3626f86acddcde796092a53d014f8f50137ace0a
prasannatuladhar/30DaysOfPython
/day17.py
1,685
4.375
4
""" 1) Create a function that accepts any number of numbers as positional arguments and prints the sum of those numbers. Remember that we can use the sum function to add the values in an iterable. 2) Create a function that accepts any number of positional and keyword arguments, and that prints them back to the user. Your output should indicate which values were provided as positional arguments, and which were provided as keyword arguments. 3) Print the following dictionary using the format method and ** unpacking. country = { "name": "Germany", "population": "83 million", "capital": "Berlin", "currency": "Euro" } 4) Using * unpacking and range, print the numbers 1 to 20, separated by commas. You will have to provide an argument for print function's sep parameter for this exercise. 5) Modify your code from exercise 4 so that each number prints on a different line. You can only use a single print call. """ # 1 Solutions def sum_to_any_num(*anynum): return sum(anynum) print(sum_to_any_num(2,4,5)) # 2 Solutions def prnt_info(*name,**info): for n in name: print(f"Namaste! {n}") for k,v in info.items(): print(f"{k.title()}:{v}") prnt_info("Prasanna","Ram","Mahesh", occupation="Engineer", age=36, gender="Male") #3 Solutions country = { "name": "Germany", "population": "83 million", "capital": "Berlin", "currency": "Euro" } template = """ Name:{name}, Population:{population}, Capital:{capital}, Currency:{currency} """ print(template.format(**country)) #4 Solutions # def print_to_20(*num): # print(num) # print_to_20(*range(1,21)) print(*range(1,21),sep=",") #5 Solutions print(*range(1,21),sep="\n")
true
35d7c42f4c010a1e13be3938b4f5a9853ac1be3b
prasannatuladhar/30DaysOfPython
/day16.py
1,224
4.5625
5
""" 1) Use the sort method to put the following list in alphabetical order with regards to the students' names: students = [ {"name": "Hannah", "grade_average": 83}, {"name": "Charlie", "grade_average": 91}, {"name": "Peter", "grade_average": 85}, {"name": "Rachel", "grade_average": 79}, {"name": "Lauren", "grade_average": 92} ] You're going to need to pass in a function as a key here, and it's up to you whether you use a lambda expression, or whether you define a function with def. 2) Convert the following function to a lambda expression and assign it to a variable called exp. def exponentiate(base, exponent): return base ** exponent 3) Print the function you created using a lambda expression in previous exercise. What is the name of the function that was created? """ # 1 Solution def get_name(student): return student["name"] students = [ {"name": "Hannah", "grade_average": 83}, {"name": "Charlie", "grade_average": 91}, {"name": "Peter", "grade_average": 85}, {"name": "Rachel", "grade_average": 79}, {"name": "Lauren", "grade_average": 92} ] sorted_name = sorted(students, key=get_name) print(sorted_name) # 2 Solution exp = lambda bs, expo: bs ** expo # 3 Solution print(exp(2,3))
true
a6b674c546b274b86005d37f47214a4395906407
alexeysorok/Udemy_Python_2019_YouRa
/Basics/03_string.py
927
4.28125
4
greeting = "Hello!" first_name = "Jack" last_name = "White" print(greeting + ' ' + first_name + ' ' + last_name) print(len(greeting)) # длина print(greeting[-1]) print(greeting[2:5]) print(greeting[::-1]) # перевернуть строку print(greeting.upper()) print(greeting.lower()) print(greeting.split()) # разделяет по пробелам # форматирование name = "Jack" age = 23 name_and_age = "My name is {0}. I\'m {1} years old.".format(name, age) name_and_age2 = "My name is {0}. I\'m {1} years old.".format('Dan', 28) name_and_age3 = "My name is {}. I\'m {} years old.".format('Ran', 30) print(name_and_age) week_days = "There are 7 days in a week: {mon}."\ .format(mon="Monday") print(week_days) float_result = 1000 / 7 print('The result of division is {0:1.3f}'.format(float_result)) # new 3.6 name_and_age = f'My name is {name}. I\'m {age} years old' print(name_and_age)
true
2baf17cc2c72406fcc1f3b089a986727cfd25230
ztnewman/python_morsels
/circle.py
619
4.21875
4
#!/usr/bin/env python3 import math class Circle: def __init__(self,radius=1): if radius < 1: raise ValueError('A very specific bad thing happened') self.radius = radius def __str__(self): return "Circle("+str(self.radius)+")" def __repr__(self): return "Circle("+str(self.radius)+")" @property def diameter(self): return self.radius*2 @property def area(self): return (self.radius**2) * math.pi @diameter.setter def diameter(self,diameter): self.diameter = diameter self.radius = diameter / 2
true
52b40ae26017b13d5f259c7790c95987186e71bd
erinszabo/260week_5
/main.py
2,301
4.34375
4
""" Chapter 6 in Runestone Exercises: 2, 3 - Do the recursive search without slicing. 5, 6, 7, 15, 16 """ if __name__ == '__main__': print("") print("") print("2) Use the binary search functions given in the text (recursive and iterative). Generate a random, " "ordered list of integers and do a benchmark analysis for each one. What are your results? Can you explain " "them?") """ BRAINSTORMING: make 2 methods for binary search, one iterative and one recursive. then make a 'binary_race' method that times and compares the two. """ print("") print("3) Implement the binary search using recursion without the slice operator. Recall that you will need to " "pass the list along with the starting and ending index values for the sublist. Generate a random, " "ordered list of integers and do a benchmark analysis.") print("") print("5) Implement the in method (__contains__) for the hash table Map ADT implementation.") print("") print("6) How can you delete items from a hash table that uses chaining for collision resolution? How about if " "open addressing is used? What are the special circumstances that must be handled? Implement the del method " "for the HashTable class.") print("") print("7) In the hash table map implementation, the hash table size was chosen to be 101. If the table gets full, " "this needs to be increased. Re-implement the put method so that the table will automatically resize itself " "when the loading factor reaches a predetermined value (you can decide the value based on your assessment " "of load versus performance).") print("") print("15) One way to improve the quick sort is to use an insertion sort on lists that have a small length (call " "it the “partition limit”). Why does this make sense? Re-implement the quick sort and use it to sort a " "random list of integers. Perform an analysis using different list sizes for the partition limit.") print("") print("16) Implement the median-of-three method for selecting a pivot value as a modification to quickSort. Run " "an experiment to compare the two techniques.") print("")
true
1aba5ddb6b34e4f6ee1a0d11f74a20de7cf975c8
tannazjahanshahi/tamrinpy
/tamrin3.py
1,151
4.3125
4
# # for i in range(6): # # for j in range(i): # # print ('* ', end="") # # print('') # # for i in range(6,0,-1): # # for j in range(i): # # print('* ', end="") # # print('') # numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Declaring the tuple # cnt_odd=0 # odd_list=[] # cnt_even=0 # even_list=[] # for i in numbers: # if i%2==0: # cnt_even+=1 # even_list.append(i) # else: # cnt_odd+=1 # odd_list.append(i) # print(f'odd numbers are {odd_list} and count is : {cnt_odd }') # print(f'even numbers are {even_list} and count is : {cnt_even }') # 8. Write a Python program that prints all the numbers from 0 to 6 except 3 and 6. # Note : Use 'continue' statement. # Expected Output : 0 1 2 4 5 # x=0 #false # y=1 #true # if not(0): # print("yes") # def Fibonacci(n): # if n<0: # print("Incorrect input") # # First Fibonacci number is 0 # elif n==1: # return 0 # # Second Fibonacci number is 1 # elif n==2: # return 1 # else: # return Fibonacci(n-1)+Fibonacci(n-2) # # Driver Program # print(Fibonacci(25))
true
2eeee06b978d55b99a68eeffa12eb62a127ee0c3
LinhPhanNgoc/LinhPhanNgoc
/page_63_project_09.py
614
4.21875
4
""" Author: Phan Ngoc Linh Date: 02/09/2021 Problem: Write a program that takes as input a number of kilometers and prints the corresponding number of nautical miles. Use the following approximations: • A kilometer represents 1/10,000 of the distance between the North Pole and the equator. • There are 90 degrees, containing 60 minutes of arc each, between the North Pole and the equator. • A nautical mile is 1 minute of an arc. Solution: .... """ km = float(input("Enter the number of kilometers = ")) nautical = (km * 90 * 60) / 10000 print("Nautical miles =", nautical, "nauts")
true
b4f79d10f725f9ab9120f67282f4d34726f60430
hafizur-r/Python
/week_2/Problem2_5.py
1,324
4.40625
4
""" Problem 2_5: Let's do a small simulation. Suppose that you rolled a die repeatedly. Each time that you roll the die you get a integer from 1 to 6, the number of pips on the die. Use random.randint(a,b) to simulate rolling a die 10 times and printout the 10 outcomes. The function random.randint(a,b) will generate an integer (whole number) between the integers a and b inclusive. Remember each outcome is 1, 2, 3, 4, 5, or 6, so make sure that you can get all of these outcomes and none other. Print the list, one item to a line so that there are 10 lines as in the example run. Make sure that it has 10 items and they are all in the range 1 through 6. Here is one of my runs. In the problem below I ask you to set the seed to 171 for the benefit of the auto-grader. In this example, that wasn't done and so your numbers will be different. Note that the seed must be set BEFORE randint is used. problem2_5() 4 5 3 1 4 3 5 1 6 3 """ """ Problem 2_5: """ import random def problem2_5(): """ Simulates rolling a die 10 times.""" # Setting the seed makes the random numbers always the same # This is to make the auto-grader's job easier. random.seed(171) # don't remove when you submit for grading for i in range(10): print(random.randint(1,6))
true
34e659a741a9be2903e86f40143d58e38623fa5b
hafizur-r/Python
/week_3/Problem3_4.py
1,400
4.34375
4
#%% """ Problem 3_4: Write a function that is complementary to the one in the previous problem that will convert a date such as June 17, 2016 into the format 6/17/2016. I suggest that you use a dictionary to convert from the name of the month to the number of the month. For example months = {"January":1, "February":2, ...}. Then it is easy to look up the month number as months["February"] and so on. Note that the grader will assume that month names begin with capital letters. *** Tip: In print statements, commas create a space. So you may have difficulty avoiding a space between the 7, 17, and 2016 below and the following comma. I suggest that you build the output as a single string containing the properly formatted date and then print that. You can convert any number to string by using str() and tie the parts together using +. Duplicate the format of the example output exactly. Everything you need to do this is covered in the lectures. *** Here is a printout of my run for June 17, 2016. problem3_4("July",17, 2016) 7/17/2016 """ #%% def problem3_4(mon, day, year): """ Takes date such as July 17, 2016 and write it as 7/17/2016 """ month = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") print(str(month.index(mon)+1)+'/'+str(day)+'/'+str(year))
true
1d8cb954d0348ffababd476a6c0cf61ea093411e
acse-os920/acse-1-assessment-3-acse-os920-master
/acse_la/det.py
742
4.21875
4
import numpy as np def det(a): """ Calculates the determinant of a square matrix of arbitrary size. Parameters ---------- a : np.array or list of lists 'n x n' array Examples -------- >> a = [[2, 0, -1], [0, 5, 6], [0, -1, 1]] >> det(a) 22.0 >> A = [[1, 0, -1], [-2, 3, 0], [1, -3, 2]] >> det(A) 3.0 """ det3 = 0 #a = a.tolist() if(len(a) == 2): value = a[0][0]*a[1][1] - a[0][1]*a[1][0] return value for col in range(len(a)): for r in (a[:0] + a[1:]): ab = [r[:col] + r[col+1:]] if not ab: continue det3 = det3 + (-1)**(0 + col)*det(ab)*a[0][col] return det3
false
885164b1fd52886a7d065fd8cdadf1b7b15d9d57
yanjun91/Python100DaysCodeBootcamp
/Day 9/blind-auction-start/main.py
978
4.15625
4
from replit import clear from art import logo #HINT: You can call clear() to clear the output in the console. print(logo) print("Welcome to the secret auction program.") continue_bid = True bidders = [] while continue_bid: name = input("What is your name?: ") bid = int(input("What's your bid?: $")) # Store names and bids into dictionary then into list bidder = {} bidder["name"] = name bidder["bid"] = bid bidders.append(bidder) more_bidder = input ("Are there any other bidders? Type 'yes' or 'no'.\n") if more_bidder == "no": continue_bid = False elif more_bidder == "yes": clear() def find_bid_winner(bidders_list): highest_bid = 0 winner = "" for bidder_dict in bidders_list: if bidder_dict["bid"] > highest_bid: winner = bidder_dict["name"] highest_bid = bidder_dict["bid"] print(f"The winner is {winner} with a bid of ${highest_bid}") find_bid_winner(bidders)
true
87465432a6a8898d2c138ea3fd51b5156fdd146f
BeLEEU/AI-For-CV
/每日一题/basic/Begining/003.py
601
4.125
4
415. ЧĴ һַжǷΪһĴֻĸ֣ԴСд 1: : "A man, a plan, a canal: Panama" : true : "amanaplanacanalpanama" 2: : "race a car" : false : "raceacar" import re class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ s=s.lower() s=re.sub(r'[^a-z0-9]', "",s) for i in range(int(len(s)/2)): if s[i]!=s[len(s)-1-i]: return False return True
false
ae0e1ab06706b644f72d16c2f6dafe0be4ef814a
xufeng010203/ML
/alogorithm/02_归并排序.py
1,103
4.1875
4
''' 归并排序 :分治 84571362 8457 1362 84 57 13 62 8 4 5 7 1 3 6 2 48 57 13 62 4578 1236 12345678 ''' def merge(left, right): """ 合并两个有序数组 :param left: arr :param right: arr :return: """ l, r = 0, 0 result = [] while l < len(left) and r < len(right): if left[l] < right[r]: """ 如果左边都比右边的小 """ result.append(left[l]) l += 1 else: result.append(right[r]) r += 1 #如果左边的值都比右边的小,执行循环后,result就是left,然后要把右边right 和result相加 #同理右边的值都比左边的小, result += left[l:] result += right[r:] return result def merge_sort(li): if len(li) <= 1: return li #二分分解 num = len(li) // 2 left = merge_sort(li[:num]) right = merge_sort(li[num:]) return merge(left, right) alist = [54,26,93,17,77,31,44,55,20] sorted_alist = merge_sort(alist) print(sorted_alist)
false
14620c9f5db9edf4caa28a5df352bcf303f45a6c
vadimsh73/python_tasks
/character string/9_10.py
1,123
4.28125
4
# -*-coding:UTF-8-*- name_1 = input("Первый город") name_2 = input("Второй город") name_3 = input("Третий город") print("Максимальная длина {}".format(max(len(name_1), len(name_2), len(name_3)))) print("Минимальная длина {}".format(min(len(name_1), len(name_2), len(name_3)))) if max(len(name_1), len(name_2), len(name_3)) == len(name_1): print("максимально длинное название {}".format(name_1)) elif max(len(name_1), len(name_2), len(name_3)) == len(name_2): print("максимально длинное название {}".format(name_2)) else: print("максимально длинное название {}".format(name_3)) if min(len(name_1), len(name_2), len(name_3)) == len(name_1): print("Минимально длинное название {}".format(name_1)) elif min(len(name_1), len(name_2), len(name_3)) == len(name_2): print("Минимальноо длинное название {}".format(name_2)) else: print("Минимально длинное название {}".format(name_3))
false
a196a7540550ffb301675dbc5138757faabf422a
MaGo1981/MITx6.00.1x
/MidtermExam/Sandbox-ExtraProblems-NotGraded/Problem9.py
928
4.59375
5
''' Problem 9 1 point possible (ungraded) Write a function to flatten a list. The list contains other lists, strings, or ints. For example, [[1,'a',['cat'],2],[[[3]],'dog'],4,5] is flattened into [1,'a','cat',2,3,'dog',4,5] def flatten(aList): ''' ''' aList: a list Returns a copy of aList, which is a flattened version of aList ''' ''' Click to expand Hint: How to think about this problem Recursion is extremely useful for this question. You will have to try to flatten every element of the original list. To check whether an element can be flattened, t he element must be another object of type list. Paste your entire function, including the definition, in the box below. Do not leave any debugging print statements. Note that we ask you to write a function only -- you cannot rely on any variables defined outside your function for your code to work correctly. Code Editor 1 ''' # Paste your function here
true
f665521d39d777428e35e4c66706e0ccf5eed10d
camitt/PracticePython_org
/PP_Exercise_1.py
1,175
4.28125
4
from datetime import date # Exercise 1 # Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old. # Extras: # # 1. Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. (Hint: order of operations exists in Python) # 2. Print out that many copies of the previous message on separate lines. (Hint: the string "\n is the same as pressing the ENTER button) def returnYear(age): intAge = int(age) birthYear = date.today().year - intAge birthdayOccurred = input("Has your birthday already occurred this year? (Y/N): ") if birthdayOccurred.lower() == "n": birthYear -= 1 return birthYear + 100 def getInfo(): name = input("What is your name? ") age = input("Please enter your current age: ") repeat = input("Enter a number: ") return name, age, repeat def main(): name, age, repeat = getInfo() centuryAge = returnYear(age) for i in range(int(repeat)): print(name + " you will turn 100 in the year " + str(centuryAge)) main()
true
f60727bc1404c6a3631e4a9b158d847abe44afef
AnkyXCoder/PythonWorkspace
/practice.py
939
4.53125
5
# Strings first_name = "Ankit" last_name = "Modi" print(first_name) print(last_name) full_name = first_name + last_name print(full_name) # printing name with spaces full_name = first_name + ' ' + last_name print(full_name) # OR you can print it like this also # with no difference print(first_name + ' ' + last_name) # when you want to write long strings, you can use ''' or """ long_string = '''What do you want to do today evening?? let's go to theatre to watch a fun movie.... okay, let's go''' print(long_string) long_string1 = """What do you want to do today evening?? let's go to theatre to watch a fun movie.... okay, let's go""" print(long_string1) # below are the examples of string concatenation # use type() to get the type of variable print("Printing,", 'C', " and its type is ", type('C')) print("Printing,", "Hello", " and its type is ", type("Hello!")) print("Printing,", 100, " and its type is ", type(100))
true
43491586c77d23d9aba8416dd658cc7bf795f917
AnkyXCoder/PythonWorkspace
/Object Oriented Programming/Abstraction.py
1,463
4.5625
5
# Create a class and constructors # Abstraction # create an object class PersonalCharacter: # global attribute _membership = True # constructor def __init__(self, name = 'anonymous', age = 0, strength = 100): # dunder method """This is a constructor using __init__ which is called a duncder method. This constructor is called every time an object is created. It instantiates the object with the given attributes of the class. Able to access data and properties unique to each instance.""" # attributes """Protected members are those members of the class which cannot be accessed outside the class but can be accessed from within the class and it’s subclasses.""" self._name = name # to make attribute protected self._age = age # to make attribute protected """Private members are similar to protected members, the difference is that the class members declared private should neither be accessed outside the class nor by any base class.""" self.__strength = strength # to make attribute private # instantiate person1 = PersonalCharacter("Andy", 25) person2 = PersonalCharacter("Cindy", 22) # location of object in memory print(person1) print(person2) # getting details of the objects print(person1._name, person1._age, "membership", person1._membership) print(person2._name, person2._age, "membership", person2._membership)
true
180c54cc32d9d18b773f9a91e734b19f254c5014
AnkyXCoder/PythonWorkspace
/python basics/dictionary.py
2,859
4.3125
4
# Dictionary # data structure that stores data in terms of keys and values as pairs # list is a sorted data structure, list of people in queue # dictionary has no order, list of a persons belongings in wardrobe user2 = dict(name = "Johny") print(user2) # another way of creating dictionary dictionary = { # immutable keys types 'a' : 45, 'b' : 99, 'c' : True, 'd' : [1,2,3], 'e' : 'here is your string', 123 : 'hi user', True : 'hello', #[100] : True can not be used as lists are muttable, can be manipulated } # Getting values from keys print ('dictionary contains:', dictionary) print(dictionary['a']) print(dictionary['b']) print(dictionary['c']) print(dictionary['d']) print(dictionary['e']) print(dictionary[123]) print(dictionary[True]) dictionary[123] = 'hi admin' # replaces the previous value print(dictionary[123]) my_list = [ { 'a' : [1,2,3], 'b' : 'hello', 'c' : True }, { 'a' : [4,5,6], 'b' : 'there', 'c' : False } ] # Getting values from keys print(my_list[0]['a'][2]) print(my_list[1]['a'][1]) # Dictionary methods user = { 'greetings' : "hello", 'basket' : [1,2,3], 'weight' : 70, } print(user['basket']) # get method print(user.get('age')) # to check whether key 'age' is available in user or not print(user.get('age', 55)) # get age from user, if age is not available in user, then displays 55 print(user.get('weight', 60)) # get weight from user, if weight is not available in user, then display 60 # search for keys in dictionaries print("does basket available in user?",'basket' in user) print("does size available in user?",'size' in user) print("does hello available in user?",'hello' in user) # searching in keys method print("does basket available in user keys?", 'basket' in user.keys()) print("does hello available in user keys?", 'hello' in user.keys()) # searching in values method print("does basket available in user values?", 'basket' in user.values()) print("does hello available in user values?", 'hello' in user.values()) # seraching in items method print("items in user: ", user.items()) print("does hello available in user items?", 'hello' in user.items()) # copying the dictionary method user3 = user.copy() print("user3 now contains: ", user3) #clearing a dictionary user.clear() # clears dictionary print("user is now: ", user) print("user3 still contains: ", user3) # pop method print(user3.pop("weight")) # pops the item with key "weight" print(user3) # popitem method print(user3.popitem()) # randomly pops any item print(user3) # update method user3.update({'weight' : 45}) # updates key to provided value print(user3) user3.update({'age': 15}) # updates dictionary with new item if key is not available print(user3)
true
81982a4ea086b205b116518aa20113f130b6d0d8
AnkyXCoder/PythonWorkspace
/Object Oriented Programming/Modifying_Dunder_Methods.py
1,175
4.75
5
# Whenever an Object is created and instantiated, it gest access to all the basic Dunder Methods available to it as per Python # Programming Language. # By defining the Dunder Method in the Class Encapsulation, the access to Dunder Methods are modified. class SuperList(list): # Defining SuperList as the Subclass of the List Class def __len__(self): # This __len__() Dunder Method will be used and the __len__() Dunder Method provided by Python will not be used. return 1000; superlist1 = SuperList() print(len(superlist1)) # Appending Number to the Superlist superlist1.append(5) print(superlist1) # Appending Number to the Superlist superlist1.append(10) print(superlist1) # Getting Number from the Superlist print(f'superlist1[0]:{superlist1[0]}') print(f'superlist1[1]:{superlist1[1]}') # Check if SuperList is a subclass of List print(f'SuperList is a subclass of List: {issubclass(SuperList, list)}') # Check if SuperList is a subclass of Tuple print(f'SuperList is a subclass of Tuple: {issubclass(SuperList, tuple)}') # Check if SuperList is a subclass of Object print(f'SuperList is a subclass of Object: {issubclass(SuperList, object)}')
true
45c8680dc29404c7cd53bf30445d9c821705c9d4
zhjohn925/niu_algorithm
/S03_Interpolation_search.py
1,573
4.5625
5
# Interpolation search can be particularly useful in scenarios where the data being searched is uniformly # distributed and has a large range. # For example: # Large Data Sets: If you have a large data set and the elements are uniformly distributed, interpolation search # can provide faster search times compared to binary search. This is because interpolation search dynamically # adjusts the search range based on the estimated position of the target element, potentially reducing the number # of iterations required. def interpolation_search(arr, target): """ Performs interpolation search on a given sorted list to find the target element. Parameters: arr (list): The sorted list to be searched. target: The element to be found. Returns: int: The index of the target element if found, or -1 if not found. """ low = 0 high = len(arr) - 1 while low <= high and arr[low] <= target <= arr[high]: if low == high: if arr[low] == target: return low return -1 pos = low + ((target - arr[low]) * (high - low)) // (arr[high] - arr[low]) if arr[pos] == target: return pos elif arr[pos] < target: low = pos + 1 else: high = pos - 1 return -1 # Element not found # Example usage my_list = [1, 3, 5, 7, 9, 11] target_element = 7 result = interpolation_search(my_list, target_element) if result != -1: print(f"Element {target_element} found at index {result}.") else: print("Element not found.")
true
20c2f4cf45a6a501895565d2f40273263d77430c
zhjohn925/niu_algorithm
/L20_Bucket_Sort.py
2,347
4.1875
4
# Bucket Sort is a linear-time sorting algorithm on average when the input elements are uniformly # distributed across the range. # It is commonly used when the input is uniformly distributed over a range or when the range of values # is relatively small compared to the input size. def bucket_sort(arr): # Create an empty list of buckets buckets = [] # Determine the number of buckets based on the input size num_buckets = len(arr) # Initialize the buckets for _ in range(num_buckets): buckets.append([]) # Place elements into their respective buckets for num in arr: index = int(num * num_buckets) buckets[index].append(num) # Sort each bucket individually for bucket in buckets: insertion_sort(bucket) # Concatenate the sorted buckets into the final sorted array sorted_arr = [] for bucket in buckets: sorted_arr.extend(bucket) return sorted_arr # Insertion Sort works by dividing the input array into two parts: the sorted portion and the unsorted portion. # 1. Start with the first element (assume it is already sorted). # 2. Take the next element from the unsorted portion and insert it into the correct position in the sorted portion. # 3. Compare the selected element with the elements in the sorted portion, shifting them to the right until # the correct position is found. # 4. Repeat steps 2 and 3 until all elements in the unsorted portion are processed. # The insertion sort algorithm has a time complexity of O(n^2) in the worst case, # where n is the number of elements in the array. However, it performs well on small lists or # partially sorted lists, where it can have a time complexity close to O(n) and exhibit good # performance. def insertion_sort(arr): # Perform insertion sort on the given array for i in range(1, len(arr)): # sorted array is before i; unsorted array is i and after i card = arr[i] # pick i j = i - 1 while j >= 0 and arr[j] > key: arr[j + 1] = arr[j] # push larger than key [i] to the right j -= 1 arr[j + 1] = card # insert the card # Example usage arr = [0.8, 0.1, 0.5, 0.3, 0.9, 0.6, 0.2, 0.4, 0.7] sorted_arr = bucket_sort(arr) print("Sorted array:", sorted_arr)
true
f8ca4890c4833c2d752a3dcf14dc404089e7c85a
Aka-Ikenga/Daily-Coding-Problems
/swap_even_odd.py
527
4.21875
4
"""Good morning! Here's your coding interview problem for today. This problem was asked by Cisco. Given an unsigned 8-bit integer, swap its even and odd bits. The 1st and 2nd bit should be swapped, the 3rd and 4th bit should be swapped, and so on. For example, 10101010 should be 01010101. 11100010 should be 11010001. Bonus: Can you do this in one line?""" def reverse_bytes(b): b = list(str(b)) for i in range(0,8,2): b[i],b[i+1] = b[i+1], b[i] return int(''.join(b)) print(reverse_bytes(11100010))
true
a26239a775b14953e7dfe6c922bbf7a95b7e6a69
juliangyurov/js-code
/matrix.py
1,170
4.71875
5
# Python3 program to find the sum # of each row and column of a matrix # import numpy library as np alias import numpy as np # Get the size m and n m , n = 3, 3 # Function to calculate sum of each row def row_sum(arr) : sum = 0 print("\nFinding Sum of each row:\n") # finding the row sum for i in range(3) : for j in range(3) : # Add the element sum += arr[i][j] # Print the row sum print("Sum of the row",i,"=",sum) # Reset the sum sum = 0 # Function to calculate sum of each column def column_sum(arr) : sum = 0 print("\nFinding Sum of each column:\n") # finding the column sum for i in range(3) : for j in range(3) : # Add the element sum += arr[j][i] # Print the column sum print("Sum of the column",i,"=",sum) # Reset the sum sum = 0 # Driver code if __name__ == "__main__" : arr = [[4, 5, 6], [6, 5, 4], [5, 5, 5]] # Get the matrix elements # x = 1 # for i in range(m) : # for j in range(n) : # arr[i][j] = x # x += 1 # Get each row sum row_sum(arr) # Get each column sum column_sum(arr) # This code is contributed by # ANKITRAI1
true
64fefed9d00b683cbbcc88668ed7d17baef8dd57
elizabethgulsby/python101
/the_basics.py
2,376
4.25
4
# print "Liz Gulsby" # name = "Liz Gulsby" # name = "Liz " + "Gulsby" # fortyTwo = 40 + 2; # print fortyTwo # fortyTwo = 84 / 2; # print fortyTwo; # array...psyche! Lists (in Python) animals = ['wolf', 'giraffe', 'hippo']; print animals print animals[0] print animals[-1] # gets the last element - hippo, here animals.append('alligator'); print animals # To delete an index, use the remove method animals.remove('wolf') print animals # del animals[0] - also deletes an index where specified # To go to a specific location: we can insert into any indice with "insert" (like splice) animals.insert(0, 'zebra') print animals #To overwrite a certain index, see directly below animals[0] = 'horse' print animals # pop works the same way - remove the last element animals.pop() print animals #split works the same way as well (below, turning a string into an array) dc_class = "Michael, Paul, Mason, Casey, Connie, Sarah, Andy" dc_class_as_array = dc_class.split(", ") print dc_class_as_array #Sorted method will sort, but not change the actual array print sorted(dc_class_as_array) print dc_class_as_array # prints array as it was declared sorted_class = sorted(dc_class_as_array) print sorted_class dc_class_as_array.sort(); #this will change the array from its original configuration print dc_class_as_array #Reverse method - reverses the array, NOT on value, but on index dc_class_as_array.reverse() print dc_class_as_array # len attribute - works like .length in JS print len(dc_class_as_array) print dc_class_as_array[0] #will print Sarah because array was previously reversed # slice in JS is [x:x] # Creates a copy of the array; does not mutate the array print dc_class_as_array[2:3] print dc_class_as_array # For loop is for>what_you_call_this_one>in>var # no brackets! for student in dc_class_as_array: # indentation matters in python! print student; for i in range(1, 10): print i; #python will create the numbers for you for i in range(0, len(dc_class_as_array)): print dc_class_as_array[i] # functions in python - not a function! It is a "definition", ergo def: def sayHello(): # just like for loops, : is the curly brace in Python for functions # indentation matters, just like the for loop print "Hello, world!"; sayHello(); def say_hello_with_name(name, state = []): print "Hello, " + name; name = "Liz" say_hello_with_name(name);
true
f4d5d91147e0a5749f7570a2fd85133fd4fcddaf
down-dive/python-practice
/maxNum.py
596
4.3125
4
# Max Num # In this activity you will be writing code to create a function that returns the largest number present in a given array. # Instructions # - Return the largest number present in the given `arr` array. # - e.g. given the following array: arr = [1, 17, 23, 5, 6]; # - The following number should be returned: # 17; def max_num(list): number = list[0] # current_num = 0 for i in list: current_num = list[i] if current_num > number: number = current_num else: continue print(current_num) max_num(arr)
true
47e869c625a2c8769d7e7765ef5f992404fd6eeb
javedmomin99/Find-the-greatest-Number-out-of-3-numbers
/main.py
384
4.1875
4
def name(num1,num2,num3): if num1 > num2 and num1 > num3: return num1 elif num2 > num1 and num2 > num3: return num2 else: return num3 num1 = int(input("pls enter number 1\n")) num2 = int(input("pls enter number 2\n")) num3 = int(input("pls enter number 3\n")) print(name(num1,num2,num3)) print("The greatest number is " + str(name(num1,num2,num3)))
false
cbc3fe3f32e2879d6594aef7746f7007dceb2743
Cwagne17/WordCloud-Generator
/WordCloud.py
2,114
4.1875
4
# Word Cloud # # This script recieves a text input of any length, strips it of the punctuation, # and transforms the words into a random word cloud based on the frequency of the word # count in the text. # # To try it - on ln20 change the .txt file to the path which youd like to use. ENJOY! import wordcloud import numpy as np from matplotlib import pyplot as plt from IPython.display import display import fileupload import io import sys #open the .txt file you want to make a word cloud for then run text_file = open("pg63281.txt", "r") file_contents = text_file.read() def calculate_frequencies(file_contents): # Here is a list of punctuations and uninteresting words you can use to process your text uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my", "we", "our", "ours", "you", "your", "yours", "he", "she", "him", "his", "her", "hers", "its", "they", "them", "their", "what", "which", "who", "whom", "this", "that", "am", "are", "was", "were", "be", "been", "being", "have", "has", "had", "do", "does", "did", "but", "at", "by", "with", "from", "here", "when", "where", "how", "all", "any", "both", "each", "few", "more", "some", "such", "no", "nor", "too", "very", "can", "will", "just"] word_count = {} text_file = "" #Removes punctuation for char in file_contents: if char.isalpha(): text_file+=char else: text_file+=" " text_set = text_file.split() #Frequency Ctr for word in text_set: if not word.lower() in uninteresting_words: if word in word_count: word_count[word.lower()]+=1 else: word_count[word.lower()]=1 #wordcloud cloud = wordcloud.WordCloud() cloud.generate_from_frequencies(word_count) return cloud.to_array() myimage = calculate_frequencies(file_contents) plt.imshow(myimage, interpolation = 'nearest') plt.axis('off') plt.show()
true
0c05275b5642bdfaa6db3f433c2983c9f9f74c70
klivingston22/tutorials
/stingzz.py
465
4.15625
4
str = 'this is string example....wow!!!' print str.capitalize() #simply capitalises the first letter sub = 'i' print str.count (sub, 4, 40) # this should output 2 as 'i' appears twice sub = 'wow' print str.count(sub) # this should output 1 as 'wow' only appears once print len(str) # this should output 33 as there are 32 characters in our string print str.upper() # converts our string to uppercase print str.lower() # converts our string to lowercase
true
4693819abd24999a8d71594784cda3099b640b7e
yuriivs/geek_python_less02_dz
/lesson02_dz05.py
734
4.3125
4
# Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел. # У пользователя необходимо запрашивать новый элемент рейтинга. # Если в рейтинге существуют элементы с одинаковыми значениями, то новый элемент с тем же значением должен разместиться после них. my_list = [7, 5, 3, 3, 2] new_el = int(input("Введите число - новый элемент рейтинга >>>")) my_list.append(new_el) my_list.sort() my_list.reverse() print(my_list)
false
cd728160534e09d7cb8adee8b4bebaaf81d083a3
shivanikarnwal/Python-Programming-Essentials-Rice-University
/week2-functions/local-variables.py
853
4.1875
4
""" Demonstration of parameters and variables within functions. """ def fahrenheit_to_celsius(fahrenheit): """ Return celsius temperature that corresponds to fahrenheit temperature input. """ offset = 32 multiplier = 5 / 9 celsius = (fahrenheit - offset) * multiplier print("inside function:", fahrenheit, offset, multiplier, celsius) return celsius temperature = 95 converted = fahrenheit_to_celsius(temperature) print("Fahrenheit temp:", temperature) print("Celsius temp:", converted) # Variables defined inside a function are local to that function fahrenheit = 27 offset = 2 multiplier = 19 celsius = 77 print("before:", fahrenheit, offset, multiplier, celsius) newtemp = fahrenheit_to_celsius(32) print("after:", fahrenheit, offset, multiplier, celsius) print("result:", newtemp)
true
824d7672f35bf799e5ce0914c29bfed54805866d
siddeshshewde/Competitive_Programming_v2
/Daily Coding Problem/Solutions/problem002.py
1,075
4.1875
4
""" This problem was asked by Uber. Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6]. Follow-up: what if you can't use division? """ def productExceptSelf(arr): solution = [] for i in range(0, len(arr)): product = 1 for j in range(0, len(arr)): if i==j: continue product *= arr[j] solution.append(product) return solution print (productExceptSelf([1, 2, 3, 4, 5])) == [120, 60, 40, 30, 24] print (productExceptSelf([3, 2, 1])) == [2, 3, 6] print (productExceptSelf([1])) == [1] print (productExceptSelf([10, 15, 3, 7])) == [315, 210, 1050, 450] """ SPECS: TIME COMPLEXITY: O(n^2) SPACE COMPLEXITY: O(n) """
true
725fd29a6a090a89a375b345965e88b4bbb173d8
DanishKhan14/DumbCoder
/Python/Arrays/bestTimeToBuySellStock.py
581
4.3125
4
""" Max profit that we can get in a day is determined by the minimum prices in previous days. For example, if we have prices array [3,2,5,8,1] we can calculate the min prices array [3,2,2,2,1] and get the difference in our max profit array [0,0,3,6,0]. We can see clearly the max profit is 6, which is buy from the index 1 and sell in index 3. """ def maxProfit(prices): min_seen, max_profit = float('inf'), 0 for p in prices: min_seen = min(min_seen, p) curr_profit = p - min_seen max_profit = max(curr_profit, max_profit) return max_profit
true
280a5cbb31989e73535ff4b77dc9f727ca36dd8a
ktb702/AutomateTheBoringStuff
/sum.py
854
4.15625
4
# PROBLEM STATEMENT # If we list all the natural numbers between 1 and 10 (not including 1 or 10) that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Write code using a language of your choice that will find the sum of all the multiples of 3 or 5 between 1 and 1000 (not including 1 or 1000) and display the result. # HINTS # Start small. Write code that solves this problem for all numbers below 10 first and verify the result is 23. After that, try solving it for 100, then 1000. An incremental approach will make sure you can think your way through. def main(): sum = 0 #initialize the sum i = 2 #start incrementing from 2 (as 1 and 1000 are excluded) while i < 1000: if(i%3==0 or i%5==0): sum += i i += 1 print("The sum is: " + str(sum)) main()
true
ca608a5b39e151d3fccadfd2dae2b543f847624d
shawnstaggs/Basic-Sorting-Implementation
/Basic Sorting Implementation/Basic_Sorting_Implementation.py
1,306
4.25
4
def bubble_sort(list_object): working_list = list_object[:] for pass_count in range(len(working_list)-1, 0, -1): for step in range(pass_count): if working_list[step] > working_list[step+1]: working_list[step+1],working_list[step]=working_list[step],working_list[step+1] return working_list def merge_sort(parent_list): if len(parent_list) <= 1: return parent_list left_half = [] right_half = [] for each in range(len(parent_list)): if each < len(parent_list) / 2: left_half.append(parent_list[each]) else: right_half.append(parent_list[each]) left_half = merge_sort(left_half) right_half = merge_sort(right_half) return merge(left_half, right_half) def merge(left, right): result = [] while len(left) > 0 and len(right) > 0: if left[0] <= right[0]: result.append(left.pop(0)) else: result.append(right.pop(0)) while len(left) > 0: result.append(left.pop(0)) while len(right) > 0: result.append(right.pop(0)) return result lst = raw_input("Go ahead and enter your list: ").split(',') bubble_sorted = bubble_sort(lst) merge_sorted = merge_sort(lst) print lst print bubble_sorted print merge_sorted
false
37f59db3e5bb8925c6913bf7f309c6e375da0069
gerardoxia/CRACKING-THE-CODING
/1.8.py
636
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def isSubstring(str1,str2): length1=len(str1) length2=len(str2) check=True if length1>length2: return False for index2 in range(length2-length1+1): index=index2-1 for index1 in range(length1): index=index+1 if str1[index1]!=str2[index]: check=False break check=True if check==True: break return check def isRotation(str1,str2): str3=str2+str2 return(isSubstring(str1,str3)) str1='waterbottle' str2='erbottlewate' print(isRotation(str1,str2))
true
31339c4dfd1287b66e689816a8f2ba69b4ceb88f
katherine-davis/katherine-davis.github.io
/day 12.py
1,525
4.15625
4
########################################################################### #********************************--day 12--******************************** ##Write a function called initials ##it to take in three perameters ## first name ## last name ## and middle name ## and then return their initials firstName = input ("What is your first name? ") middleName = input("What is your middle name? ") lastName = input("What is your last name? ") def initials(firstName,middleName, lastName): numLettersFirst = len (firstName) numLettersMiddle = len (middleName) numLettersLast = len (lastName) firstInitial = firstName[0] middleInitial = middleName [0] lastInitial = lastName [0] return "Your initials are: " + firstInitial + "." + middleInitial + "." + lastInitial + "." print (initials(firstName, middleName, lastName)) def fancyInitials(fromTheEnd, first, middle, last): if fromTheEnd == False: answer = initials(first, middle, last) return answer else: lastFirstInitial = first[len(first-1)] lastMiddleInitial = middle[len(middle-1)] lastLastInitial = last[len(last-1)] firs = str(lastFirstInitial) mids = str(lastMiddleInitial) lass = str(lastLastInitial) return firs + "." + mids + "." + lass + "." print (fancyInitials (True, firstName, middleName, lastName)) ## ##THIS DOESNT WORK AND I WANT LISTENING SO IM KINDA SCREW BUTS ITS FINE
true
3f70f8f5a551e0daebf6ef8f8b083fd552bff472
qzlgithub/MathAdventuresWithPython
/ex1.2CircleOfSquares.py
303
4.15625
4
# Write and run a function that draws 60 squares, turning right 5 degrees after each square. Use a loop! from turtle import * shape('turtle') speed(0) def createSquares(): for j in range(4): forward(100) right(90) for j in range(60): createSquares() right(5)
true
6333f91ccd0c372887a2367b29e3fbbb0a2b0d9c
AlexOfTheWired/cs114
/FinalProject/Final_Project.py
2,346
4.125
4
""" Final Project Proposal() Create a cash register program. - On initialize the user sets amount of Bills and Coins in register (starting bank amount) - Set Sales Tax - sales_tax = 2.3% - Then print Register status: - Amount of Coins and Bills - Total cash amount Render Transaction: (Start with empty list... dictionary?) - Input item price ( append price to list... dictionary?) transaction_0001 = { 'Item #1': 3.50, 'Item #2': 11.99, 'Item #3': 2.30, 'Item #4': 23.00 } - Calculate Sub Total ( ) - Calculate balance due/TOTAL ( use sum() on item list items + sales_tax) - Input amount tendered ( input how much of each unit was given ) - Calculate change return - Coins - Bills Print Receipt FORMAT EXAMPLE ====================================== - ( STORE NAME ) - list price ========================== - Item #1 $3.50 - Item #2 $11.99 - Item #3 $2.30 - Item #4 $23.00 -------------------------- - Sub Total $40.79 - SALES TAX $0.00 - Total $40.79 - Cash $50.00 - CHANGE ===> $9.23 ========================== Transaction Number: 0001 ===================================== - Make function that stores transaction data for later use. - Complete transaction (reset tranaction dictionary or start new tranaction list.) - Record amount of coins and bills were exchanged after transaction. - how many coins and bills were taken out of register? - how many coins and bills were taken in after transaction? Print Register status: (Audit Tally) - All Transactions ( Make function that stores transaction data? Transaction Class! Each transaction creates a new instance. ) - Amount of Coins and Bills - Total cash amount I can even make a GUI for this! !!!GUI IS A MUST NOW!!! (Destroy Register) Possible Bugs: - register runs out of bills or coins - customer pays in FUCKING PENNIES!!! - change back requires (1 five, 4 singles, 2 dimes, 3 pennies). but register does not have any fives. - """ # Setup # Input # Transform # Output
true
d60c724b32214d29b29a8cc0bf2b1fd47b82f3be
Environmental-Informatics/python-learning-the-basics-Gautam6-asmita
/Second attempt_Exercise3.3.py
1,009
4.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Created on 2020-01-16 by Asmita Gautam Assignment 01: Python - Learning the Basics Think Python Chapter 3: Exercise 3.3 Modified to add header and comments for resubmission on 2020-03-04 """ """ While considering th each rows of the grid we can see 2 patters of the rows The first pattern is +----+----+ and the second is | | | """ ##Defining a function first to print a first row of matrix def first(): print('+----+----+') ##Defining a function second to print a second row of matrix def second(): print('| | |') ##Defining a function grid to call a mixture of first and second function so it appears like a matrix" def grid(): first() second() second() second() second() first() second() second() second() second() first() #Displaying the function "grid" grid() """ Here the functions used are def: used to define a function, print: will print everything as indicated within the ' ' """
true
6d4bdfc40c0577433770d818112673b30c153306
PreciadoAlex/PreciadoAlex.github.io
/Projects/Series_In_Python/Step_2.py
531
4.25
4
# cosine function using the taylor series import math x = int(input("select a number: ")) def cosine(x): y = 1 - ((x**2/2) + (x**4/24) - (x**6/720) + (x**8/40320))/math.factorial(2) return y pi = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145 print (cosine(0)) print (cosine(pi/2)) print (cosine(pi))
false
df1ee3a21892feab3d619c813550c104e702370a
fantastic-4/Sudoku
/src/Parser/validator.py
2,874
4.15625
4
class Validator: def __init__(self): self.digits = "123456789" self.rows = "ABCDEFGHI" def validate_values(self,grid): '''Function to validate the values on grid given. Return True if their values are numeric or False if their not.''' full_line="" for line in grid: full_line += (line.strip(" ").strip("\n")) chars = [c for c in grid if c in self.digits or c in "0."] return (len(chars) == 81 and len(full_line) == len(chars)) def set_matrix(self, A, B): '''__set_matrix__ product of elements in A and elements in B.''' return [a+b for a in A for b in B] def __get_ini_row_and_ini_col__(self,key): '''Function to set the top-left coordinate of the square where the number is about to fit Return 2 variables, row and column where the square begins''' row = key[0] col = key[1] if(row=="A" or row=="B" or row=="C"): ini_row = 0 elif(row=="D" or row=="E" or row=="F"): ini_row = 3 else: ini_row = 6 if(col=="1" or col=="2" or col=="3"): ini_col = 1 elif(col=="4" or col=="5" or col=="6"): ini_col = 4 else: ini_col = 7 return ini_row,ini_col def check_square(self,num,key, values): '''Function to validate if the number is already in the square 3x3 Return True if can be set on the square, False if the number is already on it''' flag = True ini_row, ini_col = self.__get_ini_row_and_ini_col__(key) lim_row = ini_row + 2 aux = ini_col lim_col = ini_col + 2 while ini_row <= lim_row and flag: ini_col = aux while ini_col <= lim_col: if(values[self.rows[ini_row]+str(ini_col)] == num and key != self.rows[ini_row]+str(ini_col) and values[self.rows[ini_row]+str(ini_col)] != "0"): flag = False break ini_col += 1 ini_row += 1 return flag def check_lines(self,num, key, values): '''Function to validate if the number is already in the row or column Return True if can be set on the cell, False if the number is already on row or column''' flag = True row = key[0] col = key[1] for i in self.digits: if(values[(row+i)] == num and not(i in key) and values[(row+i)] != "0"): flag = False break if(flag): for j in self.rows: if(values[j+col] == num and not(j in key) and values[j+col] != "0"): flag = False break return flag
true
bb12fd942559c665cd13f3c12d458ed43b646d01
andersonvelasco/Programming-2020B
/Calculadora.py
771
4.21875
4
#Script:Calculadora ''' Programa que, dadas dos variables N1 = 5 y N2 = 6, permita realizar las operaciones aritméticas básicas (suma, resta, multiplicación, división) y visualice por pantalla el resultado de estas 4 operaciones. ''' #INPUTS print("Calculadora que permitira obtener los resultados") print("de las operaciones aritmeticas básicas ") print("(suma, resta, multiplicación, división)") print("Ingrese n1: ") n1=float(input()) print("Ingrese n2: ") n2=float(input()) #PROCESS suma=n1+n2 resta=n1+n2 multiplicacion=n1*n2 division=n1/n2 #OUTPUTS print ("la suma de ",n1,"+",n2,"es: ",suma) print ("la resta de ",n1,"-",n2,"es: ",resta) print ("la Multiplicación de ",n1,"x",n2,"es: ",multiplicacion) print ("la división de ",n1,"/",n2,"es: ",division)
false
bb521b8932abe5d21f01a144b5c384caa32daf2e
FelixFelicis555/Data-Structure-And-Algorithms
/GeeksForGeeks/Sorting/Bubble_Sort/bubble_sort.py
436
4.125
4
def bubbleSort(list,n): for i in range(0,n-1): for j in range(0,n-i-1): if list[j]>list[j+1]: #swap temp=list[j] list[j]=list[j+1] list[j+1]=temp print("Sorted Array : ",end=' ') print(list) def main(): list=[] print("Enter the numbers in the list(Enter x to stop): ") while True: num=input() if num=='x': break list.append(int(num)) bubbleSort(list,len(list)) if __name__ == '__main__': main()
true
7c9aae80093542f3b41713cdffcf3fb093407be8
jancal/jan2048python
/plot_ols.py
2,296
4.34375
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= Linear Regression Example ========================================================= This example uses the only the first feature of the `diabetes` dataset, in order to illustrate a two-dimensional plot of this regression technique. The straight line can be seen in the plot, showing how linear regression attempts to draw a straight line that will best minimize the residual sum of squares between the observed responses in the dataset, and the responses predicted by the linear approximation. The coefficients, the residual sum of squares and the variance score are also calculated. """ # Code source: Jaques Grobler # License: BSD 3 clause import numpy as np from sklearn import linear_model # Load the diabetes dataset # diabetes = datasets.load_diabetes() # Use only one feature # diabetes_X = [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]] def file2matrix(filename): fr = open(filename) numberOfLines = len(fr.readlines()) # get the number of lines in the file returnMat = np.zeros((numberOfLines, 16)) # prepare matrix to return classLabelVector = [] # prepare labels return fr = open(filename) index = 0 for line in fr.readlines(): line = line.strip() listFromLine = line.split('\t') returnMat[index, :] = listFromLine[0:16] classLabelVector.append(int(listFromLine[-1])) index += 1 return returnMat, classLabelVector datingDataMat, datingLabels = file2matrix('E:\PycharmProjects\machine_learning\jan2048\data.txt') diabetes_X_train = datingDataMat diabetes_y_train = datingLabels # diabetes_X_test = [[4, 4], [5, 5]] # diabetes_y_test = [4, 5] # Create linear regression object regr = linear_model.LinearRegression() # Train the model using the training sets regr.fit(diabetes_X_train, diabetes_y_train) print('Coefficients: \n', regr.coef_) # print('Variance score: %.2f' % regr.score(diabetes_X_test, diabetes_y_test)) print(regr.predict([[16, 0, 4, 0, 16, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0], [0, 0, 0, 0, 32, 0, 0, 0, 4, 0, 0, 2, 2, 0, 4, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 2, 2, 2], [32, 2, 2, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]]))
true
2a6b635baa99f5e27d0c7d89506bca8519ff6ba2
SoadB/100DaysOfCode-Python
/Day_2.py
431
4.1875
4
# Comment in one line print("Hello, World!") # Code as a comment to prevent executing # print("Good night") # Comments in multi line # This is the comment # Written in # More than just one line print("اليوم الثاني وتعلم كتابة التعليقات بلغة بايثون") # Multi line String """ If you want to write multi line string , you should put triple quotation mark at the beginning and the end """
false
2535cb0e40bc6cfdec4510b6d264a9a7f8a711c8
rachaelthormann/Project-Euler-Python
/Problem3.py
701
4.21875
4
""" File name: Problem3.py Description: This program will find the largest prime factor of the number 600851475143. Author: Rachael Thormann Date Created: 3/21/2016 Date Last Modified: 3/21/2016 Python Version: 3.4 """ def largest_prime_factor(num): """Finds the largest prime factor.""" i = 2 # largest prime factor will never be greater than square root of i # because we divide the divisors out of the number while i * i <= num: # if n divides evenly by i, replace num by num // i if (num % i == 0): num //= i # increment i else: i += 1 print(num) largest_prime_factor(600851475143)
true
3b5e0d1bf01b242fac32661aba45c6d6a0983f6c
kalnaasan/university
/Programmieren 1/PRG1/Übungen/Übung_06/Alnaasan_Kaddour_0016285_3.py
1,390
4.125
4
""" This script is the solution of Exercise Sheet No.4 - Task 3 and 4 """ __author__ = "0016285: Kaddour Alnaasan" __credits__ = """If you would like to thank somebody i.e. an other student for her code or leave it out""" __email__ = "qaduralnaasan@gmail.com" def length_list(text): length = len(text) return length def invert_list(text): new_text = "" for i in range(len(text)-1, -1, -1): new_text += text[i] print("2) The invert Text:", new_text) return True def multiplied_list(text): """""" my_default_param = 2 new_text = text * my_default_param return new_text def return_tow_character(text): """""" sobject = slice(2, 4, 1) return text[sobject] def read_text(text): """""" len_text = length_list(text) sobject = slice(len_text-4, len_text, 1) new_text = text[sobject] return return_tow_character(new_text) def main(): """ Docstring: The Main-Function to run the Program""" text = input("Geben Sie einen Text ein:") length_text = length_list(text) # 1 print("1) The Length of Text:", str(length_text)) # 1 invert_list(text) # 2 multi_text = multiplied_list(text) # 3 print("3) The multiple Text:", multi_text) # 3 tow_characters = read_text(text) # 5 print("5) The Last Tow Characters:", tow_characters) # 5 if __name__ == "__main__": main()
true
a58af9f6b048d0aa853c45a59689da0bc8abea76
olugboyegaonimole/python
/a_simple_game.py
2,907
4.4375
4
#A SIMPLE GAME class Football(): class_name='' description='' #THIS IS THE INITIAL VALUE OF THE PROPERTY objects={} #1. WHEN A SETTER IS USED, YOU MUST ASSIGN AN INITIAL VALUE TO THE PROPERTY #2. HERE FOR EXAMPLE, THE ASSIGNMENT TAKES PLACE WHEN THE PROPERTY IS DEFINED AS A CLASS ATTRIBUTE def __init__(self, name): self.name = name Football.objects[self.class_name]=self def get_description(self): print(self.class_name + '\n' + self.description) class Striker(Football): class_name = 'striker' description='scores goals' class Defender(Football): class_name='defender' description='stops striker' class Ball(Football): def __init__(self, name): self.class_name='ball' self._description='hollow spherical inflated with air' self.status=0 super().__init__(name) @property def description(self): #THIS IS THE GETTER if self.status==0: self._description='hollow spherical inflated with air' elif self.status==1: self._description = 'you beat one defender!' elif self.status==2: self._description = 'you beat another defender!' elif self.status==3: self._description = 'now you beat the goalkeeper!' elif self.status>3: self._description = 'IT\'S IN THE BACK OF THE NET!!!!!! GOALLLLLLLLLLLLLLLLLLLL!!!!!!!!!!!!!!!' return self._description #WHEN A SETTER IS USED THE GETTER MUST RETURN THE PROPERTY ITSELF (AND NOT RETURN A LITERAL VALUE) #THE SETTER DIRECTLY ASSIGNS A VALUE TO THE PROPERTY, OR IT ASSIGNS A VALUE TO SOMETHING THAT WILL DETERMINE THE VALUE OF THE PROPERTY @description.setter def description(self, value): #THIS IS THE SETTER self.status = value #HERE, THE SETTER ASSIGNS A VALUE TO SOMETHING THAT WILL DETERMINE THE VALUE OF THE PROPERTY striker1 = Striker('yekini') defender1=Defender('uche') ball01=Ball('addidas') i=0 def get_input(): global i i += 1 command = (input('enter command: ')).split(' ') verbword = command[0] if verbword in verbdict: verb = verbdict[verbword] else: print('unknown') return if len(command)>1: nounword = command[1] verb(nounword) else: verb('nothing') def say(noun): print('you said {}'.format(noun)) def examine(noun): if noun in Football.objects: Football.objects[noun].get_description() else: print('there is no {} here'.format(noun)) def kick(noun): if noun in Football.objects: item = Football.objects[noun] if type(item) == Ball: item.status += 1 if item.status == 1: print('you kicked the ball!') if 2<= item.status <=3: print('you kicked the ball again!') elif item.status>3: print('YOU\'VE SCORED!!!!!!!!!!!') else: print('you can\'t kick that') else: print('you can\'t kick that') verbdict={'say':say, 'examine':examine, 'kick':kick} while True: #while i<10: get_input()
true
02f2947e9e98e73e640aa8a46cf21878ee94bcc8
pawnwithn0name/Python3EssentialTraining
/GUI/5.event-hangling.py
728
4.1875
4
''' After the root window loads on the system, it waits for the occurence of some event. These events can be button clicks, motion of the mouse, button release, etc. These events are handled by defining functions that are executed in case an event occurs. ''' from tkinter import * def handler1(): print('White') def handler2(): print('Orange') def handler3(): print('Red') root = Tk(className = 'Event') Button(root, text='White', bg='white',fg='black', command = handler1).pack(fill = X, padx = 15) Button(root, text='Orange', bg='orange',fg='brown', command = handler2).pack(fill = X, padx = 15, pady =15) Button(root, text='Red', bg='red',fg='black', command = handler3).pack( fill = X, padx = 15) root.mainloop()
true
95d4f71e7e6a505afc4f3156a3cb57d64077db6d
pawnwithn0name/Python3EssentialTraining
/02 Quick Start/forloop.py
338
4.4375
4
#!/usr/bin/python3 # read the lines from the file fh = open('lines.txt') for line in fh.readlines(): # Print statement 'end' argument in Python 3 allows overriding the end-of-line character which # defaults to '\n'. Each line in the file already has a carriage return so the end-of-line is not needed. print(line, end = "")
true
d5cf8c7b947bc831607a66f10325b62c445eaa15
javifu00/Battleship
/Usuario.py
1,156
4.1875
4
class Usuario: """ Clase donde se deteminan los valores de cada usuario que juegue (username, nombre, edad, genero, puntaje, disparos efectuados) """ def __init__(self, username, nombre, edad, genero, puntaje=1, disparos_efectuados=100): self.username = username self.nombre = nombre self.edad = edad self.genero = genero self.puntaje = puntaje self.disparos_efectuados = disparos_efectuados def __str__(self): return "Usuario: {}\nNombre completo: {}\nEdad: {}\nGenero: {}\nPuntaje: {}\nDisparos efectuados: {}".format(self.username, self.nombre, self.edad, self.genero, self.puntaje, self.disparos_efectuados) def mostrar_datos(self): print("Info del usuario \nUsername: {} \nNombre: {}\nEdad: {}\nGenero: {}\nPuntaje: {}\nDisparos acertados: {}".format(self.username, self.nombre, self.edad, self.genero, self.puntaje, self.disparos_efectuados)) def para_txt(self): print("{}, {}, {}, {}".format(self.username, self.nombre, self.edad, self.genero)) def mostrar_usuario(self, username): self.username = username print(self.username)
false
918d17e7abb26b3e6e1290cbe09c4592090cf43d
dvishwajith/shortnoteCPP
/languages/python/containers/dictionary.py
2,402
4.375
4
#!/usr/bin/env python3 dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First', 7:'testintkey', 1.5:'testfloatkey', (1,1.5):'testTuplekey'} print(dict) # if you define values with same keys they will be replaces . for example key 7 here dict_2 = {'Name': 'Amir', 'Age': 8, 'Class': 'First', 7:'testintkey', 1.5:'testfloatkey', (1,1.5):'testTuplekey', 7:[1,2,3]} print(dict_2) del dict_2[7] # This delete en entry with key name 7 dict_2.clear() # clea all the element s in the dicitonary del dict_2 #this delete athe entire dictionary dict_3 = {'Name': 'Amir', 'Age': 8, 'Class': 'First', 7:'testintkey', 1.5:'testfloatkey', (1,1.5):'testTuplekey', 7:[1,2,3]} print(" 'Name' in dict3 = ", 'Name' in dict_3) print("dict_3.items() -> ", dict_3.items()) # returns dicitonary (key, item) tuple pairs print("dict_3.keys() -> ", dict_3.keys()) # returns dict keys print("dict_3.values() -> ", dict_3.values()) # return all items dict_3.update(dict) print("dict_3.update(dict) This will add dict into dict3 -> ", dict_3) # dict4 = dict + dict_3 This is not valid print(""" Class object as hash Keys """) class A(): def __init__(self, data=''): self.data = data def __str__(self): return str(self.data) d = {} obj = A() d[obj] = 'abc' print("d[obj] = ", d[obj]) obj2 = A() d[obj2] = "cdf" print("d[obj2] = ", d[obj2]) # KeyError because elem2 is not elem. # The __hash__() gives different outputs. if you want this to be valid override the __hash__() function # to get the has using input string data print(""" Sorting accoring to values """) x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} print("input x dictonary", x) X_sorted_by_vales_tuples = sorted(x.items(), key=lambda item: item[1]) #lamdbda function extract value print("X_sorted_by_vales_tuples ",X_sorted_by_vales_tuples) X_sorted_by_vales_dictionary = {k: val for k, val in sorted(x.items(), key=lambda item: item[1])} print("X_sorted_by_vales_dictionary ",X_sorted_by_vales_dictionary) print(""" Sorting accoring to Keys """) x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} print("input x dictonary", x) X_sorted_by_keys_tuples = sorted(x.items(), key=lambda item: item[0]) #lamdbda function extract key print("X_sorted_by_keys_tuples ",X_sorted_by_keys_tuples) X_sorted_by_keys_dictionary = {k: val for k, val in sorted(x.items(), key=lambda item: item[0])} print("X_sorted_by_keys_dictionary ",X_sorted_by_keys_dictionary)
false
e28e734decc6a09e159ce7105997df8d2bb1f437
dvishwajith/shortnoteCPP
/languages/python/algorithms/graphs/bfs/bfs.py
998
4.25
4
#!/usr/bin/env python3 graph = { 'A' : ['B','C'], 'B' : ['D', 'E'], 'C' : ['F'], 'D' : [], 'E' : ['F'], 'F' : [] } from collections import deque print("bfs first method. Using deque as a FIFO because list pop(0) is O(N)") def BFS(graph, start): node_fifo = deque([]) #using deque because pop(0) is O(N) in lists node_fifo.append(start) while len(node_fifo) != 0: traversed_node = node_fifo.popleft() print(traversed_node, " ") for connected_node in graph[traversed_node]: node_fifo.append(connected_node) BFS(graph, 'A') print("""bfs second method. Wihtout poping first element and using a list. Advantage is this store the travarsed order in nodelist as well""") def BFS(graph, start): nodelist = [] nodelist.append(start) for traversed_node in nodelist: print(traversed_node, " ") for connected_node in graph[traversed_node]: nodelist.append(connected_node) BFS(graph, 'A')
true
7cd2eef61cd8036e0e78001a306b0737f7d9e191
EfimT/pands-problems-2020
/homework 2.py
266
4.21875
4
# Write a program that asks a user to input # a string and outputs every second letter in reverse order. sentence = (input("Enter a string : ")) sentence = sentence [::-1] print ("Heres is you're string reversed and every second letter is:", sentence[::2])
true