blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0f12c136eb165f73e16dbc9d3c73d647ac6aa708 | hamzai7/pythonReview | /nameLetterCount.py | 302 | 4.25 | 4 | # This program asks for your name and returns the length
print("Hello! Please enter your name: ")
userName = input()
print("Hi " + userName + ", it is nice to meet you!")
def count_name():
count = str(len(userName))
return count
print("Your name has " + count_name() + " letters in it!")
| true |
3a55237ee2f95f66677b00a341d0b5f3585bb3d3 | rayramsay/hackbright-2016 | /01 calc1/arithmetic.py | 922 | 4.28125 | 4 | def add(num1, num2):
""" Return the sum """
answer = num1 + num2
return answer
def subtract(num1, num2):
""" Return the difference """
answer = num1 - num2
return answer
def multiply(num1, num2):
""" Return the result of multiplication """
answer = num1 * num2
return answer
def divide(num1, num2):
""" Return the result of division """
answer = float(num1)/float(num2)
# only one of these needs to be a float; an int divided by a float is a float
return answer
def square(num1):
""" Return the square """
answer = num1 * num1
return answer
def cube(num1):
""" Return the cube """
answer = num1 ** 3
return answer
def power(num1, num2):
""" Return the num1 ^ num2 power """
answer = num1 ** num2
return answer
def mod(num1, num2):
""" Return the modulous or remainder """
answer = num1 % num2
return answer
| true |
43ff1d9bd4e3b0236126c9f138da52c3edd87064 | Jordonguy/PythonTests | /Warhammer40k8th/Concept/DiceRollingAppv2.py | 1,716 | 4.59375 | 5 | # An small application that allows the user to select a number of 6 sided dice and roll them
import random
quit = False
dice_rolled = 0
results = []
while(quit == False):
# Taking User Input
dice_rolled = dice_rolled
dice_size = int(input("Enter the size of the dice you : "))
dice_num = int(input("Enter the number of dice you want : "))
print("You have selected " + str(dice_num) + " dice.")
while(dice_num > 0):
random_num = random.randint(1, dice_size)
# make this random.randint(1,6) be assigned to a variable called random_num etc.
# print(random_num)
results.append(random_num)
dice_num -= 1
dice_rolled += 1
print("Overall Dice Rolled : " + str(dice_rolled))
print("|| Results table ||")
while (dice_size > 0):
count = results.count(dice_size)
print(str(dice_size) + " was rolled : " + str(count))
dice_size -= 1
# Brief experiment with informing the user if the roll was above or below average.
#average = 0
# while(dice_rolled > 0):
# average += 3
# dice_rolled -= 1
# if (sum(results) > average):
# print("total : " + str(sum(results)) + " above average roll")
# else:
# print("total : " + str(sum(results)) + " below average roll")
#print(str((sum(results)) - average) + " from the average")
user_choice = str(
input("|| Enter [Quit] to close the application : Press enter to perform another roll || "))
if(user_choice == "Quit"):
quit = True
else:
quit = False
# Make a better way of showing results
# Allow user to keep rolling new dice(reset old results etc)
# Allow the user to select the size of the dice
| true |
90ff8bcc34a2e380db6f0b71dd113e83dd764c46 | EricksonGC2058/all-projects | /todolist.py | 704 | 4.15625 | 4 | print("Welcome to the To Do List! (:")
todolist = []
while True:
print("Enter 'a' to add an item")
print("Enter 'r' to remove an item")
print("Enter 'p' to print the list")
print("Enter 'q' to quit")
choice = input("Make your choice: ")
if choice == "q":
break
elif choice == "a":
todoitems = input("What will you add to your list? ")
todolist.append(todoitems)
elif choice == "r":
todotakeout = input("What will you take out of your list? ")
todolist.remove(todotakeout)
elif choice == "p":
count = 1
for todoitems in todolist:
print("Task " + str(count) + ": " + todoitems)
count = count + 1
else:
print("That is not a choice, please try again.") | true |
9dd4a8bea6d079f6bd3883fe53949bfbb1d58f1b | AndreasWJ/Plot-2d | /curve.py | 2,638 | 4.3125 | 4 | class Curve:
def __init__(self, curve_function, color, width):
self.curve_function = curve_function
self.color = color
self.width = width
def get_pointlist(self, x_interval, precision=1):
'''
The point precision works by multiplying the start and end of the interval. By doing so you're making
the difference between the start and end bigger. By making the difference bigger you are allowing for
more precision when generating the pointlist. More x values equals more points as the curve function
is called for each x value.
The index in the range between this multiplied interval can't simply be appended to the pointlist
as the x values are too large. For example, if you are generating points for the
interval 0 < x < 10, the multiplied interval with a precision of 10 would be 0 < x < 100.
Anything beyond 10 is irrelevant to the user since that's what is the interval that's requested.
Before appending the x and its y value to the pointlist you need to create a new variable where
you reverse the changes you made when you multiplied the interval. This will normalize the
interval back to its original state 0 < x < 10. By having an increased precision you will
generate more x values between the x values in the interval. For example, the generated
x values might look like: 0, 0.33, 0.66, 1, 1.33, 1.66, 2, etc.
To reverse you multiply the multiplied interval index with (1 / precision) which removes
the multiplication applied to the interval.
:param x_interval: The interval of x values to generate points for
:param precision: Set the point precision. The default value is 1 which will generate points for each
x in the x interval. But with an increased precision more points are generated between each x value
resulting in a better looking curve.
:return: A list of points which are tuples
'''
pointlist = []
x_start_with_precision = (x_interval[0] * precision)
x_end_with_precision = ((x_interval[1] + 1) * precision)
# Add one to the stop value of the range function. Otherwise if you have an x interval 0 < x < 10, it will
# only generate points up to and including 9. Why is it so?
for x in range(x_start_with_precision, x_end_with_precision):
# print('Generated point ({}, {})'.format(x, self.curve_function(x)))
point_x = x * (1 / precision)
pointlist.append((point_x, self.curve_function(point_x)))
return pointlist
| true |
4c1922842c2bb7027d6c1f77f5d11bb4d1250a1a | keeyong/state_capital | /learn_dict.py | 906 | 4.4375 | 4 | # two different types of dictionary usage
#
# Let's use first name and last name as an example
# 1st approach is to use "first name" and "last name" as separate keys. this approach is preferred
# 2nd approach is to use first name value as key and last name as value
# ---- 1st apprach
name_1 = { 'firstname': 'keeyong', 'lastname': 'han' }
name_2 = { 'firstname': 'dennis', 'lastname': 'yang' }
names = []
names.append(name_1)
names.append(name_2)
for name in names:
print("1st approach - first name:" + name["firstname"] + ", last name:" + name["lastname"])
# ---- 2nd approach
# 여기서는 키는 이름이 되고 값은 성이 되는 구조이다
name_1 = { 'keeyong': 'han' }
name_2 = { 'dennis': 'yang' }
names = []
names.append(name_1)
names.append(name_2)
for name in names:
for key, value in name.items():
print("2nd approach - first name:" + key + ", last name:" + value)
| true |
877fe8b28feadb49c4b071d9d1e26a3796f466cc | scresante/codeeval | /crackFreq.py2 | 1,676 | 4.21875 | 4 | #!/usr/bin/python
from sys import argv
try:
FILE = argv[1]
except NameError:
FILE = 'tests/121'
DATA = open(FILE, 'r').read().splitlines()
for line in DATA:
if not line:
continue
print line
inputText = line
#inputText = str(raw_input("Please enter the cipher text to be analysed:")).replace(" ", "")
##Input used to enter the cipher text. replace used to strip whitespace.
ngramDict = {}
highestValue = 0
def ngram(n):
#Function used to populate ngramDict with n-grams. The argument is the amount of characters per n-gram.
count = 0
for letter in inputText:
if str(inputText[count : count + n]) in ngramDict:
#Check if the current n-gram is in ngramDict
ngramDict[str(inputText[count : count + n])] = ngramDict[str(inputText[count : count + n])] + 1
#increments its value by 1
else:
ngramDict[str(inputText[count : count + n])] = 1
#Adds the n-gram and assigns it the value 1
count = count + 1
for bigram in ngramDict.keys():
#Iterates over the Bigram dict and removes any values which are less than the adaquate size (< n argument in function)
if len(bigram) < n:
del ngramDict[bigram]
ngram(int(raw_input("Please enter the n-gram value. (eg bigrams = 2 trigrams = 3)")))
ngramList = [ (v,k) for k,v in ngramDict.iteritems() ]
#iterates through the ngramDict. Swaps the keys and values and places them in a tuple which is in a list to be sorted.
ngramList.sort(reverse=True)
#Sorts the list by the value of the tuple
for v,k in ngramList:
#Iterates through the list and prints the ngram along with the amount of occurrences
print("There are " + str(v) + " " + str(k))
| true |
f0b5f940a37acd4ac16a5ab76b9331b57dec7c57 | kxhsing/dicts-word-count | /wordcount.py | 1,258 | 4.28125 | 4 | # put your code here.
#putting it all in one function
#will figure out if they can be broken later
def get_word_list(file_name):
"""Separates words and creates master list of all the words
Given a file of text, iterates through that file and puts all
the words into a list.
"""
#empty list to hold all the words in this file
all_the_words = []
#iterate through the file to get all the words
#and put them in the list
text = open(file_name)
for lines in text:
lines = lines.rstrip()
word = lines.split(" ")
#combine all words into one list
all_the_words.extend(word)
#make all lowercase
for i, word in enumerate(all_the_words):
all_the_words[i] = word.lower()
#removing punctuation
for i, word in enumerate(all_the_words):
if not word.isalpha():
all_the_words[i] = word[:-1]
#create an empty dictionary to hold the words
word_count = {}
#iterate though the list to count number of occurances
for word in all_the_words:
word_count[word] = word_count.get(word, 0) + 1
for word, count in word_count.iteritems():
print "%s %d" % (word, count)
get_word_list("test.txt")
#get_word_list("twain.txt")
| true |
93df2764f6fdcfb101521820aa3be80562e1bc47 | ottoguz/My-studies-in-Python | /aula005s.py | 816 | 4.125 | 4 | #Function that receives an integer via keyboard and determines the range(which should comprehend positive numbers)
def valid_int(question, min, max):
x = int(input(question))
if ((x < min) or (x > max)):
x = int(input(question))
return x
#Function to calculate the factorial of a given number
def factorial(num):
"""
:param num: number to be factored as a parameter
:return: returns the result of the factored number
"""
fat = 1
if num == 0:
return fat
for i in range(1, num + 1, 1):
fat *= i
return fat
# x = variable in which the function valid_int(question, min, max) is summoned
x = valid_int('Type in a factorial:', 0, 99999)
#result printed for the user
print('{}! = {}' .format(x, factorial(x)))
help(factorial)
| true |
5b928f4d9cfdd6bb4bcbca0500ffbdd6ac40c2c5 | NinjaCodes119/PythonBasics | /basics.py | 915 | 4.125 | 4 | student_grades = [9, 8, 7 ] #List Example
mySum = sum(student_grades)
length = len(student_grades)
mean = mySum / length
print("Average=",mean)
max_value = max(student_grades)
print("Max Value=",max_value)
print(student_grades.count(8))
#capitalize letter
text1 = "This Text should be in capital"
print(text1.upper())
#student grades using dictionary
student_grades2 = {"marry":9, "Sim": 8 ,"Gary":7}
mySum2 = sum (student_grades2.values()) #values is a method in dict
length2 = len (student_grades2)
mean2 = mySum2 / length2
print(mean2)
print (student_grades2.keys())
#Creating Tuple #Tuples are immutable, difference to list
#cannot use methods like using in list example list.remove()
#Tuples are faster than list
moday_temperatures = { 2,4,5}
print("monday teperatures are:",moday_temperatures)
#Creating List
#This line is edited Online
#this line is edited from PC github
#this line is from laptop Win | true |
0b1281fa76e4379219ec2637d53c94412547b52b | jemcghee3/ThinkPython | /05_14_exercise_2.py | 970 | 4.375 | 4 | """Exercise 2
Fermat’s Last Theorem says that there are no positive integers a, b, and c such that
an + bn = cn
for any values of n greater than 2.
Write a function named check_fermat that takes four parameters—a, b, c and n—and checks to see if Fermat’s theorem holds. If n is greater than 2 and
an + bn = cn
the program should print, “Holy smokes, Fermat was wrong!” Otherwise the program should print, “No, that doesn’t work.”
Write a function that prompts the user to input values for a, b, c and n, converts them to integers, and uses check_fermat to check whether they violate Fermat’s theorem."""
def check_fermat(a, b, c, n):
if n > 2 and a ** n + b ** n == c ** n:
print("Holy smokes, Fermat was wrong!")
else:
print("No, that doesn't work.")
a = int(input('Input "a": \n'))
b = int(input('Input "b": \n'))
c = int(input('Input "c": \n'))
n = int(input('Input "n": \n'))
check_fermat(a, b, c, n) | true |
32ebb0dcbf831f71f2e24e72f38fdb3cb7af8fc1 | jemcghee3/ThinkPython | /05_14_exercise_1.py | 792 | 4.25 | 4 | """Exercise 1
The time module provides a function, also named time, that returns the current Greenwich Mean Time in “the epoch”, which is an arbitrary time used as a reference point. On UNIX systems, the epoch is 1 January 1970.
Write a script that reads the current time and converts it to a time of day in hours, minutes, and seconds, plus the number of days since the epoch."""
import time
current_time = time.time()
days = int(current_time // (60 * 60 * 24))
remaining = current_time % (60 * 60 * 24)
hours = int(remaining // (60 * 60))
remaining = remaining % (60 * 60)
minutes = int(remaining // 60)
remaining = remaining % 60
seconds = int(remaining // 1)
print(f'The time of day is {hours}:{minutes}:{seconds}, and it has been {days} days since the beginning of the epoch.') | true |
4beaf5482d4fe8a76d30bb5548ae33192d33f19b | jemcghee3/ThinkPython | /09_02_exercise_4.py | 672 | 4.125 | 4 | """Exercise 4
Write a function named uses_only that takes a word and a string of letters,
and that returns True if the word contains only letters in the list.
Can you make a sentence using only the letters acefhlo? Other than “Hoe alfalfa”?"""
def letter_checker(c, letters):
for l in letters:
if c == l:
return True
return False
def uses_only(word, letters):
for c in word:
if letter_checker(c, letters) is False:
return False
return True
fin = open('words.txt')
allowed_letters = 'acefhlo'
for line in fin:
line = line.rstrip()
if uses_only(line, allowed_letters) is True:
print(line)
| true |
fa53edb7fa96c64310f584cd9d7af86b0cc9ec24 | jemcghee3/ThinkPython | /08_03_exercise_1.py | 255 | 4.25 | 4 | """As an exercise, write a function that takes a string as an argument and displays the letters backward,
one per line."""
def reverse(string):
l = len(string)
i = -1
while abs(i) <= l:
print(string[i])
i -= 1
reverse('test') | true |
2e55f9920fcf976b3027a7abf4bc175752fe2ec1 | jemcghee3/ThinkPython | /10_15_exercise_02.py | 682 | 4.28125 | 4 | """Exercise 2
Write a function called cumsum that takes a list of numbers and returns the cumulative sum;
that is, a new list where the ith element is the sum of the first i+1 elements from the original list. For example:
>>t = [1, 2, 3]
>>cumsum(t)
[1, 3, 6]
"""
def sum_so_far(input_list, n): # n is the number of items to sum, not position
total = 0
for i in range(n):
total += input_list[i]
return total
def cumsum(input_list):
sum_list = list()
for n in range(1, len(input_list)+1): # because n is the number of items to sum, not a position
sum_list.append(sum_so_far(input_list, n))
return sum_list
t = [1, 2, 3]
print(cumsum(t)) | true |
7d832e6a251f1d4a1abd229eb3ea409f76f2f164 | jemcghee3/ThinkPython | /08_13_exercise_5.py | 2,356 | 4.1875 | 4 | """Exercise 5
A Caesar cypher is a weak form of encryption that involves “rotating” each letter by a fixed number of places.
To rotate a letter means to shift it through the alphabet, wrapping around to the beginning if necessary,
so ’A’ rotated by 3 is ’D’ and ’Z’ rotated by 1 is ’A’.
To rotate a word, rotate each letter by the same amount.
For example, “cheer” rotated by 7 is “jolly” and “melon” rotated by -10 is “cubed”.
In the movie 2001: A Space Odyssey, the ship computer is called HAL, which is IBM rotated by -1.
Write a function called rotate_word that takes a string and an integer as parameters,
and returns a new string that contains the letters from the original string rotated by the given amount.
You might want to use the built-in function ord, which converts a character to a numeric code, and chr,
which converts numeric codes to characters. Letters of the alphabet are encoded in alphabetical order, so for example:
ord('c') - ord('a')
2
Because 'c' is the two-eth letter of the alphabet. But beware: the numeric codes for upper case letters are different.
Potentially offensive jokes on the Internet are sometimes encoded in ROT13, which is a Caesar cypher with rotation 13.
If you are not easily offended, find and decode some of them. Solution: http://thinkpython2.com/code/rotate.py."""
def rotate(num, n):
return num + n
def too_low(n):
return n + 26
def too_high(n):
return n - 26
def upper_wrap(n):
if n < 65:
return too_low(n)
elif n > 90:
return too_high(n)
else:
return n
def lower_wrap(n):
if n < 97:
return too_low(n)
elif n > 122:
return too_high(n)
else:
return n
def upper_caesar(num, n):
num = rotate(num, n)
num = upper_wrap(num)
return chr(num)
def lower_caesar(num, n):
num = rotate(num, n)
num = lower_wrap(num)
return chr(num)
def rotate_word(s, n):
new_word = ''
for c in s:
if c.isalpha() == False:
new_word += c
continue
num = ord(c)
if 65 <= num <= 90:
num = upper_caesar(num, n)
elif 97 <= num <= 122:
num = lower_caesar(num, n)
else:
print('something went wrong')
new_word += num
print(new_word)
rotate_word('IBM', -1) | true |
17df7ec92955ee72078b556e124938f1531f298a | jemcghee3/ThinkPython | /11_10_exercise_03.py | 1,535 | 4.5 | 4 | """Exercise 3 Memoize the Ackermann function from Exercise 2
and see if memoization makes it possible to evaluate the function with bigger arguments.
Hint: no. Solution: http://thinkpython2.com/code/ackermann_memo.py.
The Ackermann function, A(m, n), is defined:
A(m, n) =
n+1 if m = 0
A(m−1, 1) if m > 0 and n = 0
A(m−1, A(m, n−1)) if m > 0 and n > 0.
Here is the memoize code for Fibonacci sequence:
known = {0:0, 1:1}
def fibonacci(n):
if n in known:
return known[n]
res = fibonacci(n-1) + fibonacci(n-2)
known[n] = res
return res"""
known = {(0, 0): 1}
def memo_ackermann(t): # takes a tuple
if t in known:
return known[t]
# if len(t) != 2:
# return 'This function only works with tuples formatted (m, n).'
m, n = t
if m < 0 or n < 0 or type(m) != int or type(n) != int or type(t) != tuple:
return 'This function only works for tuples (m, n) where each is an integer greater than or equal to zero.'
if m == 0: # n+1 if m = 0
known[t] = n + 1
return n + 1
elif m > 0 and n == 0: # A(m−1, 1) if m > 0 and n = 0
t2 = (m - 1, 1)
res = memo_ackermann(t2)
known[t] = res
return res
elif m > 0 and n > 0: # A(m−1, A(m, n−1)) if m > 0 and n > 0
tn = (m, n-1)
n = memo_ackermann(tn)
t2 = (m - 1, n)
res = memo_ackermann(t2)
known[t] = res
return res
ans = memo_ackermann((3, 5))
print(ans)
# print(known) | true |
7e90113bc6bd97d3d3728d2527698e0e26b159a2 | shiva111993/python_exercises | /set_code.py | 2,213 | 4.1875 | 4 | # Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
# myset = {"apple", "ball", "cat", "dag", "elephate"}
# print(myset)
# myset.add("fan")
# print(myset)
# myset.add("apple")
# print(myset)
# ---------removing
# myset.remove("ball")
# print(myset)
# myset.discard("apple")
# print(myset)
# myset.pop()
# print(myset)
# myset.clear()
# print(myset)
# del myset
# print(myset)
# ------------------loop
# for x in myset:
# print(x)
# ------------------ adding & update
# myset2 = {"car", "bike", "cycle"}
# myset3 = {False, True, False, False, True}
# myset4 = {1, 2, 3, 4, 5}
# mylist = ["kiwi", "orange"]
# myset.update(myset2, myset3, myset4, mylist)
# print(myset)
# print("kiwi" in myset)
# ------------------ join set
# myset = {"a", "b", "c"}
# myset2 = {"a", "b", "c", "d"}
# myset3 = {1, 2, 3}
# myset3 = myset.union(myset2)
# print(myset3)
# --intersection and intersection_update
# set1 = {"apple","banana","carry"}
# set2 = {"google","microsoft","apple"}
# intersction
# set3 = set1.intersection(set2)
# print(set3)
# interction_update
# set1.intersection_update(set2)
# print(set1)
# --symmetric_difference_update() & symmetric_difference()
# method will keep only the elements that are NOT present in both sets.
# Keep All, But NOT the Duplicates
# set1 = {"apple","banana","carry"}
# set2 = {"google","microsoft","apple"}
# set1.symmetric_difference(set2) #it not work
# set3 = set1.symmetric_difference(set2)#o/p:-{'microsoft', 'banana', 'google', 'carry'}
# print(set3)
# set1.symmetric_difference_update(set2)
# print(set1)
# --issubset()
# set1= {"a","b","c"}
# set2 = {"f", "e", "d", "a","b","c"}
# set3 = set1.issubset(set2)
# print(set3)
# --issuperset()
# x = {"f", "e", "d", "c", "b", "a"}
# y = {"a", "b", "c"}
# z = x.issuperset(y)
# print(z)
# --isdisjoin()
# Return True if no items in set x is present in set y:
# x = {"apple", "banana", "cherry"}
# y = {"google", "microsoft", "facebook"}
# # -------------- or -------------
# x = {"apple", "banana", "cherry"}
# y = {"google", "microsoft", "apple"}
# z = x.isdisjoint(y)
# print(z)
| true |
6c463adbd86c53f3a17f58f960d6932134f29783 | emaustin/Change-Calculator | /Change-Calculator.py | 2,259 | 4.125 | 4 | def totalpaid(cost,paid):
#Checking to ensure that the values entered are numerical. Converts them to float numbers if so.
try:
cost = float(cost)
paid = float(paid)
#check to ensure the amount paid is greater than the cost
except:
print("Please enter in a number value.")
dollars = 0
quarters = 0
dimes = 0
nickels = 0
pennies = 0
#Finds the amount of change based on the amount paid subtracted from the total amount, rounded to two places
change = round(paid - cost,2)
#Uses the number preceding the decimal
dollars = int(change)
#subtracts the dollars from the total change to get the amount of cents remaining, rounded to two places
cents = round(change - dollars,2)
remaining_change = cents
#following sequence checks to see if there's enough change for each type of coin. If so, it subtracts from the running total
if cents/.25 >= 1:
quarters = int(cents/.25)
remaining_change = round(cents - (quarters*.25),2)
if remaining_change/.1 >= 1:
dimes = int(remaining_change/.1)
remaining_change = round(remaining_change - (dimes*.1),2)
if remaining_change/.05 >=1:
nickels = int(remaining_change/.05)
remaining_change = round(remaining_change - (nickels*.05),2)
if remaining_change/.01 >=1:
pennies = int(remaining_change/.01)
remaining_change = round(remaining_change - (pennies *.01),2)
print(f"The total was ${cost}. The customer paid ${paid}. \n\n Amount Due: \n Dollars: {dollars} \n Quarters: {quarters} \n Dimes: {dimes} \n Nickels: {nickels} \n Pennies: {pennies} ")
#
#Asks for cost and amount paid
#Removes leading dollar sign, if any, to convert input to float
#Runs totalpaid function to calculate change needed
#
item_cost = input("What did the item cost?")
if item_cost[0] == '$':
item_cost = item_cost.replace('$','')
item_cost = float(item_cost)
amount_paid = input("How much did the customer pay?")
if amount_paid[0] == '$':
amount_paid = amount_paid.replace('$','')
amount_paid = float(amount_paid)
totalpaid(item_cost,amount_paid)
| true |
cd736e4f096527ed9a012f7cb8e44b0c93f9d4df | eNobreg/holbertonschool-interview | /0x19-making_change/0-making_change.py | 523 | 4.40625 | 4 | #!/usr/bin/python3
"""
Module for making change function
"""
def makeChange(coins, total):
"""
Making change function
coins: List of coin values
total: Total coins to meet
Return: The lowest amount of coins to make total
or -1
"""
count = 0
if total <= 0:
return 0
coins = sorted(coins, reverse=True)
for coin in coins:
while total >= coin:
total -= coin
count += 1
if total > 0:
return -1
else:
return count
| true |
b9b329934dc1865548940c95d89b3d6a1052f4a5 | nikithapk/coding-tasks-masec | /fear-of-luck.py | 423 | 4.34375 | 4 | import datetime
def has_saturday_eight(month, year):
"""Function to check if 8th day of a given month and year is Friday
Args:
month: int, month number
year: int, year
Returns: Boolean
"""
return True if datetime.date(year, month, 8).weekday() == 5 else False
# Test cases
print(has_saturday_eight(5, 2021))
print(has_saturday_eight(9, 2017))
print(has_saturday_eight(1, 1985))
| true |
58cdadc4d72f1a81b55e16f0a4067b44ae937f37 | rcolistete/Plots_MicroPython_Microbit | /plot_bars.py | 609 | 4.125 | 4 | # Show up to 5 vertical bars from left to right using the components of a vector (list or tuple)
# Each vertical bar starts from bottom of display
# Each component of the vector should be >= 0, pixelscale is the value of each pixel with 1 as default value.
# E. g., vector = (1,2,3,4,5) will show 5 verticals bars, with 1, 2, 3, 4 and 5 leds on.
def plot_bars(vector, pixelscale = 1):
for i in range(len(vector)):
for y in range(5):
if vector[i] - (y + 1)*pixelscale >= 0:
display.set_pixel(i, 4 - y, 9)
else:
display.set_pixel(i, 4 - y, 0) | true |
d8301e71e2d210a4303273f2f875514bd4a6aff0 | mansi05041/Computer_system_architecture | /decimal_to_any_radix.py | 910 | 4.15625 | 4 | #function of converting 10 to any radix
def decimal_convert_radix(num,b):
temp=[]
while (num!=0):
rem=num%b
num=num//b
temp.append(rem)
result=temp[::-1]
return result
def main():
num=int(input("Enter the decimal number:"))
radix=int(input("enter the base to be converted:"))
result=decimal_convert_radix(num,radix)
#creating dictonary for the values greater than 9
alphabet={}
val=10
for i in list(map(chr, range(97, 123))):
key=i.upper()
value=val
val=val+1
alphabet[key]=value
print(num,' of base',10,' into base',radix,' is:',end="")
for i in result:
if i>9:
i=list(alphabet.keys())[list(alphabet.values()).index(i)] #replacing the values starting from 10
print(i,end="")
#calling main function
if __name__ == "__main__":
main()
| true |
0a6ce06157bd0fb4e30e2c98a8327f5b98f14682 | zija1504/100daysofCode | /5.0 rock paper scissors/game.py | 2,843 | 4.3125 | 4 | #!/usr/bin/python3
# Text Game rock, paper, scissors to understand classes
import random
class Player:
"""name of player"""
def __init__(self, name):
self.name = name
self.pkts = 0
def player_battle(self, pkt):
self.pkts += pkt
class Roll:
"""rolls in game"""
def __init__(self, name, winning, losing):
self.name = name
self.winning = winning
self.losing = losing
def can_defeat(self, another_roll):
"""function that check what roll wins battle"""
if self.winning == another_roll:
return 1
elif self.name == another_roll:
return 0
elif self.losing == another_roll:
return -1
def build_rolls():
Rock = Roll('rock', 'scissors', 'paper')
Scissors = Roll('scissors', 'paper', 'rock')
Paper = Roll('paper', 'rock', 'scissors')
return [Rock, Scissors, Paper]
def header():
"""simple header"""
print('---------------------')
print('---Welcome in Game---')
print('Rock, Paper, Scissors')
def get_player_name():
"""ask for name of player"""
name = input('Whats your name? ')
print(f'Welcome in game {name}')
return name
def game_loop(Player1, Player2, rolls):
"""playing up to 3, or -3"""
end_of_game = 0
while not end_of_game:
player2_roll = rolls[random.randint(0, 2)]
print(
f'Choose roll: 1:{rolls[0].name} 2:{rolls[1].name} 3:{rolls[2].name}'
)
choice = input(">>>")
if int(choice) in (1, 2, 3):
player1_roll = rolls[int(choice) - 1]
print(
f'Player {Player1.name} choose {player1_roll.name}, Player {Player2.name} choose {player2_roll.name}'
)
part = player1_roll.can_defeat(player2_roll.name)
if part == 1:
Player1.player_battle(1)
print(
f'This round win Player {Player1.name} and has {Player1.pkts} point/points'
)
elif part == -1:
Player2.player_battle(1)
print(
f'This round win Player {Player2.name} and has {Player2.pkts} point/points'
)
elif part == 0:
print(f'Draw in this round.')
if Player1.pkts == 3:
print(f'End of game, won Player {Player1.name}')
end_of_game = 1
elif Player2.pkts == 3:
print(f'End of game, won Player {Player2.name}')
end_of_game = 1
def main():
"""main function of program"""
header()
player_name = get_player_name()
Player1 = Player(player_name)
Player2 = Player('computer')
rolls = build_rolls()
game_loop(Player1, Player2, rolls)
if __name__ == '__main__':
main()
| true |
f524472f1125b5d55bd1af74de6c5e0ba81c9f54 | hiteshkrypton/Python-Programs | /sakshi1.py | 310 | 4.25 | 4 |
def factorial(n):
if n == 1:
return n
else:
return n * factorial(n - 1)
n = int(input("Enter a Number: "))
if n < 0:
print("Factorial cannot be found for negative numbers")
elif n == 0:
print("Factorial of 0 is 1")
else:
print("Factorial of", n, "is: ", factorial(n))
| true |
dfb693bb8093a5f86513a6cd0b565d5c1d0c2809 | sachinsaurabh04/pythonpract | /Function/function1.py | 544 | 4.15625 | 4 | #!/usr/bin/python3
# Function definition is here
def printme( str ):
#"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme("This is first call to the user defined function!")
printme("Again second call to the same function")
printme("hello sachin, this is 3rd call of the function")
printme(2+3)
printme("sachin")
#Output:
#This is first call to the user defined function!
#Again second call to the same function
#hello sachin, this is 3rd call of the function
#5
#sachin | true |
70b59046590e09cf64be5d6c6d210893ab3d7bfc | sachinsaurabh04/pythonpract | /Function/funtion7.py | 1,115 | 4.3125 | 4 | #keyword Argument
#This allows you to skip arguments or place them out of order because the Python
#interpreter is able to use the keywords provided to match the values with parameters. You
#can also make keyword calls to the printme() function in the following ways-
#Order of the parameters does not matter
#!/usr/bin/python3
#Function definition is here
def printinfo(name,age):
print("NAME: ",name)
print("AGE: ", age)
return
def calculation():
age=int(input("Please enter the age: "))
if (age>60):
print("You are 60+")
name=input("Please enter the name: ")
print("***Nice Name****")
print("\nWhat I got from you is: ")
printinfo(name, age)
return()
calculation()
print("\nWould you like to edit or save? Press 1 for Edit or 2 for Save: ")
res = int(input())
while (res==1):
calculation()
print("\nWould you like to edit or save? Press 1 for Edit or 2 for Save: ")
res = int(input())
if res==2:
print("\nWe have SAVED your details. Thank you.")
print("***Good bye***")
else:
print("you have not selected the right choice. Good Bye.") | true |
1ced156b8bad36c94f49d1c51483611eba47754d | Deepomatic/challenge | /ai.py | 2,709 | 4.125 | 4 | import random
def allowed_moves(board, color):
"""
This is the first function you need to implement.
Arguments:
- board: The content of the board, represented as a list of strings.
The length of strings are the same as the length of the list,
which represents a 8x8 checkers board.
Each string is a row, from the top row (the black side) to the
bottom row (white side). The string are made of five possible
characters:
- '_' : an empty square
- 'b' : a square with a black disc
- 'B' : a square with a black king
- 'w' : a square with a white disc
- 'W' : a square with a white king
At the beginning of the game:
- the top left square of a board is always empty
- the square on it right always contains a black disc
- color: the next player's color. It can be either 'b' for black or 'w'
for white.
Return value:
It must return a list of all the valid moves. Please refer to the
README for a description of what are valid moves. A move is a list of
all the squares visited by a disc or a king, from its initial position
to its final position. The coordinates of the square must be specified
using (row, column), with both 'row' and 'column' starting from 0 at
the top left corner of the board (black side).
Example:
>> board = [
'________',
'__b_____',
'_w_w____',
'________',
'_w______',
'_____b__',
'____w___',
'___w____'
]
The top-most black disc can chain two jumps and eat both left white
discs or jump only over the right white disc. The other black disc
cannot move because it does produces any capturing move.
The output must thus be:
>> allowed_moves(board, 'b')
[
[(1, 2), (3, 0), (5, 2)],
[(1, 2), (3, 4)]
]
"""
# TODO: Your turn now !
return []
def play(board, color):
"""
Play must return the next move to play.
You can define here any strategy you would find suitable.
"""
return random_play(board, color)
def random_play(board, color):
"""
An example of play function based on allowed_moves.
"""
moves = allowed_moves(board, color)
# There will always be an allowed move
# because otherwise the game is over and
# 'play' would not be called by main.py
return random.choice(moves)
| true |
5e1e2e536787176e984cd8c7ad63169371361fb9 | anokhramesh/Calculate-Area-Diameter-and-Circumference | /calculate_area_diametre_Circumference_of_a_circle.py | 466 | 4.5625 | 5 | print("A program for calculate the Area,Diameter and Circumference of a circle if Radius is known")
print("******************************************************************************************")
while True:
pi = 3.14
r = float(input("\nEnter the Radius\n"))
a = float(pi*r)*r
d = (2*r)
c = float(2*pi*r)
print ("The Area of Circle is",a)
print ("The Diameter of Circle is ",d)
print ("The Circumference of Circle is",c) | true |
b0f171588a69286bc1aaba953e45b712a23ffb66 | ggrossvi/core-problem-set-recursion | /part-1.py | 1,130 | 4.3125 | 4 | # There are comments with the names of
# the required functions to build.
# Please paste your solution underneath
# the appropriate comment.
# factorial
def factorial(num):
# base case
if num < 0:
raise ValueError("num is less than 0")
elif num == 0:
# print("num is 0")
return 1
# print(num - 1)
#recursive
return factorial(num -1) * num
# reverse
def factorial(num):
# base case
if num < 0:
raise ValueError("num is less than 0")
elif num == 0:
# print("num is 0")
return 1
# print(num - 1)
#recursive
return factorial(num -1) * num
# bunny
def bunny(count):
#base case
if count == 0:
return 0
if count == 1:
return 2
#recursive
return bunny(count-1) + 2
# is_nested_parens
def is_nested_parens(parens):
#base cases - stopping condition
if parens == "":
return True
if parens[0] != "(":
return False
if parens[-1] != ")":
return False
#recursion
return True and is_nested_parens(parens[1:-1])
| true |
1be9a89c5edc52c684a62dcefcdd417a418ef797 | aayishaa/aayisha | /factorialss.py | 213 | 4.1875 | 4 |
no=int(input())
factorial = 1
if no < 0:
print("Factorrial does not exist for negative numbers")
elif no== 0:
print("1")
else:
for i in range(1,no+ 1):
factorial = factorial*i
print(factorial)
| true |
557db6014ade0a2fc318b675bdc3fbf6aa9b3d30 | JonasJR/zacco | /task-1.py | 311 | 4.15625 | 4 | str = "Hello, My name is Jonas"
def reverseString(word):
#Lets try this without using the easy methods like
#word[::-1]
#"".join(reversed(word))
reversed = []
i = len(word)
while i:
i -= 1
reversed.append(word[i])
return "".join(reversed)
print reverseString(str)
| true |
e1cdeb27240a29c721298c5e69193576da556861 | brunacorreia/100-days-of-python | /Day 1/finalproject-band-generator.py | 565 | 4.5 | 4 | # Concatenating variables and strings to create a Band Name
#1. Create a greeting for your program.
name = input("Hello, welcome to the Band Generator! Please, inform us your name.\n")
#2. Ask the user for the city that they grew up in.
city = input("Nice to meet you, " + name + "! Now please, tell us the city you grew up in.\n")
#3. Ask the user for the name of a pet.
pet = input("What's your pet's name?\n")
#4. Combine the name of their city and pet and show them their band name.
result = input("Cool! Your band name should be " + city + " " + pet + ".") | true |
557e4d43a305b7ddcfe16e6151d7523468417278 | axxypatel/Project_Euler | /stack_implementation_using_python_list.py | 1,550 | 4.4375 | 4 | # Implement stack data structure using list collection of python language
class Stack:
def __init__(self):
self.item_list = []
def push(self, item):
self.item_list.append(item)
def pop(self):
self.item_list.pop()
def isempty(self):
return self.item_list == []
def peek(self):
return self.item_list[len(self.item_list)-1]
def size(self):
return len(self.item_list)
def test_stack_class():
sample_object = Stack()
sample_object.push(4)
sample_object.push('dog')
sample_object.push(4.7777)
print("Added the value:", sample_object.item_list)
sample_object.pop()
print("Remove the top value:", sample_object.item_list)
print("Show the top value:", sample_object.peek())
print("Size the stack:", sample_object.size())
if sample_object.isempty():
print("Stack is empty")
else:
print("Stack is not empty")
def check_balanced_parentheses(parentheses_string):
test_object = Stack()
string_len = len(parentheses_string)
status = True
for temp in range(0, string_len):
temp_char = parentheses_string[temp]
if temp_char == "(":
test_object.push(temp_char)
else:
if test_object.isempty():
status = False
else:
test_object.pop()
if test_object.isempty() and status:
return True
else:
return False
print(check_balanced_parentheses('((()))'))
print(check_balanced_parentheses('(()))'))
| true |
20bdc091aa5936ed6cfbcec4f285e9337f6040c2 | arkharman12/oop_rectangle | /ooprectangle.py | 2,518 | 4.34375 | 4 | class Size(object): #creating a class name Size and extending it from object
def __init__(self, width=0, height=0): #basically it inherts whatever is defined in object
self.__width = width #object is more than an simple argument
self.__height = height
def setWidth(self, width):
self.__width = width
#defining setters and getters functions for
def getWidth(self): #width and Height and returning the value
return self.__width #to use it later
def setHeight(self, height):
self.__height = height
def getHeight(self):
return self.__height
width = property(fset = setWidth, fget = getWidth)
height = property(fset = setHeight, fget = getHeight)
class Rectangle(Size): #creating a class name Rectangle with a single argument
def __init__(self, width=0, height=0): #of Size that way I can use the value of Size in this new class
Size.__init__(self, width, height)
def getArea(self):
return self.width * self.height #area of a rectangle is width * height
def setArea(self, area):
print("Area is something that cannot be set using a setter.")
def getPerimeter(self):
return 2 * (self.width + self.height) #perimeter of a rectangle is 2 * (width + height)
def setPerimeter(self, area):
print("Perimeter is something that cannot be set using a setter.")
area = property(fget = getArea, fset = setArea)
perimeter = property(fget = getPerimeter, fset = setPerimeter)
def getStats(self):
print("width: {}".format(self.width))
print("height {}".format(self.height)) #defining a new function getStats with self
print("area: {}".format(self.area)) #and printing the values for width, height,
print("perimeter: {}".format(self.perimeter)) #perimeter and area
def main():
print ("Rectangle a:")
a = Rectangle(5, 7)
print ("area: {}".format(a.area))
print ("perimeter: {}".format(a.perimeter)) #the whole main function was given to us
print ("")
print ("Rectangle b:")
b = Rectangle()
b.width = 10
b.height = 20
print (b.getStats())
main()
| true |
6ba40eec4a91f64bb1675e456566f2018de3c835 | f73162818/270201070 | /lab7/ex2.py | 322 | 4.125 | 4 | def is_prime(a):
if a <= 1:
return False
for i in range(2,a):
if a%i == 0:
return False
return True
def print_primes_between(a,b):
for i in range(a,b):
if is_prime(i):
print(i)
a = int(input("Enter a number:"))
b = int(input("Enter another number:"))
print_primes_between(a,b)
| true |
b68fa443c48907700332320459f7583e1d288f8a | Ealtunlu/GlobalAIHubPythonCourse | /Homeworks/day_5.py | 1,358 | 4.3125 | 4 | # Create three classes named Animals, Dogs and Cats Add some features to these
# classes Create some functions with these attributes. Don't forget! You have to do it using inheritance.
class Animal:
def __init__(self,name,age):
self.name = name
self.age = age
def is_mammel(self):
return None
class Dogs(Animal):
def __init__(self,name,age):
super().__init__(name,age)
def speak(self):
return "Woof"
def likes_walks(self):
return True
def is_good_boy(self):
return True
def is_mammel(self):
return True
class Cats(Animal):
def __init__(self,name,age):
super().__init__(name,age)
def speak(self):
return "Meow!"
def likes_sleeping(self):
return True
def is_mammel(self):
return True
cliffard = Dogs("Cliffard",3)
leo = Cats("Leo",2)
print("*"*50)
print(f"Name is {cliffard.name} , Age is {cliffard.age}")
print(f"Cliffard says {cliffard.speak()}")
print(f"Cliffard likes walks : {cliffard.likes_walks()}")
print(f"Cliffard is a Mammel : {cliffard.is_mammel()}")
print("*"*50)
print(f"Name is {leo.name} , Age is {leo.age}")
print(f"Leo says {leo.speak()}")
print(f"Leo likes sleeping : {leo.likes_sleeping()}")
print(f"Leo is a Mammel : {leo.is_mammel()}")
print("*"*50) | true |
b5fd6cb27a327d0cede09f3eb7dbf5d6569cc63d | roselandroche/cs-module-project-recursive-sorting | /src/sorting/sorting.py | 1,182 | 4.28125 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge(arrA, arrB):
# Your code here
merged_arr = []
x = y = 0
while x < len(arrA) and y < len(arrB):
if arrA[x] < arrB[y]:
merged_arr.append(arrA[x])
x += 1
else:
merged_arr.append(arrB[y])
y += 1
merged_arr.extend(arrA[x:])
merged_arr.extend(arrB[y:])
return merged_arr
# TO-DO: implement the Merge Sort function below recursively
def merge_sort(arr):
# Your code here
if len(arr) <= 1:
return arr
midpoint = len(arr) // 2
lhs = merge_sort(arr[:midpoint])
rhs = merge_sort(arr[midpoint:])
return merge(lhs, rhs)
# STRETCH: implement the recursive logic for merge sort in a way that doesn't
# utilize any extra memory
# In other words, your implementation should not allocate any additional lists
# or data structures; it can only re-use the memory it was given as input
# def merge_in_place(arr, start, mid, end):
# Your code here
# def merge_sort_in_place(arr, l, r):
# Your code here
arr1 = [1, 5, 8, 4, 2, 9, 6, 0, 3, 7]
print(arr1)
print(merge_sort(arr1)) | true |
4a8c2ad2eafe2cefe78c0ccd5750f097671c7075 | GermanSumus/Algorithms | /unique_lists.py | 651 | 4.3125 | 4 | """
Write a function that takes two or more arrays and returns a new array of
unique values in the order of the original provided arrays.
In other words, all values present from all arrays should be included in their
original order, but with no duplicates in the final array.
The unique numbers should be sorted by their original order, but the final
array should not be sorted in numerical order.
"""
def unique_list(a_list, b_list):
for num in a_list:
if num in b_list:
b_list.remove(num)
concat = a_list + b_list
print(concat)
unique_list([1,2,3], [1,2,3,4,5])
unique_list([1,1,7,5], [3,9,4,5])
| true |
b7ac1cfbb9087510ade29a2d2605b8cc01345d1f | GermanSumus/Algorithms | /factorialize.py | 268 | 4.21875 | 4 | # Return the factorial of the provided integer
# Example: 5 returns 1 * 2 * 3 * 4 * 5 = 120
def factorialize(num):
factor = 1
for x in range(1, num + 1):
factor = factor * x
print(factor)
factorialize(5)
factorialize(10)
factorialize(25)
| true |
8f076f012de7d9e71daff7736fc562eff99078aa | kartikay89/Python-Coding_challenges | /countLetter.py | 1,042 | 4.5 | 4 | """
Write a function called count_letters(text, letter), which receives as arguments a text (string) and
a letter (string), and returns the number of occurrences of the given letter (count both capital and
small letters!) in the given string. For example, count_letters('trAvelingprogrammer', 'a') should return 2
and count_letters('trAvelingprogrammer', 'A') should return also 2. If you are quite advanced,
use Regular Expressions or Lambda function here :)
"""
def count_letters(text, letter):
newText = text.lower()
result = 0
for letts in newText:
if letter in letts:
result +=1
return result
print(count_letters("Kartikay", "k"))
"""
import testyourcode
# one possibility
def count_letters(text, letter):
return text.lower().count(letter.lower())
# another possibility
import re
def count_letters2(text, letter):
return len(re.findall(letter.lower(), text.lower()))
# another possibility
def count_letters3(text, letter):
return sum(map(lambda x : 1 if letter.lower() in x else 0, text.lower()))
""" | true |
7c54349a4f78cefb44bff8616fc370b865849d48 | kartikay89/Python-Coding_challenges | /phoneNum.py | 1,223 | 4.53125 | 5 | """
Imagine you met a very good looking guy/girl and managed to get his/her phone number. The phone number has 9 digits but, unfortunately, one of the digits is missing since you were very nervous while writing it down.
The only thing you remember is that the SUM of all 9 digits was divisible by 10 - your crush was nerdy and that's one of the things you talked about.. :) Write a function called find_missing_digit(pseudo_number) that
takes as input a phone number made out of 8 digits and one 'x' (it is a string, for example '0123x1234') and returns the missing digit (as int).
"""
pseudoNumber = '0123x1234'
probNumbers = []
def divisibleFunction(sumlist):
if sumlist % 10 == 0:
print('True')
return probNumbers.append(sumlist)
def find_missing_digit(pseudo_number):
replacementNum = list(pseudo_number.replace('x', '4'))
# print(replacementNum)
intNums = list(map(int, replacementNum))
# print(intNums)
sums = sum(intNums)
# print(sums)
divisibleFunction(sums)
find_missing_digit(pseudoNumber)
print(probNumbers)
"""
def find_missing_digit(pseudo_number):
digits_sum = sum([int(i) for i in pseudo_number if i!='x'])
for i in range(10):
if (digits_sum+i)%10==0:
return i
"""
| true |
c3bd11215bb589aa0940cf92e249d2dd8815b8e8 | ravenawk/pcc_exercises | /chapter_07/deli.py | 413 | 4.28125 | 4 | #!/usr/bin/env python3
'''
Making sandwiches with while loops and for loops
'''
sandwich_orders = ['turkey', 'tuna', 'ham']
finished_sandwiches = []
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
finished_sandwiches.append(current_sandwich)
print(f"I made your {current_sandwich} sandwich.")
for sandwich in finished_sandwiches:
print(f"A {sandwich} sandwich was made today.")
| true |
b0ee2dc3c3865353f42b2b18c45e0a8b77c7c7bc | ravenawk/pcc_exercises | /chapter_04/slices.py | 326 | 4.25 | 4 | #!/usr/bin/env python3
list_of_cubes = [ value**3 for value in range(1,11)]
for cube in list_of_cubes:
print(cube)
print(f"The first 3 items in the list are {list_of_cubes[:3]}.")
print(f"Three items in the middle of the list are {list_of_cubes[3:6]}.")
print(f"The last 3 items in the list are {list_of_cubes[-3:]}.")
| true |
f87fbc9f1ad08e89dd1fd5e561bf0956f01b2a6e | ravenawk/pcc_exercises | /chapter_07/dream_vacation.py | 381 | 4.21875 | 4 | #!/usr/bin/env python3
'''
Polling for a dream vacation
'''
places_to_visit = []
poll = input("Where would you like to visit some day? ")
while poll != 'quit':
places_to_visit.append(poll)
poll = input("Where would you like to visit one day? (Enter quit to end) ")
for place in places_to_visit:
print(f"{place.title()} is one of the places people wanted to visit.")
| true |
b102953b0aaef366c4056dfb9b94210c416b7512 | ravenawk/pcc_exercises | /chapter_08/user_albums.py | 514 | 4.34375 | 4 | #!/usr/bin/env python3
'''
Function example of record album
'''
def make_album(artist_name, album_title, song_count=None):
''' Create album information '''
album = {'artist': artist_name, 'album name': album_title,}
if song_count:
album['number of songs'] = song_count
return album
while True:
ARTIST = input("What is the artis's name? (enter quit to exit) ")
if ARTIST == 'quit':
break
ALBUM = input("What is the album's name? ")
print(make_album(ARTIST, ALBUM))
| true |
12c1a2d3672a7f0c7d391e958e8a047ff3893106 | joesprogramming/School-and-Practice | /Calculate Factorial of a Number CH 4 pgm 10.py | 281 | 4.25 | 4 | # Joe Joseph
# intro to programming
# Ask user for a number
fact = int(input('Enter a number and this program will calculates its Factorial: ',))
# define formula
num = 1
t = 1
#run loop
while t <= fact:
num = num * t
t = t + 1
print(num)
| true |
6a159a65ea848c61eb4b35980b2bd524a5487b56 | BzhangURU/LeetCode-Python-Solutions | /T522_Longest_Uncommon_Subsequence_II.py | 2,209 | 4.125 | 4 | ##Given a list of strings, you need to find the longest uncommon subsequence among them. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.
##
##A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.
##
##The input will be a list of strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1.
##
##Example 1:
##Input: "aba", "cdc", "eae"
##Output: 3
##Note:
##
##All the given strings' lengths will not exceed 10.
##The length of the given list will be in the range of [2, 50].
##My comments: if subsequence of string a is LUS, then a must be LUS. So we
## sort strings, and find the longest LUS. ##def findLUSlength(strs: List[str]) -> int:
import functools
class Solution:
def cmpStr(self, a, b):
if len(a)!=len(b):
return len(b)-len(a)
else:
for i in range(len(a)):
if a[i]!=b[i]:
return ord(a[i])-ord(b[i])
return 0
def isSubsequence(self, a, b):
if len(a)>len(b):
return False
else:
j=0
for i in range(len(a)):
while a[i]!=b[j]:
j=j+1
if j>=len(b) or len(a)-i>len(b)-j:
return False
j=j+1
return True
#Check if string a is subsequence of b
def findLUSlength(self, strs: List[str]) -> int:
strs2=sorted(strs, key=functools.cmp_to_key(self.cmpStr))
for i in range(len(strs2)):
isLUS=True
if i<len(strs2)-1:
if strs2[i]==strs2[i+1]:
continue
for j in range(i):
if self.isSubsequence(strs2[i], strs2[j]):
isLUS=False
break
if isLUS:
return len(strs2[i])
return -1
| true |
79d8085cb879c116c4092396ecc83fa1b7f2b5d2 | SanaaShah/Python-Mini-Assignments | /6__VolumeOfSphere.py | 290 | 4.5625 | 5 | # 6. Write a Python program to get the volume of a sphere, please take the radius as input from user. V=4 / 3 πr3
from math import pi
radius = input('Please enter the radius: ')
volume = 4 / (4 * pi * 3 * radius**3)
print('Volume of the sphere is found to be: '+str(round(volume, 2)))
| true |
4ac590cb424a5d27fc41ccfe671b7c42db027139 | SanaaShah/Python-Mini-Assignments | /30__OccurenceOfLetter.py | 331 | 4.21875 | 4 | # 30. Write a Python program to count the number occurrence of a specific character in a string
string = input('Enter any word: ')
word = input('Enter the character that you want to count in that word: ')
lenght = len(string)
count = 0
for i in range(lenght):
if string[i] == word:
count = count + 1
print(count) | true |
53577eb885ed53f2ba4c0d09fa7a0262ff6fdb2f | SanaaShah/Python-Mini-Assignments | /2__checkPositive_negative.py | 350 | 4.4375 | 4 | # 2. Write a Python program to check if a number is positive, negative or zero
user_input = float(input('Please enter any number: '))
if user_input < 0:
print('Entered number is negative.')
elif user_input > 0:
print('Entered number is positive')
elif user_input == 0:
print('You have entered zero, its neither negative nor positive')
| true |
f81383ec7b0b8be08c8c40ec057866c6b4383879 | SanaaShah/Python-Mini-Assignments | /1__RadiusOfCircle.py | 299 | 4.53125 | 5 | # 1. Write a Python program which accepts the radius of a circle from the user and compute the area
from math import pi
radius = float((input('Please enter the radius of the cricle: ')))
print('Area of the circle of radius: '+str(radius) + ' is found to be: '+str(round((pi * radius**2), 2)))
| true |
06827bf14302ec76a9b9d64a66273db96e3746fa | duplys/duplys.github.io | /_src/recursion/is_even.py | 557 | 4.59375 | 5 | """Example for recursion."""
def is_even(n, even):
"""Uses recursion to compute whether the given number n is even.
To determine whether a positive whole number is even or odd,
the following can be used:
* Zero is even
* One is odd
* For any other number n, its evenness is the same as n-2
"""
if n == 0:
even = True
elif n == 1:
even = False
else:
even = is_even(n-2, even)
return even
for i in range(1,20):
val = None
print("[*] Is {0} even? {1}".format(i, is_even(i, val))) | true |
c3a181aea806b68ce09197560eeb485ca6d8419d | jamesb97/CS4720FinalProject | /FinalProject/open_weather.py | 1,535 | 4.25 | 4 | '''
Python script which gets the current weather data for a particular zip code
and prints out some data in the table.
REST API get weather data which returns the Name, Current Temperature,
Atmospheric Pressure, Wind Speed, Wind Direction, Time of Report.
'''
import requests
#Enter the corresponding api key from openweather
API_key = ""
base_url = "http://api.openweathermap.org/data/2.5/weather?"
#User is prompted to enter the city name or zip code
city_name = input('Enter City Name: ')
#Instantiate corresponding url from openweather_api
Final_url = base_url + "appid=" + API_key + "&q=" + city_name
weather_data = requests.get(Final_url).json()
#Get input for current temperature
temp = weather_data['main']['temp']
#Get input for the current pressure
pressure = weather_data['main']['pressure']
#Get input for wind speed
wind_speed = weather_data['wind']['speed']
#Get input for wind direction
wind_direction = weather_data['wind']['deg']
#Get input for the current weather description
description = weather_data['weather'][0]['description']
#Print the data to the console
print('\nCurrent Temperature: ', temp, "K")
print('\nAtmospheric Pressure: ', pressure, "hpa")
print('\nWind Speed: ', wind_speed, "m/h")
print('\nWind Direction: ', wind_direction)
print('\nDescription: ', description)
#Import Date and Time module for displaying the current time report.
import datetime
now=datetime.datetime.now()
print("\nTime of Report: ")
print(now.strftime('%Y-%m-%d %H:%M:%S'))
| true |
18200cb8e9e584fe454d57f3436a9184159388b8 | ayoubabounakif/edX-Python | /ifelifelse_test1_celsius_to_fahrenheit.py | 811 | 4.40625 | 4 | #Write a program to:
#Get an input temperature in Celsius
#Convert it to Fahrenheit
#Print the temperature in Fahrenheit
#If it is below 32 degrees print "It is freezing"
#If it is between 32 and 50 degrees print "It is chilly"
#If it is between 50 and 90 degrees print " It is OK"
#If it is above 90 degrees print "It is hot"
# Code Starts Here
user_input = input("Please input a temperature in Celsius:")
celsius = float(user_input)
fahrenheit = ((celsius * 9) / 5 ) +32
print ("The temperature is ",fahrenheit, "degrees Fahrenheit")
if fahrenheit < 32:
print ("It is freezing")
elif 32 <= fahrenheit <= 50:
print ("It is chilly")
elif 50 < fahrenheit < 90:
print ("It is OK")
elif fahrenheit >= 90:
print ("It is hot")
| true |
b9804e7911242e9c4eae1074e8ef2949155d60e0 | ayoubabounakif/edX-Python | /sorting.py | 515 | 4.125 | 4 | # Lets sort the following list by the first item in each sub-list.
my_list = [[2, 4], [0, 13], [11, 14], [-14, 12], [100, 3]]
# First, we need to define a function that specifies what we would like our items sorted by
def my_key(item):
return item[0] # Make the first item in each sub-list our key
new_sorted_list = sorted(my_list, key=my_key) # Return a sorted list as specified by our key
print("The sorted list looks like:", new_sorted_list)
| true |
f3019b4227dfd2a758d0585fb1c2f9e27df1b8e9 | ayoubabounakif/edX-Python | /quizz_1.py | 275 | 4.28125 | 4 | #a program that asks the user for an integer 'x'
#and prints the value of y after evaluating the following expression:
#y = x^2 - 12x + 11
import math
ask_user = input("Please enter an integer x:")
x = int(ask_user)
y = math.pow(x,2) - 12*x + 11
print(int(y))
| true |
7013c99a792f116a7b79f4ad1a60bfb3f4b1a8a2 | ayoubabounakif/edX-Python | /quizz_2_program4.py | 1,141 | 4.34375 | 4 | #Write a program that asks the user to enter a positive integer n.
#Assuming that this integer is in seconds,
#your program should convert the number of seconds into days, hours, minutes, and seconds
#and prints them exactly in the format specified below.
#Here are a few sample runs of what your program is supposed to do:
#when user enters : ---> 369121517
#your program should print:
# 4272 days 5 hours 45 minutes 17 seconds
#when user enters : ---> 24680
#your program should print:
# 0 days 6 hours 51 minutes 20 seconds
#when user enters : ---> 129600
#your program shoudl print:
# 1 days 12 hours 0 minutes 0 seconds
# CODE
#1 minute = 60 seconds
#1 hours = 60 * 60 = 3600 seconds
#1 day = 60 * 60 * 24 = 86400 seconds
sec = int(input("Enter the number of seconds:"))
time = int(sec)
days = time // 86400
hours = (time - (days * 86400)) // 3600
minuts = (time - ((days * 86400) + (hours * 3600)) ) // 60
seconds = (time - ((days * 86400) + (hours * 3600) + (minuts * 60)))
print (days, 'days' ,hours,'hours',minuts, 'minutes',seconds,'seconds')
| true |
940e284ec16e99a3349d00e0611e487cdce976f1 | ayoubabounakif/edX-Python | /quizz_3_part3.py | 397 | 4.1875 | 4 | # Function that returns the sum of all the odd numbers in a list given.
# If there are no odd numbers in the list, your function should return 0 as the sum.
# CODE
def sumOfOddNumbers(numbers_list):
total = 0
count = 0
for number in numbers_list:
if (number % 2 == 1):
total += number
if (number == count):
return (0)
return total
| true |
9774dac844cb3985d733af0c87e697b85f93be88 | ayoubabounakif/edX-Python | /for_loop_ex2.py | 296 | 4.3125 | 4 | #program which asks the user to type an integer n
#and then prints the sum of all numbers from 1 to n (including both 1 and n).
# CODE
ask_user = input("Type an integer n:")
n = int(ask_user)
i = 1
sum = 0
for i in range(1, n+1):
sum = sum + i
print (sum)
| true |
69b29ccaa611a0e92df5f8cd9b3c59c231847b72 | fingerman/python_fundamentals | /python-fundamentals/4.1_dict_key_value.py | 1,032 | 4.25 | 4 | '''
01. Key-Key Value-Value
Write a program, which searches for a key and value inside of several key-value pairs.
Input
• On the first line, you will receive a key.
• On the second line, you will receive a value.
• On the third line, you will receive N.
• On the next N lines, you will receive strings in the following format:
“key => {value 1};{value 2};…{value X}”
After you receive N key -> values pairs, your task is to go through them
and print only the keys, which contain the key and the values, which contain the value.
Print them in the following format:
{key}:
-{value1}
-{value2}
…
-{valueN}
Examples
Input:
bug
X
3
invalidkey => testval;x;y
debug => XUL;ccx;XC
buggy => testX;testY;XtestZ debug:
Output:
-XUL
-XC
buggy:
-testX
-XtestZ
---------------------------
Input:
key
valu
2
xkeyc => value;value;valio
keyhole => valuable;x;values
Output:
xkeyc:
-value
-value
keyhole:
-valuable
-values
'''
key = input()
value = input()
n = int(input())
for _ in range(0, n):
line = input()
print(i)
| true |
b0936ba1bc7bc61bec45b91ebb9467b0da6cd47e | fingerman/python_fundamentals | /python_bbq/OOP/008 settergetter.py | 1,220 | 4.46875 | 4 | class SampleClass:
def __init__(self, a):
## private varibale or property in Python
self.__a = a
## getter method to get the properties using an object
def get_a(self):
return self.__a
## setter method to change the value 'a' using an object
def set_a(self, a):
self.__a = a
## creating an object
obj = SampleClass(10)
## getting the value of 'a' using get_a() method
print(obj.get_a())
## setting a new value to the 'a' using set_a() method
obj.set_a(45)
print(obj.get_a())
print(obj.__dict__)
#SampleClass hides the private attributes and methods.
#It implements the encapsulation feature of OOPS.
#This is how you implement private attributes, getters, and setters in Python.
#The same process was followed in Java.
#Let's write the same implementation in a Pythonic way.
class PythonicWay:
def __init__(self, a):
self.a = a
#You don't need any getters, setters methods to access or change the attributes.
#You can access it directly using the name of the attributes.
## Creating an object for the 'PythonicWay' class
obj = PythonicWay(100)
print(obj.a)
#PythonicWay doesn't hide the data.
#It doesn't implement any encapsulation feature.
| true |
45b01f271a65e346353cc5fcd18383ff480b8c9d | fingerman/python_fundamentals | /python-fundamentals/exam_Python_09.2018/1.DateEstimation.py | 1,251 | 4.4375 | 4 | '''
Problem 1. Date estimation
Input / Constraints
Today is your exam. It’s 26th of August 2018. you will be given a single date in format year-month-day. You should estimate if the date has passed regarding to the date mention above (2018-08-26), if it is not or if it is today. If it is not you should print how many days are left till that date. Note that the current day stills count!
Date Format:
yyyy-mm-dd
Output
The output should be printed on the console.
If the date has passed you should print the following output:
• "Passed"
If the day is today:
"Today date"
If the date is future:
• "{number of days} days"
INPUT
2018-08-20
Output
Passed
--------------------------
Input
2021-08-26
1097 days left
--------------------------
Input - today
2018-08-26
Today date
'''
import datetime
list_nums = [int(item) for item in input().split('-')]
date_input = datetime.date(list_nums[0], list_nums[1], list_nums[2])
date_today = datetime.datetime.now().date()
if date_today == date_input:
print("Today date")
if date_input < date_today:
print("Passed")
if date_input > date_today:
days_left = date_input - date_today
days_left = days_left + datetime.timedelta(days=1)
print(f'{days_left.days} days left')
| true |
ec67e60dc31824809ecf5024ce76c1708a46b295 | rmalarc/is602 | /hw1_alarcon.py | 1,967 | 4.28125 | 4 | #!/usr/bin/python
# Author: Mauricio Alarcon <rmalarc@msn.com>
#1. fill in this function
# it takes a list for input and return a sorted version
# do this with a loop, don't use the built in list functions
def sortwithloops(input):
sorted_input = input[:]
is_sorted = False
while not is_sorted:
changes = False
for i in range(len(sorted_input)-1):
if (sorted_input[i] > sorted_input[i+1]):
changes = True
tmp = sorted_input[i]
sorted_input[i] = sorted_input[i+1]
sorted_input[i+1] = tmp
is_sorted = not(changes)
return sorted_input
#2. fill in this function
# it takes a list for input and return a sorted version
# do this with the built in list functions, don't us a loop
def sortwithoutloops(input):
sorted_input = input[:]
sorted_input.sort()
return sorted_input#return a value
#3. fill in this function
# it takes a list for input and a value to search for
# it returns true if the value is in the list, otherwise false
# do this with a loop, don't use the built in list functions
def searchwithloops(input, value):
found=False
for i in range(len(input)):
found = input[i] == value
if (found):
break
return found #return a value
#4. fill in this function
# it takes a list for input and a value to search for
# it returns true if the value is in the list, otherwise false
# do this with the built in list functions, don't use a loop
def searchwithoutloops(input, value):
return value in input #return a value
if __name__ == "__main__":
L = [6,3,6,3,13,5,5]
print sortwithloops(L) # [3, 3, 5, 5, 6, 6, 13]
print sortwithoutloops(L) # [3, 3, 5, 5, 6, 6, 13]
print searchwithloops(L, 5) #true
print searchwithloops(L, 11) #false
print searchwithoutloops(L, 5) #true
print searchwithoutloops(L, 11) #false
| true |
1ead53f839aedb80b3d3360ad1d1c972710a2d69 | Austinkrobison/CLASSPROJECTS | /CIS210PROJECTS/PROJECT3/DRAW_BARCODE/draw_barcode.py | 2,588 | 4.15625 | 4 |
"""
draw_barcode.py: Draw barcode representing a ZIP code using Turtle graphics
Authors: Austin Robison
CIS 210 assignment 3, part 2, Fall 2016.
"""
import argparse # Used in main program to obtain 5-digit ZIP code from command
# line
import time # Used in main program to pause program before exit
import turtle # Used in your function to print the bar code
## Constants used by this program
SLEEP_TIME = 30 # number of seconds to sleep after drawing the barcode
ENCODINGS = [[1, 1, 0, 0, 0], # encoding for '0'
[0, 0, 0, 1, 1], # encoding for '1'
[0, 0, 1, 0, 1], # encoding for '2'
[0, 0, 1, 1, 0], # encoding for '3'
[0, 1, 0, 0, 1], # encoding for '4'
[0, 1, 0, 1, 0], # encoding for '5'
[0, 1, 1, 0, 0], # encoding for '6'
[1, 0, 0, 0, 1], # encoding for '7'
[1, 0, 0, 1, 0], # encoding for '8'
[1, 0, 1, 0, 0] # encoding for '9'
]
SINGLE_LENGTH = 25 # length of a short bar, long bar is twice as long
def compute_check_digit(digits):
"""
Compute the check digit for use in ZIP barcodes
args:
digits: list of 5 integers that make up zip code
returns:
check digit as an integer
"""
sum = 0
for i in range(len(digits)):
sum = sum + digits[i]
check_digit = 10 - (sum % 10)
if (check_digit == 10):
check_digit = 0
return check_digit
"""
Draws a single bar
args:
digit: either 1 or 0
output:
a bar of length 25 if digit is 0, or length 50 if digit is 1
"""
def draw_bar(my_turtle, digit):
my_turtle.left(90)
if digit == 0:
length = SINGLE_LENGTH
else:
length = 2 * SINGLE_LENGTH
my_turtle.forward(length)
my_turtle.up()
my_turtle.backward(length)
my_turtle.right(90)
my_turtle.forward(10)
my_turtle.down()
"""
Draws a chuck of a barcode
args:
the zip code to be translated
output:
a chunck of a barcode in turtle graphics
"""
def draw_zip(my_turtle, zip):
for digit_spot in str(zip):
digit = int(digit_spot)
for barcode_chunk in ENCODINGS[digit]:
draw_bar(my_turtle, barcode_chunk)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("ZIP", type=int)
args = parser.parse_args()
zip = args.ZIP
if zip <= 0 or zip > 99999:
print("zip must be > 0 and < 100000; you provided", zip)
else:
my_turtle = turtle.Turtle()
draw_zip(my_turtle, zip)
time.sleep(SLEEP_TIME)
if __name__ == "__main__":
main()
| true |
8dd8056d42f4b32c463bc559c4ee173c2339e067 | tlarson07/dataStructures | /tuples.py | 1,378 | 4.3125 | 4 | #NOTES 12/31/2016
#Python Data Structures: Tuples
#Similar to lists BUT
#Can't be changed after creation (NO: appending, sorting, reversing, etc.
#Therefore they are more efficient
friends = ("Annalise", "Gigi", "Kepler") #
numbers = (13,6,1,23,7)
print friends[1]
print max(numbers)
(age,name) = (15,"Lauren") #assigning two variables at once
print name
print age
age,name = (15,"Lauren") #assigning two variables at once WITHOUT parathesis
print name
print age
print (18,33,75) > (8,32,2) #tuples are compariable, runs through each element until False, or prints True
#DICTIONARY ----> LIST of TUPLES ----> SORTED LIST
family = {"Lauren":15, "Paige":10, "Tanner":18, "Jennifer":43, "Bruce": 50}
t = family.items() #turns dict (family) into a list of tuples (t)
print t
t.sort() #sorts the list of tuples by keys
print t
#DICTIONARY ----> LIST of SORTED TUPLES
family = {"Lauren":15, "Paige":10, "Tanner":18, "Jennifer":43, "Bruce": 50}
t = sorted(family.items()) #creates sorted list of tuples (key, value pair) from a dictionary
print t
for person, age in sorted(family.items()):
print person,age
tAge = list() #creates an empty list (tAge)
for person, age in family.items(): #for key/value (person,age) in list of tuples(family)
tAge.append((age,person)) #append tuple (age,person)
tAge.sort() #sorts list (tAge), where the key is currenty age
print tAge
| true |
211273d69389aee16e11ffc9cf9275c0f509029e | sudhapotla/untitled | /Enthusiastic python group Day-2.py | 2,426 | 4.28125 | 4 | # Output Variables
# python uses + character to combine both text and Variable
x = ("hard ")
print("we need to work " + x)
x = ("hardwork is the ")
y = (" key to success")
z = (x + y)
print(z)
#Create a variable outside of a function, and use it inside the function
x = "not stressfull"
def myfunc():
print("Python is " + x)
myfunc()
# Create a variable inside a function, with the same name as the global variable
x = "not stressfull"
def myfunc():
x = "may be sometimes hard"
print("python " + x)
myfunc()
print("python is " + x)
# To create a global variable inside a function, you can use the global keyword
def myfunc():
global x
x = "easy"
myfunc()
print ("python is "+ x)
#To change the value of a global variable inside a function, refer to the variable by using the global keyword:
x = "easy"
def myfunc():
global x
x = "hard"
myfunc()
print("python is " + x)
# Learning DataTypes
x = 9
print(type(x))
x = " is everybody's lucky number" # str
print(type(x))
x = 20.5
print(type(x))
x = 1j
print(type(x))
x = ["sarees", "blouses", "dresses"]
print(type(x))
x = ("gavvalu", "chekkalu", "kova")
print(type(x))
x = range(7)
print(type(x))
x = {"name": "Pluto", "age": 12}
print(type(x))
x = {"apple", "banana", "cherry"}
print(type(x))
x = frozenset({"apple", "banana", "cherry"})
print(type(x))
x = True
print(x)
print(type(x))
x = b"Hello"
print(type(x))
x = bytearray(5)
print(x)
print(type(x))
x = memoryview(bytes(5))
print(type(x))
# Learning Python numbers
# Integers
x = 7
y = 35656222554887711
z = -67890
print(type(x))
print(type(y))
print(type(z))
#Float
x = 2.10
y = 7.0
z = -36.59
print(type(x))
print(type(y))
print(type(z))
#Complex
x= 1j
y= 7+5j
z= -5j
print(type(x))
print(type(x))
print(type(x))
# converting from one type to another with the int(), float(), and complex() methods:
x = 1 #int
y = 2.5 #float
z = 1+5j #complex
# convert from int to float
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x) #cannot convert complex numbers into another number type.
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
# Random numbers
#Python does not have a random() function to make a random number, but Python has a built-in module
#called random that can be used to make random numbers:
import random
import random
print(random.randrange(2, 100))
| true |
deaa241ca580c969b2704ae2eb830487b247c766 | sudhapotla/untitled | /Python variables,Datatypes,Numbers,Casting.py | 1,192 | 4.25 | 4 | #Python Variables
#Variables are containers for storing data values.
#Rules for Variable names
#A variable name must start with a letter or the underscore character
#A variable name cannot start with a number
#A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
#Variable names are case-sensitive (age, Age and AGE are three different variables)
my_name="sudha"
address="westchester"
print(my_name)
print(address)
#python uses + character to combine the text and variable
print(my_name + " lives in "+ address )
#If you try to combine a string and a number, Python will give you an error:
"""my_name="sudha"
address= 114
print(my_name + " lives in "+ address )"""
#Global variables
#Variables that are created outside of a function
#Global variables can be used by everyone, both inside of functions and outside.
x= "python"
y= " is awesome"
z= (x+y)
print(z)
#Global variables created outside a fnction
x= "awesome"
def myfunc():
print("python is" + x)
#creating a variable inside the function with the same name as the global variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x) | true |
a070d7391d0b798ed5d4b143c113b58d2134b6c4 | Allegheny-Computer-Science-102-F2018/classDocs | /labs/04_lab/sandbox/myTruthCalculatorDemo.py | 1,176 | 4.3125 | 4 | #!/usr/bin/env python3
# Note: In terminal, type in "chmod +x program.py" to make file executable
"""calcTruth.py A demo to show how lists can be used with functions to make boolean calculations"""
__author__ = "Oliver Bonham-Carter"
__date__ = "3 October 2018"
def myAND(in1_bool, in2_bool):
# function to determine the boolean AND calculation.
return in1_bool and in2_bool
#end of myAND()
def myOR(in1_bool, in2_bool):
# function to determine the boolean OR calculation.
return in1_bool or in2_bool
#end of myOR()
def main(): # lead function
#define the list of true and false values
A_list = [True, True, False, False]
B_list = [True, False, True, False]
print(" Welcome to the CalcTruth program!")
truth_dic = {}
for a in A_list:
for b in B_list:
# print(" Current values, a = ",a,"b = ",b)
myOR_bool = myOR(a,b)
myAND_bool = myAND(a,b)
truth_dic[str(a)+" OR "+str(b)] = myOR_bool
truth_dic[str(a)+" AND "+str(b)] = myAND_bool
for i in truth_dic:
print(" ",i, ":", truth_dic[i])
print(" All finished!")
#end of main()
main() # driver function
| true |
d80dcff9be08846685f9f553817a16daf91a2d77 | JeanneBM/PyCalculator | /src/classy_calc.py | 1,271 | 4.15625 | 4 | class PyCalculator():
def __init__(self,x,y):
self.x=x
self.y=y
def addition(self):
return self.x+self.y
def subtraction(self):
return self.x - self.y
def multiplication(self):
return self.x*self.y
def division(self):
if self.y == 0:
print("Division by zero. We cannot perform this operation.")
else:
return self.x/self.y
def main():
print("Select please one of the following operations: ")
print("1 - Addition")
print("2 - Subtraction")
print("3 - Multiplication")
print("4 - Division")
choice = input("What kind of operation should be performed? [Insert one of the options(1 2 3 4)]: ")
if choice in ('1', '2', '3', '4'):
x = float(input("Enter first number: "))
y = float(input("Enter second number: "))
calculator = PyCalculator(x,y)
if choice == '1':
print(calculator.addition())
elif choice == '2':
print(calculator.subtraction())
elif choice == '3':
print(calculator.multiplication())
else:
print(calculator.division())
if __name__ == '__main__':
main()
| true |
ff7dbb03f9a296067fbd7e9cfff1ff58d2a00a63 | jocogum10/learning_python_crash_course | /numbers.py | 1,487 | 4.40625 | 4 | for value in range(1,5):
print(value)
for value in range(1,6):
print(value)
numbers = list(range(1,6))
print(numbers)
even_numbers = list(range(2,11,2))
print(even_numbers)
#square values
squares = [] #create empty list
for value in range(1,11): #loop from 1 to 10 using range function
square = value**2 #store in square variable the current loop value raised to the 2nd power
squares.append(square) #add to the list the value of square
print(squares)
#better square values
squaresb = []
for value in range(1,11):
squaresb.append(value**2)
print("\n\n")
print(squaresb)
#list comprehensions
print("\n\n")
print("\n\n")
squares = [value**2 for value in range(1,11)]
print(squares)
add_one = [integer+1 for integer in range(1,6)]
print(add_one)
#try it yourself
print("#########################")
#counting to twenty
for number_to_twenty in range(1,21):
print(number_to_twenty)
#one million pero up to hundred lang kay dugay
hundred = []
for count_to_hundred in range(1,101):
hundred.append(count_to_hundred)
print(hundred)
#summing a million pero hundred lang kay dugay
print(min(hundred))
print(max(hundred))
print(sum(hundred))
#odd numbers
odd_numbers = []
for odd in range(1,20,2):
odd_numbers.append(odd)
print(odd_numbers)
#cubes
cubes = []
for first_10_cubes in range(1,11):
cubes.append(first_10_cubes**3)
print(cubes)
#cube comprehension
cubes_comprehension = [first_10_cubes_b**3 for first_10_cubes_b in range(1,11)]
print(cubes_comprehension)
| true |
17d50543233400d554d9c838e64ec0c6f5506ce6 | ArashDai/SchoolProjects | /Python/Transpose_Matrix.py | 1,452 | 4.3125 | 4 | # Write a function called diagonal that accepts one argument, a 2D matrix, and returns the diagonal of
# the matrix.
def diagonal(m):
# this function takes a matrix m ad returns an array containing the diagonal values
final = []
start = 0
for row in m:
final.append(row[start])
start += 1
return final
# Problem 2
# Write a function called symmetric that will accept one argument, a matrix m, and returns true if the
# matrix is symmetric or false otherwise.
def symmetric(m):
# this function takes a matrix m and returns true if the matrix is symetric or false if it is not
solution = True
for row in range(0, len(m)):
for item in range(0, len(m[row])):
if row == item:
continue # nothing to check against
elif m[row][item] == m[item][row]:
continue # yes it is symmetric
else:
solution = False
break
return solution
# Problem 3
# Write a function called transpose that will return a new matrix with the transpose matrix. The original
# matrix must not be modified. See the usage for examples of how transpose works.
def transpose(A):
# this function takes a matrix A and returns a new transposed matrix
At = []
for row in range(0, len(A)):
if row == 0:
for item in range(0,len(A[row])):
At.append([A[row][item]])
else:
for item in range(0,len(A[row])):
At[item].append(A[row][item])
return At
| true |
3f2328a01dd09470f4421e4958f607c3b97a5e1f | Remyaaadwik171017/mypythonprograms | /flow controls/flowcontrol.py | 244 | 4.15625 | 4 | #flow controls
#decision making(if, if.... else, if... elif... if)
#if
#syntax
#if(condition):
# statement
#else:
#statement
age= int(input("Enter your age:"))
if age>=18:
print("you can vote")
else:
print("you can't vote") | true |
8fd6028336cac45579980611e661c84e892bbf12 | danksalot/AdventOfCode | /2016/Day03/Part2.py | 601 | 4.125 | 4 | def IsValidTriangle(sides):
sides.sort()
return sides[0] + sides[1] > sides [2]
count = 0
with open("Input") as inputFile:
lines = inputFile.readlines()
for step in range(0, len(lines), 3):
group = lines[step:step+3]
group[0] = map(int, group[0].split())
group[1] = map(int, group[1].split())
group[2] = map(int, group[2].split())
if IsValidTriangle([group[0][0], group[1][0], group[2][0]]):
count += 1
if IsValidTriangle([group[0][1], group[1][1], group[2][1]]):
count += 1
if IsValidTriangle([group[0][2], group[1][2], group[2][2]]):
count += 1
print "Valid triangles:", count
| true |
f78c5a609bc06e6f4e623960f93838db21432089 | valerienierenberg/holbertonschool-higher_level_programming | /0x05-python-exceptions/0-safe_print_list.py | 744 | 4.125 | 4 | #!/usr/bin/python3
def safe_print_list(my_list=[], x=0):
a = 0
for y in range(x):
try:
print("{}".format(my_list[y]), end="")
a += 1
except IndexError:
break
print("")
return(a)
# --gives correct output--
# def safe_print_list(my_list=[], x=0):
# try:
# for x in my_list[:x]:
# print("{}".format(my_list[x - 1]), end="")
# print()
# except IndexError:
# print()
# finally:
# return x
#
# Function that prints x elements of a list
# a = counter variable to keep count correct, will be returned
# for loop iterates through list to index x
# print value of each element
# add to count only if index doesn't exceed length of list
| true |
bc9d2fe1398ef572e5f23841976978c19a6e21a6 | YusefQuinlan/PythonTutorial | /Intermediate/2.5 pandas/2.5.5 pandas_Column_Edit_Make_DataFrame.py | 2,440 | 4.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 19 17:11:39 2021
@author: Yusef Quinlan
"""
import pandas as pd
"""
Making a dictionary to be used to make a pandas DataFrame with.
The keys are the columns, and the values for the keys (which must be lists)
are what are used to make the DataFrame.
"""
dictionary1 = {
'Column1':['val','val','val'],
'Column2':['Jack','Dentist','lllll'],
'AColumnName':[1,2,3]
}
# The dataframe is used with pd.DataFrame(dictionary1).
df = pd.DataFrame(dictionary1)
df
"""
Here a list of tuples is created and a DataFrame will be created from these
tuples. Each tuple represents a value of the rows and there are no column
names, so column names must be specified later.
"""
Tuples1 = [('val','val2','hello'),
(4,5,3),
(99,88,77)]
"""
Here the pd.DataFrame() function is used with the tuples list as an
argument, and also with the column names as an argument and a DataFrame is
created.
"""
df = pd.DataFrame(Tuples1, columns=['Col1','Tr','MOP'])
df
"""
Here the columns attribute of our DataFrame is accessed, so that we can see
all the different columns in our DataFrame. The columns are then edited by
directly editing the .columns attribute with a list of new column names for
the existing columns. This will permanently change the column names.
"""
df.columns
df.columns = ['Col1','Mr','Mop']
df
"""
A list comprehension is used here in order to change the columns attribute
of our DataFrame, it changes our column names to uppercase versions of
themselves.
"""
df.columns = [colname.upper() for colname in df.columns]
df
# Same as the above but lower case instead.
df.columns = [colname.lower() for colname in df.columns]
df
"""
Below, the df.rename() function is used with the columns argument,
this returns a DataFrame that is a modified version of the original
DataFrame. The modifications being that the new column names specified in
the argument will be the names of the returned columns names. Note that
not all column names must be changed and that the column names that are to
be changed must be put as keys in a dictionary and the value to be changed
to should be their values.
"""
df.rename(columns={'col1':'T-rex','mop':'POM'})
df
# Same as above, but with the inplace=True argument, the DataFrame is changed.
df.rename(columns={'col1':'T-rex','mop':'POM'}, inplace=True)
df | true |
881419c45d178dec904578bbe59fac4ce828b4b7 | YusefQuinlan/PythonTutorial | /Basics/1.16.3_Basic_NestedLoops_Practice.py | 2,147 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 20 15:10:45 2019
@author: Yusef Quinlan
"""
# A nested loop is a loop within a loop
# there may be more than one loop within a loop, and there may be loops within loops
# within loops etc etc
# Any type of loop can be put into any other type of loop
#as in the example below, several loops can be put into one loop without being put into another
# i.e. in the below example the two loops with range(0,3) are both with the loop with range(0,5)
# and so are nested in that loop, but they are both independant of eachother and are not nested within
# eachother.
for i in range(0,5):
print(i+1)
for i2 in range(0,3):
print(i + 1 + (i2 + 1))
for i3 in range(0,3):
print(i + 1 + (i3 + 1))
#The below shows that you can use any type of loop within another type of loop
whilenum = 1
for i in range(0,10):
while whilenum < ((i+1) * 3):
print("Whilenum is equal to: " + str(whilenum))
whilenum = whilenum + 1
#The below demonstrates how quickly nested loops can multiply/add to the amount
# of overall lines of code actually run by your program, for those who want to do more homework
# there is something called 'Big O notation' that goes into this concept in more detail than I.
#for those of you who are curious to see the multiplicative effects of nested loops
# you may want to mess about with the value of 'Amount_Times' and experiment to see what happens
# you could change the value to a rediculous number such as 1000 or 10,000 , be warned though
# your computer may not be able to handle it and I bear no responsibility for any damages you might
# incur by experimenting with the variable value.
num1 = 1
num2 = 1
Amount_Times = 10
for i in range(0,Amount_Times):
print("iteration number: " + str(i+1) + " of the first loop")
for i in range(0,Amount_Times):
print("execution number: " + str(num1) + " of the code in the second loop")
num1 = num1 + 1
for i in range(0,Amount_Times):
print("execution number: " + str(num2) + " of the code in the third loop")
num2 = num2 + 1
| true |
05111398ed789569ad5d10cfbf537cb53a069ed5 | YusefQuinlan/PythonTutorial | /Intermediate/2.1 Some Useful-Inbuilt/2.1.8_Intermediate_Generators.py | 1,879 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 29 15:38:07 2020
@author: Yusef Quinlan
"""
# What is a generator?
# A generator is an iterable object, that can be iterated over
# but it is not an object that contains all the iterable instances of whatever
# it iterates, at once.
# return will return the first valid value and exit the function
# so the following function wont return the whole range.
def iterablereturn():
for i in range(9):
return i
# Returns 0, the first value in range(9) -- 0,1,2,3,4,5,6,7,8
iterablereturn()
"""
A generator essentially makes an iteration formula and produces a generator object
based on that formula, however the generator does not contain every iteration
rather it has to be iterated over and each item generated must be used at
each iteration in order to have value, as a generator can only be iterated
over once
"""
# generators use the keyword yield and must be iterated over to be useful.
def yielder():
for i in range(9):
yield i
# using the following function will just output a generator object not the
# iterable items that the object can produce, as it does not contain them, rather
# it generates them one by one.
yielder()
# The following is the correct use of a generator
for i in yielder():
print(i)
aList1 = [x for x in range(9)]
aList2 = [x for x in range(9)]
# The following functions have the same outputs, but differ in their
# manner of execution, their use of RAM and their efficiency.
def five_list(alist):
for i in range(len(alist)):
alist[i] = alist[i] * 5
return alist
def five_list_yield(alist):
for i in range(len(alist)):
yield i * 5
# Checking original list value
for i in aList1:
print(i)
# Proof of outputs
for i in five_list(aList1):
print(i)
for i in five_list_yield(aList2):
print(i)
| true |
b51c8430b39bdf7dce428ccaaed9ddf5ef1c9505 | mahfoos/Learning-Python | /Variable/variableName.py | 1,180 | 4.28125 | 4 | # Variable Names
# A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
# Rules for Python variables:
# A variable name must start with a letter or the underscore character
# A variable name cannot start with a number
# A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
# Variable names are case-sensitive (age, Age and AGE are three different variables)
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
print(myvar)
print(my_var)
print(_my_var)
print(myVar)
print(MYVAR)
print(myvar2)
# 2myvar = "John"
# my-var = "John"
# my var = "John"
# This example will produce an error in the result
# Multi Words Variable Names
# Variable names with more than one word can be difficult to read.
# There are several techniques you can use to make them more readable:
# Camel Case
# Each word, except the first, starts with a capital letter:
myVariableName = "John"
# Pascal Case
# Each word starts with a capital letter:
MyVariableName = "John"
# Snake Case
# Each word is separated by an underscore character:
my_variable_name = "John"
| true |
ae3689da43f974bd1948f7336e10162aea14cae6 | CharlesBasham132/com404 | /second-attempt-at-tasks/1-basics/2-input/2-ascii-robot/bot.py | 523 | 4.125 | 4 | #ask the user what text character they would wish to be the robots eyes
print("enter character symbol for eyes")
eyes = input()
print("#########")
print("# #")
print("# ",eyes,eyes, " #")
print("# ----- #")
print("#########")
#bellow is another way of formatting a face with the use of + instead of ,
#plusses + do not add spaces automatically and so are manually addes within the print statement speach marks " "
print("##########")
print("# " + eyes + " " + eyes + " #")
print("# ---- #")
print("##########")
| true |
e2e0488734dab283f61b4114adf692f8d041209e | abhisheklomsh/Sabudh | /prime_checker.py | 700 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 9 10:51:47 2019
@author: abhisheklomsh
Here we ask user to enter a number and we return whether the number is prime or not
"""
def prime_check(input_num):
flag=1
if input_num ==1: print(str(input_num)+" is not a prime number")
else:
for i in range(2,input_num+1):
if (input_num==i and flag ==1):
print(str(input_num)+" is a prime number!")
pass
elif(input_num%i==0 and flag==1):
print("This is not a prime number")
flag=0
prime_check(int(input('Enter number to be cheked if it\'s prime or not')))
| true |
17c67730fe1f49ff945cdd21cf9b814073341e32 | ThienBNguyen/simple-python-game | /main.py | 1,447 | 4.21875 | 4 | import random
def string_combine(aug):
intro_text = 'subscribe to '
return intro_text + aug
# def random_number_game():
# random_number = random.randint(1, 100)
# user_number = int(input('please guess a number that match with the computer'))
# while user_number == random_number:
# if random_number == user_number:
# print('your are correct')
# elif random_number < user_number:
# print('your number is greater than computer number')
# elif random_number > user_number:
# print('your number is less than computer number')
# return random_number
def user_guess(x):
random_number = random.randint(1,x)
guess = 0
while guess != random_number:
guess = int(input(f'guess a number between 1 and {x}: '))
if guess < random_number:
print('sorry, guess again.too low.')
elif guess > random_number:
print('sorry, guess again. too hight.')
print(f'correct. {random_number}')
def computer_guess(x):
low = 1
high = x
feedback = ''
while feedback != 'c':
guess = random.randint(low, high)
feedback = input(f'is {guess} too high(H) , too low(L) or correct(C)').lower()
if feedback == 'h':
high = guess - 1
elif feedback == 'l':
low = guess + 1
print(f'yay the computer guessed your, {guess}, correctly!!')
computer_guess(10) | true |
c8492b2fc31a4301356bdfd95ead7a6a97fcc010 | am93596/IntroToPython | /functions/calculator.py | 1,180 | 4.21875 | 4 |
def add(num1, num2):
print("calculating addition:")
return num1 + num2
def subtract(num1, num2):
print("calculating subtraction:")
return num1 - num2
def multiply(num1, num2):
print("calculating multiplication:")
return num1 * num2
def divide(num1, num2):
print("calculating division:")
if num2 == 0:
return "Invalid - cannot divide by 0"
else:
return num1 / num2
# print("Please input the numbers to be used:")
# number1 = input("Number 1: ")
# number2 = input("Number 2: ")
# if not (num1.isdigit() and num2.isdigit()):
# return "Please enter your numbers in digits"
# num1 = int(num1)
# num2 = int(num2)
#
# add_two_nums(number1, number2)
# subtract_two_nums(number1, number2)
# multiply_two_nums(number1, number2)
# divide_two_nums(number1, number2)
def calculator(instruction, int1, int2):
if instruction == "add":
return add(int1, int2)
elif instruction == "subtract":
return subtract(int1, int2)
elif instruction == "multiply":
return multiply(int1, int2)
elif instruction == "divide":
return divide(int1, int2)
else:
return "invalid instruction"
| true |
a60f3c97b90c57d099e0aa1ade1650163cf8dd8d | adam-m-mcelhinney/MCS507HW | /MCS 507 Homework 2/09_L7_E2_path_length.py | 1,656 | 4.46875 | 4 | """
MCS H2, L7 E2
Compute the length of a path in the plane given by a list of
coordinates (as tuples), see Exercise 3.4.
Exercise 3.4. Compute the length of a path.
Some object is moving along a path in the plane. At n points of
time we have recorded the corresponding (x, y) positions of the object:
(x0, y0), (x1, y2), . . ., (xn−1, yn−1). The total length L of the path from
(x0, y0) to (xn−1, yn−1) is the sum of all the individual line segments
((xi−1, yi−1) to (xi, yi), i = 1, . . . , n − 1):
L =
nX−1
i=1
p
(xi − xi−1)2 + (yi − yi−1)2 . (3.9)
Make a function pathlength(x, y) for computing L according to
the formula. The arguments x and y hold all the x0, . . . , xn−1 and
y0, . . . , yn−1 coordinates, respectively. Test the function on a triangular
triangular
path with the four points (1, 1), (2, 1), (1, 2), and (1, 1). Name of
program file: pathlength.py.
"""
def path_length(c):
"""Compute the length of a path in the plane given by a list of
coordinates (as tuples)
"""
from math import sqrt
# Break problem into the sum of the x coordinates
# and the sum of the y coordinates
# Extract list of all the x and y coordinates
x_coord=[c[i][0] for i in range(0,len(c))]
y_coord=[c[i][1] for i in range(0,len(c))]
# Compute x length and y length
x=0;y=0
for i in range(1,len(c)):
x=x+(x_coord[i]-x_coord[i-1])**2
y=y+(y_coord[i]-y_coord[i-1])**2
total_len=sqrt(x+y)
return total_len
#c=[(1,1),(2,1),(1,2),(1,1)]
#c=[(4,1),(20,1),(1,23),(1,11)]
#c=[(1,4),(4,6)]
print path_length(c)
| true |
bf8675caa23965c36945c51056f3f34ec76ce1bc | anthonyharrison/Coderdojo | /Python/Virtual Dojo 3/bullsandcows.py | 2,390 | 4.15625 | 4 | # A version of the classic Bulls and Cows game
#
import random
# Key constants
MAX_GUESS = 10
SIZE = 4
MIN_NUM = 0
MAX_NUM = 5
def generate_code():
secret = []
for i in range(SIZE):
# Generate a random digit
code = random.randint(MIN_NUM,MAX_NUM)
secret.append(str(code))
return secret
def check_guess (code, guess):
result = ""
bull = 0
cow = 0
win = False
# Validate length of guess
if len(guess) > SIZE:
# Too many digits
result = "Pig"
else:
for i in range (len(guess)):
if guess[i] == code [i]:
# A valid digit in correct position
bull = bull + 1
result = result + "Bull "
elif guess[i] in code:
# A valid digit, but not in correct position
cow = cow + 1
result = result + "Cow "
# Now check result
if bull == SIZE:
# All digits found
result = "Farmer"
win = True
elif bull == 0 and cow == 0:
# No digits found
result = "Chicken"
print ("[RESULT]",result)
return win
def introduce_game():
print ("Welcome to Bulls and Cows")
print ("Try and guess my secret", SIZE,"digit code containing the digits",MIN_NUM,"to",MAX_NUM)
print ("I know it is hard, but I will try and give you some help.")
print ("If I say:")
print ("BULL You have a valid digit in the correct position")
print ("COW You have a valid digit but in the wrong position")
print ("CHICKEN You have no valid digits")
print ("FARMER You have all valid digits in the correct position")
print ("")
print ("Good luck!")
# Game
game_end = False
while not game_end:
introduce_game()
code = generate_code()
count = 0
win = False
while count < MAX_GUESS and not win:
count = count + 1
print ("Guess #",count)
guess = input("Enter your guess ")
win = check_guess(code,guess)
# Game over...
if win:
print ("Well done")
else:
print ("Never mind, try again")
print ("My secret code was",code)
# Play again?
again = input("Do you want to play again (Y/N)? ")
if again.upper() == "N":
game_end = True
print ("Thanks for playing. Have a nice day")
| true |
6bc2dbc19391e9ef4e37a9ce96a4f5a7cdb93654 | skfreego/Python-Data-Types | /list.py | 1,755 | 4.53125 | 5 | """
Task:-Consider a list (list = []). You can perform the following commands:
. insert i e: Insert integer e at position i
. print: Print the list.
. remove e: Delete the first occurrence of integer e
. append e: Insert integer e at the end of the list.
. sort: Sort the list.
. pop: Pop the last element from the list.
. reverse: Reverse the list.
Initialize your list and read in the value of n followed by n lines of commands where each command will be of the
7 types listed above. Iterate through each command in order and perform the corresponding operation on your list.
Input Format:- The first line contains an integer,n , denoting the number of commands.
Each line i of the n subsequent lines contains one of the commands described above.
Output Format:- For each command of type print, print the list on a new line.
"""
"""
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
"""
if __name__ == '__main__':
N = int(input())
command = []
for i in range(N):
command.append(input().split())
result = []
for i in range(N):
if command[i][0] == 'insert':
result.insert(int(command[i][1]), int(command[i][2]))
elif command[i][0] == 'print':
print(result)
elif command[i][0] == 'remove':
result.remove(int(command[i][1]))
elif command[i][0] == 'append':
result.append(int(command[i][1]))
elif command[i][0] == 'pop':
result.pop()
elif command[i][0] == 'sort':
result.sort()
elif command[i][0] == 'reverse':
result.reverse()
| true |
80612a7405e7f0609f457a2263715a5077eaa327 | buy/leetcode | /python/94.binary_tree_inorder_traversal.py | 1,313 | 4.21875 | 4 | # Given a binary tree, return the inorder traversal of its nodes' values.
# For example:
# Given binary tree {1,#,2,3},
# 1
# \
# 2
# /
# 3
# return [1,3,2].
# Note: Recursive solution is trivial, could you do it iteratively?
# confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
# OJ's Binary Tree Serialization:
# The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
# Here's an example:
# 1
# / \
# 2 3
# /
# 4
# \
# 5
# The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {integer[]}
def inorderTraversal(self, root):
result, stack = [], [(root, False)]
while stack:
cur, visited = stack.pop()
if cur:
if visited:
result.append(cur.val)
else:
stack.append((cur.right, False))
stack.append((cur, True))
stack.append((cur.left, False))
return result
| true |
e8689f10872987e7c74263e68b95788dce732f56 | buy/leetcode | /python/145.binary_tree_postorder_traversal.py | 983 | 4.125 | 4 | # Given a binary tree, return the postorder traversal of its nodes' values.
# For example:
# Given binary tree {1,#,2,3},
# 1
# \
# 2
# /
# 3
# return [3,2,1].
# Note: Recursive solution is trivial, could you do it iteratively?
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {integer[]}
def postorderTraversal(self, root):
if not root:
return []
result, queue = [], [(root, False)]
while queue:
curNode, visited = queue.pop()
if curNode:
if visited:
result.append(curNode.val)
else:
queue.append((curNode, True))
queue.append((curNode.right, False))
queue.append((curNode.left, False))
return result
| true |
8f5d33183271397e07fd1b45717bc15dc24ba80f | nayanika2304/DataStructuresPractice | /Practise_graphs_trees/random_node.py | 2,420 | 4.21875 | 4 | '''
You are implementing a binary tree class from scratch which, in addition to
insert, find, and delete, has a method getRandomNode() which returns a random node
from the tree. All nodes should be equally likely to be chosen. Design and implement an algorithm
for getRandomNode, and explain how you would implement the rest of the methods.
Random number calls can be expensive. If we'd like, we can reduce the number of random number calls
substantially.
Another way to think about what we're doing is that the initial random number call indicates which node (i) to return,
and then we're locating the ith node in an in-order traversal.
Subtracting LEFT_SIZE + 1 from i reflects that, when we go right,
we skip over LEFT_SIZE + 1 nodes in the in-order traversal.
https://www.youtube.com/watch?v=nj5jFhglw8U
depth of tree is log n so time complexity is O(logn)
'''
from random import randint
class Node:
def __init__(self, data):
self.data = data
self.children = 0
self.left = None
self.right = None
# This is used to fill children counts.
def getElements(root):
if root == None:
return 0
return (getElements(root.left) +
getElements(root.right) + 1)
# Inserts Children count for each node
def insertChildrenCount(root):
if root == None:
return
root.children = getElements(root) - 1
insertChildrenCount(root.left)
insertChildrenCount(root.right)
# Returns number of children for root
def children(root):
if root == None:
return 0
return root.children + 1
# Helper Function to return a random node
def randomNodeUtil(root, count):
if root == None:
return 0
if count == children(root.left):
return root.data
if count < children(root.left):
return randomNodeUtil(root.left, count)
return randomNodeUtil(root.right,
count - children(root.left) - 1)
# Returns Random node
def randomNode(root):
count = randint(0, root.children)
return randomNodeUtil(root, count)
# Driver Code
if __name__ == "__main__":
# Creating Above Tree
root = Node(10)
root.left = Node(20)
root.right = Node(30)
root.left.right = Node(40)
root.left.right = Node(50)
root.right.left = Node(60)
root.right.right = Node(70)
insertChildrenCount(root)
print("A Random Node From Tree :",
randomNode(root)) | true |
4774e23e3a65b54ff0e96736d0d491a965c6a1b4 | nayanika2304/DataStructuresPractice | /Practise_linked_list/remove_a_node_only pointer_ref.py | 1,885 | 4.375 | 4 | '''
Implement an algorithm to delete a node in the middle (i.e., any node but
the first and last node, not necessarily the exact middle) of a singly linked list, given only access to
that node.
iterating through it is a problem as head is unkniwn
faster approach is to copy the data of next node in current node
and delete next node
# to delete middle node
LinkedListNode next =n.next;
n.data = next.data;
n.next = next.next;
return true;
'''
# a class to define a node with
# data and next pointer
class Node():
# constructor to initialize a new node
def __init__(self, val=None):
self.data = val
self.next = None
# push a node to the front of the list
def push(head, val):
# allocate new node
newnode = Node(val)
# link the first node of the old list to the new node
newnode.next = head.next
# make the new node as head of the linked list
head.next = newnode
# function to print the list
def print_list(head):
temp = head.next
while (temp != None):
print(temp.data, end=' ')
temp = temp.next
print()
# function to delete the node
# the main logic is in this
def delete_node(node):
prev = Node()
if (node == None):
return
else:
while (node.next != None):
node.data = node.next.data
prev = node
node = node.next
prev.next = None
if __name__ == '__main__':
# allocate an empty header node
# this is a node that simply points to the
# first node in the list
head = Node()
# construct the below linked list
# 1->12->1->4->1
push(head, 1)
push(head, 4)
push(head, 1)
push(head, 12)
push(head, 1)
print('list before deleting:')
print_list(head)
# deleting the first node in the list
delete_node(head.next)
print('list after deleting: ')
print_list(head) | true |
c173928913363f978662919341813f5ae867bf95 | fanyichen/assignment6 | /lt911/assignment6.py | 1,816 | 4.28125 | 4 | # This program is to manage the user-input intervals. First have a list of intervals entered,
# then by taking new input interval to merge intervals.
# input of valid intervals must start with [,(, and end with ),] in order for correct output
import re
import sys
from interval import interval
from interval_functions import *
def prompt():
'''Start the program by prompting user input'''
start = True
print "Please enter a list of intervals, start with '[]()', and put ', ' in between intervals."
user_list = raw_input("List of intervals? \n")
if user_list in ["quit","Quit","q","Q"]:
start = False
return
interval_list = user_list.split(", ")
for element in interval_list:
if not validInput(element):
start = False
else:
start = True
while start:
user_interval = raw_input("Interval? (please enter only in the right format):\n")
if user_interval in ["quit","Quit","q","Q"]:
start = False
return
elif not validInput(user_interval):
print "Invalid interval"
pass
else:
insert_interval = interval(user_interval)
if len(insert_interval.list) == 0:
print "Invalid interval"
else:
interval_list = insert(interval_list, user_interval)
print interval_list
def validInput(input_interval):
'''check is input interval is valid'''
delimiters = ",", "[","]", "(",")"
regexPattern = '|'.join(map(re.escape, delimiters))
int_element = re.split(regexPattern, input_interval)
if input_interval[0] in ["[","]","(",")"] or input_interval[-1] in ["[","]","(",")"]:
try:
lower = int(int_element[1])
upper = int(int_element[-2])
return True
except:
return False
else:
return False
class InvalidIntervalError(Exception):
def __str__(self):
return 'Invalid interval'
if __name__ == "__main__":
try:
prompt()
except:
pass
| true |
29816333038bf4bf14460d8436d1b75243849537 | kevgleeson78/Emerging-Technonlgies | /2dPlot.py | 867 | 4.15625 | 4 | import matplotlib.pyplot as plt
# numpy is used fo scientific functionality
import numpy as np
# matplotlib plots points in a line by default
# the first list is the y axis add another list for the x axis
# To remove a connecting line from the plot the third arg is
# shorthand for create blue dots
# numpy range
x = np.arange(0.0, 10.0, 0.01)
y = 3.0 * x + 1.0
# generate noise for the plot
noise = np.random.normal(0.0, 1.0, len(x))
# plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'b.')
plt.plot(x, y + noise, 'r.', label="Actual")
plt.plot(x, y, 'b', label="Model")
# plt.ylabel("Some Value Label")
# to add a title
plt.title("SImple Title")
# To add a label to the x axis
plt.xlabel("Weight")
# To add a label to the y axis
plt.ylabel("Mass")
# To add a legend to the plot label has to be added to the plots above as an extra parameter.
plt.legend()
plt.show()
| true |
f17209f360bf135a9d3a6da02159071828ca0087 | hamishscott1/Number_Guessing | /HScott_DIT_v2.py | 1,120 | 4.3125 | 4 | # Title: Guess My Number v2
# Date: 01/04/2021
# Author: Hamish Scott
# Version: 2
""" The purpose of this code is to get the user to guess a preset number.
The code will tell them if the number is too high or too low and will
tell them if it is correct."""
# Setting up variables
import random
int_guess = 0
int_number = random.randint(1, 64)
int_num_of_guesses = 1
# Asks users name.
str_name = input('What is your name? ').title()
# User feedback loop, tells user if guess is too high or too low.
while int_guess != int_number:
int_guess = int(input("Hi {}. Please try and guess \
the number between 1 and 64 inclusive: ".format(str_name)))
if int_guess > int_number:
print("{}, your guess is too high. Try again. ".format(str_name))
int_num_of_guesses += 1
elif int_guess < int_number:
print("{}, your guess is too low. Try again. ".format(str_name))
int_num_of_guesses += 1
# Prints how mant guesses user took.
print("Congratulations {}, you have guessed my number, \
you took {} guesses. Goodbye.".format(str_name, int_num_of_guesses))
| true |
e995bf856a613b5f1978bee619ad0aaab4be80ed | saibeach/asymptotic-notation- | /v1.py | 1,529 | 4.21875 | 4 | from linkedlist import LinkedList
def find_max(linked_list):
current = linked_list.get_head_node()
maximum = current.get_value()
while current.get_next_node():
current = current.get_next_node()
val = current.get_value()
if val > maximum:
maximum = val
return maximum
#Fill in Function
def sort_linked_list(linked_list):
print("\n---------------------------")
print("The original linked list is:\n{0}".format(linked_list.stringify_list()))
new_linked_list = LinkedList()
while linked_list.get_head_node():
current_max = find_max(linked_list)
linked_list.remove_node(current_max)
new_linked_list.insert_beginning(current_max)
return new_linked_list
#Test Cases
ll = LinkedList("Z")
ll.insert_beginning("C")
ll.insert_beginning("Q")
ll.insert_beginning("A")
print("The sorted linked list is:\n{0}".format(sort_linked_list(ll).stringify_list()))
ll_2 = LinkedList(1)
ll_2.insert_beginning(4)
ll_2.insert_beginning(18)
ll_2.insert_beginning(2)
ll_2.insert_beginning(3)
ll_2.insert_beginning(7)
print("The sorted linked list is:\n{0}".format(sort_linked_list(ll_2).stringify_list()))
ll_3 = LinkedList(-11)
ll_3.insert_beginning(44)
ll_3.insert_beginning(118)
ll_3.insert_beginning(1000)
ll_3.insert_beginning(23)
ll_3.insert_beginning(-92)
print("The sorted linked list is:\n{0}".format(sort_linked_list(ll_3).stringify_list()))
#Runtime
runtime = "N^2"
print("The runtime of sort_linked_list is O({0})\n\n".format(runtime)) | true |
02a7ab067157be02467fd544a87a26fb7d792d7b | mayurimhetre/Python-Basics | /calculator.py | 735 | 4.25 | 4 | ###### Python calculator Program ##############################
### taking two numbers as input from user and option
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choose = int(input("Enter your option : 1,2,3,4 : "))
a = int(input("Enter First Number :"))
b = int(input("Enter Second Number :"))
def add(a,b):
print("addition of two numbers is ", a+b)
def subtract(a,b):
print("Subtraction of two numbers is ", a-b)
def multiply(a,b):
print("Multiplication is",a*b)
def division(a,b):
print("Division is :", a/b)
if choose == 1:
add(a,b)
elif choose == 2:
subtract(a,b)
elif choose ==3:
multiply(a,b)
else:
division(a,b)
| true |
2f563e53a9d4c0bbf719259df06fb0003ac205bc | sweetise/CondaProject | /weight_conversion.py | 433 | 4.28125 | 4 | weight = float(input(("Enter your Weight: ")))
unit = input(("Is this in 'lb' or 'kg'?"))
convert_kg_to_lb = round(weight * 2.2)
convert_lb_to_kg = round(weight / 2.2)
if unit == "kg":
print(f" Your weight in lbs is: {convert_kg_to_lb}")
elif unit == "lb":
print(f" Your weight in kg is: {convert_lb_to_kg}")
else:
print("Invalid input. Please enter weight in 'kg', 'kgs', 'kilograms' or 'lb', 'lbs', 'pounds'")
| true |
f6b8082233895e0a78275d13d2ec29c14bc088cf | Ethan2957/p03.1 | /multiple_count.py | 822 | 4.1875 | 4 | """
Problem:
The function mult_count takes an integer n.
It should count the number of multiples of 5, 7 and 11 between 1 and n (including n).
Numbers such as 35 (a multiple of 5 and 7) should only be counted once.
e.g.
mult_count(20) = 7 (5, 10, 15, 20; 7, 14; 11)
Tests:
>>> mult_count(20)
7
>>> mult_count(50)
20
>>> mult_count(250)
93
"""
# Use this to test your solution. Don't edit it!
import doctest
def run_tests():
doctest.testmod(verbose=True)
# Edit this code
def mult_count(n):
count = 0
for i in range(1, n+1, 5):
count = count + 1
for l in range(1, n+1, 7):
if l % 5 != 0:
count = count + 1
for j in range(1, n+1, 11):
if j % 7 != 0 and j % 5 != 0:
count = count + 1
print(count)
| true |
f7f7a5f023f89594db74f69a1a2c3f5f34dfc881 | gpallavi9790/PythonPrograms | /StringPrograms/5.SymmetricalString.py | 241 | 4.25 | 4 | #Prgram to check for symmetrical string
mystr=input("Enter a string:")
n=len(mystr)
mid=n//2
firsthalf=mystr[0:mid]
secondhalf=mystr[mid:n]
if(firsthalf==secondhalf):
print("Symmetrical String")
else:
print("Not a Symmetrical String")
| true |
57740b0f61740553b9963170e2dddc57c7b9858b | gpallavi9790/PythonPrograms | /StringPrograms/7.RemoveithCharacterFromString.py | 400 | 4.25 | 4 | #Prgram to remove i'th character from a string
mystr="Pallavi Gupta"
# Removing char at pos 3
# using replace, removes all occurences
newstr = mystr.replace('l', '')
print ("The string after removal of i'th character (all occurences): " + newstr)
# Removing 1st occurrence of
# if we wish to remove it.
newstr = mystr.replace('l', '', 1)
print ("The string after removal of i'th character : " + newstr)
| true |
f47f69de9366760f05fda6dd697ce2301ad38e01 | johnhjernestam/John_Hjernestam_TE19C | /introkod_syntax/Annat/exclusiveclub.py | 453 | 4.125 | 4 | age = int(input('How old are you? '))
if age < 18:
print('You are too young.')
if age > 30:
print('You are too old.')
if age >= 18:
answer = input('Have you had anything to drink today or taken something? Yes or no: ')
if answer == "no":
print('You got to be turned up')
else:
print('Please answer yes or no.')
if answer == "yes":
input('So you telling me you turned up or what?')
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.