blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
e9bac2547bac4dc0637c3abee43a3194802cbddc | tab0r/Week0 | /day2/src/dict_exercise.py | 1,762 | 4.15625 | 4 | def dict_to_str(d):
'''
INPUT: dict
OUTPUT: str
Return a str containing each key and value in dict d. Keys and values are
separated by a colon and a space. Each key-value pair is separated by a new
line.
For example:
a: 1
b: 2
For nice pythonic code, use iteritems!
Note: it's possible to do this in 1 line using list comprehensions and the
join method.
'''
S = ''
for key in d.keys():
S += str(key) + ": " + str(d[key]) + "\n"
return S.rstrip()
def dict_to_str_sorted(d):
'''
INPUT: dict
OUTPUT: str
Return a str containing each key and value in dict d. Keys and values are
separated by a colon and a space. Each key-value pair is sorted in ascending order by key.
This is sorted version of dict_to_str().
Note: This one is also doable in one line!
'''
S = []
for key in d.keys():
S.append(str(key) + ": " + str(d[key]))
S.sort()
return '\n'.join(S)
def dict_difference(d1, d2):
'''
INPUT: dict, dict
OUTPUT: dict
Combine the two dictionaries, d1 and d2 as follows. The keys are the union of the keys
from each dictionary. If the keys are in both dictionaries then the values should be the
absolute value of the difference between the two values. If a value is only in one dictionary, the
value should be the absolute value of that value.
'''
newDict = {}
s1 = set(d1.keys())
s2 = set(d2.keys())
newKeys = s1.union(s2)
for key in newKeys:
if key in d1 and key in d2:
newDict[key] = abs(d1[key]-d2[key])
elif key in d1:
newDict[key] = abs(d1[key])
elif key in d2:
newDict[key] = abs(d2[key])
return newDict
| true |
360f00f7d38fa89588606cf429e0c1e9321f8680 | mounika123chowdary/Coding | /cutting_paper_squares.py | 809 | 4.1875 | 4 | '''Mary has an n x m piece of paper that she wants to cut into 1 x 1 pieces according to the following rules:
She can only cut one piece of paper at a time, meaning she cannot fold the paper or layer already-cut pieces on top of one another.
Each cut is a straight line from one side of the paper to the other side of the paper. For example, the diagram below depicts the three possible ways to cut a 3 x 2 piece of paper:
Given n and m, find and print the minimum number of cuts Mary must make to cut the paper into n.m squares that are 1 x 1 unit in size.
Note : you have to write the complete code for taking input and print the result.
Input Format
A single line of two space-separated integers denoting the respective values of n and m.
'''
n,m=map(int,input().split())
print((n-1)+n*(m-1))
| true |
12b9d7a90eb7d3e8fbec3e17144564f49698e507 | BenjaminNicholson/cp1404practicals | /cp1404practicals/Prac_05/word_occurrences.py | 401 | 4.25 | 4 | words_for_counting = {}
number_of_words = input("Text: ")
words = number_of_words.split()
for word in words:
frequency = words_for_counting.get(word, 0)
words_for_counting[word] = frequency + 1
words = list(words_for_counting.keys())
words.sort()
max_length = max((len(word) for word in words))
for word in words:
print("{:{}} : {}".format(word, max_length, words_for_counting[word]))
| true |
a44221832be1eece6cbcbd78df99a8dcc4aea9ab | mcampo2/python-exercises | /chapter_03/exercise_04.py | 539 | 4.59375 | 5 | #!/usr/bin/env python3
# (Geometry: area of a pentagon) The area of a pentagon can be computed using the
# following formula (s is the length of a side):
# Area = (5 X s²) / (4 X tan(π/5))
# Write a program that prompts the user to enter the side of a pentagon and displays
# the area. Here is a sample run:
# Enter the side: 5.5 [Enter]
# The area of the pentagon is 53.04444136781625
import math
s = eval(input("Enter the side: "))
area = (5 * s ** 2) / (4 * math.tan(math.pi/5))
print("The area of the pentagon is", area)
| true |
66106c9065c8dcabaa8a094326a2b601cdf07524 | mcampo2/python-exercises | /chapter_03/exercise_11.py | 523 | 4.34375 | 4 | #!/usr/bin/env python3
# (Reverse numbers) Write a program that prompts the user to enter a four-digit int-
# ger and displays the number in reverse order. Here is a sample run:
# Enter an integer: 3125 [Enter]
# The reversed number is 5213
reverse = ""
integer = eval(input("Enter an integer: "))
reverse += str(integer % 10)
integer //= 10
reverse += str(integer % 10)
integer //= 10
reverse += str(integer % 10)
integer //= 10
reverse += str(integer % 10)
integer //= 10
print("The reversed number is", reverse)
| true |
09fb28996aa732c01df70d674a369fafa05e0939 | mcampo2/python-exercises | /chapter_01/exercise_18.py | 410 | 4.5 | 4 | #/usr/bin/env python3
# (Turtle: draw a star) Write a program that draws a star, as shown in Figure 1.19c.
# (Hint: The inner angle of each point in the star is 36 degrees.)
import turtle
turtle.right(36+36)
turtle.forward(180)
turtle.right(180-36)
turtle.forward(180)
turtle.right(180-36)
turtle.forward(180)
turtle.right(180-36)
turtle.forward(180)
turtle.right(180-36)
turtle.forward(180)
turtle.done()
| true |
b0c6434539536ee3c7db23fb6977ca940037d147 | mcampo2/python-exercises | /chapter_03/exercise_02.py | 1,594 | 4.53125 | 5 | #!/usr/bin/env python3
# (Geometry: great circle distance) The great circle distance is the distance between
# two points on the surface of a sphere. Let (x1, y2) and (x2, y2) be the geographical
# latitude and longitude of two points. The great circle distance between the two
# points can be computed using the following formula:
# d = radius X arccos(sin(x₁) X sin(x₂) + cos(x₁) X cos(x₂) X cos(y₁ - y₂))
# Write a program that prompts the user to enter the latitude and longitude of two
# points on the earth in degrees and displays its great circle distance. The average
# earth radius is 6,371.01 km. Note that you need to convert the degrees into radians
# using the math.radians function since the Python trigonometric functions use
# radians. The latitude and longitude degrees in the formula are for north and west.
# Use negative to indicate south and east degrees. Here is a sample run:
# Enter point 1 (latitude and longitude) in degrees:
# 39.55, -116.25 [Enter]
# Enter point 2 (latitude and longitude) in degrees:
# 41.5, 87.37 [Enter]
# The distance between the two points is 10691.79183231593 km
import math
RADIUS = 6371.01
x1, y1 = eval(input("Enter point 1 (latitude and longitude) in degrees: "))
x2, y2 = eval(input("Enter point 2 (latitude and longitude) in degrees: "))
x1 = math.radians(x1)
y1 = math.radians(y1)
x2 = math.radians(x2)
y2 = math.radians(y2)
distance = RADIUS * math.acos(math.sin(x1) * math.sin(x2) \
+ math.cos(x1) * math.cos(x2) * math.cos(y1 - y2))
print("The distance between the two points is", distance, "km")
| true |
e4c59a6991788b320fdfd4aeea0e8c894d403d39 | mcampo2/python-exercises | /chapter_02/exercise_06.py | 680 | 4.46875 | 4 | #!/usr/bin/env python3
# (Sum the digits in an integer) Write a program that reads an integer between 0 and
# 1000 and adds all the digits in the integer. For example, if an integer is 932, the
# sum of all it's digits is 14. (Hint: Use the % operator to extract digits, and use the //)
# operator to remove the extracted digit. For instance, 932 % 10 = 2 and 932 //
# 10 = 93.) Here is a sample run:
# Enter a number between 0 and 1000: 999 [Enter]
# The sum of the digits is 27
number = eval(input("Enter a number between 0 and 1000: "))
sum = number // 1000
sum += number % 1000 // 100
sum += number % 100 // 10
sum += number % 10
print("The sum of the digits is", sum)
| true |
ebb74354b22feb3d6d6a27b546111115d4ae8964 | praisethedeviI/1-course-python | /fourth/pin_checker.py | 788 | 4.125 | 4 | def check_pin(pin):
nums = list(map(int, pin.split("-")))
if is_prime_num(nums[0]) and is_palindrome_num(nums[1]) and is_a_power_of_two(nums[2]):
message = "Корректен"
else:
message = "Некорректен"
return message
def is_prime_num(num):
tmp = 2
while num % tmp != 0:
tmp += 1
if tmp == num:
return True
else:
return False
def is_palindrome_num(num):
if str(num) == str(num)[::-1]:
return True
else:
return False
def is_a_power_of_two(num):
checker = True
while num != 1:
if num % 2:
checker = False
break
num /= 2
return checker
pin_code = input()
print(check_pin(pin_code))
| true |
65378f3f4696073f33c1708935fc45f8deb2e5d1 | ishaansathaye/APCSP | /programs/guessingGame.py | 1,677 | 4.125 | 4 | # from tkinter import *
#
# root = Tk()
# root.title("Computer Guessing Game")
# root.geometry("500x500")
# lowVar = StringVar()
# highVar = StringVar()
# labelVar = StringVar()
# guessVar = StringVar()
#
# def range():
# lowLabel = Label(root, textvariable=lowVar)
# lowVar.set("What is the lower bound of the range?: ")
# lowLabel.place(x=0, y=10)
# text1 = Text(root, height=1.05, width=10)
# text1.place(x=250, y=10)
#
# highLabel = Label(root, textvariable=highVar)
# highVar.set("What is the higher bound of the range?: ")
# highLabel.place(x=0, y=40)
# text2 = Text(root, height=1.05, width=10)
# text2.place(x=250, y=40)
#
#
# # lBound, hBound = range()
# # lowBound = str(lBound-1)
# # highBound = str(hBound)
#
# randomLabel = Label(root, textvariable=labelVar)
# labelVar.set("Computer Guess: ")
# randomLabel.place(x=150, y=250)
#
# randomLabel = Label(root, textvariable=guessVar)
# guessVar.set("None")
# randomLabel.place(x=260, y=250)
#
# def math()
#
#
# newMatch = True
# while newMatch:
# guessVar.set(text1.get)
# root.mainloop()
low = input("What is the lower bound of the range?: ")
high = input("What is the higher bound of the range?: ")
print()
print()
intLow = int(low)-1
intHigh = int(high)
match = True
while match:
guess = round((intLow + intHigh) / 2)
print("Computer's Guess: ", guess)
correct = input("Is the matching number? (low, correct, high): ")
print()
if correct == "low":
intLow = guess
elif correct == "high":
intHigh = guess
elif correct == "correct":
print()
print("I guessed your number:", guess)
match = False | true |
920ed667628f9fbb5783d72dd234a372c1f0ab87 | Asish-Kumar/Python_Continued | /CountingValleys.py | 743 | 4.25 | 4 | """
A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.
example input : UDDDUDUU
"""
def countingValleys(n, s):
result = 0
k = 0
start = False
for i in range(n):
if k < 0:
start = True
else:
start = False
if s[i] == 'D':
k -= 1
else:
k += 1
print(start, k)
if start and k==0:
result += 1
return result
s = input("Enter U and D combinations: ")
print(countingValleys(len(s), s))
| true |
5e36170af1209383fed6749d2c7302971cd6c354 | dhalimon/Turtle | /race.py | 1,883 | 4.25 | 4 | import turtle
import random
player_one = turtle.Turtle()
player_one.color("green")
player_one.shape("turtle")
player_one.penup()
player_one.goto(-200,100)
player_two = player_one.clone()
player_two.color("blue")
player_two.penup()
player_two.goto(-200,100)
player_one.goto(300,60)
player_one.pendown()
player_one.circle(40)
player_one.penup()
player_one.goto(-200,100)
player_two.goto(300,-140)
player_two.pendown()
player_two.circle(40)
player_two.penup()
player_two.goto(-200,-100)
#Developing the Game
# Step 1: You’ll start by telling your program to check if either turtle has reached its home.
# Step 2: If they haven’t, then you’ll tell your program to allow the players to continue trying.
# Step 3: In each loop, you tell your program to roll the die by randomly picking a number from the list.
# Step 4: You then tell it to move the respective turtle accordingly, with the number of steps based on the outcome of this random selection.
#Creating the Die
die = [1,2,3,4,5,6]
for i in range(20):
if player_one.pos() >= (300,100):
print("Player One Wins!")
break
elif player_two.pos() >= (300,-100):
print("Player Two Wins!")
break
else:
player_one_turn = input("Press 'Enter' to roll the die ")
die_outcome = random.choice(die)
print("The result of the die roll is: ")
print(die_outcome)
print("The number of steps will be: ")
print(20*die_outcome)
player_one.fd(20*die_outcome)
player_two_turn = input("Press 'Enter' to roll the die ")
d = random.choice(die)
print("The result of the die roll is: ")
print(die_outcome)
print("The number of steps will be: ")
print(20*die_outcome)
player_two.fd(20*die_outcome)
| true |
e346adc9388fadbb152c9c5698b5425a8f78afd1 | hungnv21292/Machine-Learning-on-Coursera | /exe1/gradientDescent.py | 1,511 | 4.125 | 4 | import numpy as np
from computeCost import computeCost
def gradientDescent(X, y, theta, alpha, num_iters):
#GRADIENTDESCENT Performs gradient descent to learn theta
# theta = GRADIENTDESENT(X, y, theta, alpha, num_iters) updates theta by
# taking num_iters gradient steps with learning rate alpha
# Initialize some useful values
m = y.size # number of training examples
J_history = np.zeros(shape=(num_iters, 1))
#temp = np.zeros(shape=(2, 1))
temp = np.zeros(shape=(3, 1))
print X
for i in range(num_iters):
# ====================== YOUR CODE HERE ======================
# Instructions: Perform a single gradient step on the parameter vector
# theta.
#
# Hint: While debugging, it can be useful to print out the values
# of the cost function (computeCost) and gradient here.
#
predictions = X.dot(theta).flatten()
errors_x1 = (predictions - y) * X[:, 0]
errors_x2 = (predictions - y) * X[:, 1]
errors_x3 = (predictions - y) * X[:, 2]
temp[0] = theta[0] - alpha * (1.0 / m)*errors_x1.sum()
temp[1] = theta[1] - alpha * (1.0 / m)*errors_x2.sum()
temp[2] = theta[2] - alpha * (1.0 / m)*errors_x3.sum()
theta = temp
# ============================================================
# Save the cost J in every iteration
#J_history[i, 0] = computeCost(X, y, theta)
return theta, J_history
| true |
5cce1caf8666c82ea5f180d45188272a82e290d3 | Anupam-dagar/Work-with-Python | /Very Basic/remove_vowel.py | 435 | 4.5625 | 5 | #remove vowel from the string.
def anti_vowel(text):
result = ""
for char in text:
if char == "A" or char == "a" or char == "E" or char == "e" or char == "I" or char == "i" or char == "O" or char == "o" or char == "U" or char == "u":
result = result
else:
result = result + char
return result
string = raw_input("enter your word:")
answer = anti_vowel(string)
print answer | true |
0fb68f202520e3370e544f8b7d53a2ad0ad69c42 | Anupam-dagar/Work-with-Python | /Very Basic/factorial.py | 228 | 4.1875 | 4 | #calculate factoial of a number
def factorial(x):
result = 1
for i in range(1,x+1):
result = result * i
return result
number = int(raw_input("enter a number:"))
answer = factorial(number)
print answer | true |
fb067a66d72ae73131adf2dc34c0ce568ab87cad | kushagraagarwal19/PythonHomeworks | /HW2/5.py | 876 | 4.15625 | 4 | johnDays = int(input("Please enter the number of days John has worked"))
johnHours = int(input("Please enter the number of hours John has worked"))
johnMinutes = int(input("Please enter the number of minutes John has worked"))
billDays = int(input("Please enter the number of days bill has worked"))
billHours = int(input("Please enter the number of hours bill has worked"))
billMinutes = int(input("Please enter the number of minutes bill has worked"))
totalMinutes = johnMinutes + billMinutes
carryForwardHours = totalMinutes//60
totalMinutes = totalMinutes%60
totalHours = johnHours+billHours+carryForwardHours
carryForwardDays = totalHours//24
totalHours = totalHours%24
totalDays = carryForwardDays+johnDays+billDays
print("The total time both of them worked together is: {} days, {} hours and {} minutes.".format(str(totalDays), str(totalHours), str(totalMinutes))) | true |
df23c42f672c812f81c6f10ee3558bce3f51946c | BarnaTB/Level-Up | /user_model.py | 2,023 | 4.28125 | 4 | import re
class User:
"""
This class creates a user instance upon sign up of a user,
validates their email and password, combines their first and last names
then returns the appropriate message for each case.
"""
def __init__(self, first_name, last_name, phone_number, email, password):
self.first_name = first_name
self.last_name = last_name
self.phone_number = phone_number
self.email = email
self.password = password
def validate_email(self):
"""
Method checks that a user's email follows semantics for a valid email;
first characters must be letters followed by a fullstop, then the '@'
symbol followed by letters, a fullstop and then finally letters.
Returns the valid email.
"""
# source: https://docs.python.org/2/howto/regex.html
if not re.match(r"[^@.]+@[A-Za-z]+\.[a-z]+", self.email):
return 'Invalid email address!'
return self.email
def combine_name(self):
"""
Method checks that the entered values for names are strings.
If so it returns both names combined, else it requests the user to
enter string values.
"""
if self.first_name.isalpha() and self.last_name.isalpha():
username = self.first_name + " " + self.last_name
return username
return 'Names must be alphabets'
def validate_password(self):
"""
Method checks that a user's password follows specific criteria such as
at least one uppercase character, one lowercase, one number and one
spceial character. Password should also be atleast six characters long.
"""
# source: https://docs.python.org/2/howto/regex.html
if not re.match(r"[A-Za-z0-9@#]", self.password):
return 'Oops!, invalid password'
elif len(self.password) < 6:
return 'Password should be at least six characters long'
return 'Valid password!'
| true |
d5a2414bc8d3e3fb711cc0c43fac1122173d4388 | mitchellroe/exercises-for-programmers | /python/02-counting-the-number-of-characters/count.py | 381 | 4.3125 | 4 | #!/usr/bin/env python3
"""
Prompt for an input string and print the number of characters
"""
def main():
"""
Prompt for an input string and print the number of characters
"""
my_string = input("What is the input string? ")
num_of_chars = len(my_string)
print(my_string + " has " + str(num_of_chars) + " characters.")
if __name__ == '__main__':
main()
| true |
5d9192fb3a7f91af57e796ab3325891af0c2cabe | siraiwaqarali/Python-Learning | /Chapter-05/10. More About Lists.py | 582 | 4.15625 | 4 | # generate list with range function
# index method
generated_list = list(range(1, 11))
print(generated_list) # output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3]
print(numbers.index(3)) # gives the index of the provided element
print(numbers.index(3, 3)) # gives the index of the provided element and second argument is from which index to start searching
print(numbers.index(7, 4, 8)) # gives the index of the provided element, 2nd arg=start searching index & 3rd arg=stop searching
| true |
9e0d8659be7a01bfaccc5d978b4b495e571491a1 | siraiwaqarali/Python-Learning | /Chapter-03/ForLoopExample1.py | 405 | 4.125 | 4 | # sum of first ten natural numbers
total=0
for i in range(1,11): # for sum of 20 numbers range(1,21)
total+=i
print(f"Sum of first ten natural numbers is {total}")
# Sum of n natural numbers
n=input("Enter the number: ")
n=int(n)
total=0
for i in range(1,n+1): # Second argument is excluded so to reach n we give n+1
total+=i
print(f"Sum of first {n} natural numbers is {total}")
| true |
bf1c0a0d7e98d1d89ff053e71fdd374152848ae6 | siraiwaqarali/Python-Learning | /Chapter-01/PythonCalculations.py | 758 | 4.375 | 4 | print(2+3)
print(2-3)
print(2*3)
print(2/4) # This gives answer in fraction
print(4/2) # This gives 2.0
print(4//2) # This gives 2 beacuse it is integer division
print(2//4) # This gives 0 beacuse it is integer division
print(11//3) # This gives 3 beacuse it is integer division
print(6%2) # This gives 0
print(11%3) # This gives 2
print(2**3) # This gives 8 2 power 3 = 8
print(4**2) # This gives 16 4 power 2 = 16
#agr square root nikalna hu tou power 1/2 huti hai yani 0.5 tou exponent mn 0.5 dedo square root ajyega
#for square root of 2 we write
print(2**0.5) #This gives square root of 2
# there is another function for rounding the value which is round(value,digits)
print(round(2**0.5,4)) | true |
9ebdd87c5067140b6e3d5af41a58569552b85a11 | siraiwaqarali/Python-Learning | /Chapter-16/Exercise3.py | 652 | 4.15625 | 4 | '''
Exercise#03: Create any class and count no. of objects created for that class
'''
class Person:
count_instance = 0
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
# Increment count_instance each time the object/instance is created
Person.count_instance +=1
person1 = Person('Waqar Ali', 'Siyal', 21)
person2 = Person('Ahmed Ali', 'Siyal', 24)
person3 = Person('Usama', 'Shaikh', 20)
person4 = Person('Imtiaz', 'Buriro', 14)
person5 = Person('Uzair', 'Abro', 19)
print(f'No. of Objects: {Person.count_instance}') | true |
d1ecd5f71b352f254142854248f00f9188a11718 | siraiwaqarali/Python-Learning | /Chapter-05/6. is vs equals.py | 392 | 4.15625 | 4 | # compare lists
# ==, is
# == check values inside list
# is checks address inside memory
fruits1 = ['orange', 'apple', 'pear']
fruits2 = ['banana', 'kiwi', 'apple']
fruits3 = ['orange', 'apple', 'pear']
print(fruits1==fruits2) # False
print(fruits1==fruits3) # True
print(fruits1 is fruits3) # False | true |
d351fdf978fde1ea7045c7681b8afe871e25d6d4 | siraiwaqarali/Python-Learning | /Chapter-09/4. Nested List Comprehension.py | 388 | 4.4375 | 4 | example = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
# Create a list same as above using nested list comprehension
# new_list = []
# for j in range(3):
# new_list.append([1, 2, 3])
# print(new_list)
# nested_comp = [ [1, 2, 3] for i in range(3)] # but also generate nested list using list comprehension
nested_comp = [ [i for i in range(1,4)] for j in range(3)]
print(nested_comp) | true |
d6c33d2dc1ca4b5913aaa65fbc33f4c9622ec43d | EEsparaquia/Python_project | /script2.py | 420 | 4.25 | 4 | #! Python3
# Print functions and String
print('This is an example of print function')
#Everything in single quots is an String
print("\n")
print("This is an example of 'Single quots' " )
print("\n")
print('We\'re going to store')
print("\n")
print('Hi'+'There')
#Plus sign concatenate both strings
print('Hi','There')
#Comma add an space
print("\n")
print('Hi',5)
print('Hi '+str(5))
print("\n")
print(float('8.5')+5) | true |
5e1d7603eec9b98a94386628eed855ce39e05199 | EEsparaquia/Python_project | /script25.py | 911 | 4.40625 | 4 | #! Python3
# Programming tutorial:
# Reading from a CSV spreadsheet
## Example of the content of the file
## called example.csv:
# 1/2/2014,5,8,red
# 1/3/2014,5,2,green
# 1/4/2014,9,1,blue
import csv
with open('example.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
print(row)
print(row[0])
print(row[0],row[1])
print('\n')
## Passing the data into separates string:
with open('example.csv') as csvfile:
readCSV2 = csv.reader(csvfile, delimiter=',')
dates = []
colors = []
for row in readCSV2:
color = row[3]
date = row[0]
dates.append(date)
colors.append(color)
print(dates)
print(colors)
WhatColor = input('What color do you wish to know the date of?')
coldex = colors.index(WhatColor.lower()) #lower() for make all in lowercases
print(coldex)
theDate = dates[coldex]
print(theDate)
print('the date of the color',WhatColor,'is',theDate)
| true |
07ecbbc1a8bf0e46b6432dbea343063da6d55a7b | medisean/python-algorithm | /quick_sort.py | 645 | 4.125 | 4 | '''
Quick sort in python. Quick sort is not stable.
Time complexity: O(nlogn)
Space complexity: O(log2n)
'''
def quick_sort(lists, left, right):
if left >= right:
return lists
first = left
last = right
key = lists[first]
while first < last:
while first < last and lists[last] >= key:
last = last - 1
lists[first] = lists[last]
while first < last and lists[first] <= key:
first = first + 1
lists[last] = lists[first]
lists[first] = key
quick_sort(lists, left, first-1)
quick_sort(lists, last+1, right)
return lists
if __name__ == '__main__':
lists = [3, 2, 1, 5, 4]
print(quick_sort(lists, 0, len(lists) - 1)) | true |
4eec7dce66ee380c61c8e0c1b5b680a03b6fa4ad | ccaniano15/inClassWork | /text.py | 338 | 4.25 | 4 | shape = input("triangle or rectangle?")
if shape == "triangle":
width = int(input("what is the length?"))
height = int(input("what is the height?"))
print(width * height / 2)
elif shape == "rectangle":
width = int(input("what is the length?"))
height = int(input("what is the height?"))
print(width * height)
else:
print("error")
| true |
953f98b68c708b40b32bdc581a3eaeaf74662549 | Floreit/PRG105 | /KyleLud4.1.py | 994 | 4.15625 | 4 | #Declare variables to be used in the while loop
stop = 0
calories = 4.2
minutes = 0
time = 0
#while loop with if statements to count the intervals, increments by 1 minute every iteration, when it hits an interval it will display the calories burned
while stop != 1:
minutes = minutes + 1
if minutes == 10:
print ("The calories burned in " , minutes, "minutes are: ", round(calories,2) * minutes)
if minutes == 15:
print ("The calories burned in ", minutes, "minutes are: ", round(calories,2) * minutes)
if minutes == 20:
print ("The calories burned in ", minutes, "minutes are: ", round(calories,2) * minutes)
if minutes == 25:
print ("The calories burned in ", minutes, "minutes are: ", round(calories,2) * minutes)
if minutes == 30:
print ("The calories burned in ", minutes, "minutes are: ", round(calories,2) * minutes)
stop = 1 # stopping the program at 30 so it doesnt run infinitely
| true |
1885b7c5930b016b448bff1741f70d7b2ab74941 | Hank310/RockPaperScissors | /RPS1.py | 2,028 | 4.1875 | 4 | #Hank Warner, P1
#Rock, Paper Scissors game
# break int0 pieces
# Welcome screenm with name enterable thing
# Score Screen, computer wins, player wins, and ties
# gives options for r p s & q
# Game will loop until q is pressed
# Eack loop a random choice will be generated
# a choice from thge player, compare, and update score
# When game iis over, final score display
# WELCOME PAGE
# Name prompt
# Welcome msg
# Imports
import random
# Variables
playerSC = 0
computerSC = 0
ties = 0
# make a list
cChoice =["r", "p", "s"]
print("Welcome to Rock Paper Scissors")
name = input("Enter your name: ")
# main loop
while True:
print(" Score: ")
print("Computer: " + str(computerSC))
print(name + ": " + str(playerSC))
print("Ties:" + str(ties))
choice = input("Enter 'r' for Rock, 'p' for Paper, 's' for Scissors, or 'q' to Quit")
compChoice = random.choice(cChoice)
print( "Computer picked: " + compChoice)
if choice == "q":
break
if choice == "r":
print( name +" Picked Rock")
if compChoice == "r":
print("Computer picked Rock, it is a tie")
ties = ties + 1
elif compChoice == "p":
print("Computer picked Paper, Computer wins")
computerSC = computerSC + 1
else:
print("Computer picked Scissors, " + name + " wins")
playerSC = playerSC + 1
elif choice == "p":
if compChoice == "p":
print("Computer picked Paper, it is a tie")
ties = ties + 1
elif compChoice == "s":
print("Computer picked Scissors, Computer wins")
computerSC = computerSC + 1
else:
print("Computer picked Rock, " + name + " wins")
playerSC = playerSC + 1
elif choice == "s":
if compChoice == "s":
print("Computer picked Scissors, it is a tie")
ties = ties + 1
elif compChoice == "r":
print("Computer picked Rock, Computer wins")
computerSC = computerSC + 1
else:
print("Computer picked Paper, " + name + " wins")
playerSC = playerSC + 1
else:
print("That is not an option")
| true |
8098951d28b3ca5f954b63e74ab6d887b0664e9f | lyndsiWilliams/cs-module-project-iterative-sorting | /src/searching/searching.py | 1,337 | 4.25 | 4 | def linear_search(arr, target):
# Your code here
# Loop through the length of the array
for i in range(len(arr)):
# If this iteration matches the target value
if arr[i] == target:
# Return the value
return i
return -1 # not found
# Write an iterative implementation of Binary Search
def binary_search(arr, target):
# Your code here
# Set the lowest value to 0
low = 0
# Set the highest value (boundary) to the length of the array - 1
# -1 because when only 1 item is left, it doesn't need to be sorted
high = len(arr) - 1
# While the low value is <= the high value (boundary)
while low <= high:
# Find the midpoint
mid = (high + low) // 2
# Begin comparing the target to the midpoint
if target == arr[mid]:
return mid
# If the target is < the midpoint
if target < arr[mid]:
# Cut out the right half of the array (greater than) and
# Reassign the high value to the midpoint - 1
high = mid - 1
# If the target is > the midpoint
if target > arr[mid]:
# Cut out the left half of the array (less than) and
# Reassign the low value to the midpoint + 1
low = mid + 1
return -1 # not found
| true |
f04167639ad0509853dc1c01fa872b250fc95863 | mraguilar-mahs/AP_CSP_Into_to_Python | /10_23_Lesson.py | 429 | 4.1875 | 4 |
#Lesson 1.3 Python - Class 10/23
#Obj:
#Standard:
#Modulus - Reminder in a division:
# Ex 1: 9/2 = 4 r 1
# Ex 2: 4/10 = 0 r 4
# modulus: % --> 9 mod 2
print(9%2)
print(234%1000)
print(10%2)
print(9%2) # <- with mod 2, check for even/odd
# Mod can check for divisibility, if equal to 0
#User Input:
user_name = str(input("Please enter your name:"))
print(user_name) # Name is storing the value inputed by the user from above
| true |
a1f4cc9a7b531b3bcbd01ac5eb1285ee44d1e51f | abhishekk26/NashVentures | /Random number Generation.py | 2,066 | 4.1875 | 4 |
import math, time
class MyRNG:
# MyRNG class. This is the class declaration for the random number
# generator. The constructor initializes data members "m_min" and
# "m_max" which stores the minimum and maximum range of values in which
# the random numbers will generate. There is another variable named "m_seed"
# which is initialized using the method Seed(), and stores the value of the
# current seed within the class. Using the obtained values from above, the
# "Next()" method returns a random number to the caller using an algorithm
# based on the Park & Miller paper.
def __init__(self, low = 0, high = 0):
# The constructor initializes data members "m_min" and "m_max"
if(low < 2):
low = 2
if(high < 2):
high = 9223372036854775807
self.m_min = low
self.m_max = high
self.m_seed = time.time()
def Seed(self, seed):
# Seed the generator with 'seed'
self.m_seed = seed
def Next(self):
# Return the next random number using an algorithm based on the
# Park & Miller paper.
a = self.m_min
m = self.m_max
q = math.trunc(m / a)
r = m % a
hi = self.m_seed / q
lo = self.m_seed % q
x = (a * lo) - (r * hi)
if(x < a):
x += a
self.m_seed = x
self.m_seed %= m
# ensure that the random number is not less
# than the minimum number within the user specified range
if(self.m_seed < a):
self.m_seed += a
return int(self.m_seed)
def test():
# Simple test function to see if the functionality of my class
# is there and works
random = MyRNG(6, 10)
random.Seed(806189064)
per = (73*100)/100
for x in range(per):
print("%d, " %(random.Next()))
random = MyRNG(1, 5)
for x in range(per,100):
print("%d, " %(random.Next()))
if __name__ == '__main__':
test() | true |
c95c502184424b7d7f56da51ec7df1bd24c11499 | rosexw/LearningPython | /Exercise Files/Ch2/loops_start.py | 843 | 4.25 | 4 | #
# Example file for working with loops
#
def main():
x = 0
# define a while loop
# while (x < 5):
# print(x)
# x = x+1
# define a for loop
# for x in range(5,10):
# print (x)
# use a for loop over a collection
# days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]
# for d in days:
# print (d)
# use the break and continue statements
# for x in range(5,10):
# if (x == 7): break
# BREAK if condition is met, the for loop will terminate and fall to next block of code (end of function, prints 5 and 6)
# if (x % 2 == 0): continue
# CONTINUE skips for that iteration
# skips 6, 8
# print (x)
#using the enumerate() function to get index
days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]
for i, d in enumerate(days):
print (i, d)
if __name__ == "__main__":
main()
| true |
914544f42b91b5d6b7c17378a310add1ea9a67a6 | Adarsh2412/python- | /python11.py | 663 | 4.21875 | 4 | def calculator(number_1, number_2, operation):
if(operation=='addition'):
result=number_1+number_2
return result
elif(operation=='subtract'):
result=number_1-number_2
return result
elif(operation=='multiply'):
result=number_1*number_2
return result
elif(operation=='divide'):
result=number_1/number_2
return result
else:
print('wrong input')
number_1=int(input('Enter the first number'))
number_2=int(input('Enter the second number'))
operation=str(input('Enter the operation'))
a=calculator(number_1, number_2, operation)
print(a)
s | true |
dbe00f7712f950e33b36e69e05d56d7465609c04 | StevenM42/Sandbox | /password_check.py | 389 | 4.3125 | 4 | """Password check program that returns asterisks of password length"""
Minimum_character_limit = 6
password = input("Please enter password at least {} characters long: ".format(Minimum_character_limit))
while len(password) < Minimum_character_limit:
password = input("Please enter password at least {} characters long: ".format(Minimum_character_limit))
print('*' * len(password))
| true |
ffac4f7a078c8221458dbba66af1ee4f95ad374c | shreesha-bhat/Python | /reverseofanumber.py | 309 | 4.28125 | 4 | #program to accept a number from the user and find the reverse of the entered number
number = int(input("Enter any number : "))
rev = 0
while (number > 0):
remainder = number % 10
rev = (rev * 10) + remainder
number //= 10
print("Reverse of the entered number is ",rev) | true |
45d3281927b36d539619554889b92fac37af3460 | shreesha-bhat/Python | /Series1.py | 339 | 4.15625 | 4 | #Program to accept a number “n” from the user; then display the sum of the series 1+1/2+1/3+……….+1/n
num = int(input("Enter the value of N : "))
for i in range(1,num+1):
if i == 1:
print(i,end='+')
if i != 1 and i != num:
print(f"1/{i}",end='+')
if i == num:
print(f"1/{i}",end='') | true |
3c23bc4b31be19db9439b1b1e8e96b5069c3bd35 | shreesha-bhat/Python | /Swapnumbers.py | 376 | 4.1875 | 4 | #Program to swap numbers
Number1 = int(input("Enter the First number : "))
Number2 = int(input("Enter the Second number : "))
print(f"Before swap, the values of num1 = {Number1} and num2 = {Number2}")
Number1 = Number1 + Number2
Number2 = Number1 - Number2
Number1 = Number1 - Number2
print(f"After swap, the values of num1 = {Number1} and num2 = {Number2}") | true |
92a5b52e620fabf557ff30f4d1e471d783db4f2c | shreesha-bhat/Python | /series3.py | 417 | 4.125 | 4 | #Program to accept a number “n” from the user; find the sum of the series 1/23+1/33+1/43……..+1/n3
num = int(input("Enter the value of N : "))
sum = 0
for i in range(1,num+1):
if i == 1:
print(i,end='+')
if i != 1 and i != num:
print(f"1/{i}^3",end='+')
if i == num:
print(f"1/{i}^3")
sum += 1/(i * i * i)
print("Sum of the series is : ",round(sum,2))
| true |
a452c61845d7ec8f285b3aec32bbb707b8ac38e8 | rcmhunt71/hackerrank | /DLLs/insert_into_dllist.py | 2,038 | 4.15625 | 4 | #!/bin/python3
class DoublyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_node(self, node_data):
node = DoublyLinkedListNode(node_data)
if not self.head:
self.head = node
else:
self.tail.next = node
node.prev = self.tail
self.tail = node
def print_doubly_linked_list(node, sep):
while node:
print(str(node.data), end='')
node = node.next
if node:
print(sep, end='')
print()
#
# For your reference:
#
# DoublyLinkedListNode:
# int data
# DoublyLinkedListNode next
# DoublyLinkedListNode prev
#
#
def sorted_insert(head, data):
node = head
insert_node = DoublyLinkedListNode(data)
while node is not None:
if node.next is None or data < node.data or node.data <= data <= node.next.data:
break
node = node.next
if node is None:
return insert_node
if node.next is None:
node.next = insert_node
insert_node.prev = node
elif data < node.data:
insert_node.next = node
node.prev = insert_node
head = insert_node
else:
next_node = node.next
node.next = insert_node
insert_node.prev = node
insert_node.next = next_node
next_node.prev = insert_node
return head
if __name__ == '__main__':
test_data = [
([1, 3, 4, 10], 5),
([1, 3, 4, 10], 0),
([1, 3, 4, 10], 20),
([1, 3, 4, 10], 3),
([], 3),
([3, 3, 3], 3),
([1, 3, 3, 4, 10], 3),
]
for test_case in test_data:
llist = DoublyLinkedList()
for llist_item in test_case[0]:
llist.insert_node(llist_item)
llist1_head = sorted_insert(llist.head, test_case[1])
print_doubly_linked_list(llist1_head, ' ')
| true |
d9b437283616b1d92f2881a77c4505c421a7f10b | mariasilviamorlino/python-programming-morlino | /PB_implementations/backward_hmm.py | 2,510 | 4.21875 | 4 | """
Backward algorithm implementation for hmms
###########
INPUT:
model parameters
sequence to evaluate
OUTPUT:
probability of sequence given model
###########
Setup
Read list of states
Read transition probabilities
Read emission probabilities
Read sequence
rows = n. of states
cols = length of sequence
Create a rows x cols matrix
Initialization
Start from last column of matrix
Store in each cell of the column the corresponding transition from that state to the end state
Iteration
For each column (proceeding backwards):
For each cell in column:
sum over the probabilities of the following column, times the transition probabilities to that column,
times the emission probabilities of the "following" symbol
Termination
Compute total score by summing over the probabilities in the first column, times the transition
probabilities to the first column, times the emission probabilities of the 1st symbol in each state
Generate output: print probability
"""
def prettymatrix(listoflists):
"""Human-readable display of lists of lists"""
for lyst in listoflists:
print(lyst)
# set of states
state = ["B", "Y", "N", "E"]
# transition probabilities -> dictionary of dictionaries
t = {"B": {"B": 0, "Y": 0.2, "N": 0.8, "E": 0},
"Y": {"B": 0, "Y": 0.7, "N": 0.2, "E": 0.1},
"N": {"B": 0, "N": 0.8, "Y": 0.1, "E": 0.1},
"E": {"B": 0, "N": 0, "Y": 0, "E": 0}}
# transitions are used as follows: first key is starting state, second key is ending state
# starting and ending probabilities
begin = {"Y": 0.2, "N": 0.8}
end = {"Y": 0.1, "N": 0.1} # usage ex.: end["Y"] is the trans probability from Yes to End
# emission probabilities -> dictionary of dictionaries
e = {"Y": {"A": 0.1, "C": 0.4, "G": 0.4, "T": 0.1},
"N": {"A": 0.25, "C": 0.25, "G": 0.25, "T": 0.25}}
# input sequence
sequence = "ATGCG"
# matrix setup
rows = len(state)
cols = len(sequence)
backward = [[0 for col in range(cols)] for row in range(rows)]
# initialization
for i in range(1, rows-1):
backward[i][cols-1] = end[state[i]]
# iteration
for j in range(cols-2, -1, -1):
for i in range(1, rows-1):
for h in range(1, rows-1):
increment = backward[h][j+1] * t[state[i]][state[h]] * e[state[h]][sequence[j+1]]
backward[i][j] += increment
# termination
score = 0
for h in range(1, rows-1):
increment = backward[h][0] * begin[state[h]]
score += increment
prettymatrix(backward)
print(score)
# output: 0.00035011440000000003
| true |
7dab3037afa1f2cf84dd957060a094840efe7308 | gibbs-shih/stanCode_Projects | /stanCode_Projects/Weather Master/quadratic_solver.py | 1,207 | 4.5 | 4 | """
File: quadratic_solver.py
-----------------------
This program should implement a console program
that asks 3 inputs (a, b, and c)
from users to compute the roots of equation
ax^2 + bx + c = 0
Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
import math
def main():
"""
This function will compute the roots of equation: ax^2+bx+c=0.
"""
print('stanCode Quadratic Solver!')
compute_the_roots_of_equation()
def compute_the_roots_of_equation():
"""
Use the three given numbers(a,b,and c), and discriminant(b^2-4ac) to get the roots of equation.
discriminant>0, two roots.
discriminant=0, one root.
discriminant<0, no real roots.
"""
a = int(input('Enter a : '))
if a != 0:
b = int(input('Enter b : '))
c = int(input('Enter c : '))
discriminant = b**2-4*a*c
if discriminant > 0:
y = math.sqrt(discriminant)
x1 = (-b+y)/(2*a)
x2 = (-b-y)/(2*a)
print('Two roots: ' + str(x1) + ' , ' + str(x2))
elif discriminant == 0:
x = -b/(2*a)
print('One root: ' + str(x))
else:
print('No real roots.')
else:
print("'a' can not be zero!")
###### DO NOT EDIT CODE BELOW THIS LINE ######
if __name__ == "__main__":
main()
| true |
9139e03d276b2d33323343e59a2bf01ad9600911 | gibbs-shih/stanCode_Projects | /stanCode_Projects/Hangman Game/similarity.py | 1,801 | 4.34375 | 4 | """
Name: Gibbs
File: similarity.py
----------------------------
This program compares short dna sequence, s2,
with sub sequences of a long dna sequence, s1
The way of approaching this task is the same as
what people are doing in the bio industry.
"""
def main():
"""
This function is used to find the most similar part between s1(long DNA sequence) and s2(short DNA sequence).
"""
long = give_long()
short = give_short()
similarity1 = find_similarity(long, short)
print('The best match is '+similarity1+'.')
def give_long():
"""
Users give a long DNA sequence to search.
:return: long DNA sequence
"""
long = input('Please give me a DNA sequence to search: ')
long = long.upper()
return long
def give_short():
"""
Users give a short DNA sequence to match.
:return: short DNA sequence
"""
short = input('What DNA sequence would you like to match? ')
short = short.upper()
return short
def find_similarity(long, short):
"""
This function will find out the most similar part in long DNA sequence when compared to short DNA sequence.
:param long: long DNA sequence
:param short: short DNA sequence
:return: the most similar part between long and short DNA sequence
"""
similarity1 = 0
similarity2 = 0
for i in range(len(long)-len(short)+1):
a = 0
part = long[i:i+len(short)]
for j in range(len(part)):
if part[j] == short[j]:
a += 1
if a == len(short):
similarity1 = part
return similarity1
elif a > similarity2:
similarity2 = a
similarity1 = part
return similarity1
###### DO NOT EDIT CODE BELOW THIS LINE ######
if __name__ == '__main__':
main()
| true |
0619ec96483920be456730016ece7f7ef5b3ed57 | takisforgit/Projects-2017-2018 | /hash-example1.py | 2,939 | 4.1875 | 4 | import hashlib
print(hashlib.algorithms_available)
print(hashlib.algorithms_guaranteed)
## MD5 example ##
'''
It is important to note the "b" preceding the string literal,
this converts the string to bytes, because the hashing function only takes
a sequence of bytes as a parameter
'''
hash_object = hashlib.md5(b"Hello World")
print("MD5 :",hash_object.hexdigest())
'''
So, if you need to take some input from the console, and hash this input,
do not forget to encode the string in a sequence of bytes
'''
##mystring = input('Enter String to hash: ')
### Assumes the default UTF-8
##hash_object = hashlib.md5(mystring.encode())
##print(hash_object.hexdigest())
## SHA1 example ##
hash_object = hashlib.sha1(b'Hello World')
hex_dig = hash_object.hexdigest()
print("SHA1 :",hex_dig)
## SHA224 example ##
hash_object = hashlib.sha224(b'Hello World')
hex_dig = hash_object.hexdigest()
print("SHA224:",hex_dig)
## SHA256 example ##
hash_object = hashlib.sha256(b'Hello World')
hex_dig = hash_object.hexdigest()
print("SHA256:",hex_dig)
## SHA384 example ##
hash_object = hashlib.sha384(b'Hello World')
hex_dig = hash_object.hexdigest()
print("SHA384:",hex_dig)
## SHA512 example ##
hash_object = hashlib.sha512(b'Hello World')
hex_dig = hash_object.hexdigest()
print("SHA512:",hex_dig)
## DSA example ##
hash_object = hashlib.new('DSA')
hash_object.update(b'Hello World')
print("DSA :",hash_object.hexdigest())
###################################################
''' In the following example we are hashing a password in order to store it in a database.
In this example we are using a salt. A salt is a random sequence added to the password string
before using the hash function. The salt is used in order to prevent dictionary attacks
and rainbow tables attacks. However, if you are making real world applications and working
with users' passwords, make sure to be updated about the latest vulnerabilities in this field.
If you want to find out more about secure passwords please refer to this article
https://crackstation.net/hashing-security.htm
'''
import uuid
import hashlib
def hash_password(password):
# uuid is used to generate a random number
salt = uuid.uuid4().hex
return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt
def check_password(hashed_password, user_password):
password, salt = hashed_password.split(':')
return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()
new_pass = input('Please enter a password: ')
hashed_password = hash_password(new_pass)
print('The string to store in the db is: ' + hashed_password)
old_pass = input('Now please enter the password again to check: ')
if check_password(hashed_password, old_pass):
print('You entered the right password')
else:
print('ATTENTION ! The password does not match')
| true |
d64e446e9730ed833bb0dfd669d3c6aba98e6653 | Deepti3006/InterviewPractise | /Amazon Interview/OccuranceOfElementInArray.py | 370 | 4.15625 | 4 | def numberOfOccurancesOfNumberinArray():
n = int(input("Enter number of Elements"))
arr =[]
for i in range(n):
elem = input("enter the array number")
arr.append(elem)
print(arr)
find_element = input("Enter the element to be found")
Occurances = arr.count(find_element)
print(Occurances)
numberOfOccurancesOfNumberinArray()
| true |
2eb7016701c2f1b1d6368a1ba08994e89930be57 | Jenell-M-Hogg/Codility-Lesson-Solutions | /Lesson1-FrogJmp.py | 1,296 | 4.125 | 4 | '''A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.
Count the minimal number of jumps that the small frog must perform to reach its target.
Write a function:
def solution(X, Y, D)
that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
For example, given:
X = 10
Y = 85
D = 30
the function should return 3, because the frog will be positioned as follows:
after the first jump, at position 10 + 30 = 40
after the second jump, at position 10 + 30 + 30 = 70
after the third jump, at position 10 + 30 + 30 + 30 = 100
Assume that:
X, Y and D are integers within the range [1..1,000,000,000];
X ≤ Y.
Complexity:
expected worst-case time complexity is O(1);
expected worst-case space complexity is O(1).'''
#100% solution
import math
def solution(X, Y, D):
#The distance the frog has to go
distance=Y-X
#Convert to float to avoid integer division
df=float(distance)
jumps=df/D
#Round up the number of jumps
jumps=math.ceil(jumps)
#must return an integer
toInt=int(jumps)
return toInt
pass
| true |
74b87ea175e4c7ef7ac9802e865783101a87097d | JennSosa-lpsr/class-samples | /4-2WritingFiles/writeList.py | 405 | 4.125 | 4 | # open a file for writing
# r is for reading
# r + is for reading and writing(existing file)
# w is writing (be careful! starts writing from the beginning.)
# a is append - is for writing *from the end*
myFile = open("numlist.txt", "w")
# creat a list to write to my file
nums = range(1, 501)
# write each item to the file
for n in nums:
myFile.write(str(n) + '\n' )
# close the file
myFile.close()
| true |
715cfb565d350b68bf0d20367cedcde62562e66c | JennSosa-lpsr/class-samples | /remotecontrol.py | 1,080 | 4.40625 | 4 | import turtle
from Tkinter import *
# create the root Tkinter window and a Frame to go in it
root = Tk()
frame = Frame(root)
# create our turtle
shawn = turtle.Turtle()
myTurtle = turtle.Turtle()
def triangle(myTurtle):
sidecount = 0
while sidecount < 3:
myTurtle.forward(100)
myTurtle.right(120)
sidecount = sidecount + 1
# make some simple buttons
fwd = Button(frame, text='fwd', command=lambda: shawn.forward(50))
left = Button(frame, text='left', command=lambda: shawn.left(90))
right = Button(frame, text='right', command=lambda: shawn.right(90))
penup = Button(frame, text='penup', command=lambda:shawn.penup())
pendown = Button(frame, text='pendown', command=lambda:shawn.pendown())
backward = Button(frame, text='backward', command=lambda:shawn.backward(50))
shape = Button(frame, text='shape', command=lambda:triangle.(shawn)
# put it all together
fwd.pack(side=LEFT)
left.pack(side=LEFT)
right.pack(side=LEFT)
penup.pack(side=LEFT)
pendown.pack(side=LEFT)
backward.pack(side=LEFT)
shape.pack(side=LEFT)
frame.pack()
turtle.exitonclick()
| true |
f623fbc9ad297294904cf231202e7e2ae1282524 | AJoh96/BasicTrack_Alida_WS2021 | /Week38/2.14_5.py | 476 | 4.25 | 4 | #solution from Lecture
principal_amount = float(input("What is the principal amount?"))
frequency = int(input("How many times per year is the interest compounded?"))
interest_rate = float(input("What is the interest rate per year, as decimal?"))
duration = int(input("For what number of years would like to calculate the compound interest?"))
final_amount= principal_amount * (1 + (interest_rate/frequency))** (frequency*duration)
print("The final amount is:", final_amount) | true |
92077bb80eda2fe5208c7b2eeeac3d53c4251ebc | PriyankaBangale/30Day-s_Code | /day_8_DictionaryMapping.py | 1,381 | 4.34375 | 4 | """Objective
Today, we're learning about Key-Value pair mappings using a Map or Dictionary data structure. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for is not found, print Not found instead.
Note: Your phone book should be a Dictionary/Map/HashMap data structure."""
N = int(input())
d = dict{}
for i in range(0, N):
name, number = input().split()
d[name] = number
for i in range(0, N):
name = input()
if name in d:
print("{}={}".format(name, d[name]))
else:
print("Not found")
n=int(input().strip())
phone_book={}
for i in range(n):
x= input().strip()
listx = list(x.split(' '))
phone_book[listx[0]] = listx[1]
name=[]
try:
while True:
inp = input().strip()
if inp != "":
name.append(inp)
else:
break
except EOFError:
pass
for i in name:
c=0
if i in phone_book:
print(i+'='+phone_book[i])
else:
print('Not found') | true |
015cac95f4680a6fa0f62999caff7e8d500634b9 | assuom7827/Hacktoberfest_DSA_2021 | /Code/game_projects/word guessing game/word_guessing_game.py | 1,088 | 4.28125 | 4 | from random import choice
# list of words(fruits and vegetables)
words=["apple","banana","orange","kiwi","pine","melon","potato","carrot","tomato","chilly","pumpkin","brinjol","cucumber","olive","pea","corn","beet","cabbage","spinach"]
c_word = choice(words)
lives=3
unknown = ["_"]*len(c_word)
while lives>0:
guess=input("Please guess a letter or word: ")
if guess == c_word:
print('You won! The secret word was ' + c_word)
break
elif guess in c_word:
unknown[c_word.index(guess)]=guess
if "_" in unknown:
print(unknown)
print("Hurray!,you succeded in guessing a letter correct.go ahead!")
print(f"chances left are {lives}")
else:
print(unknown)
print("Congrats!\nyou won!")
else:
if lives==1:
print(unknown)
print("you are run out of lifes.\nBetter luck next time!")
elif lives>0:
print(unknown)
print("you lost a life.try again!")
print(f"chances left are {lives}")
lives=lives-1
| true |
fb278d9975471e74e188f621cc722444410ada76 | Sarthak1503/Python-Assignments | /Assignment4.py | 1,100 | 4.28125 | 4 | #1.Find the length of tuple
t=(2,4,6,9,1)
print(len(t))
#2.Find the largest and smallest element of a tuple.
t=(2,4,6,8,1)
print(max(t))
print(min(t))
#3.Write a program to find the product os all elements of a tuple.
def pro(t):
r=1
for i in t:
r=r*i
return r
t=(1,2,3,4)
p=pro(t)
print(p)
#4.Calculate difference between two sets.
s1=set([1,2,4,6,9])
s2=set([2,3,4,5,7])
print(s1-s2)
#5.Print the result of intersection of two sets.
s1=set([1,2,5])
s2=set([2,3,4])
print(s1 & s2)
#6.Create a Dictionary to store names and marks of 10 students by user input.
d={}
for i in range(10):
name=input('enter your name')
marks=int(input('enter marks'))
d[name]=marks
print(d)
#7.Sorting of Dictionary
d={'a':60,'b':100,'c':80}
print(d)
value_list=list(d.values())
print(value_list)
value_list.sort()
print(value_list)
#8.Count the number of occurence of each letter in word "MISSISSIPPI". Store count of every letter with the letter in a dictionary.
l=list("MISSISSIPPI")
d={}
d['M']=l.count('M')
d['I']=l.count('I')
d['S']=l.count('S')
d['P']=l.count('P')
print(d)
| true |
9b7380e82a01b8a68bec953a32119f10b2f34ad1 | Sarthak1503/Python-Assignments | /Assignment11.py | 1,317 | 4.34375 | 4 | import threading
from threading import Thread
import time
#1. Create a threading process such that it sleeps for 5 seconds and
# then prints out a message.
def show():
time.sleep(5)
print(threading.current_thread().getName(),"Electronics & Communication Engineering")
t= Thread(target=show)
t.setName("B.tech in:")
t.start()
print(threading.current_thread().getName())
#2. Make a thread that prints numbers from 1-10, waits for 1 sec between
def number():
for x in range (1,11):
print(threading.current_thread().getName(),":",x)
time.sleep(1)
t = Thread(target=number)
t.setName("Number")
t.start()
# 3. Make a list that has 5 elements.Create a threading process that prints the 5
# elements of the list with a delay of multiple of 2 sec between each display.
# Delay goes like 2sec-4sec-6sec-8sec-10sec
l=[1,2,3,4,5]
def delay():
n = 2
for x in l:
if n%2==0:
time.sleep(n)
print(threading.current_thread().getName(), ":", x)
n=n+2
t = Thread(target=delay)
t.setName("Number")
t.start()
#4. Call factorial function using thread.
def fact():
n=int(input("Enter the no"))
f=1
while n>=1:
f=f*n
n=n-1
print(threading.current_thread().getName(),":",f)
t= Thread(target=fact)
t.setName("Factorial")
t.start() | true |
a1e326537c4cadefbae38f73356c33a3cb920f1c | ArnabC27/Hactoberfest2021 | /rock-paper-scissor.py | 1,678 | 4.125 | 4 | '''
Rock Paper Scissor Game in Python using Tkinter
Code By : Arnab Chakraborty
Github : https://github.com/ArnabC27
'''
import random
import tkinter as tk
stats = []
def getWinner(call):
if random.random() <= (1/3):
throw = 'Rock'
elif (1/3) < random.random() <= (2/3):
throw = 'Scissors'
else:
throw = 'Paper'
if (throw == 'Rock' and call == 'Paper') or (throw == 'Paper' and call == 'Scissors') or (throw == 'Scissors' and call == 'Rock'):
stats.append('W')
result = "You Won!!!"
elif throw == call:
stats.append('D')
result = "It Is A Draw!!!"
else:
stats.append('L')
result = 'You Lost!!!'
global output
output.config(text = 'Computer Threw : ' + throw + '\n' + result)
def sPass():
getWinner('Scissors')
def rPass():
getWinner('Rock')
def pPass():
getWinner('Paper')
window = tk.Tk()
scissors = tk.Button(window, text='Scissors', bg='#ff9999', padx=10, pady=5, command=sPass, width=20)
rock = tk.Button(window, text='Rock', bg='#80ff80', padx=10, pady=5, command=rPass, width=20)
paper = tk.Button(window, text='Paper', bg='#3399ff', padx=10, pady=5, command=rPass, width=20)
output = tk.Label(window, width=20, fg='red', text="What's Your Call?")
scissors.pack(side='left')
rock.pack(side='left')
paper.pack(side='left')
output.pack(side='right')
window.mainloop()
for i in stats:
print(i, end=' ')
if stats.count('L') > stats.count('W'):
result = 'You have Lost the series.'
elif stats.count('L') == stats.count('W'):
result = 'Series has ended in a Draw.'
else:
result = 'You have Won the series.'
print('\n',result,'\n', end='')
| true |
c66911b7118dfe6ca6dde2d28c00b8eeaf0ace72 | MacHu-GWU/pyclopedia-project | /pyclopedia/p01_beginner/p03_data_structure/p03_set/p01_constructor.py | 1,219 | 4.28125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Set Constructor
==============================================================================
"""
import random
import string
def construct_a_set():
"""Syntax: ``set(iterable)``
"""
assert set([1, 2, 3]) == {1, 2, 3}
assert set(range(3)) == {0, 1, 2}
construct_a_set()
def using_mutable_object_as_item_of_set():
"""By default, only integer, string and other hashable immutable built-in
object can be item of a set. Any user defined object are not behave correctly.
You could define ``__hash__`` method to make sure your object is hashable.
Usually returns a integer or a string.
"""
def random_text():
return "".join([random.choice(string.ascii_letters) for i in range(32)])
class Comment(object):
def __init__(self, id, text):
self.id = id
self.text = text
def __repr__(self):
return "Comment(id=%r, text=%r)" % (self.id, self.text)
def __hash__(self):
return hash(self.id)
l = [Comment(id=i, text=random_text()) for i in range(5)]
s = set(l)
for c in l:
assert c in s
using_mutable_object_as_item_of_set()
| true |
96290a7e696a0c6c70bcf234648877536d5c53e2 | DiQuUCLA/python_59_skill | /3_python_bytes_str_unicode.py | 1,180 | 4.1875 | 4 | """
Two types that represent sequence of char: str and bytes(Python3), unicode and str(Python2)
Python3:
str: Unicode character
bytes: 8 bits raw data
Python2:
unicode: Unicode character
str: 8 bits raw data
"""
import sys
version = sys.version_info[0]
if version is 3:
#encoding will take unicode str to bytes
#where decoding will take bytes to unicode str
def to_str(bytes_or_str):
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode('utf-8')
else:
value = bytes_or_str
return value
def to_bytes(bytes_or_str):
if isinstance(bytes_or_str, str):
value = bytes_or_str.encode('utf-8')
else:
value = bytes_or_str
return value
if version is 2:
def to_str(str_or_unicode):
if isinstance(bytes_or_str, unicode):
value = bytes_or_str.encode('utf-8')
else:
value = bytes_or_str
return value
def to_unicode(bytes_or_str):
if isinstance(bytes_or_str, str):
value = bytes_or_str.decode('utf-8')
else:
value = bytes_or_str
return value
| true |
e5d3d5fcc86b340efb23b0cf99b4652daa6e3e4d | juanjosua/codewars | /find_the_odd_int.py | 599 | 4.1875 | 4 | """
Find the Odd Int
LINK: https://www.codewars.com/kata/54da5a58ea159efa38000836/train/python
Given an array of integers, find the one that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
"""
def find_it(seq):
numbers = set(seq)
return[n for n in numbers if seq.count(n) % 2 ==1][0]
# voted best practice 1
def find_it(seq):
return [x for x in seq if seq.count(x) % 2][0]
# voted best practice 2
def find_it(seq):
for i in seq:
if seq.count(i)%2!=0:
return i
# test code
find_it([10]) #10
find_it([1,1,1,2,2]) #1 | true |
6115fe58abcf4cedf25d90d87613590919ec494a | lisamryl/oo-melons | /melons.py | 2,057 | 4.15625 | 4 | """Classes for melon orders."""
import random
import datetime
class AbstractMelonOrder(object):
"""Abstract for both domestic and international melon orders."""
def __init__(self, species, qty):
"""Initialize melon order attributes."""
self.species = species
self.qty = qty
self.shipped = False
def get_base_price(self):
"""randomly get a base price between 5 and 9 and return it."""
# in progress
# day = datetime.date.weekday()
# print day
# time = datetime.time()
# print time
base_price = random.randint(5, 9)
return base_price
def get_total(self):
"""Calculate price, including tax."""
base_price = self.get_base_price()
if self.species == "Christmas":
base_price *= 1.5
total = (1 + self.tax) * self.qty * base_price
return total
def mark_shipped(self):
"""Record the fact than an order has been shipped."""
self.shipped = True
class DomesticMelonOrder(AbstractMelonOrder):
"""A melon order within the USA."""
tax = 0.08
order_type = "domestic"
class InternationalMelonOrder(AbstractMelonOrder):
"""An international (non-US) melon order."""
tax = 0.17
order_type = "international"
def __init__(self, species, qty, country_code):
"""Initialize melon order attributes."""
self.country_code = country_code
return super(InternationalMelonOrder, self).__init__(species, qty)
def get_country_code(self):
"""Return the country code."""
return self.country_code
def get_total(self):
total = super(InternationalMelonOrder, self).get_total()
if self.qty < 10:
total += 3
return total
class GovernmentMelonOrder(AbstractMelonOrder):
"""Special orders from the Government."""
tax = 0
passed_inspection = False
def mark_inspection(self, passed):
"""Updates inspection status."""
self.passed_inspection = passed
| true |
96a58d71f67b01d07897d83fca08c3beb5c718cd | loudsoda/CalebDemos | /Multiples_3_5/Multiples_3_5.py | 1,228 | 4.125 | 4 | '''
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.
Note: If the number is a multiple of both 3 and 5, only count it once.
Courtesy of ProjectEuler.net
https://www.codewars.com/kata/514b92a657cdc65150000006/train/python
Solution by Caleb Ellis
Date: 5/27/2020
'''
def solution(number):
# Create range for loop, mak it so the loop does not exceed x
# number is simplified to x for the sake of irs
x = number
y = range(1, int(x))
# Create list to find sum
number_list = []
# Loop though all iterations of the input number
for i in y:
multi_5 = i * 5
multi_3 = i * 3
# Check if digits exist in list or if digit is greater than x
if multi_3 >= x or multi_3 in number_list:
pass
else:
number_list.append(multi_3)
if multi_5 >= x or multi_5 in number_list:
pass
else:
number_list.append(multi_5)
# Add contents of list together
Sum = sum(number_list)
return (Sum)
print(solution(200))
| true |
ee7195c77b6de0b24df33b938058b4a2f45ec48e | sunnysunita/BinaryTree | /take_levelwise_input.py | 1,353 | 4.25 | 4 | from queue import Queue
class BinaryTree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def print_binary_tree(root):
if root is None:
return
else:
print(root.data, end=":")
if root.left != None:
print("L", root.left.data, end=", ")
if root.right != None:
print("R", root.right.data, end="")
print()
print_binary_tree(root.left)
print_binary_tree(root.right)
def take_level_input():
root_data = int(input("enter the root value: "))
if root_data is -1:
return None
root = BinaryTree(root_data)
q = Queue()
q.put(root)
while q.empty() is False:
curr = q.get()
left_data = int(input("enter the left child of "+str(curr.data)+":"))
if left_data is not -1:
left_child = BinaryTree(left_data)
curr.left = left_child
q.put(left_child)
right_data = int(input("enter the right child of "+str(curr.data)+":"))
if right_data is not -1:
right_child = BinaryTree(right_data)
curr.right = right_child
q.put(right_child)
return root
root = take_level_input()
print_binary_tree(root)
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 | true |
c368badfeda0bd1f7079c807eb072dbbb6938641 | weinbrek8115/CTI110 | /P4HW2_RunningTotal_WeinbrennerKarla.py | 628 | 4.15625 | 4 | #CTI-110
#P4HW2
#Karla Weinbrenner
#22 March 2018
#Write a program that asks the user to enter a series of numbers
#It should loop, adding these numbers to a running total
#Until a negative number is entered, the program should exit the loop
#Print the total before exiting
#accumulator variable
runningTotal=0
count=0
userInput=int(input("Enter a number or negative number to exit: "))
print ()
while userInput >=0:
runningTotal=runningTotal+userInput
count=count+1
userInput=int(input("Enter a number or a negative number to exit: "))
print()
print ("The running total is: ", runningTotal)
| true |
9f7ab2ec4f7747b7c72e3815310403bcaf53bac8 | ShushantLakhyani/200-Python-Exercises | /exercise_7.py | 570 | 4.28125 | 4 | # Q7) Write a Python program to construct the following pattern, using a nested for loop.
# *
# * *
# * * *
# * * * *
# * * * * *
# * * * *
# * * *
# * *
# *
#step 1: let a variable have the value 5, because of the final number of asterisks is 5
x = 5
# step 2: first 'for loop' to output the asterisks for the first 5 rows
for n in range(x):
for j in range(n):
print('* ',end="")
print('')
# step 2: 'for loop' the number of asterisks for the last 4 rows
for n in range(x,0,-1):
for j in range(n):
print('* ',end="")
print(' ')
| true |
f4753e41101f6702cad27b5c62848e3afc1662a3 | ShushantLakhyani/200-Python-Exercises | /exercise_5.py | 538 | 4.4375 | 4 | #Write a python program to check if a triangle is valid or not
def triangle_validity_check(a,b,c):
if (a>b+c) or (b>a+c) or (c>a+b):
print("This is not a valid triangle.")
elif (a==b+c) or (b==c+a) or (c==a+b):
print("This can form a degenerated triangle.")
else:
print("These values can surely form a triangle.")
side_1 = input("Input length of side 1:\n")
side_2 = input("Input length of side 2:\n")
side_3 = input("Input length of side 3:\n")
triangle_validity_check(side_1,side_2,side_3)
| true |
2de6e4f4e6b61f97dc19627994d5d7fe04c0bcfd | ShushantLakhyani/200-Python-Exercises | /square_root__positive_number.py | 247 | 4.21875 | 4 | # Q3) Find the square root of a positive number
#Declare a number in a variable
a = 8
#to find thhe square root we raise the number to the power of 0.5, so raise a to the power of 0.5
a = a ** 0.5
# Now, print a to get the square root
print(a)
| true |
ba5ab5edaf9b9f85d5b95bc454e418d7cfc0cc6c | Paulvitalis200/Data-Structures | /Sorting/sort_list.py | 1,641 | 4.125 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
# split the list into two halves
left = head
right = self.getMid(head)
tmp = right.next
right.next = None
right = tmp
left = self.sortList(left)
right = self.sortList(right)
return self.merge(left, right)
def getMid(self, head):
slow, fast = head, head.next
while fast and fast.next:
slow= slow.next
fast = fast.next.next
return slow
def merge(self, list1, list2):
# tail will be the position we insert our merged node at
# dummy allows us to avoid the edge case where we merge the two lists, the first node will be the head
tail = dummy = ListNode()
while list1 and list2:
if list1.val < list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
# shift tail pointer so that we can add at the end of the list
tail = tail.next
if list1:
tail.next = list1
if list2:
tail.next = list2
# Return dummy.next to avoid putting the unnecessary node ListNode()
return dummy.next
# Input: head = [4,2,1,3]
# Output: [1,2,3,4] | true |
20cb8f53226940b8b42a70cc1d524d2a37e1d1e8 | Ornella-KK/password-locker | /user_test.py | 1,841 | 4.125 | 4 | import unittest
from user import User
class TestUser(unittest.TestCase):
def setUp(self):
self.new_user = User("Ornella")#create user object
def test_init(self):
'''
test_init test case to test if the object is initialized properly
'''
self.assertEqual(self.new_user.user_name,"Ornella")
def test_save_user(self):
'''
test_save_user test case to test if the user object is saved into
the user list
'''
self.new_user.save_user()
self.assertEqual(len(User.user_list),1)
def tearDown(self):
'''
tearDown method that does clean up after each test case has run.
'''
User.user_list = []
def test_save_multiple_user(self):
'''
test_save_multiple_user to check if we can save multiple user
objects to our user_list
'''
self.new_user.save_user()
test_user = User("user")
test_user.save_user()
self.assertEqual(len(User.user_list),2)
def test_delete_user(self):
'''
test_delete_user to test if we can remove a user from our user list
'''
self.new_user.save_user()
test_user = User("user")
test_user.save_user()
self.new_user.delete_user() #deleting a user object
self.assertEqual(len(User.user_list),1)
def test_user_exists(self):
self.new_user.save_user()
test_user = User("user")
test_user.save_user()
user_exists = User.user_exist("Ornella")
self.assertTrue(user_exists)
def test_display_all_user(self):
'''
method that returns a list of all users saved
'''
self.assertEqual(User.display_user(),User.user_list)
if __name__ == '__main__':
unittest.main() | true |
ba7389bd2476a80e1bd31936abce463963884f4d | DerrickChanCS/Leetcode | /426.py | 1,837 | 4.34375 | 4 | """
Let's take the following BST as an example, it may help you understand the problem better:
We want to transform this BST into a circular doubly linked list. Each node in a doubly linked list has a predecessor and successor. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element.
The figure below shows the circular doubly linked list for the BST above. The "head" symbol means the node it points to is the smallest element of the linked list.
Specifically, we want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. We should return the pointer to the first element of the linked list.
The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship.
"""
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
"""
class Solution(object):
def treeToDoublyList(self, root):
"""
:type root: Node
:rtype: Node
"""
if root:
head, _ = self.helper(root)
return head
return None
def helper(self, root):
head, tail = root, root
if root.left:
h, t = self.helper(root.left)
t.right = root
root.left = t
head = h
if root.right:
h, t = self.helper(root.right)
h.left = root
root.right = h
tail = t
head.left = tail
tail.right = head
return (head,tail)
| true |
164ab46dfc6364b49b06b0bd442fe5e85bd6ca37 | sushmeetha31/BESTENLIST-Internship | /Day 3 task.py | 1,042 | 4.40625 | 4 | #DAY 3 TASK
#1)Write a Python script to merge two Python dictionaries
a1 = {'a':100,'b':200}
a2 = {'x':300,'y':400}
a = a1.copy()
a.update(a2)
print(a)
#2)Write a Python program to remove a key from a dictionary
myDict = {'a':1,'b':2,'c':3,'d':4}
print(myDict)
if 'a' in myDict:
del myDict['a']
print(myDict)
#3)Write a Python program to map two lists into a dictionary
keys = ['red','green','blue']
values = ['1000','2000','3000']
color_dictionary = dict(zip(keys, values))
print(color_dictionary)
#4)Write a Python program to find the length of a set
a = set([1,2,3,4,5)]
print(len(a))
#5)Write a Python program to remove the intersection of a 2nd set from the 1st set
s1 = {1,2,3,4,5}
s2 = {4,5,6,7,8}
print("Original sets:")
print(s1)
print(s2)
print("Remove the intersection of a 2nd set from the 1st set using difference_update():")
s1.difference_update(s2)
print(s1)
s1 = {1,2,3,4,5}
s2 = {4,5,6,7,8}
print("Remove the intersection of a 2nd set from the 1st set using -= operator:")
print(s1-s2)
| true |
125eaf98db6359cb6d899c8e6aea55556c6c99f3 | DKumar0001/Data_Structures_Algorithms | /Bit_Manipulation/Check_Power2.py | 366 | 4.4375 | 4 | # Check wheather a given number is a power of 2 or 0
def Check_pow_2(num):
if num ==0:
return 0
if(num & num-1) == 0:
return 1
return 2
switch ={
0 : "Number is 0",
1 : "Number is power of two",
2 : "Number is neither power of 2 nor 0"
}
number = int(input("Enter a Number"))
case =Check_pow_2(number)
print(switch[case])
| true |
ff61137fb930d6a2b211d8eeb1577ca67ec64924 | YammerStudio/Automate | /CollatzSequence.py | 490 | 4.28125 | 4 |
import sys
'''
Rules:
if number is even, divide it by two
if number is odd, triiple it and add one
'''
def collatz(num):
if(num % 2 == 0):
print(int(num/2))
return int(num/2)
else:
print(int(num * 3 + 1))
return int(num*3 + 1)
print('Please enter a number and the Collatz sequence will be printed!')
try:
x = int(input())
except ValueError:
print('Error: Invalid Value, only integer man')
sys.exit()
while x != 1:
x = collatz(x)
| true |
5ec608e2a356eb31b0095da2153cedb1e74152d3 | oreo0701/openbigdata | /Review/integer_float.py | 801 | 4.1875 | 4 | num = 3
num1 = 3.14
print(type(num))
print(type(num1))
print(3 / 2) # 1.5
print(3 // 2) # floor division = 1
print(3**2) #exponnet
print(3%2) #modulus - distinguish even and odd
print(2 % 2) #even
print(3 % 2) #odd
print(4 % 2)
print(5 % 2)
print(3 * (2 + 1))
#incrementing values
num = 1
num = num + 1
num1 *= 10 #(num =num * 10)
print(num)
print(abs(-3)) #abs :absolute values
print(round(3.75))
print(round(3.75, 1)) #round to the 1st digit of decimial
num_1 = 3 # == comparision, = assignment
num_2 = 2
print(num_1 != num_2)
print(num_1 == num_2)
print(num_1 < num_2)
print(num_1 >= num_2)
#number looks like string
num_3 = '100'
num_4 = '200'
#concatenate together
print(num_3 + num_4)
# casting : cast string to integer
num_3 = int(num_3)
num_4 = int(num_4)
print(num_3 + num_4) | true |
f870ea6fa7baca5bb9c428128313c3a56ac80f4e | oreo0701/openbigdata | /Review/list_tuple_set.py | 1,463 | 4.25 | 4 | #list : sequential data
courses = ['History', 'Math', 'Physic','CompSci']
print(len(courses)) #4 values in list
print(courses[0])
print(courses[3])
print(courses[-1])
print(courses[-4])
print(courses[0:2])
print(courses[:2])
print(courses[2:])
#add values
courses.append('Art')
print(courses)
#choose location to add
courses.insert(0,'Eng')
print(courses)
courses_2 = ['Hello', 'Education']
courses.insert(0, courses_2) # add entire list
print(courses)
print(courses[0])
#combine two lists
courses.extend(courses_2)
print(courses)
#remove
courses.remove('Hello')
print(courses)
courses.pop() # remove last values of list
print(courses)
popped = courses.pop()
print(popped)
print(courses)
courses.reverse()
print(courses)
nums = [1,5,2,4,3]
nums.sort(reverse=True)
print(courses)
print(nums)
print(min(nums))
print(max(nums))
print(sum(nums))
#sorted_courses = sorted(courses) #sorted version of list
#print(sorted_courses)
print(courses.index('CompSci'))
print('Math' in courses)
for item in courses:
print(item)
for index, course in enumerate(courses): #enumerate function
print(index, course)
for index, course in enumerate(courses, start =1): #enumerate function
print(index, course)
courses = ['History', 'Math', 'Physic','CompSci']
#join method
course_str = ', '.join(courses)
print(course_str)
course_str = ' - '.join(courses)
print(course_str)
new_list = course_str.split(' -')
print(course_str)
print(new_list)
| true |
852a1cbe7932d9065b29b6d11f81c3bdc8db6227 | nadiabahrami/c_war_practice | /level_8/evenorodd.py | 272 | 4.4375 | 4 | """Create a function that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers."""
def even_or_odd(number):
return "Even" if number % 2 == 0 else "Odd"
def even_or_odd_bp(num):
return 'Odd' if num % 2 else 'Even'
| true |
4464f45eaf50f90ef887757f56d9ecd02ed7330c | imvera/CityUCOM5507_2018A | /test.py | 500 | 4.21875 | 4 | #0917test
#print("i will now count my chickens")
#print ("hens", 25+30/6)
#print("roosters",100-25*3%4)
#print("now count the eggs")
#print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
#print("is it true that 3+2<5-7?")
#print(3+2<5-7)
#print("what is 3+2?",3+2)
#print("what is 5-7?",5-7)
#print("is it greater?",5 > -2)
#print("is it greater or equal?",5 >= -2)
#print("is it less or equal?",5 <= -2)
#n = int(input('enter a number'))
#while n >= 0:
# print(n)
# n=n-1
## break
#print('done!')
| true |
1a6195375e49cdcf2c06f3fd89f38134bc0ab80e | yukan97/python_essential_mini_tasks | /005_Collections/Task1_3_and_additional.py | 508 | 4.25 | 4 | def avg_multiple(*args):
return sum(args)/len(args)
print(avg_multiple(1, 2, 4, 6))
print(avg_multiple(2, 2))
def sort_str():
s = input("Eneter your text ")
print(' '.join(sorted(s.split(' '))))
sort_str()
def sort_nums():
num_seq_str = input("Please, enter your sequence ").split()
try:
num_seq = [int(x) for x in num_seq_str]
print(sorted(num_seq, reverse=False))
except ValueError:
print('You have entered not numbers into the sequence')
sort_nums() | true |
67dfa55500af7f9c1e0e57bcd96cb01b30d2353c | murchie85/hackerrank_myway | /findaString.py | 1,407 | 4.1875 | 4 | """
https://www.hackerrank.com/challenges/find-a-string/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen
Sample Input
ABCDCDC
CDC
Sample Output
2
Concept
Some string processing examples, such as these, might be useful.
There are a couple of new concepts:
In Python, the length of a string is found by the function len(s), where is the string.
To traverse through the length of a string, use a for loop:
for i in range(0, len(s)):
print (s[i])
A range function is used to loop over some length:
range (0, 5)
Here, the range loops over to . is excluded.
# alternate options
# USING STARTSWITH
def count_substringBest(string, sub_string):
count = 0
for i in range(len(string)):
if string[i:].startswith(sub_string):
count += 1
return count
# USING SLICE
def count_substringUsingSlice(string, sub_string):
count = 0
for letter in range(0,len(string)):
if(string[slice(letter,letter+len(sub_string,1)] == sub_string):
count+=1
return(count)
"""
def count_substring(string, sub_string):
count = 0
for letter in range(len(string)):
if(string[letter:letter+len(sub_string)] == sub_string):
count+=1
return(count)
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
count = count_substring(string, sub_string)
print(count) | true |
87e87abc6bcedda29a349fb945fd45541e8a681a | AirborneRON/Python- | /chatbot/chatBot.py | 1,980 | 4.1875 | 4 | file = open("stop_words")
stopList = file.read().split("\n")
file.close()
# how to open up my plain text file, then create a variable to stuff the read file into
#seperating each element of the list by the return key
#then close
# all responses should start with a space before typing
print(" Hello ")
response = raw_input(" what is your name ?")
words = response.split(" ")
for nextWord in words:
if nextWord not in stopList:
response = response.replace(nextWord, "")
print("Well hello" +" " +nextWord)
#because of how my stopList was formatted ive had to use the split function which has conflicted
#with the String
#print ("line 21" + nextWord)
response = raw_input ("how lovely to meet you")
if (response == "my names aaron"):
print("how is that pronounced if you dont mind me asking ? ")
response = raw_input( " Interesting name btw, my names Mac")
if (response == " nice to meet you"):
print("likewise")
response = raw_input (" where are you from originally ? ")
if (response == "im from cornwall originally"):
print("oh I hear its beautiful down those parts")
#if (response == "")
response = raw_input("is there anywhere you'd want to go for a coffee there ?")
if (response == " yes"):
print("Great I look forward to it")
elif(response == " no"):
print("sod you then" + " i'll go by myself")
response = raw_input("anyways, so how old are you ?")
if (response == " 18"):
print(" not as old as me then ")
elif (response == " 23"):
print("same age as me then")
response = raw_input(" whats your favourite colour ?")
if (response == "blue"):
print("thats mine too")
elif(response == "red"):
print("red is sick" + " but unfortunetly we must end this conversation" )
elif(response == "yellow"):
print ("yellows pretty cool too " + " anyways i really must be off TTFN")
else: print("im not a fan of that colour" + "and on that note good day to you sir")
| true |
c451f37b2016ec1ad6b073a5bae922a98c72e270 | RiverEngineer2018/CSEE5590PythonSPring2018 | /Source Code/Lab3 Q3.py | 2,249 | 4.34375 | 4 | #Don Baker
#Comp-Sci 5590
#Lab 3, Question 3
#Take an Input file. Use the simple approach below to summarize a text file:
#- Read the file
#- Using Lemmatization, apply lemmatization on the words
#- Apply the bigram on the text
#- Calculate the word frequency (bi-gram frequency) of the words (bi-grams)
#- Choose top five bi-grams that has been repeated most
#- Go through the original text that you had in the file
#- Find all the sentences with those most repeated bi-grams
#- Extract those sentences and concatenate
#- Enjoy the summarization
#Import Packages
import nltk
from nltk.tokenize import TweetTokenizer
from nltk.stem import WordNetLemmatizer
#Read Text File
file_path = 'd:/Google Drive/UMKC/PhD/Classes/Python/Labs/Lab 3/Python_Lab3.txt'
text_file = open(file_path,'r')
text_data=text_file.read()
text_file.close()
#Using Lemmatization, apply lemmatization on the words
#First step is to tokenize the data file into individual words
tkn = TweetTokenizer() #create a tokenizer
token = tkn.tokenize(text_data) #tokenize the data
print("Tokenize: \n",(token),"\n")
#print(token_results)
#Now lemmatize the tokenize text file (noun is th default)
wnl = WordNetLemmatizer() #create lemmatizer
lem = [wnl.lemmatize(tkn) for tkn in token]
print("Lemmatize (nouns): \n",lem,"\n")
#Try lemmatizing looking for verbs
wnl = WordNetLemmatizer() #create lemmatizer
lem = [wnl.lemmatize(tkn,pos="v") for tkn in token]
print("Lemmatize (verbs): \n",lem,"\n")
#Try lemmatizing looking for adjectives
wnl = WordNetLemmatizer() #create lemmatizer
lem = [wnl.lemmatize(tkn,pos="a") for tkn in token]
print("Lemmatize (adjectives): \n",lem,"\n")
#Try lemmatizing looking for adverbs
wnl = WordNetLemmatizer() #create lemmatizer
lem = [wnl.lemmatize(tkn,pos="r") for tkn in token]
print("Lemmatize (adverbs): \n",lem,"\n")
#Apply bigram on the text
#Grouping two words together. This includes special characters like '('
bigram = [tkn for tkn in nltk.bigrams(token)]
print("Bigram: \n",bigram)
#Calculate the Bigram Frequency
freq_bi=nltk.FreqDist(bigram)
#Find the 5 most common bigrams
bi_common=freq_bi.most_common(5)
print("\nThe 5 most common bigrams are:\n",bi_common) | true |
49007104a978b21ad305c9ae13413da0dccd7e77 | noy20-meet/meet2018y1lab4 | /sorter.py | 228 | 4.375 | 4 | bin1="apples"
bin2="oranges"
bin3="olives"
new_fruit = input('What fruit am I sorting?')
if new_fruit== bin1:
print('bin 1')
elif new_fruit== bin2:
print('bin 2')
else:
print('Error! I do not recognise this fruit!')
| true |
ed6f6da350b48cde11a0e7952aad238c590cca74 | mkoryor/Python | /coding patterns/dynamic programming/palindromic_subsequence/palindromic_partitioning_brute.py | 1,329 | 4.15625 | 4 |
"""
Given a string, we want to cut it into pieces such that each piece is a palindrome. Write a function to return the minimum number of cuts needed.
Example 1:
Input: "abdbca"
Output: 3
Explanation: Palindrome pieces are "a", "bdb", "c", "a".
Example 2:
Input: = "cddpd"
Output: 2
Explanation: Palindrome pieces are "c", "d", "dpd".
"""
# Time: O(2^n) Space: O(n)
def find_MPP_cuts(st):
return find_MPP_cuts_recursive(st, 0, len(st)-1)
def find_MPP_cuts_recursive(st, startIndex, endIndex):
# we don't need to cut the string if it is a palindrome
if startIndex >= endIndex or is_palindrome(st, startIndex, endIndex):
return 0
# at max, we need to cut the string into its 'length-1' pieces
minimumCuts = endIndex - startIndex
for i in range(startIndex, endIndex+1):
if is_palindrome(st, startIndex, i):
# we can cut here as we have a palindrome from 'startIndex' to 'i'
minimumCuts = min(
minimumCuts, 1 + find_MPP_cuts_recursive(st, i + 1, endIndex))
return minimumCuts
def is_palindrome(st, x, y):
while (x < y):
if st[x] != st[y]:
return False
x += 1
y -= 1
return True
def main():
print(find_MPP_cuts("abdbca"))
print(find_MPP_cuts("cdpdd"))
print(find_MPP_cuts("pqr"))
print(find_MPP_cuts("pp"))
print(find_MPP_cuts("madam"))
main()
| true |
d7830b9e24ae1feeff3e2e7fce5b3db531adab73 | mkoryor/Python | /coding patterns/dynamic programming/palindromic_subsequence/longest_palin_substring_topDownMemo.py | 1,591 | 4.15625 | 4 |
"""
Given a string, find the length of its Longest Palindromic Substring (LPS).
In a palindromic string, elements read the same backward and forward.
Example 1:
Input: "abdbca"
Output: 3
Explanation: LPS is "bdb".
Example 2:
Input: = "cddpd"
Output: 3
Explanation: LPS is "dpd".
Example 3:
Input: = "pqr"
Output: 1
Explanation: LPS could be "p", "q" or "r".
"""
# Time: O(N^2) Space: O(N^2)
def find_LPS_length(st):
n = len(st)
dp = [[-1 for _ in range(n)] for _ in range(n)]
return find_LPS_length_recursive(dp, st, 0, n - 1)
def find_LPS_length_recursive(dp, st, startIndex, endIndex):
if startIndex > endIndex:
return 0
# every string with one character is a palindrome
if startIndex == endIndex:
return 1
if dp[startIndex][endIndex] == -1:
# case 1: elements at the beginning and the end are the same
if st[startIndex] == st[endIndex]:
remainingLength = endIndex - startIndex - 1
# if the remaining string is a palindrome too
if remainingLength == find_LPS_length_recursive(dp, st, startIndex + 1, endIndex - 1):
dp[startIndex][endIndex] = remainingLength + 2
return dp[startIndex][endIndex]
# case 2: skip one character either from the beginning or the end
c1 = find_LPS_length_recursive(dp, st, startIndex + 1, endIndex)
c2 = find_LPS_length_recursive(dp, st, startIndex, endIndex - 1)
dp[startIndex][endIndex] = max(c1, c2)
return dp[startIndex][endIndex]
def main():
print(find_LPS_length("abdbca"))
print(find_LPS_length("cddpd"))
print(find_LPS_length("pqr"))
main()
| true |
027f1de2e737fdc5556c86a83f0e7248c2812934 | mkoryor/Python | /coding patterns/subsets/string_permutation.py | 1,143 | 4.1875 | 4 |
"""
[M] Given a string, find all of its permutations preserving the character
sequence but changing case.
Example 1:
Input: "ad52"
Output: "ad52", "Ad52", "aD52", "AD52"
Example 2:
Input: "ab7c"
Output: "ab7c", "Ab7c", "aB7c", "AB7c", "ab7C", "Ab7C", "aB7C", "AB7C"
"""
# Time: O(N * 2^n) Space: O(N * 2^n)
def find_letter_case_string_permutations(str):
permutations = []
permutations.append(str)
# process every character of the string one by one
for i in range(len(str)):
if str[i].isalpha(): # only process characters, skip digits
# we will take all existing permutations and change the letter case appropriately
n = len(permutations)
for j in range(n):
chs = list(permutations[j])
# if the current character is in upper case, change it to lower case or vice versa
chs[i] = chs[i].swapcase()
permutations.append(''.join(chs))
return permutations
def main():
print("String permutations are: " +
str(find_letter_case_string_permutations("ad52")))
print("String permutations are: " +
str(find_letter_case_string_permutations("ab7c")))
main()
| true |
2c713bda8945104526d6784acdced81ae0681ad4 | mkoryor/Python | /coding patterns/modified binary search/bitonic_array_maximum.py | 957 | 4.1875 | 4 |
"""
[E] Find the maximum value in a given Bitonic array. An array is
considered bitonic if it is monotonically increasing and then
monotonically decreasing. Monotonically increasing or decreasing means
that for any index i in the array arr[i] != arr[i+1].
Example 1:
Input: [1, 3, 8, 12, 4, 2]
Output: 12
Explanation: The maximum number in the input bitonic array is '12'.
Example 2:
Input: [3, 8, 3, 1]
Output: 8
"""
# Time: O(logn) Space: O(1)
def find_max_in_bitonic_array(arr):
start, end = 0, len(arr) - 1
while start < end:
mid = start + (end - start) // 2
if arr[mid] > arr[mid + 1]:
end = mid
else:
start = mid + 1
# at the end of the while loop, 'start == end'
return arr[start]
def main():
print(find_max_in_bitonic_array([1, 3, 8, 12, 4, 2]))
print(find_max_in_bitonic_array([3, 8, 3, 1]))
print(find_max_in_bitonic_array([1, 3, 8, 12]))
print(find_max_in_bitonic_array([10, 9, 8]))
main()
| true |
83407eac0a8aaa8a71aa1631bbd17f5818dc877c | mkoryor/Python | /coding patterns/dynamic programming/longest_common_substring/subsequence_pattern_match_bottomUpTabu.py | 1,261 | 4.15625 | 4 |
"""
Given a string and a pattern, write a method to count the number of
times the pattern appears in the string as a subsequence.
Example 1: Input: string: “baxmx”, pattern: “ax”
Output: 2
Explanation: {baxmx, baxmx}.
Example 2:
Input: string: “tomorrow”, pattern: “tor”
Output: 4
Explanation: Following are the four occurences:
{tomorrow, tomorrow, tomorrow, tomorrow}.
"""
# Time: O(m * n) Space: O(m * n)
def find_SPM_count(str, pat):
strLen, patLen = len(str), len(pat)
# every empty pattern has one match
if patLen == 0:
return 1
if strLen == 0 or patLen > strLen:
return 0
# dp[strIndex][patIndex] will be storing the count of SPM up to str[0..strIndex-1][0..patIndex-1]
dp = [[0 for _ in range(patLen+1)] for _ in range(strLen+1)]
# for the empty pattern, we have one matching
for i in range(strLen+1):
dp[i][0] = 1
for strIndex in range(1, strLen+1):
for patIndex in range(1, patLen+1):
if str[strIndex - 1] == pat[patIndex - 1]:
dp[strIndex][patIndex] = dp[strIndex - 1][patIndex - 1]
dp[strIndex][patIndex] += dp[strIndex - 1][patIndex]
return dp[strLen][patLen]
def main():
print(find_SPM_count("baxmx", "ax"))
print(find_SPM_count("tomorrow", "tor"))
main() | true |
b2ae19549528e82aaec418c4bb32868ac9272b73 | mkoryor/Python | /binary trees/diameterBT.py | 1,697 | 4.3125 | 4 |
# A binary tree Node
class Node:
# Constructor to create a new Node
def __init__(self, data):
self.data = data
self.left = self.right = None
# utility class to pass height object
class Height:
def __init(self):
self.h = 0
# Optimised recursive function to find diameter
# of binary tree
def diameterOpt(root, height):
# to store height of left and right subtree
lh = Height()
rh = Height()
# base condition- when binary tree is empty
if root is None:
height.h = 0
return 0
"""
ldiameter --> diameter of left subtree
rdiamter --> diameter of right subtree
height of left subtree and right subtree is obtained from lh and rh
and returned value of function is stored in ldiameter and rdiameter
"""
ldiameter = diameterOpt(root.left, lh)
rdiameter = diameterOpt(root.right, rh)
# height of tree will be max of left subtree
# height and right subtree height plus1
height.h = max(lh.h, rh.h) + 1
# return maximum of the following
# 1)left diameter
# 2)right diameter
# 3)left height + right height + 1
return max(lh.h + rh.h + 1, max(ldiameter, rdiameter))
# function to calculate diameter of binary tree
def diameter(root):
height = Height()
return diameterOpt(root, height)
# Driver function to test the above function
"""
Constructed binary tree is
1
/ \
2 3
/ \
4 5
"""
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print( diameter(root) )
| true |
b6c8c4750c8feca766f8d199428d11f6d5410ec6 | mkoryor/Python | /binary trees/inorder_traversal_iterative.py | 657 | 4.15625 | 4 |
# Iterative function to perform in-order traversal of the tree
def inorderIterative(root):
# create an empty stack
stack = deque()
# start from root node (set current node to root node)
curr = root
# if current node is None and stack is also empty, we're done
while stack or curr:
# if current node is not None, push it to the stack (defer it)
# and move to its left child
if curr:
stack.append(curr)
curr = curr.left
else:
# else if current node is None, we pop an element from the stack,
# print it and finally set current node to its right child
curr = stack.pop()
print(curr.data, end=' ')
curr = curr.right
| true |
68db251c87295d02c092b7e521524f134b55d0a8 | mkoryor/Python | /coding patterns/dynamic programming/palindromic_subsequence/palindromic_partitioning_bottomUpTabu.py | 1,836 | 4.15625 | 4 |
"""
Given a string, we want to cut it into pieces such that each piece is a palindrome. Write a function to return the minimum number of cuts needed.
Example 1:
Input: "abdbca"
Output: 3
Explanation: Palindrome pieces are "a", "bdb", "c", "a".
Example 2:
Input: = "cddpd"
Output: 2
Explanation: Palindrome pieces are "c", "d", "dpd".
"""
# Time: O(N^2) Space: O(N^2)
def find_MPP_cuts(st):
n = len(st)
# isPalindrome[i][j] will be 'true' if the string from index 'i' to index 'j' is a palindrome
isPalindrome = [[False for _ in range(n)] for _ in range(n)]
# every string with one character is a palindrome
for i in range(n):
isPalindrome[i][i] = True
# populate isPalindrome table
for startIndex in range(n-1, -1, -1):
for endIndex in range(startIndex+1, n):
if st[startIndex] == st[endIndex]:
# if it's a two character string or if the remaining string is a palindrome too
if endIndex - startIndex == 1 or isPalindrome[startIndex + 1][endIndex - 1]:
isPalindrome[startIndex][endIndex] = True
# now lets populate the second table, every index in 'cuts' stores the minimum cuts needed
# for the substring from that index till the end
cuts = [0 for _ in range(n)]
for startIndex in range(n-1, -1, -1):
minCuts = n # maximum cuts
for endIndex in range(n-1, startIndex-1, -1):
if isPalindrome[startIndex][endIndex]:
# we can cut here as we got a palindrome
# also we don't need any cut if the whole substring is a palindrome
minCuts = 0 if endIndex == n-1 else min(minCuts, 1 + cuts[endIndex + 1])
cuts[startIndex] = minCuts
return cuts[0]
def main():
print(find_MPP_cuts("abdbca"))
print(find_MPP_cuts("cdpdd"))
print(find_MPP_cuts("pqr"))
print(find_MPP_cuts("pp"))
print(find_MPP_cuts("madam"))
main() | true |
db3da546c26b6d3c430ca62e18a2fc2127d76e60 | mkoryor/Python | /coding patterns/dynamic programming/knapsack_and_fib/count_subset_sum_bruteforce.py | 1,325 | 4.15625 | 4 |
"""
Given a set of positive numbers, find the total number of subsets whose sum
is equal to a given number ‘S’.
Example 1: #
Input: {1, 1, 2, 3}, S=4
Output: 3
The given set has '3' subsets whose sum is '4': {1, 1, 2}, {1, 3}, {1, 3}
Note that we have two similar sets {1, 3}, because we have two '1' in our input.
Example 2: #
Input: {1, 2, 7, 1, 5}, S=9
Output: 3
The given set has '3' subsets whose sum is '9': {2, 7}, {1, 7, 1}, {1, 2, 1, 5}
"""
# Time: O(2^n) Space: O(N)
def count_subsets(num, sum):
return count_subsets_recursive(num, sum, 0)
def count_subsets_recursive(num, sum, currentIndex):
# base checks
if sum == 0:
return 1
n = len(num)
if n == 0 or currentIndex >= n:
return 0
# recursive call after selecting the number at the currentIndex
# if the number at currentIndex exceeds the sum, we shouldn't process this
sum1 = 0
if num[currentIndex] <= sum:
sum1 = count_subsets_recursive(
num, sum - num[currentIndex], currentIndex + 1)
# recursive call after excluding the number at the currentIndex
sum2 = count_subsets_recursive(num, sum, currentIndex + 1)
return sum1 + sum2
def main():
print("Total number of subsets " + str(count_subsets([1, 1, 2, 3], 4)))
print("Total number of subsets: " + str(count_subsets([1, 2, 7, 1, 5], 9)))
main() | true |
1f567c01031206e9cd45c02f0590a36a0affde12 | mkoryor/Python | /coding patterns/dynamic programming/longest_common_substring/longest_common_substring_topDownMemo.py | 1,204 | 4.125 | 4 |
"""
Given two strings ‘s1’ and ‘s2’, find the length of the longest substring which
is common in both the strings.
Example 1:
Input: s1 = "abdca"
s2 = "cbda"
Output: 2
Explanation: The longest common substring is "bd".
Example 2:
Input: s1 = "passport"
s2 = "ppsspt"
Output: 3
Explanation: The longest common substring is "ssp".
"""
# Time: O(m * n) Space: O(m * n)
def find_LCS_length(s1, s2):
n1, n2 = len(s1), len(s2)
maxLength = min(n1, n2)
dp = [[[-1 for _ in range(maxLength)] for _ in range(n2)]
for _ in range(n1)]
return find_LCS_length_recursive(dp, s1, s2, 0, 0, 0)
def find_LCS_length_recursive(dp, s1, s2, i1, i2, count):
if i1 == len(s1) or i2 == len(s2):
return count
if dp[i1][i2][count] == -1:
c1 = count
if s1[i1] == s2[i2]:
c1 = find_LCS_length_recursive(
dp, s1, s2, i1 + 1, i2 + 1, count + 1)
c2 = find_LCS_length_recursive(dp, s1, s2, i1, i2 + 1, 0)
c3 = find_LCS_length_recursive(dp, s1, s2, i1 + 1, i2, 0)
dp[i1][i2][count] = max(c1, max(c2, c3))
return dp[i1][i2][count]
def main():
print(find_LCS_length("abdca", "cbda"))
print(find_LCS_length("passport", "ppsspt"))
main()
| true |
adf515163aad1d273839c8c6ed2ca2d8503dfb9b | adamomfg/lpthw | /ex15ec1.py | 1,187 | 4.59375 | 5 | #!/usr/bin/python
# from the sys module, import the argv module
from sys import argv
# Assign the script and filename variables to argv. argv is a list of
# command lne parameters passed to a python script, with argv[0] being the
# script name.
script, filename = argv
# assign the txt variable to the instance of opening the variable filename.
txt = open(filename)
# print the raw contents (read eval print loop!) of the instance of open
# from the variable filename.
print "Here's your file %r:" % filename
# execute the read function on the open instantiation on filename
print txt.read()
# prompt the user of the script for the string representation of the file
# that we had just opened.
print "Type the filename again:"
# assign the variable file_again to the string form of the input from the prompt
file_again = raw_input(" ")
# try to open the file with the name that's the string of the input just
# given to the script. as in, instantiate the open method on the parameter
# file_again, which is a string representation of the file's name
txt_again = open(file_again)
# print the contents of the file that was instantiated with the open command
print txt_again.read()
| true |
92be2d072d41e740329b967749d113fb96a40882 | amZotti/Python-challenges | /Python/12.2.py | 993 | 4.15625 | 4 |
class Location:
def __init__(self,row,column,maxValue):
self.row = row
self.column = column
self.maxValue = float(maxValue)
print("The location of the largest element is %d at (%d, %d)"%(self.maxValue,self.row,self.column))
def getValues():
row,column = [int(i) for i in input("Enter the number of rows and columns in the list: ").split(',')]
l1=[]
for k in range(row):
l1.append([])
for i in range(row):
print("Enter row: ",i)
l1[i] = input().split()
if len(l1[i]) == column:
pass
else:
print("Invalid entry, Enter",column,"values,not",len(l1[i]),". Aborting!")
break
return l1
def locateLargest():
l1 = getValues()
maxValue = max(max(l1))
row = l1.index(max(l1))
column = l1[row].index(maxValue)
return Location(row,column,maxValue)
def main():
locateLargest()
if __name__ == "__main__":
main()
| true |
b3fbd14eb0439bbb1249fd30112f81f1c72f2d51 | lglang/BIFX502-Python | /PA8.py | 2,065 | 4.21875 | 4 | # Write a program that prompts the user for a DNA sequence and translates the DNA into protein.
def main():
seq = get_valid_sequence("Enter a DNA sequence: ")
codons = get_codons(seq.upper())
new_codons = get_sets_three(codons)
protein = get_protein_sequence(new_codons)
print(protein)
def get_valid_sequence(prompt):
seq = input(prompt)
seq = seq.upper()
nucleotides = "CATGX"
for nucleotide in nucleotides:
if nucleotide in seq:
return seq
else:
print("Please enter a valid DNA sequence")
return get_valid_sequence(prompt)
def get_codons(seq):
codons = [seq[i: i + 3] for i in range(0, len(seq), 3)]
return codons
def get_sets_three(codons):
for item in codons:
short = len(item) < 3
if short:
codons.remove(item)
return codons
def get_protein_sequence(codons):
gencode = {'TTT': 'F', 'TTC': 'F', 'TTA': 'L', 'TTG': 'L', 'TCT': 'S', 'TCC': 'S', 'TCA': 'S',
'TCG': 'S', 'TAT': 'Y', 'TAC': 'Y', 'TGT': 'C', 'TGC': 'C', 'TGG': 'W', 'CTT': 'L',
'CTC': 'L', 'CTA': 'L', 'CTG': 'L', 'CCT': 'P', 'CCC': 'P', 'CCA': 'P', 'CCG': 'P',
'CAT': 'H', 'CAC': 'H', 'CAA': 'Q', 'CAG': 'Q', 'CGT': 'R', 'CGC': 'R', 'CGA': 'R',
'CGG': 'R', 'ATT': 'I', 'ATC': 'I', 'ATA': 'I', 'ATG': 'M', 'ACT': 'T', 'ACC': 'T',
'ACA': 'T', 'ACG': 'T', 'AAT': 'N', 'AAC': 'N', 'AAA': 'K', 'AAG': 'K', 'AGT': 'S',
'AGC': 'S', 'AGA': 'R', 'AGG': 'R', 'GTT': 'V', 'GTC': 'V', 'GTA': 'V', 'GTG': 'V',
'GCT': 'A', 'GCC': 'A', 'GCA': 'A', 'GCG': 'A', 'GAT': 'D', 'GAC': 'D', 'GAA': 'E',
'GAG': 'E', 'GGT': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'G'}
stop_codons = {'TAA': '*', 'TAG': '*', 'TGA': '*'}
protein = []
for item in codons:
if item in gencode:
protein = protein + list(gencode[item])
if item in stop_codons:
protein = protein + list(stop_codons[item])
return protein
main()
| true |
1efa65530ee7adfb87f28b485aa621d7bab157ca | nat-sharpe/Python-Exercises | /Day_1/loop2.py | 264 | 4.125 | 4 | start = input("Start from: ")
end = input("End on: ") + 1
if end < start:
print "Sorry, 2nd number must be greater than 1st."
start
end
for i in range(start,end):
if end < start:
print "End must be greater than start"
print i
| true |
fb971ad16bda2bb5b3b8bff76105a45510bcc24c | fyupanquia/idat001 | /a.py | 469 | 4.125 | 4 | name = input("Enter your name: ")
worked_hours = float(input("How many hours did you work?: "))
price_x_hour = float(input("Enter your price per hour (S./): "))
discount_perc = 0.15;
gross_salary = worked_hours*price_x_hour
discount = gross_salary*discount_perc
salary=gross_salary-discount
print("")
print("*"*10)
print(f"Worker : {name}")
print(f"Gross Salary : S./{gross_salary}")
print(f"Discount (15%): S./{discount}")
print(f"Salary : S./{salary}")
print("*"*10)
| true |
fd66e0908166c686971c2164cb81331045a54f49 | AniyaPayton/GWC-SIP | /gsw.py | 1,714 | 4.375 | 4 | import random
# A list of words that
word_bank = ["daisy", "rose", "lily", "sunflower", "lilac"]
word = random.choice(word_bank)
correct = word
# Use to test your code:
#print(word){key: value for key, value in variable}
# Converts the word to lowercase
word = word.lower()
# Make it a list of letters for someone to guess
current_word = []
for w in range(len(word)):
current_word.append("_")
print(current_word)
# TIP: the number of letters should match the word
# Some useful variables
guess = []
maxfails = 3
fails = 0
count = 0
letter_guess = ''
word_guess = ''
store_letter = ''
#you should make a loop where it checks the amount of letters inputted
while fails < maxfails:
guess = input("Guess a letter: ")
#while count < fails:
if letter_guess in word:
print('yes!')
store_letter += letter_guess
count += 1
if letter_guess not in word:
print('no!')
count += 1
print('Now its time to guess. You have guessed',len(store_letter),'letters correctly.')
print('These letters are: ', store_letter)
#you don't need this because o fyour previous while loop. The one above
#will only run until the user runs out of guesses
while fails > maxfails:
word_guess = input('Guess the whole word: ')
while word_guess:
if word_guess.lower() == correct:
print('Congrats!')
break
elif word_guess.lower() != correct:
print('Unlucky! The answer was,', word)
break
#check if the guess is valid: Is it one letter? Have they already guessed it?
# check if the guess is correct: Is it in the word? If so, reveal the letters!
print(current_word)
#fails = fails+1
#print("You have " + str(maxfails - fails) + " tries left!")
| true |
f873c177b269ff834f3cb930f14b17d6295c4c1c | kronicle114/codewars | /python/emoji_translator.py | 837 | 4.4375 | 4 | # create a function that takes in a sentence with ASCII emoticons and converts them into emojis
# input => output
# :) => 😁
# :( => 🙁
# <3 => ❤
ascii_to_emoji = {
':)': '😁',
':(': '🙁',
'<3': '❤️',
':mad:': '😡',
':fire:': '🔥',
':shrug:': '¯\_(ツ)_/¯'
}
def emoji_translator(input, mapper):
output = ''
# take the input and split it
words_list = input.split(' ')
# use a forloop and in to figure out if the word is in the dict to map
for word in words_list:
if word in mapper: # if it is then add it but as the value of the ascii dict
output += ' ' + mapper[word]
else: # if the word is not there then add it to the string output
output += word
print(output)
return output
emoji_translator('hello :)', ascii_to_emoji) | true |
8cfc878be48ddbf6fc5a6a977075b1691b4c44c6 | IcefoxCross/python-40-challenges | /CH2/ex6.py | 778 | 4.28125 | 4 | print("Welcome to the Grade Sorter App")
grades = []
# Data Input
grades.append(int(input("\nWhat is your first grade? (0-100): ")))
grades.append(int(input("What is your second grade? (0-100): ")))
grades.append(int(input("What is your third grade? (0-100): ")))
grades.append(int(input("What is your fourth grade? (0-100): ")))
print(f"\nYour grades are: {grades}")
# Data Sorting
grades.sort(reverse=True)
print(f"\nYour grades from highest to lowest are: {grades}")
# Dropping lowest grades
print("\nThe lowest two grades will now be dropped.")
print(f"Removed grade: {grades.pop()}")
print(f"Removed grade: {grades.pop()}")
# Final printing
print(f"\nYour remaining grades are: {grades}")
print(f"Nice work! Your highest grade is a {grades[0]}.") | true |
b0be90fabd5a0ba727f3e8c36d79aead438e20b5 | TheOneTAR/PDXDevCampKyle | /caish_money.py | 2,961 | 4.375 | 4 | """An account file ofr our Simple bank."""
class Account:
"""An Account class that store account info"""
def __init__(self, balance, person, account_type):
self.balance = balance
self.account_type = account_type
self.owner = person
def deposit(self, money):
self.balance += money
self.check_balance()
def withdraw(self, money):
if money > self.balance:
print("Insufficient funds. Apply for a loan today!!")
else:
self.balance -= money
self.check_balance()
def check_balance(self):
print("Your account balance is ${:,.2f}".format(self.balance))
class Person:
"""A class that tracks Persons in our bank."""
def __init__(self, first_name, last_name, email):
self.first_name = first_name
self.last_name = last_name
self.email = email
self.accounts = {}
def open_account(self, init_balance, account_name, account_type = 'checking'):
self.accounts[account_name] = Account(init_balance, self, account_type)
print("Your account is open!")
self.accounts[account_name].check_balance()
def close_account(self, index):
del self.accounts[index]
print("Please come back when you have more money.")
def list_accounts(self):
for account_name, account in self.accounts.items():
print("{} is a {} account with a balance of ${:,.2f}.".format(
account_name,
account.account_type,
account.balance
))
class Bank:
"""Our top-level class; controls Persons and their Accounts."""
def __init__(self):
self.customers = {}
self.savings_interest = 1.07
def new_customer(self, first_name, last_name, email):
self.customers[email] = Person(first_name, last_name, email)
def remove_customer(self, email):
del self.customers[email]
def show_customer_info(self, email):
customer = self.customers[email]
print("\nCustomer: {}, {}\nEmail: {}\n".format(
customer.last_name, customer.first_name, customer.email
))
print("Accounts:\n" + ("-" * 40))
customer.list_accounts()
def customer_deposit(self, email, money, account_name):
self.customers[email].accounts[account_name].deposit(money)
def customer_withdraw(self, email, money, account_name):
self.customers[email].accounts[account_name].withdraw(money)
def make_customer_account(self, email, money, account_name, account_type="checking"):
self.customers[email].open_account(money, account_name, account_type)
if __name__ == '__main__':
bank = Bank()
bank.new_customer("Kyle", "Joecken", "kjoecken@hotmail.com")
bank.make_customer_account("kjoecken@hotmail.com", 1000, "Primary Checking")
bank.make_customer_account("kjoecken@hotmail.com", 10000, "Primary Savings", "savings")
bank.show_customer_info("kjoecken@hotmail.com")
| true |
6e7622b6cc1de5399b05d7c52fe480f832c495ba | jacobkutcka/Python-Class | /Week03/hash_pattern.py | 636 | 4.25 | 4 | ################################################################################
# Date: 02/17/2021
# Author: Jacob Kutcka
# This program takes a number from the user
# and produces a slant of '#' characters
################################################################################
# Ask user for Input
INPUT = int(input('Enter the number of lines: '))
# Begin loop between 0 and INPUT
for i in range(INPUT):
# Begin output
output = '#'
# Count spaces requried
for c in range(i):
# Add spaces to output
output += ' '
# Add final '#' to output
output += '#'
# Print output
print(output)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.