blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
98269365703f82e15da200949483316583454b29 | lshpaner/python-datascience-cornell | /Writing Custom Python Functions, Classes, and Workflows/Simple Ciphers With Lists and Dictionaries/exercise.py | 2,492 | 4.59375 | 5 | """
Simple Ciphers With Lists and Dictionaries
Author: Leon Shpaner
Date: August 14, 2020
"""
# Examine the starter code in the editor window.
# We first define a character string named letters which includes all the
# upper-case and lower-case letters in the Roman alphabet.
# We then create a dictionary (using a one-line dictionary comprehension) named
# cipher that maps each letter to another letter shifted three to its left in
# the list of all letters.
# Run the starter code in the interpreter and print the contents of the cipher.
# You should see that it maps each letter in letters to a different letter.
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
cipher = {letters[i]: letters[(i-3) % len(letters)] for i in range(len(letters))
}
# Let’s encrypt some messages now, using cipher. In the code editor, write the
# function named transform_message(message, cipher) that takes two inputs: a
# message that you want to encrypt, and a cipher to do the encryption. The body
# of this function is rather simple: it initializes an empty string named tmsg,
# loops over the characters in the input message, transforms them according to
# the cipher, and sticks that transformed character onto the end of tmsg. Once
# the entire message is transformed, the transformed message is returned.
def transform_message(message, cipher):
tmsg = ''
for c in message:
tmsg = tmsg + (cipher[c] if c in cipher else c)
return tmsg
"""
The starter code has a test message (named test). Try your transform_message
function on the test message: does the output look like this:
'F Zljb ql Yrov zXbpXo, klq ql moXfpb efj.'? In addition to having it printed
out on the screen, you should also save the transformed message to a variable
named ttest, so that we can reuse it later.
"""
test = "I come to bury Caesar, not to praise him."
# Having a coded message does not help you so much if you don’t have a way to
# decode it. Fortunately, we can do that just by creating another cipher. In the
# code editor, define a new dictionary named decoder that maps from a
# transformed letter back to the original letter, i.e., it just undoes the
# transformation that the original cipher did. The easiest way to do this is to
# recognize that the cipher is a dictionary that maps keys to values, and you
# want a different dictionary that maps the values back to keys.
decoder = {letters[i]: letters[(i+3) % len(letters)] for i in range(len(letters)
)} | true |
bcdb572bcbba2ed318e0d0d9121285be989d6621 | lastcanti/effectivePython | /item3helperFuncs.py | 848 | 4.4375 | 4 | # -----****minimal Python 3 effective usage guide****-----
# bytes, string, and unicode differences
# always converts to str
def to_str(bytes_or_str):
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode('utf-8')
else:
value = bytes_or_str
return value
# always converts to bytes
def to_bytes(bytes_or_str):
if isinstance(bytes_or_str,str):
value = bytes_or_str.encode('utf-8')
else:
value = bytes_or_str
return value
# create str var a and make sure its str
a = to_str("andrew")
print(a)
# create str var and convert to bytes
a = to_bytes(a)
print(a)
# bytes are sequences of 8-bit values
# bytes and str instances are not compatible
# use helper functions to ensure inputs are proper type
# always open file in binary mode('rb' or 'wb') if you want to
# read or write to file
| true |
6e27535bde7a1978b86b9d03381e72a745af83ed | VladislavRazoronov/Ingredient-optimiser | /examples/abstract_type.py | 1,520 | 4.28125 | 4 | class AbstractFood:
"""
Abstract type for food
"""
def __getitem__(self, value_name):
if f'_{value_name}' in self.__dir__():
return self.__getattribute__(f'_{value_name}')
else:
raise KeyError('Argument does not exist')
def __setitem__(self, value_name, value):
if f'_{value_name}' in self.__dir__():
self.__setattr__(f'_{value_name}', value)
else:
raise KeyError('Argument does not exist')
def compare_values(self, other, value):
"""
Compares given values of two food items
"""
if value in self.__dir__() and value in other.__dir__():
return float(self.__getattribute__(value)) > float(other.__getattribute__(value))
else:
return "Can't compare values"
def __eq__(self, other):
"""
Checks if two food items are the same
"""
if self is other:
return True
if type(self) == type(other):
return self._name == other._name and self._calories == other._calories and \
self._carbohydrates == other._carbohydrates and self._fat == other._fat\
and self._proteins == other._proteins
def __str__(self):
"""
Returns string representation of food
"""
return f'{self._name} has {self._calories} calories, {self._carbohydrates}' +\
f'g. carbohydrates, {self._fat}g. of fat and {self._proteins}g. of proteins'
| true |
6c291c935764c099d5c861d070780800d69d965d | HOL-BilalELJAMAL/holbertonschool-python | /0x0B-python-inheritance/11-square.py | 1,102 | 4.28125 | 4 | #!/usr/bin/python3
"""
11-square.py
Module that defines a class called Square that inherits from
class Rectangle and returns its size
Including a method to calculate the Square's area
Including __str__ method to represent the Square
"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
"""
Represents a class called Square with a private instance
attribute called size
"""
def __init__(self, size):
"""
Initialization of the private instance attribute
Size will be validated using the integer_validator
implemented in the base class
"""
self.integer_validator("size", size)
super().__init__(size, size)
self.__size = size
def area(self):
"""Function that returns the area of the Square"""
return self.__size ** 2
def __str__(self):
"""
Function str that defines the string representation of the Square
"""
return "[Square] {}/{}".format(str(self.__size),
str(self.__size))
| true |
da4284aa2521689c430d51e0c275b40f2f86348d | HOL-BilalELJAMAL/holbertonschool-python | /0x0C-python-input_output/0-read_file.py | 393 | 4.125 | 4 | #!/usr/bin/python3
"""
0-read_file.py
Module that defines a function called read_file that reads
a text file (UTF8) and prints it to stdout
"""
def read_file(filename=""):
"""
Function that reads a text file and prints it to stdout
Args:
filename (file): File name
"""
with open(filename) as f:
for line in f:
print(line, end="")
| true |
0bbcccf7cb91667ab15a317c53ac951c900d93a6 | HOL-BilalELJAMAL/holbertonschool-python | /0x0B-python-inheritance/10-square.py | 819 | 4.28125 | 4 | #!/usr/bin/python3
"""
10-square.py
Module that defines a class called Square that inherits from
class Rectangle and returns its size
Including a method to calculate the Square's area
"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
"""
Represents a class called Rectangle with a private instance
attribute called size
"""
def __init__(self, size):
"""
Initialization of the private instance attribute
Size will be validated using the integer_validator
implemented in the base class
"""
self.integer_validator("size", size)
super().__init__(size, size)
self.__size = size
def area(self):
"""Function that returns the area of the rectangle"""
return self.__size ** 2
| true |
adee2a41e59f94a940f45ebbf8fddb16582614a6 | sonsus/LearningPython | /pywork2016/arithmetics_classEx1018.py | 1,334 | 4.15625 | 4 | #Four arithmetics
class Arithmetics:
a=0
b=0
#without __init__, initialization works as declared above
def __init__(self,dat1=0,dat2=0):
a=dat1
b=dat2
return None
def set_data(self,dat1,dat2):
self.a=dat1
self.b=dat2
return None
def add(self):
return self.a+self.b
def sub(self):
return self.a-self.b
def mul(self):
return self.a*self.b
def div(self):
if self.b!=0: pass
else:
print("error! cannot div by 0") #printed
return None
return self.a/self.b
#if we dont want to execute below when only opened this file, not imported by others
if __name__=="__main__":
A=Arithmetics(3,4)
#let us see how initialization works when we dont define init manually
print(A.a)
print(A.b) #initialization as declared.
# A.set_data(1,0)
#same as the expression on the right: Arithmetics.setdata(A,1,2)
print(A.add())
print(A.sub())
print(A.mul())
print(A.div())
#Inheritance?
print("inheritance test")
class test(Arithmetics):
pass
def testprint(self):
print(self.a)
print(self.b)
I=test()
I.testprint()
#output:
#1
#0 | true |
aa226fc06796e2e12132527b270f9671bd66bb55 | annabalan/python-challenges | /Practice-Python/ex-01.py | 489 | 4.25 | 4 | #Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
def aging():
name = input("Enter your name: ")
age = int(input("Enter your age: "))
number = int(input("Enter a number: "))
year = str((2018 - age)+100)
print(("\nHello " + name + "!" + " You are " + str(age) + "." + " You will be 100 years old in the year," + str(year) + ".") * (number))
aging()
| true |
bc917efa9ab9aef3260e21326d9c10c7f51cbc0e | strawhatasif/python | /calculate_average_rainfall.py | 2,396 | 4.5 | 4 | # This program calculates and displays average rainfall based on rainfall amounts per month entered by the user.
# constant for number of months in a year
NUMBER_OF_MONTHS_IN_YEAR = 12
# stores the number of years entered by the user
number_of_years = int((input('Please enter the number of years: ')))
# if the initial entry for number of years is less than or equal to zero, display an error message.
# also, ask user to reenter number of years.
while number_of_years <= 0:
print('Invalid entry! The number of years must be greater than zero.')
# stores the number of years entered by the user (subsequent attempt).
number_of_years = int(input('Please reenter the number of years: '))
# accumulator variable for rainfall total.
total_rainfall = 0.0
# iterate once per year
for year in range(number_of_years):
# years start at 1, not 0. format as a string for display purposes.
print('Enter monthly rainfall for year ' + str(year + 1))
# iterate for the number of months in a year (Gregorian calendar).
for month in range(NUMBER_OF_MONTHS_IN_YEAR):
# months start at 1, not 0. format as a string for display purposes.
display_month = str(month + 1)
# stores the monthly rainfall entered by the user.
# format as a string for display purposes
monthly_rainfall = float(input('Enter rainfall for month ' + display_month + ': '))
# if the entry for monthly rainfall is less than zero, display an error message and ask user to reenter value.
while monthly_rainfall < 0:
print('Invalid entry! Monthly rainfall must be greater than zero.')
# stores the monthly rainfall entered by the user (subsequent attempt).
monthly_rainfall = float(input('Reenter rainfall for month ' + display_month + ': '))
total_rainfall += monthly_rainfall
# Display the total number of months. As a reminder, months begin at 1 and not 0.
total_months = int(display_month) * number_of_years
print('Number of months: ' + str(total_months))
# Displays the total rainfall for all months. Formatted to display 2 decimal places.
print('Total inches of rainfall: ' + format(total_rainfall, ',.2f'))
# The average rainfall formula is TOTAL RAINFALL divided by the NUMBER OF MONTHS.
# Formatted to display 2 decimal places.
print('Average rainfall: ' + format(total_rainfall/total_months, '.2f'))
| true |
e6c7ddd18304dd9cb6fadb4d98058483494c0300 | strawhatasif/python | /commission_earned_for_investor.py | 2,983 | 4.34375 | 4 | # This program tracks the purchase and sale of stock based on investor input.
# constant percentage for how much commission an investor earns.
COMMISSION_RATE = 0.03
# PURCHASE OF STOCK SECTION
# Stores the name of the investor when entered.
investor_name = input('What is your name? ')
# Stores the number of shares purchased (assuming whole numbers only)
number_of_shares_purchased = int(input('How many shares did you purchase? (whole numbers only) '))
# Stores the price per share. Assumption: USD format
price_per_share = float(input('What is the price per share? (in dollars) '))
# the product between number of shares purchased and price per share
purchase_amount = number_of_shares_purchased * price_per_share
# the investor earns 3% of the purchase amount
purchase_commission = purchase_amount * COMMISSION_RATE
# Displays the purchase amount as a floating point with a precision of 2 decimal places
print('The purchase amount is $' + format(purchase_amount, ',.2f'))
# Displays the total commission earned for the purchase as a floating point with a precision of 2 decimal places
print('The commission earned for this purchase is $' + format(purchase_commission, ',.2f'))
# SALE OF STOCK SECTION
# Stores of the name of the investor when entered.
investor_name = input('What is your name? ')
# Stores the number of shares sold (assuming whole numbers only)
number_of_shares_sold = int(input('How many shares did you sell? (whole numbers only) '))
# Stores the cost per share. Assumption: USD format
cost_per_share = float(input('What is the price per share? (in dollars) '))
# the product between number of shares sold and the cost per share
sale_amount = number_of_shares_sold * cost_per_share
# the investor earns 3% of the sale amount.
sale_commission = sale_amount * COMMISSION_RATE
# Displays the sale amount as a floating point with a precision of 2 decimal places
print('The sale amount is $' + format(sale_amount, ',.2f'))
# Displays the total commission earned for the sale as a floating point with a precision of 2 decimal places
print('The commission earned for this sale is $' + format(sale_commission, ',.2f'))
# SUMMARY OF TRANSACTIONS SECTION
# This is the total commission earned by the investor as a floating point with a precision of 2 decimal places.
total_commission = float(format((purchase_commission + sale_commission), '.2f'))
# Displays the investor's name
print('Name of investor: ' + investor_name)
# Prints the total commission earned by the investor as a floating point with a precision of 2 decimal places.
print('Total commission earned: $' + format(total_commission, ',.2f'))
# Prints an amount which represents either a profit or loss and is the result between the purchase and sale amounts.
# The format is a floating point with a precision of 2 decimal places
print('Profit/Loss amount: $' + format((sale_amount -
(number_of_shares_sold * price_per_share) - total_commission), ',.2f'))
| true |
6fc6becc03fbd9d920f80033889746e04d5852ed | justintuduong/CodingDojo-Python | /Python/intro_to_data_structures/singly_linked_lists.py | 1,957 | 4.125 | 4 |
class SLNode:
def __init__ (self,val):
self.value = val
self.next = None
class SList:
def __init__ (self):
self.head = None
def add_to_front(self,val):
new_node = SLNode(val)
current_head = self.head #save the current head in a variable
new_node.next = current_head # SET the new node's next To the list's current head
self.head = new_node #return self to allow for chaining
return self
def print_values(self):
runner = self.head #a pointer to the list's first node
while(runner != None): #iterating while runner is a node and None
print(runner.value) #print the current node's value
runner = runner.next #set the runner to its neighbor
return self#once the loop is done, return self to allow for chaining
#not needed
# def add_to_back(self,val): #accepts a value
# new_node = SLNode(val) #create a new instance of our Node class with the given value
# runner = self.head
# while (runner.next != None): #iterator until the iterator doesnt have a neighbor
# runner = runner.next #increment the runner to the next node in the list
# runner.next = new_node #increment the runner to the next node in the list
# return self
#-------------------
def add_to_back(self,val):
if self.head == None: # if the list is empty
self.add_to_front(val) #run the add_to_front method
return self # let's make sure the rest of this function doesnt happen if we add to the front
new_node = SLNode(val)
runner = self.head
while (runner.next != None):
runner = runner.next
runner.next = new_node #increment the runner to the next node in the list
return self # return self to allow for chaining
my_list=SList()
my_list.add_to_front("are").add_to_front("Linked lists").add_to_back("fun!").print_values()
| true |
5457e1f66077f12627fd08b2660669b21c3f34d3 | AmonBrollo/Cone-Volume-Calculater | /cone_volume.py | 813 | 4.28125 | 4 | #file name: cone_volume.py
#author: Amon Brollo
"""Compute and print the volume of a right circular cone."""
import math
def main():
# Get the radius and height of the cone from the user.
radius = float(input("Please enter the radius of the cone: "))
height = float(input("Please enter the height of the cone: "))
# Call the cone_volume function to compute the volume
# for the radius and height that came from the user.
vol = cone_volume(radius, height)
# Print the radius, height, and
# volume for the user to see.
print(f"Radius: {radius}")
print(f"Height: {height}")
print(f"Volume: {vol}")
def cone_volume(radius, height):
"""Compute and return the volume of a right circular cone."""
volume = math.pi * radius**2 * height / 3
return volume
main()
| true |
e93a9c53e043b7c1689f8c5c89b6365708153861 | diamondhojo/Python-Scripts | /More or Less.py | 928 | 4.21875 | 4 | #Enter min and max values, try to guess if the second number is greater than, equal to, or less than the first number
import random
import time
min = int(input("Enter your minimum number: "))
max = int(input("Enter your maximum number: "))
first = random.randint(min,max)
second = random.randint(min,max)
print ("The first number is " + str(first))
choice = input("Do you think the second number will be higher, lower, or the same as the first number? ")
if choice == "higher" or choice =="lower" or choice == "same":
if choice == "higher" and second > first:
print ("You're correct")
elif choice == "lower" and first > second:
print("You're correct")
elif choice == "same" and first == second:
print("You're correct")
else:
print("You're wrong")
time.sleep(1)
print("Idiot.")
time.sleep(1)
else:
print("Answer with 'higher', 'lower', or 'same'")
| true |
01d4ea985f057d18b978cdb28e8f8d17eac02a6d | matthew-kearney/cs-module-project-recursive-sorting | /src/sorting/sorting.py | 1,938 | 4.28125 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
merged_arr = [0] * elements
# Your code here
index_a = 0
index_b = 0
# Iterate through all indices in merged array
for i in range(elements):
# Make sure that we aren't past the end of either of the two input arrays
if index_a == len(arrA):
merged_arr[i] = arrB[index_b]
index_b += 1
elif index_b == len(arrB):
merged_arr[i] = arrA[index_a]
index_a += 1
# Set merged array at i to the smaller of the two elements at the current index in either array
# Increment appropriate index
elif arrA[index_a] < arrB[index_b]:
merged_arr[i] = arrA[index_a]
index_a += 1
else:
merged_arr[i] = arrB[index_b]
index_b += 1
# increment pionter
return merged_arr
# TO-DO: implement the Merge Sort function below recursively
def merge_sort(arr):
# Your code here
# If at base case (1 element) return array as it is already sorted
if len(arr) <= 1:
return arr
# Divide in half
mid = len(arr) // 2
# Merge sort either half of the array
left_array = merge_sort(arr[0:mid])
right_array = merge_sort(arr[mid:len(arr)])
# Now we operate as if each half has already been sorted
arr = merge(left_array, right_array) # Merge using our helper function
return arr
# # STRETCH: implement the recursive logic for merge sort in a way that doesn't
# # utilize any extra memory
# # In other words, your implementation should not allocate any additional lists
# # or data structures; it can only re-use the memory it was given as input
# def merge_in_place(arr, start, mid, end):
# # Your code here
# def merge_sort_in_place(arr, l, r):
# # Your code here
| true |
00b7d2b18548c195bedf516c25a3eda1f4a169ed | Joewash1/password | /Password2-2.py | 596 | 4.21875 | 4 | s=input("please enter your password :: ")
Password = str( 'as1987Jantu35*^ft$TTTdyuHi28Mary')
if (s == Password):
print("You have successfully entered the correct password")
while (s != Password):
print("Hint:1 The length of your password is 32 characters")
s=input("please enter your password :: ")
if(s!= Password):
print("Your password has 8 numbers")
s= input("please enter your password :: ")
if (s!= Password):
print("Your password has 1 i in it")
if (s == Password):
break
print("You successfully entered the correct password")
| true |
bdb4ad158aeda38ada8f2ca88850aab3338393b4 | elrosale/git-intro | /intro-python/part1/hands_on_exercise.py | 1,140 | 4.3125 | 4 | """Intro to Python - Part 1 - Hands-On Exercise."""
import math
import random
# TODO: Write a print statement that displays both the type and value of `pi`
pi = math.pi
print(type(pi), (pi))
# TODO: Write a conditional to print out if `i` is less than or greater than 50
i = random.randint(0, 100)
if i < 50:
print("i es menor a 50")
elif i > 50:
print("i es mayor a 50")
print("valor de i es:", i)
# TODO: Write a conditional that prints the color of the picked fruit
picked_fruit = random.choice(["orange", "strawberry", "banana"])
print(picked_fruit)
if picked_fruit == "orange":
print("Fruit color is orange")
elif picked_fruit == "strawberry":
print("Fruit color is red")
elif picked_fruit == "banana":
print("Fruit color is yellow")
# TODO: Write a function that multiplies two numbers and returns the result
# Define the function here.
def times(num1, num2):
result = num1 * num2
return result
# TODO: Now call the function a few times to calculate the following answers
print("12 x 96 =", times(12, 96))
print("48 x 17 =", times(48, 17))
print("196523 x 87323 =", times(196523, 87323))
| true |
277001f219bf21982133779920f98e4b77ca9ec0 | DeLucasso/WePython | /100 days of Python/Day3_Leap_Year.py | 465 | 4.3125 | 4 | year = int(input("Which year do you want to check? "))
# A Leap Year must be divisible by four. But Leap Years don't happen every four years … there is an exception.
#If the year is also divisible by 100, it is not a Leap Year unless it is also divisible by 400.
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("Leap year.")
else:
print("Not a leap year.")
else:
print("Leap year.")
else:
print("Not a leap year.")
| true |
435f96309f8dbcc0ebf5de61390aae7f06d4d7e9 | ashwin1321/Python-Basics | /exercise2.py | 1,541 | 4.34375 | 4 | ##### FAULTY CALCULATOR #####
def calculetor():
print("\nWellcome to Calc:")
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
** for power
% for modulo
Enter Your Choise:
''')
num1 = int(input("Enter first Number: "))
num2 = int(input("Enter second Number: "))
if operation == '+':
if num1 == 56 and num2 ==9:
print("56 + 9 = 77")
else:
print(f"{num1} + {num2} = {num1 + num2}")
elif operation == '-':
print(f"{num1} - {num2} = {num1 - num2}")
elif operation == '*':
if num1 == 45 and num2 == 3:
print("45 * 3 = 555")
else:
print(f"{num1} * {num2} = {num1 * num2}")
elif operation == '/':
if num1 == 56 and num2 == 4:
print("56/6 = 4")
else:
print(f"{num1} / {num2} = {num1 / num2}")
elif operation == '**':
print(f"{num1} ** {num2} = {num1 ** num2}")
elif operation == '%':
print(f"{num1} % {num2} = {num1 % num2}")
else:
print("You Press a Invalid Key")
again()
def again():
cal_again = input('''
Do you want to calculate again?
Please type y for YES or n for NO.
''')
if cal_again == 'y':
calculetor()
elif cal_again == 'n':
print("See You Later")
else:
again()
calculetor() | true |
1b022a05c38b11750eeb5bc824ea2968628533a5 | ashwin1321/Python-Basics | /lists and its function.py | 1,724 | 4.625 | 5 |
########## LISTS #######
# list is mutable, we can replace the items in the lists
'''
grocery = [ 'harpic', ' vim bar', 'deodrant', 'bhindi',54] # we can include stirng and integer together in a list
print(grocery)
print(grocery[2])
'''
'''
numbers = [12,4,55,16,7] # list can also be empty [], we can add items in it later
print(numbers)
print(numbers.sort()) # it gives none output
numbers.sort() # it sorts the numbers in ascending order in a list
print(numbers)
numbers.reverse() # it sorts the numbers in reverse order
print(numbers)
numbers.append(17) # .append adds the item in the last of the list
print(numbers)
numbers.insert(1,123) # . insert(index,item), we can add item in the desired index
print(numbers)
numbers.remove(55) # .removes the items we want to remove
print(numbers)
numbers.pop() # .pop is used to remove the last items, Or it pops out the last item in the list
print(numbers)
numbers[1] = 45 # we can replace the item in the list with desired item
print(numbers)
'''
# MUTABLE = can change
# IMMUTABLE = cannot change
####### TUPLES #######
# tuples are immutable, as we cannot change the items in a tuple as of lists
tuple = (1,2,3,4,5)
print(tuple)
# tuple[1] = 6 # see, we cannot replace the items in tuple, as its immutable
# print(tuple)
'''
a=9
b=1
a,b = b,a # in this we can swap the values in python. like in traditional programming we use (temp=a, a=b, b= temp)
print(a,b)
'''
| true |
53b0a04657a620aaaf20bfee9f8a5b8e9b08e322 | ashwin1321/Python-Basics | /oops10.public, protected and private.py | 1,231 | 4.125 | 4 | class Employee:
no_of_leaves = 8 # This is a public variable having access for everybody inside a class
var = 8
_protec = 9 # we write a protected variable by writing "_" before a variable name. Its accessible to all the child classses
__pr = 98 # this is a private variable. we write this by writing "__" before a variable name
def __init__(self, aname, asalary, arole):
self.name = aname
self.salary = asalary
self.role = arole
def printdetails(self):
return f"The Name is {self.name}. Salary is {self.salary} and role is {self.role}"
@classmethod
def change_leaves(cls, newleaves):
cls.no_of_leaves = newleaves
@classmethod
def from_dash(cls, string):
return cls(*string.split("-"))
@staticmethod
def printgood(string):
print("This is good " + string)
emp = Employee("harry", 343, "Programmer")
print(emp._Employee__pr) # to access the private class we use ( ._"Class_name"__"private variable") | true |
0209c76a48557122b10eaedbac5667641078a631 | jvansch1/Data-Science-Class | /NumPy/conditional_selection.py | 292 | 4.125 | 4 | import numpy as np
arr = np.arange(0,11)
# see which elements are greater than 5
bool_array = arr > 5
#use returned array of booleans to select elements from original array
print(arr[bool_array])
#shorthand
print(arr[arr > 5])
arr_2d = np.arange(50).reshape(5,10)
print(arr_2d[2:, 6:)
| true |
dc914377bfebde9b6f5a4e2b942897d4cd2a8e25 | lilimehedyn/Small-projects | /dictionary_practice.py | 1,082 | 4.125 | 4 | #create a dict
study_hard = {'course': 'PythonDev', 'period': 'The first month', 'topics': ['Linux', 'Git', 'Databases','Tests', 'OOP'] }
# add new item
study_hard['tasks'] = ['homework', 'practice online on w3resourse', 'read about generators', 'pull requests',
'peer-review', 'status', 'feedback']
#print out items
print(study_hard)
print(study_hard.get('course'))
print(study_hard.get('period'))
print(study_hard.get('topics'))
print(study_hard.get('tasks'))
#updating the dict
study_hard.update({'course': 'Phyton Developer'})
print(study_hard)
print("The lenth of dictionary is", len(study_hard))
print(study_hard.keys())
print(study_hard.values())
# for loop for dict
for key, value in study_hard.items():
print(key, value)
for value in study_hard:
print(study_hard['period'])
# dictionary comprehension, how it works
# first step - create 2 lists
courses = ['JS Developers', 'Java Developers', 'Python Developers']
period = ["2 months", '5 months', '4 months']
my_dict = {cour: time for cour, time in zip (courses,period)}
print(my_dict) | true |
97dce44d9bdd9dfad2fd37f8e79d5956f6c64bd0 | Vagacoder/LeetCode | /Python/DynamicProgram/Q0122_BestTimeBuySellStock2.py | 2,454 | 4.15625 | 4 | #
# * 122. Best Time to Buy and Sell Stock II
# * Easy
# * Say you have an array prices for which the ith element is the price of a given
# * stock on day i.
# * Design an algorithm to find the maximum profit. You may complete as many
# * transactions as you like (i.e., buy one and sell one share of the stock multiple
# * times).
# * Note: You may not engage in multiple transactions at the same time (i.e., you
# * must sell the stock before you buy again).
# * Example 1:
# Input: [7,1,5,3,6,4]
# Output: 7
# Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
# Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
# * Example 2:
# Input: [1,2,3,4,5]
# Output: 4
# Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
# Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
# engaging multiple transactions at the same time. You must sell before buying again.
# * Example 3:
# Input: [7,6,4,3,1]
# Output: 0
# Explanation: In this case, no transaction is done, i.e. max profit = 0.
# * Constraints:
# 1 <= prices.length <= 3 * 10 ^ 4
# 0 <= prices[i] <= 10 ^ 4
#%%
class Solution:
# * Solution 1
# ! Dynamic programming
def maxProfit1(self, prices: list) -> int:
n = len(prices)
if n == 0:
return 0
# * Since k is no limited, we don't need consider k any longer
dp = [[0, 0] for _ in range(n)]
for i in range(n):
# * Base case
# * since k is not considered, we only consider base case fo first day
if i == 0:
dp[i][0] = 0
dp[i][1] = -prices[i]
else:
dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])
dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i])
return dp[n-1][0]
# * Solution 2
# ! Greedy algorithm
def maxProfit2(self, prices:list) -> int:
n = len(prices)
if n == 0:
return 0
maxProfit = 0
for i in range(1, n):
maxProfit += max(0, prices[i] - prices[i-1])
return maxProfit
sol = Solution()
a1 = [7,1,5,3,6,4]
r1 = sol.maxProfit2(a1)
print(r1)
a1 = [1,2,3,4,5]
r1 = sol.maxProfit2(a1)
print(r1)
a1 = [7,6,4,3,1]
r1 = sol.maxProfit2(a1)
print(r1)
# %%
| true |
6396751b5e099078737ff179113ceda89fbce28c | dishashetty5/Python-for-Everybody-Functions | /chap4 7.py | 743 | 4.40625 | 4 | """Rewrite the grade program from the previous chapter using
a function called computegrade that takes a score as its parameter and
returns a grade as a string.
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F"""
score=float(input("enter the score:"))
def computegrade(score):
try:
if(score > 1 or score < 0):
return"bad score"
elif(score > 0.9):
return"A"
elif(score > 0.8):
return"B"
elif(score > 0.7):
return"C"
elif(score > 0.6):
return"D"
elif(score <= 0.6):
return"F"
else:
return"bad score"
except:
return"Bad score"
print(computegrade(score))
| true |
dfe1b71f4bca7dc0438ae83fd418ad131fb8aba9 | huzaifahshamim/coding-practice-problems | /Lists, Arrays, and Strings Problems/1.3-URLify.py | 1,061 | 4.1875 | 4 | """
Write a method to replace all spaces in a string with '%20'. You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true"
length of the string. (Note: if implementing in Java, please use a character array so that you can
perform this operation in place.)
"""
def URLify(str1, true_length):
modified = []
for place in range(true_length):
if str1[place] == ' ':
modified.append('%20')
else:
modified.append(str1[place])
back_to_str = ''.join(modified)
return back_to_str
""""
Since we are using appending to a list. TC will be O(true_length) + O(len(modified)) due to the .join. The length of
modified will be larger than true_length.
Time Complexity: O(len(modified))
"""
"""
Using a list and appending values to it.
Space Complexity: ~O(n)
"""
ans1 = URLify('Mr John Smith ', 13)
print(ans1)
ans2 = URLify('what is popp in', 15)
print(ans2)
ans3 = URLify('hello ', 6)
print(ans3)
ans4 = URLify(' DOG', 4)
print(ans4) | true |
e294f151d8eaded0356ab30f0cc961a31aff3698 | vishnuvs369/python-tutorials | /inputs.py | 421 | 4.21875 | 4 | # inputs
name = input("Enter your name")
email = input("Enter your email")
print(name , email)
#-------------------------------------------------
num1 = input("Enter the first number") #The input number is in string we need to convert to integer
num2 = input("Enter the second number")
#num1 = int(input("Enter the first number"))
#num2 = int(input("Enter the second number"))
sum = num1 + num2
print(sum) | true |
0bddc508ce2a5079507fdd0dbe4f55a0c09a2ef7 | Joezeo/codes-repo | /python-pro/io_prac.py | 508 | 4.15625 | 4 | forbideen = ('!', ',', '.', ';', '/', '?', ' ')
def remove_forbideen(text):
text = text.lower()
for ch in text:
if ch in forbideen:
text = text.replace(ch, '')
return text
def reverse(text):
return text[::-1]# 反转字符串
def is_palindrome(text):
return text == reverse(text)
instr = input('Please input a string:')
instr = remove_forbideen(instr)
if is_palindrome(instr):
print('Yes, it is a palindrome')
else:
print('No, it is not a palindrome')
| true |
6e83d95f12ae67d956867620574d63000b4ed848 | famosofk/PythonTricks | /ex/dataStructures.py | 800 | 4.40625 | 4 | #tuples
x = ('string', 3, 7, 'bh', 89)
print(type(x))
#tuples are imatuble. This is a list of different types object. We create tuples using (). In python this would be listof
y = ["fabin", 3, "diretoria", 8, 73]
y.append("banana")
print(type(y))
#lists are mutable tuples. We create lists using []
#both of them are iterable so we can do this
for element in x:
print(element)
#We can access elements using index as well. To do this you can simply use brackets y[3]
#to discover the length of a list or tuple we can use length.
# Operation: + concatenate lists. * repeats the list
#Dictionaries are collections of objects with key and value. They don't have index and we create them with curly braces
dic = {"fabiano" : "fabiano.junior@nobugs.com.br", "jace" : "jacevenator@gmail.com"}
nome, sobrenome = dic
print(dic[nome])
| true |
03dae7a8d59866b3c788c42fbc5c43a09d4e89ef | famosofk/PythonTricks | /2-DataStructures/week3/files.py | 739 | 4.3125 | 4 | # to read a file we need to use open(). this returns a variable called file handler, used to perform operations on file.
#handle = open(filename, mode) #Mode is opcional. If you plan to read, use 'r', and use 'w' if you want to write
#each line in file is treated as a sequence of strings, so if you want to print
name = input('Enter filename: ')
file = open(name, 'r')
#for word in file:
# print(word)
#How to read the whole file
readedFile = file.read()
#print(len(readedFile))
#Read all the stuff as a string
print(readedFile)
fhand = open('file.txt', 'r')
for line in fhand:
if line.startswith('o fabin'):
print(line)
#to remove the double \n just use .rstrip() in print, like this: print(line.rstrip())
| true |
8a781a70cc04d0d89c28c3db8da5d5ee0e9b49da | AhmadAli137/Base-e-Calculator | /BorderHacks2020.py | 1,521 | 4.34375 | 4 | import math #library for math operation such as factorials
print("==============================================")
print("Welcome to the Exponent-Base-e Calculator:")
print("----------------------------------------------")
print(" by Ahmad Ali ") #Prompts
print(" (BorderHacks 2020) ")
print("----------------------------------------------")
exp = float(input(" Enter your exponent: "))
sd = int(input(" Enter number of correct significant digits: ")) #User input
print("----------------------------------------------")
n = 1
sol = 1
Es = (0.5*10**(2-sd)) #formula to calculate error tolerance given number of significant digits
print("Error Tolerance: "+str(Es)+"%")
#Loop represents algorithm for a numerical calculation which
# becomes increasingly accurate with each iteration
# This calculation is only approximate to analytical calculation which has an infinite process
Repeat = True
while Repeat == True:
solOld = sol
sol = 1
n = n + 1
for i in range(n):
sol += (((exp)**(i+1))/(math.factorial(i+1)))
Ea = 100*(sol - solOld)/sol #Calculating approximation error between interations
if Ea < Es:
Repeat = False #loop ends once approximation error is below error tolerance
exponent_base_e = sol
print("Answer: "+str(exponent_base_e))
print("[correct to at least "+str(sd)+ " significant digits] ") #User Output
print("==============================================")
| true |
ee5ff425f61a596cc7edddb5bc3b11211cdc2e56 | urandu/Random-problems | /devc_challenges/interest_challenge.py | 938 | 4.21875 | 4 |
def question_generator(questions):
for question in questions:
yield question.get("short") + input(question.get("q"))
def answer_questions(questions):
output = "|"
for answer in question_generator(questions):
output = output + answer + " | "
return output
questions = [
{
"q": "Hi whats your name? ",
"short": "Name :"
},
{
"q": "Which year did you start writing code? ",
"short": "Year I began coding: "
},
{
"q": "Which stack is your favorite? ",
"short": "Preferred stack: "
},
{
"q": "One fact about you? ",
"short": "Fun fact: "
},
]
print(answer_questions(questions))
"""
The task is to write a simple function that asks one to input name, year started coding, stack and fun_fact,
then outputs(prints) all the inputs in a single line. Screen shot code then nominate two others to do the same
"""
| true |
c44ca53b2a11e083c23a725efcb3ac17df10d8ee | bowersj00/CSP4th | /Bowers_MyCipher.py | 1,146 | 4.28125 | 4 | alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def shifter(start_string, shift):
new_string=""
for character in start_string:
if character.isalpha():
new_string=new_string+(alphabet[(alphabet.index(character)+shift)%26])
else:
new_string=new_string+character
print(new_string)
is_active=True
while is_active:
start_string=str(input("Enter the string you wish to change:\n"))
which=input("Would you like to encode (e), decode (d), or brute force (b)?\n")
if which=="e":
shift=int(input("How many letters to shift by? (Enter as Number)\n"))
print("Your output is:")
shifter(start_string,shift)
elif which=="d":
shift=int(input("How many letters was it shifted by?\n"))
print("Your output is:")
shifter(start_string,26-shift)
elif which=="b":
print("Cipher possibilities are:\n")
for i in range(1,26):
shifter(start_string,i)
again=input("would you like to do another? (y or n)\n")
if again=="n":
is_active=False | true |
d86b80e7d3283ff2ee1b062e14539dbb87e34206 | anillava1999/Innomatics-Intership-Task | /Task 2/Task3.py | 1,778 | 4.40625 | 4 | '''
Given the names and grades for each student in a class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
Note: If there are multiple students with the second lowest grade, order their names alphabetically and print each name on a new line.
Example
The ordered list of scores is , so the second lowest score is . There are two students with that score: . Ordered alphabetically, the names are printed as:
alpha
beta
Input Format
The first line contains an integer, , the number of students.
The subsequent lines describe each student over lines.
- The first line contains a student's name.
- The second line contains their grade.
Constraints
There will always be one or more students having the second lowest grade.
Output Format
Print the name(s) of any student(s) having the second lowest grade in. If there are multiple students, order their names alphabetically and print each one on a new line.
Sample Input 0
5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39
Sample Output 0
Berry
Harry
Explanation 0
There are students in this class whose names and grades are assembled to build the following list:
python students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]]
The lowest grade of belongs to Tina. The second lowest grade of belongs to both Harry and Berry, so we order their names alphabetically and print each name on a new line.
'''
Result =[]
scorelist = []
if __name__ == '__main__':
for _ in range(int(input())):
name = input()
score = float(input())
Result+=[[name,score]]
scorelist+=[score]
b=sorted(list(set(scorelist)))[1]
for a,c in sorted(Result):
if c==b:
print(a)
| true |
3664b39e29387cb4c7beb0413249014d34b132bc | Arsalan-Habib/computer-graphics-assignments | /mercedez-logo/main.py | 1,719 | 4.21875 | 4 | import turtle
# initializing the screen window.
canvas = turtle.Screen()
canvas.bgcolor('light grey')
canvas.title('Mercedez logo')
# initializing the Turtle object
drawer = turtle.Turtle()
drawer.shape('turtle')
drawer.speed(3)
# Calculating the radius of the circumscribing circle of the triangle.
# The formula is: length of a sides/sqrt(3)
radius = 200/(3**(1/float(2)))
# drawing the concentric circles.
drawer.circle(radius+10)
drawer.penup()
drawer.setpos((0,10))
drawer.pendown()
drawer.circle(radius)
# Moving turtle to the initial position for drawing triangle.
drawer.penup()
drawer.setpos((0, (radius*2)+10 ))
drawer.pendown()
drawer.left(60)
# initializing empty arrays for cornerpoints of the outer triangle and the inner points.
endPoints = []
centrePoints=[]
# Drawing the triangle and adding the points to the array.
for i in range(3):
endPoints.append(drawer.pos())
drawer.right(120)
drawer.forward(200)
# Calculating and adding the innner points to the array.
for i in range(3):
drawer.penup()
drawer.setpos(endPoints[i])
drawer.setheading(360-(60+(120*i)))
drawer.forward(100)
drawer.right(90)
drawer.forward(40)
centrePoints.append(drawer.pos())
# Joining the outer points to the inner points.
for i in range(3):
drawer.penup()
drawer.color('black')
drawer.setpos(centrePoints[i])
drawer.pendown()
drawer.setpos(endPoints[i])
drawer.setpos(centrePoints[i])
drawer.setpos(endPoints[(i+1)%3])
# Erasing the outer triangle.
for i in range(3):
drawer.setpos(endPoints[i])
drawer.color('light grey')
drawer.setheading(360-(60+(120*i)))
drawer.forward(200)
drawer.penup()
drawer.forward(50)
turtle.done() | true |
49fb9f94501503eedfd7f5913efb3c8ffe656e68 | Saij84/AutomatetheBoringStuff_Course | /src/scripts/12_guessNumber.py | 968 | 4.3125 | 4 | import random
#toDo
'''
-ask players name
-player need to guess a random number between 1 - 20
-player only have 6 guesses
-player need to be able to input a number
-check need to be performed to ensure number us between 1 - 20
-check that player is imputing int
-after input give player hint
-"Your guess is too high"
-"Your guess is too low"
-"You guessed right, the number i thinking of is {number}
'''
randInt = random.randint(1, 20)
print("what is your name?")
playerName = input()
print("Hi {}".format(playerName))
for count in range(1, 7):
print("Please guess a number from 1 - 20")
guess = input()
try:
int(guess)
except ValueError:
print("Please enter a number")
if int(guess) < randInt:
print("Your guess is too low")
elif int(guess) > randInt:
print("Your guess is too high")
else:
print("Correct {}! The number is {}".format(playerName, randInt))
break
| true |
d28b91aa36ee49eb6666a655e1ef9fb6239b1413 | geisonfgf/code-challenges | /challenges/find_odd_ocurrence.py | 701 | 4.28125 | 4 | """
Given an array of positive integers. All numbers occur even number of times
except one number which occurs odd number of times. Find the number in O(n)
time & constant space.
Input = [1, 2, 3, 2, 3, 1, 3]
Expected result = 3
"""
def find_odd_ocurrence(arr):
result = 0
for i in xrange(len(arr)):
result = result ^ arr[i]
return result
if __name__ == '__main__':
print "Input [1, 2, 3, 2, 3, 1, 3]"
print "Expected result: 3"
print "Result: ", find_odd_ocurrence([1, 2, 3, 2, 3, 1, 3])
print "Input [2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2]"
print "Expected result: 5"
print "Result: ", find_odd_ocurrence([2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2])
| true |
1758af802adc1bf5dbf6b10bf4c04fd19d48e975 | mk9300241/HDA | /even.py | 209 | 4.34375 | 4 | #Write a Python program to find whether a given number (accept from the user) is even or odd
num = int(input("Enter a number:"))
if (num%2==0):
print(num," is even");
else:
print(num," is odd");
| true |
3c16a7d51658806c1233e14640f6ce6d3cabda12 | voksmart/python | /QuickBytes/StringOperations.py | 1,601 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 11 13:35:40 2019
@author: Mohit
"""
# String Assignment
str1 = "Hello"
str2 = "John"
# Checking String Length
print("Length of String is :",len(str1))
# String Concatenation (join)
print(str1 + " "+str2)
# String Formatting
# inserting name of guest after welcome
print("Welcome %s.Enjoy your stay"%(str2))
# Changing String Case
guestname = "John Smith"
# converts string to lower case
print(guestname.lower())
# converts string to UPPER case
print(guestname.upper())
# converts string to title case
# First letter of every word is capital
print(guestname.title())
# Stripping White Spaces
# string below has leading and trailing
# white space
message = " Good Morning John "
# remove all leading and trailing whitespace
print(message.strip())
# remove leading white space
print(message.lstrip())
# remove trailing white space
print(message.rstrip())
# String Formatting
# Using format{} function
guest = "John Smith"
city = "New York"
mobile="iphone"
price=199.234
# Simple Formatter with place holders
print("Hello {}! Welcome to {}".format(guest,city))
print("My {} cost me {}".format(mobile,price))
# With positional arguments
# Note changed position in format function
print("My {1} cost me {0}".format(price,mobile))
# controlling display with format specifiers
print("My {1:s} cost me {0:.2f}".format(price,mobile))
# Formatting using fstring
print(f"Hello {guest}. Welcome to {city}")
print(f"My new {mobile} cost me {price:.2f}")
| true |
c5e7b72cabf084c40320d31eb089b93451d7072d | ErosMLima/python-server-connection | /average.py | 217 | 4.375 | 4 | num = int(input("how many numbers ?"))
total_sum = 0
for n in range (num):
numbers = float(input("Enter any number"))
total_sum += numbers
avg = total_sum / num
print('The Average number is?'. avg) | true |
3a926ac51f31f52184607c8e4b27c99b4cbb9fb8 | AnujPatel21/DataStructure | /Merge_Sort.py | 863 | 4.25 | 4 | def merge_sort(unsorted_list):
if len(unsorted_list) <= 1:
return unsorted_list
middle = len(unsorted_list) // 2
left_half = unsorted_list[:middle]
right_half = unsorted_list[middle:]
left_half = merge_sort(left_half)
right_half = merge_sort(right_half)
return list(merge(left_half,right_half))
def merge (left_half,right_half):
result = []
while len(left_half) != 0 and len(right_half) != 0:
if left_half[0] < right_half[0]:
result.append(left_half[0])
left_half.remove(left_half[0])
else:
result.append(right_half[0])
right_half.remove(right_half[0])
if len(left_half) == 0:
result = result + right_half
else:
result = result + left_half
return result
unsorted_list = [9,8,7,6,5,4,3,2,1]
print(merge_sort(unsorted_list))
| true |
9fe71cad659e416a3c9349114ceebacae3895b15 | 12agnes/Exercism | /pangram/pangram.py | 317 | 4.125 | 4 | def is_pangram(sentence):
small = set()
# iterate over characters inside sentence
for character in sentence:
# if character found inside the set
try:
if character.isalpha():
small.add(character.lower())
except:
raise Exception("the sentence is not qualified to be pangram")
return len(small) == 26 | true |
c5a777c88c3e6352b2890e7cc21d5df29976e7e7 | edwardcodes/Udemy-100DaysOfPython | /Self Mini Projects/turtle-throw/who_throw_better.py | 1,371 | 4.3125 | 4 | # import the necessary libraries
from turtle import Turtle, Screen
import random
# Create custom screen
screen = Screen()
screen.setup(width=600, height=500)
guess = screen.textinput(title="Who will throw better",
prompt="Guess which turtle will throw longer distance?")
colors = ["red", "orange", "blue", "green", "purple"]
turtles = []
y_positions = [-85, -60, -35, -10, 15, 40, 65]
# Create multiple turtles and ask them to throw
for turtle_index in range(0, 5):
new_turtle = Turtle(shape="turtle")
new_turtle.penup()
new_turtle.color(colors[turtle_index])
new_turtle.goto(x=-285, y=y_positions[turtle_index])
turtles.append(new_turtle)
# Check whether user given guessed color as input
dist = {}
if guess:
for turtle in turtles:
rand_throw = random.randint(0, 500)
turtle.fd(rand_throw)
dist[turtle.pencolor()] = rand_throw
winning_turtle = max(dist, key=dist.get)
winning_dist = max(dist.values())
if winning_turtle == guess:
print(
f"you've won! The winning turtle is {winning_turtle} with covered distance of {winning_dist}")
else:
print(
f"you've lost! The winning turtle is {winning_turtle} with covered distance of {winning_dist}")
# Show results to the user whether he guessed right or wrong
screen.exitonclick()
| true |
73d4dbc12fed8bc83ac68f19a31a729283c9a05f | cascam07/csf | /hw2.py | 2,244 | 4.34375 | 4 | # Name: ... Cameron Casey
# Evergreen Login: ... cascam07
# Computer Science Foundations
# Programming as a Way of Life
# Homework 2
# You may do your work by editing this file, or by typing code at the
# command line and copying it into the appropriate part of this file when
# you are done. When you are done, running this file should compute and
# print the answers to all the problems.
## Hello!
###
### Problem 1
###
# DO NOT CHANGE THE FOLLOWING LINE
print "Problem 1 solution follows:"
import hw2_test
i = 1
x = 0
while (i<=hw2_test.n):
x = x + i
i=i+1
print x
###
### Problem 2
###
# DO NOT CHANGE THE FOLLOWING LINE
print "\n"
print "Problem 2 solution follows:"
for t in range(2,11):
print '1/',t
###
### Problem 3
###
# DO NOT CHANGE THE FOLLOWING LINE
print "\n"
print "Problem 3 solution follows:"
n = 10
triangular = 0
for i in range(n+1):
triangular = triangular + i
print "Triangular number", n, "via loop:", triangular
print "Triangular number", n, "via formula:", n*(n+1)/2
###
### Problem 4
###
# DO NOT CHANGE THE FOLLOWING LINE
print "\n"
print "Problem 4 solution follows:"
n = 10
factorial = 1
for i in range(1,n+1):
factorial = factorial*i
print n, "factorial:", factorial
###
### Problem 5
###
# DO NOT CHANGE THE FOLLOWING LINE
print "\n"
print "Problem 5 solution follows:"
n = 10
for counter in range(n): #execute inner loop 10 times
factorial = 1
for i in range(1,n+1): #computes n factorial
factorial = factorial*i
print factorial
n=n-1
###
### Problem 6
###
# DO NOT CHANGE THE FOLLOWING LINE
print "\n"
print "Problem 6 solution follows:"
reciprocal = 1
n = 10
for counter in range(n): #execute inner loop n times
factorial = 1.0
for i in range(1,n+1): #adds up 1/n!
factorial = factorial*i
reciprocal = reciprocal + (1/factorial)
n=n-1
print reciprocal
###
### Collaboration
###
# ... List your collaborators and other sources of help here (websites, books, etc.),
# ... as a comment (on a line starting with "#").
###
### Reflection
###
# ... The assignment took me around 3 hours. It would have been helpful to get
# ... some examples of how to use for loops in class before spending so much
# ... time on the code critique.
| true |
8bbd6935cc49c5280a79327c61d90ffb2ef5889c | Skp80/mle-tech-interviews | /data-structure-challenges/leetcode/543. Diameter of Binary Tree.py | 1,658 | 4.25 | 4 | """
Given the root of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree.
This path may or may not pass through the root.
The length of a path between two nodes is represented by the number of edges between them.
Example 1:
Input: root = [1,2,3,4,5]
Output: 3
Explanation: 3is the length of the path [4,2,1,3] or [5,2,1,3].
Example 2:
Input: root = [1,2]
Output: 1
Constraints:
The number of nodes in the tree is in the range [1, 104].
-100 <= Node.val <= 100
Learning:
- Solution must be between 2 leaf nodes
- Recursion. O(n)
"""
from typing import List
class TreeNode:
"""Definition for a binary tree node."""
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
diameter = 0
def diameterOfBinaryTree(self, root: TreeNode) -> int:
self._longest_path(root)
return self.diameter
def _longest_path(self, node):
if not node:
return 0
left_path = self._longest_path(node.left)
right_path = self._longest_path(node.right)
self.diameter = max(self.diameter, left_path + right_path)
return max(left_path, right_path) + 1
tree = TreeNode(val=1)
tree.left = TreeNode(val=2)
tree.right = TreeNode(val=3)
tree.left.left = TreeNode(val=4)
tree.left.right = TreeNode(val=5)
sol = Solution().diameterOfBinaryTree(root=tree)
print(sol == 3)
tree = TreeNode(val=1)
tree.left = TreeNode(val=2)
sol = Solution().diameterOfBinaryTree(root=tree)
print(sol == 1)
| true |
f0881f9ec77a982825071ed8106c4900278ac1a5 | vuthysreang/python_bootcamp | /sreangvuthy17/week01/ex/17_str_last.py | 625 | 4.40625 | 4 | """ Description : You will write a program that ask for one string as and return the last character.
If no argument is passed, display “Empty”
Requirements : ● Program must be named : 17_str_last.py and saved into week01/ex folder
Hint : ❖ print function
❖ string index
"""
# user input
strInput = input("Enter a string: ")
# check the condition again
if strInput == "":
# print output
print("Empty")
else:
# reverse the strInput
x = strInput[::-1]
# print output (we want to print the last character of the string)
print(x[0])
| true |
b09cbe34ac66a41d58ab047f0dfbb6024c9a105e | vuthysreang/python_bootcamp | /Documents/week03/sreangvuthy17/week03/ex/45_auto_folder.py | 2,173 | 4.46875 | 4 | """
Description : You will create a program that take a list of string as argument, that represents folders names.
Then, for each, you will create a folder with the corresponding name.
Before create anything, you will check that the folders doesn’t already exists.
If they, you will ask: “Are you sure you want to replace <FOLDER_NAME>? [Y/N]”
If the user enter anything that is not Y or N, you will write:
“Invalid Option” and then print the confirmation message again:
“Are you sure you want to replace <FOLDER_NAME>? [Y/N]”
Make sure that you ask for EVERY folders that already exist only.
Be careful with this program and don’t delete your work!
At the end, if your program did create any new folder you will return 1 Else you will return 0.
If the list of folder name is empty, your program will also return 0.
Requirements : ● Program name : 45_auto_folder.py
● Function name : auto_folder
● Directory : week03/ex folder
Hint : ❖ os library
"""
import os
import shutil
def auto_folder(mylist_folder):
modification = 0
if mylist_folder == []:
return 0
for foldername in mylist_folder:
if not os.path.exists(foldername):
os.makedirs(foldername)
modification = 1
elif os.path.exists(foldername):
while True:
user_input = input("Are you sure you want to replace " + str(foldername) + "? [Y/N]\n>> ")
if (user_input == "Y" or user_input == "y"):
shutil.rmtree(foldername)
os.makedirs(foldername)
modification = 1
break
elif (user_input == "N" or user_input == "n"):
break
else:
print(">> Invalid Option")
return modification
#auto_folder(["new_folder_name", "second_folder", "third_folder"])
#auto_folder([])
| true |
201dac84630f55ffceb24392cd58051b66e60495 | vuthysreang/python_bootcamp | /sreangvuthy17/week01/ex/08_random.py | 465 | 4.28125 | 4 | """ Description : You will write a program that take display a random number between 1 and 100
Requirements : ● Program must be named : 08_random.py and saved into week01/ex folder
Hint : ❖ print function
❖ random
"""
# import random library
import random
# print random output between 1 and 100
print(random.randint(1,100))
# another way
# x = random.randrange(1,101) or x = random.randint(1,100)
# print(x)
| true |
421e2d5f4300102b66651efd180d3dbd6bf66a82 | vuthysreang/python_bootcamp | /sreangvuthy17/week01/ex/06_odd_even.py | 1,491 | 4.46875 | 4 | """ Description : You will write a program that take will ask for a number in parameter and display “<number> is EVEN” or “number is ODD”.
If the number is not an integer, you will have to display “<input> is not a valid number.”.
If you enter “exit” or “EXIT” the program will quit. Else the program will continue ask you for a number.
Requirements : ● Program must be named : 06_odd_even.py and saved into week01/ex folder
Hint : ❖ print function
❖ input function
❖ arithmetic operators ❖ conditions
"""
# assign the True variable
program_is_running = True
# check the loop True or False
while (program_is_running == True):
# user input
n = input("Enter a number:\n>> ")
# check the condition
if n == "EXIT" or n == "exit":
# If program_is_running is False the program will be break
program_is_running = False
# check he condition again (check if digit or not)
elif n.isdigit():
# convert string to integer or number
num = int(n)
# check the condition again (check is even or not)
if (num % 2 == 0):
print(n+" is EVEN")
# check the condition again (check is odd or not)
else:
print(n+" is ODD")
# check the condition again after above "EXIT" or "exit"
else:
print(n+" is not a valid number.")
| true |
926c19499256827be9c6f281257082f307432908 | vuthysreang/python_bootcamp | /Documents/week03/sreangvuthy17/week03/ex/59_regex_html.py | 1,235 | 4.1875 | 4 | """
Description : You will create a function that take a string in parameter and remove every HTML content ( everything between ‘<’ and ‘>’ ) You will return the new formatted string.
You need to do it using REGEX only.
EXAMPLE :
regex_html("<html lang = 'pl' ><body> content of body </body> ... </html>")
⇒ " content of body ..."
regex_html("<h1>hello</h1> <p>hello</p>")
⇒ "hello hello"
regex_html("")
⇒ ""
regex_html("hello")
⇒ "hello"
regex_html("<<><>>><>")
⇒ ">>"
Requirements : ● Program name : 59_regex_html
● Function name : regex_html
● Directory : week03/ex folder
Hint : ❖ re
❖ sub
"""
import re
def regex_html(mystr):
print('regex_html("' + str(mystr) + '")')
final_str = re.sub(r'<.*?>', '', mystr)
print('=> "' + str(final_str) + '"')
return final_str
# regex_html("<html lang = 'pl' ><body> content of body </body> ... </html>")
# regex_html("<<><>>><>")
| true |
a287483a91fa92fd183f524039b0255d4ea11f7d | vuthysreang/python_bootcamp | /sreangvuthy17/week02/ex/35_current_time.py | 1,079 | 4.3125 | 4 | """
Description : You will write a function that return the current time with the following format: hh:mm:ss The return value must be a string.
Requirements : ● Program must be named : 35_current_time.py and saved into week02/ex folder
Hint : ❖ function
❖ datetime
Output :
current_time()
>> 04:59:40
"""
from datetime import datetime
from datetime import time
from datetime import date
# Define current_time() method/function
def current_time():
# inside the function/method
# print output
print('current_time()')
# declare (my_current_time) and to assign current time with only time format: hh:mm:ss
my_current_time = datetime.time(datetime.now())
# convert time format into string format
my_current_time = my_current_time.strftime("%H:%M:%S")
# print output of (my_current_time)
print(">> " + str(my_current_time))
# return output of (my_current_time)
return my_current_time
# outside the function/method
# call the current_time() function/method
current_time()
| true |
0613d7beaa42dfe4acbccbcd93a154f788ba7c6f | vuthysreang/python_bootcamp | /sreangvuthy17/week03/ex/41_current_path.py | 577 | 4.15625 | 4 | """
Description : You will write a function that print the current path of your program folder, then you will return it as a string.
Requirements : ● Program name : 41_current_path.py
● Function name : current_path
● Directory : week03/ex folder
Hint : ❖ os library
❖ os path
"""
import os
def current_path():
my_current_path = os.getcwd()
print("My current path of my program folder is:\n>> " + str(my_current_path))
return str(my_current_path)
#current_path()
| true |
9e2f2ccb0e7c1f8103abb86d1581e24ca4d03f3d | aengel22/Homework_Stuff | /module12_high_low.py | 2,532 | 4.21875 | 4 | # The get_price function accepts a string that is assumed to be
# in the format MM-DD-YYYY:Price. It returns the Price component
# as a float.
def get_price(str):
# Split the string at the colon.
items = str.split(':')
# Return the price, as a float.
return float(items[1])
# The get_year function accepts a string that is assumed to be
# in the format MM-DD-YYYY:Price. It returns the YYYY component
# as an int.
def get_year(str):
# Split the string at the colon.
items = str.split(':')
# Split the date item at the hyphens.
date_items = items[0].split('-')
# Return the year, as an int.
return int(date_items[2])
# The display_highest_per_year function steps through the gas_list
# list, displaying the highest price for each year.
def display_highest_per_year(gas_list):
current_year = get_year(gas_list[0])
highest = get_price(gas_list[0])
for e in gas_list:
if get_year(e) == current_year:
if get_price(e) > highest:
highest = get_price(e)
else:
print('Highest price for ', current_year, ': $',
format(highest, '.2f'), sep='')
current_year = get_year(e)
highest = get_price(e)
# Display the highest for the last year.
print('Highest price for ', current_year, ': $',
format(highest, '.2f'), sep='')
# The display_lowest_per_year function steps through the gas_list
# list, displaying the lowest price for each year.
def display_lowest_per_year(gas_list):
current_year = get_year(gas_list[0])
lowest = get_price(gas_list[0])
# Step through the list.
for e in gas_list:
if get_year(e) == current_year:
if get_price(e) < lowest:
lowest = get_price(e)
else:
print('Lowest price for ', current_year, ': $',
format(lowest, '.2f'), sep='')
current_year = get_year(e)
lowest = get_price(e)
# Display the lowest for the last year.
print('Lowest price for ', current_year, ': $',
format(lowest, '.2f'), sep='')
def main():
# Open the file.
gas_file = open('GasPrices.txt', 'r')
# Read the file's contents into a list.
gas_list = gas_file.readlines()
# Display the highest prices per year.
display_highest_per_year(gas_list)
# Display the lowest prices per year.
display_lowest_per_year(gas_list)
main()
| true |
55ebfed116af1e9389e2a81d432a237b90e7262e | RecklessDunker/Codewars | /Get the Middle Character.py | 789 | 4.25 | 4 | # --------------------------------------------------------
# Author: James Griffiths
# Date Created: Wednesday, 3rd July 2019
# Version: 1.0
# --------------------------------------------------------
#
# You are going to be given a word. Your job is to return the middle character of the
# word. If the word's length is odd, return the middle character. If the word's length
# is even, return the middle 2 characters.
def get_middle(s):
# your code here
wordlen = len(s)
if wordlen % 2 == 0:
# is even, so find middle two characters
middlechar = s[len(s) // 2 - 1] + s[len(s) // 2]
else:
# is odd, so find the middle letter
middlechar = s[len(s) // 2]
return middlechar
midchar = get_middle(input("Please type in a word: "))
print(midchar)
| true |
deec653fc1bbe1f2ff5d32d2970265a89e68b7b0 | cthompson7/MIS3640 | /Session01/hello.py | 2,277 | 4.59375 | 5 | print("Hello, Christian!")
# Whenever you are experimenting with a new feature, you should try to make mistakes. For example, in the “Hello, world!” program, what happens if you leave out one of the quotation marks? What if you leave out both? What if you spell print wrong?
print(Hello, world!")
# When I leave out one of the quotation marks, I get the following error, SyntaxError: invalid syntax/
print(Hello, world!)
# When I leave out both of the quotation marks, I get the following error, SyntaxError: invalid syntax/
prin("Hello, world!")
# When I spell print wrong, I get the following error, NameError: name 'prin' is not defined
# Exercise 1
# 1.) In a print statement, what happens if you leave out one of the parentheses, or both? */
print("Hello, world!"
# When I leave out one of the parentheses, as shown above, I get the following error, SyntaxError: unexpected EOF while parsing
print"Hello, world!"
# When I leave out both of the parentheses, as shown above, I get the following error, SyntaxError: invalid syntax
# 2.) If you are trying to print a string, what happens if you leave out one of the quotation marks, or both?
print(Hello")
# When trying to print a string, if I left out one of the quotation marks, I get the following error, SyntaxError: EOL while scanning string literal
print(Hello)
# When trying to print a string, if I left out both of the quotation marks, I get the following error, NameError: name 'Hello' is not defined
# 3.) You can use a minus sign to make a negative number like -2. What happens if you put a plus sign before a number? What about 2++2?
print(+2)
# If you put a plus sign before a number like 2, as shown above, you get an output of 2.
print(2++2)
# If you try to perform 2++2, as shown above, you get the following error, SyntaxError: invalid syntax
# 4.) In math notation, leading zeros are ok, as in 02. What happens if you try this in Python?
print(02)
# When you try to include leading zeros, as shown above, you get the following error, SyntaxError: invalid token
# 5.) What happens if you have two values with no operator between them?
print(2 5)
# When you have two values with no operator between them, as shown above, you get the following error, SyntaxError: invalid syntax | true |
e2ae0826393ebf746222d47506a538662f0c4016 | cthompson7/MIS3640 | /Session11/binary_search.py | 1,069 | 4.28125 | 4 | def binary_search(my_list, x):
'''
this function adopts bisection/binary search to find the index of a given
number in an ordered list
my_list: an ordered list of numbers from smallest to largest
x: a number
returns the index of x if x is in my_list, None if not.
'''
left = 0
right = len(my_list)-1
middle = int((left+right)/2)
if x not in my_list:
return None
while (right - left > 1):
if my_list[middle] == x:
return middle
elif my_list[middle] > x:
right = middle
middle = int((left+right/2))
elif my_list[middle] < x:
left = middle
middle = int((left+right/2))
if my_list[right] == x:
return right
elif my_list[left] == x:
return left
test_list = [1, 3, 5, 235425423, 23, 6, 0, -23, 6434]
test_list.sort()
print(binary_search(test_list, -23))
print(binary_search(test_list, 0))
print(binary_search(test_list, 235425423))
print(binary_search(test_list, 30))
# expected output
# 0
# 1
# 8
# None
| true |
d2c3f792c5b41ff79f7d6f7fa76c75317c6687be | aleperno/blog | /fibo.py | 1,313 | 4.25 | 4 | #!/usr/bin/python
import time
def recursiveFibo(number):
"""Recursive implementation of the fibonacci function"""
if (number < 2):
return number
else:
return recursiveFibo(number-1)+recursiveFibo(number-2)
def iterativeFibo(number):
list = [0,1]
for i in range(2,number+1):
list.append(list[i-1]+list[i-2])
return list[number]
def main():
print "Calculating the fibonacci of 4 by recursion"
exetime = time.time()
print "The fibonacci of 4 is: ",recursiveFibo(4)
print "The execution lasted: ",time.time()-exetime," seconds"
print "-----------------------------------------------------"
print "Calculating the fibonacci of 4 by iteration"
exetime = time.time()
print "The fibonacci of 4 is: ",iterativeFibo(4)
print "The execution lasted: ",time.time()-exetime," seconds"
print "#####################################################"
print "Calculating the fibonacci of 40 by recursion"
exetime = time.time()
print "The fibonacci of 40 is: ",recursiveFibo(40)
print "The execution lasted: ",time.time()-exetime," seconds"
print "-----------------------------------------------------"
print "Calculating the fibonacci of 40 by iteration"
exetime = time.time()
print "The fibonacci of 40 is: ",iterativeFibo(40)
print "The execution lasted: ",time.time()-exetime," seconds"
main() | true |
7850a710550a6bba787f81b5945d70098c60ba14 | jradd/small_data | /emergency_map_method.py | 518 | 4.46875 | 4 | #!/usr/bin/env python
'''
the following is an example of map method in python:
class Set:
def __init__(self, values=None):
s1 = []
# s2 = Set([1,2,2,3])
self.dict = {}
if values is not None:
for value in values:
self.add(value)
def __repr__(self):
return "Set: " + str(self.dict.keys())
def add(self, value):
self.dict[value] = True
print("OOPs")
def contains(self, value):
return value in self.dict
def remove(self, value):
del self.dict[value]
'''
| true |
925ffcfcff7df4ee4db086783374321ee32f092a | Andreabrian/python-programming-examples-on-lists | /assign1.py | 295 | 4.21875 | 4 | #find the largest number in the list.
a=[]
n=int(input("Enter the number of elements:"))
for i in range(n):
a.append(int(input("enter new element:")))
print(a)
s=a[0]
for i in range(1,len(a)):
if a[i]>s:
s=a[i]
y=("the largest number is: ")
print(y,s)
| true |
5f498fc6d83701963d4800d121630523e805568b | chriskok/PythonLearningWorkspace | /tutorial11-tryelsefinally.py | 1,333 | 4.4375 | 4 | # ---------- FINALLY & ELSE ----------
# finally is used when you always want certain code to
# execute whether an exception is raised or not
num1, num2 = input("Enter to values to divide : ").split()
try:
quotient = int(num1) / int(num2)
print("{} / {} = {}".format(num1, num2, quotient))
except ZeroDivisionError:
print("You can't divide by zero")
# else is only executed if no exception was raised
else:
print("You didn't raise an exception")
finally:
print("I execute no matter what")
# ---------- PROBLEM EXCEPTIONS & FILES ----------
# 1. Create a file named mydata2.txt and put data in it
# 2. Using what you learned in part 8 and Google to find
# out how to open a file without with try to open the
# file in a try block
# 3. Catch the FileNotFoundError exception
# 4. In else print the file contents
# 5. In finally close the file
# 6. Try to open the nonexistent file mydata3.txt and
# test to see if you caught the exception
try:
myFile = open("mydata.txt", encoding="utf-8")
# We can use as to access data and methods in the
# exception class
except FileNotFoundError as ex:
print("That file was not found")
# Print out further data on the exception
print(ex.args)
else:
print("File :", myFile.read())
myFile.close()
finally:
print("Finished Working with File")
| true |
1d1b0213e352a561d37417353719711b31bd3de4 | chriskok/PythonLearningWorkspace | /primenumber.py | 696 | 4.34375 | 4 | # Note, prime can only be divided by 1 and itself
# 5 is prime because only divided by 1 and 5 - positive factor
# 6 is not a prime, divide by 1,2,3,6
# use a for loop and check if modulus == 0 True
def is_prime(num):
for i in range(2, num):
if (num % i) == 0:
return False
return True
def get_prime(max_number):
list_of_primes = []
for num1 in range(2, max_number):
if is_prime(num1):
list_of_primes.append(num1)
return list_of_primes
# Ask the user to type in the maximum prime
max_prime = input("Insert max prime: ")
max_prime = int(max_prime)
primes_list = get_prime(max_prime)
for prime in primes_list:
print(prime)
| true |
8d598dc40e8428a74f5668cc6b6a29a86214e9bd | chriskok/PythonLearningWorkspace | /pinetree.py | 1,026 | 4.3125 | 4 | # How tall is the tree: 5
# 1 while loop and 3 for loops
#
###
#####
#######
#########
#
# 4 spaces: 1 hash
# 3 spaces: 3 hashes
# 2 spaces: 5 hashes
# ...
# 0 spaces: 9 hashes
# Need to do
# 1. Decrement spaces by 1 each time through the loop
# 2. Increment the hashes by 2 each time through the loop
# 3. Save spaces to the stump by calculating tree height
# 4. Decrement from tree height until it equals 0
# 5. Print spaces and then hashes for each row
# 6. Print stump spaces and then 1 hash
# Note: print('', end="") for space with no new line
# get user input
height = input("What is the height of your tree: ")
height = int(height)
initialSpaces = height - 1
increment = 1
# While loop checking going from height to 0
while height > 0:
spaces = height - 1
for s in range(spaces):
print(' ', end="")
for j in range(increment):
print('#', end="")
print('')
increment += 2
height -= 1
for s in range(initialSpaces):
print(' ', end="")
print('#', end="")
| true |
cd6759aa55356291bb5b1f277fd8f0a88f950be1 | TapasDash/Python-Coding-Practice | /oddEvenList.py | 519 | 4.1875 | 4 | '''
This is a simple programme which takes in input from the user as a series of numbers
then, filter out the even and odd ones and
append them in two different lists naming them oddList and evenList
Input : 1,2,3,4,5,6
Output : oddList = [1,3,5]
evenList = [2,4,6]
'''
myList = [eval(x) for x in input("Enter series of numbers = ").split(",")]
oddList = []
evenList = []
for x in myList:
if(x % 2 == 0):
evenList.append(x)a
else:
oddList.append(x)
print("Odd List=",oddList)
print("Even List=",evenList)
| true |
04edbaa127a19c39abb58fc4ab009161ddd40aee | rexarabe/Python_Projects | /class_01.py | 1,414 | 4.53125 | 5 | """Creating and using class """
#The car class
class Car():
""" A simple attemt to model a car. """
def __init__(self, make, model, year):
"""Initialize car attributes."""
self.make = make
self.model = model
self.year = year
#Fuel capacity and level in gallons.
self.fuel_capacity = 15
self.fuel_level = 0
def fill_tank(self):
"""Fill gas tank to capacity. """
self.fuel_level = self.fuel_capacity
print("Fuel tank is full.")
def drive(self):
""" Simulate driving."""
print("The car is moving.")
#creating and using a class
my_car = Car('audi' , 'a4', 2016)
print(my_car.make)
print(my_car.model)
print(my_car.year)
#calling methods
my_car.fill_tank()
my_car.drive()
my_new_car = Car('peugeot' , '205' , 1997)
my_new_car.fuel_level = 5
#Writing a method to update an attribute's value
def update_fuel_level(self, new_level):
""" Update the fuel level. """
if new_level <= self.fuel_capacity:
self.fuel_level = new_level
else:
print("The tank can't hold that much!")
def update_fuel_level(self, amount):
""" Add Fuel to the tank."""
if (self.fuel_level + amount
<= self.fuel_capacity):
self.fuel_level += amount
print("Added fuel.")
else:
print("The tank won't hold that much.")
| true |
b71c815fa1f8167c8594774745dfccef3931add9 | mustafaAlp/StockMarketGame | /Bond.py | 1,075 | 4.3125 | 4 | #!/usr/bin/env python
"""
This module includes Bond class which is a subclass of the Item class.
Purpose of the module to learn how to use
inheritance and polymorphizm in the python.
Its free to use and change.
writen by Mustafa ALP.
16.06.2015
"""
import random as ra
from Item import Item
#
#
# object
#
#
class Bond(Item):
"""
subclass Bond derived from Item superclass
purpose of the Bond class:
to learn inheritance and polymorphizm in python
"""
def __init__(self):
super(Bond, self).__init__()
self._name = 'bond'
#
# object property
#
def name():
doc = """The name property, keeps name of the Item and can't be changed"""
def fget(self):
return self._name
return locals()
name = property(**name())
#
# object static method
#
@staticmethod
def setWorth():
"""changes worth of Bond items"""
Bond._worth = ra.randint(25, 75)
#
# object static method
#
@staticmethod
def worth():
"""@return worth of Bond items"""
return Bond._worth
| true |
76512e65fadd9589b50889cbf42b99f68686983e | andrewlehmann/hackerrank-challenges | /Python Data Structures/Compare two linked lists/compare_linked_lists.py | 956 | 4.1875 | 4 | #Body
"""
Compare two linked list
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method.
"""
def equalityCheck(first, other):
var = 1
if first is None:
if other is not None:
var = 0
elif other is None:
if first is not None:
var = 0
else:
var = first.data == other.data
return var
def notEqual(first, other):
return not equalityCheck(first, other)
def CompareLists(headA, headB):
cur_nodeA = headA
cur_nodeB = headB
while cur_nodeA is not None and cur_nodeB is not None:
if cur_nodeA.data != cur_nodeB.data:
return 0
cur_nodeA = cur_nodeA.next
cur_nodeB = cur_nodeB.next
return int(cur_nodeA == None and cur_nodeB == None)
| true |
f5090b41b7e5cb5e98c4dc3ac85f092df79000bd | iyoussou/CAAP-CS | /hw1/fibonacci.py | 469 | 4.28125 | 4 | #Prints a specific value of the Fibonacci Sequence.
def main():
print("This program prints a specific term of the Fibonacci Sequence.")
term = eval(input("Which term of the Fibonacci Sequence would you like?: "))
current = 1
previous = 0
old_previous = 0
for i in range(0, term-1):
old_previous = previous
previous = current
current = previous + old_previous
print("Term " + str(term) + " of the Fibonacci Sequence is " + str(current) + ".")
main()
| true |
2212f3aa40b95de35bb686d7462c95119bc865be | idealgupta/pyhon-basic | /matrix1.py | 310 | 4.1875 | 4 | matrix =[
[3,4,5],
[5,7,8],
[4,9,7]
]
print(matrix)
transposed=[]
#for colem
for i in range(3):
list=[]
for row in matrix:
list.append(row[i])
transposed.append(list)
print(transposed)
#same
trans =[[row[i] for row in matrix] for i in range(3)]
print(trans) | true |
8646d28c0880d9b3851d0ec49e97ef259031bec3 | akshitshah702/Akshit_Task_5 | /# Task 5 Q3.py | 436 | 4.21875 | 4 | # Task 5 Q3
def mult_digits():
x = input("Enter number ")
while type(x) is not int:
try:
while int(x) <= 1:
x = input("Please enter a number greater than 1: ")
x = int(x)
except ValueError:
x = input("Please enter integer values only: ")
x = int(x)
print(f"Yes, you have entered {x}.") | true |
183b9a7d439dca14510d9257712d90d1adc8a515 | ANTRIKSH-GANJOO/-HACKTOBERFEST2K20 | /Python/QuickSort.py | 801 | 4.125 | 4 | def partition(array, low, high):
i = (low - 1)
pivot = array[high]
for j in range(low, high):
if array[j] <= pivot:
i = i + 1
array[i], array[j] = array[j], array[i]
array[i+1], array[high] = array[high], array[i+1]
return (i + 1)
def quickSort(array, low, high):
if len(array) == 1:
return array
if low < high:
part = partition(array, low, high)
quickSort(array, low, part - 1)
quickSort(array, part + 1, high)
array = []
while 1:
try:
x = input("Enter a number (To exit write something tha is not a number): ")
except:
break
array.append(x)
quickSort(array, 0, len(array) - 1)
print("Sorted array using Quicksort:")
for i in range(len(array)):
print("%d" % array[i]), | true |
c4f2ba0d605988bfcfb046c42e92b4ef216c0534 | ANTRIKSH-GANJOO/-HACKTOBERFEST2K20 | /Python/Merge_sort.py | 916 | 4.28125 | 4 | def merge_sort(unsorted_list):
if len(unsorted_list) <= 1:
return unsorted_list
# Finding the middle point and partitioning the array into two halves
middle = len(unsorted_list) // 2
left = unsorted_list[:middle]
right = unsorted_list[middle:]
left = merge_sort(left)
right = merge_sort(right)
return list(merge(left, right))
#Merging the sorted halves
def merge(left,right):
res = []
while len(left) != 0 and len(right) != 0:
if left[0] < right[0]:
res.append(left[0])
left.remove(left[0])
else:
res.append(right[0])
right.remove(right[0])
if len(left) == 0:
res = res + right
else:
res = res + left
return res
input_list = list(map(int,input("Enter unsorted input list: ").split()))
print("Unsorted Input: ", input_list)
print("Sorted Output: ", merge_sort(input_list)) | true |
6e3235205388258659eb7ac63925152e52267ed9 | ANTRIKSH-GANJOO/-HACKTOBERFEST2K20 | /Python/Insertion_sort.py | 305 | 4.21875 | 4 | def insertionSort(array):
for index in range(1,len(array)):
currentvalue = array[index]
position = index
while position>0 and array[position-1]>currentvalue:
array[position]=array[position-1]
position = position-1
array[position]=currentvalue
return array
| true |
f48416b78c2e6a29a4b041b843cd8de5d280a2b0 | anilgeorge04/cs50harvard | /python-intro/credit.py | 1,958 | 4.25 | 4 | # This software validates a credit card number entered by the user
# Validity checks: Format, Luhn's checksum algorithm*, Number of digits, Starting digit(s) with RegEx
# Output: It reports whether the card is Amex, Mastercard, Visa or Invalid
# *Luhn's checksum algorithm: https:#en.wikipedia.org/wiki/Luhn_algorithm
import re
def main():
card_type = {
1: "AMEX",
2: "MASTERCARD",
3: "VISA",
4: "INVALID"
}
# Get credit card number
cardnum = input("Number: ")
# check card length
if len(cardnum) == 13 or len(cardnum) == 15 or len(cardnum) == 16:
key = checkcard(cardnum)
else:
key = 4
print(card_type[key])
def checkcard(cardnum):
# check card meet Luhn's algorithm specs
# if yes, RegEx check on first digits of card
if luhn(int(cardnum)):
# AMEX starts with 34 or 37
if re.search("^3(4|7)*", cardnum):
return 1
# MASTERCARD starts with 51-55
elif re.search("^5[1-5]*", cardnum):
return 2
# VISA starts with 4
elif re.search("^4+", cardnum):
return 3
else:
return 4
else:
return 4
def luhn(cardnum):
last_digit, sum_odd, sum_prod_even, pos = 0, 0, 0, 1
num = cardnum
while num > 0:
last_digit = num % 10
# alternate numbers from right
if not pos % 2 == 0:
sum_odd += last_digit
# alternate numbers second from right
else:
sum_prod_even += (last_digit * 2) % 10
if last_digit * 2 >= 10:
# max number in 10s place can only be 1 (9*2=18)
sum_prod_even += 1
# remove last digit
num = (num - last_digit) / 10
pos += 1
# Luhn's algorithm check
if (sum_prod_even + sum_odd) % 10 == 0:
return True
else:
# print("Failed Luhn Algorithm check")
return False
main()
| true |
0cf8dabae652848b5d0ac46fd753e0ee977630ee | AjayMistry29/pythonTraining | /Extra_Task_Data_Structure/ETQ8.py | 831 | 4.1875 | 4 | even_list=[]
odd_list=[]
while True:
enter_input = int(input("Enter a number from from 1 to 50: "))
if enter_input>=1 and enter_input<=50 and (enter_input % 2) != 0 and len(odd_list)<5:
odd_list.append(enter_input)
print("Odd List :" ,odd_list)
continue
elif enter_input>=1 and enter_input<=50 and (enter_input % 2) == 0 and len(even_list)<5:
even_list.append(enter_input)
print("Even List :" ,even_list)
else:
print("Entered Number is out of range")
break
print("Sum of Even Numbers List is :", sum(even_list))
print("Sum of Odd Numbers List is :", sum(odd_list))
print("Maximum number from Even List is :", max(even_list))
print("Maximum number from Odd List is :", max(odd_list))
| true |
b7497ea31a107328ecb0242600df34d808483353 | AjayMistry29/pythonTraining | /Task4/T4Q2.py | 359 | 4.3125 | 4 | def upperlower(string):
upper = 0
lower = 0
for i in string:
if (i>='a'and i<='z'):
lower=lower+1
if (i>='A'and i<='Z'):
upper=upper+1
print('Lower case characters = %s' %lower,
'Upper case characters = %s' %upper)
string = input("Enter the String :")
upperlower(string) | true |
3fab33ec2b0ec5d95bcfefbab6c1b878d0c81daf | mrodzlgd/dc-ds-071519 | /Warm_Ups/number_finder.py | 766 | 4.25 | 4 | def prime_finder(numbers):
import numpy as np
prime=np.array([])
"""will select only the prime #'s from a given numpy array"""
for n in np.nditer(numbers):
if (n%2)>0:
prime = np.append(prime,n)
return prime
#a series of numbers in which each number ( Fibonacci number ) is the sum of the \n,
#two preceding numbers. The simplest is the series 1, 1, 2, 3, 5, 8, etc.\n,
def fibonacci_finder(numbers):
""""will select only the Fibonacci numbers from a given numpy array."""
import numpy as np
fib_nums=np.array([])
x=2 #index counter
for n in np.nditer(numbers[2:]):
if n == (numbers[x-1]+numbers[x-2]):
fib_nums = np.append(fib_nums,n)
x+=1
return fib_nums | true |
df78a002fdb80aa75916d98777f5036f53c24082 | mariololo/EulerProblems | /problem41.py | 1,162 | 4.25 | 4 | """
We shall say that an n-digit number is pandigital if it makes use of
all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
"""
def is_pandigital(n):
digits = []
for dig in str(n):
if dig in digits:
return 0
else:
digits.append(int(dig))
digits = sorted(digits)
if digits[0] == 1:
last = 1
if len(digits) == 1:
return 1
for dig in digits[1:]:
if dig != last + 1:
return 0
last = dig
return len(digits)
else:
return 0
from math import sqrt
def is_prime(a):
if a % 3 == 0:
return False
else:
for div in range(5, int(sqrt(a))+1, 2):
if a % div == 0:
return False
return True
def largest_pandigital():
print("Searching largest pandigital prime")
largest = float("-inf")
running = 9999999
while True:
if is_prime(running) and is_pandigital(running) > 0:
return running
running = running - 2
if running % 10000 == 0:
print(running)
if __name__ == "__main__":
print(largest_pandigital())
| true |
97cc0a8e13f2517cd8c55c0741cc5d94bfa4d7ea | AshTiwari/Standard-DSA-Topics-with-Python | /Array/Array_Merge_Sorted_Array_in_O(1)_Space.py | 772 | 4.28125 | 4 | # Merge two sorted array in O(1) time.
from binaryInsertion import binaryInsertion
######### Increase the Efficiency by using binaryInsertion function to add element in sorted arr2 ###########
def addElement(arr,element):
index = 0
# alternate way is to use binaryInsertion.
while(index < len(arr)-1):
if arr[index] > arr[index+1]:
arr[index], arr[index+1] = arr[index+1], arr[index]
index += 1
def swapAndSort(arr1,arr2):
index1 = 0
index2 = 0
while(index1 < len(arr1)):
if arr1[index1] > arr2[index2]:
arr1[index1], arr2[index2] = arr2[index2], arr1[index1]
temp_index2 = index2
addElement(arr2,arr1[index1])
index1 += 1
if __name__ == "__main__":
arr1 = [0,8,9,10,15]
arr2 = [1,3,9,11,14,16]
swapAndSort(arr1,arr2)
print(*arr1+arr2) | true |
835cfbcb2ebd756769226a1b3745427f70c17c50 | LucioOSilva/HackerRankPython-PS | /LinkedList-PrintTheElementsOfALinkedList.py | 1,868 | 4.375 | 4 | """
If you're new to linked lists, this is a great exercise for learning about them. Given a pointer to the head node of a
linked list, print its elements in order, one element per line. If the head pointer is null (indicating the list is
empty), don’t print anything.
Input Format:
The first line of input contains "n", the number of elements in the linked list.
The next "n" lines contain one element each, which are the elements of the linked list.
Note: Do not read any input from stdin/console. Complete the printLinkedList function in the editor below.
Constraints:
1 <= n <= 1000
1 <= list[i] <= 1000, where list[i] is the i[th] element of the linked list.
Output Format:
Print the integer data for each element of the linked list to stdout/console (e.g.: using printf, cout, etc.).
There should be one element per line.
Sample Input:
2
16
13
Sample Output:
16
13
Explanation:
There are two elements in the linked list. They are represented as 16 -> 13 -> NULL. So, the printLinkedList function
should print 16 and 13 each in a new line.
"""
class SinglyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_node(self, node_data):
node = SinglyLinkedListNode(node_data)
if not self.head:
self.head = node
else:
self.tail.next = node
self.tail = node
def printLinkedList(head):
cur = llist.head
while cur.next != None:
print(cur.data)
cur = cur.next
print(cur.data)
if __name__ == '__main__':
llist_count = int(input())
llist = SinglyLinkedList()
for _ in range(llist_count):
llist_item = int(input())
llist.insert_node(llist_item)
printLinkedList(llist.head)
| true |
8db7becd41ea2f645a1f523a662ca9715da4121b | MrKonrados/PythonTraining | /Change Calculator/change_calc.py | 1,369 | 4.3125 | 4 | """
BASIC GOAL Imagine that your friend is a cashier, but has a hard time counting back change to customers.
Create a program that allows him to input a certain amount of change, and then print how how many quarters, dimes,
nickels, and pennies are needed to make up the amount needed.
For example, if he inputs 1.47, the program will tell that he needs 5 quarters, 2 dimes, 0 nickels, and 2 pennies.
SUBGOALS
1. So your friend doesn't have to calculate how much change is needed, allow him to type in the amount of money
given to him and the price of the item. The program should then tell him the amount of each coin he needs
like usual.
2. To make the program even easier to use, loop the program back to the top so your friend can continue to use
the program without having to close and open it every time he needs to count change.
"""
from decimal import Decimal
coins = {
'quarter': Decimal(.25),
'dime': Decimal(.10),
'nickel': Decimal(.05),
'penny': Decimal(.01),
}
amount_money = Decimal(4.21)
price = Decimal(1.47)
price = amount_money - price
change = {}
for coin in sorted(coins, key=coins.__getitem__, reverse=True):
div, mod = divmod(price, coins[coin])
change[coin] = int(div)
price = Decimal(price) - Decimal(coins[coin] * div)
for c in change:
print(c,"\t=\t", change[c]) | true |
b017de724c850cdc2c2dd757d7508ee2083db0f6 | lmitchell4/Python | /ch_3_collatz.py | 428 | 4.3125 | 4 | ## Collatz sequence
def collatz(number):
if number % 2 == 0:
print(number // 2)
return(number // 2)
else:
print(3*number + 1)
return(3*number + 1)
inputOK = False
while not inputOK:
try:
print('Enter an integer to start the Collatz sequence:')
n = int(input())
inputOK = True
except ValueError:
print('That\'s not an integer! Try again below ...\n')
while n > 1:
n = collatz(n)
| true |
a95914f8996bc96b2e60ca8951bdeaf3611652d5 | igelritter/learning-python | /ex35-lphw.py | 2,759 | 4.125 | 4 | #This is basically a text style adventure. Each room is defined as a function
#as well as the starting and dying text.
#importing the exit function
from sys import exit
#gold room.
def gold_room():
print "This room is full of gold. How much do you take?"
next=(raw_input(">"))
#This 'if/else' statement is broken. It will only accept numbers with 1 or 0
#It does very little to figure out whether the user entered numbers or a string
## if "0" in next or "1" in next:
## how_much=int(next)
## else:
## dead("Man, learn to type a number.")
#what we need here is a try/except block. The try except attempts to convert the
#inputed string into an int. If it succeeds, then the int is evaluated for
#the next condition; if not, then the user gets a homemade error message--they die--
#and the program terminates.
try:
how_much=int(next)
except:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
EXIT (0)
else:
dead("You greedy bastard!")
#bear room
def bear_room():
print "There is a bear here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to move the bear?"
bear_moved = False
while True:
next = raw_input(">")
if next == "take honey":
dead("The bear looks at you then slaps your face off.")
elif next == "taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through it now."
bear_moved = True
elif next == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your leg off.")
elif next == "open door" and bear_moved:
gold_room()
else:
print "I got no idea what that means."
# cthulu room
def cthulu_room():
print "Here you see the great evil Cthulu."
print "He...it...whatever...stares at you and you go insane."
print "Do you flee for your life or eat your head?"
next = raw_input(">")
if "flee" in next:
start()
elif "head" in next:
dead("Well that was tasty")
else:
cthulu_room()
#dead() and start() functions
def dead(why):
print why,"Good job!"
exit (0)
def start():
print "You are in a dark room."
print "There is a door to your right and left."
print "Which one do you take?"
next = raw_input(">")
if next == "left":
bear_room()
elif next == "right":
cthulu_room()
else:
dead("you stumble around the room until you starve.")
#after all the function definitions, we get to the function call that starts
#the program
start()
| true |
95af2966515dd3cfca5459096762f8c0d5790ab3 | dao-heart/Leetcode-solutions | /pythonDataStructures/llist.py | 2,157 | 4.1875 | 4 | # Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
## Test the nodes
n1 = Node("Mon")
n2 = Node("Tues")
n1.next = n2
print(n1)
class LinkedList:
print_list = []
def __init__(self):
self.headval = None
def __repr__(self):
return "->".join(self.helperFunction(self.headval))
# IMPROV: Using generator instead of iterator.
# Recursive traversal and print linked list - O(n)
def helperFunction(self,node):
if node:
self.print_list.append(node.data)
self.helperFunction(node.next)
return self.print_list
# Insert at the front of the linked List - O(1)
def insertNodeStart(self,data):
NewNode = Node(data)
NewNode.next = self.headval
self.headval = NewNode
# Insert at the end of the linked list - O(n) transverse using while loop
def insertNodeEnd(self, data):
node = self.headval
NewNode = Node(data)
if node is None:
node = NewNode
while node.next is not None:
node = node.next
node.next = NewNode
# Insert at the middle of the list - O(1) traverse and swap pointers
def insertNodeMiddle(self, middle_node, new_data):
if middle_node is None:
print("The mentioned node is empty")
return
NewNode = Node(new_data)
NewNode.next = middle_node.next
middle_node.next = NewNode
# Delete the selected node. Need to traverse the list - O(n)
def removeNode(self, delete_node):
node = self.headval
target_node = self.delete_node(node,delete_node)
target_node.next = delete_node.next
delete_node = None
def del_helper_function(self, node, delete_node):
if node.next is delete_node:
retun node
else:
self.del_helper_function(node.next, delete_node)
#### Create a Linked List
l1 = LinkedList()
l1.headval = Node("Mon")
l2 = Node("Tues")
l1.headval.next = l2
l2.next = Node("Wed")
l1.insertNodeStart("Sun")
l1.insertNodeEnd("Fri")
l1.insertNodeMiddle(l2.next, "Thu")
print(l1)
| true |
06e0eeff8467efd1538056e984644ea665656c0c | mobbarley/python2x | /fizzbuzz.py | 559 | 4.3125 | 4 | # This program mocks the script for the game fizz - buzz where we print all the numbers
# from 1 to the number entered by the user but we say Fizz when number is divisible by 3
# and Buzz when it is divisible by 5, when it is both like in 15, 30 etc we will say FizzBuzz
num = int(raw_input("Enter a number : "))
if num < 0:
print "Invalid number ", num
else:
for ix in range(1,num+1):
text = ''
if ix%3 == 0:
text = text + "Fizz"
if ix%5 == 0:
text = text + "Buzz"
if text == '':
print ix
else:
print text
| true |
88663a9fba92b5e8ca7a0121d3fdfabea283cb05 | cindygao93/Dartboard | /assignment 2 third try.py | 2,469 | 4.1875 | 4 | ##this is a program in turtle that will draw a dart board
from turtle import *
def main() :
shape("turtle")
pendown()
pencolor("yellow")
pensize(5)
speed(20)
radius=200
subradius=0
forward(radius)
left(90)
sideCount = 0
color = "yellow"
while sideCount <80:
if sideCount>0 and sideCount<20:
if color == "yellow":
color = "black"
elif color== "black":
color="yellow"
if sideCount==20:
subradius=subradius+20
home()
forward(radius-subradius)
left(90)
if sideCount>20 and sideCount<40:
if color == "yellow":
color = "black"
elif color== "black":
color="yellow"
if sideCount==40:
subradius=subradius+80
home()
forward(radius-subradius)
left(90)
if sideCount>40 and sideCount<60:
if color == "yellow":
color = "black"
elif color== "black":
color="yellow"
if sideCount==60:
##stop
subradius=subradius+10
home()
forward(radius-subradius)
left(90)
if sideCount>60 and sideCount<80:
if color == "yellow":
color = "black"
elif color== "black":
color="yellow"
pencolor(color)
fillcolor(color)
circle(radius-subradius, 18)
pendown()
begin_fill()
left(90)
forward(radius-subradius)
left(162)
forward(radius-subradius)
end_fill()
left(90)
circle(radius-subradius,18)
penup()
sideCount = sideCount + 1
home()
forward(30)
begin_fill()
pencolor("black")
fillcolor("black")
left(90)
circle(30)
end_fill()
home()
forward(20)
begin_fill()
pencolor("red")
fillcolor("red")
left(90)
circle(20)
end_fill()
home()
main()
| true |
8dc6e4c41403953b42dde18cfb626598815bcee7 | rkuzmyn/DevOps_online_Lviv_2020Q42021Q1 | /m9/task9.1/count_vowels.py | 428 | 4.125 | 4 | vowels = 'aeiou'
def count_vowels(string, vowels):
# casefold() it is how lower() , but stronger
string = string.casefold()
# Forms a dictionary with key as a vowel
count = {}.fromkeys(vowels, 0)
# To count the vowels
for character in string:
if character in count:
count[character] += 1
return count
string = 'YaroslavVoloshchukISdevops'
print(count_vowels(string, vowels)) | true |
d643bffc1fc1c1c029543510b66c5a0b1bc77377 | slauney/Portfolio | /Python/InClassMarking/TC5/HighestCommonDivisor.py | 2,611 | 4.125 | 4 | ###########################################
# Desc: Highest Common Divisor
#
# Author: Zach Slaunwhite
###########################################
def main():
#initialize the continue condition
continueLoop = "y"
#while continue loop is equal to y, repeat the program
while(continueLoop == "y"):
#get the first number from the user
num1 = input("Enter the first number: ")
#if the input is not a number, ask the user until it is a number
while (not num1.isnumeric()):
print("ERROR! Enter a valid first number.")
num1 = input("Enter the first number: ")
#cast the input to an int (this is because we cannot initialize the input as an int, or else the while loop wouldn't work)
num1 = int(num1)
#get the second number from the user
num2 = input("Enter the second number: ")
#if the input is not a number, ask the user until it is a number
while (not num2.isnumeric()):
print("ERROR! Enter a valid second number.")
num2 = input("Enter the second number: ")
#cast the input to an int
num2 = int(num2)
#sort the min and max numbers (could use sort() instead?)
minNumber = min(num1, num2)
maxNumber = max(num1, num2)
#calling highest divisor function and catching the result
highestDivisor = getHighestCommonDivisor(minNumber, maxNumber)
print("The Highest Common Divisor of {} and {} is {}.\n".format(num1, num2, highestDivisor))
#ask user to repeat program
continueLoop = input("Would you like to try again? (y/n)").lower()
#End message once loop is exited
print("\nThank you for using HCD program.")
#this function is to get the highest common divisor of two numbers
def getHighestCommonDivisor(num1, num2):
#initialize variable for checking if there is a remainder
noRemainder = 0
rangeOffSet = 1
#initialize highest divisor
highestDivisor = 0
#loop to go through all possible divisors
for x in range(num1 + rangeOffSet):
#if the number is 0, continue (cannot divide by 0 or it breaks program)
if x == 0:
continue
#if the lowest number divided by x has no remainder, continue to second if statement
if (num1 % x) == noRemainder:
#if the highest number divided by x has no remainder, set highest divisor to x
if (num2 % x) == noRemainder:
highestDivisor = x
#returns the highest divisor
return highestDivisor
if __name__ == "__main__":
main() | true |
6c85d89a5becfcce7df81801b3cd511c82b829b8 | slauney/Portfolio | /Python/Labs/Lab04/ProvincialTaxes.py | 2,194 | 4.21875 | 4 | ###########################################
# Desc: Enter application description here.
#
# Author: Enter name here.
###########################################
def main():
# Constants
GST = 1.05
HARMONIZED_TAX = 1.15
# PROVINCIAL_TAX will be added onto GST to bring tax to 1.11
PROVINCIAL_TAX = 0.06
#addTax is false by default, and set later on if conditions are met
addTax = False
continueProgram = True
# Input
while continueProgram:
purchaseCost = float(input("Please enter the cost of your purchase: "))
customerCountry = input("Please enter the country you are from: ")
# Process
totalCost = purchaseCost
tax = 0
customerCountry = customerCountry.lower()
#adding tax if the country is canada
if customerCountry == "canada":
addTax = True
if addTax:
customerProvince = input("Please enter what province you are from: ")
#if province is alberta, set tax to 5% and calculate total cost
if customerProvince == "alberta":
tax = GST
#if the province is ontario, new brunswick, or nova scotia, set tax to 15% and calculate total cost
elif customerProvince == "ontario" or customerProvince == "new brunswick" or customerProvince == "nova scotia":
tax = HARMONIZED_TAX
#if the province is not any of the provinces listed above, set tax to 11% and calculate total cost
else:
tax = GST + PROVINCIAL_TAX
totalCost = purchaseCost * tax
#changing tax from decimal to percentage
tax = (tax - 1) * 100
# Output
print("\nYour total cost is ${:.2f}".format(totalCost))
print("Tax was {:.0f}%\n".format(tax))
#prompting user if they would like to run the program again
userContinue = input("Would you like to run this program again? (Yes/no): ")
userContinue = userContinue.lower()
if userContinue != "yes":
continueProgram = False
#PROGRAM STARTS HERE. DO NOT CHANGE THIS CODE.
if __name__ == "__main__":
main() | true |
df11e224537c2d5ea2aa747b7a71e12b0c4a975c | slauney/Portfolio | /Python/InClassMarking/TC2/taxCalculator.py | 1,638 | 4.25 | 4 | ###########################################
# Desc: Calculates the total amount of tax withheld from an employee's weekly salary (income tax?)
#
# Author: Zach Slaunwhite
###########################################
def main():
# Main function for execution of program code.
# Make sure you tab once for every line.
# Input
#prompt user for pre-tax weekly salary amount, and the number of dependants they wish to claim
salaryAmount = float(input("Please enter the full amount of your weekly salary: $"))
totalDependants = int(input("How many dependants do you have?: "))
# Process
#program calculates the provincial tax withheld, the federal tax withheld, the total tax withheld, and the users take home amount
#provincial tax: 6.0%
provTaxWithheld = salaryAmount*0.06
#federal tax: 25.0%
fedTaxWithheld = salaryAmount*0.25
#deduction amount: 2.0% of salary per dependant
taxDeduction = salaryAmount * (totalDependants * 0.02)
#calculate total tax withheld
totalTaxWithheld = provTaxWithheld + fedTaxWithheld - taxDeduction
#calculate total take home pay
takeHomePay = salaryAmount - totalTaxWithheld
# Output
print("Provincial Tax Withheld ${:.2f}".format(provTaxWithheld))
print("Federal Tax Withheld ${:.2f}".format(fedTaxWithheld))
print("Dependant deduction for {} dependants: {:.2f}".format(totalDependants, taxDeduction))
print("Total Withheld: ${:.2f}".format(totalTaxWithheld))
print("Total Take-Home Pay: ${:.2f}".format(takeHomePay))
#PROGRAM STARTS HERE. DO NOT CHANGE THIS CODE.
if __name__ == "__main__":
main()
| true |
067ba4d62b07896b1a484dc7a47a39d9aba968e7 | ggibson5972/Project-Euler | /euler_prob_1.py | 232 | 4.15625 | 4 | result = 0
#iterate from 1 to 1000
for i in range(1000):
#determine if i is a multiple of 3 or 5
if ((i % 3 == 0) or (i % 5 == 0)):
#if i is a multiple of 3 or 5, add to sum (result)
result += i
print result
| true |
052857681781833e79edd5eecb1e32b99f561749 | chmod730/My-Python-Projects | /speed_of_light.py | 944 | 4.375 | 4 |
'''
This will query the user for a mass in kilograms and outputs the
energy it contains in joules.
'''
SPEED_OF_LIGHT = 299792458 # c in m/s2
TNT = 0.00000000024 # Equivalent to 1 joule
def main():
print()
print("This program works out the energy contained in a given mass using Einstein's famous equation: E = mc2 ")
while True:
print()
mass = input("Please enter a mass in Kg: ")
energy = float(mass) * (float(SPEED_OF_LIGHT) ** 2)
boom = (float(energy) * TNT) / 1000000
boom = int(boom)
print()
print("E = mc2")
print("Mass = " + str(mass) + " Kg")
print("C = 299792458 m/s")
print("Energy = " + str(energy) + " joules")
print()
print("That's the same as " + str(boom) + " Megatons of TNT !! ")
# This provided line is required at the end of a Python file
# to call the main() function.
if __name__ == '__main__':
main() | true |
eb54fcd8f36e094f77bccdcebc0ae8230a2db34d | adneena/think-python | /Iteration/excercise1.py | 1,142 | 4.25 | 4 | import math
def mysqrt(a):
"""Calculates square root using Newton's method:
a - positive integer < 0;
x - estimated value, in this case a/2
"""
x = a/2
while True:
estimated_root = (x + a/x) / 2
if estimated_root == x:
return estimated_root
break
x = estimated_root
def test_square_root(list_of_a):
"""Displays outcomes of calculating square root of a using different methods;
list_of_a - list of positive digit.
"""
line1a = "a"
line1b = "mysqrt(a)"
line1c = "math.sqrt(a)"
line1d = "diff"
line2a = "-"
line2b = "---------"
line2c = "------------"
line2d = "----"
spacing1 = " "
spacing2 = " " * 3
spacing3 = ""
print(line1a, spacing1, line1b, spacing2, line1c, spacing3, line1d)
print(line2a, spacing1, line2b, spacing2, line2c, spacing3, line2d)
for a in list_of_a:
col1 = float(a)
col2 = mysqrt(a)
col3 = math.sqrt(a)
col4 = abs(mysqrt(a) - math.sqrt(a))
print(col1, "{:<13f}".format(col2), "{:<13f}".format(col3), col4)
test_square_root(range(1, 10)) | true |
3642cd6a682a9a05c2a5bc9c7597fd02af43a417 | adneena/think-python | /Fruitiful-functions/excercise-3.py | 856 | 4.34375 | 4 | '''
1. Type these functions into a file named palindrome.py and test them out. What happens if
you call middle with a string with two letters? One letter? What about the empty string,
which is written '' and contains no letters?
2. Write a function called is_palindrome that takes a string argument and returns True if it
is a palindrome and False otherwise. Remember that you can use the built-in function len
to check the length of a string
'''
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
def is_palindrome(word):
if len(word) <= 1:
return True
if first(word) != last(word):
return False
return is_palindrome(middle(word))
print(is_palindrome('adheena'))
print(is_palindrome('wow'))
print(is_palindrome('malayalam'))
print(is_palindrome('yellow'))
| true |
5674ddd6d622dad21e14352332cdb85bf7adf9fc | adneena/think-python | /variables-expressions-statements/excercise1.py | 520 | 4.375 | 4 | '''
Assume that we execute the following assignment statements:
width = 17
height = 12.0
delimiter = '.'
For each of the following expressions, write the value of the expression and the type (of the value of
the expression).
1. width/2
2. width/2.0
3. height/3
4. 1 + 2 * 5
5. delimiter * 5
'''
width = 17
height = 12.0
delimiter = '.'
x = width/2
print(x)
print(type(x))
y = width/2.0
print(y)
print(type(y))
z = height/3
print(z)
print(type(z))
p = 1+2*5
print(p)
print(type(p))
q = delimiter*5
print(q)
print(type(q)) | true |
5327e3c6d6563e1fe25572b838f7274c7524c7ba | 09jhoward/Revison-exercies | /task 2 temprature.py | 482 | 4.15625 | 4 | #08/10/2014
#Jess Howard
#development exercises
#write a program that reads in the temperature of water in a container(in centigrade and displays a message stating whether the water os frozen,boiling or neither.
temp= int(input(" Please enter the water temprature in the unit of centigrade:"))
if temp<= 0:
print(" Your water is currently frozen")
elif temp >=100:
print("Your water is currently boiling")
else:
print("Your water is niether froezen or boiling")
| true |
7aa43ddbb81ccbb9e8ad6fa74424dbe46fdeca35 | Wambita/pythonwork | /converter.py | 597 | 4.1875 | 4 | #Program to convert pounds to kilograms
#Prompt user to enter the first value in pounds
print("Enter the first value in pounds you wish to convert into kilograms")
pound1= float(input())
#prompt user to enter the second value in pounds
print("Enter the second value in pounds you wish to convert into kilograms")
pound2 = float(input())
#converting pounds to kgs
kgs1 = pound1/2.20462
kgs2 = pound2/2.20462
#display the results
print("Results")
print(" ")
print("The weight in kgs of" ,pound1, " pounds is",round(kgs1,3))
print("The weight in kgs of" ,pound2, " pounds is",round(kgs2,3))
| true |
e0aea95c21e5134bef5cf6501033d9b9d7d8119a | hwichman/CYEN301 | /KeyedCaesar/KeyedCaesar.py | 1,330 | 4.21875 | 4 | import sys
alphabet = "abcdefghijklmnopqrstuvwxyz"
### Main ###
# Check for arguments
if sys.argv < 3:
raise Exception("CaesarCipher.py <1-25> <alphabetKey>")
try:
# Make sure second argument is an int
numKey = int(sys.argv[1])
except:
print "Key must be an integer."
alphaKey = sys.arv[2]
# New alphabet the cipher will use
# Starts with the alphaKey
# Each character in the alphabet not in the alphaKey is added to the end of the alphaKey
for character in alphabet:
if character not in alphaKey:
alphaKey += character
# Get user input for encoded text
cypherText = raw_input()
# Split cypherText up by spaces
cypherText = cypherText.split(" ")
plainText = []
# Decode each word based on the key and add it to the plainText list
for word in cypherText:
plainWord = ""
for character in word:
# Shift index of character by key.
x = alphaKey.index(character)
x = (x - numKey) % 26
# Decrypted character is the character at the new index
character = alphaKey[x]
# Add character to decrypted word
plainWord.append(character)
plainWord = "".join(plainWord)
plainText.append(plainWord)
# Join everything together and print it
# Make everything lowercase because Caesar() prints it in upper
print " ".join(plainText).lower() | true |
2a4a4034e78d0dca4a5e3429fc29e0df2cfbb35e | popovata/ShortenURL | /shorten_url/app/utils.py | 393 | 4.21875 | 4 | """
A file contains utility functions
"""
import random
import string
LETTERS_AND_DIGITS = string.ascii_letters + string.digits
def get_random_alphanumeric_string(length):
"""
Generates a random string of the given length
:param length: length of a result string
:return: a random string
"""
return ''.join(random.choice(LETTERS_AND_DIGITS) for i in range(length))
| true |
f2fba366bd724b0bbcb6d9ef80cad1edcb1e546e | AswinSenthilrajan/PythonRockPaperScissor | /PaperStoneScissor/StonePaperScissor.py | 848 | 4.1875 | 4 | from random import randrange
options = ["Scissor", "Stone", "Paper"]
random_number = randrange(3)
user_option = input("Choose between Paper, Scissor and Stone:")
computer_option = options[random_number]
def play():
if computer_option == user_option:
user_optionNew = input("Choose again:")
elif computer_option == "Scissor" and user_option == "Stone" or computer_option == "Stone" and user_option == "Paper" \
or computer_option == "Paper" and user_option == "Scissor":
print("You won")
print("Computer: " + computer_option)
elif computer_option == "Scissor" and user_option == "Paper" or computer_option == "Stone" and user_option == "Scissor" \
or computer_option == "Paper" and user_option == "Stone":
print("You lost")
print("Computer: " + computer_option)
play()
| true |
2311b07ae564fd53cabee5532a39392c9e86793c | hiteshvaidya/Football-League | /football.py | 2,397 | 4.25 | 4 | # Football-League
#This is a simple python program for a Football League Management System. It uses sqlite and tkinter for managing database and UI.
#created by Hitesh Vaidya
from tkinter import *
import sqlite3
class App:
def __init__(self,master):
frame = Frame(master)
frame.pack()
a=StringVar()
b=StringVar()
a1=StringVar()
b1=StringVar()
c=StringVar()
self.button=Button(frame, text='Open Db', fg='red', command=self.ouvrir) #ouvrir method called by command on mouse click
self.button.pack(side=LEFT)
self.button2=Button(frame, text='Create Table',fg='green', command=self.tabluh) #tabluh method called by command on click
self.button2.pack(side=LEFT)
self.button3=Button(frame,text='Close Db',fg='blue',command=self.ferver) #ferver method called on click
self.button3.pack(side=LEFT)
self.button4=Button(frame,text='Insert Rec',command=self.insertar)
self.button4.pack(side=LEFT)
self.button5=Button(frame,text='List Recs',command=self.listar)
self.button5.pack(side=LEFT)
self.a=Entry(frame)
self.a.pack(side=BOTTOM)
self.b=Entry(frame)
self.b.pack(side=BOTTOM)
self.c=Entry(frame)
self.c.pack(side=BOTTOM)
def ouvrir(self):
#method which makes database.Its name may change
self.con=sqlite3.connect('footballdb')
self.cur=self.con.cursor()
def tabluh(self):
#method for creating table.Name may vary
#self.cur = self.con.cursor()
self.cur.execute('''CREATE TABLE team(
team_id INTEGER,
team_name stringvar(20),
team_players INTEGER)''')
def ferver(self):
self.con.close()
def insertar(self):
#self.con=sqlite3.connect('footballdb') #doubt=why these 2 lines
#self.cur=self.con.cursor() #are again needed? not in original code
a1=self.a.get()
b1=self.b.get()
c1=int(self.c.get())
self.cur.execute('''insert into team(team_id,team_name,team_players) values(?,?,?)''',(c1,a1,b1))
self.con.commit()
def listar(self):
self.cur.execute('SELECT * FROM team')
print(self.cur.fetchall())
root = Tk()
root.title('Dbase R/W')
root.geometry('700x300')
app = App(root)
root.mainloop()
| true |
2224d73582b20f4542eb637c3a40579571ed4ac3 | azzaHA/Movie-Trailer | /media.py | 1,220 | 4.21875 | 4 | """
Define Movie class to encapsulate movies attributes and methods
"""
class Movie():
"""
Define attributes and methods associated to Movie objects
* Attributes:
title (string): Movie name
story_line (string): Brief summary of the movie
trailer_youtube_id (string): trailer ID on youtube
poster_image_url (string): link to movie's poster image
* Methods:
__init__: instantiates a new Movie object with passed arguments
serialize: serializes Movie object to its JSON representation
"""
def __init__(self, movie_name, movie_story_line, movie_youtube_trailer_id,
movie_poster_url):
"""Generate a movie object and assign its value"""
self.title = movie_name
self.story_line = movie_story_line
self.trailer_youtube_id = movie_youtube_trailer_id
self.poster_image_url = movie_poster_url
def serialize(self):
"""serialize Movie object to its JSON representation"""
return{
'title': self.title,
'story_line': self.story_line,
'trailer_youtube_id': self.trailer_youtube_id,
'poster_image_url': self.poster_image_url
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.