blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
305d22b7d4094bfe69f613bc6a11cac088cd51f0 | ShreyasAmbre/python_practice | /IntroToPython/Numpy/Basic Numpy.py | 773 | 4.375 | 4 | # Basic of Numpy, creating array using numpy
# numpy is faster then list because it store data in continous manner
# array() method is built-in in numpy yo create the numpy object, we can pass any array like object such as
# list & tuple
import numpy
# Basic Numpy Array
arr = numpy.array([12, "12", False, "Shreyas", 1.2])
for i in arr:
print(i)
print(type(arr))
# 2-D & 3-D Array using Array
# Note:- 1-D as an element called 2-D
# Note:- 2-D as an element called 3-D
# arr2 = numpy.array([ [1-D Element], [1-D Element] ])
arr2 = numpy.array([[2, 3, 5], [4, 6, 5]])
arr3 = numpy.array([[[12, 23, 15], [13, 16, 15]], [[1, 2, 3], [1, 2, 3]]])
print("2-D Array :- ")
print(arr2)
print("3-D Array :- ")
print(arr3)
print(arr.ndim)
print(arr2.ndim)
print(arr3.ndim)
| true |
290f44cf617673bc0203df18a99141e36e701a9d | rudrashishbose/PythonBible | /emailSlicer.py | 346 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 24 19:24:24 2020
@author: Desktop
"""
email_id = input("enter your email id: ")
username = email_id[0:email_id.index("@"):1]
domain_name = email_id[email_id.index("@")+1:]
output = "Your username is {} and your domain name is {}"
print(output.format(username,domain_name)) | true |
4a43883591df60bf17aaa26b91aa6fdadf470f6e | safin777/ddad-internship-Safin777 | /factorial.py | 391 | 4.21875 | 4 | def factorial(n):
factorial=1
if n<0 :
print("Factorial does not exits for value less than 0")
elif n == 0 :
print("The factorial of 0 is 1")
elif 0<n<10 :
for i in range(1,n+1):
factorial=factorial*i
print("The factorial of",n,"is",factorial)
else:
print("The input number is greater than 10")
if __name__ == '__main__':
number = int(input())
factorial(number)
| true |
48f7a90dfc5a7e933d00ad2b69806418992baf48 | jillianhou8/CS61A | /labs/lab01/lab01.py | 1,192 | 4.15625 | 4 |
""
"Lab 1: Expressions and Control Structures"""
# Coding Practice
def repeated(f, n, x):
"""Returns the result of composing f n times on x.
>>> def square(x):
... return x * x
...
>>> repeated(square, 2, 3) # square(square(3)), or 3 ** 4
81
>>> repeated(square, 1, 4) # square(4)
16
>>> repeated(square, 6, 2) # big number
18446744073709551616
>>> def opposite(b):
... return not b
...
>>> repeated(opposite, 4, True)
True
>>> repeated(opposite, 5, True)
False
>>> repeated(opposite, 631, 1)
False
>>> repeated(opposite, 3, 0)
True
"""
while n>0:
x = f(x)
n -= 1
return x
def sum_digits(n):
"""Sum all the digits of n.
>>> sum_digits(10) # 1 + 0 = 1
1
>>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
12
>>> sum_digits(1234567890)
45
"""
total = 0
while n > 0:
total += n % 10
n = n // 10
return total
def double_eights(n):
"""Return true if n has two eights in a row.
>>> double_eights(8)
False
>>> double_eights(88)
True
>>> double_eights(880088)
True
>>> double_eights(12345)
False
>>> double_eights(80808080)
False
"""
while n > 0:
if n % 10 == 8 and (n // 10) % 10 == 8:
return True
n = n // 10
return False
| true |
2ae557b4da917c5273c5a79b86618bd97805134e | antGulati/number_patterns | /narssistic numbers/narcissistic_number_list_python.py | 887 | 4.28125 | 4 | # program to take a long integer N from the user and print all the narcissistic number between one and the given number
# narcissistic numbers are those whose sum of individual digits each raised to the power of the number of digits gives the orignal number
import math
def digitcount(num):
return int(math.log(num,10)) + 1
def isNstc(a):
if a <= 9 and a >= 0:
return True
q = 0
num_digits = digitcount(a)
for i in range(num_digits):
digit = int(a/(10 ** i))
digit = digit % 10
q += (digit ** num_digits)
if q == a:
return True
return False
if __name__ == "__main__":
print("to find all narcissistic number between one and a given upper bound number")
upper_bound = int(input("enter the upperbound: "))
print("the narcissistic numbers in the given range are:")
for i in range(1,upper_bound+1):
if isNstc(i):
print(i)
| true |
488db0e00a310b5c45987ccbdf3171ccb6d875fb | clickykeyboard/SEM-2-OOP | /OOP/Week 08/assignment/employee.py | 2,941 | 4.34375 | 4 | class Employee:
def __init__(self, name, id, department, job_title):
self.name = name
self.id = id
self.department = department
self.job_title = job_title
employee_1 = Employee("Ahmed", "12345", "Management", "Manager")
employee_2 = Employee("Abbas", "54321", "Creative Team", "Designer")
employee_3 = Employee("Ahsan", "67891", "Management", "Senior Manager")
employees = {
employee_1.id: employee_1,
employee_2.id: employee_2,
employee_3.id: employee_3
}
while True:
print("""
Welcome to our system\n
Press 1 to look up an employee\n
Press 2 to add a new employee\n
Press 3 to change an existing employees name, department, or job title in the dictionary\n
Press 4 to delete an employee from the dictionary\n
Press 5 to exit\n
""")
print(employees)
choices = [1, 2, 3, 4, 5]
choice = int(input("> "))
if choice not in choices:
print("Please enter a valid choice")
elif choice == 1:
employee_id = input("Which employee do you want to look up?\n> ")
query = employees.get(employee_id)
if query is None:
print("Could not find employee!")
else:
print(query.id, query.name, query.department, query.job_title)
elif choice == 2:
print("Add a new employee: ")
employee_name = input("Enter employee name: ")
employee_id = input("Enter employee id: ")
employee_department = input("Enter employee department: ")
employee_job_title = input("Enter employee job title: ")
new_employee = Employee(employee_name, employee_id, employee_department, employee_job_title)
employees[new_employee.id] = new_employee
elif choice == 3:
print("Which employee information do you want to change?")
employee_choice = input("> ")
query = employees.get(employee_choice)
if query is None:
print("Could not find employee!")
else:
employee_name = input("Enter employee name: ")
employee_id = input("Enter employee id: ")
employee_department = input("Enter employee department: ")
employee_job_title = input("Enter employee job title: ")
query.name = employee_name
query.id = employee_id
query.department = employee_department
query.job_title = employee_job_title
employees.pop(query.id)
employees[query.id] = query
elif choice == 4:
print("Which employee information do you want to delete?")
employee_choice = input("> ")
query = employees.get(employee_choice)
if query is None:
print("Could not find employee!")
else:
employees.pop(query.id)
print("Deleted employee!")
elif choice == 5:
print("Exiting...")
exit()
| true |
ef24c44d58052f1cba4008a7449b61fc123da0f1 | ARPIT443/Python | /problem6.py | 881 | 4.125 | 4 | option = '''
Select operation you want to perform--->>
1.Show contents of single file :
2.Show contents of multiple file :
3.cat -n command :
4.cat -E command :
'''
print(option)
choice=input()
if choice == '1':
fname=input('Name of file :')
f=open(fname,'r')
print(f.read())
f.close()
elif choice == '2':
num=int(input('Enter no. of files :'))
fnames=[]
print('Enter name of files seperated by enter :')
for i in range(1,num+1):
name=input()
fnames.append(name)
for i in fnames:
f=open(i,'r')
print(f.read())
f.close()
elif choice == '3':
fname=input('Name of file :')
f=open(fname,'r')
data=f.read()
a=data.split('\n')
n=1
for i in a:
print(str(n)+' ' +i)
n=n+1
elif choice == '4':
fname=input('Name of file :')
f=open(fname,'r')
data=f.read()
a=data.split('\n')
for i in a:
print(i+'$')
else:
print('wrong input')
| true |
9a6cd9211feb8dc010e44af0e55eeecc592bbc1d | Benjamin1118/cs-module-project-recursive-sorting | /src/searching/searching.py | 1,160 | 4.3125 | 4 | # TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
# Your code here
#find a midpoint start search there
#check if start < end first
if start > end:
return -1
mid = (start + end) // 2
if arr[mid] == target:
return mid
# check if mid is < target
#if yes call binary search on new area
else:
if arr[mid] < target:
start = mid + 1
end = len(arr)
return binary_search(arr[start:end], target, start, end)
# check if mid is > target
#if yes call binary search on new area
if arr[mid] > target:
start = 0
end = mid
return binary_search(arr[start:end], target, start, end)
# STRETCH: implement an order-agnostic binary search
# This version of binary search should correctly find
# the target regardless of whether the input array is
# sorted in ascending order or in descending order
# You can implement this function either recursively
# or iteratively
def agnostic_binary_search(arr, target):
# Your code here
pass
| true |
5a58d0e43b93f4ea82b39b3fb181f89458b5369b | nabepa/coding-test | /Searching/bisect_library.py | 549 | 4.125 | 4 | # Count the number of frequencies of elements whose value is between [left, right] in a sorted array
from bisect import bisect_left, bisect_right
def count_by_range(array, left_val, right_val):
right_idx = bisect_right(array, right_val)
left_idx = bisect_left(array, left_val)
return right_idx - left_idx
if __name__ == '__main__':
array = list(map(int, input().split()))
left, right = map(int, input().split())
cnt = count_by_range(array, left, right)
print(cnt) if cnt > 0 else print(-1)
'''
1 2 3 3 4 5
3 4
'''
| true |
3a12122d4e65fd58d473244fe50a9de3a1339b27 | austinjhunt/dailycodingproblem | /dcp2.py | 1,924 | 4.125 | 4 | #This problem was asked by Uber.
#Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
#For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
#Follow-up: what if you can't use division?
# First use division approach
def dcp2_wDiv(num_array):
product = 1
for num in num_array:
product = product * num
for i in range(len(num_array)):
num_array[i] = product / num_array[i]
return num_array
#print(dcp2_wDiv([1,2,3,4,5]))
# Now, if you cant divide?
def dcp2_woDiv(num_array):
# exclusively multiply everything
count = 0
new_num_array = []
for i in range(len(num_array)):
product = 1
print "\n\ni = " + str(i)
for j in range(0,i): #nums before current num
print "product =" + str(product) + "*" + str(num_array[j])
product = product * num_array[j]
count += 1
for k in range(i+1, len(num_array)):
print "product =" + str(product) + "*" + str(num_array[k])
product = product * num_array[k]
count += 1
print "product = " + str(product)
new_num_array.append(product)
print("Count =", count)
return new_num_array
#print(dcp2_woDiv([1,2,3,4,5]))
def newdcp2(num_array):
temp = 1
products = [None] * len(num_array)
for j in range(0, len(num_array)):
products[j] = 1;
for i in range(0,len(num_array)):
products[i] = temp
temp = temp * num_array[i]
# init temp to one for product on right side
for i in range(len(num_array) - 1, -1,-1):
products[i] = products[i] * temp
temp = temp * num_array[i]
return products
#print(newdcp2([1,2,3,4,5])
| true |
18e5a15a489628f3c1a1e8d2a6e5b99ce66ddeeb | DrDavxr/email-text-finder | /mainPackage/extension_detector.py | 320 | 4.40625 | 4 | '''
This module finds the extension of the file selected by the user.
'''
def find_extension(filename):
'''
Finds the extension of a given file.
input: filename
output: file extension
'''
filename_list = filename.split('/')
extension = filename_list[-1].split('.')[-1]
return extension
| true |
e009fa6b516388eb7018d208ee2325196c7909ba | sonisidhant/CST8333-Python-Project | /calc.py | 2,170 | 4.1875 | 4 | ######################
# calc.py
# By Sidhant Soni
# October 24, 2018
######################
# Declaring variables and assigning user input
a = input('Enter First Number: ');
b = input('Enter Second Number: ');
print('\n')
# Converting user input string to integer
firstN = int(a);
secondN = int(b);
# Making the list of two numbers using user input
numbers = [firstN,secondN];
# Defining a test case
def arthDivide(c,d):
return c / d;
def add(c,d):
return c + d;
# Function for operating arithmetic operation
def arithmetic():
Sub = numbers[0] - numbers[1];
Add = numbers[0] + numbers[1];
modulus = numbers[0] % numbers[1];
multiply = numbers[0] * numbers[1];
print('Result of a-b = ', Sub);
print('Result of a+b = ', Add);
print('Result of a%b = ', modulus);
print('Result of a/b = ', multiply, '\n');
# Function for operating comparison operation
def comparison():
if numbers[0] == numbers[1]:
print('number a and b are equal');
else:
print('Number a and b are not equal');
if numbers[0] > numbers[1]:
print('Number a is greater than b');
else:
print('Number a is smaller than b');
# Function for operating logic operation
def logic():
if numbers[0] >= 10 and numbers[1] >=5:
print('True')
else:
print('False')
if numbers[0] > 10 or numbers[1] >= 5:
print('True')
else:
print('False')
# Function for operating decision structure operation
def decisionStructure():
age = int(input('Enter your age: '))
if age >= 18:
print('You are eligible for driving');
else:
print('Your age is less than 18. So, you are not eligible for driving.');
# Function for operating repetition structure operation
def repetitionStructure():
firstNumber = int(input('Enter the number to start printing: '));
secondNumber = int(input('Enter the number to finish printing: '))
while(firstNumber<secondNumber):
print('The number is: ', firstNumber);
firstNumber += 1;
# Running all the functions
repetitionStructure();
arithmetic();
comparison();
logic();
decisionStructure();
| true |
702f5ca9c7b730ac315b0fc6072e4bee0216824f | decadevs/use-cases-python-oluwasayo01 | /instance_methods.py | 1,277 | 4.3125 | 4 | # Document at least 3 use cases of instance methods
class User():
def __init__(self, username = None):
self.__username = username
def setUsername(self, x):
self.__username = x
def getUsername(self):
return(self.__username)
Steve = User('steve1')
print('Before setting:', Steve.getUsername())
Steve.setUsername('steve2')
print('After setting:', Steve.getUsername())
class BankAccount:
def __init__(self):
self.balance = 0
def withdraw(self, amount):
self.balance -= amount
return self.balance
def deposit(self, amount):
self.balance += amount
return self.balance
class Shape:
def __init__(self, length, width):
self.length = length
self.width = width
self.area = 0
self.perimeter = 0
def calc_area(self):
pass
def calc_perimeter(self):
pass
class Rectangle(Shape):
def calc_area(self):
self.area = self.length * self.width
def calc_perimeter(self):
self.perimeter = 2(self.length + self.width)
def get_area(self):
return self.area
def get_perimeter(self):
return self.perimeter
shape = Rectangle(23, 12)
print(shape.get_area())
print(shape.calc_area())
print(shape.get_area())
| true |
abad3a169e74dd4e19cbc6877567eb39a0bdb683 | AthenaTsai/Python | /python_notes/OOP/class.py | 904 | 4.5625 | 5 | # Class: object-oriented programming, inheritance
class Parent: # parent class, class is a structure, start with uppercase
def __init__(self, name, age, ht=168): # self tells the function is for which class
self.name = name
self.age = age
self.ht = ht
print('this is the parent class')
def parent_func(self):
print('your name is:' + self.name)
def test(self):
print('parent_before')
p = Parent('athena', 18) # now creating an object
p.parent_func()
#
class Child(Parent): # inherit contents from Parent class
def child_func(self):
print('this is the child func')
def test(self): # will overwrite parent methods
print('child_after')
c = Child('Kev', 23) # inherit this from Parent class
c.child_func()
c.parent_func() # inherit this from Parent class
c.test() # overwrite Parent class version
print(c.ht) | true |
a48f0730061352526c030c3ac66845e48fd213a8 | thelmuth/ProfessorProjectPrograms110 | /calculations/pizza.py | 1,003 | 4.25 | 4 | """
*****************************************************************************
FILE: pizza.py
AUTHOR: Professors
ASSIGNMENT: Calculations
DESCRIPTION: Professors' program for Pizza problem.
*****************************************************************************
"""
import math
def main():
standard_diameter = int(input('What is the diameter of a "standard" size pie? '))
slice_count = int(input("How many slices are in a standard size pie? "))
slices = int(input("How many standard slices do you want? "))
diameter = int(input("What is the diameter of the pies you will buy? "))
# Calculate number of pies
pies = slices * (standard_diameter ** 2.0) / ((diameter ** 2) * slice_count)
pies_ceiling = int(math.ceil(pies))
print("You will need to buy", pies_ceiling, str(diameter) + "-inch diameter pies.")
# this invokes the main function. It is always included in our
# python programs
if __name__ == "__main__":
main()
| true |
9dd0b3f60eb6ed3e167b001035da7cb07630a480 | Jaffacakeee/Python | /Python_Bible/Section 5 - The ABCs/hello_you.py | 437 | 4.125 | 4 | # Ask user for name
name = input("What is your name? ")
# Ask user for age
age = input("What is your age? ")
# Ask user for city
city = input ("What city do you live in? ")
# Ask user for what they love
love = input("What do you love? ")
# Build the structure of the sentence
string = "Your name is {} and you are {} old. You live in {} and love {}."
output = string.format(name, age, city, love)
# Print out sentence
print(output)
| true |
d3906ba829aecd6d2d665ba33306ebcafcb39f26 | Virtual-Uni/Discover-Python | /Exams/15.11.2020/Solutions/Mueem/Exam1/Task6.py | 549 | 4.25 | 4 | """
6. Task
Your code should calculate the average mark of students in a dictionary as key/value pairs.
Key represents the name of the student, whereas value represents marks_list from last few exams.
"""
marks_dictionary = {
'Hasan': [10, 5, 20],
'Sakir': [10, 10, 14],
'Hanif': [20, 15, 10],
'Saiful': [20, 20, 20]
}
empty_list = []
for x in marks_dictionary.keys():
empty_list.append(x)
for y in empty_list:
marks_list = marks_dictionary[y]
average = sum(marks_list) / len(marks_list)
print('Average of {} : {}'.format(y,average))
| true |
119b1ca27fc2a33b201c4f635e37fa8c7d77d4e6 | Virtual-Uni/Discover-Python | /Exams/15.11.2020/Solutions/Mueem/Exam1/Task4.py | 422 | 4.3125 | 4 | """
4. Task
Your provided code section should find a meaning of a word from a dictionary containing
key/value pairs of word: value.
line.
"""
input_word = input('Enter a word(Passed/Failed/Other) = ')
dictionary = {'Passed':'You have practiced at home.', 'Failed': 'You was not serious.',
'Other': 'Write your own meaning.'}
if input_word.isalpha():
print(dictionary[input_word])
else:
print('Enter a string')
| true |
58d38c4e908813e76d824039e7921e3dbfe91bb2 | marvin939/projecteuler-python | /problem 9 - special pythagorean triplet/problem9.py | 1,347 | 4.34375 | 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.
'''
from math import sqrt, floor, ceil
a = 1
b = None
c = None
P = 1000 # Perimeter of right-angled triangle. eg. a + b + c = 1000
# Must be a valid right-angle triangle perimeter since I'm only
# allowing natural numbers for a, b and c!!!
satisfied = False
aThirdOfP = floor(P / 3)
while a <= aThirdOfP:
# ^ condition is narrowed to 1/3 of P because we expect a < b < c
# and a + b + c = P; a cannot be larger than b and c, but can get somewhat
# close.
b = floor((P - 2 * a) * P / (2 * (P - a)))
c = floor(sqrt(a**2 + b**2))
if a + b + c == P and (a < b < c):
satisfied = True
break
a += 1
if satisfied:
print('pythagorean triplet satisfying a + b + c = {}'
' and a < b < c found:'.format(P))
print('a = {}, b = {}, c = {}'.format(a, b, c))
print('a * b * c =', a * b * c)
print('CONDITION SATISFIED!!!')
else:
print('a = {}, b = {}, c = {}'.format(a, b, c))
print('a^2 + b^2 = {}, and c^2 = {}'.format(a**2 + b**2, c**2))
print('a * b * c =', a * b * c)
print('NOT SATISFIED')
| true |
b068813edb18ee50949c41b70ba6047a906ea794 | marvin939/projecteuler-python | /problem 1 - multiples of 3 and 5/problem1.py | 402 | 4.25 | 4 | """
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get
3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
x = 1
sum35 = 0
while x < 1000: # below 10
addToSum = False
if x % 3 == 0 or x % 5 == 0:
sum35 += x
x += 1
print(sum35)
# sum of multiples of 3 and 5's below 1000 is 233168
| true |
1855ba6951647a66912cde9b70e1574cef006706 | ZryletTC/CMPTGCS-20 | /labs/lab02/lab02Funcs.py | 2,281 | 4.1875 | 4 | # lab02Funcs.py Define a few sample functions in Python
# T. Pennebaker for CMPTGCS 20, Spring 2016
def perimRect(length,width):
"""
Compute perimiter of rectangle
>>> perimRect(2,3)
10
>>> perimRect(4, 2.5)
13.0
>>> perimRect(3, 3)
12
>>>
"""
return 2*(length+width)
def areaRect(length,width):
"""
compute area of rectangle
>>> areaRect(2,3)
6
>>> areaRect(4, 2.5)
10.0
>>> areaRect(3,3)
9
>>>
"""
return length*width
def isList(x):
"""
returns True if argument is of type list, otherwise False
>>> isList(3)
False
>>> isList([5,10,15,20])
True
"""
return ( type(x) == list ) # True if the type of x is a list
def isString(x):
""""
return True if x is a string, otherwise False
"""
return (type(x)==str)
# The following function is provided for you as an example
# of how to write a Python function involving "or"
# This contains HINTS as to how to do the next function definition.
def isAdditivePrimaryColor(color):
"""
return True if color is a string equal to "red", "green" or "blue", otherwise False
>>> isAdditivePrimaryColor("blue")
True
>>> isAdditivePrimaryColor("black")
False
>>> isAdditivePrimaryColor(42)
False
>>>
"""
return ( (color == "red" ) or (color == "green" ) or (color == "blue") )
# NOTE: the following will NOT work for isAdditivePrimaryColor:
#
# def isAdditivePrimaryColor(color):
# return ( color == "red" or "green" or "blue" )
#
# Try it, and convince yourself that it doesn't work.
# Does it fail to compile, fail to run (python vomit), or just give the
# wrong answer? You may be surprised!
# Try it, then try to understand _why_ this doesn't do what you want
# Hints: 'or' is an operator, and it must take operands that are
# either True or False
# (color == "red") is either True or False. What about the other operands?
def isSimpleNumeric(x):
"""
returns True if x is has type int or float; anything else, False
>>> isSimpleNumeric(5)
True
>>> isSimpleNumeric(3.5)
True
>>> isSimpleNumeric("5")
False
>>> isSimpleNumeric([5])
False
>>> isSimpleNumeric(6.0221415E23)
True
>>>
"""
return ((type(x)==int) or (type(x)==float))
| true |
86a7139693f7997f4b0b0018f298bb45fbbd4126 | shivapk/Programming-Leetcode | /Python/Trees/checkGraphisaTreecolorsGraphds[n,n].py | 2,218 | 4.21875 | 4 | #say given graph is a valid tree or not.An undirected graph is tree if it has following properties.
#1) There is no cycle.
#2) The graph is connected.
#Time: O(n) where n is the number of vertices..as number of edges will be n-1.
#space: O(n) where n is number of vertices
# keep track of parent in case of undirected graph, although directed graph is not tree but if you want to find cycle for directed graph then p is not required
'''
cycle:For every visited vertex ‘v’, if there is an adjacent ‘u’ such that u is already visited and u is not parent of v,
then there is a cycle in graph. If we don’t find such an adjacent for any vertex, we say that there is no cycle.
'''
from collections import defaultdict
class Graph:
def __init__(self,n):
self.vcount=n
self.adjlist=defaultdict(list)
def insert(self,v1,v2):
self.adjlist[v1].append(v2)
self.adjlist[v2].append(v1)
class Solution:
def isgraph_tree(self,g):
color=['w']*(g.vcount)
#for v in range(g.vcount):#as we need to show graph is connected so need to do for every vertex
if self.dfs(0,color,g,-1): #choose any random vertex- 0 and -1 is assumed parent of 0 #parent is not required to check cycle in directed graph
return False
for i in range(g.vcount): #check after dfs anything is left still not visited
if color[i]=='w':
return False
return True
def dfs(self,v,color,g,p): # returns True if there is any cycle in the graph, p is for parent
color[v]='g' # grey means in process not yet backtracked to this vertex
for w in g.adjlist[v]:
if color[w]=='w' and self.dfs(w,color,g,v): # for directed graph p is not required
return True
elif color[w]=='g' and w!=p : # for directed graph p is not required
return True # cycle found
color[v]='b' #time to backtrack
return False # no cycle found
g=Graph(5)# number of vertices so nodes are labels from 0 to n-1
g.insert(1, 0)
g.insert(0, 2)
#g.insert(2,1)
g.insert(0, 3)
g.insert(3, 4)
s=Solution()
print (s.isgraph_tree(g))
| true |
f95f64cfdb3c2aa61700e311d79610d79262d1e8 | TheDiegoFrade/python_crash_course_2nd_ed | /input_while_loops.py | 1,515 | 4.125 | 4 | #number = input("Enter a number, and I'll tell you if it's even or odd: ")
#number = int(number)
#if number % 2 == 0:
# print(f"\nThe number {number} is even.")
#else:
# print(f"\nThe number {number} is odd.")
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
#prompt = "\nTell me something, and I will repeat it back to you:"
#prompt += "\nEnter 'quit' to end the program. "
#message = ""
#while message != 'quit':
# message = input(prompt)
# if message != 'quit':
# print(message)
# prompt = "\nPlease enter the name of a city you have visited:"
# prompt += "\n(Enter 'quit' when you are finished.) "
#Using break
# ➊ while True:
# city = input(prompt)
# if city == 'quit':
# break
# else:
# print(f"I'd love to go to {city.title()}!")
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# Verify each user until there are no more unconfirmed users.
# Move each verified user into the list of confirmed users.
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user)
# Display all confirmed users.
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(f'\n{pets}')
while 'cat' in pets:
pets.remove('cat')
print(pets)
| true |
d34f14cf5ffa70b9d4bacf51ef4a41e8c41d533c | TheDiegoFrade/python_crash_course_2nd_ed | /python_poll.py | 1,020 | 4.15625 | 4 | responses = {}
# Set a flag to indicate that polling is active.
polling_active = True
while polling_active:
# Prompt for the person's name and response.
name = input("\nWhat is your name? ")
response = input("Which are your favorite tacos? ")
# Store the response in the dictionary.
responses['name'] = name
responses['flavor'] = response
# Find out if anyone else is going to take the poll.
repeat = input("Would you like to tell me something else about you?(yes/no)")
if repeat.lower() == 'no':
polling_active = False
comment = ""
print(comment)
print("Goodbye!")
else:
comment = input("Write your comment please: ")
polling_active = False
print(comment)
print("Goodbye!")
responses['comment'] = comment
print(responses.items())
# Polling is complete. Show the results.
print("\n--- Poll Results ---")
for value in responses.values():
print(value)
print(f'Poll Dictionary: {responses}')
print("\n--- Poll Results ---")
for item in responses.items():
print(item) | true |
f740acd2ff5d494434ef64d91baed730e754f779 | Izydorczak/learn_python | /gdi_buffalo_2015/class2/functions_continued.py | 1,899 | 4.78125 | 5 | """
filename: functions_continued.py
author: wendyjan
This file shows more about functions.
"""
def say_hi():
print "Hello World!"
def say_hi_personally(person):
print "Hello " + person + "!"
def add_together(a, b):
return a + b
def calculate_y(m, x, b):
return m * x + b
def add_together_many(a, *args):
result = a
for n in args:
result += n
return result
def scale_list(my_list):
# TODO please implement this!
pass
if __name__ == "__main__":
# Call a function.
say_hi()
# Call a function with a parameter (also called an argument).
say_hi_personally("Elena")
# Print a value returned from a function.
result = add_together(2, 3)
print "The first result is:", result
# See the scope of a variable.
# Comment out the following three lines unless you want an error!
# result = add_together(5, 6)
# print "Done adding together", a, "and", b
# print "The result of add_together(5, 6) is", result
# Another scope example. What's different about this one?
# Why did it work, when the previous one in comments did not?
a = 7
b = 11
result = add_together(a, b)
print "Done adding together", a, "and", b
print "The result of add_together(a, b) is", result
# Now what if we want to give three parameters?
print "Given the formula y = 3x + 5, what is y when x is 8?"
print "Don't forget that old formula, y = mx + b."
print "y =", calculate_y(3, 8, 5)
# What about an arbitrary number of parameters?
result = add_together_many(1, 2, 3, 4, 5, 6)
print "All of those together equal:", result
# Now what if we have a list, and want to multiply each element?
my_list = range(5)
print my_list, "scaled by 3 is", my_list * 5
print "Oops!!! No!!! I meant to say it's", scale_list(my_list)
# Hmm... looks like this needs work!
| true |
c2f2744f17073e94b26f0c01f33dfd4750a65007 | shaneapen/LeetCode-Search | /src/utils.py | 1,643 | 4.34375 | 4 | def parse_args(argv):
"""Parse Alfred Arguments
Args:
argv: A list of arguments, in which there are only two
items, i.e., [mode, {query}].
The 1st item determines the search mode, there are
two options:
1) search by `topic`
2) search by `problem content/name/index`
The 2nd item is a string which is the user entered
from Alfred, which as known as {query}.
Return:
A argument dictionary, which contains following fields:
- mode: topic/problem
- difficulty: easy/medium/hard
- query: <query content>
"""
args = {}
# determine search mode
if(argv[0].lower() == "--topic"):
args["mode"] = "topic"
else:
args["mode"] = "problem"
# parsing query arguments
query_args = argv[1].split(' ')
# get difficulty (only take the highest level if
# multi-level are selected)
args["difficulty"] = None
if ("-e" in query_args) or ("--easy" in query_args):
args["difficulty"] = "Easy"
if ("-m" in query_args) or ("--medium" in query_args):
args["difficulty"] = "Medium"
if ("-h" in query_args) or ("--hard" in query_args):
args["difficulty"] = "Hard"
# get query content, any word start with '-' will be ignored
query_content = ""
for arg in query_args:
if arg and arg[0] != '-':
query_content += arg + " "
args["query"] = query_content[:-1]
return args
def is_match(dst, src):
if dst in src:
return True
else:
return False | true |
70c91c40394ae59ca2973541bd8a4d73da98b0c3 | skilstak/code-dot-org-python | /mymod.py | 1,758 | 4.25 | 4 | """Example module to contain methods, functions and variables for reuse.
This file gets loaded as a module (sometimes also called a library) when
you call `import mymod` in your scripts.
"""
import codestudio
class Zombie(codestudio.Artist):
"""An Artist with a propensity for brains and drawing squares.
While class definitions look like function definitions they are different.
The parameter inside the parenthesis () is the parent class. This means
all Zombies are Artists and can do everything an Artist can do.
The `start_direction` and `speed` are special variables that goes with
all Zombies. These are called class or static attributes. An attribute
is a variable that goes with a class or the objects created from a class.
"""
start_direction = 90 # facing the east, or right of screen
speed = 'slow' # it is a zombie after all
color = 'green' # it is a zombie after all
def draw_square(self,length):
for count in range(4):
self.move_forward(length)
self.turn_right(90)
def draw_circle(self):
saved_speed = zombie.speed
zombie.speed = 'fastest'
for count in range(360):
zombie.move_forward(1)
zombie.turn_right(1)
zombie.speed = saved_speed
def draw_snowman(self,length):
self.left()
distances = [length * 0.5, length * 0.3, length * 0.2]
for counter in range(6):
distance = distances[counter if counter < 3 else 5 - counter] / 57.5
for degree in range(90):
self.move(distance)
self.right(2)
if counter != 2:
self.left(180)
self.left()
| true |
081d354575e425e7e2a8f9f32d6729df27b3ca88 | Cyansnail/Backup | /PythonLists.py | 1,378 | 4.28125 | 4 | # how to make a list
favMovies = ["Star Wars", "Avengers", "LOTR"]
# prints the whole list
print(favMovies)
#prints only one of the items
print(favMovies[1])
# to add you can append or insert
# append adds to the end
favMovies.append("Iron Man 1")
print(favMovies)
# insert will put the item wherevre you want
favMovies.insert(1, "Harry Potter")
print(favMovies)
# how to remove items
# remove by name or by index
# remove by name use remove
favMovies.remove("LOTR")
print(favMovies)
#favMovies.remove("Kill Bill")
# pop will remove the last item, unless index is given
favMovies.pop()
print(favMovies)
favMovies.pop(1) # will remove whatever is in index 1
print(favMovies)
# get the length of a list
# this is a function
# the function name is len
print("My list has " + str(len(favMovies)) + " items.")
favMovie = input("What is your favorite movie? ")
favMovies.append(favMovie)
print(favMovies)
print(favMovies[len(favMovies)-1])
#loop through a list
count = 1
for movie in favMovies:
print("My number " + str(count) + " movie is " + movie )
count = count + 1
numList = [1, 3, 5, 7, 9, 11, 13, 15]
# challenge: Loop through the list and add all of the numbers together
total = 0
for totall in numList:
total = total + totall
print(total)
if "Harry Potter" in favMovies:
favMovies.remove("Endgame")
else:
print("Not in list") | true |
b0a55be05b1fc2e33561b8e676a8e3bd8916e489 | Munster2020/HDIP_CSDA | /labs/Topic04-flow/lab04.05-topthree.py | 687 | 4.1875 | 4 | # This program generates 10 random numbers.
# prints them out, then
# prints out the top 3
# I will use a list to store and
# manipulate the number
import random
# I programming the general case
howMany = 10
topHowMany = 3
rangeFrom = 0
rangeto = 100
numbers = []
for i in range(0,10):
numbers.append(random.randint(rangeFrom, rangeto))
print("{} random numbers\t {}".format(howMany, numbers))
# I am keeping the original list maybe I don't need to
# I got the idea to sort and split the list from stackover flow
# https://stackoverflow.com/q/32296887
topOnes = numbers.copy()
topOnes.sort(reverse=True)
print("The top {} are \t\t {}".format(topHowMany, topOnes[0:topHowMany]))
| true |
a1a02e09b242546b8003baf6caff98e293370a50 | makthrow/6.00x | /ProblemSet3/ps3_newton.py | 2,692 | 4.34375 | 4 | # 6.00x Problem Set 3
#
# Successive Approximation: Newton's Method
#
# Problem 1: Polynomials
def evaluatePoly(poly, x):
'''
Computes the value of a polynomial function at given value x. Returns that
value as a float.
poly: list of numbers, length > 0
x: number
returns: float
'''
indexValue = 0
total = 0.0
power = 0 # count the index. this is the power
for c in poly:
total += c * (x ** power)
power += 1
return total
# Problem 2: Derivatives
def computeDeriv(poly):
'''
Computes and returns the derivative of a polynomial function as a list of
floats. If the derivative is 0, returns [0.0].
poly: list of numbers, length > 0
returns: list of numbers (floats)
'''
"""
example case:
- 13.39 + 17.5x^2 + 3x^3 + x^4
poly = [-13.39, 0.0, 17.5, 3.0, 1.0]
print computeDeriv(poly)
[0.0, 35.0, 9.0, 4.0] # 35x + 9x^2 + 4x^3
"""
# FILL IN YOUR CODE HERE...
# poly value. muliply by its power
# then put in a new list, omit first poly value
power = 0.0 # count the index. this is the power. omit first value
derivList = []
if len(poly) == 1:
# print "length poly is 0"
derivList.append(0.0)
return derivList
else:
for c in poly:
value = c * power
power += 1
derivList.append(value)
derivList.pop(0)
return derivList
# Problem 3: Newton's Method
def computeRoot(poly, x_0, epsilon):
iter = 0
rootiter = [] # return list
# calculate x0
calcguess = evaluatePoly(poly, x_0)
#print "calcguess: %r " % calcguess
while abs(calcguess) > epsilon:
# use recursion call to calculate x1
iter += 1
# print "iter: %r" % iter
# print "x_0: %r" % x_0
x_0 = x_0 - (evaluatePoly(poly, x_0) / evaluatePoly(computeDeriv(poly), x_0))
calcguess = evaluatePoly(poly, x_0)
rootiter.append(x_0)
rootiter.append(iter)
return rootiter
print computeRoot([-13.39, 0.0, 17.5, 3.0, 1.0], 0.1, .0001)
print computeRoot([1, 9, 8], -3, .01)
print computeRoot([1, -1, 1, -1], 2, .001)
print evaluatePoly(computeDeriv([1, 9, 8]),2)
"""
def computeRoot(poly, x_0, epsilon):
iter = 0
x1 = 0
rootiter = []
# calculate x0
calcguess = evaluatePoly(poly, x_0)
if calcguess < epsilon:
rootiter.append(calcguess)
rootiter.append(iter)
return rootiter
else: # use recursion call to calculate x1
x1 = x_0 - evaluatePoly(poly, x_0) / evaluatePoly(computeDeriv(poly), x_0)
computeRoot(poly, x1, epsilon)
#returns: list [float, int]
return
"""
| true |
b39ca0c3cfb9a13ef5b02d0b8f705e89e9b4971f | makthrow/6.00x | /ProblemSet2/PS2-2.py | 1,165 | 4.21875 | 4 | balance = 4773
annualInterestRate = 0.2
# result code should generate: Lowest Payment: 360
# Variables:
# balance - the outstanding balance on the credit card
# annualInterestRate - annual interest rate as a decimal
# The monthly payment must be a multiple of $10 and is the same for all months
# TODO: CALCULATE MONTHLY PAYMENT BASED ON INITIAL BALANCE
""" MATHS:
Monthly interest rate = (Annual interest rate) / 12
Updated balance each month = (Previous balance - Minimum monthly payment) x (1 + Monthly interest rate)
"""
monthlyInterestRate = annualInterestRate / 12
fixedMonthlyPayment = 0
updatedBalance = balance
def remainingBalance(fixedMonthlyPayment):
month = 1
updatedBalance = balance
while month <= 12:
updatedBalance = round((updatedBalance - fixedMonthlyPayment) * (1 + monthlyInterestRate), 2)
month += 1
return updatedBalance
def balancePaidInFull(updatedBalance):
return updatedBalance <= 0
while not balancePaidInFull(updatedBalance):
fixedMonthlyPayment += 10
updatedBalance = remainingBalance(fixedMonthlyPayment)
print "Lowest Payment: %r" % fixedMonthlyPayment
| true |
ca3e671fd66ef9063da94334696dd8b11ebab69a | yueyueyang/inf1340_2015_asst2 | /exercise1.py | 1,481 | 4.125 | 4 | vowels = "aeiou"
def pig_latinify(word):
"""
Main translator function.
:param : string from function call
:return: word in pig latin
:raises:
"""
# convert string to all lowercase
word = word.lower()
# if string has numbers -> error
if not word.isalpha():
result = "Please only enter alphabetic characters."
# check if the first letter is a vowel
elif word[0] in ("a", "e", "i", "o", "u"):
result = word + "yay"
# there is a vowel in the word somewhere other than the first letter
elif check_for_any_vowels(word) == 1:
index = get_first_vowel_position(word)
word = word[index:] + word[0:index]
result = word + "ay"
# there are no vowels in the word
else:
if check_for_any_vowels(word) == 0:
result = word + "ay"
return result
def get_first_vowel_position(word):
"""
Figures out where the first vowel is
:param : word from pig_latinify
:return: index of vowel
:raises:
"""
no_vowel = False
if not no_vowel:
for c in word:
if c in vowels:
return word.index(c)
def check_for_any_vowels(word):
"""
Figures out if the word has any vowels
:param : word from pig_latinify
:return: 1 if any vowels, 0 if no vowerls
:raises:
"""
for c in vowels:
if c in word:
return 1
return 0
#pig_latinify("apple") | true |
02272ce4fee1b49d2c7d137bf7d930a18d3b6394 | key36ra/m_python | /log/0723_PickleSqlite3/note_sqlite3.py | 2,033 | 4.125 | 4 | import sqlite3
"""
Overview
"""
# Create "connection" obect.
conn = sqlite3.connect('example.db')
# Create "cursor" onject from "connection" object.
c = conn.cursor()
# Create table
c.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
# Insert a row of data
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
# Save (commit) the changes
conn.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()
"""
Rule to input securely
"""
# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print(c.fetchone())
# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
"""
Get data from 'SELECT' command
"""
# Iterator
for row in c.execute('SELECT * FROM stocks ORDER BY price'):
print(row)
# fetchone()
c.execute('SELECT * FROM stocks ORDER BY price')
print(c.fetchone())
# fetchall()
c.execute('SELECT * FROM stocks ORDER BY prince')
print(c.fetchall())
"""
Cursor object
"""
# class sqlite3.connect().cursor()
# execute(sql[,parameters)
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table peaple (name_last, age)")
# This is the qmark style:
cur.execute("insert into people values (?,?)",(who,age))
# And this is the named style:
cur.execute("select * from people where name_last=:who and age=:age",{"who":who,"age":age})
print(cur.fetchone())
# executemany(sql, seq_of_parameters)
# executescript(sql_script)
# fetchone(), fetchmany(size=cursor.arraysize), fetchall()
# close()
"""
Row object
"""
# class sqlite3.Row
| true |
8bc413580dd92b6ab78befe3ec6cc045b6698cd4 | GMcghn/42---Python-Bootcamp-Week1 | /day01/ex01/game.py | 1,498 | 4.25 | 4 | class GotCharacter:
# https://www.w3schools.com/python/python_inheritance.asp
def __init__(self, first_name, is_alive = True):
#properties (ne doivent pas forcément être en attributes)
self.first_name = first_name
self.is_alive = is_alive
# Inheritance allows us to define a class that inherits all the methods and properties from another class
# To create a class that inherits the functionality from another class,
# send the parent class as a parameter when creating the child class
class Lannister(GotCharacter):
""" class representing the Lannister family. Definitely the most badass of the saga. """
# When you add the __init__() function, the child class will no longer
# inherit the parent's __init__() function.
# To keep the inheritance of the parent's __init__() function, add a call to the parent's __init__() function
# Python also has a super() function that will make the child class inherit all the methods and properties from its parent
def __init__(self, first_name, family_name = 'Lannister', house_words = "A Lannister always pays his debts."):
self.family_name = family_name
self.house_words = house_words
# no 'self'
# define a value (is_alive) if not in child properties (first_name)
super().__init__(first_name, is_alive = True)
def print_house_words(self):
print(self.house_words)
def die(self):
self.is_alive = False
return self.is_alive
| true |
7cc8e38f5fcd767d522c5289fc2f9e60ecb00e71 | Sepp1324/Python---Course | /tut010.py | 595 | 4.53125 | 5 | #!/usr/bin/env python3
# strip() -> Removes Spacings at the beginning and the end of a string
# len() -> Returns the length of a String (w/0 \n)
# lower() -> Returns the string with all lowercase-letters
# upper() -> Returns the string with all uppercase-letters
# split() -> Split a string into a list where each word is a list item
_text = input('Input something: ')
print('Strip:',_text.strip())
print('Length:', len(_text))
print('Lower:', _text.lower())
print('Upper:', _text.upper())
print('Split:', _text.split()) # Default-Deliminator: Spacing; Other Indicator e.g: _text.split('.')
| true |
4a9bdc08f081dee7c1e469e016eaba575cece2f8 | kalpanayadav/shweta | /shweta1.py | 776 | 4.3125 | 4 | def arearectangle(length,breadth):
'''
objective: to calculate the area of rectangle
input:
length and breadth of rectangle
'''
# approach: multiply length and breadth
area = length*breadth
return area
def areasquare(side):
'''
objective: to calculate the area of square
input:
length of square
approach: multiply side by itself
'''
return(arearectangle(side,side))
def main():
'''
objective: to calculate the area of square
input: length of square
approach: multiply side by side itself
'''
a = int(input("enter the length of a side"))
print("area of square is",areasquare(a))
print("end of output")
if __name__ == '__main__':
main()
print("end of program")
| true |
0f6fc453225f9495703a7e4118e2e2d3b146860b | MnAkash/Python-programming-exercises | /My solutions/Q21.py | 1,248 | 4.59375 | 5 | '''
A robot moves in a plane starting from the origin point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps.
The trace of robot movement is shown as the following:
UP 5
DOWN 3
LEFT 3
RIGHT 2
The numbers after the direction are steps.
Please write a program to compute the distance from current position after a sequence of movement and original point.
If the distance is a float, then just print the nearest integer.
Example:
If the following tuples are given as input to the program:
UP 5
DOWN 3
LEFT 3
RIGHT 2
Then, the output of the program should be:
2
'''
from math import sqrt
updown_dist=0
leftright_dist=0
while True:
str = input ("Enter movement: ")
movement = str.split(" ")
type = movement [0]
dist = int (movement [1])
if type=="DOWN":
updown_dist += dist
elif type=="UP":
updown_dist -= dist
elif type=="LEFT":
leftright_dist += dist
elif type=="RIGHT":
leftright_dist -= dist
str = input ("Continue?(y/n):")
if not (str[0] =="Y" or str[0] =="y") :
break
#print(updown_dist,leftright_dist)
approx_pythagorian_dist=round(sqrt(updown_dist**2+leftright_dist**2))
print ("\nApprox Pythagorian Distancee: ", approx_pythagorian_dist) | true |
4074246e3cb5b70bd035663133ce58f9a68a69b8 | KaptejnSzyma/pythonexercises | /ifChallenge/ifChallenge.py | 233 | 4.1875 | 4 | name = input("Please enter your name: ")
age = int(input("Enter your age: "))
if 18 <= age < 31:
# if age <= 18 or age > 31:
print("Welcome to holiday, {}".format(name))
else:
print("Kindly, fuck off {}".format(name))
| true |
99f672c74e220a309801e670abfed73990a36d9a | mepragati/100_days_of_Python | /Day 019/TurtleRace.py | 1,229 | 4.34375 | 4 | from turtle import Turtle, Screen
import random
is_race_on = False
all_turtles = []
screen = Screen()
screen.setup(width=500,height=400)
color_list = ["red","green","blue","yellow","orange","purple"]
y_position = [-70,-40,-10,20,50,80]
user_input = screen.textinput("Enter here: ","Who do you think will win the race out of (red/green/blue/yellow/orange/purple)? Enter the colour: ").capitalize()
for turtle_count in range(6):
new_turtle = Turtle(shape='turtle')
new_turtle.penup()
new_turtle.goto(x=-230,y=y_position[turtle_count])
new_turtle.color(color_list[turtle_count])
all_turtles.append(new_turtle)
if user_input:
is_race_on = True
while is_race_on:
for turtle in all_turtles:
if turtle.xcor()>230:
is_race_on = False
winning_color = turtle.pencolor()
if winning_color.lower() == user_input.lower():
print(f"You won.The {winning_color.capitalize()} turtle is the winner!")
else:
print(f"You lost.The {winning_color.capitalize()} turtle is the winner and you chose {user_input}!")
random_distance = random.randint(0,10)
turtle.forward(random_distance)
screen.exitonclick() | true |
b218e1c5be5716b1b0e645018e64ea2f76a4e593 | SeyyedMahdiHP/WhiteHatPython | /python_note.py | 1,361 | 4.21875 | 4 | #PYTHON note
##########################List Slicing: list[start:end:step]######################################
user_args = sys.argv[1:] #sys.argv[1],sys.argv[2],....
#note that sys.argv is a collection or list of stringsT and then with above operation , user_args will be too
user_args = sys.argv[2:4]#sys.argv[2],sys.argv[3],sys.argv[4]
#Suppose you want the last argument (last argument is always -1,second last argument is -2 ,....
#so what is happening here is we start the count from back. So start is last, no end, no step) :
user_args = sys.argv[-1]
#Suppose you want the last two arguments :
user_args = sys.argv[-2:]
#Suppose you want the arguments in reverse order :
user_args = sys.argv[::-1]
#server.accept() output is a collection of {[socket object],[socket(ip,port)]}: (<socket._socketobject object at 0x02E3C998>, ('127.0.0.1', 25129))
#item1,item2,....=collection
client, addr=server.accept()# now we can use client as a socket object, and use addr[0] for ip, and addr[1] is port
#######################################################################
str = "doesn't or dosn\'t" * 10
1j + 3j
list_kharid[1:3]
#['sibzamini', 'mast']
list_kharid[1:3]=["sir"]
list_kharid[:]=[]
list_kharid
#[]
list_kharid.append("goje")
| true |
74f6bb45f38a8351d3a5b918ca3e571bfaec6441 | Vlad-Yekat/py-scripts | /sort/sort_stack.py | 454 | 4.15625 | 4 | # sort stack recursively using only push, pop and isepmpty
def insert(element, stack):
if len(stack) != 0 and element > stack[-1]:
top = stack.pop()
insert(element, stack)
stack.append(top)
else:
stack.append(element)
def stack_sort(stack):
if len(stack) != 0:
top = stack.pop()
stack_sort(stack)
insert(top, stack)
stack = [1, 2, 3, 4]
print(stack)
stack_sort(stack)
print(stack) | true |
cfca498a6f0f3f73f698ba67ea6589fac8f7d29d | Nithi07/hello_world | /sum_of_lists.py | 335 | 4.375 | 4 | """1.(2) Write a python program to find the sum of all numbers in a list"""
def sum_list(numbers):
a = range(numbers)
c = []
for _ in a:
b = int(input('enter your number: '))
c.append(b)
return sum(c)
message = int(input('how many numbers you calculate: '))
print(sum_list(message)) | true |
809e901bd59261096a299234c7fc7e45d996f5c1 | Nithi07/hello_world | /sum&avg.py | 336 | 4.15625 | 4 | """ 8. (3)Given a string, return the sum and average of the digits that appear in the string,
ignoring all other characters
"""
message = input('Enter: ')
a = []
for i in message:
if i.isdigit():
a.append(int(i))
tot = sum(a)
ave = tot / len(a)
print(f'sum of digit: {tot}\n average of digits: {ave}')
| true |
eb7d3ce1447378e96790b98903528afc3a2efc5f | Nithi07/hello_world | /div3and5.py | 437 | 4.25 | 4 | """
Write a function that returns the sum of multiples of 3 and 5 between 0 and limit (parameter).
For example, if limit is 20, it should return the sum of 3, 5, 6, 9, 10, 12, 15, 18, 20.
"""
def sum (limit):
i = limit + 1
x = range(0, i)
res = []
for num in x:
if num % 3 == 0 or num % 5 == 0:
res.append(num)
return res
message = int(input('upto: '))
print(sum(message)) | true |
70a74f5c8a7603f20958dea54051eb4b842168a3 | emellars/euler-sol | /019.py | 1,672 | 4.40625 | 4 | #Runtime ~0.07s.
#Determines if the year "n" is a leap year.
def is_leap_year(n):
if n % 400 == 0: return True
elif n % 100 == 0: return False
elif n % 4 == 0: return True
else: return False
#Determines if a month started with Sunday.
def month_starting_sunday(days):
if days % 7 == 2: return 1
else: return 0
#1 Jan 1900 begins on a Monday and the year has 365 days. Since 365 % 7 = 1, Jan 1901 must begin on a Tuesday.
#1901 % 7 = 4 corresponds to Tuesday. So we may take the current year (adjusted for leap years) and add the number of days in each month and divide by 7. If the remainder is 2, that month began with a Sunday.
year=1901
remaining_months = [31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
cumulative_leap_years = 0
cumulative_sundays = 0
while year < 2001:
if is_leap_year(year - 1): cumulative_leap_years += 1
adjusted_year = year + cumulative_leap_years #If the preceding year was a leap year, then, since 365 % 7 = 2, the January of that year starts on a day advanced one more than would be expected if all years were 365 days long.
#Determine if each month of the year started with a Monday.
#January.
if adjusted_year % 7 == 2:
cumulative_sundays += 1
#February.
if is_leap_year(year): number_of_days = 31 + 29
else: number_of_days = 31 + 28
cumulative_sundays += month_starting_sunday(adjusted_year + number_of_days)
#Remaining months in year.
for days in remaining_months:
number_of_days += days
cumulative_sundays += month_starting_sunday(adjusted_year + number_of_days)
year += 1
print(cumulative_sundays)
| true |
f9398e1f459c0713816924539bd642ba9d206a76 | sry19/python5001 | /hw06/turtle_draw.py | 2,003 | 4.8125 | 5 | # Author: Ruoyun Sun
# The program uses the star's segment to draw a star and a circle around the
# star
import turtle
import math
TRIANGLE_DEGREE = 180
TAN_18_DEGREE = 0.325
STAR_SEG = 500
COS_18_DEGREE = 0.951
STAR_DEGREE = 36
STAR_SIDE = 5
CIRCLE_ANGLE = 360
def main():
'''give the star's segment, draw a star and a circle around star
None -> None'''
turtle.hideturtle()
radius = STAR_SEG / 2 / COS_18_DEGREE
circle_x, circle_y = 0, -radius
draw_circle(radius, circle_x, circle_y)
star_x, star_y = -STAR_SEG / 2, STAR_SEG / 2 * TAN_18_DEGREE
draw_star(STAR_SEG, star_x, star_y)
turtle.exitonclick()
def draw_circle(radius, circle_x, circle_y):
'''use the radius to draw a circle
radius, x, y -> None'''
CIRCLE_LINE_COLOR = "blue"
CIRCLE_FILL_COLOR = "cyan"
ACCURACY = 400
turtle.color(CIRCLE_LINE_COLOR, CIRCLE_FILL_COLOR)
turtle.penup()
turtle.setposition(circle_x, circle_y)
turtle.pendown()
turtle.begin_fill()
# To simplify, we can use 'turtle.circle(radius)'
circle(radius, CIRCLE_ANGLE, ACCURACY)
turtle.end_fill()
turtle.penup()
def circle(radius, angle, step):
'''draw a circle. angle usually equals 360. The more steps, the more
accurate.
number, number, number -> None'''
distance = 2 * radius * math.sin(angle / CIRCLE_ANGLE / step * math.pi)
for i in range(step):
turtle.left(angle / step)
turtle.forward(distance)
def draw_star(star_seg, star_x, star_y):
'''use the star's segments to draw a star
size, x, y -> None'''
STAR_LINE_COLOR = 'red'
STAR_FILL_COLOR = "yellow"
turtle.pencolor(STAR_LINE_COLOR)
turtle.penup()
turtle.setposition(star_x, star_y)
turtle.pendown()
turtle.fillcolor(STAR_FILL_COLOR)
turtle.begin_fill()
for i in range(STAR_SIDE):
turtle.forward(star_seg)
turtle.right(TRIANGLE_DEGREE - STAR_DEGREE)
turtle.end_fill()
turtle.penup()
main()
| true |
9d162e4b60638bc81f79889ad5adc8d223fc8f1c | STJRush/handycode | /Python Basics Loops, Lists, Logic, Quiz etc/time&date/timesDates.py | 794 | 4.25 | 4 | from time import sleep
from datetime import datetime
now = datetime.now()
print("The full datetime object from the computer is", now)
print("\n We don't want all that, so we can just pick out parts of the object using strftime. \n")
# It's not necessary to list all of these in your own program, think of this a selection box of delicious
# chocolate chunks of code to choose from.
yearNow = now.strftime("%Y")
print("year:", yearNow)
monthNow = now.strftime("%m")
print("month:", monthNow)
dayOfDaMonth = now.strftime("%d")
print("day:", dayOfDaMonth)
timeNow = now.strftime("%H:%M:%S")
print("time:", timeNow)
hoursNow = now.strftime("%H")
print("hours:", hoursNow)
minsNow = now.strftime("%M")
print("mins:", minsNow)
secsNow = now.strftime("%S")
print("seconds:", secsNow)
| true |
0b569dc264fb884868bd7d98ebe2ade16b153c1e | STJRush/handycode | /ALT2 Analytics and Graphing/Live Web Data/openWeatherMapperino.py | 2,512 | 4.125 | 4 | # Python program to find current
# weather details of any city
# using openweathermap api
# 0K = 273.15 °C
# import required modules
import requests, json
# Enter your API key here. Uf you're using this in a progect, you should sign up and get your OWN API key. This one is Kevin's.
api_key = "a19c355c905cbcb821b784d45a9cb1de"
# base_url variable to store url
base_url = "http://api.openweathermap.org/data/2.5/weather?"
# Give city name
city_name = "Rush"
# complete_url variable to store
# complete url address
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
# get method of requests module
# return response object
response = requests.get(complete_url)
# json method of response object
# convert json format data into
# python format data
x = response.json()
"""play with this to see the raw, full output from the data stream"""
# print(x)
# Now x contains list of nested dictionaries
# Check the value of "cod" key is equal to
# "404", means city is found otherwise,
# city is not found
if x["cod"] != "404":
# store the value of "main"
# key in variable y
y = x["main"]
#print(y)
# store the value corresponding
# to the "temp" key of y
current_temperature = y["temp"]
# store the value corresponding
# to the "pressure" key of y
current_pressure = y["pressure"]
# store the value corresponding
# to the "humidity" key of y
current_humidiy = y["humidity"]
# store the value of "weather"
# key in variable z
z = x["weather"]
# store the value corresponding
# to the "description" key at
# the 0th index of z
weather_description = z[0]["description"]
# Here are those outputs printed very plainly so that you can use them
print(current_temperature)
print(current_pressure)
print(current_humidiy)
print(weather_description)
# Things to do:
# Displaty the temperature in °C instead of kelvin (subtract 273.15)
# Round this number using: whatYouWant = round(number_to_round, 2) That's 2 decimal places.
# COVID SAFETY ALARM IDEA:
# Run this program on a Raspberri Pi. Use a DHT sensor to measure the actual room temperature indoors.
# Compare the Room Temperature to the Outside Weathermap Temperature. If the room temperature is 23°C and the outside temperature is 4°C then someone is very wrong. There is no way those classroom windows could be open (unless you're burning a fire indoors). You should notify the students in the room with an alarm sound or bright flashy LED lights! They're in a poorly ventilated area!
| true |
b4f7d2810b41752a75c3c457e44a3af88972dc8b | STJRush/handycode | /Python Basics Loops, Lists, Logic, Quiz etc/runBetweenHoursOf.py | 810 | 4.4375 | 4 | # modified from https://stackoverflow.com/questions/20518122/python-working-out-if-time-now-is-between-two-times
import datetime
def is_hour_between(start, end):
# Get the time now
now = datetime.datetime.now().time()
print("The time now is", now)
# Format the datetime string to just be hours and minutes
time_format = '%H:%M'
# Convert the start and end datetime to just time
start = datetime.datetime.strptime(start, time_format).time()
end = datetime.datetime.strptime(end, time_format).time()
is_between = False
is_between |= start <= now <= end
is_between |= end <= start and (start <= now or now <= end)
return is_between
check = is_hour_between('08:30', '15:30') #spans to the next day
print("time check", check) # result = True
| true |
1b6c299cc1dfde6fb9049cba1af4b37494123774 | AyushGupta05/Coding-Lessons | /Python/string.py | 594 | 4.3125 | 4 | username=input("Please enter your name")
print("Hello",username,"welcome to this class")
print("Hello "+username+ " welcome to this class")
print(f"Hello {username},welcome to this class")
print ("Hello {},welcome to this class".format(username))
#Ways to put a print statement
age=input("Please enter your age")
print("Your age is cofirmed as",age)
print("Your name is",username, "and your age is",age)
print(f"Your name is {username}, and your age is {age}")
print("Your name is {}, and your age is {}".format(username,age))
print("Your name is {1}, and your age is {0}".format(age,username)) | true |
cd2f045291ce3ce1d0b9c1653752b989fb3a1860 | jordan-carson/Data_Structures_Algos | /HackerRank/staircase.py | 594 | 4.15625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the staircase function below.
def staircase(n):
# get the number of the base
# calculate the number of blank spaces for the first row, (do we need an empty row)
# so if we are at 1 and n = 10 then we need to print 1 '#' while also printing 9 ' '
for i in range(1, n+1):
print(' ' * (n-i) + '#' * i)
# for i in range(1, n+1):
# print(' '*(n-i) + '#'*i)
# [print(' '*(n-i) + '#'*i) for i in range(1,n+1)]
if __name__ == '__main__':
n = int(input())
staircase(n)
| true |
a6ee152b820fa607e090e0d5c44a8f8e854fb190 | jordan-carson/Data_Structures_Algos | /Udacity/1. Data Structures/0. Strings/anagram_checker.py | 1,085 | 4.28125 | 4 | # Code
def anagram_checker(str1, str2):
"""
Check if the input strings are anagrams of each other
Args:
str1(string),str2(string): Strings to be checked
Returns:
bool: Indicates whether strings are anagrams
"""
if len(str1) != len(str2):
# remove the spaces and lower the strings
str1_update = str1.replace(' ', '').lower()
str2_update = str2.replace(' ', '').lower()
if len(str1_update) == len(str2_update):
if ''.join(sorted(str1_update)) == ''.join(sorted(str2_update)):
return True
return False
if __name__ == '__main__':
# Test Cases
print("Pass" if not (anagram_checker('water', 'waiter')) else "Fail")
print("Pass" if anagram_checker('Dormitory', 'Dirty room') else "Fail")
print("Pass" if anagram_checker('Slot machines', 'Cash lost in me') else "Fail")
print("Pass" if not (anagram_checker('A gentleman', 'Elegant men')) else "Fail")
print("Pass" if anagram_checker('Time and tide wait for no man', 'Notified madman into water') else "Fail")
| true |
a5e5305b4997a6fa42444dc521c311506558fbfc | jordan-carson/Data_Structures_Algos | /HackerRank/30daysofcode/day3.py | 837 | 4.40625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Given an integer, , perform the following conditional actions:
# If is odd, print Weird
# If is even and in the inclusive range of to , print Not Weird
# If is even and in the inclusive range of to , print Weird
# If is even and greater than , print Not Weird
# Complete the stub code provided in your editor to print whether or not is weird.
def isOdd(n):
return n % 2 != 0
def isEven(n):
return n % 2 == 0
def solution(inp):
N = inp
if isOdd(N):
print('Weird')
elif isEven(N) and N >= 2 and N <= 5:
print('Not Weird')
elif isEven(N) and N >= 6 and N <= 20:
print('Weird')
elif isEven(N) and N > 20:
print('Not Weird')
if __name__ == '__main__':
N = int(input())
solution(N)
| true |
7ee8d81ca6f796c8a6934e30ac80873de2d9034b | jordan-carson/Data_Structures_Algos | /Udacity/0. Introduction/Project 1/Task4.py | 1,575 | 4.21875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
# Declare variables
PRINT_MSG_4 = """These numbers could be telemarketers: """
incoming_calls, incoming_texts, outgoing_calls, outgoing_texts = set(), set(), set(), set()
def print_task4(print_msg, list_of_numbers, formatter=52):
print(print_msg)
for i in list_of_numbers: print(i)
for call in calls:
outgoing_calls.add(call[0])
incoming_calls.add(call[1])
for text in texts:
outgoing_texts.add(text[0])
incoming_texts.add(text[1])
if __name__ == '__main__':
# final_set = {element for element in incoming_calls if element not in outgoing_calls and element not in outgoing_texts and element not in incoming_texts}
final_list = list(sorted(outgoing_calls - (incoming_calls | incoming_texts | outgoing_texts))) # set difference = outgoing_calls - incoming_calls - incoming_texts - outgoing_texts
print_task4(PRINT_MSG_4, final_list) | true |
7bf93a3bc135b7981e7d51910f7bbd78a745a0bf | jordan-carson/Data_Structures_Algos | /Coursera/1. AlgorithmicToolbox/week2_algorithmic_warmup/8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers/fibonacci_sum_squares.py | 1,951 | 4.21875 | 4 | # Uses python3
from sys import stdin
import time
## a simple Fibonacci number genarator
def get_next_fib():
previous, current = 0, 1
yield previous
yield current
while True:
previous, current = current, previous + current
yield current
## find the Pisano sequence for any given number
## https://en.wikipedia.org/wiki/Pisano_period
"""
In number theory, the nth Pisano period, written π(n),
is the period with which the sequence of Fibonacci numbers taken modulo n repeats
"""
def get_pisano_seq(m):
def check(candidate):
middle = len(candidate) // 2
if middle == 0:
return False
for i in range(middle):
if candidate[i] != candidate[middle + i]:
return False
return True
seq = []
for fib in get_next_fib():
seq.append(fib % m)
if (len(seq) % 2):
if check(seq):
return seq[:len(seq) // 2]
## get the last digits of the n-th and (n+1)-th Fib number
## by using the Pisano sequence for 10
def get_last_digits(n):
seq = get_pisano_seq(10)
return seq[n % len(seq)], seq[(n+1) % len(seq)]
## calculate the last digit of the sum of squared Fib numbers
## by using that F0^2+F1^2+.....+Fn^2 = Fn * F(n+1)
## https://math.stackexchange.com/questions/2469236/prove-that-sum-of-the-square-of-fibonacci-numbers-from-1-to-n-is-equal-to-the-nt
def fibonacci_sum_squares_naive(n):
previous, current = get_last_digits(n)
return (previous * current) % 10
# def fibonacci_sum_squares_naive(n):
# if (n <= 0):
# return 0
#
# fibo = [0] * (n + 1)
# fibo[1] = 1
#
# # Initialize result
# sm = fibo[0] + fibo[1]
#
# # Add remaining terms
# for i in range(2, n + 1):
# fibo[i] = fibo[i - 1] + fibo[i - 2]
# sm = sm + fibo[i]
#
# return sm
if __name__ == '__main__':
n = int(stdin.read())
print(fibonacci_sum_squares_naive(n))
| true |
6829e40eebf18276067138b8e59cb87c3a091073 | jordan-carson/Data_Structures_Algos | /Udacity/1. Data Structures/5. Recursion/staircase.py | 609 | 4.375 | 4 |
def staircase(n):
"""
Write a function that returns the number of steps you can climb a staircase that
has n steps.
You can climb in either 3 steps, 2 steps or 1 step.
Example:
n = 3
output = 4
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
4. 3 steps
"""
if n == 1:
return 1
elif n == 2:
return 2
elif n == 3:
return 4
return staircase(n - 1) + staircase(n - 2) + staircase(n - 3)
if __name__ == '__main__':
print(staircase(4) == 7)
print(staircase(3) == 4)
| true |
fcd90e605a660a2a6190b8a28411c943adfc8ac5 | cleelee097/MIS3640 | /Session06/calc.py | 2,695 | 4.1875 | 4 | # age = input('please enter your age:')
# if int(age) >= 18:
# print('adult')
# elif int(age) >=6:
# print('teenager')
# else:
# print('kid')
# if x == y:
# print('x and y are equal')
# else:
# if x < y:
# print('x is less than y')
# else:
# print('x is greater than y')
# import webbrowser
# def calculate_bmi(weight, height):
# bmi=weight/(height*hegiht)
# if bmi<=18.5:
# print("your bmi is {:.1f}. You are underweighted.".format (bmi))
# elif 18.5 < bmi <= 25:
# print('y')
# print('Overweight')
# elif 18.5<=int(bmi)<=24.9:
# print('Normal weight')
# else:
# print('underweight')
# 2. Assume that two variables, varA and varB, are assigned values, either numbers or strings.
# Write a piece of Python code that prints out one of the following messages:
# "string involved" if either varA or varB are strings
# "bigger" if varA is larger than varB
# "equal" if varA is equal to varB
# "smaller" if varA is smaller than varB
def compare(varA, varB):
if isinstnace(varA, str) or isinstance(varB, str):
print('string involved')
else:
if varA > varB:
print('bigger')
elif varA==varB:
print('equal')
else:
print('smaller')
a='hello'
b=3
c=5
compare(a,b)
compare(b,c)
def diff21(n):
if n<=21:
return 21-n
else:
return (n-21)*2
#hen squirrels get together for a party, they like to have cigars.
# A squirrel party is successful when the number of cigars is between 40 and 60, inclusive.
# Unless it is the weekend, in which case there is no upper bound on the number of cigars.
# Return True if the party with the given values is successful, or False otherwise.
return is_weekend and cigars >=40 or 40 <=cigars <=60
print(cigar_party(30,False)) #False
print(cigar_party(50,False)) #True
print(cigar_party(70,False))#True
# def cigar_party(cigars, is_weekend):
# if is_weekend and cigars
# return True
# else:
# if 40<=cigars<=60:
# return True
# else:
# return False
print(cigar_party(30,False)) #False
print(cigar_party(50,False)) #True
print(cigar_party(70,False))#True
def countdown(n):
if n <= 0:
print('Blastoff!')
else:
print(n)
countdown(5)
def print_n(s, n):
if n <= 0:
return
print(s)
print_n(s, n-1)
#countdown(5)
def fabonacci(n):
if n == 1 or n == 2:
return 1
return fabonacci(n-2) + fabonacci(n-1)
# print(fabonacci(6))
# print(fabonacci(2))
def factorial(n):
if n == 1:
return 1
else:
return factorial(n-1)*n
print(factorial(3)) | true |
2f5d0a2673e142b6753b704659fef639b0b586d3 | JdeH/LightOn | /LightOn/prog/pong/pong4.py | 2,526 | 4.125 | 4 | class Attribute: # Attribute in the gaming sense of the word, rather than of an object
def __init__ (self, game):
self.game = game # Done in a central place now
self.game.attributes.append (self) # Insert each attribute into a list held by the game
# ============ Standard interface starts here
def reset (self):
pass
def predict (self):
pass
def interact (self):
pass
def commit (self):
pass
# ============ Standard interface ends here
class Sprite (Attribute): # Here, a sprite is an rectangularly shaped attribute that can move
def __init__ (self, game, width, height):
self.width = width
self.height = height
Attribute.__init__ (self, game) # Call parent constructor to set game attribute
class Paddle (Sprite):
width = 10 # Constants are defined per class, rather than per individual object
height = 100 # since they are the same for all objects of that class
# They are defined BEFORE the __init__, not INSIDE it
def __init__ (self, game, index):
self.index = index # Paddle knows its player index, 0 == left, 1 == right
Sprite.__init__ (self, game, self.width, self.height)
class Ball (Sprite):
side = 8
def __init__ (self, game):
Sprite.__init__ (self, game, self.side, self.side)
class Scoreboard (Attribute): # The scoreboard doesn't move, so it's an attribute but not a sprite
pass
class Game:
def __init__ (self):
self.attributes = [] # All attributes will insert themselves into this polymorphic list
self.paddles = [Paddle (self, index) for index in range (2)]
self.ball = Ball (self)
self.scoreboard = Scoreboard (self)
for attribute in self.attributes:
attribute.reset ()
def update (self): # To be called cyclically by game engine
for attribute in self.attributes: # Compute predicted values
attribute.predict ()
for attribute in self.attributes: # Correct values for bouncing and scoring
attribute.interact ()
for attribute in self.attributes: # Commit them to game engine for display
attribute.commit ()
game = Game () # Create and run game
| true |
e9be930cb5bf1cab43b288ccb2b68d0d8f1dd003 | felipeng/python-exercises | /12.py | 370 | 4.34375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25])
and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function.
'''
a = [5, 10, 15, 20, 25]
def first_last(list):
return [list[0], list[-1]]
print(first_last(a))
| true |
25c85e50548c1d465bdccb3e396f3c98b1f74c4c | felipeng/python-exercises | /11.py | 615 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten,
a prime number is a number that has no divisors.). You can (and should!) use your answer to Exercise 4 to help you.
Take this opportunity to practice using functions, described below.
'''
n = raw_input("Number: ")
n = int(n)
def prime(n):
c = []
for x in range(2,n):
if (n % x) == 0:
c.append(x)
if len(c) != 0:
r = " NOT"
else:
r = ""
print("The number {} is{} prime.".format(n,r))
prime(n)
| true |
d38a0334a8851b5e69809e73aef8cc758ea0e9a6 | harrytouche/project-euler | /023/main.py | 2,669 | 4.1875 | 4 | """
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
"""
from functools import reduce
import math
import numpy as np
def SumOfTwoNumbers(a, b):
return a + b
def SumOfDivisorsOfNumber(n):
output = []
max_iteration = math.ceil(n / 2) + 1
for i in range(1, max_iteration):
if n % i == 0:
if i not in output:
output.append(i)
# only append the other factor if no the sqrt
if i ** 2 != n and int(n / i) != n and int(n / i) not in output:
output.append(int(n / i))
return reduce(SumOfTwoNumbers, output)
def GetAbundantNumbersUpToN(n):
abundant_numbers_ceiling = n
abundant_numbers = []
for i in range(1, abundant_numbers_ceiling + 1):
if SumOfDivisorsOfNumber(i) > i:
abundant_numbers.append(i)
return abundant_numbers
abundant_max = 28123
try:
print(
"There are {} abundant numbers up to {}".format(
len(abundant_numbers), abundant_max
)
)
except Exception:
abundant_numbers = GetAbundantNumbersUpToN(abundant_max)
# create matrix of all abundant number sums
matrix = np.zeros((len(abundant_numbers), len(abundant_numbers)), dtype=int)
for i in range(len(abundant_numbers)):
for j in range(len(abundant_numbers)):
new_addition = abundant_numbers[i] + abundant_numbers[j]
if new_addition < abundant_max:
matrix[i, j] = new_addition
# get the uniques and sum, then take from the sum of all numbers
unique_sums = list(np.unique(matrix))
unique_sums_sum = reduce(SumOfTwoNumbers, unique_sums)
sum_of_all_numbers_to_abundant_max = reduce(SumOfTwoNumbers, range(abundant_max))
difference = sum_of_all_numbers_to_abundant_max - unique_sums_sum
print(difference)
| true |
69c35b2065585d91bb59322b28d0664df638d254 | harrytouche/project-euler | /009/main.py | 733 | 4.21875 | 4 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
a + b + c = 1000
a**2 + b**2 = c**2
"""
sum_number = 1000
complete = 0
loop_max = sum_number
for a in range(1, loop_max):
for b in range(1, loop_max - a):
# c is defined once a and b are
c = loop_max - a - b
if (a ** 2 + b ** 2) == c ** 2:
print("Found! a={}, b={}, c={}".format(a, b, c))
print("Product is: {}".format(a * b * c))
complete = 1
if complete == 1:
break
if complete == 1:
break
| true |
6a9c0f0926fa39305376a3632ef442fb4062c2c3 | harrytouche/project-euler | /019/main.py | 933 | 4.25 | 4 | """
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
from datetime import date
min_year = 1901
max_year = 2000
n_sundays_as_firsts = 0
for i in range(min_year, max_year + 1):
for j in range(1, 13):
current_date = date(i, j, 1)
if current_date.weekday() == 6:
n_sundays_as_firsts += 1
print(
"There were {} Sundays as first of months between the years {} and {}".format(
n_sundays_as_firsts, min_year, max_year
)
)
| true |
e4eee2f6325eb055064b9f94c82eb278296e7c03 | Parnit-Kaur/Learning_Resources | /Basic Arithmetic/fibonacci.py | 237 | 4.28125 | 4 | print("Enter the number till you want fibonacci series")
n = int(input())
a = 1
b = 1
print("The fibonacci sequence will be")
print(a)
print(b)
for i in range(2, n):
fibonacci = a + b
b = a
a = fibonacci
print(fibonacci)
| true |
39dfeeb264d7dc50e7c7acd992e442b789dcf029 | bnewton125/MIT-OpenCourseWare | /6.0001/ps4/ps4a_edited.py | 2,539 | 4.1875 | 4 | # Problem Set 4A
# Name: <your name here>
# Collaborators:
# Time Spent: x:xx
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part. Non-recursive solutions will not be
accepted.
Returns: a list of all permutations of sequence
Example:
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Note: depending on your implementation, you may return the permutations in
a different order than what is listed here.
'''
def permute(seq, perm):
if len(seq) < 1: # Out of letters to permute so stop recursion
return
else: # still have letters to permute through so continue recursion
if len(perm) == 0: # basically a first letter check
perm.append(seq[0]) # only permutation of the first letter are that letter
else: # for each different permutation fill
perms_copy = perm.copy() # create a copy of perms so perms can be emptied
perm.clear() # empty perms
for word in perms_copy: # for each existing word in perms fill out permutations into perms
for letters in range(len(word)+1):
if letters == 0:
perm.append(str(seq[0] + word))
elif letters == len(word)+1:
perm.append(str(word + seq[0]))
else:
perm.append(str(word[:letters] + seq[0] + word[letters:]))
permute(seq[1:], perm) # recurse with the first letter ripped out
permutations = []
permute(sequence, permutations)
return permutations
if __name__ == '__main__':
#EXAMPLE
example_input = 'cba'
print('Input:', example_input)
print('Expected Output:', ['abc', 'bac', 'bca', 'acb', 'cab', 'cba'])
print('Actual Output:', get_permutations(example_input))
print('')
example_input = 'xyz'
print('Input:', example_input)
print('Expected Output:', ['zyx', 'yzx', 'yxz', 'zxy', 'xzy', 'xyz'])
print('Actual Output:', get_permutations(example_input))
print('')
example_input = 'mno'
print('Input:', example_input)
print('Expected Output:', ['onm', 'nom', 'nmo', 'omn', 'mon', 'mno'])
print('Actual Output:', get_permutations(example_input)) | true |
99b08d79c104a1995e201ff2cccae06b131a6ee6 | mareliefi/learning-python | /calendar.py | 1,977 | 4.40625 | 4 | # This is a calender keeping track of events and setting reminders for the user in an interactive way
from time import sleep,strftime
your_name = raw_input("Please enter your name: ")
calender = {}
def welcome():
print "Welcome " + your_name
print "Calender is opening"
print strftime("%A, %B, %d, %Y")
print strftime("%H:%M:%S")
sleep(1)
print "What would you like to do?"
def start_calender():
welcome()
start = True
while start == True:
user_choice = raw_input("Please enter A to Add, U to Update, V to View , D to Delete and X to Exit")
user_choice = user_choice.upper()
if user_choice =="V":
if len(calender.keys()) < 1:
print "Calender is empty"
else:
print calender
elif user_choice == "U":
date = raw_input("What date? ")
update = raw_input("Enter the update: ")
calender[date] = update
print "Update successful!"
print calender
elif user_choice == "A":
event = raw_input("Enter event: ")
date = raw_input("Enter date (MM/DD/YYYY)")
if len(date) > 10 or len(date) < 10 or int(date[6:]) < int(strftime("%Y")):
print "Invalid date was entered"
try_again = raw_input("Try Again? Y for Yes, N for No: ")
try_again = try_again.upper()
if try_again == "Y":
continue
else:
start = False
else:
calender[date] = event
print "Event was successfully added."
elif user_choice == "D":
if len(calender.keys()) < 1:
print "Calender is empty"
else:
event = raw_input("What event? ")
for date in calender.keys():
if event == calender[date]:
del calender[date]
print "Event was successfully deleted"
else:
print "Incorrect event was specified"
elif user_choice == "X":
start = False
else:
print "Invalid command was entered"
exit()
start_calender()
| true |
23b21cec45b892ff56c982f21ec07b78d61b9c87 | borisBelloc/onlineChallenges_Algorithms_RecruitmentTests | /Algorithms/sort_on_the_fly.py | 305 | 4.1875 | 4 | # Sort on the fly
# we ask user 3 numbers and we sort them as they arrive
lst = []
while len(lst) < 3:
value = int(input("enter one number (sort on the fly) :\n"))
i = 0
while i < len(lst) and value > lst[i]:
i += 1
lst.insert(i, value)
print("here is the sorted array {}\n".format(lst))
| true |
93dc0a880bf9d61481d40f0e9f49e7e2e034d8d2 | cg342/iWriter | /start.py | 1,728 | 4.21875 | 4 | '''
https://hashedin.com/blog/how-to-convert-different-language-audio-to-text-using-python/
Step 1: Import speech_recognition as speechRecognition. #import library
Step 2: speechRecognition.Recognizer() # Initializing recognizer class in order to recognize the speech. We are using google speech recognition.
Step 3: recogniser.recognize_google(audio_text) # Converting audio transcripts into text.
Step 4: Converting specific language audio to text.
'''
import speech_recognition as sr
r = sr.Recognizer()
def getLanguage(argument):
switcher = {
1: "en-IN",
2: "hi-IN",
3: "kn-IN"
}
return switcher.get(argument, 0)
def getSelection():
try:
userInput = int(input())
if (userInput<1 or userInput>3):
print("Not an integer! Try again.")
except ValueError:
print("not an integer! Try again.")
else:
return userInput
# Reading Audio File as source
# output stored in audio_text variable
def startConvertion(path, lang = 'en-IN'):
with sr.AudioFile(path) as source:
print('Fetching File')
audio_text = r.listen(source)
try:
print('Converting audio transcripts into text ...')
text = r.recognize_google(audio_text, language = lang)
print(text)
# print("hello how are you")
except:
print('Sorry.. run again...')
# if __name__ == '__main__':
# print('Please Select Language: ')
# print('1. English')
# print('2. Chinese')
# languageSelection = getLanguage(getSelection())
# startConvertion('sample.m4a', languageSelection)
print(startConvertion('sample2.wav','en-IN'))
| true |
f06d11254eda94677d3d723852e6b214222bd85a | BlissfulBlue/linux_cprogramming | /sample_population_deviation.py | 1,550 | 4.4375 | 4 | # Number values in the survey
survey = [10, 12, 6, 11, 8, 13]
# sorts numbers into ascending order and prints it out
survey.sort()
print(f"The order from lowest to highest: {survey}")
# assigns variable number of values in the list and prints
list_length = (len(survey))
print(f"There are {list_length} values in the list.")
# calculates the mean by sum of list / number of values and prints it out
mean = sum(survey) / (len(survey))
print(f"The mean is {mean}\n")
# takes each individual number, subtracts by mean, squares it, and prints it
subtract_xbar = []
for value in survey:
subtract_xbar.append(value - mean)
squared = []
for deviation in subtract_xbar:
squared.append(deviation ** 2)
print(f"Before squaring: {subtract_xbar}")
print(f"After squaring: {squared} (Worry about this part)")
print()
# adds the sum of all squared numbers and print as integer
sigma = sum(squared)
print((f"Sum of list after squaring: {sigma}"))
# divide sigma (sum of all squared values) by len(squared) (number of values in list: squared), then square root it, and print it.
import math
#################################
# uncomment for sample deviation
sample_dev = len(survey) - 1
print(f"n - 1 = {sample_dev} (To understand, look at formula)")
print()
Nminus1_divide = sigma / sample_dev
print("Answer:\n")
print(math.sqrt(Nminus1_divide))
#################################
# uncomment for population deviation
# n_divide = sigma / len(survey)
# print(math.sqrt(n_divide))
| true |
119af8834d42cf7fae4effba7fb229b0e42983c6 | Pratik-sys/code-and-learn | /Modules/sorted_random_list.py | 620 | 4.25 | 4 | #!/usr/bin/python3
# Get a sorted list of random integers with unique elements
# Given lower and upper limits, generate a sorted list of random numbers with unique elements, starting from start to end.
"""
Input: num:10, start:100, end:200
Output: [102, 118, 124, 131, 140, 148, 161, 166, 176, 180]
Input: num:5, start:1, end:100
Output: [37, 49, 64, 84, 95]
"""
import random
def sorted_random(num, start, end):
'''
To-do: Change a default value to the desirable value
start < end, always
'''
return sorted(random.randint(start, end) for i in range(num))
print(sorted_random(10, 1, 200)) | true |
b2d11e2223b46cce0f39978d561dd96bead9e03c | Pratik-sys/code-and-learn | /Modules/password_gen.py | 2,736 | 4.25 | 4 | #!/usr/bin/python3
# Write a password generator in Python.
# Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols.
# The passwords should be random, generating a new password every time the user asks for a new password.
"""
No test cases.
This question is left open-ended as it may vary various implemention.
Using two or more different modules is allowed.
"""
import random
def generate_password(digits, low_case, up_case, symbol):
# combine the characters from the arrya that has been passed.
combine_cahr = digits + low_case + up_case + symbol
# randomly select atleast one char from each array.
rand_digit = random.choice(digits)
rand_upper_char = random.choice(low_case)
rand_lower_char = random.choice(up_case)
rand_symbol = random.choice(symbol)
# combine the each character driven from above
temp_pass = rand_digit + rand_upper_char + rand_lower_char + rand_symbol
password = temp_pass + random.choice(combine_cahr)
return (f'"{password}" is the random generated password')
print(
generate_password(
["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
[
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
],
[
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"M",
"N",
"O",
"p",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
],
["@", "#", "$", "%", "=", ":", "?", ".", "/", "|", "~", ">", "*", "(", ")"],
)
)
import secrets
import string
'''
The secrets module is used for generating random numbers for managing important data such as passwords, account authentication, security tokens, and related secrets, that are cryptographically strong.
'''
def gen_password():
alphabets = string.ascii_letters + string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation
password = ''.join (secrets.choice(alphabets) for i in range(10))
return password
print(f'"{gen_password()}" is the random generated password') | true |
7b6e3af7a399d49e8cc7979d658c3dfe7e4349cc | Pratik-sys/code-and-learn | /Recursion/Fibonacci/fibonacci_using_recursion.py | 535 | 4.15625 | 4 | #!/usr/bin/python3
# Write a function int fib(int n) that returns Fn. For example, if n = 0, then fib() should return 0. If n = 1, then it should return 1. For n > 1, it should return Fn-1 + Fn-2.
"""
Input: 9
Output : 34
"""
# Solution: Method 1 ( Use recursion )
def fib(n):
"""
This function returns the the fibonaaci number
"""
if n < 0:
print("we don't do that here")
elif n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
print(fib(9))
| true |
9cf37d2ecef5737c12ba23a5e6b99a0380c051ef | Pratik-sys/code-and-learn | /Dictionary/winner.py | 1,350 | 4.15625 | 4 | # Given an array of names of candidates in an election. A candidate name in array represents a vote casted to the candidate. Print the name of candidates received Max vote. If there is tie, print lexicographically smaller name.
# Check lexographically smaller/greater on wiki.
"""
Input : votes[] = {"john", "johnny", "jackie",
"johnny", "john", "jackie",
"jamie", "jamie", "john",
"johnny", "jamie", "johnny",
"john"};
Output : 'john'
We have four Candidates with name as
'John', 'Johnny', 'jamie', 'jackie'.
The candidates John and Johny get maximum votes.
Since John is alphabetically smaller, we print it.
"""
from collections import Counter
def winner(voters):
vote_name = Counter(voters)
name_vote = {}
for value in vote_name.values():
name_vote[value] = []
for key, value in vote_name.items():
name_vote[value].append(key)
winner_value = sorted(name_vote, reverse=True)[0]
winner_name = sorted(name_vote[winner_value])[0]
print(f' The winner is {winner_name}')
winner(
[
"john",
"johnny",
"jackie",
"johnny",
"john",
"jackie",
"jamie",
"jamie",
"john",
"johnny",
"jamie",
"johnny",
"john",
]
)
| true |
10f55cdc4a5acee3e1ece322810f64f1f30ecd25 | RealMirage/Portfolio | /Python/ProjectEuler/Problem1.py | 637 | 4.28125 | 4 | '''
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
# List comprehension method
def solve_with_lc():
numbers = range(1000)
answer = sum([x for x in numbers if x % 3 == 0 or x % 5 == 0])
print(answer)
# Simpler method
def solve_simply():
numbers = range(1000)
answer = 0
for number in numbers:
if number % 3 == 0 or number % 5 == 0:
answer = answer + number
print(answer)
if __name__ == '__main__':
solve_with_lc()
solve_simply() | true |
7ec6facac795aff55fc277f331fe57fcaf63d312 | juliusortiz/PythonTuts | /ListAndTuplesTutorial.py | 1,405 | 4.28125 | 4 | # #+INDEX - 0 1 2
# courses = ["BSIT","BSCS","BLIS","BA","ACS","BSCS","BSIT"]
#
# #Range selection
# print(courses[1:5])
#
# #Changing index value
# courses[0] = "Accountancy"
# print(courses)
#
# #Printing the length of the list
# print(len(courses))
#
# #Printing the number of duplicates from the list
# print(courses.count("BSIT"))
#
# #Adding values from the list
# courses.append("Business")
# courses.append("PE")
# courses.append("Health")
# print(courses)
#
# #Inserting index from the list
# courses.insert(1,"Family Planning")
# print(courses)
#
# #Deleting specified item from the list
# courses.remove("Accountancy")
# print(courses)
#
# #Deleting specified index from the list
# courses.pop(0)
# print(courses)
#
# #Delete default end from the list
# courses.pop()
# print(courses)
#
# #delete the whole list
# del courses
# print(courses)
#
#
# #Clear the indexes from the list
# test = ["Math", "English"]
# test.clear()
# print(test)
# #Copy lists from another lists
# listOne = ["BSIT", "BSCS", "BLIS"]
# listOne.pop()
# listTwo = listOne.copy()
# print(listTwo)
# #Combining Lists by adding
# listOne = ["BSIT","BSCS","BLIS"]
# listTwo = ["Hatdog","CheeseDog"]
# listThree = listOne + listTwo
# print(listThree)
# #Combining Lists by adding(using extend)
# listOne = ["BSIT","BSCS","BLIS"]
# listTwo = ["Hatdog","CheeseDog"]
# listOne.extend(listTwo)
# print(listOne)
| true |
95829d0e11c21cbd29e53f6ad71211e4fb320bf7 | amitsubedi353/Assignment | /assign2.py | 412 | 4.21875 | 4 | def is_Anagram(str1, str2):
n1 = len(str1)
n2 = len(str2)
if n1 != n2:
return 0
str1 = sorted(str1)
str2 = sorted(str2)
for i in range(0, n1):
if str1[i] != str2[i]:
return 0
return 1
str1 = "realmadrid"
str2 = "elarmdiard"
if is_Anagram(str1, str2):
print ("The two strings are anagram of each other")
else:
print ("The two strings are not anagram of each other") | true |
160ef0394e57547b4fac0d3afd7b8ef11a21d42f | SushanKattel/LearnBasicPython | /Dictionaries_example.py | 1,023 | 4.375 | 4 | month_names = {
"jan": "January",
1: "January",
"feb": "February",
2: "February",
"mar": "March",
3: "March",
"apr": "April",
4: "April",
"may": "May",
5: "May",
"jun": "June",
6: "June",
"jul": "July",
7: "July",
"aug": "August",
8: "August",
"sep": "September",
9: "September",
"oct": "October",
10: "October",
"nov": "November",
11: "November",
"dec": "December",
12: "December"
}
def get_work():
a= input("Press 'a' keyword for entering name in abberations and 'n' keyword if you want to input number: ")
if a == "a":
x= input("Enter the three digit abberation of english month: ")
return x
elif a == "n":
x= int(input("Enter the number of month: "))
return x
else:
print("PLEASE ENTER VALID CHARACTER! {Input in lowercase!!}")
y = get_work()
if y:
print(month_names.get(y,"Opps!! Invalid entry!!! Try giving name in lowercase or omit 0 before number."))
| true |
b4ae05891fe87614b461f12bb04a933d48093c67 | SaiAshish9/PythonProgramming | /generators/size.py | 934 | 4.28125 | 4 | # generator functions are a
# special kind of function that
# return a lazy iterator. These are objects
# that you can loop over like a list. However, unlike
# lists, lazy iterators do not store their conten
# Python generators are a simple way of creating iterators.
def rev_str(my_str):
length = len(my_str)
for i in range(length - 1, -1, -1):
yield my_str[i]
for char in rev_str("hello"):
print(char)
def fibonacci():
current,previous=0,1
while True:
current,previous=current+previous,current
yield current
fib=fibonacci()
# for i in range(6):
# print(next(fib))
def oddnumbers():
n=1
while True:
yield n
n+=2
def pi_series():
odds=oddnumbers()
approx=0
while True:
approx+=(4/next(odds))
yield approx
approx-=(4/next(odds))
yield approx
approx=pi_series()
for x in range(100000):
print(next(approx))
| true |
06100aee24e1c23fa77cbd1cd43b8ef89bf01d77 | Christopher-Caswell/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 495 | 4.25 | 4 | #!/usr/bin/python3
"""
Write a class My_List that inherits from list
Public instance meth: def print_sorted(self):
that prints the list, but sorted (ascending sort)
"""
class MyList(list):
"""Top shelf, have some class"""
def __init__(self):
"""Superdot inits with parent parameters"""
super().__init__()
def print_sorted(self):
"""return the sorted list intake"""
print(sorted(self))
"""print("{}".format(self.sort)) does not work tho?"""
| true |
9748755004c7e42dd8817a6a52bd83ff29765926 | Christopher-Caswell/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 1,186 | 4.34375 | 4 | #!/usr/bin/python3
"""
Print a pair of new lines between the strings
separators are . ? :
raise a flag if not a string, though
"""
def text_indentation(text):
"""Consider me noted"""
if not isinstance(text, str):
raise TypeError("text must be a string")
"""
chr(10) is a new line.
Written in ASCII to keep clean
and somewhat save space for pep8
x is a string variable used to-
-convert the old string into new
"""
i = 0
x = ""
while i in range(len(text) - 1):
if text[i] is '.':
x += text[i] + chr(10) + chr(10)
elif text[i] is '?':
x += text[i] + chr(10) + chr(10)
elif text[i] is ':':
x += text[i] + chr(10) + chr(10)
elif (text[i - 1] is '.' or
(text[i - 1] is ':') or
(text[i - 1] is '?') and
text[i] is " "):
while text[i] == " ":
i += 1
x += text[i]
elif (text[i - 1] is not '.' and
(text[i - 1] is not ':') and
(text[i - 1] is not '?')):
x += text[i]
i += 1
print("{}{}".format(x, text[-1]), end="")
| true |
d101baa4a1ecbde443c85ea6c6f2accbf3d3ab2a | pankilshah412/P4E | /Assignment 3.2.py | 742 | 4.375 | 4 | #Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error. If the score is between 0.0 and 1.0, print a grade using the following table:
#Score Grade
#>= 0.9 A
#>= 0.8 B
#>= 0.7 C
#>= 0.6 D
#< 0.6 F
#If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85.
try :
grade = raw_input("Enter Score: ")
g = float(grade)
except :
print "Please Enter score between 0.0 and 1.0"
quit()
if g < 0.6 and g >= 0.0:
print "F"
elif g >=0.6 and g < 0.7:
print "D"
elif g >=0.7 and g < 0.8 :
print "C"
elif g >=0.8 and g < 0.9 :
print "B"
elif g>0.9 and g<=1.0:
print "A"
else:
print "Number out of range"
| true |
020749fd6c1c702e6212c5df834d5b83ae20d92f | bikenmoirangthem/Python | /reverse_string.py | 361 | 4.59375 | 5 | #program to reverse a string
#function to reverse a string
def reverse(s):
str = ''
for i in s:
str = i + str
return str
#getting a string from user
str = input('Enter any string : ')
#printing the original string
print('Your original string : ',str)
#printing the reverse string
print('Reverse string : ',reverse(str))
| true |
6780b2fa26b4c1649f2787738e03ee7c042a453b | chetan4151/python | /positivelist.py | 341 | 4.15625 | 4 | # Write a Python program to print all positive numbers in a range.
list1=[]
n=int(input("Enter number of elements you want in list :"))
print(f"Enter {n} elements:")
for i in range(0,n):
a=int(input())
list1.append(a)
print("list1=",list1)
list2=[]
for i in range(0,n):
if list1[i]>0:
list2.append(list1[i])
print(list2)
| true |
4229ec2c151a99ef52eec1c7841e31e2e12d8794 | JanviChitroda24/pythonprogramming | /10 Days of Statistics/Day 0/Weighted Mean.py | 1,512 | 4.28125 | 4 | '''
Objective
In the previous challenge, we calculated a mean. In this challenge, we practice calculating a weighted mean. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given an array, , of integers and an array, , representing the respective weights of 's elements, calculate and print the weighted mean of 's elements. Your answer should be rounded to a scale of decimal place (i.e., format).
Input Format
The first line contains an integer, , denoting the number of elements in arrays and .
The second line contains space-separated integers describing the respective elements of array .
The third line contains space-separated integers describing the respective elements of array .
Constraints
, where is the element of array .
, where is the element of array .
Output Format
Print the weighted mean on a new line. Your answer should be rounded to a scale of decimal place (i.e., format).
Sample Input
5
10 40 30 50 20
1 2 3 4 5
Sample Output
32.0
Explanation
We use the following formula to calculate the weighted mean:
And then print our result to a scale of decimal place () on a new line.
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
# import numpy as np
n = int(input())
x = list(map(int, input().split()))
y = list(map(int, input().split()))
# print(round(np.average(x, weights = y), 1))
print(round(sum(map(lambda a: a[0] * a[1], zip(x,y)))/sum(y), 1))
| true |
2a18ab3e5918b5518454ac41565769a3912d7d1f | JanviChitroda24/pythonprogramming | /Hackerrank Practice/RunnerUp.py | 879 | 4.25 | 4 | '''
Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given scores. Store them in a list and find the score of the runner-up.
Input Format
The first line contains . The second line contains an array of integers each separated by a space.
Constraints
Output Format
Print the runner-up score.
Sample Input 0
5
2 3 6 6 5
Sample Output 0
5
Explanation 0
Given list is . The maximum score is , second maximum is . Hence, we print as the runner-up score.
'''
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
x = set(arr)
x = list(x)
x.sort(reverse=True)
print(x[1])
'''x.sort(reverse=True)
print(x);
x = list(set(x))
print(x)
#x = set(x.sort(reverse = True))
print(x[0]) #[1])''' | true |
eae94c125d5a7b3f733c77573111e92cc1fdb527 | JanviChitroda24/pythonprogramming | /Hackerrank Practice/Mini_Max Sum.py | 1,796 | 4.40625 | 4 | '''
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
For example, . Our minimum sum is and our maximum sum is . We would print
16 24
Function Description
Complete the miniMaxSum function in the editor below. It should print two space-separated integers on one line: the minimum sum and the maximum sum of of elements.
miniMaxSum has the following parameter(s):
arr: an array of integers
Input Format
A single line of five space-separated integers.
Constraints
Output Format
Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than a 32 bit integer.)
Sample Input
1 2 3 4 5
Sample Output
10 14
Explanation
Our initial numbers are , , , , and . We can calculate the following sums using four of the five integers:
If we sum everything except , our sum is .
If we sum everything except , our sum is .
If we sum everything except , our sum is .
If we sum everything except , our sum is .
If we sum everything except , our sum is .
Hints: Beware of integer overflow! Use 64-bit Integer.
Need help to get started? Try the Solve Me First problem
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the miniMaxSum function below.
def miniMaxSum(arr):
arr.sort()
s = 0
min, max = sum(arr[:len(arr)-1]), sum(arr[1:])
print(min, max)
if __name__ == '__main__':
arr = list(map(int, input().rstrip().split()))
miniMaxSum(arr)
| true |
08d15907da0916342026766888602ebb9c9c9e56 | JanviChitroda24/pythonprogramming | /Hackerrank Practice/Time Conversion.py | 1,395 | 4.15625 | 4 | '''
Given a time in -hour AM/PM format, convert it to military (24-hour) time.
Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.
Function Description
Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format.
timeConversion has the following parameter(s):
s: a string representing time in hour format
Input Format
A single string containing a time in -hour clock format (i.e.: or ), where and .
Constraints
All input times are valid
Output Format
Convert and print the given time in -hour format, where .
Sample Input 0
07:05:45PM
Sample Output 0
19:05:45
'''
#!/bin/python3
import os
import sys
#
# Complete the timeConversion function below.
#
def timeConversion(s):
#
# Write your code here.
#
time = s.split(":")
if s[-2:] == "PM":
if time[0] != "12":
time[0] = str(int(time[0])+12)
else:
if time[0] == "12":
time[0] = "00"
ntime = ':'.join(time)
return str(ntime[:-2])
if __name__ == '__main__':
f = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
print(s)
result = timeConversion(s)
f.write(result + '\n')
f.close()
| true |
d908a2c337533ac0f25113b1ca7ac994247cb4ec | JanviChitroda24/pythonprogramming | /Hackerrank Practice/Lists.py | 1,889 | 4.65625 | 5 | ```
Consider a list (list = []). You can perform the following commands:
insert i e: Insert integer at position .
print: Print the list.
remove e: Delete the first occurrence of integer .
append e: Insert integer at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
Initialize your list and read in the value of followed by lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list.
Input Format
The first line contains an integer, , denoting the number of commands.
Each line of the subsequent lines contains one of the commands described above.
Constraints
The elements added to the list must be integers.
Output Format
For each command of type print, print the list on a new line.
Sample Input 0
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
Sample Output 0
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
```
if __name__ == '__main__':
arr = []
for i in range(int(input())):
s = input().split()
for i in range(1, len(s)):
s[i] = int(s[i])
if s[0] == "append":
arr.append(s[1])
elif s[0] == "extend":
arr.extend(s[1:])
elif s[0] == "insert":
arr.insert(s[1],s[2])
elif s[0] == "remove":
arr.remove(s[1])
elif s[0] == "pop":
arr.pop()
elif s[0] == "index":
print(arr.index(s[1]))
elif s[0] == "count":
print(arr.count(s[1]))
elif s[0] == "sort":
arr.sort()
elif s[0] == "reverse":
arr.reverse()
elif s[0] == "print":
print(arr) | true |
3ce7edd59141cefc007942f7ddbd53ba0a12c8ad | fahimkk/automateTheBoringStuff | /chapter_5/birthdays.py | 491 | 4.15625 | 4 | birthdays = {'Alice':'April 1', 'Bob':'March 21', 'Carol':'Dec 4'}
while True:
name = input('Enter a name: (blank to Quit)\n')
if name == '':
break
if name in birthdays:
print(birthdays[name]+' is the birthday of '+name)
print()
else:
print('I dont have birthday informaton for '+name)
bday = input('What is their birthday ?\n')
birthdays[name] = bday
print('Birthday database updated')
print()
print(birthdays) | true |
726eca08e0049d17f4000037c283bacc627d1eb2 | larsnohle/57 | /21/twentyoneChallenge2.py~ | 1,239 | 4.15625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
def get_positive_number_input(msg, to_float = False):
done = False
while not done:
try:
i = -1.0
if to_float == True:
i = float(input(msg))
else:
i = int(input(msg))
if i < 0:
print("Please enter a number > 0")
else:
done = True
except ValueError:
print("That was not a valid integer. Please try again!")
return i
def main():
month_as_number = get_positive_number_input("Please enter the number of the month: ")
month_dict = {}
month_dict[1] = "January"
month_dict[2] = "February"
month_dict[3] = "March"
month_dict[4] = "April"
month_dict[5] = "May"
month_dict[6] = "June"
month_dict[7] = "July"
month_dict[8] = "August"
month_dict[9] = "September"
month_dict[10] = "October"
month_dict[11] = "November"
month_dict[12] = "December"
month_as_string = month_dict.get(month_as_number, "there is no such month!")
string_to_output = "The name of the month is %s." % month_as_string
print(string_to_output)
### MAIN ###
if __name__ == '__main__':
main()
| true |
f6fcd47c5084c99cf3738301b304398fde52d508 | larsnohle/57 | /18/eighteenChallenge2.py | 1,682 | 4.1875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
def get_positive_number_input(msg, to_float = False):
done = False
while not done:
try:
i = -1.0
if to_float == True:
i = float(input(msg))
else:
i = int(input(msg))
if i < 0:
print("Please enter a number > 0")
else:
done = True
except ValueError:
print("That was not a valid integer. Please try again!")
return i
def input_scale():
done = False
print("Press C to convert from Fahrenheit to Celsius.")
print("Press F to convert from Celsius to Fahrenheit.")
while not done:
scale = input("Your choice? ")
if scale == 'C' or scale == 'c' or scale == 'F' or scale == 'f':
scale = scale.upper()
done = True
return scale
def calculate_fahrenheit_to_celsius(f):
return (f - 32) * 5.0 / 9.0
def calculate_celsius_to_fahrenheit(c):
return (c * 9.0 / 5.0) + 32
def input_and_convert_from_celsius():
c = get_positive_number_input("Please enter the temperature in Celsius: ")
f = calculate_celsius_to_fahrenheit(c)
print("The temperature in Fahrenheit is %.1f" % f)
def input_and_convert_from_fahrenheit():
f = get_positive_number_input("Please enter the temperature in Fahrenheit: ")
c = calculate_fahrenheit_to_celsius(f)
print("The temperature in Celsius is %.1f" % c)
def main():
scale = input_scale()
if scale == "C":
input_and_convert_from_celsius()
else:
input_and_convert_from_fahrenheit()
### MAIN ###
if __name__ == '__main__':
main()
| true |
de6c5c6492335f75b402a2d5228bcf8d25511b98 | larsnohle/57 | /8/eightChallenge3.py | 921 | 4.21875 | 4 | def get_positive_integer_input(msg):
done = False
while not done:
try:
i = int(input(msg))
if i < 0:
print("Please enter a number > 0")
else:
done = True
except ValueError:
print("That was not a valid integer. Please try again!")
return i
number_of_people = get_positive_integer_input("How many people? ")
number_of_pieces_per_pizza = get_positive_integer_input("How many pieces per pizza? ")
number_of_pieces_per_person = get_positive_integer_input("How many pieces do each person want? ")
desired_number_of_slices = number_of_people * number_of_pieces_per_person
number_of_pizzas_needed = desired_number_of_slices / number_of_pieces_per_pizza
if desired_number_of_slices % number_of_pieces_per_pizza != 0:
number_of_pizzas_needed += 1
print("%d number of pizzas are needed" % number_of_pizzas_needed)
| true |
e42960bffe6815300320f8d19fb6ea226e6ac0cd | larsnohle/57 | /24/twentyfour.py~ | 634 | 4.3125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
def is_anagram(first_string, second_string):
if len(first_string) != len(second_string):
return False
HERE
def main():
print("Enter two strings and I'll tell you if they are anagrams")
first_string = input("Enter the first string:")
second_string = input("Enter the second string:")
if is_anagram(first_string, second_string):
print("\"%s\" and \"%s\" are anagrams" % (first_string, second_string))
else:
print("\"%s\" and \"%s\" are NOT anagrams" % (first_string, second_string))
### MAIN ###
if __name__ == '__main__':
main()
| true |
73c23d579194a4b068c24d0336e5fbd5e506ae3e | eric-mahasi/algorithms | /algorithms/linear_search.py | 808 | 4.1875 | 4 | """This script demonstrates the linear search algorithm in Python 3."""
AGES = [19, 20, 13, 1, 15, 7, 11, 3, 16, 10]
def display():
"""Prints all the items in the list."""
print("The ages are: ")
for i in range(len(AGES)):
print(AGES[i])
def linear_search(array, x):
"""Sequentially check each element of the list until a match is found or
until the whole list has been searched. Time complexity of O(n).
"""
for i in range(len(AGES)):
if AGES[i] == x:
print("A student aged", x, "was found.")
return 0
else:
print("A student aged", x, "was not found.")
return -1
if __name__ == '__main__':
display()
search_key = int(input("Enter an age to search for: "))
linear_search(AGES, search_key)
| true |
5fca17139a2fb3bcfb68acedd4ee3428735b32f6 | eric-mahasi/algorithms | /algorithms/bubble_sort.py | 895 | 4.4375 | 4 | """This script demonstrates the bubble sort algorithm in Python 3."""
AGES = [19, 20, 13, 1, 15, 7, 11, 3, 16, 10]
def display():
"""Prints all the items in the list."""
print("The ages are: ")
for i in range(len(AGES)):
print(AGES[i])
print("\n")
def bubble_sort(array):
"""Repeatedly step through the list, compare adjacent items and swap
them if they are in the wrong order. Time complexity of O(n^2).
Parameters
----------
array : iterable
A list of unsorted numbers
Returns
-------
array : iterable
A list of sorted numbers
"""
for i in range(len(array) - 1):
for j in range(len(array) - 1 - i):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
return array
if __name__ == '__main__':
display()
bubble_sort(AGES)
display()
| true |
c0c1dbd89be9a529c9cb3b78e8a913d66fa6a89e | MirzaRaiyan/The-Most-Occuring-Number-In-a-String-Using-Regex.py | /Occuring.py | 1,132 | 4.375 | 4 | # your code goes here# Python program to
# find the most occurring element
import re
from collections import Counter
def most_occr_element(word):
# re.findall will extract all the elements
# from the string and make a list
arr = re.findall(r'[0-9] +', word)
def most_occr_element(word):
# re.findall will extract all the elements
# from the string and make a list
arr = re.findall(r'[0-9]+', word)
# to store maxm frequency
maxm = 0
# to store maxm element of most frequency
max_elem = 0
# counter will store all the number with
# their frequencies
# c = counter((55, 2), (2, 1), (3, 1), (4, 1))
c = Counter(arr)
# Store all the keys of counter in a list in
# which first would we our required element
for x in list(c.keys()):
if c[x]>= maxm:
maxm = c[x]
max_elem = int(x)
return max_elem
# Driver program
if __name__ == "__main__":
word = 'geek55of55gee4ksabc3dr2x'
print(most_occr_element(word)) | true |
9e675b13c7217efa27655e0950b31b8525e2bbda | pereiralabs/publiclab | /python/csv_filter_lines/ex_csv.py | 903 | 4.125 | 4 | #This script reads a CSV file, then return lines based on a filter
#Setting the locale
# -*- coding: utf-8 -*
#Libraries section
import csv
#List of files you want to extract rows from
file_list = ["/home/foo/Downloads/20180514.csv"]
#List of columns you want to extract from each row
included_cols = [5,2,1]
#Now let's iterate through each file on the list
for file in file_list:
#For each file:
with open(file) as csvfile:
cdrreader = csv.reader(csvfile, delimiter=',', quotechar='"')
j = 1
#For each row in a file:
for row in cdrreader:
#Checks if condition is satisfied
if row[1] == "alô":
#If it is, then the selected columns are retrieved from the row
content = list(row[x] for x in included_cols)
print(content)
j = j + 1
| true |
a52b5830ce6e24ae87193c9d2b51fa4a97160959 | yun-lai-yun-qu/patterns | /design-patterns/python/creational/factory_method.py | 1,620 | 4.59375 | 5 | #!/usr/bin/python
# -*- coding : utf-8 -*-
"""
brief:
Factory method. Use multiple factories for
multiple products
pattern:
Factory method:
Define an interface for creating an object,
but let subclasses decide which class to
instantiate.Factory Method lets a class defer
instantiation to subclasses.
AbstractProduct < = > AbstractFactory
| | | |
ProductA ProductB FactoryA(for ProductA) FactoryB(for ProductB)
"""
# AbstractProduct
class Animal:
def __init__(self):
self.boundary = 'Animal'
self.state = self.boundary
def __str__(self):
return self.state
# Product
class Lion(Animal):
def __init__(self):
super(Lion, self).__init__();
self.state = self.boundary + ' - Lion'
def __str__(self):
return self.state
class Tiger(Animal):
def __init__(self):
super(Tiger, self).__init__();
self.state = self.boundary + ' - Tiger'
def __str__(self):
return self.state
# AbstractFactory
class Factory():
def create_animal(self):
pass
# Factory
class LionFactory(Factory):
def __init__(self):
print('Initialize LionFactory.')
def create_animal(self):
return Lion()
class TigerFactory(Factory):
def __init__(self):
print('Initialize TigerFactory.')
def create_animal(self):
return Tiger()
if __name__ == '__main__':
lion_factory = LionFactory()
tiger_factory = TigerFactory()
obj1 = lion_factory.create_animal()
obj2 = tiger_factory.create_animal()
print('obj1: {0}'.format(obj1))
print('obj2: {0}'.format(obj2)) | true |
46bde43ea1468e8b0e96c26935a4bb77baec0e7e | vkagwiria/thecodevillage | /Python Week 2/Day 1/exercise4.py | 573 | 4.21875 | 4 | # User Input: Ask the user to input the time of day in military time without a
# colon (1100 = 11:00 AM). Write a conditional statement so that it outputs the
# following:
# a. “Good Morning” if less than 1200
# b. “Good Afternoon” if between 1200 and 1700
# c. “Good Evening” if equal or above 1700
time=int(input("Please insert your local time here in millitary hours without spacing, a colon or hrs: "))
if(time<1200):
print("Good morning!")
elif(1700>time>=1200):
print("Good afternoon!")
elif(time>=1700):
print("Good evening!") | true |
bb8a0d849cd2a47df53088fee0b8c926f8654c9a | vkagwiria/thecodevillage | /Python Week 2/Day 2/exercise1.py | 464 | 4.1875 | 4 | # Ask the user for 3 numbers
# Calculate the sum of the three numbers
# if the values are equal then return thrice of their sum
# else, return the sum
num1=int(input("Please insert the first number here: "))
num2=int(input("Please insert the second number here: "))
num3=int(input("Please insert the third number here: "))
sum=num1+num2+num3
if(num1==num2==num3):
print(f"The sum of your numbers is {3*sum}.")
else:
print(f"The sum is {sum}.") | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.