blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
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
640811ff6a744e85fed8dbdd264aaf6c87907a63
samuei/Snippets
/String Reversal.py
556
4.53125
5
#1. Write the function that reverses a string without using explicit loops. E.g. “Hello” should return “olleH”. # For Python 2.6+ users, comment out this line. Otherwise, keep it. from __future__ import print_function def StringRev(inString): if(len(inString)>0): print(inString[len(inString) -1:], end='') StringRev(inString[:-1]) #Test Input: StringRev("Hello, Darkness, my old friend") print() StringRev("I've come to talk with you again") #Test Output: #dneirf dlo ym ,ssenkraD ,olleH #niaga uoy htiw klat ot emoc ev'I
false
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
4b454d4524ad8d02c883008d52eab7386104ee43
Devendra1998/Python-Basics
/deva8.py
245
4.125
4
print("enter your age") print("age should be in between 7 to 70") a1=int(input()) if a1<7&a1>77: print("Re enter your age") if a1<18: print("you cant drive") elif a1==18: print("you have to come") else: print("you can drive")
false
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
2ba201d1203a8f64019be99e509592865e887359
jessejacob19/freeCodeCampPython
/if_statements.py
264
4.125
4
is_male = True is_tail = False if is_male and is_tail: print("you are a tall male") elif is_male and not(is_tail): print("you are a short male") elif not(is_male) and is_tail: print("you are not a male but are tall") else: print("you are neither")
false
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
6632e1092655ba9d4f79afd6bd4e95f0a84b3f62
yanbin0061/TensorFlow
/MyPython/functionTest.py
1,693
4.59375
5
""" 定义函数的规则 1.函数代码快以def开头, 后面接标识符合圆括号 """ def hello(): print('Hello world!') hello() # 计算矩形的面积 def area(width, height): return width * height def print_welcome(name): print("Welcome", name) print_welcome("闫斌") w = 4 h = 5 print("width:", w, "heigh:", h, "area = ", area(w, h)) # 定义函数 def print_me(strs): "打印传入的字符串" print(strs) return # 调用函数 print_me("调用自定义函数") print_me("调用同一个自定义的函数") # 传不可变的对象(整数, 字符串, 元组) def changeInt(a): a = 10 b = 2 changeInt(b) print(b) # 传可变的对象 def changeList(myList): myList.append([1, 2, 3, 4]) print("函数内取值:", myList) return myList = [10, 20, 30] changeList(myList) print("函数外取值:", myList) # 使用关键字参数 def printInfo(name, age): print("姓名:", name) print("年龄:", age) return printInfo(age=20, name="闫斌") # 默认参数 def printInfo1(name, age=50): print("姓名:", name) print("年龄:", age) return printInfo1(name="张三", age=14) printInfo1(name="李四") # 不定长参数 def printInfo2(arg1, *varTuple): "打印任何传入的参数" print("输出:") print(arg1) for var in varTuple: print(var) return print('----------------------') printInfo2(10) printInfo2(10, 10, 10, 10) # 匿名函数 sum1 = lambda arg1, arg2: arg1 + arg2 print("相加后的值:", sum1(10, 20)) matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ] print([[row[i] for row in matrix] for i in range(4)])
false
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
ac1929211392f6252c10706a8ac93615d11fe217
elephannt/PythonTrain
/10-ExamenU2/ExamenPT2.py
708
4.125
4
#!/usr/local/bin/python # -*- coding: utf-8 -*- ##Diferentes ##list1, list2 = ["Verde","Rojo","Morado","Azul","Negro","Blanco","Rosa","Anaranjado"], ["Plateado","Guinda","Dorado","Menta","Gris","Lila","Amarillo","Crema"] ##Iguales list1, list2 = ["Verde","Rojo","Morado","Azul","Negro","Blanco","Rosa","Anaranjado"], ["Verde","Rojo","Morado","Azul","Negro","Blanco","Rosa","Anaranjado"] #Imprime el resultado de la comparación de ambas listas print ("\nEl resultado: ", list1 == list2) #Imprime los elementos de la lista 1 print "\nElementos de la lista 1:" for ciclo in list1: print (ciclo) #Imprime los elementos de la lista 2 print "\nElementos de la lista 2:" for ciclo in list2: print (ciclo)
false
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
b30c7ff4d25a8ca82ee30391453a81dce452307b
bravestone831/fundamental-python
/if.py
720
4.125
4
#if语句是自上而下判断,也就是说,if遇到第一个满足条件(判断为true)的语句, #就停止下面所有的判断(跳出if) s = int(input('Please enter your age:')) if s >6: print('teen') elif s >18: print('you\'re old') else: print('kid') birth = int(input('birth: '))#input返回是str,不能和2000这个整型比较,所以加int if birth < 2000: print('00前') else: print('00后') #BMI a=float(input('Please enter your height:')) b=float(input('Please enter your weight:')) c= b/(a*a) if c<18.5: print('too thin') elif c>18.5 and c<25: print('normal') elif c>=25 and c<28: print('overweight') else: print('obesity')
false
cb3b03645efb41d5ec0abf9351ed165b0d2d0755
johannest18/timi409
/max_int.py
763
4.125
4
#taka við heiltölum í input num_int = int(input("Input a number: ")) # Do not change this line #Láta forritið muna eftir tölunni max_int = num_int #Ef að ekki er skráð inn jákvæð heiltala (0 meðtalinn) þá er hún hæsta talan og skal því prenta hana út. #Aftur skal biðja um heiltölu í input. # Ef hún er hærri en hæsta talan sem forritið man eftir skal forritið gleyma þeirri tölu og muna þessa í staðinn. #Ef talan er neikvæð heiltala skal forritið prenta út hæstu tölu sem slegin hefur verið inn. # EF talan er jákvæð skal endurtaka while num_int >= 0: num_int = int(input("Input a number: ")) if num_int > max_int: max_int=num_int print("The maximum is", max_int) # Do not change this line
false
241da34541380a455a71fe0ba5e4f2518beac801
tianqing617/PythonStudy
/advancedUsage/generator.py
1,069
4.15625
4
# -*- coding: utf-8 -*- # generator的演变 # 使用场景:当一个List有很多个元素,而这些元素是可以通过计算得到的,此时可以使用generator。 # 例如:[1, 2, 3, 5, 8, 13, 21, ...]这个list是前后者是前两个的和。 # generator的演变过程 # 斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到: def fib(max): n, a, b = 0, 0, 1 while n < max: print(b) a, b = b, a + b n = n + 1 return 'done' fib(10) print('------------------------------') # 注意: # a, b = b, a + b # 相当于 # t = (b, a + b) t是一个tuple # a = t[0] # b = t[1] # 变为generator的方法: # 只需将print(b)改为yield b def fib2(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return 'done' print(fib2(10)) print('------------------------------') for n in fib2(10): print(n) # 在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。
false
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
a68d1965b9ae8172a9f003b64770ff008ef12ce2
HLOverflow/school_stuffs
/Year2/Algorithm/mergesort.py
945
4.1875
4
# python 2 def mergesort(array): low = 0 high = len(array) - 1 mid = (low + high)/2 if (len(array)==1): return array else: array1 = mergesort(array[: mid+1]) array2 = mergesort(array[mid+1:]) return merge(array1, array2) def merge(array1,array2): #print array1, array2 i=j=k=0 sortedarray = [] while( i < len(array1) and j < len(array2) ): if array1[i] <= array2[j]: sortedarray.append(array1[i]) i += 1 k += 1 else: sortedarray.append(array2[j]) j += 1 k += 1 if (i >= len(array1)): sortedarray.extend(array2[j:]) elif (j >= len(array2)): sortedarray.extend(array1[i:]) #print sortedarray #print '='*10 return sortedarray; unsorted = [2,3,1,4,7,6] print "unsorted: ", unsorted print "sorted: ", mergesort(unsorted)
false
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
4c43fe88fa960ecf2c92d6e070827a7f9e275301
harshadak/fun-functions
/index.py
934
4.125
4
# Odd/Even: def odd_even(): for i in range(1, 2001): if i % 2 == 0: print "Number is {}. This is an even number.". format(i) else: print "Number is {}. This is an odd number.". format(i) odd_even() # Multiply: def multiply(arr,num): for x in range(len(arr)): print arr[x] arr[x] *= num return arr a = [2,4,10,16] b = multiply(a,5) print b # Multiply: #def multiply(arr, num): # for i in arr: # arr[i] = arr[i] * num # print arr # return arr # # # # #b = multiply([2,4,10,16], 5) #print b # Hacker Challenge: def layered_multiples(arr): # your code here new_array = [] for i in arr: temp_array = [] for j in range(0,i): temp_array.append(1) new_array.append(temp_array) return new_array x = layered_multiples(multiply([2,4,5],3)) print x # [6, 12, 15]
false
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
e1acadcbb37a8de7e990553ab34dbfe1ed6e0cf8
JollenWang/study
/python/python_prj/using_tuple.py
516
4.125
4
#!/usr/bin/python # Demo of using tuple zoo = ('wolf', 'elephant', 'tiger', 'monkey', 'eagle') new_zoo = ('horse', 'cat', zoo) print('Number of animals in the zoo is:', len(zoo)) print('Number of animals in the new zoo is:', len(new_zoo)) print('All animals in the new zoo are:', new_zoo) print('Animals brought from old zoo are:', new_zoo[2]) print('The last animal in the old zoo is:', new_zoo[2][4]) # Demo of print tuple name='Swaroop' age = 22 print('%s\'s age is %d years old' %(name, age))
false
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
d1cacc95f1e12d055c4b32b7a2beddda33860080
adebraine/Project-Euler-Fun-Pastime
/Q09.py
604
4.125
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 18 22:16:55 2018 @author: Adebraine """ """ A Pythagorean triplet is a set of three natural numbers, a<b<c, for which a^2+b^2=c^2 For example, 3^2+4^2=9+16=25=5^2. There exists exactly one Pythagorean triplet for which a+b+c=1000. Find the product abc. """ n = 1000 def trip(n): for i in range(1,n+1): for j in range(i,n): k = n - i - j if i**2 + j**2 == k**2: r1 = i r2 = j r3 = k return r1,r2,r3 r1,r2,r3 = trip(n) print(r1,r2,r3) print(r1*r2*r3)
false
1197259909b840cb2df84d79e1c6510fdee195cc
MiaZhang0/Learning
/QuestionTypes/demo56.py
512
4.21875
4
#将三个全英文字符串(比如,‘ok’,‘hello’,‘thank you’)分行打印,实现左对齐、右对齐和居中对齐效果 a = ['ok','hello','thank you'] #len_max为最长字符串的长度 len_max = max([len(item) for item in a]) for item in a: print('"%s"'%item.ljust((len_max))) print('------------------------------------') for item in a: print('"%s"'%item.rjust(len_max)) print('-------------------------------------') for item in a: print('"%s"'%item.center((len_max)))
false
300c20c47f79a629bcd3d42e7c293a304602ea10
MiaZhang0/Learning
/numpy_practice/demo01.py
719
4.15625
4
#利用numpy模块将列表转化为数组,并对数组进行运算 import numpy as np list = [[1,2,3],[4,5,6],[7,8,9]] #将二维列表转换成二维数组 array = np.array(list) print(array) #计算每一行的和,结果是3行1列的矩阵,瘦axis=1 sum = [] for row in range(3): sum.append(np.sum(array[row,:])) print(sum) sum1 = array.sum(axis=1) print(sum1) sum2 = np.sum(array,axis=1) print(sum2) #计算每一列的平均值,结果是1行3列的矩阵,胖axis=0 avg = [] for col in range(3): avg.append(np.mean(array[:,col])) print(avg) #avg是一个列表 print(type(avg)) #avg1是一个数组 avg1 = array.mean(axis=0) print(avg1) print(type(avg1)) avg2 = np.mean(array,axis=0) print(avg2)
false
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
ce795a7fd4bca9356b1181a677884e5320dc5e17
george39/hackpython
/funciones/calculadora.py
1,483
4.125
4
#!/usr/bin/env python #_*_ coding: utf8 _*_ def sumar(valor1, valor2): print("La suma es: {}".format(valor1 + valor2) ) def restar(valor1, valor2): print("La resta es: {}".format(valor1 - valor2) ) def dividir(valor1, valor2): print("La division es: {}".format(valor1 / valor2) ) def multiplicar(valor1, valor2): print("La multiplicacion es: {}".format(valor1 * valor2) ) def main(): while True: print("\nBienvenida\n") print("1: Suma dos numeros") print("2: Resta dos numeros") print("3: Divide dos numeros") print("4: Multiplica dos numeros") print("5: Salir") opcion = int(raw_input('Opcion: ')) if opcion == 1: valor1 = int(raw_input("Valor 1: ")) valor2 = int(raw_input("Valor 2: ")) sumar(valor1, valor2) if opcion == 2: valor1 = int(raw_input("Valor 1: ")) valor2 = int(raw_input("Valor 2: ")) restar(valor1, valor2) if opcion == 3: valor1 = int(raw_input("Valor 1: ")) valor2 = int(raw_input("Valor 2: ")) dividir(valor1, valor2) if opcion == 4: valor1 = int(raw_input("Valor 1: ")) valor2 = int(raw_input("Valor 2: ")) multiplicar(valor1, valor2) if opcion == 5: exit() if opcion > 5: print("\nOpcion invalida\n") if __name__ == '__main__': main()
false
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
862accd5cb643fdf7e89cbc0614144e2bd50abf0
Ayesha116/official.assigment
/grading.py
851
4.125
4
print(input("enter your name ")) a = int(input("Enter your physics marks ")) b = int(input("Enter your mathematics marks ")) c = int(input("Enter your english marks ")) d = int(input("Enter your chemistry marks ")) e = int(input("Enter your urdu marks ")) Total_marks = a + b + c + d + e percentage = (Total_marks/500)*100 if percentage >=80: print("your percentage is " + str(percentage)+" and Grade is A+") elif percentage >=70: print("your percentage is " + str(percentage)+" and Grade is A") elif percentage>=60: print("your percentage is " + str(percentage)+" and Grade is B") elif percentage >=50: print("your percentage is " + str(percentage)+" and Grade is C") elif percentage>=40: print("your percentage is " + str(percentage)+" and Grade is D") else: print("your percentage is " + str(percentage)+" and you are fail")
false
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
f48bbfb02624f2fc16d077b19eb87bae67a3203d
japablaza/python
/2018/exercises/string_find.py
352
4.28125
4
#!/usr/bin/python3 a = ("No tengo idea cuantos caracteres tienes esta oracion, esta, esta") print(a) if "idea" in a: print("Esa palabra existe") else: print("la palabra idea no se encuentra") print("Encuentra la posicion de la palabra -esta-: ") c = input() b = a.find("c") print("La palabra que buscas se encuentra en la posicion: " + str(b))
false
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
12c1a9be466a23ddedbaa35527e086a5bb0c9229
DragaDoncila/AssignmentOneCP1404
/DictionariesSetsPractice.py
1,495
4.1875
4
# contacts = {'bill': '353-1234', 'rich': '269-1234', 'jane': '352-1234'} # # print(contacts) # # print(contacts['bill']) # # print(contacts['jane']) # # contacts['barb'] = '271-1234' # # print(contacts) # # demo = {2: ['a', 'b', 'c'], (2,4): 27, 'x': {6: 2.5, 'a':3}} # # print(demo) # # print(demo[2]) # # print(demo[(2,4)]) # # print(demo['x']) # # print(demo[2][0]) #indexing a list means you index by position, indexing into a dict you index by key # print(len(demo)) # print(2 in demo) # print(1 in demo) # for key in demo: # print(key, end=" ") # for key in demo: # print('\n',key, demo[key]) # print(min(demo)) # my_dict = {'a': 2, 3: ['x', 'y'], 'joe': 'smith'} # for key, val in my_dict.items(): # print("Key: {:<7} Value: {}".format(key, val)) # # my_dict_values = my_dict.values() # print(my_dict_values) # for val in my_dict_values: # print(val, type(val)) word_list = ['the', 'black', 'and', 'the', 'black', 'the', 'and', 'black', 'and', 'and', 'and'] word_dict = {} for word in word_list: word_dict[word] = word_dict.get(word, 0) + 1 print(word_dict) last_biggest_val = 0 last_biggest_word = '' # for word in word_dict: # if word_dict[word] > last_biggest_val: # last_biggest_word = word # last_biggest_val = word_dict[word] # print(word_dict[last_biggest_word]) for word,frequency in word_dict.items(): if frequency > last_biggest_val: last_biggest_word = word last_biggest_val = frequency print(last_biggest_word)
false
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
43f65417df793810d673e87d36aea7fb4aae1e84
dlavareda/Inteligencia-Artificial
/Ficha 1/5.py
1,436
4.25
4
""" A biblioteca numpy é muito útil para processamento matemático de dados (tipo matlab). Para a podermos usar devemos fazer o seguinte import: import numpy as np Agora podemos criar, por exemplo, um array 7x3 (7 linhas e 3 colunas) inicializado a zero com: a = np.zeros([7,3]) Escreva um programa um programa que peça ao utilizador duas matrizes quadradas 2x2, A e B, e mostre no ecrã: (a) o produto elemento a elemento A.B (b) o produto matricial A ∗ B (c) a diferença entre matrizes A − B (d) o logaritmo dos elementos de A (se existirem elementos negativos, use o seu valor absoluto) (e) o maior valor da segunda linha de A vezes o menor valor da primeira coluna de B. """ import numpy as np def lerMatriz(): matriz = np.zeros([2, 2]) for i in range(2): for j in range(2): print("Posição " + str(i) + " x " + str(j)) matriz[i, j] = int(input()) return matriz """ (a) """ def produtoElementoaElementoMatriz(a, b): z = a * b return z """ (b) """ def diferencaMatriz(a, b): z = a - b return z """ (c) """ def multiplicacaoMatriz(a, b): z = a.dot(b) return z """ (d) """ def logMatriz(a): a = np.absolute(a) z = np.log(a) return z """ (e) """ def maiorXmenor(a,b): z = np.amax(matriz1, axis=1) z2 = np.amin(matriz2, axis=0) return z[1]* z2[0] matriz1 = lerMatriz() matriz2 = lerMatriz() print(maiorXmenor(matriz1, matriz2))
false
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
6458a883981897f05204794b775e85f223e3b818
alwinmreji/ROS-and-ML
/Assingment_#1/#5_factorial.py
269
4.125
4
######################################################## #Factorial of a number a = int(input("Enter the decimal number:\t")) mul = 1 for i in range(1,a+1): mul*= i print("Factorial of ",a,"is",mul) #OUTPUT: # Enter the decimal number: 5 # Factorial of 5 is 120
false
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
50c582d49f1918149df308d773d4a85172e47624
NBakulin/PythonStaff
/Lists/Lists.py
1,518
4.1875
4
class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None def push(self, node): node.next = self.head self.head = node def sortedPush(self, node): if self.head is None: self.head = node elif self.head.value < node.value: node.next = self.head self.head = node else: current = self.head while current.next is not None: if current.value > node.value > current.next.value: node.next = current.next current.next = node else: current = current.next if current.next is None and node.next is None: current.next = node def print(self): value_to_print = self.head while value_to_print: print(value_to_print.value, end="->") value_to_print = value_to_print.next list = LinkedList() new_node = Node(5) list.push(new_node) new_node = Node(7) list.push(new_node) new_node = Node(11) list.push(new_node) new_node = Node(13) list.push(new_node) new_node = Node(21) list.push(new_node) new_node = Node(30) list.push(new_node) new_node = Node(1) list.sortedPush(new_node) new_node = Node(15) list.sortedPush(new_node) new_node = Node(16) list.sortedPush(new_node) new_node = Node(2) list.sortedPush(new_node) print("Create Linked List") list.print()
false
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
f62481278b39b3fa0e048a5caa09331efed3a486
shubham3796/ML_Introductory
/tryExceptSmallestLargest.py
689
4.25
4
largest = None smallest = None list = [] while True: num = input("Enter a number: ") if num == "done" : break try: number = int(num) except: print("Invalid input") continue list.append(number) print(list) for n in list: if largest is None: largest = n elif largest < n: largest = n if smallest is None: smallest = n elif smallest > n: smallest = n print("Maximum is", largest) print("Minimum is", smallest) # https://www.coursera.org/learn/python-data/home/welcome # https://www.coursera.org/programs/capgemini-learning-program-71mtd?authProvider=capgemini
false
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
bc9a6559e9e47ffd6604a8b69e3336f42b7926d3
em55/Python-exercises
/five3.py
385
4.21875
4
import math def check_fermat(a,b,c,n): if n>2: if (math.pow(a,n)+math.pow(b,n)) == math.pow(c,n): return "Holy smokes, Fermat was wrong!" return "No, that doesn't work" def main(): a = int(raw_input("Enter value a: ")) b = int(raw_input("Enter value b: ")) c = int(raw_input("Enter value c: ")) n = int(raw_input("Enter value n: ")) print check_fermat(a,b,c,n) main()
false
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
06f38a305660d4b5f3193c6fccb41ee01810aaf8
godinenbicicleta/IntroComputation
/handlingExceptions/stringMethods.py
515
4.40625
4
# some useful string methods in python: s = 'hola bruno como estas - ' print('s = ',s) # counts how many times s1 occurs in s print('s.count("o") = ',s.count('o')) # returns index of first occurrence print('s.find("o") = ', s.find('o')) # same as find but from the right print('s.rfind("o") = ', s.rfind('o')) # print('s.lower() = ', s.lower()) print('s.replace("o","a") = ', s.replace('o','a')) #removes trailing white space print('s.strip() = ', s.strip()) # splits print('s.split("-") = ', s.split("-"))
false
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
1da2e6db32fd5cd7bf80126001b7c8a8031aa832
zhouxiongh/cookbook
/3_date-and-time/3.3.py
366
4.15625
4
""" 你需要将数字格式化后输出,并控制数字的位数、对齐、千位分隔符和其他的细节 """ if __name__ == "__main__": x = 1234.56789 print(format(x, '0.2f')) print(format(x, '>10.1f')) print(format(x, '<10.1f')) print(format(x, '^10.1f')) print(format(x, ',')) print(format(x, '0.2E')) print(format(x, 'e'))
false
a343e782ddd97f129d666740cc06495109f2fb0b
zhouxiongh/cookbook
/7_fun/7.7.py
864
4.3125
4
""" 你用 lambda 定义了一个匿名函数,并想在定义时捕获到某些变量的值。""" if __name__ == "__main__": x = 10 a = lambda y: x + y x = 20 b = lambda y: x + y print(a(10)) print(b(10)) # lambda 表达式中的 x 是一个自由变量,在运行时绑定值,而不是定义时就绑定 # 因此在调用这个 lambda 表达式的时候,x 的值是执行时的值 # 如果你想让某个匿名函数在定义时就捕获到值,可以将那个参数值定义成默认参数即可 x = 10 a = lambda y, x=x: x + y x = 20 b = lambda y, x=x: x + y print(a(10)) print(b(10)) # FAQ funcs = [lambda x: x+n for n in range(5)] for f in funcs: print(f(0)) # right way funcs = [lambda x, n=n: x+n for n in range(5)] for f in funcs: print(f(0))
false
be93040a2768146375a5f9e28063d5800a2ce225
zhouxiongh/cookbook
/3_date-and-time/3.12.py
589
4.28125
4
""" 你需要执行简单的时间转换,比如天到秒,小时到分钟等的转换。 """ if __name__ == "__main__": from datetime import timedelta, datetime a = timedelta(days=2, hours=6) b = timedelta(hours=4.5) c = a + b print(c.days) print(c.seconds) print(c.seconds / 3600) print(c.total_seconds() / 3600) a = datetime(2012, 9, 23) print(a + timedelta(days=10)) b = datetime(2012, 12, 21) print((b - a).days) now = datetime.today() print(now) # 在计算的时候,需要注意的是 datetime 会自动处理闰年
false
8e85ee56f90bdb0d623cf1cb772dc12fd42aae50
nicolecpeoples/python-basics
/strings.py
214
4.125
4
""" Built in functions .capitalize() .format() .lower() .upper() .swapcase() .find() .replace() """ first_name = "nicole" last_name = "peoples" print "Your name is {} {}".format(first_name, last_name).upper()
false
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