blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
f9b7c11118c0e2ccf65dab75f01d0cdb1001532a
nrglll/katasFromCodeWars
/string_example_pigLatin.py
1,052
4.375
4
# -*- coding: utf-8 -*- """ Created on Sat May 9 15:44:33 2020 @author: Nurgul Aygun """ # ============================================================================= # Kata explanation: # Move the first letter of each word to the end of it, then add "ay" to # the end of the word. Leave punctuation marks untouched. # # Examples # pig_it('Pig latin is cool') # igPay atinlay siay oolcay # pig_it('Hello world !') # elloHay orldway ! # ============================================================================= import string def pig_it(text): new_words = [] for w in text.split(): if w[::] not in string.punctuation: new_words += [w[1::] + w[0] + "ay"] else: new_words += w return " ".join(new_words) # ============================================================================= # print(pig_it('Panem et circenses')) # anemPay teay ircensescay # print(pig_it('Hello world !')) # elloHay orldway ! # =============================================================================
true
2fdb8c0b1434cf8ce72e7c6f6840166c8d72ffd5
azka97/practice1
/beginner/PrintInput.py
642
4.125
4
#input() will by default as String #basic math same as other language, which is +,-,/,* #exponent in python notated by '**' #There's '//' which is used for devided number but until how many times it will be reach the first number. Was called ' Integer Division' #Modulus operator notated by '%'. This is the remain number of some formula. example: 7 % 3 = 1 because 7/3= 6 with one remain number which is "1" or its called remainder #'type' for calling what type of a Variable is print('Pick a number :') num1 = input() print('Pick a number again :') num2 = input() print(type(num2)) Jumlah = int(num1)+int(num2) print(Jumlah)
true
b2a2f7598364273be0ca0a62e3339fe7cf4f2695
LalitGsk/Programming-Exercises
/Leetcode/July-Challenge/prisonAfterNDays.py
1,700
4.125
4
''' There are 8 prison cells in a row, and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. Otherwise, it becomes vacant. We describe the current state of the prison in the following way: cells[i] == 1 if the i-th cell is occupied, else cells[i] == 0. Given the initial state of the prison, return the state of the prison after N days (and N such changes described above.) Input: cells = [0,1,0,1,1,0,0,1], N = 7 Output: [0,0,1,1,0,0,0,0] Explanation: The following table summarizes the state of the prison on each day: Day 0: [0, 1, 0, 1, 1, 0, 0, 1] Day 1: [0, 1, 1, 0, 0, 0, 0, 0] Day 2: [0, 0, 0, 0, 1, 1, 1, 0] Day 3: [0, 1, 1, 0, 0, 1, 0, 0] Day 4: [0, 0, 0, 0, 0, 1, 0, 0] Day 5: [0, 1, 1, 1, 0, 1, 0, 0] Day 6: [0, 0, 1, 0, 1, 1, 0, 0] Day 7: [0, 0, 1, 1, 0, 0, 0, 0] ''' class Solution: def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]: _dict = {} self.cells = cells for i in range(N): s = str(self.cells) if s in _dict: loop_len = i- _dict[s] left_days = (N-i)%loop_len return self.prisonAfterNDays(self.cells, left_days) else: _dict[s] = i prev = self.cells[0] for j in range(1,7): curr, next = self.cells[j], self.cells[j+1] self.cells[j] = 1 - (prev^next) prev = curr self.cells[0], self.cells[7] = 0,0 return self.cells
true
5409e790168cb5f59ad3e1f4ef8dc63914cf2245
MadhanBathina/python
/odd even count of in between intigers of two numbers.py
519
4.21875
4
Start=int(input('Starting intiger :')) End=int(input('Ending intiger :')) if Start < 0 : print('1 ) The numbers lessthan 0 is not supposed to be count as either odd or even.') print('2 ) {0} to -1 are not considered as per the above statement.'.format(Start)) Start = 0 oddcount = 0 evencount= 0 for i in range (Start, End+1) : if i % 2 == 0 : evencount += 1 else : oddcount += 1 print ('evencount={0}.'.format(evencount)) print ('oddcount={0}.'.format(oddcount))
true
84b5d6b336751efd0e7f9a6bde1a8ad50e5631f2
RohiniRG/Daily-Coding
/Day39(Bit_diff).py
896
4.28125
4
# You are given two numbers A and B. # The task is to count the number of bits needed to be flipped to convert A to B. # Examples : # Input : a = 10, b = 20 # Output : 4 # Binary representation of a is 00001010 # Binary representation of b is 00010100 # We need to flip highlighted four bits in a # to make it b. # Input : a = 7, b = 10 # Output : 3 # Binary representation of a is 00000111 # Binary representation of b is 00001010 # We need to flip highlighted three bits in a # to make it b. # *************************************************************************************************** def countBitsFlip(a,b): ans = a ^ b count = 0 while ans: count += 1 ans &= (ans-1) return count one = int(input('Enter 1st number: ')) two = int(input('Enter 2nd number: ')) print('The number of bits to be flipped: ', countBitsFlip(one, two))
true
f35713a8ec7b2fbf0a0c957c023e74aa58cd55db
randyarbolaez/codesignal
/daily-challenges/swapCase.py
232
4.25
4
# Change the capitalization of all letters in a given string. def swapCase(text): originalLen = len(text) for i in text: if i.isupper(): text += i.lower() else: text += i.upper() return text[originalLen:]
true
89f316d8298d5ccbdbac841a9a6f3eea5d67d8e4
randyarbolaez/codesignal
/daily-challenges/CountDigits.py
259
4.1875
4
# Count the number of digits which appear in a string. def CountDigits(string): totalNumberOfDigits = 0 for letterOrNumber in string: if letterOrNumber.isnumeric(): totalNumberOfDigits += 1 else: continue return totalNumberOfDigits
true
d008f4f9d0f64f72bbda7be1909e5ae71f2cf1fc
Fittiboy/recursive_hanoi_solver
/recursive_hanoi.py
707
4.25
4
step = 0 def move(fr, to): global step step += 1 print(f"Step {step}:\tMove from {fr} to {to}") def hanoi(fr, to, via, n): if n == 0: pass else: hanoi(fr, via, to, n-1) move(fr, to) hanoi(via, to, fr, n-1) n = input("\n\nHow many layers does your tower of Hanoi have?\t") try: n = int(n) except: pass while type(n) is not int or n < 1: n = input("Please enter a positive number as the tower's height!\n\t") try: n = int(n) except: pass print("\nTo solve the tower in the least possible moves, follow these instructions:") input("(press Enter to start)\n") hanoi(1, 3, 2, n) print(f"\nCompleted in {step} steps.\n")
true
7aa978fad9e053f9d0541bb07585ba90027fcd6e
Digit4/django-course
/PYTHON_LEVEL_ONE/Part10_Simple_Game.py
2,536
4.21875
4
########################### ## PART 10: Simple Game ### ### --- CODEBREAKER --- ### ## --Nope--Close--Match-- ## ########################### # It's time to actually make a simple command line game so put together everything # you've learned so far about Python. The game goes like this: # 1. The computer will think of 3 digit number that has no repeating digits. # 2. You will then guess a 3 digit number # 3. The computer will then give back clues, the possible clues are: # # Close: You've guessed a correct number but in the wrong position # Match: You've guessed a correct number in the correct position # Nope: You haven't guess any of the numbers correctly # # 4. Based on these clues you will guess again until you break the code with a # perfect match! # There are a few things you will have to discover for yourself for this game! # Here are some useful hints: def num_len_check(x): if(x.isnumeric()): if (len(x) > 3): print("Oops! you've entered too many numbers, please try lesser numbers.") elif (len(x) < 3): print("You must enter at least 3 numbers, please try more numbers.") else: return False else: print("Please Enter numeric values only") return True def num_validity_converstion(num): if (num.isnumeric()): valid_nums = list(map(int, num)) return valid_nums def game_rules(actual_digits, guessed_digits): match, close, nope = 0, 0, 0 for i in guessed_digits: flag = False for j in actual_digits: if (j == i): if (guessed_digits.index(i) == actual_digits.index(j)): match += 1 flag = True break else: close += 1 flag = True break if (not flag): nope += 1 return [match,close,nope] # Try to figure out what this code is doing and how it might be useful to you import random digits = list(range(10)) random.shuffle(digits) print(digits[:3]) # Another hint: # Think about how you will compare the input to the random number, what format # should they be in? Maybe some sort of sequence? Watch the Lecture video for more hints! digits_matched = False while (not digits_matched): guess = input("What is your guess? ") print(guess) if (num_len_check(guess)): continue guessed_nums = num_validity_converstion(guess) clues_arr = game_rules(digits[:3], guessed_nums) if (clues_arr[0] == 3): digits_matched = True if (not digits_matched): print("Here's the result of your guess:") print ("Matches:%d\tClose:%d\t\tNope:%d\t" %(clues_arr[0],clues_arr[1],clues_arr[2])) else: print("Hooray!! YOU WIN!!")
true
d05dd4b1903d781d594e0b125266c3a58706382b
jon-moreno/learn-python
/ex3.py
769
4.34375
4
print "I will now count my chickens:" print "Hens", 25 + 30 / 6 print "Roosters", 100 - 25 * 3 % 4 print "Now I will count the eggs:" print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 print "Is it true that 3 + 2 < 5 - 7?" print 3 + 2 < 5 - 7 print "What is 3 + 2?", 3 + 2 print "What is 5 - 7?", 5 - 7 print "Oh that's why it's False." print "How about some more." print "Is it greater?", 5 > -2 print "Is it greater or equal?", 5 >= -2 print "Is it less or equal?", 5 <= -2 print "What does comma","do?" #comma separates different objects in a print statement that should be #printed on the same line, adding a space b/w objects #if you put a comma at end of print stmt, it will prevent a newline #Single and double quotes work the same until you need to delimit one
true
631922ad9ea661de547af2af1a1500fb5ec4c065
maahokgit/Python-Assignments
/Assigments/Assignment4/AManNamedJed/aManNamedJedi.py
2,037
4.28125
4
""" Student Name: Edward Ma Student ID: W0057568 Date: November 16, 2016 A Man Named Jedi Create a program that will read in a file and add line numbers to the beginning of each line. Along with the line numbers, the program will also pick a random line in the file and convert it to all capital letters. All other lines in the program will be converted to lowercase letters. The program will then write the resulting lines out to a second file and display the contents of each file on the console. """ import csv #use cool csv function bruh import random #to allow random number to be made! wooooooah! fileName = "AManNamedJed.txt" fileName2 = "AManNamedJed2.txt" #second file name accessMode = "r" #to read the file accessMode2 = "w" #to write the file print("***ORIGINAL TEXT***\n") with open(fileName, accessMode) as INPUT: #Read the file contents dataPlaceholder = csv.reader(INPUT) datalist = [] #a list with each line as value counter = 0 data = [] for row in dataPlaceholder: counter += 1 #add line number to the list! print(' '.join(row)) data = str(counter)+": "+str(' '.join(row)) datalist.append(data) randomLine = random.randint(0,(len(datalist))) #set random number to go as far as length of the list print("\n***NEW TEXT***\n") with open(fileName2, accessMode2) as OUTPUT: for counter in range(len(datalist)): if counter == randomLine: #IF the row is samn as random number, change it to uppercase #If not, make it lowercase OUTPUT.write(datalist[randomLine].upper()+str("\n")) else: OUTPUT.write(datalist[counter].lower()+str("\n")) with open(fileName2, accessMode) as SHOW: #Read new file, and print out what happened! #Read the file contents dataPlaceholder = csv.reader(SHOW) datalist1 = [] #a list with each line as value for row in dataPlaceholder: datalist1.append(row) for row in datalist1: print(' '.join(row))
true
55701fa458fc998a4d3fe5e38afec0808d36e88f
matthewlee1/Codewars
/create_phone_number.py
484
4.125
4
# Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number. #Example: # create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) # => returns "(123) 456-7890" def create_phone_number(n): f = "".join(map(str, n[:3])) s = "".join(map(str, n[3:6])) t = "".join(map(str, n[6:10])) return "({}) {}-{}".format(f,s,t) myNumber = [8,6,0,7,5,1,2,6,8,7] print(create_phone_number(myNumber))
true
9116283a58b98e8debeea1bb279fc1988d9e0f1a
Ahameed01/tdd_challenge
/weather.py
1,015
4.125
4
# Assume the attached file port-harcourt-weather.txt contains weather data for # Port Harcourt in 2016. Download this file and write a program that returns the # day number (column one) with the smallest temperature spread (the maximum # temperature is the second column, the minimum the third column). filename = "port-harcourt-weather.txt" def weatherReport(): with open(filename) as file: file.next() next(file) dayList = [] dailyTempSpread = [] for line in file: line.strip() splitted_line = line.split() try: dayListNum = int(splitted_line[0]) dailyHigh = int(splitted_line[1]) dailyLow = int(splitted_line[2]) except Exception as e: pass dailyTempSpread.append(dailyHigh - dailyLow) dayList.append(dayListNum) weatherDict = dict(zip(dayList, dailyTempSpread)) print weatherDict weatherReport()
true
225160859f926e7f08af188dbceb46c9c81a35b1
carrba/python-stuff
/pwsh2python/functions/ex1.py
369
4.125
4
#!/usr/bin/python3.6 def divide (numerator, denominator): myint = numerator // denominator myfraction = numerator % denominator if myfraction == 0: print("Answer is", myint) else: print("Answer is", myint, "remainder", myfraction) num = int(input("Enter the numerator ")) den = int(input("Enter the denominator ")) divide (num, den)
true
ca02219c4ec546314f18f7f2779f815833e13951
arohigupta/algorithms-interviews
/hs_interview_question.py
1,794
4.21875
4
# def say_hello(): # print 'Hello, World' # for i in xrange(5): # say_hello() # # Your previous Plain Text content is preserved below: # # This is just a simple shared plaintext pad, with no execution capabilities. # # When you know what language you'd like to use for your interview, # simply choose it from the dropdown in the top bar. # # You can also change the default language your pads are created with # in your account settings: https://coderpad.io/profile # # Enjoy your interview! # # # // Given a string of numbers between 1-9, write a function that prints out the count of consecutive numbers. # // For example, "1111111" would be read as "seven ones", thus giving an output of "71". Another string like "12221" would be result in "113211". # // "" -> "" def look_and_say(input): # split input # result_array # set counter to 1 i = 0 counter = 0 # num_arr = list(input) result = "" if input: current_char = input[0] # loop over num_arr while i < len(input): # if not num_arr[i] and not num_array[i+1]: # break # if num_arr[i] == num_arr[i+1] # counter += 1 if current_char == input[i]: counter += 1 # else # result_array.append(counter) # result_array.append(num_array[i] # counter = 1 else: # print "else" result = result + str(counter) + str(current_char) current_char = input[i] counter = 1 i += 1 result = result + str(counter) + str(current_char) else: result = "" return result print look_and_say("99992222888hhhhheeeelllloooo88833332222")
true
b687c97076dba795663606e9dc2c30408cf47d31
arohigupta/algorithms-interviews
/fizz_buzz_again.py
673
4.1875
4
#!/usr/bin/env python """fizz buzz program""" def fizz_buzz(fizz_num, buzz_num): """function to print out all numbers from 1 to 100 and replacing the numbers completely divisible by the fizz number by 'Fizz', the numbers completely divisible the buzz number by 'Buzz' and the numbers completely divisible by both by 'FizzBuzz' """ for i in range(1, 101): # loop to go from 1 included to 101 excluded if i % (fizz_num*buzz_num) == 0: print "FizzBuzz", elif i % fizz_num == 0: print "Fizz", elif i % buzz_num == 0: print "Buzz", else: print i, fizz_buzz(7, 5)
true
441329bf024a6db66f938d86543d361dba98d2b6
Moondance-NL/Moondance-NL
/ex1.py
792
4.5
4
print("I will now count my chickens:") # we are calulating the number of hens and roosters print("Hens", 25.0 + 30.0 /6.0) print("Roosters", 100 - 25 * 3 % 4) print("Now I will count the eggs:") # we are calculating the number of eggs print(3.0 + 2.0 + 1-5 + 4 % 2-1 / 4.0 + 6.0) # we are attemting to find the answer print("Is it true that 3 + 2 < 5 - 7?") # we are doing a calc to get at the truth print(3 + 2 < 5 - 7) # doing the math print("what is 5 -7?", 5 - 7) # and more math print("Oh, that's why it's false.") #eurika! print ("How about some more.") #what do you think? print("Is it greater?", 5 > -2) #getting to the heart of the matter print("Is it greater or equal", 5 >= -2) #discovering the real real print("Is it less or equal?", 5 <= -2) #maybe not
true
4733713d4de3ca0f91ff841167162ff8f963c445
chuymedina96/coding_dojo
/chicago_codes_bootcamp/chicago_codes_python/python_stack/python/fundamentals/practice_strings.py
2,028
4.78125
5
print ("Hello world") #Concatentaing strings and variables with the print function. # multiple ways to print a string containing data from variables. name = "zen" print("My name is,", name) name = "zen" print("My name is " + name) #F-strings (Literal String Interpolation) first_name = "zen" last_name = "Coder" age = 27 print(f"My name is {first_name} {last_name} and I am {age} years old.") #this is the new way to do it :) first_name = "Chuy" last_name = "Medina" age = 23 food = "sushi" print(f"Hello, my first name is {first_name} and my last name is {last_name}, and also my current age is {age}. I also really enjoy {food}, but I ain't trying to get Mercury poisoning though") # String.format() method. first_name = "Zen" last_name = "Coder" age = 27 print("My name is {} {} and I am {} years old.".format(first_name, last_name, age)) #putting in variables in the order in which they should fill the brackets. # output: My name is Zen Coder and I am 27 years old. print("My name is {} {} and I am {} years old.".format(age, first_name, last_name)) # output: My name is 27 Zen and I am Coder years old. name = "Jesus Medina" food = "pizza and sushi" print("Hello, I really like {} and my name is {}".format(food, name)) # This is an even older way of string interpolation. # Rather than curly braces, the % symbol is used to indicate a placeholder, a %s for a string and %d for a number. After the string, a single % separates the string to be interpolated from the values to be inserted into the string, like so: hw = "Hello %s" % "world" # with literal values py = "I love Python %d" % 3 print(hw, py) # output: Hello world I love Python 3 name = "Zen" age = 27 print("My name is %s and I'm %d" % (name, age)) # or with variables # output: My name is Zen and I'm 27 # Built-In String Methods # We've seen the format method, but there are several more methods that we can run on a string. Here's how to use them: x = "hello world" print(x.title()) # this is so weird # output: "Hello World"
true
aa9eb750a1e0c98949015dd27e7d2c5ff2805a75
MrFichter/RaspSort1
/main.py
947
4.375
4
#! /usr/bin/python #sort a file full of film names #define a function that will return the year a film was made #split the right side of the line a the first "(" def filmYear(film): return film.rsplit ('(',1)[1] #load the file into a list in Python memory #and then close the file because the content is now in memory with open ("filmList.txt", "r") as file: filmList = file.read().splitlines() #sort by name using library function ##Me: This is one way to sort. filmList.sort() #sort by year using key to library function - the film list #must end with a year in the format (NNNN) filmList.sort(key=filmYear) ##Me: This is another way to sort. ##'key =' expects a function. Many times, people use lambda ##notation to quickly create a function. The function is called ##'exactly once for each input record.' wiki.python.org/moin/HowTo/Sorting ##More on lambda notation: htt://tinyurl.com/pylambda for film in filmList: print (film)
true
df80aedb4695956eb49f9be9b4954eaa246f951e
PeaWarrior/learn-py
/ex_07/ex_07_02.py
914
4.28125
4
# Exercise 2: Write a program to prompt for a file name, and then read through the file and look for lines of the form: # X-DSPAM-Confidence: 0.8475 # When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart the line to extract the floating-point number on the line. Count these lines and then compute the total of the spam confidence values from these lines. When you reach the end of the file, print out the average spam confidence. # Enter the file name: mbox.txt # Average spam confidence: 0.894128046745 # Enter the file name: mbox-short.txt # Average spam confidence: 0.750718518519 fileHandle = open(input('Enter the file name: ')) sum = 0 count = 0 for line in fileHandle : if 'X-DSPAM-Confidence:' in line : firstSpaceInLine = line.find(' ') sum = sum + float(line[firstSpaceInLine + 1 : ].rstrip()) count = count + 1 print('Average spam confidence:', sum/count)
true
469b980fe77547f9eb561ce3f32765d59fe955b7
PeaWarrior/learn-py
/ex_12/ex_12_04.py
716
4.125
4
# Exercise 4: Change the urllinks.py program to extract and count paragraph (p) tags from the retrieved HTML document and display the count of the paragraphs as the output of your program. Do not display the paragraph text, only count them. Test your program on several small web pages as well as some larger web pages. # http://dr-chuck.com/dr-chuck/resume/bio.htm from urllib.request import urlopen from bs4 import BeautifulSoup import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter URL: ') html = urlopen(url, context=ctx) soup = BeautifulSoup(html, 'html.parser') print('Number of p tags:', len(soup('p')))
true
066da0f2759113dc0b1289705f92311fe6abb01e
JamieJ12/Team-23
/Functions/Function_6.py
2,655
4.15625
4
def word_splitter(df): """ The function splits the sentences in a dataframe's column into a list of the separate words.: Arguments: The variable 'df' is the pandas input. Returns: df with the added column named 'Splits Tweets' Example: Prerequites: >>> twitter_url = 'https://raw.githubusercontent.com/Explore-AI/Public-Data/master/Data/twitter_nov_2019.csv' >>> twitter_df = pd.read_csv(twitter_url) Inputs: >>>twitter_df.copy().head() Tweets Date 0 @BongaDlulane Please send an email to mediades... 2019-11-29 12:50:54 1 @saucy_mamiie Pls log a call on 0860037566 2019-11-29 12:46:53 2 @BongaDlulane Query escalated to media desk. 2019-11-29 12:46:10 3 Before leaving the office this afternoon, head... 2019-11-29 12:33:36 4 #ESKOMFREESTATE #MEDIASTATEMENT : ESKOM SUSPEN... 2019-11-29 12:17:43 >>>word_splitter(twitter_df.copy()) Output Tweets Date Split Tweets 0 @BongaDlulane Please send an email to mediades... 2019-11-29 12:50:54 [@bongadlulane, please, send, an, email, to, m... 1 @saucy_mamiie Pls log a call on 0860037566 2019-11-29 12:46:53 [@saucy_mamiie, pls, log, a, call, on, 0860037... 2 @BongaDlulane Query escalated to media desk. 2019-11-29 12:46:10 [@bongadlulane, query, escalated, to, media, d... 3 Before leaving the office this afternoon, head... 2019-11-29 12:33:36 [before, leaving, the, office, this, afternoon... 4 #ESKOMFREESTATE #MEDIASTATEMENT : ESKOM SUSPEN... 2019-11-29 12:17:43 [#eskomfreestate, #mediastatement, :, eskom, s... ... ... ... ... 195 Eskom's Visitors Centres’ facilities include i... 2019-11-20 10:29:07 [eskom's, visitors, centres’, facilities, incl... 196 #Eskom connected 400 houses and in the process... 2019-11-20 10:25:20 [#eskom, connected, 400, houses, and, in, the,... 197 @ArthurGodbeer Is the power restored as yet? 2019-11-20 10:07:59 [@arthurgodbeer, is, the, power, restored, as,... 198 @MuthambiPaulina @SABCNewsOnline @IOL @eNCA @e... 2019-11-20 10:07:41 [@muthambipaulina, @sabcnewsonline, @iol, @enc... 199 RT @GP_DHS: The @GautengProvince made a commit... 2019-11-20 10:00:09 [rt, @gp_dhs:, the, @gautengprovince, made, a,... """ # Get Tweets from DataFrame tweets = df["Tweets"].to_list() # Split the Tweets into lowercase words split_tweets = [tweet.lower().split() for tweet in tweets] # Add Split Tweets to own column df["Split Tweets"] = split_tweets return df
true
4617883396bfe24d19ab40f77451291f088721ec
yuanxu-li/careercup
/chapter6-math-and-logic-puzzles/6.8.py
1,714
4.28125
4
# 6.8 The Egg Drop Problem: There is a building of 100 floors. If an egg drops # from the Nth floor or above, it will break. If it's dropped from any floor # below, it will not break. You're given two eggs. Find N, while minimizing the # number of drops for the worst case. # Here I denote floors from 0 to 99 import random import math import pdb def brute_force(): n = random.randint(0, 100) for i in range(100): if i == n: return i drops = 0 break_floor = 20 def drop(floor): global drops drops += 1 return floor >= break_floor def find_breaking_floor(k): """ When we use egg1, we could skip floors each time and reduce the range, like when we drop egg1 from 10th floor it is Ok, but broken from 20th floor, then we should search from 11th floor through 19th floor using egg2. Because egg2 is our last choice, we should use the safest linear search. Then how should we minimize the total number of drops for the worst case? The idea to keep drops(egg1) + drops(egg2) steady, meaning to keep the worst case almost the same as the best case. Then each time we drop egg1 one more time adding drop(egg1) by 1, we should reduce the increment by 1 thus reducing drop(egg2) by 1. >>> find_breaking_floor(30) 30 >>> find_breaking_floor(50) 50 >>> find_breaking_floor(70) 70 """ global break_floor global drops break_floor = k interval = 14 previous = 0 egg1 = interval drops += 1 # drop egg1 while not drop(egg1) and egg1 <= 100: interval -= 1 previous = egg1 egg1 += interval # drop egg2 egg2 = previous + 1 while egg2 < egg1 and egg2 <= 100 and not drop(egg2): egg2 += 1 return -1 if egg2 > 100 else egg2 if __name__ == "__main__": import doctest doctest.testmod()
true
89b2cab05c4ecf1a2a10c60fa306ef7f8ea79bed
yuanxu-li/careercup
/chapter16-moderate/16.24.py
845
4.15625
4
# 16.24 Pairs with Sum: Design an algorithm to find all pairs of integers within # an array which sum to a specified value. from collections import Counter def pairs_with_sum(arr, k): """ put all elements into a Counter (similar to a dict), for each value, search for the complementary value >>> pairs_with_sum([1, 2, 3, 1, 5, 3, 4, 9, 4, 6, 2, 2, 2, 2], 4) [[1, 3], [1, 3], [2, 2], [2, 2]] """ c = Counter(arr) result = [] while c: value1, count1 = c.popitem() # the value matches itself if k - value1 == value1: for _ in range(count1 // 2): result.append([value1, value1]) # find matching value count2 = c.pop(k - value1, None) if count2 is None: continue for _ in range(min(count1, count2)): result.append([value1, k - value1]) return result if __name__ == "__main__": import doctest doctest.testmod()
true
3bf4269c79a0b223fad38ae3a178a5e7c5212fe2
yuanxu-li/careercup
/chapter10-sorting-and-searching/10.2.py
966
4.46875
4
# 10.2 Group Anagrams: Write a method to sort an array of strings so that all the anagrams are # next to each other. from collections import defaultdict def group_anagrams(strings): """ create a dict to map from a sorted string to a list of the original strings, then simply all strings mapped by the same key will be grouped together. If the length of string are considered constant, time complexity is only O(n), since we only have to loop over the array twice, first time to generate the dict, second time to loop over the keys to group anagrams mapped by the same key >>> group_anagrams(["asd", "atr", "tar", "pppp", "dsa", "rta", "eryvdf"]) ['atr', 'tar', 'rta', 'asd', 'dsa', 'pppp', 'eryvdf'] """ d = defaultdict(list) for s in strings: sorted_s = "".join(sorted(s)) d[sorted_s].append(s) new_strings = [] for sorted_s in d: new_strings.extend(d[sorted_s]) return new_strings if __name__ == "__main__": import doctest doctest.testmod()
true
7837501cf9c4e8589734f09883875d0fff5c2062
yuanxu-li/careercup
/chapter8-recursion-and-dynamic-programming/8.4.py
1,436
4.25
4
# 8.4 Power Set: Write a method to return all subsets of a set. def power_set(s, memo=None): """ For a set, each we add it to the final list, and run the algorithm against its one-item-less subset >>> power_set(set([1,2,3,4,5])) [{1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5}, set(), {4}, {3, 5}, {3}, {3, 4}, {2, 4, 5}, {2, 5}, {2}, {2, 4}, {2, 3, 5}, {2, 3}, {2, 3, 4}, {1, 3, 4, 5}, {1, 4, 5}, {1, 5}, {1}, {1, 4}, {1, 3, 5}, {1, 3}, {1, 3, 4}, {1, 2, 4, 5}, {1, 2, 5}, {1, 2}, {1, 2, 4}, {1, 2, 3, 5}, {1, 2, 3}, {1, 2, 3, 4}] """ returned = False if memo is None: memo = [] returned = True if s not in memo: memo.append(s) for elem in s: power_set(s - set([elem]), memo) if returned == True: return memo def power_set_updated(s): """ Actually the previous method is a top-down approach, and now let's consider a bottom-up approach. Since it is bottom-up, we do not have to worry about the duplicated cases and thus can ignore memo. We start from when set size is 0, 1, 2, up to n. >>> power_set_updated(set([1,2,3,4,5])) """ # base case if len(s) == 0: return [set()] # recursive case item = s.pop() all_subsets = power_set_updated(s) more_subsets = [] for subset in all_subsets: new_subset = subset.copy() new_subset.add(item) more_subsets.append(new_subset) all_subsets.extend(more_subsets) return all_subsets if __name__ == "__main__": import doctest doctest.testmod()
true
858dd659ac6bb2648fca973c6695abcdccddd951
yuanxu-li/careercup
/chapter5-bit-manipulation/5.8.py
1,585
4.28125
4
# 5.8 Draw Line: A monochrome screen is stored as a single array of bytes, allowing eight consecutive pixels # to be stored in one byte. The screen has width w, where w is divisible by 8 (that is, no byte will be split # across rows). The height of the screen, of course, can be derived from the length of the array and the width. # Implement a function that draws a horizontal line from (x1, y) to (x2, y). # The method signature should look something like: # drawLine(byte[] screen, int width, int x1, int x2, int y) import pdb def draw_line(screen, width, x1, x2, y): """ find the indices of x1 and x2, fix the bytes of x1 and x2 and in between. >>> screen = [0, 0, 0, 0, 0, 0, 0, 0, 0] >>> draw_line(screen, 24, 4, 22, 1) >>> screen[3] 15 >>> screen[4] 255 >>> screen[5] 254 """ if width % 8 != 0: raise Exception("width is not multiple of 8!") x1_ind = y * (width // 8) + x1 // 8 x1_offset = x1 % 8 x2_ind = y * (width // 8) + x2 // 8 x2_offset = x2 % 8 # fix the bytes between x1 and x2 for ind in range(x1_ind + 1, x2_ind): screen[ind] = 255 # if x1 and x2 are in different bytes if x1_ind != x2_ind: # fix the byte of x1 mask = (1 << (8 - x1_offset)) - 1 screen[x1_ind] |= mask # fix the byte of x2 mask = (1 << (x2_offset + 1)) - 1 mask <<= (8 - x2_offset - 1) screen[x2_ind] |= mask # if x1 and x2 are in the same byte else: mask1 = (1 << (8 - x1_offset)) - 1 mask2 = (1 << (x2_offset + 1)) - 1 mask2 <<= (8 - x2_offset - 1) screen[x1_ind] |= (mask1 & mask2) if __name__ == "__main__": import doctest doctest.testmod()
true
81a90ce343ff4d49098ada9f12429821aed4e57b
yuanxu-li/careercup
/chapter16-moderate/16.16.py
1,330
4.125
4
# 16.16 Sub Sort: Given an array of integers, write a method to find inices m and n such # that if you sorted elements m through n, the entire array would be sorted. Minimize n - m # (that is, find the smallest such sequence). # EXAMPLE # Input: 1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19 # Output: (3, 9) import pdb def sub_sort_brute_force(arr): """ In this method, we simply sort the array, and find the part of the sorted array where it is different from the original array. Time Complexity: 1. sorting the array takes O(nlogn) 2. searching from the beginning and end of the array takes O(n) >>> sub_sort_brute_force([1, 2, 3, 4, 5, 6, 7]) (0, 0) >>> sub_sort_brute_force([1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19]) (3, 9) """ sorted_arr = sorted(arr) # search from the beginning to find m, where it starts to differ from the original array m = 0 while m < len(arr): if sorted_arr[m] != arr[m]: break m += 1 # if the sorted array is identical to the original array, which means the original array is already sorted if m == len(arr): return (0, 0) # search from the end to find n, where it starts to differ from the original array n = len(arr) - 1 while n > m: if sorted_arr[n] != arr[n]: break n -= 1 return (m, n) if __name__ == "__main__": import doctest doctest.testmod()
true
b49ddf7666de93c2f767510cc8354e4e556009cb
yuanxu-li/careercup
/chapter8-recursion-and-dynamic-programming/8.10.py
1,215
4.1875
4
# 8.10 Paint Fill: Implement the "paint fill" function that one might see on many image editing programs. # That is, given a screen (represented by a two-dimensional array of colors), a point, and a new color, # fill in the surrounding area until the color changes from the original color. def paint_fill(array, row, col, new_color, old_color=None): """ >>> array = [[0, 0, 0, 0], [0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1]] >>> paint_fill(array, 1, 3, 9) True >>> array [[9, 9, 9, 9], [9, 9, 9, 9], [1, 1, 1, 1], [1, 1, 1, 1]] """ # alternative for initial call if old_color is None: old_color = array[row][col] # if the point is off limit if row < 0 or row >= len(array) or col < 0 or col >= len(array[0]): return False # if arrives at the border of old color if array[row][col] != old_color: return True # change the color of this point, and recursively change its neighbors array[row][col] = new_color paint_fill(array, row+1, col, new_color, old_color) paint_fill(array, row, col+1, new_color, old_color) paint_fill(array, row-1, col, new_color, old_color) paint_fill(array, row, col-1, new_color, old_color) return True if __name__ == "__main__": import doctest doctest.testmod()
true
d62dee378aee2ad5621da0821e3d26bb801e741b
yuanxu-li/careercup
/chapter4-trees-and-graphs/4.3.py
1,264
4.125
4
# 4.3 List of Depths: Given a binary tree, design an algorithm which creates a linked list of all the # nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists) from collections import deque class Node: def __init__(self): self.left = None self.right = None def list_of_depths(self): """ >>> n0 = Node() >>> n1 = Node() >>> n2 = Node() >>> n3 = Node() >>> n4 = Node() >>> n5 = Node() >>> n6 = Node() >>> n7 = Node() >>> n0.left = n1 >>> n0.right = n2 >>> n1.left = n3 >>> n1.right = n4 >>> n2.left = n5 >>> n2.right = n6 >>> n3.left = n7 >>> l = n0.list_of_depths() >>> len(l[0]) 1 >>> len(l[1]) 2 >>> len(l[2]) 4 >>> len(l[3]) 1 """ depth_lists = [[self]] queue = deque() queue.appendleft(self) while queue: temp_list = [] # for a specific depth while queue: node = queue.pop() if node.left: temp_list.append(node.left) if node.right: temp_list.append(node.right) # if this depth still has nodes if len(temp_list) > 0: # store the list of the depth depth_lists.append(temp_list) for node in temp_list: queue.appendleft(node) return depth_lists if __name__ == "__main__": import doctest doctest.testmod()
true
905d3e94a6e6ab1bcd68bd26b6839baf5b178bd4
yuanxu-li/careercup
/chapter1-arrays-and-strings/1.7.py
1,623
4.34375
4
# 1.7 Rotate Matrix: Given an image represented by an N*N matrix, where each pixel in the image is 4 bytes, write a method to rotate # the image by 90 degrees. Can you do this in place? def rotate_matrix(matrix): """ Take a matrix (list of lists), and rotate the matrix clockwise >>> rotate_matrix([[1,2,3],[4,5,6],[7,8,9]]) [[7, 4, 1], [8, 5, 2], [9, 6, 3]] >>> rotate_matrix([]) [] """ length = len(matrix) # first, flip along the main diagonal for i in range(length): for j in range(i+1, length): # swap two elements matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # second, flip left and right for i in range(length): for j in range(int(length/2)): # swap two elements matrix[i][j], matrix[i][length-1-j] = matrix[i][length-1-j], matrix[i][j] return matrix def rotate_matrix_modified(matrix): """ Rotate a matrix with a layer-by-layer approach >>> rotate_matrix_modified([[1,2,3],[4,5,6],[7,8,9]]) [[7, 4, 1], [8, 5, 2], [9, 6, 3]] >>> rotate_matrix_modified([]) [] """ length = len(matrix) for layer in range(int(length / 2)): for i in range(length - 1 - layer): # left, top, right, bottom <- bottom, left, top, right offset = layer + i matrix[length - 1 - offset][layer],\ matrix[layer][offset],\ matrix[offset][length - 1 - layer],\ matrix[length - 1 - layer][length - 1 - offset]\ =\ matrix[length - 1 - layer][length - 1 - offset],\ matrix[length - 1 - offset][layer],\ matrix[layer][offset],\ matrix[offset][length - 1 - layer] return matrix def main(): import doctest doctest.testmod() if __name__ == "__main__": main()
true
0db6f0e7aaf5666e4b839fc40d977672988b32cd
yuanxu-li/careercup
/chapter10-sorting-and-searching/10.4.py
1,487
4.15625
4
# 10.4 Sorted Search, No size: You are given an array-like data structure Listy which lacks a size method. It does, however, # have an elementAt(i) method that returns the element at index i in O(1) time. If i is beyond the bounds of the data structure, # it returns -1. (For this reason, the data structure only supports positive integers.) Given a Listy which contains sorted, # positive integers, find the index at which an element x occurs. If x occurs multiple times, you may return any index. def find_index(arr, x): """ The naive approach is O(n) by searching through the entire array. A better approach would be using binary search, but one problem remains: we do not know the array length. Therefore we split this problem into two steps: 1. find the length n in O(logn) time, by increasing n from 1, to 2, 4, 8 until element_at returns -1 which means it is out of bound 2. apply binary search to this array in O(logn) >>> find_index([1,2,5,7,9,10], 9) 4 >>> find_index([1,2,5,7,9,10], 3) -1 """ # find the length n = 1 while element_at(arr, n) != -1: n *= 2 # binary search low = 0 high = n - 1 while low <= high: mid = (low + high) // 2 mid_value = element_at(arr, mid) if mid_value == x: return mid elif mid_value > x or mid_value == -1: high = mid - 1 else: low = mid + 1 return -1 def element_at(arr, i): if i in range(len(arr)): return arr[i] else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
true
7c0e1d9a77cfb59763f5067ce087deb67eeb2181
w4jbm/Python-Programs
/primetest.py
1,018
4.125
4
#!/usr/bin/python3 # Based on code originally by Will Ness: # https://stackoverflow.com/questions/2211990/how-to-implement-an-efficient-infinite-generator-of-prime-numbers-in-python/10733621#10733621 # # and updated by Tim Peters. # # https://stackoverflow.com/questions/2211990/how-to-implement-an-efficient-infinite-generator-of-prime-numbers-in-python/10733621#10733621 # def psieve(): import itertools yield from (2, 3, 5, 7) D = {} ps = psieve() next(ps) p = next(ps) assert p == 3 psq = p*p for i in itertools.count(9, 2): if i in D: # composite step = D.pop(i) elif i < psq: # prime yield i continue else: # composite, = p*p assert i == psq step = 2*p p = next(ps) psq = p*p i += step while i in D: i += step D[i] = step # Driver code to check above generator function for value in psieve(): print(value)
true
d2dcd6ce2a0e54b4c95acca0dafb9d3aa95c8920
lxw0109/JavaPractice
/Sort/Bubble/pBubble.py
1,235
4.21875
4
#!/usr/bin/python2.7 #File: pBubble.py #Author: lxw #Time: 2014-09-19 #Usage: Bubble sort in Python. import sys def bubbleSort(array): bound = len(array) - 1 while 1: i = 0 tempBound = 0 swap = False while i < bound: if array[i] > array[i+1]: array[i], array[i+1] = array[i+1], array[i] tempBound = i swap = True i += 1 if swap: bound = tempBound else: break def main(): print("---------------------------------------------") print("| Usage: Program ArrayLength |") print("| If no ArrayLength offered, 5 is default. |") print("---------------------------------------------\n") arrSize = 5 argc = len(sys.argv) if argc == 2: arrSize = int(sys.argv[1]) elif argc != 1: sys.exit("Too much parameters.") numbers = [] print("Input {} numbers:(each line with only 1 number) ".format(arrSize)) for i in range(arrSize): number = input() numbers.append(number) bubbleSort(numbers) print(numbers) if __name__ == '__main__': main() else: print("Being imported as a module.")
true
b06883d59473eb92521e61b581674978f79755f5
TylorAtwood/Hi-Lo-Game
/Hi_Lo_Game.py
1,455
4.34375
4
#!/usr/bin/env python3 #Tylor Atwood #Hi-Lo Game #4/14/20 #This is a def to inlcude the guessing game. def game(): #Immport random library import random #Declare varibles. Such as max number, generated random number, and user's number guess max = int(input("What should the maximum number for this game be?: ")) print("\n") num = random.randint(1,max) guess = int(input("Guess my number: ")) #While loop for guessing number while guess != num: if guess > num: print("Your guess is too high") #Number is higher than generated random number print("\n") guess = int(input("Guess my number: ")) if guess < num: print("Your guess is too low")#Number is lower than generated random number print("\n") guess = int(input("Guess my number: ")) if guess == num: print("You guessed my number!") #User guess the number right print("\n") restart = input("Do you wish to play again? (Y/N)") #Asking the user to restart guessing game. This is why I declared the game as a def. if restart == "Y": game() #restarts game. Goes back to the top of the program. else: print("Thanks for playing!") #If the user does not want to restart. It ends the program exit #Exits program game()
true
14703a10efdf73974802db15a4d644aa7b9854ea
Garima2997/All_Exercise_Projects
/PrintPattern/pattern.py
327
4.125
4
n = int(input("Enter the number of rows:")) boolean = input("Enter True or False:") if bool: for i in range(0, n): for j in range(i + 1): print("*", end=" ") print("") else: for i in range(n, 0, -1): for j in range(i): print("*", end=" ") print("")
true
2587f2a265238875e932ffcbaaa1b028abbf7929
Jakksan/Intro-to-Programming-Labs
/Lab8 - neighborhood/pythonDrawingANeighborhood/testingShapes.py
1,890
4.15625
4
from turtle import * import math import time def drawTriangle(x, y, tri_base, tri_height, color): # Calculate all the measurements and angles needed to draw the triangle side_length = math.sqrt((0.5*tri_base)**2 + tri_height**2) base_angle = math.degrees(math.atan(tri_height/(tri_base/2))) top_angle = 180 - (2 * base_angle) # Lift pen to prevent stray lines penup() # Go to some x and y coordinates goto(x, y) setheading(0) # Fill the triangle with some color fillcolor(color) begin_fill() pendown() # Draw the triangle forward(tri_base) left(180 - base_angle) forward(side_length) left(180 - top_angle) forward(side_length) # Stop filling and lift pen end_fill() penup() def drawRectangle(x, y, rec_width, rect_height, color): # Lift pen to prevent stray lines penup() # Go to some x and y coordinates goto(x, y) setheading(0) # Set fill color, put pen back onto canvas pendown() fillcolor(color) begin_fill() # Draw the rectangle for side in range(2): forward(rec_width) left(90) forward(rect_height) left(90) # Stop filling and lift pen end_fill() penup() def drawCircle(x, y, radius, color): # Lift pen to prevent stray lines penup() # Go to some x and y coordinates goto(x, y) setheading(0) setpos(x, (y-radius)) # Put pen down, then start filling pendown() fillcolor(color) begin_fill() # Draw the circle circle(radius) # Stop filling and lift pen end_fill() penup() # drawTriangle(60, 60, 25, 40, "blue") # drawTriangle(100, -100, 70, 20, "pink") # # drawRectangle(60, -60, 60, 40, "yellow") # drawRectangle(-100, 100, 25, 60, "green") # # drawCircle(-60, 60, 15, "green") # drawCircle(150, 120, 30, "purple") input()
true
8d6fb45b0bc9753d718e558815a6e70178db88fd
Vasilic-Maxim/LeetCode-Problems
/problems/494. Target Sum/3 - DFS + Memoization.py
1,041
4.1875
4
class Solution: """ Unlike first approach memoization can make the program significantly faster then. The idea is to store results of computing the path sum for each level in some data structure and if there is another path with the same sum for specific level than we already knew the number of paths which will match the target value. That phenomena appears only if one value is repeated several times in 'nums' list. """ def findTargetSumWays(self, nums: list, target: int) -> int: return self.calculate(nums, target, 0, 0, {}) def calculate(self, nums: list, target: int, val: int, lvl: int, memo: dict) -> int: if lvl >= len(nums): return int(val == target) key = f"{lvl}-{val}" if key in memo: return memo[key] left_sum = self.calculate(nums, target, val - nums[lvl], lvl + 1, memo) right_sum = self.calculate(nums, target, val + nums[lvl], lvl + 1, memo) memo[key] = left_sum + right_sum return memo[key]
true
5fa3c31eda3e66eeb0fb0de5b7d11f90b03eea6e
notsoseamless/python_training
/algorithmic_thinking/Coding_activities/alg_further_plotting_solution.py
1,138
4.15625
4
""" Soluton for "Plotting a distribution" for Further activities Desktop solution using matplotlib """ import random import matplotlib.pyplot as plt def plot_dice_rolls(nrolls): """ Plot the distribution of the sum of two dice when they are rolled nrolls times. Arguments: nrolls - the number of times to roll the pair of dice Returns: Nothing """ # initialize things rolls = {} possible_rolls = range(2, 13) for roll in possible_rolls: rolls[roll] = 0 # perform nrolls trials for _ in range(nrolls): roll = random.randrange(1, 7) + random.randrange(1, 7) rolls[roll] += 1 # Normalize the distribution to sum to one roll_distribution = [rolls[roll] / float(nrolls) for roll in possible_rolls] # Plot the distribution with nice labels plt.plot(possible_rolls, roll_distribution, "bo") plt.xlabel("Possible rolls") plt.ylabel("Fraction of rolls") plt.title("Distribution of rolls for two six-sided dice") plt.show() plot_dice_rolls(10000)
true
c2a0a60091658bb900d0fcf3c629c3f284288fa5
dennisjameslyons/magic_numbers
/15.py
882
4.125
4
import random #assigns a random number between 1 and 10 to the variable "magic_number" magic_number = random.randint(1, 10) def smaller_or_larger(): while True: try: x = (int(input("enter a number please: "))) # y = int(x) except ValueError: print("Ever so sorry but I'm going to need a number.") continue else: break if x < magic_number: print("guess too small. guess some more.") return smaller_or_larger() elif x > 10: print("make sure your guess is smaller than 11.") return smaller_or_larger() elif x > magic_number: print("guess too great. try again, you'll get it.") return smaller_or_larger() else: print("Cherrio, you've done it, the magic number is yours! ") print(magic_number) smaller_or_larger()
true
779abded16b15cb8eb80fe3dc0ed36309b9cec59
MFahey0706/LocalMisc
/N_ary.py
1,399
4.1875
4
# --------------- # User Instructions # # Write a function, n_ary(f), that takes a binary function (a function # that takes 2 inputs) as input and returns an n_ary function. def n_ary_A(f): """Given binary function f(x, y), return an n_ary function such that f(x, y, z) = f(x, f(y,z)), etc. Also allow f(x) = x.""" def n_ary_f(x, *args): if args: # if not f(x); note this is being called more than needed via recursion if len(args)> 1: # if not f(x,y) return f(x, n_ary_f(args[0],*args[1:])) #recursive call, use * to expand tuple to list of args else: return f(x, args[0]) #handle f(x,y) case return x #handle f(x) case return n_ary_f def n_ary_B(f): """Given binary function f(x, y), return an n_ary function such that f(x, y, z) = f(x, f(y,z)), etc. Also allow f(x) = x.""" def n_ary_f(x, *args): if args: # if not f(x), ie f(x,None), or f(x,[]), (which is what args[0:] pnce empty) return f(x, n_ary_f(args[0],*args[1:])) #recursive call, use * to expand tuple to list of args return x #handle f(x) case # return x if not args else f(x, n_ary_f(*args)) <<< conditional return & *args will expand into args[0], *args[1:] return n_ary_f t = lambda i,j: i + j t_seqA = n_ary_A(t) t_seqB = n_ary_B(t) print t(2,3) print t_seqA(1,2,3,4,5) print t_seqB(1,2,3)
true
4738082f42766a81e204ce364000a790a959fdf1
JeffreyAsuncion/PythonCodingProjects
/10_mini_projects/p02_GuessTheNumberGame.py
917
4.5
4
""" The main goal of the project is to create a program that randomly select a number in a range then the user has to guess the number. user has three chances to guess the number if he guess correct then a message print saying “you guess right “otherwise a negative message prints. Topics: random module, for loop, f strings """ import random high_end = 100 # be able to generate a random number num = random.randint(1, high_end) print(num) guess = int(input("Enter your guess: ")) if guess == num: print("You Chose Wisely.") else: print("You Chose Poorly.") # import random # number = random.randint(1,10) # for i in range(0,3): # user = int(input("guess the number")) # if user == number: # print("Hurray!!") # print(f"you guessed the number right it's {number}") # break # if user != number: # print(f"Your guess is incorrect the number is {number}")
true
ff88f375bd9e0ff5d34a60155fac35faaf3c8329
sec2890/Python
/Python Fundamentals/bike.py
840
4.15625
4
class Bike: def __init__(self, price, max_speed): self.price = price self.max_speed = max_speed self.miles = 0 def displayInfo(self): print("This bike has a price of",self.price,", a maximum speed of",self.max_speed, "and a total of", self.miles, "miles on it.") return self def ride(self): print("Riding") self.miles += 10 return self def reverse(self): print("Reversing") if self.miles >= 5: self.miles -= 5 return self new_bike1 = Bike(199,"25mph") new_bike1.ride().ride().ride().reverse().displayInfo() new_bike2 = Bike(399, "32mph") new_bike2.ride() .ride().reverse().reverse().displayInfo() new_bike3 = Bike(89, "14mph") new_bike3.reverse().reverse().reverse().displayInfo()
true
14989dacdda1f7c8cf589f5bdf556c9cbcd6db0e
fhylinjr/Scratch_Python
/learning dictionaries 1.py
1,196
4.1875
4
def display(): list={"ID":"23","Name":"Philip"} print(list)#prints the whole list for n in list: print(n)#prints the keys print(list.keys())#alternative print(list["Name"])#prints a specific value print(list.get("Name"))#alternative '''list["Name"]="Joe"#change a value in a list''' print(list) print(list.values())#returns all the values print(list.items())#returns every item for x,y in list.items(): print(x,y)#returns items column-wise print(len(list))#returns number of items list["Age"]=25#adds new item to list print(list) list.pop("Age")#removes item from list print(list) list.popitem()#removes last item in list print(list) '''del list''' #deletes the whole list '''list.clear()'''#removes all items and leaves dict. empty '''list.update({"color":"red"})''' dict2=list.copy()#copies items from one dictionary to another dict2=dict(list)#alternative k=("key1","key2")#attaches keys to values y=0 list.fromKeys(k,y) list.setdefault("username","Philip")#first checks if key exist if not then creates this item display()
true
4bbadc10900a6ea43dc032411c7d65dca29666e4
aevri/mel
/mel/lib/math.py
2,583
4.375
4
"""Math-related things.""" import math import numpy RADS_TO_DEGS = 180 / math.pi def lerp(origin, target, factor_0_to_1): towards = target - origin return origin + (towards * factor_0_to_1) def distance_sq_2d(a, b): """Return the squared distance between two points in two dimensions. Usage examples: >>> distance_sq_2d((1, 1), (1, 1)) 0 >>> distance_sq_2d((0, 0), (0, 2)) 4 """ assert len(a) == 2 assert len(b) == 2 x = a[0] - b[0] y = a[1] - b[1] return (x * x) + (y * y) def distance_2d(a, b): """Return the squared distance between two points in two dimensions. Usage examples: >>> distance_2d((1, 1), (1, 1)) 0.0 >>> distance_2d((0, 0), (0, 2)) 2.0 """ return math.sqrt(distance_sq_2d(a, b)) def normalized(v): """Return vector v normalized to unit length. Usage examples: >>> normalized((0, 2)) (0.0, 1.0) """ inv_length = 1 / distance_2d((0, 0), v) return (v[0] * inv_length, v[1] * inv_length) def angle(v): """Return the angle between v and 'right'. Usage examples: >>> angle((1, 0)) 0.0 >>> angle((-1, 0)) 180.0 >>> angle((0, 1)) -90.0 >>> angle((0, -1)) 90.0 """ cos_theta = normalized(v)[0] theta = math.acos(cos_theta) if v[1] > 0: theta = -theta return rads_to_degs(theta) def rads_to_degs(theta): return theta * RADS_TO_DEGS def raise_if_not_int_vector2(v): if not isinstance(v, numpy.ndarray): raise ValueError( "{}:{}:{} is not a numpy array".format(v, repr(v), type(v)) ) if not numpy.issubdtype(v.dtype.type, numpy.integer): raise ValueError("{}:{} is not an int vector2".format(v, v.dtype)) # ----------------------------------------------------------------------------- # Copyright (C) 2015-2020 Angelos Evripiotis. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ------------------------------ END-OF-FILE ----------------------------------
true
b25a60e2013b9451ba7eb8db5ead8f56e5a59fcd
Pdshende/-Python-for-Everybody-Specialization-master
/-Python-for-Everybody-Specialization-master/Coursera---Using-Python-to-Access-Web-Data-master/Week-6/Extracting Data from JSON.py
1,695
4.1875
4
''' In this assignment you will write a Python program somewhat similar to http://www.pythonlearn.com/code/json2.py. The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file and enter the sum below: We provide two files for this assignment. One is a sample file where we give you the sum for your testing and the other is the actual data you need to process for the assignment. Sample data: http://python-data.dr-chuck.net/comments_42.json (Sum=2553) Actual data: http://python-data.dr-chuck.net/comments_353540.json (Sum ends with 71) You do not need to save these files to your folder since your program will read the data directly from the URL. Note: Each student will have a distinct data url for the assignment - so only use your own data url for analysis. ''' import time start = time.time() import urllib.request, urllib.parse, urllib.error import json #Data collection link = input('Enter location: ') print('Retrieving', link) html = urllib.request.urlopen(link).read().decode() print('Retrieved', len(html), 'characters') try: js = json.loads(html) except: js = None cn = 0 sm = 0 for item in js['comments']: cn += 1 sm += int(item['count']) print('Count:', cn) print('Sum:', sm) end = time.time() print("The total excecution Time for this code is sec", (end-start)) ''' Output: - Enter location: http://py4e-data.dr-chuck.net/comments_417438.json Retrieving http://py4e-data.dr-chuck.net/comments_417438.json Retrieved 2717 characters Count: 50 Sum: 2178 The total excecution Time for this code is sec 2.7438461780548096 '''
true
17094896a237ce2d5f4cc2e0a3b770058f187bcb
fatihtkale/Term-Todo
/script.py
1,174
4.15625
4
import sqlite3 conn = sqlite3.connect('db.db') query = conn.cursor() def run_program(): def get_info(): query = conn.cursor() query.execute("SELECT * FROM Information") rows = query.fetchall() for row in rows: print(row) run_program() def save_info(value): query.execute("INSERT INTO information (info) values ('"+value+"')") conn.commit() run_program() def delete_info(value): query.execute("DELETE FROM information WHERE info=?", (value,)) conn.commit() run_program() print("Choose one of the options listed below") print("[S]ave for saving a information | [D]elete | [L]ist all the information | [Q]uit the program") choice = input() if choice.lower() == "s": print("Type a piece of information you want to save.") val = input() save_info(val) elif choice.lower() == "d": print("Type the data you want to remove") val = input() delete_info(val) elif choice.lower() == "l": get_info() elif choice.lower() == "q": conn.close() return 0 run_program()
true
8ff6e4d16550bff45f3c2e75d17f18cd1640adb1
mvg2/astr-119-hw-2
/variables_and_loops.py
771
4.15625
4
import numpy as np # imports the numpy module def main(): i = 0 # assign integer value 0 to variable i n = 10 # assign integer value 10 to variable n x = 119.0 # assign float value 119.0 to variable x # we can use numpy to declare arrays quickly y = np.zeros(n, dtype=float) # declares 10 zeroes (referenced by variable n) # we can use for loops to iterate with a variable for i in range(n): # runs the loop 10 times y[i] = 2.0 * float(i) + 1. # set y = 2i + 1 as floats # we can also simply iterate through a variable for y_element in y: print(y_element) # execute the main function if __name__ == "__main__": main()
true
157c530a6a6f8d7bc729cbf6c1b945b3bdd83507
Moosedemeanor/learn-python-3-the-hard-way
/ex03.py
1,195
4.625
5
# + plus # - minus # / slash # * asterisk # % percent # < less-than # > greater-than # <= less-than-equal # >= greater-than-equal # print string text question print("I will now count my chickens:") # print Hens string then perform calculation print("Hens", 25 + 30 / 6) # print Roosters string then perform calculation print("Roosters", 100 - 25 * 3 % 4) # print string statement print("Now I will count the eggs:") # print the result of the calculation # PEMDAS - Parentheses Exponents Multiplication Division Addition Subtraction print(3 + 2 + 1 - 5 + 4 % 2 - 1.00 / 4 + 6) # print string question print("Is it true that 3 + 2 < 5 -7?") # perform the actual calculation print(3 + 2 < 5 -7) # print string question, perform addition print("What is 3 + 2?", 3 + 2) # print string question, perform subtraction print("What is 5 - 7?", 5 - 7) # print string question print("Oh, that's what it's False.") # print string question print("How about some more.") # print string, perform boolean operation print("Is it greater?", 5 > -2 ) # print string, perform boolean operation print("Is is greater or equal?", 5 >= -2) # print string, perform boolean operation print("Is it less or equal?", 5 <= -2)
true
75888241e7d1af247414e9cdb72a2a2e9ebf70f3
theodorp/CodeEval_Easy
/ageDistribution.py
1,798
4.40625
4
# AGE DISTRIBUTION # CHALLENGE DESCRIPTION: # You're responsible for providing a demographic report for your local school district based on age. To do this, you're going determine which 'category' each person fits into based on their age. # The person's age will determine which category they should be in: # If they're from 0 to 2 the child should be with parents print : 'Still in Mama's arms' # If they're 3 or 4 and should be in preschool print : 'Preschool Maniac' # If they're from 5 to 11 and should be in elementary school print : 'Elementary school' # From 12 to 14: 'Middle school' # From 15 to 18: 'High school' # From 19 to 22: 'College' # From 23 to 65: 'Working for the man' # From 66 to 100: 'The Golden Years' # If the age of the person less than 0 or more than 100 - it might be an alien - print: "This program is for humans" # INPUT SAMPLE: # Your program should accept as its first argument a path to a filename. Each line of input contains one integer - age of the person: # 0 # 19 # OUTPUT SAMPLE: # For each line of input print out where the person is: # Still in Mama's arms # College ################################ def ageDistribution(test): age = int(test.strip()) if age < 0 or age > 100: return('This program is for humans') elif age in range(0,2): return("Still in Mama's arms") elif age in range(3,4): return("Preschool Maniac") elif age in range(5,11): return('Elementary school') elif age in range(12,14): return('Middle school') elif age in range(15,18): return('High school') elif age in range(19,22): return('College') elif age in range(23,65): return('Working for the man') elif age in range(66,100): return('The Golden Years') file = open("ageDistribution.txt", "r") for test in file: print(ageDistribution(test))
true
bb889189b4f6ed0e6e0119fa5f2612904fa95921
theodorp/CodeEval_Easy
/swapCase.py
645
4.25
4
# SWAP CASE # CHALLENGE DESCRIPTION: # Write a program which swaps letters' case in a sentence. All non-letter characters should remain the same. # INPUT SAMPLE: # Your program should accept as its first argument a path to a filename. Input example is the following # Hello world! # JavaScript language 1.8 # A letter # OUTPUT SAMPLE: # Print results in the following way. # hELLO WORLD! # jAVAsCRIPT LANGUAGE 1.8 # a LETTER def swapCase(filename): f = open(filename,'r') for test in f: test = test.strip() t2 = ''.join([i.lower() if i.isupper() else i.upper() for i in test]) print(t2) f.close() swapCase('swapCase.txt')
true
e32d4c0ff6b060534d93f0d05d181de0bb6785d4
theodorp/CodeEval_Easy
/happyNumbers.py
1,204
4.25
4
# HAPPY NUMBERS # CHALLENGE DESCRIPTION: # A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers. # INPUT SAMPLE: # The first argument is the pathname to a file which contains test data, one test case per line. Each line contains a positive integer. E.g. # 1 # 7 # 22 # OUTPUT SAMPLE: # If the number is a happy number, print out 1. If not, print out 0. E.g # 1 # 1 # 0 # For the curious, here's why 7 is a happy number: 7->49->97->130->10->1. # Here's why 22 is NOT a happy number: 22->8->64->52->29->85->89->145->42->20->4->16->37->58->89 ... def happy(n): past = set() while n != 1: n = sum(int(i)**2 for i in str(n)) if n in past: return (0) past.add(n) return (1) def happyNumbers(filename): f = open(filename, 'r') for test in f: t = test.strip() print(happy(int(t))) # print(happy(7)) happyNumbers('happyNumbers.txt')
true
fe8869fcc3952b4c795d5f4723d578c234e93b8d
theodorp/CodeEval_Easy
/majorElement.py
1,138
4.15625
4
# THE MAJOR ELEMENT # CHALLENGE DESCRIPTION: # The major element in a sequence with the length of L is the element which appears in a sequence more than L/2 times. The challenge is to find that element in a sequence. # INPUT SAMPLE: # Your program should accept as its first argument a path to a filename. Each line of the file contains a sequence of integers N separated by comma. E.g. # 92,19,19,76,19,21,19,85,19,19,19,94,19,19,22,67,83,19,19,54,59,1,19,19 # 92,11,30,92,1,11,92,38,92,92,43,92,92,51,92,36,97,92,92,92,43,22,84,92,92 # 4,79,89,98,48,42,39,79,55,70,21,39,98,16,96,2,10,24,14,47,0,50,95,20,95,48,50,12,42 # OUTPUT SAMPLE: # For each sequence print out the major element or print "None" in case there is no such element. E.g. # 19 # 92 # None # Constraints: # N is in range [0, 100] # L is in range [10000, 30000] # The number of test cases <= 40 def majorElement(test): from collections import Counter line = test.strip().split(',') c = Counter(line).most_common(1) x,y = c[0] return (x if y > len(line)/2 else 'None') file = open("majorElement.txt", "r") for test in file: print(majorElement(test))
true
2c991f2a5e7da455ff2fcecc75ec4d7368e2af72
theodorp/CodeEval_Easy
/lowerCase.py
588
4.3125
4
# LOWERCASE # CHALLENGE DESCRIPTION: # Given a string write a program to convert it into lowercase. # INPUT SAMPLE: # The first argument will be a path to a filename containing sentences, one per line. You can assume all characters are from the english language. E.g. # HELLO CODEEVAL # This is some text # OUTPUT SAMPLE: # Print to stdout, the lowercase version of the sentence, each on a new line. E.g. # hello codeeval # this is some text def lowerCase(filepath): f = open(filepath, "r") for line in f: print(line.lower().strip()) f.close() lowerCase("lowerCase.txt")
true
bc608d508ceb1236e5f6d020d216af56e751434c
theodorp/CodeEval_Easy
/mixedContent.py
1,038
4.15625
4
# MIXED CONTENT # CHALLENGE DESCRIPTION: # You have a string of words and digits divided by comma. Write a program # which separates words with digits. You shouldn't change the order elements. # INPUT SAMPLE: # Your program should accept as its first argument a path to a filename. Input # example is the following # 8,33,21,0,16,50,37,0,melon,7,apricot,peach,pineapple,17,21 # 24,13,14,43,41 # OUTPUT SAMPLE: # melon,apricot,peach,pineapple|8,33,21,0,16,50,37,0,7,17,21 # 24,13,14,43,41 def mixedContent(test): line = test.strip().split(',') numbers = [] words = [] for i in line: try: numbers.append(int(i)) except ValueError: words.append(i) pass return(words, numbers) test_cases = open('mixedContent.txt','r') for test in test_cases: words, numbers = mixedContent(test) if len(words) and len(numbers) > 0: print(','.join(words) + "|" + ','.join(map(str, numbers))) elif len(words) == 0: print(','.join(map(str, numbers))) elif len(numbers) == 0: print(','.join(words)) test_cases.close()
true
05b9dbed2d6c37958599957c9a05b177f3b08b73
jbhennes/CSCI-220-Programming-1
/Chapter 7 Decisions/LetterGrade.py
507
4.15625
4
## LetterGrade.py def main(): print ("Given a numerical grade, returns the letter grade.") # Get the numerical grade grade = input("Enter your numerical grade: ") if grade >= 90: print ("Letter grade = A") elif grade < 90 and grade >= 80: print ("Letter grade = B") elif grade < 80 and grade >= 70: print ("Letter grade = C") elif grade < 70 and grade >= 60: print ("Letter grade = D") else: print ("Letter grade = F") main()
true
28e47d7fd4572ff14512a9e86541cfeb8ee0e848
jbhennes/CSCI-220-Programming-1
/rectArea.py
1,039
4.25
4
#This function calculates the area of a rectangle. def rectArea(): #Purpose of the program. print("This program calculates the area of a rectangle.") units = input("First, tell me the units that will be used: ") #Define variables length = eval(input("Please input the length of the rectangle: ")) width = eval(input("Please input the width of the rectangle: ")) #Perform the calculation. area = length * width print("The area of the rectangle is", area, units, "squared.") #Restart command. restart = int(input("Would you like to restart? (1 = Yes / 0 = No): ")) if restart == (1): rectArea() elif restart == (0): print("Gsme Over") elif restart < (0) or > (1): print("Funny. Try again.") restart = int(input("( Yes = 1 / No = 0): ")) if restart == (1): rectArea() elif restart == (0): print("Game Over") elif restart < (0) or > (1): print("Fine, have it your way.") rectArea()
true
4c114ee054f6bca751ac665fb7fce7a63dcf6f1c
jbhennes/CSCI-220-Programming-1
/Chapter 11 - lists/partialListFunctions.py
1,967
4.375
4
# listFunctions.py # Author: Pharr # Program to implement the list operations count and reverse. from math import sqrt def getElements(): list = [] # start with an empty list # sentinel loop to get elements item = raw_input("Enter an element (<Enter> to quit) >> ") while item != "": list.append(item) # add this value to the list item = raw_input("Enter an element (<Enter> to quit) >> ") return list # count(list, x) counts the number of times that x occurs in list def count(list, x): num = 0 for item in list: if item == x: num = num + 1 return num # isinBad(list, x) returns whether x occurs in list # This is bad because it is inefficient. def isinBad(list, x): occurs = False for item in list: if item == x: occurs = True return occurs # isin(list, x) returns whether x occurs in list # This is better because it is more efficient. def isin(list, x): return False # reverse(list) reverses the list # This function destructively modifies the list. # It would be easier to write if it just returned the reversed list! def reverse(list): print "Your code will reverse the list in place" def main(): print 'This program reads a list, counts the number of elements,' print 'and reverses the list.' data = getElements() item = raw_input("Enter element you want to count in the list: ") theCount = count(data, item) print "\nTnere are", theCount, "occurrences of", item, "in", data item = raw_input("\nEnter element that should occur in the list: ") occurs = isinBad(data, item) if occurs: print item, "occurs in", data else: print item, "does not occur in", data occurs = isin(data, item) if occurs: print item, "occurs in", data else: print item, "does not occur in", data reverse(data) print "\nTne reversed list is", data main()
true
913c3d0fafc5017bc72172796e8b2c793d190c61
jbhennes/CSCI-220-Programming-1
/Chapter 7 Decisions/MaxOfThree3.py
729
4.46875
4
## MaxOfThree3.py ## Finds largest of three user-specified numbers def main(): x1 = eval(input("Enter a number: ")) x2 = eval(input("Enter a number: ")) if x1 > x2: temp = x1 x1 = x2 x2 = temp print ("here") print ("The numbers in sorted order are: ") print (str(x1) + " " + str(x2)) ## x3 = eval(input("Enter a number: ")) ## ## # Determine which number is the largest ## ## max = x1 # Is x1 the largest? ## if x2 > max: ## max = x2 # Maybe x2 is the largest. ## if x3 > max: ## max = x3 # No, x3 is the largest. ## ## # display result ## print ("\nLargest number is", max) main()
true
e97f890f65d8e44456af6118610c52f96d0e82ab
jbhennes/CSCI-220-Programming-1
/Chapter 7 Decisions/MaxOfThree1.py
508
4.53125
5
## MaxOfThree1.py ## Finds largest of three user-specified numbers def main(): x1 = input("Enter a number: ") x2 = input("Enter a number: ") x3 = input("Enter a number: ") # Determine which number is the largest if x1 >= x2 and x1 >= x3: # x1 is largest max = x1 elif x2 >= x1 and x2 >= x3: # x2 is largest max = x2 else: # x3 is largest max = x3 # display result print "\nLargest number is", max main()
true
2f6867f9b3569cfddafea7b46bf11ad254713d75
jbhennes/CSCI-220-Programming-1
/Chapter 8 While/GoodInput5.py
493
4.28125
4
## GoodInput5.py # This program asks the user to enter exactly 12 or 57. # This version is WRONG!!!!!! def main(): number = input("Enter the number 12 or 57: ") # This version tries to move the negation in, but incorrectly, # thus creating an infinite loop: while number != 12 or number != 57: print "That number was not the requested value.\n" number = input("Enter the number 12 or 57: ") print "Thank you for entering", number main()
true
1ef289b88e2cf959f9e0f533df0ccfa180605154
Matt-McConway/Python-Crash-Course-Working
/Chapter 7 - User Input and While Loops/ex7-2_pp121_restaurantSeating.py
216
4.15625
4
""" """ toBeSeated = input("How many people are dining tonight? ") if int(toBeSeated) > 8: print("I'm sorry, you are going to have to wait for a table.") else: print("Right this way, your table is ready.")
true
45142c33c0203fe1bc2386bb7b53e0fb919f5b27
Gutencode/python-programs
/conditionals/gradePercent.py
829
4.3125
4
## Program to compute the grade from given percentage. def grade(percent): """ This function takes the percentage as input and returns the relevant grade. """ if (percent > 100): print("Please enter the correct obtained percentage") elif (percent >= 90): return("A") elif (percent >= 80): return("B") elif (percent >= 70): return("C") elif (percent >= 60): return("D") elif (percent >= 50): return("E") elif (percent >= 40): return("F") elif (percent >= 30): return("G") else: return("Fail") # Input from the user. percent = float(input("Please enter the obtained percentage : ")) # Function get called and the statement print the corresponding returned grade. print("You earned",grade(percent),"grade")
true
c6acf0c506bae2c792f8e9f647036776c335b506
innovation-platform/Mad-Lib-generator
/mad.py
1,203
4.125
4
import tkinter from tkinter import * main=Tk() main.geometry("500x500") main.title("Mad Libs Generator") Label(main,text="Mad Libs Generator",font="arial",bg="black",fg="white").pack() Label(main,text="Click one:",font="italic",bg="white",fg="black").place(x=40,y=80) def madlib1(): name=input("Enter a name of a boy:") color=input("Enter a color name") food=input("Enter a food name") adjective=input("Enter an adjective") profession=input("Enter a professsion") print("Once upon a time there lived a person called "+name+".He was "+color+"colored. He always ate "+food+".He was a very " +adjective+". He was a "+profession+".") def madlib2(): animal=input("Enter name of an animal") color=input("Enter color of an animal") food=input("Enter food") adjective=input("Enter an adjective") print(animal+" is an animal which is in "+color+" color. It eats "+food+". It is a very "+adjective+" animal.") Button(main,text="A Person",font="italic",command=madlib1,bg="black",fg="white").place(x=40,y=160) Button(main,text="An Animal",font="italic",command=madlib2,bg="black",fg="white").place(x=40,y=240) main.mainloop()
true
a907255a5ecbd9c126c08cad5693e319344d6027
Alekssin1/first_lab_OOP
/first_task.py
649
4.15625
4
import sys # cut first element(name of the file) expression = "".join(sys.argv[1:]) # We use join to make our expression a string with # spaces and then using the function eval # check whether the user input is empty if expression: try: print(eval(expression)) except ZeroDivisionError: print("Attempt to divide a number by zero") except NameError: print("Incorrect input! Name error, try again") except SyntaxError: print("Invalid syntax. Try again.") except EOFError or KeyboardInterrupt: print("Error, incorrect input! Try again.") else: print("You need to enter an expression")
true
be9109066f9f34b4fa21aa46312871fb244c35ec
griadooss/HowTos
/Tkinter/05_buttons.py
2,223
4.34375
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ ZetCode Tkinter tutorial In this script, we use pack manager to position two buttons in the bottom right corner of the window. author: Jan Bodnar last modified: December 2010 website: www.zetcode.com """ #We will have two frames. #There is the base frame and an additional frame, which will expand in both directions and #push the two buttons to the bottom of the base frame. #The buttons are placed in a horizontal box and placed to the right of this box. from Tkinter import Tk, RIGHT, BOTH, RAISED from ttk import Frame, Button, Style class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Buttons") self.style = Style() self.style.theme_use("default") frame = Frame(self, relief=RAISED, borderwidth=1) frame.pack(fill=BOTH, expand=1) #We create another Frame widget. #This widget takes the bulk of the area. #We change the border of the frame so that the frame is visible. #By default it is flat. self.pack(fill=BOTH, expand=1) closeButton = Button(self, text="Close") closeButton.pack(side=RIGHT, padx=5, pady=5) #A closeButton is created. #It is put into a horizontal box. #The side parameter will create a horizontal box layout, in which the button is placed to the right of the box. #The padx and the pady parameters will put some space between the widgets. #The padx puts some space between the button widgets and between the closeButton and the right border of the root window. #The pady puts some space between the button widgets and the borders of the frame and the root window. okButton = Button(self, text="OK") okButton.pack(side=RIGHT) #The okButton is placed next to the closeButton with 5px space between them. def main(): root = Tk() root.geometry("300x200+300+300") app = Example(root) root.mainloop() if __name__ == '__main__': main()
true
f82da39fce4bb6efbffd817b4651cb1027e15410
griadooss/HowTos
/Tkinter/01_basic_window.py
2,700
4.34375
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ ZetCode Tkinter tutorial This script shows a simple window on the screen. author: Jan Bodnar last modified: January 2011 website: www.zetcode.com """ #While this code is very small, the application window can do quite a lot. #It can be resized, maximized, minimized. #All the complexity that comes with it has been hidden from the application programmer. from Tkinter import Tk, Frame, BOTH #Here we import Tk and Frame classes. #The first class is used to create a root window. #The latter is a container for other widgets. class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent, background="white") #Our example class inherits from the Frame container widget. #In the __init__() constructor method we call the constructor of our inherited class. #The background parameter specifies the background color of the Frame widget. self.parent = parent #We save a reference to the parent widget. The parent widget is the Tk root window in our case.''' self.initUI() #We delegate the creation of the user interface to the initUI() method. def initUI(self): self.parent.title("Simple") #We set the title of the window using the title() method. self.pack(fill=BOTH, expand=1) #The pack() method is one of the three geometry managers in Tkinter. #It organizes widgets into horizontal and vertical boxes. #Here we put the Frame widget, accessed via the self attribute to the Tk root window. #It is expanded in both directions. In other words, it takes the whole client space of the root window. def main(): root = Tk() #The root window is created. #The root window is a main application window in our programs. #It has a title bar and borders. #These are provided by the window manager. #It must be created before any other widgets. root.geometry("250x150+300+300") #The geometry() method sets a size for the window and positions it on the screen. #The first two parameters are width and height of the window. #The last two parameters are x and y screen coordinates. app = Example(root) #Here we create the instance of the application class. root.mainloop() #Finally, we enter the mainloop. #The event handling starts from this point. #The mainloop receives events from the window system and dispatches them to the application widgets. #It is terminated when we click on the close button of the titlebar or call the quit() method. if __name__ == '__main__': main()
true
2a535a9f8cf2b45ffc9469195319a9a0df2df168
griadooss/HowTos
/Tkinter/14_popup_menu.py
1,706
4.40625
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ ZetCode Tkinter tutorial In this program, we create a popup menu. author: Jan Bodnar last modified: December 2010 website: www.zetcode.com """ '''Popup menu''' # In the next example, we create a popup menu. # Popup menu is also called a context menu. # It can be shown anywhere on the client area of a window. # In our example, we create a popup menu with two commands. from Tkinter import Tk, Frame, Menu class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Popup menu") self.menu = Menu(self.parent, tearoff=0) #A context menu is a regular Menu widget. #The tearoff feature is turned off. #Now it is not possible to separate the menu into a new toplevel window. self.menu.add_command(label="Beep", command=self.bell()) self.menu.add_command(label="Exit", command=self.onExit) self.parent.bind("<Button-3>", self.showMenu) #We bind the <Button-3> event to the showMenu() method. #The event is generated when we right click on the client area of the window. self.pack() #The showMenu() method shows the context menu. #The popup menu is shown at the x and y coordinates of the mouse click. def showMenu(self, e): self.menu.post(e.x_root, e.y_root) def onExit(self): self.quit() def main(): root = Tk() root.geometry("250x150+300+300") app = Example(root) root.mainloop() if __name__ == '__main__': main()
true
cf108c19ac33a9286c8daba5bff0c3f9b7098711
djcolantonio/PythonProjects
/homework_function_scor.py
407
4.15625
4
# This program evaluates the score and LOOPS while True: score = input('What is your score: ') try: if int(score) >= 90: print('This is an excellent score') elif int(score) >=80: print('This is a good score') else: print('You need a better score') break except ValueError: print('Please enter a number')
true
534456b717efe50a9709c45edeedf8579a945769
CGayatri/Python-Practice1
/control_3.py
298
4.3125
4
## program 3 - to display a group of messages when the condition is true - to display suite str = 'Yes' if str == 'Yes': print("Yes") print("This is what you said") print("Your response is good") ''' F:\PY>py control_3.py Yes This is what you said Your response is good '''
true
a3df363bd6c12796722d7c243b009bd04a213538
CGayatri/Python-Practice1
/control_13.py
252
4.28125
4
## program 13 - to display each character from a string using sequence index str = 'Hello' n = len(str) # find no. of chars in str print("Lenght :", n) for i in range(n): print(str[i]) ''' F:\PY>py control_13.py Lenght : 5 H e l l o '''
true
75dc369c4b309a387583cc7dc8d05d91c29cf318
CGayatri/Python-Practice1
/Module1/CaseStudy_1/demo5.py
501
4.34375
4
# 5.Please write a program which accepts a string from console and print the characters that have even indexes. # Example: If the following string is given as input to the program: # H1e2l3l4o5w6o7r8l9d # Then, the output of the program should be: # Helloworld str = input("Enter input string : ") str = str[0: len(str) : 2] print(str) ''' F:\PY\Module1\CaseStudy_1>py demo5.py Enter input string : H1e2l3l4o5w6o7r8l9d Helloworld F:\PY\Module1\CaseStudy_1> '''
true
286c01b126996d05ee34b93bca9b3616a3199d69
CGayatri/Python-Practice1
/string_13_noOfWords.py
668
4.125
4
## Program 13 - to find the number of words in a string # as many number of spaces; +1 wuld be no of words # to find no. of words in a string str = input('Enter a string : ') i=0 count=0 flag = True # this becomes False when no space is found for s in str: # Count only when there is no space previously if (flag==False and str[i]==' '): count+=1 # If a space is found, make flag as True if (str[i]==' '): flag = True else : flag = False i=i+1 print('No. of words :', (count+1)) ''' F:\PY>py string_13_noOfWords.py Enter a string : You are a sweet girl baby No. of words : 6 '''
true
456bc270c408a04758347728e9bd02c1b3a96e52
CGayatri/Python-Practice1
/string_9_chars.py
1,010
4.4375
4
## Working with Characters -- get a string --> get chars using indexing or slicing ## program 9 - to know the type of character entered by the user str = input('Enter a character : ') ch = str[0] # take only 0th character niito ch # test ch if (ch.isalnum()): print("It is an alphabet or numeric character") if (ch.isalpha()): print("It is an alphabet") if (ch.isupper()): print("It is capital letter") else : print("It is lowercase letter") else : print("It is a numeric digit") elif (ch.isspace()): print("It is a space") else : print("It may be a special character") ''' F:\PY>py string_9_chars.py Enter a character : a It is an alphabet or numeric character It is an alphabet It is lowercase letter F:\PY>py string_9_chars.py Enter a character : & It may be a special character F:\PY>py string_9_chars.py Enter a character : 5 It is an alphabet or numeric character It is a numeric digit '''
true
ea4b5b1bdd6bb54b8c439ee2ecfa37a0d0149748
CGayatri/Python-Practice1
/control_11.py
707
4.15625
4
## program 11 - to display even numbers between m and n (minimum and maximum range) m , n = [int(i) for i in input("Enter comma separated minimum and maximum range: ").split(',')] # 1 to 10 ===> x = m # start from m onwards #x = 1 # start from ths number # make start as even so that adding 2 to it would give next even number if(x%2 != 0): x = x + 1 while(x>=m and x<=n): print(x) x+=2 print("End") """ F:\PY>py control_11.py Enter comma separated minimum and maximum range: 1, 10 2 4 6 8 10 End F:\PY> """ ''' while(x>=m and x<=n): if(x%2 == 0): print(x) x+=2 print("End") F:\PY>py control_11.py Enter comma separated minimum and maximum range: 1, 10 End '''
true
9d029614f80818e96a163348028788b3b4639937
CGayatri/Python-Practice1
/string_8.py
416
4.28125
4
## Splitting and Joining Strings ## Program 8 - to accept and display a group of numbers # string.split(seperator) # separator.join(string) str = input('Enter numbers separated by space : ') # cut the string where a space is found lst = str.split(' ') # display the numbers from teh list for i in lst : print(i) ''' F:\PY>py string_8.py Enter numbers separated by space : 10 20 30 40 10 20 30 40 '''
true
bdde2a9d113f48aac14994980bad4e84caedd315
CGayatri/Python-Practice1
/prime.py
558
4.15625
4
# program to display prime numbers between range #Take the input from the user: lower = int(input("Enter lower range: ")) upper = int(input("Enter upper range: ")) for num in range(lower,upper + 1): if num > 1: for i in range(2,num): if (num % i) == 0: break else: print(num) """ F:\PY>py prime.py Enter lower range: 1 Enter upper range: 10 2 3 5 7 F:\PY>py prime.py Enter lower range: 10 Enter upper range: 50 11 13 17 19 23 29 31 37 41 43 47 F:\PY> """
true
457950d15654565ce70aa6b6c664eeb431ea25a2
CGayatri/Python-Practice1
/function_12_functionReturnsAnotherFun.py
452
4.25
4
## Program 12 - to know how a function can return another function # functions can return other functions def display(): def message(): return 'How are you?' return message # call display() function and it returns message() function # in following code, 'fun' refers to the name : 'message' @ line:9 fun = display() print(fun()) #Output: ''' F:\PY>py function_12_functionReturnsAnotherFun.py How are you? '''
true
8e9e41a1adabea2eef1da2b4f66e6f1794105b1a
CGayatri/Python-Practice1
/input22_argparse.py
660
4.59375
5
## program - 22 : to find the power value of a number when it is rised to a particular power import argparse # call the ArgumentParser() parser = argparse.ArgumentParser() # add the arguments to teh parser parser.add_argument('nums', nargs=2) # retrieve arguments from parser args = parser.parse_args() #find the power value #args.nums is a list print("Number =", args.nums[0]) print("It\'s power =", args.nums[1]) # calculate power by coverting strings to numbers result = float(args.nums[0]) ** float(args.nums[1]) print("power rsult = ", result) """ F:\PY>py input22_argparse.py 10.5 3 Number = 10.5 It's power = 3 power rsult = 1157.625 """
true
69d2b90af1c5dfa0145321e0d808576599d31ec7
raiyanshadow/BasicPart1-py
/ex21.py
272
4.40625
4
# Write a Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user. n = int(input("ENTER NUMBER: ")) if n % 2 == 0: print("That is an even number.") else: print("That is an odd number.")
true
89d58cabd879fb0e9a0f3b01bf665c754f367653
SharonOBoyle/python-lp3thw
/ex7.py
1,028
4.25
4
# print the sentence to the screen print("Mary had a little lamb.") # print the sentence to the screen, substituting 'snow' inside the {} print("Its fleece was white as {}.".format('snow')) # print the sentence to the screen print("And everywhere that Mary went.") # this printed 10 . characters in succession on the same line i.e. ".........." print("." * 10) # what'd that do? # creates a variable named end* and assigns the character value to it end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e" end7 = "B" end8 = "u" end9 = "r" end10 = "g" end11 = "e" end12 = "r" #debugging by printing the variable value :) #print(end10) # prints the words "Cheese Burger" but concatenating the value of each # specified variable, when you print, instead of a new line use a space # watch that comma at the end. try removing it to see what happens # Removing the comma causes an error: SyntaxError: invalid syntax print(end1 + end2 + end3 + end4 + end5 + end6, end=' ') print(end7 + end8 + end9 + end10 + end11 + end12)
true
e127418b2765a0cb6c76915003aafd5535aea7c1
SharonOBoyle/python-lp3thw
/ex30.py
1,007
4.25
4
# create a variable named people with value 40 people = 40 cars = 4 trucks = 15 # if the boolean expression is true, execute the code in the block, otherwise skip it if cars > people or trucks > people: print(">>> if cars > people or trucks > people:", cars, people, trucks) print("We should go somewhere") # execute this condition if the above if boolean expression is false # if the boolean expression is true, execute the code in the block, otherwise skip it elif cars < people: print(">>> elif cars < people:", cars, people) print("We should not take the cars.") # execute this condition if both the above if and elif boolean expressions are false else: print (""We can't decide.") if trucks > cars: print("That's too many trucks.") elif trucks < cars and people != 40 : print("Maybe we could take the trucks.") else: print("We still can't decide.") if people > trucks: print("Alright, let's just take the trucks.") else: print("Fine, let's stay home then.")
true
270bd98e879bcc4a2af763a7b6a399b812bce881
SharonOBoyle/python-lp3thw
/ex15.py
1,229
4.59375
5
# import the argv module (argument variable/vector) from the sys package # argv holds the arguments specified when running this script # from the command line from sys import argv # unpack argv and assign it to the variables on the left, in that order script, filename = argv # open the file with the open() function which returns the file object # assign the file object to a variable named txt txt = open(filename, "a") txt.write("appended some text") txt.close() txt = open(filename) # display this message on screen print(f"Here's your file {filename}:") # call a function named "read" on txt i.e. run the "read" command on it # and print the results print(txt.read()) # close the file txt.close() # Ask user to input the filename at the prompt print("Type the filename again:") # prompt the user and assign the value of what user typed in # to a variable named "file_again" file_again = input("> ") # assign the file to a variable called "txt_again" # open a file, and return it as a file object txt_again = open(file_again) # read the file and print the output to the screen, # by calling the function "read()" on txt_again # print the contents of the file print(txt_again.read()) # close the file txt_again.close()
true
d0be707b6b95674e7a55339a7774568045b2a525
stacykutyepov/python-cp-cheatsheet
/educative/slidingWindow/non_repeat_substring.py
537
4.21875
4
""" time: 13 min errors: none! """ def non_repeat_substring(str): maxLen, i = 0, 0 ht = {} for i, c in enumerate(str): if c in ht: maxLen = max(maxLen, len(ht)) ht.clear() ht[c] = True maxLen = max(len(ht), maxLen) return maxLen def main(): print("Length of the longest substring: " + str(non_repeat_substring("aabccbb"))) print("Length of the longest substring: " + str(non_repeat_substring("abbbb"))) print("Length of the longest substring: " + str(non_repeat_substring("abccde"))) main()
true
4b598ac15547bccf6febd027fc489c6d28657761
rashi174/GeeksForGeeks
/reverse_array.py
666
4.15625
4
""" Given a string S as input. You have to reverse the given string. Input: First line of input contains a single integer T which denotes the number of test cases. T test cases follows, first line of each test case contains a string S. Output: Corresponding to each test case, print the string S in reverse order. Constraints: 1 <= T <= 100 3 <= length(S) <= 1000 Example: Input: 3 Geeks GeeksforGeeks GeeksQuiz Output: skeeG skeeGrofskeeG ziuQskeeG ** For More Input/Output Examples Use 'Expected Output' option ** Contributor: Harsh Agarwal Author: harsh.agarwal0 """ for _ in range(int(input())): s=input() print(s[::-1])
true
c28f332fc9cbc62aa584fb9cca14452e89904da7
jieunjeon/daily-coding
/Leetcode/716-Max_Stack.py
2,235
4.125
4
""" https://leetcode.com/problems/max-stack/ 716. Max Stack Design a max stack that supports push, pop, top, peekMax and popMax. push(x) -- Push element x onto stack. pop() -- Remove the element on top of the stack and return it. top() -- Get the element on the top. peekMax() -- Retrieve the maximum element in the stack. popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one. Example 1: MaxStack stack = new MaxStack(); stack.push(5); stack.push(1); stack.push(5); stack.top(); -> 5 stack.popMax(); -> 5 stack.top(); -> 1 stack.peekMax(); -> 5 stack.pop(); -> 1 stack.top(); -> 5 Note: -1e7 <= x <= 1e7 Number of operations won't exceed 10000. The last four operations won't be called when stack is empty. Time Complexity: O(1), except for popMax O(n) Space Complexity: O(n) """ class MaxStack(object): def __init__(self): """ initialize your data structure here. """ self.stack = [] self.maxStack = [] def push(self, x): """ :type x: int :rtype: None """ self.stack.append(x) if not self.maxStack or x >= self.maxStack[-1]: self.maxStack.append(x) def pop(self): """ :rtype: int """ if self.stack[-1] == self.maxStack[-1]: self.maxStack.pop() return self.stack.pop() def top(self): """ :rtype: int """ return self.stack[-1] def peekMax(self): """ :rtype: int """ if self.maxStack: return self.maxStack[-1] def popMax(self): """ :rtype: int """ temp = [] while self.stack[-1] != self.maxStack[-1]: temp.append(self.stack[-1]) self.stack.pop() res = self.stack.pop() self.maxStack.pop() while temp: self.push(temp[-1]) temp.pop() return res # Your MaxStack object will be instantiated and called as such: # obj = MaxStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.peekMax() # param_5 = obj.popMax()
true
6a5f82b4645e349246761c8b39829823fa7407a4
Christopher14/Selection
/revision exercise 2.py
240
4.15625
4
#Christopher Pullen #30-09-2014 #Revision exercise 2 age = int(input("please enter your age:")) if age >= 17: print ("you are legally able to drive a car with learner plates") else: print ("you are not legally able to drive a car")
true
7ed3bf159a9e29e856944f8fca2ad7c81bbb58cc
infx598g-s16/04-18-python3
/interest.py
1,118
4.40625
4
# Prompt the user for an Initial Balance (and save to a variable) # use the float() function to convert the input into a number. balance = float(input("Initial balance: ")) # Prompt the user for an Annual Interest % (and save to a variable) # use the float() function to convert the input into a number interest = float(input("Annual interest % ")) # change the percentage number into a decimal (e.g. 6 turns into .06, 5 turns into .05, etc). # remember to save your new value to a variable! interest = interest/100 # Prompt the user for a Number of years (and save to a variable) # use the int() function to convert the input into an integer years = int(input("Years: ")) def calculate_interest(balance, interest, years): new_balance = balance*(1+(interest/12))**(12*years) interest_earned = new_balance - balance return interest_earned # Output the interest earned earned = calculate_interest(balance, interest, years) output = "Interest earned in "+str(years)+" years: $"+str(earned) print(output) # Output the total value print("Total value after "+str(years)+" years: $"+str(earned + balance))
true
a9bed29fb65836ee58d9de662e6ea4d1612ffdea
Mokarram-Mujtaba/Mini-Projects
/faulty calculator.py
688
4.15625
4
#Faulty calculator #Design a calculator which gives wrong input whebn user enters the following calculation # 45 * 3 = 555, 56+9 = 77, 56/6 = 4 x1=input("Enter the opertions you want.+,-,/,%,* \n") x2=int(input("Enter the 1st number")) x3=int(input("Enter the 2nd number")) if x2==45 and x3==3 and x1=='*': print("555") elif x2==56 and x3==9 and x1=='+': print("77") elif x2==56 and x3==6 and x1=='/': print("4") elif x1=='*': mult=x2*x3 print(mult) elif x1=='+': add=x2+x3 print(add) elif x1=='-': sub=x2-x3 print(sub) elif x1=='/': div=x2/x3 print(div) elif x1=='%': perc=x2%x3 print(perc) else: print("Something went wrong")
true
b5778f7a056996cd63f63aa462d925ecfb0edd86
khan-c/learning_python
/py3tutorial.py
397
4.34375
4
print("hello world") # this is a tuple as opposed to a list # syntax would be either written like this or with parantheses programming_languages = "Python", "Java", "C++", "C#" # an array would use brackets like this: languages_list = ["Python", "Java", "C++", "C#"] # for - in loop for language in programming_languages: print(language) for language in languages_list: print(language)
true
5b5c378c445b9de900f3a5a1a82970f784a4d2ca
spencercorwin/automate-the-boring-stuff-answers
/Chapter12MultiplicationTable.py
952
4.15625
4
#! usr/bin/env python3 #Chapter 12 Challenge - Multiplication Table Marker #Takes the second argument of input, an integer, and makes a multiplication #table of that size in Excel. import os, sys, openpyxl from openpyxl.styles import Font wb = openpyxl.Workbook() sheet = wb.active #tableSize = sys.argv[1] tableSize = 6 fontObj = Font(bold=True) #Loop to add the top row of 1 to tableSize then left column of save size, in bold for topCell in range(1,tableSize+1): sheet.cell(row=1, column=topCell+1).value = topCell sheet.cell(row=1, column=topCell+1).font = fontObj sheet.cell(row=topCell+1, column=1).value = topCell sheet.cell(row=topCell+1, column=1).font = fontObj #Loop through and multiply for x in range(2,tableSize+2): for y in range(2,tableSize+2): sheet.cell(row=x, column=y).value = sheet.cell(row=x, column=1).value * sheet.cell(row=1, column=y).value #Save the new workbook wb.save('multiTable.xlsx')
true
43e0551fe36887ca2b140c7ab04352332c3b499f
DhruvGala/LearningPython_sample_codes
/TowerOfHanoi.py
1,014
4.1875
4
''' Created on Oct 10, 2015 @author: DhruvGala The following code is a general implementation of Tower of hanoi problem using python 3. ''' from pip._vendor.distlib.compat import raw_input ''' The following method carries out the recursive method calls to solve the tower of hanoi problem. ''' def towerOfHanoi(number,source,inter,dest): if(number == 1): print("Disk 1 from {} to {} ".format(source,dest)) else: towerOfHanoi(number-1, source, dest, inter) print("Disk {} from {} to {}".format(number,source,dest)) towerOfHanoi(number-1, inter, source, dest) ''' the main method ''' def main(): towerOfHanoi(takeInput(),"A","B","C") ''' takes the input as the number of disk involved in the problem. ''' def takeInput(): n = raw_input("Enter the number of disks: ") try: nDisk = int(n) except: print("Invalid input") return nDisk; #call the main method if __name__ == "__main__": main()
true
f916bcbca35a5b84111b9894f85bcc637628d1ff
arimont123/python-challenge
/PyBank/main.py
2,137
4.125
4
import os import csv #python file in same folder as budget_data.csv csvpath = "budget_data.csv" with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter = ",") #start reading in data after first row of text csvheader = next(csvreader) #create empty lists to store data from each column date = [] prof_loss = [] #loop through columns in file for row in csvreader: date.append(row[0]) prof_loss.append(float(row[1])) num_months = len(date) #calculates total number of months net_prof_loss = sum(prof_loss) #calculates net prof/loss over entire period #create empty list to store changes in prof/loss over time change = [] for i in range(1,len(prof_loss)): #calculates difference in current month and previous month change.append(prof_loss[i]-prof_loss[i-1]) avg_change = sum(change)/len(change) #find max and min change max_change = max(change) min_change = min(change) #For loop loops from 1 to length of prof/loss column #Add 1 to the index of change in order to match index of date max_date = str(date[change.index(max(change))+1]) min_date = str(date[change.index(min(change))+1]) #Print results to terminal print("Financial Analysis") print("-----------------------------------") print(f"Total Months: {num_months}") print(f"Total: $ {round(net_prof_loss)}") print(f"Average Change: ${round(avg_change,2)}") print(f"Greatest Increase in Profits: {max_date} (${round(max_change)})") print(f"Greatest Decrease in Profits: {min_date} (${round(min_change)})") #Output results into text file f= open("bank_results.txt", 'w+') f.write("Financial Analysis\n") f.write("-----------------------------------\n") f.write(f"Total Months: {num_months}\n") f.write(f"Total: $ {round(net_prof_loss)}\n") f.write(f"Average Change: ${round(avg_change,2)}\n") f.write(f"Greatest Increase in Profits: {max_date} (${round(max_change)})\n") f.write(f"Greatest Decrease in Profits: {min_date} (${round(min_change)})\n")
true
29c45bbdc3bf5ff5b822dbffc16ce7e1a91e7037
kml1972/python-tutorials
/code/tutorial_27.py
1,125
4.1875
4
shopping_list = [ 'milk','eggs','bacon','beef', 'soup','bread','mustard','toothpaste' ] # looping by index vs using an iterator i = 0 while i < len(shopping_list): curr_item = shopping_list[i] print( curr_item ) i += 1 for curr_item in shopping_list: print( curr_item ) #shopping_list.__iter__() pencil_holder = iter(shopping_list) #pencil_holder.__next__() first = next(pencil_holder) sec = next(pencil_holder) print( first, sec ) # very large generator expression pow_three = (n ** 3 for n in range(1000000000000)) # if you used a list comprehension you'd most likely run out of memory. #pow_three = [n ** 3 for n in range(1000000000)] # the generator will only calculate the first 10 powers of three and then pause until you use next() again for t in range(10): print(t, next(pow_three) ) # prints out the eleventh power of 3 print( next(pow_three) ) # use generators to create previous comprehensions pow_four = tuple(n ** 4 for n in range(10)) pow_five = list(n ** 5 for n in range(10)) pow_six = set(n ** 6 for n in range(10)) pow_sev = dict( (n, n ** 7) for n in range(10))
true
3c99da6c123b0f76b02f11746f584acd92c00c48
LKHUUU/SZU_Learning_Resource
/计算机与软件学院/Python程序设计/实验/实验1/problem1.py
228
4.3125
4
import math radius = float(input("Enter the radius of a cylinder:")) length = float(input("Enter the length of a cylinder:")) area = radius*radius*math.pi print("The area is", area) print("The volume is", area*length)
true
502edac5b8c26c2ef81609d497f8084db91f0401
zhaphod/ProjectEuler
/Python/proj_euler_problem_0001.py
651
4.15625
4
''' Problem 1 Multiples of 3 and 5 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. ''' sum = 0 def EulerProblem0001(): global sum for i in range(1, 1000): if i % 5 == 0 or i % 3 == 0: print(i, end=" ") sum += i print("Sum with for loop = " + str(sum)) sum = 0 sum += 3 * (333 * 334 / 2) sum += 5 * (199 * 200 / 2) sum -= 15 * (66 * 67 / 2) print("Sum with closed form = " + str(sum)) if __name__ == "__main__": print("Euler problem one") EulerProblem0001() print("Sum = " + str(sum))
true
c65e8e6d41ac120b28cf31d9f9dcf4f74d78c45e
leonguevara/DaysInAMonth_Python
/main.py
930
4.625
5
# main.py # DaysInAMonth_Python # # This program will give you the number of days of any given month of any given year # # Python interpreter: 3.6 # # Author: León Felipe Guevara Chávez # email: leon.guevara@itesm.mx # date: May 31, 2017 # # We ask for and read the month's number month = int(input("Give me the number of the month (1 - 12): ")) # We ask for and read the year's number year = int(input("Give me the number of the year (XXXX): ")) # We find out the number of days that last this particular month if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12: daysOfMonth = 31 elif month == 4 or month == 6 or month == 9 or month == 11: daysOfMonth = 30 else: if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0): daysOfMonth = 29 else: daysOfMonth = 28 # We display our findings print("The numbers of days in this month is " + str(daysOfMonth))
true
75972d8413cedaba4efe98bc5c28bbfed5c093ca
jungjung917/Coderbyte_challenges
/easy/solutions/ThirdGreatest.py
1,142
4.5
4
""" Using the Python language, have the function ThirdGreatest(strArr) take the array of strings stored in strArr and return the third largest word within in. So for example: if strArr is ["hello", "world", "before", "all"] your output should be world because "before" is 6 letters long, and "hello" and "world" are both 5, but the output should be world because it appeared as the last 5 letter word in the array. If strArr was ["hello", "world", "after", "all"] the output should be after because the first three words are all 5 letters long, so return the last one. The array will have at least three strings and each string will only contain letters. """ def ThirdGreatest(strArr): len_dic = {} for index, word in enumerate(strArr): len_dic[index] = len(word) for i in range(0,2): max_value = max(len_dic.values()) for k,v in len_dic.items(): if v == max_value: del len_dic[k] break keys = len_dic.keys() values = len_dic.values() max_index = values.index(max(len_dic.values())) return strArr[keys[max_index]] print ThirdGreatest(["one","two","three"])
true
bd5801f9768c16fdf16d9992dd47f5506cbdedcc
jungjung917/Coderbyte_challenges
/medium/solutions/StringScramble.py
572
4.375
4
""" the function StringScramble(str1,str2) take both parameters being passed and return the string true if a portion of str1 characters can be rearranged to match str2, otherwise return the string false. For example: if str1 is "rkqodlw" and str2 is "world" the output should return true. Punctuation and symbols will not be entered with the parameters. """ def StringScramble(str1,str2): for letter in str2.lower(): if letter not in str1.lower(): return "false" return "true" print StringScramble("cdore","coder") print StringScramble("ctiye","colrd")
true
26e0e5220c163bfc0631b25aabfb7395f986c941
Endlex-net/practic_on_lintcode
/reverse-linked-list/code.py
600
4.21875
4
#-*-coding: utf-8 -*- """ Definition of ListNode 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. """ def reverse(self, head): # write your code here now = head temp = None while now: next = now.next now.next = temp temp = now now = next return temp
true