blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
01d9fb6b2beaaf0ec20b04968465667abf6e7a42 | ivan-yosifov88/python_basics | /Nested Conditional Statements/03. Flowers.py | 954 | 4.125 | 4 | numbers_of_chrysanthemums = int(input())
number_of_roses = int(input())
number_of_tulips = int(input())
season = input()
is_day_is_holiday = input()
chrysanthemums_price = 0
roses_price = 0
tulips_price = 0
bouquet_price = 0
if season == "Spring" or season == "Summer":
chrysanthemums_price = 2
roses_price = 4.1
tulips_price = 2.5
elif season == "Autumn" or season == "Winter":
chrysanthemums_price = 3.75
roses_price = 4.5
tulips_price = 4.15
bouquet_price = numbers_of_chrysanthemums * chrysanthemums_price + number_of_roses * roses_price + number_of_tulips * tulips_price
if is_day_is_holiday == "Y":
bouquet_price *= 1.15
if number_of_tulips > 7 and season == "Spring":
bouquet_price *= 0.95
if number_of_roses >= 10 and season == "Winter":
bouquet_price *= 0.9
if (number_of_roses + number_of_tulips + numbers_of_chrysanthemums) > 20:
bouquet_price *= 0.8
bouquet_price += 2
print(f"{bouquet_price:.2f}")
| true |
bc1e774ca217588ba4a73263971168008f430fe0 | ivan-yosifov88/python_basics | /Exams -Training/05. Movie Ratings.py | 706 | 4.15625 | 4 | import sys
number_of_films = int(input())
max_rating = 0
movie_with_max_rating = ""
min_rating = sys.maxsize
movie_with_min_rating = ""
total_sum = 0
for films in range(number_of_films):
movie_title = input()
rating = float(input())
total_sum += rating
if rating > max_rating:
max_rating = rating
movie_with_max_rating = movie_title
if rating < min_rating:
min_rating = rating
movie_with_min_rating = movie_title
average_rating = total_sum / number_of_films
print(f"{movie_with_max_rating} is with highest rating: {max_rating:.1f}")
print(f"{movie_with_min_rating} is with lowest rating: {min_rating:.1f}")
print(f"Average rating: {average_rating:.1f}")
| true |
c61bb81014dba0334bb13516bd8044cc520bde54 | Williano/Solved-Practice-Questions | /MaleFemalePercentage.py | 1,308 | 4.1875 | 4 | # Script: MaleFemalePercentage.py
# Description: This program ask the user for the number of males and females
# registered in a class. The program displays the percentage of
# males and females in the class.
# Programmer: William Kpabitey Kwabla
# Date: 11.03.17
# Declaring the percentage variable for the percentage of the students.
PERCENTAGE = 100
# Defining the main function
def main():
# Asking the user for the number of males in the class.
males = int(input("Please enter the number of males in the class: "))
# Asking the user for the number of females in the class.
females = int(input("Please enter the number of females in the class: "))
# Calculating the total of the number of males and females.
total_students = males + females
# Finding the percentage of males.
percentage_of_males = (males / total_students) * PERCENTAGE
# Finding the percentage of females.
percentage_of_females = (females / total_students) * PERCENTAGE
# Displaying the total percentage to the user.
print("The percentage of males in the class is: ", format(percentage_of_males, ".0f"))
print("The percentage of females in the class is: ", format(percentage_of_females, ".0f"))
# Calling the main function to start execution of the program.
main()
| true |
2582a618219a2e0d3d43d30273d576a824303311 | Williano/Solved-Practice-Questions | /mass_and_weight.py | 1,791 | 4.71875 | 5 | # Scripts : mass_and_weight
# Description : This program asks the user to enter an object’s mass,
# and then calculates its weight using
# weight = mass * acceleration due to gravity.
# If the object weighs more than 1,000 newtons,
# it displays a message indicating that it is too heavy.
# If the object weighs less than 10 newtons,
# it display a message indicating that it is too light.
# Programmer : William Kpabitey Kwabla
# Date : 19.05.16
# Declaring gravity,maximum and minimum weight as Constants and assigning values to them.
ACCELERATION_DUE_TO_GRAVITY = 9.8
MAXIMUM_WEIGHT = 1000
MINIMUM_WEIGHT = 10
# Defining the main function
def main():
print("This program asks the user to enter an object’s mass,")
print("and then calculates its weight using")
print("weight = mass * acceleration due to gravity.")
print("If the object weighs more than 1,000 newtons,")
print("it displays a message indicating that it is too heavy.")
print("If the object weighs less than 10 newtons,")
print("it display a message indicating that it is too light.")
print()
# Asking User to enter object's mass and assigning to the Mass variable.
mass = float(input("Please Enter the Mass of the Object: "))
print()
# Calculating Objects weights using weight = mass * acceleration due to gravity.
weight = mass * ACCELERATION_DUE_TO_GRAVITY
print("The weight of the object is", weight,"Newton")
print()
# Determining whether the object is heavier or light in this manner.
if weight > MAXIMUM_WEIGHT or weight < MINIMUM_WEIGHT:
print("Object is too heavy ")
else:
print("Object is too light ")
# Calling the main function.
main()
| true |
5086ee66505c76e27be7738c6022065c451771bb | Williano/Solved-Practice-Questions | /MultiplicationTable.py | 2,041 | 4.3125 | 4 | # Script: MultiplicationTable.py
# Description: This program ask for a number and limit and generates
# multiplication table for it.
# Programmer: William Kpabitey Kwabla
# Date: 20.07.16
# Defines the main function.
def main():
# Calls the intro function
intro()
# Declares variable for repeating the loop.
keep_going = 'Y' or 'y'
# Loop for asking user for another input.
while keep_going == 'Y' or keep_going == 'y':
print()
# Asks user for the limit
limit = int(input("\t\t\tPlease Enter the limit you want to display to: "))
# Asks user for the number
number = int(input("\t\t\tPlease Enter the number you want to display the multiplication table of : "))
print()
# Displays the heading.
print("\t\t\t\t\t\tMultiplication of ", number)
print("\t\t\t\t\t************************************")
# Calls the multiplication function.
multiplication(limit, number)
# Asks User if he/she wants to check for another number.
keep_going = input("\t\t\tDo you want to check for another number ? Yes = y or Y No = N or n: ")
# Defines the intro function to display what the program does.
def intro():
print("\t\t\t*********************************************************")
print("\t\t\t*\tThis program ask for a number and limit and \t*")
print("\t\t\t*\tgenerates multiplication table for it. \t*")
print("\t\t\t*********************************************************")
# Defines the multiplication function and using the num_limit and number_choice as parameter variables.
def multiplication(num_limit, number_choice):
# Loops and displays the multiplication table
for num in range( num_limit + 1 ):
ans = num * number_choice
print('\t\t\t\t\t\t', num, "X", number_choice, "=" ,ans)
print()
# Calls the main function.
main()
| true |
596e39993129339fa272c671b82d43c35ccaf17e | Akarshit7/Python-Codes | /Coding Ninjas/Conditionals and Loops/Sum of even & odd.py | 284 | 4.15625 | 4 | # Write a program to input an integer N
# and print the sum of all its even
# digits and sum of all its odd digits separately.
N = input()
total = 0
evens = 0
for c in N:
c = int(c)
total += c
if c % 2 == 0:
evens += c
odds = total - evens
print(evens, odds)
| true |
4dfe380f00ab58f5741096abaf9493e869792cef | kelvDp/CC_python-crash_course | /chapter_5/toppings.py | 2,546 | 4.4375 | 4 | requested_topping = 'mushrooms'
# checks inequality: so if the req_topping is NOT equal to anchovies, then it will print the message
if requested_topping != 'anchovies':
print("Hold the anchovies!")
# you can check whether a certain value is in a list, if it is the output will be true, and if not --> false:
more_toppings = ['mushrooms', 'onions', 'pineapple']
# so you can ask :
# "mushrooms" in more_toppings -->true because it is in the list
# "pepperoni" in more_toppings --> false
# you can use multiple if statements to test multiple conditions :
more_requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in more_requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in more_requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in more_requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")
# this checks to see whether all checks passes whereas if you used elif etc it will stop running after one test passes.
# Checking for special items:
toppings = ['mushrooms', 'green peppers', 'extra cheese']
for topping in toppings:
print(f"Adding {topping}.")
print("\nFinished making your pizza!")
# But what if the pizzeria runs out of green peppers? An if statement inside
# the for loop can handle this situation appropriately:
for topping in toppings:
if topping == 'green peppers':
print("Sorry, we are out of green peppers right now.")
else:
print(f"Adding {topping}.")
print("\nFinished making your pizza!")
# Checking that a list is not empty :
just_more_toppings = [] #if empty --> false , if full --> true
if just_more_toppings: #if there are items in list
for requested_topping in just_more_toppings:
print(f"Adding {requested_topping}.") #loop through and print toppings
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?") #if list empty (it is) then it will ask if the person wants a plain pizza
# Using multiple lists:
available_toppings = ['mushrooms', 'olives', 'green peppers','pepperoni', 'pineapple', 'extra cheese']
requested_toppings_list = ['mushrooms', 'french fries', 'extra cheese']
# this will loop through both lists and check to see if items in the one are in the other
for requested_topping in requested_toppings_list:
if requested_topping in available_toppings:
print(f"Adding {requested_topping}.")
else:
print(f"Sorry, we don't have {requested_topping}.")
print("\nFinished making your pizza!")
| true |
630e926f49514037051c98cded41250dc8c12f11 | kelvDp/CC_python-crash_course | /chapter_10/word_count.py | 929 | 4.4375 | 4 | def count_words(file):
"""Counts the approx number of words in a file"""
try:
with open(file,encoding="utf-8") as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, but this file {file} does not exist here...")
else:
words = contents.split()
num_words = len(words)
print(f"The file {file} has about {num_words} words.")
file_name = "alice.txt"
count_words(file_name)
# In the previous example, we informed our users that one of the files was
# unavailable. But you don’t need to report every exception you catch.
# Sometimes you’ll want the program to fail silently when an exception occurs
# and continue on as if nothing happened. To make a program fail silently,
# you write a try block as usual, but you explicitly tell Python to do nothing in
# the except block. Python has a pass statement that tells it to do nothing in a
# block.
| true |
fcefa167431b4e2efd08e9f95b43fb57cf3bd37b | kelvDp/CC_python-crash_course | /chapter_2/hello_world.py | 469 | 4.5 | 4 | #can simply print out a string without adding it to a variable:
#print("Hello Python World!")
#or can assign it to a variable and then print the var:
message= "Hello Python world!"
print(message)
#can print more lines:
message_2="Hello Python crash course world!!"
print(message_2)
#code that generates an error :
# another_message="This is another message"
# print(nother_mesage) #this will create an error because the variable name in the print is misspelled.
| true |
59cdb01876a7669b21e7d9f71920850a2a88091c | kelvDp/CC_python-crash_course | /chapter_3/cars.py | 919 | 4.75 | 5 | cars = ['bmw', 'audi', 'toyota', 'subaru']
#this will sort the list in alphabetical order but permanently, so you won't be able to sort it back:
cars.sort()
print(cars)
# You can also sort this list in reverse alphabetical order by passing the
# argument reverse=True to the sort() method. The following example sorts the
# list of cars in reverse alphabetical order:
cars.sort(reverse=True)
print(cars)
print("\n")
#you can sort the list values only for printing/output without changing the list permanently by using sorted instead of sort:
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
print("\n")
#you can reverse a list with the reverse method:
print(cars)
cars.reverse() #this also changes list permanently , but can just apply reverse again if you want normal list
print(cars)
print("\n")
| true |
9a6c01e73c78e5c039f7b4af55924e22b1d4ca85 | kelvDp/CC_python-crash_course | /chapter_4/dimensions.py | 542 | 4.21875 | 4 | dimensions = (200, 50)
#tuples are basically same as lists but they are immutable which means you can't change them without re-assigning the whole thing
print(dimensions[0])
print(dimensions[1])
print("\n")
#!!! cant do this : dimensions[0] = 250 !!!
#you can loop through them just like a list
#this is how to change a tuple:
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
print("\n")
#new tuple:
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension) | true |
906a57cb5b9813652c9d66960ab30f157c769421 | kelvDp/CC_python-crash_course | /chapter_10/write_message.py | 1,615 | 4.84375 | 5 | # To write text to a file, you need to call open() with a second argument telling
# Python that you want to write to the file.
filename = "programming.txt"
with open(filename,"w") as file_object:
file_object.write("I love programming!")
# The second
# argument, 'w', tells Python that we want to open the file in write mode.
# You
# can open a file in read mode ('r'), write mode ('w'), append mode ('a'), or a mode
# that allows you to read and write to the file ('r+').
# It opens in read mode automatically if you don't pass in an argument.
# The open() function automatically creates the file you’re writing to if it
# doesn’t already exist.
# Be careful opening a file in write mode ('w')
# because if the file does exist, Python will erase the contents of the file before
# returning the file object.
# The write() function doesn’t add any newlines to the text you write. So if you
# write more than one line without including newline characters, your file may
# not look the way you want it to.
# ----------APPENDING TO A FILE------------
# If you want to add content to a file instead of writing over existing content,
# you can open the file in append mode. When you open a file in append mode,
# Python doesn’t erase the contents of the file before returning the file object.
# Any lines you write to the file will be added at the end of the file. If the file
# doesn’t exist yet, Python will create an empty file for you.
with open(filename,"a") as f:
f.write("I also love finding meaning in large datasets. \n")
f.write("I love creating apps that can run in a browser.\n")
| true |
8f732d671d158a32dfa7e691f588bef489b74ae8 | beffiom/Learn-Python-The-Hard-Way | /ex6.py | 1,204 | 4.71875 | 5 | # initializing a variable 'types_of_people' as an integer
types_of_people = 10
# initializing a variable 'x' as a formatted string with an embedded variable
x = f"There are {types_of_people} types of people."
# initializing a variable 'binary' as a string
binary = "binary"
# initializing a variable 'do_not' as a string
do_not = "don't"
# initializing a variable 'y' as a formatted string with two embedded variables
y = f"Those who know {binary} and those who {do_not}."
# printing x
print(x)
# printing y
print(y)
# printing a formatted string with embedded variable x
print(f"I said: {x}")
# printing a formatted string with embedded variable y
print(f"I also said: '{y}'")
# initializing a variable 'hilarious' as binary value False
hilarious = False
# initializing a variable 'joke_evualation' as a string
joke_evaluation = "Isn't that joke so funny?! {}"
# printing joke_evaluation formatted with hilarious as an embedded variable
print(joke_evaluation.format(hilarious))
# initializing a variable 'w' as a string
w = "This is the left side of..."
# initializing a variable 'e' as a string
e = "a string with a right side."
# printing a concatenated string combining 'w' and 'e'
print(w+e)
| true |
cd1e137d53325fcd2f7084654877b0c10646ae40 | sitaramsawant2712/Assessment | /python-script/problem_1_solution_code.py | 926 | 4.34375 | 4 | """
1. If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
(Answer: 233168) (solution code attached: problem_1_solution_code.py)
"""
def natural_number_multi_three_and_five(lower, upper):
'''
@description : Calculate the sum of all the multiples of 3 or 5 as per given param.
'''
sum_of_multiple = 0
for i in range(lower, upper):
if (i % 3 == 0) or (i % 5 == 0):
sum_of_multiple += i
return sum_of_multiple
if __name__ == '__main__':
lower = int(input("Enter lower range limit:"))
upper = int(input("Enter upper range limit:"))
sum_of_multiple = natural_number_multi_three_and_five(lower, upper)
output = "Sum of all the multiples of 3 or 5 below {0}. \n(Answer : {1})".format(upper, sum_of_multiple)
print(output)
| true |
cc7a50c93dded63e648a1e0f3c627cf0e490b207 | OngZhenHui/Sandbox_Prac3 | /ascii_table.py | 1,054 | 4.1875 | 4 | def main():
character = str(input("Enter a character: "))
print("The ASCII code for {} is {}".format(character, ord(character)))
lower_limit = 33
upper_limit = 127
number = get_number(lower_limit, upper_limit)
print("The character for {} is {}".format(number, chr(number)))
for i in range(lower_limit, upper_limit + 1):
print("{0:>5} {1:>5}".format(i, chr(i)))
print("How many columns do you want to print?")
upper_limit = lower_limit + int(input(">>>"))
for i in range(lower_limit, upper_limit):
print("{0:>5} {1:>5}".format(i, chr(i)))
def get_number(lower_limit, upper_limit):
valid = False
while valid == False:
try:
number = int(input("Enter a number between 33 to 127: "))
if number < lower_limit or number > upper_limit:
print("Invalid number; number is out of range")
else:
valid = True
except ValueError:
print("Invalid input; input is not an integer")
return number
main() | true |
d9d43b943dd3dd38d8c0584f1fac139ad181b38c | aJns/cao19 | /E4/ex04_01.py | 1,970 | 4.21875 | 4 | """
This coding exercise involves checking the convexity of a piecewise linear function.
You task is to fill in the function "convex_check".
In the end, when the file is run with "python3 ex04_01.py" command, it should display the total number of convex functions.
"""
# basic numpy import
import numpy as np
import time
import matplotlib.pyplot as plt
# random seed fix, do not change this
np.random.seed(0)
initial_func_val = 0 # initial function value which is f(0)=0
# this creates an array of slopes to be checked
slopes_array = np.random.randint(10, size=(100, 5))
# each row within slopes array represents the sequence of slopes m_i's
# m_i represents the slope within the interval (t_i,t_{i+1})
# for example: m_1 = slopes[0] is the slope within [a,t_1]
# List of 5 Break points
# a = t_1 = 0, t_2 = 20, t_3 = 40, t_4 = 60, b = t_5 = 100
# we collect all the points into the following list
break_points = [0, 20, 40, 60, 80, 100]
# Helpful for visualization
def plot_function(slopes, break_points):
x = np.array(break_points)
y = np.array([x[0]])
for i in range(len(slopes)):
new_y = y[i] + slopes[i] * (x[i + 1] - x[i])
y = np.append(y, new_y)
plt.plot(x, y)
plt.show()
def convex_check(slopes, break_points):
"""Checks if the function is convex or not.
Arguments:
slopes {np.array} -- List of Slopes
break_points {np.array} -- List of Breakpoints
"""
convexity = True
# If the slope is smaller than the last one, the function is non-convex
prev_slope = slopes[0]
for slope in slopes[1:]:
if slope < prev_slope:
convexity = False
break
else:
prev_slope = slope
return convexity
convex_func_count = 0
for slopes in slopes_array:
if convex_check(slopes, break_points):
convex_func_count += 1
else:
pass
print('Number of convex functions: ', convex_func_count)
| true |
ca00bc72743cb5168f449a4e7032d3cfdcb884c4 | mikeykh/prg105 | /13.1 Name and Address.py | 2,405 | 4.25 | 4 | # Write a GUI program that displays your name and address when a button is clicked (you can use the address of the school). The program’s window should appear as a sketch on the far left side of figure 13-26 when it runs. When the user clicks the Show Info button, the program should display your name and address as shown in the sketch on the right of the figure.
import tkinter
class MyGUI:
def __init__(self):
# Create main window
self.main_window = tkinter.Tk()
# Create StringVar objects to display name,
# street, and city-state-zip
self.name_value = tkinter.StringVar()
self.street_value = tkinter.StringVar()
self.csz_value = tkinter.StringVar()
# Create two frames
self.info_frame = tkinter.Frame(self.main_window)
self.button_frame = tkinter.Frame(self.main_window)
# Create the label widgets associated with the StringVar objects
self.name_label = tkinter.Label(self.info_frame,
textvariable=self.name_value)
self.street_label = tkinter.Label(self.info_frame,
textvariable=self.street_value)
self.csz_label = tkinter.Label(self.info_frame,
textvariable=self.csz_value)
# Pack the labels
self.name_label.pack()
self.street_label.pack()
self.csz_label.pack()
# Create two buttons
self.show_info_button = tkinter.Button(self.button_frame,
text='Show Info',
command=self.show)
self.quit_button = tkinter.Button(self.button_frame,
text='Quit',
command=self.main_window.destroy)
# Pack the buttons
self.show_info_button.pack(side='left')
self.quit_button.pack(side='right')
# Pack the frames
self.info_frame.pack()
self.button_frame.pack()
# Enter the tkinter main loop
tkinter.mainloop()
# Callback function for the Show Info button
def show(self):
self.name_value.set('Michael Harris')
self.street_value.set('8900 US-14')
self.csz_value.set('Crystal Lake, IL 60012')
# Create an instance of the MyGUI class
my_gui = MyGUI()
| true |
a2f82639d7a3d84317e5d0c3bfe6e5d8b9ea91dc | mikeykh/prg105 | /Automobile Costs.py | 2,135 | 4.59375 | 5 | # Write a program that asks the user to enter the
# monthly costs for the following expenses incurred from operating
# his or her automobile: loan payment, insurance, gas, oil, tires and maintenance.
# The program should then display the total monthly cost of these expenses,
# and the total annual cost of these expenses.
# Assign meaningful names to your functions and variables.
# Every function also needs a comment explaining
# what it does and what other function it works with.
# Function 1:
# Gather information from user
# Accumulate the total in a local variable
# Print the monthly costs on screen, formatted appropriately for money
# Pass the monthly cost to Function 2
# Function 2:
# Accepts a float parameter
# Calculates yearly cost by multiplying monthly cost by 12
# Displays the yearly cost on screen, formatted appropriately for money
def calculate_total_monthly_cost():
# This function is used to gather all of the information,
# adds all of the users inputs and sets the sum to a variable,
# passes the variable to the function calculate_total_yearly_cost,
# and calls the function calculate_total_monthly_cost.
loan = float(input("Please enter your car payment: "))
insurance = float(input("Please enter your the amount of your insurance payment: "))
gas = float(input("Please enter your monthly gas expense: "))
oil = float(input("Please enter your monthly oil expense: "))
tire = float(input("Please enter your monthly expense for tires: "))
maintenance = float(input("Please enter your monthly maintenance expense: "))
total_monthly_cost = loan+insurance+gas+oil+tire+maintenance
print("This is the total monthly cost: $", format(total_monthly_cost, ",.2f"), sep="")
calculate_total_yearly_cost(total_monthly_cost)
def calculate_total_yearly_cost(total_monthly_cost):
# This function calculates and prints the total yearly cost
# and is called by the function calculate_total_monthly_cost.
yearly_total = total_monthly_cost * 12
print("This is the yearly cost: $", format(yearly_total, ',.2f'), sep="")
calculate_total_monthly_cost()
| true |
f2b94660239c6fa96843a0d999ffe0c40b13bfa4 | shadiqurrahaman/python_DS | /tree/basic_tree.py | 1,644 | 4.15625 | 4 | from queue import Queue
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
self.queue = Queue()
def push_tree(self,data):
new_node = Node(data)
if self.root is None:
self.root = new_node
self.queue.put(self.root)
else:
recent_node = self.queue.get()
if recent_node.left and recent_node.right is not None:
recent_node = self.queue.get()
if recent_node.left is None:
recent_node.left = new_node
self.queue.put(recent_node)
self.queue.put(recent_node.left)
elif recent_node.right is None:
self.queue.put(recent_node)
recent_node.right = new_node
self.queue.put(recent_node.right)
def print_tree(self):
self.q = Queue()
self.q.put(self.root)
while(self.q.qsize()!=0):
temp = self.q.get()
print(temp.data)
if temp.left != None:
self.q.put(temp.left)
if temp.right != None:
self.q.put(temp.right)
def print_hudai(self):
temp = self.root
print(temp.left.left.data)
if __name__ == "__main__":
tree = Tree()
tree.push_tree(10)
tree.push_tree(11)
tree.push_tree(9)
tree.push_tree(7)
tree.push_tree(15)
tree.push_tree(8)
tree.print_tree()
tree.print_hudai()
| true |
2699742da7500f56858626be9c6369a58c96f0ed | jyoshnalakshmi/python_examples | /file_handling/file_write.py | 691 | 4.25 | 4 | #--------------------------------------------------------------------
#Description : Writing into the file
#Used Function : write()
#Mode : 'w'
#--------------------------------------------------------------------
with open('file1.py','w') as f:
print("write(This is write function using 'w')");
f.write("Hey this the write function");
#--------------------------------------------------------------------
#Description : Adding data into the file
#Used Function : write()
#Mode : 'a'
#--------------------------------------------------------------------
with open('file1.py','a') as f:
print("write(writing data using append it at the end)");
f.write("--Adding this line --");
| true |
10b02c26c2f09f703ce16eab5d8a0183677d8fb2 | dhiraj1996-bot/Code-a-Thon | /list.py | 502 | 4.125 | 4 | #Question 2
list1 = ["aman","raj","ayush","gracie"]
list2 = ["akshay","rakesh","raj","ram"]
#creating a function to check for duplicate values and then removing them
#and creating list without the duplicate values
def find_common(list1,list2):
for x in list1:
for y in list2:
if x == y :
list2.remove(x)
list1.remove(y)
print(" list1:",list1)
print(" list2:",list2)
print(" new_list:",list1+list2)
find_common(list1,list2)
| true |
dd52c000cd4d5d7a021449a7451de4fa84047042 | nkuhta/Python-Data-Structures | /2. Files/average_spam_confidence.py | 938 | 4.125 | 4 | ##############################################################
######### compute the average spam ############
##############################################################
# X-DSPAM-Confidence:0.8475
# Prompt for user input filename then search for the number and average
fname=input('Enter filename: ')
try:
fhand = open(fname)
except:
print("file does not exist")
exit()
# line iteration variable
count=0
# spam value iteration variable that will be summed over
num=0
# extract the spam confidence values and average them
for line in fhand:
if line.startswith("X-DSPAM-Confidence"):
# index value for the ":" chararcter
ival = line.find(":")
# numline is the number after the ":"
numline = float(line[ival+1:].lstrip())
count = count+1
num = num + numline
avg = num/count
print('count = ',count)
print('average spam confidence = ',avg)
| true |
b4846a2a1d6db0d4cbc3bb5a9097c509af4484a5 | nitschmann/python-lessons | /04_list_manipulations/exc_18.py | 374 | 4.25 | 4 | # list manipulations - exercise 18
cities = ["St. Petersburg", "Moscow", "Buenos Aires", "New York", "Stockholm",
"Amsterdam"]
print(cities)
print(sorted(cities))
print(cities)
print(sorted(cities, reverse = True))
print(cities)
cities.reverse()
print(cities)
cities.reverse()
print(cities)
cities.sort()
print(cities)
cities.sort(reverse = True)
print(cities)
| true |
c3e5bce720be7b1d73cdc72befdaf18f9e6c27da | dipikarpawarr/TQ_Python_Programming | /PythonPracticePrograms/String/Remove_Occurrances_Of_Specific_Character.py | 257 | 4.28125 | 4 | # WAP to remove all occurences of given char from String
strInput = input("\nEnter the string = ")
charRemove = input("Which character you have to remove = ")
result = strInput.replace(charRemove,"")
print("\nBefore = ", strInput)
print("After = ",result) | true |
06970f054e1768bc231abc16a32fff9286e053f6 | dipikarpawarr/TQ_Python_Programming | /PythonPracticePrograms/String/Anagram_String.py | 456 | 4.15625 | 4 | # WAP to accept 2 string and check whether they are anagram or not eg) MARY ARMY
strInput1 = input("Enter the first string = ")
strInput2 = input("Enter the second string = ")
if len(strInput1) == len(strInput2):
sorted1 = sorted(strInput1)
s1 = "".join(sorted1)
sorted2=sorted(strInput2)
s2 = "".join(sorted2)
if s1 == s2:
print("Anagram String")
else:
print("Not Anagram String")
else:
print("Mismatch input") | true |
77bd1bf62927f89fbbfc01fd300a2d5ca7677dc3 | dipikarpawarr/TQ_Python_Programming | /PythonPracticePrograms/Flow Control - Loops/Count_Digits_In_Given_Number.py | 247 | 4.28125 | 4 | # Write a Python program to count number of digits in any number
num = int(input("Enter the number = "))
numHold = num
count = 0
while(num>0):
digit = num %10
count += 1
num //= 10
print("Total digits in the ",numHold," is = ", count) | true |
85bd50a7ef08b61082969d3a7a8b5a9a7efc04e9 | dipikarpawarr/TQ_Python_Programming | /PythonPracticePrograms/Flow Control - Loops/Pallindrome_Number.py | 576 | 4.125 | 4 | # WAP to check given no is palindrome or not. Original =Reverse
# Eg 1221, 141, 12321, etc
num = input("Enter the number = ")
print("\n---- Solution 1 ----")
reverse = num[::-1]
if num == reverse:
print(num," is palindrome")
else:
print(num, " is not palindrome")
# OR
print("\n---- Solution 2 ----")
num1 = int(input("Enter the number = "))
numHold1 = num1
strReverse = ""
while(numHold1>0):
digit = numHold1 % 10
strReverse += str(digit)
numHold1 //= 10
if num == strReverse:
print(num," is palindrome")
else:
print(num, " is not palindrome") | true |
55c986710dc439d7818700236233a042e3ca1a76 | jerome1232/datastruct-tut | /src/2-topic-starter.py | 1,629 | 4.34375 | 4 | class Queue:
'''
This represents a queue implemented by a doubly
linked list.
'''
class Node:
'''
An individual node inside a linked list
'''
def __init__(self, data):
'''Initialize with provided data and no links.'''
self.data = data
self.previous = None
self.next = None
def __init__(self):
'''Initialize an empty linked list.'''
self.head = None
self.tail = None
def enqueue(self, value):
'''Add a node to the end of the queue'''
pass
def dequeue(self):
'''Remove a node from the front of the queue.'''
pass
def proccess(self, athelete):
'''Processes an atheletes information'''
place = ""
if athelete is None:
return
elif athelete[1] == 1:
place = "got Gold"
elif athelete[1] == 2:
place = "got Silver"
elif athelete[1] == 3:
place = "got Bronze"
elif athelete[1] == 4:
place = "got honorable mention"
else:
place = "Did not place"
print(athelete[0], place, "with score:", athelete[2])
athletes = (('Susan', 1, 100),
('Billy', 3, 300),
('Jill', 2, 500),
('Anthony', 3, 200),
('Eric', 4, 30),
('Erin', 2, 25),
('Elizabeth', 5, 32),
('Angela', 1, 22),
('Emilee', 3, 89),
('Sarah', 6, 999),
('Anna', 8, 245))
work = Queue()
work_length = 0
for athelete in athletes:
work.enqueue(athelete)
work_length += 1
while work_length > 0:
work.proccess(work.dequeue())
work_length -= 1 | true |
47f966adae31358284fc408907a2eea4a60f5c23 | kensekense/unige-fall-2019 | /metaheuristics/example_for_kevin.py | 2,864 | 4.4375 | 4 | '''
When you're coding, you want to be doing your "actions" inside of functions.
You are usually using your "global" space to put in very specific values.
Here's an example.
'''
import random
def modifier_function (input1, input2):
'''
For simplicity, I've named the inputs to this function input1 and input2 to drive home the concept
that each function has inputs. You can call them whatever you want.
Think of it as, the function will take whatever object you give it, and the function will refer to it
as input1 (or input2 or whatever you put the name there) and that reference will only exist INSIDE the function.
'''
for i in range(0, len(input1)): #iterate through each value input1
input1[i] += 1 #modify that value by increasing it by 1
while(input2): #shows you that input1 and input2 don't have to be the same type of object
print("Infinite loop.") #here input2 is obviously a boolean value (True, False)
return input1 #this function returns your input1. From the for loop, you should know that input1 is a list of sorts.
def generator_function (input):
'''
I think the idea of a generator makes sense. Take a look.
'''
output = [0]*input #input here is an integer value, output here is define IN the function.
for i in range(0, len(output)): #iterate through the list output.
output[i] = random.randint(1,10) #think about what this does
return output
def observer_function (input):
'''
This would be an observer function. They still "return" a value, but these are generally boolean (T/F)
'''
if len(input) == 0: #can you explain what this function does?
return True
else:
return False
def observer_function_2 (input):
'''
This is an example of an observer function that does not return anything.
'''
if len(input) == 0:
print("I had a good day")
else:
pass
if __name__ == "__main__": #don't worry about what this means, just know that everything past this is "global"
array1 = generator_function(10) #it's a generator because it takes an integer input, but your output is something new.
#it "generated" (made something new) an array
print("Generated array: ", array1)
#you stored the array generated by the function as array1.
array1 = modifier_function(array1, False) #here the modifier changes the values of the array you put in. You don't get something new as an output.
#you can store this array under a new name, but I kept it the same to emphasize the idea of a "modifier."
print("After modified: ", array1)
obs = observer_function(array1)
print(obs)
observer_function_2 #do you understand why I don't save observer_function_2 to a variable name?
| true |
1eafc06083e85e6fff87c4a0c26b0c7a759844f9 | deleks-technology/myproject | /simpleCal.py | 1,493 | 4.21875 | 4 | print("Welcome to our simple Calculator... ")
print("====================================================================")
# Prompt User for first number
# to convert a string to a number with use the int()/ float()
first_number = float(input("Please input your first number: "))
print("====================================================================")
# Prompt User for second number
second_number = float(input("Please input your second number: "))
print("====================================================================")
# Math Logic
# Logic for Addition
print(" The Sum of ", first_number, "and", second_number, "=", (first_number + second_number))
print("====================================================================")
# Logic for substraCTION
print(" The Substraction of ", first_number, "and", second_number, "=", (first_number - second_number))
print("====================================================================")
# Logic for division
print(" The division of ", first_number, "and", second_number, "=", round(first_number / second_number, 2))
print("====================================================================")
# Logic for multiplication
print(" The multiple of ", first_number, "and", second_number, "=", (first_number * second_number))
print("====================================================================")
# Logic for raise to power 2
print("The square of", first_number, "=", (first_number ** 2))
| true |
24dccadfc40fb85d20305d92ba298bc511a6ea64 | niranjan2822/PythonLearn | /src/Boolean_.py | 804 | 4.375 | 4 | # Boolean represent one of two values :
# True or False
print(10 > 9) # --> True
print(10 == 9) # --> False
print(10 < 9) # --> False
# Ex :
a = 200
b = 300
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
# Output --> b is greater than a
# bool() --> The bool() function allows you to evaluate any value and give you True or False in return .
# Example :
print(bool("Hello")) # --> True
print(bool(15)) # --> True
# Evaluate two variables :
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
# Output - True
# Output - True
# Some values are False
print(bool(False))
print(bool(None))
print(bool(0))
print(bool(""))
print(bool(()))
print(bool([]))
print(bool({}))
# Function can return a boolean
def func():
return True
print(func())
# True
| true |
223bf6f986a50959f1f6f61520204ad384e2daec | sachdevavaibhav/CFC-PYDSA-TEST01 | /Test-01-Py/Ans-03.py | 281 | 4.1875 | 4 | # 3. Write a Python program to sum of two given integers. However, if the sum
# is between 15 to 20 it will return 20.
num1 = int(input("Enter a number: "))
num2 = int(input("Enter a number: "))
ans = num1 + num2
if 15 <= ans <= 20:
print(20)
else:
print(ans) | true |
17eec4b963a4a7fb27a29279261a1df059be22e3 | amaria-a/secu2002_2017 | /lab03/code/hangman.py | 2,022 | 4.15625 | 4 |
# load secret phrase from file
f = open('secret_phrase.txt','r')
# ignore last character as it's a newline
secret_phrase = f.read()[:-1]
# get letters to guess, characters to keep, initialize ones that are guessed
to_guess = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
to_keep = " ,'-"
guessed = []
# create version to show to user with letters turned to -
shown_phrase = ''
for char in secret_phrase:
# want to preserve certain characters
# ternary operator, could do using regular if/else as we do below
char_to_add = char if char in to_keep else '_'
shown_phrase = shown_phrase + char_to_add
# now start interacting with users to get them to guess letters
# terminate when they have guessed the phrase
while shown_phrase != secret_phrase:
text = 'The phrase is\n' + shown_phrase + '\nNow guess a letter: '
x = raw_input(text)
# only want users to guess single letters
while len(x) > 1:
x = raw_input('Sorry, please guess only a single character: ')
# also want them guessing only letters
while x not in to_guess:
x = raw_input('Sorry, please guess only letters: ')
# now cast input as lowercase value to be consistent with phrase
x = x.lower()
# if the user has guessed letter already there's no point in redoing this
if x not in guessed:
# log that the user has guessed the character
guessed.append(x)
# now replace in shown_phrase if it's in secret_phrase
if x in secret_phrase:
# recreate shown_phrase with replacements in guessed
new_shown_phrase = ''
for char in secret_phrase:
if char in guessed or char in to_keep:
new_shown_phrase = new_shown_phrase + char
else:
new_shown_phrase = new_shown_phrase + '_'
# now replace shown_phrase with updated value
shown_phrase = new_shown_phrase
print 'Congratulations! You guessed the phrase in', len(guessed), 'tries.'
| true |
42e1b76389b3f6dd99e36f7d8f4d3f89fe3af8c0 | mguid73/basic_stats | /basic_stats/basic_stats.py | 788 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Basic stats module
"""
def mean(a):
"""
input is the list of numbers you want to take the mean
"""
# computing amount
ctlist= []
for n in a:
n=1 # changing every value in the list to 1
ctlist.append(n) # creating a new list made up of 1's
count = 0
for s in ctlist: # for loop to iteratively add values in sumlist
count += s # augmented assignment expression calculates count
# Compute the mean of the elements in list a.
listsum = 0
for n in a: # for loop to iteratively add values
listsum += n # augmented assignment expression calculates sum
# we have the sum and the N of the list, now lets calculate mean
avg = listsum/count
return avg | true |
43e2dccabe35905571ca61822de501fd25906b79 | AlexanderHurst/CrackingVigenereCypher | /vigenere.py | 2,009 | 4.1875 | 4 | from sys import argv
import string_tools
from sanitization import sanitize
# takes a secret message and key and returns
# vigenere ciphertext
# note secret message and key must be a list of numbers
# use string tools to convert
def encrypt(secret_message, secret_key):
cipher_text = []
# encrypting adds the key, if result it outside of alphabet
# roll back to the beginning of the alphabet
rollback = 26
# for each letter in the secret message
# use the index of the key for a ceasarian cipher
# and append the new letter to the cipher text
for i, letter in enumerate(secret_message):
# rotate the letter by the secret key index
# key is repeated for cipher texts longer than key
cipher_letter = (
letter + secret_key[i % len(secret_key)]) % rollback
cipher_text.append(cipher_letter)
return cipher_text
# takes a cipher text and key and returns
# decryption of that text with the key
# note cipher text and key must be a list of numbers
# use string tools to convert
def decrypt(cipher_text, secret_key):
secret_message = []
rollforward = 26
# basically performs the above operation in reverse
for i, letter in enumerate(cipher_text):
secret_letter = (
letter - secret_key[i % len(secret_key)]) % rollforward
secret_message.append(secret_letter)
return secret_message
# quick validation method
if __name__ == "__main__":
secret_message = string_tools.string_to_num_list(
sanitize(argv[1], '[^a-zA-Z]', ""), 'A')
secret_key = string_tools.string_to_num_list(
sanitize(argv[2], '[^a-zA-Z]', ""), 'A')
cipher_text = encrypt(secret_message, secret_key)
print("encrypt(", secret_message, ", ", secret_key, "):\n\t", cipher_text)
print()
secret_message = decrypt(cipher_text, secret_key)
print("decrypt(", cipher_text, ", ", secret_key, "):\n\t", secret_message)
print(string_tools.num_list_to_string(secret_message, 'A'))
| true |
eb8f13ba8ef2c9a7adad8dcc94081a8aa24cb93e | hsinhuibiga/Python | /insertion sort.py | 1,419 | 4.34375 | 4 |
# sorts the list in an ascending order using insertion sort
def insertion_sort(the_list):
# obtain the length of the list
n = len(the_list)
# begin with the first item of the list
# treat it as the only item in the sorted sublist
for i in range(1, n):
# indicate the current item to be positioned
#print(i)
current_item = the_list[i]
#print(current_item)
# find the correct position where the current item
# should be placed in the sorted sublist
pos = i
#print(the_list[pos])
while pos > 0 and the_list[pos - 1] > current_item:
# shift items in the sorted sublist that are
# larger than the current item to the right
the_list[pos] = the_list[pos - 1]
pos -= 1
print(the_list[pos])
# place the current item at its correct position
the_list[pos] = current_item
return the_list
the_list = [54,26,93,17,77,31,44,55,20]
#the_list = [77,31,55,20]
print(insertion_sort(the_list))
"""
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)
""" | true |
d70613eaa55ed3f52e384a4f97e3a751d0723e87 | grimmi/learnpython | /linkedlist1.py | 1,132 | 4.125 | 4 | '''
Linked Lists - Push & BuildOneTwoThree
Write push() and buildOneTwoThree() functions to easily update and
initialize linked lists. Try to use the push() function within your
buildOneTwoThree() function.
Here's an example of push() usage:
var chained = null
chained = push(chained, 3)
chained = push(chained, 2)
chained = push(chained, 1)
push(chained, 8) === 8 -> 1 -> 2 -> 3 -> null
The push function accepts head and data parameters, where head is either
a node object or null/None/nil. Your push implementation should be able
to create a new linked list/node when head is null/None/nil.
The buildOneTwoThree function should create and return a linked list with three nodes:
1 -> 2 -> 3 -> null
taken from: http://www.codewars.com/kata/linked-lists-push-and-buildonetwothree/train/python
'''
class Node(object):
def __init__(self, data, next_node = None):
self.data = data
self.next = next_node
def push(head, data):
return Node(data, head)
def build_one_two_three():
return push(push(push(None, 3), 2), 1)
chain = push(None, 1)
chain = push(chain, 2)
chain = push(chain, 3)
print(chain) | true |
d3e25805b601aff974c730abd85b4368724d09d4 | grimmi/learnpython | /reversebytes.py | 810 | 4.125 | 4 | '''
A stream of data is received and needs to be reversed.
Each segment is 8 bits meaning the order of these segments need to be reversed:
11111111 00000000 00001111 10101010
(byte1) (byte2) (byte3) (byte4)
10101010 00001111 00000000 11111111
(byte4) (byte3) (byte2) (byte1)
Total number of bits will always be a multiple of 8.
The data is given in an array as such:
[1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]
taken from: https://www.codewars.com/kata/569d488d61b812a0f7000015/train/python
'''
def data_reverse(data):
def chunk(ns, size):
for x in range(0, len(ns), size):
yield ns[x:x + size]
chunks = reversed(list(chunk(data, 8)))
return sum(chunks, [])
print(data_reverse([1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]))
| true |
b813a38631d35d6ccc84b871fade7dc9ccbde14c | ll0816/My-Python-Code | /decorator/decorator_maker_with_arguments.py | 1,084 | 4.1875 | 4 | # !/usr/bin/python
# -*- coding: utf-8 -*-
# decorator maker with arguments
# Liu L.
# 12-05-15
def decorator_maker_with_args(d_arg1, d_arg2):
print "I make decorators! And I accept arguments:{} {}".format(d_arg1, d_arg2)
def decorator(func):
print "I am the decorator. Somehow you passed me arguments: {} {}".format(d_arg1, d_arg2)
def wrapper(*args):
print ("I am the wrapper around the decorated function.\n"
"I can access all the variables\n"
"\t- from the decorator: {0} {1}\n"
"\t- from the function call: {2} {3}\n"
"Then I can pass them to the decorated function"
.format(d_arg1, d_arg2, *args))
return func(*args)
return wrapper
return decorator
@decorator_maker_with_args("Leonard", "Sheldon")
def decorated_func_with_args(*args):
print ("I am the decorated function and only knows about my arguments: {0}"
" {1}".format(*args))
if __name__ == '__main__':
decorated_func_with_args("Rajesh", "Howard") | true |
295ace8f90f7303eba831493003cdd7289a4c3c9 | ll0816/My-Python-Code | /decorator/dive_in_decorator.py | 1,094 | 4.21875 | 4 | # !/usr/bin/python
# -*- coding: utf-8 -*-
# dive in decorator
# Liu L.
# 12-05-15
def decorator_maker():
print "I make decorators! I am executed only once:"+\
"when you make me create a decorator"
def my_decorator(func):
print "I am a decorator! I am executed"+\
"only when you decorate a function."
def wrapper():
print "I am the wrapper around the decorated function. "+\
"I am called when you call the decorated function. "+\
"As the wrapper, I return the RESULT of the decorated function."
return func()
print "As the decorator, I return the wrapped function."
return wrapper
print "As a decorator maker, I return a decorator"
return my_decorator
if __name__ == '__main__':
def decorated_func():
print "I am the decorated function"
decorated_function = decorator_maker()(decorated_func)
decorated_function()
print "\n"
@decorator_maker()
def decorated_func2():
print "I am the decorated function."
decorated_func2() | true |
b8fdbfa602d0928217d6fa18a3dee3bdfaf6890d | AnanthaVamshi/PySpark_Tutorials | /code/chap02/word_count_driver_with_filter.py | 2,672 | 4.21875 | 4 | #!/usr/bin/python
#-----------------------------------------------------
# This is a word count in PySpark.
# The goal is to show how "word count" works.
# Here we write transformations in a shorthand!
#
# RULES:
#
# RULE-1:
# Here I introduce the RDD.filter() transformation
# to ignore the words if their length is less than 3.
# This is implemented by:
# .filter(lambda word : len(word) > 2)
# RULE-2:
# If the total frequency of any unique word is less
# than 2, then ignore that word from the final output
# This is implemented by:
# .filter(lambda (k, v) : v > 1)
#
#------------------------------------------------------
# Input Parameters:
# argv[1]: String, input path
#-------------------------------------------------------
# @author Mahmoud Parsian
#-------------------------------------------------------
from __future__ import print_function
import sys
from pyspark.sql import SparkSession
#=====================================
def debug_file(input_path):
# Opening a file in python for reading is easy:
f = open(input_path, 'r')
# To get everything in the file, just use read()
file_contents = f.read()
#And to print the contents, just do:
print ("file_contents = \n" + file_contents)
# Don't forget to close the file when you're done.
f.close()
#end-def
#=====================================
if __name__ == '__main__':
if len(sys.argv) != 2:
print("Usage: word_count_driver.py <input-path>", file=sys.stderr)
exit(-1)
spark = SparkSession\
.builder\
.appName("Word-Count-App")\
.getOrCreate()
# sys.argv[0] is the name of the script.
# sys.argv[1] is the first parameter
input_path = sys.argv[1]
print("input_path: {}".format(input_path))
debug_file(input_path)
# create frequencies as RDD<unique-word, frequency>
# Rule-1: filter(): if len(word) < 3, then
# drop that word
frequencies = spark.sparkContext.textFile(input_path)\
.filter(lambda line: len(line) > 0)\
.flatMap(lambda line: line.lower().split(" "))\
.filter(lambda word : len(word) > 2)\
.map(lambda word: (word, 1))\
.reduceByKey(lambda a, b: a + b)
#
print("frequencies.count(): ", frequencies.count())
print("frequencies.collect(): ", frequencies.collect())
# Rule-2: filter(): if frequency of a word is > 1,
# then keep that word
filtered = frequencies.filter(lambda (k, v) : v > 1)
print("filtered.count(): ", filtered.count())
print("filtered.collect(): ", filtered.collect())
# done!
spark.stop()
| true |
aa60328ddf11240a19c9aa1360b49ae37777aee9 | shreya-trivedi/PythonLearn | /q03lenght.py | 515 | 4.21875 | 4 | #!/usr/bin/python3.5
'''
Problem Statement
Define a function that computes the length of a given list or string.
(It is true that Python has the len() function built in,
but writing it yourself is nevertheless a good exercise.)
'''
import sys
def get_lenght(word):
''' Function to get lenght of a string
Args:
word = The only parameter.
Returns:
count = lenght of string.
'''
count = 0
for char in word:
count += 1
return count
print get_lenght(sys.argv[1])
| true |
43ea03ea1d693d03366841964a2808e64626c414 | MihaiRr/Python | /lab11/Recursion.py | 1,335 | 4.46875 | 4 | # The main function that prints all
# combinations of size r in arr[] of
# size n. This function mainly uses
# combinationUtil()
def printCombination(arr, n, r):
# A temporary array to store
# all combination one by one
data = [""] * r
# Print all combination using
# temprary array 'data[]'
combinationUtil(arr, n, r, 0, data, 0)
''' arr[] ---> Input Array
n ---> Size of input array
r ---> Size of a combination to be printed
index ---> Current index in data[]
data[] ---> Temporary array to store
current combination
i ---> index of current element in arr[] '''
def combinationUtil(arr, n, r, index, data, i):
# Current cobination is ready,
# print it
if (index == r):
for j in range(r):
print(data[j], end = " ")
print()
return
# When no more elements are
# there to put in data[]
if (i >= n):
return
# current is included, put
# next at next location
data[index] = arr[i]
combinationUtil(arr, n, r, index + 1, data, i + 1)
# current is excluded, replace it
# with next (Note that i+1 is passed,
# but index is not changed)
combinationUtil(arr, n, r, index, data, i + 1) | true |
86b6be121a3af8171cf502278d6a7cd974db0533 | jshubh19/pythonapps | /bankaccount.py | 2,486 | 4.15625 | 4 | # bank account
class BankAccount:
''' this is Janta ka Bank'''
def __init__(self,accountname='BankAccount',balance=20000): #for making class method we use __init__ const
self.accountname=accountname
self.balance=baalance
def deposite (self,value):
self.balance=self.balance+value
print('your balance is ',self.balance)
def withdraw (self,value):
self.balance=self.balance-value
print('your balance is ',self.balance)
class currentaccount(BankAccount):
def __init__(self,accountname='currentaccount',balance=20000):
self.accountname=accountname
self.balance=balance
def withdraw(self,value):
if value>1000:
print('you cant withdraw that amount')
else:
self.balance=self.balance-value
print('your currentaccount balance is',self.balance)
class savingaccount(BankAccount):
def __init__(self,accountname='savingaccount',balance=20000):
self.accountname=accountname
self.balance=balance
def deposite (self,value):
self.balance=self.balance+value*0.3
print('your savingaccount balance is ',self.balance)
oc=currentaccount()
os=savingaccount()
while True:
print('1.currentaccount')
print('2.savingaccount')
main_menu=int(input('please select your option '))
if main_menu==1:
print('1.deposite')
print('2.withdraw')
sub_menu=int(input('please choose your option '))
if sub_menu==1:
value=int(input('enter the amount to deposite '))
oc.deposite(value)
elif sub_menu==2:
value=int(input('enter amount to withdraw '))
oc.withdraw(value)
else:
print('you just choosed invalid option ')
elif main_menu==2:
print('1.deposite')
print('2.withdraw')
sub_menu=int(input('please choose your option '))
if sub_menu==1:
value=int(input('enter your amount for deposite '))
os.deposite(value)
elif sub_menu==2:
value=int(input('enter amount to withdraw '))
os.withdraw(value)
else:
print('you just choosed invalid option ')
else:
print('you choose invalid account type ')
break
| true |
6c562dadd0b180b5357b4ce57c73b440cb7c06a3 | Mariam-Hemdan/ICS3U-Unit-4-01-Python | /while_loop.py | 470 | 4.1875 | 4 | #!/usr/bin/env python3
# Created by : Mariam Hemdan
# Created on : October 2019
# This program uses while loop
def main():
# this program uses While loop
sum = 0
loop_counter = 0
# input
positive_integer = int(input("Enter an integer: "))
print("")
# process & output
while loop_counter <= positive_integer:
sum = sum + loop_counter
print(sum)
loop_counter = loop_counter + 1
if __name__ == "__main__":
main()
| true |
78eebbec669e95bedd57fb74714c56a8a3705178 | Pyabecedarian/Algorithms-and-Data-Structures-using-Python | /Stage_1/Task5_Sorting/bubble_sort.py | 729 | 4.28125 | 4 | """
Bubble Sort
Compare adjacent items and exchange those are out of order. Each pass through the list places the next
largest value in its proper place.
If not exchanges during a pass, then the list has been sorted.
[5, 1, 3, 2] ---- 1st pass ----> [1, 3, 2, 5]
Complexity: O(n^2)
"""
def bubble_sort(alist: list) -> list:
exchanges = True
passnum = len(alist) - 1
while passnum > 0 and exchanges:
exchanges = False
for i in range(passnum):
if alist[i] > alist[i + 1]:
alist[i], alist[i + 1] = alist[i + 1], alist[i]
exchanges = True
return alist
if __name__ == '__main__':
a = [5, 1, 3, 2]
print(bubble_sort(a)) | true |
5e3a27d7f44acfc40517e889015a6bc778855ade | EarthBeLost/Learning.Python | /Exercise 3: Numbers and Math.py | 1,051 | 4.59375 | 5 | # This is the 3rd exercise!
# This is to demonstrate maths within Python.
# This will print out the line "I will now count my chickens:"
print "I will now count my chickens:"
# These 2 lines will print out their lines and the result of the maths used.
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4
# This will print out the line "Now I will count the eggs:"
print "Now I will count the eggs:"
# This prints out the value of this calculation...
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# Just prints out the line in here.
print "Is it true that 3 + 2 < 5 - 7?"
# This prints out true.
print 3 + 2 < 5 - 7
# These 2 lines prints out the strings and the result of the maths.
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
# Just prints out another line.
print "Oh, that's why it's False."
# Just prints out another line.
print "How about some more."
# This prints out True or False for these... go Boolean!
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
| true |
a3ee6737bc9880a213034cfc71ffd34b3f4d1215 | JakeGads/Python-tests | /Prime.py | 888 | 4.1875 | 4 | """
Ask the user for a number and determine whether the number is prime or not.
(For those who have forgotten, a prime number is a number that has no divisors.).
You can (and should!) use your answer to Exercise 4 to help you.
Take this opportunity to practice using functions, described below.
"""
def main():
run = 1
while run == 1:
run = 0
num = int(input("Please enter an integer (not 0,1,2) "))
i = 1
truth = 0
while i < num:
tester = num % i
if tester == 0:
truth += 1
i += 1
if num == 2 or num == 1 or num == 0:
print("%d is not a vaild input " % num)
run = 1
else:
if truth > 2:
print("%d is not a prime number " % num)
else:
print("%d is a prime number " % num)
main()
| true |
54c8d3a2094f4f575acd6ea4ecac7a4dc1746ec8 | green-fox-academy/wenjing-liu | /week-01/day-03/data_structure.py/product_db_2.py | 1,472 | 4.53125 | 5 | product_db = {
'milk': 200,
'eggs': 200,
'fish': 400,
'apples': 150,
'bread': 50,
'chicken': 550
}
def search_db(db):
print('Which products cost less than 201?')
smaller_keys = []
for key, value in product_db.items():
if value < 201:
smaller_keys.append(key)
if smaller_keys:
print(f"The less than 201 products: { ', '.join(smaller_keys)}")
else:
print('Sorry, we don\'t have.')
print('Which products cost more than 150?')
bigger_keys = []
for key, value in product_db.items():
if value > 150:
bigger_keys.append(key)
if bigger_keys:
for key in bigger_keys:
print(f'{key} {product_db[key]}')
else:
print('Sorry, we don\'t have.')
search_db(product_db)
"""
# Product database 2
We are going to represent our products in a map where the keys are strings
representing the product's name and the values are numbers representing the
product's price.
- Create a map with the following key-value pairs.
| Product name (key) | Price (value) |
|:-------------------|:--------------|
| Eggs | 200 |
| Milk | 200 |
| Fish | 400 |
| Apples | 150 |
| Bread | 50 |
| Chicken | 550 |
- Create an application which solves the following problems.
- Which products cost less than 201? (just the name)
- Which products cost more than 150? (name + price)
""" | true |
c874fd86801315b98f608f9011a54ef8299a8b54 | green-fox-academy/wenjing-liu | /week-01/day-05/matrix/matrix_rotation.py | 952 | 4.1875 | 4 | """
# Matrix rotation
Create a program that can rotate a matrix by 90 degree.
Extend your program to work with any multiplication of 90 degree.
"""
import math
def rotate_matrix(matrix, degree):
rotate_times = degree//90%4
print(rotate_times)
for rotate_time in range(rotate_times):
tmp_matrix = []
totalRowsOfRotatedMatrix = len(matrix)
totalColsOfRotatedMatrix = len(matrix[0])
for i in range(totalColsOfRotatedMatrix):
tmp_matrix.append([None]*totalRowsOfRotatedMatrix)
for row_num in range(totalRowsOfRotatedMatrix):
for col_num in range(totalColsOfRotatedMatrix):
tmp_matrix[totalColsOfRotatedMatrix - 1 - col_num][row_num] = matrix[row_num][col_num]
matrix, tmp_matrix = tmp_matrix, matrix
return matrix
matrix_x = [[12, 7, 3], [4, 5, 6]]
print(rotate_matrix(matrix_x, 90))
print(rotate_matrix(matrix_x, 180))
print(rotate_matrix(matrix_x, 270))
print(rotate_matrix(matrix_x, 360))
| true |
75194eb550340de1c1ab9a31adc510fec7ef771b | green-fox-academy/wenjing-liu | /week-02/day-01/encapsulation-constructor/counter.py | 947 | 4.125 | 4 | class Counter:
def __init__(self, num = 0):
self.num = int(num)
self._initial_num = self.num
def add(self, number = 1):
if isinstance(number, (int, float)):
self.num += int(number)
else:
raise Exception('You must input number')
def get(self):
return self.num
def reset(self):
self.num = self._initial_num
"""
# Counter
- Create `Counter` class
- which has an integer field value
- when creating it should have a default value 0 or we can specify it when creating
- we can `add(number)` to this counter another whole number
- or we can `add()` without parameters just increasing the counter's value by one
- and we can `get()` the current value
- also we can `reset()` the value to the initial value
- Check if everything is working fine with the proper test
- Download `test_counter.py` and place it next to your solution
- Run the test file as a usual python program
""" | true |
12c1001a8ec9759c913683af89a5f8db183d87a7 | green-fox-academy/wenjing-liu | /week-02/day-02/decryption/reversed_order.py | 510 | 4.15625 | 4 | # Create a method that decrypts reversed-order.txt
def decrypt(file_name, result_file_name):
try:
with open(file_name, 'r') as source_file:
with open(result_file_name, 'a') as result_file:
line_list = source_file.readlines()
result_file.write(''.join(reverse_order(line_list)))
except Exception as e:
print(f'Error occurs when do decrypt {file_name}: {e}')
def reverse_order(line_list):
return line_list[::-1]
decrypt('reversed_order.txt', 'reversed_order_result.txt') | true |
6f8fa5537d1c905be5afa97b890f334fb16fcd43 | green-fox-academy/wenjing-liu | /week-01/day-02/loops/guess_the_number.py | 634 | 4.21875 | 4 | # Write a program that stores a number, and the user has to figure it out.
# The user can input guesses, after each guess the program would tell one
# of the following:
#
# The stored number is higher
# The stried number is lower
# You found the number: 8
magic_num = 5
print('Guess the number!')
is_found = False
while not(is_found) :
guess_num = float(input('Please input a number(press enter to stop enter):\n'))
if guess_num > magic_num:
print('The stored number is lower')
elif guess_num < magic_num:
print('The stored number is higher')
else:
print(f'You found the number: {magic_num}')
is_found = True | true |
01e271b2fd0fbdd4b16f96d6171e294982bd0674 | green-fox-academy/wenjing-liu | /week-01/day-05/matrix/transposition.py | 465 | 4.15625 | 4 | """
# Transposition
Create a program that calculates the transposition of a matrix.
"""
def transposition_matrix(matrix):
result = []
for col_num in range(len(matrix[0])):
result.append([None]*len(matrix))
print(result)
for row_num in range(len(result)):
for col_num in range(len(result[row_num])):
result[row_num][col_num] = matrix[col_num][row_num]
return result
matrix_x = [[12, 7, 3], [4, 5, 6]]
print(transposition_matrix(matrix_x)) | true |
29031610a8bc863cea296a89d3bc058715762bf3 | green-fox-academy/wenjing-liu | /week-01/day-03/functions/bubble.py | 575 | 4.34375 | 4 | # Create a function that takes a list of numbers as parameter
# Returns a list where the elements are sorted in ascending numerical order
# Make a second boolean parameter, if it's `True` sort that list descending
def bubble(arr):
return sorted(arr)
def advanced_bubble(arr, is_descending = False):
sorted_arr = sorted(arr)
if is_descending:
sorted_arr.reverse()
return sorted_arr
# Example:
print(bubble([43, 12, 24, 9, 5]))
# should print [5, 9, 12, 24, 34]
print(advanced_bubble([43, 12, 24, 9, 5], True))
# should print [34, 24, 9, 5]
| true |
6eeb0463f0b42acc6fde7d5b61449e790949897b | dylan-hanna/ICS3U-Unit-5-05-Python | /address.py | 816 | 4.125 | 4 | #!/usr/bin/env python3
# Created by: Dylan Hanna
# Created on: Nov 2019
# This program accepts user address information
def mailing(name_one, address_one, city_one, province_one, postal_code_one):
print(name_one)
print(address_one)
print(city_one, province_one, postal_code_one)
def main():
while True:
name = input("Enter the name of the receiver: ")
address = input("Enter the address: ")
city = input("Enter the city: ")
province = input("Enter the province: ")
postal_code = input("Enter the postal code: ")
print()
try:
mailing(name, address, city, province, postal_code)
except ValueError:
print("Invalid Input")
continue
else:
break
if __name__ == "__main__":
main()
| true |
870d8536737e98f5e09e6475cea90552b8ae1aaf | vamshi-krishna-prime/Programming_Nanodegree | /6. Python, Part 2/Lesson 4 - Style and Structure/73-multi-line-strings.py | 2,669 | 4.125 | 4 | # Udacity > Intro to the Programming Nanodegree >
# Python part 2 > 4. Style & Structure > Section 3:
# Multi-line strings (1/2)
'''
Sometimes we end up wanting to use very long strings, and this can
cause some problems.
If you run pycodestyle on this, you'll get the following message:
some_script.py: E501 line too long
For such reasons, the Python style guide recommends keeping all
lines of code to a maximum of 79 characters in length—or even
72 characters, in some cases.
'''
'''
EOL stands for End Of Line. And a key thing to understand is that
this is actually a character in your code editor—it's just an
invisible one. In some code editors, there's an option to make these
visible.
'''
story = "Once upon a time there was a very long string that was \
over 100 characters long and could not all fit on the \
screen at once."
print('\n' + story)
# It prints, but there are a bunch of extra spaces between some of the words.
# One option would be to simply remove the indentation:
story = "Once upon a time there was a very long string that was \
over 100 characters long and could not all fit on the \
screen at once."
print('\n' + story)
# This would work, but it makes the code harder to read. We need a better
# solution.
# Instead of the escape character, how about if we use triple quotes?
story = """Once upon a time there was a very long string that was
over 100 characters long and could not all fit on the
screen at once."""
print('\n' + story)
# It prints the string, but there are a bunch of extra spaces between some
# of the words.
'''
What if we try using multiple strings, and using the + operator to
concatenate them? Like this:'
story = "Once upon a time there was a very long string that was " +
"over 100 characters long and could not all fit on the " +
"screen at once."
print(story)
It throws the error Invalid syntax.
'''
# What if we try both concatenation and the escape character?
story = "Once upon a time there was a very long string that was " + \
"over 100 characters long and could not all fit on the " + \
"screen at once."
print('\n' + story)
# It prints the string perfectly.
# Here's something rather different:
story = ("Once upon a time there was a very long string that was "
"over 100 characters long and could not all fit on the "
"screen at once.")
print('\n' + story)
# It prints the string perfectly.
'''
This should be a bit surprising. Why would this work?
The reason is a combination of two lesser-known Python features:
Implicit line-joining and automatic string-literal concatenation.
'''
| true |
861a628085be4eea68e5e32c6cab55f2d0f36838 | vamshi-krishna-prime/Programming_Nanodegree | /6. Python, Part 2/Lesson 2 - Strings and Lists, Part 1/29-f-strings.py | 1,068 | 4.3125 | 4 | # Udacity > Intro to the Programming Nanodegree >
# Python part 2 > 2. Strings & Lists Part 1 > Section 16: f-strings
# Do it in the terminal:
'''
f-strings is something that was added to Python in version 3.6—
so in order for this to work on your own computer, you must be sure
to have Python 3.6 or later. As a reminder, you can check which version
you have by going to your terminal and entering:
python3 --version
'''
>>> import math
>>> import math
3.141592653589793
>>> f"pi is about {math.pi:.6}"
pi is about 3.14159
# This is because of ':.6' inside f-strings (formatted strings)
'''
Suppose that we want to get the following string:
'The aardwolf eats termites.'
'''
>>> animal = "aardwolf"
>>> food = "termites"
>>> "The " + animal + " eats " + food + "."
# Works
>>> animal = "aardwolf"
>>> food = "termites"
>>> "The {animal} eats {food}"
# Doesn't work.
>>> animal = "aardwolf"
>>> food = "termites"
>>> f"The " {animal} " eats " {food} "."
# Doesn't work.
>>> animal = "aardwolf"
>>> food = "termites"
>>> f"The {animal} eats {food}."
# Works
| true |
8eafc4cab7035114ead9e844e3f5a57c3c489e01 | vamshi-krishna-prime/Programming_Nanodegree | /6. Python, Part 2/Lesson 2 - Strings and Lists, Part 1/24-slicing-word-triangle-exercise.py | 977 | 4.1875 | 4 | # Udacity > Intro to the Programming Nanodegree >
# Python part 2 > 2. Strings & Lists Part 1 > Section 12: Slicing(1/2)
'''
Exercise: Word triangle
find a partially completed for loop.
Goal is to finish the loop so that it prints out the following:
d
de
def
defi
defin
defini
definit
definite
definitel
definitely
'''
# Approach 1
print('\nApproach 1:\n')
word = "definitely"
length = len(word)
for n in range(length):
print(word[0:n + 1])
# Approach 2
print('\nApproach 2:\n')
new_word = ''
for ch in 'definitely':
new_word += ch
print(new_word)
'''
Each time through the loop, n gets larger. So [0:n] is a slice expression
that will start from the beginning of the string (at the character with
index 0) and go up until the character at index n. Since n is growing,
the string that gets printed will also grow longer each time.
Notice that we have to add + 1, because n starts at 0 and goes up to 9
(but we want it to start at 1 and go up to 10).
'''
| true |
95e54eacc1da6c8c5b8724634c686b56b1ae1e41 | vamshi-krishna-prime/Programming_Nanodegree | /6. Python, Part 2/Lesson 3 - Strings and Lists, Part 2/43-mutable-vs-immutable.py | 905 | 4.3125 | 4 | # Udacity > Intro to the Programming Nanodegree >
# Python part 2 > 3. Strings & Lists Part 2 > Section 3:
# Mutable vs. immutable
'''
List are mutable (can be modified)
Strings are immutable (cannot be modified)
'''
# Exercise 1 - Mutable
print('\nExercise 1 - Mutable:\n')
breakfast = ['toast', 'bacon', 'eggs']
print(breakfast)
# ['toast', 'bacon', 'eggs']
print(breakfast[0])
# 'toast'
breakfast[0] = 'spam'
print(breakfast)
# ['spam', 'bacon', 'eggs']
breakfast[1] = 'spam'
print(breakfast)
# ['spam', 'spam', 'eggs']
breakfast[2] = 'spam'
print(breakfast)
# ['spam', 'spam', 'spam']
# Exercise 2 - immutable
print('\nExercise 2 - immutable:\n')
breakfast = 'waffles'
print(breakfast)
new_breakfast = breakfast + ' and strawberries'
print(new_breakfast)
print(breakfast)
breakfast = breakfast + ' and strawberries'
print(breakfast)
# but here the concatenated 'breakfast' is a new string.
| true |
f9ca6dad8f3dc6f8363fe1b8a49072604bb770ab | vamshi-krishna-prime/Programming_Nanodegree | /6. Python, Part 2/Lesson 3 - Strings and Lists, Part 2/66-convert-string-into-list.py | 800 | 4.5625 | 5 | # Udacity > Intro to the Programming Nanodegree >
# Python part 2 > 3. Strings & Lists Part 2 > Section 17:
# Find and replace (1/2)
# Convert a string into a list
# Approach 1 (without using split method)
def list_conversion(string):
list = []
for index in string:
list.append(index)
return list
string = input('Enter a string: ')
print(' Approach 1: without using split method:')
print('list converted:' + str(list_conversion(string)))
# Approach 2 using split method
# this can be used only when the string has a specific separator
print(' Approach 2: using split method:')
string1 = 'Going to the work'
string2 = 'mangos, stawberry, pears'
string3 = 'c-a-t'
# so string.split() will not work
print(string1.split(' '))
print(string2.split(','))
print(string3.split('-'))
| true |
46b0b93e3d86c6cc425459be309bd3bd15ed3d1c | vamshi-krishna-prime/Programming_Nanodegree | /6. Python, Part 2/Lesson 2 - Strings and Lists, Part 1/19-range-function.py | 1,245 | 4.71875 | 5 | # Udacity > Intro to the Programming Nanodegree >
# Python part 2 > 2. Strings & Lists Part 1 > Section 9:
# The range function, revisited
'''
Earlier, we used the range function with for loops.
We saw that instead of using a list like this:
'''
print()
for side in [0, 1, 2, 3]:
print(side)
print()
# Range can be used like below:
for n in range(4):
print(n)
print()
'''
So we can pass range up to three arguments.
what the three range parameters do:
1. The first parameter is the number to start with.
2. The second parameter is the number to stop at (or rather, to
stop before, since it's excluded).
3. The third parameter is the step size (i.e., how large a step to
take when counting up).
Notice that start and step are optional—
if you leave either (or both) out, the function will just go with
the defaults— a start of 0 and a step of 1.
range(5) is same as range(0, 5, 1)
range(0, 5) is same as range(0, 5, 1)
range(4) is same as range(0, 4, 1)
range(0, 4, 1) is same as range(0, 4, 1)
range(2, 5) is same as range(2, 5, 1)
'''
print()
for n in range(5):
print(n)
print()
for n in range(1, 4):
print(n)
print()
for n in range(97, 101):
print(n)
print()
for n in range(0, 10, 2):
print(n)
print()
| true |
9580691741d7e3c606279cd91512724f8c087993 | vamshi-krishna-prime/Programming_Nanodegree | /6. Python, Part 2/Lesson 3 - Strings and Lists, Part 2/56-break-exercise-no-repeating-words.py | 686 | 4.21875 | 4 | # Udacity > Intro to the Programming Nanodegree >
# Python part 2 > 3. Strings & Lists Part 2 > Section 10:
# Infinite loops and breaking out
# Exercise - Repeated words:
'''
Write an function to store the words input by the user
and exit the while loop when a word is repeated.
There's another way to exit from an infinite loop. Inside a while or
for loop, you can use the break statement to immediately exit the loop .
'''
def no_repeating():
words = []
while True:
word = input("Tell me a word: ")
if word in words:
print("You told me that word already!")
break
words.append(word)
return words
print(no_repeating())
| true |
612dbf123309396abbe8755f327c1e0eed8d5303 | divineBayuo/NumberGuessingGameWithPython | /Number_Guessing_GameExe.py | 1,959 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 3 10:52:42 2021
@author: Divine
"""
#putting both programs together
#importing required libs
import tkinter as tk
import random
import math
root = tk.Tk()
canvas1 = tk.Canvas(root, width = 300, height = 300)
canvas1.pack()
#making the game code a function
def NumberGuessingGame ():
#take the inputs from the user
lowerBound = int(input("Enter lower bound:- ")) #lower bound
upperBound = int(input("Enter upper bound:- ")) #upper bound
#generating random figure between the lower and upper bound
x = random.randint(lowerBound,upperBound)
print("\n\tYou have only chances ",
round(math.log(upperBound-lowerBound+1,2)),
"to guess the integer!\n")
#initializing the number of guesses
count = 0
#min number of guesses depends on the range given
while count <= round(math.log(upperBound-lowerBound+1,2)):
count = count + 1
#taking the player's guess
guess = int(input("Guess the number:- "))
#test a condition
if x == guess:
print("\nCongratulations! You did it in ",count," tries.")
#once the guess is correct, the loop will break
break
elif x > guess:
print("\nGuessed too small!")
elif x < guess:
print("\nGuessed too high!")
#if guessing is more than the required guesses, give the following
if count > round(math.log(upperBound-lowerBound+1,2)):
print("\nThe number is %d" %x)
print("\tBetter luck next time!")
button1 = tk.Button(text='Start!',command = NumberGuessingGame, bg='green', fg='white')
canvas1.create_window(150,150,window=button1)
#button2 = tk.Button(text='Play Again',command = NumberGuessingGame, bg='green', fg='white')
#canvas1.create_window(150,150,window=button2)
root.mainloop() | true |
cca6ea9561c63a741e72107d537b70054a4220c2 | goateater/MyCode | /learn_python/basic_string_operations.py | 785 | 4.5 | 4 | #!/usr/bin/env python
bso = """
Basic String Operations
----------------------
Strings are bits of text. They can be defined as anything between quotes:
As you can see, the first thing you learned was printing a simple sentence. This sentence was stored by Python as a string.
However, instead of immediately printing strings out, we will explore the various things you can do to them.
You can also use single quotes to assing a string. However, you will face problems if the value to be assigned itself
contains single quotes.For example to assign the string in these bracket(single quotes are ' ') you need to use double
quotes only like this.
"""
astring = "Hello World!"
astring2 = 'Hello World!'
print astring
print astring2
print "single quotes are ' '"
print len(astring) | true |
78b6c9150a4804af6f60d62d040fc09c9f86d0a1 | nfbarrett/CCIS-1505-02 | /Session11/Test2-Q28.py | 549 | 4.21875 | 4 | blnDone = False # sets Boolean to false
while blnDone == False: # checks Boolean is still false
try: # repeats this until Boolean is true
num = int(input( "Enter your age" )) # asks for number, converts input into integer
blnDone = True # sets Boolean to true
except (ValueError): # if input is not a number will error out.
print ("invalid age entered, please re-enter!") # returns error line and keeps Boolean to false and repeats
print ("Your age is", num) # once Boolean is true displays this line with the number
| true |
ba771d7f4f312d4276781c88642d7aae08baaf7d | nfbarrett/CCIS-1505-02 | /Session11/Test2-Q27.py | 837 | 4.46875 | 4 | def maximumValue( x, y, z ): # calls the function for maximumvalue
maximum = x # if position 1 is max this will be displayed
if y > maximum: # checks if position 2 is larger that position 1
maximum = y # if position 2 is larger, position 2 will be displayed
if z > maximum: # checks if position 3 is larger that position 1
maximum = z # if position 3 is larger, position 3 will be displayed
return maximum # displays the largest number
####Mainline#### # seperation of functions and the program
a = int(input( "Enter first integer: " ) ) # asks for 1st number
b = int(input( "Enter second integer: " ) ) # asks for 2nd number
c = int(input( "Enter third integer: " ) ) # asks for 3rd number
print ("Maximum integer is:", maximumValue( a, b, c )) # calls function maximumValue and displays the result
| true |
15b5733f80fddc8c8a22522ae0653f1de90546bf | liujiantao007/Perform-Object-Detection-With-YOLOv3-in-Keras | /Draw_rectangle/single_rectangle_cv2.py | 911 | 4.3125 | 4 | # Python program to explain cv2.rectangle() method
# importing cv2
import cv2
from matplotlib import pyplot as plt
path ='2.jpg'
# Reading an image in default mode
image = cv2.imread(path)
# Window name in which image is displayed
window_name = 'Image'
# Start coordinate, here (5, 5)
# represents the top left corner of rectangle
"""
<bndbox>
<xmin>216</xmin>
<ymin>359</ymin>
<xmax>316</xmax>
<ymax>464</ymax>
</bndbox>
"""
start_point = (216,359)
# Ending coordinate, here (220, 220)
# represents the bottom right corner of rectangle
end_point = (316,464)
# Blue color in BGR
color = (255, 0, 0)
# Line thickness of 2 px
thickness = 2
# Using cv2.rectangle() method
# Draw a rectangle with blue line borders of thickness of 2 px
image = cv2.rectangle(image, start_point, end_point, color, thickness)
cv2.imwrite('r.jpg',image)
# Displaying the image
plt.imshow(image)
| true |
5d9b8983b5652dc449658873bfd8b237fdc57b64 | jsheridanwells/Python-Intro | /7_dates.py | 955 | 4.375 | 4 | #
# Example file for working with date information
#
from datetime import date
from datetime import time
from datetime import datetime # imports standard modules
def main():
## DATE OBJECTS
# Get today's date from the simple today() method from the date class
today = date.today()
print('la fecha es ', today)
# print out the date's individual components
print('components::', today.month, today.day, today.year)
# retrieve today's weekday (0=Monday, 6=Sunday)
days = [
'monda',
'tuesday',
'wednesday',
'thursday',
'friday',
'saturday',
'sunday'
]
print('today\'s weekday number is', today.weekday()) # => 6
print('which is', days[today.weekday()])
## DATETIME OBJECTS
# Get today's date from the datetime class
currentDate = datetime.now()
print(currentDate)
# Get the current time
time = datetime.time(currentDate)
print('la hora es', time)
if __name__ == "__main__":
main();
| true |
a1a92e7de2c597aaa4d1a6443bc2354216c9f1f5 | pavan1126/python-1-09 | /L3 8-09 Reverse order.py | 379 | 4.25 | 4 | #copying elements from one array to another array in reverse order
a=[1,2,3,4,5]
b=[None]*len(a)
length=len(a)
#logic starts here
for i in range(0,length):
b[i]=a[length-i-1]
#printing output
print("the elements of first array is")
for i in range(0,length):
print(a[i])
print("the elements of reversed array is",b)
for i in range(0,len(b)):
print(b[i])
| true |
84eb0afd3ad225fc0e23eb56292b845ed1d4e4ec | eessm01/100-days-of-code | /python_for_everybody_p3/files_exercise1.py | 348 | 4.375 | 4 | """Python for everybody.
Exercise 1: Write a program to read through a
file and print the contents of the file (line
by line) all in upper case. Executing the
program will look as follows:
"""
fname = input('Enter a file name: ')
try:
fhand = open(fname)
except:
print('File not found')
exit()
for line in fhand:
print(line)
| true |
b01c74c82073bf2a8cfdbbba7ac08bfd433a4560 | eessm01/100-days-of-code | /platzi_OOP_python/insertion_sort.py | 799 | 4.21875 | 4 | from random import randint
def insertion_sort(one_list):
# iterate over one_list from 1 to list's length
for i in range(1, len(one_list)):
current_element = one_list[i]
# iterate over all elements in the left side (from i-1 to 0)
for j in range(i-1,-1,-1):
# compare current element whith each left element
if current_element < one_list[j]:
# if current_element is smaller, then swap
one_list[j+1] = one_list[j]
one_list[j] = current_element
return one_list
if __name__ == "__main__":
size = int(input('De que tamaño será la lista: '))
my_list = [randint(0, 100) for i in range(size)]
print(my_list)
ordered_list = insertion_sort(my_list)
print(ordered_list) | true |
3869deac3ad24925a63d2cdaeb4db9431e08a8af | eessm01/100-days-of-code | /real_python/day10_11_dear_pythonic_santa_claus.py | 1,732 | 4.28125 | 4 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""
Exercises from https://realpython.com/python-thinking-recursively/
The algorithm for interative present delivery implemented in Python
Now that we have some intuition about recursion, let's introduce the formal
definition of a recursive function. A recursive function is a function defined
in terms of itself via self-referencial expressions.
This means that the function will continue to call itself and repeat its
behavior until some condition is met to return a result. All recursive
functions share a common structure made up of two parts:
1. base case
2. recursive case.
"""
houses = ["Eric's house", "Kenny's house", "Kyle's house", "Stan's house"]
def deliver_presents_iteratively():
for house in houses:
print("Delivering present to", house)
# deliver_presents_iteratively()
# Each function call represents an elf doing his work
def deliver_presents_elves_iteratively(houses):
# Worker elf doing his work
if len(houses) == 1:
house = houses[0]
print("Delivering presents to", house)
# Manager elf doing his work
else:
mid = len(houses) // 2
first_half = houses[:mid]
second_half = houses[mid:]
# Divides his work among two elves
deliver_presents_elves_iteratively(first_half)
deliver_presents_elves_iteratively(second_half)
deliver_presents_elves_iteratively(houses)
# Recursive function for calculating n! implemented in Python
def factorial_recursive(n):
#Base case: 1! = 1
if n == 1:
return 1
# Recursive case: n! = n * (n-1)!
else:
return n * factorial_recursive(n-1)
factorial = factorial_recursive(8)
print(factorial)
| true |
c2cde7223eafaf4d2c98b3bdef23a6653511f93e | BitPunchZ/Leetcode-in-python-50-Algorithms-Coding-Interview-Questions | /Algorithms and data structures implementation/binary search/index.py | 678 | 4.34375 | 4 |
def binarySearch(arr, target):
left = 0
right = len(arr)-1
while left <= right:
mid = (left+right)//2
# Check if x is present at mid
if arr[mid] == target:
return mid
# If x is greater, ignore left half
elif arr[mid] < target:
left = mid + 1
# If x is smaller, ignore right half
else:
right = mid - 1
# If we reach here, then the element was not present
return -1
arr = [1, 2, 3, 4, 5, 6]
target = 6
result = binarySearch(arr, target)
if result != -1:
print("Element is present at index %d" % result)
else:
print("Element is not present in array")
| true |
efd43f194e740f108d25a1a7a8e3fce39e208d5a | DhananjayNarayan/Programming-in-Python | /Google IT Automation with Python/01. Crash Course on Python/GuestList.py | 815 | 4.5 | 4 | """
The guest_list function reads in a list of tuples with the name, age, and profession of each party guest, and prints the sentence "Guest is X years old and works as __." for each one.
For example, guest_list(('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer"))
should print out:
Ken is 30 years old and works as Chef.
Pat is 35 years old and works as Lawyer.
Amanda is 25 years old and works as Engineer.
"""
def guest_list(guests):
for guest in guests:
name,age,profession=guest
print(f"{name} is {age} years old and works as {profession}")
guest_list([('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")])
"""
Output should match:
Ken is 30 years old and works as Chef
Pat is 35 years old and works as Lawyer
Amanda is 25 years old and works as Engineer
"""
| true |
1bf31d944d5650e5c3c2bd35a75dbef782f24ec7 | ReDi-school-Berlin/lesson-6-exercises | /6-dictionaries/dictionaries.py | 1,298 | 4.5 | 4 | # What are some differences between dictionaries and lists?
# dict is not indexable
# lists are ordered and dictionaries aren't
# dictionaries cannot have duplicate keys
# --------------------
# How to create an empty dictionary
person = {}
# --------------------
# add values for this person, like name, phone, email, address etc in the dictionary
person["name"] = "Harika"
person["phone"] = 125384804
person["address"] = "Berlin"
# --------------------
# Check if the dictionary has a key that doesn't exist (id)
print("id" in person)
print("phone" in person)
# ----------------
# get person's phone. Hint: there are two ways
# print(person["phone"])
# print(person.get("phone"))
# print(person["id"])
print(person.get("id"))
# ----------------
# Get all the keys of this person dictionary
print(person.keys())
# ----------------
# Get all the values of this person dictionary
print(person.values())
# ----------------
# Change person's address
person["address"] = "Istanbul"
print(person)
# ----------------
# Remove person's phone Hint: two ways to do it (pop/del)
# person.pop("phone")
del person["phone"]
print(person)
person.clear()
print(person)
# Find more info about python dictionaries here -> https://www.w3schools.com/python/python_dictionaries.asp | true |
9a27ab3cacd389a2bd69066a4241542185256072 | tomdefeo/Self_Taught_Examples | /python_ex284.py | 419 | 4.3125 | 4 | # I changed the variable in this example from
#
text in older versions of the book to t
# so the example fits on smaller devices. If you have an older
# version of the book, you can email me at cory@theselftaughtprogrammer.io
# and I will send you the newest version. Thank you so much for purchasing my book!
import re
t = "__one__ __two__ __three__"
results = re.findall("__.*?__", t)
for match in results:
print(match)
| true |
d6c7cd46e60e6aa74cdd28de4f94aa45a65eb861 | GarrisonParrish/binary-calculator | /decimal_conversions.py | 1,823 | 4.1875 | 4 | """Handle conversions from decimal (as integer/float) to other forms."""
# NOTE: A lot of this code is just plain bad
def dec_to_bin(dec: int, N: int = 32):
"""Converts decimal integer to N-bit unsigned binary as a list. N defaults to 32 bits."""
# take dec, use algorithm to display as a string of 1's and 0's in 16-bit binary
# 0. Check if the decimal value exceeds the maximum alotted space (whatever that is)
# 1. Make an array of size N with all ints 0
# 2. Starting from leftmost bit (index bits-1):
# 3. bit = dec % 2
# 4. dec = dec / 2
# 5. repeat
# 6. If you run out of space early, terminate looping and leave the rest as 0
if (dec > ( 2**N + ( 2**N - 1))):
print(f"Cannot represent { dec } in { N } bits.")
return ""
# NOTE: Now we will have to be able to handle a null string.
# Either this or we will have to throw an exception instead.
bits: int[N] = [0] * N # initializes list with N number of 0's
# bits are either 1 or 0. Will read these into a string afterwards.
dec_copy: int = dec
i: int = N-1
while dec_copy > 0:
bits[i] = dec_copy % 2
dec_copy = dec_copy // 2 # floor division
i -= 1
return bits
def dec_to_ones_compl(dec):
"""Converts a decimal to signed ones complement."""
# NOTE: this one is broken
# If dec is negative (below 0):
# Take absolute value
# Convert to unsigned magnitude binary
# Convert to ones complement with neg = True
# If dec is positive:
# Convert to unsigned magnitude binary
# Convert to ones complement with neg = False (changes nothing)
neg: bool = False
if dec < 0:
neg = True
dec = abs(dec)
# return bin_to_ones_compl(dec_to_bin(dec, 8), neg)
return 0
| true |
2726d03db151046c1091b93d14a5593c2d368e52 | vrillusions/python-snippets | /ip2int/ip2int_py3.py | 963 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Asks for an IPv4 address and convert to integer.
In Python v3.3 the ipaddress module was added so this is much simpler
"""
import sys
import ipaddress
__version__ = '0.1.0-dev'
def main(argv=None):
"""The main function.
:param list argv: List of arguments passed to command line. Default is None,
which then will translate to having it set to sys.argv.
:return: Optionally returns a numeric exit code. If not given then will
default to 0.
:rtype: int
"""
if argv is None:
argv = sys.argv
if argv[1]:
ip_address = argv[1]
else:
ip_address = input("Enter an ipv4 dotted quad or decimal: ")
if ip_address.isdigit():
# Received a decimal, convert to ip
print(str(ipaddress.ip_address(int(ip_address))))
else:
print(int(ipaddress.ip_address(ip_address)))
if __name__ == "__main__":
sys.exit(main())
| true |
30d6d86bbcdcfee563d26985ccfaae90c8480397 | Splufic-Automation-Systems-Ltd/Python-Training-Online-Cohort-One | /Week Three/Day 2/temp.py | 340 | 4.375 | 4 |
import math
# a python program that converts temperature from Farenheit to Celcius
# get the user input
fahrenheit = input('Enter the temperature in degrees Fahrenheit: ')
# calculate the result
result = (5/9 * (int(fahrenheit) - 32))
result = math.trunc(result)
# print the result
print(f'The temperature in degrees Celsius is {result}') | true |
d1d792d85b93fcb95cfc3183cf05541dd8579d84 | rotus/the-python-bible | /tuple_examples.py | 248 | 4.125 | 4 | # Tuples, like lists, hold values - Except tuple data CANNOT be changed
# Useful for storing data/values that never need updated or modified
our_tuple = (1,2,3,"a","b")
print(our_tuple)
# Pull data out of individual elements
print(our_tuple[3])
| true |
9cf228ee2b0cd2fa8899ce07b5ccc5738d729e92 | rotus/the-python-bible | /dictionary_basics.py | 394 | 4.5625 | 5 | # Used to store values with "keys" and then can retreive values based on those keys
students = {"Alice":25, "Bob":27, "Claire":17, "Dan":21, "Emma":25}
print(students)
# extract Dan's value from dict
print(students["Dan"])
# Update Alice's age
print(students["Alice"])
students["Alice"] = 26
print(students["Alice"])
print(students.items())
print(students.keys())
print(students.values())
| true |
ba5f177e8ed7dff0164f72206401d5dd35ab690a | johnnymcodes/cs131b_python_programming | /4_functions/w10exhand.py | 1,504 | 4.21875 | 4 | # Write a program that expects numeric command line arguments and calls
# functions to print descriptive statistics such as the mean, median,
# mode, and midpoint.
# Week 9 : Severance 4
import sys #expects numeric command line arguments
cmarg = sys.argv[1:] #returns a list of cmd arguments
numlist = list()
for arg in cmarg:
try:
number = float(arg)
numlist.append(number)
# except:
# continue
except Exception as err:
print(arg, ' is not a number')
print(err)
print()
print(numlist)
def mode(numlist):
mode = 0
counts = dict()
for number in numlist:
if number not in counts:
counts[number] = 1
else:
counts[number] += 1
lst = list()
for number, count in list(counts.items()):
lst.append((count, number))
lst.sort(reverse=1)
for count, number in lst[:1]:
mode = number;
print(mode, " is the mode appearing ", count, " times")
return mode;
def median(numlist):
numlist.sort()
middle = int(len(numlist)/2)
median = numlist[middle]
print('The median is : ', median)
return median
def midpoint(numlist):
maxnum = max(numlist)
minnum = min(numlist)
midpoint = (maxnum-minnum)/2
print('The midpoint is : ', midpoint)
def mean(numlist):
sumnum = sum(numlist)
mean = sumnum/len(numlist)
print('The mean is : ', mean)
mode(numlist)
median(numlist)
midpoint(numlist)
mean(numlist) | true |
87f7b24055a392eb6a29a2a72b8b9395b4c083fe | johnnymcodes/cs131b_python_programming | /6_strings/sortuserinput.py | 944 | 4.5625 | 5 | #intro to python
#sort user input
#write a program that prints out the unique command line arguments
#it receives, in alphabetical order
import sys
cmdarg = sys.argv[1:]
cmdarg.sort()
delimiter = ' '
if len(cmdarg) > 1:
joinstring = delimiter.join(sys.argv[1:])
print('this is your command argument ', joinstring)
joinstring = delimiter.join(cmdarg)
print('this is your command argument sorted ! ', joinstring, '\n')
print('this program prints your string in alphabetical order')
string = input('enter a string :')
splitstring = string.split() #creating a list using stirng method split()
print('this is your split string ', splitstring)
joinstring = delimiter.join(splitstring)
print('this is your split string list joined back ', joinstring)
splitstring.sort() #no return value for sorted, modifies data
joinstring = delimiter.join(splitstring)
print('this is your sorted string ! ', joinstring)
| true |
8d88e73998d7d8bdfb3d323a963369c44aee27db | aliyakm/ICT_task1 | /3.py | 521 | 4.28125 | 4 | print("Please, choose the appropriate unit: feet = 1, meter = 2.")
unit = int(input())
print("Please, enter width and length of the room, respectively")
width = float(input())
length = float(input())
if unit == 1:
area = width*length
result = "The area of the room is {0} feets"
print(result.format(area))
elif unit == 2:
area = width*length
result = "The area of the room is {0} meters"
print(result.format(area))
else:
print("You didn't write a correct number of unit")
| true |
2f91d697437a7ae3ffb51c07443634f68505566b | androidgilbert/python-test | /ex33.py | 514 | 4.1875 | 4 |
def test_while(a,b):
numbers=[]
i=0
while i<a:
print "At the top is %d"%i
numbers.append(i)
i=i+b
print "numbers now:",numbers
print "at the bottom i is %d"%i
return numbers
def test_for(a):
numbers=[]
for i in range(0,a,3):
print "at the top is %d"%i
numbers.append(i)
print "numbers now:",numbers
print "at the bottom i is %d"%i
return numbers
tests=test_while(8,3)
abc=test_for(8)
print "the numbers:"
for num in tests:
print num
print "the abc:"
for a in abc:
print a | true |
00cf375c449164d643f12c421ffc3fbbde8a789e | androidgilbert/python-test | /ex30.py | 410 | 4.15625 | 4 | people=30
cars=40
buses=15
if cars>people:
print "we should take the cars"
elif cars<people:
print "we should not take the cars"
else:
print "we can't decide"
if buses>cars:
print "that is too many buses"
elif buses<cars:
print "maybe we could take the buses"
else:
print "we still can not decide"
if people>buses:
print "Alright,let us just take the buses."
else:
print "file,let us stay home then." | true |
3391a8aed49e4335f75ad4b18ac26639b9752b6e | JenySadadia/MIT-assignments-Python | /Assignment2/list_comprehension(OPT.2).py | 714 | 4.125 | 4 | print 'Exercise OPT.2 : List comprehension Challenges(tricky!)'
print '(1)'
print 'find integer number from list:'
def int_element(lists):
return [element for element in lists if isinstance(element, int)]
lists = [52,53.5,"grp4",65,42,35]
print int_element(lists)
print '(2)'
print 'Here the y = x*x + 1 and [x,y] will be:'
print ([[x,x*x+1] for x in range(-5,6) if 0 <= x*x + 1 <=10])
print '(3)'
print 'The posible solutions for [x,y] with radious 5'
print ([[x,y] for x in range (-5,6) for y in range(-5,6) if x*x + y*y == 25])
print '(4)'
print 'List comprehension for Celsius to Fahrenheit'
celsius = [22,28,33,35,42,52]
print ([fahrenhit *(9/5) + 32 for fahrenhit in celsius])
| true |
860251764c96cccf6db12d1695ae1774d9332dc4 | Tanner0397/LightUp | /src/chromosome.py | 2,288 | 4.125 | 4 | """
Tanner Wendland
9/7/18
CS5401
Missouri University of Science and Technology
"""
from orderedset import OrderedSet
"""
This is the class defintion of a chromosome. A chromosome has genetic code that ddetermines the phenotype of the population member (the placement of the bulbs).
The genetic code is a list of integer tuples, each tuple representing a bulb placement with the tupes being (row, col)
While each entry in the genetic code is independed (and unordered) from one another since no bulb placement directly determines the placement of an other bulb on the bulb,
I use an OrderedSet to remove duplicate entries to avoid have redundant genes, and to keep the list in order when remove duplicate genes.
"""
class chromosome:
"""
Chromosme constructor. No Paramaters
"""
def __init__(self):
self.genetic_code = []
"""
Paramaters: object, any object but for this class it will always be a tuple
Return: None
This function will append an object passed to it to the genetic code of the chromosome
"""
def append(self, object):
self.genetic_code.append(object)
"""
Paramters: None
Return: None
This function simply removes any duplicate entires within the chromosome, since no two bulbs can occupy the same panel
"""
def remove_duplicates(self):
#still use a list, but set removes the duplicate entries. Keep in order of list
self.genetic_code = list(OrderedSet(self.genetic_code))
"""functions defined for chromosome so that chromosomes acts similar to a list"""
def __getitem__(self, key):
return self.genetic_code[key]
def __setitem__(self, key, value):
self.genetic_code[key] = value
def __str__(self):
return str(self.genetic_code)
def __len__(self):
return len(self.genetic_code)
def __contains__(self, value):
return value in self.genetic_code
def length(self):
return len(self.genetic_code)
def remove_gene(self, gene):
#Since this fucntion is only used once when trying to remove dummy genes, if the gene is not present then ignore
try:
self.genetic_code.remove(gene)
except:
pass
| true |
a221f1dd62fc93c85c1329c670fe4d330df35caa | imthefrizzlefry/PythonPractice | /DailyCodingChallenge/Hard_Problem004.py | 1,069 | 4.125 | 4 | import logging
'''This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
You can modify the input array in-place.'''
def firstMissingPositiveInt(myArray):
''' Method to return the first positive integer missing from an array'''
myArray.sort()
lowestFound = 1
for i in myArray:
if i >= 1:
if i == lowestFound:
lowestFound = lowestFound + 1
elif i > lowestFound:
return lowestFound
return lowestFound
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
a = [3,4,-1,1]#2
result = firstMissingPositiveInt(a)
logging.debug(result)
a=[1,1,1,1,2,4,0]#3
result = firstMissingPositiveInt(a)
logging.debug(result) | true |
79dacd2b79eb76486bfcb0ad860b01eced6ff016 | imthefrizzlefry/PythonPractice | /DailyCodingChallenge/Hard_Problem012.py | 1,032 | 4.53125 | 5 | '''This problem was asked by Amazon.
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.
For example, if N is 4, then there are 5 unique ways:
1, 1, 1, 1
2, 1, 1
1, 2, 1
1, 1, 2
2, 2
What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
'''
def stair_climb(n,s):
if n == 0: return 1
nums = [0] * (n+1)
nums[0] = 1
for i in range(1,n+1):
total = 0
for j in s:
if i-j >= 0: total += nums[i-j]
nums[i] = total
return nums[n]
if __name__ == '__main__':
print(stair_climb(0, [1,2]))
print(stair_climb(1, [1,2]))
print(stair_climb(2, [1,2]))
print(stair_climb(3, [1,2]))
print(stair_climb(5, [1,2]))
print(stair_climb(10, [1,2])) | true |
b075eaa1eb0118a9f0fd0e112b91f318e4a98a20 | Aifedayo/Logic | /palindrome.py | 346 | 4.375 | 4 | def palindrome(string):
'''
Python function that checks whether a word
or phrase is palindrome or not
'''
new_string = string.replace(' ','')
if new_string == new_string[::-1]:
print(f'{string} is a palindrome')
else:
print(f'{string} is not a palindrome')
palindrome(input('Enter a string here: '))
| true |
2b288e37ceb0c00528623ce6c863597d09aebfb8 | ish-suarez/afs-200 | /week5/function/function.py | 481 | 4.1875 | 4 | def step1():
user_input = []
print(f'I will be asking you for 3 numbers')
for i in range(3):
num = int(input(f'Give me a number: '))
user_input.append(num)
input_max = max(num for num in user_input)
input_min = min(num for num in user_input)
print(f'Your Numbers are: {user_input}. Calculating the max. ')
print(f'The Max from the numbers given is {input_max}')
print(f'The Min from the numbers given is {input_min}')
step1() | true |
affa4eda6861fe0c5a2e31f232d3714fa15d84e8 | ish-suarez/afs-200 | /week2/evenOrOdd/evenOrOdd.py | 1,078 | 4.28125 | 4 | # Getting input to determine if numbers are even or odd
def user_input_eve_or_odd():
number = int(input('Give me a number and I will tell you if it is even or odd? '))
check_if_even_or_odd = number % 2
if check_if_even_or_odd == 0:
print(f"{number} is Even")
else:
print(f"{number} is Odd")
user_input_eve_or_odd()
# Is 'Number' a multiple of 4
def is_number_multiple_of_4():
number = int(input('Give me a number and I will tell you if it is a multiple of 4... '))
if number % 4 == 0:
print(f"Yes, {number} is a multiple of 4")
else:
print(f"No, {number} is not a multiple of 4")
is_number_multiple_of_4()
# Does 'Num' divide evenly into 'Check'
def is_it_divisible():
num = int(input('Give me a number to be divided... '))
check = int(input(f"Give me a number that {num} will be divided by... "))
if num % check == 0:
print(f"The numbers {num} and {check} are Evenly Divisible")
else:
print(f"The numbers {num} and {check} are Not Evenly Divisible")
is_it_divisible()
| true |
1ee69b4669c48ad85dd511ae57d7d4125cf6f645 | VimleshS/python-design-pattern | /Strategy pattern/solution_1.py | 2,021 | 4.125 | 4 | """
All the classes must in a seperate file.
Problems in this approch.
Order Class
It is not adhering to S of solid principles
There is no reason for order class to know about shipper.
Shipping Cost
Uses a default contructor.
Uses the shipper type stored in a shipper class to calculate cost(number crunching)
It uses lots of elif..(which means something is wrong)
If we have to add a new shipper we have to add a new elif and write the private helper method to get the cost, which
violates the O in solid principles
In a last section were we instanciate the shippingcost calculator, we are programming to implementation not to a abstraction
which violates the D in solid priciples.
"""
class Order(object):
def __init__(self, shipper):
self._shipper = shipper
@property
def shipper(self):
return self._shipper
#
class Shipper(object):
fedex = 1
ups = 2
postal = 3
class ShippingCost(object):
def shipping_cost(self, order):
if order.shipper == Shipper.fedex:
return self._fedex_cost(order)
elif order.shipper == Shipper.ups:
return self._ups_cost(order)
elif order.shipper == Shipper.postal:
return self._postal_cost(order)
else:
raise ValueError('Invalid shipper %s', order.shipper)
def _fedex_cost(self, order):
return 3.00
def _ups_cost(self, order):
return 4.00
def _postal_cost(self, order):
return 5.00
order = Order(Shipper.fedex)
cost_calulator = ShippingCost() # <-- violates D
cost = cost_calulator.shipping_cost(order)
assert cost == 3.0
# Test UPS shipping
order = Order(Shipper.ups)
cost_calulator = ShippingCost()
cost = cost_calulator.shipping_cost(order)
assert cost == 4.0
# Test Postal Service shipping
order = Order(Shipper.postal)
cost_calulator = ShippingCost()
cost = cost_calulator.shipping_cost(order)
assert cost == 5.0
print('Tests passed') | true |
3947858a10bb6fe6e1f0549d39c60f70de70a696 | UmberShadow/PigLatin | /UmberShadow_Pig Latin.py | 989 | 4.5 | 4 | #CJ Malson
#March 6th, 2021
#Intro to Python Programming
#Professor Wright
#I don't understand pig latin at all. What is this??
#Program requests a word (in lowercase letters) as input and translates the word into Pig Latin.
#If the word begins with a group of consonants, move them to the end of the word and add "ay". For instance, "chip" becomes "ipchay".
#If the word begins with a vowel, add "way" to the end of the word. For instance, "else" becomes "elseway".
#Ask the user to kindly insert a word to translate to Pig.
word = input("Enter word to translate: ")
#vowel and consonant letters
vowel = ['a','e','i','o','u']
consonant = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
#when the first letter of a word is a vowel, add "way" to the end.
if word[0] in vowel:
print(word + "way")
elif word[0] and word[1] in consonant:
print(word[2:] + word[0:2] + "ay")
else:
print(word[1:] + word[0] + 'ay')
| true |
693aa7a983a83814395518f00d68d6345502694b | luqiang21/Hackerrank.com | /Cracking the Coding Interview/Davis'_Staricase.py | 1,891 | 4.1875 | 4 | '''
Davis' staircase, climb by 1, 2 or 3 steps when given n stairs
in a staircase
'''
import numpy as np
def staircase(n):
# this function is written based on discussion of this problem on
# the website
A = [1,2,4]
A.append(sum(A))
A.append(A[1] + A[2] + A[3])
M = np.array([[1,1,0],[1,0,1],[1,0,0]])
An = np.array([[A[4], A[3], A[2]], [A[3],\
A[2], A[1]], [A[2], A[1], A[0]]])
if n < 5:
return A[n-1]
else:
return np.dot(An, np.matrix(M)**(n-5)).item(0)
print staircase(1) # 1
print staircase(30) # 53798080
print staircase(36) # 2082876103
def staircase(n):
# Recursive
if n == 1:
return 1
if n == 2:
return 2
if n == 3:
return 4
return staircase(n-1) + staircase(n-2) + staircase(n-3)
# same result, but take much longer time
print 'Recursive Approach'
print staircase(1) # 1
# print staircase(30) # 53798080
# print staircase(36) # 2082876103
memory = {1:1, 2:2, 3:4}
def staircase(n):
if n not in memory.keys():
memory[n] = staircase(n-1) + staircase(n-2) + staircase(n-3)
return memory[n]
# using memory, much more efficient
print staircase(1) # 1
print staircase(30) # 53798080
print staircase(36) # 2082876103
# DP approach
def staircase(n):
if n < 0:
return 0
elif n <= 1:
return 1
paths = [None] * (n + 1)
paths[0] = 1
paths[1] = 1
paths[2] = 2
for i in range(3, n + 1):
paths[i] = paths[i - 1] + paths[i - 2] + paths[i - 3]
return paths[n]
print 'DP'
print staircase(1) # 1
print staircase(30) # 53798080
print staircase(36) # 2082876103
# save space
def staircase(n):
if n < 0:
return 0
elif n <= 1:
return 1
paths = [1,1,2]
for i in range(3, n + 1):
count = paths[0] + paths[1] + paths[2]
paths[0] = paths[1]
paths[1] = paths[2]
paths[2] = count
return paths[2]
print 'Another DP save space version'
print staircase(1) # 1
print staircase(30) # 53798080
print staircase(36) # 2082876103 | true |
321cb60befeebd95889763e272177d7cdfd9f1a0 | sureshrmdec/algorithms | /app/dp/knapsack.py | 1,105 | 4.1875 | 4 | """
Given a weight limit for a knapsack, and a list of items with weights and benefits, find the optimal knapsack
which maximizes the benefit, whilee the total weight being less than the weight limit
https://www.youtube.com/watch?v=ipRGyCcbrGs
eg -
item 0 1 2 3
wt 5 2 8 6
benefit 9 3 1 4
wt limit = 10
soln: best items = 0 + 1 for benefit = 9 + 3 = 12 within a wt of 7
"""
def _find_best_knapsack(remaining_weight, wt_benefit_list, index, optimal_knapsack):
"""
:param remaining_weight integer
:param wt_benefit_tuple: list of tuple
:param index: index of current wt_benefit_list item being processed
:param optimal_knapsack: a tuple of (int[] knapsack_item_indices, benefit)
:return: a tuple of (list[], benefit) where list[] is all the items in the knapsack with total benefit
"""
def find_best_knapsack(weight_limit, wt_benefit_list):
"""
:param weight_limit: integer
:param wt_benefit_list: list of tuple with each tuple being (weight, benefit) pair
:return:
"""
return _find_best_knapsack(weight_limit, wt_benefit_list, 0, ([],0)) | true |
28d24e0531c3f15a5f79fd0501f8f58662452f0b | joaolrsarmento/university | /courses/CT-213/lab3_ct213_2020/hill_climbing.py | 1,841 | 4.1875 | 4 | from math import inf
import numpy as np
def hill_climbing(cost_function, neighbors, theta0, epsilon, max_iterations):
"""
Executes the Hill Climbing (HC) algorithm to minimize (optimize) a cost function.
:param cost_function: function to be minimized.
:type cost_function: function.
:param neighbors: function which returns the neighbors of a given point.
:type neighbors: list of numpy.array.
:param theta0: initial guess.
:type theta0: numpy.array.
:param epsilon: used to stop the optimization if the current cost is less than epsilon.
:type epsilon: float.
:param max_iterations: maximum number of iterations.
:type max_iterations: int.
:return theta: local minimum.
:rtype theta: numpy.array.
:return history: history of points visited by the algorithm.
:rtype history: list of numpy.array.
"""
# First guess
theta = theta0
history = [theta0]
# Number of iterations
num_iterations = 0
# Check stopping condition
while cost_function(theta) >= epsilon and num_iterations < max_iterations:
num_iterations += 1
# Starts the array best with None
best = np.array([None] * len(theta))
for neighbor in neighbors(theta):
# Checks if the best is None (is this the first attempt?) or
# the neighbor is better than best
if np.all(best == None) or cost_function(neighbor) < cost_function(best):
best = neighbor
# If there isn't a neighbor better than theta, return the answer
if cost_function(theta) < cost_function(best):
return theta, history
# Now, we should test the best
theta = best
# Stores this new theta
history.append(theta)
return theta, history
| true |
95bf38eccb1a70731cc9cc4602a440fdb98043dd | ranjanlamsal/Python_Revision | /file_handling_write.py | 1,891 | 4.625 | 5 | '''In write mode we have attributes such as :
To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
'''
'''
in write mode:
.write() : which creates the file is not existed . If existed then override the file content
and replace them with the content given in argument.
'''
f = open("Ranjan1.txt","w")
#Ranjan.txt file doesnot exist in the python folder. It is still not created
f.write("Ranjan is a good boy\n")
#now a new file named Ranjan.txt is created with content passed in argument
f.write("Ranjan is not a good boy\n")
'''
Point to be noted: write attribute create new file if not existed and replace the content of the file
if it is already present in project directory. But if you use .write() attribute again
in the same bunch of code i.e without once closing the file pointer, new contents are appended in the
file rather than replacing the old content.
Now when the program is closed and again the file pointer for the same file is opened in new program
then the write attribute override the old content and replace them
'''
f.close()
'''In append mode
.write() attribute is used to append the content given in argument in the file.
this also creates a file if not existed but if existed then append the content in old contents
'''
f = open("Ranjan1.txt", "a")
f.write("Ranjan is a handsome muscular man.\n")
'''
If the file pointer is closed and then again opened in apend mode then the contents are appended in the file
'''
a = f.write("Hey Buddy")
#if we store this attribute then the nukber of characted passed as argument is stored in object
print(a)
f.close()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.