blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
008a940140a4dd9f3532dddf90b3ec61b8dc18a3 | HarshithaKP/Python-practice-questions- | /7.py | 347 | 4.6875 | 5 | #Implement a program to reverse a string (without standard library function)
def reverse_string(string):
newstr=' '
for i in string:
newstr=i+newstr
print("Originsal string :",string)
print("Reversed string :",newstr)
def main():
string=input("Enter the string to be reversed :" )
reverse_string(string)
if __name__ == '__main__':
main() | true |
9cf2470e431829653e6e90e4f730e83b43247331 | HarshithaKP/Python-practice-questions- | /1.py | 1,226 | 4.4375 | 4 | # Implement a menu based program for Arithemetic Calculator
import sys
def addition(num1,num2):
summ=num1+num2;
print("Sum of two numbers is :",summ);
def subtraction(num1,num2):
diff=num1-num2;
print("Diffetence of two numbers is :",diff);
def multiplication(num1,num2):
mul=num1*num2;
print("Multiplication of two numbers is :",mul);
def division(num1,num2):
div=num1/num2;
print("Division of two numbers is :",div);
def modulus(num1,num2):
mod=num1%num2;
print("Remainder is :",mod);
def main():
print("Simple Arithemetic calculatior ")
while True:
num1=int(input("Enter the first number :"));
num2=int(input("Enter the second number :"));
print("1 : Addition ")
print("2 : Subtraction ")
print("3 : Multiplication ")
print("4 : Division ")
print("5 : Remainder ")
print("q : Quit ")
option=input("Choose the operation to perform : ")
if(option=='1'):
addition(num1,num2)
elif(option=='2'):
subtraction(num1,num2)
elif(option=='3'):
multiplication(num1,num2)
elif(option=='4'):
division(num1,num2)
elif(option=='5'):
modulus(num1,num2)
elif(option=='q'):
sys.exit()
else:
print("Enter the correct option !")
if __name__ == '__main__':
main()
| true |
8c23f636385b10ecec8b31caa40f56cdd93ccc0d | HarshithaKP/Python-practice-questions- | /10.py | 729 | 4.5 | 4 | # Implement a program to find the square root of a function using newton-rapson method.
# babylonial method for finding square root of a number (derived from newton-rapson method)
# 1 Start with an arbitrary positive start value x (the closer to the root, the better).
# 2 Initialize y = 1.
# 3. Do following until desired approximation is achieved.
# a) Get the next approximation for root using average of x and y
# b) Set y = n/x
def square_root(n):
x = n
y = 1
e = 0.000000000000001
while(x-y > e):
x = (x+y)/2
y = n/x
return x
def main():
try:
n = int(input("Enter a number :"))
print(" Square root is: \n", square_root(n))
except:
print("Enter a valid number")
if __name__=="__main__":
main()
| true |
3b96225e0dbd61af9635bc30d2b1b98a87a1b04f | HarshithaKP/Python-practice-questions- | /21.py | 365 | 4.125 | 4 | # Implement a program to find the euclidean distance of two points.
import math
def euclidean_distance():
p1=[3,4]
p2=[4,9]
print("Point 1:",p1)
print("point 2:",p2)
distance=math.sqrt(((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2))
print("Euclidean distance between two points is :",distance)
def main():
euclidean_distance()
if __name__ == '__main__':
main() | true |
49e8d72a170401a58a96307dfba8510964249049 | sainarasimhayandamuri/pythonsetsexplanations | /twelve.py | 2,095 | 4.3125 | 4 | """
What is a set?
Set is also a collection of similar or different types of elements.
How to create a set?
1.We can create a set using curly braces{}
2.We can also create set with keyword set
3.It is also mutable object
4.Set does not allow duplicate elements.
5.Set also does not follow any order.
"""
s1 = set({10,20})
print("s1:\t",s1)
s2 = {10,20,30,30,40,40,50,70}
print("s2:\t",s2)
print("Address OF Set:\t",id(s2))
s2.remove(70)
print("Set2 after removing:\t",s2)
s2.pop()
print("set after popping:\t",s2)
l1 = [10,20,30]
l1.pop(0)
print(l1)
s2.discard(50)
print("set after discarding:\t",s2)
#both discard() and remove() methods are used to delete elements...........
s2.clear()
print("set after clearing:\t",s2)
s2 = {10,20,30,40}
s3 = s2.copy()
print("my set:\t",s2)
print("copy set:\t",s3)
s1 = {10,20,30,40,50}
s2 = {10,30,50,70,90}
s3 = s1.difference(s2)
s4 = s2.difference(s1)
print("s1:\t",s1)
print("s2:\t",s2)
print("s3:\t",s3)
print("s4:\t",s4)
s1.difference_update(s2)
print("s1:\t",s1)
print("s2:\t",s2)
s5={"vijji","naga","lakshmi","jyothi"}
s6={"sai","devika","vijji","naga"}
s7 = s5.intersection(s6)
print("s5:\t",s5)
print("s6:\t",s6)
print("s7:\t",s7)
s5={"vijji","naga","lakshmi","jyothi"}
s6={"sai","devika","vijji","naga"}
s6.intersection_update(s5)
print("s5:\t",s6)
s5={"vijji","naga","lakshmi","jyothi"}
s6={"sai","devika","vijji","naga"}
s8 = s5.union(s6)
print("UNION SET S8:\t",s8)
s5={"vijji","naga","lakshmi","jyothi"}
s6={"sai","devika","vijji","naga"}
s5.update(s6)
print("Set after updating s5:\t",s5)
s5={"vijji","naga","lakshmi","jyothi"}
s6={"sai","devika","vijji","naga"}
print("s5.isdisjoint(s6):\t",s5.isdisjoint(s6))
s5={"vijji","naga","lakshmi","jyothi"}
s6={"sai","devika"}
print("s5.isdisjoint(s6):\t",s5.isdisjoint(s6))
s7={"vijji","naga","lakshmi","jyothi"}
s8={"sai","devika"}
print("s7.issubset(s8):\t",s7.issubset(s8))
s9 = {1,2,3,4,5}
s10 = {1,2,3,4,5,6,7,8,9}
s11 = s10.issuperset(s9)
print("s11:\t",s11)
s1 = {1,2,3,4,5}
s2 = {1,3,7}
s3 =s2.symmetric_difference(s1)
s1.symmetric_difference_update(s2)
print("s3:\t",s3)
print("s1:\t",s1) | true |
5fff235206b81cf67317b49816268eb7903ffaa8 | nrivkin/ToolBox-WordFrequency | /frequency.py | 2,585 | 4.46875 | 4 | """ Analyzes the word frequencies in a book downloaded from
Project Gutenberg
Noah Rivkin
"""
import string
import os
def get_word_list(file_name):
""" Reads the specified project Gutenberg book. Header comments,
punctuation, and whitespace are stripped away. The function
returns a list of the words used in the book as a list.
All words are converted to lower case.
"""
if os.path.exists(file_name): # checks if the file has already been downloaded
f = open(file_name, 'r')
lines = f.readlines() # reads each line of the text into lines
currline = 0
while lines[currline].find('START OF THIS PROJECT GUTENBERG EBOOK') == -1: # reads threough lines until it finds the end of the intro
currline += 1 # moves onto next line
lines = lines[currline + 1:] # lines is every thing from the line after START OF ... to the end of the text
f.close
word_list = []
for line in lines:
line = line.split()
for word in line:
word = word.strip(string.punctuation + string.whitespace)
word = word.lower()
word_list.append(word)
return word_list
else:
print ("\nError: File not found\n")
return None
def get_top_n_words(word_list, n):
""" Takes a list of words as input and returns a list of the n most frequently
occurring words ordered from most to least frequently occurring.
word_list: a list of words (assumed to all be in lower case with no
punctuation
n: the number of words to return
returns: a list of n most frequently occurring words ordered from most
frequently to least frequently occurring
"""
histogram = {}
for word in word_list:
if word not in histogram:
histogram[word] = 1
else:
histogram[word] += 1
top_n_words = []
top_n_freqs = []
for i in range(n):
most_common = ''
most_times = 0
for key in histogram:
if key not in top_n_words:
num = histogram[key]
if num > most_times:
most_times = num
most_common = key
top_n_words.append(most_common)
top_n_freqs.append(most_times)
return top_n_words
if __name__ == "__main__":
print("Running WordFrequency Toolbox")
print(string.punctuation + string.whitespace)
word_list = get_word_list('pg32325.txt')
top_words = get_top_n_words(word_list, 100)
for word in top_words:
print(word)
| true |
72fc444c82cf6eff9b270c8ad19d4f9411970669 | juliusbc/hackerrank | /is-fibo.py | 728 | 4.28125 | 4 | import math
# implementing https://en.wikipedia.org/wiki/Square_number#Properties
def is_square(num):
x = str(num)
# A square number can end only with digits 1, 4,6, 9, 00, or 25
if (x[-1:] not in ['1', '4', '6', '9'] and
x[-2:] not in ['00', '25']):
return False
# could be improved using newton's method and stopping when it's clear it isn't an integer
return math.sqrt(num).is_integer()
# implementing https://en.wikipedia.org/wiki/Fibonacci_number#Recognizing_Fibonacci_numbers
for _ in range(int(input())):
x = int(input())
# if and only if one or both of 5x^2+4 or 5x^2-4 is a perfect square
print("IsFibo" if is_square(5*x*x+4) or is_square(5*x*x-4) else "IsNotFibo") | true |
37b98aa594988bd812b545202cedac70eeabf7f7 | hp04301986/leetcode | /125ValidPalindrome.py | 821 | 4.21875 | 4 | """
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
"""
import re
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
ss = re.sub("\W", "", s.strip())
if not ss or len(ss) == 1:
return True
l = list(ss.lower())
l.reverse()
rss = "".join(l)
if ss.lower() == rss:
return True
return False
sol = Solution()
print(sol.isPalindrome("ab"))
| true |
23e56cb5cc891b3be3c537463b436461c0eb039e | hp04301986/leetcode | /069Sqrt.py | 463 | 4.3125 | 4 | """
Implement int sqrt(int x).
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncate
"""
import math
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
return math.floor(math.sqrt(x))
| true |
f13faf559f66f2229939efd834f0ff801176e179 | sahayajessemonisha/python-programming | /beginner/Factorial number.py | 225 | 4.28125 | 4 | a=5
factorial=1
if(a<0):
print("the factorial number is negative")
elif(a==0):
print("the factorial number 0 is 1")
else:
for i in range(1,a+1):
factorial=factorial*i
print("the factorial of",a,"is",factorial)
| true |
dd0bdb12c71b9ccd8d79fb379d4cdb78d3dd6dd7 | pkmartin82/pythonsnork | /src/main/python/com/pkm/helloworld/datetimes.py | 459 | 4.4375 | 4 | from datetime import datetime, timedelta
# the .now() function returns a datetime object
current_date = datetime.now()
print("Today is {}".format(current_date))
# timedelta function example
one_day = timedelta(days=1)
yesterday = current_date - one_day
print("Yesterday was {}".format(yesterday))
thirty_six_hours = timedelta(days = 1.5)
day_and_a_half_ago = current_date - thirty_six_hours
print("Day and a half ago = {0}".format(day_and_a_half_ago))
| true |
43b2f7415df6ae2fcabfa03726bd45226342cc3d | symonk/python-musings | /object_data_model/__bool__.py | 1,222 | 4.4375 | 4 | """
Dunder __bool__ is used to implement custom `truthy` testing. bool(obj) is the built in function
that will call an objects dunder __bool__ implementation.
In the event that dunder __bool__() is not defined; dunder __len__() will be invoked by the bool(obj)
built in. In this scenario; the object is considered `True` if dunder __len__() returns a non-zero
value.
If a class does not define dunder __bool__() OR dunder __len__() then all of its instances are considered
`True`.
"""
class Both:
"""
As you can see here; bool is implemented so __len__() is not accounted for when bool(Both()) is called.
"""
def __len__(self) -> int:
return 0
def __bool__(self) -> bool:
return True
class LenOnly:
def __len__(self) -> int:
# return -1 raises a ValueError in python; positive integers only
# return 0; would create bool(LenOnly()) to be False
return 1 # All instances of LenOnly are `True`
class BoolOnly:
def __bool__(self) -> bool:
# return False; all instances would be considered False
return True; all instances of BoolOnly are `True`
class Default:
# By default; no dunder __len__() or __bool__() will result in instances being `True`
...
| true |
8ab298a4c77f24705dff69cda62ff8174ebc4624 | symonk/python-musings | /object_data_model/__repr__.py | 1,678 | 4.28125 | 4 | """
dunder __repr__ is called by the builtin repr() function and should
look like a valid python expression, usable to reconstruct the object.
if a class defines a dunder __repr__() but not a dunder __str__() then
the repr will be called in place of __str__() for things like print(x);
format(x); str(x).
__repr__() is used for debugging and should be unambiguous.
"""
class Train:
def __init__(self, wheels: int, color: str, power_mechanism: str) -> None:
self.wheels = wheels
self.color = color
self.power_mechanism = power_mechanism
def __str__(self) -> str:
return f"A {self.power_mechanism} train with: {self.wheels} wheels"
def __repr__(self) -> str:
return f"Train(wheels={self.wheels}, color={self.color}, power_mechanism={self.power_mechanism})"
class TrainTwo:
def __init__(self, wheels: int, color: str, power_mechanism: str) -> None:
self.wheels = wheels
self.color = color
self.power_mechanism = power_mechanism
# When __str__() is not implemented; repr is called in place by the builtins (print|str|format)
def __repr__(self) -> str:
return f"Train(wheels={self.wheels}, color={self.color}, power_mechanism={self.power_mechanism})"
train = Train(36, 'red', 'steam')
str(train) # 'A steam train with: 36 wheels'
repr(train) # 'Train(wheels=36, color=red, power_mechanism=steam)
train_two = TrainTwo(100, 'green', 'electric')
print(train_two) # TrainTwo(wheels=100, color=green, power_mechanism=electric)
str(train_two) # TrainTwo(wheels=100, color=green, power_mechanism=electric)
"formatted: {}".format(train_two) # TrainTwo(wheels=100, color=green, power_mechanism=electric)
| true |
ec2ffd1699ba3b68ad6f2287282917dd45c6c365 | seun-beta/OOP | /shoe.py | 757 | 4.125 | 4 | class Shoe:
# Class variables 'brand' & 'group'
brand = 'Nike'
group = 'Men'
# Instance variables 'name' & 'size' from the constructor method
def __init__(self, name, size):
self.name = name
self.size = size
# Instance variable 'outsole' from the method
def outsole_material(self, outsole):
return ("The outsole material is " + outsole)
def main():
shoe_1 = Shoe('Air Max', 42)
print(shoe_1.name)
print(shoe_1.size)
print(shoe_1.brand)
shoe_1.outsole_material('Natural Rubber')
print()
shoe_2 = Shoe('React', 56)
print(shoe_2.brand)
print(shoe_2.name)
print(shoe_2.size)
shoe_2.outsole_material('Polyuretane')
if __name__ =='__main__':
main()
| true |
4c9e2f64c153ed5d007cc244c880dfd33e186eb3 | bryanpramana/PythonClass | /HW1.py | 710 | 4.125 | 4 | def main():
payment1=float(input('Please Enter the payment Amount: '))
term=int(input('Please Enter the Term You Wish in Year: '))
rate = float(input('Please Enter the Interest Rate: '))
while True:
if rate<0 or rate>1.0:
rate = float(input('Please Enter the Interest Rate in the Range 0 to 1.0:'))
else:
Presentvalue=payment1*((1-(1+rate)**(-term))/rate)
print('Given')
print('Payment Amount:','${:,.2f}'.format(payment1))
print('Interest Rate:', '{0:.1f}%'.format(rate * 100))
print('Term:',term,'years')
print('The present value is','${:,.2f}'.format(Presentvalue))
break
main()
| true |
078260efef71ac8235de9a7a039cb8c22c9634cc | rkranjancs1014/pythons | /suffile_using_randint.py | 241 | 4.125 | 4 | def shuffile_using_randint(x):
"""This function is use to suffle the iterable object using randint"""
for f in range(len(x)):
a = randint(0, len(x)-1)
b = randint(0, len(x)-1)
x[a], x[b] = x[b], x[a]
print(x)
| true |
7444735c76e155a50430e45aba6f297a01d7db36 | hmshepard/Contacts | /README.md | 2,400 | 4.28125 | 4 | #!/usr/bin/env python3
import csv
FILENAME = "contacts.csv"
def write_contacts(contacts):
with open(FILENAME, "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(contacts)
def read_contacts():
contacts = []
with open(FILENAME, newline="") as file:
reader = csv.reader(file)
for row in reader:
contacts.append(row)
return contacts
def list_contacts(contacts):
for i in range(len(contacts)):
contact = contacts[i]
print(str(i+1) + ". " + contact[0])
print()
def view_contact(contacts):
index= int(input("Number: "))
if index < 1 or index > len(contacts):
print("This value does not exist. Please enter an existing value.\n")
else:
contact = contacts.pop(index)
print(contact[0] + ", "+ contact[1] + ", "+ contact[2])
print()
def add_contact(contacts):
name = input("Name: ")
email = input("Email: ")
phone_number=input("Phone number: ")
contact = []
contact.append(name)
contact.append(email)
contact.append(phone_number)
contacts.append(contact)
write_contacts(contacts)
print(name + " was added.\n")
def delete_contact(contacts):
index = int(input("Number: "))
if index < 1 or index > len(contacts):
print("This value does not exist. Please enter an existing value.\n")
else:
contact = contacts.pop(index - 1)
write_contacts(contacts)
print(contact[0] + " was deleted.\n")
def display_menu():
print("Contact Manager")
print()
print("COMMAND MENU")
print("list - Display all contacts")
print("view - view a contact")
print("add - Add a contact")
print("del - Delete a contact")
print("exit - Exit program")
print()
def main():
display_menu()
contacts = read_contacts()
while True:
command = input("Command: ")
if command.lower()== "list":
list_contacts(contacts)
elif command.lower()=="view":
view_contact(contacts)
elif command.lower()=="add":
add_contact(contacts)
elif command.lower()=="del":
delete_contact(contacts)
elif command.lower()=="exit":
break
else:
print("This is not a valid command. Please enter a valid command.\n")
print("Bye!")
if __name__ == "__main__":
main()
| true |
716473579813cb75e18affb84bbf284f812841b0 | jamescole/cp1404practicals | /prac_03/oddName.py | 712 | 4.3125 | 4 | """
Asks the user for their name, checks it isn't blank, then prints every second letter in the name.
James Cole
"""
def main():
name = get_name()
step = int(input("Enter in step value: "))
print(get_every_nth_letter(name, step))
def get_name():
"""
get user's name, repeatedly asking for input until a non-empty string is entered
"""
name = input("Enter your name: ")
while name == "":
print("Error, empty name string")
name = input("Enter your name: ")
return name
def get_every_nth_letter(string, step):
"""
return a string containing every Nth letter (where N is indicated by 'step') of string
"""
return string[step - 1::step]
main()
| true |
9958e9f6b5500eb87fe7655103cd4240635f6fbb | jamescole/cp1404practicals | /prac_02/ascii_table.py | 1,470 | 4.1875 | 4 | import math
import sys
MIN_ASCII_CODE_NUMBER = 33
MAX_ASCII_CODE_NUMBER = 127
character = raw_input("Enter a character: ").strip()
ascii_code = ord(character)
print("The ASCII code for {} is {}".format(character, ascii_code))
valid_number = False
while not valid_number:
prompt = "Enter a number between {} and {} (inclusive): ".format(MIN_ASCII_CODE_NUMBER, MAX_ASCII_CODE_NUMBER)
ascii_code_number = int(raw_input(prompt).strip())
if MIN_ASCII_CODE_NUMBER <= ascii_code_number <= MAX_ASCII_CODE_NUMBER:
valid_number = True
else:
print("Error, invalid number entered - outside of specified range")
print("The character for {} is {}".format(ascii_code_number, chr(ascii_code_number)))
for curr_code_number in range(MIN_ASCII_CODE_NUMBER, MAX_ASCII_CODE_NUMBER + 1):
print("{:3} {:>3}".format(curr_code_number, chr(curr_code_number)))
print("\n\n")
number_of_columns = int(raw_input("How many columns for ASCII display table? "))
number_of_ascii_codes_to_print = MAX_ASCII_CODE_NUMBER - MIN_ASCII_CODE_NUMBER
number_of_rows = int(math.ceil(float(number_of_ascii_codes_to_print) / number_of_columns))
curr_code_number = MIN_ASCII_CODE_NUMBER
for table_rows in range(number_of_rows):
for column_index in range(number_of_columns):
if not curr_code_number > MAX_ASCII_CODE_NUMBER:
sys.stdout.write("{:7} {}".format(curr_code_number, chr(curr_code_number)))
curr_code_number += 1
print("")
| true |
290a1b191a93dcb5ee107d55e976877bb31ddd8f | Rohith-githu/python-projects | /python series/caluculator.py | 412 | 4.15625 | 4 | operat = input('enter the operation(+,-,*,/)')
firstnum = float(input('enter the first number'))
secondnum = float(input('enter the second number'))
if operat == '+':
print(firstnum + secondnum)
elif operat == '-':
print(firstnum - secondnum)
elif operat == '*' :
print(firstnum * secondnum)
elif operat == '/' :
print(firstnum / secondnum)
else :
print('pls check the input and try again')
| true |
35271790422a97d5a5fe70654b74f74da9794507 | Rohith-githu/python-projects | /Python course/varibles.py | 355 | 4.34375 | 4 | first_name = 'Rohith '
print(first_name)
last_name = 'venkata sai'
print(last_name)
full_name = first_name + last_name
print(full_name)
"""
now lets get the input from users
"""
firstname = input('what is your first name')
lastname = input('what is your last name')
fullname = 'hello {1} {0}'.format(firstname,lastname)
print(fullname)
print(type(firstname)) | true |
0a22bd6857f98cfd7c765d9f58c43bae4ac52a7b | SyTuan10/C4T16 | /Session7/emailhople.py | 431 | 4.1875 | 4 | while True:
email = input("Nhap Email : ")
if len(email)<8:
print("Chua Du So Ky Tu")
elif email.isalpha():
print("Email Must Have Number")
elif email.isdigit():
print("Email Must Have Alphabet")
elif "@" not in email:
print("Email Phai Co @")
elif "." not in email:
print("Email Phai Co .")
else:
break
print("Your Email : ",email)
print("You Have Done") | false |
598ba9e3e4f4b446bb797e9986793b51d369b7e3 | Vale-Mais/birthdays | /checker.py | 1,101 | 4.125 | 4 | """ this module has 3 functions that interact
with the database to print the whole database,
return the specific birthday of a certain person,
and check if a known person given as an input by the
user is present in the database"""
import csv
import pandas as pd
def print_birthdays():
print('Welcome to the birthday dictionary.' +
'We know the birthdays of these people:')
db = pd.DataFrame(pd.read_csv('people_birthday.csv'))
return print(db)
def return_birthday(name):
name = name.lower()
db = pd.DataFrame(pd.read_csv('people_birthday.csv'))
people = db["Person"].str.lower()
if name in people.values:
return print('{}\'s birthday is {}.'.format(name,
db["Birthday"].loc[people == name].values[0]))
else:
return print('Sadly, we don\'t have {}\'s birthday.'
.format(name))
def check_person(person):
person = person.lower()
db = pd.DataFrame(pd.read_csv('people_birthday.csv'))
people = db["Person"].str.lower()
if person in people.values:
return True
return False
| true |
bf253ddbbb01b79c9ef6e2de0bb8e825e8b3c8e2 | RachelA314/Aboutme | /python/dictionary_survey.py | 1,364 | 4.15625 | 4 | #This project takes in a question and an answer and assigns it
#to a dictionary.
#while loop
#use a variable as a condition to exit out of while loop
addQues = "YES"
#initilizalize dictionary
inputDictionary = {}
#inputDictionary = {}
listOfAnswers = []
while True:
#variable to take in the question
key = input("Type in a question: ")
#variable to take in answer
answer = input("Answer: ")
while answer == "":
print("Not valid answer, try again")
print(key)
answer = input("Answer: ")
#set key:answer
inputDictionary[key] = answer
# 'Diana' = 30
addQues = input("Do you want to add another question?")
if addQues == "no":
newUser = input("Do you want to add a new user? ")
newUser2 = input("Do you want me to give you a question? ")
if newUser == "yes":
listOfAnswers.append(inputDictionary)
inputDictionary = {}
continue
elif newUser == "no":
listOfAnswers.append(inputDictionary)
if newUser2 == "yes":
newUser2 = input("What is your favorite color?")
answer = input("Answer: ")
inputDictionary = {}
continue
elif newUser2 == "no":
listOfAnswers.append(inputDictionary)
break
#print_list
print(listOfAnswers)
| true |
669442a83ad5c0ab18c6e3ad4bc95e4e6b10b45b | RachelA314/Aboutme | /DataVisualizationProject/TwitterData/Twitter_data_code_along.py | 720 | 4.28125 | 4 | '''
In this program, we print out all the text data from our Twitter JSON file.
'''
import json
#Open JSON file. Tag file as "r" read only because we are only
#looking at the data.
tweetFile = open("../TwitterData/tweets_small.json","r")
#we use the JSON file to get data from the file as JSON data
tweetData = json.load(tweetFile)
#Close the file now that we have locally stored the data
tweetFile.close()
#Print the data of the ONE tweet
#The [0] denotes the *first* tweet object
print("Tweet id:", tweetData[0]["id"])
#Print text of first object
print("Tweet text: ", tweetData[0]["text"])
#Print out "text" key in JSON file
for idx in range(len(tweetData)):
print("Tweet text: " + tweetData[idx]["text"])
| true |
180d070bddb59a34b22c2027442532d2a4f17079 | EldarAshirovich/Eldar_python | /lesson3_3.py | 853 | 4.15625 | 4 | import pydoc
#Autor Sabri Eldar
#3. Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов.
temp = []
def my_func(num_1, num_2, num_3):
"""
Сумма наибольших двух аргументов.
param: num_1(int)
param: num_2(int)
param: num_3(int)
result: res(str)
"""
if num_1>num_2 or num_1>num_3:
temp.append(num_1)
if num_2>num_1 or num_2>num_3:
temp.append(num_2)
if num_3>num_1 or num_3>num_2:
temp.append(num_3)
res = temp[0] + temp[1]
res = f"Сумма наибольших двух аргументов из чисел: {num_1}, {num_2}, {num_3}\nЯвляется: {temp[0]} + {temp[1]} = {res}"
return res
result = my_func(32, 7, 14)
print(result)
| false |
e268e7d46b311a9928bcf114366780caec9f8866 | klmr/argx | /default.py | 1,069 | 4.125 | 4 | #!/usr/bin/env python
import argparse
def default_arg(default):
"""
Create an action for optional arguments which provides two defaults.
Use as argument `action` to the argparse.ArgumentParser.add_argument` method.
This defines a command line argument which, in addition to its normal default,
has an additional default value which is taken when this optional argument is
present, but has no value. For instance:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--s', default = 'a', nargs = '?', action = default_arg('b'))
>>> parser.parse_args([])
Namespace(s='a')
>>> parser.parse_args(['--s'])
Namespace(s='b')
>>> parser.parse_args(['--s', 'c'])
Namespace(s='c')
"""
class DefaultArg(argparse.Action):
def __call__(self, parser, namespace, value, option_string):
if value is None:
setattr(namespace, self.dest, default)
else:
setattr(namespace, self.dest, value)
return DefaultArg
| true |
488bd3ed99ee530fedd2c245319bfdf00d1a8126 | priyankitshukla/CurdwithDjango | /core/Topic-9.2_Function_PassByValue_VS_Ref.py | 888 | 4.25 | 4 | # All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter
# refers to within a function, the change also reflects back in the calling function. For example −
# Function definition is here
def changeme( mylist ):
#"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print("Values inside the function: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print("Values outside the function: ", mylist)
# Function definition is here
def changeme(mylist):
# This changes a passed list into this function
mylist.append([1,2,3,4]);
print("Values inside the function: ", mylist)
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist) | true |
484b3256f7e413e7d25715d0c57d5c8515a1dcdb | gear/learn | /udacity_softwaredev/find_html_tags.py | 1,524 | 4.15625 | 4 | """Find html tags using regex"""
import re
def findtags(text):
tags_pattern = r"""<\s*\w+((\s+\w+(\s*=\s*(".*?"|'.*?'))?)+\s*|\s*)>"""
start_index = 0
tags = []
while start_index < len(text):
tag = re.search(tags_pattern, text[start_index:])
if not tag:
return tags
else:
tags.append(text[start_index+tag.start():start_index+tag.end()])
start_index += tag.end()
return tags
texttest1 = """
My favorite website in the world is probably
<a href="www.udacity.com">Udacity</a>. If you want
that link to open in a <b>new tab</b> by default, you should
write <a href="www.udacity.com"target="_blank">Udacity</a>
instead!
"""
testtext2 = """
Okay, so you passed the first test case. <let's see> how you
handle this one. Did you know that 2 < 3 should return True?
So should 3 > 2. But 2 > 3 is always False.
"""
testtext3 = """
It's not common, but we can put a LOT of whitespace into
our HTML tags, For example, we can make something bold by
doing < b > this < /b >. Though I
don't know why you would ever want to.
"""
def test():
assert findtags(texttest1) == ['<a href="www.udacity.com">',
'<b>',
'<a href="www.udacity.com"target="_blank">']
assert findtags(testtext2) == []
assert findtags(testtext3) == ['< b >']
return 'tests pass'
def main():
print(test())
if __name__ == '__main__':
main()
| true |
01e9f34570cb09645c0270dbb103dd2dcdd73083 | paolokalvo/exercios_sala | /formatção1texto | 395 | 4.28125 | 4 | #!/usr/bin/env python3
# Programa para testar a função format()
s = 'Adoro Python'
# alinha a direita com 20 espaços em branco
print("{0:>20}".format(s))
# alinha a direita com 20 símbolos #
print("{0:#>20}".format(s))
# alinha ao centro usando 10 espaços em branco a esquerda e 10 a direita
print("{0:^20}".format(s))
# imprime só as primeiras cinco letras
print("{0:.5}".format(s))
| false |
cbd14d1555b3411cce6498bf8f2443b1737225a0 | childe/leetcode | /quick-sort/solution.py | 1,276 | 4.125 | 4 | # -*- coding: utf-8 -*-
def quickSort(nums):
"""
>>> from random import shuffle
>>> nums = range(10)
>>> quickSort(nums)
>>> nums
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> nums = range(10)
>>> shuffle(nums)
>>> quickSort(nums)
>>> nums
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
def quickSort2(nums, low, high):
# print nums, low, high
if high - low < 1:
return
f = nums[high]
p = None # point to first num that's bigger than f
for i, n in enumerate(nums[low: high]):
if n >= f:
if p is None:
p = i+low
else:
if p is not None:
nums[i+low], nums[p] = nums[p], nums[i+low]
p += 1
# print '~~~', nums, p
if p is not None:
nums[p], nums[high] = nums[high], nums[p]
# print '!!!', nums
quickSort2(nums, low, p-1)
quickSort2(nums, p+1, high)
else:
quickSort2(nums, low, high-1)
quickSort2(nums, 0, len(nums)-1)
if __name__ == '__main__':
from random import shuffle
nums = range(10)
shuffle(nums)
# nums = [2, 3, 1]
print nums
quickSort(nums)
print nums
| false |
a9e8645b5908b0d74d5ee6d73db7c72c6794f26c | childe/leetcode | /palindrome-number/solution.py | 2,179 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/palindrome-number/
Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
"""
import unittest
class Solution:
# @param {integer} x
# @return {boolean}
def isPalindrome(self, x):
if x < 0:
return False
if x < 10:
return True
n = 0
origin = x
while(x > 0):
x/=10
n+=1
x = origin
i = 0
while(i<=(n-1)/2):
righti = x/(10**i)%10
lefti = x/(10**(n-i-1))%10
if lefti != righti:
return False
i += 1
return True
class TestSolution(unittest.TestCase):
def test_isPalindrome(self):
s = Solution()
self.assertEqual(True, s.isPalindrome(919))
self.assertEqual(False, s.isPalindrome(1000021))
self.assertEqual(True, s.isPalindrome(313))
self.assertEqual(False, s.isPalindrome(-100))
self.assertEqual(True, s.isPalindrome(0))
self.assertEqual(False, s.isPalindrome(100))
self.assertEqual(True, s.isPalindrome(111111))
self.assertEqual(True, s.isPalindrome(1111111))
self.assertEqual(True, s.isPalindrome(1110111))
self.assertEqual(False, s.isPalindrome(123))
import random
for i in range(1000):
x = random.randint(0,100000000000)
rst = str(x) == str(x)[::-1]
self.assertEqual(rst, s.isPalindrome(x))
for i in range(1000):
x = random.randint(0,100000)
x = int(str(x)+str(x)[::-1])
self.assertEqual(True, s.isPalindrome(x))
if __name__ == '__main__':
unittest.main()
| true |
16b8ad4809f9c679ccb45de83bad7e0c8ddff0b9 | childe/leetcode | /search-insert-position/solution.py | 1,333 | 4.21875 | 4 | # -*- coding: utf-8 -*-
'''
https://leetcode-cn.com/problems/search-insert-position/
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
'''
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
s, e = 0, len(nums)-1
while s <= e:
m = (s+e)//2
if target == nums[m]:
return m
if target < nums[m]:
e = m-1
else:
s = m+1
return s
def main():
s = Solution()
nums = [1, 3, 5, 6]
target = 5
a = 2
assert s.searchInsert(nums, target) == a
nums = [1, 3, 5, 6]
target = 2
a = 1
assert s.searchInsert(nums, target) == a
nums = [1, 3, 5, 6]
target = 7
a = 4
assert s.searchInsert(nums, target) == a
nums = [1, 3, 5, 6]
target = 0
a = 0
assert s.searchInsert(nums, target) == a
if __name__ == '__main__':
main()
| true |
c34c0f1ed1507fbbd49503ab57cbee2c0a0371f8 | childe/leetcode | /binary-tree-preorder-traversal/binary-tree-preorder-traversal.py | 1,360 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/binary-tree-preorder-traversal/description/
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
>>> root = TreeNode(1)
>>> root.right = TreeNode(2)
>>> root.right.left = TreeNode(3)
>>> s = Solution()
>>> s.preorderTraversal(root)
[1, 2, 3]
>>> root = TreeNode(1)
>>> s = Solution()
>>> s.preorderTraversal(root)
[1]
"""
if root is None:
return []
rst = []
stack = [root]
while stack:
currentNode = stack.pop()
rst.append(currentNode.val)
if currentNode.right is not None:
stack.append(currentNode.right)
if currentNode.left is not None:
stack.append(currentNode.left)
return rst
| true |
8723fb669dd8cf54f3fe6f438bc0641e9dbe7529 | childe/leetcode | /rotate-image/solution.py | 2,137 | 4.25 | 4 | # -*- coding: utf-8 -*-
'''
https://leetcode-cn.com/problems/rotate-image/
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
'''
def p(matrix):
for l in matrix:
print(l)
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
for level in range(0, (1+n)//2):
for i in range(level, n-1-level):
print(level, i)
x, y = level, i
num = matrix[x][y]
for _ in range(4):
nx, ny = y, n-x-1
num, matrix[nx][ny] = matrix[nx][ny], num
x, y = nx, ny
p(matrix)
def main():
s = Solution()
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
a = [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
s.rotate(matrix)
p(matrix)
assert a == matrix
matrix = [
[5, 1, 9, 11],
[2, 4, 8, 10],
[13, 3, 6, 7],
[15, 14, 12, 16]
]
a = [
[15, 13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7, 10, 11]
]
s.rotate(matrix)
p(matrix)
assert a == matrix
matrix = [
[1, 2],
[3, 4]
]
a = [
[3, 1],
[4, 2]
]
s.rotate(matrix)
p(matrix)
assert a == matrix
if __name__ == '__main__':
main()
| true |
121d2e8a922eb9c5cb66a4bbbd39f835440d7b40 | childe/leetcode | /diagonal-traverse/solution.py | 1,741 | 4.25 | 4 | # -*- coding: utf-8 -*-
'''
https://leetcode-cn.com/problems/diagonal-traverse/
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Explanation:
Note:
The total number of elements of the given matrix will not exceed 10,000.
'''
class Solution(object):
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if len(matrix) == 0:
return []
i, j, rst = 0, 0, []
d = 1
while True:
# print(i, j, matrix[i][j], rst)
rst.append(matrix[i][j])
if i == len(matrix)-1 and j == len(matrix[-1])-1:
break
if d == 1:
if j == len(matrix[i])-1:
i += 1
d = -d
continue
if i == 0:
j += 1
d = -d
continue
i -= 1
j += 1
else:
if i == len(matrix) - 1:
j += 1
d = -d
continue
if j == 0:
i += 1
d = -d
continue
i += 1
j -= 1
return rst
def main():
s = Solution()
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
output = [1, 2, 4, 7, 5, 3, 6, 8, 9]
a = s.findDiagonalOrder(matrix)
print(a)
assert(a == output)
if __name__ == '__main__':
main()
| true |
1484d2c75040a64ca7c273bffa02c755f989b5f1 | childe/leetcode | /license-key-formatting/license-key-formatting.py | 1,634 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k.
We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.
Return the reformatted license key.
Example 1:
Input: s = "5F3Z-2e-9-w", k = 4
Output: "5F3Z-2E9W"
Explanation: The string s has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.
Example 2:
Input: s = "2-5g-3-J", k = 2
Output: "2-5G-3J"
Explanation: The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.
Constraints:
1 <= s.length <= 105
s consists of English letters, digits, and dashes '-'.
1 <= k <= 104
"""
class Solution:
def licenseKeyFormatting(self, s: str, k: int) -> str:
s_without_dash = s.replace("-", "")
rst = []
while s_without_dash:
rst.insert(0, s_without_dash[-k:].upper())
s_without_dash = s_without_dash[:-k]
return "-".join(rst)
def main():
so = Solution()
s = "5F3Z-2e-9-w"
k = 4
output = "5F3Z-2E9W"
ans = so.licenseKeyFormatting(s, k)
print(ans)
assert output == ans
if __name__ == "__main__":
main()
| true |
4d6706eb63d0b929cec5046d5e0c6701b11dc69b | childe/leetcode | /zigzag-conversion/solution.py | 1,944 | 4.34375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/zigzag-conversion/
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
(you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
"""
import unittest
class Solution:
# @param {string} s
# @param {integer} numRows
# @return {string}
def convert(self, s, numRows):
"""
每个Z字有2*numRows-2个字符
idx个字符位于第idx / (2*numRows-2)个Z字 (index从0开始), 是这个Z字的idx % (2*numRows-2)的字符
"""
if numRows == 1:
return s
rst = []
for idx,e in enumerate(s):
#print
#print idx,e
z_idx = idx / (2*numRows -2)
z_inner_idx = idx % (2*numRows -2)
inner_row = z_inner_idx if z_inner_idx < numRows else (2*numRows-z_inner_idx-2)
inner_col = 0 if z_inner_idx < numRows else (z_inner_idx-numRows+1)
#print "inner", inner_row, inner_col
row = inner_row
col = z_idx * (numRows-1) + inner_col
#print row,col
rst.append( ((row,col), e) )
rst.sort(key=lambda e:e[0])
return "".join([e[1] for e in rst])
class TestSolution(unittest.TestCase):
def test_convert(self):
s = Solution()
rst = s.convert("PAYPALISHIRING", 3)
self.assertEqual("PAHNAPLSIIGYIR", rst)
rst = s.convert("A", 1)
self.assertEqual("A", rst)
rst = s.convert("ABCDE", 4)
self.assertEqual("ABCED", rst)
if __name__ == '__main__':
unittest.main()
| false |
10073b0abd4d10ad56c336bf85b7a4511e0a88d1 | navya126/Pro-C227-ReferenceCode | /CeaserCryptography.py | 1,291 | 4.21875 | 4 |
print("Welcme to the world of cryptography")
def main():
print()
print("Choose one option")
choice = int(input("1. Encryption\n2. Decryption\nChoose(1,2): "))
if choice == 1:
encryption()
elif choice == 2:
decryption()
else:
print("Wrong Choice")
def encryption():
print("Encryption")
msg = input("Enter your message: ")
key = int(input("Enter key(1-94): ")) # based on 26 letters of alphabet
encrypted_text = ""
for i in range(len(msg)):
temp = (ord(msg[i]) + key)
if(temp > 126):
temp = temp - 127 + 32
encrypted_text += chr(temp)
print("Encrypted: " + encrypted_text)
main()
def decryption():
print("Decryption")
print("Message can only be Lower or Uppercase alphabet")
encrp_msg = input("Enter encrypted Text: ")
decrp_key = int(input("Enter key(1-94): "))
decrypted_text = ""
for i in range(len(encrp_msg)):
temp = (ord(encrp_msg[i]) - decrp_key)
if(temp < 32):
temp = temp + 127 - 32
decrypted_text += chr(temp)
print("Decrypted Text: " + decrypted_text)
if __name__ == "__main__":
main()
| true |
926efb856eef24a47f239ee3db6da1b075f61345 | adaluong/miscellaneous | /bad_code/spongebob.py | 871 | 4.25 | 4 | # a program to capitalise the first vowel of a word
sentence = input('sentence: ')
while sentence:
spongebob = ""
counter = 0
for letter in sentence:
if letter == ' ':
counter = 0
elif letter in 'aeiou' and counter == 0:
letter = letter.upper()
counter += 1
spongebob += letter
print(spongebob)
print(
'''
*
*
----//-------
\..C/--..--/ \ `A
(@ ) ( @) \ \// |w
\ \ \---/
HGGGGGGG \ /`
V `---------`--'
<< <<
### ###
'''
)
sentence = input('sentence: ')
#import re; print(re.sub(r'[^aeiou ]*([aeiou])[^ ]*', lambda c: c[0].replace(c[1], c[1].upper(), 1), input('Sentence: ')))
| false |
4917b5437b6842e93b69262827f9701995089f0e | ksmith-1989/problem_sets | /ps1b.py | 997 | 4.3125 | 4 | # annual salary
annual_salary = int(input("Enter annual salary: "))
monthly_salary = annual_salary/12
#ask user for semi annual raise
salary_raise = float(input("Enter a semi annual salary raise as a decimal:"))
# saving 10% each month
portion_saved = float(
input("Enter how much you will save each month as a decimal: "))
monthly_saved = monthly_salary * portion_saved
# cost of home
total_cost = int(input("Enter the cost of your dream home:"))
# down payment %
portion_down_payment = 0.25
down_payment = total_cost * portion_down_payment
# current savings
current_savings = 0
# investments earn 4%
r = 0.04
ror = r/12
months = 0
while current_savings < down_payment:
months += 1
current_savings *= 1 + ror
current_savings += monthly_saved
if months % 6 == 0:
annual_salary = (annual_salary * salary_raise) + annual_salary
monthly_salary = annual_salary/12
monthly_saved = monthly_salary * portion_saved
print('Number of months:', months) | true |
73ee8bf80b4e1d7de65c159a2ec8d216f702876a | nymoral/euler | /p9.py | 1,020 | 4.375 | 4 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
"""
We have:
a^2 + b^2 = c^2
a + b + c = 1000
a + b = 1000 - c // ^2
a^2 + b^2 + 2ab = 1000^2 - 2000c + c^2
^^^^^^^^^ == c^2
c^2 + 2ab = 1000^2 - 2000c + c^2
2ab = 1000^2 - 2000c
ab = 500000 - 1000c
We need to find abc, so we can look at ab = t as one variable
t = 500000 - 1000c
As t >= 2, 2 <= 500000 - 1000c, 1000c <= 499998
c is Natural number, thus c <= 49
3 <= c <= 499
"""
def tripletProduct():
for c in range(3, 499 + 1):
t = 500000 - (1000 * c)
# a < b < c, a*b = t
for a in range(1, c):
if t % a == 0:
b = t // a
if a**2 + b**2 == c**2:
return (t*c)
if __name__ == "__main__":
print(tripletProduct())
| false |
dec45ddb7f0eadd1c109c42e6686e577db71f317 | nymoral/euler | /p30.py | 649 | 4.15625 | 4 | """
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 14 + 64 + 34 + 44
8208 = 84 + 24 + 04 + 84
9474 = 94 + 44 + 74 + 44
As 1 = 14 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
"""
def is_made_of_pow(n):
return n == sum(int(i)**5 for i in str(n))
def sum_fifth_pow_nums():
# I tested 10^5, 10^6 and 10^7. 5 < 6 = 7
return sum(i for i in range(2, 10**6) if is_made_of_pow(i))
if __name__ == "__main__":
print(sum_fifth_pow_nums())
| true |
1067226f07563292302c53fe8fc92d1db967675e | benjamin22-314/codewars | /Basic Mathematical Operations.py | 636 | 4.34375 | 4 | """
Your task is to create a function - basic_op().
The function should take three arguments
operation(string/char), value1(number), value2(number).
The function should return result of numbers after applying
the chosen operation.
"""
# %%
def basic_op(operator, value1, value2):
d = {
'+':value1+value2,
'-':value1-value2,
'*':value1*value2,
'/':value1/value2,
}
return d[operator]
# %%
# test
print(basic_op('-', 10, 12))
# %%
# other solutions
def basic_op_v1(operator, value1, value2):
return eval("{}{}{}".format(value1, operator, value2))
print(basic_op_v1('-', 10, 13)) | true |
ec8dc770ef9f6d4a0422f45cae591cdda6be559a | takumab/algorithms | /sorting_and_searching/selection_sort.py | 2,063 | 4.34375 | 4 | """
Selection Sort:
...find the smallest unsorted element and add it to the
sorted list.
Pseudocode:
Repeat until no unsorted elements remain:
--> Search the unsorted part of the data to find the smallest value
--> Swap the smallest found value with the first element of the unsorted part
Big-O == O(n^2)
"""
# selection_sort :: unsorted_list -> sorted_list
def selection_sort(unsorted_list):
"""Takes an unsorted_list and returns a sorted list
>>> selection_sort([3, 2, 1])
[1, 2, 3]
"""
sorted_list = []
while len(unsorted_list) != 0:
# find_smallest number in list
smallest = find_smallest(unsorted_list)
# move smallest number to sorted
move_smallest_to_sorted(sorted_list, smallest)
remove_unsorted_element(unsorted_list, smallest)
return sorted_list
# find_smallest :: List -> Integer
def find_smallest(xs):
"""Takes a list of numbers and returns the smallest number
>>> find_smallest([3, 2, 1])
1
"""
acc = xs[0]
smallest = None
for x in range(0, len(xs)):
if xs[x] > acc:
smallest = acc
else:
smallest = xs[x]
acc = smallest
# ...n
return acc
# move_smallest_to_sorted :: smallest_num --> sorted_list
def move_smallest_to_sorted(sorted, smallest):
"""Takes smallest number from find_smallest() and moves it to the sorted_list
>>> move_smallest_to_sorted([1, 2], 3)
[1, 2, 3]
"""
sorted.append(smallest)
return sorted
# remove_unsorted_list :: (List, Integer) --> List
def remove_unsorted_element(original_unsorted_list, smallest_num):
"""Remove unsorted element from list
>>> remove_unsorted_element([3,2,1], 1)
[3, 2]
"""
smallest_index = original_unsorted_list.index(smallest_num)
original_unsorted_list.pop(smallest_index)
return original_unsorted_list
if __name__ == "__main__":
import doctest
doctest.testmod()
print(selection_sort([5, 7, 2, 6, 8, 4, 1, 3, 10, 0, 25]))
| true |
7f2eb372293a7766dc30e78ceaeda04393dc8d2f | Kousi-ops/Data-Folkz-test | /test6.py | 282 | 4.1875 | 4 | def multiplication_or_sum(num1, num2):
product = num1 * num2
if product >= 1000:
return product
else:
return num1 + num2
number1 = 20
number2 = 30
print("\n")
result = multiplication_or_sum(number1, number2)
print("The result is", result)
| true |
31a8957bc07da73f53de5064cb1aff70ce78f71e | Abadjula/Sign-up-Log-in | /main.py | 1,642 | 4.28125 | 4 | running = True
# Loops forever
while running:
# If he says yes it will keep on going if he says no it will cancel if he says somthing else it would print error
Check_if_want_sign_up = input("Hello welcome to this sign up page to sign up type yes to cancel type no: ")
if Check_if_want_sign_up == "no":
print("Bye bye hopefully we see you again")
running = False
elif Check_if_want_sign_up == "yes":
print("Ok, lets start by setting up your username and password")
Sign_up_username = input("Create your username: ")
Sign_up_password = input("Create a password: ")
print("Now enter the credentials you just made")
Username = ""
Password = ""
Tries = 0
Out_of_tries = 5
Show_tries = 5
while Username != Sign_up_username or Password != Sign_up_password and Tries < Out_of_tries:
Tries += 1
Username = input("Enter your username: ")
Password = input("Enter your password: ")
# If he gets it right the loop will end and will say hello to the user
if Username == Sign_up_username and Password == Sign_up_password:
print("Hello " + Username + " you successfully signed up")
running = False
# If he gets it wrong it will show how many attempts he has and will cancel if he gets it wrong in less than 5 tries
elif Username != Sign_up_username or Password != Sign_up_password:
Show_tries -= 1
print("You have " + str(Show_tries) + " attempts left")
else:
print("Error")
# Made by Abadjula#4856
| true |
c86f65430a50dc63d78822b8889fda03cd9610d6 | lexic92/Practice-Programs | /Python/ex7.py | 910 | 4.34375 | 4 | #prints the contents between the "'s and a newline character.
print "Mary had a little lamb."
#prints the contents between the "s and a newline.
#The %s means "String: (converts any python object using str())."
#Then % means that the formatting character takes that as an argument.
print "Its fleece was white as %s." % 'snow'
#prints the string and a newline.
print "And everywhere that Mary went."
#prints the string 10 times (or whatever number you put there.)
print '.' * 20 # what'd that do?
#A bunch of string variables
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
# watch that comma at the end. try removing it to see what happens
#putting a comma will erase the implied "newline."
#BUT IT WILL INSERT A SPACE!!!!!!
print end1 + end2 + end3 + end4 + end5 + end6 +end7 + end8 + end9 + end10 + end11 + end12 | true |
d3e16446a0578af3aafaac2c9d467a205a14f294 | marinapts/prefix_infix_calculator | /calculator.py | 2,933 | 4.71875 | 5 | import argparse
import re
def compute_calculation(input_str):
"""Computes prefix or infix calculation, depending on the notation of the input expression.
Also checks that the given input doesn't contain any alphabetical characters.
Args:
input_str (str): The input expression in string format
Returns:
res (float): The result of the prefix or infix calculation
"""
assert bool(re.search('[a-zA-Z]', input_str)) is False, 'Only digits and operators +-*/() are allowed.'
if '(' in input_str or ')' in input_str: # Infix notation
res = infix_calc(input_str)
print('Infix result: ', res)
else: # Prefix notation
res = prefix_calc(input_str)
print('Prefix result:', res)
return res
def prefix_calc(prefix_str):
"""Calculates an expression in prefix notation. E.g. + * 1 2 3 should return 5
Args:
prefix_str (str): The input in prefix notation
Returns:
(float): The result of the prefix calculation
"""
prefix_arr = prefix_str.split()
prefix_arr.reverse()
if not prefix_arr:
return None
operators = set(['+', '-', '*', '/'])
stack = []
while prefix_arr:
curr = prefix_arr.pop(0)
if curr not in operators:
stack.append(curr)
else:
left_num = stack.pop()
right_num = stack.pop()
res = eval(' '.join([left_num, curr, right_num]))
stack.append(str(res))
return float(stack[0])
def infix_calc(infix_str):
"""Calculates an expression in infix notation. E.g. ( ( 1 * 2 ) + 3 ) should return 5
Args:
infix_str (str): The input in infix notation
Returns:
(float): The result of the infix calculation
"""
assert infix_str.count('(') == infix_str.count(')'), 'Expression not correct. Ensure all parentheses are closed.'
infix_arr = infix_str.replace(')', '').split()
if not infix_arr:
return None
stack = []
while infix_arr:
curr = infix_arr.pop()
if curr != '(':
stack.append(curr)
else:
left_num = stack.pop()
operator = stack.pop()
right_num = stack.pop()
res = eval(' '.join([left_num, operator, right_num]))
stack.append(str(res))
return float(stack[0])
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--input', required=False, help='Expression for prefix or infix calculation')
args = parser.parse_args()
input_str = args.input
if input_str: # Input expression was not passed through the command line
compute_calculation(input_str)
else: # Allow for user interaction using the input prompt
while True:
input_str = input('Enter prefix or infix expression: ')
if not input_str: break
compute_calculation(input_str)
| true |
a5b7b9ef68e600565d02e4ffb3794ea8d8539d6c | madrascode/basic-python-code | /Native-Datatypes/set_operations.py | 459 | 4.125 | 4 | E = {0, 2, 4, 6, 8}
N = {1, 2, 3, 4, 5}
print("Union operation in python sets: ", E|N)
print("Intersection of E and N: ", E&N)
print("Difference of E and N: ", E-N) # will be considered for E...
print("Symmetric Difference of E and N: ", E^N) # jo dono sets me individually lie karta hai.
# also we have in-built functions in python for set operations
print(E.union(N))
print(E.intersection(N))
print(E.difference(N))
print(E.symmetric_difference(N)) | false |
0f296a2dfda923b26c476ba3eac6a8f49a833105 | coder-dipesh/Basic_Python | /labwork2/number_guessing.py | 354 | 4.125 | 4 | '''
Game finding a secret number within 3 attempts using while loop
'''
secret_number=3
limit=3
while limit:
user_num=int(input("Enter your guess number: "))
if user_num==secret_number:
print('You won! Guessed correct number.')
break
else:
print('Sorry! wrong guess .')
else:
print('Your max guess has ended.') | true |
3653506950b51456ea061e43daa4b51b40dfe0f7 | coder-dipesh/Basic_Python | /labwork2/len_function.py | 422 | 4.625 | 5 | '''
If name is less than 3 characters long name must be at least 3 characters otherwise if it's more than 50 characters name must be maximum
of 50 characters otherwise - name looks good!
'''
user_name= input('Enter your name: ')
length=len(user_name)
if length<3:
print("Name must be at least 3 characters.")
elif length>50:
print("Max length must be of 50 characters.")
else:
print("The name looks good.")
| true |
543b34183688ce058e86259317c55bab97535cc2 | coder-dipesh/Basic_Python | /labwork2/checking_smalles.py | 525 | 4.21875 | 4 | '''
Que.4: Given three integer print the smallest one (Three integer must be inputed by user)
'''
input1=int(input('Enter first number to check: '))
input2=int(input('Enter second number to check: '))
input3=int(input('Enter Third number to check: '))
#Main condition to check
if input1<input2 and input1<input3:
print(f'{input1} frist number entered is smallest.')
elif input2<input1 and input2<input3:
print(f'{input2} second number entered is smallest.')
else:
print(f'{input3} third number entered is smallest.') | true |
eb0eb897a6b3c4296059ac2bfddd85a8b5826124 | coder-dipesh/Basic_Python | /labwork1/desk_buying.py | 888 | 4.125 | 4 |
"""
Question 5:-->
A school decided to replace the desks in three

coderclassroom.Each desk sits two students.Given the number of students
in each class, print the smallest possible number of desks that can be purchased.
The program should read the integers: the number of students in each of the three classes a,b and c respectively.
"""
student_Class_A = int(input("Enter the number of students in class A :"))
student_Class_B = int(input("Enter the number of students in class B :"))
student_Class_C = int(input("Enter the number of students in class C :"))
stu_per_desk = 2
total_student = (student_Class_A+student_Class_B+student_Class_C)
desk_to_buy = total_student//stu_per_desk
remaning_stu = total_student % stu_per_desk
print(f"The smallest possible number of desks to be purchased is {desk_to_buy}.")
print(f"{remaning_stu} student will not fit in desk.")
| true |
61ed546415d9677b351eb00ce1e6b7b8afc4f005 | thepixelboy/snake-game | /snake.py | 2,186 | 4.125 | 4 | from turtle import Turtle
SNAKE_STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0
class Snake:
def __init__(self):
self.segments = []
self.create_snake()
self.head = self.segments[0]
self.last_direction = self.head.heading()
def create_snake(self):
"""Creates the snake body"""
for position in SNAKE_STARTING_POSITIONS:
self.add_segment(position)
def add_segment(self, position):
snake_segment = Turtle(shape="square")
snake_segment.color("white")
snake_segment.penup()
snake_segment.goto(position)
self.segments.append(snake_segment)
def extend(self):
"""Adds a new segment to the snake"""
# -1 in the segments means that starts counting in the end of the list
self.add_segment(self.segments[-1].position())
def move(self):
"""Moves each snake's segment position to the position of the preceding segment position (3 to 2, 2 to 1, etc.)"""
# range(start, stop, step)
for seg_num in range(len(self.segments) - 1, 0, -1):
new_x_position = self.segments[seg_num - 1].xcor()
new_y_position = self.segments[seg_num - 1].ycor()
self.segments[seg_num].goto(new_x_position, new_y_position)
# moving first snake's segment 20 spaces and updating last_direction
self.head.forward(MOVE_DISTANCE)
self.last_direction = self.head.heading()
def reset(self):
for seg in self.segments:
seg.hideturtle()
self.segments.clear()
self.create_snake()
self.head = self.segments[0]
def up(self):
"""Moves the snake up"""
if self.head.heading() != DOWN and self.last_direction != DOWN:
self.head.setheading(UP)
def down(self):
"""Moves the snake down"""
if self.head.heading() != UP and self.last_direction != UP:
self.head.setheading(DOWN)
def left(self):
"""Moves the snake to the left"""
if self.head.heading() != RIGHT and self.last_direction != RIGHT:
self.head.setheading(LEFT)
def right(self):
"""Moves the snake to the righ"""
if self.head.heading() != LEFT and self.last_direction != LEFT:
self.head.setheading(RIGHT)
| true |
8a8c6cc8e755f9e748d470561a805791dc828e95 | lukeDoub/dice | /dice.py | 1,449 | 4.46875 | 4 | import random
'''
Allows the user to specify a certain number of dice to generate,
how many sides they should all have, and how many times each should be rolled, then
print results
'''
'''
Represents a Dice object
'''
class dice:
numSides = 0
#default initialization to 6 sides
def __init__(self):
self.numSides = 6
#allows a specifc number of sides
def __init__(self, sides):
self.numSides = sides
def printSides(self):
print"sides: ", self.numSides
'''
simulates rolling the die byreturning a number between 1
and the number of sides the die has
'''
def roll(self):
return random.randint(1, self.numSides)
'''
ask the user for the number of dice to create, as well as the number of sides the dice
should have, makes a list of the dice and inits them, them ask them how many times to
roll the dice and prints the results
'''
def main():
numDice = input("Enter the number of dice to generate: ")
sides = input("Enter the number of sides the dice should have: ")
diceList = list()
#making the dice
for x in range(numDice):
diceList.append(dice(sides))
rollPerDie = input("How many times should each dice be rolled? ")
#rolling the dice
for j in range(numDice):
for i in range(rollPerDie):
print("Die {0}, roll {1} - result: {2}".format(j+1, i+1, diceList[i].roll()))
main()
| true |
1e4372c0361f07bc38e3852a216a40c4fdad89cb | nrkroeker/Sorting-Project | /sort.py | 963 | 4.5 | 4 | # Method to sort an array of integers using Bubble sort
def sortList(numbers):
size = len(numbers)
for i in range(size):
for j in range(0, size - i - 1):
if (numbers[j] < numbers[j + 1]):
temp = numbers[j]
numbers[j] = numbers[j + 1]
numbers[j + 1] = temp
# Method to print the array of integers on one line
def printIntArray(arr):
for i in range(len(arr)):
print ("%d" %arr[i], end=" ")
def main():
# Get 10 integers from the user and append them to an array
print("Please input 10 integers")
numbers = [];
for x in range(10):
newNumber = input("> ")
numbers.append(int(newNumber))
# Print the array as it was inputted
print("\n\nUnsorted List: ", end="")
printIntArray(numbers)
# Sort the array and print it in sorted order
sortList(numbers)
print ("\n\nSorted List: ", end="")
printIntArray(numbers)
main() | true |
5a74838a99dbf4047a23f0e63542203dcb65280e | nimitpatel/python-practice | /w175b.py | 667 | 4.125 | 4 | '''
Read a text file in Python and print no. of lines and no. of unique words.
&
Write a Python program to read a text file and do following:
1. Print no. of words
2. Print no. statements
&
Write a Python program to count words, characters and spaces from text file
'''
fname = "w175b.txt"
num_lines = 0
num_words = 0
num_chars = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_lines += 1
num_words += len(words)
num_chars += len(line)
print("No. of Lines", num_lines)
print("No. of Words", num_words)
print("No. of Characters", num_chars)
| true |
07950a7a298b5b9898a6695218769648e3256366 | OvsyannikovYuri/algoPython | /lesson1Part7.py | 1,138 | 4.34375 | 4 | # По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника,
# составленного из этих отрезков. Если такой треугольник существует, то определить, является ли он разносторонним,
# равнобедренным или равносторонним.
a = float(input("введите длину основания A"))
b = float(input("введите длину основания B"))
c = float(input("введите длину основания C"))
if (a + b > c) & (b + c > a) & (a + c > b):
print("треугольник существует")
if ((a==b) & (b==c) & (a==c)):
print("треугольник равносторонний")
elif ((((a==b) | (b==c) | (a==c)))):
print("треугольник равнобедренный")
else:
print("треугольник разносторонний")
else:
print("треугольник не существует")
| false |
abea7caec51793ba3b10f9f8a14592e0b1fc8b68 | dcherry123/CDPythonWorkRepository | /Training/4 Working with Li sts/4-10_list_slices.py | 1,286 | 4.9375 | 5 | # 4-10. Slices: Using one of the programs you wrote in this chapter, add several
# lines to the end of the program that do the following:
# Print the message, The first three items in the list are:. Then use a slice to
# print the first three items from that programs list.
# Print the message, Three items from the middle of the list are:. Use a slice
# to print three items from the middle of the list.
# Print the message, The last three items in the list are:. Use a slice to print
# the last three items in the list.
pizza = ['Pizza1', 'Pizza2', 'Pizza3', 'Pizza4', 'Pizza5', 'Pizza6']
# Print the message, The first three items in the list are:. Then use a slice to
# print the first three items from that programs list.
# Use while loop to print first three items
i = 0
while(i < len(pizza[0:3])):
print (pizza[i])
i = i + 1
print("\n")
# Print the message, Three items from the middle of the list are:. Use a slice
# to print three items from the middle of the list.
# Use while loop
i = len(pizza)/2
while(i < len(pizza)):
print (pizza[i])
i = i + 1
# print(pizza[1:4])
print("\n")
# Print the message, The last three items in the list are:. Use a slice to print the last three items in the list.
print(pizza[2::])
| true |
25947d3344a6bba995580a56b808a784b586001a | dcherry123/CDPythonWorkRepository | /Training/4 Working with Li sts/4-8_list_cubes.py | 388 | 4.4375 | 4 | # 4-8. Cubes: A number raised to the third power is called a cube. For example,the cube of 2 is written as 2**3 in Python.
# Make a list of the first 10 cubes (that is, the cube of each integer from 1 through 10), and use a for loop to print out
# the value of each cube.
value = list(range(1, 11, 1))
print ("Cube Table:-")
print ("#" *20 + "\n")
for i in value:
print (str(i**3)) | true |
c87811fe93c1795de542230f182712d96dda9aec | dcherry123/CDPythonWorkRepository | /Training/Misc/famous_quote2.py | 405 | 4.15625 | 4 | # 2-6. Famous Quote 2: Repeat Exercise 2-5, but this time store the famous persons
# name in a variable called famous_person. Then compose your message
# and store it in a new variable called message. Print your message.
famous_person = raw_input("Enter the name of the person you admire: ")
message = raw_input("Enter His quote: ")
print ("Your hero {0} once said, {1} ".format(famous_person,message)) | true |
22ada7ac1c12741981ae0471034fb8a537cf7d0d | dcherry123/CDPythonWorkRepository | /Training/3 List/3-2_list_greetings.py | 876 | 4.375 | 4 | # 3-2. Greetings: Start with the list you used in Exercise 3-1, but instead of just
# printing each persons name, print a message to them. The text of each message
# should be the same, but each message should be personalized with the
# persons name.
names_list = ['peter', 'jack', 'eric']
# print (names_list[0])
# print (names_list[1])
# print (names_list[2])
# Converting from lower case to upper case using for loop
# for i in range(0, len(names_list)):
# names_list[i] = names_list[i].upper()
# Print the message
# for names in names_list:
# print("Good morning " + names)
# Converting from lower case to upper case using while loop
# i = 0
# while(len(names_list) > i):
# names_list[i] = names_list[i].upper()
# # print ("Name ", names_list[i])
# i = i + 1
#Print the message
for names in names_list:
print("Good morning " + names.upper()) | true |
162bbdc84eac234698056b21e6186a88b3807b7b | dcherry123/CDPythonWorkRepository | /Training/6 Dictionary/6-5_dictionary_Rivers.py | 1,009 | 4.875 | 5 | # 6-5. Rivers: Make a dictionary containing three major rivers and the country
# each river runs through. One key-value pair might be 'nile': 'egypt'.
# Use a loop to print a sentence about each river, such as The Nile runs through Egypt.
# Use a loop to print the name of each river included in the dictionary.
# Use a loop to print the name of each country included in the dictionary.
river_city = {'River1': 'City1', 'River2': 'City2', 'River3': 'City3'}
# print(person_details['first_name'])
# print(person_details['last_name'])
# print(person_details['age'])
# print(person_details['city'])
# Use a loop to print a sentence about each river, such as The Nile runs through Egypt.
for i in river_city:
print (i),'runs through', river_city[i]
# Use a loop to print the name of each river included in the dictionary.
print " "
for i in river_city:
print (i)
# Use a loop to print the name of each country included in the dictionary.
print " "
for i in river_city:
print river_city[i]
| true |
412ca85f4faff17380e60b994bd811d9501b25ad | YuedaLin/python | /其他/01_体验多态.py | 829 | 4.125 | 4 | # 定义:多态是一种使用对象的方法,子类重用父类方法,调用不同子类对象的相同方法,可以产生不同的执行结果
# 步骤:
# 1.定义父类,并提供公共方法;警犬 和 人
# 定义警犬这个类
class Dog():
def work(self):
print('指哪打哪。。。')
# 定义人这个类
class Person():
def work_with_dog(self, dog):
dog.work()
# 2.定义子类,并重写父类方法;定义2个类表示不同的警犬
class ArmyDog(Dog):
def work(self):
print('追击敌人。。。')
class DrugDog(Dog):
def work(self):
print('追查毒品。。。')
# 3.传递子类对象给调用者,传入不同的对象,观察执行的结果
ad = ArmyDog()
dd = DrugDog()
daqiu = Person()
daqiu.work_with_dog(ad)
daqiu.work_with_dog(dd)
| false |
4c2f6e6a8d9cefd5010ac9f7adf7a48ca26ee574 | Szyszuniec/100-zada- | /zadanie 19.py | 703 | 4.375 | 4 | # You are required to write a program to sort the (name, age, height) tuples by ascending order
# where name is string, age and height are numbers. The tuples are input by console. The sort criteria is:
# 1: Sort based on name;
# 2: Then sort based on age;
# 3: Then sort by score.
# The priority is that name > age > score.
def trzeciawart(wart):
return wart[2]
def drugawart(wart):
return wart[1]
linia = ""
print("Podaj dane (Imię,Wiek,Wzrost):")
baza = []
while True:
linia = input()
if linia == "koniec":
break
osoba = tuple(linia.split(","))
baza.append(osoba)
baza.sort(key=trzeciawart)
baza.sort(key=drugawart)
baza.sort()
print(baza) | true |
aa776abf82b81a6612d1641e30f8f4172ddb20c6 | Taylor4484/CS-313E---Elements-of-Software-Design | /Assignment 1/open.py | 565 | 4.28125 | 4 | #Read File
openfile = open('myWordList.txt', 'r')
#Create wordList from content of read file
wordList = openfile.readlines()
#Clean the wordlist
cleanWordList = [line.strip().rstrip() for line in wordList]
#Set a default filename
defaultFile = 'myWordList.txt'
#Tell user the default filename
print('The default filename is [%s]' % defaultFile)
#Ask the user to accept default or type new filename
inputFileName = input("Hit 'Enter' to accept, or type new filename: ")
#Use defaultFile if no input, or use input
inputFileName = defaultFile or inputFileName
| true |
fa35073cab641f6737b0388a9023b39e8a5c5716 | cf17josetorres/Practica1M5UF2 | /ex2for.py | 201 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
nom = raw_input ("introducir el nom: ")
num = int(raw_input("Introduce el numero de veces: "));
print nom
print num
for i in range(0,num,1):
print nom,
| false |
9a31a37ea6bfca4c96a255f4561a3e157f34fe6d | akira2nd/CODES | /Algoritmos e Lógica de Programação/lista 3 akira/questao02.py | 431 | 4.1875 | 4 | '''
2. Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao
nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações.
'''
while True:
usuário = input('Digite um usuário: ')
senha = input('Digite uma senha: ')
if usuário == senha:
print('senha deve ser diferente do nome de usuário!')
else:
break
print('Usuário e senha OK')
| false |
0608fb751d147efa38f12d29d643e4c4d1269d1e | vinuv296/luminar_python_programs | /Advanced_python/oops/pgm1.py | 588 | 4.125 | 4 | #class : design pattern
#object : real world entity
#references : name that refers a memory location of a object
class Person:
def walk(self):
print("person is walking")
def run(self):
print("person is running")
def jump(self):
print("person is jumping")
obj=Person()
obj.walk()
obj.run()
obj.jump()
ab=Person()
ab.walk()
class Person1:
def setVal(self,name,age):
self.age=age
self.name=name
def printval(self):
print("name",self.name)
print("age",self.age)
odj=Person1()
odj.setVal('rzm',23)
odj.printval()
| true |
797d419f2d471866790be1e279b14f9fdeb829e7 | vinuv296/luminar_python_programs | /Advanced_python/constructor/pgm1.py | 321 | 4.1875 | 4 | # constructor is used to initailize instance variables
# constructor automatically invoke when creating object
class Person:
def __init__(self,name,age):
self.nam=name
self.ag=age
def printval(self):
print("name-",self.nam)
print("age-",self.ag)
ob=Person("Manu",15)
ob.printval() | true |
5843d1133ccd31e4ba8180ad970ec6cf52e66d76 | momchilantonov/SoftUni-Python-Fundamentals-September-2020 | /Final-Exam/Final-Exam-13-December-2020/01_problem.py | 1,478 | 4.1875 | 4 | username = input()
def case(user, inst):
if inst == "lower":
user = user.lower()
elif inst == "upper":
user = user.upper()
print(user)
return user
def reverse(user, start, end, sub):
sub = sub[::-1]
if 0 <= start < len(user) > end > 0:
print(sub)
def cut(user, sub):
if sub not in username:
print(f"The word {user} doesn't contain {sub}.")
return user
else:
user = user.replace(sub, "", 1)
print(user)
return user
def replace(user, ch):
user = user.replace(ch, "*")
print(user)
return user
def check(user, ch):
if ch in user:
print("Valid")
else:
print(f"Your username must contain {ch}.")
while True:
command = input()
if command == "Sign up":
break
actions = command.split(" ")
action = actions[0]
if action == "Case":
case_action = actions[1]
username = case(username, case_action)
elif action == "Reverse":
start_index = int(actions[1])
end_index = int(actions[2])
substring = username[start_index:end_index+1]
reverse(username, start_index, end_index, substring)
elif action == "Cut":
substring = actions[1]
username = cut(username, substring)
elif action == "Replace":
char = actions[1]
username = replace(username, char)
elif action == "Check":
char = actions[1]
check(username, char)
| true |
6bc37f82c17f5da9bb2a0f2ff2c5905c9ee37a81 | momchilantonov/SoftUni-Python-Fundamentals-September-2020 | /Functions/Functions-Exercise/06_password_validator.py | 917 | 4.15625 | 4 | def password_validation(password):
sum_chars = 0
sum_digits = 0
sum_special_char = 0
is_valid = True
for index in range(len(password)):
sum_chars += 1
if password[index].isdigit():
sum_digits += 1
if not password[index].isalpha() and not password[index].isdigit():
sum_special_char += 1
if not 6 <= sum_chars <= 10:
is_valid = False
print("Password must be between 6 and 10 characters")
if not sum_special_char == 0:
is_valid = False
print("Password must consist only of letters and digits")
if sum_digits < 2:
is_valid = False
print("Password must have at least 2 digits")
if is_valid:
print("Password is valid")
password_for_check = input()
password_for_check = [password_for_check[char] for char in range(len(password_for_check))]
password_validation(password_for_check)
| true |
f6191ba640b93a625c5f1f8b7acb54b6afbd09ab | githubkannadhasan/kanna | /oddeven.py | 235 | 4.21875 | 4 |
name = input("Please enter the name")
print("Entered input is " + name)
oddeven = int(input("Please enter the number"))
if oddeven % 2 == 0:
print("Entered number is even")
else:
print("Entered number is odd")
| true |
a94a73ed87518feb78bc8cdf6ac6413f98b6603d | guyavrah1986/learnPython | /learnPython/questions/checkIfThereAreTwoNumbersThatThierSubstrcutionIsOneInAnArray.py | 879 | 4.15625 | 4 | '''
Given an array of integers, return true if there are at least two numbers that one is greater than the
other by 1. Return false otherwise
'''
def check_adjacent_numbers_in_array(arr: list) -> bool:
print("got the following array of numbers:" + str(arr))
numbers_in_arr_dict = {}
for num in arr:
numbers_in_arr_dict[num] = 1
print("checking number:" + str(num))
if numbers_in_arr_dict.get(num - 1, None) is not None or numbers_in_arr_dict.get(num + 1, None) is not None:
print("number:" + str(num) + " has its respective number that is greater or less then it by 1")
return True
return False
arr = [1, 4, 6, 9, 5]
ret_code = check_adjacent_numbers_in_array(arr)
expected_val = True
if ret_code != expected_val:
print("expected to receive:" + str(expected_val) + " BUT got:" + str(ret_code))
exit(1)
| true |
989ab166bdfdcae17fc7f99c509f132516be7fcc | guyavrah1986/learnPython | /learnPython/questions/mirrorBinaryTree.py | 1,153 | 4.21875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def invert_tree(root: TreeNode) -> TreeNode:
if root is None:
return root
invert_tree(root.left)
invert_tree(root.right)
tmp = root.right
root.right = root.left
root.left = tmp
return root
""" Helper function to print Inorder traversal."""
def inOrder(node):
if (node == None):
return
inOrder(node.left)
print(node.val, end=" ")
inOrder(node.right)
# Driver code
if __name__ == "__main__":
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
""" Print inorder traversal of
the input tree """
print("Inorder traversal of the",
"constructed tree is")
inOrder(root)
""" Convert tree to its mirror """
invert_tree(root)
""" Print inorder traversal of
the mirror tree """
print("\nInorder traversal of",
"the mirror trees ")
inOrder(root)
| true |
a52c48d2cd8fb697c471d6d96695ba1464494607 | guyavrah1986/learnPython | /learnPython/trainingNotes/ex_1.py | 968 | 4.5625 | 5 | # I/O
# by default every input that is recived from the user, for instance via the built-in
# input() method is being "read" as string, so, in case the value read needs to be used
# not as a string, for instance as an int, a conversion of its value MUST take place.
# NOTE: it is possible to use the built-in eval() method in order to automatically
# converts it to the "proper" type. Pay attention, however, that in case a string is
# required, then when typing the input, a string MSUT be provided within "".
func_name = "ex_1 - "
user_input = eval(input("Please enter a number:"))
print(func_name + "user entered number:" + str(user_input))
'''
try:
val = int(user_input)
except ValueError:
print(func_name + "entered:" + user_input + " which is not an int!")
'''
# array iteration: it is always faster (fasted !!) to iterate over a collection with the
# "for each" flavour
for i in range(4):
print(i)
arr = [0,1,2,3]
for num in arr:
print(num)
| true |
77ce4fb0e8014081d9b26ecde876dcceddbb8595 | guyavrah1986/learnPython | /learnPython/questions/getKNumbersFromArrayWithMaxSum.py | 742 | 4.15625 | 4 | '''
Given an array of positive integers and number K, find K elements in the array that their sum is
the largest.
'''
def get_max_sum_of_k_elements_in_array(arr: list, k: int) -> int:
print("the array is:" + str(arr) + " and K is:" + str(k))
max_sum = 0
num_of_numbers_added = 0
sorted_array = sorted(arr, reverse=True)
while num_of_numbers_added < k:
max_sum += sorted_array[num_of_numbers_added]
num_of_numbers_added += 1
return max_sum
arr = [3, 4, 5, 7, 1, 9, 7, 8, 4, 5]
k = 3
expected_ret_sum = 9 + 8 + 7
ret_sum = get_max_sum_of_k_elements_in_array(arr, k)
if ret_sum != expected_ret_sum:
print("expected sum:" + str(expected_ret_sum) + ", but instead got:" + str(ret_sum))
exit(1)
| true |
0396652e092610c082c08c0781f79351fd19f3ed | guyavrah1986/learnPython | /learnPython/questions/findIndexToWhichIfWeInsertTheNumberFiveWeWillGetLargestNumber.py | 1,142 | 4.25 | 4 | '''
Given an array of integers, find the index to which if we insert the number 5, we will get the
largest number.
'''
def get_index_to_which_if_num_is_inserted_then_we_get_largest_number(num_to_insert: int,
arr: list) -> int:
print("got the following array of integers:" + str(arr) + ", and number to insert:" + str(num_to_insert))
arr_len = len(arr)
index = 0
while index < arr_len:
if arr[index] < num_to_insert:
return index
index += 1
return arr_len
arr = [9, 8, 7, 4, 6]
num_to_insert = 5
expected_ret_val = 3
ret_val = get_index_to_which_if_num_is_inserted_then_we_get_largest_number(num_to_insert, arr)
if ret_val != expected_ret_val:
print("got ret val:" + str(ret_val) + ", BUT expected to get:" + str(expected_ret_val))
exit(1)
arr = [1, 2, 3, 4]
expected_ret_val = 0
ret_val = get_index_to_which_if_num_is_inserted_then_we_get_largest_number(num_to_insert, arr)
if ret_val != expected_ret_val:
print("got ret val:" + str(ret_val) + ", BUT expected to get:" + str(expected_ret_val))
exit(1)
| true |
58ad66245265d791bcfceb0d98b60593ad2c9833 | kmustyxl/DSA_final_fighting | /NowCoder/Array_Sort/冒泡排序.py | 412 | 4.125 | 4 | def BubbleSort(arr):
'''
模拟冒泡过程,从下往上
:param arr:
:return:
'''
num_arr = len(arr)
for i in range(num_arr-1):
for j in range(num_arr-i-1):
if arr[j+1] <= arr[j]:
swap(arr, j+1, j)
return arr
def swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
arr = [3,3,2,1,8,5,0,9]
ans = BubbleSort(arr)
print(ans) | false |
8c7ca53f2397446b9184a9da2a44a00a4b9d6948 | kasanagottu/sdet | /python/Activity 1.py | 305 | 4.15625 | 4 |
# Activity 1
#Enter Name
name = input( "What is your name: " )
#Enter Aga
age = int( input( "How old are you: " ) )
# age = float( input( "How old are you: " ) )
year = str( ( 2020 - age ) + 100 )
#Printing the values on the screen
print( name + " will be 100 years old in the year " + year ) | false |
418faaf681b948e577e5482cb151b617ea46ea22 | tri2sing/IntroPython | /Functions03.py | 932 | 4.46875 | 4 | '''This module shows canonical example of recursion.
'''
def factorial (n):
if not isinstance(n, int):
print('Factorial is only defined for integers.')
return None
elif n < 0:
print('Factorial is not defined for negative integers.')
return None
elif n == 0:
return 1
else:
return n * factorial(n-1)
def fibonacci (n):
if not isinstance(n, int):
print('Fibonacci is only defined for integers.')
return None
elif n < 0:
print('Fibonacci is not defined for negative integers.')
return None
elif n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
if __name__ == "__main__":
print('The factorial of 7 = ' + str(factorial(7)))
print('The fibonacci of 7 = ' + str(fibonacci(7)))
n = factorial(-1)
if n is None:
print('Something is wrong') | true |
edc4dad1878fe800f7782cc393b18011ec0cb95e | tri2sing/IntroPython | /Strings02.py | 1,248 | 4.34375 | 4 |
if __name__ == "__main__":
dish = "szechuan chicken"
print(dish)
# String slices
print(dish[0:5])
print(dish[:4])
print(dish[9:])
print(dish[-8:-3])
print(dish[:])
# Some string methods
print('In upper case our string is "' + dish.upper())
print('We can find "masala" at location = ' + str(dish.find('masala')))
print('We can find "chicken" at location = ' + str(dish.find('chicken')))
print('Between 0 and 8 Wwe can find "chicken" at location = ' + str(dish.find('chicken', 0, 8)))
# Another use of the 'in' operator
flavor = 'masala'
if flavor in dish:
print(flavor + ' is in ' + dish)
else:
print(flavor + ' is not in ' + dish)
flavor = 'szechuan'
if flavor in dish:
print(flavor + ' is in ' + dish)
else:
print(flavor + ' is not in ' + dish)
# Comparison operators for strings
# Useful in lexical ordering
lessthan = 'masala chicken' < 'szechuan chicken'
print('Less than test is ' + str(lessthan))
equalto = 'masala chicken' == 'szechuan chicken'
print('Equal to test is ' + str(equalto))
greaterthan = 'masala chicken' > 'szechuan chicken'
print('Greater than test is ' + str(greaterthan))
| true |
a947c808f9d61d53f5bd07ed67fe5350a0e5c48a | ChuixinZeng/PythonStudyCode | /PythonCode-OldBoy/Day6/随堂练习/03.类的定义.py | 1,045 | 4.375 | 4 | # -*- coding:utf-8 -*-
# Author:Chuixin Zeng
class Dog1(object):
print("hello, I am a dog1")
d = Dog1() # 实例化这个类
# 此时的d就是类Dog的实例化对象
# 实例化,其实就是以Dog类为模版,在内存里开辟一块空间,存上数据,赋值成一个变量名
# 执行了之后,结果是直接打印print的内容了:hello, I am a dog
# 这种操作是有问题的,比如下面的代码,我们想给狗起名字是传不进去的
class Dog(object):
def __init__(self,name,dog_type): # 这个叫构造函数,构造方法,也叫初始化方法
self.name = name
self.dog_type = dog_type
def sayhi(self): # 类的方法,类的功能都写到这里,多个功能就写多个类的方法
print("hello,I am a dog, my name is", self.name)
d = Dog('aaa',"京巴") # 实例化类,实例化后的对象叫实例
d.sayhi() # 调用对象并输出
# 如果把上面两行注释掉的话,输出的是一个内存地址:<class '__main__.Dog'>
# self其实就是实例本身
| false |
7a790bf90a3c6622b09bdd326a7709b5033dfe07 | RaphaelZwecker/Raphael_Zwecker | /ex2_315521609.py | 1,894 | 4.53125 | 5 | ''' Exercise #2. Computational Thinking and Programming.'''
#########################################
# Question 1 - do not delete this comment
#########################################
number = input('please choose a number: ')
# Replace ??? with an appropriate command to get a number from the user.
# Write the rest of the code for question 1 below here.
number=int(number)
if number%2==0:
print(f'I am {number} and I am even')
else:
print(f'I am {number} and I am odd')
#########################################
# Question 2 - do not delete this comment
#########################################
number = input('please choose another number: ')
# Replace ??? with an appropriate command to get a number from the user.
# Write the rest of the code for question 2 below here.
number=int(number)
if number%6==0:
print('divisible by 6')
if number%3==0 and number%2!=0:
print('divisible by 3')
if len(str(number))%2==0:
print('even number of digits')
#########################################
# Question 3 - do not delete this comment
#########################################
grade =58
# Replace ??? with an integer of your choice.
# Write the rest of the code for question 3 below here.
if grade<0 or grade>100:
print('illegal grade')
if 0<=grade and grade<=59:
print('F')
if 60<=grade and grade<=69:
print('D')
if 70<=grade and grade<=79:
print('C')
if 80<=grade and grade<=89:
print('B')
if 90<=grade and grade<=100:
print('A')
#########################################
# Question 4 - do not delete this comment
#########################################
my_str ='aBBa'
# Replace ??? with a string of your choice.
# Write the rest of the code for question 4 below here.
rev_string=my_str[::-1]
if my_str==rev_string:
print('True')
if my_str!=rev_string:
print('False')
| true |
23294961bf1b1eb5bbae03c9aa552b7c0df22d2e | phmartinsconsult/curso_python_3_luis_otavio | /Aula_4.py | 1,236 | 4.40625 | 4 | '''
O Python já identifica automaticamente o tipo da variável digitada
str - string - é um texto
int - inteiro - é um número inteiro
float - é um número flutuante
bool - boleano - é um valor que pode ser True or False
'''
print(12345, "O tipo desta variável é", type(12345))
print('10', "O tipo desta variável é", type('10'))
print(25.15, "O tipo desta variável é", type(25.15))
print(10 == 10, "O tipo desta variável é", type(10==10))
print("Paulo" == "Vivi", "O tipo desta variável é", type("Paulo" == "Vivi"))
# TYPE CASTING - TROCAR O TIPO DA VARIAVEL
print("Paulo", type("Paulo"), bool("Paulo"))
# Quando nós colocamos o tipo da variável na frente dela
# o Python automaticamente toca o tipo da variável
paulo = "1000000"
paulo2 = 1000000
print(paulo, type(paulo)) # Perguntar o tipo da variável
print(paulo2, type(paulo2)) # Perguntar o tipo da variável
print(paulo2, str(paulo2)) # Alterar o tipo da variável
print(paulo, bool(paulo)) # Alterar o tipo da variável
print("")
# Exercícios
# String = nome
print("Paulo", type("Paulo"))
# Int = Idade
print(34, type(34))
# Float = Altura
print(1.60, type(1.60))
# Boll = maior de idade
print(34>18, type(34>18))
| false |
b8ba24a8edbf64204583a3b9dee11e81e993397c | phmartinsconsult/curso_python_3_luis_otavio | /Aula_9_Calculadora_Programada.py | 921 | 4.4375 | 4 | '''
Entrada dos dados - Função INPUT
'''
'''
nome = input("Digite o seu nome: ")
print("")
print(f'O usuário digitou o seguinte {nome}',
f'e essa variável é do tipo {type(nome)}')
'''
print('******************************')
print('*** CALCULADORA PROGRAMADA ***')
print('******************************')
print(" ")
print("Se for soma, digite 1")
print("Se for subtração, digite 2")
print("Se for multiplicação, digite 3")
print("Se for divisão, digite 4")
print("")
form = int(input("Qual a função da calculadora você quer usar? "))
print("")
a = int(input("Primeiro número: "))
b = int(input("Segundo número: "))
if form == 1:
print("O resultado da soma é: ", a + b)
elif form == 2:
print("O resultado da subtração é:", a - b)
elif form == 3:
print("O resultado da multiplicação é: ", a * b)
elif form == 4:
print("O resultado da divisão é: ", a/b)
| false |
d540fd9c6e6cbbf9edb8bac8280446a6a445b672 | phmartinsconsult/curso_python_3_luis_otavio | /Aula_8_Desafio_1.py | 1,006 | 4.375 | 4 | '''
* Criar variáveis com nome (str), idade (int), altura (float) e peso (float) de uma pessoa.
* Criar variável com o ano atual (int)
* Obter o ano de nascimento da pessoa (baseado na idade e no ano atual)
* Obter o IMC da pessoa com 2 casas decimais (baseado no peso e altura da pessoa)
* Exibir um texto com todos os valores na tela usando F-String (com as chaves)
'''
def descricao():
nome = str(input("Digite seu nome: "))
idade = int(input("Digite sua idade: "))
altura = float(input("Digite sua altura: "))
peso = float(input("Digite o seu peso: "))
print("")
ano_atual = 2021
ano_nascimento = ano_atual - idade
imc = peso/(altura**2)
print(f'{nome} tem {idade} anos e {altura} de altura.')
print(f'{nome} pesa {peso} kg e nasceu em {ano_nascimento}.')
print(f'{nome} tem o IMC de: {imc:.2f}.')
if imc <= 25:
print(f'Parabéns {nome}, seu imc está muito bom!')
else:
print(f'Cuidado {nome}! Seu imc está elevado!')
descricao() | false |
78d43f56eea8ffec311a7686bac5caf9e7df64e2 | dansuh17/compiler-design | /syntax_tree.py | 1,998 | 4.125 | 4 | class SyntaxNode:
"""Represents a node in abstract syntax tree."""
def __init__(self, type, token=None):
self.parent = None
self.token = token
self.left_child = None
self.right_child = None
self.type = type
def is_epsilon(self):
"""
Determines whether this syntax node is epsilon.
Returns:
True if determined epsilon
"""
return self.token is None
def __str__(self):
result = ''
if self.token is not None:
result = str(self.token)
return result
class SyntaxTree:
"""Represents an abstract syntax tree."""
def __init__(self):
self.root = None
def pre_order(self, start_node, nodes=None):
"""
Pre-order traversal of this abstract syntax tree.
Args:
start_node (SyntaxNode): starting point
nodes (List[SyntaxNode]): result array of traversal
Returns:
nodes (List[SyntaxNode]): result array of traversal
"""
if nodes is None:
nodes = []
# print(start_node.type + ':' + str(start_node))
# it has to traverse right child first...strangely...
nodes.append(start_node)
if start_node.right_child is not None:
nodes = self.pre_order(start_node.right_child, nodes)
if start_node.left_child is not None:
nodes = self.pre_order(start_node.left_child, nodes)
return nodes
def print_tree(self, option='pre_order'):
"""
Prints the tree contents in string.
Args:
option (str): traversal option
Returns:
print_str (str): the string as a result of traversal
"""
if option == 'preorder':
nodes = self.pre_order(self.root)
else:
nodes = [] # not desired!
print_str = ''
for node in nodes:
print_str += str(node)
return print_str
| true |
e4b32f3c86887eb7bb56a69fa074db819eafbcb0 | ysfranciszhou/MyLMSC261 | /pyramid assignment/{YishengZhou}paramid.py | 354 | 4.21875 | 4 | x = int(input("Enter the tall(1~8) of pyramid: "))
y = 2*x - 2
if x > 0 and x < 9:
for m in range(0, x):
for n in range(0, y):
print(end=" ")
y = y - 2
for n in range(0, m+1):
print("# ", end="")
print("\r")
else:
print("The number is out of range, please exit the program and try again.")
| true |
0ea9656da2abdb0bee129e280518a088a381fae8 | altynai02/Chapter1-Part3-Task6 | /task6.py | 412 | 4.21875 | 4 | # 6. Напишите функцию которая подсчитает количество
# счетных и несчетных чисел в списке чисел.
def even_odd(list_):
even = 0
odd = 0
# list_ = input("Enter a list: ")
for i in list_:
if i % 2 == 0:
even+=1
else:
odd += 1
return list_, even, odd
print(even_odd([3,3,7,9])) | false |
5dfcc1008b796b446f2060c4027e99b7f16bedf5 | SurferZant/Small-games | /guess the number game - Copy (2).py | 949 | 4.25 | 4 | #a game where the player tries to guess what number the computer is thinking of between 1 and 20
import random
def guessingGame():
guessesTaken = 0
print ("Hey there! What's your name? ")
myName = input()
number = random.randint (1, 20)
print ("Well there " + myName +', ' "I am thinking of a number between 1 and 20 what is it?")
for guessesTaken in range(6):
print ('Take a guess')
guess = input()
guess = int(guess)
if guess < number:
print ("Your guess is too low")
if guess > number:
print("Your guess is too high")
if guess == number:
break
if guess == number:
print ("Good job " + myName + "! you correctly guessed the number I was thinking of in " + str(guessesTaken) + " Tries!")
if guess != number:
print ("Too bad, my number was " + str(number))
guessingGame()
| true |
533851062bae666d8dd3bd2f0aab2b3e9bb5127a | YCooE/Python-projects | /Math/numerical_integration_differential_equation/numerical_integration_differential_equation/num_int.py | 1,060 | 4.46875 | 4 | # Numerically estimate an integral for a function specified at integer samples
# 1) input: sample_fun: A N x 1 numpy array representing N samples f(1), f(2), f(3), ... f(N)
# x1: integer, the lower bound for the integral
# x2: integer, the upper bound for the integral
# 2) output: int_val: float (a real number), the approximated value of the integral
import numpy as np
#Load the data
data = np.loadtxt("data/precipitation.txt")
N = data.size
def num_int(sample_fun, x1, x2):
# Numerically approximate the integral as a Riemann sum, as discussed in the lecture
# Makes sure the interval makes sense.
assert (0 <= x1)
assert (x1 <= x2)
assert (x2 <= N)
# Here we could check if x1 and x2 are integers.
int_val = 0
# We want to include the x2'th.
for t in range(x1, x2+1):
int_val += sample_fun(t)
# Comment in if you want to see the values.
#print("day", t, "had", sample_fun(t), "mm percipation")
return int_val
# Precipitation functions
def p(t):
return data[t]
def P(t):
return num_int(p, 0, t)
P(182)
| true |
a6ecc3f3dc80a221714cd28b7717d9666d7e646d | anagorko/inf | /home/kolszak/greedy_change.py | 679 | 4.125 | 4 | """
Finds minimal number of coins needed to make a change using greedy algorithm.
"""
import unittest
from typing import Dict
coins = [500, 200, 100, 50, 20, 10, 5, 2, 1]
def change(amount: int) -> Dict[int, int]:
result = {}
for i in range(len(coins)):
result[coins[i]] = 0
while amount >= coins[i]:
amount -= coins[i]
result[coins[i]] += 1
return result
class GreedyChangeTest(unittest.TestCase):
"""Change function tests."""
def test_change_test(self):
"""Test some small hand picked example."""
self.assertEqual(change(1423), {500: 2, 200: 2, 100: 0, 50: 0, 20: 1, 10: 0, 5: 0, 2: 1, 1: 1})
| true |
88ff3db829110f235d6ff7156d275c660375e0a4 | DavidMena-Q/learning_python | /first_steps-py/bucles.py | 815 | 4.125 | 4 | # def potencia(numero, exponente):
# if exponente > 0:
# bandera = numero**exponente
# bandera = str(bandera)
# print('La potencia de {} a la {} es: {}'.format(numero, exponente, bandera))
# exponente = exponente - 1
# else:
# print('OK')
# def run():
# numero = float(input("Dame un número: "))
# exponente = float(input("Dame una potencia: "))
# potencia(numero, exponente)
# if __name__ == '__main__':
# run()
def run():
numero = int(input('Dame un número: '))
exponente = int(input('Dame un exponente: '))
while exponente > 0:
bandera = numero ** exponente
print(f'La potencia de {numero} elevado a la {exponente} es: {bandera}')
exponente -= 1
if __name__ == '__main__':
run()
| false |
cbfcf5686846ee0292d5198200c3f28f488df9dc | tkomasa/python_online_hw | /biologist.py | 652 | 4.40625 | 4 | num_organisms = int(input("Enter the initial number of organisms: "))
rate_growth = float(input("Enter the rate of growth: "))
growth_period = int(input("Enter the number of hours to achieve the rate of growth: "))
total_hours = int(input("Enter the total hours of growth: "))
hours = 0
while hours < total_hours:
num_organisms *= rate_growth
hours += growth_period
# simply to check the data
print(hours, num_organisms)
# stops the loop is the next iteration will exceed the max total time allowed
if hours + growth_period >= total_hours:
break
print("\nThe total population:", num_organisms)
| true |
990c8bd755adf0bd2d75afec1aac0ed1f47d06a9 | blancopedro/100daysOfcode | /day 12.py | 547 | 4.3125 | 4 | #finger exercise. write a program that examines three variables, x , y z and prints the larges odd number among them. If none of them are odd, it should print a message to that effect.
x = 10
y = 20
z = 30
if x%2 = 0 and x > y and y > z:
print 'x is the largest odd among x, y, and z'
elif y%2 !== 0 and y > z and z > x:
print 'y is the largest odd among x, y, and z'
elif z%2 !== 0 and z > y and y > x:
print 'z is the largest odd among x, y, and z'
elif x%2 == 0 or y % 2 == 0 or z%2 == 0:
print 'even' | true |
6a27db11962750ab918b84c2053be30185f2109a | git-athul/Python-HARDWAY | /ex36.py | 2,103 | 4.3125 | 4 | #Ex36.py: Designing and Debugging
# Homework problem
# Maze : Player have to escape the maze using left right and forward only
def dead():
print('You activated some trap, sounds like exit is closed. Good job!')
exit(0)
def ask_choice():
print("Which way you want to go")
ch = input(">")
return ch
def ask_left():
print("There is a way to the left")
ch = ask_choice()
return ch
def ask_right():
print("There is a way to the right.")
ch = ask_choice()
return ch
def loop_left():
count =0
while count != 3:
choice =ask_left()
if 'left' in choice:
count += 1
continue
else:
dead()
def loop_right():
count =0
while count != 3:
choice =ask_right()
if 'right' in choice:
count += 1
continue
else:
dead()
def loop(choice):
while 'forward' not in choice:
if 'right' in choice:
loop_right()
print("It looks you reached where you are started.")
choice = ask_choice()
if 'left' in choice:
loop_left()
print("It looks you reached where you are started.")
choice = ask_choice()
else:
dead()
def start():
print("""You are trapped in a maze.To make matters worse, it's dark everywhere.
Someone shouted 'Dont walk backward!'
So, which way do you want to go? forward, left or right """)
choice = input(">")
loop(choice)
choice =ask_right()
if 'right' in choice:
choice =ask_left()
if 'left' in choice:
print("There is way to left and right")
choice = ask_choice()
if 'right' in choice:
print("Congratulations. You have escaped")
elif 'left' in choice:
print("You fall into death")
exit(0)
else:
dead()
else:
dead()
else:
dead()
if __name__ == "__main__":
start()
| true |
7fce47195066eee70633d911b76f0d96d23bb7f5 | Lukazovic/Learning-Python | /CursoEmVideo/exercicio033 - maior e menor.py | 469 | 4.1875 | 4 | numero1 = float(input('Informe o primeiro número: '))
numero2 = float(input('Informe o segundo número: '))
numero3 = float(input('Informe o terceiro número: '))
maior = numero1
menor = numero1
if numero2 > maior:
maior = numero2
else:
if numero2 < menor:
menor = numero2
if numero3 > maior:
maior = numero3
else:
if numero3 < menor:
menor = numero3
print('\nO maior número é: {}' .format(maior))
print('O menor número é: {}\n' .format(menor)) | false |
75a1d9249c5d6b8a64f3dd55cde8eb018e0e68bc | Lukazovic/Learning-Python | /Aprendendo pelo App/String-Parte1.py | 750 | 4.125 | 4 | s = "hello world"
print(s)
print(len(s))
print('\nPrintando apenas alguns paremetros da String: ' + s[0] + s[1])
print('\nPrintando a partir de um certo parametro: ' +s[2:])
print('Ou até um certo parametro: ' +s[:2]) #não inclue o parametro 2
print('\nÉ possível printar o útimo paramtro sem sabe o tamanho da frase: ' +s[-1])
print('\nE pode-se fazer isso: ' + s[:-2] + ' -- ou -- ' +s[-4:])
#Pegar elementos de 1 em 1 da lista
print('\nPegando elementros de 1 e 1 na lista: ' +s[::1])
print('\nPegando elementros de 2 e 2 na lista: ' +s[::2])
print('\nPegando elementros de 1 em 1 e de trás para frente: ' +s[::-1])
print('\nPegando elementos de 1 em 1 apartir do terceiro elemento até o penúltimo: ' +s[3:9:1]) | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.