blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
6ebdc47b984d3f9b7b65663b2ba01f9b54fc7edf
dks1018/CoffeeShopCoding
/2021/Code/Python/Exercises/Calculator2.py
1,480
4.1875
4
# Variable statements Number1 = input("Enter your first number: ") Number2 = input("Enter your second number: ") NumberAsk = input("Would you like to add a third number? Y or N: ") if NumberAsk == str("Y"): Number3 = input("Please enter your third number: ") Operation = input("What operation would you like to perform on these numbers? +, -, *, or /? ") # Operations Sum = (int(Number1) + int(Number2)) # noinspection PyUnboundLocalVariable Sum2 = (int(Number1) + int(Number2) + int(Number3)) Difference = (int(Number1) - int(Number2)) Difference2 = (int(Number1) - int(Number2) - int(Number3)) Product = (int(Number1) * int(Number2)) Product2 = (int(Number1) * int(Number2) * int(Number3)) Quotient = (int(Number1) / int(Number2)) Quotient2 = (int(Number1) / int(Number2) / int(Number3)) # Variable operations Addition = "+" Subtraction = "-" Multiplication = "*" Division = "/" # Conditionals if Operation == str("+") and NumberAsk == str("N"): print(Sum) if Operation == str("+") and NumberAsk == str("Y"): print(Sum2) if Operation == str("-") and NumberAsk == str("N"): print(Difference) if Operation == str("-") and NumberAsk == str("Y"): print(Difference2) if Operation == str("*") and NumberAsk == str("N"): print(Product) if Operation == str("*") and NumberAsk == str("Y"): print(Product2) if Operation == str("/") and NumberAsk == str("N"): print(Quotient) if Operation == str("/") and NumberAsk == str("Y"): print(Quotient2)
true
7b98a668260b8d5c0b729c6687e6c0a878574c9d
ajanzadeh/python_interview
/games/towers_of_hanoi.py
1,100
4.15625
4
# Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: # 1) Only one disk can be moved at a time. # 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. # 3) No disk may be placed on top of a smaller disk. # Take an example for 2 disks : # Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'. # # Step 1 : Shift first disk from 'A' to 'B'. # Step 2 : Shift second disk from 'A' to 'C'. # Step 3 : Shift first disk from 'B' to 'C'. # # The pattern here is : # Shift 'n-1' disks from 'A' to 'B'. # Shift last disk from 'A' to 'C'. # Shift 'n-1' disks from 'B' to 'C'. def tower(n,source,helper,dest): if n == 1: print("move disk",n, "from", source,"to",dest) return else: tower(n-1,source,dest,helper) print("move disk",n,"from",source,"to", dest) tower(n-1,helper,source,dest) tower(5,"a","b","c")
true
ca091bae52a3e79cece2324fe946bc6a52ca6c2f
mrmuli/.bin
/scripts/python_datastructures.py
2,019
4.15625
4
# I have decided to version these are functions and operations I have used in various places from mentorship sessions # articles and random examples, makes it easier for me to track on GitHub. # Feel free to use what you want, I'll try to document as much as I can :) def sample(): """ Loop through number range 1 though 11 and multiply by 2 """ total = 0 # to be explicit about even numbers, you can add a step to range as: range(2,11,2) for number in range(2, 101, 2): # If the number is 4, skip and continue if number == 4: continue total += number # Calculate the product of number and 2 product = number * 2 # Print out the product in a friendly way print(number, '* 2 = ', product) # sample() def password_authenticate(): """ A very simple way to validate or authenticate """ # set random value and Boolean check. (This is subject to change, on preference.) user_pass = "potato" valid = False while not valid: password = input("Please enter your password: ") if password == user_pass: print("welcome back user!") valid = True else: print("Wrong password, please try again.") print("bye!") # password_authenticate() # use of pass, continue and break def statements_demo(): for number in range(0, 200): if number == 0: continue elif number % 3 != 0: continue elif type(number) != int: break else: pass print(number) # statements_demo() def nested_example(): for even in range(2, 11, 2): for odd in range(1, 11, 2): val = even + odd print(even, "+", odd, "=", val) print(val) # nested_example() def randome_args(*args): for value in args: if type(value) == int: continue print(value) # randome_args(1,2,3,4,"five","six","seven",8,"nine",10)
true
356122c10a2bb46ca7078e78e991a08781c46254
KingHammer883/21.Testing-for-a-Substring-with-the-in-operator.py
/21.Testing-for-Substring-With-the-in-operator.py
752
4.40625
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 18, 2019 File: Testing for a Substring with the in operator @author: Byen23 Another problem involves picking out strings that contains known substrings. FOr example you might wnat to pick out filenames with a .txt extension. A slice would work for this but using Python's in operator is the right operand is the string to be searched. The operator in returns True if the target string is somewhere in teh search string, or False otherwise. The next code segment traverses a list of filenames and prints just the filenames taht have a .txt extension: """ filelist = ["myfile.txt", "myprogram.exe", "yourfile.txt"] for fileName in filelist: if ".txt" in fileName: print(fileName)
true
0606ac38799bfe01af2feda28a40d7b863867569
PacktPublishing/Python-for-Beginners-Learn-Python-from-Scratch
/12. Downloading data from input/downloading-data.py
260
4.15625
4
print("Program that adds two numbers to each other") a = int(input("First number: ")) b = int(input("Second number: ")) #CASTING allows you to change ONE type of variable to another type of variable print("Sum of a =", a, "+", "b =", b, "is equal to", a + b)
true
9dbcec24d2b156aa7f69a8bf1e65ade631e0eea3
sdelpercio/cs-module-project-recursive-sorting
/src/sorting/sorting.py
2,202
4.1875
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [None] * elements # Your code here while None in merged_arr: if not arrA: popped = arrB.pop(0) first_instance = merged_arr.index(None) merged_arr[first_instance] = popped elif not arrB: popped = arrA.pop(0) first_instance = merged_arr.index(None) merged_arr[first_instance] = popped elif arrA[0] < arrB[0]: popped = arrA.pop(0) first_instance = merged_arr.index(None) merged_arr[first_instance] = popped elif arrB[0] < arrA[0]: popped = arrB.pop(0) first_instance = merged_arr.index(None) merged_arr[first_instance] = popped else: continue return merged_arr # TO-DO: implement the Merge Sort function below recursively def merge_sort(arr): # base case if len(arr) == 0 or len(arr) == 1: return arr # recursive case elif len(arr) == 2: return merge([arr[0]], [arr[1]]) else: middle = (len(arr) - 1) // 2 left = arr[:middle] right = arr[middle:] return merge(merge_sort(left), merge_sort(right)) return arr # STRETCH: implement the recursive logic for merge sort in a way that doesn't # utilize any extra memory # In other words, your implementation should not allocate any additional lists # or data structures; it can only re-use the memory it was given as input def merge_in_place(arr, start, mid, end): swapped = False while True: swapped = False for i in range(start, end): if arr[i] > arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] swapped = True if swapped == False: break return arr def merge_sort_in_place(arr, l, r): # base case if l < r: middle = l + (r - l) // 2 merge_sort_in_place(arr, l, middle) merge_sort_in_place(arr, middle + 1, r) merge_in_place(arr, l, middle, r) return arr
true
e0f808f1c93b832eeb29f9133a86ce99dbbe678d
NuradinI/simpleCalculator
/calculator.py
2,097
4.40625
4
#since the code is being read from top to bottom you must import at the top import addition import subtraction import multiplication import division # i print these so that the user can see what math operation they will go with print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") #this is a while loop, different from the for loop in that it will not run 'x' amount of times, #a while loop runs as a set of code if the condition defined is true # here i create the while loop by writing while and then true so that the code statements below #only execute when true, i add the : to start it up while True: #here i define the variable Userchoice, then i put the input function which allows for user input # i give the user a choice to enter values UserChoice = input("Choose (1,2,3,4): ") #if the users choice is 1 2 3 4 run this code if UserChoice in ('1', '2', '3', '4'): #the code that is run is a input in which the first number is a variable that stores the users input num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) #if the userschoice is equal to one, print the value of num1 concatonate with a string that shows #that the content was added and concatonate with a = and then run the function that acc does the math #that is now called back so the value of x, y is now the variables num1 and num2 if UserChoice == '1': print(num1, "+", num2, "=", addition.addNum(num1, num2)) elif UserChoice == '2': print(num1, "-", num2, "=", subtraction.subtractNum(num1, num2)) elif UserChoice == '3': print(num1, "*", num2, "=", multiplication.multiplyNum(num1, num2)) elif UserChoice == '4': print(num1, "/", num2, "=", division.divideNum(num1, num2)) #we use the break to stop the code, otherwise the if the conditions remain true the code #will run up again, its basically a period i think break else: #if they dont chose any print invalid input print("pick a num 1 - 4 silly ")
true
8ba9f444797916c33a00ce7d7864b1fa60ae6f24
Bongkot-Kladklaen/Programming_tutorial_code
/Python/Python_basic/Ex24_UserInput.py
271
4.1875
4
#* User Input """ Python 3.6 uses the input() method. Python 2.7 uses the raw_input() method. """ #* Python 3.6 username = input("Enter username:") print("Username is: " + username) #* Python 2.7 username = raw_input("Enter username:") print("Username is: " + username)
true
d982dbcd9d34ecfd77824b309e688f9e077093d5
gcvalderrama/python_foundations
/DailyCodingProblem/phi_montecarlo.py
1,292
4.28125
4
import unittest # The area of a circle is defined as πr ^ 2. # Estimate π to 3 decimal places using a Monte Carlo method. # Hint: The basic equation of a circle is x2 + y2 = r2. # we will use a basic case with r = 1 , means area = π ^ 2 and x2 + y2 <=1 # pi = The ratio of a circle's circumference to its diameter # https://www.youtube.com/watch?v=PLURfYr-rdU import random def get_rand_number(min_value, max_value): """ This function gets a random number from a uniform distribution between the two input values [min_value, max_value] inclusively Args: - min_value (float) - max_value (float) Return: - Random number between this range (float) """ range = max_value - min_value choice = random.uniform(0, 1) return min_value + range * choice def estimate(): square_points = 0 circle_points = 0 for i in range(1000000): x = get_rand_number(0, 1) y = get_rand_number(0, 1) dist = x ** 2 + y ** 2 if dist <= 1: circle_points += 1 square_points += 1 pi = 4 * (circle_points / square_points) return pi class Test(unittest.TestCase): def test_monte_carlo(self): print(estimate()) if __name__ == "__main__": unittest.main()
true
24cf6864b5eb14d762735a27d79f96227438392f
ramalldf/data_science
/deep_learning/datacamp_cnn/image_classifier.py
1,545
4.28125
4
# Image classifier with Keras from keras.models import Sequential from keras.layers import Dense # Shape of our training data is (50, 28, 28, 1) # which is 50 images (at 28x28) with only one channel/color, black/white print(train_data.shape) model = Sequential() # First layer is connected to all pixels in original image model.add(Dense(10, activation='relu', input_shape=(784,))) # 28x28 = 784, so one input from every pixel # More info on the Dense layer args: https://keras.io/api/layers/core_layers/dense/ # First arg is units which corresponds to dimensions of output model.add(Dense(10, activation='relu')) model.add(Dense(10, activation='relu')) # Unlike hidden layers, output layer has 3 for output (for 3 classes well classify) # and a softmax layer which is used for classifiers model.add(Dense(3, activation='softmax')) # Model needs to be compiled before it is fit. loss tells it to optimize for classifier model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # Prepare data (needs to be tabular so 50 rows and 784 cols) train_data = train_data.reshape((50, 784)) # Fit model # To avoid overfiting we set aside 0.2 of images for validation set # We'll send data through NN 3 times (epochs) and test on that validation set model.fit(train_data, train_labels, validation_split=0.2, epochs=3) # Evaluate on test set that's not evaluation set using the evaluation function test_data = test_data.reshape((10, 784)) model.evaluate(test_data, test_labels)
true
60b60160f8677cd49552fedcf862238f9128f326
Prash74/ProjectNY
/LeetCode/1.Arrays/Python/reshapematrix.py
1,391
4.65625
5
""" You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively. The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were. If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. Example 1: Input: nums = [[1,2], [3,4]] r = 1, c = 4 Output: [[1,2,3,4]] Explanation: The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list. Example 2: Input: nums = [[1,2], [3,4]] r = 2, c = 4 Output: [[1,2], [3,4]] Explanation: There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix. Note: The height and width of the given matrix is in range [1, 100]. The given r and c are all positive. """ def matrixReshape(nums, r, c): """ :type nums: List[List[int]] :type r: int :type c: int :rtype: List[List[int]] """ if r*c != len(nums)*len(nums[0]): return nums nums = [i for item in nums for i in item] val = [] for i in range(0, len(nums), c): val.append(nums[i:i+c]) return val nums = [[1, 2], [3, 4]] r = 1 c = 4 print matrixReshape(nums, r, c)
true
3d999f7baa9c6610b5b93ecf59506fefd421ff86
Minglaba/Coursera
/Conditions.py
1,015
4.53125
5
# equal: == # not equal: != # greater than: > # less than: < # greater than or equal to: >= # less than or equal to: <= # Inequality Sign i = 2 i != 6 # this will print true # Use Inequality sign to compare the strings "ACDC" != "Michael Jackson" # Compare characters 'B' > 'A' # If statement example age = 19 #age = 18 #expression that can be true or false if age > 18: #within an indent, we have the expression that is run if the condition is true print("you can enter" ) #The statements after the if statement will run regardless if the condition is true or false print("move on") # Condition statement example album_year = 1990 if(album_year < 1980) or (album_year > 1989): print ("Album was not made in the 1980's") else: print("The Album was made in the 1980's ") # Write your code below and press Shift+Enter to execute album_year = 1991 if album_year < 1980 or album_year == 1991 or album_year == 1993: print(album_year) else: print("no data")
true
f256746a37c0a050e56aafca1315a517686f96c8
luxorv/statistics
/days_old.py
1,975
4.3125
4
# Define a daysBetweenDates procedure that would produce the # correct output if there was a correct nextDay procedure. # # Note that this will NOT produce correct outputs yet, since # our nextDay procedure assumes all months have 30 days # (hence a year is 360 days, instead of 365). # def isLeapYear(year): if year%4 != 0: return False elif year%100 !=0: return True elif year%400 !=0: return False else: return True def daysInMonth(month, year): daysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if month == 2 and isLeapYear(year): daysOfMonths[month-1] += 1 return daysOfMonths[month-1] def nextDay(year, month, day): """Simple version: assume every month has 30 days""" if day < daysInMonth(month, year): return year, month, day + 1 else: if month == 12: return year + 1, 1, 1 else: return year, month + 1, 1 def daysBetweenDates(year1, month1, day1, year2, month2, day2): """Returns the number of days between year1/month1/day1 and year2/month2/day2. Assumes inputs are valid dates in Gregorian calendar, and the first date is not after the second.""" # YOUR CODE HERE! days = 0 second_date = (year2, month2, day2) first_date = (year1, month1, day1) assert not first_date > second_date while first_date < second_date: days += 1 first_date = nextDay(*first_date) return days def test(): test_cases = [((2012,1,1,2012,2,28), 58), ((2012,1,1,2012,3,1), 60), ((2011,6,30,2012,6,30), 366), ((2011,1,1,2012,8,8), 585 ), ((1900,1,1,1999,12,31), 36523)] for (args, answer) in test_cases: result = daysBetweenDates(*args) if result != answer: print "Test with data:", args, "failed" else: print "Test case passed!" test()
true
bf6d09ae3d5803425cf95dd4e53fe62dad41fda0
reveriess/TarungLabDDP1
/lab/01/lab01_f.py
618
4.6875
5
''' Using Turtle Graphics to draw a blue polygon with customizable number and length of sides according to user's input. ''' import turtle sides = int(input("Number of sides: ")) distance = int(input("Side's length: ")) turtle.color('blue') # Set the pen's color to blue turtle.pendown() # Start drawing deg = 360 / sides # Calculate the turn for i in range(sides): turtle.forward(distance) # By using loop, turn and turtle.left(deg) # move the turtle forward turtle.hideturtle() # Hide the turtle/arrow turtle.exitonclick() # Close the window on click event
true
2c2b4f56fc3f3c0c76ba69866da852edcfbf8186
Anshikaverma24/to-do-app
/to do app/app.py
1,500
4.125
4
print(" -📋YOU HAVE TO DO✅- ") options=["edit - add" , "delete"] tasks_for_today=input("enter the asks you want to do today - ") to_do=[] to_do.append(tasks_for_today) print("would you like to do modifications with your tasks? ") edit=input("say yes if you would like edit your tasks - ") if edit=="yes": add=input("say yes if you would like add some more tasks - ") if add=="yes": added=input("enter the task you would like to add - ") to_do.append(added) delete=input('say yes if you would like delete your tasks - ') for i in range(len(to_do)): print(to_do[i]) if delete=="yes": delte=input("enter the task you want to delete - ") to_do.remove(delte) for i in range(len(to_do)): print(to_do[i]) print("NUMBER OF TASKS YOU HAVE TO DO TODAY") i=0 tasks=0 while i<len(to_do): tasks=tasks+1 i+=1 print(tasks) done_tasks=int(input("enter the total number of tasks that you have completed : ")) in_progress=int(input("enter the number of tasks which are in progress : ")) not_done=int(input("enter the number of tasks which you haven't done : ")) status=[done_tasks , in_progress , not_done] i=0 sum=0 while i<len(status): sum=sum+status[i] print(sum) i+=1 if sum>len(to_do): print("your tasks is more than total number of tasks, please check the tasks once") elif sum<len(to_do): print("your tasks is less than the total number of tasks,please check the tasks once") else: print("your schedule have been set")
true
6fd57771b4a4fdbd130e6d408cd84e02f89f48a4
Jayasuriya007/Sum-of-three-Digits
/addition.py
264
4.25
4
print ("Program To Find Sum of Three Digits") def addition (a,b,c): result=(a+b+c) return result a= int(input("Enter num one: ")) b= int(input("Enter num one: ")) c= int(input("Enter num one: ")) add_result= addition(a,b,c) print(add_result)
true
2da2d69eb8580ba378fac6dd9eff065e2112c778
sk24085/Interview-Questions
/easy/maximum-subarray.py
898
4.15625
4
''' Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A subarray is a contiguous part of an array. Example 1: Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Example 2: Input: nums = [1] Output: 1 Example 3: Input: nums = [5,4,-1,7,8] Output: 23 ''' class Solution: def maxSubArray(self, nums: List[int]) -> int: # sliding window len_nums = len(nums) if len_nums == 1: return nums[0] cur_sum, max_so_far, i, j = 0, -99999999, 0, 1 while(i<len_nums): cur_sum += nums[i] if cur_sum > max_so_far: max_so_far = cur_sum if cur_sum <= 0: cur_sum = 0 i += 1 return max_so_far
true
daa21099590ab6c4817de8135937e9872d2eb816
sk24085/Interview-Questions
/easy/detect-capital.py
1,464
4.34375
4
''' We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capitals, like "leetcode". Only the first letter in this word is capital, like "Google". Given a string word, return true if the usage of capitals in it is right. Example 1: Input: word = "USA" Output: true Example 2: Input: word = "FlaG" Output: false ''' class Solution: def allUpper(self,str): for char in str: ascii_code = ord(char) if ascii_code <65 or ascii_code >90: return False print('returning true') return True def allLower(self,str): for char in str: ascii_code = ord(char) if ascii_code <97 or ascii_code >122: return False return True def detectCapitalUse(self, word: str) -> bool: # case when only one letter exists if len(word) == 1: return True # get the first capital letter firstCapital = word[0].isupper() # get the second caspital letter secondCapital = word[1].isupper() # conditions if firstCapital and secondCapital: # all others should be upper return self.allUpper(word[1:]) elif firstCapital: return self.allLower(word[1:]) else: return self.allLower(word[1:])
true
bca49786c266839dc0da317a76d6af24b20816e5
mtahaakhan/Intro-in-python
/Python Practice/input_date.py
708
4.28125
4
# ! Here we have imported datetime and timedelta functions from datetime library from datetime import datetime,timedelta # ! Here we are receiving input from user, when is your birthday? birthday = input('When is your birthday (dd/mm/yyyy)? ') # ! Here we are converting input into birthday_date birthday_date = datetime.strptime(birthday, '%d/%m/%Y') # ! Here we are printing birthday date print('Birthday: ' + str(birthday_date)) # ! Here we are again just asking one day before from timedelta one_day = timedelta(days=1) birthday_eve = birthday_date - one_day print('Day before birthday: ' + str(birthday_eve)) # ! Now we will see Error Handling if we receive birthday date in spaces or ashes.
true
2937f2007681af5aede2a10485491f8d2b5092cf
mtahaakhan/Intro-in-python
/Python Practice/date_function.py
649
4.34375
4
# Here we are asking datetime library to import datetime function in our code :) from datetime import datetime, timedelta # Now the datetime.now() will return current date and time as a datetime object today = datetime.now() # We have done this in last example. print('Today is: ' + str(today)) # Now we will use timedelta # Here, from timedelta we are getting yesterdays date time one_day = timedelta(days=1) yesterday = today - one_day print('Yesterday was: ' + str(yesterday)) # Here, from timedelta we are getting last weeks date time one_week = timedelta(weeks=1) last_week = today - one_week print('Last week was: ' + str(last_week))
true
e797aa24ce9fbd9354c04fbbf853ca63e967c827
xtdoggx2003/CTI110
/P4T2_BugCollector_AnthonyBarnhart.py
657
4.3125
4
# Bug Collector using Loops # 29MAR2020 # CTI-110 P4T2 - Bug Collector # Anthony Barnhart # Initialize the accumlator. total = 0 # Get the number of bugs collected for each day. for day in range (1, 6): # Prompt the user. print("Enter number of bugs collected on day", day) # Input the number of bugs. bugs = int (input()) # Add bugs to toal. total = total + bugs # Display the total bugs. print("You have collected a total of", total, "bugs") # Psuedo Code # Set total = 0 # For 5 days: # Input number of bugs collected for a day # Add bugs collected to total number of bugs # Display the total bugs
true
6e7401d2ed0a82b75f1eaec51448f7f20476d46e
xtdoggx2003/CTI110
/P3HW1_ColorMix_AnthonyBarnhart.py
1,039
4.40625
4
# CTI-110 # P3HW1 - Color Mixer # Antony Barnhart # 15MAR2020 # Get user input for primary color 1. Prime1 = input("Enter first primary color of red, yellow or blue:") # Get user input for primary color 2. Prime2 = input("Enter second different primary color of red, yellow or blue:") # Determine secondary color and error if not one of three listed colors if Prime1 == "red" and Prime2 == "yellow" or Prime1 == "yellow" and Prime2 == "red": print("orange") elif Prime1 == "blue" and Prime2 == "yellow" or Prime1 == "yellow" and Prime2 == "blue": print("green") elif Prime1 == "blue" and Prime2 == "red" or Prime1 == "red" and Prime2 == "blue": print("purple") else: print("error") # Pseudocode # Ask user to input prime color one # Ask user to imput prime color two # Only allow input of three colors Red, Yellow, Blue # Determine the secondary color based off of user input # Display secondary color # Display error if any color outside of given perameters is input
true
c3ffa8b82e2818647adda6c69245bbc9841ffd76
tsuganoki/practice_exercises
/strval.py
951
4.125
4
"""In the first line, print True if has any alphanumeric characters. Otherwise, print False. In the second line, print True if has any alphabetical characters. Otherwise, print False. In the third line, print True if has any digits. Otherwise, print False. In the fourth line, print True if has any lowercase characters. Otherwise, print False. In the fifth line, print True if has any uppercase characters. Otherwise, print False.""" s = "6$%^#" alph = False alphanumeric = False digits = False lowercase = False uppercase = False if len(s) < 1000: for l in s: if l.isalpha(): alph = True if l.isdigit(): digits = True if l.isalnum(): alphanumeric = True if l.islower(): lowercase = True if l.isupper(): uppercase = True print(alphanumeric) print(alph) print(digits) print(lowercase) print(uppercase)
true
4d1605f77acdf29ee15295ba9077d47bc3f62607
zakwan93/python_basic
/python_set/courses.py
1,678
4.125
4
# write a function named covers that accepts a single parameter, a set of topics. # Have the function return a list of courses from COURSES # where the supplied set and the course's value (also a set) overlap. # For example, covers({"Python"}) would return ["Python Basics"]. COURSES = { "Python Basics": {"Python", "functions", "variables", "booleans", "integers", "floats", "arrays", "strings", "exceptions", "conditions", "input", "loops"}, "Java Basics": {"Java", "strings", "variables", "input", "exceptions", "integers", "booleans", "loops"}, "PHP Basics": {"PHP", "variables", "conditions", "integers", "floats", "strings", "booleans", "HTML"}, "Ruby Basics": {"Ruby", "strings", "floats", "integers", "conditions", "functions", "input"} } def covers(courses): answer = [] for key,value in COURSES.items(): if value.intersections(courses): answer.append(key) return answer # Create a new function named covers_all that takes a single set as an argument. # Return the names of all of the courses, in a list, where all of the topics # in the supplied set are covered. # For example, covers_all({"conditions", "input"}) would return # ["Python Basics", "Ruby Basics"]. Java Basics and PHP Basics would be excluded # because they don't include both of those topics. def covers_all(topics): answer = [] for course,value in COURSES.items(): if (value & topics) == topics: answer.append(course) return answer
true
6ce838e30b83b79bd57c65231de2656f63945486
prashant2109/django_login_tas_practice
/python/Python/oops/polymorphism_info.py
2,144
4.40625
4
# Method Overriding # Same method in 2 classes but gives the different output, this is known as polymorphism. class Bank: def rateOfInterest(self): return 0 class ICICI(Bank): def rateOfInterest(self): return 10.5 if __name__ == '__main__': b_Obj = Bank() print(b_Obj.rateOfInterest()) ##############################################################################################33 # Polymorphism with class class Cat: def __init__(self, name): self.name = name def info(self): print(f'My name is {self.name}. I belong to cat family.') def make_sound(self): print('meow') class Dog: def __init__(self, name): self.name = name def info(self): print(f'My name is {self.name}. I belong to Dog family.') def make_sound(self): print('Bark') cat = Cat('kitty') dog = Dog('tommy') # Here we are calling methods of 2 different class types with common variable 'animal' for animal in (cat, dog): print(animal.info()) print(animal.make_sound()) ############################################################################################################# class India(): def capital(self): print("New Delhi") def language(self): print("Hindi and English") class USA(): def capital(self): print("Washington, D.C.") def language(self): print("English") obj_ind = India() obj_usa = USA() for country in (obj_ind, obj_usa): country.capital() country.language() ######################################################################################################## class Bird: def intro(self): print("There are different types of birds") def flight(self): print("Most of the birds can fly but some cannot") class parrot(Bird): def flight(self): print("Parrots can fly") class penguin(Bird): def flight(self): print("Penguins do not fly") obj_bird = Bird() obj_parr = parrot() obj_peng = penguin() obj_bird.intro() obj_bird.flight() obj_parr.intro() obj_parr.flight() obj_peng.intro() obj_peng.flight()
true
f7b7853e9332ef9fd2a5c16733f1908c00ea2a04
redoctoberbluechristmas/100DaysOfCodePython
/Day03 - Control Flow and Logical Operators/Day3Exercise3_LeapYearCalculator.py
826
4.375
4
#Every year divisible by 4 is a leap year. #Unless it is divisible by 100, and not divisible by 400. #Conditional with multiple branches year = int(input("Which year do you want to check? ")) if(year % 4 == 0): if(year % 100 == 0): if(year % 400 == 0): print("Leap year.") else: print("Not leap year.") else: print("Leap year.") else: print("Not leap year.") #Refactored using more condense conditional statement. #"If a year is divisible by 4, and it is either not divisible by 100, or is not not divisible by 100 but is # divisible by 400, then it is a leap year. Otherwise, it is not a leap year." if(year % 4 == 0) and ((not year % 100 == 0) or (year % 400 == 0)): #if(year % 4 == 0) and ((year % 100 != 0) or (year % 400 == 0)): print("Leap year.") else: print("Not leap year.")
true
d167ac2865745d4e015ac1c8565dd07fba06ef4d
redoctoberbluechristmas/100DaysOfCodePython
/Day21 - Class Inheritance/main.py
777
4.625
5
# Inheriting and modifying existing classes allows us to modify without reinventing the wheel.add class Animal: def __init__(self): self.num_eyes = 2 def breathe(self): print("Inhale, exhale.") class Fish(Animal): def __init__(self): super().__init__() # The call to super() in the initializer is recommended, but not strictly required. def breathe(self): # Extend an inherited method. Running this will produce "Inhale, exhale" \n "doing this underwater." Wont' totally override the method. super().breathe() print("doing this underwater.") def swim(self): print("moving in water.") nemo = Fish() nemo.swim() # Inherit methods. nemo.breathe() # Inherit attributes. print(nemo.num_eyes)
true
d999a0fd4f5a5516a6b810e76852594257174245
redoctoberbluechristmas/100DaysOfCodePython
/Day08 - Functions with Parameters/cipherfunctions.py
846
4.125
4
alphabet = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ] def caesar(start_text, shift_amount, cipher_direction): output_text = "" # Will divide the shift amount to fit into length of alphabet. shift_amount = shift_amount % 26 if cipher_direction == "decode": shift_amount *= -1 for char in start_text: if char in alphabet: start_index = alphabet.index(char) end_index = start_index + shift_amount output_text += alphabet[end_index] else: output_text += char print(f"The {cipher_direction}d text is {output_text}.")
true
9006fe1d04ceee567b8ced73bddd2562d0239fb8
zhartole/my-first-django-blog
/python_intro.py
1,313
4.21875
4
from time import gmtime, strftime def workWithString(name): upper = name.upper() length = len(name) print("- WORK WITH STRING - " + name * 3) print(upper) print(length) def workWithNumber(numbers): print('- WORK WITH NUMBERS') for number in numbers: print(number) if number >= 0: print("--positive val") else: print("--negative val") def addItemToDictionary(key,value): dictionaryExample = {'name': 'Olia', 'country': 'Ukraine', 'favorite_numbers': [90, 60, 90]} dictionaryExample[key] = value print('- WORK WITH DICTIONARY') print(dictionaryExample) def workWithFor(): for x in range(0, 3): print("We're in for ") def workWithWhile(): x = 1 while (x < 4): print("Were in while") x += 1 def showBasicType(): text = "Its a text" number = 3 bool = True date = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) print(text) print(number) print(bool) print(date) def hi(name): print('Hi ' + name + '!' + ' Lets show you a few example of Python code') def init(): hi('Victor') workWithString("Igor") workWithNumber([1, 5, 4, -3]) addItemToDictionary('new', 'child') workWithFor() workWithWhile() showBasicType() init()
true
b5b8ad763c493b7e79cd419bdc08170b1a11dd58
TranshumanSoft/quotient-and-rest
/modulexercises.py
268
4.15625
4
fstnumber = float(input("Introduce a number:")) scndnumber = float(input("Introduce another number:")) quotient = fstnumber//scndnumber rest = fstnumber%scndnumber print(f"Between {fstnumber} and {scndnumber} there's a quotient of {quotient} and a rest of {rest}")
true
bd6b8a39bd376c6bcf9a3a56a4a70453159e05f4
baixianghuang/algorithm
/python3/merge_linked_lists.py
2,215
4.3125
4
class ListNode: def __init__(self, val): self.val = val self.next = None def merge_linked_lists_recursively(node1, node2): """"merge 2 sorted linked list into a sorted list (ascending)""" if node1 == None: return node2 elif node2 == None: return node1 new_head = None if node1.val >= node2.val: new_head = node2 new_head.next = merge_linked_lists_recursively(node1, node2.next) else: new_head = node1 new_head.next = merge_linked_lists_recursively(node1.next, node2) return new_head def merge_linked_lists(head1, head2): """"merge 2 sorted linked list into a sorted list (ascending)""" node1 = head1 node2 = head2 if node1 == None: return head2 elif node2 == None: return head1 if node1.val >= node2.val: head_tmp = node2 node2 = node2.next else: head_tmp = node1 node1 = node1.next node_tmp = head_tmp while node1 and node2: # print(node1.val, node2.val) if node1.val >= node2.val: # insert node2 after head_new node_tmp.next = node2 node_tmp = node2 node2 = node2.next else: # insert node1 after head_new node_tmp.next = node1 node_tmp = node1 node1 = node1.next if node1 != None: while node1 != None: node_tmp.next = node1 node_tmp = node_tmp.next node1 = node1.next elif node2 != None: while node2 != None: node_tmp.next = node2 node_tmp = node_tmp.next node2 = node2.next return head_tmp # list 1: 1 -> 3 -> 5 # list 2: 2 -> 4 -> 6 node_1 = ListNode(1) node_2 = ListNode(2) node_3 = ListNode(3) node_4 = ListNode(4) node_5 = ListNode(5) node_6 = ListNode(6) node_1.next = node_3 node_3.next = node_5 node_2.next = node_4 node_4.next = node_6 test1 = merge_linked_lists(node_1, node_2) while test1: print(test1.val, " ", end="") test1 = test1.next print() # test2 = merge_linked_lists_recursively(node_1, node_2) # while test2: # print(test2.val, " ", end="") # test2 = test2.next
true
96133f56fdadf80059d2b548a3ae485dee91f770
suhaslucia/Pythagoras-Theorem-in-Python
/Pythagoras Theorem.py
1,114
4.40625
4
from math import sqrt #importing math package print(" ----------Pythagoras Theorem to Find the sides of the Triangle---------- ") print(" ------------ Enter any one side as 0 to obtain the result -------------- ") # Taking the inputs as a integer value from the user base = int(input("Enter the base of the Triangle: ")) perpendicular = int(input("Enter the perpendicular of the Triangle: ")) hypotenuse = int(input("Enter the hypotenuse of the Triangle: ")) # Calculating the Hypotenuse value and printing it if hypotenuse == 0: b = base ** 2 p = perpendicular ** 2 hyp = b + p result = sqrt(hyp) print(f'\n Hypotenuse of Triangle is {result}') # Calculating the Perpendicular value and printing it elif perpendicular == 0: b = base ** 2 hyp = hypotenuse ** 2 p = hyp - b result = sqrt(p) print(f'\n Perpendicular of Triangle is {result}') # Calculating the Base value and printing it else: p = perpendicular ** 2 hyp = hypotenuse ** 2 b = hyp - p result = sqrt(b) print(f'\n Base of Triangle is {result}')
true
68e32356ee24ab2bbfc87c4ca3508e89eacd3a0b
Kumar1998/github-upload
/scratch_4.py
397
4.25
4
d1={'Canada':100,'Japan':200,'Germany':300,'Italy':400} #Example 1 Print only keys print("*"*10) for x in d1: print(x) #Example 2 Print only values print ("*"*10) for x in d1: print(d1[x]) #Example 3 Print only values print ("*"*10) for x in d1.values(): print(x) #Example 4 Print only keys and values print ("*"*10) for x,y in d1.items(): print(x,"=>",y)
true
f38bd5b4882bd3787e78bcb653ca07d48b1f7093
Kumar1998/github-upload
/python1.py
573
4.3125
4
height=float(input("Enter height of the person:")) weight=float(input("Enter weight of the person:")) # the formula for calculating bmi bmi=weight/(height**2) print("Your BMI IS:{0} and you are:".format(bmi),end='') #conditions if(bmi<16): print("severly underweight") elif(bmi>=16 and bmi<18.5): print("underweight") elif(bmi>=18.5 and bmi>=25): print("underweight") elif(bmi>=18.5 and bmi<25): print("healthy") elif(bmi>=25 and bmi<30): print("overweight") elif(bmi>=30): print("severly overweight") import time time.sleep(30)
true
98f763bd336731f8fa0bd853d06c059dd88d8ca7
septhiono/redesigned-meme
/Day 2 Tip Calculator.py
316
4.1875
4
print('Welcome to the tip calculator') bill = float(input('What was the total bill? $')) tip= float(input('What percentage tip would you like to give? ')) people = float(input("How many people split the bill? ")) pay= bill*(1+tip/100)/people pay=float(pay) print("Each person should pay: $",round(pay,2))
true
fea4e23725b61f8dd4024b2c52065870bbba6da1
rugbyprof/4443-2D-PyGame
/Resources/R02/Python_Introduction/PyIntro_05.py
548
4.15625
4
# import sys # import os # PyInto Lesson 05 # Strings # - Functions # - Input from terminal # - Formatted Strings name = "NIKOLA TESLA" quote = "The only mystery in life is: why did Kamikaze pilots wear helmets?" print(name.lower()) print(name.upper()) print(name.capitalize()) print(name.title()) print(name.isalpha()) print(quote.find('Kamikaze')) print(quote.find('Kamikazsdfe')) new_name = input("Please enter a name: ") print(new_name) print(len(quote)) print(f"Hello {new_name}, you owe me 1 million dollars!") print(f"{quote.strip('?')}")
true
79d70dca2e86013310ae0691b9a8e731d26e2e75
nidhinp/Anand-Chapter2
/problem36.py
672
4.21875
4
""" Write a program to find anagrams in a given list of words. Two words are called anagrams if one word can be formed by rearranging letters to another. For example 'eat', 'ate' and 'tea' are anagrams. """ def sorted_characters_of_word(word): b = sorted(word) c = '' for character in b: c += character return c def anagram(list_of_words): a = {} for word in list_of_words: sorted_word = sorted_characters_of_word(word) if sorted_word not in a: d = [] d.append(word) a[sorted_word] = d else: d = a[sorted_word] d.append(word) a.update({sorted_word:d}) print a.values() anagram(['eat', 'ate', 'done', 'tea', 'soup', 'node'])
true
a1b103fb6e85e3549090449e71ab3908a46b2e9c
nidhinp/Anand-Chapter2
/problem29.py
371
4.25
4
""" Write a function array to create an 2-dimensional array. The function should take both dimensions as arguments. Value of element can be initialized to None: """ def array(oneD, twoD): return [[None for x in range(twoD)] for x in range(oneD)] a = array(2, 3) print 'None initialized array' print a a[0][0] = 5 print 'Modified array' print a
true
4cbcb6d66ee4b0712d064c9ad4053456e515b14b
SandipanKhanra/Sentiment-Analysis
/tweet.py
2,539
4.25
4
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] #This function is used to strip down the unnecessary characters def strip_punctuation(s): for i in s: if i in punctuation_chars: s=s.replace(i,"") return s # lists of words to use #As part of the project this hypothetical .txt file was given positive_words = [] with open("positive_words.txt") as pos_f: for lin in pos_f: if lin[0] != ';' and lin[0] != '\n': positive_words.append(lin.strip()) #This function returns number of positive words in the tweet def get_pos(s): count=0 s=s.lower() x=[] x=s.split() for i in x: i=strip_punctuation(i) if i in positive_words: count+=1 return count #As part of the project this hypothetical .txt file was given negative_words = [] with open("negative_words.txt") as pos_f: for lin in pos_f: if lin[0] != ';' and lin[0] != '\n': negative_words.append(lin.strip()) #This function returns number of negitive words in the tweet def get_neg(s): count=0 s=s.lower() x=[] x=s.split() for i in x: i=strip_punctuation(i) if i in negative_words: count+=1 return count #This hypothetical .csv file containing some fake tweets was given for analysi filedName = None file = open("project_twitter_data.csv") lines = file.readlines() fieldName = lines[0].strip().split(',') #print(fieldName) '''here we are iterating over each line, considering only the tweet then processing it with the previous functions storing positive word count, negative word count, net score(how much positiive or negative) ''' ans = [] for line in lines[1:]: tweet= line.strip().split(',') tempTweet = strip_punctuation(tweet[0]) posCount = get_pos(tempTweet) negCount = get_neg(tempTweet) net = posCount - negCount #Making a tuple containing Number of retweets,number of replies,posCount,negCount,Net score t = (int(tweet[1]),int(tweet[2]),posCount,negCount,net) ans.append(t) #print(ans[4]) #Making the header of the new csv file outputHeader = "{},{},{},{},{}".format('Number of Retweets','Number of Replies', 'Positive Score','Negative Score','Net Score') #writing data in the new csv file output = open('resulting_data.csv','w') output.write(outputHeader) output.write('\n') for i in ans: raw = '{},{},{},{},{}'.format(i[0],i[1],i[2],i[3],i[4]) output.write(raw) output.write('\n')
true
8c79d7caeb39a173173de7e743a8e2186e2cfc0a
osirisgclark/python-interview-questions
/TCS-tataconsultancyservices2.py
344
4.46875
4
""" For this list [1, 2, 3] return [[1, 2, 3], [2, 4, 6], [3, 6, 9]] """ list = [1, 2, 3] list1 = [] list2 = [] list3 = [] for x in range(1, len(list)+1): list1.append(x) list2.append(2*x) list3.append(3*x) print([list1, list2, list3]) """ Using List Comprehensions """ print([[x, 2*x, 3*x] for x in range(1, len(list)+1)])
true
7cc58e0ee75580bc78c260832e940d0fd07b9e2a
minerbra/Temperature-converter
/main.py
574
4.46875
4
""" @Author: Brady Miner This program will display a temperature conversion table for degrees Celsius to Fahrenheit from 0-100 degrees in multiples of 10. """ # Title and structure for for table output print("\nCelsius to Fahrenheit") print("Conversion Table\n") print("Celsius\t Fahrenheit") for celsius in range(0, 101, 10): # loop degrees celsius from 0 to 100 in multiples of 10 fahrenheit = (celsius * 9 / 5) + 32 # Formula to convert celsius to fahrenheit print("{}\t\t {}".format(celsius, round(fahrenheit))) # Format the data to display in the table
true
ec2ffda93473b99c06258761740065801e017162
saimkhan92/data_structures_python
/llfolder1/linked_list_implementation.py
1,445
4.28125
4
# add new node in the front (at thr root's side) import sys class node(): def __init__(self,d=None,n=None): self.data=d self.next=n class linked_list(node): def __init__(self,r=None,l=0): self.length=l self.root=r def add(self,d): new_node=node() new_node.data=d if (self.root==None): self.root=new_node new_node.next=None self.length=1 else: self.length+=1 new_node.next=self.root self.root=new_node def display(self): i=self.root while i: print(str(i.data)+" --> ",end="") i=i.next print("None") def delete(self,i): if self.root.data==i: self.root=self.root.next else: current_node=self.root.next previous_node=self.root while current_node: if current_node.data==i: previous_node.next=current_node.next return True print(2) else: previous_node=current_node current_node=current_node.next print("3") #lnk=linked_list() #lnk.add(10) #lnk.add(20) #lnk.add(30) #lnk.add(25) #lnk.display() #lnk.delete(30) #lnk.display()
true
d7fb7ba1b47eb9787dc45de53dd221d75d52a05f
catterson/python-fundamentals
/challenges/02-Strings/C_interpolation.py
1,063
4.78125
5
# Lastly, we'll see how we can put some data into our strings # Interpolation ## There are several ways python lets you stick data into strings, or combine ## them. A simple, but very powerful approach is to us the % operator. Strings ## can be set up this way to present a value we didn't know when we defined the ## string! s = 'this string is %d characters long' ## We can apply values to a string with an expression that goes: ## string % value(s) ## if there's more than one, put them in ()'s with commas between! ## Go ahead and compute the length of s and substitute it into the string: d = len(s) print s%d # conversion ## Adding a string and a number together doesn't make sense... for example, ## what's the right thing to do for '1.0' + 2? Let's explore both ways that ## could go. First, we need to do the conversion ourselves. Remember, you can ## use the type functions to do that, in this case, str() and float() - int() ## would lose the decimal point that is clearly there for a reason! print '1.0' + str(2) print float('1.0') + float(2)
true
dc0755a55ce75ca7b9b98acb9d32c4c04663b834
glennlopez/Python.Playground
/SANDBOX/python3/5_loops_branches/break_continue.py
332
4.28125
4
starting = 0 ending = 20 current = starting step = 6 while current < ending: if current + step > ending: # breaks out of loop if current next step is larger than ending break if current % 2: # skips the while loop if number is divisible by 2 continue current += step print(current)
true
4f619614442506f1567eb9ecc0de6c989f0c2c21
ashburnere/data-science-with-python
/python-for-data-science/1-2-Strings.py
2,344
4.28125
4
'''Table of Contents What are Strings? Indexing Negative Indexing Slicing Stride Concatenate Strings Escape Sequences String Operations ''' # Use quotation marks for defining string "Michael Jackson" # Use single quotation marks for defining string 'Michael Jackson' # Digitals and spaces in string '1 2 3 4 5 6 ' # Special characters in string '@#2_#]&*^%$' # Assign string to variable name = "Michael Jackson" print(name, "length:", len(name)) # Print the first element in the string --> M print(name[0]) # Print the last element in the string --> n print(name[len(name)-1]) # Print the element on index 6 in the string --> l print(name[6]) # Print the element on the 13th index in the string --> o print(name[13]) # Print the last element in the string by using negativ indexing --> n print(name[-1]) # Print the first element in the string by using negativ indexing --> M print(name[-len(name)]) # Take the slice on variable name with only index 0 to index 3 --> Mich print(name[0:4]) # Take the slice on variable name with only index 8 to index 11 --> Jack print(name[8:12]) # Stride: Get every second element. The elments on index 0, 2, 4 ... print(name[::2]) # Stride: Get every second element in the range from index 0 to index 4 --> Mca print(name[0:5:2]) # Concatenate two strings statement = name + " is the best" print(statement) # Print the string for 3 times print(3*statement) # New line escape sequence print(" Michael Jackson \n is the best" ) # Tab escape sequence print(" Michael Jackson \t is the best" ) # Include back slash in string print(" Michael Jackson \\ is the best" ) # r will tell python that string will be display as raw string print(r" Michael Jackson \ is the best" ) ''' String operations ''' # Convert all the characters in string to upper case A = "Thriller is the sixth studio album" print("before upper:", A) B = A.upper() print("After upper:", B) # Replace the old substring with the new target substring is the segment has been found in the string A = "Michael Jackson is the best" B = A.replace('Michael', 'Janet') # Find the substring in the string. Only the index of the first elment of substring in string will be the output name = "Michael Jackson" # --> 5 print(name.find('el')) # If cannot find the substring in the string -> result is -1 print(name.find('Jasdfasdasdf'))
true
d86edccc25b0e5e6aebddb9f876afd3219c58a65
ashburnere/data-science-with-python
/python-for-data-science/4-3-Loading_Data_and_Viewing_Data_with_Pandas.py
2,038
4.25
4
'''Table of Contents About the Dataset Viewing Data and Accessing Data with pandas ''' '''About the Dataset The table has one row for each album and several columns artist - Name of the artist album - Name of the album released_year - Year the album was released length_min_sec - Length of the album (hours,minutes,seconds) genre - Genre of the album music_recording_sales_millions - Music recording sales (millions in USD) on SONG://DATABASE claimed_sales_millions - Album's claimed sales (millions in USD) on SONG://DATABASE date_released - Date on which the album was released soundtrack - Indicates if the album is the movie soundtrack (Y) or (N) rating_of_friends - Indicates the rating from your friends from 1 to 10 ''' import pandas as pd # read from file csv_path='D:/WORKSPACES/data-science-with-python/resources/data/top_selling_albums.csv' # read from url #csv_path='https://ibm.box.com/shared/static/keo2qz0bvh4iu6gf5qjq4vdrkt67bvvb.csv' df = pd.read_csv(csv_path) # We can use the method head() to examine the first five rows of a dataframe: print("top 5 rows\n", df.head()) #We use the path of the excel file and the function read_excel. The result is a data frame as before: # xlsx_path='https://ibm.box.com/shared/static/mzd4exo31la6m7neva2w45dstxfg5s86.xlsx' # df = pd.read_excel(xlsx_path) #df.head() # We can access the column "Length" and assign it a new dataframe 'x': x=df[['Length']] print(x) ''' Viewing Data and Accessing Data ''' # You can also assign the value to a series, you can think of a Pandas series as a 1-D dataframe. Just use one bracket: x=df['Length'] print(type(x)) # You can also assign different columns, for example, we can assign the column 'Artist': x=df[['Artist']] print(type(x)) y=df[['Artist','Length','Genre']] print(type(y)) # print value of first row first column print(df.iloc[0,0]) # --> Michael Jackson print(df.loc[0,'Artist']) # --> Michael Jackson # slicing print(df.iloc[0:2, 0:3]) print(df.loc[0:2, 'Artist':'Released'])
true
a016c597b8fc5f70e2ab5d861b756d347282289d
jourdy345/2016spring
/dataStructure/2016_03_08/fibonacci.py
686
4.125
4
def fib(n): if n <= 2: return 1 else: return fib(n - 1) + fib(n - 2) # In python, the start of a statement is marked by a colon along with an indentation in the next line. def fastFib(n): a, b = 0, 1 for k in range(n): a, b = b, a+b # the 'a' in the RHS is not the one in the RHS. Python distinguishes LHS from RHS and does not mix them up. return a # For n = 1, the slower version of fib function is actually faster than the faster one. # In small values of n, the comparison between two functions is actually not revealing as much as we would expect it to be. # Thus, we introduce a new concept O(n) ("Big oh"): asymptotic time complexity. print(fastFib(45))
true
be9b1b682cc8b1f6190fead9c3441ce72f512cf4
Nathan-Dunne/Twitter-Data-Sentiment-Analysis
/DataFrameDisplayFormat.py
2,605
4.34375
4
""" Author: Nathan Dunne Date last modified: 16/11/2018 Purpose: Create a data frame from a data set, format and sort said data frame and display data frame as a table. """ import pandas # The pandas library is used to create, format and sort a data frame. # BSD 3-Clause License # Copyright (c) 2008-2012, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development from tabulate import tabulate # The tabulate library is used to better display the pandas data frame as a table. # MIT License Copyright (c) 2018 Sergey Astanin class DataFrameDisplayFormat: def __init__(self): pass # There is nothing to initialise so pass is called here. The pass statement is a null operation. @staticmethod # Method is static as it alters no values of the self object. def convertDataSetToDataFrame(data_set): """ Convert a data set to a pandas data frame. """ data_frame = pandas.DataFrame(data_set) # Convert the data set (List of dictionaries) to a pandas data frame. return data_frame @staticmethod # Method is static as it alters no values of the self object. def formatDataFrame(data_frame): """ Format and sort a data frame. """ data_frame = data_frame[['favorite_count', # Order and display only these three columns. 'retweet_count', 'text', ]] print("\nSorting data by 'favorite_count', 'retweet_count', descending.") # Sort the rows first by favorite count and then by retweet count in descending order. data_frame = data_frame.sort_values(by=['favorite_count', 'retweet_count'], ascending=False) return data_frame @staticmethod # Method is static as it neither accesses nor alters any values or behaviour of the self object. def displayDataFrame(data_frame, amount_of_rows, show_index): """ Display a data frame in table format using tabulate. """ # Print out an amount of rows from the data frame, possibly with showing the index, with the headers as the # data frame headers using the table format of PostgreSQL. # Tabulate can't display the word "Index" in the index column so it is printed out right before the table. print("\nIndex") print(tabulate(data_frame.head(amount_of_rows), showindex=show_index, headers=data_frame.columns, tablefmt="psql"))
true
bfd6a6a1ce1a215bd6e698e732194b26fd0ec7b4
tjnelson5/Learn-Python-The-Hard-Way
/ex15.py
666
4.1875
4
from sys import argv # Take input from command line and create two string variables script, filename = argv # Open the file and create a file object txt = open(filename) print "Here's your file %r:" % filename # read out the contents of the file to stdout. This will read the whole # file, because the command ends at the EOF character by default print txt.read() # always close the file - like gates in a field! txt.close() # create a new string variable from the prompt print "Type the filename again:" file_again = raw_input("> ") # Create a new file object for this new file txt_again = open(file_again) # Same as above print txt_again.read() txt.close()
true
6b9281109f10fd0d69dfc54ce0aa807f9592109a
xy008areshsu/Leetcode_complete
/python_version/intervals_insert.py
1,267
4.125
4
""" Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. Example 2: Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. """ # Definition for an interval. class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e class Solution: # @param intervals, a list of Intervals # @param newInterval, a Interval # @return a list of Interval def insert(self, intervals, newInterval): if len(intervals) == 0: return [newInterval] intervals.append(newInterval) intervals.sort(key=lambda x: x.start) res = [intervals[0]] for i in range(1, len(intervals)): if intervals[i].start <= res[-1].end: # here needs <= instead of <, e.g. [1, 3], and [3, 5] should be merged into [1, 5] res[-1].end = max(res[-1].end, intervals[i].end) else: res.append(intervals[i]) return res
true
7e3a1b29b321ff31e6e635d825ddcfb1668aeb5c
xy008areshsu/Leetcode_complete
/python_version/dp_unique_path.py
1,531
4.15625
4
""" A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? Above is a 3 x 7 grid. How many possible unique paths are there? Note: m and n will be at most 100. """ class Solution: # @return an integer def uniquePaths(self, m, n): unique_paths_number = {} unique_paths_number[(0, 0)] = 1 unique_paths_number.update({(0, i) : 1 for i in range(n)}) unique_paths_number.update({(i, 0) : 1 for i in range(m)}) return self.solve(unique_paths_number, m - 1, n - 1) def solve(self, unique_paths_number, m, n): if m == 0 or n == 0: unique_paths_number[(m, n)] = 1 return 1 if (m - 1, n) in unique_paths_number: unique_paths_number_m_1_n = unique_paths_number[(m-1, n)] else: unique_paths_number_m_1_n = self.solve(unique_paths_number, m - 1, n) if (m, n - 1) in unique_paths_number: unique_paths_number_m_n_1 = unique_paths_number[(m, n - 1)] else: unique_paths_number_m_n_1 = self.solve(unique_paths_number, m , n - 1) unique_paths_number_m_n = unique_paths_number_m_1_n + unique_paths_number_m_n_1 unique_paths_number[(m, n)] = unique_paths_number_m_n return unique_paths_number_m_n
true
c20802ed076df2adc4c4b430f6761742487d37a7
samluyk/Python
/GHP17.py
900
4.46875
4
# Step 1: Ask for weight in pounds # Step 2: Record user’s response weight = input('Enter your weight in pounds: ') # Step 3: Ask for height in inches # Step 4: Record user’s input height = input('Enter your height in inches: ') # Step 5: Change “string” inputs into a data type float weight_float = float(weight) height_float = float(height) # Step 6: Calculate BMI Imperial (formula: (5734 weight / (height*2.5)) BMI = (5734 * weight_float) / (height_float**2.5) # Step 7: Display BMI print("Your BMI is: ", BMI) # Step 8: Convert weight to kg (formula: pounds * .453592) weight_kg = weight_float * .453592 # Step 9: Convert height to meters (formula: inches * .0254) height_meters = height_float * .0254 # Step 10: Calculate BMI Metric (formula: 1.3 * weight / height** 2.5 BMI = 1.3 * weight_kg / height_meters**2.5 # Step 11: Display BMI print("Your BMI is: ", BMI) # Step 12: Terminate
true
0448e9274de805b9dec8ae7689071327677a6abb
wxhheian/hpip
/ch7/ex7_1.py
641
4.25
4
# message = input("Tell me something, and I will repeat it back to you: ") # print(message) # # name = input("Please enter your name: ") # print("Hello, " + name + "!") # prompt = "If you tell us who you are,we can personalize the messages you see." # prompt += "\nWhat is your first name? " # # name = input(prompt) # print("\nHello, " + name + "!") # age = input("How old are you? ") # print(int(age)>= 18) number = input("Enter a number, and I'll tell you if it's even or odd:") number = int(number) if number % 2 == 0: print("\nThe number " + str(number) + " is even") else: print("\nThe number " + str(number) + " is odd.")
true
856461a845a16813718ace33b8d2d5782b0d7914
JapoDeveloper/think-python
/exercises/chapter6/exercise_6_3.py
1,891
4.40625
4
""" Think Python, 2nd Edition Chapter 6 Exercise 6.3 Description: A palindrome is a word that is spelled the same backward and forward, like “noon” and “redivider”. Recursively, a word is a palindrome if the first and last letters are the same and the middle is a palindrome. The following are functions that take a string argument and return the first, last, and middle letters: def first(word): return word[0] def last(word): return word[-1] def middle(word): return word[1:-1] We’ll see how they work in Chapter 8. 1) Type these functions into a file named palindrome.py and test them out. What happens if you call middle with a string with two letters? One letter? What about the empty string, which is written '' and contains no letters? 2) Write a function called is_palindrome that takes a string argument and returns True if it is a palindrome and False otherwise. Remember that you can use the built-in function len to check the length of a string. """ from palindrome import * def is_palindrome(word): if len(word) <= 1: return True elif first(word) == last(word): return is_palindrome(middle(word)) else: return False print(first('Hello')) # H print(middle('Hello')) # ell print(last('Hello')) # o # What happens if you call middle with a string with two letters? print(middle('ab')) # empty string is returned # One letter? print(middle('a')) # empty string is returned # What about the empty string, which is written '' and contains no letters? print(middle('')) # empty string is returned print('Are palindromes?:') print('noon', is_palindrome('noon')) # Yes print('redivider', is_palindrome('redivider')) # Yes print('a', is_palindrome('a')) # Yes print('empty string', is_palindrome('')) # Yes print('night', is_palindrome('night')) # No print('word', is_palindrome('word')) # No
true
6ffba84aafcdb3a4491c8268cba8ea1e2adfdf1e
JapoDeveloper/think-python
/exercises/chapter6/exercise_6_2.py
951
4.3125
4
""" Think Python, 2nd Edition Chapter 6 Exercise 6.2 Description: The Ackermann function, A(m,n), is defined: n + 1 if m = 0 A(m,n) = A(m-1, 1) if m > 0 and n = 0 A(m-1, A(m,n-1)) if m > 0 and n > 0 See http://en.wikipedia.org/wiki/Ackermann_function. Write a function named ack that evaluates the Ackermann function. Use your function to evaluate ack(3, 4), which should be 125. What happens for larger values of m and n? """ def ack(m, n): if m < 0 or n < 0: print('ack function called with invalid input, only positive integers are valid') return elif m == 0: return n + 1 elif n == 0: return ack(m-1, 1) else: return ack(m-1, ack(m, n-1)) print(ack(3, 4)) # 125 print(ack(1, 2)) # 4 print(ack(4, 3)) # RecursionError # For larger values of m and n python can proceed the operation because # the number of allow recursion call is exceeded
true
508a885f71292a801877616a7e8132902d1af6c5
JapoDeveloper/think-python
/exercises/chapter6/exercise_6_4.py
643
4.3125
4
""" Think Python, 2nd Edition Chapter 6 Exercise 6.4 Description: A number, a, is a power of b if it is divisible by b and a/b is a power of b. Write a function called is_power that takes parameters a and b and returns True if a is a power of b. Note: you will have to think about the base case. """ def is_power(a, b): """Check if a integer 'a' is a power of a integer 'b'""" if a == 1 or a == b: # base case return True elif a % b != 0: return False else: return is_power(a / b, b) print(is_power(2,2)) # True print(is_power(1,2)) # True print(is_power(8,2)) # True print(is_power(9,2)) # False
true
8c5faf13fe2952f33dd45000bf56e87bd1a0747e
Shubham1304/Semester6
/ClassPython/4.py
711
4.21875
4
#31st January class #string operations s='hello' print (s.index('o')) #exception if not found #s.find('a') return -1 if not found #------------------check valid name------------------------------------------------------------------------------------- s='' s=input("Enter the string") if(s.isalpha()): print ("Valid name") else : print ("Not a valid name") #--------------------check a palindrome---------------------------------------------------------------------------------- s=input ("Enter a number") r=s[::-1] if r==s: print ("It is a palindrome") else: print("It is not a palindrome") s='abba' print (s.index('a')) s = input ("Enter the string") while i<len(s): if (s.isdigit()): if(
true
b896f3577f80daaf46e56a70b046aecacf2288cb
sukirt01/Python-for-Beginners-Solve-50-Exercises-Live
/17.py
718
4.375
4
''' Write a version of a palindrome recognizer that also accepts phrase palindromes such as "Go hang a salami I'm a lasagna hog.", "Was it a rat I saw?", "Step on no pets", "Sit on a potato pan, Otis", "Lisa Bonet ate no basil", "Satan, oscillate my metallic sonatas", "I roamed under it as a tired nude Maori", "Rise to vote sir", or the exclamation "Dammit, I'm mad!". Note that punctuation, capitalization, and spacing are usually ignored. ''' def palindrome(x): l=[] for i in x: if i.isalpha(): l.append(i.lower()) print ''.join(l) if l==l[::-1]: print 'palindrome' else: print 'Not a palindrome' palindrome("Go hang a salami I'm a lasagna hog.")
true
40589034a276810b9b22c31ca519399df66bd712
sukirt01/Python-for-Beginners-Solve-50-Exercises-Live
/02.py
277
4.125
4
''' Define a function max_of_three() that takes three numbers as arguments and returns the largest of them. ''' def max_of_three(a,b,c): if a>b and a>c: print a elif b>c and b>a: print b else: print c print max_of_three(0,15,2)
true
fc24e9ff6df3c2d766e719892fae9426e33f81f6
Isonzo/100-day-python-challenge
/Day 8/prime_number_checker.py
460
4.15625
4
def prime_checker(number): if number == 0 or number == 1: print("This number is neither prime nor composite") return prime = True for integer in range(2, number): if number % integer == 0: prime = False break if prime: print("It's a prime number") else: print("It's not a prime number") n = int(input("Check this number: ")) prime_checker(number=n)
true
6e8ac25e465a4c45f63af8334094049c0b660c4b
IrisCSX/LeetCode-algorithm
/476. Number Complement.py
1,309
4.125
4
""" Promblem: Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. Note: The given integer is guaranteed to fit within the range of a 32-bit signed integer. You could assume no leading zero bit in the integer’s binary representation. Example 1: Input: 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. Example 2: Input: 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. Note: 任何二进制数和1111按位异都是该数字的互补数字 比如 (101)表示5 (111) (010)得到5的互补数字是3 算法: 1.得到与n的位数相同的1111 2.与1111取异 """ def numComplement(n): # 1.得到与n的二进制位数相同的111 lenth = len(bin(n))-2 compareN = 2 ** lenth -1 # 2.让111与数字n取异 complementN = compareN ^ n return complementN def numComplement2(num): i = 1 while i <= num: i = i << 1 return (i - 1) ^ num def test(): n = 8 m = numComplement2(n) print(bin(n),"的互补的二进制数是:",bin(m)) if __name__ == '__main__': test()
true
124f02540d0b7712a73b5d2e2e03868ac809b791
anikaator/CodingPractice
/Datastructures/HashMap/Basic/Python/main.py
687
4.15625
4
def main(): # Use of dict contacts = {} contacts['abc'] = 81 contacts['pqr'] = 21 contacts['xyz'] = 99 def print_dict(): for k,v in contacts.items(): print 'dict[', k, '] = ', v print("Length of dict is %s" % len(contacts)) print("Dict contains:") print_dict() print("Deleting dict[key]:") del(contacts['abc']) print_dict() print("Checking if pqr key is present %r :" % ('pqr' in contacts)) print("Deleting non existant key \'lmn\'") try: del(contacts['lmn']) except KeyError: print("Caught error : KeyError:item does not exist") if __name__ == "__main__": main()
true
e2350657520b17cc90a0fb9406a4cc6f99cee53a
CookieComputing/MusicMaze
/MusicMaze/model/data_structures/Queue.py
1,532
4.21875
4
from model.data_structures.Deque import Deque class Queue: """This class represents a queue data structure, reinvented out of the wheel purely for the sake of novelty.""" def __init__(self): """Constructs an empty queue.""" self._deque = Deque() def peek(self): """Peek at the earliest entry in the queue without removing it. Returns: Any: the data of the front-most entry in the queue Raises: IndexError: If no data is in the queue.""" if not self._deque: raise IndexError("Queue is empty") return self._deque.peek_head() def enqueue(self, data): """Puts the given data into the queue. Args: data(Any): the data to be inserted into the back of the queue""" self._deque.push_tail(data) def dequeue(self): """Removes the earliest entry from the queue and returns it. Returns: Any: the data of the earliest entry in the queue Raises: IndexError: If the queue is empty""" if not self._deque: raise IndexError("Queue is empty") return self._deque.pop_head() def __len__(self): """Returns the size of the queue. Returns: int: the size of the queue""" return len(self._deque) def __bool__(self): """Returns true if the queue has an entry Returns: bool: True if len(queue) > 0, false otherwise""" return len(self) > 0
true
9bc3ae714f881fd44890ed63429dc9bc4de89b5c
codewithgauri/HacktoberFest
/python/Learning Files/10-List Data Type , Indexing ,Slicing,Append-Extend-Insert-Closer look at python data types.py
1,129
4.28125
4
l=[10,20,22,30,40,50,55] # print(type(l)) # 1 Lists are mutable = add update and delete # 2 Ordered = indexing and slicing # 3 Hetrogenous # indexing and slicing: # print(l[-1]) # print(l[1:3]) #end is not inclusive # reverse a Lists # print(l[::-1]) # if you want to iterate over alternate characters # for value in l[::2]: # print(value) # append # if u want to add single element in a list # it wont return any thing #memory location will be the same # l.append(60) # print(l) # extend # if u want to add multiple elements # it only take one agrument # it will iterate over give argument #l.extend("Python") # l.extend([500,600,700,800]) # print(l) # in case of append it will add the whole list as one element # insert # Both append and extend will add element at last but if you want to add at particular # position we use insert method # l.insert(1,1000) # print(l) # l = [ 10,20,30] # l2=l # l.append(40) # print(id(l),id(l2)) # print(l,l2) # if we modifiy the frist list it will also modifiy the second list # so we use some time copy l = [ 10,20,30] l2=l.copy() l.append(40) print(id(l),id(l2)) print(l,l2)
true
453eb80f8c7d3c8353c7288f4beea8e3f7e0c1c5
codewithgauri/HacktoberFest
/python/Cryptography/Prime Numbers/naive_primality_test.py
576
4.21875
4
##Make sure to run with Python3 . Python2 will show issues from math import sqrt from math import floor def is_prime(num): #numbers smaller than 2 can not be primes if num<=2: return False #even numbers can not be primes if num%2==0: return False #we have already checked numbers < 3 #finding primes up to N we just have to check numbers up to sqrt(N) #increment by 2 because we have already considered even numbers for i in range(3,floor(sqrt(num)),2): if num%i==0: return False return True if __name__ == "__main__": print(is_prime(99194853094755497))
true
51d1cb5a523fa102734d50143a3b9eab17faf2cb
codewithgauri/HacktoberFest
/python/Learning Files/13-Dictionary Data Types , Storing and Accessing the data in dictionary , Closer look at python data types.py.py
1,580
4.3125
4
# dict: # 1. mutable # 2.unordered= no indexing and slicing # 3.key must be unque # 4.keys should be immutable # 5. the only allowed data type for key is int , string , tuple # reason mutable data type is not allowed # for example # d={"emp_id":101 , [10,20,30]:100,[10,20]:200} # if we add an element into [10,20] of 30 we will be creating a duplicate key #d={"emp_id":101, "emp_name":"Uday Kiran", "email_id":"kiranu941@gmail.com"} # print(d) #d["email_id"]=102 #print(d) #d["contact_no"]=123456789 #print(d) # d["contact_no"]=1234567898 # it will update the value # get # setdeafult # get retrive a data from the key specified #print(d.get("emp_name")) # if we specified a key which doesnt exist it wont through an error # it will return None # if u want the function to return a value when the key doesnt exist # we can specify a second parameter #print(d.get("email","Key doesnt exist")) #setdeafult adds elemets if key doesnt exit else it will retrive data #print(d.setdefault("age")) # since age is not present it will add the age key and the assign a value of None # if we want to assign a value to it i inilization its self # print(d.setdefault("age",50)) #d["email_id"]="kiranu942@gmail.com" #print(d) #for x in d: # print(x) # defaultly it will iterate over the keys #for x in d: # print(x,d[x]) # if we also want the values #dic={} #for num in range(1,11): # dic[num]=num*num #print(dic) #keys #values #items # print(d.keys()) it is a list of all the keys # print(d.values()) it is a list of all the values # print(d.items()) it returns a tuple # for t in d.items(): # print(t)
true
2725b85849ce224e97685919f148cc9807e60d83
bdngo/math-algs
/python/checksum.py
1,155
4.21875
4
from typing import List def digit_root(n: int, base: int=10) -> int: """Returns the digital root for an integer N.""" assert type(n) == 'int' total = 0 while n: total += n % base n //= base return digit_root(total) if total >= base else total def int_to_list(n: int, base: int=10) -> List[int]: """Returns a list of the digits of N.""" digit_list = [] while n: digit_list += [n % base] n //= base return list(reversed(digit_list)) def check_sum(n: int) -> bool: """Checks if N is a valid bank card.""" digits, doubled_digits = int_to_list(n), [] for i in range(len(digits)): doubled_digits.append( digit_root(digits[i] * 2) if i % 2 == 0 else digits[i]) return sum(doubled_digits) % 10 == 0 def vat_check(n: int) -> bool: """Checks if N satisfies the old HMRC VAT number check.""" factor = 8 digits, last_two = int_to_list(n)[:-2], int_to_list(n)[-2:] for i in range(len(digits)): digits[i] *= factor factor -= 1 check_digit = sum(digits) + (last_two[0]*10 + last_two[1]) + 55 return check_digit % 97 == 0
true
52c44bf0aa15ba0bfcc1abda81fffefba6be075c
DistantThunder/learn-python
/ex33.py
450
4.125
4
numbers = [] # while i < 6: # print("At the top i is {}".format(i)) # numbers.append(i) # # i = i + 1 # print("Numbers now: ", numbers) # print("At the bottom i is {}\n{}".format(i, '-')) def count_numbers(count): count += 1 for i in range(0, count): numbers.append(i) return 0 count_numbers(int(input("Enter the number you want to count to: "))) print("The numbers: ") for num in numbers: print(num)
true
1fe48d3656b9437f43b79afa4ba5d9f2ffe13c2f
adamfitzhugh/python
/kirk-byers/Scripts/Week 1/exercise3.py
942
4.375
4
#!/usr/bin/env python """Create three different variables: the first variable should use all lower case characters with underscore ( _ ) as the word separator. The second variable should use all upper case characters with underscore as the word separator. The third variable should use numbers, letters, and underscores, but still be a valid variable Python variable name. Make all three variables be strings that refer to IPv6 addresses. Use the from future technique so that any string literals in Python2 are unicode. compare if variable1 equals variable2 compare if variable1 is not equal to variable3 """ from __future__ import print_function ipv_six_addr_1 = "2001:db8:1234::1" IPV_SIX_ADDR_2 = "2001:db8:1234::2" ipv_6_addr_3 = "2001:db8:1234::3" print("") print("Is var1 == var2: {}".format(ipv_six_addr_1 == IPV_SIX_ADDR_2)) print("Is var1 != var3: {}".format(ipv_six_addr_1 != ipv_6_addr_3)) print("")
true
d925d4b637199ad159b36b33dcb0438ccca0f95a
adamfitzhugh/python
/kirk-byers/Scripts/Week 5/exercise3.py
1,788
4.15625
4
""" Similar to lesson3, exercise4 write a function that normalizes a MAC address to the following format: 01:23:45:67:89:AB This function should handle the lower-case to upper-case conversion. It should also handle converting from '0000.aaaa.bbbb' and from '00-00-aa-aa-bb-bb' formats. The function should have one parameter, the mac_address. It should return the normalized MAC address Single digit bytes should be zero-padded to two digits. In other words, this: a:b:c:d:e:f should be converted to: 0A:0B:0C:0D:0E:0F Write several test cases for your function and verify it is working properly. """ from __future__ import print_function, unicode_literals import re def normal_mac_addr(mac_address): mac_address = mac_address.upper if ':' in mac_address or '-' in mac_address: new = [] octets = re.split(r"[-:]", mac_address) for octet in octects: if len(octet) < 2: octet = octet.zfill(2) new.append(octet) elif '.' in mac_address: mac = [] sec = mac_address.split('.') if len(sec) != 3: raise ValueError("This went wrong") for word in sec: if len(word) < 4: word = word.zfill(4) new.append(word[:2]) mac.append(word[:2]) return ":".join(mac) # Some tests assert "01:23:02:34:04:56" == normal_mac_addr('123.234.456') assert "AA:BB:CC:DD:EE:FF" == normal_mac_addr('aabb.ccdd.eeff') assert "0A:0B:0C:0D:0E:0F" == normal_mac_addr('a:b:c:d:e:f') assert "01:02:0A:0B:03:44" == normal_mac_addr('1:2:a:b:3:44') assert "0A:0B:0C:0D:0E:0F" == normal_mac_addr('a-b-c-d-e-f') assert "01:02:0A:0B:03:44" == normal_mac_addr('1-2-a-b-3-44') print("Tests passed")
true
2c9a6858ef76026d57e96ce85724e7c062e657d5
nileshmahale03/Python
/Python/PythonProject/5 Dictionary.py
1,487
4.21875
4
""" Dictionary: 1. Normal variable holds 1 value; dictionary holds collection of key-value pairs; all keys must be distinct but values may be repeated 2. {} - curly bracket 3. Unordered 4. Mutable 5. uses Hashing internally 6. Functions: 1. dict[] : returns value at specified index 2. len() : returns length of dictionary min() : returns min value in dictionary max() : returns max value in dictionary sum() : returns sum of values in dictionary 3. dict.reverse() : 'dict' object has no attribute 'reverse' 4. dict.sort() : 'dict' object has no attribute 'sort' 5. in : operator returns bool stating if specified value present in dictionary or not 6. dict[key] = value : add value with specified key 7. dict[key] : get value from dict with specified key dict.get(key) returns None if key dosen't exists 11. dict.pop(key) : dict.pop() dict.popitem() pop() will remove last value 12. del dict[key] : delete """ dict = {10:"abc", 20:"xyz", 30:"pqr"} print(dict) print(type(dict)) print(dict[10]) print(dict, len(dict), min(dict), max(dict), sum(dict)) dict[40] = "def" print(dict) print(dict[30], dict.get(30)) print(dict.get(50), dict.get(60, "Not Available")) #dict.reverse() #dict.sort() print(20 in dict, 80 in dict) dict.popitem() print(dict) dict.pop(10) print(dict) del dict[30] print(dict)
true
e3f5d349f45c8d01cd939727a9bbd644ddaa0bdd
changjunxia/auto_test_example1
/test1.py
228
4.125
4
def is_plalindrome(string): string = list(string) length = len(string) left = 0 right = length - 1 while left < right: if string[left] != string[right]: return False left += 1 right -= 1 return True
true
a1a7e5faad35847f22301b117952e223857d951a
nestorsgarzonc/leetcode_problems
/6.zigzag_convertion.py
1,459
4.375
4
""" The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); Example 1: Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2: Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I """ """ 1158 / 1158 test cases passed. Status: Accepted Runtime: 88 ms Memory Usage: 13.9 MB """ # Solution brute force class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s arrResult = [[] for i in range(numRows)] counter = 0 numRows -= 1 reverse = False for i in s: if counter == numRows: reverse = True if counter == 0: reverse = False if counter < numRows and reverse == False: arrResult[counter].append(i) counter += 1 if counter > 0 and reverse == True: arrResult[counter].append(i) counter -= 1 myResult = '' for i in arrResult: myResult.join(i) return myResult
true
e2349b63116bb7f3e83aa436c41175efda4a8d9d
llNeeleshll/Python
/section_3/string_play.py
290
4.15625
4
text = "This is awesome." # Getting the substring print(text[8:]) print(text[0:4]) # text[start:end:step] print(text[0:14:2]) print(text[0::2]) # Reversing the string print(text[::-1]) # Print a word 10 times? print("Hello " * 10) print("Hello " * 10 + "World!") print("awe" in text)
true
2690856645451099474cbed49d688a0fecd653f4
KaviyaMadheswaran/laser
/infytq prev question.py
408
4.15625
4
Ex 20) 1:special string reverse Input Format: b@rd output Format: d@rb Explanation: We should reverse the alphabets of the string by keeping the special characters in the same position s=input() alp=[] #index of char ind=[] for i in range(0,len(s)): if(s[i].isalpha()): alp.append(s[i]) else: ind.append(i) rev=alp[::-1] for i in ind: #character value in s char=s[i] rev.insert(i,char) print(rev)
true
50e3bc5493956708bf1897a74600cd9639777bf8
KaviyaMadheswaran/laser
/w3 resource.py
403
4.1875
4
Write a Python program to split a given list into two parts where the length of the first part of the list is given. Go to the editor Original list: [1, 1, 2, 3, 4, 4, 5, 1] Length of the first part of the list: 3 Splited the said list into two parts: ([1, 1, 2], [3, 4, 4, 5, 1]) n=int(input()) l=list(map(int,input().split())) ans=[] l1=l[:n] l2=l[n:] ans.append(l1) ans.append(l2) print(tuple(ans))
true
5539d4170fa7ecc1a9a97ba4aa3ed2f23650bd1a
KaviyaMadheswaran/laser
/Birthday Cake candle(Hackerrank).py
490
4.125
4
Output Format Return the number of candles that can be blown out on a new line. Sample Input 0 4 3 2 1 3 Sample Output 0 2 Explanation 0 We have one candle of height 1, one candle of height 2, and two candles of height 3. Your niece only blows out the tallest candles, meaning the candles where height = 3. Because there are 2 such candles, we print 2 on a new line. n=int(input()) l=list(map(int,input().split())) maxi=max(l) c=0; for i in l: if(i==maxi): c+=1 print(c)
true
a5ed73ac78f673fa965b551bef169860cd38a658
timclaussen/Python-Examples
/OOPexample.py
441
4.25
4
#OOP Example #From the simple critter example, but with dogs class Dog(object): """A virtual Dog""" total = 0 def _init_(self, name): print("A new floof approaches!") Dog.total += 1 #each new instance adds 1 to the class att' total self.name = name #sets the constructor input to an attribute def speak(self): print("Woof, I am dog.") def #main pup = Dog() pup.speak()
true
7ca7a468dcc8aea1cc45757f9430b5fa0c0d736f
JuanHernandez2/Ormuco_Test
/Ormuco/Strings comparator/comparator.py
1,188
4.25
4
import os import sys class String_comparator: """ Class String comparator to compare two strings and return which is greater, less or equal than the other one. Attributes: string_1: String 1 string_2: String 2 """ def __init__(self, s1, s2): """ Class constructor Params: s1: string 1 s2: string 2 """ self.string_1 = s1 self.string_2 = s2 def compare(self): """ This function compares if both strings are greater, less or equal to the other one """ if str(self.string_1) > str(self.string_2): return "{} is greater than {}".format(self.string_1, self.string_2) elif str(self.string_1) < str(self.string_2): return "{} is less than {}".format(self.string_1, self.string_2) else: return "{} is equal to {}".format(self.string_1, self.string_2) def check_strings(self): """ Checks if the two strings are valid """ if self.string_1 is None or self.string_2 is None: raise ValueError("One of the arguments is missing or NoneType")
true
1ed4ea179560b5feec261b094bdbe5b2848b4e03
Sharmaanuj10/Phase1-basics-code
/python book/book projects 1/4-7/input while loop/flag.py
321
4.1875
4
active = True print("if you want to quit type quit") while active: message = input("Enter your message: ") if message == 'quit': # break # to break the loop here active = False #comtinue # to execute left over code exiting the if else: print(message)
true
0227e6263035a7b7e6cf67dadde3eb91576afc0b
Sharmaanuj10/Phase1-basics-code
/python book/book projects 1/4-7/input while loop/deli.py
710
4.28125
4
user_want = {} # fistly define a dictonairy empty poll_active = True while poll_active: name = input('Enter your name: ') want = input('if you visit one place in the world where you visit? ') repeat = input('waant to know others wnats (yes,no)? ') # after input store the data at dictionary user_want user_want[name] = want # but user dont want to know about other if he/she type no so to stop the loop we can do: if repeat == 'no': poll_active = False # at last we take keys and values form the user_want dictionary and just print them for names,wants in user_want.items(): print(f'\tHi! {names} you want to visit {wants}')
true
8592b3147c28ef1b09589c048dfa30e0eb87aa5a
Sharmaanuj10/Phase1-basics-code
/python book/Python/password.py/password 1.5.py/password1.5.py
1,287
4.28125
4
name = input("Enter your username: ") passcode = input("Enter you password: ") # upper is used to capatilize the latter name = name.upper() # all the password saved def webdata(): webdata= input("Enter the key word : ") user_passwords = { 'youtube' : 'subscribe', # here now you can save infinte number of password 'twitter' : 'qwerty', # '' : '', # I created many string to store the data } print(user_passwords.get(webdata)) # here the attribute '.get' get the data from the names; # username and their passwords userdata = { 'ANUJ' : 'lol', 'ANUJ SHARMA' : 'use', '' : '' } # now we looped the dictonairy and get the keys and values or username and password to check for username , password in userdata.items(): # In this case if the name == username we enter so it check wether passcode is equal or not if name == username: if passcode == password: # now the user is verified so we import the webdata or passowords data webdata() # in this the the username and passowrd are linked so they are not going to mess with each other like older have # Note : still it have a problem can you find out what??🧐🧐
true
213ebf4489f815cf959de836a11e2339ca8bcfaa
rsleeper1/Week-3-Programs
/Finding Max and Min Values Recursively.py
2,148
4.21875
4
#Finding Max and Min Values #Ryan Sleeper def findMaxAndMin(sequence): #This method finds the max and min values of a sequence of numbers. if len(sequence) < 2: #This catches a sequence that doesn't have enough numbers to compare (less than 2) and returns the invalid sequence. print("Please create a sequence of at least 2 numbers.") minNum = sequence maxNum = sequence return minNum, maxNum elif len(sequence) == 2: #This is my base case. Once the sequence gets down to two numbers we have found the max and min. sequence.sort() return sequence[0], sequence[1] else: if sequence[0] <= sequence[1]: #This if statement initializes the minimum number and the maximum number. minNum = sequence[0] maxNum = sequence[1] else: minNum = sequence[1] maxNum = sequence[0] if minNum < sequence[2]: #Once we have a minimum and maximum, the method checks the next number and compares it to the if maxNum > sequence[2]: #minimum value and the maximum value. If it is less than the minimum, then it becomes the new sequence.remove(sequence[2]) #minimum value. If it is greater than the maximum value then it becomes the new max value. If return findMaxAndMin(sequence) #it is neither than it gets removed from the list. else: sequence.remove(maxNum) maxNum = sequence[1] return findMaxAndMin(sequence) else: sequence.remove(minNum) minNum = sequence[1] return findMaxAndMin(sequence) def main(): sequence = [54, 79, 8, 0, 9, 9, 23, 120, 40] #This is my sequence, feel free to change it to see different results. minNum, maxNum = findMaxAndMin(sequence) print("The minimum number is: {}".format(minNum)) #I had the program print out the results to make sure it was producing the correct answers. print("The maximum number is: {}".format(maxNum)) main()
true
d075b9df570b98066efa80959ee3d102bca91614
chigozieokoroafor/DSA
/one for you/code.py
259
4.28125
4
while True: name = input("Name: ") if name == "" or name==" ": print("one for you, one for me") raise Exception("meaningful message required, you need to put a name") else: print(f"{name} : one for {name}, one for me")
true
28e8f771a7968081d3ced6b85ddec657163ad7d1
avi527/Tuple
/different_number_arrgument.py
248
4.125
4
#write a program that accepts different number of argument and return sum #of only the positive values passed to it. def sum(*arg): tot=0 for i in arg: if i>0: tot +=i return tot print(sum(1,2,3,-4,-5,9))
true
711646003de502ae59915ebcd3fff47b56b0144d
Wh1te-Crow/algorithms
/sorting.py
1,318
4.21875
4
def insertion_sorting(array): for index in range(1,len(array)): sorting_part=array[0:index+1] unsorting_part=array[index+1:] temp=array[index] i=index-1 while(((i>0 or i==0) and array[i]>temp)): sorting_part[i+1]=sorting_part[i] sorting_part[i]=temp i-=1 array=sorting_part+unsorting_part return(array) def bubble_sorting(array): indicator_of_change=1 index_of_last_unsorted=len(array) while(indicator_of_change): indicator_of_change=0 for index in range(0,index_of_last_unsorted-1): if (array[index]>array[index+1]): temp=array[index] array[index]=array[index+1] array[index+1]=temp indicator_of_change+=1 index_of_last_unsorted-=1 return array def sorting_by_choice(array): sorting_array=[] while(len(array)>0): minimum = array[0] for index in range(1,len(array)): if minimum>array[index]: minimum=array[index] array.remove(minimum) sorting_array.append(minimum) return sorting_array print(insertion_sorting([1,2,3,8,9,0,-1,-5,0])) print(bubble_sorting([1,2,3,8,9,0,-1,-5,0])) print(sorting_by_choice([1,2,3,8,9,0,-1,-5,0]))
true
ba0bf77d3202493747e94c0a686c739d6cb98e9f
srisreedhar/Mizuho-Python-Programming
/Session-18-NestedConditionals/nestedif.py
510
4.1875
4
# ask user to enter a number between 1-5 and print the number in words number=input("Enter a number between 1-5 :") number=int(number) # if number == 1: # print("the number is one") # else: # print("its not one") # Nested conditions if number==1: print("number is one") elif number==2: print("number is two") elif number==3: print("number is Three") elif number==4: print("number is Four") elif number==5: print("number is Five") else: print("The number is out of range")
true
04c4b07e6e7e980e7d759aff14ce51d38fa89413
davelpat/Fundamentals_of_Python
/Ch2 exercises/employeepay.py
843
4.21875
4
""" An employee’s total weekly pay equals the hourly wage multiplied by the total number of regular hours, plus any overtime pay. Overtime pay equals the total overtime hours multiplied by 1.5 times the hourly wage. Write a program that takes as inputs the hourly wage, total regular hours, and total overtime hours and displays an employee’s total weekly pay. Below is an example of the program inputs and output: Enter the wage: $15.50 Enter the regular hours: 40 Enter the overtime hours: 12 The total weekly pay is $899.0 """ # Get employee weekly data wage = float(input("Enter the wage: ")) regHours = float(input("Enter the regular hours: ")) overtime = float(input("Enter the overtime hours: ")) # Calculate the pay pay = wage * regHours + wage * overtime * 1.5 # and display it print("The total weekly pay is $"+str(pay))
true
d5367ee9332da2c450505cb454e4e8dac87b2bf8
davelpat/Fundamentals_of_Python
/Student_Files/ch_11_student_files/Ch_11_Student_Files/testquicksort.py
1,817
4.15625
4
""" File: testquicksort.py Tests the quicksort algorithm """ def quicksort(lyst): """Sorts the items in lyst in ascending order.""" quicksortHelper(lyst, 0, len(lyst) - 1) def quicksortHelper(lyst, left, right): """Partition lyst, then sort the left segment and sort the right segment.""" if left < right: pivotLocation = partition(lyst, left, right) quicksortHelper(lyst, left, pivotLocation - 1) quicksortHelper(lyst, pivotLocation + 1, right) def partition(lyst, left, right): """Shifts items less than the pivot to its left, and items greater than the pivot to its right, and returns the position of the pivot.""" # Find the pivot and exchange it with the last item middle = (left + right) // 2 pivot = swap(lyst, middle, right) # pivot = lyst[middle] # lyst[middle] = lyst[right] # lyst[right] = pivot # Set boundary point to first position boundary = left # Move items less than pivot to the left for index in range(left, right): if lyst[index] < pivot: swap(lyst, index, boundary) boundary += 1 # Exchange the pivot item and the boundary item swap(lyst, right, boundary) return boundary quicksortHelper(0, len(lyst) - 1) def swap(lyst, i, j): """Exchanges the items at positions i and j.""" # You could say lyst[i], lyst[j] = lyst[j], lyst[i] # but the following code shows what is really going on temp = lyst[i] lyst[i] = lyst[j] lyst[j] = temp return temp import random def main(size = 20, sort = quicksort): """Sort a randomly ordered list and print before and after.""" lyst = list(range(1, size + 1)) random.shuffle(lyst) print(lyst) sort(lyst) print(lyst) if __name__ == "__main__": main()
true
1a7183d7758f27abb21426e84019a9ceeb5da7c7
davelpat/Fundamentals_of_Python
/Ch3 exercises/right.py
1,344
4.75
5
""" Write a program that accepts the lengths of three sides of a triangle as inputs. The program output should indicate whether or not the triangle is a right triangle. Recall from the Pythagorean theorem that in a right triangle, the square of one side equals the sum of the squares of the other two sides. Use "The triangle is a right triangle." and "The triangle is not a right triangle." as your final outputs. An example of the program input and proper output format is shown below: Enter the first side: 3 Enter the second side: 4 Enter the third side: 5 The triangle is a right triangle. """ # Get the side lengths sideA = float(input("Enter length of side 1 of the triangele: ")) sideB = float(input("Enter length of side 2 of the triangele: ")) sideC = float(input("Enter length of side 3 of the triangele: ")) # Determine which side is potentially the hypotenuse if sideA == max(sideA, sideB, sideC): hypot = sideA side2 = sideB side3 = sideC elif sideB == max(sideA, sideB, sideC): hypot = sideB side2 = sideA side3 = sideC else: hypot = sideC side2 = sideB side3 = sideA # Determinei if it is a right triangle using the Pythagorean theorem if hypot ** 2 == (side2 ** 2 + side3 ** 2): print("The triangle is a right triangle.") else: print("The triangle is not a right triangle.")
true
82808ac569c685a2b864fd668edebbb7264cd07d
davelpat/Fundamentals_of_Python
/Ch9 exercises/testshapes.py
772
4.375
4
""" Instructions for programming Exercise 9.10 Geometric shapes can be modeled as classes. Develop classes for line segments, circles, and rectangles in the shapes.py file. Each shape object should contain a Turtle object and a color that allow the shape to be drawn in a Turtle graphics window (see Chapter 7 for details). Factor the code for these features (instance variables and methods) into an abstract Shape class. The Circle, Rectangle, and Line classes are all subclasses of Shape. These subclasses include the other information about the specific types of shapes, such as a radius or a corner point and a draw method. Then write a script called testshapes.py that uses several instances of the different shape classes to draw a house and a stick figure. """
true
f9a84cff7e4e9c4a92167506a09fcf09726ecfc1
davelpat/Fundamentals_of_Python
/Ch3 exercises/salary.py
1,387
4.34375
4
""" Instructions Teachers in most school districts are paid on a schedule that provides a salary based on their number of years of teaching experience. For example, a beginning teacher in the Lexington School District might be paid $30,000 the first year. For each year of experience after this first year, up to 10 years, the teacher receives a 2% increase over the preceding value. Write a program that displays a salary schedule, in tabular format, for teachers in a school district. The inputs are: Starting salary Annual percentage increase Number of years for which to print the schedule Each row in the schedule should contain the year number and the salary for that year An example of the program input and output is shown below: Enter the starting salary: $30000 Enter the annual % increase: 2 Enter the number of years: 10 Year Salary ------------- 1 30000.00 2 30600.00 3 31212.00 4 31836.24 5 32472.96 6 33122.42 7 33784.87 8 34460.57 9 35149.78 10 35852.78 """ salary = int(input("Please enter starting salary in dollars: ")) incr = float(input("Please enter the percent annual increase: ")) / 100 service = int(input("Please enter the years of service (max = 10): ")) print("%4s%10s" % ("Year", "Salary")) print("-"*14) for year in range(1, service + 1): print("%-6i%0.2f" % (year, salary)) salary += salary * incr
true
2ee467b7f70e740bce32e857df97bd311034e494
davelpat/Fundamentals_of_Python
/Ch4 exercises/decrrypt-str.py
1,106
4.5625
5
""" Instructions for programming Exercise 4.7 Write a script that decrypts a message coded by the method used in Project 6. Method used in project 6: Add 1 to each character’s numeric ASCII value. Convert it to a bit string. Shift the bits of this string one place to the left. A single-space character in the encrypted string separates the resulting bit strings. An example of the program input and output is shown below: Enter the coded text: 0010011 1001101 1011011 1011011 1100001 000011 1110001 1100001 1100111 1011011 1001011 000101 Hello world! """ DIST = 1 FIRST_ORD = 0 LAST_ORD = 127 SPACE = " " charList = input("Enter the coded text: ").split() eTxt = "" for bstring in charList: # Shift bit string 1 to the left bStrSize = len(bstring) bstring = bstring[-DIST:bStrSize] + bstring[0:bStrSize - DIST] # Convert ordinal bit string to decimal charOrd = 0 exponent = bStrSize - 1 for digit in bstring: charOrd = charOrd + int(digit) * 2 ** exponent exponent = exponent - 1 # Readjust ordinal value eTxt += chr(charOrd - 1) print(eTxt)
true
5b3f98828c1aa52309d9450094ecb3ab990bae91
davelpat/Fundamentals_of_Python
/Ch4 exercises/encrypt-str.py
1,246
4.53125
5
""" Instructions for programming Exercise 4.6 Use the strategy of the decimal to binary conversion and the bit shift left operation defined in Project 5 to code a new encryption algorithm. The algorithm should Add 1 to each character’s numeric ASCII value. Convert it to a bit string. Shift the bits of this string one place to the left. A single-space character in the encrypted string separates the resulting bit strings. An example of the program input and output is shown below: Enter a message: Hello world! 0010011 1001101 1011011 1011011 1100001 000011 1110001 1100001 1100111 1011011 1001011 000101 """ DIST = 1 FIRST_ORD = 0 LAST_ORD = 127 SPACE = " " txt = input("Enter a message: ") eTxt = "" for char in txt: # get and increment character's ASCII value charOrd = ord(char) + DIST # Not sure if the wrap around is required if charOrd > LAST_ORD: charOrd = FIRST_ORD + LAST_ORD - charOrd # Convert it to a bit string bstring = "" while charOrd > 0: remainder = charOrd % 2 charOrd = charOrd // 2 bstring = str(remainder) + bstring # Shift bit string 1 to the left bstring = bstring[DIST:len(bstring)]+bstring[0:DIST] eTxt += bstring + SPACE print(eTxt)
true
8b70613ee7350c54156a4eb076f11b82356055f7
davelpat/Fundamentals_of_Python
/Ch3 exercises/population.py
1,828
4.65625
5
""" Instructions A local biologist needs a program to predict population growth. The inputs would be: The initial number of organisms The rate of growth (a real number greater than 1) The number of hours it takes to achieve this rate A number of hours during which the population grows For example, one might start with a population of 500 organisms, a growth rate of 2, and a growth period to achieve this rate of 6 hours. Assuming that none of the organisms die, this would imply that this population would double in size every 6 hours. Thus, after allowing 6 hours for growth, we would have 1000 organisms, and after 12 hours, we would have 2000 organisms. Write a program that takes these inputs and displays a prediction of the total population. An example of the program input and output is shown below: Enter the initial number of organisms: 10 Enter the rate of growth [a real number > 0]: 2 Enter the number of hours to achieve the rate of growth: 2 Enter the total hours of growth: 6 The total population is 80 """ curPop = initPop = int(input("Enter the initial number of organisms: ")) growthRate = float(input("Enter the rate of growth [a real number > 0]: ")) growthCycle = float(input("Enter the number of hours to achieve the rate of growth: ")) period = float(input("Enter the total hours of growth: ")) fullCycles = int(period // growthCycle) # print("fullCycles =", fullCycles) partCycle = (period % growthCycle) / growthCycle # print("partCycle =", partCycle) for cycle in range(0, fullCycles): curPop = round(curPop * growthRate) # print("Population after", cycle + 1, "cycles is", curPop) # the Python course test is only looking for complete growth cycles # partPop = round((curPop * growthRate - curPop) * partCycle) # urPop = curPop + partPop print("The total population is", curPop)
true
d4a8cd543636b4375918bfe64430df051604c4da
nachoaz/Data_Structures_and_Algorithms
/Stacks/balanced_brackets.py
745
4.15625
4
# balanced_brackets.py """ https://www.hackerrank.com/challenges/balanced-brackets """ from stack import Stack def is_balanced(s): if len(s) % 2 == 1: return 'NO' else: stack = Stack() counterparts = {'{':'}', '[':']', '(':')'} for char in s: if char in counterparts: stack.push(char) elif stack.is_empty() or counterparts[stack.pop()] != char: return 'NO' return 'YES' if stack.is_empty() else 'NO' def main(): n = int(input()) for _ in range(n): bracket_string = input() output = is_balanced(bracket_string) print(output) if __name__ == '__main__': main()
true
15198370140d3b04074d6647eda200767cc2479d
rahulpawargit/UdemyCoursePractice
/Tuples.py
290
4.1875
4
""" Tuples are same as list. The diffferance between list and tuples. Tuples are unmutalble. Tuples add using parenthesis """ my_tuple=(1, 2, 3, 4,3, 3, 3) print(my_tuple) print(my_tuple[1]) print(my_tuple[1:]) print(my_tuple[::-1 ]) print(my_tuple.index(3)) print((my_tuple.count(3)))
true
f7ec1c0eca2e27e733473040f284640f75c37a80
flahlee/Coding-Dojo
/pythonFundamentals/string_list.py
586
4.125
4
#find and replace words = "It's thanksgiving day. It's my birthday, too!" day = 'day' print words.find(day) print words.replace(day, "month") #min and max x = [2,54,-2,7,12,98] print min(x) print max(x) #first and last x = ["hello", 2, 54, -2, 7, 12, 98, "world"] newX= [x[0],x[7]] print newX #new list '''sort list first- split list in half- push the list created from the first half to position O of the list created from the second half''' x = [19,2,54,-2,7,12,98,32,10,-3,6] x.sort() print x first_half= x[len(x)/2] second_half= x[len(x)/2:] print first_half print second_half
true
75f2c8f77f19883b41af604e0bb70318243efcd5
Sameer19A/Python-Basics
/HelloWorld.py
243
4.28125
4
#Compulsory Task 3 name = input("Enter your name: ") age = input("Enter your age: ") print(name) #prints user entered name print(age) #prints user entered age print("") #prints a new empty line print("Hello World!")
true
286cb30b15f984cb922dc229773e6e2eda569ddd
Shreyasi2002/CODE_IN_PLACE_experience
/Section2-Welcome to python/8ball.py
954
4.1875
4
""" Simulates a magic eight ball. Prompts the user to type a yes or no question and gives a random answer from a set of prefabricated responses. """ import random RESPONSES = ["As I see it, yes.", "Ask again later.", "Better not to tell you now." , "Cannot predict now.", "Concentrate and ask again.", "Don't count on it." , "It is certain.", "It is decidedly so.", "Most likely.", "My reply is no." , "My sources say no.", "Outlook not so good.", "Outlook good.", "Reply hazy, try again." , "Signs point to yes.", "Very doubtful.", "Without a doubt.", "Yes." , "Yes - definitely.", "You may rely on it."] TOTAL_RESPONSES = 19 def main(): question = input("Ask a yes or no question: ") num = 0 # to represent the index of the RESPONSES list while question != "": num = random.randint(0, TOTAL_RESPONSES) print(RESPONSES [num]) question = input("Ask a yes or no question: ") if __name__ == "__main__": main()
true