blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
40a867cb13e82c92137838f1a9a0d7cfd515fdc2 | DeveloperJoseph/PYTHON---DE---0---10000 | /Modulo 1/ejercicio4.py | 939 | 4.40625 | 4 |
#ARRAY LISTS SIN CICLO FOR + SALIDA
the_list = ["love","sad","funny","crazy"]#My list of feelings
print(">> The list is (without for): "+str(the_list))#salida de mi lista de array
print("## The item in position '0' of the list is (without for): "+the_list[0])
print("## The item in position '1' of the list is (without for): "+the_list[1])
print("## The item in position '2' of the list is (without for): "+the_list[2])
print("## The item in position '3' of the list is (without for): "+the_list[3])
#ARRAY LIST CON CICLO FOR + SALIDA
the_list2 = ["rabbit","cat","dog","parrot"]
print(">> The list number 2 is (with for): "+str(the_list2))
for animal in the_list2:
print("## The animal secret is: "+animal)
if "rabbit" in animal: #si rabbit existe o es igual a animal
print("## My favorite animal is rabbit and is in the list 2.")#salida de condicion ifs
print("The list number has "+str(len(the_list2))+" items.")
| false |
d86d291ac0a1a21683cd70d4a23bed601a90262a | DeveloperJoseph/PYTHON---DE---0---10000 | /Modulo 1/appBirthday.py | 705 | 4.25 | 4 | dictionary = {}
while True:
print("--- APP BIRTHDAY ---")
print(">>(1) Show birthdays")
print(">>(2) Add to Birthday list")
print(">>(3) Exit")
choice = int(input("Enter the choice: "))
if choice == 1:
if(len(dictionary.keys()))==0:
print("Nothing to show..")
else:
name = str(input("Enter name to look for birthday: "))
birthday= dictionary.get(name,"Not data found")
print("> Birthday: ",birthday)
elif choice ==2:
name = str(input("# Enter name:"))
date = str(input("# Enter birthdate: "))
dictionary[name]=date
print("#> Birthday Added")
elif choice == 3:
break | true |
29c5eaa6897dbbbb6d3cbfe9d868c5110992366b | DeveloperJoseph/PYTHON---DE---0---10000 | /Modulo 1/ejercicio24.py | 2,464 | 4.34375 | 4 | ## PYTHON JSON ##
# - JSON is a syntax for storing and exchanging data.
# - JSON is text, written with Javascript object notation.
# JSON IN PYTHON:
#Python has built-in package called json, which can be use
#to work with JSON data.
#Example:
# Import the json module:
import json
#Parse JSON - Convert from JSON to Python:
#If you have a JSON string, you can parse it by using the
# json.loads() method.(The result will be a Python Dictionary)
#Example:
# Conert from JSON to Python:
"""
x = '{"name":"Joseph","age":17,"city":"New York"}' #some JSON
y = json.loads(x) #convert x string to y json
print(y["name"])#The result is a dictionary, and print value 'name' key
"""
#Convert from Python to JSON:
#If you have a Python object, you can convert it into a JSON string by
#using the json.dumps() method.
""""
x = {"name":"Joseph","age":17,"city":"New York"}
y = json.dumps(x)
print(y)
"""
#You can convert Python objects of the following types, into JSON strings:
"""
dict
list
tuple
string
int
float
True
False
None
#----------------------------------------#
#Example:
# Convert Python object into JSON string, and print the values.
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
"""
#Example:
# Convert a Python object containing all the legal data types:
legal_data = {
"name":"Joseph",
"age": 18,
"married": False,
"divorcied": False,
"children": None,
"pets": ('Cone', 'Candy'),
"cars": [
{"model":"BMW 230", "mpg": 27.5},
{"model":"Ford Edge", "mpg": 24.1}
]
}
# Whitout format the result
"""print(json.dumps(legal_data))"""
#Format the result:
# - The example above prints a JSON string, but it is not very easy to
# read, with no indentations and line breaks.
# - The json.dumps() method has parameters to make it easier to read the
# result.
#Example:
# Use the indet parameter to define the numbers of indents:
"""
legalData_json = json.dumps(legal_data,indent=4)
print(legalData_json)
"""
#Order the result:
#The json.dumps() method has parameters to order the keys in the result:
#Example:
# Use the sort_key parameters to specify if the result should be
# sorted or not:
print(json.dumps(legal_data,indent=3,sort_keys=True)) | true |
39773f7d4aa077701cbb9b8bd826f63c5b6169a4 | DeveloperJoseph/PYTHON---DE---0---10000 | /Modulo 3 - File Handling/writeFiles.py | 1,040 | 4.65625 | 5 | # PYTHON FILE WRITE #
#Create a new File:
# To create a new file in Python, use the open() method, with one of the
# following parameter:
# "x" - Create - will create a file, returns an error if the file exist
# "a" - Append - will create a file if the specified file does not exist
#Example:
# Create a file called "demofile.txt"
"""
myFile = open("demofile.txt","x")
"""
#or
#Example: Create a new file if it does not exist:
"""
myFile = open("demofile.txt","w")
"""
#Write to an Existing File:
# To write toan existing file, you must add parameter to the open() function:
# "a" - Append - will append to the end of the file
# "w" - Write - will overwrite any existing content
#Example: 'Open the file "demofile.txt" and append content to the file'
f = open("\PYTHON - DE - 0 - 10000\Modulo 3 - File Handling\demofile.txt","x") #create file
f.write("Now the file has one more line!")#write file
f = open("\PYTHON - DE - 0 - 10000\Modulo 3 - File Handling\demofile.txt","r") #read file
print(f.read())
| true |
0663f1986d43764b32f2af2db2bfc3269a0862f1 | gtfotis/python_functions | /functionsExercise.py | 1,542 | 4.125 | 4 | #1. Madlib Function
def make_formal_greeting(name, game):
return ("%s's favorite video game is %s" % (name, game))
def ask_for_user_info():
name = input("What is your name? ")
game = input("What is favorite video game? ")
if len(name) < 1 or len(game) < 1:
print("Terminating since you don't want to play along >:(")
else:
print(make_formal_greeting(name, game))
#ask_for_user_info()
#2. Celsius to Fahrenheit conversion
def celsiusToFahrenheit():
num = input("Enter temperature in Celsius: ")
return print((float(num) * 9/5) + 32)
#celsiusToFahrenheit()
#3. Fahrenheit to Celcius conversion
def fahrenheitToCelsius():
num = input("Enter temperature in Fahrenheit: ")
return print((float(num) - 32) * 5/9)
#fahrenheitToCelsius()
#4. is_even function
def is_even():
num = input("Enter a number to find out if even: ")
if int(num) % 2 == 0:
return print("True")
else:
return print("False")
is_even()
#5. is_odd function, first one is ez second one uses is_even()
def is_odd():
num = input("Enter a number to find out if odd: ")
number = is_even(num)
if int(number) % 2 != 0:
return print("True")
else:
return print ("False")
is_odd()
#6. only_evens function using is_even
#def only_evens()
#def only_evens(list):
#new_list = []
#for num in list:
#if num % 2 == 0:
#new_list.append(num)
#return print()
#only_evens([11, 20, 42, 97, 23, 10])
#7. only_odds function using is_odd
#def only_odds() | false |
429f9f55f17d32174ab5c856728622926b38c861 | juanmunoz00/python_classes | /ej_validate_user_input.py | 829 | 4.40625 | 4 | ##This code validates if the user's input is a number, it's type or it's a string
##So far no library's needed
##Method that performs the validation
def ValidateInput(user_input):
try:
# Verify input is an integer by direct casting
is_int = int(user_input)
print("Input is an integer: ", is_int)
except ValueError:
try:
# Verify input is a float by direct casting
if_float = float(user_input)
print("Input is a float: ", if_float)
except ValueError:
print("It's a string or NaN (Not a Number)")
user_input = 'i' ##Initilize
##User input will be solicited and validated until user types an enter
while( user_input.strip() != '' ):
user_input = raw_input("Please type a number. Enter to exit: ")
ValidateInput(user_input) | true |
1af6e34b568f7615ffbec35404ca39f4ba851c8b | gjf2a/date_triples | /date_triples.py | 540 | 4.125 | 4 | import calendar
def pythagorean_triple(a, b, c):
return a ** 2 + b ** 2 == c ** 2
def pythagorean_dates(start_year, end_year):
dates = []
c = calendar.Calendar()
for year in range(start_year, end_year + 1):
for month in range(1, 13):
for day in (d for d in c.itermonthdays(year, month) if d != 0):
if pythagorean_triple(day, month, year % 100):
dates.append((day, month, year))
return dates
if __name__ == "__main__":
print(pythagorean_dates(2000, 2099)) | false |
626dc70789de6e61963051996357f3ba6aae42e6 | noisebridge/PythonClass | /instructors/course-2015/errors_and_introspection/project/primetester4.py | 1,242 | 4.46875 | 4 | """
For any given number, we only need to test the primes below it.
e.g. 9 -- we need only test 1,2,3,5,7
e.g. 8 -- we need only test 1,2,3,5,7
for example, the number 12 has factors 1,2,3,6,12.
We could find the six factor but we will find the two factor first.
The definition of a composite number is that it is composed of primes, therefore it will always have a prime as a factor.
This prime test should have an index of all primes below i.
"""
total_range = 1000
primes = list()
def prime_test(i):
"""
Cases:
Return False if i is not prime
Return True if i is prime
Caveat: cannot test 1.
Caveat 2: Cannot test 2.
It is fortuitous that these tests both return true.
"""
for possible_factor in primes:
if i % possible_factor == 0:
return False
return True
for prime in range(2,total_range):
import timeit
# This isn't good enough, we'll have to use a context
# manager or something to set up and tear down the right
# prime list and current integer to test.
setup = "from __main__ import prime_test"
print(timeit.timeit("is_prime = prime_test(prime)", number=1, setup=setup))
if is_prime:
primes.append(prime)
print len(primes)
| true |
9c81264446ef2fd968208b79fd0d696409bb5f83 | noisebridge/PythonClass | /instructors/lessons/higher_order_functions/examples/closure1.py | 1,509 | 4.15625 | 4 | """
This example intentionally doesn't work.
Go through this code and predict what will happen, then run
the code.
The below function fixes i in the parent scope, which means
that the function 'f' 'gets updates' as i progresses through
the loop.
Clearly we need to somehow fix i to be contained in the local
scope for 'f'.
Original code at: http://eev.ee/blog/2011/04/24/gotcha-python-scoping-closures/
"""
if __name__ == "__main__":
"""
Only read the code the first time through.
Then read the comments after you see the results.
"""
# We'll append a bunch of functions into this list.
myfunctions = list()
for i in range(4):
"""
We'll use the namespace f repeatedly in this scope, but
the functions will actually be bound as indexed items in
our list. The 'f' name will be fresh in each loop.
"""
def f():
"""
Each time we build this function, we are fixing the
value i into the function from the parent scope.
Here we try and fail to fix a new value of i into the
function f each time through the loop. Why does it fail?
Note: in Python, child scopes have access to all parent
scopes up to the global scope, so be wary of this and
use it to your advantage where possible.
"""
print i
myfunctions.append(f)
i=7
for my_function in myfunctions:
my_function()
| true |
f412f50e278ad7ba058891a8e463625155bffdfb | noisebridge/PythonClass | /instructors/projects-2015/workshop_100515/quick_sort.py | 1,124 | 4.1875 | 4 | """ Quick Sort
Implement a simple quick sort in Python.
"""
# we'll use a random pivot.
import random
def my_sorter(mylist):
""" The atomic component of recursive quick sort
"""
# we are missing a base case
if len(mylist) == 1:
return mylist
# do we need this?
if len(mylist) == 0:
return mylist
pivot_index = random.choice(range(len(mylist)))
pivot = mylist[pivot_index]
left_side = mylist[0:pivot_index]
right_side = mylist[pivot_index+1:]
#print left_side, pivot, right_side
# can swap left and right once we find one in each, then append
# once we run out on one side.
right_side_2 = list()
left_side_2 = list()
for item in left_side+right_side:
if item > pivot:
right_side_2.append(item)
if item <= pivot:
left_side_2.append(item)
print "l:", left_side_2
print "p:", pivot
print "l+p:", left_side_2 + [pivot]
print "r:", right_side_2
return my_sorter(left_side_2) + [pivot] + my_sorter(right_side_2)
mylist = [4,6,5,9,2,3,1,8]
print mylist
print my_sorter(mylist)
| true |
9db3cd6f2fbadcfa1e558ac85e38bb1129f163b2 | noisebridge/PythonClass | /instructors/lessons/functions_and_gens/examples/example0.py | 618 | 4.1875 | 4 | #Return the absolute value of the number x. Floats as well as ints are accepted values.
abs(-100)
abs(-77.312304986)
abs(10)
#Return True if any element of the iterable is true. If the iterable is empty, return False.
any([0,1,2,3])
any([0, False, "", {}, []])
#enumerate() returns an iterator which yields a tuple that keeps count of the elements in the sequence passed.
#Since the return value is an iterator, directly accessing it isn't particularly useful.
from string import ascii_letters as ltrs
for index, letter in enumerate(ltrs):
print index, letter
print enumerate(ltrs)
print list(enumerate(ltrs)) | true |
9846b1a24c40d2da5e5737d15c2a92725560e7c0 | otobin/CSSI-stuff | /Python/Playground.py | 2,806 | 4.46875 | 4 | # #!/usr/bin/python
#
#
# # # # print("Hello, World!")
# # # #
# # # #
# # # #
# # # # i = 0
# # # #
# # # # while (i < 3):
# # # # num = int(input("Enter a number"))
# # # #
# # # # if num > 0:
# # # # print("This number is positive")
# # # # elif num < 0:
# # # # print("This number is negative")
# # # # else:
# # # # print("This number is 0")
# # # # i += 1
# # #
# # # greeting = "Hello, World!"
# # # for letter in greeting:
# # # print(letter.upper())
# # #
# # #
# # # for i in range(10, 5, -1):
# # # print(i)
# # #
# # #
# # # my_name = "Olivia"
# # # friend1 = "Jess"
# # # friend2 = "Julia"
# # # friend3 = "Ciera"
# # # friend4 = "Matthew"
# # #
# # # print("My name is " + my_name + " and my friends are " + friend1 + " , ")
# # # print("My name is %s and my friends are %s, %s, %s, and %s." %(my_name, friend1, friend2, friend3, friend4))
# # name = str(raw_input("Enter your name"))
# # adverb = str(raw_input("Enter an adverb"))
# # plural_noun = str(raw_input("Enter a plural noun"))
# # noun = str(raw_input("Enter another noun"))
# # noun2 = str(raw_input("Enter another noun"))
# # animal = str(raw_input("Enter an animal"))
#
#
#
# # print(("One day %s woke up and realized that they had slept through their alarm. %s sprinted to "
# # "the bus stop %s, dragging their %s behind them while shouting at the bus driver to stop. %s leaped over "
# # " a %s and almost bumped into a %s, desperate to not be late to school."
# # " Alas, the bus driver drove away, leaving %s to ride their %s to school.")
# # %(name, name, adverb, plural_noun, name, noun, noun2, name, animal))
#
# def greetSecretAgent(first_name, last_name):
# return ("%s, %s %s") %(last_name, first_name, last_name)
#
# greeting = greetSecretAgent("Olivia", "Tobin")
# print(greeting)
# def mystery1(a):
# return a + 5
#
# def mystery2(b):
# return b * 2
#
# result = mystery1(mystery2(3))
#
#
# def mystery(word, number):
# number = number * 2
# word = word.upper()
# return word * number #you can't multiply two strings
#
# print(mystery("2", "he"))
friends = ["Olivia", "Jackelen",
"Phoebe", "Savion"]
myName = "olivia"
print("My name is %s and I have %s friends" %(myName, len(friends)))
friends.append("Areeta")
friends.insert(1, "Logan")
friends.remove("Areeta")
print("My friends are: ")
for i in range(0,len(friends)):
if (i == 0):
print(friends[0]),
else:
print("and " + friends[i])
print(range(4))
for friend in friends:
print(friend)
# for i in range(0, len(friends)):
# print(friends[i])
#
#
# tableGroups = [["Olivia", "Savion"], ["Jackelen", "Phoebe"]]
#
# for i in range(0, len(tableGroups)):
# for j in range(0, len(tableGroups[i])):
# print(tableGroups[i][j])
| false |
908accf654cd559a95b1ce89dd9b4b1e332cabe1 | makcipes/budg-intensive | /day_1/scope/task_1/question.py | 580 | 4.25 | 4 | """
Что будет выведено после выполнения кода? Почему?
"""
x = 42
def some_func():
global x
x = x + 1
print(x)
some_func()
print(x)
"""выведет 2 раза чилсло 43 тк в функции мы определили глобальную переменную и прибавили к ней единицу
тоесть, при выполнении some_func мы прибавили единицу к числу , a print не переопределяет переменную и также выведет 43""" | false |
3d7581fb9378298bd491df6a5f54063a659ae965 | PhuocThienTran/Learning-Python-During-Lockdown | /30DaysOfPython/chapter6/strings.py | 720 | 4.125 | 4 | word = "Ishini"
def backward(word):
index = len(word) - 1
while index >= 0:
print(word[index])
index -= 1
backward(word)
fruit = "apple"
def count(fruit, count):
count = 0
for letter in fruit:
if letter == "p":
count = count + 1
print("Amount of p:", count)
count(fruit,"p")
q4_word = "tennakoon"
print("Amount of n: ", q4_word.count("n"), "Amount of o: ", q4_word.count("o"))
str = "X-DSPAM-Confidence:0.8475"
colon = str.find(":")
print("Find the index of (:)", colon)
last_num = str.find("5")
print("Find the index of 5: ", last_num)
slice_str = str[colon+1:last_num] #start from colon + 1 to get number 0
print("Convert str to float", float(slice_str))
| true |
b1d766d3d8a6a7635f7c928e085844594e0eb329 | PhuocThienTran/Learning-Python-During-Lockdown | /30DaysOfPython/chapter5/iteration.py | 1,479 | 4.3125 | 4 | import math
n = 5
while n > 0:
print(n)
n =- 1
print("Launched!")
while True:
line = input('> ')
if line == 'done':
break #this means if input is "done" -> break the while loop
print(line)
print('Done!')
while True:
usr_line = input('> ')
if usr_line[0] == '#':
continue #finish the current # iteration input, then jump to the next iteration which is the next input without the #
if usr_line == 'done':
break
print(usr_line)
print('Done!')
friends = ['John', 'Barnaby', 'Thien']
for friend in friends:
print('Happy New Year:', friend)
print('Done!')
#questions
total = 0
count = 0
average = 0
while True:
number = input("Enter a number: ")
try:
if number == "done":
break
total += float(number)
count += 1
average = total / count
except:
print("bad data")
print ("Total: ", total, "Count: ", count, "Average: ", average)
numbers = []
while True:
num = input("Enter a number: ")
try:
if num == "done":
break
else:
numbers.append(int(num))
except:
print("bad data")
print("Max: ", max(numbers))
print("Min: ", min(numbers))
#Important:
"""
We call the while statement
an indefinite loop because it simply loops until some condition becomes False,
whereas the for loop is looping through a known set of items so it runs through
as many iterations as there are items in the set.
"""
| true |
425a7de115ec728612aa7bdbbe81d2b3c0395fe3 | pujaaryal89/PythonAssignment | /function/function1.py | 555 | 4.125 | 4 | def max_num(num_list):
largest_num=num_list[0]
for num in num_list[1:]:
if num >largest_num:
largest_num=num
return largest_num
number = input('Enter a number separate by comma: ').split(',')
# print(number)
#split le pailai , bata split garera list ma leraauxa
num=[int(x) for x in number]
#Ahh harek item lai for loop bata tanera int ma one by one convert garera arko naya list ma haleko
# print(num)
print(f"The numbers are:{num}")
largest_num=max_num(num)
print(f"The largest numbers is:{largest_num}")
| false |
ad1894bc97e870b14a06d8dd46bcc6ff9875cdb5 | rakshithvasudev/Datacamp-Solutions | /Recommendation Engines in Pyspark/How ALS works/ex16.py | 606 | 4.28125 | 4 | """
Get RMSE
Now that you know how to build a model and generate predictions, and have an evaluator to tell us how well it predicts ratings, we can calculate the RMSE to see how well an ALS model performed. We'll use the evaluator that we built in the previous exercise to calculate and print the rmse.
Instructions
100 XP
Call the .evaluate() method on our evaluator to calculate our RMSE on the test_predictions dataframe. Call the result RMSE.
Print the RMSE
Take Hint (-30 XP)
"""
# Evaluate the "test_predictions" dataframe
RMSE = evaluator.evaluate(test_predictions)
# Print the RMSE
print (RMSE) | true |
c34d4873e498d568971b362d20e40af0a16d0a16 | kopxiong/Leetcode | /sort/python3/01_bubble_sort.py | 1,315 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# 冒泡排序 (Bubble Sort) 是一种简单的排序算法。它重复地走访过要排序的数列,一次比较两个元素,
# 如果他们的顺序错误就把他们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。
# 这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。
# Time complexity: O(n^2)
class Solution(object):
def bubbleSort(self, lists):
n = len(lists)
# after each iteration, the last element is the maximum
for i in range(n-1):
flag = True
for j in range(n-1-i):
if lists[j] > lists[j+1]:
# swap, doesn't use temp because Python passes by reference (pointer in C++)
# shallow copy vs copy.deepcopy in Python
lists[j], lists[j+1] = lists[j+1], lists[j]
flag = False
print("current lists: ", lists)
# if no exchange, return arr or lists
if flag:
return lists
return lists
if __name__ == '__main__':
lists = [32, 64, 1, 4, 98, 23, 8, 46, 10, 90]
#lists = [9, 8, 7, 6, 5, 4, 3, 2, 1]
print(Solution().bubbleSort(lists))
| false |
5e5e7df63660f904a45f4350df321e9ce8d600c0 | tbeaux18/rosalind | /point_mutation.py | 1,127 | 4.34375 | 4 | #!/usr/bin/env python3
"""
@author: Timothy Baker
@version: 01/15/2019
Counting Point Mutations Rosalind
Input:
Standard Input
Output:
Console
"""
import sys
def hamming_distance(sequence_one, sequence_two):
""" Calculates hamming distance between 2 strings
Args:
sequence_one (str) : sequence of ACGT
sequence_two (str) : sequence of ACGT
Returns:
Hamming distance (int) : number of mismatches between 2 strings
"""
count = 0 #initialize the count to 0
for n_1, n_2 in zip(sequence_one, sequence_two): #iterates through 2 sequences
if n_1 != n_2: #checks equality against each nucleotide
count += 1 # if not equal adds 1 to the count
return count
def main():
""" Takes standard input of two sequences and prints the hamming hamming_distance
to the console
"""
lines = [x.rstrip() for x in sys.stdin.readlines()] # converts std input into list
first_sequence = lines[0]
second_sequence = lines[1]
print(hamming_distance(first_sequence, second_sequence))
if __name__ == '__main__':
main()
| true |
22cfe29daf5a9adca5e908e8c4fda15132536133 | sapalamut/homework | /ClassWork_4.py | 1,764 | 4.25 | 4 | # FUNCTIONS
# Ex:1
def add_two_numbers(num1, num2):
return num1 + num2
result = add_two_numbers(1, 2)
print(result)
print(add_two_numbers(1, 2))
first = 1
second = 2
third = 3
print(add_two_numbers(first, second), add_two_numbers(second, third))
print('\n')
# Ex:2
def print_hello_world():
print("Hello Wolrd")
print_hello_world()
# Ex:3
def box(six, five):
return six * five
box_ad = box(6, 5)
print(box(6, 5))
print('\n')
# Ex:4
def math_class(first_num, second_num, third_num):
return (first_num + second_num) // third_num
ent_frst = int(input('Enter the first number please: '))
ent_second = int(input('Enter the second number please: '))
ent_thhird = int(input('Enter the third number please: '))
print('The total sum is: ',math_class(ent_frst, ent_second, ent_thhird))
print('\n')
# Ex:5
def even_or_odd(number):
if number % 2 == 0:
return "Even"
return "Odd"
print_num = int(input("Enter a number: "))
print(even_or_odd(int(float(print_num))))
print('\n')
# Ex:6
def two_numbers(num1, num2):
return num1 + num2
print(two_numbers(1, 2))
# Ex:7
summing = 0
def add_numbers(num1, num2):
summing = num1 + num2
add_numbers(5,6)
print(summing)
# Ex:8
def two_numbers(num1, num2 = 9):
return num1 + num2
print(two_numbers(1,))
# Ex:9
def currency_amount(amount, currency="USD"):
amount = str(amount)
if currency == "JPY":
return "¥" + amount
elif currency == "USD":
return "$" + amount
elif currency == "EUR":
return "€" + amount
else:
return amount
print(currency_amount(5, "JPY"))
#Ex:10
def check_balance(balance, entr_amount):
entr_amount = int(input('Taxes are: '))
if entr_amount <= balance:
return True
else:
return False
print(check_balance(400, 1000)) | true |
ca6f5f7bb7fc627f7278170fecbb630e5a00ec7c | RRRustik/Algorithms | /alg_lesson_1.8.py | 567 | 4.21875 | 4 | """8. Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого)."""
n1 = int(input("Введите первое число: "))
n2 = int(input("Введите второе число: "))
n3 = int(input("Введите третье число: "))
if n1 > n2 and n1 < n3:
print(f'{n1} - среднее число')
elif n2 > n1 and n2 < n3:
print(f'{n2} - среднее число')
else:
print(f'{n3} - среднее число')
| false |
44d2fe6c8ff90183d9826fdb89850085071f2f32 | darrenrs/ica-projects | /ICA Creative Applications/Python/Python Turtle/main.py | 1,766 | 4.1875 | 4 | import turtle
import math
'''
void drawLine(int x, int y):
draws a single line
'''
def drawLine(x, y):
turtle.penup()
turtle.setposition(x, y)
turtle.pendown()
turtle.forward(math.sqrt(50**2+50**2))
'''
void drawSquare(int x, int y, int d):
draws a square
'''
def drawSquare(x, y, d):
turtle.setposition(x, y)
turtle.pendown()
for i in range(4):
turtle.forward(d)
turtle.right(90)
turtle.penup()
## FIRST, THE LETTER
print(turtle.heading())
turtle.color("#FF0000")
turtle.speed(0)
turtle.circle(100, 180)
turtle.left(90)
turtle.forward(200)
turtle.penup()
turtle.setposition(15, 20)
turtle.left(90)
turtle.pendown()
turtle.circle(80, 180)
turtle.left(90)
turtle.forward(160)
##
turtle.penup()
turtle.setposition(-50, -50)
turtle.left(90)
turtle.pendown()
turtle.circle(100, 180)
turtle.left(90)
turtle.forward(200)
turtle.penup()
turtle.setposition(-35, -30)
turtle.left(90)
turtle.pendown()
turtle.circle(80, 180)
turtle.left(90)
turtle.forward(160)
##
turtle.left(135)
turtle.forward(math.sqrt(50**2+50**2))
drawLine(-50, -50)
drawLine(-50, 150)
drawLine(-35, 130)
drawLine(50, 50)
drawLine(20, -20)
drawLine(20, 120)
turtle.penup()
## NEXT, THE CUBE
turtle.setposition(0)
turtle.seth(270)
print(turtle.heading())
drawSquare(-50, -50, 50)
drawSquare(0, 0, 50)
turtle.speed(5)
turtle.setposition(-50, -100)
turtle.pendown()
turtle.left(135)
turtle.forward(math.sqrt(50**2+50**2))
turtle.penup()
'''
turtle.setposition(-50, -50)
turtle.pendown()
turtle.forward(math.sqrt(50**2+50**2))
turtle.penup()
'''
turtle.setposition(-100, -50)
turtle.pendown()
turtle.forward(math.sqrt(50**2+50**2))
turtle.penup()
turtle.setposition(-100, -100)
turtle.pendown()
turtle.forward(math.sqrt(50**2+50**2))
turtle.penup() | false |
7dd17ad1a08aa1fe100a432bdb76f3fea11b371c | andreferreira4/Programa-o1 | /ficha 2 entregar/ex2.py | 799 | 4.21875 | 4 | #Exercício2
Numero1 = int(input("Escreva o primeiro número "))
Numero2 = int(input("Escreva o segundo número "))
Numero3 = int(input("Escreva o terceiro número "))
if Numero1 > Numero2 and Numero2 > Numero3 :
print("{} > {} > {}".format(Numero1,Numero2,Numero3))
elif Numero1 > Numero2 and Numero1 > Numero3 :
print("{} > {} > {}".format(Numero1,Numero3,Numero2))
elif Numero2 > Numero1 and Numero1 > Numero3 :
print("{} > {} > {}".format(Numero2,Numero1,Numero3))
elif Numero2 > Numero1 and Numero2 > Numero3 :
print("{} > {} > {}".format(Numero2,Numero3,Numero1))
elif Numero3 > Numero2 and Numero2 > Numero1 :
print("{} > {} > {}".format(Numero3,Numero2,Numero1))
elif Numero3 > Numero2 and Numero3 > Numero1 :
print("{} > {} > {}".format(Numero3,Numero1,Numero2))
| false |
5766534c0e915f055d9fdfe3d2451303ddfbc1d7 | zs18034pn/ORS-PA-18-Homework07 | /task2.py | 727 | 4.375 | 4 |
"""
=================== TASK 2 ====================
* Name: Recursive Sum
*
* Write a recursive function that will sum given
* list of integer numbers.
*
* Note: Please describe in details possible cases
* in which your solution might not work.
*
* Use main() function to test your solution.
===================================================
"""
# Write your function here
def recursive_function(given_list):
if not given_list:
return 0
return given_list[0] + recursive_function(given_list[1:])
def main():
# Test your function here
example_list = [2, 2, 3, 4, 5]
print("The sum of the given list is: ", recursive_function(example_list))
pass
if __name__ == "__main__":
main()
| true |
d93b00c503f7cf24933359240b330423efc511e2 | Chris-uche/Pythonbasics | /Work/loops.py | 670 | 4.15625 | 4 | for x in range(0,10,2): #start,stop,step
print(x)
#The While Loop section
uche = True
while uche:
name = input("insert something here: ")
if name == "stop":
uche = False
break
Fredschoolname = True
while Fredschoolname:
nameOfschool =input("insert Fred's schoool name: ")
if nameOfschool == "FUTO":
break
MastersProgram = True
while MastersProgram:
classOfDegree = input("What class of Degree: ")
if classOfDegree == "Distinction":
break
school = ["FUTO","Uniport","EmbryRiddle","Caltech"]
for college in school:
if college != "Caltech":
print(college)
else:
print("Caltech") | false |
bbf65e88dffba753cd3ae13fef8d76c2e6439692 | CodeBall/Learn-Python-The-Hard-Way | /yanzilu/ex32.py | 2,647 | 4.4375 | 4 | # -*- coding: utf-8 -*-
#Exercise 32:Loops and List
the_count = [1,2,3,4,5]
fruits = ['apples','oranges','pears','banana']
change = [1,'pennies',2,'dimes',3,'quarters']
print "change[0]: ", change[0]
print "change[2:5]: ", change[2:5]
#this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" %number
#same as above
for fruit in fruits:
print "A fruit of type:%s"%fruit
#also we can go through mixed lists too
#notice we have to use %r since we don't know what's in it
for i in change:
print "I got %r"%i
#we can also build lists,first start with an empty one
elements = []
#then use the range function to do 0 to 5 counts
for i in range(0,6):
print "Adding %d to the list."% i
#append is a function that lists understand
elements.append(i)
#now we can print them out too
for i in elements:
print "Element was : %d" % i
print "the_count[3]:",the_count[3]
the_count[3] = 2015
print "the_count[3]:",the_count[3]
the_count[3] = 'The_count'
print "the_count[3]:",the_count[3]
print the_count
del the_count[3]
print "After deleting value at index 3 : "
print the_count
#计算the_count列表的长度
print len(the_count)
#组合两个列表
list1 = the_count + fruits
print list1
#循环列表元素
list2 = fruits * 3
print list2
#查看某一个元素是否存在于列表中
flag = 7 in the_count
print flag
flag = 'banana' in fruits
print flag
#迭代效果
for x in change:
print x
#比较两个列表的元素
print "Compare the_count and fruits"
print cmp(the_count,fruits)
print "Compare the_count and the_count"
print cmp(the_count,the_count)
print "Compare fruits and the_count"
print cmp(fruits,the_count)
#返回列表元素最大最小值
print "change max is:",max(change)
print "change min is:",min(change)
#在列表末尾添加新的对象
change.append(2015)
print "new change is:",change
#统计某个元素在列表中出现的次数
print change.count(1)
#在列表末尾一次性追加另一个序列的多个值
print "old change is :",change
change.extend(the_count)
print "new change is :",change
#从列表中找出某个值第一个匹配项的索引位置
print "the first 1 in change is :",change.index(1)
#将对象插入列表
#指在第一个参数的位置插入第二个参数
change.insert(3,'love')
print change
#移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
print change.pop()
#移除列表中某个值的第一个匹配项
change.remove(3)
print change;
#反向列表中元素
change.reverse()
print change;
#对原列表进行排序,默认按照从小到大顺序
change.sort()
print change
| true |
6248d8ced78cf9b217c28b88189424dae0b41e01 | starschen/learning | /data_structure/binaryTreeTravle.py | 2,590 | 4.21875 | 4 | #encoding:utf8
#二叉树的遍历(前、中、后)
#代码来源:http://blog.csdn.net/littlethunder/article/details/9707669,仅学习用
class Node:
def __init__(self,value=None,left=None,right=None):
self.value=value
self.left=left
self.right=right
#此部分为后加,代码来源http://www.cnblogs.com/sunada2005/p/3326160.html
class BinaryTree(object):
def __init__(self):
self.root=Node()
def add(self,value):
node=Node(value)
if self.isEmpty():
self.root=node
else:
tree_node=self.root
queue=[]
queue.append(self.root)
while queue:
tree_node=queue.pop(0)
if tree_node.left==None:
tree_node.left=node
return
elif tree_node.right==None:
tree.node.right=node
return
else:
queue.append(tree_node.left)
queue.append(tree_node.right)
def preTraverse(root):
if root==None:
return
print root.value
preTraverse(root.left)
preTraverse(root.right)
def midTraverse(root):
if root==None:
return
midTraverse(root.left)
print root.value
midTraverse(root.right)
def afterTraverse(root):
if root==None:
return
afterTraverse(root.left)
afterTraverse(root.right)
print root.value
if __name__=='__main__':
root=Node('D',Node('B',Node('A'),Node('C')),Node('E',right=Node('G',Node('F'))))
print '前序遍历:'
preTraverse(root)
print '中序遍历:'
midTraverse(root)
print '后序遍历:'
afterTraverse(root)
print '\n'
#已知先序遍历结果和中序遍历求后序遍历
preList=list('DBACEGF')
midList=list('ABCDEFG')
afterList=[]
def findTree(preList,midList,afterList):
if len(preList)==0: #树为空时
return
elif len(preList)==1: #树只有根结点
afterList.append(preList[0])
return
root=preList[0] #前序遍历的第一个元素为根结点
n=midList.index(root) #在中序遍历中找到根结点所在的位置,结点左为左子树,右为右子树
#前序遍历中第1到n的元素左子树,同时1为左子树的根
findTree(preList[1:n+1],midList[:n],afterList) #这部分不太能理解,midList不应该是左子树范围吗?
findTree(preList[n+1:],midList[n+1:],afterList)
afterList.append(root)
return afterList
print findTree(preList,midList,afterList)
| false |
7b7ea0f2690579220e1dd50f8151e0214c950ec8 | hxsnow10/BrainNN | /SORN/general_model.py | 2,398 | 4.15625 | 4 | '''一个general的RNN
应该定义的计算结构
'''
class RNN(SimpleRecurrent):
'''
some abstract model to define structural RNN.
abstracts of RNN is dynamic systems, all variables has it's dynamics, \
when in NN some as states some as weights.
when NN become more complex, for example biology models, LSTM, multi\
scale weights, simple RNN return complex dynamics, although we can
say neuron and weights becom more complex.
here we follow some iteration uodates form. given compoments(states),
states updates (network), learning rule(weights update rule)
Parameters
------------
Example
-----------
inputs=tensor.vector()
en_states=
in_states=
out=
SORN=RNN([],
'''
@lazy(allocation=['dim'])
def __init__(self, compoments,compoments_type,weights, states_update,weight **kwargs):
self.compoments = compoments
self.states=states#TODO
self.weights=weights
self.states_update=states_update
self.weights_update=weights_update
children = [activation]
kwargs.setdefault('children', []).extend(children)
super(SimpleRecurrent, self).__init__(**kwargs)
def get_dim(self, name):
if name == 'mask':
return 0
if name in (SimpleRecurrent.apply.sequences +
SimpleRecurrent.apply.states):
return self.dim
return super(SimpleRecurrent, self).get_dim(name)
def _allocate(self):
def _initialize(self):
for weights in self.parameters[:5]:
self.weights_init.initialize(weights, self.rng)
@recurrent(sequences=['inputs', 'mask'],
states=['states', 'weights'],
outputs=['output'], contexts=[])
def apply(self, inputs, states, weights, mask=None, updates=True):
"""Apply the simple transition.
"""
next_states = self.states_updates(states, weights)
next_weights = self.weights_updates(states, weights, next_states)
return next_states, next_weights
@application(outputs=apply.states)
def initial_states(self, batch_size, *args, **kwargs):
return tensor.repeat(self.initial_states_E[None, :], batch_size, 0),
tensor.repeat(self.initial_states_I[None, :], batch_size, 0),
[tesnor.repeat(p) for p in self.parameters[:5]]
| true |
5081fb1aabe670d901a8215ac85d44233bf715b2 | biroska/Python-Study | /repeticao/DigitoAdjacente.py | 982 | 4.1875 | 4 | # Este programa contempla a resolução do primeiro exercício opcional do curso:
# Introdução à Ciência da Computação com Python Parte 1
# Disponível no coursera.
#
# EXERCÍCIO OPCIONAL 2
# Escreva um programa que receba um número inteiro na entrada e verifique se o número
# recebido possui ao menos um dígito com um dígito adjacente igual a ele. Caso exista,
# imprima "sim"; se não existir, imprima "não".
strNumero = input("Digite um número inteiro: ")
numero = int( strNumero )
digitoAnterior = -1000
proximoDigito = 1
count = 0
isAdjacente = False
qtdCaracteres = len( strNumero )
while not isAdjacente and count < qtdCaracteres:
proximoDigito = numero % 10
if proximoDigito == digitoAnterior:
isAdjacente = True
else:
digitoAnterior = proximoDigito
numero = numero // 10
count = count + 1
if isAdjacente:
print("sim")
else:
print("não") | false |
089ff3c062a5b18c9f1c318561e8603d5ddc62ee | biroska/Python-Study | /condicionais/Ordenados.py | 633 | 4.34375 | 4 | # Este programa contempla a resolução do primeiro exercício opcional do curso:
# Introdução à Ciência da Computação com Python Parte 1
# Disponível no coursera.
#
# EXERCÍCIO 5
# Receba 3 números inteiros na entrada e imprima crescente se eles forem dados em
# ordem crescente. Caso contrário, imprima não está em ordem crescente
numero1 = int( input("Forneca um numero: ") )
numero2 = int( input("Forneca um numero: ") )
numero3 = int( input("Forneca um numero: ") )
if ( numero3 > numero2 and numero2 > numero1 ):
print( "crescente" )
else:
print( "não está em ordem crescente" ) | false |
176fb212620acdcf861e9999a496d699c730fc11 | biroska/Python-Study | /repeticao/SomaDigitos.py | 511 | 4.1875 | 4 | # Este programa contempla a resolução do primeiro exercício opcional do curso:
# Introdução à Ciência da Computação com Python Parte 1
# Disponível no coursera.
#
# EXERCÍCIO 2
# Escreva um programa que receba um número inteiro na entrada, calcule e imprima
# a soma dos dígitos deste número na saída
n = int( input("Digite um número inteiro: ") )
aux = n
soma = 0
while aux > 0:
soma = soma + ( aux % 10 )
aux = aux // 10
print(soma)
| false |
14211c899a064cff7330fba2bd74711c4dc0dda6 | monkeesuit/Intro-To-Python | /scripts/trialdivision.py | 479 | 4.15625 | 4 |
num = int(input('Enter a numer to be check for primality: '))
ceiling = int(pow(num, .5)) + 1 # Get ceiling of sqaure root of number (b/c of how range works
for i in range(2, ceiling):
if (num % i == 0): # if any number between 2 and ceiling-1 divides num
print('{} is composite'.format(num)) # then num is a composite unmber
break
else: # if we make it through the loop then the number is prime
print('{} is prime'.format(num))
| true |
924e46c90bc31ed5fd44ccc3da128734d006fb1a | martincxx/PythonPlay | /PythonforAstronomers/exercise2.py | 356 | 4.125 | 4 | """2. Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise.
2.1. Use the module re (regular expressions)"""
def find_m(word):
import re
if re.match("[aeiou]$",word.lower()):
return True
else:
return False
print find_m("A")
print find_m("x")
print find_m("0")
| true |
87031f94d2855382675da6a49829599fca6792a5 | poojan14/Python-Practice | /Automate the boring stuff with python/Pattern_Matching_With_Regular_Expressions/Regex Version of strip().py | 443 | 4.1875 | 4 | import re
def strip(string , sep = None):
if sep == None:
sep = '\s'
return re.sub(r'^[{0}]+|[{0}]+$'.format(sep),'',string) #first {0} is replaced by {sep}
if __name__ == '__main__':
string = input('Enter string : ')
sep = input('Enter character to be stripped from both sides --> ')
if sep == '':
print(strip(string))
else:
print(strip(string,sep))
| false |
0902f72d26a0a9cc71e41dfa76f0b5b7e62bf07e | poojan14/Python-Practice | /GeeksForGeeks/Good or Bad string.py | 1,378 | 4.125 | 4 | '''
In this problem, a String S is composed of lowercase alphabets and wildcard characters i.e. '?'. Here, '?' can be replaced by any of the
lowercase alphabets. Now you have to classify the given String on the basis of following rules:
If there are more than 3 consonants together or more than 5 vowels together, the String is considered to be "BAD". A String is considered
"GOOD" only if it is not “BAD”.
'''
def vowel(char):
if char == 'a' or char == 'e' or char == 'i' or char == 'o' or char == 'u':
return True
return False
if __name__ == '__main__':
T = int(input())
for _ in range(T):
s = input()
conscount , vowcount = 0,0
maxcons ,maxvow = 3 , 5
bad = False
for ch in s:
if vowel(ch):
conscount = 0
vowcount+=1
if vowcount > maxvow :
bad = True
break
elif ch == '?':
vowcount+=1
conscount+=1
if vowcount > maxvow or conscount > maxcons :
bad = True
break
else:
vowcount = 0
conscount+=1
if conscount > maxcons :
bad = True
break
if bad:print(0)
else : print(1)
| true |
def77432cc97bb70a22c8e37b0e237b05f3dbb9e | poojan14/Python-Practice | /Data Structures and File Processing/Heap/Heap_Class.py | 2,756 | 4.25 | 4 | import math
class Heap:
heap=[]
def __init__(self):
'''
Objective : To initialize an empty heap.
Input parameters :
self : Object of class Heap.
Output : None
'''
#Approach : Heap is an empty list.
self.heap=[]
def HeapInsert(self,e):
'''
Objective : To insert an element in a heap.
Input :
self : Object of class Heap.
e: Element to be inserted in the list.
Output : None
Side Effect : Element is inserted at proper position.
'''
#Approach : Element is compared with its parent node and if it is larger then swap them and continue.
if self.heap==[]:
self.heap.append(e)
else:
self.heap.append(e)
index=len(self.heap)-1
while index>0:
parent=math.floor((index-1)//2)
if e>self.heap[parent]:
self.heap[index]=self.heap[parent]
index=parent
else:
break
self.heap[index]=e
def HeapDelete(self):
'''
Objective : To delete element at the root node of heap.
Input :
self : Object of class Heap.
Output : None
Side Effect : Element is removed from root node and remaining elements constitue heap.
'''
#Approach : Remove first element from heap and place the last element at its proper position in heap.
self.heap[0]=self.heap[-1]
self.heap.pop()
index=0
val=self.heap[0]
while index<len(self.heap):
child1=2*index+1
child2=2*index+2
if child1>len(self.heap)-1 : break
if child1<len(self.heap) and child2>=len(self.heap): maxchild=self.heap[child1]
else : maxchild=max(self.heap[child1],self.heap[child2])
if maxchild==self.heap[child1]:
if maxchild>val:
self.heap[index]=maxchild
index=child1
else:
break
else:
if maxchild>val:
self.heap[index]=maxchild
index=child2
else:
break
self.heap[index]=val
def __str__(self):
'''
Objective : To print heap object.
Input parameters :
self : Object of class Heap.
Output : string representation of heap object.
'''
#Approach : use print() function.
return str(self.heap)
| true |
617d3cdc74bcc4d7f1cd3489881efb9da784dfcc | bilaer/Algorithm-And-Data-Structure-Practices-in-Python | /heap_sort.py | 1,922 | 4.25 | 4 | ####################################
# Heap Sort #
# ##################################
# #
# Max_heapify: O(lgn) #
# Build_max_heap: O(n) #
# Overall performance is O(nlgn) #
# #
####################################
import math
# Calculate the index of left child of certain root
def get_left_child(l, index):
if index == 0:
return 1
else:
return 2*index + 1
# Calculate the index of right child of certain root
def get_right_child(l, index):
if index == 0:
return 2
else:
return 2*(index + 1)
# Exchange the values in two places of a given list
def swap(l, i, j):
temp = l[i]
l[i] = l[j]
l[j] = temp
# Change a heap into the max heap
def max_heapify(l, index, heap_size, depth=0):
indent = " "*depth
left = get_left_child(l, index)
right = get_right_child(l, index)
largest = index
if left < heap_size and l[left] > l[largest]:
largest = left
if right < heap_size and l[right] > l[largest]:
largest = right
# If root don't have largest values, change the value with
# it's child which has the largest value and do the recursion
if largest != index:
swap(l, index, largest)
print(indent + "the index of largest: %d\n" %(largest))
max_heapify(l, largest, heap_size, depth+1)
else:
return
def build_max_heap(l):
heap_size = len(l)
for index in range(math.ceil(len(l)/2), -1, -1):
print("the index: %d\n" %(index))
max_heapify(l, index, heap_size)
def heap_sort(l):
# Exchange the value at the end of the list to the font and build the list again
build_max_heap(l)
heap_size = len(l)
for i in range(len(l)-1, 0, -1):
swap(l, i, 0)
heap_size = heap_size - 1
max_heapify(l, 0, heap_size)
| true |
1be2eb9e19b8341b6622460623edd22664d8f5f2 | pawloxx/CodeWars | /CreditCardValidifier.py | 1,340 | 4.34375 | 4 | """
Make a program that sees if a credit card number is valid or not.
Also the program should tell you what type of credit card it is if it is valid.
The five things you should consider in your program is: AMEX, Discover, VISA, Master, and Invalid :
Discover starts with 6011 and has 16 digits,
AMEX starts with 34 or 37 and has 15 digits,
Master Card starts with 51-55 and has 16 digits,
VISA starts with 4 and has 13 or 16 digits.
"""
def credit(num):
number_as_string = str(num)
number_length = len(number_as_string)
providers_list = ['VISA', 'MasterCard', 'AMEX', 'Discover', 'Invalid']
#VISA
if (number_as_string[0] == '4' and (number_length == 13 or number_length == 16)):
return providers_list[0]
#MasterCard
elif int(number_as_string[:2]) in range(51, 56) and number_length == 16:
return providers_list[1]
#AMEX
elif int(number_as_string[:2]) in (34, 37) and number_length == 15:
return providers_list[2]
#Discover
elif number_as_string[:4] == '6011' and number_length == 16:
return providers_list[3]
#Invalid
else:
return providers_list[4]
"""
assert(credit(6011364837263748), "Discover")
assert(credit(5318273647283745), "MasterCard")
assert(credit(12345678910), "Invalid")
assert(credit(371236473823676), "AMEX")
assert(credit(4128374839283), "VISA")
""" | true |
ef4501237a29658db20410fa1825da1346b56483 | ArnoldCody/Python-100-exercise | /exercise6.py | 1,066 | 4.21875 | 4 | # coding=utf-8
"""
题目:斐波那契数列。
程序分析:斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……。
在数学上,费波那契数列是以递归的方法来定义:
F0 = 0 (n=0)
F1 = 1 (n=1)
Fn = F[n-1]+ F[n-2](n=>2)
"""
"""
# 这个函数可以输出制定从 0~i 的数列,比较省内存,计算 i 很大的时候很快得出结果
def Fib(i):
Fib = []
Fib.append(0)
Fib.append(1)
n = 2
while n <= i:
Fib.append(Fib[n-1]+Fib[n-2])
n += 1
return Fib[i-1]
i = int(raw_input("input a number: "))
print "the %dth number in Fibonacci sequence is %d." % (i, Fib(i))
"""
# 更简单的函数,但只能输出制定位置的菲波那切数,但是很占用内存
def Fib(i):
if i==0:
return 0
elif i==1:
return 1
else:
return Fib(i-2) + Fib(i-1)
i = int(raw_input("input a number: "))-1
print "the %dth number in Fibonacci sequence is %d." % (i+1, Fib(i))
| false |
b5c453b32461e11eb27c42b38ca495a94a33124a | ArnoldCody/Python-100-exercise | /exercise4.py | 1,134 | 4.1875 | 4 | # coding:utf-8
# 题目:输入某年某月某日,判断这一天是这一年的第几天?
birthday = raw_input("please input birthday, like yyyymmdd: ")
# 检验是否为闰年
def leap_year(year):
if year%4 == 0:
return True
else:
return False
# 定义每月的天数
def month_has_days(month):
for i in [1, 3, 5, 7, 9, 10, 12]:
if month == i:
days = 31
for i in [4, 6, 8, 11]:
if month == i:
days = 30
if month == 2:
if leap_year:
days = 28
else:
days = 29
return days
# 提取年月日
year = int(birthday[0:4])
day = int(birthday[6:8])
month = int(birthday[4:6])
# 检验输入日期是否正确
while month<1 or month>12 or day<1 or day>31:
print "error"
birthday = raw_input("please input birthday, like yyyymmdd: ")
year = int(birthday[0:4])
day = int(birthday[6:8])
month = int(birthday[4:6])
# 计算天数
days = day
while month > 1:
month = month - 1
days += month_has_days(month)
# print days
print "your birhtday is the %dth day in year %d." %(days, year)
| false |
22523d88e2faa931e6535429110634ab47a564e0 | Megatech13/Pythontutor | /Lesson 1. Data input and output/1. Problem Sum of three numbers.py | 451 | 4.125 | 4 | # Условие
# Напишите программу, которая считывает три числа и выводит их сумму. Каждое число записано в отдельной строке.
a = int(input())
b = int(input())
c = int(input())
print(a + b + c)
# Если аргументов намного больше, то можно так
# c = 0
# for i in range(10):
# a = int(input())
# c += a
# print(c) | false |
1721135b50b49c0cfb109712ce9355a7695bb438 | Jaykb123/jay | /jay1.py | 831 | 4.5 | 4 |
print("To check the greater number from the given number!".center(70,'-'))
# To take a numbers as an input from the user.
first_num = int(input("Enter the first number: "))
second_num = int(input("Enter the second number: "))
third_num = int(input("Enter the third number: "))
# To check among the numbers which is greatest.
# We do this using if,else condition
if first_num > second_num and first_num > third_num:
print("The first number is the greatest among other numbers which is " ,first_num)
elif second_num > first_num and second_num > third_num:
print("The second number is the greatest among other numbers which is " ,second_num)
else:
print("The first number is the greatest among other numbers which is " ,third_num)
print("Program Over!!".center(70,'-'))
| true |
8f711d9c3fd1c55bad77a4a1980c5d6a4bea22c6 | tusharpl/python_tutorial | /max_value_function.py | 502 | 4.125 | 4 | # Get the list of values ..here it is student scores
student_scores = input("Enter the list of student scores").split()
# change str to integer so that calculations can be done
for n in range(0, len(student_scores)):
student_scores[n] = int(student_scores[n])
print(student_scores)
# find max value through iteration instead of function
max_score = 0
for score in student_scores:
if ( score > max_score):
max_score = score
print(f" The highest score in the class is : {max_score}") | true |
ff508760139b4197b86726ac82a698f82ae8caec | QasimK/Project-Euler-Python | /src/problems/p_1_49/p19.py | 2,544 | 4.28125 | 4 | '''
You are given the following information, but you may prefer
to do some research for yourself.
* 1 Jan 1900 was a Monday.
* Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
* A leap year occurs on any year evenly divisible by 4,
but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth
century (1 Jan 1901 to 31 Dec 2000)?
'''
'''
I will attempt this by counting the number of days elapsed
by the start of each month and then seeing if it is divisible by 7
(which shows it is a Sunday)
'''
import utility.factors as factors
def get_days_in_month(month, year):
'''Return the number of days in a given month in a given year
(the year part matters for February)
Month should be a number from 1-12
'''
#September, April, June, November
if month in [9, 4, 6, 11]:
return 30
elif month == 2: #February
#Is leap year?
if factors.is_factor(4, year):
if(factors.is_factor(100, year) and
not factors.is_factor(400, year)):
return 28
else:
return 29
else:
return 28
else:
return 31
if __name__ == '__main__':
#===========================================================================
# def testl(year):
# print(year, get_days_in_month(2, year))
# testl(1900)
# testl(1904)
# testl(2000)
# testl(1950)
# testl(2300)
# testl(2400)
#===========================================================================
day_number = 1 #January 1st 1900 (monday, not a sunday so we ignore)
day_number = 2 #January 1st 1901 (Tuesday)
sunday_fell = 0
for year in range(1901, 2001): #excludes 2001
for month in range(1, 13): #excludes 13
if year == 2000 and month == 12:
#This is the last December
#We do not want to add these days on
continue
#Day number that next month starts on
day_number += get_days_in_month(month, year)
if factors.is_factor(7, day_number):
sunday_fell += 1
#print(year, month+1, day_number, "sunday")
#else:
#print(year, month+1, day_number)
print(sunday_fell)
| true |
b108c2c7de3669c11c6e765d6e213619aa3d91fe | QasimK/Project-Euler-Python | /src/problems/p_1_49/p23.py | 2,656 | 4.125 | 4 | '''
A perfect number is a number for which the sum of its
proper divisors is exactly equal to the number.
For example, the sum of the proper divisors of 28
would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is
a perfect number.
A number n is called deficient if the sum of its proper
divisors is less than n and it is called abundant if this
sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16,
the smallest number that can be written as the sum of two abundant
numbers is 24. By mathematical analysis, it can be shown that all
integers greater than 28123 can be written as the sum of two abundant
numbers. However, this upper limit cannot be reduced any further
by analysis even though it is known that the greatest number that
cannot be expressed as the sum of two abundant numbers is less than
this limit.
Find the sum of all the positive integers which cannot be written
as the sum of two abundant numbers.
'''
import utility.factors as factors
#Zegote number = A number which can be expressed as the sum of two abundants
#Antizegote = A number which CANNOT be expressed as the sum of two abundants
def get_all_abundants(max_number):
"""Return all abundant numbers upto but excluding max_number"""
abundants = []
#12 is known to be the smallest abundant
for n in range(12, max_number):
if sum(factors.get_proper_divisors(n)) > n:
abundants.append(n)
return abundants
def p23():
'''
I will find all Zegotes in [1, 28123] and remove them from the
set {1, 2, ..., 28123}.
The largest abundant number needed, x, is known to follow:
x+12 = 28,123 (largest possible antizegote)
therefore x = 28,111
There is no need to check any abundants larger than this.
Similarly, the smallest abundant = 12.
'''
abundants = get_all_abundants(28111+1)
#Find all zegotes and remove them from {1, 2, ..., 28123}
full_set = set([num for num in range(1, 28123+1)])
zygote_set = set()
for i, first_number in enumerate(abundants):
go_upto = 28123 - first_number
for second_number in abundants[i:]:
if second_number > go_upto:
break
zygote = first_number+second_number
try:
zygote_set.add(zygote)
except ValueError:
pass
list_of_antizygotes = full_set - zygote_set
return sum(list_of_antizygotes)
if __name__ == '__main__':
#print(get_all_abundants(20))
import time
start = time.time()
print(p23())
print("Time taken: ", (time.time()-start)*1000, "ms", sep="") | true |
ed0baab15b160004bc09324389f4b13c2a927266 | sap218/python | /csm0120/02/lect_02b_hw.py | 663 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 12 11:03:24 2017
@author: sap21
"""
'''
An interactive game to exercise what you know about variables, if statements, loops and input/output.
Game: Guess the secret number!
● Initialise a variable to hold a secret number of your choice.
● Prompt the user to input a guess.
● Compare the guess to the secret number. If it's correct, print a congratulations message and stop.
● If it's not correct, then tell the user if the secret is lower or higher than their guess, and prompt them to
guess again. Keep going until they've guessed correctly (while their guess is still wrong).
'''
| true |
f7115ec803f7fa5935712ad690bc385142dcbbeb | Phantsure/algo-rythm-urf-algorithm | /Searching/python/fibonacciSearch.py | 1,185 | 4.15625 | 4 | #List should be in Sorted ascending order
from bisect import bisect_left
def fibonacciSearch(arr, x, n):
# Initialize fibonacci numbers
m2 = 0 # (m-2)'th Fibonacci No.
m1 = 1 # (m-1)'th Fibonacci No.
m = m2 + m1 # m'th Fibonacci
# m is going to store the smallest
# Fibonacci Number greater than or equal to n
while (m < n):
m2 = m1
m1 = m
m = m2 + m1
offset = -1;
while (m > 1):
i = min(offset+m2, n-1)
if (arr[i] < x):
m = m1
m1 = m2
m2 = m - m1
offset = i
elif (arr[i] > x):
m = m2
m1 = m1 - m2
m2 = m - m1
else :
return i
if(m1 and arr[offset+1] == x):
return offset+1;
return -1
print("Enter the elements of the array in a single line: ")
arr = list(map(int,input().split()))
num = int(input("Enter the number you want to search\n"))
ind = fibonacciSearch(arr, num, len(arr))
if(ind>=0):
print("Found at index: ",ind)
else:
print("Searched Element not found")
| false |
3978a26c7eae2acc34309229aba939942f55edf8 | mellosilvajp/projetos_unipampa | /teste github/exercicios_vetores_14.py | 1,728 | 4.15625 | 4 | # https://www.passeidireto.com/arquivo/56813560/listas-em-python-exercicios-iniciais
#
# Os alunos de uma turma foram muito mal em uma prova.
# O professor resolveu, então considerar a maior nota como o 10.0 e transformar as demais notas em relação
# a esta nota da seguinte maneira: nota do aluno * 10/ maior nota.
# Faça uma função que receba a lista de notas dos alunos, calcule a nova nota dos
# alunos mostrando as notas antigas e as novas na tela.
def inicializa_notas_originais(melhor_nota):
notas_originais = []
notas_originais.append(melhor_nota)
return notas_originais
def inicializa_notas_novas():
novas_notas = []
novas_notas.append(10)
return novas_notas
def enfeita_codigo():
print('='*30)
def adiciona_valores_aos_vetores(notas_originais, novas_notas, melhor_nota):
quantidade_alunos = int(input('Digite a quantidade de alunos: '))
enfeita_codigo()
for i in range(0, quantidade_alunos):
notas_alunos = int(input('Digite a nota dos demais alunos: '))
notas_originais.append(notas_alunos)
nota_nova = int(notas_alunos*10/melhor_nota)
print('A nova nota deste aluno é: ', nota_nova)
novas_notas.append(nota_nova)
enfeita_codigo()
def main():
melhor_nota = int(input('Qual foi a melhor nota da turma(entre 0 a 10)? '))
novas_notas = inicializa_notas_novas()
notas_originais = inicializa_notas_originais(melhor_nota)
adiciona_valores_aos_vetores(notas_originais, novas_notas, melhor_nota)
enfeita_codigo()
print('A melhor nota foi: ', melhor_nota)
print('As notas originais eram: ', sorted(notas_originais[:]))
print('As novas notas são: ', sorted(novas_notas[:]))
main()
| false |
5c773bead4c91bd8a50fb5441f9631cbe9edc027 | yurizirkov/PythonOM | /if.py | 657 | 4.125 | 4 | answer = input("Do you want to hear a joke?")
#affirmative_responses = ["Yes", "yes", "y"]
#negative_responses = ["No", "no", "n"]
#if answer.lower() in affirmative_responses:
#print("I am against picketing, but I do not know how to show it.")
#elif answer.lower() in negative_responses:
#print("Fine")
#if answer == "Yes" or answer == "yes":
#print("I am against picketing, but I do not know how to show it.")
#elif answer == "No":
#print("Fine.")
if "y" in answer.lower():
print("I am against picketing, but I do not know how to show it.")
elif "n" in answer.lower():
print("Fine.")
else:
print("I do not understand.") | true |
b40fa3ed7cfd83a46f24eaa9fbcc05b5ad35dee3 | Xigua2011/mu_code | /names.py | 278 | 4.28125 | 4 | name = input("What is your name?")
print("Hello", name)
if name=="James":
print("Your name is James. That is a silly name")
elif name=="Richard":
print("That is a good name.")
elif name=="Anni":
print("Thats a stupid name")
else:
print("I do not know your name") | true |
628e319d65d3dd83d540ab326913f2bb62cca265 | shivveerq/python | /replacementop.py | 430 | 4.25 | 4 | name="shiva"
salary=15000
gf="sunny"
print("Hello {0} your salary is {1} and your girlfriend waiting {2}".format(name,salary,gf)) # wint index
print("Hello {} your salary is {} and your girlfriend waiting {}".format(name,salary,gf))
print("Hello {x} your salary is {y} and your girlfriend waiting {z}".format(x=name,y=salary,z=gf))# without index
# in third line order is not important
# {} using replacement operator
| true |
b4c433ee6ddb5c5f1e04c27963d9b56ce104ce87 | pavarotti305/python-training | /while_loop.py | 599 | 4.125 | 4 | print('')
print("Use while with modulus this expression for x in xrange(2, 21): is the same as i = 2 while i < 21:")
i = 2
while i < 21:
print(i)
stop10 = i == 10
if i % 2 != 0:
break
if stop10:
break
i += 2
print('')
print("Same code with for")
for x in range(2, 21):
if x % 2 == 0:
print(x)
if x > 10:
break
print('''Syntax while expression is true:
statements
if expression is true:
break
i += 2 condition''')
l = list(range(10))
print(l, 'List of range the 10 like (0, 10) 0 included 10 excluded')
while l:
l.pop(0)
print(l)
| true |
a37de490c4738e54d1f68f6194af7c2a47c96969 | pavarotti305/python-training | /if_else_then.py | 2,994 | 4.4375 | 4 | print('')
print('''Here is the structure:
if expression: like on this example if var1 is true that means = 1 print the value of true expression
statement(s)
else: else var1 is false that means = 0 print the value of false expression
statement(s)''')
truevalue = 1
if truevalue:
print("1 - Got a true expression value")
print(truevalue)
else:
print("1 - Got a false expression value")
print(truevalue)
falsevalue = 0
if falsevalue:
print("2 - Got a true expression value")
print(falsevalue)
else:
print("2 - Got a false expression value")
print(falsevalue)
print("Good bye!")
print('')
print('''Here is the second structure with elif:
if expression1:
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)''')
var = 100
if var == 200:
print("1 - Got a true expression value")
print(var)
elif var == 150:
print("2 - Got a true expression value")
print(var)
elif var == 100:
print("3 - Corresponding to a true expression value")
print(var)
else:
print("4 - Got a false expression value")
print(var)
print("Good bye!")
print('''Python operators:
+ Addition Adds values on either side of the operator.
- Subtraction Subtracts right hand operand from left hand operand.
* Multiplication Multiplies values on either side of the operator
/ Division Divides left hand operand by right hand operand
% Modulus Divides left hand operand by right hand operand and returns remainder
** Exponent Performs exponential (power) calculation on operators
// Floor Division - The division of operands where the result is the quotient in which the digits after
the decimal point are removed. like 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0
== If the values of two operands are equal, then the condition becomes true.
!= If values of two operands are not equal, then condition becomes true.
<> If values of two operands are not equal, then condition becomes true.
> If the value of left operand is greater than the value of right operand, then condition becomes true.
< If the value of left operand is less than the value of right operand, then condition becomes true.
>= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true.
<= If the value of left operand is less than or equal to the value of right operand, then condition becomes true.
= Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c
+= It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a
-= Subtract AND subtracts right operand from the left operand and assign the result to left operand c -= a = c = c - a
*= Multiply AND c *= a is equivalent to c = c * a
/= Divide AND c /= a is equivalent to c = c / a
%= Modulus AND c %= a is equivalent to c = c % a
**= Exponent AND c **= a is equivalent to c = c ** a
//= Floor Division c //= a is equivalent to c = c // a''')
| true |
f62f9f153a2b413d32bf07f4cd9e660e4adfcfea | SaurabhRuikar/CdacRepo | /Python and Advanced Analytics/Lab Practice/ConsonantReplace.py | 1,176 | 4.15625 | 4 | '''
Q. 1. Given a dictionary of students and their favourite colours:
people={'Arham':'Blue','Lisa':'Yellow',''Vinod:'Purple','Jenny':'Pink'}
1. Find out how many students are in the list
2. Change Lisa’s favourite colour
3. Remove 'Jenny' and her favourite colour
4. Sort and print students and their favourite colours alphabetically by name
Write a function translate() that will translate a text into "rövarspråket" (Swedish for
"robber's language").
That is, double every consonant and place an occurrence of "o" in between. For
example, translate("this
is fun") should return the string "tothohisosisosfofunon".
p={'Arham':'Blue','Lisa':'Yellow','Vinod':'Purple','Jenny':'Pink'}
print("No of students - ")
print(len(p))
c=input("Enter the new color for Lisa ")
print("Previous color of Lisa")
print(p["Lisa"])
p["Lisa"]=c
print("New color for Lisa is ")
print(c)
print(p)
print()
p.pop("Jenny")
print(p)
for i in sorted(p):
print(i,"---->",p[i])
'''
s=input("Enter the string")
print(s)
s1="aeiouAEIOU"
s2=""
for i in s:
if i in s1:
s2+=i
else:
s2+=i+"o"+i
print(s2)
| true |
8ee6a5e0a13f0db31fdae73f1492ba225a6c480d | SaurabhRuikar/CdacRepo | /Python and Advanced Analytics/Advanced Analytics/libraries3.py | 1,819 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 7 17:19:54 2019
@author: student
"""
import sys
import numpy as np
def createArange():
r1=int(input("Enter the number of rows for matrix A "))
c1=int(input("Enter the number of column for matrix A "))
m1=r1*c1
a=np.arange(m1).reshape(r1,c1)
print(a)
r2=int(input("Enter the number of rows for matrix B "))
c2=int(input("Enter the number of column for matrix B "))
m2=r2*c2
b=np.arange(m2).reshape(r2,c2)
print(b)
print("Shape of Matrix A is : ")
print(a.shape)
print("Shape of Matrix B is : ")
print(b.shape)
if c1==r2:
print(np.dot(a,b))
else:
print("Can't perform multiplication since rows and columns do not match")
def createRand():
r1=int(input("Enter the number of rows for matrix C "))
c1=int(input("Enter the number of column for matrix C "))
m1=r1*c1
c=np.random.randn(m1).reshape(r1,c1)
print(c)
r2=int(input("Enter the number of rows for matrix A "))
c2=int(input("Enter the number of column for matrix A "))
m2=r2*c2
a=np.arange(m2).reshape(r2,c2)
print(a)
if r1==r2 and c1==c2:
print('Addition is ')
print(a+c)
print()
print('Subtraction is ')
print(a-c)
print()
print('Multiplication is ')
print(a*c)
else:
print("Row and columns do not match so can't perform operations")
choice=0
while choice!=3:
print("1. Create Matrix A and B ")
print("2. Create Random Matrix C ")
print("3. Exit ")
choice=int(input("Enter your choice : "))
if choice==1:
createArange()
elif choice==2:
createRand()
else:
sys.exit(0)
| true |
14e688e1b7f4f8116a1ac43140a8bb508bcfa392 | SaurabhRuikar/CdacRepo | /Python and Advanced Analytics/Database/sqlite3/database.py | 2,039 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 6 12:27:14 2019
@author: student
"""
import sqlite3
import sys
db=sqlite3.connect('mydb1.db') #Connecting to database
if db!=None:
print("Connection done")
else:
print("Connection not done")
cursor=db.cursor() #cursor generate some RAM for data coming from database
def displayAll():
cursor.execute("select * from mytable")
for row in cursor.fetchall():#It returns list of tuple eg.[(10,'aaa'354),(20,'abc'222)]
print(str(row[0])+","+str(row[1])+","+str(row[2]))
#print(row)#Tuple
def insertrec():
id=int(input("Enter id"))
name=input("Enter the name")
sal=int(input("Enter salary"))
cursor.execute('''INSERT INTO mytable VALUES(?,?,?)''',(id,name,sal))
#cursor.execute('''INSERT INTO myatable VLUES(:id,:name,:sal)''',(id,name,sal)) for oracle :id indicates placeholders
db.commit()
def deleterec():
id=int(input("Enter id to be deleted"))
cursor.execute("delete from mytable where id=?",(id,))
#after id , comma is given because typle is size of 1
def update():
id=int(input("Enter id to be updated"))
sal=int(input("Enter the salary"))
cursor.execute("update mytable set sal=? where id=?",(sal,id,))
db.commit()
def displayID():
id=int(input("Enter id to be searched"))
cursor.execute("select * from mytable where id=?",(id,))
for row in cursor:
print(str(row[0])+","+str(row[1])+","+str(row[2]))
#ans="y"
choice=0
while choice!=6:
print("1. Insert Data ")
print("2. Delete Data ")
print("3. Modify Data")
print("4. Display All ")
print("5. Display by Id ")
print("6. Exit ")
choice=int(input("Enter the choice"))
if choice==1:
insertrec()
elif choice==2:
deleterec()
elif choice==3:
update()
elif choice==4:
displayAll()
elif choice==5:
displayID()
elif choice==6:
sys.exit(0)
| true |
92799c5dad508dbe76b9a231dc82cfa22e01b7f5 | erferguson/CodeWars | /9.13.20/kata.py | 1,639 | 4.15625 | 4 | # 8kyu
# This kata is from check py.checkio.org
# You are given an array with positive numbers and a number N.
# You should find the N-th power of the element in the array with the index N.
# If N is outside of the array, then return -1.
# Don't forget that the first element has the index 0.
# Let's look at a few examples:
# array = [1, 2, 3, 4] and N = 2, then the result is 3^2 == 9;
# array = [1, 2, 3] and N = 3, but N is outside of the array, so the result is -1.
def index(array, n):
if len(array) > n:
return array[n]**n
else:
return -1
# 8kyu
# Keep Hydrated!
# Nathan loves cycling.
# Because Nathan knows it is important to stay hydrated,
# he drinks ( 0.5 litres of water per hour of cycling ).
# You get given the time in hours and
# you need to return the number of litres Nathan will drink,
# rounded to the smallest value.
# For example:
# time = 3 ----> litres = 1
# time = 6.7---> litres = 3
# time = 11.8--> litres = 5
def litres(time):
litres = .5
return int(time * litres)
# 8kyu
# Is n divisible by x and y?
# Create a function that checks if a number n is divisible by two numbers x AND y.
# All inputs are positive, non-zero digits.
# Examples:
# 1) n = 3, x = 1, y = 3 => true because 3 is divisible by 1 and 3
# 2) n = 12, x = 2, y = 6 => true because 12 is divisible by 2 and 6
# 3) n = 100, x = 5, y = 3 => false because 100 is not divisible by 3
# 4) n = 12, x = 7, y = 5 => false because 12
def is_divisible(n,x,y):
if n % x == 0 and n % y == 0:
return True
else:
return False | true |
9dfe1eb181d7260f35d81c380e385008ebcf519d | run-fourest-run/PythonBeyondTheBasics | /Inheritence/singleinheritence.py | 885 | 4.15625 | 4 | ####Example given by instructor#####
class Base:
def __init__(self):
print('Base Intilizer')
def f(self):
print('Base.f()')
class Sub(Base):
def __init__(self):
super().__init__()
print('Sub Intilizer')
def f(self):
print('Sub.f()')
#####################Self made example###################3
class Bird:
def __init__(self,color):
self.color = color
def topspeed(self):
avg_speed = [10,40,34,54]
topspeed = max(avg_speed)
return topspeed
def print_color(self,color):
print(color)
class Tucan(Bird):
def __init__(self,color):
self.color = color
def topspeed(self):
avg_speed = [10,20,30,40,50]
func = lambda x: x + 1
top_speed = max(map(func,avg_speed))
print(top_speed)
base = Base()
base.f()
sub = Sub()
sub.f() | false |
1c44e33f725fbc0d5268277482ce1c001c614025 | rkidwell2/teachingPython | /HowManyCows.py | 1,444 | 4.21875 | 4 | """
Rosalind Kidwell
6/26/19
This program creates an interactive riddle for the cow game,
and is being used to demonstrate python fundamentals for high school students
"""
import random
from time import sleep
def cows():
print('')
myList = [[0, "? "],
[2, "How many? "],
[3, "How many cows? "],
[4, "How many are there? "],
[5, "How many cows are there? "],
[6, "How many cows are there now? "],
[5,"Do you know the answer? "],
[8,"How many cows do you think there are? "],
[8, "Do you know how many cows there are? "],
[7, "How many cows are on the farm? "]]
thisRound = random.choice(myList)
answer = thisRound[0]
question = thisRound[1]
print("I have a farm with no cows yet...")
sleep(1)
possibles = ["add", "remove", "buy", "sell", "get rid of", "bring in"]
for i in range(0, random.randint(3,7)):
print("I", random.choice(possibles), random.randint(1,8), "cows on the farm.")
sleep(1)
print('')
response = int(input(question))
if response == answer:
print("Correct!")
else:
print("Incorrect. There are", answer, "cows")
again = input("\nWant to play again? (y/n) ")
if again.lower() == "y":
cows()
print("-" * 25)
print("Welcome to the cow game!")
print("-" * 25)
cows()
print("\nThanks for playing!")
| true |
389b2826c6f9ab6a0ab39423ff8a7c66311f05e7 | em0flaming0/Mock-Database | /mock_db.py | 1,075 | 4.34375 | 4 | #!/usr/bin/python
#demonstrating basic use of classes and inheritance
class Automobile(object):
def __init__(self, wheels):
self.wheels = wheels #all autmobiles have wheels
class Car(Automobile):
def __init__(self, make, model, year, color):
Automobile.__init__(self, "4") #all Car objects should have 4 wheels
self.make = make
self.model = model
self.year = year
self.color = color
self.owner = None #an optional attribute for Car objects
self.engine = "N/A" #default engine_type for all instances of Car
class Bike(Automobile):
def __init__(self, make, model, year, color):
Automobile.__init__(self, "2") #all Bike objects should have 2 wheels
self.make = make
self.model = model
self.year = year
self.color = color
self.owner = None
def main():
Car1 = Car("Ford", "Mustang", "2001", "Red")
Bike1 = Bike("Kawasaki", "Ninja-ZX", "2005", "Green")
Car2 = Car("Honda", "S2000","2009","Silver")
Bike1.owner = "Mary Thompson"
Car1.owner = "Mike Smith"
Car1.engine = "Supercharged"
Car2.owner = "Robert Johnson"
if __name__ == "__main__":
main()
| true |
6cdc61e07a9a2a52d7c07a5a48570e4f2d80c0ce | aliamjad1/Data-Structure-Fall-2020 | /BubbleSorting.py | 571 | 4.28125 | 4 | ##It compares every index like [2,1,4,3]-------Firstly 2 compare with 1 bcz of greater 1 is moved towards left and 2 is on right
# [1,2,4,3]
def bubblesort(list):
listed=len(list)
isSorted=False
while not isSorted:
isSorted=True
for eachvalue in range(0,listed-1):
if list[eachvalue]>list[eachvalue+1]:
isSorted=False
temp=list[eachvalue]
list[eachvalue]=list[eachvalue+1]
list[eachvalue+1]=temp
print(list)
listed=[3,2,5,4,6]
bubblesort(listed)
# print(list) | true |
4a117edd4e73e2a8830804061c0f3e61a7ea4865 | trademark152/Data_Mining_USC | /hw5/test.py | 1,156 | 4.15625 | 4 | import re
import random
def isprime(num):
# If given number is greater than 1
if num > 1:
# Iterate from 2 to n / 2
for i in range(2, num // 2):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
if (num % i) == 0:
return False
else:
return True
else:
return False
def isPrime2(n):
# Corner cases
if (n <= 1):
return False
if (n <= 3):
return True
# This is checked so that we can skip
# middle five numbers in below loop
if (n % 2 == 0 or n % 3 == 0):
return False
i = 5
while (i * i <= n):
if (n % i == 0 or n % (i + 2) == 0):
return False
i = i + 6
return True
print(isprime(21))
print(isPrime2(1398318269))
random.seed(7)
random_prime_a = random.choices([x for x in range(1000, 2000) if isprime(x)], k=23)
random_prime_b = random.choices([x for x in range(1000, 2000) if isprime(x)], k=23)
print(random_prime_a)
print(random_prime_b)
PRIME = random.choices([x for x in range(1000000, 1000100) if isPrime2(x)])
print(PRIME) | true |
8b398401d12c5c9470dabcf3acf682e91aa3520a | RokKrivicic/webdevelopment2 | /Homeworks/homework1.py | 840 | 4.21875 | 4 | from smartninja_sql.sqlite import SQLiteDatabase
db = SQLiteDatabase("Chinook_Sqlite.sqlite")
# all tables in the database
db.print_tables(verbose=True)
#This database has many tables. Write an SQL command that will print Name
# from the table Artist (for all the database entries)
db.pretty_print("SELECT Name FROM Artist;")
#Print all data from the table Invoice where BillingCountry is Germany
db.pretty_print("SELECT * FROM Invoice WHERE BillingCountry = 'Germany';")
#Count how many albums are in the database. Look into the SQL documentation for help.
# Hint: look for Min&Max and Count, Avg, Sum
db.pretty_print("SELECT COUNT(AlbumId) AS 'Number of albums' FROM Album;")
#How many customers are from France?
db.pretty_print("SELECT COUNT(CustomerId) AS 'Number of costumer from France' FROM Customer WHERE Country = 'France';") | true |
a1675e46df676847b8576ef35a2ef5bf95061fab | Omisw/Python_100_days | /Day 3/leap_year.py | 950 | 4.53125 | 5 | # Day 3 - Third exercise.
# Leap Year
# Instructions
# Write a program that works out whether if a given year is a leap year. A normal year has 365 days, leap years have 366, with an extra day in February.
# The reason why we have leap years is really fascinating, this video does it more justice:
# This is how you work out whether if a particular year is a leap year.
# 🚨 Don't change the code below 👇
year = int(input("Which year do you want to check? "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
year_out_4 = year % 4
year_out_100 = year % 100
year_out_400 = year % 400
if year_out_4 == 0:
if year_out_100 == 0:
if year_out_400 == 0:
print(f"The year {year}, is actually a leap year. :D ")
else:
print(f"The year {year}, is not a leap year. ")
else:
print(f"The year {year}, is not a leap year. ")
else:
print(f"The year {year}, is not a leap year. ")
| true |
93dc5203b837b3ce41dd6df3051f1e8446113245 | Omisw/Python_100_days | /Day 10/Calculator/main.py | 1,438 | 4.1875 | 4 | # Day 10 - Final challenge.
from art import logo
# from replit import clear
def add(number_1, number_2):
return number_1 + number_2
def subtract(number_1, number_2):
return number_1 - number_2
def multiply(number_1, number_2):
return number_1 * number_2
def divide(number_1, number_2):
return number_1 / number_2
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide
}
def calculator():
print(logo)
still_calc = True
number_1 = float(input("Whats the firts number? "))
for symbol in operations:
print(symbol)
while still_calc:
operator_sym = input("Pick an operation: ")
number_2 = float(input("Whats the next number? "))
result = operations[operator_sym](number_1, number_2)
if operator_sym == "+":
print(f"{number_1} {operator_sym} {number_2} = {result}")
elif operator_sym == "-":
print(f"{number_1} {operator_sym} {number_2} = {result}")
elif operator_sym == "*":
print(f"{number_1} {operator_sym} {number_2} = {result}")
elif operator_sym == "/":
print(f"{number_1} {operator_sym} {number_2} = {result}")
continue_calc = input(f"Type 'y' to continue calculating with {result}, or type 'n' to start a new calculating ")
if continue_calc == "y":
number_1 = result
still_calc = True
# clear()
elif continue_calc == "n":
still_calc = False
# clear()
calculator()
calculator()
| true |
24c5920330ecb18cad06ee63444aa9432ad58dfc | Omisw/Python_100_days | /Day 9/dictionary_in_list.py | 1,258 | 4.5 | 4 | # Day 9 - Second exercise.
# Dictionary in List
# Instructions
# You are going to write a program that adds to a travel_log. You can see a travel_log which is a List that contains 2 Dictionaries.
# Write a function that will work with the following line of code on line 21 to add the entry for Russia to the travel_log.
# add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
# You've visited Russia 2 times.
# You've been to Moscow and Saint Petersburg.
# DO NOT modify the travel_log directly. You need to create a function that modifies it.
travel_log = [
{
"country": "France",
"visits": 12,
"cities": ["Paris", "Lille", "Dijon"]
},
{
"country": "Germany",
"visits": 5,
"cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
#🚨 Do NOT change the code above
#TODO: Write the function that will allow new countries
#to be added to the travel_log. 👇
def add_new_country(country, visited, city):
new_space = { }
new_space["country"] = country
new_space["visitis"] = visited
new_space["cities"] = city
travel_log.append(new_space)
#🚨 Do not change the code below
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
add_new_country("México", 10, ["Guadalajara", "Monterrey", "Merida"])
print(travel_log)
| true |
498e80a75aa31b4bad5652b9cebc4f0c11dfeb7a | Omisw/Python_100_days | /Day 9/grading_program.py | 1,517 | 4.65625 | 5 | # Day 9 - First exercise.
# Instructions
# You have access to a database of student_scores in the format of a dictionary. The keys in student_scores are the names of the students and the values are their exam scores.
# Write a program that converts their scores to grades. By the end of your program, you should have a new dictionary called student_grades that should contain student names for keys and their grades for values. The final version of the student_grades dictionary will be checked.
# DO NOT modify lines 1-7 to change the existing student_scores dictionary.
# DO NOT write any print statements.
# This is the scoring criteria:
# Scores 91 - 100: Grade = "Outstanding"
# Scores 81 - 90: Grade = "Exceeds Expectations"
# Scores 71 - 80: Grade = "Acceptable"
# Scores 70 or lower: Grade = "Fail"
student_scores = {
"Harry": 81,
"Ron": 78,
"Hermione": 99,
"Draco": 74,
"Neville": 62,
}
# 🚨 Don't change the code above 👆
#TODO-1: Create an empty dictionary called student_grades.
student_grades = {}
#TODO-2: Write your code below to add the grades to student_grades.👇
for name in student_scores:
score = student_scores[name]
if score > 90:
student_grades[name] = "Outstanding"
elif score <= 90 and score >= 81:
student_grades[name] = "Exceeds Expectations"
elif score <= 80 and score >= 70:
student_grades[name] = "Acceptable"
elif score < 70 and score >= 0:
student_grades[name] = "Fail"
# 🚨 Don't change the code below 👇
print(student_grades)
| true |
62d5ab70daaf6ea89567f6e2e3903f481401dc29 | eddieatkinson/Python101 | /guess_num_high_low.py | 421 | 4.25 | 4 | # Guess the number! Gives clues as to whether the guess is too high or too low.
secret_number = 5
guess = 2
print "I'm thinking of a number between 1 and 10."
while secret_number != guess:
print "What's the number?"
guess = int(raw_input("> "))
if (guess > secret_number):
print "%d is too high. Try again!" % guess
elif (guess < secret_number):
print "%d is too low. Try again!" % guess
else:
print "You win!" | true |
1fb3875553dd99fb89943a9c954029f1d0213877 | saddamarbaa/object-oriented-programming-concepts | /Intro OOP1.py | 1,187 | 4.4375 | 4 | # Object Oriented Programming
# Class and Object in Python
# Robot class
class Robot:
# instance attribute
def __init__(self, name, color, weight):
self.name = name
self.color = color
self.weight = weight
# instance method
def introduce_self(self):
print("My name is : " + self.name)
# instantiate the object 1
# Create an object of Robot
robot1 = Robot("Sadam", "blue", 30)
# call our instance methods
robot1.introduce_self()
# instantiate the object 2
# Create another object of Robot
robot2 = Robot("Ali", "red", 33)
# call our instance methods
robot2.introduce_self()
# person class
class Person:
# instance attribute
def __init__(self, name, personality, is_siting):
self.name = name
self.persoality = personality
self.is_siting = is_siting
# instance methods
def sit_down(self):
self.is_siting = True;
def stand_up(self):
self.is_siting = False;
# instantiate the object 1
person1 = Person("John", "Aggressive", False)
# instantiate the object 2
person2 = Person("Hanan", "Talkative", True)
| true |
92d3eeecb0efceb24b34a7f87488d3296c7d99de | lelongrvp/Special_Subject_01 | /homeword_2/problem3.py | 1,856 | 4.53125 | 5 | # Obtain phone number from user and split it into 3 parts
phone_number = input('Enter a phone number using the format XXX-XXX-XXXX: ')
split_number = phone_number.split('-')
#initializing some control variables
weird_character = False # True will stop while loop and display an error
count = 0 # Keeps track of which part of phone number we're
# currently looking at: area code, central office
# prefix, or line number
# This will hold the numeric version of the user's phone number
numeric_phone_number = ''
# Loop over each of the 3 parts of the number and over each character in that part.
while weird_character == False and count < 3:
for ch in split_number[count]:
if ch.isdigit():
numeric_phone_number += ch
elif ch.upper() in 'ABC':
numeric_phone_number += '2'
elif ch.upper() in 'DEF':
numeric_phone_number += '3'
elif ch.upper() in 'GHI':
numeric_phone_number += '4'
elif ch.upper() in 'JKL':
numeric_phone_number += '5'
elif ch.upper() in 'MNO':
numeric_phone_number += '6'
elif ch.upper() in 'PQRS':
numeric_phone_number += '7'
elif ch.upper() in 'TUV':
numeric_phone_number += '8'
elif ch.upper() in 'WXYZ':
numeric_phone_number += '9'
else:
weird_character = True
if count != 2:
numeric_phone_number += '-'
count += 1
# Error message if non-alphanumeric character pops up
if weird_character:
print('\nSome weird characters showed up in the number that I don\'t know what to do with.')
# Otherwise, here's some numeric version of the phone number
else:
print ('\nThe phone number you entered is', numeric_phone_number + '.') | true |
44746aec5d7405051b68ec4f1ead570f57e57ce0 | tnovak123/hello-spring | /crypto/caesar.py | 567 | 4.1875 | 4 | from helpers import rotate_character, alphabet_position
def encrypt(text, rot):
newtext = ""
for char in text:
if char.isalpha() == True:
newtext += rotate_character(char, rot)
else:
newtext += char
return(newtext)
def main():
inputtext = ""
displace = 0
inputtext = input("What do you want to encrypt?")
displace = input("What encryption value do you want to use?")
if displace.isdigit() == True:
print(encrypt(inputtext, displace))
else:
pass
if __name__ == "__main__":
main() | true |
d6c30d2048e7e815b9550b05e2abe1966c7d4332 | probuse/prime_numbers | /prime_numbers_.py | 810 | 4.15625 | 4 | def prime_numbers(n):
"Generate prime numbers between 0 and n"
while isinstance(n, int) and n > 0:
prime = []
def is_prime(number):
"Tests if number is prime"
if number == 1 or number == 0:
return False
for num in range(2, number):
if number % num == 0:
return False
return True
def primes(num = 0):
"Generator function yielding prime numbers"
while True:
if is_prime(num): yield num
num += 1
for number in primes():
if number > n: break
prime.append(number)
return prime
raise TypeError('argument needs to be a positive integer')
#print prime_numbers(3)
| true |
2d195bd9e64a571692a80213e75beddf8235052c | ironboxer/leetcode | /python/214.py | 983 | 4.15625 | 4 | """
https://leetcode.com/problems/shortest-palindrome/
Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
Example 1:
Input: "aacecaaa"
Output: "aaacecaaa"
Example 2:
Input: "abcd"
Output: "dcbabcd"
"""
class Solution:
"""
KMP is good, but it's too complicated to understand
Also, if you try your best, you can do it.
"""
def shortestPalindrome(self, s: str) -> str:
r = s[::-1]
for i in range(len(s) + 1):
print(s, r[i:], s.startswith(r[i:]))
# 稍微想一下 其实很简单
# 就是一个简单的翻转对称
if s.startswith(r[i:]):
return r[:i] + s
if __name__ == '__main__':
print(Solution().shortestPalindrome("abcdefg"))
print(Solution().shortestPalindrome("aacecaaa"))
print(Solution().shortestPalindrome("abcd"))
| true |
bc509ad8e8375270c803a118c24746d45af97088 | ironboxer/leetcode | /python/49.py | 1,050 | 4.1875 | 4 | """
https://leetcode.com/problems/group-anagrams/
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
Constraints:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] consists of lower-case English letters.
"""
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
from collections import defaultdict
dic = defaultdict(list)
for s in strs:
dic[''.join(sorted(s))].append(s)
return list(dic.values())
if __name__ == "__main__":
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
print(Solution().groupAnagrams(strs))
| true |
9b79ae5a9eaadcef2a1be81c479ca9675c0d3553 | ironboxer/leetcode | /python/231.py | 652 | 4.125 | 4 | """
https://leetcode.com/problems/power-of-two/
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Explanation: 20 = 1
Example 2:
Input: 16
Output: true
Explanation: 24 = 16
Example 3:
Input: 218
Output: false
"""
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
for i in range(32):
v = 1 << i
if v == n:
return True
if v > n:
break
return False
if __name__ == '__main__':
print(Solution().isPowerOfTwo(1))
print(Solution().isPowerOfTwo(16))
print(Solution().isPowerOfTwo(218))
| true |
9e4fc7517fbe8fd3e2f9c68694b0692e5ad0eef4 | Steven4869/Simple-Python-Projects | /excercise21.py | 434 | 4.25 | 4 | #Amstrong number
print("Welcome to Amstrong number checker, if the number's sum is same as the sum of the cubes of respective digits then it is called Amstrong number")
a=int(input("Please enter your number\n"))
sum=0
temp=a
while(temp >0):
b=temp%10
sum+=b **3
temp//=10
if(a==sum):
print(a,"is an Amstrong number")
else:
print(a,"isn't an Amstrong number")
print("It's sum for the respective digits is", sum) | true |
8331900c3a1c5d994c1b3616e62198af66396cb4 | RainbowBite/Project_Eilera | /1-10/py1.py | 2,286 | 4.21875 | 4 | """
Если выписать все натуральные числа меньше 10, кратные 3 или 5, то получим 3, 5, 6 и 9. Сумма этих чисел равна 23.
Найдите сумму всех чисел меньше 1000, кратных 3 или 5.
"""
# создаем переменную = список
zed = []
# заполняем список числами от одного до 1000
for i in range(1,1001):
zed.append(i) # append записывает i в нужную ячейку
# print(zed) # проверяем все ли правильно получилось
# находим все числа кратные 3 или 5 и записываем списки
three = []
five = []
for i in zed:
if i%3 == 0: # если число делится на 3 без остатка то это число проходит и
three.append(i) # записывается в список 'three'
elif i%5 == 0: # если число делится на 5 без остатка то это число проходит и
five.append(i) # записывается в список 'five'
svitch = True # нужна для бесконечного цикла
while svitch: # а вот и сам бесконечный цикл
print("что вы хотите увидеть?")
inp = str(input()) # дает возможность ввести что то и оно будет преобразованно в строку
if inp == 'три': # если мы напишем "три" то выведеться это -
print(three) # наш список в котором все числа кратны 3
elif inp == 'пять':
print(five)
elif inp == 'стоп':
break # выход из бесконечного цикла
else:
print("Вводить можно только: \n == три - покажет список чисел кратных трем \n == пять - покажет список чисел кратных пяти \n == стоп - остановит цикл")
sum3 = 0
aps = 0
for i in three:
sum3 += i
aps +=1
print(sum3)
print(aps)
sum5 = 0
aps2 = 0
for i in five:
sum5 += i
aps2 +=1
print(sum5)
print(aps2) | false |
b15b77753c5241a39900ca8f697e160215d794e3 | emersonleite/python | /Introdução a Programação com Python - exercícios baixados do site oficial/Exercícios/exercicio-04-04.py | 791 | 4.34375 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2014
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpressão - Novembro/1012
# Terceira reimpressão - Agosto/2013
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Site: http://python.nilo.pro.br/
#
# Arquivo: exercicios_resolvidos\capitulo 04\exercicio-04-04.py
##############################################################################
salário = float(input("Digite seu salário:"))
pc_aumento = 0.15
if salário > 1250:
pc_aumento = 0.10
aumento = salário * pc_aumento
print("Seu aumento será de: R$ %7.2f" % aumento)
| false |
7988fec9082331a5ca49538884019261be7bc21c | emersonleite/python | /Introdução a Programação com Python - exercícios baixados do site oficial/Exercícios/exercicio-06-07.py | 1,014 | 4.15625 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2014
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpressão - Novembro/1012
# Terceira reimpressão - Agosto/2013
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Site: http://python.nilo.pro.br/
#
# Arquivo: exercicios_resolvidos\capitulo 06\exercicio-06-07.py
##############################################################################
expressão = input("Digite a sequência de parênteses a validar:")
x=0
pilha = []
while x<len(expressão):
if(expressão[x] == "("):
pilha.append("(")
if(expressão[x] == ")"):
if(len(pilha)>0):
topo = pilha.pop(-1)
else:
pilha.append(")") # Força a mensagem de erro
break
x=x+1
if(len(pilha)==0):
print("OK")
else:
print("Erro")
| false |
a92a5371ecbf8a8b7e80695f1935ea44606983fb | davidholmes1999/first-project1 | /Holmes_numbergenerator.py | 892 | 4.15625 | 4 | #David Holmes
#3/9/17
#Number Simulator
#Print Statements
print("\nWeclome to the number simulator game! You will be seeing how many guesses it takes for you to guess my number!\n")
print("\nFirst let me think of a number between 1 and 100\n")
print("\nHmmmmmm...\n")
import random
#Defining Variables
player=int(input("\nI got it! Guess wisely, I can be a trickster! Now plesase type in a number between 1-100.\n"))
computer=random.randint(1,100)
#If Statements
x= 1
while player != computer:
if player>computer:
print("\nGuess lower...")
elif player<computer:
print("\nGuess higher...")
x= x+1
player= int(input("\nGuess again please...\n"))
#Outro Statement
print("\nYou guessed the number right! It took you", x, "attempts to guess it! Good job!\n")
#Input Statement
input("\n\nPress enter to continue")
| true |
21d764b5c154ea14771a48b5e0c0d9b0bcac4509 | bhagyamudgal/learning-python | /data-types/data-types.py | 2,563 | 4.125 | 4 | # Variables
num1 = 10
num2 = 5
num3 = 2
num4 = 3
print("Sum of 10 and 5 is", num1 + num2)
print("Differnce of 10 and 5 is", num1 - num2)
print("Product of 10 and 5 is", num1 * num2)
print("Dividend of 10 and 5 is", num1 / num2)
print("Remainder of 10 and 5 is", num1 % num2)
print("2 to the power of 3 is", num3**num4)
print("BODMAS rule applies [ 2 + 10 * 10 + 3 ] here",
num3 + num1 * num1 + num4)
print("BODMAS rule applies [ (2 + 10) * (10 + 3) ] here",
(num3 + num1) * (num1 + num4))
# Check data type using type()
print(type(num1))
#Strings
my_string = "Bhagya Mudgal"
# Printing str length using len()
print(len(my_string))
# String slicing
print(my_string[7:13:2])
# Reverse string
print(my_string[::-1])
# Strings are immutable
# name="Bhagya"
# name[0]="M"
# it will not work
# String concatenation
name = "Bhagya"
last = name[1:]
name = "M" + last
print(name)
# Multiply string
letter = "B"
letter = letter * 10
print(letter)
# String methods
my_string2 = "Bhagya Mudgal"
print(my_string2.upper())
print(my_string2.lower())
print(my_string2.split()) # Default split on white space
# String interpolation
print("Bhagya {}".format("Mudgal"))
print("Bhagya {} Mudgal".format("is"))
print("Bhagya {1} Mudgal {2}".format("is", "am", "are"))
print("Bhagya {a} Mudgal {ar}".format(i="is", a="am", ar="are"))
# Float formatting
result = 100 / 777
print("Result is", result)
print("Result is {}".format(result))
print("Result is {:1.3f}".format(result)) # {value:width:precision}
# Another way
name = "Bhagya"
print(f"Hi {name}")
# List
my_list = [1, 2, 3, 4, 5]
my_list2 = [6, 7, 8]
print(my_list)
print(len(my_list))
print(my_list[-2])
print(my_list + my_list2)
# List are mutable
my_list2[2] = 9
print(my_list2)
my_list.append(100)
print(my_list)
pop_item = my_list.pop()
print("Pop item is {}".format(pop_item))
# Sort list
my_list = [34, 94, 24, 82, 12]
my_list.sort()
print(my_list)
# Dictionaries -> Key value pair (Object in JS)
my_dict = {"name": "bhagya", "age": 19}
print(my_dict)
print(my_dict["age"])
# Dictionaries are mutable
my_dict["name"] = "John"
print(my_dict)
# Dictionaries methods
print(my_dict.keys())
print(my_dict.values())
print(my_dict.items())
# Tuples -> are immutable
my_tuple = (1, 2, 3)
my_list = [1, 2, 3]
print(my_tuple)
print(my_list)
# my_tuple[2]=4 .... it will generate error
# Sets -> unique items only
my_set = set()
my_set.add(1)
print(my_set)
my_set.add(2)
print(my_set)
my_set.add(3)
print(my_set)
my_set.add(1)
print(my_set)
# Boolean -> true || false
boolean = 1 > 2
print(boolean)
| false |
fd74144669b2dfb6dd3ad08b4ad8f029d817b0d3 | Dexmo/pypy | /playground.py | 1,126 | 4.21875 | 4 | values = (1,2,3,4,5) #tuple - immutable, orderly data structure
squares = [value**2 for value in range(1,11)] #list comprehension
''' 3 short subprogram for quick work '''
print(max(values))
print(min(values))
print(sum(values))
print(squares)
'''---------------------------------------'''
for number in range(1, 21):
print(number)
# creating list with 1000 values
thousand_list = []
for number in range(1,1001):
thousand_list.append(number)
# creating list with odd numbers
odd_number = []
for number in range(1,20,2):
odd_number.append(number)
print(odd_number)
# creating the list with values to cube using list comprehension
cube_values = [value**3 for value in range(1,11)]
print(cube_values)
""" taking some part of list """
players = ['Mati', 'Kati', 'Pati', "Sati"]
print(players[2:]) #Only shows Pati and Sati
print(players[:2]) #Only shows Mati and Kati
new_players = players[:]
print(new_players)
""" TUPLE """
dimensions = (200, 50)
print("First dimension: " + str(dimensions[0]) + ", and second: " + str(dimensions[1]) +
".\nBecause dimensions are storage in tuple we cannot change it!") | true |
956fd0812e6565fa8f6843af933c225e7ae22a7c | emailman/Raspberry_Pi_Heater | /sorted grades/function demo.py | 647 | 4.15625 | 4 | def rectangle_calc(x, y):
area = x * y
perimeter = 2 * (x + y)
return area, perimeter
def main():
try:
length = float(input("Enter the length of a rectangle: "))
width = float(input("Enter the width of a rectangle: "))
units = input("Enter the units: ")
area_, perimeter_ = rectangle_calc(length, width)
print("length =", length, units, ", width =", width, units)
print("area = ", area_, "sq", units, ", perimeter = ",
perimeter_, units)
print(rectangle_calc(length, width))
except ValueError:
print("You messed up")
exit(1)
main()
| true |
39028abf4600601082d0c7f24f718739f5e77c3a | queenskid/MyCode | /labs/introfor/forloop2.py | 542 | 4.15625 | 4 | #!/usr/bin/env python3
# 2 seprate list of vendors
vendors = ['cisco', 'juniper', 'big_ip', 'f5', 'arista', 'alta3', 'zach', 'stuart']
approved_vendors = ['cisco', 'juniper', 'big_ip']
# for loop going through list of vendors and printing to screen with a conditional statement.
for x in vendors:
print("\nThe vendors is " + x, end="")
# if statement looking for vendors that are not in the approved vendor list.
if x not in approved_vendors:
print(" - NOT AN APPROVED VENDOR!", end="")
print("\nOur loop has ended.") | true |
bf40a829a9887f981a48f429835956a807d3cf03 | cowsertm1/Python-Assignments | /functions-and-collections.py | 2,974 | 4.6875 | 5 | """
As we saw in class, in Python arguments passed to a function are
treatedly differently depending on whether they are a "normal"
variable or a collection. In this file we will go over some additional
examples so that you get used to this behavior:
1. Write a program that assigns some value to a global variable called
"my_global_string".
Add to your program a function called "modify_string" that receives a
string as an argument. (Call the argument something like "string_arg",
eg.) Have that function try to set the string to a different value and
then return.
In your program, call that function, passing it my_global_string as an
argument, and then print out the value of my_global_string.
Observe what happens.
2. Repeat exercise one but for a number (integer) variable. Observe
what happens.
3. Write a program that creates a dictionary called 'peoples_ages'
mapping names to ages. Insert into the dictionary data for 3 people.
4. Add to that program a function called "modify_dictionary" that
takes a dictionary as an argument. (When defining the function, be
sure to name the argument something *other* than 'peoples_ages'.) In
that function,
(i) add a new element to the argument (e.g., "marisa" => 75)
(ii) modify the age of one of the people listed in peoples_ages
(iii) remove from the argument one element present in peoples_ages.
In your program, run that function and then print out the contents of
peoples_ages. Observe what happened. Which of the three changes made
within the function modify_dictionary to its argument were actually
being done on (the global collection) peoples_ages?
5. Add to that program a new function called "modify_dictionary_2"
that takes a dictionary as an argument. (As above, when defining the
function, be sure to name the argument something *other* than
'peoples_ages'. Below, and for the sake of clarity, I assumed the
argument is 'dic_passed_as_argument'.) In this function, to to "clear"
or "empty" the dictionary passed as an argument by assigning to it an
empty dictionary, e.g.:
dic_passed_as_argument = {}
As above, have your program execute this function and then print out
the dictionary peoples_ages. What happened?
6. Edit the function modify_dictionary_3 so that, rather than assigning
dic_passed_as_argument = {}
it instead calls
dic_passed_as_argument.clear()
Why did this work while our attempt in question 5 failed?
7. To really drive the point home, do a similar experiment with a list
and a set. See if they behave the same way as dictionaries.
===
So, as we see above Python lets your functions modify the arguments
passed to functions -- as long as those arguments are *collections*.
Does that mean you should do it? Nope. To keep your code clean and
easy to maintain, if your function wants to share some modified data
with the rest of your program, the way to do so is by having your
function *return* that modified data -- never by directly modifying
its arguments.
"""
| true |
0b9802a4b4ecc2823db5761773af068cad2d0e56 | davifelix5/design-patterns-python | /structurals/adapter/adapter.py | 2,102 | 4.3125 | 4 | """
Serve par ligar duas classes diferentes
"""
from abc import ABC, abstractmethod
class iGameControl(ABC):
@abstractmethod
def left(self) -> None: pass
@abstractmethod
def right(self) -> None: pass
@abstractmethod
def down(self) -> None: pass
@abstractmethod
def up(self) -> None: pass
class GameControl(iGameControl):
def left(self) -> None:
print('Moving left')
def right(self) -> None:
print('Moving right')
def down(self) -> None:
print('Moving down')
def up(self) -> None:
print('Moving up')
class NewGameControl:
def move_left(self) -> None:
print('Moving to the elft direction')
def move_right(self) -> None:
print('Moving to the right direction')
def move_down(self) -> None:
print('Moving to the down direction')
def move_up(self) -> None:
print('Moving to the up direction')
class GameControlAdapter(iGameControl, NewGameControl):
"""
Adaptador usando herança
"""
def left(self) -> None:
self.move_left()
def right(self) -> None:
self.move_right()
def down(self) -> None:
self.move_down()
def up(self) -> None:
self.move_up()
class GameControlAdapter2:
"""
Adaptador usando composição
"""
def __init__(self, adaptee: NewGameControl):
self.adaptee = NewGameControl()
def left(self) -> None:
self.adaptee.move_left()
def right(self) -> None:
self.adaptee.move_right()
def down(self) -> None:
self.adaptee.move_down()
def up(self) -> None:
self.adaptee.move_up()
if __name__ == "__main__":
control = GameControl()
new_control = GameControlAdapter()
new_control2 = GameControlAdapter2(new_control)
control.right()
control.up()
control.left()
control.down()
print()
new_control.right()
new_control.up()
new_control.left()
new_control.down()
print()
new_control2.right()
new_control2.up()
new_control2.left()
new_control2.down()
| true |
7bfd6160f69605ad5009e8baca3c065aa739b1d0 | joyrexus/nst | /misc/poset.py | 2,638 | 4.1875 | 4 | '''
In NST Sect 14 (p. 57) Halmos gives three examples of partially ordered sets
with amusing properties to illustrate the various possibilities in their
behavior.
Here we aim to define less_than functions for each example. Each function
should return a negative value if its first argument is "less than" its
second, 0 if the two arguments are "equal", and a positive value otherwise.
'''
from __future__ import division
from random import shuffle
ii_unordered = set()
iii_unordered = set()
def i_less_than(M, N):
(a, b) = M
(x, y) = N
p = ((2 * a) + 1) * (2 ** y)
q = ((2 * x) + 1) * (2 ** b)
if p <= q:
print "Defined for {} since {} <= {}".format((M, N), p, q)
return True
else:
print "Undefined for {} since {} > {}".format((M, N), p, q)
# ordering for relation ii:
# a < x or (a == x and (b < y or b == y)
# (a < x or a == x) and (a < x and (b < y or b == y))
#
# ordering for relation iii:
# (a < x or a == x) and (b < y or b == y)
def ii_less_than(M, N):
'''
Compare two 2-tuples based on lexicographic order.
'''
(a, b) = M
(x, y) = N
if a < x:
return True
elif a == x and (b < y or b == y):
return True
def iii_less_than(M, N):
'''
Compare two 2-tuples based on present order.
Note that unlike lexicographic order, if the first
element of the first 2-tuple is not less than or equal
to the first element of the second 2-tuple, we do not
evaluate the order between the tuples at all.
'''
(a, b) = M
(x, y) = N
if (a < x or a == x) and (b < y or b == y):
return True
X = [(a, b) for a in range(10) for b in range(10)]
for a, b in X:
M = (a, b+1)
N = (a, b)
i_less_than(M, N)
# create a shuffled list of 2-tuples
X = [(a, b) for a in range(10) for b in range(10)]
shuffle(X)
S = [(M, N) for M in X for N in X if ii_less_than(M, N)] # the relation S
T = [(M, N) for M in X for N in X if iii_less_than(M, N)] # the relation T
print "S:", len(S)
print "T:", len(T)
print list(set(S) - set(T))[:10]
'''
print sorted(X, cmp=i_less_than)
print
print sorted(X, cmp=ii_less_than)
print
print sorted(X, cmp=iii_less_than)
'''
print '-' * 30
print ii_unordered ^ iii_unordered
'''
Another poset example.
See p. 57 of NST where Halmos describes three partially-ordered sets "with some
amusing properties."
'''
def z(x, y):
return (2*x + 1) / 2**y
def z_over(a, b):
for x in range(a, b):
print
print "x ==", x
for y in range(a, b):
print " z({}, {}) == {}".format(x, y, z(x, y))
z_over(-2, 3)
| true |
59b252c6a2308eb7c590901f9aa0090186b83161 | mitalishah25/hackerRank_problems | /introduction.py | 1,525 | 4.21875 | 4 | # Introduction
#Say "Hello, World!" With Python https://www.hackerrank.com/challenges/py-hello-world/problem
print("Hello, World!")
#Python If-Else https://www.hackerrank.com/challenges/py-if-else/problem
#!/bin/python3
N = int(input())
if N%2 == 0:
if 2 <= N <= 5:
print('Not Weird')
elif 6 <= N <= 20 :
print('Weird')
elif N > 20:
print('Not Weird')
else:
print('Weird')
#Arithmetic Operators https://www.hackerrank.com/challenges/python-arithmetic-operators/problem
if __name__ == '__main__':
a = int(input())
b = int(input())
print(a+b)
print(a-b)
print(a*b)
#Python: Division https://www.hackerrank.com/challenges/python-division/problem
if __name__ == '__main__':
a = int(input())
b = int(input())
print(a//b)
print(a/b)
#Loops https://www.hackerrank.com/challenges/python-loops/problem
if __name__ == '__main__':
n = int(input())
for i in range(n):
print(i*i)
#Write a function https://www.hackerrank.com/challenges/write-a-function/problem
def is_leap(year):
leap = False
# Write your logic here
if year%4 == 0 and (year% 400 == 0 or year%100 != 0):
leap = True
return leap
year = int(input())
print(is_leap(year))
#Print function https://www.hackerrank.com/challenges/python-print/problem
if __name__ == '__main__':
n = int(input())
arr = []
for i in range(1,n+1):
arr.append(i)
print(*arr, sep='')
| false |
8be7ea60b1cd7f0ce2ab030b7d25c63b257a686a | MarcusGraetsch/awsrestart | /Exercise_1_ConvertHourintoSeconds.py | 295 | 4.34375 | 4 | hours = input("How many hours to you want to convert into seconds? ")
hours = int(hours)
seconds = hours*3600
print("{} hours are {} seconds!".format(hours, seconds))
print("Now with usage of a function")
def convert_hours (hrs):
sec = hrs * 3600
print(f"{hrs} are {sec}")
convert_hours(8) | true |
eccc6cac4824435c77a7d706f555976b788e7446 | thinkingape46/Full-Stack-Web-Technologies | /Python/regular_expressions.py | 798 | 4.28125 | 4 | # Regular expressions
# Import regular expressions
import re
# mytext = "I am from Earth"
# USING REGULAR EXPRESSIONS TO FIND THE MATCH
# if re.search("Earth", mytext):
# print("MATCH found")
# else:
# print("MATCH not found")
# x = re.search("Earth", mytext)
# FIND THE START AND END INDEX OF THE MATCH
# print(x)
# print(type(x))
# print(x.start())
# print(x.end())
# USING REGULAR EXPRESSION TO SPLIT THE STRING.
# REMEMBER THAT THIS METHOD IS ALREADY BUILT INTO STRINGS.
# split_term = "@"
# email = "hello@gmail.com"
# output = re.split(split_term, email)
# print(output)
# FIND ALL INSTANCES OF THE MATCH.
# my_text = "the cat can walk like a cat, what else a cat can do?"
# x = re.findall("cat", my_text)
# print(x)
# You len() method to find the number of instances
# Meta | true |
0f76462a6eca506d11f58d6f1314a1a175ddfd5f | AdamJSoftware/iti1120 | /assignments/A2/a2_part2_300166171.py | 1,935 | 4.21875 | 4 | # Family name: Adam Jasniewicz
# Student number: 300166171
# Course: ITI 1120
# Assignment Number 2
# year 2020
########################
# Question 2.1
########################
def min_enclosing_rectangle(radius, x, y):
'''
(Number, Number, Number) -> (Number, Number)
Description: Calculates the x and y-coordinates of the bottom left corner of the smallest axis-aligned rectangle that could contain the circle
Preconditions: All 3 numbers are real numbers (if radius is negative function will return none)
'''
if radius < 0:
return None
return (x-radius, y-radius)
########################
# Question 2.2
########################
def vote_percentage(results):
'''
(string) -> Number
Description: Calculates the percentage of yes in the paramater results among all other substrings (yes, no and abastained (abstained does not count towards the percentage, it is ignored)
Preconditions: Results only contains yes,no or abstained and at least one yes or no
'''
if(results.count('no') == 0):
return 1
if(results.count('yes') == 0):
return 0
yes = results.count('yes')
no = results.count('no')
return yes/(yes+no)
########################
# Question 2.3
########################
def vote():
'''
(None) -> None
Description: Invokes the user to enter a string of yes', no's and abastained's, after it prints if the vote is unanimous, a super majority, simple majority or if it fails
Preconditions: Input contains only yes', no's and abastains
'''
result = vote_percentage(
input("Enter the yes, no, abstained votes one by one and then press enter: "))
if result == 1:
print("proposal passes unanimously")
elif result >= 2/3:
print("proposal passes with super majority")
elif result >= .5:
print("proposal passes with simple majority")
else:
print("proposal fails")
| true |
7f2c16d15d19183ceabdbcd7ea311bc4f4c27838 | ph4ge/ost-python | /python1_Lesson06/src/word_frequency.py | 456 | 4.125 | 4 | """Count the number of different words in a text."""
text = """\
Baa, baa, black sheep,
Have you any wool?
Yes sir, yes sir,
Three bags full;
One for the master,
And one for the dame,
And one for the little boy
Who lives down the lane."""
for punc in ",?;.":
text = text.replace(punc, "")
freq = {}
for word in text.lower().split():
freq[word] = freq.get(word, 0)+1
for word in sorted(freq.keys()):
print(word, freq[word])
| true |
17e0981af5496c8fe8a3c05e7d2ef15b2681064e | Benkimeric/number-game | /number_guess.py | 863 | 4.1875 | 4 | import random
def main():
global randomNumber
randomNumber = random.randrange(1, 101)
# print(randomNumber)
number = int(input("I have generated a Random number between 1 and 100, please guess it: "))
guess(number)
# guess method with while loop to loop when user does not give correct guess
def guess(number1):
correct = False
while correct is False:
if number1 > randomNumber:
print("That is high. Try again with a lower number.")
elif number1 < randomNumber:
print("That is too low. Try again with a larger one.")
elif number1 == randomNumber:
print("Congratulations! You guessed it")
break
number1 = int(input("Guess again? Type your guess here: "))
# calling main method to run the guess method as well as generate first random number
main()
| true |
63c90181fe378d9bb9093d8395ba0f1f147daf26 | shwesinhtay111/Python-Study-Step1 | /list.py | 1,501 | 4.53125 | 5 | # Create list
my_list = [1, 2, 3]
print(my_list)
# lists can actually hold different object types
my_list = ['A string', 23, 100.22, 'o']
print(my_list)
# len() function will tell you how many items are in the sequence of the list
print(len(my_list))
# Indexing and Slicing
my_list = ['one','two','three',4,5]
print(my_list[0])
print(my_list[:3])
new_list = my_list + ['new item']
print(new_list)
# use the * for a duplication method similar to strings
print(new_list*2)
# Basic List Methods
list1 = [1, 2, 3]
list1.append('append me!')
print(list1)
# Use pop to "pop off" an item from the list
list1.pop(0)
print(list1)
# Assign the popped element, remember default popped index is -1
popped_item = list1.pop()
print(popped_item)
# use the sort method and the reverse methods to also effect your lists
new_list = ['a','b','x','b','c']
# Use reverse to reverse order (this is permanent!)
new_list.reverse()
print(new_list)
# Use sort to sort the list (in this case alphabetical order, but for numbers it will go ascending)
new_list.sort()
print(new_list)
# Nesting Lists
# Let's make three lists
lst_1=[1,2,3]
lst_2=[4,5,6]
lst_3=[7,8,9]
# Make a list of lists to form a matrix
matrix = [lst_1,lst_2,lst_3]
print(matrix)
# Grab first item in matrix object
matrix[0]
# Grab first item of the first item in the matrix object
matrix[0][0]
# List Comprehensions
# Build a list comprehension by deconstructing a for loop within a []
first_col = [row[0] for row in matrix]
print(first_col)
| true |
723cfd942791ed9266f240781f58118cb30ddea9 | shwesinhtay111/Python-Study-Step1 | /abstract_class.py | 1,280 | 4.6875 | 5 | # abstract class is one that never expects to be instantiated. For example, we will never have an Animal object, only Dog and Cat objects, although Dogs and Cats are derived from Animals
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def speak(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
class Dog(Animal):
def speak(self):
return self.name+' says Woof!'
class Cat(Animal):
def speak(self):
return self.name+' says Meow!'
fido = Dog('Fido')
isis = Cat('Isis')
print(fido.speak())
print(isis.speak())
# Special Methods- __init__(), __str__(), __len__() and __del__() methods
class Book:
def __init__(self, title, author, pages):
print("A book is created")
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return "Title: %s, author: %s, pages: %s" %(self.title, self.author, self.pages)
def __len__(self):
return self.pages
def __del__(self):
print("A book is destroyed")
book = Book("Python Rocks!", "Jose Portilla", 159)
#Special Methods Usage
print(book)
print(len(book))
del book | true |
3d20fa99eae7df1270b21c6a08bd3cc5d6adb375 | ocmadin/molssi_devops | /util.py | 694 | 4.4375 | 4 | """
util.py
A file containing utility functions.
"""
def title_case(sentence):
"""
Convert a string into title case.
Title case means that the first letter of each word is capitalized with all other letter lower case
Parameters
----------
sentence : str
String to be converted into title case.
Returns
-------
title : str
String in title case format.
Example
-------
>>> title_case("ThiS iS a STriNG To bE coNVERTed")
'This Is A String To Be Converted'
"""
words = sentence.split()
title = ""
for word in words:
title = title + word[0].upper() + word[1:].lower() + " "
return title
| true |
4f46f746f21e445f71ea8fc61155dff62e3ce033 | ToBeTree/cookbookDemo | /1-数据结构和算法/1-19转换计算.py | 610 | 4.15625 | 4 | # 需要灵活使用生成器,避免内存消耗
s = {'name', 12, 11.11}
print(','.join(str(a) for a in s))
nums = [1, 2, 3, 6, 7]
# 生成器
s = sum(s * s for s in nums)
print(s)
# 下面的方式会生成一个临时的列表
s = sum([s * s for s in nums])
print(s)
# 命名元组不能修改但是_replace可以创建一个新的对象替代
from collections import namedtuple
Student = namedtuple('Student', ['name', 'age', 'date', 'grade'])
s1 = Student('peter', '21', None, None)
s2 = Student('ali', '22', '0824', '10')
print(s1)
print(s2)
s1_c = s1._replace(name='wyq')
print('after change:', s1_c)
| false |
12f4625a421f85e40f4ab2700795fceb8e53acad | TLTerry23/CS30practice | /CS_Solutions/Thonnysolutions/3.3.2Area_of_figures.py | 791 | 4.4375 | 4 | # Area Calculator
# Put Your Name Here
# Put the Date Here
choice=input("What do you want to find the area of? Choose 1 for rectangle, 2 for circle, or 3 for triangle.")
if choice=='1':
rectangle_width=float(input("What is the width of your rectangle?"))
rectangle_height=float(input("What is the length of your rectangle?"))
print("The area of your rectangle is", rectangle_width*rectangle_height)
elif choice=='2':
circle_radius=float(input("What is the radius of your circle?"))
print("The area of your circle is", circle_radius*3.14**2)
else:
triangle_base=float(input("What is the base of your triangle?"))
triangle_height=float(input("What is the height of your triangle?"))
print("The area of your triangle is", 0.5*triangle_base*triangle_height)
| true |
a2781049e4ac8d2f94355326498919ad5501cd25 | brettmadrid/Algorithms | /recipe_batches/recipe_batches.py | 1,409 | 4.25 | 4 | #!/usr/bin/python
import math
def recipe_batches(recipe, ingredients):
batches = math.inf
'''
First check to see if there are enough ingredients to satisfy the recipe requirements
'''
if len(recipe) > len(ingredients):
return 0
'''
Now check to see if there are enough of each ingredient in the ingredients dictionary. Since the ingredient order is the same in both dictionaries, we can compare the index values for each against each other
'''
for i in recipe:
if ingredients[i] < recipe[i]: # if not enough ingredients
return 0
# calc batches that can be made for each ingredient
batch_calc = ingredients[i] // recipe[i]
# store lowest value of batches possible after each ingredient check
if batch_calc < batches:
batches = batch_calc
return batches
# print(recipe_batches({ 'milk': 100, 'butter': 50, 'cheese': 10 }, { 'milk': 200, 'butter': 100, 'cheese': 10 }))
if __name__ == '__main__':
# Change the entries of these dictionaries to test
# your implementation with different inputs
recipe = {'milk': 100, 'butter': 50, 'flour': 5}
ingredients = {'milk': 132, 'butter': 48, 'flour': 51}
print("{batches} batches can be made from the available ingredients: {ingredients}.".format(
batches=recipe_batches(recipe, ingredients), ingredients=ingredients))
| true |
f8fa6b77b71bd50acf2cbddeff370e0b2709d3bf | barvaliyavishal/DataStructure | /Cracking the Coding Interview Exercises/Linked Lists/SinglyLinkedList/RemoveDups.py | 741 | 4.3125 | 4 | from LinkedList import LinkedList
class RemoveDuplicates:
# Remove duplicates Using O(n)
def removeDuplicates(self, h):
if h is None:
return
current = h
seen = set([current.data])
while current.next:
if current.next.data in seen:
current.next = current.next.next
else:
seen.add(current.next.data)
current = current.next
obj = LinkedList()
obj.add(1)
obj.add(2)
obj.add(3)
obj.add(3)
obj.add(4)
obj.add(5)
obj.add(7)
obj.add(9)
obj.add(9)
obj.add(2)
print("Before Removing Duplicates")
obj.show()
obj1 = RemoveDuplicates()
obj1.removeDuplicates(obj.head)
print()
print("After Removing Duplicates")
obj.show()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.