blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
979435e090e41bff2066755c1c0d65a4c33298cf
aryajayan/python-training
/day3/q2.py
262
4.375
4
# Given a dictionary {"name": "python", "ext": "py", "creator": "guido"}, print both keys and values. d={"name": "python", "ext": "py", "creator": "guido"} for key, value in d.items(): print(key, value) # --Output-- # name python # ext py # creator guido
true
cd8a38d26c03dd73fde61e337aecd5c02b7761b5
aryajayan/python-training
/day3/q4.py
485
4.25
4
# Guessing Game. Accept a guess number and tell us if it's higher or less than the hardcoded number num=10 guess_num=int(input("Guess the number : ")) if guess_num>num: print("higher than the given number") elif guess_num<num: print("lower than the given number") else: print("You got the number") # --Output-- # Guess the number : 6 # lower than the given number # Guess the number : 29 # higher than the given number # Guess the number : 10 # You got the number
true
69110ed6b4e2943ca3cb7ca4e56d5ce884b3bf60
sumedhkhodke/waiver_assignment
/eas503_test.py
2,239
4.53125
5
""" ------------ INSTRUCTIONS ------------ The file 'Students.csv' contains a dump of a non-normalized database. Your assignment is to first normalize the database and then write some SQL queries. To normalize the database, create the following four tables in sqlite3 and populate them with data from 'Students.csv'. 1) Degrees table has one column: [Degree] column is the primary key 2) Exams table has two columns: [Exam] column is the primary key column [Year] column stores the exam year 3) Students table has four columns: [StudentID] primary key column [First_Name] stores first name [Last_Name] stores last name [Degree] foreign key to Degrees table 4) StudentExamScores table has four columns: [PK] primary key column, [StudentID] foreign key to Students table, [Exam] foreign key to Exams table , [Score] exam score Call the normalized database: 'normalized.db'. Q1: Write an SQL statement that selects all rows from the `Exams` table and sorts the exams by year and then exam name Output columns: exam, year Q2: Write an SQL statement that selects all rows from the `Degrees` table and sorts the degrees by name Output column: degree Q3: Write an SQL statement that counts the numbers of gradate and undergraduate students Output columns: degree, count_degree Q4: Write an SQL statement that calculates the exam averages for exams and sort by the averages in descending order. Output columns: exam, year, average round to two decimal places Q5: Write an SQL statement that calculates the exam averages for degrees and sorts by average in descending order. Output columns: degree, average round to two decimal places Q6: Write an SQL statement that calculates the exam averages for students and sorts by average in descending order. Show only the top 10 students. Output columns: first_name, last_name, degree, average round to two decimal places More instructions: 1) All work must be done in Python. 2) You CANNOT use 'pandas'. 3) You CANNOT use the 'csv' module to read the file 3) All SQL queries must be executed through Python. 4) Neatly print the output of the SQL queries using Python. Hint: Ensure to strip all strings so there is no space in them """
true
022d70630593eeccb4082c9378465f0551f39f9c
bhavesh-20/Genetic-Algorithm
/Sudoku/random_generation.py
2,493
4.1875
4
import numpy as np """Function which generates random strings for genetic algorithm, each string is a representation of genetic string used in the algorithm. Randomness is used in a smart way to remove the chance of each row having duplicates in sudoku and also trying to minimise conflicts with columns, hence the generated random string doesn't have any duplicates row-wise and minimum duplicates column-wise""" def random_generation(): l = ["x8xxxxx9x","xx75x28xx","6xx8x7xx5","37xx8xx51","2xxxxxxx8","95xx4xx32","8xx1x4xx9","xx19x36xx", "x4xxxxx2x"] rand_string = [] number_set = {1,2,3,4,5,6,7,8,9} columns = [] for _ in range(9): columns.append(set()) for i in l: for j in range(9): if i[j]!='x': columns[j].add(int(i[j])) for i in l: s = '' n = list(number_set - set([int(x) for x in i if x!='x'])) for column in range(9): possible = set(n) if i[column]!='x': s+=i[column] else: a = list(possible - columns[column]) if len(a) == 0: r = np.random.randint(0, len(n)) r = n[r] n.remove(r) s+=str(r) else: r = np.random.randint(0, len(a)) r = a[r] n.remove(r) s+=str(r) rand_string.append(s) rand_string = ''.join(x for x in rand_string) return rand_string """Function which generates random strings for genetic algorithm, each string is a representation of genetic string used in the algorithm. Randomness is used in a smart way to remove the chance of each row having duplicates in sudoku, hence the generated random string doesn't have any duplicates row-wise""" def random_generation2(): l = ["x8xxxxx9x","xx75x28xx","6xx8x7xx5","37xx8xx51","2xxxxxxx8","95xx4xx32","8xx1x4xx9","xx19x36xx", "x4xxxxx2x"] rand_string = [] number_set = {1,2,3,4,5,6,7,8,9} for i in l: a = set([int(x) for x in i if x!='x']) a = np.array(list(number_set - a)) np.random.shuffle(a) a, k, string = list(a), 0, "" for j in i: if j=='x': string+=str(a[k]) k+=1 else: string+=j rand_string.append(string) rand_string = ''.join(x for x in rand_string) return rand_string
true
8c3267e725eb737b3335f0ff4d94977e1a90be59
ViMitre/sparta-python
/1/classes/car.py
797
4.15625
4
# Max speed # Current speed # Getter - return current speed # Accelerate and decelerate methods # Accelerate past max speed # What if it keeps braking? class Car: def __init__(self, current_speed, max_speed): self.current_speed = current_speed self.max_speed = max_speed def get_speed(self): return self.current_speed def accelerate(self, speed): new_speed = self.current_speed + speed self.current_speed = min(self.max_speed, new_speed) def decelerate(self, brake): new_speed = self.current_speed - brake self.current_speed = max(0, new_speed) my_car = Car(60, 200) my_car.accelerate(20) print(my_car.get_speed()) my_car.decelerate(120) print(my_car.get_speed()) my_car.accelerate(400) print(my_car.get_speed())
true
e3156589342632ac3996d4787be30275f7b9b062
standrewscollege2018/2021-year-11-classwork-ethanbonis
/Zoo.py
245
4.28125
4
#This code will ask for your age and based on this info, will ask - #you to pay the child price or to pay the adult price. CHILD_AGE = 13 age = int(input("What is your age?")) if age <= CHILD_AGE: print("child") else: print("adult")
true
10dbdc70ade2b6ba83a7b1233d70e636d8747626
ERAN1202/python_digital_net4u
/lesson_1/Final_Pro.Func.py
2,213
4.15625
4
'''create a menu: a. IP system? b. DNS system? a ==== 1. search for IP address from a list 2. add IP address to a list 3. delete IP address to a list 4. print all the IPs to the screen b === 1. serach for URL from a dictionary 2. add URL + IP address to a dictionary 3. delete URL from a dictionary 4.update the IP address of specific URL 5. print all the URL:IP to the screen''' from time import sleep def menu(): while(True): choice_1=input("Menu:\n------------\na. IPSystem\nb. DNS System\n") if (choice_1 == "a"): choice_2 = input("Menu IP System:\n-----------\n1.search IP\n2.add IP\n3.delete IP\n4.Print all IP ") if choice_2 == "1": search_ip() elif choice_2 == "2": add_ip() elif choice_2 == "3": delete_ip() elif choice_2 == "4": print_IPs() elif (choice_1 == "b"): choice_3 = input("Menu DNS system:\n--------------\n1.search URL\n2.add IP+URL to dict.\n3.delete URL from dict.\n4.update IP address spec. URL\n5.print all the URL:IP to the screen") if choice_3 == "1": search_URL() elif choice_3 == "2": add_ip_URL() elif choice_3 == "3": delete_URL() elif choice_3 == "4": update_IPs() elif choice_3 == "5": print_URL() else: print("Enter a/b only") continue exit=input("Do you wnat to exit? yes/no") if (exit == "yes"): print("ByeBye") break def search_ip(): print("1") def add_ip(): ip_added = input("IP add is : ") print(str(ip_added)) filename = "C:/Users/eranb/Desktop/IP.txt" file = open(filename, "a") file.write(ip_added) file.close() file = open(filename, "r") file.read() file.close() def delete_ip(): print("3") def print_IPs(): print("4") def search_URL(): print("1") def add_ip_URL(): print("2") def delete_URL(): print("3") def update_IPs(): print("4") def print_URL(): print("5") menu()
true
cdd3dbd0d964d9d914893f60a95ed0a79129a626
AvivSham/LeetCodeQ
/Easy/DistanceBetweenBusStops.py
413
4.125
4
from typing import List def distance_between_bus_stops(distance: List[int], start: int, destination: int) -> int: clockwise = sum(distance[min(start, destination):max(start, destination)]) counter_clockwise = sum(distance) - clockwise return min(clockwise, counter_clockwise) if __name__ == '__main__': print(distance_between_bus_stops(distance=[1, 2, 3, 4], start=0, destination=1))
true
99fc98fe21ae10439644ff02e044d377e5a346c1
rafawelsh/CodeGuildLabs
/python/Python labs/9.unit_converter.py
254
4.1875
4
#9.unit_converter.py # ft = int(input("What is the distance in feet?: ")) # m = round((ft * 0.3048),5) # # print(ft,"ft is", m, "m") def conversion(disntance, meter): disntance = int(input("What is the distance? ")) unit = input("What are the units? ")
true
e4692682f070ad1e3ed787efbd8811d68d74d253
a62mds/exercism
/python/linked-list/linked_list.py
1,841
4.125
4
# Skeleton file for the Python "linked-list" exercise. # Implement the LinkedList class class Node(object): def __init__(self, value, next=None, prev=None): self.value = value self.next = next self.prev = prev def __str__(self): return '{}'.format(self.value) class LinkedList(object): def __init__(self): self.head = None self.tail = None def __iter__(self): self.current = self.head return self def next(self): if self.current is None: raise StopIteration else: curr = self.current self.current = self.current.next return curr.value def __len__(self): l = 0 for node in self: if node is None: break else: l += 1 return l def __str__(self): return '<->'.join(str(node) for node in self) def push(self, value): if self.tail is None: self.head = self.tail = Node(value) else: new_tail = Node(value) self.tail.next = new_tail new_tail.prev = self.tail self.tail = new_tail def pop(self): old_tail = self.tail self.tail = self.tail.prev if self.tail is not None: self.tail.next = None else: self.head = self.tail return old_tail.value def shift(self): old_head = self.head self.head = self.head.next if self.head is not None: self.head.prev = None else: self.tail = self.head return old_head.value def unshift(self, value): if self.head is None: self.head = self.tail = Node(value) else: new_head = Node(value) self.head.prev = new_head new_head.next = self.head self.head = new_head
true
69c9988c1a00e304da3a71ba9e589142db2c17d9
RCTom168/Intro-to-Python-1
/Intro-Python-I-master/src/09_dictionaries.py
2,180
4.53125
5
""" Dictionaries are Python's implementation of associative arrays. There's not much different with Python's version compared to what you'll find in other languages (though you can also initialize and populate dictionaries using comprehensions just like you can with lists!). The docs can be found here: https://docs.python.org/3/tutorial/datastructures.html#dictionaries For this exercise, you have a list of dictionaries. Each dictionary has the following keys: - lat: a signed integer representing a latitude value - lon: a signed integer representing a longitude value - name: a name string for this location """ waypoints = [ { "lat": 43, "lon": -121, "name": "a place" }, { "lat": 41, "lon": -123, "name": "another place" }, { "lat": 43, "lon": -122, "name": "a third place" } ] # Add a new waypoint to the list # YOUR CODE HERE waypoints.append({ "lat": 41, "lon": -124, "name": "that other place" }) # Modify the dictionary with name "a place" such that its longitude # value is -130 and change its name to "not a real place" # Note: It's okay to access the dictionary using bracket notation on the waypoints list. # YOUR CODE HERE # The "a place" value takes up the 0 slot waypoints[0]["lat"] = 43 waypoints[0]["lon"] = -130 waypoints[0]["name"] = "not a real place" # Write a loop that prints out all the field values for all the waypoints # YOUR CODE HERE for waypoint in waypoints: for v in waypoint.values(): print(v) # Lecture Example # input letters will be a list of single character # lowercase strings (a-z) def mapping(letters): # create an empty dictionary result = {} # loop through the input provided for letter in letters: # add letter to the dictionary # make the letter uppercase for the value # leave lowercase for the key result[letter] = letter.upper() # return value return result # dictionary with key-values where the # key is the lowercase letter from the input # and value is the correlating uppercase letter print(mapping(["a", "b", "e", "g"]))
true
1b09af7656619a1281f588e050f722e326edca1b
krishnanandk/kkprojects
/functions/demo.py
645
4.21875
4
#inbuild function #print() #input() #type #normal syntax to create a function #def functionname(arguments): #function definition #function call: #using fn name #3methods #1. Functions without an argument and no return type #2. Function with arguments and no return type #3. Function with arguments and return type #1. #def add(): # num1=int(input("enter number1")) # num2=int(input("enter number2")) # sum=num1+num2 # print(sum) #add() #2. # def addition(num1,num2): # sum=num1+num2 # print(sum) # addition(30,50) #3. # def sumN(num1,num2): # sum=num1+num2 # return sum # data=sumN(15,25) # print(data)
true
a61f578bb01b0c574a3ba130db048990c2712189
excaliware/python
/lcm.py
1,328
4.28125
4
""" Find the lowest common multiple (LCM) of the given numbers. """ import math """ Find the prime factors of the given number. """ def find_factors(n): factors = [] # First, find the factor 2, if any. while n % 2 == 0: n = n // 2 factors.append(2) # From now on, check odd numbers only. d = 3 while d <= math.sqrt(n): # Divide by the factor while it is possible. while n % d == 0: n = n // d factors.append(d) d = d + 2 if n > 1: factors.append(n) return factors """ Find the lowest common multiple (LCM) of the given numbers. """ def calc_lcm(nums): ndict = {} result = {} for n in nums: for f in find_factors(n): if ndict.get(f) == None: ndict[f] = 1 else: ndict[f] += 1 for f in ndict.keys(): if result.get(f) == None: result[f] = ndict[f] elif ndict[f] > result[f]: result[f] = ndict[f] # New dict for the next number, if any. ndict = {} p = 1 for f in result.keys(): p *= math.pow(f, result[f]) return int(p) # An alternative approach. def lcm(a, b): return a * b / gcd(a, b) if __name__ == "__main__": nums = [12, 18, 5, 3, 10] lcm = calc_lcm(nums) print("The LCM of %s is %d" % (nums, lcm)) # Check the correctness of the result. for n in nums: if lcm % n != 0: print("%d / %d = %d" % (lcm, n, lcm / n))
true
5d83d1235d048388394af8a6e56bf55c289c7957
johnyijaq/Pyhton-For-Everybody
/Course 3. Using Python to Access Web Data/Week 2. Regular Expressions.py
2,782
4.5625
5
Chapter 11 Assignment: Extracting Data With Regular Expressions # Finding Numbers in a Haystack # In this assignment you will read through and parse a file with text and # numbers. You will extract all the numbers in the file and compute the sum of # the numbers. # Data Files # We provide two files for this assignment. One is a sample file where we give # you the sum for your testing and the other is the actual data you need to # process for the assignment. # Sample data: http://python-data.dr-chuck.net/regex_sum_42.txt # (There are 87 values with a sum=445822) # Actual data: http://python-data.dr-chuck.net/regex_sum_201873.txt # (There are 96 values and the sum ends with 156) # These links open in a new window. Make sure to save the file into the same # folder as you will be writing your Python program. Note: Each student will # have a distinct data file for the assignment - so only use your own data file # for analysis. # Data Format # The file contains much of the text from the introduction of the textbook # except that random numbers are inserted throughout the text. Here is a sample # of the output you might see: ''' Why should you learn to write programs? 7746 12 1929 8827 Writing programs (or programming) is a very creative 7 and rewarding activity. You can write programs for many reasons, ranging from making your living to solving 8837 a difficult data analysis problem to having fun to helping 128 someone else solve a problem. This book assumes that everyone needs to know how to program ... ''' # The sum for the sample text above is 27486. The numbers can appear anywhere # in the line. There can be any number of numbers in each line (including none). # Handling The Data # The basic outline of this problem is to read the file, look for integers using # the re.findall(), looking for a regular expression of '[0-9]+' and then # converting the extracted strings to integers and summing up the integers. import re fhand = open("regex_sum_378376.txt") sum = 0 for line in fhand: line = line.rstrip() numbers = re.findall('[0-9]+', line) if len(numbers) > 0: for number in numbers: sum= sum + int(number) print(sum) *********************************************** #Alternative import re #Extracting Digits and Summing them fhand = open("regex_sum_378376.txt") total = [] for line in fhand: line = line.rstrip() numbers = re.findall("([0-9]+)", line) if len(numbers) < 1 : continue for number in numbers: num = float(number) total.append(num) #Alternative #for i in range(len(numbers)): #num = float(numbers[i]) #total.append(num) print(sum(total))
true
491bee39b76c5252187bc734dddd247aa017ed7d
thomasyu929/Leetcode
/Tree/symmetricTree.py
1,436
4.21875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 1 Recursive # def isSymmetric(self, root: TreeNode) -> bool: # if not root: # return True # return self.isLRSymmetric(root.left, root.right) # def isLRSymmetric(self, left, right): # if not left and not right: # return True # if (not left and right) or (left and not right) or (left.val != right.val): # return False # return self.isLRSymmetric(left.left, right.right) and self.isLRSymmetric(left.right, right.left) # 2 Iteration def isSymmetric(self, root: TreeNode) -> bool: if not root: return True queue1, queue2 = [root.left], [root.right] while queue1 and queue2: node1, node2 = queue1.pop(), queue2.pop() if not node1 and not node2: continue if (not node1 and node2) or (node1 and not node2): return False if node1.val != node2.val: return False queue1.append(node1.left) queue1.append(node1.right) queue2.append(node2.right) queue2.append(node2.left) return True
true
e7c2a3d268ff5f03cb453656cf931a91a9e7a529
ccmaf/Python-Stuff
/listfun.py
265
4.28125
4
#goal: make a list from user input and print out any #number from the list that is < 5 print("please enter 3 numbers.") n1 = input("n1: ") n2 = input("n2: ") n3 = input("n3: ") list = [int(n1),int(n2),int(n3)] for element in list: if element < 5: print(element)
true
34cd3453ff8de1f95b60e93bd24e575870bcc669
Thiksha/Pylab
/prog7.py
439
4.21875
4
# Python program using NumPy # for some basic mathematical # operations import numpy as np # Creating two arrays of rank 2 x = np.array([[1, 2], [3, 4]]) y = np.array([[5, 6], [7, 8]]) # Creating two arrays of rank 1 v = np.array([9, 10]) w = np.array([11, 12]) # Inner product of vectors print(np.dot(v, w), "\n") # Matrix and Vector product print(np.dot(x, v), "\n") # Matrix and matrix product print(np.dot(x, y))
true
1359d33adaa10e2ba9022cc703ef855ccf7c9355
distracted-coder/Exercism-Python
/yacht/yacht.py
2,602
4.125
4
""" This exercise stub and the test suite contain several enumerated constants. Since Python 2 does not have the enum module, the idiomatic way to write enumerated constants has traditionally been a NAME assigned to an arbitrary, but unique value. An integer is traditionally used because it’s memory efficient. It is a common practice to export both constants and functions that work with those constants (ex. the constants in the os, subprocess and re modules). You can learn more here: https://en.wikipedia.org/wiki/Enumerated_type """ # Score categories. # Change the values as you see fit. YACHT = "YACHT" ONES = "ONES" TWOS = "TWOS" THREES = "THREES" FOURS = "FOURS" FIVES = "FIVES" SIXES = "SIXES" FULL_HOUSE = "FULL_HOUSE" FOUR_OF_A_KIND = "FOUR_OF_A_KIND" LITTLE_STRAIGHT = "LITTLE_STRAIGHT" BIG_STRAIGHT = "BIG_STRAIGHT" CHOICE = "CHOICE" def score(dice, category): numbers = {"ONES": 1, "TWOS": 2, "THREES": 3, "FOURS": 4, "FIVES": 5, "SIXES": 6} score = 0 if category in numbers: for i in dice: if i == numbers[category]: score += i return score if category == "YACHT": score = 50 for i in range(1, len(dice)): if dice[i] != dice[i -1]: score = 0 return score if category == "FULL_HOUSE": temp_dict = {} triple = 0 double = 0 for i in dice: if i not in temp_dict: temp_dict[i] = 1 else: temp_dict[i] += 1 for i in temp_dict: if temp_dict[i] >= 3: triple = i temp_dict[i] = 0 for i in temp_dict: if temp_dict[i] >= 2: double = i if triple != 0 and double != 0: return 3 * triple + 2 * double else: return 0 if category == "CHOICE": return sum(dice) if category == "FOUR_OF_A_KIND": temp_dict = {} quadruple = 0 for i in dice: if i not in temp_dict: temp_dict[i] = 1 else: temp_dict[i] += 1 for i in temp_dict: if temp_dict[i] >= 4: quadruple = i if quadruple != 0: return 4 * quadruple else: return 0 if category == "LITTLE_STRAIGHT": if sorted(dice) == [1, 2, 3, 4, 5]: return 30 else: return 0 if category == "BIG_STRAIGHT": if sorted(dice) == [2, 3, 4, 5, 6]: return 30 else: return 0
true
669ed897002906ec966e9e6c7d06a97230402f0a
noalez/Assignment1
/Q3.py
1,371
4.21875
4
def compare_subjects_within_student(subj1_all_students, subj2_all_students): """ Compare the two subjects with their students and print out the "preferred" subject for each student. Single-subject students shouldn't be printed. Choice for the data structure of the function's arguments is up to you. """ best_subject = {} names = subj1_all_students.keys() for name in names: if name != 'Subject': if str(subj2_all_students.get(name)) != 'None': subj2_all_students[name] = max(subj2_all_students[name]) subj1_all_students[name] = max(subj1_all_students[name]) if subj1_all_students[name]>subj2_all_students[name]: best_subject[name] = subj1_all_students['Subject'] elif subj1_all_students[name]<subj2_all_students[name]: best_subject[name] = subj2_all_students['Subject'] else: best_subject[name] = str(subj1_all_students[name])+' in both' print(best_subject) dict1 = {'Subject': 'Math', 'Amy': [90,80], 'Ben': [70,80], 'John': [55,65], 'Jane': [80,70], 'Alex': [100,90]} dict2 = {'Subject': 'History', 'Amy': [95,80], 'Ben': [70,60], 'John': [60,95], 'Alex': [55,90]} compare_subjects_within_student(dict1,dict2)
true
48dba6ea3eab7303ec08688d1964730d12a64a51
affandhia/ifml-pwa
/main/utils/naming_management.py
1,875
4.125
4
import re def dasherize(word): """Replace underscores with dashes in the string. Example:: >>> dasherize("FooBar") "foo-bar" Args: word (str): input word Returns: input word with underscores replaced by dashes """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1-\2', word) s2 = re.sub('([a-z0-9])([A-Z])', r'\1-\2', s1) return s2.replace('_','-').lower().replace(' ','') def camel_classify(word): """Creating class name based on a word that have a dash or underscore. Example:: >>> classify("foo_bar") >>> classify("foo-bar") "FooBar" Args: word (str): input word Returns: Class name based on input word """ return word.replace('_', ' ').replace('-', ' ').title().replace(' ','') def camel_function_style(word): """Creating class name based on a word that have a dash or underscore. Example:: >>> classify("foo_bar") >>> classify("foo-bar") "fooBar" Args: word (str): input word Returns: Funcation or var name styling based on input word """ classy_name = camel_classify(word) first_lowercase_letter = classy_name[:1].lower() rest_of_word = classy_name[1:] return first_lowercase_letter + rest_of_word def creating_title_sentence_from_dasherize_word(word): return word.replace('-',' ').title() #Specially used for ABS Microservice Framework naming convention def change_slash_and_dot_into_dash(word): return word.replace('/','-').replace('.','-') def change_slash_and_dot(word, replaced_string): return word.replace('/', replaced_string).replace('.', replaced_string) def remove_slash_and_dot(word): return word.replace('/', '').replace('.', '')
true
0c781cdc145f18c892b5eb8a6cfc5548451f1b85
abhishekk3/Practice_python
/monotonic_array.py
758
4.25
4
#Problem Statement: Given an array of integers, we would like to determine whether the array is monotonic (non-decreasing/non-increasing) or not. #Examples: #1 2 5 5 8->true #9 4 4 2 2->true #1 4 6 3->false #1 1 1 1 1 1->true def monotonic_arr(arr): num = arr[1] if arr [0] < arr [1]: for i in range(2,len(arr)): if arr[i] < num: return False return True elif arr [0] > arr [1]: for i in range(2,len(arr)): if arr[i] > num: return False return True else: return True a= [10,10,10,9,14] res=monotonic_arr(a) print(res)
true
43a6ed3e8d2afe9b208f4d790d2c784593bb16ce
djangoearnhardt/Exercism
/acronym.py
254
4.15625
4
# Convert a long phrase to its acronym print("Enter your long phrase, and I'll convert it to an acronym.") str = input() # str = str.split() str_len = len(str) output = '' for i in str.upper().split(): output += i[0] print(f"Your acronym is", output)
true
2ad6f815dbd3d0bdc29d9902486701b6790dbfa5
Emaasit/think-python
/card.py
1,757
4.5625
5
"""This is Chapter 18: Inheritance Learning Python programming using the book titled Think Python, 2nd Edition by Allen Downey http://thinkpython2.com Copyright 2017 Daniel Emaasit License: http://creativecommons.org/licenses/by/4.0/ """ from random import shuffle class Card: """Represents the cards in deck Attributes ---------- suits : int ranks : int """ suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] def __init__(self, suit = 0, rank = 2): """Initialize a Card object """ self.suit = suit self.rank = rank def __str__(self): return "%s of %s" % (Card.suit_names[self.suit], Card.rank_names[self.rank]) def __lt__(self, other): # using tuple comparison t1 = self.suit, self.rank t2 = other.suit, other.rank return t1 < t2 class Deck: """Represents a deck of 52 cards""" def __init__(self): self.cards = [] for suit in range(4): for rank in range(1, 14): card = Card(suit, rank) self.cards.append(card) def __str__(self): res = [] for card in self.cards: res.append(str(card)) return "\n".join(res) def remove_card(self): return self.cards.pop() def add_card(self, card): self.cards.append(card) def shuffle_deck(self): shuffle(self.cards) class Hand(Deck): """Represents a Hand which inherits from Deck class""" def __init__(self, label = ""): self.cards = [] self.label = label
true
166a849b4c82c1f0486cce56a0dcf17cf9e0ca9f
foureyes/csci-ua.0479-spring2021-001
/resources/code/class11/fraction.py
1,429
4.125
4
class Fraction: def __init__(self, n, d): self.n = n self.d = d # this means that this method can be called without instance # and consequently, no self is needed # instead, you call it on the actual class itself # Fraction.gcf() @staticmethod def gcf(a, b): # go through every possible factor # check if it divides evenly into both # return the largest one cur_gcf = 1 for factor in range(1, a + 1): if a % factor == 0 and b % factor == 0: cur_gcf = factor return cur_gcf def reduce(self): gcf = Fraction.gcf(self.n, self.d) return Fraction(self.n // gcf, self.d // gcf) def __str__(self): return "{}/{}".format(self.n, self.d) def __repr__(self): # we can call methods that already defined return self.__str__() def add(self, other): new_n = (self.n * other.d) + (other.n * self.d) new_d = self.d * other.d return Fraction(new_n, new_d) def __add__(self, other): return self.add(other) def __eq__(self, other): return self.n == other.n and self.d == other.d a = Fraction(1, 2) b = Fraction(6, 8) c = Fraction(1, 3) fractions = [a, b, c] print(fractions) print(a.add(c)) print(a + c) print(a == c) print(a == Fraction(1, 2)) print(Fraction.gcf(9, 12)) print(Fraction(4, 8).reduce())
true
5ce4d0d839d165438d3149d00e6ceea0bd48d2fa
foureyes/csci-ua.0479-spring2021-001
/assignments/hw03/counting.py
593
4.46875
4
""" counting.py ===== use *while* loops to do the following: * print out "while loops" * use a while loop to count from 2 up-to and including 10 by 2's. * use another while loop to count down from 5 down to 1 use *for* loops to do the following: * print out "for loops" * use a for loop to count from 2 up-to and including 10 by 2's. * use another for loop to count from 5 down to 1. * comment your code (name, date and section on top, along with appropriate comments in the body of your program) example output: while loops 2 4 6 8 10 5 4 3 2 1 for loops 2 4 6 8 10 5 4 3 2 1 """
true
c9f5850173477fdec74a2cf3eeaea216a5d221b7
foureyes/csci-ua.0479-spring2021-001
/_includes/classes/17/count.py
315
4.1875
4
def count_letters(letter, word): """returns the number of times a letter occurs in a word""" count = 0 for c in word: if c == letter: count += 1 return count assert 3 == count_letters("a", "aardvark"), "should count letters in word" assert 0 == count_letters("x", "aardvark"), "zero if no letters in word"
true
33827cee45fdaf7aa3210750392d51b51c4a58f9
foureyes/csci-ua.0479-spring2021-001
/resources/code/class04_return.py
766
4.375
4
""" return is a statement a value has to be on the right hand side that value can be an expression (that will be evaluated before the return) and it does 2 things: * immediately stops the function * gives back the value / expression to the right of it return statements have to be in a function they can be in a loop, as long as that loop is in a function """ """ def experiment(): print(1) return 'foo' print(2) experiment() """ """ def experiment(): for i in range(5): return i print(experiment()) # function ends on first iteration! """ """ def experiment(): for i in range(5): print(i) # after the for loop, i will still refer to its last value return i print('out of function', experiment()) """
true
3df9bf90f72f82039043e5db9b15d36424e2a5b6
foureyes/csci-ua.0479-spring2021-001
/_includes/classes/15/factorial_iterative_version_user_input.py
214
4.21875
4
def factorial(n): product = 1 for i in range(n, 0, -1): product = product * i return product user_input = input("Give me a number, I'll give you the factorial\n>") num = int(user_input) print(factorial(num))
true
244f4199d414d124c61646de18df4e6cfa1f30b8
foureyes/csci-ua.0479-spring2021-001
/resources/code/class05.py
2,109
4.46875
4
# go over some of the "old" slides # try a sample "quiz" question(s) ... practice for the upcoming # field some homework questions # go over strings # or go over more intermediate level stuff w/ lists """ >>> def foo(bar): ... """ """foo will print out the argument passed in""" """ ... print(bar) ... >>> help(foo) >>> # docstrings is_leap_year... """ # call the function # print out the result # does the result match my expectation # call the function twice # automatically test the observed result vs your expected result # assert statement # assert boolean expression, "description" # assert oberved == expected, "description of the test" """ def is_short_string(s): return len(s) < 3 #return True assert is_short_string('hello') == False, "this test determines if function returns false if we have a long string" assert is_short_string('') == True, "returns true if string is less than 3 chars" """ """ designing functions create a chart called input, output and processing input - what are the parameters? output - what's the return value (NOT WHAT IS PRINTED) processing - what goes in the body my_abs <-- input: * a number output: * a number, the absolute value of the input processing * whatever calculation you have to make """ """ in the doc string is_leap_year(y) y: int - the year used to determine if leap year our not return: bool - True or False depending on if year is leap year processing: describe the algo you might use """ """ the most common case for no params is a main """ """ def main(): name = input('what is your name?') print(name) main() """ """ def foo(): s = "bar" # no return result = foo() print(result) """ # if there's no return, then function gives back None # None is a special value that means NO VALUE result = print('hello') # print does not return anything!!!! <-- None print(result) """ def print() show something on screen but don't return anything """ # hello # None # it will def print out None
true
0497b83fab0d8c6f4eb21717c2ffdb9f4717f926
foureyes/csci-ua.0479-spring2021-001
/resources/code/class07_redact_dna.py
1,561
4.21875
4
""" redact(words, illegal_words) word is a list of strings illegal_words also a list of strings if one of the strings in words exists in illegal words then "replace" the first three letters with dashes otherwise, word stays the same if less than 3, then all chars returns an entirely new list composed of censored words """ """ def redact(words, illegal_words): new_words = [] for word in words: if word in illegal_words: if len(word) <= 3: redacted_word = len(word) * '-' else: redacted_word = '---' + word[3:] new_words.append(redacted_word) else: new_words.append(word) return new_words print(redact(['a', 'very', 'delicious', 'cake', 'for', 'me'], ['delicious', 'cake', 'me'])) """ """ codons 3 of ACTG | \/ AAG-CCA-ATG CAG-TCA """ """ import random def gen_dna(codons): dna = '' for i in range(codons): # if we are on the last index.... dna += gen_codon() if i < codons - 1: dna += '-'; return dna def gen_codon(): letters = 'ACTG' codon = '' for i in range(3): n = random.randint(0, 3) letter = letters[n] codon += letter return codon print(gen_dna(3)) print(gen_dna(7)) """ """ # split and join # split turn string into list # join turn list into string # both are called as methods on a string names = 'alice and bob and carol' names_as_list = names.split(' and ') print(names_as_list) print('---'.join(names_as_list)) """
true
58a7b172b7f719eca24e0f98780dc5056daa0a3e
foureyes/csci-ua.0479-spring2021-001
/assignments/hw03/grade.py
1,073
4.5
4
""" grade.py ===== Translate a numeric grade to a letter grade. 1. Ask the user for a numeric grade. 2. Use the table below to calculate the corresponding letter: 90-100 - A 80-89 - B 70-79 - C 60-69 - D 0-59 - F 3. Print out both the number and letter grade. 4. If the value is not numeric, allow the error to happen. 5. However, if the number is not within the ranges specified in the table, output: "Could not translate %s into a letter grade" where %s is the numeric grade" __COMMENT YOUR SOURCE CODE__ by * briefly describing parts of your program * including your name, the date, and your class section at the top of your file (above these instructions) Example Output (consider text after the ">" user input): Run 1: ----- What grade did you get? > 59 Number Grade: 59 Letter Grade: F Run 2: ----- What grade did you get? > 89 Number Grade: 89 Letter Grade: B Run 3: ----- What grade did you get? > 90 Number Grade: 90 Letter Grade: A Run 4: ----- What grade did you get? > -12 Couldn't translate -12 into a letter grade """
true
64153c77965ffd4fc5ecab9c382e17c496b9ed6b
foureyes/csci-ua.0479-spring2021-001
/assignments/hw06/translate_passage.py
2,885
4.25
4
""" translate_passage.py ===== Use your to_pig_latin function to translate an entire passage of text. Do this by importing your pig_latin module, and calling your to_pig_latin function. You can use any source text that you want! For example: Mary Shelley's Frankenstein from Project Gutenberg: http://www.gutenberg.org/cache/epub/84/pg84.txt Or... the Hacker Manifesto from phrack http://phrack.org/issues/7/3.html Here's an example of using Mary Shelley's Frankenstein. Taking The second paragraph in "Letter 1"... ----- I am already far north of London, and as I walk in the streets of Petersburgh, I feel a cold northern breeze play upon my cheeks, which braces my nerves and fills me with delight. ... Would be translated to... ----- i amway alreadyway arfay orthnay ofway ondonlay, andway asway i alkway inway ethay treetssay ofway etersburghpay, i eelfay a oldcay orthernnay reezebay laypay uponway ymay eekschay, hichway racesbay ymay ervesnay andway illsfay emay ithway elightday. This program can be implemented two ways: 1. (easy) using a built string method called split to break up the passage into individual words only using space as a word boundary 2. (medium) manually break apart the passage by looping and accumulating characters, using space non-letter characters as word boundaries Step-by-step instructions: 1. Bring in your pig_latin module using import 2. Copy a large paragraph as a triple quoted string and assign this string to a variable name. 3. Write a function that will: a. one parameter, a string, the entire passage to be translated. b. return a translated version of the string by using the pig latin function (that only translates single words) 4. To do this treat all consecutive letters as words. Note that numbers, punctuation and white space do not count as "letters". Translate each word and create a string that represents the translation of the full text. * ALTERNATIVELY, an easy way to deal with breaking up a string is by using the string method called split: * s = 'the hacker manifesto' * words = s.split(' ') # words is ['the', 'hacker', 'manifesto'] 7. Print out the result of calling your translate_passage function on a paragraph from Frankenstein HINT for the standard version (don't read this until you've tried writing the pseudocode for the above specifications on your own) 1. Accumulate two strings... your current word, and the actual translation. 2. Go through every character, collecting them into a word. 3. When you encounter a non letter character (use islpha), take what you currently have as a word, translate it, and add it to the translation 4. Add the non letter character to the translation 5. Reset your current word to empty string and go on with the loop (This is just one possible implementation; there are other ways to do this!) """
true
1fb70af92655eb5feeefcdb9b69a6eac5bab9db7
julienawilson/data-structures
/src/shortest_path.py
1,492
4.15625
4
"""Shortest path between two nodes in a graph.""" import math def dijkstra_path(graph, start, end): """Shortest path using Dijkstra's algorithm.""" path_table = {} node_dict = {} # try: # infinity = math.inf # except: infinity = float("inf") for node in graph.nodes(): path_table[node] = [None, infinity] node_dict[node] = infinity path_table[start][1] = 0 node_dict[start] = 0 while node_dict: shortest_dist_node = min(node_dict, key=node_dict.get) current_node_val = shortest_dist_node if current_node_val == end: break node_dict.pop(current_node_val) for child in graph.neighbors(current_node_val): current_node_distance = path_table[current_node_val][1] for edge in graph.node_dict[current_node_val]: if edge[0] == child: edge_length = edge[1] trial_distance = current_node_distance + edge_length if trial_distance < path_table[child][1]: path_table[child][1] = trial_distance node_dict[child] = trial_distance path_table[child][0] = current_node_val current = end total_length = path_table[end][1] path_list = [current] while current is not start: path_list.append(path_table[current][0]) current = path_table[current][0] return "Total length: {}, Path: {}""".format(total_length, path_list[::-1])
true
4713b6f84dd3413a20d71fe230fdcf2b499a2621
fermolanoc/sw-capstone
/lab2/student_dataclass.py
676
4.3125
4
from dataclasses import dataclass @dataclass # dataclass decorator to simplify class definition class Student: # define attributes with data types -> this usually goes on __init__ method along with self name: str college_id: int gpa: float # override how info will be printed def __str__(self): return f'Student: {self.name}\nCollege id: {self.college_id}\nGPA: {self.gpa}\n' def main(): # Create Students instances alice = Student('Alice Cooper', 12345, 4.0) meli = Student('Melissa Cobo', 12124, 3.99) ethan = Student('Ethan Ludovick', 99882, 2.001) # Print each student data print(alice) print(meli) print(ethan) main()
true
9697410fe37ce6a23ed05209a1f203ffd532cbc1
codingram/courses
/python-for-everybody/08_file_count.py
712
4.28125
4
# Exercise 5: # # Open the file mbox-short.txt and read it line by line. When you find a line # that starts with 'From ' like the following line: # # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 # # You will parse the From line using split() and print out the second word in # the line (i.e. the entire address of the person who sent the message). Then # print out a count at the end. fname = input("Enter file name: ") fh = open(fname) count = 0 for line in fh: line = line.rstrip() if not line.startswith("From "): # Different solution in Ex.2 continue word = line.split() print(word[1]) count = count + 1 print("There were", count, "lines in the file with From as the first word")
true
ead7827cba391e26589a66717709406c0a27001b
codingram/courses
/python-for-everybody/08_list_max_min.py
586
4.46875
4
# Exercise 6: # # Rewrite the program that prompts the user for a list of numbers and prints out # the maximum and minimum of the numbers at the end when the user enters “done”. # Write the program to store the numbers the user enters in a list and use the # max() and min() functions to compute the maximum and minimum numbers after the # loop completes. mml = [] while True: mmdata = input("Enter a number: ") if mmdata == "done": break mmdata = float(mmdata) mml.append(mmdata) print("Maximum value is:", max(mml)) print("Minimum value is:", min(mml))
true
d847f9cc90b307d3f6aeb41d3841b26fe94fdf66
codingram/courses
/MITx6001x/edx/ps1/ps1_3.py
815
4.34375
4
""" Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print: Longest substring in alphabetical order is: beggh In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print: Longest substring in alphabetical order is: abc """ # s = 'abcbcd' s = "azcbobobegghakl" # s = 'aaaaaaaaaaaabaaaaaaaaaazaaaaaaaaaafaaaaaaaaayaaaaaaaa' strg = s[0] for let in s[1:]: strg = strg + let if strg[-1] <= let else strg + " " + let strList = strg.split() largest = "" for i in strList: if len(i) > len(largest): largest = i print("Longest substring in alphabetical order is:", largest)
true
8f8c494b841104a69bea119b5a278f74479070a3
bestyoucanbe/joypython0826-b
/dictionaryOfWords.py
1,599
4.8125
5
# You are going to build a Python Dictionary to represent an actual dictionary. Each key/value pair within the Dictionary will contain a single word as the key, and a definition as the value. Below is some starter code. You need to add a few more words and definitions to the dictionary. # After you have added them, use square bracket notation to output the definition of two of the words to the console. # Lastly, use the for in loop to iterate over the KeyValuePairs and display the entire dictionary to the console. """ Create a dictionary with key value pairs to represent words (key) and its definition (value) """ word_definitions = dict() """ Add several more words and their definitions Example: word_definitions["Awesome"] = "The feeling of students when they are learning Python" """ # Define different keys in the dictionary. word_definitions["Exciting"] = "It is exciting to learn a new language" word_definitions["Challenging"] = "It is challenging to learn a new computer language" """ Use square bracket lookup to get the definition of two words and output them to the console with `print()` """ # Lookup the definition of each item in the dictionary. definition_of_exciting = word_definitions["Exciting"] definition_0f_challenging = word_definitions["Challenging"] """ Loop over the dictionary to get the following output: The definition of [WORD] is [DEFINITION] The definition of [WORD] is [DEFINITION] The definition of [WORD] is [DEFINITION] """ for eachword in word_definitions: print(f'The definition of {eachword} is {word_definitions[eachword]}')
true
0b7e61fb66ee63523dd111eec1e8b4184d373191
Ayush05m/coding-pattern
/Python Codes/longestSubString.py
682
4.125
4
def longest_unique_subString(str1): windowstart = 0 max_length = 0 index_map = {} for windowend in range(len(str1)): right = str1[windowend] if right in index_map: windowstart = max(windowstart, index_map[right] + 1) index_map[right] = windowend max_length = max(max_length, windowend - windowstart + 1) return max_length if __name__ == '__main__': print("Length of the longest substring: " + str(longest_unique_subString("aabccbb"))) print("Length of the longest substring: " + str(longest_unique_subString("abbbb"))) print("Length of the longest substring: " + str(longest_unique_subString("abccde")))
true
68f7c4431ce6d5e6ba0cff983ed6f23603434d22
zahraishah/zahraishah.github.io
/ErdosRenyi_graphs.py
1,217
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jun 13 11:43:46 2020 @author: malaikakironde """ #This document goes over implementing a random graph using #the Erdos-Renyi Model import sys import matplotlib.pyplot as plt import networkx as nx import random def erdos_renyi(G,p): #finding all possible edges in G for i in G.nodes(): for j in G.nodes(): #the edges do not count if they start and end at the same node if i != j: r = random.random() #if the random number is less than the probabilty, then #an edge will be drawn if r <= p: G.add_edge(i,j) #if not, the edge will not be drawn else: continue def graph_G(): #G(n,p) n = int(input('Enter the number of nodes: ')) p = float(input('Enter a number between 0 and 1 for the probability: ')) #Creating an empty graph G = nx.Graph() #Adding nodes and edges to the graph G.add_nodes_from([i for i in range(n)]) erdos_renyi(G,p) #Drawing the graph nx.draw(G) plt.show() graph_G()
true
c085dc3d74bbb82b00b1de60f434a9a0dd53be3e
milenacudak96/python_fundamentals
/labs/04_conditionals_loops/04_07_search.py
365
4.15625
4
''' Receive a number between 0 and 1,000,000,000 from the user. Use while loop to find the number - when the number is found exit the loop and print the number to the console. ''' number = int(input('enter the number between 0 and 1000000000: ')) while number in range(1, 1000000000): print(number) break else: int(input('enter the other number: '))
true
ec8885cb263e5d23fc69f837f83882bab1d48d23
milenacudak96/python_fundamentals
/labs/04_conditionals_loops/04_01_divisible.py
333
4.40625
4
''' Write a program that takes a number between 1 and 1,000,000,000 from the user and determines whether it is divisible by 3 using an if statement. Print the result. ''' number = int(input('enter the number between 1 and 1000000000: ')) if number % 3 == 0: print('its divisible by 3') else: print('its not divisible by 3')
true
d12615c7de5b1a340a8469fb265b15aa3c5fc7b3
milenacudak96/python_fundamentals
/labs/07_classes_objects_methods/07_02_shapes.py
797
4.5
4
''' Create two classes that model a rectangle and a circle. The rectangle class should be constructed by length and width while the circle class should be constructed by radius. Write methods in the appropriate class so that you can calculate the area (of the rectangle and circle), perimeter (of the rectangle) and circumference of the circle. ''' class Rectangle: def __init__(self, length, width): self.length = length self.width = width def perimeter(self): return (2 * self.length) + (2 * self.width) class Circle: def __init__(self, radius): self.radius = radius def circumference(self): return 2 * 3.14 * self.radius Circle = Circle(5) print(Circle.circumference()) Rectangle = Rectangle(6, 5) print(Rectangle.perimeter())
true
35968dce2d4f437986f46c8762d798a869a32eec
ashutoshnarayan/Coursera
/guess_the_number.py
2,461
4.34375
4
# "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import math import random # initialize global variables used in your code count_of_guesses = 7 game_range = 100 secret_number = random.randrange(0, 100) startgame = 0 # By default game in the range 0-100 starts. print "New Game. Range in between 0 to 100" print "Number of remaining guesses is ", count_of_guesses # define event handlers for control panel def range100(): # button that changes range to range [0,100] and restarts global count_of_guesses, game_range secret_number = random.randrange(0,100) count_of_guesses = 7 game_range = 100 print "New Game. Range in between 0 to 100" print "Number of remaining guesses is ", count_of_guesses def range1000(): # button that changes range to range [0,1000] and restarts global count_of_guesses, game_range count_of_guesses = 10 game_range = 1000 secret_number = random.randrange(0,1000) print "New Game. Range is between 0 to 1000" print "Number of remaining guesses is ", count_of_guesses def get_input(guess): # main game logic goes here global count_of_guesses, secret_number, startgame guess = int(guess) print "Guess was:" ,guess count_of_guesses -= 1 if guess == secret_number: print "Number of remaining guesses is ", count_of_guesses print "Correct.." startgame = 1 if guess < secret_number: print "Number of remaining guesses is ", count_of_guesses print "Lower.." if guess > secret_number: print "Number of remaining guesses is ", count_of_guesses print "Higher.." if count_of_guesses == 0: startgame = 1 if guess != secret_number: print "You ran out of guesses. Correct number was", secret_number if(startgame == 1): if(game_range == 100): range100() else: range1000() startgame = 0 # create frame f = simplegui.create_frame("Guess the number", 200, 200) # register event handlers for control elements f.add_button("Range is [0,100]", range100, 200) f.add_button("Range is [0,1000]", range1000, 200) f.add_input("Enter the number", get_input, 200) # start frame f.start()
true
654adb4d0cfffff4f410b5408e631eeeb9d4856e
mannhuynh/Python-Codes
/OOP/APP_1/water.py
1,271
4.5625
5
class Water: """ How do you access a class variable (e.g., boiling_temperature ) from within a method (e.g., from state)? The answer is: You can access class variables by using self. So, in our example, you would write self.boiling_temperature. See the state method below for an illustration. The key takeaway here is that even though boiling_temperature is a class variable (i.e., it belongs to the class and not to the instance of the class), such a variable can still be accessed through the instance (i.e., through self). So, class variables belong to the class, but they also belong to the instance created by that class. """ boiling_temperature = 100 freezing_temperature = 0 def __init__(self, temperature): self.temperature = temperature def state(self): # Return 'solid' if water temp is less or equal than 0 if self.temperature <= self.freezing_temperature: return 'solid' # Return 'liquid' if water temp is between 0 and 100 elif self.freezing_temperature < self.temperature < self.boiling_temperature: return 'liquid' # Return 'gas' in other scenarios (water temp higher than 100) else: return 'gas'
true
051dc584bef186573140404b6de74f8ba9fc1fdf
Mariobouzakhm/Hangman
/hangman.py
2,574
4.1875
4
import filemanager, random def createWordList(word): lst = list() for i in range(len(word)): lst.append('-') return lst def modifyWordList(lst, word, letter): for i in range(len(word)): if word[i] == letter: lst[i] = letter return lst #Open a File Handle with the file containing all the words file = open('wordlist.txt', 'r') #list of all the words contained in the hangman dictionnary lst = filemanager.readLines(file) #Number of wrong choices the user can make while guessing a word chances = 8 while True: choice = input('Enter \'new\' to start a new game or \'done\' to exit the game - ').lower() if choice == 'new': print('Starting a new game....') #Word the user need to guess word = lst[random.randint(0, len(lst) -1)].lower() print(word) #Choices that are still available for the user choices = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] #Holds the correct letters a user has guessed with the remaining ones as well wordchoices = createWordList(word) ##Holds the wrong guesses a user has made wrong = list() while True: letter = input('Enter a new letter - ').lower() while letter not in choices: print('Invalid Choice') print('Choices: ', choices) letter = input('Enter a new letter - ').lower() index = word.find(letter) if index != -1: choices.remove(letter) print('Correct Letter: ', letter) wordchoices = modifyWordList(wordchoices, word, letter) print(wordchoices) if '-' not in wordchoices: print('Successfully Completed the Game !') break else: print('You are still missing some letters.') continue else: choices.remove(letter) print('Wrong Letter: ', letter) wrong.append(letter) print(wrong) if len(wrong) > chances: print('Game Lost. You have ran out of chances') break; else: print('You still have %d chances.' % (chances - len(wrong))) continue elif choice == 'done': print('Exiting the system...') break else: print('Wrong Argument')
true
7ccc450c398e40e9e8c97b927d20dbf0d4f83b7b
sergiosanchezbarradas/Udemy_Masterclass_Python
/sequences/automate boring.py
551
4.1875
4
# This program says hello and asks for my name. print('Hello, world!') print('Whats your name') your_name = input() print('nice to meet you ' + your_name) length_name = (len(your_name)) print('your name is {} characters long'.format(length_name)) print("What's your age") age = input() print("You will be " + str(int(age)+1) + " next year.....old fella") #Casting #If you want to specify the data type of a variable, this can be done with casting. #Example #x = str(3) # x will be '3' #y = int(3) # y will be 3 #z = float(3) # z will be 3.0
true
2ed3de8d74a1df5c2a32776675614f670af9b7bc
eraldomuha/software_development_projects
/rock_paper_scissors.py
2,995
4.21875
4
#!/usr/bin/env python3 from random import choice """This program plays a game of Rock, Paper, Scissors between two Players, and reports both Player's scores each round.""" moves = ['rock', 'paper', 'scissors'] """The Player class is the parent class for all of the Players in this game""" class Player: def move(self): return "rock" def learn(self, last_move): pass class HumanPlayer(Player): def move(self): myChoice = input("choose a move (paper, scissors, rock): ").lower() while myChoice not in moves: print("Not a valid move!") return self.move() return myChoice class RandomPlayer(Player): def move(self): return choice(moves) class ReflectPlayer(Player): def __init__(self): Player.__init__(self) self.last_move = None def learn(self, last_move): self.last_move = last_move def move(self): if (self.last_move is None): return Player.move(self) return self.last_move class CyclePlayer(Player): def __init__(self): Player.__init__(self) self.last_move = None def move(self): if (self.last_move is None): move = Player.move(self) else: index = moves.index(self.last_move) + 1 if index >= len(moves): index = 0 move = moves[index] self.last_move = move return move def beats(one, two): return ((one == 'rock' and two == 'scissors') or (one == 'scissors' and two == 'paper') or (one == 'paper' and two == 'rock')) class Game: def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 self.score1 = 0 self.score2 = 0 def play_round(self): move1 = self.p1.move() move2 = self.p2.move() if (beats(move1, move2) is True): print("PLAYER WINS :)") self.score1 += 1 elif (move1 == move2): print("It's a DRAW") pass else: print("COMPUTER WINS") self.score2 += 1 print(f"Player Move: {move1}, Computer Move: {move2}") print(f"Player Score: {self.score1}, Computer Score: {self.score2}") self.p1.learn(move1) self.p2.learn(move1) def play_game(self): print("Game start!") for round in range(3): print(f"Round {round+1}:") self.play_round() if (self.score1 > self.score2): print("PLAYER is the WINNER :)") elif (self.score1 == self.score2): print("No one is the Winner") else: print("COMPUTER is the WINNER") print("Game over!") if __name__ == '__main__': Player1 = HumanPlayer() Player2 = ReflectPlayer() game = Game(Player1, Player2) game.play_game()
true
2a53202790f416952f3e0eeaf46eeffda1b2440f
lachilles/oo-melons
/melons2.py
2,009
4.25
4
"""This file should have our order classes in it.""" class AbstractMelonOrder(object): """Default melon order """ def __init__(self, species, qty): self.species = species self.qty = qty self.shipped = False self.flat_rate = 0 def get_total(self): """Calculate price.""" if self.species == "Christmas": base_price = (5 * 1.5) else: base_price = 5 total = (1 + self.tax) * self.qty * base_price if self.order_type == "international" and self.qty < 10: total += 3 return total def mark_shipped(self): """Set shipped to true.""" self.shipped = True class DomesticMelonOrder(AbstractMelonOrder): """A domestic (in the US) melon order.""" order_type = "domestic" tax = 0.08 #order_type and tax are the class attributes class InternationalMelonOrder(AbstractMelonOrder): #InternationalMelonOrder subclasses AbstractMelonOrder """An international (non-US) melon order.""" def __init__(self, species, qty, country_code): #Defined the initialization method with attributes species, qty, country_code super(InternationalMelonOrder, self).__init__(species, qty) #Calling the initialization method of the super self.country_code = country_code #country_code is the instance attribute order_type = "international" tax = 0.17 #order_type and tax are the class attributes def get_country_code(self): """Return the country code.""" return self.country_code class GovernmentMelonOrder(AbstractMelonOrder): def __init__(self, species, qty, passed_inspection): super(GovernmentMelonOrder, self).__init__(species, qty) self.passed_inspection = False order_type = "government" tax = 0 def mark_inspections(self, passed): self.passed_inspection = passed
true
56fe479ffd914e40a60ecdd381d7dbfe37163c32
Tonyynot14/Textbook
/chapter5.10.py
339
4.15625
4
students = int(input("How many students do you have?")) highest = 0 secondhighest = 0 for i in range(students): score = int(input("What are the scores for the test?")) if score > highest: secondhighest=highest highest = score print("The highest test score was", highest, "\nThe second highest was",secondhighest )
true
7eb418fe5e33623b74ee446a4d515e32afa5c82c
Tonyynot14/Textbook
/nsidepolygonclass.py
1,229
4.1875
4
#Tony Wade # Class for regular polygons # Class that defines a polygon based on n(number of sides), side(length of side) # x(x coordinate) y(y coordinate) import math class RegularPolygon: # initalizer and default constructor of regular polygon def __init__(self, n=3, side = 1, x = 0, y = 0 ): self.__n= n self.__side = side self.__x = x self.__y = y # accessor function followed by mutator function of each piece of data def getN(self): return self.__n def setN(self,n): self.__n = n def getSide(self): return self.__side def setSide(self, side): self.__side = side def getX(self): return self.__x def setX(self, x): self.__x = x def getY(self): return self.__Y def setY(self, y): self.__y = y # Function for finding perimeter of regular sided polygon def getPerimeter(self): perimeter = self.__side*self.__n return perimeter # Function for finding the area of a regular sided polygon. Need math module for pi and tan functions. def getArea(self): area = (self.__n*(self.__side**2))/(4*math.tan(math.pi/self.__n)) return area
true
c5634614d01183874ccc6c7e0a0f651e9cd345ca
coldmanck/leetcode-python
/0426_Convert_Binary_Search_Tree_to_Sorted_Doubly_Linked_List.py
1,445
4.28125
4
# Runtime: 36 ms, faster than 55.87% of Python3 online submissions for Convert Binary Search Tree to Sorted Doubly Linked List. # Memory Usage: 14.8 MB, less than 100.00% of Python3 online submissions for Convert Binary Search Tree to Sorted Doubly Linked List. # Definition for a Node. class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right class Solution: '''Time O(n) Space O(h)''' def treeToDoublyList(self, root: 'Node') -> 'Node': def tree_to_doubly_list(root): if not root: return None, None left_tail, left_head = tree_to_doubly_list(root.left) # left_tail is used to connect with lower elements if left_tail: left_tail.right = root root.left = left_tail right_tail, right_head = tree_to_doubly_list(root.right) # right_head is used to connect with upper elements if right_head: right_head.left = root root.right = right_head # left_head and right_tail are kept as the final head and tail return (right_tail or root, left_head or root) if not root: return None tail, head = tree_to_doubly_list(root) tail.right = head head.left = tail return head
true
e0453bfe71a01326909b1105ad8333463af4d7a4
coldmanck/leetcode-python
/0077_Combinations.py
1,190
4.15625
4
class Solution: '''Backtrack. Time: O(k*C^n_k) Space (C^n_k)''' def combine(self, n: int, k: int) -> List[List[int]]: def backtrack(i, cur_arr, ans, arr): if len(cur_arr) == k: ans.append(cur_arr) return for j in range(i, n): backtrack(j + 1, cur_arr + [arr[j]], ans, arr) ans = [] arr = [i for i in range(1, n + 1)] backtrack(0, [], ans, arr) return ans ''' Algorithm Backtracking is an algorithm for finding all solutions by exploring all potential candidates. If the solution candidate turns to be not a solution (or at least not the last one), backtracking algorithm discards it by making some changes on the previous step, i.e. backtracks and then try again. Here is a backtrack function which takes a first integer to add and a current combination as arguments backtrack(first, curr). If the current combination is done - add it to output. Iterate over the integers from first to n. Add integer i into the current combination curr. Proceed to add more integers into the combination : backtrack(i + 1, curr). Backtrack by removing i from curr. '''
true
4bdb539d304920611d832ccf249baa155666b01b
JelenaKiblik/School-python
/kt1/exam.py
1,672
4.125
4
"""Kontrolltoo.""" def capitalize_string(s: str) -> str: """ Return capitalized string. The first char is capitalized, the rest remain as they are. capitalize_string("abc") => "Abc" capitalize_string("ABc") => "ABc" capitalize_string("") => "" """ if len(s) >= 1: return s[0].upper() + s[1:] else: return "" def sum_half_evens(nums: list) -> int: """ Return the sum of first half of even ints in the given array. If there are odd number of even numbers, then include the middle number. sum_half_evens([2, 1, 2, 3, 4]) => 4 sum_half_evens([2, 2, 0, 4]) => 4 sum_half_evens([1, 3, 5, 8]) => 8 sum_half_evens([2, 3, 5, 7, 8, 9, 10, 11]) => 10 """ new_list = [] list = [] for i in nums: if i % 2 == 0: new_list.append(i) if len(new_list) % 2 == 0: a = len(new_list) // 2 for i in range(a): list.append(new_list[i]) else: a = len(new_list) // 2 for i in range(a + 1): list.append(new_list[i]) return sum(list) def max_block(s: str) -> int: """ Given a string, return the length of the largest "block" in the string. A block is a run of adjacent chars that are the same. max_block("hoopla") => 2 max_block("abbCCCddBBBxx") => 3 max_block("") => 0 """ count = 1 string = s.lower() if len(string) == 0: return 0 else: for i in range(0, len(string) - 1): if string[i] == string[i + 1]: count += 1 return count print(max_block("hoopla")) print(max_block("")) print(max_block("abbCCCddBBBxx"))
true
6c0e0a844f7b4a863884ece04c4560c09167bb17
lkrauss15/Old-School-Stuff
/CarCalc.py
660
4.1875
4
# Programmer: Luke Krauss # Date: 9/15/14 # File: Wordproblems.py # This program allows a user to input specific numbers for a word problem. In this case, the user is saing up to purchase a car. def main(): print ("So you're saving up to buy a car?") carCost = input("How much is the car? ") currentCash = input("How much money do you have now? ") jobWage = input("How much money do you make per hour? ") hours = (carCost - currentCash)/jobWage days = (hours/24.0) weeks = (days/7.0) print ("You will need to work " + str(hours) + " hours,"+ str(days) + " days, or " + str(weeks) + " weeks in order to afford this car.") main()
true
3d9b540022732b42d3cb58317f9ac9c0fd2193cb
lcarbonaro/python
/session20161129/guess.v1.py
336
4.15625
4
from random import randint rand = randint(1,20) print('I have picked a random integer between 1 and 20.') guess = input('Enter your guess: ') if guess<rand: print('That is too low.') if guess>rand: print('That is too high.') if guess==rand: print('That is correct.') print('The random integer was: ' + str(rand))
true
5f241775792987d41cda409b63a38a36cf5981b7
KevinMFinch/Python-Samples
/productCommercial.py
591
4.125
4
print("Hello! I am going to ask you questions about your device to create a commercial.") yourObject = input("What is your object? ") yourData = input("What data does it take? ") how = input("How will you record the "+yourData+" from your "+yourObject+"?") where = input("Where will the "+how+" be located? ") cost = input("How expensive will your "+yourObject+" be in dollars? ") print("Coming soon! For the low price of "+cost+" dollars, ",end="") print("this new "+yourObject+" will easily record "+yourData+". It is easy to control from "+how+" located ",end="") print("on "+where+".")
true
a69bfc55246f403b8b5711818e6591e150739c09
jaysonmassey/CMIS102
/Assignment_2_CMIS_102_Jayson_Massey.py
2,585
4.53125
5
# Assignment 2 CMIS 102 Jayson Massey # The second assignment involves writing a Python program to compute the price of a theater ticket. # Your program should prompt the user for the patron's age and whether the movie is 3D. # Children and seniors should receive a discounted price. x # There should be a surcharge for movies that are 3D. x # You should decide on the age cutoffs for children and seniors and the prices for the three different age groups. x # You should also decide on the amount of the surcharge for 3D movies. # Your program should output the ticket price for the movie ticket based on the age entered # and whether the movie is in 3D. # Your program should include the pseudocode used for your design in the comments. # Document the values you chose for the age cutoffs for children and seniors, # the prices for the three different age groups and the surcharge for 3D movies in your comments as well. # Predefined variables child_age = 12 # upper age limit senior_age = 60 # lower age limit child_discount = 5 senior_discount = 3 ticket_price = 15 # for ages 13 - 59 three_d_surcharge = 5 # Get user input - "should prompt the user for the patron's age and whether the movie is 3D" print("Welcome to Movie Calculator! If you give me a little info, I'll tell you the price for your movie.") patron_name = input("What is your name?") print(patron_name, "what is your age?") patron_age = eval(input()) print("Thanks", patron_name, "you're", patron_age, ". Is the movie you want to see in 3D? Yes or No?") is_three_d = input() # added logic to ensure that the user says yes or no to the 3D question if is_three_d.lower() == "yes": #used lower() here to allow answers like YES and Yes print("Your movie is in 3D") ticket_price = ticket_price + three_d_surcharge # adds 3D surcharge elif is_three_d.lower() == "no": print("Your movie is not in 3D") else: print("I missed that", patron_name, ". Is the movie you want to see in 3D? Yes or No?") is_three_d = input() # logic for age-based discounts if patron_age <= child_age: ticket_price = ticket_price - child_discount print("Child price") elif patron_age >= senior_age: ticket_price = ticket_price - senior_discount print("Senior price") else: print("Calculations done!") # "output the ticket price for the movie ticket based on the age entered and whether the movie is in 3D." print(patron_name, "I've calculated your movie price, and it's $",ticket_price,". Thanks for using Movie Calculator!")
true
9fa7ba142e1959040911fd07092dabf96e018ecf
gasgit-cs/pforcs-problem-sheet
/es.py
2,040
4.3125
4
# program to read in a file and count ocurrence of a char # author glen gardiner # run program calling es.py and passing the name of a file to read # example: python es.py Lorem-ipsum.txt # for this task its es.py md.txt import sys # fn - filename # i - input from user # uc - uppercase i # lc - lowercase i fn = sys.argv[1] # get letter from user i = input("Enter the letter you require counted: ") # convert input to upper and lower uc = i.upper() lc = i.lower() # f - file # t - text # l - line # c - charachter def read_file(fn, lc, uc): # count all non space char count_all = 0 # count lower count_lower = 0 # count upper count_upper = 0 try: # open file in read mode with open(fn, "r") as f: # iterate for each line in f for line in f: # iterate for each char in each line for c in line: # check if c is a space if not c.isspace(): # if not increment count_all counter count_all +=1 # check if c is lowercase if c == lc: # increment count_lower count_lower += 1 # check if c is uppercase elif c == uc: # increment count_upper count_upper +=1 count_total = count_lower + count_upper # display count result print("Total Chars count: {} \t Total Lower input: {} \t Total Upper input: {} \t Total input: {}".format(count_all,count_lower, count_upper, count_total)) # close the file #f.close() # catch teh exception and display my message and built in python message (e) except Exception as e: # my message print("File not found, check name and path:(") # python exception message print(e) read_file(fn, lc, uc)
true
df03082be153b1535a15ba6a35f9fbfd8c6480e5
robertggovias/robertgovia.github.io
/python/cs241/w04/assignment04/customer.py
2,220
4.1875
4
from order import Order from product import Product class Customer: '''id=0 price quantity''' def __init__(self): ''' Construction of an empty object to receive the id from the customer, and his name. Then will receive the list of orders ''' self.id = "" self.name= "" #this empty list will receive all new order self.orders = [] def add_order(self,add_new): ''' Each time a new object of th class order is created will be appended on this line. ''' self.orders.append(add_new) def get_total(self): ''' The last code create a list, but we need to iterate on each element to get from each one de return of the funciton get_total from the class order. ''' sum_of_orders = 0 for final_totals in self.orders: sum_of_orders += final_totals.get_total() return sum_of_orders def get_order_count(self): ''' as easy as qwe have a list, to know the quantity of member of taat list we will use -len - which will evaluate how long is the list ''' amount = len(self.orders) return amount def print_orders(self): ''' To print each order, we iterate on each element and print each one with its display code. ''' for order in self.orders: if self.get_order_count() > 1: print() order.display_receipt() def display_summary(self): ''' Print each customer, and its orders (with products) ''' print("Summary for customer '{}':\nName: {}".format(self.id,self.name)) print("Orders:",self.get_order_count()) print("Total: ${:.2f}".format(self.get_total())) def display_receipts(self): ''' getting advance from all the other display functions, this one will print in detail all the details of the sale ''' print("Detailed receipts for customer '{}':\nName: {}".format(self.id,self.name)) if self.get_order_count() < 2: print() self.print_orders()
true
b0972ddcba708ccaf388c5f53d596f2bccebfb99
NishantGhanate/PythonScripts
/Scripts/alien.py
927
4.21875
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 11 13:39:32 2019 @author: Nishant Ghanate """ # your code goes here import pandas as pd #Take User input for alphabetical order and string #a= input('Enter the order of alphabet : \n') #b= input('Enter the string you want to sort according to the Alphabet provided : \n') a = "abcdefghijklmnopqrstuvwxyz" b = "cyxbza" df = [] #Combining both list to a new list for i,j in zip(list(a),list(a.upper())): df.append(j) df.append(i) #print(df) a=df #Converting list to the dataframe alphabet = pd.DataFrame(index=range(0,len(a)),columns=['letter']) spell = pd.DataFrame(index=range(0,len(b)),columns=['letter']) alphabet['letter'] = list(a) spell['letter'] = list(b) #Sorting of String according to alphabet as per condition provided alphabet=pd.merge(alphabet,spell,how='inner') ##Printing the final result #output = ''.join(alphabet['letter'].values.tolist()) #print(output)
true
bd446e6a1cd0e8bcb5fe6745d2ebe9b78c40639e
pavanpandya/Python
/Python Basic/27_Sets.py
589
4.5
4
# Set-Unordered Collection of unique objects my_set = {1, 2, 3, 4, 5, 6} print(my_set) # Now let say we have an another set name my_set2 my_set2 = {1, 2, 3, 4, 5, 5} print(my_set2) # Here this will only print the unique objects. my_set.add(100) my_set.add(2) # Here 2 is not added in the set because it is already present in the set. print(my_set) # print(my_set[0]) #This will throw an error as we can't access the elements like this. print(len(my_set)) print(2 in my_set) # Trick my_list = [1, 2, 3, 4, 5, 6, 5] print(set(my_list)) new = my_set2.copy() print(new) print(list(new))
true
adff70a67790e99f15a4effcddf6d69269395bf9
pavanpandya/Python
/Python Basic/38_Range().py
965
4.46875
4
# Range - It returns an object that produces a sequence of integers from start(inclusive) to stop(exclusive) by step. # Syntax: # range(stop) # range(start, stop[, step]) print(range(100)) # will give output: # range(0, 100) print(range(0, 100)) # will give output: # range(0, 100) for number in range(0, 100): print(number) # Will print the no. starting from 0 till 99 for _ in range(0, 10): print(_) # If you want don't need the variable then you can use underscore(_). # It indicates that hey i dont really care what's the variable name, I am just using range to get my desired output. for _ in range(0, 10, 2): print(_) # Will print the no. starting from 0 till 9 and will step over the number by 2 (Be Default it is 1) for _ in range(0, 10, -1): print(_) # Will not print anything for _ in range(10, 0, -1): print(_) # Will print it in reverse order i.e 10 to 1 for _ in range(2): print(list(range(10)))
true
4bf1675599ba2c0097469ead8eccccc889334057
pavanpandya/Python
/Other Python Section/06_Error_Handling.py
718
4.21875
4
# Error Handling: while True: try: age = int(input('What is your age: ')) print(age) except: print('Please enter a number') # The above code means try the code and if there is any error run except. else: print('Thank You') break # If there is any error then instead of some pre_written error, msg(print in above case) written in except will get printed. # If there are multiple diff error: while True: try: age = int(input('What is your age: ')) print(age) except ValueError: print('Please Enter a number') except ZeroDivisionError: print("You can't Enter Zero") else: print('Thank You') break
true
59ca9c162a99aabaa5affebfe41f32241e655379
pavanpandya/Python
/Python Basic/11_Formatted_Strings.py
768
4.34375
4
# Formatted Strings name = 'Pavan' age = 19 # print('Hi' + name + '. You are ' + age + ' year old.') --> This will throw an error as age is int # and string Concatenation only works with strings print('Hi ' + name + '. You are ' + str(age) + ' year old.') # Better Way of doing This print(f'Hi {name}. You are {age} year old.') # Formatted Strings # print('Hi {}. You are {} year old.').format('Pavan', '19') --> This will throw an error as it # will run for print and not for the elements in print. print('Hi {}. You are {} year old.'.format('Pavan', '19')) # This also works the same as above print('Hi {}. You are {} year old.'.format(name, age)) # printing other variable print('Hi {new_name}. You are {age} year old.'.format( new_name='John', age='20'))
true
be072451108e2ad01b0c6f2638d13f3352104d16
pavanpandya/Python
/OOP by Telusko/10_Constructor_in_Inheritance.py
1,292
4.59375
5
# SUB CLASS CAN ACCESS ALL THE FEATURES OF SUPER CLASS # BUT # SUPER CLASS CANNOT ACCESS ANY FEATURES OF SUB CLASS ''' IMPORTANT RULE: When you create object of sub class it will call init of sub class first. If you have call super then it will first call init of super class and then call the init of sub class. ''' # Rules : If you create object of sub class it will first try to find init of sub class, # if it is not found then it will call init of super class. class A: def __init__(self): print('INIt in A') def feature1(self): print("Feature-1 is Working") def feature2(self): print("Feature-2 is Working") class B(A): def __init__(self): # If you also want to call the init method of class A then use 'super' keyword or you can say method. # By writing super we are representing super class A. super().__init__() print('INIt in B') def feature3(self): print("Feature-3 is Working") def feature4(self): print("Feature-4 is Working") a1 = A() # Here though it is the object of Class B, it is will call init method(Constructor of Class A) # Because Class B was not having it's own init method. But after adding the init method, it will call it's own init method. a2 = B()
true
266c658edeabb5217f3cd1b8cf61a2ad2de4fea2
pavanpandya/Python
/Python Basic/07_Augmented_Assignment_Operator.py
471
4.71875
5
# Augmented Assignment Operator Some_value = 5 # Some_value = Some_value + 5 # instead of doing this we will use Augmented Assignment Operator, Some_value += 5 # --> which is equal to Some_value = Some_value + 5 # NOTE : In order to work this "Some_value += 5", the variable "Some_value" should be defined before or in other words, # It should have some value defined to it. print(Some_value) # We can also do # Some_value -= 5 # Some_value *= 5 # Some_value /= 5
true
3f1dce9f42dbd335fa08610df5732a308fb7f744
pavanpandya/Python
/Python Basic/56_Exercise_Functions.py
332
4.125
4
def Highest_Even_Number(li): evens = [] for item in li: if(item % 2 == 0): evens.append(item) max = 0 for i in evens: if(i > max): max = i return max # By using Max Function. # return max(evens) my_List = [10, 2, 3, 4, 8, 11] print(Highest_Even_Number(my_List))
true
14039762193d12d2ab24057aa383a327bc254eb5
pavanpandya/Python
/Other Python Section/08_Exercise_error_handling.py
551
4.15625
4
while True: try: age = int(input('What is your age: ')) print(age) except ValueError: print('Please Enter a number') except ZeroDivisionError: print("You can't Enter Zero") else: print('Thank You') break finally: print("Okay, I'am Finally Done") print("Can you hear me?") # Finally runs regardless at the end of everything. # Though we use break to get out of the loop, Finally will still get executed. # Print statement will not get executed as we have break the loop.
true
ff82750488e0dd6ee02cdda39ebad5fc36df5fe4
cameron-teed/ICS3U-5-04-PY
/cyliinder.py
922
4.3125
4
#!/usr/bin/env python3 # Created by: Cameron Teed # Created on: Nov 2019 # This program calculates volume of a cylinder import math def volume_calculator(radius, height): # calculates the volume # process volume = math.pi * radius * radius * height return round(volume, 2) def main(): # This is asks for the user input # Welcomes user print("This program calculates the volume of a cylinder. ") while True: try: # input radius = float(input("What is the radius: ")) height = float(input("What is the height: ")) # runs volume_calculator() volume = volume_calculator(height=height, radius=radius) # output print("\nThe volume is " + str(volume) + " units cubed.") break except ValueError: print("Please put in integer.\n") if __name__ == "__main__": main()
true
0fd7593dc7b0faafc04fa0664278eb7ed1859e80
Zgonz19/Towers-of-Hanoi
/TowersofHanoi.py
2,875
4.125
4
# COSC 3320, Towers of Hanoi, Assignment 1 # Gonzalo Zepeda, ID: 1561524 # when called, printMove function prints the current move as long as the parameters # entered correspond to the solution. # notable parameters: which disk is moving, disk location, disk destination, number of moves so far def printMove(disk, source, dest, currentStep): print("Move number " + str(currentStep) + ": Move disk " + str(disk) + " from " + str(source) + " to " + str(dest)) # the hanoi function is the main recursive function of the program # notable parameters: how many disks there are, the 5 pegs, the current move # once called, this function will call itself until all disks are in the destination peg def hanoi(numOfDisks, Start, source, dest, aux, last, current,r): numOfDisks = int(numOfDisks) if numOfDisks == 1: printMove(numOfDisks, source, aux, current) current+=1 printMove(numOfDisks, aux, dest, current) current+=1 elif numOfDisks == 2: printMove(numOfDisks-1, source, aux, current) current+=1 printMove(numOfDisks-1, aux, dest, current) current+=1 if current == 4: printMove(numOfDisks, Start, source, current) current+=1 printMove(numOfDisks, source, aux, current) current+=1 printMove(numOfDisks-1, dest, aux, current) current+=1 printMove(numOfDisks-1, aux, source, current) current+=1 printMove(numOfDisks, aux, dest, current) current+=1 if r == 2: printMove(2, dest, last, current) current+=1; printMove(numOfDisks-1, source, aux, current) current+=1 printMove(numOfDisks-1, aux, dest, current) current+=1; elif numOfDisks > 2: current = hanoi(numOfDisks-1, Start, source, dest, aux, last, current, r) if(hasItMoved[numOfDisks]!=1): printMove(numOfDisks, Start, source, current) current+=1 hasItMoved[numOfDisks]=1 printMove(numOfDisks, source, aux, current) current+=1 current = hanoi(numOfDisks-1,Start, dest, source, aux,last, current, r) printMove(numOfDisks, aux, dest, current) current+=1 if(toDest[numOfDisks+1]!=0): printMove(numOfDisks, dest, last, current) current+=1 toDest[numOfDisks]=1 if(numOfDisks == r): r-=1 current = hanoi(numOfDisks-1, Start,source, dest, aux,last, current, r) return current; # the hanoiInit function is only called once to initiate our program. # within hanoiInit is the first call to our recursive hanoi function. def hanoiInit(numOfDisks, start, source, dest, aux, last, current, r): printMove(1, start, source, current) current+=1 current = hanoi(n,"Start","Aux1","Aux3","Aux2","Dest",current,r) printMove(1, dest, last, current) current+=1 current=1 hasItMoved = [None]*12 toDest = [None]*12 n = input("How many disks are we solving for? ") r = int(n) hanoiInit(n,"Start","Aux1","Aux3","Aux2","Dest",current,r)
true
985035622d0ea945f08a311f4b075820771d1652
mswift42/project-euler
/euler38.py
954
4.28125
4
#!/usr/bin/env # -*- coding: utf-8 -*- """Pandigital mutiples Problem 38 28 February 2003 Take the number 192 and multiply it by each of 1, 2, and 3: 192 1 = 192 192 2 = 384 192 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n 1?""" def is_pandigital(number): if len(number) != 9: return False return sorted([int(i) for i in number]) == range(1,10) for i in range(20000, 5000, -1): number = str(i*1) + str(i*2) if is_pandigital(number): print number break # with Help From Dreamshire Blog.
true
46811fc30524954812699c4ecc59ea0ce77735fb
Igor-Zhelezniak-1/ICS3U-Unit4-02-Python-Math_Program
/math_program.py
766
4.21875
4
#!/usr/bin/env python3 # Created by: Igor # Created on: Sept 2021 # This is math_program def main(): loop_counter = 1 answer = 1 # input integer = input("Enter any positive number: ") print("") # process & output try: number = int(integer) if number < 0: print("Please follow the instructions! Enter any POSITIVE number") else: while loop_counter <= number: answer = answer * loop_counter loop_counter = loop_counter + 1 print("{0}! = {1}".format(number, answer)) except Exception: print("Please follow the instructions! Use numbers") finally: print("") print("Done") if __name__ == "__main__": main()
true
aedda9665a6e79cc9c6fb033d1b04aa9c4ba3565
ecornelldev/ctech400s
/ctech402/module_6/M6_Codio_PROJECT/exercise_files/startercode3.py
498
4.34375
4
#### # Player and Computer each have 3 dice # They each roll all 3 dice until one player rolls 3 matching dice. ####### # import random package import random # player and computers total score player_score = 0 computer_score = 0 # define a function that is checks for three matching dice # function returns True or False # Computer and user roll until one rolls 3 matching dice # Display the 3 dice with each roll # Print both the player and computer's final score and report who wins
true
688528928849a3a923618670d60ad349799e16a2
satvikag2001/codechef
/func_game_south.py
1,541
4.1875
4
from sys import exit import func_extra prompt = ">>>>" def south(): print("You have entered the castle of DOOM ,from its rear end") print("It is dark and faint sounds of screaming can be heard.") print("you are absoulutely defenceless so like every sane peron you walk down the dusty corridor taking in") print("all that you can see.you make out 3 doors .What do you do") print("#hint:try typing 'open door 1' or 'go back'") S_dr_1_list = ['open door 1', 'open door 2', 'open door 3', 'go out'] S_dr_1 = input(prompt) while S_dr_1 not in S_dr_1_list: print("You cannot do that ") S_dr_1 = input(prompt) if S_dr_1 =="open door 1": S_dr_1_1() elif S_dr_1 =="open door 2": S_dr_1_2() elif S_dr_1 =="open door 3": S_dr_2_3() else : func_extra.dead("the grim reaper was waiting for u outside.he drank your soul\n") def S_dr_1_1() : print(" There is a giant cat here eating a cheese cake. What do you do?") print("1. Take the cake .") print("2' Scream at the bear.") cat = input(prompt) if cat == "take the cake" or cat == "1": func_extra.dead("The bear eats off yours face. Good job!") elif cat=="2"or cat == "scream at the bear": func_extra.dead("the bear eats your legs off. Good job!") else : print("Well doing %s is probably better. The bear ran away \n You win"%cat) print("there is nothing else to do ") S_dr_1_1 = input() def S_dr_1_1() : print("good") func_extra.play_again() def S_dr_1_1() : print("good") func_extra.play_again()
true
943d825de16d00b7e445aaa34666b1cad7ec2844
ishantk/GW2021PY1
/Session18C.py
2,084
4.125
4
# Why Inheritance # Code Redundancy -> Development Time class FlightBooking: def __init__(self, from_location, to_location, departure_date, travellers, travel_class): self.from_location = from_location self.to_location = to_location self.departure_date = departure_date self.travellers = travellers self.travel_class = travel_class def show(self): print("~~~~~~~~~~~~~~~~~~~~~~~~~~") print(self.from_location, self.to_location) print(self.departure_date) print(self.travellers, self.travel_class) print("~~~~~~~~~~~~~~~~~~~~~~~~~~") # RoundTripFlightBooking IS-A FlightBooking # extension class RoundTripFlightBooking(FlightBooking): def __init__(self, from_location, to_location, departure_date, travellers, travel_class, return_date): FlightBooking.__init__(self, from_location, to_location, departure_date, travellers, travel_class) self.return_date = return_date def show(self): FlightBooking.show(self) print(self.return_date) def main(): one_way_booking = FlightBooking(from_location="Delhi", to_location="Bangalore", departure_date="12th Aug 2021", travellers=2, travel_class="economy") print(vars(one_way_booking)) print() two_way_booking = RoundTripFlightBooking(from_location="Delhi", to_location="Bangalore", departure_date="12th Aug 2021", travellers=2, travel_class="economy", return_date="20th Aug 2021") print(vars(two_way_booking)) two_way_booking.show() if __name__ == '__main__': main() # Assignment: Code Inheritance looking into the PayTM App """ Types of Inheritance 1. Single Level class CA: pass class CB(CA): pass 2. Multi Level class CA: pass class CB(CA): pass class CC(CB): pass 3. Hierarchy class CD(CA): pass 4. Multiple class CE: pass class CF(CE, CA): pass """
true
7ad70114f889d526874f3bda353179532676a51c
rantsandruse/pytorch_lstm_01intro
/main_example.py
2,312
4.25
4
''' This is the "quick example", based on: https://pytorch.org/tutorials/beginner/nlp/sequence_models_tutorial.html ''' import numpy as np import torch import torch.nn as nn # This is the beginning of the original tutorial torch.manual_seed(1) # The first implementation # Initialize inputs as a list of tensors # passes each element of the input + hidden state to the next step. # Think of hidden state as memory # inputs = [torch.rand(1,3) for _ in range(5)] # for i in inputs: # # Step through the sequence one element at a time. # # after each step, hidden contains the hidden state. # out, hidden = lstm(i.view(1, 1, -1), hidden) # # inputs = torch.cat(inputs).view(len(inputs), 1, -1) lstm = nn.LSTM(3, 3) # Alternatively, we can just initialize input as a single tensor instead of a list. inputs = torch.randn(5, 1, 3) hidden = (torch.randn(1, 1, 3), torch.randn(1, 1, 3)) # clean out hidden state out, hidden = lstm(inputs, hidden) # Additional examples are given for understanding of NLL loss and Cross Entropy loss implementation in pytorch import torch.nn.functional as F softmax_prob = torch.tensor([[0.8, 0.2], [0.6, 0.4]]) log_softmax_prob = torch.log(softmax_prob) print("Log softmax probability:", log_softmax_prob) target = torch.tensor([0,0]) # Note the NLL loss is the negative log at the correct class # The real NLL Loss is the sum of negative log of the correct class. # NLL loss = -1/n (sum(yi dot log(pi)) # Note: (1/n is the average loss here, which is the default pytorch implementation (reduction=mean). What you usually # see in textbooks/wikipedia is the sum of all losses (i.e. without 1/n) (reduction=sum in pytorch). # What is being implemented by pytorch, where xi is the input. # It is taken for granted that xi = log(pi), i.e. it's already gone through the log_softmax transformation when you # are feeding it into NLL function in pytorch. # Pytorch NLL loss = -1/n (sum(yi dot xi)) # In the example below: # When target = [0,0], both ground truth classifications below to the first class --> y1 = [1,0], y2 = [1,0] # y1 = [1,0]; log(p1) = [-0.22, -1.61] # y2 = [1,0]; log(p2) = [-0.51, -0.91] # Pytorch NLL loss = -1/n (sum(yi dot xi)) = 1/2 * (-0.22*1 - 0.51*1) = 0.36 nll_loss = F.nll_loss(log_softmax_prob, target) print("NLL loss is:", nll_loss)
true
3c04e2019071ccdf771f3fd7c2bfb0189235ac59
hirenpatel1207/IPEM_Smart_Coffee
/WorkingDirectory/Raspberry_Pi_Code/calculateParticularFeature.py
1,037
4.15625
4
""" Brief: this file calculates particular features passed in the argument. Calculate various features to generate the feature vector which can be used for prediction """ import numpy as np # Note: pass the feature name correctly to avoid error def calculateParticularFeatureFunc(x, featureName): # calculateParticularFeature This function calculates various features based on arguments # X is column vector which has the given data # featureName is the name of feature the user wants to calculate featureVal = 0 if(featureName =='Root Mean Square'): featureVal = np.sqrt(np.mean(np.square(x))) if (featureName == 'Variance'): featureVal = np.var(x) if (featureName == 'Mean'): featureVal = np.mean(x) if (featureName == 'Sum Of Frequency Amplitudes'): featureVal = np.sum(x) if (featureName == 'Root Variance Of Frequency'): featureVal = np.sqrt( np.var(x)) # return the featureValue return featureVal
true
150583f46366913093372af43576e892f3d7b3e5
aysegulkrms/SummerPythonCourse
/Week3/10_Loops_4.py
345
4.1875
4
max_temp = 102.5 temperature = float(input("Enter the substance's temperature ")) while temperature > max_temp: print("Turn down the thermostat. Wait 5 minutes. Check the temperature again") temperature = float(input("Enter the new Celsius temperature ")) print("The temperature is acceptable") print("Check it again in 15 minutes")
true
ee1cc4de9e1fefc268d34dfc27d1ef6cd73573ea
nbrahman/LeetCode
/ReverseInteger.py
929
4.15625
4
''' Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 click to show spoilers. Note: The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows. ''' class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ strNum = str(x) intMult = 1 if (strNum[0]=="-"): strFinalNum = strNum[1:len(strNum)] intMult = -1 else: strFinalNum = strNum strRevNum = strFinalNum[::-1] print (strRevNum) rtype = 0 if (int(strRevNum)<=2147483647) and (int(strRevNum)>=-2147483648): rtype = intMult * int(strRevNum) return rtype if __name__ == '__main__': num1 = input ("enter the string for atoi: ") num2 = "9" result = Solution().reverse(num1) print (result)
true
3c7f4279f3901b455a9a8320029206845a06afc4
atriekak/LeetCode
/solutions/341. Flatten Nested List Iterator.py
2,459
4.1875
4
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger: # def isInteger(self) -> bool: # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # """ # # def getInteger(self) -> int: # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # """ # # def getList(self) -> [NestedInteger]: # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # """ class NestedIterator: #Approach: Stack of iterators #Time Complexity: O(l / n) #Space Complexity: O(d) #where l is number of lists and n is the number of integers in the nestedList #and, d is the maximum nesting depth def __init__(self, nestedList: [NestedInteger]): self.st = [] self.st.append(iter(nestedList)) def next(self) -> int: return self.nextEl.getInteger() def hasNext(self) -> bool: while self.st: try: self.nextEl = next(self.st[-1]) except: self.st.pop() continue if self.nextEl.isInteger(): return True else: self.st.append(iter(self.nextEl.getList())) return False """ from collections import deque class NestedIterator: #Approach: Flattening using recursion #Time Complexity: O(1) // flattening is a one time operation #Space Complexity: O(n) #where, n is the total number of integers in the nestedList def __init__(self, nestedList: [NestedInteger]): self.de = deque() self.flatten(nestedList) def next(self) -> int: return self.de.popleft() def hasNext(self) -> bool: return len(self.de) > 0 def flatten(self, nestedList): for el in nestedList: if el.isInteger(): self.de.append(el.getInteger()) else: self.flatten(el.getList()) return """ # Your NestedIterator object will be instantiated and called as such: # i, v = NestedIterator(nestedList), [] # while i.hasNext(): v.append(i.next())
true
a3a462573a5d9069a7736bd4036dd1f2012e079f
Novandev/chapt2
/convert3.py
483
4.25
4
# convert3.py # A program that convert Celsius temps to Fahrenheit and prints a table # redone by donovan Adams def main(): print "This is a program that converts Celcius to Fahrenheit." print "Here are the temperatures every 10 degrees" print " ____________________" for i in [10,20,30,40,50,60,70,80,90,100]: celsius = i fahrenheit = 9.0 / 5.0 * celsius + 32 print "The temperature is", fahrenheit, "degrees Fahrenheit." i = i + 10 main()
true
9d0a204ea2f2a8311b09b1c3cc7e278e9535364a
danieled01/python
/myapps/test_scripts/reverse.py
355
4.5625
5
#have to write a function that will return the value of a string backwards: def solution(string): return string[::-1] #string[::1] works by specifying which elements you want as [begin:end:step]. So by specifying -1 for the step you are telling Python to use -1 as a step which in turn starts #from the end. This works both with strings and lists
true
db892f7ee026d9356d5ffce80899ffb20bc3e698
DevanKula/CP5632_Workshops
/Workshop 7/do from scratch.py
364
4.15625
4
word_string = str(input("Enter the a phrase: ")).split() counter = 0 words_dicts = {} for word in word_string: counter = word_string.count(word) words_dicts = {word:counter} print(words_dicts) #print(word_count) # print(words_lists) # # word_count = word_string.count(words) #for word in words_lists: # print("{} : {}".format(word[0],word[1]))
true
b86a00994c09f0ecf9cd87ef82f50d66b69f9dc7
abhisheklomsh/MyTutorials
/#100daysOfCode/day1.py
2,781
4.34375
4
""" Two Number Sum: Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. If any two numbers in the input array sum upto the target sum, the function should return them in an array, in any order. If no two numbers sum up to the target sum, the function should return an empty array. Note that the target sum has to be obtained by summing two different integers in the array; you can't add a single integer to itself in order to obtain the target sum. You can assume that there will be at most one pair of numbers summing up to the target sum. There are 3 possible solutions for the question as follow. """ import unittest """ # O(n^2,) time | O(1) space def twoNumberSum(array, targetSum): for i in range(0, len(array) - 1): firstNum = array[i] for j in range(i + 1, len(array)): secondNum = array[j] if firstNum + secondNum == targetSum: return [firstNum, secondNum] return [] # O(n) time | O(n) space def twoNumberSum(array, targetSum): complements = {} n = len(array) for i in range(0, n): temp = targetSum - array[i] if temp in complements: return sorted([temp, array[i]]) else: complements[array[i]] = temp return [] """ # O(nlog(n)) time | O(1) space def twoNumberSum(array, targetSum): array.sort() #inplace sort left = 0 right = len(array) - 1 while left < right: currentSum = array[left] + array[right] if currentSum == targetSum: return [array[left], array[right]] elif currentSum < targetSum: left += 1 elif currentSum > targetSum: right -= 1 return [] class TestProgram(unittest.TestCase): def test_case_1(self): output = twoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 10) self.assertTrue(len(output) == 2) self.assertTrue(11 in output) self.assertTrue(-1 in output) def test_case_2(self): output = twoNumberSum([4, 6], 10) self.assertTrue(len(output) == 2) self.assertTrue(4 in output) self.assertTrue(6 in output) def test_case_3(self): output = twoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 15) self.assertTrue(len(output) == 0) def test_case_4(self): output = twoNumberSum([-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], 163) self.assertTrue(len(output) == 2) self.assertTrue(210 in output) self.assertTrue(-47 in output) def test_case_5(self): output = twoNumberSum([-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], 164) self.assertTrue(len(output) == 0) if __name__ == '__main__': unittest.main()
true
ee53bf76298753fd95975aefde030d4ae3baf56a
prathimaautomation/python_oop
/python_functions.py
1,422
4.59375
5
# Let's create a function # Syntax def is used to declare followed by name of the function(): # First Iteration # def greeting(): # print("Welcome on Board! enjoy your trip.") # # pass # pass keyword that allows the interpretor to skip this without errors # # # greeting() # if we didn't call the function it would execute the code with no error but no outcome # # # # DRY Don't Repeat Yourself by declaring functions and reusing code # # # Second Iteration using RETURN statement # def greeting(): # print("Good Morning") # return "Welcome on board! Enjoy your trip!!" # # # print(greeting()) # # # # Third Iteration with username as a String as an argument/args # def greeting(name): # return "Welcome on board " + name # # # print(greeting("Prathima")) # # # Fourth Iteration to prompt the user to enter their name and display the name back to user with greeting message # # def greeting(name): # return "Welcome on board " + name # # # print(greeting(input("Please give your name: "))) # Let's create a function with multiple args as an int def add(num1, num2): return num1 + num2 print(add(9, 3)) def multiply(num1, num2): print("This functions multiplies 2 numbers ") return num1 * num2 print(" this is the required outcome of 2 numbers ") # this line of code will not be executed as return statement is last line of code that function executes print(multiply(3, 3))
true
b77dc0558251c9f7e86390143e4d708a48249f15
2kaiser/raspberry_pi_cnn
/mp1/pt2.py
2,403
4.15625
4
import numpy as np #Step 1: Generate a 2-dim all-zero array A, with the size of 9 x 6 (row x column). A = np.zeros((9,6)) print("A is: ") print(A) #Step 2: Create a block-I shape by replacing certain elements from 0 to 1 in array A A[0][1:5] = 1 #top of I A[1][1:5] = 1 #top of I A[2][2:4] = 1 #middle of I A[3][2:4] = 1 #middle of I A[4][2:4] = 1 #middle of I A[5][2:4] = 1 #middle of I A[6][2:4] = 1 #middle of I A[7][1:5] = 1 #bottom of I A[8][1:5] = 1 #bottom of I print("I shaped A is: ") print(A) ################################################################################################################################ #todo #Step 3: Generate a 2-dim array B by filling zero-vector at the top and bottom of the array A. #make a zero array of desired size and then enclose the previous array around it B = np.zeros((11,6)) B[:A.shape[0],:A.shape[1]] = A #add in a row of zeros and remove the last row Z = np.concatenate(([[0,0,0,0,0,0]],B[0:10][:])) print("B is: ") print(Z) ################################################################################################################################ C =(np.arange(66).reshape(11, 6))+1 print("C is: ") print(C) ################################################################################################################################ D = np.multiply(Z,C) print("D is: ") print(D) ################################################################################################################################ E = np.zeros(26) index = 0 for i in range(D.shape[0]): for j in range(D.shape[1]): if(D[i][j] != 0): #print(D[i][j]) E[index] = D[i][j] index = index + 1 print("E is: ") print(E) ################################################################################################################################ max, min = E.max(), E.min() index = 0 F = np.zeros((11,6)) for i in range(D.shape[0]): for j in range(D.shape[1]): if(D[i][j] != 0): F[i][j] = (D[i][j] - min) / (max - min) index = index + 1 print("F is: ") print(F) #Step 8: Find the element in F with the closest absolute value to 0.25 and print it on screen. curr_closest = 10000 for i in range(D.shape[0]): for j in range(D.shape[1]): if(abs(curr_closest-.25) > abs(F[i][j]-.25)): curr_closest =F[i][j] print("Closest value is: ") print(curr_closest)
true
9b7535587b9e92bcd7cf5bb1577863b01b1f3792
lacoperon/CTCI_Implementations
/1_ArraysAndStrings/1.3.py
1,672
4.1875
4
''' Elliot Williams 08/02/18 Q: `URLify`: Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string ''' def URLify(char_array, true_length): j = len(char_array) - 1 # index of last character # Iterates through characters in char_array in reverse, # to prevent overwriting necessary characters for i in reversed(range(len(char_array))): current_char = char_array[i] if current_char is not None: if current_char is " ": # Adds in %20 in appropriate places, and goes back 3 characters char_array[j] = "0" char_array[j-1] = "2" char_array[j-2] = "%" j -= 3 else: char_array[j] = current_char j -= 1 return char_array # Time Complexity: O(N) # Space Complexity: O(1) ~in place~ # Helper function to generate appropriate input def char_arrayify(input): num_spaces = 0 char_array = [] for char in input: if char is " ": num_spaces += 1 char_array.append(char) char_array += [None] * num_spaces * 2 return char_array fox_str = "The Fox jumped quickly" empty_str = "" borg_str = "NoSpacesAreNecessaryForTheBorg" fox_example = (char_arrayify(fox_str), len(fox_str)) empty_example = (char_arrayify(empty_str), len(empty_str)) borg_example = (char_arrayify(borg_str), len(borg_str)) print("".join(URLify(*fox_example))) print("".join(URLify(*empty_example))) print("".join(URLify(*borg_example)))
true
5a481d5050fe713ca17e5b63747f03488e0f6540
jknight1725/pizza_compare
/pizza.py
948
4.125
4
#!/usr/bin/env python3 from math import pi from sys import argv p1_size = int(argv[1]) p1_price = int(argv[2]) p2_size = int(argv[3]) p2_price = int(argv[4]) def pizza(size, price): stats = {} radius = size / 2 radius_squared = radius*radius area = radius_squared * pi stats['size'] = size stats['price'] = price stats['area'] = area stats['price_per_unit'] = price / area return stats def compare(p1, p2): more_expensive, less_expensive = (p1, p2) if p1['price_per_unit'] > p2['price_per_unit'] else (p2, p1) ratio = more_expensive['price_per_unit'] / less_expensive['price_per_unit'] print("Best deal") print(f"{less_expensive['size']} inch pizza for {less_expensive['price']}") print(f"Price per sq. inch {less_expensive['price_per_unit']}") print(f"{ratio} times more value by choosing this pizza") p1 = pizza(p1_size, p1_price) p2 = pizza(p2_size, p2_price) compare(p1, p2)
true
4ea6c3c11397c35e0acadf6e69de7c2489d6ddbf
RLewis11769/holbertonschool-higher_level_programming
/0x0B-python-input_output/100-append_after.py
773
4.125
4
#!/usr/bin/python3 """ append_after - inserts text to file if line contains string @filename: file to search and append to @search_string: if in line, insert text after given line @new_string: text to insert after found text """ def append_after(filename="", search_string="", new_string=""): """ Appends new_string to filename after search_string line in filename """ string = "" with open(filename) as f: for line in f: """ Adds each line to new line """ string += str(line) """ If search_string is in line, adds string after """ if search_string in line: string += new_string """ Overwrites file with final string """ with open(filename, 'w') as f: f.write(string)
true
182e81555a1d0d5f4d9312d73ba8dfed7bc50841
Andy931/AssignmentsForICS4U
/BinarySearchInPython.py
2,318
4.15625
4
# Created by: Andy Liu # Created on: Oct 17 2016 # Created for: ICS4U # Assignment #3b # This program searches a number exists in an random array using binary search from random import randint array_size = 250 # define the size of the array def binary_search(search_value, num): # these variables define a range for searching start_position = 0 end_position = array_size - 1 mid_position = int((end_position - start_position) / 2 + start_position + 0.5) # loop the process until the number is found while search_value != num[mid_position]: mid_position = int((end_position - start_position) / 2 + start_position + 0.5) if search_value > num[mid_position]: start_position = mid_position else: end_position = mid_position if end_position-start_position <= 1: if search_value == num[start_position]: return start_position elif search_value == num[end_position]: return end_position else: print("Not Found!") return -1 return mid_position def bubble_sort(number_list): flag = False # set flag to false to begin first pass temp = 0 # holding variable while flag == False: flag = True # set flag to true awaiting a possible swap for j in range(len(number_list)-1): if number_list[j] > number_list[j+1]: # change to > for ascending sort temp = number_list[j+1] # swap elements number_list[j+1] = number_list[j] number_list[j] = temp flag = False # shows a swap occurred # Main program starts numberArray =[randint(1,2000) for i in range(0,array_size)] bubble_sort(numberArray) # call bubble sort function to sort the array for counter in range(0, array_size): print("A[",counter,"] = ", numberArray[counter]) # print out the sorted array # input inputNumber = eval(input("Please enter an integer to search: \n")) # input the number to search # process position = binary_search(inputNumber, numberArray) # call binary search function to search the number # output print("The position of the number is", position) # print out the position
true
697b324ffae85c598109b5ac5986f2c3af5dddc3
DenisLo-master/python_basic_11.06.2020
/homeworks/less3/task3.py
839
4.5625
5
""" 3. Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов. """ def my_func(num1: int, num2: int, num3: int) -> int: """ search for two of the smallest arguments out of three :param num1: any number :param num2: any number :param num3: any number :return: print (sum of two max value) """ m1_num = 0 m2_num = 0 i = 0 numbers = [num1, num2, num3] while i < len(numbers): m1_num = numbers[i] if numbers[i] > m1_num else m1_num i += 1 i = 0 while i < len(numbers): m2_num = numbers[i] if m1_num > numbers[i] > m2_num else m2_num i += 1 print(m1_num + m2_num) my_func(9, 7, 17)
true
d621e1e36862636796eb36c99ecbdc070b4a2328
skawad/pythonpractice
/datastructures/ex_08_05.py
1,003
4.1875
4
# Open the file mbox-short.txt and read it line by line. When you find a line # that starts with 'From ' like the following line: # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 # You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sent the message). Then print out a count at the end. # Hint: make sure NOT to include the lines that start with 'From:'. Also look at the last line of the sample output to see how to print the count. # You can download the sample data at http://www.py4e.com/code3/mbox-short.txt fname = input("enter file name: ") count = 0 try: fhand = open(fname) for line in fhand: if line.startswith("From "): temp_list = line.split() print(temp_list[1]) count = count + 1 else: continue except: print("File cannot be opened:", fname) quit() print("There were", count, "lines in the file with From as the first word")
true
cc6567dbbf51778cc3aa8ca439727d1b6b80ea07
janelstewart/myshoppinglistproject.py
/shopping_list_project.py
2,044
4.25
4
my_shopping_lists_by_list_name = {} def add_list(list_name): #check if list name exists in dictionary #if doesnt exist add list to dictionary if list_name not in my_shopping_lists_by_list_name: my_shopping_lists_by_list_name[list_name] = [] def add_item_to_list(list_name,item): #use list name to retrieve list #check if item doesnt exists, list_name = list_name.lower() if list_name in my_shopping_lists_by_list_name: shopping_list = my_shopping_lists_by_list_name[list_name] if item in shopping_list: print "This %s is already in this list." % (item) else: shopping_list.append(item) shopping_list.sort() print shopping_list else: print "This %s does not exist." % (list_name) #add item to list #if item does exists already then tell user its already there #print out current list after item added using list_sorter function def remove_item_from_list(list_name,item): #check if item exists in list list_name = list_name.lower(): if list_name in my_shopping_lists_by_list_name: shopping_list = my_shopping_lists_by_list_name[list_name] if item not in shopping_list: print "This %s does not exist." % (item) else: shopping_list.remove(item) shopping_list.sort() print shopping_list else: print "This %s does not exist." % (item) #if yes, remove item #if it doesnt exist tell user it doesnt exist #print out current list after removing item use list_sorter function def remove_list(list_name): if list_name in my_shopping_lists_by_list_name: #check if list name is in dictionary #if yes, remove list #if not, tell user list does not exist #def list_sorter(list_name): #NOT NEEDED IF SORTING LIST THROUGHOUT FUNCTIONS #get list from dictionary #sort list using .sort() and return sorted list def menu_option(): #returns menu option def all_list(): #need dictionary with key:value pairs #print def main(): #ask for input #use menu function to get choice then based on choice #you will decide which function to use if __name__ == '__main__': main()
true
e4b882493feb4792ecd3b72b781edb0856b5ffb5
Suhyun-2012/Suhyun-2012.github.io
/Works/CYO.py
893
4.28125
4
answer1 = input("Should I go walk on the beach or go inside or go to the city?") if answer1 == "beach": if input("Should I go swimming or make a sandcastle?") == "sandcastle": print("Wow, my sandcastle is very tall!") #elif input(print("Should I go swimming or make a sandcastle?")) == "jiooswimming": else: print("Shark!") elif answer1 == "inside" elif input("Should I go walk on the beach or go inside or go to the city?") == "inside": if input("Should I go sleep or make lunch?") == "sleep": print("I think I am going to take a nap.") else: print("I think I am going to cut carrots.") print("Aah! I cut myself!") else: if answer1 == "court": print("Lets make a jury") else: print ("This is boring") #elif input(print("Should I go walk on the beach or go inside?")) == "inside":
true
19c38fbcff05936e5b981613229378b6569c890f
williamdarkocode/AlgortithmsAndDataStructures
/threeway_set_disjoint.py
1,243
4.125
4
# given 3 sequences of numbers, A, B, C, determine if their intersection is empty. Namely, there does not exist an element x such that # x is in A, B, and C # Assume no individual sequence contains duplicates import numpy as np def return_smallest_to_largest(A,B,C): list_of_lists = [A,B,C] len_list = [len(A), len(B), len(C)] fin_list = [0]*3 for i in range(len(len_list)): idx = np.argmin(len_list) fin_list[i] = list_of_lists[idx] len_list = len_list[0:idx] + len_list[idx+1:] list_of_lists = list_of_lists[0:idx] + list_of_lists[idx+1:] return fin_list def set_disjoint1(A,B,C): smtlrg = return_smallest_to_largest(A,B,C) for a in smtlrg[0]: for b in smtlrg[1]: if a == b: # we only check an intersection with c if a, and b intersect for c in smtlrg[2]: if a == c: return [False, a] return [True, ''] def main(): A = input('Enter sequence A: ') B = input('Enter sequence B: ') C = input('Enter sequence C: ') A = A.split(',') B = B.split(',') C = C.split(',') resp = set_disjoint1(A, B, C) print(resp) if __name__ == '__main__': main()
true
11a37184c06031fb300cc01555acc86b5fc7620e
milesmackenzie/dataquest
/step_1/python_intro_beginner/intro_functions/movie_metadata_exercise3.py
785
4.375
4
# Write a function index_equals_str() that takes in three arguments: a list, an index and a string, and checks whether that index of the list is equal to that string. # Call the function with a different order of the inputs, using named arguments. # Call the function on wonder_woman to check whether or not it is a movie in color, store it in wonder_woman_in_color, and print the value. wonder_woman = ['Wonder Woman','Patty Jenkins','Color',141,'Gal Gadot','English','USA',2017] def is_usa(input_lst): if input_lst[6] == "USA": return True else: return False def index_equals_str(lst, idx, string): if lst[idx] == string: return True else: return False wonder_woman_in_color = index_equals_str(wonder_woman,2,"Color") print (wonder_woman_in_color)
true
144387536b64e9518bb04d72279f8bcd28cd4e77
sivabuddi/Python_Assign
/python_deep_learning_icp1/stringreplacement.py
1,355
4.21875
4
# Replace Class in Python class Replace: def replace(self,input_string,original_word, replacement_word): output_string = "" temp_string = "" temp_counter = -1 init = 0 for char in input_string: # check if its starting with Original word for replacing if temp_counter < 0 and char == original_word[init]: temp_counter = init temp_counter += 1 temp_string += char # its matching and still going. elif 0 < temp_counter < len(original_word) and char == original_word[temp_counter]: temp_counter += 1 temp_string += char # Matching Complete if temp_string == original_word: temp_counter = -1 temp_string = "" output_string += replacement_word # Partially matched, but not entirely, so don't replace use the temp string formed so far. elif 0 < temp_counter < len(original_word) and char != original_word[temp_counter]: temp_string += char output_string += temp_string temp_counter = -1 temp_string = "" elif temp_counter == -1: output_string += char return output_string
true
624fece2eb26804725675757255cafe640ad30a5
islamuzkg/tip-calculator-start
/main.py
1,332
4.15625
4
#If the bill was $150.00, split between 5 people, with 12% tip. #Each person should pay (150.00 / 5) * 1.12 = 33.6 #Format the result to 2 decimal places = 33.60 #Tip: There are 2 ways to round a number. You might have to do some Googling to solve this.💪 #HINT 1: https://www.google.com/search?q=how+to+round+number+to+2+decimal+places+python&oq=how+to+round+number+to+2+decimal #HINT 2: https://www.kite.com/python/answers/how-to-limit-a-float-to-two-decimal-places-in-python print("Welcome to the tip calculator") bill = input("What was the total bill! ") bill_as_float = float(bill) current_bill = (f"Your current bill is {bill_as_float}") print(current_bill) tip = input("What percentage tip would you like to leave? 10, 12 or 15? ") tip_as_int = int(tip) tip_percent = tip_as_int / 100 how_many_people = int(input("How many people to split the bill?")) total_tip_amount = bill_as_float * tip_percent total_bill = total_tip_amount + bill_as_float total_bill_as_rounded = round(total_bill, 2) each_person = bill_as_float / how_many_people * (1 + tip_percent) print(tip_percent) each_person_as_rounded = "{:.2f}".format(each_person) message = f" Total bill is {total_bill_as_rounded}, you are giving {tip_as_int} percent tips, between {how_many_people} people each person will pay {each_person_as_rounded}" print(message)
true
ab4dc1572c3040ffb05287f4779bb16b41b0fa65
Magical-Man/Python
/Learning Python/allcmd.py
990
4.34375
4
assert 2 + 2 == 4, "Huston, we have a probelm" #If the above was == 5, there would be an error. for n in range(2, 10): for x in range(2, n): if n % x == 0: print(n, 'equals', x, '*', n//x) break else: #loop fell through without finding a factor print(n, 'is a prime number') #Basically what break does is loop us back to the top of a loop. #Here is an example of classes class Dog: tricks = [] def __init__ (self, name): self.name = name def add_tricks(self, trick): self.tricks.append(trick) '''This is a class, it says that the variable in the class, or the object, is this list. By using __init__ it is a bit like argv and lets you add arguments to your functions. Then by using the .\'s we are able to call the functions. ''' #The thing that the continue statement does is just says to go back to the start of the loop and keep looping. ##Also remember that you have a quizlet to STUDY!!!!
true