blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
91cc4ff7b8e7e275ba61d799d81c8eecb7587b7c | Shreyasi2002/CODE_IN_PLACE_experience | /CoreComplete/leap.py | 930 | 4.4375 | 4 | """
Example of using the index variable of a for loop
"""
def main():
pass
def is_divisible(a, b):
"""
>>> is_divisible(20, 4)
True
>>> is_divisible(12, 7)
False
>>> is_divisible(10, 10)
True
"""
return a % b == 0
def is_leap_year(year):
"""
Returns Boolean indicating if given year is a leap year.
It is a leap year if the year is:
* divisible by 4, but not divisible by 100
OR
* divisible by 400
Doctests:
>>> is_leap_year(2001)
False
>>> is_leap_year(2020)
True
>>> is_leap_year(2000)
True
>>> is_leap_year(1900)
False
"""
# if the year is divisible by 400, it is a leap year!
if is_divisible(year, 400):
return True
# other wise its a leap year if its divisible by 4 and not 100
return is_divisible(year, 4) and not is_divisible(year, 100)
if __name__ == '__main__':
main()
| true |
edf4a58d87d2c5cef9a6e06e2ace05ad5096268d | djoo1028/Euler | /euler01.py | 1,636 | 4.3125 | 4 | '''
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
def findSum(arg1):
a = arg1 # input value will be range for the summation
arr3 = [] # multiple of 3
for i in range(1,x+1): # Remove 0 and include the last spot
if 3 * i > x: # If the value is greater than range than break for loop
break
else:
arr3.append(3 * i) # add in to the list
print(list(arr3))
arr5 = [] # multiple of 5
for i in range(1,x+1):
if 5 * i >= x:
break
else:
arr5.append(5 * i)
print(list(arr5))
arr = arr3 + arr5 # Add two list which have multiple of 3 and 5
noDup = []
for i in arr: # Remove duplicate numbers
if i not in noDup: # If a number does not exist add and if number is exist move to next index
noDup.append(i)
print(list(noDup)) # checke
SSum = sum(noDup) # Sum all numbers in list
print(SSum)
#Second idea(shorter version)
def findSumShort(arg1):
a = arg1
sum = 0
for i in range(a):
if (i % 3 == 0) or (i % 5 == 0): # I do not have to think about duplicates because this statement check element at the same time.
# For example, if i = 15 then T or T is True so 15 will be added sum.
sum += i
print(sum)
x = int(input())
findSum(x)
findSumShort(x)
| true |
f0b39ddce7802ef09e39599f494c3461fc18007f | rati90/mjeraarmjera | /service/trustorNot.py | 2,590 | 4.15625 | 4 | def hands_table_clear(table, said_cards):
"""
for some decisions clears table and say lists
:param tuple player_hands_table_say not cleared table and say
:return tuple player_hands_table_say cleared table and say
"""
table.clear()
said_cards.clear()
return table, said_cards
def do_you_trust(player_hands_table_say: tuple, player: int):
"""
The function takes next players choices Yes, No, or Add
and depend on it give cards to players and removes
:param player_hands_table_say tuples that included three lists
:param player the player that made previous decision
:return player_hands_table_say tuple modified depend on choices
"""
all_players_cards = player_hands_table_say[0]
table = player_hands_table_say[1]
said_cards = player_hands_table_say[2]
next_player = player + 1
while True:
choice = input( f"Player N {player + 2} Do you trust? choice \"Yes\" or \"No\" or \"Add\" to add more cards:")
if choice == "Yes":
print(table, said_cards)
if sorted(table[len(said_cards)-1:]) == sorted(said_cards):
hands_table_clear(table, said_cards)
break
else:
if len(all_players_cards) > next_player:
all_players_cards[next_player].extend(table)
hands_table_clear(table, said_cards)
break
elif len(all_players_cards) == next_player:
all_players_cards[0].extend(table)
hands_table_clear(table, said_cards)
break
elif choice == "No":
if sorted(table[len(said_cards)-1:]) == sorted(said_cards):
if len(all_players_cards) > next_player:
all_players_cards[next_player].extend(table)
hands_table_clear(table, said_cards)
break
elif len(all_players_cards) == next_player:
all_players_cards[0].extend(table)
hands_table_clear(table, said_cards)
break
else:
all_players_cards[player].extend(table)
hands_table_clear(table, said_cards)
break
elif choice == "Add":
said_cards.clear()
return player_hands_table_say
else:
print("Please write right answer, Yes, No, or add\n")
continue
print("print here2")
return player_hands_table_say
| true |
d999688c971c11599747b52a8f1630c1f56e3542 | Ryandalion/Python | /Repetition Structures/Distance Travelled/Distance Travelled/Distance_Travelled.py | 777 | 4.4375 | 4 | # Function that asks the user to input the number of hours they have driven and the speed at which they were driving, the program will then calculate the total distance travelled per hour
distanceTravelled = 0;
numHours = int(input("Please enter the number of hours you drove: "));
speed = int(input("Please enter the average speed of the vehicle: "));
while (numHours < 0):
numHours = int(input("Hours cannot be negative. Please enter the number of hours you drove: "));
while(speed < 0):
speed = int(input("Speed cannot be negative. Please enter the average speed of the vehicle: "));
print("HOUR ---------- DISTANCE TRAVELLED")
for x in range (1, numHours+1, 1):
distanceTravelled = x * speed;
print(x, " ", distanceTravelled,"miles"); | true |
3d9f49a20ba365934e8a47255bde04df1db32495 | Ryandalion/Python | /Dictionaries and Sets/File Analysis/File Analysis/File_Analysis.py | 1,525 | 4.1875 | 4 | # Program will read the contents of two text files and determine a series of results between the two, such as mutual elements, exclusive elements, etc.
def main():
setA = set(open("file1.txt").read().split()); # Load data from file1.txt into setA
setB = set(open("file2.txt").read().split()); # Load data from file2.txt into setB
mutualElements = setA.intersection(setB); # Mutual Elements - Intersection between the two sets. The values found in both sets.
unionElements = setA.union(setB); # Union Elements - The total array of elements between the two sets
exclusiveElements = unionElements - mutualElements; # Exclusive Elements - List of elements that are exclusive to set A and exclusive to set B, combined
setAelements = unionElements-setB; # Set A Elements - All elements exclusive to set A only
setBelements = unionElements-setA; # Set B Elements - All elements exclusive to set B only
print("Here is some data about the text files"); # Display the data to the user
print("\nMutual Elements: ", mutualElements); # Mutual elements
print();
print("\nExclusive Elements: ", exclusiveElements); # Exclusive elements
print();
print("\nAll Elements: ", unionElements); # Union of set A and set B
print();
print("\nElements of Set A (exclusive): ", setAelements); # Exclusive elements of set A
print();
print("\nElements of Set B (exclusive): ", setBelements); # Exclusive elements of set B
print("Set A and Set B Analysis\n");
main(); # Execute main
| true |
564b68912dd8b44e4001a22d92ff18471a55fbe4 | Ryandalion/Python | /Decision Structures and Boolean Logic/Age Calculator/Age Calculator/Age_Calculator.py | 568 | 4.4375 | 4 | # Function takes user's age and tells them if they are an infant, child, teen, or adult
# 1 year old or less = INFANT
# 1 ~ 13 year old = CHILD
# 13 ~ 20 = TEEN
# 20+ = ADULT
userAge = int(input('Please enter your age: '));
if userAge < 0 or userAge > 135:
print('Please enter a valid age');
else:
if userAge <= 1:
print('You are an infant');
elif userAge > 1 and userAge < 13:
print('You are a child');
elif userAge >= 13 and userAge <= 20:
print('You are a teen');
elif userAge >= 20:
print('You are an adult');
| true |
8a4d3456f828edb3893db4e6dd836873344b91e9 | Ryandalion/Python | /Functions/Future Value/Future Value/Future_Value.py | 1,862 | 4.59375 | 5 | # Program calculates the future value of one's savings account
def calculateInterest(principal, interestRate, months): # Function calculates the interest accumulated for the savings account given the arguments from the user
interestRate /= 100; # Convert the interest rate into a decimal
futureValue = principal * pow(1 + interestRate, months); # Assign the projected balance to the future value variable
return futureValue; # Return future value
def main(): # Function is responsible for user input and validation, calling required functions, and displaying the project account balance to the user
principal = float(input("Enter the current savings account balance: ")); # Collect current balance of savings account
while(principal < 0):
principal = float(input("Account balance must be greater than zero. Enter the current savings account balance: "));
interestRate = float(input("Enter the current interest rate: ")); # Collect the interest rate for the savings account
while(interestRate < 0):
interestRate = float(input("Interest rate must be greater than zero. Enter the current interest rate: "));
months = int(input("Enter the number of months you wish to find the projection for: ")); # Collect the number of months the balance will stay in savings
while(months < 0):
months = int(input("Months be greater than zero. Enter the number of months you wish to find the projection for: "));
account_value = calculateInterest(principal, interestRate, months); # Send the user's inputs as parameters to the calculate interest function and assign the return value to account_value
print("The account will be worth $", format(account_value,'.2f'),"in",months,"months"); # Display the projected account balance to the user
print("Savings Account Future Value Calculator");
print();
main(); | true |
39cd605853421bafc6abaeda2b905e3bf06b6c6e | Ryandalion/Python | /Functions/Rock, Paper, Scissors!/Rock, Paper, Scissors!/Rock__Paper__Scissors_.py | 2,151 | 4.46875 | 4 | # Program is a simple rock paper scissors game versus the computer. The computer's hand will be randomly generated and the user will input theirs. Then the program will determine the winner. If it is a tie, a rematch will execute
import random; # Import random module to use randint
def generate_random(): # Generate a random number that corresponds to either rock,paper, or scissors
randNum = random.randint(1,3);
return randNum; # Return the generated number to caller
def calculate_winner(userHand, computerHand): # Function calculates the winner between computer and user
if(userHand == 1 and computerHand == 3):
print("User Wins");
elif(userHand == 2 and computerHand == 1):
print("User Wins");
elif(userHand == 3 and computerHand == 2):
print("User Wins");
elif(userHand == 3 and computerHand == 1):
print("Computer Wins");
elif(userHand == 1 and computerHand == 2):
print("Computer Wins");
elif(userHand == 2 and computerHand == 3):
print("Computer Wins");
else: # If it is a draw then we set tie status to true and return to caller
print("It is a tie");
tieStatus = 0;
return tieStatus;
def main(): # Function is responsible for getting user input and calling the appropriate functions and handling the while loop
status = 1;
while(status != -1): # Keep looping until status equals -1
computerHand = generate_random(); # Generate a random number and assign it to computer hand
print("Select your move");
print("1. Rock");
print("2. Paper");
print("3. Scissors");
userHand = int(input()); # Get user's selection
status = calculate_winner(userHand, computerHand); # Send the user's and the computer's hand as arguments to the calculate_winner function
if(status == 0): # If the return value from calculate_winner is 0, a tie has occured and we execute another round
status = 1;
else: # There was a winner and we assign status -1 to exit the while loop and program
status = -1;
print("Rock, Paper, or Scissors");
print();
main(); | true |
c19b84caf9895177da8ccbcbd845ef5f03653e4d | Ryandalion/Python | /Functions/Fat and Carb Calorie Calculator/Fat and Carb Calorie Calculator/Fat_and_Carb_Calorie_Calculator.py | 1,465 | 4.34375 | 4 | # Function that gathers the carbohyrdates and fat the user has consumed and displays the amount of calories gained from each
def fatCalorie(fat): # Function calculates the calories gained from fat
calFat = fat * 9;
print("The total calories from",fat,"grams of fat is", calFat,"calories");
def carbCalorie(carbs): # Function calculates the calories gained from carbs
carbFat = carbs * 4;
print("The total calories from", carbs,"grams of carbs is", carbFat, "calories");
def main(): # Function gathers user information and validates it. Then sends the arguments to their respective functions`
fat = int(input("Enter the amount of fat in grams consumed today: ")); # Gather fat consumed from user
while(fat < 0): # Validate user input
fat = int(input("Input must be greater than zero. Enter the amount of fat in grams consumed today: "));
carbs = int(input("Enter the amount of carbs consumed today: ")); # Gather carbs consumed from user
while(carbs < 0): # Validate user input
carbs = int(input("Input must be greater than zero. Enter the amount of carbs consumed today: "));
print();
# All inputs have passed validation so we pass the variables to their respective functions
fatCalorie(fat); # Call fatCalorie function and pass fat as argument
print();
carbCalorie(carbs); # Call carbCalorie function and pass carbs as argument
print("Fat and Carb to Calorie Calculator");
print();
main(); | true |
5d4fa6aaab3cc50ab1b67c9ab5add9ca49d2f25a | Ryandalion/Python | /Decision Structures and Boolean Logic/Roman Numeral Converter/Roman Numeral Converter/Roman_Numeral_Converter.py | 1,269 | 4.21875 | 4 | # Function converts a number to a roman numeral
userNum = int(input('Please enter a literal number between 1 ~ 10 you wish to convert to a Roman numeral: '));
if userNum < 0 or userNum > 10:
print('Please enter a number between 1 and 10');
else:
if userNum == 1:
print('I');
else:
if userNum == 2:
print('II');
else:
if userNum == 3:
print('III');
else:
if userNum == 4:
print('IV');
else:
if userNum == 5:
print('V');
else:
if userNum == 6:
print('VI');
else:
if userNum == 7:
print('VII');
else:
if userNum == 8:
print('VIII');
else:
if userNum == 9:
print('IX');
else:
if userNum == 10:
print('X');
| true |
2b7ac8c5047791e80d7078a9f678b27c0c79d997 | Ryandalion/Python | /Lists and Tuples/Larger than N/Larger than N/Larger_than_N.py | 1,752 | 4.3125 | 4 | # Program generates a list via random generation and compares it to a user input number n which will determine if the elements within the last are greater than the number
import random; # Import the random module to generate a random integer
def main():
randNum = [0] * 10; # Intialize list with 10 elements of zero
for x in range(10): # Loop 10 times
randNum[x] = random.randint(0,10); # Generate a random number between 0 and 10
x+=1; # Increment x by one
userNum = int(input("Please enter a number: ")); # Get the user's number they wish to compare to the elements of the list
print(randNum); # Print list for verification purposes
numGreater = compareNum(randNum, userNum); # Send the list and the user number to the numGreater function to be evaluated
print("There are",numGreater,"numbers greater than",userNum); # Print the results that were returned by the compare function
def compareNum(userList, userNum): # Function will compare the elements in the list to the user specified number. It will calculate the number of elements that are greater than the user number
numGreater = 0; # Create a numGreater variable to hold the number of elements that are greater than the user specified number
for x in range(len(userList)): # Loop through the length of the list
if userNum < userList[x]: # If list element is greater than user number execute
numGreater += 1; # Increase the numGreater variable by one
x += 1; # Increase the counter variable
else: # If userNum is greater than the list element
x +=1; # Increase x by one
return numGreater; # Return the results to the caller
print("Larger than N\n")
main(); # Execute main
| true |
daee14c84fcbbe19529eae9f874083297fc67493 | run-fourest-run/PythonDataStructures-Algos | /Chapter 3 - Python Data Types and Structures/Sets.py | 2,216 | 4.125 | 4 | '''
Sets are unordered collection of unique items. Sets are mutable, but the elements inside of them are immutable.
* Important distinctions is that the cannot contain duplicate keys
* Sets are typically used to perform mathmatical operations such as intersection, union, difference and complement.
Unlike sequence types, set types do not provide any indexing or slicing operations. There are also no keys associated with values.
'''
player_list = ['alex','spencer','don','don']
cod_players = set(player_list)
'''
Methods and operations:
'''
#len(s)
#length
length = len(cod_players)
#s.copy()
#copy
copy = cod_players.copy()
#s.add()
#add
copy.add('ryan')
#s.difference(t)
#difference --> returns all items in s but not in t
difference = cod_players.difference(copy)
#s.intersection(t)
#intersections --> returns a set of all items in both t and s
intersection = cod_players.intersection(copy)
#s.isdisjoint(t)
#is disjoint --> Returns True if S and t have no items in common
isdisjoint = cod_players.isdisjoint(copy)
#s.issubset(t)
# is subset --> Returns True if all items in s are also in t
subset = cod_players.issubset(copy)
#s.issuperset(t)
# is superset --> Returns True if all items in t are also in s
superset = cod_players.issuperset(copy)
#s.union(t)
# union --> returns a set of all items in s or t
union = cod_players.union(copy)
'''Mutable set object methods '''
#s.add(item)
#add
cod_players.add('doug')
#s.clear()
#clear
copy_cod_players = cod_players.copy()
copy_cod_players.clear()
#s.difference_update(t)
#difference update --? removes all items in s that are also in t
cod_players.difference_update(['spencer','alex'])
#s.discard(item)
#discard --> remove item from set
cod_players.discard('doug')
#s.intersection_update(t)
#intersection update --> removes all items from s that are not in the intersection of s and t
cod_players.intersection_update(['alex'])
#s.pop
#pop --> returns and removes
cod_players.pop('don')
#s.symetric_difference_updater
#symeteric difference updater --> removes all items from s that are not in the symettric difference of s and t (no idea what the fuck that means)
cod_players.symmetric_difference_update(['dontknow'])
| true |
90e9a6e867b5601d2ce5fc2ed648d980eb904b17 | PWalis/Intro-Python-I | /src/10_functions.py | 495 | 4.28125 | 4 | # Write a function is_even that will return true if the passed-in number is even.
# YOUR CODE HERE
def is_even(n):
if n % 2 == 0:
return True
else:
return False
print(is_even(6))
# Read a number from the keyboard
num = input("Your number here")
num = int(num)
# Print out "Even!" if the number is even. Otherwise print "Odd"
# YOUR CODE HERE
def even_odd():
global num
if num % 2 == 0:
return 'Even'
else:
return 'Odd'
print(even_odd())
| true |
ad0017b73937ba9313620bfc23101a2502707321 | Sumanthsjoshi/capstone-python-projects | /src/get_prime_number.py | 728 | 4.125 | 4 | # This program prints next prime number until user chooses to stop
# Problem statement: Have the program find prime numbers until the user chooses
# to stop asking for the next one.
# Define a generator function
def get_prime():
num = 3
yield 2
while True:
is_prime = True
for j in range(3, num, 2):
if num % j == 0:
is_prime = False
if is_prime:
yield num
num += 2
# Initialize a generator instance
g = get_prime()
# Get the user input
while True:
inp = input("Press enter to get next prime number(Enter any key to stop)")
if not inp:
print(next(g))
else:
print("Stopping the prime generator!!")
break
| true |
8c99ba43d3481a6190df22b51b93d2d94358f68c | abhic55555/Python | /Assignments/Assignment2/Assignment2_3.py | 440 | 4.15625 | 4 | def factorial(value1):
if value1 > 0:
factorial = 1
for i in range(1,value1 + 1):
factorial = factorial*i
print("The factorial of {} is {}".format(value1,factorial))
elif value1==0:
print("The factorial of 0 is 1 ")
else:-
print("Invalid number")
def main():
value1 = int(input("Enter first number : "))
factorial(value1)
if __name__ == "__main__":
main() | true |
6b89934c7911e7f1c24db7c739b46eb26050297c | Tyler668/Code-Challenges | /twoSum.py | 1,018 | 4.1875 | 4 | # # Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
# # (i.e., [0, 1, 2, 4, 5, 6, 7] might become[4, 5, 6, 7, 0, 1, 2]).
# # You are given a target value to search. If found in the array return its index, otherwise return -1.
# # You may assume no duplicate exists in the array.
# # Your algorithm's runtime complexity must be in the order of O(log n).
# # Example 1:
# # Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 0
# # Output: 4
# # Example 2:
# # Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 3
# # Output: -1
# def search(nums, target):
# mid = len(nums) // 2
# # print(mid, nums[mid])
# if nums[mid] == target:
# return mid
# elif nums[mid] > target:
# lowerHalf
# nums = [4, 5, 6, 7, 0, 1, 2, 19]
# target = 0
# print(search(nums, target))
def double_char(txt):
solution = ''
for i in range(len(txt)):
double = 2 * txt[i]
solution += double
return solution
print(double_char("Hello"))
| true |
15be302b0b417de9eb462b731ad20a0d78e448d8 | SaiJyothiGudibandi/Python_CS5590-490-0001 | /ICE/ICE1/2/Reverse.py | 328 | 4.21875 | 4 | num = int(input('Enter the number:')) #Taking nput from the user
Reverse = 0
while(num > 0): #loop to check whether the number is > 0
Reminder = num%10 # finding the reminder for number
Reverse = (Reverse * 10) + Reminder
num = num // 10
print('Reverse for the Entered number is:%d' %Reverse)
| true |
bb0b85fbe5e9fe5c3e05dfb28f35feba48e2d0d7 | jarturomora/learningpython | /ex16bis.py | 834 | 4.28125 | 4 | from sys import argv
script, filename = argv
# Opening the file in "read-write" mode.
my_file = open(filename, "rw+")
# We show the current contents of the file passed in filename.
print "This is the current content of the file %r." % filename
print my_file.read()
print "Do you want to create new content for this file?"
raw_input("(hit CTRL-C if you don't or hit RETURN if you do) >")
# In order to truncate the file we move the pointer to the first line.
my_file.seek(0)
my_file.truncate()
print "\nThe file %r was deleted..." % filename
print "\nWrite three lines to store in the file %r" % filename
line1 = raw_input("Line 1: ")
line2 = raw_input("Line 2: ")
line3 = raw_input("Line 3: ")
my_file.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
my_file.close()
print "The new contents for %r has been saved." % filename
| true |
8e81b8f7d46c6257d8a6dbabfd677297149148be | jarturomora/learningpython | /ex44e.py | 863 | 4.15625 | 4 | class Other(object):
def override(self):
print "OTHER override()"
def implicit(self):
print "OTHER implicit()"
def altered(self):
print "OTHER altered()"
class Child(object):
def __init__(self):
self.other = Other() # The composition begins here
# where Child has-a other
def implicit(self):
self.other.implicit() # Call to the implicit() method of
# Child's 'other' instance.
def override(self):
print "CHILD override()"
def altered(self):
print "CHILD BEFORE OTHER altered()"
self.other.altered() # Call to the altered() method of 'other' object.
print "CHILD AFTER OTHER altered()"
son = Child()
son.implicit() # Call to the method "composed" from "Other" class.
son.override()
son.altered() | true |
01ce27d5d65b55566cccded488d1c99d2fd848b0 | dablackwood/my_scripts_project_euler | /specific_solutions/project_euler_019.py | 1,079 | 4.1875 | 4 | """
You are given the following information, but you may prefer to do some
research for yourself.
* 1 Jan 1900 was a Monday.
* Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
* A leap year occurs on any year evenly divisible by 4, but not on a
century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century
(1 Jan 1901 to 31 Dec 2000)?
"""
day = 2
tally = 0
months_common = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
months_leap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for year in xrange(1901, 2001):
#print
print year,
if year % 4 == 0:
months_current = months_leap
else:
months_current = months_common
for month in xrange(0, 12):
#print day, day % 7,
if day % 7 == 0:
tally = tally + 1
day = day + months_current[month]
print tally
print "*", tally
| true |
159b7422dc21ca5c01cec91b1c27ee3a88b08ca1 | dablackwood/my_scripts_project_euler | /specific_solutions/project_euler_029a.py | 759 | 4.15625 | 4 | """
Consider all integer combinations of a^(b) for 2<=a<=5 and 2<=b<=5:
2^(2)=4, 2^(3)=8, 2^(4)=16, 2^(5)=32
3^(2)=9, 3^(3)=27, 3^(4)=81, 3^(5)=243
4^(2)=16, 4^(3)=64, 4^(4)=256, 4^(5)=1024
5^(2)=25, 5^(3)=125, 5^(4)=625, 5^(5)=3125
If they are then placed in numerical order, with any repeats removed, we get
the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by a^(b) for 2<=a<=100
and 2<=b<=100?
"""
max_a_b = input("Max for 'a' and 'b': ")
big_list = []
for a in xrange(2, max_a_b + 1):
for b in xrange(2, max_a_b + 1):
if big_list.count(a ** b) == 0:
big_list.append(a ** b)
print len(big_list)
| true |
73980da3c813213a81f11db877458ff72c0a47b7 | shaziya21/PYTHON | /constructor_in_inheritance.py | 732 | 4.1875 | 4 | class A: # Parent class / Super class
def __init__(self): # Constructor of parent class A
print("in A init")
def feature1(self):
print("feature1 is working")
def feature2(self):
print("feature2 is working")
class B(A):
def __init__(self):
super().__init__() # jump up to super class A executes it thn jump back to B and thn execute it.
print("in B init")
def feature3(self):
print("feature3 is working")
def feature4(self):
print("feature4 is working")
a1 = B()
# when you create object of sub class it will call init of sub class first.
# if you have ccall super then it will first call init of super class thn call init of sub class.
| true |
6ffafcc1da316699df44275889ffab8ba957265f | shaziya21/PYTHON | /MRO.py | 1,004 | 4.4375 | 4 | class A: # Parent class / Super class
def __init__(self): # Constructor of parent class A
print("in A init")
def feature1(self):
print("feature 1-A is working")
def feature2(self):
print("feature2 is working")
class B:
def __init__(self): # Constructor of class B
print("in B init")
def feature1(self):
print("feature 1-B is working")
def feature4(self):
print("feature4 is working")
class C(A,B): # C is inheriting both from A & B
def __init__(self):
super().__init__() # Constructor of parent class A
print("in C init")
def feature5(self):
print("feature5 is working")
def feat(self):
super().feature2() # super method is used to call other method as well not just init
a1 = C() # it will give output for C & A only coz in multiple inheritance
a1.feature1() # it starts from left to right
a1.feat() # to represent super class we use super method.
| true |
1e870f6429ff8f0b0cde4f40b7d0f3e148242257 | JoshiDivya/PythonExam | /Pelindrome.py | 354 | 4.3125 | 4 | def is_pelindrome(word):
word=word.lower()
word1=word
new_str=''
while len(word1)>0:
new_str=new_str+ word1[-1]
word1=word1[:-1]
print(new_str)
if (new_str== word):
return True
else:
return False
if is_pelindrome(input("Enter String >>>")):
print("yes,this is pelindrome")
else:
print("Sorry,this is not pelindrome") | true |
2dd93300d7ede7b2fd78a925eeea3d912ae55c51 | dhaffner/pycon-africa | /example1.py | 408 | 4.53125 | 5 | # Example #1: Currying with inner functions
# Given a function, f(x, y)...
def f(x, y):
return x ** 2 + y ** 2
# ...currying constructs a new function, h(x), that takes an argument
# from X and returns a function that maps Y to Z.
#
# f(x, y) = h(x)(y)
#
def h(x):
def curried(y):
return f(x, y)
return curried
fix10 = h(10)
for y in range(10):
print(f'fix10({y}) = {fix10(y)}') | true |
a93f8e9ac02ba81adbd2b0ead5aa0a2af11d6011 | egill12/pythongrogramming | /P3_question4.py | 842 | 4.625 | 5 | '''
Write a program that asks the user for a long string containing multiple words.
Echo back to the user the same string, except with the words in backwards order.
For example, say we type the string:
My name is Michele
Then we would expect to see the string:
Michele is name My
'''
def reverse_str(string):
'''
Write a program that asks the user for a long string containing multiple words.
Echo back to the user the same string, except with the words in backwards order.
:param string:
:return:
'''
broken_string = string.split()
reversed_string = []
for element in reversed(broken_string):
reversed_string.append(element)
return reversed_string
string = str(input("please give str:"))
reversed_string = reverse_str(string)
for element in reversed_string:
print(element, end = " " ) | true |
fc044bef4295e8e85313366be4a89689938756c2 | BjornChrisnach/Basics_of_Computing_and_Programming | /days_traveled.py | 233 | 4.125 | 4 | print("Please enter the number of days you traveled")
days_traveled = int(input())
full_weeks = days_traveled // 7
remaining_days = days_traveled % 7
print(days_traveled, "days are", full_weeks, "weeks and",\
remaining_days,"days") | true |
386917245b7e7130aa3a96abccf9ca35842e1904 | getachew67/UW-Python-AI-Coursework-Projects | /Advanced Data Programming/hw2/hw2_pandas.py | 2,159 | 4.1875 | 4 | """
Khoa Tran
CSE 163 AB
This program performs analysis on a given Pokemon data file,
giving various information like average attack levels for a particular type
or number of species and much more. This program immplements the panda
library in order to compute the statistics.
"""
def species_count(data):
"""
Returns the number of unique species in the
given file
"""
result = data['name'].unique()
return len(result)
def max_level(data):
"""
Returns a tuple with the name and level of the Pokemon
that has the highest level
"""
index = data['level'].idxmax()
result = (data.loc[index, 'name'], data.loc[index, 'level'])
return result
def filter_range(data, low, high):
"""
Returns a list of Pokemon names having a level that is
larger or equal to the lower given range and less than
the higher given range
"""
temp = data[(data['level'] >= low) & (data['level'] < high)]
return list(temp['name'])
def mean_attack_for_type(data, type):
"""
Returns the average attack for all Pokemon
in dataset with the given type
Special Case: If the dataset does not contain the given type,
returns 'None'
"""
temp = data.groupby('type')['atk'].mean()
if type not in temp.index:
return None
else:
return temp[type]
def count_types(data):
"""
Returns a dictionary of Pokemon with the types
as the keys and the values as the corresponding
number of times that the type appears in the dataset
"""
temp = data.groupby('type')['type'].count()
return dict(temp)
def highest_stage_per_type(data):
"""
Returns a dictionary with the key as the type of
Pokemon and the value as the highest stage reached for
the corresponding type in the dataset
"""
temp = data.groupby('type')['stage'].max()
return dict(temp)
def mean_attack_per_type(data):
"""
Returns a dictionary with the key as the type of Pokemon
and the value as the average attack for
the corresponding Pokemon type in the dataset
"""
temp = data.groupby('type')['atk'].mean()
return dict(temp)
| true |
5d01d82bfd16634be636cce2cf2e1d31ea7208b1 | Razorro/Leetcode | /88. Merge Sorted Array.py | 1,353 | 4.28125 | 4 | """
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
No other tricks, just observation.
执行用时: 68 ms, 在Merge Sorted Array的Python3提交中击败了8.11% 的用户
内存消耗: 13.1 MB, 在Merge Sorted Array的Python3提交中击败了0.51% 的用户
Although the result is not so well, but I think there is no big difference with other solutions.
"""
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
idx1, idx2 = m - 1, n - 1
fillIdx = len(nums1) - 1
while idx1 >= 0 and idx2 >= 0:
if nums1[idx1] > nums2[idx2]:
nums1[fillIdx] = nums1[idx1]
idx1 -= 1
else:
nums1[fillIdx] = nums2[idx2]
idx2 -= 1
fillIdx -= 1
while idx2 >= 0:
nums1[fillIdx] = nums2[idx2]
idx2 -= 1
fillIdx -= 1 | true |
2cd13056f72eaf8f16e342bacde6c9b17bd43d3b | Razorro/Leetcode | /49. Group Anagrams.py | 863 | 4.125 | 4 | """
Description:
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
Runtime: 152 ms, faster than 39.32% of Python3 online submissions for Group Anagrams.
Memory Usage: 15.5 MB, less than 100.00% of Python3 online submissions for Group Anagrams.
Not very fast, but I guess all the answer comply the rule:
Make unique hash value of those same anagrams.
"""
class Solution:
def groupAnagrams(self, strs: 'List[str]') -> 'List[List[str]]':
import collections
h = collections.defaultdict(list)
for s in strs:
h[''.join(sorted(s))].append(s)
return list(h.values())
return list(collectorDict.values()) | true |
d2d6f21556955a4b8ec8893b8bf03e7478032b68 | Razorro/Leetcode | /7. Reverse Integer.py | 817 | 4.15625 | 4 | """
Description:
Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1].
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
"""
""" Analysis:
Easy...
Nope... forget to deal with overflow
"""
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
flag = x < 0
constant = 2**31
x = abs(x)
x = str(x)
x = x[::-1]
x = int(x)
if flag:
x = -x if x <= constant else 0
else:
x = x if x <= constant-1 else 0
return x
if __name__ == '__main__':
testCase = [
] | true |
92b2ac96f202ac222ccd4b9572595602abf0a459 | jrahman1988/PythonSandbox | /myDataStruct_CreateDictionaryByFilteringOutKeys.py | 677 | 4.34375 | 4 | '''
A dictionary is like an address-book where we can find the address or contact details of a person by knowing only his/her name
i.e. we associate keys (name) with values
Dictionary is represented by dict class. Pair of keys and values are specified in dictionary using the notation
d = {key1 : value1, key2 : value2 }
When we need to create a dictionary from a dictionary by filtering specific keys
'''
# Single dictionary, from here will create another dictionary by filtering out keys 'a' and 'c':
d1 = {"c": 3, "a": 1, "b": 2, "d": 4}
filter_list = ["a", "c"]
d11 = dict((i, d1[i])
for i in filter_list if i in d1)
print("Type of d11: ", type(d11))
print(d11) | true |
1a4d781b35cfbb98acbc1b8b9fad8aa9a78c51ac | jrahman1988/PythonSandbox | /myPandas_DescriptiveStatistics.py | 1,754 | 4.40625 | 4 | '''
A large number of methods collectively compute descriptive statistics and other related operations on DataFrame.
Most of these are aggregations like sum(), mean(), but some of them, like sumsum(), produce an object of the same size.
Generally speaking, these methods take an axis argument, just like ndarray.{sum, std, ...}, but the axis can be specified by name or integer
'''
import pandas as pd
desired_width=320
pd.set_option('display.width', desired_width)
pd.set_option('display.max_columns',100)
#Read the pokemon_data.csv from the file system and transform into a DataFrame using read_csv() method
df = pd.read_csv("~/Desktop/Learning/Sandbox/PythonSandbox/Data/pokemon_data.csv")
#Output statistics of all data in the file using describe() method
print("\nOutput all basic statistics using describe(): \n", df.describe())
#Sort output using sort_values() method (default is ascending order)
print("\nOutput sorted data based on the column named 'Name': \n", df.sort_values('Name'))
#Sorting based on a single column in a file and output using sort_values() method (descending order - ascending=false)
print("\nOutput sorted data based on the column named 'Name' in descending order: \n", df.sort_values('Name', ascending=False))
#Sorting based on a multiple columns in a file and output using sort_values() method ('Name' column in ascending order and 'HP' column in descending order)
print("\nOutput sorted data based multiple columns 'Name' and 'HP' one in ascending and other in descending order: \n", df.sort_values(['Name', 'HP'], ascending=[1,0]))
#Summing the values in the columns of a DF using sum(axis) where axis = 0 is vertical and 1= horizontal
print("\nSum of the values in column with index 1 of the DF :\n", df.sum(1)) | true |
f45471a04eef4398d02bbe12151a6b031b394452 | jrahman1988/PythonSandbox | /myFunction_printMultipleTimes.py | 427 | 4.3125 | 4 | '''
Functions are reusable pieces of programs. They allow us to give a name to a block of statements, allowing us to run that block
using the specified name anywhere in your program and any number of times. This is known as calling the function.
'''
def printMultipleTimes(message:str, time:int):
print(message * time)
#Call the functions by passing parameters
printMultipleTimes("Hello ",2)
printMultipleTimes("Hello ",5) | true |
b2965c970bce71eee39841548b95ab6edf37d99b | jrahman1988/PythonSandbox | /myLambdaFunction.py | 1,212 | 4.125 | 4 | '''
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Syntax
lambda arguments : expression
'''
#define the lambda function
sentence = "I bought a bike, from a bike store, she bought a bike from amazon, they bought a bike from bike stores"
myLambdaFunction = lambda argument: argument.count("bike")
#here we are calling the lambda function: passing the 'sentence' as parameter and lamda function is taking it as an 'argument'
print("Total number of 'bike' word appeared = ", myLambdaFunction(sentence))
# filePath = "~/Desktop/Learning/Sandbox/PythonSandbox/Data/README.md"
# readFile=open('~/Desktop/Learning/Sandbox/PythonSandbox/Data/README.md', 'r')
with open('/home/jamil/Desktop/Learning/Sandbox/PythonSandbox/Data/README.md') as f:
readFile = f.readlines()
print (readFile)
print(readFile.count("Spark"))
sparkAppeared = lambda s: s.count("Spark")
apacheAppeared = lambda s: s.count("Apache")
hadoopAppeared = lambda s: s.count("Hadoop")
print("Spark word appeared = ", sparkAppeared(readFile))
print("Apache word appeared = ", apacheAppeared(readFile))
print("Hadoop word appeared = ", hadoopAppeared(readFile)) | true |
76e7dc6bfa340596459f1a535e4e2e191ea483bc | jrahman1988/PythonSandbox | /myOOPclass3.py | 2,017 | 4.46875 | 4 | '''
There is way of organizing a software program which is to combine data and functionality and wrap it inside something called an object.
This is called the object oriented programming paradigm.
In this program we'll explore Class, behaviour and attributes of a class
'''
#Declaring a class named Mail and its methods (behaviours). All methods of a class must have a default parameter 'self'
class Mail():
#Class variable to count 'how many' types of Mail instances created
numberOfObjectsCreated = 0
#Init method to create an instance (object) by passing an object name
def __init__(self, name):
"""Initilializes the data"""
self.name = name
print("Initializing an {}".format(self.name))
Mail.numberOfObjectsCreated +=1
def destinationOfMail(self, type: str):
self.type = type
def costOfMail(self, cost: int):
self.cost = cost
def sizeOfmail(self, size: int):
self.size = size
def getDescription(self):
print("The type of the mail is ", self.type)
print("The cost of the mail is ", self.cost)
print("The size of the mail is ", self.size)
@classmethod
def countOfMail(count):
"""Prints number of Mail objects"""
print("Created objects of Mail class are = {}".format(count.numberOfObjectsCreated))
#Create an object of the class Mail named domesticMail
dMail = Mail("domesticMail")
dMail.destinationOfMail("Domestic")
dMail.costOfMail(10)
dMail.sizeOfmail("Large")
dMail.getDescription()
#Create an object of the class Mail named internationalMail
iMail = Mail("internationalMail")
iMail.destinationOfMail("International")
iMail.costOfMail(99)
iMail.sizeOfmail("Small")
iMail.getDescription()
#How many Mail objects were created (here we are using class variable 'numberOfObjectsCreated'
print("Total Mail objects created = {} ".format(Mail.numberOfObjectsCreated))
#How many Mail objects were created (here we are using class method 'countOfMail()'
Mail.countOfMail() | true |
cf3158ef73377ac7fe644d4637c21ae1501d804b | jrahman1988/PythonSandbox | /myStringFormatPrint.py | 551 | 4.25 | 4 | #Ways to format and print
age: int = 20
name: str = "Shelley"
#Style 1 where format uses indexed parameters
print('{0} was graduated from Wayne State University in Michigan USA when she was {1}'.format(name,age))
#Style 2 where 'f' is used as f-string
print(f'{name} was graduated from Wayne State University in Michigan USA when she was {age}')
#Style 3 where format's parameters can mbe changed as local variable
print('{someOne} was graduated from Wayne State University in Michigan USA when she was {someAge}'.format(someOne=name,someAge=age)) | true |
34653fdfffaacb579ad87ee2d590c6ae37c5bb71 | mimipeshy/pramp-solutions | /code/drone_flight_planner.py | 1,903 | 4.34375 | 4 | """
Drone Flight Planner
You’re an engineer at a disruptive drone delivery startup and your CTO asks you to come up with an efficient algorithm that calculates
the minimum amount of energy required for the company’s drone to complete its flight.
You know that the drone burns 1 kWh (kilowatt-hour is an energy unit) for every mile it ascends, and it gains 1 kWh for every mile it descends.
Flying sideways neither burns nor adds any energy.
Given an array route of 3D points, implement a function calcDroneMinEnergy that computes and returns the minimal amount of energy the drone would need
to complete its route. Assume that the drone starts its flight at the first point in route. That is, no energy was expended to place the drone at the starting point.
For simplicity, every 3D point will be represented as an integer array whose length is 3.
Also, the values at indexes 0, 1, and 2 represent the x, y and z coordinates in a 3D point, respectively.
input: route = [ [0, 2, 10],
[3, 5, 0],
[9, 20, 6],
[10, 12, 15],
[10, 10, 8] ]
output: 5 # less than 5 kWh and the drone would crash before the finish
# line. More than `5` kWh and it’d end up with excess e
"""
# O(n) time
# O(1) space
def calc_drone_min_energy(route):
energy_balance = 0
energy_deficit = 0
prev_altitude = route[0][2]
for i in range(1, len(route)):
curr_altitude = route[i][2]
energy_balance += prev_altitude - curr_altitude
if energy_balance < 0:
energy_deficit += abs(energy_balance)
energy_balance = 0
prev_altitude = curr_altitude
return energy_deficit
def calc_drone_min_energy(route):
max_altitude = route[0][2]
for i in range(1, len(route)):
if route[i][2] > max_altitude:
max_altitude = route[i][2]
return max_altitude - route[0][2]
| true |
dd9c666ab17a5afeb3e6c0fa1bdd1b27bb7f78ce | CSC1-1101-TTh9-S21/lab-week3 | /perimeter.py | 594 | 4.3125 | 4 | # Starter code for week 3 lab, parts 1 and 2
# perimeter.py
# Prof. Prud'hommeaux
# Get some input from the user.
a=int(input("Enter the length of one side of the rectangle: "))
b=int(input("Enter the length of the other side of the rectangle: "))
# Print out the perimeter of the rectangle
c = a + a + b + b
print("The perimeter of your rectangle is: ", c)
# Part 1: Rewrite this code so that it gets the sides from
# command line arguments (i.e., Run... Customized)
# Part 2: Rewrite this code so that there are two functions:
# a function that calculates the perimeter
# a main function
| true |
abdff8d3bf6c1e1cc39a24519587e5760294bdc6 | arkiz/py | /lab1-4.py | 413 | 4.125 | 4 | studentName = raw_input('Enter student name.')
creditsDegree = input('Enter credits required for degree.')
creditsTaken = input('Enter credits taken so far.')
degreeName = raw_input('Enter degree name.')
creditsLeft = (creditsDegree - creditsTaken)
print 'The student\'s name is', studentName, ' and the degree name is ', degreeName, ' and There are ', creditsLeft, ' credits left until graduation.'
| true |
517f231a66c9d977bc5a34eaa92b6ad986a8e340 | rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python | /Module-3/3-1-2-12-Python-loops-else-The-while-loop-and-the-else-branch.py | 356 | 4.15625 | 4 | #!/usr/bin/python3
"""
Both loops, while and for, have one interesting (and rarely used) feature.
As you may have suspected, loops may have the else branch too, like ifs.
The loop's else branch is always executed once,
regardless of whether the loop has entered its body or not.
"""
i = 1
while i < 5:
print(i)
i += 1
else:
print("else:", i)
| true |
6920b44453655be0855b3977c12f2ed33bdb0bc3 | rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python | /Module-4/4-1-3-10-LAB-Converting-fuel-consumption.py | 1,432 | 4.4375 | 4 | #!/usr/bin/python3
"""
A car's fuel consumption may be expressed in many different ways. For example,
in Europe, it is shown as the amount of fuel consumed per 100 kilometers.
In the USA, it is shown as the number of miles traveled by a car using one
gallon of fuel.
Your task is to write a pair of functions converting l/100km into mpg, and
vice versa.
The functions:
are named l100kmtompg and mpgtol100km respectively;
take one argument (the value corresponding to their names)
Complete the code in the editor.
Run your code and check whether your output is the same as ours.
Here is some information to help you:
1 American mile = 1609.344 metres;
1 American gallon = 3.785411784 litres.
Test Data
Expected output:
60.31143162393162
31.36194444444444
23.52145833333333
3.9007393587617467
7.490910297239916
10.009131205673757
"""
def l100kmtompg(liters):
"""
100000 m * 3.785411784 l [ mi ]
________________________ ________
1609.344 m * liters [ g ]
"""
return ((100000*3.785411784)/(1609.344*liters))
def mpgtol100km(miles):
"""
100000 m * 3.785411784 l [ l ]
________________________ _________
1609.344 m * miles [ 100Km ]
"""
return ((100000*3.785411784)/(1609.344*miles))
print(l100kmtompg(3.9))
print(l100kmtompg(7.5))
print(l100kmtompg(10.))
print(mpgtol100km(60.3))
print(mpgtol100km(31.4))
print(mpgtol100km(23.5))
| true |
c9bedff4032b89fbd4054b4f03093af06a3d01d0 | rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python | /Module-2/2-1-4-10-LAB-Operators-and-expressions.py | 567 | 4.5625 | 5 | #!/usr/bin/python3
"""
Take a look at the code in the editor: it reads a float value,
puts it into a variable named x, and prints the value of a variable named y.
Your task is to complete the code in order to evaluate the following
expression:
3x3 - 2x2 + 3x - 1
The result should be assigned to y.
"""
x = 0
x = float(x)
y = 3 * x ** 3 - 2 * x ** 2 + 3 * x - 1
print('x =', x, ' y =', y)
x = 1
x = float(x)
y = 3 * x ** 3 - 2 * x ** 2 + 3 * x - 1
print('x =', x, ' y =', y)
x = -1
x = float(x)
y = 3 * x ** 3 - 2 * x ** 2 + 3 * x - 1
print('x =', x, ' y =', y)
| true |
fd86bac9750e54714b1fe65d050d336dba9399ca | rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python | /Module-4/4-1-3-9-LAB-Prime-numbers-how-to-find-them.py | 1,302 | 4.28125 | 4 | #!/usr/bin/python3
"""
A natural number is prime if it is greater than 1 and has no divisors other
than 1 and itself.
Complicated? Not at all. For example, 8 isn't a prime number, as you can
divide it by 2 and 4 (we can't use divisors equal to 1 and 8, as the
definition prohibits this).
On the other hand, 7 is a prime number, as we can't find any legal divisors
for it.
Your task is to write a function checking whether a number is prime or not.
The function:
is called isPrime;
takes one argument (the value to check)
returns True if the argument is a prime number, and False otherwise.
Hint: try to divide the argument by all subsequent values (starting from 2)
and check the remainder - if it's zero, your number cannot be a prime; think
carefully about when you should stop the process.
If you need to know the square root of any value, you can utilize the **
operator. Remember: the square root of x is the same as x0.5
Complete the code in the editor.
Run your code and check whether your output is the same as ours.
Test Data
Expected output:
2 3 5 7 11 13 17 19
"""
def isPrime(num):
for n in range(2, num):
if ((num % n) == 0):
return False
return True
for i in range(1, 20):
if isPrime(i + 1):
print(i + 1, end=" ")
print()
| true |
3e7b84ff790a508534c03cdc878f6abdf2e32a53 | rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python | /Module-3/3-1-6-1-Operations-on-lists-The-inner-life-of-lists.py | 1,345 | 4.375 | 4 | #!/usr/bin/python3
"""
The inner life of lists
Now we want to show you one important, and very surprising, feature of lists,
which strongly distinguishes them from ordinary variables.
We want you to memorize it - it may affect your future programs, and cause
severe problems if forgotten or overlooked.
Take a look at the snippet in the editor.
The program:
- creates a one-element list named list1;
- assigns it to a new list named list2;
- changes the only element of list1;
- prints out list2.
The surprising part is the fact that the program will output: [2], not [1],
which seems to be the obvious solution.
Lists (and many other complex Python entities) are stored in different ways
than ordinary (scalar) variables.
You could say that:
- the name of an ordinary variable is the name of its content;
- the name of a list is the name of a memory location where the list is
stored.
Read these two lines once more - the difference is essential for
understanding what we are going to talk about next.
The assignment: list2 = list1 copies the name of the array, not its
contents. In effect, the two names (list1 and list2) identify the same
location in the computer memory. Modifying one of them affects the other,
and vice versa.
How do you cope with that?
"""
list1 = [1]
list2 = list()
list2 = list1
list1[0] = 2
print(list2)
| true |
946ec887e106dde979717832e603732ef85a750c | rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python | /Module-4/4-1-2-2-How-functions-communicate-with-their-environment-Parametrized-functions.py | 1,358 | 4.375 | 4 | #!/usr/bin/python3
"""
It's legal, and possible, to have a variable named the same as a function's
parameter.
The snippet illustrates the phenomenon:
def message(number):
print("Enter a number:", number)
number = 1234
message(1)
print(number)
A situation like this activates a mechanism called shadowing:
parameter x shadows any variable of the same name, but...
... only inside the function defining the parameter.
The parameter named number is a completely different entity from the variable
named number.
This means that the snippet above will produce the following output:
Enter a number: 1
1234
"""
def message(number):
print("Enter a number:", number)
message(4)
number = 1234
message(1)
print(number)
"""
A function can have as many parameters as you want, but the more parameters
you have, the harder it is to memorize their roles and purposes.
Functions as a black box concept
Let's modify the function - it has two parameters now:
def message(what, number):
print("Enter", what, "number", number)
This also means that invoking the function will require two arguments.
The first new parameter is intended to carry the name of the desired value.
Here it is:
"""
def message1(what, number):
print("Enter", what, "number", number)
message1("telephone", 11)
message1("price", 6)
message1("number", "number")
| true |
b6732e8d49b943a0391fe3d6521bdf29d2f840ee | rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python | /Module-3/3-1-1-11-LAB-Comparison-operators-and-conditional-execution.py | 1,014 | 4.46875 | 4 | #!/usr/bin/python3
"""
Spathiphyllum, more commonly known as a peace lily or white sail plant,
is one of the most popular indoor houseplants that filters out harmful
toxins from the air. Some of the toxins that it neutralizes include benzene,
formaldehyde, and ammonia.
Imagine that your computer program loves these plants.
Whenever it receives an input in the form of the word Spathiphyllum,
it involuntarily shouts to the console the following string:
"Spathiphyllum is the best plant ever!"
Test Data
Sample input: spathiphyllum
Expected output: No, I want a big Spathiphyllum!
Sample input: pelargonium
Expected output: Spathiphyllum! Not pelargonium!
Sample input: Spathiphyllum
Expected output: Yes - Spathiphyllum is the best plant ever!
"""
word = input("Please input your string: ")
if word == "Spathiphyllum":
print("Yes - Spathiphyllum is the best plant ever!")
elif word == "spathiphyllum":
print("No, I want a big Spathiphyllum!")
else:
print("Spathiphyllum! Not " + word + "!")
| true |
ad07c957de435974775396e4cc0b8a793ffe4141 | michellecby/learning_python | /week7/checklist.py | 788 | 4.1875 | 4 | #!/usr/bin/env python3
# Write a program that compares two files of names to find:
# Names unique to file 1
# Names unique to file 2
# Names shared in both files
import sys
import biotools
file1 = sys.argv[1]
file2 = sys.argv[2]
def mkdictionary(filename):
names = {}
with open(filename) as fp:
for name in fp.readlines():
name = name.rstrip()
names[name] = True
return names
d1 = mkdictionary(file1)
d2 = mkdictionary(file2)
u1 = []
u2 = []
both = []
for word in d1:
if word in d2:
both.append(word)
else:
u1.append(word)
for word in d2:
if word not in d1:
u2.append(word)
print("Names unique to file 1:")
print(u1)
print("Names unique to file 2:")
print(u2)
print("Names shared in both files:")
print(both)
"""
python3 checklist.py file1.txt file2.txt
"""
| true |
2f8d761707c15cef64f9e8b49aae03c733959d00 | leetuckert10/CrashCourse | /chapter_9/exercise_9-6.py | 1,668 | 4.375 | 4 | # Exercise 9-6: Ice Cream Stand
# Write a class that inherits the Restaurant class. Add and an attribute
# called flavors that stores a list of ice cream flavors. Add a method that
# displays the flavors. Call the class IceCreamStand.
from restaurant import Restaurant
class IceCreamStand(Restaurant):
def __init__(self, name, cuisine, flavors=None):
super().__init__(name, cuisine)
self.flavors = flavors
def add_flavor(self, flavor):
"""This method adds an ice cream flavor to the the flavors list."""
self.flavors.append(flavor)
def remove_flavor(self, flavor):
"""This mehtod removes a flavor from the list of ice cream flavors."""
self.flavors.remove(flavor)
def show_flavors(self):
"""This method displays all the flavors available at the ice cream
stand."""
print("Available ice cream flavors are: ", end="")
for flavor in self.flavors:
if flavor == self.flavors[-1]:
print(f"{flavor.title()}.", end="")
else:
print(f"{flavor.title()}, ", end="")
print("")
flavors = ["chocolate","vanilla","strawberry"]
ics = IceCreamStand("Terry's Ice Cream Shop", "Ice Cream", flavors)
ics.show_flavors()
print("\nAdding new flavors!")
ics.add_flavor("butter pecan")
ics.add_flavor("cookie dough")
ics.add_flavor("carmal")
ics.show_flavors()
print("\nOops! Out of Butter Pecan because Terry ate it all!\n")
ics.remove_flavor("butter pecan")
ics.show_flavors()
ics.set_number_served(238_449)
# Showing that we have this attribute from Restaurant.
print(f"We have served {ics.number_served} customers!")
| true |
df70e46cceaa083c3a0545af8eb83463295b0b40 | leetuckert10/CrashCourse | /chapter_11/test_cities.py | 1,339 | 4.3125 | 4 | # Exercise 11-1: City, Country
#
# Create a file called test_city.py that tests the function you just wrote.
# Write a method called test_city_country() in the class you create for testing
# the function. Make sure it passes the test.
#
# Remember to import unittest and the function you are testing. Remember that
# the test class should inherit unittest.TestCase. Remember that the test
# methods in the class need to begin with the word 'test' to be automatically
# executed.
import unittest
from city_functions import get_formatted_city_country
class CityCountryNameTestCase(unittest.TestCase):
"""Tests get_formatted_city_country()."""
def test_city_country(self):
"""Do names like santiago chile work?"""
formatted_city_country = get_formatted_city_country('santiago', 'chile')
self.assertEqual(formatted_city_country, "Santiago, Chile")
def test_city_country_population(self):
"""Does a city name, a country name, and a population work?"""
formatted_city_country = get_formatted_city_country('santiago',
'chile', 50_000_000)
self.assertEqual(formatted_city_country, "Santiago, Chile - "
"Population 50000000")
if __name__ == '__main__':
unittest.main()
| true |
f4f669c12f07d0320e5d9a01fec7542e249d4962 | leetuckert10/CrashCourse | /chapter_4/exercise_4-10.py | 539 | 4.5625 | 5 | # Slices
# Use list splicing to print various parts of a list.
cubes = [value**3 for value in range(1, 11)] # list comprehension
print("The entire list:")
for value in cubes:
# check out this syntax for suppressing a new line.
print(value, " ", end="")
print('\n')
# display first 3 items
print(f"The first three items are: {cubes[:3]}")
# display items from the middle of the list
print(f"Three items beginning at index 3 are: {cubes[3:6]}")
# display last three items in list
print(f"The last three items are: {cubes[-3:]}")
print() | true |
1897ec6770bca8f6e0dc72abbcdcd70644e6f182 | leetuckert10/CrashCourse | /chapter_8/exercise_8-14.py | 764 | 4.3125 | 4 | # Exercise 8-13: Cars
# Define a function that creates a list of key-value pairs for all the
# arbitrary arguments. The syntax **user_info tell Python to create a
# dictionary out of the arbitrary parameters.
def make_car(manufacturer, model, **car):
""" Make a car using a couple positional parameters and and arbitrary
number of arguments as car. """
car['manufacturer'] = manufacturer
car['model'] = model
return car
def print_car(car):
""" Print out key/value pairs in the user profile dictionary."""
for key, value in car.items():
print(f"{key}: {value}")
car = make_car('Chevrolett',
'Denali',
sun_roof=True,
heated_sterring_wheel=True,
color='Black',
towing_package=True,
)
print_car(car) | true |
997df0520551de4bfb67665932840b09fa1a6d5a | leetuckert10/CrashCourse | /chapter_6/exercise_6-9.py | 1,229 | 4.21875 | 4 | # Favorite Places:
# Make a dictionary of favorite places with the persons name as the kep.
# Create a list as one of the items in the dictionary that contains one or
# more favorite places.
favorite_places = {
'terry': ['wild cat rock', 'mount mitchell', 'grandfather mountain'],
'carlee': ['blue ridge parkway', 'tweetsie', 'boone', 'carter falls',
'cave', 'burger king'],
'linda': ['thrift store', 'home', 'little switzerland', 'sparta'],
'rebekah': [], # let's have one blank and know how to check it
}
# If you leave off items, the default behavior of the for loop is to
# return the key and the value.
# for name, place in favorite_places.items():
for name, places in favorite_places.items():
if places:
print(f"{name.title()} has {len(places)} favorite places:")
print("\t", end="")
for place in places:
# doing trailing comma control...
if place == places[-1]: # [-1] returns last item in list
print(f"{place.title()}", end="")
else:
print(f"{place.title()}, ", end="")
else:
print(f"{name.title()} doesn't have any favorite places defined yet.")
print("\n") | true |
ab6b62451de82d2c52b1b994cfabab7893c4f64e | leetuckert10/CrashCourse | /chapter_8/exercise_8-3.py | 541 | 4.125 | 4 | # Exercise 8-3: T-Shirt
# Write a function called make_shirt() that accepts a size and a string for
# the text to be printed on the shirt. Call the function twice: once with
# positional arguments and once with keyword arguments.
def make_shirt(text, size):
print(f"Making a {size.title()} T-Shirt with the text '{text}'...")
make_shirt('Love You', 'large') # positional arguments
# use keyword arguments: note the order does not matter
make_shirt(text="Love YOU", size='Medium')
make_shirt(size='extra large', text='Love YOU') | true |
928d97a0023a0a64773fb1df4c1e59bc20f01123 | algorithms-21-devs/Interview_problems | /weekly_interview_questions/IQ_4/Q4_emmanuelcodev/Q4Medium_N.py | 1,840 | 4.25 | 4 | import node as n
'''
Time complexity: O(n)
Algorithm iterates through link list once only. It adds memory location as a key to a dictionary. As it iterates it checks if the
current node memory matches any in the dictionary in O(1) time. If it does a cycle must be present.
'''
def cycle(head_node):
#must be a linked list
if head_node is None:
raise Exception('Cannot process an empty linked list')
current_node = head_node
nodes_dic = {}#stores memory locations as keys and data of node as value
#iterate through the list once
while current_node is not None:
if current_node not in nodes_dic:#put in dictionary if node is not in dic
nodes_dic[current_node] = current_node.data
else:#we found a node twice meaning there is a cycle
return True
current_node = current_node.next#make sure we iterate through the list
return False
#Testing
node_a = n.Node('A')
node_b = n.Node('B')
node_c = n.Node('C')
node_d = n.Node('D')
l1 = node_a
l1.next = node_b
l1.next.next = node_c
l1.next.next.next = node_d
l1.next.next.next.next = node_b #cycle
print(cycle(l1))
node_a = n.Node('A')
node_b = n.Node('B')
node_c = n.Node('C')
node_d = n.Node('D')
#'A'->'B'-->'C'->'D'->'B' (different node with data b)
l2 = node_a
l2.next = node_b
l2.next.next = node_c
l2.next.next.next = node_d
l2.next.next.next.next = n.Node('B') #cycle
print(cycle(l2))
node_a = n.Node('A')
node_b = n.Node('B')
node_c = n.Node('C')
node_d = n.Node('D')
#your_function('A') returns False
l3 = node_a
print(cycle(l3))
node_a = n.Node('A')
node_b = n.Node('B')
node_c = n.Node('C')
node_d = n.Node('D')
#your_function('A'->'B'-->'C') returns False
l4 = node_a
l4.next = node_b
l4.next.next = node_c
print(cycle(l4))
#your_function(none) returns Exception
l5 = None
print(cycle(l5))
| true |
4374c169c241a96ef6fc26f74a3c514f4cc216ed | algorithms-21-devs/Interview_problems | /weekly_interview_questions/IQ_2/Q2_Emmanuelcodev/Q2Medium_Nsquared.py | 2,634 | 4.1875 | 4 |
def unique_pairs(int_list, target_sum):
#check for None
'''
Time complexity: O(n^2).
1) This is because I have a nested for loop. I search through int_list,
and for each element in int_list I search through int_list again.
N for the outer and n^2 with the inner.
2) The second part of my algorithm which iteraters through the pairs and checks a dictionary is done in O(n) time.
for x in pairs:
if x in upairs
I am checking n items (b/c of pairs), at O(1) time due to upairs being
a dictionary. Overall, highest cost is O(n^2)
Space complexity: O(n)
1) I create another array and dictionary in the worst case n size.
'''
if None in (int_list, target_sum):
raise Exception("int_list and target_sum cannot be of NoneType")
if len(int_list) < 2:
return []
pairs = []
for x in int_list:
duplicate = False #only count num if it occurs more than once, since second loop will count current num as as second instance due it starting from begining and first loop counitng it as the first INSTANCE
for y in int_list:
if x == y:#counts current num in second loop, any more occurances are duplicates and therefore valid
if duplicate == False:
duplicate = True
else:
if x + y == target_sum:
pairs.append((x,y))
else:
if x + y == target_sum:#if current num (x) and y together == target_sum, then append group
pairs.append((x,y))
#have duplicate pairs need to clean data
upairs = {}
#print(pairs)
for x in pairs:
if x[0] < x[1]:# sorts tuple of size 2 , so n operationgs for entire loop
if x in upairs:
pass
else:
upairs[str(x)]=1
else:
if (x[1],x[0]) in upairs:
pass
else:
upairs[str((x[1],x[0]))]=1
pairs = []
for x in upairs.keys():
pairs.append(x)
return pairs
#duplicate pairs
print(unique_pairs([1, 3, 2, 2,3,5,5], 4)) # Returns [(3,1),(2,2)]
print(unique_pairs([3, 4, 19, 3, 4, 8, 5, 5], 6))#returns 1,1
print(unique_pairs([-1, 6, -3, 5, 3, 1], 2)) # Returns [(-1,3),(5,-3)]
print(unique_pairs([3, 4, 19, 3, 3, 3, 3], 6)) # Returns [(3,3)]
print(unique_pairs([-1, 6, -3, 5, 3, 1], 5000)) # Returns []
print(unique_pairs([], 10)) # Returns Exception
print(unique_pairs([4],54)) #returns []
print(unique_pairs(None,54))# raises Exception
| true |
f587e8614825a2d013715057bf7cffc0ed0cf287 | Earazahc/exam2 | /derekeaton_exam2_p2.py | 1,032 | 4.25 | 4 | #!/usr/bin/env python3
"""
Python Exam Problem 5
A program that reads in two files and prints out
all words that are common to both in sorted order
"""
from __future__ import print_function
def fileset(filename):
"""
Takes the name of a file and opens it.
Read all words and add them to a set.
Args:
filename: The name of the file
Return:
a set with all unique words in the file
"""
with open(filename, mode='rt', encoding='utf-8') as reading:
hold = set()
for line in reading:
temp = line.split()
for item in temp:
hold.add(item)
return hold
def main():
"""
Test your module
"""
print("Enter the name of a file: ", end='')
file1 = input()
print("Enter the name of a file: ", end='')
file2 = input()
words1 = fileset(file1)
words2 = fileset(file2)
shared = words1.intersection(words2)
for word in shared:
print(word)
if __name__ == "__main__":
main()
exit(0)
| true |
b2c24fe1f3d4f3474b70461b608a2c14e9d44e9b | viralsir/python_saket | /if_demo.py | 1,045 | 4.15625 | 4 | '''
control structure if
syntax :
if condition :
statement
else :
statement
relational operator
operator symbol
greater than >
less than <
equal to ==
not equal to !=
greater than
or equal to >=
less than
or equal to <=
logical operator
operator symbol
and and
or or
not not
'''
no1=int(input("Enter No1:"))
no2=int(input("Enter No2:"))
no3=int(input("Enter No3:"))
if no1>0 and no2>0 and no3>0 :
if no1>no2 and no1>no3:
print(no1," is a maxium no")
elif no2>no1 and no2>no3 :
print(no2," is a maximum no")
else :
print(no3," is a maximum no")
else :
if no1<0:
print(no1," is a invalid")
elif no2<0:
print(no2," is a invalid")
else :
print(no3," is a invalid")
#print("invalid input")
| true |
0bdb3507ea776a6b421a6e8dfda6c3e47f2c38bd | viralsir/python_saket | /def_demo3.py | 354 | 4.1875 | 4 | def prime(no):
is_prime=True
for i in range(2,no):
if no % i == 0 :
is_prime=False
return is_prime
def factorial(no):
fact=1
for i in range(1,no+1):
fact=fact*i
return fact
# no=int(input("enter No:"))
#
# if prime(no):
# print(no," is a prime no")
# else :
# print(no," is not a prime no")
| true |
2a0ffb39c845e7827d3a841c9f0475f42e8a5838 | kalyan-dev/Python_Projects_01 | /demo/oop/except_demo2.py | 927 | 4.25 | 4 | # - Accept numbers from user until zero is given and display SUM of the numbers; handle Invalid Numbers;
# program should not crash, but should continue;
def is_integer(n):
try:
return float(n).is_integer()
except ValueError:
return False
def is_integer_num(n):
if isinstance(n, int):
return True
if isinstance(n, float):
return False
nums = []
while True:
try:
# n = int(input("Enter a number(0 to End) :"))
sn = input("Enter a number(0 to End) :")
if not is_integer_num(sn):
n = float(sn)
else:
n = int(sn)
if n == 0:
break
else:
nums.append(n)
except:
print("You have entered an invalid number. Please enter an Integer.")
continue
print(f"You have entered {nums}")
print(f"Sum of the numbers = {sum(nums)}")
| true |
9b6a117c5d2ae6e591bc31dfd1ba748b84079710 | tejaboggula/gocloud | /fact.py | 332 | 4.28125 | 4 | def fact(num):
if num == 1:
return num
else:
return num*fact(num-1)
num = int(input("enter the number to find the factorial:"))
if num<0:
print("factorial is not allowed for negative numbers")
elif num == 0:
print("factorial of the number 0 is 1")
else:
print("factorial of",num, "is:",fact(num)) | true |
0fa7e809c7f4a8c7b0815a855cbc482abf600a77 | dimpy-chhabra/Artificial-Intelligence | /Python_Basics/ques1.py | 254 | 4.34375 | 4 | #Write a program that takes three numbers as input from command line and outputs
#the largest among them.
#Question 02
import sys
s = 0
list = []
for arg in sys.argv[1:]:
list.append(int(arg))
#arg1 = sys.argv[1]
list.sort()
print list[len(list)-1]
| true |
e8e83ac29ce59ebb1051bbe6457e3d5bd8ade162 | snail15/AlgorithmPractice | /Udacity/BasicAlgorithm/binarySearch.py | 1,127 | 4.3125 | 4 | def binary_search(array, target):
'''Write a function that implements the binary search algorithm using iteration
args:
array: a sorted array of items of the same type
target: the element you're searching for
returns:
int: the index of the target, if found, in the source
-1: if the target is not found
'''
start = 0
end = len(array) - 1
while start <= end:
mid = (start + end) // 2
if array[mid] == target:
return mid
elif array[mid] > target:
end = mid - 1
else:
start = mid + 1
return -1
def binary_search_recursive_soln(array, target, start_index, end_index):
if start_index > end_index:
return -1
mid_index = (start_index + end_index)//2
mid_element = array[mid_index]
if mid_element == target:
return mid_index
elif target < mid_element:
return binary_search_recursive_soln(array, target, start_index, mid_index - 1)
else:
return binary_search_recursive_soln(array, target, mid_index + 1, end_index) | true |
460d75a61550f0ae818f06ad46a9c210fe0d254e | lyderX05/DS-Graph-Algorithms | /python/BubbleSort/bubble_sort_for.py | 911 | 4.34375 | 4 | # Bubble Sort For Loop
# @author: Shubham Heda
# Email: hedashubham5@gmail.com
def main():
print("**NOTE**: Elements should be less then 25 as alogrithm work best on that only")
print("Enter Bubble Sort elements sepreated by (',') Comma: ")
input_string = input()
array = [int(each) for each in input_string.split(",")]
array_len = len(array)
if array_len > 1:
for _ in range(array_len):
swapped = False
for col in range(array_len - 1):
if array[col] > array[col + 1]:
array[col], array[col + 1] = array[col + 1], array[col]
swapped = True
print("New Array: ", array)
if not swapped:
break
else:
print("Array Contains Only One Value: ", array)
print("===========================")
print("Sorted Array: ", array)
if __name__ == '__main__':
main()
| true |
8674d8f7e11eae360e63b470b7b2310f7170c5cc | zeusumit/JenkinsProject | /hello.py | 1,348 | 4.40625 | 4 | print('Hello')
print("Hello")
print()
print('This is an example of "Single and double"')
print("This is an example of 'Single and double'")
print("This is an example of \"Single and double\"")
seperator='***'*5
fruit="apple"
print(fruit)
print(fruit[0])
print(fruit[3])
fruit_len=len(fruit)
print(fruit_len)
print(len(fruit))
print(fruit.upper())
print('My'+''+'name'+''+'is'+''+'Sumit')
print('My name is Sumit')
first='sumit'
second="Kumar"
print(first+second)
print(first+''+second)
print(first+' '+second)
fullname=first+' '+second
print(fullname)
print(fullname.upper())
print(first[0].upper())
print(first[0].upper()+first[1].lower())
print('-'*10)
happiness='happy '*3
print(happiness)
age=37
print(first.upper()+"'"+'s'+' age is: '+str(age))
print(seperator+'Formatting Strings'+seperator)
print('My name is: {}'.format(first))
print('My name is: {}'.format(first.upper()))
print('{} is my name'.format(first))
print('My name is {0} {1}. {1} {0} is my name'.format('Sumit', 'Kumar'))
print('My name is {0} {1}. {1} {0} is my name'.format(first, second))
print('{0:8} | {1:8}'. format(first, second))
print('{0:8} | {1:0}'. format('Age', age))
print('{0:8} | {1:8}'. format('Height', '6 feet'))
print('{0:8} | {1:0} {2:1}'. format('Weight', 70,'kgs'))
print(seperator+'User input'+seperator)
| true |
33553f9506dc46c9c05101074116c5254af7d0e9 | EderVs/hacker-rank | /30_days_of_code/day_8.py | 311 | 4.125 | 4 | """ Day 8: Dictionaries and Maps! """
n = input()
phones_dict = {}
for i in range(n):
name = raw_input()
phone = raw_input()
phones_dict[name] = phone
for i in range(n):
name = raw_input()
phone = phones_dict.get(name, "Not found")
if phone != "Not found":
print name + "=" + phone
else:
print phone | true |
6784ec88c6088dfcd462a124bc657be9a4c51c3c | asmitaborude/21-Days-Programming-Challenge-ACES | /generator.py | 1,177 | 4.34375 | 4 | # A simple generator function
def my_gen():
n = 1
print('This is printed first')
# Generator function contains yield statements
yield n
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
# Using for loop
for item in my_gen():
print(item)
#Python generator using loops
def rev_str(my_str):
length = len(my_str)
for i in range(length - 1, -1, -1):
yield my_str[i]
# For loop to reverse the string
for char in rev_str("hello"):
print(char)
#python generator expression
# Initialize the list
my_list = [1, 3, 6, 10]
# square each term using list comprehension
list_ = [x**2 for x in my_list]
# same thing can be done using a generator expression
# generator expressions are surrounded by parenthesis ()
generator = (x**2 for x in my_list)
print(list_)
print(generator)
#pipeline generator
def fibonacci_numbers(nums):
x, y = 0, 1
for _ in range(nums):
x, y = y, x+y
yield x
def square(nums):
for num in nums:
yield num**2
print(sum(square(fibonacci_numbers(10)))) | true |
46a7b9c9a436f4620dac591ed193a09c9b164478 | asmitaborude/21-Days-Programming-Challenge-ACES | /python_set.py | 2,244 | 4.65625 | 5 | # Different types of sets in Python
# set of integers
my_set = {1, 2, 3}
print(my_set)
# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)
# set cannot have duplicates
# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
# we can make set from a list
# Output: {1, 2, 3}
my_set = set([1, 2, 3, 2])
print(my_set)
# Distinguish set and dictionary while creating empty set
# initialize a with {}
a = {}
# check data type of a
print(type(a))
# initialize a with set()
a = set()
# check data type of a
print(type(a))
# initialize my_set
my_set = {1, 3}
print(my_set)
#if you uncomment the line below you will get an error
# my_set[0]
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
# add multiple elements
# Output: {1, 2, 3, 4}
my_set.update([2, 3, 4])
print(my_set)
# add list and set
# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4, 5], {1, 6, 8})
print(my_set)
# Difference between discard() and remove()
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)
# pop an element
# Output: random element
print(my_set.pop())
# pop another element
my_set.pop()
print(my_set)
# clear my_set
# Output: set()
my_set.clear()
print(my_set)
print(my_set)
# Set union method
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)
# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use & operator
# Output: {4, 5}
print(A & B)
# Difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A
# Output: {1, 2, 3}
print(A - B)
# Symmetric difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
| true |
1a87238ebb8b333148d1c2b4b094370f21fd230b | asmitaborude/21-Days-Programming-Challenge-ACES | /listsort.py | 677 | 4.4375 | 4 | #python list sort ()
#example 1:Sort a given list
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort()
# print vowels
print('Sorted list:', vowels)
#Example 2: Sort the list in Descending order
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort(reverse=True)
# print vowels
print('Sorted list (in Descending):', vowels)
#Example 3: Sort the list using key
# take second element for sort
def takeSecond(elem):
return elem[1]
# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# sort list with key
random.sort(key=takeSecond)
# print list
print('Sorted list:', random)
| true |
6346a452b77b895e2e686c5846553687459798ca | asmitaborude/21-Days-Programming-Challenge-ACES | /dictionary.py | 2,840 | 4.375 | 4 | #Creating Python Dictionary
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
#Accessing Elements from Dictionary
# get vs [] for retrieving elements
my_dict = {'name': 'Jack', 'age': 26}
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# Trying to access keys which doesn't exist throws error
# Output None
print(my_dict.get('address'))
# KeyError
#print(my_dict['address'])
#Changing and Adding Dictionary elements
# Changing and adding Dictionary Elements
my_dict = {'name': 'Jack', 'age': 26}
# update value
my_dict['age'] = 27
#Output: {'age': 27, 'name': 'Jack'}
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
print(my_dict)
# Removing elements from a dictionary
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# remove a particular item, returns its value
# Output: 16
print(squares.pop(4))
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)
# remove an arbitrary item, return (key,value)
# Output: (5, 25)
print(squares.popitem())
# Output: {1: 1, 2: 4, 3: 9}
print(squares)
# remove all items
squares.clear()
# Output: {}
print(squares)
# delete the dictionary itself
del squares
# Throws Error
#print(squares)
#Some Python Dictionary Methods
# Dictionary Methods
marks = {}.fromkeys(['Math', 'English', 'Science'], 0)
# Output: {'English': 0, 'Math': 0, 'Science': 0}
print(marks)
for item in marks.items():
print(item)
# Output: ['English', 'Math', 'Science']
print(list(sorted(marks.keys())))
#Python Dictionary Comprehension
# Dictionary Comprehension
squares = {x: x*x for x in range(6)}
print(squares)
# Dictionary Comprehension with if conditional
odd_squares = {x: x*x for x in range(11) if x % 2 == 1}
print(odd_squares)
#Other Dictionary Operations
#Dictionary Membership Test
# Membership Test for Dictionary Keys
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: True
print(1 in squares)
# Output: True
print(2 not in squares)
# membership tests for key only not value
# Output: False
print(49 in squares)
## Iterating through a Dictionary
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])
# Dictionary Built-in Functions
squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: False
print(all(squares))
# Output: True
print(any(squares))
# Output: 6
print(len(squares))
# Output: [0, 1, 3, 5, 7, 9]
print(sorted(squares)) | true |
f1e73874c9d09a51aa7b9c4a5890fe3cb34f5622 | parth-sp02911/My-Projects | /Parth Patel J2 2019 problem.py | 1,161 | 4.125 | 4 | #Parth Patel
#797708
#ICS4UOA
#J2 problem 2019 - Time to Decompress
#Mr.Veera
#September 6 2019
num_of_lines = int(input("Enter the number of lines: ")) #asks the user how many lines they want and turns that into an integer
output_list = [] #creates a list which will hold the values of the message the user wants
for line in range(num_of_lines): #creates a for loop which will repeat as many times, as the user inputed in the "num_of_lines" variable
user_input = (input("Enter the message: ")).split() #in the loop I ask the user to enter the message they want and split it by the space (turning it into a list)
num_of_char = int(user_input[0]) #I create a variable which will hold the number of times the user wants their character repeated
char = user_input[1] #i create a variable which will hold the character the user wants to be repeated
output_list.append(char * num_of_char) #I make the program repeat the character as many times as the user wants and then append it to the final output list
for element in output_list:
print(element) #I print all the elements in the list
| true |
4783c951d8caaf9c5c43fb57694cfb8d60d466b7 | marcinosypka/learn-python-the-hard-way | /ex30.py | 1,691 | 4.125 | 4 | #this line assigns int value to people variable
people = 30
#this line assigns int value to cars variable
cars = 30
#this line assigns int value to trucks variable
trucks = 30
#this line starts compound statemet, if statemets executes suite below if satement after if is true
if cars > people:
#this line belongs to suite started by if above, prints a string to terminal
print("We should take the cars.")
#this line starts elif statement, if statement after elif is true suite below is executed, it has to be put after if compound statement
elif cars < people:
#this line belongs to suite started by elif, it prints string to terminal
print("We should not take the cars.")
#this line starts a compound statement, if if statement and all elif statements above are false then else suite is executed
else:
#this line belongs to else suite, it prints string to terminal
print("We can't decide.")
#this line starts if statement
if trucks > cars:
#this line prints string to terminal if if statement is true
print("That's too many trucks.")
#this line starts elif statement
elif trucks < cars:
#this line prints string to terminal if elif statement is true
print("Maybe we could take the trucks.")
#this line starts else statement
else:
#this line prints string to terminal if all elifs and if above is false
print("We still can't decide")
#this line starts if statement
if people > trucks or not people > cars * 2 :
#this line prints string to terminal if if statement above is true
print("Alright, let's just take the trucks.")
#this line starts else statement
else:
#this line prints string to terminal if all elifs and if statement above is false
print("Fine, let's stay home than.")
| true |
c5d852ead39ef70ee91f26778f4a7874e38466cf | bohdi2/euler | /208/directions.py | 792 | 4.125 | 4 | #!/usr/bin/env python3
import collections
import itertools
from math import factorial
import sys
def choose(n, k):
return factorial(n) // (factorial(k) * factorial(n-k))
def all_choices(n, step):
return sum([choose(n, k) for k in range(0, n+1, step)])
def main(args):
f = factorial
expected = {'1' : 2, '2' : 2, '3' : 2, '4' : 2, '5' : 2}
print("All permutations of 10: ", 9765625)
print("All permutations of pairs: ", 113400)
print("All 11s: ", 22680)
print("All 12s: ", 42840)
length = 10
count = 0
for p in itertools.product("12345", repeat=length):
p = "".join(p)
c = collections.Counter(p)
#print(c)
if c == expected:
print(p)
if __name__ == '__main__':
sys.exit(main(sys.argv))
| true |
656d28880463fdd9742a9e2c6c33c2c247f01fbf | andylws/SNU_Lecture_Computing-for-Data-Science | /HW3/P3.py | 590 | 4.15625 | 4 | """
#Practical programming Chapter 9 Exercise 3
**Instruction**
Write a function that uses for loop to add 1 to all the values from input list
and return the new list. The input list shouldn’t be modified.
Assume each element of input list is always number.
Complete P3 function
P3([5, 4, 7, 3, 2, 3, 2, 6, 4, 2, 1, 7, 1, 3])
>>> [6, 5, 8, 4, 3, 4, 3, 7, 5, 3, 2, 8, 2, 4]
P3([0,0,0])
>>> [1,1,1]
"""
def P3(L1: list) -> list:
##### Write your Code Here #####
result = []
for i in L1:
result.append(i + 1)
return result
##### End of your code #####
| true |
69e6a29d952a0a5faaceed45e30bf78c5120c070 | TommyWongww/killingCodes | /Daily Temperatures.py | 1,025 | 4.25 | 4 | # @Time : 2019/4/22 22:54
# @Author : shakespere
# @FileName: Daily Temperatures.py
'''
739. Daily Temperatures
Medium
Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].
'''
class Solution(object):
def dailyTemperatures(self, T):
"""
:type T: List[int]
:rtype: List[int]
"""
res = [0] * len(T)
stack = []
for i in range(len(T)):
while stack and (T[i] > T[stack[-1]]):
idx = stack.pop()
res[idx] = i-idx
stack.append(i)
return res | true |
1ae82daf01b528df650bd7e72a69107cdf686a82 | TommyWongww/killingCodes | /Invert Binary Tree.py | 1,251 | 4.125 | 4 | # @Time : 2019/4/25 23:51
# @Author : shakespere
# @FileName: Invert Binary Tree.py
'''
226. Invert Binary Tree
Easy
Invert a binary tree.
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root is not None:
nodes = []
nodes.append(root)
while nodes:
node = nodes.pop()
node.left,node.right = node.right,node.left
if node.left is not None:
nodes.append(node.left)
if node.right is not None:
nodes.append(node.right)
return root | true |
202bd0898352102599f6e4addccaec7a60b46a8f | amymhaddad/exercises_for_programmers_2019 | /flask_product_search/products.py | 1,454 | 4.15625 | 4 | import json
#convert json file into python object
def convert_json_data(file):
"""Read in the data from a json file and convert it to a Python object"""
with open (file, mode='r') as json_object:
data = json_object.read()
return json.loads(data)
#set json data that's now a python object to projects_json
products_json = convert_json_data('products.json')
#Use the 'products' key from the products_json dictionary to get a LIST of dictionaries
products = products_json['products']
def show_all_products(products):
"""Display all provects from json file"""
display_product = ''
#cycle through the list of dictionaries
for product in products:
#cycle through the dicionaries
for category, detail in product.items():
if category == "price":
detail = f"${product['price']:.2f}"
display_product += f"{category.title()}: {detail}" + "\n"
return display_product
def one_product(products, itemname):
"""Return a single product based on user input"""
inventory_details = ''
for product in products:
if product['name'] == itemname:
for category, detail in product.items():
if category == 'price':
detail = f"${product['price']:.2f}"
inventory_details += f"{category.title()}: {detail}" + "\n"
return inventory_details
print(one_product(products, 'Thing'))
| true |
ab06ae955363b0ac7fcdfd22f35e9ea6e698d5c3 | LakshayLakhani/my_learnings | /programs/binary_search/bs1.py | 484 | 4.125 | 4 | # given a sorted arrray with repititions, find left most index of an element.
arr = [2, 3, 3, 3, 3]
l = 0
h = len(arr)
search = 3
def binary_search(arr, l, h, search):
mid = l+h//2
if search == arr[mid] and (mid == 0 or arr[mid-1] != search):
return mid
elif search <= arr[mid]:
return binary_search(arr, l, mid, search)
# else search > arr[mid]:
else:
return binary_search(arr, mid, h, search)
print(binary_search(arr, l, h, search))
| true |
99f8aed5acd78c31b9885eba4b830807459383be | chenp0088/git | /number.py | 288 | 4.375 | 4 | #!/usr/bin/env python
# coding=utf-8
number = input("If you input a number ,I will tell you if the number is multiplier of ten! Please input the number: ")
number = int(number)
if number%10 == 0:
print("It`s the multiplier of ten!")
else:
print("It`s not the multiplier of ten!")
| true |
08e48ae76c18320e948ec941e0be4b598720feeb | nkarasovd/Python-projects | /Data Structures and Algorithms Specialization/Algorithms on Strings/week2/4_suffix_array/suffix_array.py | 632 | 4.1875 | 4 | # python3
import sys
def build_suffix_array(text):
"""
Build suffix array of the string text and
return a list result of the same length as the text
such that the value result[i] is the index (0-based)
in text where the i-th lexicographically smallest
suffix of text starts.
"""
suffixes = [(text[i:], i) for i in range(len(text))]
result_util = sorted(suffixes, key=lambda x: x[0])
result = [el[1] for el in result_util]
return result
if __name__ == '__main__':
text = sys.stdin.readline().strip()
print(" ".join(map(str, build_suffix_array(text))))
| true |
de7f2d2afcb130e6d5484bdbad0795fbf54bdf2f | Moloch540394/machine-learning-hw | /linear-regression/driver.py | 1,398 | 4.3125 | 4 | """Computes the linear regression on a homework provided data set."""
__author__="Jesse Lord"
__date__="January 8, 2015"
import numpy as np
import matplotlib.pyplot as plot
from computeCost import computeCost
from gradientDescent import gradientDescent
from featureNormalization import featureNormalization
import readData
nfeatures = 2
if __name__=="__main__":
if nfeatures == 1:
(x,y,nexamples) = readData.readSingleFeature()
elif nfeatures == 2:
(x,y,nexamples) = readData.readMultiFeature()
# transforming the X array into a matrix to simplify the
# matrix multiplication with the theta_zero feature
X = np.ones((nfeatures+1,nexamples))
X[1:,:]=x[:,:]
theta = np.zeros(nfeatures+1)
if nfeatures==2:
(X_norm,mu,sigma) = featureNormalization(X)
# computes the cost as a test, should return 32.07
print computeCost(X_norm,y,theta)
if nfeatures == 1:
iterations = 1500
elif nfeatures == 2:
iterations = 400
alpha = 0.01
# computes the linear regression coefficients using gradient descent
theta = gradientDescent(X_norm,y,theta,alpha,iterations)
print theta[0]+theta[1]*((1650-mu[0])/sigma[0])+theta[2]*((3-mu[1])/sigma[1])
if nfeatures==1:
plot.plot(x,y,'o',x,np.dot(theta,X))
plot.show()
#plot.plot(x[0,:],y,'o',x[0,:],np.dot(theta[:1],X[:1,:])
#plot.show()
| true |
1a3bd1022273e086eeeb742ebace201d1aceceae | tmoraru/python-tasks | /less9.py | 434 | 4.1875 | 4 |
#Print out the slice ['b', 'c', 'd'] of the letters list.
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(letters[1:4])
#Print out the slice ['a', 'b', 'c'] of the letters list
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(letters[0:3])
#Print out the slice ['e', 'f', 'g'] of the letters list.
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(letters[4:]) #or use the command print(letters[-3:])
| true |
d4076402594b83189895f19cdc4730f9bd5e9072 | liginv/LP3THW | /exercise11-20/ex15.py | 547 | 4.15625 | 4 | # Importing the function/module argv from sys library in python
from sys import argv
# Assigning the varable script & filename to argv function
script, filename = argv
# Saving the open function result to a variable txt.
# Open function is the file .txt file.
txt = open(filename)
# Printing the file name.
print(f"Here's your file {filename}:")
# Printing the content of the file.
print(txt.read())
# Closing the file.
txt.close()
# trying with inout alone.
file = input("Enter the file name: ")
txt1 = open(file)
print(txt1.read())
txt1.close() | true |
7106600daa9540e96be998446e8e199ffd56ec28 | rhino9686/DataStructures | /mergesort.py | 2,524 | 4.25 | 4 |
def mergesort(arr):
start = 0
end = len(arr) - 1
mergesort_inner(arr, start, end)
return arr
def mergesort_inner(arr, start, end):
## base case
if (start >= end):
return
middle = (start + end)//2
# all recursively on two halves
mergesort_inner(arr, middle + 1, end)
mergesort_inner(arr, start, middle)
## merge everything together
temp = [0 for item in arr]
temp_it = start
first_half_it = start
first_half_end = middle
second_half_it = middle + 1
second_half_end = end
## merge the two halves back into a temp array
while (first_half_it <= first_half_end and second_half_it <= second_half_end):
if arr[first_half_it] < arr[second_half_it]:
temp[temp_it] = arr[first_half_it]
first_half_it += 1
else:
temp[temp_it] = arr[second_half_it]
second_half_it += 1
temp_it += 1
##copy remainders/ only one of the two will fire at ay given time
while(first_half_it <= first_half_end):
temp[temp_it] = arr[first_half_it]
first_half_it += 1
temp_it += 1
while(second_half_it <= second_half_end):
temp[temp_it] = arr[second_half_it]
second_half_it += 1
temp_it += 1
## copy everything back into array
size = end - start + 1
arr[start:(start + size) ] = temp[start:(start + size)]
def quicksort(arr):
start = 0
end = len(arr) - 1
quicksort_inner(arr, start, end)
return arr
def quicksort_inner(arr, left, right):
## Base case
if left >= right:
return
#get a pivot point, in this case always use middle element
pivot_i = (left + right)//2
pivot = arr[pivot_i]
## partition array around pivot
index = partition(arr, left, right, pivot)
##recursively sort around index
quicksort_inner(arr, left, index-1)
quicksort_inner(arr, index, right)
def partition(arr, left, right, pivot):
while (left <= right):
while arr[left] < pivot:
left +=1
while arr[right] > pivot:
right -= 1
if left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return left
def main():
arr = [3,6,4,8,4,1,3,5,3]
arr2 = arr[:]
sorted_arr = mergesort(arr)
print(sorted_arr)
sorted_arr = quicksort(arr2)
print(sorted_arr)
if __name__ == "__main__":
main() | true |
8b54f8006c98b5e88b7dd655e8338bb4fe3ba02c | CyberSamurai/Test-Project-List | /count_words.py | 574 | 4.4375 | 4 | """
-=Mega Project List=-
5. Count Words in a String - Counts the number of individual words in a string.
For added complexity read these strings in from a text file and generate a
summary.
"""
import os.path
def count_words(string):
words = string.split()
return len(words)
def main(file):
filename = os.path.abspath(file)
with open(filename, 'r') as f:
count = [count_words(line) for line in f]
for i, v in enumerate(count):
print "Line %d has %d words in it." % (i+1, v)
if __name__ == '__main__':
main('footext.txt')
| true |
f5f862e7bc7179f1e9831fe65d20d4513106e764 | AhmedMohamedEid/Python_For_Everybody | /Data_Stracture/ex_10.02/ex_10.02.py | 1,079 | 4.125 | 4 | # 10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
# Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.
# Use the file name mbox-short.txt as the file name
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
hour = dict()
for line in handle:
line.rstrip()
if not line.startswith('From '): continue
words = line.split()
hour[words[5]] = hour.get(words[5] , 0 ) + 1
#print (hour)
hour2 = dict()
for key in hour.keys():
key.split(":")
hour2[key[0:2]] = hour2.get(key[0:2],0)+1
#print (hour2)
lst = []
for a,b in hour2.items():
lst.append((a,b))
lst.sort()
for a,b in lst:
print (a,b)
# ############# OutPut ==
# 04 3
# 06 1
# 07 1
# 09 2
# 10 3
# 11 6
# 14 1
# 15 2
# 16 4
# 17 2
# 18 1
# 19 1
| true |
14fd0afadadb85ccffb9e5cb447fa155874479ea | thienkyo/pycoding | /quick_tut/basic_oop.py | 657 | 4.46875 | 4 | class Animal(object):
"""
This is the animal class, an abstract one.
"""
def __init__(self, name):
self.name = name
def talk(self):
print(self.name)
a = Animal('What is sound of Animal?')
a.talk() # What is sound of Animal?
class Cat(Animal):
def talk(self):
print('I\'m a real one,', self.name)
c = Cat('Meow')
c.talk() # I'm a real one, Meow
# Compare 2 variables reference to a same object
a = [1, 2, 3]
b = a
print(b is a) # True
# Check if 2 variables hold same values
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) # False
print(a == b) # True
# None is an Object
print(None is None) # True
| true |
4f330c0fdbe5a6cc49b506011b88c610ef1abc60 | Jules-Boogie/controllingProgramFlow | /SearchAStringFunction/func.py | 1,087 | 4.21875 | 4 | """
A function to find all instances of a substring.
This function is not unlike a 'find-all' option that you might see in a text editor.
Author: Juliet George
Date: 8/5/2020
"""
import introcs
def findall(text,sub):
"""
Returns the tuple of all positions of substring sub in text.
If sub does not appears anywhere in text, this function returns the empty tuple ().
Examples:
findall('how now brown cow','ow') returns (1, 5, 10, 15)
findall('how now brown cow','cat') returns ()
findall('jeeepeeer','ee') returns (1,2,5,6)
Parameter text: The text to search
Precondition: text is a string
Parameter sub: The substring to search for
Precondition: sub is a nonempty string
"""
result = ()
start = 0
l = len(sub)
while start < len(text):
print(str(start) + "first")
if (sub in text) and (text.find(sub,start,start+l+1) != -1):
start = (text.find(sub,start,start+l+1))
result = result + (start,)
start = start + 1
print(str(start) + "end")
return result
| true |
b1185e9c9738f772857051ae03af54a4fb20487e | Jules-Boogie/controllingProgramFlow | /FirstVowel-2/func.py | 976 | 4.15625 | 4 | """
A function to search for the first vowel position
Author: Juliet George
Date: 7/30/2020
"""
import introcs
def first_vowel(s):
"""
Returns the position of the first vowel in s; it returns -1 if there are no vowels.
We define the vowels to be the letters 'a','e','i','o', and 'u'. The letter
'y' counts as a vowel only if it is not the first letter in the string.
Examples:
first_vowel('hat') returns 1
first_vowel('grrm') returns -1
first_vowel('sky') returns 2
first_vowel('year') returns 1
Parameter s: the string to search
Precondition: s is a nonempty string with only lowercase letters
"""
result = len(s)
vowels = ['a','e','i','o','u']
for x in vowels:
if x in s:
result = min(result,introcs.find_str(s,x))
if not x in s and "y" in s and introcs.rfind_str(s,"y") != 0:
result = introcs.rfind_str(s,"y")
return result if result != len(s) else -1
| true |
b7d990539a50faef24a02f8325342f385f518101 | github0282/PythonExercise | /Abhilash/Exercise2.py | 1,141 | 4.34375 | 4 | # replace all occurrences of ‘a’ with $ in a String
text1 = str(input("Enter a string: "))
print("The string is:", text1)
search = text1.find("a")
if(search == -1):
print("Character a not present in string")
else:
text1 = text1.replace("a","$")
print(text1)
# Take a string and replace every blank space with hyphen
text2 = str(input("Enter a string: "))
print("The string is:", text2)
text2 = text2.replace(" ","-")
print(text2)
# count the number of upper case and lower-case letters in a string
text3 = str(input("Enter a desired string: "))
print(text3)
UpperCase = 0
LowerCase = 0
for i in text3:
if( i >= "a" and i <= "z"):
LowerCase = LowerCase + 1
if( i >= "A" and i <= "Z"):
UpperCase = UpperCase + 1
print("No of UpperCase Characters: ", UpperCase)
print("No of LowerCase Characters: ", LowerCase)
# Check if a substring is present in a given string
text4 = str(input("Enter a desired string: "))
substring = str(input("Enter the substring: "))
if(text4.find(substring) == -1):
print("Substring is not present in the string")
else:
print("Substring is present in the string") | true |
89495c7cb55268122493bb126b1e3ea9a9c19fca | Jamilnineteen91/Sorting-Algorithms | /Merge_sort.py | 1,986 | 4.34375 | 4 | nums = [1,4,5,-12,576,12,83,-5,3,24,46,100,2,4,1]
def Merge_sort(nums):
if len(nums)<=1:
return nums
middle=int(len(nums)//2)#int is used to handle a floating point result.
left=Merge_sort(nums[:middle])#Divises indices into singular lists.
print(left)#Prints list division, lists with singular items are the final results.
right=Merge_sort(nums[middle:])#Divises indices into singular lists.
print(right)#Prints list division, lists with singular items are the final results.
return merge(left,right)
def merge(left, right):
sorted_list=[]
index_L=0 #index_L is used to incrementally ascend the left list.
index_R=0 #index_R is used to incrementally ascend the right list.
#Lists containing more than one item will enter the while loop where they'll be sorted.
while index_L < len(left) and index_R < len(right):
#Prints left & right groups that are have entered the while loop.
print(left[index_L:], right[index_R:])
if left[index_L]<=right[index_R]:
sorted_list.append(left[index_L])
index_L+=1
#Prints the current sorted_list state, the smallest item between the left group and right group has been inserted into sorted_list.
print(sorted_list)
else:
sorted_list.append(right[index_R])
index_R+=1
#Prints the current sorted_list state, the smallest item between the left group and right group has been inserted into sorted_list.
print(sorted_list)
#Lists containing one item will be added to the sorted_list.
#The append function is unable to append lists into new_list, hence why'+=' is used.
#Unable to use 'index_L' as a list index since the incrementation only takes place in the while loop,hence why 'index_L:' and 'index_R:' are used.
sorted_list+= left[index_L:]
sorted_list+= right[index_R:]
return sorted_list
print(Merge_sort(nums))
| true |
b4d3e19be67069f37487506a473ba9bce4def0be | jeffjbilicki/milestone-5-challenge | /milestone5/m5-bfs.py | 631 | 4.1875 | 4 | #!/usr/bin/env python
# Given this graph
graph = {'A': ['B', 'C', 'E'],
'B': ['A','D', 'E'],
'C': ['A', 'F', 'G'],
'D': ['B'],
'E': ['A', 'B','D'],
'F': ['C'],
'G': ['C']}
# Write a BFS search that will return the shortest path
def bfs_shortest_path(graph, start, goal):
explored = []
# keep track of all the paths to be checked
queue = [start]
# return path if start is goal
if start == goal:
return "Home sweet home!"
# Find the shortest path to the goal
return "Cannot reach goal"
ans = bfs_shortest_path(graph,'G', 'A')
print(ans)
| true |
580a215b24366f1e6dcf7d3d5253401667aa1aae | afialydia/Graphs | /projects/ancestor/ancestor.py | 2,127 | 4.125 | 4 | from util import Queue
class Graph:
"""Represent a graph as a dictionary of vertices mapping labels to edges."""
def __init__(self):
self.vertices = {}
def add_vertex(self, vertex_id):
"""
Add a vertex to the graph.
"""
if vertex_id not in self.vertices:
self.vertices[vertex_id] = set()
def add_edge(self, v1, v2):
"""
Add a directed edge to the graph.
"""
if v1 in self.vertices and v2 in self.vertices:
self.vertices[v1].add(v2)
else:
raise IndexError('Vertex does not exist in graph')
def get_neighbors(self, vertex_id):
"""
Get all neighbors (edges) of a vertex.
"""
if vertex_id in self.vertices:
return self.vertices[vertex_id]
else:
raise IndexError('ERROR: No such Vertex exist.')
def earliest_ancestor(ancestors, starting_node):
g = Graph()
for pair in ancestors: #< instead of for pair do for parent , child for more readability of code
g.add_vertex(pair[0])
g.add_vertex(pair[1])
g.add_edge(pair[1],pair[0])
q = Queue()
q.enqueue([starting_node]) # <- enqueue a path to starting node
visited = set() #<- creating a set to store visited
earliest_ancestor = -1 #<- no parents set to -1 initializing parents
while q.size() > 0:
path = q.dequeue()#<- gets the first path in the queue
v = path[-1]#<- gets last node in the path
if v not in visited:#<- check if visited and if not do the following
visited.add(v)
if((v < earliest_ancestor) or (len(path)>1)): #<-checks if path(v) is less than parent meaning if there was no path it would be the parent or length is longer than 1
earliest_ancestor = v #sets ancestor
for neighbor in g.get_neighbors(v): # copy's path and enqueues to all its neighbors
copy = path.copy()
copy.append(neighbor)
q.enqueue(copy)
return earliest_ancestor
| true |
4e21512a276938c54dc5a26524338584d3d31673 | snangunuri/python-examples | /pyramid.py | 1,078 | 4.25 | 4 | #!/usr/bin/python
############################################################################
#####This program takes a string and prints a pyramid by printing first character one time and second character 2 timesetc.. within the number of spaces of length of the given string###
############################################################################
seq="abcdefghijklmnopqrstuvwxyz"
spaces=""
letters_str=""
for letter in seq: #runs for length of seq
for i in range(1, len(seq) - seq.index(letter)): #uses a backwards for loop to add the number of spaces required and decrease the number of spaces by one each time
spaces += " " #adds spaces to the list concat_space
for j in range(0, seq.index(letter) + 1): #uses a forward for loop to add the right letter and number of letters to the triangle
letters_str += letter #adds letters to the list concat_str
print spaces + letters_str #joins the spaces and the letters together
spaces = "" #resets for a new line of the triangle
letters_str="" #resets for a new line of the triangle
| true |
76c008e9115f338deac839e9e2dafd583377da46 | pkongjeen001118/awesome-python | /generator/simple_manual_generator.py | 517 | 4.15625 | 4 | def my_gen():
n = 1
print('This is printed first')
yield n
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
if __name__ == '__main__':
a = my_gen()
# return generator obj.
print(a)
print(next(a))
# it will resume their execution and state around the last point of value
print(next(a))
# and go to next yield
print(next(a))
# and when no more yiled it will do a 'StopIteration'
print(next(a)) | true |
1f291ba8c19a6b242754f14b58e0d229385efe8b | JunyoungJang/Python | /Introduction/01_Introduction_python/10 Python functions/len.py | 663 | 4.1875 | 4 | import numpy as np
# If x is a string, len(x) counts characters in x including the space multiple times.
fruit = 'banana'
fruit_1 = 'I eat bananas'
fruit_2 = ' I eat bananas '
print len(fruit) # 6
print len(fruit_1) # 13
print len(fruit_2) # 23
# If x is a (column or row) vector, len(x) reports the length of vector x.
a = np.array([[1], [2], [3]])
b = np.array([1, 2, 3])
print len(a)
print len(b)
# If x is a matrix, len(x) reports the number of rows in matrix x.
c = np.array([[1, 2, 3], [1, 2, 3]])
d = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
e = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]])
print len(a)
print len(b)
print len(c)
| true |
571400657495936c96d31a67b1bc2afeeeaa1bf6 | ICESDHR/Bear-and-Pig | /Practice/Interview/24.反转链表.py | 1,016 | 4.34375 | 4 | # -*- coding:utf-8 -*-
class ListNode:
def __init__(self,value):
self.value = value
self.next = None
# 没思路
def ReverseList(root):
pNode,parent,pHead = root,None,None
while pNode:
child = pNode.next
if child is None:
pHead = pNode
pNode.next = parent
parent = pNode
pNode = child
return pHead
# 递归方法,需要返回两个值
def ReverseList2(root):
if root and root.next:
pHead,parent = ReverseList2(root.next)
parent.next = root
root.next = None
return pHead,root
return root,root
def Build():
root = ListNode(0)
node1 = ListNode(1)
root.next = node1
node2 = ListNode(2)
node1.next = node2
node3 = ListNode(3)
node2.next = node3
node4 = ListNode(4)
node3.next = node4
return root
def Print(root):
temp = root
while temp:
print(temp.value)
temp = temp.next
if __name__ == '__main__':
test = []
root = Build()
print('The List is:')
Print(root)
print('After reverse:')
Print(ReverseList(root))
# pHead,parent = ReverseList2(root)
# Print(pHead)
| true |
c247ba288604b38dafbb692aa49acf8b74ebd353 | izdomi/python | /exercise10.py | 482 | 4.25 | 4 | # Take two lists
# and write a program that returns a list that contains only the elements that are common between the lists
# Make sure your program works on two lists of different sizes. Write this using at least one list comprehension.
# Extra:
# Randomly generate two lists to test this
import random
list1 = random.sample(range(1,15), 10)
list2 = random.sample(range(1,30), 8)
common = [i for i in list1 if i in list2]
print(f'list1 = {list1} \nlist2 = {list2}')
print(common) | true |
698212d5376c53e07b4c5410dfd77aac16e97bd2 | izdomi/python | /exercise5.py | 703 | 4.21875 | 4 | # Take two lists,
# and write a program that returns a list that contains only the elements that are common between the lists.
# Make sure your program works on two lists of different sizes.
# Extras:
# Randomly generate two lists to test this
# Write this in one line of Python
lst1 = []
lst2 = []
num1 = int(input("length of list 1: "))
for i in range(num1):
element1 = int(input("Element for list 1: "))
lst1.append(element1)
num2 = int(input("length of list 2: "))
for j in range(num2):
element2 = int(input("Element for list 2: "))
lst2.append(element2)
if num1 < num2:
common = [i for i in lst1 if i in lst2]
else:
common = [j for j in lst2 if j in lst1]
print(common)
| true |
3a53ab12f8144942fbfcb56bbb56d407c32bdf3e | autumnalfog/computing-class | /Week 2/a21_input_int.py | 345 | 4.21875 | 4 | def input_int(a, b):
x = 0
while x != "":
x = input()
if x.isdigit():
if int(x) >= a and int(x) <= b:
return x
print("You should input a number between " + str(a) + " and " + str(b) + "!")
print("Try once more or input empty line to cancel input check.")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.