blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
eee3e14ebd6c8df03effc41e02b8abb0784b5f05
musflood/code-katas
/direction-reduction/dir_reduct.py
1,666
4.25
4
"""Kata: Directions Reduction. #1 Best Practices Solution by Unnamed and others opposite = {'NORTH': 'SOUTH', 'EAST': 'WEST', 'SOUTH': 'NORTH', 'WEST': 'EAST'} def dir_reduct(plan): new_plan = [] for d in plan: if new_plan and new_plan[-1] == opposite[d]: new_plan.pop() else: new_plan.append(d) return new_plan """ def dir_reduct(arr): """Collapse a set of directions to minimize movements. Given a list of string directions 'NORTH', 'SOUTH', 'EAST', 'WEST', removes directions that will cancel each other out. That is, the pairs ['NORTH', 'SOUTH'] or ['EAST', 'WEST'] cancel each other and therefore are removed from the directions. Pairs must be adjacent to cancel each other out. """ if not arr or len(arr) == 1: return arr direct = arr[:] new_direct = ['start'] while len(new_direct) != len(direct): if new_direct != ['start']: direct = new_direct[:] new_direct = [] i = 0 while i < len(direct) - 1: if direct[i] == 'NORTH' and direct[i + 1] != 'SOUTH': new_direct.append(direct[i]) elif direct[i] == 'SOUTH' and direct[i + 1] != 'NORTH': new_direct.append(direct[i]) elif direct[i] == 'EAST' and direct[i + 1] != 'WEST': new_direct.append(direct[i]) elif direct[i] == 'WEST' and direct[i + 1] != 'EAST': new_direct.append(direct[i]) else: i += 1 i += 1 if i == len(direct) - 1: new_direct.append(direct[-1]) return new_direct
true
ebb7e4b3143c89f27a322cd6adaf718a37115d7c
musflood/code-katas
/string-pyramid/string_pyramid.py
2,807
4.25
4
"""Kata: String Pyramid. #1 Best Practices Solution by zebulan def watch_pyramid_from_the_side(characters): if not characters: return characters width = 2 * len(characters) - 1 output = '{{:^{}}}'.format(width).format return '\n'.join(output(char * dex) for char, dex in zip(reversed(characters), xrange(1, width + 1, 2))) def watch_pyramid_from_above(characters): if not characters: return characters width = 2 * len(characters) - 1 dex = width - 1 result = [] for a in xrange(width): row = [] for b in xrange(width): minimum, maximum = sorted((a, b)) row.append(characters[min(abs(dex - maximum), abs(0 - minimum))]) result.append(''.join(row)) return '\n'.join(result) def count_visible_characters_of_the_pyramid(characters): if not characters: return -1 return (2 * len(characters) - 1) ** 2 def count_all_characters_of_the_pyramid(characters): if not characters: return -1 return sum(a ** 2 for a in xrange(1, 2 * len(characters), 2)) """ def watch_pyramid_from_the_side(characters): """Side view of a pyramid where each row is a char in the given string. a watch_pyramid_from_the_side('abc') => bbb ccccc """ if not characters: return characters pyramid = '' width = 1 + 2 * (len(characters) - 1) row_width = 1 for ch in characters[::-1]: pyramid += '{:^{width}}\n'.format(ch * row_width, width=width) row_width += 2 return pyramid[:-1] def watch_pyramid_from_above(characters): """Top view of a pyramid where each row is a char in the given string. ccccc cbbbc watch_pyramid_from_above('abc') => cbabc cbbbc ccccc """ if not characters: return characters pyramid = [] row_width = 1 + 2 * (len(characters) - 1) edge = '' for ch in characters: pyramid.append('{}{}{}'.format(edge, ch * row_width, edge[::-1])) edge += ch row_width -= 2 pyramid.extend(pyramid[-2::-1]) return '\n'.join(pyramid) def count_visible_characters_of_the_pyramid(characters): """Count the number of visible blocks in the pyramid.""" if not characters: return -1 return (1 + 2 * (len(characters) - 1)) ** 2 def count_all_characters_of_the_pyramid(characters): """Count the total number of blocks in the pyramid.""" if not characters: return -1 width = 1 + 2 * (len(characters) - 1) return sum(n**2 for n in range(1, width + 1, 2))
true
f3b7fb3044363da065c2e7e85fc0efeb46eaf89e
Ifeoluwakolopin/ECX-30daysofcode-2020
/code files/Ifeoluwa_Are_day23.py
897
4.34375
4
# -*- coding: utf-8 -*- """ Created on Fri Apr 17 17:14:20 2020 @author: TheAre """ def find_Armstrong(start, end): '''This function takes in two integers indicating the start and end of an interval it returns the armstrong numbers within that interval. Note: An armstrong number is a number that is equal to the sum of the cubes of it's digit Example: find_Armstrong(152, 155) :... [153] ** since, 1^3 + 5^3 + 3^3 = 153, then 153 is the armstrong number in that range ''' armstong_numbers = [] for number in range(start, end+1): number = str(number) sum_of_digits = 0 for i in number: sum_of_digits += (int(i) ** 3) if sum_of_digits == int(number): armstong_numbers.append(int(number)) return armstong_numbers print(find_Armstrong(1, 1000)) print(find_Armstrong(200,500))
true
73ecc8d7a746aa750721f0fc79e3d80ea5db1098
Ifeoluwakolopin/ECX-30daysofcode-2020
/code files/Ifeoluwa_Are_day6.py
411
4.3125
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 31 18:07:11 2020 @author: TheAre """ import itertools def power_list(list1: list): ''' Takes in a list and returns the corresponding power list of the list''' pow_list = [] for i in range(len(list1)+1): for j in itertools.combinations(list1, i): pow_list.append(list(j)) return pow_list print(power_list([1,2,3]))
true
55c3a23948c26489410b73cb44ee07a42a249c67
UchechiUcheAjike/programming_with_functions
/checkpoint_02_boxes.py
922
4.4375
4
#A manufacturing company needs a program that will help its employees # pack manufactured items into boxes for shipping. Write a Python # program named boxes.py that asks the user for two integers: 1) # the number of manufactured items and 2) the number of items that # the user will pack per box. Your program must compute and print # the number of boxes necessary to hold the items. This must be a # whole number. Note that the last box may be packed with fewer # items than the other boxes. #import the math module import math #Ask user for input, and convert it to integer num_items = int(input('Enter the number of items: ')) items_per_box = int(input('Enter the number of items per box: ')) #number of boxes num_boxes = math.ceil(num_items / items_per_box) #display results for user to see print(f'For {num_items} items, packing {items_per_box}' f' items in each box, you will need {num_boxes} boxes.' )
true
67610b84cdcde5d34e0a974c544262fb7871922a
FrenchBear/Python
/Pandas/base2.py
531
4.71875
5
# Learning Pandas # 2021-03-01 PV # https://www.learndatasci.com/tutorials/python-pandas-tutorial-complete-introduction-for-beginners/ import pandas as pd data = { 'apples': [3, 2, 0, 1, 4, 3], 'oranges': [0, 3, 7, 2, 5, 0] } # Create from scratch # Each (key, value) item in data corresponds to a column in the resulting DataFrame. # By default, the Index of this DataFrame was given to us on creation as the numbers 0-3 purchases = pd.DataFrame(data) print(purchases) pp = purchases[purchases.oranges>0] print(pp)
true
65f6092cc51de46f8dd6cabbba3594df83c11ec2
FrenchBear/Python
/Learning/107_Multiple_Constructors/a_newinit.py
680
4.375
4
# Play with Python contructors # 01 Refresher about __new__ and __init__ # # 2022-03-19 PV # A base class is object, identical to class A(object): class A: def __new__(cls): print("Creating instance of A") return super(A, cls).__new__(cls) # Should return None def __init__(self): print("A Init is called") A() print() class B: # Actually, __new__ can return anything... def __new__(cls): print("Creating instance of B") return "Hello world" # Note that __init__ is not called, since __new__ did not return a __B__ object def __init__(self): print("B Init is called") b = B() print(b)
true
c40ebfa80afc506486e4818d013a524c499f7d37
FrenchBear/Python
/Learning/013_Arrays/13_Arrays.py
1,664
4.4375
4
# Arrays # Learning Python # 2015-05-03 PV # Simple array myList = [] for i in range(10): # mylist[i]=1 # IndexError: list assignment index out of range myList.append(1) myList = [i*i for i in range(10)] # Array of squares [0, ..., 81] # Creates a list containing 5 lists initialized to 0 using a comprehension Matrix = [[0 for x in range(5)] for x in range(5)] Matrix[0][0] = 1 Matrix[4][0] = 5 print(Matrix[0][0]) # prints 1 print(Matrix[4][0]) # prints 5 # Retrieve a column as a list j = 0 col = [row[j] for row in Matrix] # Transpose a matrix t = [[row[i] for row in Matrix] for i in range(len(Matrix))] # shorter notation for initializing a list of lists: m = [[0]*5 for i in range(5)] # Unfortunately shortening this to something like 5*[5*[0]] doesn't really work because you end up with 5 copies of the same list, so when you modify one of them they all change, for example: matrix = 5*[5*[0]] print(matrix) # [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]l matrix[4][4] = 2 print(matrix) # [[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]] # With numpy import numpy as np print(np.zeros((3, 3))) # Array of doubles print(np.matrix([[1, 2], [3, 4]])) print(np.matrix('1 2; 3 4')) print(np.arange(9).reshape((3, 3))) print(np.array(range(9)).reshape((3, 3))) print(np.ndarray((3, 3))) # Real arrays, compare size with list print() import array, sys tl = [2,3,5,7,11,13,17,19,23,27] ta = array.array('i', tl) tn = np.array(tl, dtype=int) print(tl, sys.getsizeof(tl)) print(ta, sys.getsizeof(ta)) print(tn, sys.getsizeof(tn))
true
fe32573df0314ce6dc03a27a607ce75fa63ca174
Som94/Python-repo
/display no of 2nd n 4th saturday in given range of date.py
908
4.125
4
""" Given two dates d1 to d2 ( both inclusive) Print all the 2nd and 4th Saturdays Count how many are there? """ import datetime print("Enter dates input format example: 8 Feb 2021") date_start_str = '20 Feb 2010' #input("Enter start date: ") date_end_str = '12 Dec 2011' # input("Enter end date: ") # convert string to date format date_start = datetime.datetime.strptime(date_start_str, '%d %b %Y') date_end = datetime.datetime.strptime(date_end_str, '%d %b %Y') # initialization of the initial number of weekends day = datetime.timedelta(days=1) count_saturday = 0 count_sunday = 0 # iteration over all dates in the range while date_start <= date_end: if date_start.isoweekday() == 6: print(date_start.isoweekday()) print(date_start.day) count_saturday += 1 date_start += day # output a single line containing two space-separated integers print(count_saturday)
true
7ce7a8f93858d069aec1cb98d795f07c9c506a88
Som94/Python-repo
/21st july/Assignment 2.txt
506
4.25
4
''' Take several input from user as string , check wether it is palindrome or not store into a dictionary as if it is palindrome assign the value as true else assign false {'liril': True, 'abc' : False} And so on ''' def palindrome(n): for i in range(n): str1=input("Enter any String :") if str1==str1[::-1]: dic[str1]=True else: dic[str1]=False return dic n=int(input("Enter number of input you want :")) dic={} print(palindrome(n))
true
50063f065de4c19c68024ee8410f49a68456dd80
polinaya777/goit-python
/python_1/lesson_02/hw_03.py
1,089
4.34375
4
flag = True while (flag): num_1 = input('Enter number 1: ') try: num_1 = int(num_1) except ValueError: print(f"Number {num_1} is not a number") else: flag = False flag = True while (flag): num_2 = input('Enter number 2: ') try: num_2 = int(num_2) except ValueError: print(f"Number {num_2} is not a number") else: flag = False result = 0 flag = True while (flag): oper = input('Enter operand: ') if oper == '+': result = num_1 + num_2 print(f'Result is {result}') flag = False elif oper == '-': result = num_1 - num_2 print(f'Result is {result}') flag = False elif oper == '*': result = num_1 * num_2 print(f'Result is {result}') flag = False elif oper == '/': try: result = num_1 / num_2 print(f'Result is {result}') flag = False except ZeroDivisionError: print('Number 2 could not be zero') else: print('This is not an operand!')
true
45e96a7a37eb0e6c7ecf0c6779426d83266b2c00
pkoarmy/Learning-Python
/sorting/sorting.py
684
4.40625
4
# Sort in Python def sort(array): # run loops two times: one for walking through the array # and the other for comparison for i in range(len(array)): for j in range(0, len(array) - i - 1): # To sort in descending order, change > to < in this line. if array[j] > array[j + 1]: # swap if greater is at the rear position (array[j], array[j + 1]) = (array[j + 1], array[j]) data = [7, 3, 22, 11, 17, 5, 19] sort(data) print('Sorted List in Ascending Order:') print(data) # Sort in Python data = [7, 3, 22, 11, 17, 5, 19] print(data) print('Sorted List in Ascending Order:') data.sort() print(data)
true
a7bb9bd5fa9535112126b900f360f4cd1978b685
Monsteryogi/Python
/string_methods.py
308
4.4375
4
#string methods used for manuputlating the Strings word=input("Enter the string:") lenght_word=len(word) upper_case=word.upper() lower_case=word.lower() print ("Lenth of String: %s" %(lenght_word)) print ("Upper case of String: %s" %(upper_case)) print ("Lower case of String: %s" %(lower_case))
true
fc38561aab9f7a41243707c4942025990318dc08
jean957/eulerproblems
/prob12b.py
1,554
4.25
4
from math import sqrt print(''' The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors? ''') # Factorization # Make a function 'factor' that finds the first prime divisor for any given number. Store those divisors, this is the factorization. # Make a function that finds all subsets of the set of your exponents def factor(num): end = int(sqrt(num)+1) for ab in xrange(2, end): if num % ab == 0: return ab return num def factorize(triangle): factorization = [] while True: fact = factor(triangle) factorization.append(fact) triangle = triangle / factorization[-1] if triangle == 1: break return factorization def exponenticize(factors): exponents = [1] count = 1 for ab in factors: try: if ab == factors[count]: exponents[-1] += 1 else: exponents.append(1) except: break count += 1 return exponents triangle = 25 for ab in range(10, 27): triangle = ab print factorize(triangle), exponenticize(factorize(triangle))
true
dfe728d7e38f68704ff6a353776e948ce0802ce2
ew67/CSE
/notes/List Notes.py
2,489
4.46875
4
# Lists shopping_list = ["whole milk", "PC", "Eggs", "Trash (Xbox One)", "Other Trash (PS4)", "Batteries"] print(shopping_list) print(shopping_list[0]) print("The second thing in the list is %s" % shopping_list[1]) print("The length of the list is %d" % len(shopping_list)) # Changing Elements in a list shopping_list[0] = "2% milk" print(shopping_list) print(shopping_list[0]) # Looping through lists # for item in shopping_list: # print(item) # List Practice name_list = ["Monique", "Jun", "June", "Angelina", "Danny", "Braydon", "Anthony", "Brian"] name_list[2] = "James" print(name_list[2]) print(name_list) new_list = ["eggs", "cheese", "oranges", "raspberries", "banana"] new_list[2] = "apples" print("The last thing in the list is %s" % new_list[len(new_list) - 1]) print(new_list) # Getting part of a list print(new_list[1:3]) print(new_list[1:4]) # 1:4 goes up to the indices but doesn't include the last one print(new_list[1:]) # Would include everything from Index 1 to the very end. print(new_list[:2]) # This is the same thing, but it would go from the start, and only up to Index 2. # Adding things to a list holiday_list = [] # Always use Brackets for Lists holiday_list.append("Tacos") holiday_list.append("Bumblebee") holiday_list.append("Red Dead Redemption 2") print(holiday_list) # Notice this is "object.method(Parameters)" # Remove things from a lst holiday_list.remove("Tacos") print(holiday_list) # List Practice ''' 1. Make a new list with 3 items 2. Add a 4th item to the lis 3 Remove one of the first three items from the list. ''' gift_list = ["Toys","Games","Roblox $10 Gift Card"] gift_list.append("Food") gift_list.remove("Toys") print(gift_list) gift_list.pop(0) # Pop is like remove, but removes the item in the Index Number Instead print(gift_list) # Tuple brands = ("Apple", "Samsung", "HTC") # notice the parentheses colors = ["blue", "red", "green", "black", "brown", "purple", "pink", "orange", "teal", "white", "yellow", "indigo", "violet", "magenta", "gray", "cyan", "tan", "lime", "Jade", "Silver"] print(len(colors)) # Find the index print(colors.index("violet")) # Changing things into a list string1 = "Jade" list1 = list(string1) print(list1) for character in list1: if character == "u": # replace with a * current_index = list1.index(character) list1.pop(current_index) list1.insert(current_index, "*") # Changing lists into strings print("3".join(list1))
true
9740ad504a07c6140578cd5f74b7a71ec6c1de94
13jacole/Portfolio
/Project Euler/Problem 4/BruteForce.py
1,455
4.15625
4
# Brute Force Method #Largest possible product of two 3-digit numbers = 999*999 = 998001 --> largest palindrome beneath this is 997799 #Lowest possible product of two 3-digit numbers = 100*100 = 10000 --> smallest palindrome above this is 10001 ###METHODOLOGY### # 1) Starting at 997799, decrement until palindrome. # 2) Starting at 999, decrement and check multiplicands until both are 3-digit and factors. ####### #Returns True if input is palindrome def checkPalindrome(n): return str(n) == str(n)[::-1] def main(): limit = 997799 # Largest possible palindrome product of two 3-digit numbers for i in range(limit, 10000, -1): if checkPalindrome(i): for j in range(999, 99, -1): # Check all 3-digit numbers in descending order ### Since we only want 3-digit numbers: ### If i/j > 999, then one of the multiplicands would be 4 digit or more. ### Because we are checking in descending order, we should find the higher multiplicand first. So if j^2 is less than i, we have found the lesser multiplicand, and should stop checking numbers. if (i/j > 999) or (j*j < i): break if i%j == 0: mult1 = j mult2 = i/j print("Palindrome " + str(i) + " is the product of " + str(mult1) + " and " + str(mult2)) exit() main()
true
84e84f247770cd75bc88abc1f0056f5e141d6607
brn016/cogs18
/18 Projects/Project_yax048_attempt_2018-12-12-10-21-46_COGS 18 Final Project/COGS 18 Final Project/my_module/while_loop.py
1,263
4.21875
4
def while_loop_answer(): """Keep reporting error if the answer is not valid""" msg = input('INPUT :\t') # Check if user's answer is valid(Yes or No) if msg == 'No': print('Thank you and have a great day!') chat = False elif msg == 'Yes': print('Okay, give me a second...') chat = True # If answer is not valid, start a while loop else: while msg != 'Yes' or 'No': # Keep reporting error if the answer is not valid print("Sorry, I can't understand you. please call (888)888-8888") print('Anything else I can help you with? (please answer Yes or No)') msg = input('INPUT :\t') # When answer is No, break this while loop and return chat=False which will end the chatbot loop. if msg == 'No': print('Thank you and have a great day!') chat = False break # When answer is Yes, break this while loop and return chat=True which will keep the chatbot loop. elif msg == 'Yes': print('Okay, give me a second...') chat = True break return chat
true
80a093d763ff33c3f45228d0db2e4ccec1c87344
xXYeetMasterXx/Py_Assignments-1
/A23.py
240
4.15625
4
def sum_three(): print ("This finds the sum of three numbers") a = int(input("Enter your first number:")) b = int(input("Enter your second number:")) c = int(input("Enter your third number:")) return (a+b+c) print(sum_three())
true
c7ba44d412a32d4e129b52794b42a32e1b4e55ea
pallavidesai/PythonDeepLearningICP
/Source/CountSentence.py
368
4.1875
4
#accepts a sentence and prints the number of letters anddigits in Sentence. string = input("Please Enter Your String") digit=0 letter=0 for count in string: if count.isdigit(): digit=digit+1 elif count.isalpha(): letter=letter+1 else: pass print("Number of Letters in Sentence", letter) print("Number of Digits in Sentence", digit)
true
6715d0bcff9aa51db2facf3f40be8f562180070d
venuxvg/coding_stuff
/sortarray.py
213
4.40625
4
# python program to print the array elements in ascending order inp = int(input('How many elements you want to enter:')) arr = [] for i in range(inp): n = input() arr.append(int(n)) arr.sort() print(arr)
true
7961d302423591ffd311f55ba3c6e5bbcbeed4d1
jlunder00/blocks-world
/location.py
1,323
4.1875
4
''' Programmer: Jason Lunder Class: CPSC 323-01, Fall 2021 Project #4 - Block world 9/30/2021 Description: This is a class representing a location in the block world. It has a list of the blocks it contains, keeps track of which block is on top, and has the ability to place a given block on its stack and remove one from the top of its stack. ''' import block class Location: def __init__(self): self.current_blocks = [] self.top_block = None def place_block(self, block): """ Place a given block on the top of the stack at this location Parameters ---------- block : the block to place of type Block """ if self.top_block != None: self.current_blocks[-1].cover() self.top_block = block self.current_blocks.append(block) def remove_block(self): """ Remove the block on the stack at this location and return it Parameters ---------- Returns The block removed from the top of the stack """ block = self.current_blocks.pop() if len(self.current_blocks) > 0: self.current_blocks[-1].uncover() self.top_block = self.current_blocks[-1] else: self.top_block = None return block
true
c41ccd9bcf54dfd30c84f10fd2dea166a61c6903
digitalight/Python_Crash_Course
/042-classes2.py
2,770
4.53125
5
# Starting classes and OOP # Sun 19th April 2020 # Mike Glover class Car: """A simple attempt to represent a car.""" def __init__(self, make, model, year): """Initialize attributes to describe a car.""" self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_description_name(self): """Return a neatly formatted descriptive name.""" long_name = f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """Print a statement showing the car's mileage.""" print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self, mileage): """ Set the odometer reading to the given value. Reject the change if it attempts to roll the odometer back. """ if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): """Add the given amount to the odometer reading.""" self.odometer_reading += miles # Child Class class ElectricCar(Car): """Represents aspects of a car, specific to electric vehicles.""" def __init__(self, make, model, year): """Initialize attributes of the parent class.""" super().__init__(make, model, year) self.battery = Battery() # Instances as Attributes # If we see a class growing too big we can split it up to seperate class. class Battery: """A simple attempt to model a battery for an electric car.""" def __init__(self, battery_size=75): """Initialize the battery's attributes""" self.battery_size = battery_size def describe_battery(self): """Print a statement describing the battery.""" print(f"This car has a {self.battery_size}-kWh battery.") def get_range(self): """Print a statement about the range this battery provides.""" if self.battery_size == 75: range = 260 elif self.battery_size == 100: range = 314 print(f"This car can go about {range} miles on a full charge.") # Car class output my_new_car = Car('audi', 'a4', 2019) print(my_new_car.get_description_name()) my_new_car.odometer_reading = 23 my_new_car.read_odometer() used_car = Car('subaru', 'outback', 2002) print(used_car.get_description_name()) used_car.update_odometer(23_500) used_car.read_odometer() used_car.increment_odometer(100) used_car.read_odometer() # Child class output my_tesla = ElectricCar('tesla', 'model f', 2020) print(my_tesla.get_description_name()) my_tesla.battery.describe_battery() my_tesla.battery.get_range()
true
0879773c17e20ab21a9290d05e4e3ee98cb49251
digitalight/Python_Crash_Course
/031-loadsofcats.py
202
4.15625
4
pets = ['dog', 'fish', 'cat', 'cat', 'rabbit', 'cat'] print(pets) # Use while loop and not a for loop as they can't track lists or dictionaries. while 'cat' in pets: pets.remove('cat') print(pets)
true
ff8230980f768c8291ea8f3da8306dd486bf6dfd
koichi21/lintCode
/linkedList/reverse.py
1,611
4.28125
4
#!/usr/bin/python """ Reverse a linked list. """ def main(): # create a linked list a = [1,2,3] head1 = getLinkedList(a) head2 = getLinkedList(a) # check print toList(head1) # reverse test = Solution() head1 = test.reverse(head1) print toList(head1) head2 = test.reverse2(head2) print toList(head2) def getLinkedList(a): head = None for i in a[::-1]: head = ListNode(i,head) return head def toList(head): a = [] node = head while node: a.append(node.val) node = node.next return a class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next class Solution: """ @param head: The first node of the linked list. @return: You should return the head of the reversed linked list. Reverse it in-place. """ # first attempt def reverse(self, head): # write your code here if not head or not head.next: return head node = head.next head.next = None while node: tmp = node.next node.next = head head = node node = tmp return head # better def reverse2(self, head): # write your code here dummy = ListNode(0, None) while head: tmp = head.next head.next = dummy.next dummy.next = head head = tmp return dummy.next if __name__ == '__main__': main()
true
8c698e39fad48cc366ca6390012a9f3074858796
koichi21/lintCode
/binarySearch_sortedArray/mergeSortedArray.py
905
4.28125
4
#!/usr/bin/python """ Given two sorted integer arrays A and B, merge B into A as one sorted array. """ class Solution: """ @param A: sorted integer array A which has m elements, but size of A is m+n @param B: sorted integer array B which has n elements @return: void """ def mergeSortedArray(self, A, m, B, n): # write your code here i = m-1 j = n-1 # while i >= 0 and j >= 0: # if A[i] > B[j]: A[i+j+1] = A[i] i -= 1 else: A[i+j+1] = B[j] j -= 1 # A is finished if i < 0: A[:i+j+2] = B[:j+1] return A # if __name__ == "__main__": test = Solution() A = [1, 2, 3, 0, 0] B = [4, 5] print test.mergeSortedArray(A, 3, B, 2)
true
0296328b041b70f1ea09cf2e72c5ec51355ae4c2
redyelruc/BoringStuff
/asterisk printer.py
983
4.4375
4
# module to validate input import pyinputplus as pyip # Dictionary containing value for each row ascending through the digits (0-2) # ( with spaces after digits so they are not all clumped together led = {'row1' : ['### ', '# ', '### '], 'row2' : ['# # ', '# ', ' # '], 'row3' : ['# # ', '# ', '### '], 'row4' : ['# # ', '# ', '# '], 'row5' : ['### ', '# ', '### ']} # Ask for input and force user to enter a positive integer while True: num_entered = pyip.inputInt('please enter a number to digitalize?: ') if num_entered <0: print('The number cannot be negative. Try again.') continue break # Convert number entered to a list containing individual digits list_of_digits = list(str(num_entered)) # Loop through rows for row_number in range(5): # Loop to print each digit for i in list_of_digits: print(led['row' + str(row_number + 1)][int(i)], end = '') # Get a new line print()
true
757cf6122e08f1e5ca2f320d607638dd328b64ed
redyelruc/BoringStuff
/CaeserCypher.py
2,120
4.4375
4
import pyinputplus as pyip # CaeserCypher - a programme of simple encrpytion and decryption of text '''asks the user for one line of text to encrypt; asks the user for a shift value (an integer number from the range 1..25 prints out the encoded text.''' # Get the message and the code shift and validate them before progressing text = pyip.inputStr('Please enter your message: ') while True: shiftby = pyip.inputInt('Please enter a number to encode by: ') if shiftby < 0 or shiftby > 25: print('Sorry, it must be between 0 and 25.') continue break cypher = '' # go through text one character at a time for character in text: # if not an alphabetic character, disregard it. if not character.isalpha(): cypher += character continue # Treat upper and lower cases as seperate codes if character.isupper(): character = ord(character) character += shiftby # if gone past 'Z', back to start if character > 90: character -= 25 elif character.islower(): character = ord(character) character += shiftby # if gone past 'z', back to start if character > 122: character -= 25 # add character to the cypher cypher += (chr(character)) print(cypher) # check if user wants to decypher message print() decypher = pyip.inputYesNo('Do yo want to decypher the message now?') if decypher: # to decypher the code text = '' for character in cypher: if not character.isalpha(): text += character continue if character.isupper(): character = ord(character) character -= shiftby # if gone past 'Z', count back from 'z' if character < 65: character += 25 elif character.islower(): character = ord(character) character -= shiftby # if gone past 'a', count back from 'z' if character <97: character += 25 # add character to the cypher text += (chr(character)) print(text)
true
b7174c39bb28f021b0177a71b9e579ad01a37bb1
carl-parrish/codeEval
/findWriter.py2
783
4.15625
4
#!/usr/bin/python """ Find a Writer You have a set of rows with names of famous writers encoded inside. Each row is divided into 2 parts by pipe char (|). The first part has a writer's name. The second part is a "key" to generate a name. Your goal is to go through each number in the key (numbers are separated by space) left-to-right. Each number represents a position in the 1st part of a row. This way you collect a writer's name which you have to output. """ from sys import argv file_name = argv[1] file_input = open(file_name) for line in file_input.readlines(): haystack, numbers = line.split('|') writer = '' map_list = numbers.strip().split(' ') for index in map_list: index = int(index)-1 writer += haystack[index] print writer
true
c92f1554c408d57233767610ee681d65811c8596
sritasngh/programming
/HackerRank/practice_python/find_a_string.py
442
4.15625
4
##https://www.hackerrank.com/challenges/find-a-string/problem def count_substring(string, sub_string): counter=0 n=len(string)-len(sub_string) for i in range (n+1): if string.find(sub_string,i,i+len(sub_string))>=0: counter+=1 return counter if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count)
true
466f2eb29300c9e545ab454252f10743eddd53f9
parxhall/com404
/1-basics/4-repetition/3-nested-loop/1-nested/bot.py
254
4.1875
4
#input row = int(input("how many rows should i have?\n")) column = int(input("how many coulmns should i have?\n")) #for for count in range(0,row,1): for count in range(0,column,1): print(":-)", end="") print("") #finish print("Done!")
true
87dcb8b247d209eb1054917bf5cf7c9ddfcd083e
parxhall/com404
/1-basics/3-decision/03-if-elif-else/bot.py
523
4.1875
4
#ask for input paint = input("Towards which direction should I paint (up, down, left or right)?\n") #if statement if paint == "up": print("I am painting in the upward direction!\n") #else if statements elif paint == ("down"): print("I am painting in the downward direction!\n") elif paint == ("left"): print("I am painting towards the left direction!\n") elif paint == ("right"): print("I am painting towards the right direction!\n") #else statement else: print("I dont know what you are painting 0_0")
true
591f0a9cd226ff94e4feea95dec3e2768abe7b8e
AshayFernandes/PythonPrograms
/Assignment/assignment1.py
1,645
4.15625
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 5 17:56:53 2019 @author: Ashay Fernandes """ """<q> Create a list and do the following manipulation 1> Find the length of the list 2>Create a new list as an element of an existing list 3>use the slice Operator 4>Replace the second element of the list with a fruit name 5>concatenate two list 6>Find atleast two ways to copy and clone a list 7>find out atleast one way to split a list into evenly sized chunks """ #<q>list of seven wonders of the Ancient World lst1=["The Great Pyramid of Giza","Hanging Gardens of Babylon","Colossus of Rhodes","Temple of Artemis","light house of Alexandria","Statue of Zeus at Olympia","Mausoleum at Halicarnassus"] #1> print('Length of the List is :',len(lst1)) #2> lst2=[] for i in range(0,4): lst2.append(lst1[i]) print(lst2) #3> lst3=lst1[4:] print(lst3) #4> lst1[1]='PEACH' #5>seven wonders of Modern World lst4=['Taj Mahal','Christ The Redeemer','Petra','The Great Wall Of China','The Colosseum Of Rome','Machu Picchu','Chichen Itza' ] lst5=lst1 + lst4 print(lst5) #6>method 1 clst1=lst1[:] #method2 clst2=list(lst1) #method3 clst3=lst4.copy() #method5 import copy clst4=copy.copy(lst1) #7> def chuck(listx,chunksize): finalist=[] for i in range(0,len(lst1),chunksize): finalist.append(lst1[i:i+chunksize]) return finalist lst7=[] lst7=chuck(lst1,2) """<q2>write a Python Program to create a tuple with number and print one item""" tpl_number=(9,4,8,2,6,9,6,0,1,6) print(tpl_number[5]) """<q3>convert the tuple to list""" tlst=list(tpl_number)
true
57d8912687ccae9e6b73cc49b95dba48a718620d
morris-necc/assignments
/Week7/JCassignment.py
2,370
4.34375
4
from __future__ import annotations #for the :Car typing, this apparently won't be necessary in Python 3.10 class Company: def __init__(self, name: str, cars: list): """ name: prints the name of the company cars: a list of 'Car' objects that this company manufactures """ self.name = name self.car = cars class Car: def __init__(self, model:str, speed:int, tank_capacity:float, fuel_usage:float): """ model: the name/model of the car speed: average speed in km/h tank_capacity: max capacity of the gas tank in Liters fuel_usage: gas used in liters/100km """ self.model = model self.speed = speed self.tank_capacity = tank_capacity self.fuel_usage = fuel_usage def max_distance(self) -> float: """ calculates the maximum distance the car can run in km """ return (self.tank_capacity / self.fuel_usage) * 100 def max_duration(self) -> float: """ calculates how many minutes the car can go """ return (self.max_distance() / self.speed) * 60 def is_better_than(self, other_car: Car) -> str: """ compares if this car is better than another """ if self.max_distance() > other_car.max_distance() and self.max_duration() > other_car.max_duration(): return "yes" elif self.max_distance() > other_car.max_distance() or self.max_duration() > other_car.max_duration(): return "maybe" else: return "no" def compare_cars(self, other_company: Company) -> None: """ compares this car with every car in that company""" count = 0 for car in other_company.car: if self.is_better_than(car) == "yes": count += 1 print(f"Our car, {self.model} is better than {count} out of {len(other_company.car)} in their company") car1 = Car("Model S", 50, 37, 8.5) car2 = Car("Model 3", 45, 40, 10.2) car3 = Car("Model X", 55, 46, 7.9) car4 = Car("Rock", 50, 45, 9.4) company1 = Company("Tebsla", [car1, car2, car3]) print(car4.is_better_than(car1)) # Prints "yes" print(car2.is_better_than(car3)) # Prints "no" print(car1.is_better_than(car2)) # Prints "maybe" print(car4.compare_cars(company1)) # Prints "Our car, Rock is better than 2 out of 3 of all the cars in their company."
true
5dbd45475c7408103adef7870d7f840525d4ecd8
MilapPrajapati70/AkashTechnolabs-Internship
/day 4/task 1 (4).py
593
4.28125
4
# 1. Create a class cal1 that will calculate sum of three numbers. # Create setdata() method which has three parameters that contain numbers. # Create display() method that will calculate sum and display sum. class myclass: def setdata(self,n1,n2,n3): self.n1=n1 self.n2=n2 self.n3=n3 def display(self): print(" ans is :" ,n1+n2+n3) n1=int(input("entervalue of n1 :")) n2=int(input("enter value of n2 :")) n3= int(input("enter value of n3 :")) myc = myclass() myc.setdata() myc.display()
true
ca594a7d1aecdcfe3f0abd307879e51a760c4f6e
Aniketthani/Python-Tkinter-Tutorial-With-Begginer-Level-Projects
/3grid.py
244
4.3125
4
from tkinter import * root=Tk() #Creating a Label Widget mylabel1=Label(root,text="Hello World") mylabel2=Label(root,text="Hi This is Tkinter") #showing it on screen mylabel1.grid(row=0,column=0) mylabel2.grid(row=3,column=3) root.mainloop()
true
e13507bd91d0478fa5170214daef004e7d567d2c
GarethAn/LeetCode
/No575_Distribute Candies/Python_Solution.py
1,340
4.1875
4
# -*- coding: utf-8 -*- # Renyi Hou. 23/6/2017 题目: Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain. 解题思路: For given input list -- lst, len(set(lst) represents the different type of element(不同的元素) len(candies) represents the number of element case 1: 设想,lst包括了26个elements, 其中有10种kind,那么return result should be 10 因为sister could gain the 13 elements, 这13个元素中就可以包括10种kind element case 2: 设想,lst包括了26个elements, 其中有15种kind,那么return result should be 13 因为sister could gain the 13 elements, 这13个元素中就可以包括10种kind element 所以说,result与kind and number of element有关 解答: class Solution: def distributeCandies(self, candies): """ :type candies: List[int] :rtype: int """ return min(len(set(candies)), int(len(candies)/2))
true
76813266c3c4b73bd2f167b312a0c46bd7f11a28
omaskery/yellow-lama
/material/conceptual/exercises/comparison.py
1,275
4.1875
4
#!/usr/bin/python import unittest # # This example involves writing a simple 'comparison' function # # The input will be two integers, a and b # If a is greater than b, the output should be "greater" # If a is less than b, the output should be "lesser" # If a is equal to b, the output should be "equal" # def compare(num_a, num_b): output = "" # your own code here return output class CompareTestCase(unittest.TestCase): def test_lesser(self): a = 10 b = 100 c = compare(a, b) self.assertEqual(c, "lesser", "expected this comparison to say 'lesser'") def test_greater(self): a = 42 b = 10 c = compare(a, b) self.assertEqual(c, "greater", "expected this comparison to say 'greater'") def test_equal(self): a = 30 b = 30 c = compare(a, b) self.assertEqual(c, "equal", "expected this comparison to say 'equal'") def suite(): suite = unittest.TestSuite() suite.addTest(CompareTestCase('test_lesser')) suite.addTest(CompareTestCase('test_greater')) suite.addTest(CompareTestCase('test_equal')) return suite if __name__ == "__main__": unittest.TextTestRunner(verbosity=2).run(suite())
true
3d52ecf60924f61ebc963ca04aa462b8345e8c9e
YellowDust/Projects
/Solutions/prime_factor.py
609
4.3125
4
"""Prime Factorization - Have the user enter a number and find all Prime Factors (if there are any) and display them.""" #Check if the number is prime. def is_prime(n): if n % 2 == 0: return False for i in range(3, int(n**0.5) + 1, 2): if n % i == 0: return False return True input = int(raw_input("Enter a number >> ")) factors = [1] #Two is always prime, so treat it on the side. if input % 2 == 0: factors.append(2) #Check numbers from 3 and check if it's a interger. for x in range(3, int(input / 2) + 1): if input % x == 0: if is_prime(x) == True: factors.append(x) print factors
true
113783d42b3836722d6d49d4ea7be02140abf0a4
fengxia41103/myblog
/content/downloads/euler/p4.py
762
4.25
4
# -*- coding: utf-8 -*- """A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ import itertools def is_palindromic(n): """Test n to be palindromic number. The easiest way, I think, is to convert "n" to string and test its reverse == itself. """ string_version = str(n) return ''.join(reversed(string_version)) == string_version def main(): matrix = set(itertools.imap( lambda (x, y): x * y, itertools.combinations(range(100, 999), 2))) results = filter(lambda x: is_palindromic(x), matrix) print max(results) if __name__ == '__main__': main()
true
881657859f1ba39f3ead2a37ff25d54ccf6792ef
DarrenVictoriano/Python-Mastery
/Data_Structures/Singly_LinkedList/simple_singly_list.py
1,429
4.25
4
""" This is a simple singly linked list implementation from the book Elements of Programming Interview in Python. """ class ListNode: """ simple singly list self.data = data self.next = ListNode() """ def __init__(self, data=0, next_node=None): self.data = data self.next = next_node def make_node(self, data: int) -> 'ListNode': """ make new node out of data""" return ListNode(data) def search_list(self, list_node: 'ListNode', key: int) -> 'ListNode': """ list_node - ListNode key - Item to search for """ while list_node and list_node.data != key: list_node = list_node.next # if key was not present in the list, L will have become null return list_node def insert(self, data): new_node = self.make_node(data) new_node.next = self.next self.next = new_node def insert_after(self, node: 'ListNode', new_node: 'ListNode') -> None: """ insert new node after a node node = node in the list new_node = new node to insert """ new_node = self.make_node(new_node) new_node.next = node.next node.next = new_node def delete_after(self, node: 'ListNode') -> None: """ delete the node past this one assume node is not a tail """ node.next = node.next.next
true
fc859aa037ccb3206f4ced07d6397179899a68eb
sangeetameena580/Algo-DS
/Python/Misc/reverse_integer.py
822
4.3125
4
# Python Program to Reverse a Number using Functions def Reverse_Integer(num): rev = 0 sign = 1 if num < 0: num = -num sign = -1 while(num > 0): rem = num %10 rev = (rev *10) + rem num = num //10 return rev*sign num = int(input("Please Enter any Number: ")) rev = Reverse_Integer(num) print("\n Reverse of entered number is = %d" %rev) #An example to demonstrate above mentioned apporach: # num = 123 # First iteration: # rem = 3 (123%10 = 3) # rev = 3 (0*10 + 3 = 3) # num = 12 (123/10 = 12) #Second interation: # rem = 2 (12%10 = 2) # rev = 32 (3*10+2 = 32) # num = 1 (12/10 = 1) #Third interation: # rem = 1 (1%10 = 1) # rev = 321 (32*10+1 = 321) # num = 0 (1/10 = 0) # end of while loop (since num=0) # hence Reverse of 123 is 321
true
b4d65cdefd0cf5eabd1a7446bcab010029a97227
kaistreet/python-text-manipulation
/palindrome_checker.py
784
4.53125
5
""" This script checks if a string is a palindrome. Author: Kai Street Date: 22 September 2019 """ def reverse(palindrome_checker): """ This function reverses a string and returns reversed string Author: Kai Street Date: 22 September 2019 Parameter palindrome_checker: a string to reverse Precondition: palindrome_checker must be string type """ palindrome_checker = palindrome_checker[::-1] return palindrome_checker #Asks user for a word palindrome_checker = input('Enter a word: ') assert type(palindrome_checker) == str,repr(palindrome_checker)+' is not string type.' #Checks user input to see if it's a palindrome and tells user whether it is if palindrome_checker == reverse(palindrome_checker): print('this is a palindrome') else: print("this isn't a palindrome")
true
2a9655b037f4221066dc559bb2258e53f82deaf6
lfamarantine/Baruch-CIS-2300
/assignments/homework_4.py
2,436
4.34375
4
""" Write a program that asks the user to enter the number of hours they worked for in a given week. Number of hours entered should be in the range of 0 to 60. Also ask user to enter their pay rate. It should be a positive value above minimum wage (Assume minimum wage of $15). Your program should ask user to re-enter the values for hours and wages until valid inputs are given. Based on the hours entered calculate their wages as follows: 40 hours or less: regular pay between 40 and 50: regular pay for first 40 + 1.5*regular pay for extra hours above 40 between 50 and 60: regular pay for first 40 + 1.5*regular pay for next 10 hours + 2*regular pay for extra hours above 50 """ # TESTS: # hours | rate | expected # ------|-------|--------- # 0 | 15 | 0 # 40 | 15 | 600 # 50 | 15 | 825 # 60 | 15 | 1125 hours = None # do{ # hours = input() # }while(hours < 0 || hours > 60) # unfortunately Python doesn't have a do while equivalent while True: hours = float(input("Enter hours worked: ")) if 0 <= hours <= 60: # break from loop if hours are within range 0-60 break print("Hours worked must be from 0-60") pay_rate = None while True: pay_rate = float(input("Enter pay rate: $")) if pay_rate >= 15: # break from loop if pay rate is $15 or above break print("Pay rate must be at least $15") # calculate base rate as hours * rate (max 40 hours) pay = pay_rate * min(hours, 40) # calculate 1.5x overtime as hours * rate (min 0 hours max 10 hours past 40) pay += pay_rate * 1.5 * max(min(hours-40, 10), 0) # calculate 2x overtime as hours * rate (min 0 hours past 50) pay += pay_rate * 2.0 * max(hours-50, 0) print("Pay: $", pay, sep='') # are the other parts also part of the HW? ↓ ''' """ Complete the code on lines 4 and 6 so that it prints the number 6. """ x = 3 i = 0 while i < 3: x = x + 1 # technically x = 6 would be correct because x is now 6 i = i + 1 print(x) # technically you could just print 6 and it would be correct """ The following program segment should result in an infinite loop. But the lines have been mixed up and include extra lines of code that aren't needed in the solution. """ first = 7 second = 5 third = 9 while (first > second): print ("This is an infinite loop") # indent this line and remove below to make an infinite loop # while (first > third): # print ("I wonder which while loop I am in?") '''
true
606347a6cd7bb473379ed8e400c51c7c9eebdf4a
AndrewMatos/Random-Python-code
/car_class.py
1,389
4.3125
4
class Car: """A simple attempt to represent a car.""" def __init__(self, maker, model, year): """ Initialize attributes that describe a car """ self.maker= maker self.model= model self.year= year self.odometer_reading = 0 def get_descriptive_name(self): """ return a neatly formate descriptive name. """ long_name = f"{self.year} {self.maker} {self.model}" return long_name.title() def read_odometer(self): """Print a statment showing the car's mileage """ print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self, mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("you can't roll back an odometer!") my_new_car = Car("audi", "a4", 2019) print(my_new_car.get_descriptive_name()) class Battery: """A simple attempt to model a battery for an electric car """ def __init__(self, battery_size = 75): """Initialize the battery attributes """ self.battery_size = battery_size def describe_battery(self): """ Print a statemenet describing the battery size. """ print(f"This cars has a {self.battery_size}-kwh battery") class ElectricCar(Car): """ Represent aspects of a car, specific to electric vehicles. """ def __init__(self, maker, model, year): """ Initialize attributes of the parent class""" super().__init__(maker, model, year) self.battery = Battery()
true
f713cd35248786f079e472e1c8115b363ed27a20
RohanPatil1/Programming_Problems_Solutions
/Basic Recursion/x_to_the_power_ n.py
238
4.1875
4
""" Write a program to find x to the power n (i.e. x^n). Take x and n from the user. You need to return the answer. Do this recursively. """ def power(x,n): if (n==1): return 1 return x*power(x,n-1) print power(2,5)
true
ffc466ff535b629ec05cf28615818378d0a9e8fb
BilalAhmedim/learn-python
/list/list_and_method.py
793
4.21875
4
# Declare Empty List list = ['0','1', '35', '449', '0'] # insert Method list.insert(0,'2') # insert 2 at location of 0 in the list # Modify list list[0] = '1' # insert item using append method at the last of the list # apppend metho use to add item at end of the list list.append('2') # delete item using pop poped = list.pop() print('poped item: '+ str(poped)) # delete item using del keyword del list[0] # delete element using remoev method list.remove('1') # in this method you need to know the element to delete not the location # sorting temporary print(sorted(list)) # this metho is temporary sort list # sorting permanent list.sort() # final out put with length of list print('Final Output: '+ str(list) +'\nlist length is: ' + str(len(list)))
true
9db683d8b067434b88efd33b4bffcc4dda485d6e
JasonPBurke/Intro-to-Python-class
/Lab_7/Jason_Burke_Lab7b.py
1,929
4.375
4
# This program allows you to input and save student # names to a file #set a constant for the number of students student_no = 12 def main(): #create an empty list students = [] #create an accumulator and prime the while loop count = 0 #get the user to add students to the list if they want to while count < student_no: print('Please enter a student name:') stu_name = str(input()) #append the students list students.append(stu_name) #iterate the accumulator count += 1 #run the edit_list module and pass in the #students as an arguement edit_list(students) # Open a file to write to outfile = open('names.txt', 'w') #write the list to file for name in students: outfile.write(name + '\n') #close the file outfile.close() #call the read_list function print('Here is a list of the contents of the names.txt file:') read_list() #define the read list function def read_list(): infile = open('names.txt', 'r') #read the contents of names.txt to a list names_list = infile.readlines() # Close the file infile.close() #strip the \n from each element index = 0 while index < len(names_list): names_list[index] = names_list[index].rstrip('\n') index += 1 #print the contents print(names_list) #convert list to tuple names_tuple = tuple(names_list) #print (names_tuple) # Define the edit_list function to sort, reverse, append and insert # data to the file. def edit_list(stu_list): #sort the list alphabetical and then again in reverse order stu_list.sort() stu_list.reverse() # Append the list with the teachers name and insert # my name at the beginnig of the list stu_list.append('Polanco') stu_list.insert(0, 'Burke') return stu_list main()
true
4480a541fb8e77509eb16de5983cda2b8a17bb6d
JasonPBurke/Intro-to-Python-class
/Lab_8/Jason_Burke_Lab8b.py
2,217
4.6875
5
# This program will allow a user to enter a date in # numeric format. It will test the month, day, and # year and have the user correct if errors are found. # It will then output the date in long date format. # Import the calander module to assist with renaming # months entered by the user. import calendar def main(): # Call the dates_list function to get date element values. m, d, y = dates_list() # Use the numerical month and assign it a month name. month = calendar.month_name[m] # Return to user the date entered in long date format. print('The date you entered is ', month, ' ', d, ', ', '20', y, '.', sep='') # Create a function to split the date and rename the # list elements. def dates_list(): # Get a date from the user in numeric format. user_date = input('Please enter a date in mm/dd/yy format: ') # Split up the day, month, and year from user_date into a list. date_list = user_date.split('/') # Rename the list elements. m = int(date_list[0]) d = int(date_list[1]) y = int(date_list[2]) m, d, y = date_validation(m,d,y) return (m, d, y) # Create a function to print error messages. def date_error(): print('Error. That is an invalid date.') print('Make sure the year is 2013 and entered' ' using only 2 digits.') # This module will verify if the date is a valid date. def date_validation(m,d,y): # Check to make sure the date entered is a valid date. while m < 1 or m > 12 or d < 1 or d > 31 or y != 13: # Call date_error function to display error message. date_error() # Call the dates_list function to get new date values. m, d, y = dates_list() if m == 4 or m == 6 or m == 9 or m == 11: if d > 30: # Call date_error function to display error message. date_error() m, d, y = dates_list() if m == 2: if d > 28: # Call date_error function to display error message. date_error() m, d, y = dates_list() # Returnm the values. return (m, d, y) main()
true
43f62555fd78c01351a434309368a3a6121509a4
sindredl/temp
/temp/mystuff/33-sim.py
769
4.1875
4
# -*- coding: utf-8 -*- numbers = [] def looping(number, increment): i = 0 while i < number: print "At the top i is %d" % i numbers.append(i) i = i + increment print "Numbers now: ", numbers print "At the bottom i is %d" % i def looping_for(number, increment): for i in range(0,number): print "At the top i is %d" % i numbers.append(i) print "Numbers now: ", numbers print "At the bottom i is %d" % i looping_for(22,5) print "the numbers: " for num in numbers: print num
true
671d3ba572e8b16bb873239f61c61f556171342f
Ilya-Merkulov/ProjectEuler
/problem_1.py
647
4.28125
4
""" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ # my first result def multiples(a, b): sum = 0 for i in range(1, 1000): if i % a == 0 or i % b == 0: sum += i return sum print(multiples(3, 5)) # more general result def divisible_by_under(limit, divs): return (i for i in range(limit) if any(i % div == 0 for div in divs)) print(sum(divisible_by_under(1000, (3, 5)))) # list comprehension print(sum([i for i in range(1, 1000) if i % 3 == 0 or i % 5 == 0]))
true
cfc3af19e0fcb8f3da09e352057c238ee26d48bc
jc451073/workshops
/Prac02/ASCII.py
241
4.15625
4
lower = 10 upper = 100 print("Enter a number (" + str(lower) + "-" + str(upper) + "):") str = "Enter a number {} - {}:".format(lower, upper) print(str) for i in range(lower, upper): print("ASCII code for {} char is {}".format(i, chr(i)))
true
24e0e3d6cc783635f5b265966406441feec11d15
kburchfiel/cdfcurve
/cdfplot.py
1,674
4.1875
4
#Program for plotting both the normal distribution and its corresponding cumulative density function #Helpful references included: #http://home.ustc.edu.cn/~lipai/auto_examples/plot_exp.html #https://courses.csail.mit.edu/6.867/wiki/images/3/3f/Plot-python.pdf #https://matplotlib.org/tutorials/introductory/pyplot.html #https://stackoverflow.com/questions/28504737/how-can-i-plot-a-single-point-in-matplot-python/44420447 #https://stackoverflow.com/questions/20130227/matplotlib-connect-scatterplot-points-with-line-python import matplotlib.pyplot as plt import numpy as np from statistics import NormalDist xset = np.arange(-3.5,3.5,0.01) b = 0 #b = mean c = 1 #c = standard deviation zscores = [] percentiles = [] #As a newcomer to Python, I am not aware of a way to plot the cumulative density function of the normal distribution as a continuous line. Instead, I will generate 751 points along this line (representing z scores of -3.5 to 3.5), add them to two lists, and then plot the lists as a line graph. for i in range (-350,351,1): #We will divide i by 100 so that it can represent z scores in .01 increments from -3.5 to 3.5 zscore = i/100 percentile = NormalDist(mu=b, sigma=c).cdf(zscore) print(f"A z score of {zscore} corresponds to a percentile of {percentile}.") #This prints out each z score-percentile pair, but can be commented out if desired. zscores.append(zscore) #Building our list of zscores percentiles.append(percentile) #Building our corresponding list of percentiles plt.plot(zscores,percentiles) yset2 = (1/(c*(2*np.pi)**(1/2)))*np.exp(-1/2*((xset-b)/c)**2) #Normal distribution function plt.plot(xset,yset2) plt.show()
true
246b8c45ddb3440c4ca86e91939a391aaa41bf47
WhosGotFrost/ATOM_DEV
/python/calulator.py
687
4.4375
4
#A simple calulator #try catch will catch an error if number or number2 is not a number try: number = int(input('Enter first number: ')); number2 = int(input('Enter second number: ')); operator = input("Enter a operator: "); #checks if the users added a valid operator. if(operator == "+"): print("Your answer: ", number + number2); elif(operator == "-"): print("Your answer: ", number - number2); elif(operator == "/"): print("Your answer: ", number / number2); elif(operator == '*'): print("Your answer:", number * number2); else: print("Not a Valid Operator!") except: print('This is not a Valid Number!')
true
8fa937db9b2277aadfa63d09681d282c28022248
bryandngo/PFB2017_problemsets
/elifpython.py
365
4.15625
4
#!/usr/bin/env python3 count = 20 if count < 0: message = "is less than 0" print(count, message) elif count < 20: message = "is less than 20" print(count, message) elif count > 20: message = "is greater than 20" print(count, message) elif count != 20: message = "NOT TRUE" print(count, message) else: message = "TRUE" print(count, message)
true
6b78dd87374d09e7f8639111d2581ee826f81582
Evilzlegend/Structured-Programming-Logic
/Chapter 07 - File Handling and Applications/Coding Snippets/Python/Reading Text with the read Method.py
1,417
4.6875
5
# TOPIC SUMMARY: # Once a file is opened for reading, we can get all the text from it in one # step using the file object's "read" method. This method reads the whole # file in one step. Once the text is read from a file, it is just a long string, # and Python's string manipulation tools may be applied to it. # TOPIC EXPLANATION: # Note that when a file is opened, the file object keeps track of a cursor in # the file. The cursor is the location in the text that the program has read # to. Reading from the file advances the cursor. The "read" method moves # the cursor all the way to the file's end. Reading at the end of the file # returns an empty string. # PLAYING WITH CODING SNIPPETS: # 1. Hit the Run button to see the output in the snippet box. # 2. Play around with the snippet code - change variable names, parameters, etc. # 3. Hit the Run button again to see what works and what does not work after you manipulate the code. # 4. Run the correct code again to compare it to the manipulated code. # 5. Have fun practicing this snippet as many times as you like - htere are no limits! frankenFile = open("Frankenstein.txt", "r") frankText = frankenFile.read() nothingLeftText = frankeFile.read() print(len(frankText), "characters in the text") if nothingLeftText == "": print("Once have read all text, nothing more to read!") frankenFile.close() # close the file when done
true
a24f595dbf3e0afdcae9891cad266e7747116ed7
Evilzlegend/Structured-Programming-Logic
/Chapter 07 - File Handling and Applications/Instructor Demos/read_emp_records.py
833
4.15625
4
# This program displays the records that are # in the employees.txt file. # Open the employees.txt file. empFile = open("employees.txt", 'r') # Read the first line from the file, which is # the name field of the first record. name = empFile.readline() # If a field was read, continue processing. while name != '': # Read the ID number field. idNum = empFile.readline() # Read the department field. dept = empFile.readline() # Strip the newlines from the fields. name = name.rstrip("\n") idNum = idNum.rstrip("\n") dept = dept.rstrip("\n") # Display the record. print("Name:", name) print("ID:", idNum) print("Dept:", dept) print() # Read the name field of the next record. name = empFile.readline() # Close the file. empFile.close()
true
deb9147894d3e9e261076ed1d30e973e0d7f5de7
Evilzlegend/Structured-Programming-Logic
/Chapter 02 - Elements of High Quality Programs/Coding Snippets/Python Codes/Strings in Python.py
1,526
4.5
4
# Topic Summary: # A string is a piece of text that is data in a program. In Python, # you can use single quotes or double quotes to mark the boundaries # of a string, so long as you use the same symbol at start and end: # 'a simple string', "another string" # TOPIC EXPLANATION: # Inside a string you can put any text you can type on the keyboard. If the string was written with double- # quotes, then you may use a single-quote inside the string: "I'm a big fan". Similarily, strings bounded # with single-quotes may include double-quotes within them: 'He said, "Drat!"'. What if you wanted # to include both single and double-quotes inside a string? Then you would use the special character \ # to indicate that the quote that follows is not the end of the string: 'I\'ve never said "Rudolph!"'. # Other usefule special codes include \n to indicate a newline and \\ to indicate that you want the # backlash in the string. # PLAY WITH CODING SNIPPETS: # 1. Hit the Run button to see the output in the snippet box. # 2. Play around with the snippet code - change variable names, parameters, etc. # 3. Hit the Run button against to see what works and what does not work after # you manipulate the code. # 4. Run the correct code again to compare it to the manipulated code. # 5. Have fun practicing this snippet as many times as you like - there are no limits! s1 = "Green eggs and ham" s2 = 'Sam-I-am' s3 = 'I like the backslash (\\) character!' s4 = "I do not like them\n Sam-I-am!" print(s4)
true
1dcdfba0c9fea904e2fba364e7e25f72b35e4d3f
Evilzlegend/Structured-Programming-Logic
/Chapter 06 - Arrays/Mindtap Assignments/List Basics in Python.py
2,368
4.53125
5
# SUMMARY # In this lab, you complete a partially prewritten Python program that uses a list. # The program prompts the user to interactively enter eight batting averages, which the pgoram # stores in an array. It should then find the minimum and maximum batting averages stored in the # array, as well as the average of the eight batting averages. The data file provided for this # lab includes the input statement and some variable declarations. Comments are included to help # you write the remainder of the program. # INSTRUCTIONS # 1. Make sure the file BattleAverage.py is selected and open. # 2. Write the Python statements as indicated by the comments. # 3. Execute the program by clicking the Run button at the bottom of the screen. Enter the following # batting averages: .299, .157, .242, .203, .198, .333, .270, .190. The minimum batting average # should be .157 and the maximum batting average should be .333. The average should be .2365. # Declare a named constant for array size here. MAX_AVERAGES = 8 # Declare array here. averages = [] # Write a loop to get batting averages from user and assign to array. for i in range(MAX_AVERAGES): averageString = input("Enter a batting average: ") battingAverage = float(averageString) # Assign value to array. averages.append(battingAverage) # Assign the first element in the array to be the minimum and the maximum. minAverage = averages[0] maxAverage = averages[0] # Start out your total with the value of the first element in the array. total = 0 # Write a loop here to access array values starting with averages[1] for i in range(MAX_AVERAGES): # Within the loop for the minimum and maximum batting averages. if averages[i] < minAverage: minAverage = averages[i] if averages [i] > maxAverage: maxAverage = averages[i] total = total + averages[i] # Also accumulate a total of all batting averages. # Caluculate the average of the 8 batting averages. average = total / MAX_AVERAGES # Print the batting averages stored in the averages array. print(averages) # Print the maximum batting average, minimum batting average, and average batting average. print("Minimum batting average is ", minAverage) print("Maximum batting average is ", maxAverage) print("Average batting average is ", average)
true
c5d7058c8a4059ea04286c2f81112c868a1e5f89
Evilzlegend/Structured-Programming-Logic
/Chapter 10 - Object-Oriented Programming/D2L Assignments/joshua_tiemens_CH10PE1.py
2,657
4.3125
4
# importing the class wages to import wages # defining the main function here. def main(): # Disclaimer of what the program does. print("The program will create a class storing an employees name and calculates weekly pay for the employee.") print() # Initializer to start the class engagement. userName = input("What is your name? ") # Obtain the user's name. userHours = validate_hours() # Obtain the user's hours. userWage = validate_wage() # Obtain the user's wage. info = wages.Wages(userName, userHours, userWage) # Transfer the user's information to the class's initializer function. # Brings over the attributes from the wages class back to the main() (info.getHours()) # hour return (info.getWage()) # wage return print("Pay for",info.getName(), "is", info.payForWeek()) # Prints returned calculations for user's inputs. again() # Runs the again function. # defining the validation of hours. def validate_hours(): while True: hours = input("Enter total hours worked: ") # first attempt to gather input. try: hours = float(hours) if hours > 0: # successful input break out of the while loop. break else: # displays message to remind user the number cannot be negative. print("Hours cannot be negative or zero!") # ValueError is displayed if user inputs anything other than a number. except ValueError: print("Hours must be a number!") return hours # submits the information once obtained. # defining the validation of wage. def validate_wage(): while True: wage = input("Enter your hourly wage: ") # first attempt to gather wage. try: wage = float(wage) if wage > 0: # successful input breaks out of loop. break else: # displays error message to remind user wage cannot be negative. print("Wage cannot be negative! ") # ValueErro is displayed if user inputs anything other than a number. except ValueError: print("Wage must be a number! ") return wage # defines the again function if user has more entries. def again(): yesOrNo = input("Do you want to run the program again? ('Y' for yes, anything else to quit)\n") if yesOrNo.upper() == "Y": print() main() # Runs the program again from the start. else: # Ends the program with a farewell message. print("Have a great day!") exit() main() # This is where the main() program runs.
true
e95249b190c21316fb2fbc093819c26174ae73eb
Evilzlegend/Structured-Programming-Logic
/Chapter 06 - Arrays/D2L Assignments/joshua_tiemens_CH6PE2.py
1,937
4.3125
4
# Explain what the program does. print("") # Break to display a clean presentation. print("This program will take a user supplied series of numbers and provide the Low, High, Total, and Average of the numbers input.") print("") # Break to display a clean presentation. # Declarations notQuit = "Y" numCount = [] # Start of loop with sentinel statement. while notQuit == "Y": # Obtain the count of numbers the user wishes to use. numCount = int(input("How many numbers do you want? ")) while numCount <= 0: numCount = int(input("You must enter a number greater than 0: ")) # Informs user if input is invalid. # Initialize the index to store the count of numbers. numVariable = [0] * numCount index = 0 # Loop to run through the series of numbers to obtain the desired numbers to calculate. while index < numCount: print("Enter number ", index + 1, " of ", numCount, ": ", sep="", end="") numVariable[index] = float(input()) index += 1 # Running through the index of numbers. # Calculations involving all of the numbers the user inputs. print("") minNum=min(numVariable) maxNum=max(numVariable) totalNum=sum(numVariable) averageNum=totalNum / numCount # Print sequences for output messages print("Here is the output") print("----------------------") print("Low: \t \t","{:.2f}".format(minNum)) print("High: \t \t","{:.2f}".format(maxNum)) print("Total: \t \t","{:.2f}".format(totalNum)) print("Average: \t","{:.2f}".format(averageNum)) print("") # Ask the user if they would like to start the program over with a new series of numbers. print("Do you want to enter another set of numbers?", end="") notQuit = input("Enter N to quit or Y to continue ") if notQuit == "N": print("Have a great day.") # Ends program if user prefers to quit. quit
true
acf6eb3f92acad7428210099fc4921fd898aed27
Evilzlegend/Structured-Programming-Logic
/Chapter 09 - Advanced Modularization Techniques/MindTap Assignments/Passing Lists to Functions.py
1,348
4.6875
5
""" Passing Lists to Functions Summary In this lab, you complete a partially written Python program that reverses the order of five numbers stored in a list. The program should first print the five numbers stored in the array. Next, the program passes the array to a function where the numbers are reversed. Finally, the main program should print the reversed numbers. The source code file provided for this lab includes the necessary variable assignments. Comments are included in the file to help you write the remainder of the program. Instructions Make sure the file Reverse.py is selected and open. Write the Python statements as indicated by the comments. Execute the program by clicking the Run button at the bottom of the screen. """ """ Reverse.py - This program reverses numbers stored in an array. Input: Interactive. Output: Original contents of array and the reversed contents of the array. """ # Write reverseArray function here. def reverseArray(numbers): return [5, 6, 7, 8, 9] numbers = [9, 8, 7, 6, 5] # Print contents of array. print("Original contents of array:") for text in numbers: print(text) # Call reverseArray function here. result = reverseArray(numbers) # Print contents of reversed array. print("Reversed contents of array:") for text in result: print(text)
true
e5635433b38bc930e7d170d1e4ed483d19e7fedd
Evilzlegend/Structured-Programming-Logic
/Chapter 09 - Advanced Modularization Techniques/MindTap Assignments/Writing Functions that Return a Value.py
1,675
4.375
4
""" Writing Functions that Return a Value Summary In this lab, you complete a partially written Python program that includes a function that returns a value. The program is a simple calculator that prompts the user for two numbers and an operator ( +, -, *, or / ). The two numbers and the operator are passed to the function where the appropriate arithmetic operation is performed. The result is then returned to where the arithmetic operation and result are displayed. For example, if the user enters 3, 4, and *, the following is displayed: 3 * 4 = 12 The source code file provided for this lab includes the necessary input and output statements. Comments are included in the file to help you write the remainder of the program. Instructions Write the Python statements as indicated by the comments. Execute the program. """ # Calculator.py - This program performs arithmetic, ( +. -, *. / ) on two numbers. # Input: Interactive # Output: Result of arithmetic operation # Write performOperation function here def performOperation(x, y, op): if op == "+": return x + y elif op == "-": return x - y elif op == "*": return x * y elif op == "/": return x / y if __name__ == '__main__': numberOne = int(input("Enter the first number: ")) numberTwo = int(input("Enter the second number: ")) operation = input("Enter an operator (+ - * /): ") # Call performOperation method here and store the value in "result" result = performOperation(numberOne, numberTwo, operation) print(str(numberOne) + " " + operation + " " + str(numberTwo) + " = " + str(result))
true
29f514a870e85f54f02384c1eaf6b4dfc607ef8c
Evilzlegend/Structured-Programming-Logic
/Chapter 02 - Elements of High Quality Programs/Coding Snippets/Python Codes/Arithmetic Shortcuts for Updating Variables.py
1,264
4.59375
5
# TOPIC SUMMARY: # We often update the value of a variable by applying some arithmetic operation to its old value. The # simplest case of this is incrementing or decrementing the value of a variable. Python provides a special # assignment operation to make incrementing and shorter to write. Instead of writing x = x + 1 you # may write x += 1. The increment/decrement amount does not have to be 1, you can increase by any # value you like. # TOPIC EXPLANATION: # There is a version of this shortcut assignment operation for every arithmetic operator. You can update # a variable by multiplying a value to the old value, by dividing, raising to an exponent, and so forth. # PLAY WITH CODING SNIPPETS: # 1. Hit the Run button to see the output in the snippet box. # 2. Play around with the snippet code - change variable names, parameters, etc. # 3. Hit the Run button again to see what works and what does not work after you manipulate the code. # 4. Run the correct code again to compare it to the manipulated code. # 5. Have fun practicing this snippet as many times as you like - there are no limits! a = 5 b = 5 print(a, b) a += 1 b += 2 print(a, b) c = 2 d = 3 print(c, d) c *= 5 d **= 2 print(c, d) d /= 3 print(d)
true
6d39b9d412c6ac361b84e688ba939735502d7f66
Ayesha116/official.assigment
/ques42.py
259
4.1875
4
n = int(input("enter no of rows: ")) for rows in range(1, n+1): for columns in range (1 , rows+1): print(columns, end = "") print() for rows in range(n, 0, 1): for columns in range (rows-1,0,1): print(columns, end = "") print()
true
c7e63f0779360106e8178017dee9bc97b270477c
mikeplimo/finalproject17
/day32rocket.py
953
4.375
4
from math import sqrt class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self, x=0, y=0): # Each rocket has an (x,y) position. self.x = x self.y = y def move_rocket(self, x_increment=0, y_increment=1): # Move the rocket according to the paremeters given. # Default behavior is to move the rocket up one unit. self.x += x_increment self.y += y_increment def get_distance(self, other_rocket): # Calculates the distance from this rocket to another rocket, # and returns that value. distance = sqrt((self.x-other_rocket.x)**2+(self.y-other_rocket.y)**2) return distance # Make two rockets, at different places. rocket_0 = Rocket(33,444) rocket_1 = Rocket(20,7) # Show the distance between them. distance = rocket_0.get_distance(rocket_1) print("The rockets are %f units apart." % distance)
true
f8028a5f18f1fc7b3cf4e6bff38b1a4a90e29226
VaibhavEng/PYTHON-CODES
/curd using list project +++++++++++++++++++++++++++++++.py
2,337
4.15625
4
student_name=[] while True: print("""select a option form the below menu: 1.Inserting one name 2.Inserting multiple names 3.Updating an exisiting name 4.deleting a name 5.view all the names 6.quit the program""") ch = int(input("enter your choice:")) if ch==1: #pass means nothing / there will a coming soon ## pass student_name.append(input("enter student name:")) elif ch == 2: names = input("enter multiple names comma seprated:") names = names.strip() if not names == "" or not names is None or not names == " ": student_name.extend(names.split(",")) elif ch == 3: ch1 = int(input("How would like to input data \n1.name \n2.number")) if ch1==1: name = input("enter the name you want to modify:") if name in student_name: student_name[student_name.index(name)]= input("enter name:") else: print("this name is not available") else: for i in range(len(student_name)): print("{}. {}".format(i+1, student_name[i])) idx = int(input("the number of the name u want to change:")) if idx <= len(student_name): student_name[idx-1]= input("enter name:") else: print("invalid input") elif ch == 4: ch1 = int(input("How would like to input data \n1.name \n2.number")) if ch1==1: name = input("enter the name you want to del:") if name in student_name: student_name.remove(name) else: print("this name is not available") else: for i in range(len(student_name)): print("{}. {}".format(i+1,student_name[i])) idx = int(input("the number of the name u want to delete:")) if idx <= len(student_name): student_name.pop(idx-1) else: print("this name is not available") elif ch == 5: for name in student_name: print(name) elif ch == 6: print("""Thank you for using our program!""") break else: print("you have entered a wrong choice. please try again.")
true
73a3555b40047afa7c831d08259ae7da918c81b7
190599/ITP
/Chocolate machine.py
1,233
4.15625
4
#Enter the Price of the Chocolate bar) vPrice=float(input("Please enter the price of the chocolate you want:")) print(vPrice) #Enter the Cash to pay for hte chocolate vCash=float(input("Please enter the cash of the chocolate you want:")) print(vCash) ##Calculat the Change DUe vChangeDue=vPrice-vCash vChangeGiven=round(vChangeDue,2) #Display the Price, Cash, Change Due and ChangeGiven print("TRANSACTION SUMMARY MY FUNCTION") print("Price of Chocolate:",vPrice) print("Cash Paid:",vCash) print("Change Due:",round(vChangeDue,2)) print("Total CHange Given:",vChangeGiven) #While the Change Due is great than - #Give out the largest coin possible while vChangeDue>=50: vChangeGiven=vChangeGiven+50 vChangeDue=vChangeDue-50 print("Giving out $50 note") while vChangeDue>=20: vChangeGiven=vChangeGiven+20 vChangeDue=vChangeDue-20 print("Giving out $20 note") while vChangeDue>=10: vChangeGiven=vChangeGiven+10 vChangeDue=vChangeDue-10 print("Giving out $10 note") while vChangeDue>=5: vChangeGiven=vChangeGiven+5 vChangeDue=vChangeDue-5 print("Giving out $5 note") while vChangeDue>=2: vChangeGiven=vChangeGiven+2 vChangeDue=vChangeDue-2 print("Giving out $2 note")
true
826b097b15c73e156b264044e395178e1ec38d39
nmazzilli3/Intro_to_Self_Driving_Cars_Nanodegree
/Vehicle_Motion_Control/lesson2/int_acc_data.py
2,115
4.125
4
''' What to Remember Once again, don't try to memorize this code! The key thing to remember is this: An integral accumulates change by calculating the area of lots of little rectangles and summing them up. ''' from helpers import process_data, get_derivative_from_data from matplotlib import pyplot as plt PARALLEL_PARK_DATA = process_data("parallel_park.pickle") TIMESTAMPS = [row[0] for row in PARALLEL_PARK_DATA] DISPLACEMENTS = [row[1] for row in PARALLEL_PARK_DATA] YAW_RATES = [row[2] for row in PARALLEL_PARK_DATA] ACCELERATIONS = [row[3] for row in PARALLEL_PARK_DATA] ''' Integrating Accelerometer Data In the last lesson, I gave you code for a get_derivative_from_data function and then later asked you to implement it yourself. We'll be doing something similar for get_integral_from_data here. ''' def get_integral_from_data(acceleration_data, times): # 1. We will need to keep track of the total accumulated speed accumulated_speed = 0.0 # 2. The next lines should look familiar from the derivative code last_time = times[0] speeds = [] # 3. Once again, we lose some data because we have to start # at i=1 instead of i=0. for i in range(1, len(times)): # 4. Get the numbers for this index i acceleration = acceleration_data[i] time = times[i] # 5. Calculate delta t delta_t = time - last_time # 6. This is an important step! This is where we approximate # the area under the curve using a rectangle w/ width of # delta_t. delta_v = acceleration * delta_t # 7. The actual speed now is whatever the speed was before # plus the new change in speed. accumulated_speed += delta_v # 8. append to speeds and update last_time speeds.append(accumulated_speed) last_time = time return speeds # 9. Now we use the function we just defined integrated_speeds = get_integral_from_data(ACCELERATIONS, TIMESTAMPS) # 10. Plot plt.scatter(TIMESTAMPS[1:], integrated_speeds) plt.show()
true
9e025c24d6aa536a3aaa130cc8b47cfbfc41929e
chihyuchin/SC-projects
/SC-projects/weather_master/weather_master.py
1,472
4.375
4
""" File: weather_master.py ----------------------- This program should implement a console program that asks weather data from user to compute the average, highest, lowest, cold days among the inputs. Output format should match what is shown in the sample run in the Assignment 2 Handout. """ # Type this number to stop GG = -100 def main(): """ Enter numbers as temperature to calculate the highest, lowest and average temperature of the list function also counts the number of cold day(s), defined as temperature <16 """ print('StanCode \"Weather Master 4.0"!') data = float(input('temperature')) count = 0 average = 0 cold_days = 0 if data == GG: print('No temperature was entered') else: Highest_temperature = data Lowest_temperature = data if data < 16: cold_days += 1 while True: data = float(input('Next temperature: (or -100 to quit)?')) if data != GG: average = (average * count + data)/(count + 1) count += 1 if data < 16: cold_days += 1 if data >= Highest_temperature and data != GG: Highest_temperature = data if data <= Lowest_temperature and data != GG: Lowest_temperature = data if data == GG: print('Highest temperature= '+str(Highest_temperature)) print('Lowest temperature= '+str(Lowest_temperature)) print('Average= '+str(average)) print('Cold Day(s)= '+str(cold_days)) break ###### DO NOT EDIT CODE BELOW THIS LINE ###### if __name__ == "__main__": main()
true
f2f959acff77d888078a28b430b00dde9b58697a
alwinmreji/ROS-and-ML
/Assingment_#1/#8_largest_among_three.py
343
4.375
4
###################################################### #Find largest among three print("Largest value ",max(int(input("Enter the first number: ")),int(input("Enter the second number: ")),int(input("Enter the third number: ")))) # OUPUT: # Enter the first number: 1 # Enter the second number: 6 # Enter the third number: 4 # Largest value 6
true
345d8324e1fa0d1541e86f27ae92275d2aaf79c3
alwinmreji/ROS-and-ML
/Assingment_#2/#1_max_outof_two.py
270
4.125
4
def maximum(x,y): if x>y: return x else: return y x = float(input("Enter first variable:\t")) y = float(input("Enter second variable:\t")) print("Greatest is ",maximum(x,y)) # OUTPUT # Enter first variable: 4 # Enter second variable: 5 # Greatest is 5.0
true
fdc907963bb826fdcdbd01693ec53ba97fe8b65c
alwinmreji/ROS-and-ML
/Assingment_#1/#9_smallest_in_list.py
302
4.15625
4
##################################################### #Find the smallest in the list a = int(input("Enter the number of terms:\t")) lst = [] while(a): lst.append(int(input())) a-=1 print("Minimum value",min(lst)) # OUTPUT: # Enter the number of terms: 5 # 3 # 2 # 8 # 6 # 1 # Minimum value 1
true
394d7439a3f6e992d32cf5f16bf65899bfbee3d1
udayreddy026/pdemo_Python
/logical_aptitude/08-04-2021/Palindrome.py
430
4.15625
4
num = int(input("Enter a number:::")) temp = num res = 0 while num > 0: l_num = num % 10 # Getting Last number from user entered number its remainder num = num // 10 # Getting coefficient of number will become it means except last number remaining number will # stored in num res = (res*10)+l_num #print(res) if temp == res: print(res, "Is palindrome Number") else: print(res,"is not a palindrome number")
true
853d13a6160712656d249958dc1d8e9b82d9dce5
duncanmichel/Programming-Problem-Solutions
/LeetCode/NumberOneBits.py
1,684
4.40625
4
""" Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight). Example 1: Input: 00000000000000000000000000001011 Output: 3 Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits. Example 2: Input: 00000000000000000000000010000000 Output: 1 Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit. Example 3: Input: 11111111111111111111111111111101 Output: 31 Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits. Note: Note that in some languages such as Java, there is no unsigned integer type. In this case, the input will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned. In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3 above the input represents the signed integer -3. Follow up: If this function is called many times, how would you optimize it? """ class Solution(object): def hammingWeight(self, n): numones = 0 while n > 0: numones += n % 2 n //= 2 return numones """ My solution: Runtime: 24 ms, faster than 52.81% of Python online submissions for Number of 1 Bits. Memory Usage: 11.7 MB, less than 5.10% of Python online submissions for Number of 1 Bits. """ """ Fastest Solution (16ms): class Solution(object): def hammingWeight(self, n): return bin(n).count('1') Smallest Memory (10520 kb): [same as fastest] """
true
65612bb67a0b106453dc7b4d4a9a9593426f70d4
pritamksahoo/III-IV-YEAR-Assignments
/BIO/triplets.py
1,143
4.125
4
no_char, pair = 4, 3 dict_char = {'a':0, 'c':1, 'g':2, 't':3} class Triplet(object): ''' Trie data structure to store triplets and their frequencies ''' def __init__(self): super(Triplet, self).__init__() self.freq = 0 self.children = [None for i in range(no_char)] def add_to_suffix_tree(triplet, part): ''' Function to add a triplet to Trie data structure Parameters: triplet : Pointer to the root od Trie part : The actual triplet to enter into the Trie ''' trip = triplet ret = 0 for i in range(pair): val = dict_char[part[i]] if trip.children[val] is None: trip.children[val] = Triplet() trip = trip.children[val] else: trip = trip.children[val] if i == pair-1: trip.freq = trip.freq + 1 ret = trip.freq return ret if __name__ == '__main__': string = input() triplet = Triplet() max_freq, ans = 0, list() for i in range(0,len(string)-pair+1): part = string[i:i+pair] freq = add_to_suffix_tree(triplet, part) if freq > max_freq: ans = [part] max_freq = freq elif freq == max_freq: ans.append(part) print("Triplets :-", ans, "|| Frequency :-", max_freq)
true
9ec46eed13310d3a71be627e182d7d526313d2fa
em55/Python-exercises
/eight12.py
501
4.53125
5
"""This program takes a word and encrypts it usgin the ROTn method rotating the letters of the word n times""" #must be modified to rotate only alphabets, now it rotates among all ascii characters def rotate_word(s, n): char = "abcdefghijklmnopqrstuvwxyz" a = '' for c in s: a += char[(char.index(c)+n) % 26 ] return a input_string = raw_input("Enter the word to be encrypted: ") n = int(raw_input("Enter the number of rotations: ")) print "Rotated word is ", rotate_word(input_string, n)
true
75ead60db9b7143f0a933fd20babeeca554cf1f4
em55/Python-exercises
/six2.py
290
4.15625
4
import math def hypo(a,b): c = math.sqrt(a**2+b**2) return c side_a = int(raw_input("Enter the length of side a of the triangle: ")) side_b = int(raw_input("Enter the length of side b of the triangle: ")) print "The hypotenuse of the right triangle is of length:", hypo(side_a, side_b)
true
fa860381fccfa267ece78f4fc2ec7edc8ca79be8
godinenbicicleta/IntroComputation
/SimpleAlgorithms/exhaustiveEnumeration.py
1,102
4.125
4
# -*- coding: utf-8 -*- # find the cube root of a perfect cube x = int(input('Enter an integer: ')) ans = 0 while ans**3 - abs(x) < 0: #this is de decrementing function ans = ans + 1 if ans**3 != abs(x): print( x, 'is not a perfect cube') else: if x < 0: ans *=-1 print( f'Cube root of {x} is {ans}') # find root and pwr such that root**pwr is equal to the integer provided x = int(input('Enter an integer: ')) messages = [] for pwr in range(2,6): root = 0 while root**pwr - abs(x) < 0: root+=1 if root**pwr == abs(x): if x<0: ans*=-1 messages.append(f'{root} to the {pwr} = {x}') if len(messages) == 0: print(f'No 1<pwr<6 and root exist such that pwr**root equals {x}') else: for message in messages: print(message) # Exhaustive enumeration using a for loop x = int(input('Enter an integer: ')) for ans in range(0, abs(x)+1): if ans**3>= abs(x): break if ans**3 != abs(x): print(x, 'is not a perfect cube') else: if x<0: ans = -ans print(ans, 'is the cube root of', x)
true
da8c9fd68bc9ff81d934c94b63aaa31665b64674
jan-wo/data-cheatsheet
/pandas_missing_data.py
896
4.1875
4
""" This is small tutorial about what to do with the missing data. """ import pandas as pd import numpy as np # Fake data with missing values data = {'a': [1, 2, np.nan], 'b': [4, np.nan, np.nan], 'c': [3, 2, 1]} # Data frame: df = pd.DataFrame(data) # ------------------------ Dropping rows/columns -------------------------- # Discard rows/columns containing insufficient data: dis_1 = df.dropna() # Drop columns and rows. dis_2 = df.dropna(axis=1) # Drop all axis=1 (columns) with missing data set. # Set treshold: minimal number of data entries to keep row/column: dis_3 = df.dropna(axis=0, thresh=2) # ------------------------ Filling empty spaces ---------------------------- # Filling with some entry given a priori: fill_1 =df.fillna(value='CUSTOM FILLING') # Filling with a mean of a given column: fill_2 = df['a'].fillna(value=df['a'].mean()) print(fill_2)
true
d53e50a5abb31e42a4ec079f82399f68028a3862
purvesh-patel/HackerRank
/printString.py
344
4.34375
4
# The included code stub will read an integer,n from STDIN. # # Without using any string methods, try to print the following: # 1234...n # Note that "..." represents the consecutive values in between. # # Example n = 5 # Print the string 12345. n = 5 string ="" for i in range(1,n+1): #print(i) string = string + str(i) print(string)
true
33403bd7ba0a7203ced5d88e8c660a91d5971e12
league-python-student/level1-module4-ezgi-b
/_01_dictionaries/_a_dictionaries_demo.py
2,696
4.625
5
""" Demonstration of dictionaries """ # Dictionaries are data structures that hold pairs of items. For example: # p_table = {1 : 'Hydrogen', 2 : 'Helium', 3 : 'Lithium', 4 : 'Beryllium'} # # The dictionary p_table contains 4 pairs of items, separated by commas, with # the first one being 1 : 'Hydrogen'. # The first item, 1, is called the 'key' and the second item, 'Hydrogen', is # called the 'value'. # 1 : 'Hydrogen' # / \ # key value # Given the key it's possible to get the corresponding value, but given the # value it's not possible to get the key. For example: # print(p_table[3]) # prints Lithium # print(p_table['Helium']) # ERROR: KeyError # # Dictionaries can have duplicate values, but not duplicate keys. All keys in # a dictionary are unique. If a new key-value pair is added and that key is # already in the dictionary it gets replaced by the new pair. For example: # p_table[1] = 'Deuterium' # print(p_table[1]) # prints Deuterium, the 1 : 'Hydrogen' pair was replaced # # The key-value pair types do not have to be the same for all the dictionary # elements. For example: # var = {'key' : 'value', 10 : 20, True : 'True', 'Pi' : 3.14} # Initializing a dictionary p_table = {1 : 'Hydrogen', 2 : 'Helium', 3 : 'Lithium', 4 : 'Beryllium'} dict_1 = {'key' : 'value', 10 : 20, True : 'True', 'Pi' : 3.14} # Getting a value from a key val = dict_1['Pi'] print("Getting value from key 'Pi', " + str(val)) # Adding/replacing a single element to a dictionary p_table[5] = 'Boron' print("Adding Boron to p_table, p_table[5] = " + str(p_table[5])) # Adding/replacing multiple elements to a dictionary p_table.update({6 : 'Carbon', 7 : 'Nitrogen', 8 : 'Oxygen'}) # Iterating through all the key-value pairs method #1 print("All elements in p_table:") for key in p_table: # *NOTE* DO NOT rely on the order elements to be the same as # the order in which they were added! print(str(key) + " : " + str(p_table[key])) # Get the total number of key-value pair elements using the len() function print('dict_1 has a total of ' + str(len(dict_1)) + ' elements') # Removing a key-value pair. This changes the size of the dictionary. print("Removing key Pi...") if 'Pi' in dict_1: del dict_1['Pi'] print('dict_1 has a total of ' + str(len(dict_1)) + ' elements') # Iterating through all the key-value pairs method #2 print("\nAll elements in dict_1:") for key, value in dict_1.items(): print(str(key) + " : " + str(value)) # Iterating through all the values print("\nAll values in p_table:") for value in p_table.values(): print(str(value), end=', ')
true
571844d871608fee02b41c6ab3a6fe5451b50554
shanjidakamal/csci127-assignments
/hw_05/hw_05.py
1,416
4.25
4
'''Write a function filterodd(l) that takes in a list and returns a new list that consists of only the odd numbers from the original list. That is the list [1,2,3,4,5,6,7,8] would return a new list [1,3,5,7]. The lists don't have to be in order.''' l=[1,2,3,4,5,6,7,8,9,10,11,12] def filterodd(l): newlist=[] for n in l: if n % 2 == 1: newlist.append(n) return newlist print(filterodd(l)) x=20 def filtereven(l): newlist=[] global x x=x+1 for n in l: if n % 2 == 0: newlist.append(n) return newlist print(filtereven(l)) '''Write a function mapsquare(l) that takes a list and returns a new list that consists of the original items squared. For example, the list [4,2,5,3,5] would return a new list [16,4,25,15,25]''' l2=[12,3,5,6,2,1,8,9,0,14,7] def mapsquare(l2): newlist2=[] for n in l2: newlist2.append(n ** 2) return newlist2 print(mapsquare(l2)) def is_odd(n): return n%2==1 def is_even(n): return n ==0 def is_big(n): return n>5 def myfilter(predicate,l): result=[] for n in l: if predicate(n): result.append(n) return result def mymap(f,l): result=[] for n in l: result.append(f(n)) return result def cube(n): return n*n*n def make_upper return def is_name(world): return word [0] == word[0].upper()
true
cb86e69bca028a95afc36491a1d75aaf522639e3
nicolecpeoples/python-basics
/assignments/grades.py
459
4.125
4
count=10 while count > 0: print "What is your grade?" grade = raw_input() if grade >= "90": print "Score: " , grade, "; Your grade is a A" elif grade >= "80": print "Score: " , grade, "; Your grade is a B" elif grade >= "70": print "Score: " , grade, "; Your grade is a C" elif grade >= "60": print "Score: " , grade, "; Your grade is a D" else: print "You've failed, I'm sorry :(" count -=1 raw_input("\n\nEnd of Program. Bye!")
true
eb63bba945e75b3d1d897fb37b9ecc3b705b7829
claraj/web-autograder
/grading_module/example_assignments/example_python_assignment/lab_questions/q3_which_number_is_larger.py
787
4.40625
4
# Question 1: if-else in a function. Which number is larger? def main(): # You don't need to modify this function. a = input('Enter one number: ') b = input('Enter another number: ') compare = which_number_is_larger(a, b) if compare == 'same': print('The two numbers are the same') else: print('The {} number is larger'.format(compare)) def which_number_is_larger(first, second): pass # TODO delete this line and replace this with your code # TODO if the first number is larger, return the string 'first' # TODO if the second number is larger, return the string 'second' # TODO if the numbers are the same, return the string 'same' # You don't need to modify the following code. if __name__ == "__main__": main()
true
c30dfd8de5ecd8153fdbcca2ec7183e74c92a1ab
claraj/web-autograder
/grading_module/example_assignments/example_python_assignment/lab_questions/Loop2fun.py
2,015
4.21875
4
""" NOTE Chapter 3 lab (Lab 6) & Homework assignments are redesigns of previous programs, to follow the new IPO structure.​ Use the code from the Loop-2 program from last time You will create functions called main(), inputNumbers(), processing(), and outputAnswer(). The old program and new program will have a similar feel when run: - ask the user for a small number. - Then, ask the user for a larger number.​ Your program should display all the numbers in the range, add up all the numbers in the range, and display the total.​ So if your user enters 20 and 23, the program should display the numbers in that range, and calculate 20+21+22+23 = 86.​ Add exception handling in main() and test with bad inputs. ​ Add validations and your own touches. """ # TODO your code here. def inputNumbers(): # Validation should go here? # Check that data is an integer and the first number is smaller than the seconds. while True: try: firstNum = int(input('Enter a small number: ')) secondNum = int(input(f'Enter another number that is larger than {firstNum}: ')) if firstNum > secondNum: print('The second number should be larger than the first number.') continue return firstNum, secondNum except ValueError: print('Make sure you enter an integer number.') def processing(n1, n2): # math total = 0 for n in range(n1, n2+1): total += n return total def outputAnswer(total, n1, n2): print(f'All the numbers in the range {n1} to {n2} are:') for n in range(n1, n2+1): print(n) print(f'The total is {total}') def main(): n1, n2 = inputNumbers() total = processing(n1, n2) outputAnswer(total, n1, n2) # It is important that you call main in this way, # or all the code will run when this is imported into # the test file, including input statements, which # will confuse the tests. if __name__ == '__main__': main()
true
630afbcab875ba20023877706a42d4e70fd09315
nileshhadalgi016/python3
/For loop in python.py
834
4.25
4
""" Python For Loops - Techie Programmer A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). """ # Looping Through a String for x in "banana": print(x) # The break Statement fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break # The continue Statement fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x) # The range() Function for x in range(1,6,2): print(x) # Else in For Loop for x in range(6): print(x) else: print("Finally finished!") # Nested Loops adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: for y in fruits: print(x, y) # The pass Statement for x in [0, 1, 2]: pass
true
25b76979d4c22ea67555610bb4f64dc8f713d8f8
Sevansu/Python-Tasks-Basic-to-Advance
/Task 2/task_2_01_A.py
1,151
4.15625
4
#1. Create two python files. say 'task_2_01_A.py' and 'task_2_01_B.py'. Create a class in the 'task_2_01_A.py' having some attributes and functions and constructor defined in the class. Create a method outside that class in the file 'task_2_01_A.py'. Use that class and its attributes and mehtods and the method that is defined outside the class in the file 'task_2_01_B.py'. class SimpleInterest: #variables m = "" p = 0 r = 0 t = 0 #constructor def __init__(self, Message, PrincipleAmount, RateOfInterest, Time): self.m = Message self.p = PrincipleAmount self.r = RateOfInterest self.t = Time #class methods def showMessage(self): print(self.m) def InterestGenerator(self): x = (self.p*self.r*self.t)/100 print(x) person1 = SimpleInterest(Message="seva", PrincipleAmount=60000, RateOfInterest=2, Time=2) person2 = SimpleInterest(Message="nsu", PrincipleAmount=100000, RateOfInterest=3, Time=5) person1.showMessage() person1.InterestGenerator() person2.showMessage() person2.InterestGenerator()
true
6d3bbf1614e30f76dcbe63a9091b78e635e6fbc3
AlexPolGit/Python-Projects
/strings_test.py
623
4.5625
5
#strings_test.py #Testing out string functions Python string = "python is a programming language" print "\nOriginal string:" print string print "\nAs a sentence:" print string.capitalize() + "!" print "\nLength of string:" print len(string) print "\nNumber of g's: " print string.count("g") print "\nIs alphabetic? Is numeric? Is alphanumeric?" print string.isalpha(), string.isdigit(), string.isalnum() print "\nUppercase all:" print string.upper() print "\nTitle-cased:" print string.title() print "\nBack to lower:" print string.lower() print "\nSplit into words:" for word in string.split(" "): print word
true
015964ff2101192be30278b7e38b9e8e6254c937
kulvirvirk/Python_Number
/main.py
770
4.125
4
#declare some math variables x = 6 y = 2.2 print('x = 6 \ny = 2.2\n') #perform some math functions sum = x + y; print('sum is: ' + str(sum)) substraciton = x - y print('difference is: ' + str(substraciton)) multiplication = x * y print('multiplication is: {:0.2f}'.format( multiplication)) # output is formated # Where: # : introduces the format spec # 0 enables sign-aware zero-padding for numeric types # .2 sets the precision to 2 # f displays the number as a fixed-point number division = x/y print('division is: {:0.2f}'.format(division)) exponent = x**y print('exponent is: ' + str(exponent)) mod = x%y #remainder print('remainder is: ' + str(mod)) div = x//y #quotient of a division print('quotient is: ' + str(div)) print(round(4.5)) print(abs(-20))
true
cfa75fa7477dcd832853b4a34a13d889c8f708ce
QLGQ/learning-python
/prime.py
1,139
4.21875
4
#-*-coding:utf-8-*- #Set a condition for exiting the loop def main(maximum=1000): pr = primes(maximum) for n in pr: if n < maximum: print(n) else: break #Construct a sequence of odd numbers starting from 3 def _odd_iter(maximum): n = 1 while n < maximum: n = n + 2 yield n #Construct a filter function to filter the sequence of previous constructs #lambda:Anonymous function and The return value is the result of the expression. def _not_divisible(n): return lambda x: x % n > 0 #Define a generator, and continue to return to the next prime number ''' filter: Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list. ''' def primes(maximum): yield 2 it = _odd_iter(maximum) n = next(it) yield n while True: try: it = filter(_not_divisible(n), it) n = it.pop(0) yield n except Exception: break #invoke function main(10000)
true
9f580eff78dd811bae154193b94535881327d541
PunjabiTadka/FIT1008_Assignment1
/29202515_Assessment1/Task4_A.py
2,469
4.375
4
""" @author: Amrita Kaur @since: 16/3/2018 @modified: 17/3/2018 """ def populateList(size): """ This function takes in the size as an argument, and accepts 'size' number of inputs from the user, stores them in a list and returns it @:param size: The number of inputs to accept from the user @:return: my_list: The list containing 'size' number of numbers @pre-condition: - @post-condition: - @complexity: Worst-Case: O(n) @complexity: Best-Case: O(n) @exeception(raises): - """ # Allocate the memory to store the list my_list = [0] * size print("Enter the temperatures: ") for i in range(size): item = int(input()) my_list[i] = item return my_list def bubble_sort(myList): """ This function sorts a given list of integers in place using the bubble sort algorithm @:param myList: List of numbers to sort @:return: None @pre-condition: - @post-condition: The given list 'myList' is sorted in place @complexity: Worst-Case: O(n^2) @complexity: Best-Case: O(n^2) @exeception(raises): - """ size = len(myList) for i in range(size): for j in range(0, size-i-1): if myList[j] > myList[j + 1]: temp = myList[j] myList[j] = myList[j+1] myList[j+1] = temp return myList def count(size, myList): """ This function counts the frequency of each number in the list and prints it @:param size: size of the list @:param myList: The list of numbers @:return: None @pre-condition: - @post-condition: - @complexity: Worst-Case: O(n^2) @complexity: Best-Case: O(n^2) @exeception(raises): - """ bubble_sort(myList) i = 0 while i < size: count = 0 for j in range(i, size): if j == size - 1: count += 1 print(str(myList[i]) + " appears " + str(count) + " times") i = j break if myList[j] == myList[i]: count += 1 continue else: print(str(myList[i]) + " appears " + str(count) + " times") i = j - 1 break i += 1 n = int(input("Enter the size of the list: ")) my_list = populateList(n) count(n, my_list)
true
d629ec1ddb5e77cb43a491ab39e285928d659a23
taarunsinggh/class-work
/33.py
682
4.34375
4
#3-3. Your Own List: Think of your favorite mode of transportation, such as a #motorcycle or a car, and make a list that stores several examples. Use your list #to print a series of statements about these items, such as “I would like to own a #Honda motorcycle.” transport=['bus','motorcycle','scooter','train','flight'] print("I commute to my work everyday by "+transport[0]) print("Back in India I had a "+transport[1]) print("I also owned a "+transport[2]+" which I found to be more comfortable than the "+ transport[1]) print("In India mostly I travelled by "+transport[3]+" for domestic travel") print("The "+transport[4] +" that I took to come to USA was 20 hours long")
true
7f579387832a0fe9dc55fdfa1e0651560d3710d7
taarunsinggh/class-work
/31.py
289
4.34375
4
#Names: Store the names of a few of your friends in a list called names. Print #each person’s name by accessing each element in the list, one at a time. names=['Vibhor','Deven','Mohit','Rajbeer','Swapnil'] print(names[0]) print(names[1]) print(names[2]) print(names[3]) print(names[4])
true
c7a2dd3611c38269715fd6fce7459bb2e6b46e5b
daniloiiveroy/MyPythonTraining
/02-list_tuple_set/app.py
2,989
4.125
4
# from typing_extensions import TypeVarTuple courses = ["History", "Math", "Physics", "CompSci"] print(courses) # List print(courses[2]) # Specific course via index print(courses[-1]) # Last item print(courses[0:2]) # List of items print(courses[2:]) # List of items # Append function courses.append("Art I") print(courses) # Insert function courses.insert(1, "Art II") print(courses) # Insert List function Adding list new_courses = ["Computer", "Science"] courses.insert(-1, new_courses) print(courses) # Extend function Adding value at the end new_courses = ["Filipino", "MAPEH"] courses.extend(new_courses) print(courses) # Remove Function courses.remove(("Filipino")) courses.remove(("Art I")) print(courses) # Pop Function Removing last value in list courses.pop() print(courses.pop()) print(courses) # Reverse Function courses.reverse() print(courses) # Sort Function sort_courses = courses sort_courses.sort() print(sort_courses) nums = [3, 5, 4, 1, 2] nums.sort() print(nums) # Sort Reverse Function sort_courses.sort(reverse=True) print(sort_courses) # Sort without altering original list Function print(sorted(courses)) # Min, Max and Sum Function print(min(nums)) print(max(nums)) print(sum(nums)) # Search function print(courses.index("CompSci")) # Search if exist print("Math" in courses) # for loop function for course in courses: print(course) # for loop with enumerate function for course in enumerate(courses): print(course) for index, course in enumerate(courses): print(index, course) # for loop with index start for index, course in enumerate(courses, start=1): print(index, course) # list to string course_str = ", ".join(courses) print(course_str) # split string function print(course_str.split(", ")) list_1 = ["History", "Math", "Physics", "CompSci"] list_2 = list_1 print(list_1) print(list_2) # replacing list data via index list_1[0] = "Art III" print(list_1) print(list_2) # tuples tuple_1 = ("History", "Math", "Physics", "CompSci") tuple_2 = tuple_1 print(tuple_1) print(tuple_2) # replacing list data via index # tuple_1[0] = "Art III" print(tuple_1) print(tuple_2) # Sets removes duplicate data cs_courses = {"History", "Math", "Physics", "CompSci", "Math"} print(cs_courses) # set searching print("Math" in cs_courses) # intersection like inner join it_courses = {"Boilogy", "Math", "Chemistry", "CompSci"} print(cs_courses.intersection(it_courses)) # union function print(cs_courses.union(it_courses)) # empty lists empty_list = [] empty_list = list() # empty tuples empty_tuple = () empty_tuple = tuple() # empty sets empty_set = {} # this isn't right! It's a dict empty_set = set() coordinates = (1, 2, 3) x, y, z = coordinates print(x, y, z) customer = { "name": "Dan", "age": 27, "is_verified": True } customer["name"] = "DAV" print(customer.get("name")) ### excercise ''' clear & "D:/Program Files/Python39/python.exe" d:/Solutions/PythonTraining/02-list_tuple_set/app.py '''
true
7d31ad86b378446d2397312cfec27c90e9aebf9f
fadikoubaa19/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
235
4.15625
4
#!/usr/bin/python3 """ module that contains the append write""" def append_write(filename="", text=""): """ appends a string to end of txt file""" with open(filename, 'a', encoding='utf-8') as f: return f.write(text)
true
bdc0c9be95f2bc224281624a42fa6347abf4c7ff
MapleDa/Python
/topic13_files_io.py
1,241
4.15625
4
#T13Q1 #The open method returns a file object. Syntax: open(name[, mode]). where mode #can be 'r' (read), 'w'(write) or 'a'(append). The default mode is 'r'.The #close method closes an opened file object. filename = 'tmp.txt' mode = 'w' f = open(filename, mode) # open a file f.write('hello') # write to file f.close() # close a file #T13Q2 #Create a function that appends the name and email to the end of a named file. def addEmail(filename, name, email): mode = 'a' f = open(filename, mode) # replace the mode f.write("%s %s\n" % (name, email)) f.close() return f # do not remove this line #T13Q4 #read([size]). Read size bytes from the file, unless EOF is hit. If size is #omitted or negative, the full data is returned. def readFile(filename): f = open(filename) count = 0 lines = 0 while 1: char = f.read(1) if not char: break count+=1 if(char == '\n'): lines+=1 f.close() # close file return (count, lines) #T13Q6 #Write a function to read the scores and compute the average score of the #class. (Ignore the first line which contains the field headers). print(readFile('test.txt'))
true
95c8cd2f0e63aab72f9862fc611ca54ed30970ce
dansmyers/IntroToCS
/Examples/2-Conditional_Execution/is_positive.py
222
4.28125
4
""" Test if an input number is positive, negative, or zero """ value = int(input('Type a number.')) if value > 0: print('Positive.') elif value < 0: print('Negative.' else: print('Zero.') print('Done.')
true
c61c8f95784a8ac91a1a85f0e6b12b8552d2cc03
alosoft/bank_app
/bank_class.py
2,453
4.3125
4
"""Contains all Class methods and functions and their implementation""" import random def account_number(): """generates account number""" num = '300126' for _ in range(7): num += str(random.randint(0, 9)) return int(num) def make_dict(string, integer): """makes a dictionary of Account Names and Account Numbers""" return {string: integer} class Account: """ This Class contains Balance and Name with functions like Withdraw, Deposit and Account History """ def __init__(self, name, balance=0, total_deposit=0, total_withdrawal=0): """Constructor of __init__""" self.name = name.title() self.balance = balance self.records = [f'Default Balance: \t${self.balance}'] self.total_deposit = total_deposit self.total_withdrawal = total_withdrawal self.account = account_number() def __str__(self): """returns a string when called""" return f'Account Name:\t\t{self.name} \nAccount Balance:\t${str(self.balance)} ' \ f'\nAccount History:\t{self.records} \nAccount Number:\t\t{ self.account}' def __len__(self): """returns balance""" return self.balance def history(self): """returns Account Information""" return self.records def print_records(self, history): """Prints Account Records""" line = ' \n' print(line.join(history) + f' \n\nTotal Deposit: \t\t${str(self.total_deposit)} ' f'\nTotal Withdrawal: \t${str(self.total_withdrawal)} ' f'\nTotal Balance: \t\t${str(self.balance)} ') def deposit(self, amount): """Deposit function""" self.total_deposit += amount self.balance += amount self.records.append(f'Deposited: ${amount}') return f'Deposited: ${amount}' def withdraw(self, amount): """Withdrawal function""" if self.balance >= amount: self.total_withdrawal += amount self.balance -= amount self.records.append(f'Withdrew: ${amount}') return f'Withdrew: ${amount}' self.records.append( f'Balance: ${str(self.balance)} ' f'is less than intended Withdrawal Amount: ${amount}') return f'Invalid command \nBalance: ${str(self.balance)} ' \ f'is less than intended Withdrawal Amount: ${amount}'
true
c333d408b37574b13a5f92fb68825e4725ac223e
samdish7/COSC420
/Notes/Py/pyfuncs.py
1,104
4.25
4
# Python functions are defined with the # "def" keyword, then the name, list of # parameters, then a colon. # note that functions do not have # return types, and parameters do not # have types (but you can provide them # anyway) # scopes in python are delineated not by # curly braces (as in c/c++) but by tabs # you can use spaces to indent or tabs, # but don't mix-and-match def func(): # all following indented lines are # bound to the "func" block print("hello from func") # non type-hinted version def funcParams(a,b,c): # using python's "f-strings" print(f"a: {a}") print(f"b: {b+10}") print(f"c: {c}") return 10 # return looks the same # hinted version def funcParams2( a : str, b : int, c : float) -> int : # using python's "f-strings" print(f"a: {a}") print(f"b: {b+10}") print(f"c: {c}") return "10" # return looks the same def main(): print("Start of program") print("about to call the function:") func() # call the funcion #val = funcParams(15, 10, 3.4) val = funcParams2(15, 10, 3.4) print(val) # back in the top-level scope main()
true
6fd3b644ed043a8b288065be615f638f9436e8b0
awlange/project_euler
/python/p72.py
1,834
4.1875
4
import time from p27 import get_primes_up_to def farey(n): """ Thanks for the help Wikipedia! Python function to print the nth Farey sequence, either ascending or descending. """ a, b, c, d = 0, 1, 1, n print "%d/%d" % (a,b) while c <= n: k = int((n + b)/d) a, b, c, d = c, d, k*c - a, k*d - b print "%d/%d" % (a,b) def phi(n, primes=None): """ totient function of n for general use later below, we use a sieve approach and don't use this function """ if not primes: primes = get_primes_up_to(n) result = float(n) for p in primes: if p > n: break elif n % p == 0: result *= 1.0 - 1.0/float(p) return int(result) def phi_float(n, primes=None): """ totient function of n for general use later below, we use a sieve approach and don't use this function """ if not primes: primes = get_primes_up_to(n) result = float(n) for p in primes: if p > n: break elif n % p == 0: result *= 1.0 - 1.0/float(p) return result def main(): start = time.time() # Using formula found on Wikipedia under Farery sequence MAX_N = 1000000 primes = get_primes_up_to(MAX_N) prime_divs = [[] for _ in xrange(MAX_N+1)] for p in primes: m = p while m <= MAX_N: prime_divs[m].append(p) m += p # Now compute the totient for each using the provided primes, and compute the Farey length answer = 0 for m in xrange(2, MAX_N + 1): totient = float(m) for p in prime_divs[m]: totient *= 1.0 - 1.0/float(p) answer += int(totient) print answer print "Time: {}".format(time.time() - start) if __name__ == '__main__': main()
true