blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
eed8d54cb38af8b0bb62927b9dadfdf0aa69d378 | debargham14/bcse-lab | /Sem 4/Adv OOP/python_assignments_set1/sol10.py | 444 | 4.125 | 4 | import math
def check_square (x) :
"Function to check if the number is a odd square"
y = int (math.sqrt(x))
return y * y == x
# input the list of numbers
print ("Enter list of numbers: ", end = " ")
nums = list (map (int, input().split()))
# filter out the odd numbers
odd_nums = filter (lambda x: x%2 == 1, nums)
# filter out the odd squares
odd_squares = list (filter (check_square, odd_nums))
print ("Odd squares are: ", odd_squares) | true |
669f4bbca09f2d6062be01a30fdfd0f7a0367394 | mckinleyfox/cmpt120fox | /pi.py | 487 | 4.15625 | 4 | #this program is used to approximate the value of pi
import math
def main():
print("n is the number of terms in the pi approximation.")
n = int(input("Enter a value of n: "))
approx = 0.0
signchange = 1.0
for i in range(1, n+1, 2):
approx = approx + signchange * 4.0/i # JA
signchange = -signchange
print("The aprroximate value of pi is: ", approx)
print("The difference between the approximation and real pi is: ", math.pi - approx)
main()
| true |
0b1c100231c6dbe5d970655a92f4baed0cbe1221 | firoj1705/git_Python | /V2-4.py | 1,745 | 4.3125 | 4 |
'''
1. PRINT FUNCTION IN PYTHON:
print('hello', 'welcome')
print('to', 'python', 'class')
#here by default it will take space between two values and new line between two print function
print('hello', 'welcome', end=' ')
print('to', 'python', 'class')
# here we can change end as per our requirement, by addind end=' '
print('hello', 'welcome', end=' ')
print('to', 'python', 'class', sep=',')
# here you can change sep as per our requirement by writing it. By default sep as SPACE is present.
2. KEYWORDS IN PYTHON: RESERVED WORDS
import keyword
print(keyword.kwlist) #you will get list of keyword in Python
print(len(keyword.kwlist))
print(dir(keyword.kwlist))
print(len(dir(keyword.kwlist)))
3. BASIC CONCEPTS IN PYTHON:
A. INDEXING:
+indexing: strats from 0
-indexing: starts from -1
0 1 2 3 4 5
s= 'P y t h o n'
-6-5-4-3-2-1
B. HASHING:
s='Pyhton'
print(s[0])
print(s[-6])
print(s[4])
print(s[7])
C. SLICING:
s='Python'
print(s[0:4])
print(s[3:])
print(s[:])
print(s[:-3])
print(s[5:4])
D. STRIDING/STEPPING:
s='Python'
print(s[0:5:2])
print(s[0:7:3])
print(s[5:0:-2])
print(s[::-1])
#E. MEMBERSHIP:
s='Python'
print('o' in s)
print('p' in s)
#F. CONCATENATION:
s1='Hi'
s2='Hello'
s3='303'
print(s1+s2)
print(s1+' '+s2)
print(s1+s2+s3)
print(s1+s2+100) # error will occur, As datatype should be same.
#G. REPLICATION:
s1='Firoj'
print(s1*3)
print(s1*s1) # multiplier should be integer
#H. TYPECASTING:
s='100'
print(int(s))
n=200
s1=str(n)
print(s1)
s='Hello'
print(list(s))
#I. CHARACTER TO ASCII NUMBER:
print(ord('a'))
print(ord('D'))
#J. ASCII TO CHARACTER NUMBER:
print(chr(97))
print(chr(22))
'''
| true |
c5db4886b9e216f7da109bcfdd190a2267d7258b | BMHArchives/ProjectEuler | /Problem_1/Problem_1.py | 1,128 | 4.21875 | 4 | # Multiples of 3 and 5
#---------------------
#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.
numberCount = 1000 # Use this number to find all multiples under the numberCount
total = 0 # summerize the total count of multiples under 1000
# loop between 1 and 1000
for count in range(1,numberCount):
if count != 0: # can't divide by 0
# if the % value is equal to 0 for 3 or 5, then add it to the total.
if (count % 3) == 0 or (count % 5) == 0:
total += count
#def FindAllMultiplesOfTragetNumber(TargetNumber):
# sumTotal = 0
# for a in range(1,numberCount):
# if(a % TargetNumber) == 0:
# sumTotal += a
# return sumTotal
# We're using 3, 5 and 15 here because 15 is the lowest common denominator between 3 and 5, so we will add 3 + 5 to 8 and then subtract from 15 to get the value.
#print(FindAllMultiplesOfTragetNumber(3) + FindAllMultiplesOfTragetNumber(5) - FindAllMultiplesOfTragetNumber(15))
print("Answer: {}".format(total))
| true |
c219b35384dcc23574658cfcbae883f4223f8709 | LRG84/python_assignments | /average7.5.py | 538 | 4.28125 | 4 | # calculate average set of numbers
# Write a small python program that does the following:
# Calculates the average of a set of numbers.
# Ask the user how many numbers they would like to input.
# Display each number and the average of all the numbers as the output.
def calc_average ():
counter = int (input('How many numbers would you like to input?_'))
total = 0
for a in range (0, counter):
total = total + int(input('Enter number_ '))
print('The average of your input is ', total/counter)
calc_average ()
| true |
f179a86035e710a59300a467e2f3cd4e9f8f0b15 | tweatherford/COP1000-Homework | /Weatherford_Timothy_A3_Gross_Pay.py | 1,299 | 4.34375 | 4 | ##-----------------------------------------------------------
##Programmed by: Tim Weatherford
##Assignment 3 - Calculates a payroll report
##Created 11/10/16 - v1.0
##-----------------------------------------------------------
##Declare Variables##
grossPay = 0.00
overtimeHours = 0
overtimePay = 0
regularPay = 0
#For Presentation
print("Payroll System")
print("=-"*30)
##Input Section##
empName = str(input("Enter the Employee's Full Name:"))
hoursWorked = float(input("Enter Hours Worked:"))
payRate = float(input("Enter " + empName + "'s hourly rate of pay:$"))
print("-"*60)
##Logic Functions##
if hoursWorked > 40:
overtimeHours = hoursWorked - 40
regularPay = 40 * payRate
overtimePay = (payRate*1.5) * overtimeHours
grossPay = regularPay + overtimePay
else:
regularPay = hoursWorked * payRate
grossPay = regularPay
#Output
print("=-"*30)
print("Payroll Report for " + empName)
print("=-"*30)
print("--Hours Worked--")
print("Total Hours Worked:" + str(hoursWorked))
print("Overtime Hours:" + str(overtimeHours))
print("--Pay Information--")
print("Regular Pay:$" + str(format(regularPay, "9,.2f")))
print("Overtime Pay:$" + str(format(overtimePay, "9,.2f")))
print("Total Gross Pay:$" + str(format(grossPay, "9,.2f")))
print("=-"*30)
print("End Payroll Report")
| true |
046ecafc48914b85956a7badd6b8500232a57db4 | lathika12/PythonExampleProgrammes | /areaofcircle.py | 208 | 4.28125 | 4 | #Control Statements
#Program to calculate area of a circle.
import math
r=float(input('Enter radius: '))
area=math.pi*r**2
print('Area of circle = ', area)
print('Area of circle = {:0.2f}'.format(area)) | true |
362eb0297bbb144719be1c76dc4696c141b72017 | lathika12/PythonExampleProgrammes | /sumeven.py | 225 | 4.125 | 4 | #To find sum of even numbers
import sys
#Read CL args except the pgm name
args = sys.argv[1:]
print(args)
sum=0
#find sum of even args
for a in args:
x=int(a)
if x%2==0:
sum+=x
print("Sum of evens: " , sum) | true |
99ef2163869fda04dbe4f1c23b46e56c14af7a17 | TredonA/PalindromeChecker | /PalindromeChecker.py | 1,822 | 4.25 | 4 | from math import floor
# One definition program to check if an user-inputted word
# or phrase is a palindrome. Most of the program is fairly self-explanatory.
# First, check if the word/phrase in question only contains alphabetic
# characters. Then, based on if the word has an even or odd number of letters,
# begin comparing each letter near the beginning to the corresponding word
# near the end.
def palindromeChecker():
word = input("Please enter a word: ")
if not word.isalpha():
print("Word is invalid, exiting program.")
elif len(word) % 2 == 0:
leftIndex = 0
rightIndex = len(word) - 1
while leftIndex != (len(word) / 2):
if word[leftIndex] == word[rightIndex]:
leftIndex += 1
rightIndex -= 1
else:
print("\'" + word + "\' is not a palindrome.")
leftIndex = -1
break
if leftIndex != -1:
print("\'" + word + "\' is a palindrome!")
else:
leftIndex = 0
rightIndex = len(word) - 1
while leftIndex != floor(len(word) / 2):
if word[leftIndex] == word[rightIndex]:
leftIndex += 1
rightIndex -= 1
else:
print("\'" + word + "\' is not a palindrome.")
leftIndex = -1
break
if leftIndex != -1:
print("\'" + word + "\' is a palindrome!")
answer = input("Would you like to use this program again? Type in " +\
"\'Yes\' if you would or \'No\' if not: ")
if(answer == 'Yes'):
palindromeChecker()
elif(answer == 'No'):
print("Thank you for using my program. Have a great day!")
else:
print("Invalid input. Ending program...")
return
palindromeChecker()
| true |
a113879ec0112ff4c269fb2173ed845c29a3b5e5 | ravenclaw-10/Python_basics | /lists_prog/max_occur_elem.py | 708 | 4.25 | 4 | # Element with maximum occurence in a list=[2, 3, 8, 4, 7, 9, 8, 2, 6, 5, 1, 6, 1, 2, 3, 4, 6, 9, 1, 2] .
#Python program to check if the elements of a given list are unique or not.
n=int(input("Enter the no. of element in the list(size):"))
list1=[]
count=0
max=0
print("Enter the elements of the lists:")
for i in range(0,n):
elem=input()
list1.append(elem)
max_elem=list1[0]
for i in range(0,n):
count=0
for j in range(0,n):
if list1[i]==list1[j]:
count+=1
if max<=count:
max=count
max_elem=list1[i]
if max==1:
print("The given list have unique elements")
else:
print("Maximum occered element:",max_elem) | true |
6094c69f6d4fa7a0bb59fc8da0eb7fb379832514 | Boukos/AlgorithmPractice | /recursion/rec_len.py | 328 | 4.1875 | 4 | def rec_len(L):
"""(nested list) -> int
Return the total number of non-list elements within nested list L.
For example, rec_len([1,'two',[[],[[3]]]]) == 3
"""
if not L:
return 0
elif isinstance(L[0],list):
return rec_len(L[0]) + rec_len(L[1:])
else:
return 1 + rec_len(L[1:])
print rec_len([1,'two',[[],[[3]]]]) | true |
15f68fe0b019bb466d2d7bcfbd83c6baabf2efc4 | eyeCube/Softly-Into-the-Night-OLD | /searchFiles.py | 925 | 4.125 | 4 | #search a directory's files looking for a particular string
import os
#get str and directory
print('''Welcome. This script allows you to search a directory's
readable files for a particular string.''')
while(True):
print("Current directory:\n\n", os.path.dirname(__file__), sep="")
searchdir=input("\nEnter directory to search in.\n>>")
find=input("Enter string to search for.\n>>")
#search each (readable) file in directory for string
for filename in os.listdir(searchdir):
try:
with open( os.path.join(searchdir,filename)) as file:
lineNum = 1
for line in file.readlines():
if find in line:
print(filename, "| Line", lineNum)
lineNum +=1
except Exception as err:
pass
print("End of report.\n------------------------------------------")
| true |
8097283ba70a2e1ee33c31217e4b9170a45f2dd1 | NagarajuSaripally/PythonCourse | /StatementsAndLoops/loops.py | 2,014 | 4.75 | 5 | '''
Loops: iterate through the dataypes that are iterable, iterable datatypes in python or in any language
string, lists, tuples, dictionaries
keywords to iterate through these iterables:
#for
syntax
for list_item in list_items:
print(list_item)
'''
# lists:
my_list_items = [1,2,3,4,5,6]
for my_list_item in my_list_items:
print(my_list_item)
# strings
mystring = 'Hello World!'
for eachChar in mystring:
print(eachChar)
#without assigning varibles
for variable in 'Good Morning':
print(variable)
# here instead of each character, we can print what ever the string that we want many times as string length
# so instead of putting a variable name we can use _ there
for _ in 'Hello World!':
print('cool!')
# tuples:
tup = (1,2,3)
for eachTup in tup:
print(eachTup)
# Tuple unpacking, sequence contain another tuples itself then for will upack them
my_tuples = [(1,2),(3,4),(5,6),(7,8),(9,0)]
print("length of my_tuples: {}".format(len(my_tuples)))
for item in my_tuples:
print(item)
# this is called tuple unpacking. techincally we don't need paranthesis like (a,b) it can be just like a,b
for (a,b) in my_tuples:
print(a)
print(b)
#dictionaries:
d = {'k1': 1, 'K2': 2, 'K3': 3}
for item in d:
print(item)
for value in d.values():
print(value)
'''
While loop, it continues to iterate till the condition satisfy
syntax:
while conition:
# do something
while condition:
# do something:
else:
# do something else:
'''
x = 0
while x < 5:
print(f'The current value of x is {x}')
x += 1
while x < 10:
print(f'The current value of x is {x}')
x += 1
else:
print('X is not should not greater than 10')
'''
useful keywords in loops
break, continue, pass
pass: do nothing at all
'''
p = [1,2,3]
for item in p:
#comment
pass # it just passes, in pythong for loops we need at least on statement in loop
print("Passed");
letter = 'something here'
for let in letter:
if let == 'e':
continue
print(let)
for let in letter:
if let == 'e':
break
print(let) | true |
30cf7566ca858b10b86bf6ffc72826de02134db2 | NagarajuSaripally/PythonCourse | /Methods/lambdaExpressionFiltersandMaps.py | 1,141 | 4.5 | 4 | '''
Lambda expressions are quick way of creating the anonymous functions:
'''
#function without lamda expression:
def square(num):
return num ** 2
print(square(5))
#converting it into lambda expression:
lambda num : num ** 2
#if we want we can assign this to variable like
square2 = lambda num : num ** 2. # we are not going to use this very often, cause lamda function are anonymous
print(square2(5))
print(list(map(lambda num : num **2, [1,2,3,4])))
'''
Map: map() --> map(func, *iterables) --> map object
'''
def square(num):
return num ** 2
my_nums = [1,2,3,4,5]
#if I wanna get sqaure for all the list items, we can use map function, instead of for loop, for loop is costly
#Method 1:
for item in map(square, my_nums):
print(item)
#method 2:
list(map(square, my_nums))
def splicer(mystring):
if len(mystring) % 2 == 0:
return 'EVEN'
else:
return mystring[0]
names = ['andy', 'sally', 'eve']
print(list(map(splicer, names)))
'''
Filter: iterate function that returns either true or false
'''
def check_even(num):
return num % 2 == 0
my_numbers = [1,2,3,4,5,6]
print(list(filter(check_even, my_numbers))) | true |
3f947479dbb78664c2f12fc93b926e26d16d2c34 | ankurkhetan2015/CS50-IntroToCS | /Week6/Python/mario.py | 832 | 4.15625 | 4 | from cs50 import get_int
def main():
while True:
print("Enter a positive number between 1 and 8 only.")
height = get_int("Height: ")
# checks for correct input condition
if height >= 1 and height <= 8:
break
# call the function to implement the pyramid structure
pyramid(height)
def pyramid(n):
for i in range(n):
# the loop that controls the blank spaces
for j in range(n - 1 - i):
print(" ", end="")
# the loop that controls and prints the bricks
for k in range(i + 1):
print("#", end="")
print(" ", end="")
for l in range(i + 1):
# the loop that control the second provided pyramid
print("#", end="")
# goes to the next pyramid level
print()
main()
| true |
49d3fbe78c86ab600767198110c6022be77fefe9 | SagarikaNagpal/Python-Practice | /QuesOnOops/F-9.py | 507 | 4.1875 | 4 | # : Write a function that has one character argument and displays that it’s a small letter, capital letter, a digit or a special symbol.
# 97-122 65-90 48-57 33-47
def ch(a):
if(a.isupper()):
print("upper letter")
elif(a.islower()):
print("lower letter")
elif (a.isdigit()):
print("is digit")
else:
print("Special")
a=input("ch is: ")
print(ch(a)) | true |
43462ac259650bcea0c4433ff1d27d90bbc7a09e | SagarikaNagpal/Python-Practice | /QuesOnOops/C-4.py | 321 | 4.40625 | 4 | # input a multi word string and produce a string in which first letter of each word is capitalized.
# s = input()
# for x in s[:].split():
# s = s.replace(x, x.capitalize())
# print(s)
a1 = input("word1: ")
a2 = input("word2: ")
a3 = input("word3: ")
print(a1.capitalize(),""+a2.capitalize(),""+a3.capitalize()) | true |
c56fecfa02ec9637180348dd990cf646ad00f77f | SagarikaNagpal/Python-Practice | /QuesOnOops/B-78.py | 730 | 4.375 | 4 | # Write a menu driven program which has following options:
# 1. Factorial of a number.
# 2. Prime or Not
# 3. Odd or even
# 4. Exit.
n = int(input("n: "))
menu = int(input("menu is: "))
factorial = 1
if(menu==1):
for i in range(1,n+1):
factorial= factorial*i
print("factorial of ",n,"is",factorial)
elif(menu==2):
if(n>1):
for i in range (2,n):
if(n%i)==0:
print("num ",n,"is not prime")
break
else:
print("num", n ,"is prime")
break
else:
print("num is not prime")
elif(menu==3):
if(n%2 ==0):
print(n,"is even")
else:
print(n, "is odd")
else:
print("exit!")
| true |
7b8acefe0e74bdd25c9e90f869009c2e3a24a4fc | SagarikaNagpal/Python-Practice | /QuesOnOops/C-13.py | 213 | 4.40625 | 4 | # to input two strings and print which one is lengthier.
s1 = input("String1: ")
s2 = input("String2: ")
if(len(s1)>len(s2)):
print("String -",s1,"-is greater than-", s2,"-")
else:
print(s2,"is greater") | true |
a33e791b4fc099c4e607294004888f145071e6ff | SagarikaNagpal/Python-Practice | /QuesOnOops/A22.py | 254 | 4.34375 | 4 | #Question A22: WAP to input a number. If the number is even, print its square otherwise print its cube.
import math
a=int(input("num: "))
sq = int(math.pow(a,2))
cube =int (math.pow(a,3))
if a%2==0:
print("sq of a num is ",sq)
else:
print(cube) | true |
169945565fd5ffb9c590d7a38715b3a08a8280ff | SagarikaNagpal/Python-Practice | /QuesOnOops/A-10.py | 248 | 4.34375 | 4 | # to input the number the days from the user and convert it into years, weeks and days.
days = int(input("days: "))
year = days/365
days = days%365
week = days/7
days = days%7
day = days
print("year",year)
print("week",week)
print("day",day)
| true |
f8087e5bf4e1234b7dddf18f6cd7f3612b4563c4 | ElminaIusifova/week1-ElminaIusifova | /04-Swap-Variables**/04.py | 371 | 4.15625 | 4 | # # Write a Python program to swap two variables.
#
# Python: swapping two variables
#
# Swapping two variables refers to mutually exchanging the values of the variables. Generally, this is done with the data in memory.
#
#
# ### Sample Output:
# ```
# Before swap a = 30 and b = 20
# After swaping a = 20 and b = 30
# ```
a=30
b=20
print(a,b)
c=a
a=b
b=c
print(a,b) | true |
da4cf09617b4a09e36a1afa5ebcb28ae049331fe | ElminaIusifova/week1-ElminaIusifova | /01-QA-Automation-Testing-Program/01.py | 968 | 4.28125 | 4 | ## Create a program that asks the user to test the pages and automatically tests the pages.
# 1. Ask the user to enter the domain of the site. for example `example.com`
# 2. After entering the domain, ask the user to enter a link to the 5 pages to be tested.
# 3. Then display "5 pages tested on example.com".
# 4. Add each page to a variable of type `list` called` tested_link_list`.
# 5. Finally, display `tested pages:` and print the links in the `tested_link_list` list.
siteDomain=input("Please enter domain of the site:")
link1 =input ("Please enter link 1 to be tested:")
link2 =input ("Please enter link 2 to be tested:")
link3 =input ("Please enter link 3 to be tested:")
link4 =input ("Please enter link 4 to be tested:")
link5 =input ("Please enter link 5 to be tested:")
tested_link_list = [link1, link2, link3, link4, link5]
print(siteDomain)
print(tested_link_list)
print("5 pages tested on", siteDomain)
print("tested pages: ", tested_link_list) | true |
563c9c6658a045bee7b35b510f706a1ae17039b8 | Dilan/projecteuler-net | /problem-057.py | 1,482 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# It is possible to show that the square root of two can be expressed as an infinite continued fraction.
# √ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
# By expanding this for the first four iterations, we get:
# 1 + 1/2 = 3/2 = 1.5
# 1 + 1/(2 + 1/2) = 7/5 = 1.4
# 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
# 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...
# The next three expansions are 99/70, 239/169, and 577/408,
# but the eighth expansion, 1393/985, is the first example where
# the number of digits in the numerator exceeds the number of digits in the denominator.
# In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?
import time
ti=time.time()
def sum_up(a, fraction): # a + b/c
# print a, '+', b, '/', c, ' = ', (c * a + b), '/', c
b = fraction[0]
c = fraction[1]
return ((c * a + b), c)
def plus1(fraction): # a + b/c
return sum_up(1, fraction)
def swap(fraction): # a + b/c
return (fraction[1], fraction[0])
def is_length_different(x, y):
return len(str(x)) != len(str(y))
def solution(length):
counter = 0
prev = (3, 2)
while length > 0:
# 1 + 1 / (prev)
prev = sum_up(1, swap(plus1(prev)))
if is_length_different(prev[0], prev[1]):
counter += 1
length -= 1
return counter
print 'Answer is:', solution(1000), '(time:', (time.time()-ti), ')'
| true |
3f2e1e7f00004e07ed45b0499bfcacb873d6ef92 | CodedQuen/python_begin1 | /simple_database.py | 809 | 4.34375 | 4 | # A simple database
people = {
'Alice': {
'phone': '2341',
'addr': 'Foo drive 23'
},
'Beth': {
'phone': '9102',
'addr': 'Bar street 42'
},
'Cecil': {
'phone': '3158',
'addr': 'Baz avenue 90'
}
}
# Descriptive lables for the phone number and address.
labels = {
'phone': 'phone number',
'addr': 'address'
}
name = input('Name:')
# Are we looking for a phone number or an address?
request = input('Phone number (p) or address (a)?')
# Use the correct key:
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'
# Only try to print information if the name is a valid key in our dictionary:
if name in people:
print ("%s's %s is %s." % (name, labels[key], people[name][key]))
| true |
e84ea0ce2afb28b4bb2c13a0f8b44fbbb08788bc | aayanqazi/python-preparation | /A List in a Dictionary.py | 633 | 4.25 | 4 | from collections import OrderedDict
#List Of Dictionary
pizza = {
'crust':'thick',
'toppings': ['mashrooms', 'extra cheese']
}
print("You ordered a " + pizza['crust'] + "-crust pizza " +
"with the following toppings:")
for toppings in pizza['toppings']:
print ("\t"+toppings)
#Examples 2
favourite_languages= {
'jen': ['python', 'ruby'],
'sarah': ['c'],
' edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name,languages in favourite_languages.items():
print("\n"+name.title()+"'s favourite languages are :")
for language in languages:
print ("\t"+language.title()) | true |
05a1e4c378524ef50215bd2bd4065b9ab696b80d | Glitchier/Python-Programs-Beginner | /Day 2/tip_cal.py | 397 | 4.15625 | 4 | print("Welcome to tip calculator!")
total=float(input("Enter the total bill amount : $"))
per=int(input("How much percentage of bill you want to give ? (5%, 10%, 12%, 15%) : "))
people=int(input("How many people to split the bill : "))
bill_tip=total*(per/100)
split_amount=float((bill_tip+total)/people)
final_bill=round(split_amount,2)
print(f"Each person should pay : ${final_bill}") | true |
507fdcb28060f2b139b07853c170974939267b63 | Abhinav-Rajput/CodeWars__KataSolutions | /Python Solutions/Write_ Number_in_Expanded_Form.py | 611 | 4.34375 | 4 | # Write Number in Expanded Form
# You will be given a number and you will need to return it as a string in Expanded Form. For example:
# expanded_form(12) # Should return '10 + 2'
# expanded_form(42) # Should return '40 + 2'
# expanded_form(70304) # Should return '70000 + 300 + 4'
def expanded_form(num):
strNum = str(num)
line = ''
for i in range(0,len(strNum)):
if strNum[i]=='0':
continue
line += strNum[i] + ''
for j in range(0,(len(strNum)-(i+1))):
line += '0'
line += ' + '
line = line[0:len(line)-3]
return line | true |
b8ca7993c15513e13817fa65f892ebd014ca5743 | Satona75/Python_Exercises | /Guessing_Game.py | 816 | 4.40625 | 4 | # Computer generates a random number and the user has to guess it.
# With each wrong guess the computer lets the user know if they are too low or too high
# Once the user guesses the number they win and they have the opportunity to play again
# Random Number generation
from random import randint
carry_on = "y"
while carry_on == "y":
rand_number = randint(1,10)
guess = int(input("Try and guess the number generated between 1 and 10 "))
while guess != rand_number:
if guess < rand_number:
guess = int(input("Sorry too low! Try again.. "))
else:
guess = int(input("Sorry too high! Try again.. "))
print("Congratulations!! You have guessed correctly!")
carry_on = input("Do you want to play again? (y/n).. ")
print("Thanks for playing!") | true |
c069374b1d2c822c9a71b4c7c95ac5e7e3ca945f | Satona75/Python_Exercises | /RPS-AI.py | 1,177 | 4.3125 | 4 | #This game plays Rock, Paper, Scissors against the computer.
print("Rock...")
print("Paper...")
print("Scissors...\n")
#Player is invited to choose first
player=input("Make your move: ").lower()
#Number is randomly generated between 0 and 2
import random
comp_int=random.randint(0, 2)
if comp_int == 0:
computer = "rock"
elif comp_int == 1:
computer = "paper"
else:
computer = "scissors"
print("Computer has chosen: " + computer)
if player == "rock" or player == "paper" or player == "scissors":
if computer == player:
print("It's a tie!")
elif computer == "rock":
if player == "paper":
print("You Win!")
elif player == "scissors":
print("Computer Wins!")
elif computer == "paper":
if player == "scissors":
print("You Win!")
elif player == "rock":
print("Computer Wins!")
elif computer == "scissors":
if player == "rock":
print("You Win!")
elif player == "paper":
print("Computer Wins!")
else:
print("Something has gone wrong!")
else:
print("Please enter either rock, paper or scissors")
| true |
474ae873c18391c8b7872994da02592b59be369c | Satona75/Python_Exercises | /RPS-AI-refined.py | 1,977 | 4.5 | 4 | #This game plays Rock, Paper, Scissors against the computer
computer_score = 0
player_score = 0
win_score = 2
print("Rock...")
print("Paper...")
print("Scissors...\n")
while computer_score < win_score and player_score < win_score:
print(f"Computer Score: {computer_score}, Your Score: {player_score}")
#Player is invited to choose first
player=input("Make your move: ").lower()
if player == "quit" or player == "q":
break
#Number is randomly generated between 0 and 2
import random
comp_int=random.randint(0, 2)
if comp_int == 0:
computer = "rock"
elif comp_int == 1:
computer = "paper"
else:
computer = "scissors"
print("Computer has chosen: " + computer)
if player == "rock" or player == "paper" or player == "scissors":
if computer == player:
print("It's a tie!")
elif computer == "rock":
if player == "paper":
print("You Win!")
player_score += 1
elif player == "scissors":
print("Computer Wins!")
computer_score += 1
elif computer == "paper":
if player == "scissors":
print("You Win!")
player_score += 1
elif player == "rock":
print("Computer Wins!")
computer_score += 1
elif computer == "scissors":
if player == "rock":
print("You Win!")
player_score += 1
elif player == "paper":
print("Computer Wins!")
computer_score += 1
else:
print("Something has gone wrong!")
else:
print("Please enter either rock, paper or scissors")
if computer_score > player_score:
print("Oh no! The Computer won overall!!")
elif player_score > computer_score:
print("Congratulations!! You won overall")
else:
print("It's a tie overall")
| true |
19dbab140d55e0b7f892d66f08b9dc26ba5f4095 | timurridjanovic/javascript_interpreter | /udacity_problems/8.subsets.py | 937 | 4.125 | 4 | # Bonus Practice: Subsets
# This assignment is not graded and we encourage you to experiment. Learning is
# fun!
# Write a procedure that accepts a list as an argument. The procedure should
# print out all of the subsets of that list.
#iterative solution
def listSubsets(list, subsets=[[]]):
if len(list) == 0:
return subsets
element = list.pop()
for i in xrange(len(subsets)):
subsets.append(subsets[i] + [element])
return listSubsets(list, subsets)
print listSubsets([1, 2, 3, 4, 5])
#recursive solution
def sublists(big_list, selected_so_far):
if big_list == []:
print selected_so_far
else:
current_element = big_list[0]
rest_of_big_list = big_list[1:]
sublists(rest_of_big_list, selected_so_far + [current_element])
sublists(rest_of_big_list, selected_so_far)
dinner_guests = ["LM", "ECS", "SBA"]
sublists(dinner_guests, [])
| true |
c593ca80cbc671e86d12f8d2ffaf0829fdb024ea | jacobfdunlop/TUDublin-Masters-Qualifier | /10.py | 470 | 4.1875 | 4 | usernum1 = int(input("Please enter a number: "))
usernum2 = int(input("Please enter another number: "))
usernum3 = int(input("Please enter another number: "))
if usernum1 > usernum2 and usernum1 > usernum3:
print(usernum1, " is the largest number")
elif usernum2 > usernum1 and usernum2 > usernum3:
print(usernum2, " is the largest number")
elif usernum3 > usernum1 and usernum3 > usernum2:
print(usernum3, " is the largest number")
| true |
267335a2b28e9bc77b99f0b288f5bbb6f5b4d763 | KelseySlavin/CIS104 | /Assignments/Lab1/H1P1.py | 524 | 4.15625 | 4 | first_name = input("What is your first name?: ")
last_name = input("What is your last name?: ")
age = int(input("What is your age?: "))
confidence=int(input("How confident are you in programming between 1-100%? "))
dog_age= age * 7
print("hello, " + first_name+ " " + last_name + " , nice to meet you! You might be " + str(age) + " in human years, but in dog year you are " +str(dog_age)+"." )
if confidence < 50:
print("I agree, programmers can't be trusted!")
else:
print("Writing good code takes hard work!")
| true |
87e0c4f5b7335390da9274aedad193cbdb99d5ce | Ghelpagunsan/classes | /lists.py | 2,473 | 4.15625 | 4 |
class manipulate:
def __init__(self, cars):
self.cars = cars
def add(self):
self.cars.append("Ford")
self.cars.sort()
return self.cars
def remove(self):
print("Before removing" + str(self.cars))
self.cars.remove("Honda")
return str("After removing" + str(self.cars))
def update(self, car):
car.update(["Pajero", "Mitzubishi"])
sorted(car)
return car
class show:
def __init__(self, num):
self.num = num
def getvalue(self):
return str(self.num.index(4))
def popval(self):
self.num.pop()
return self.num
def reversing(self):
self.num.reverse()
return self.num
def counting(self):
i = 0
for j in self.num:
i+=1
return i
class change:
def __init__(self,year):
self.year = year
def deletingval(self):
del self.year[3]
return self.year
def looping(self):
for x in self.year:
print(x)
def check(self):
if 2001 in self.year:
return str("Found!")
class compare:
def __init__(self, a, b):
self.a = a
self.b = b
def length(self, n):
return str("The length of the list is " + str(len(n)))
def multipleset(self, n):
return str(n)
y = n[0]
return str(y)
x = y[0]
return str(x)
z = x[1]
return str(z)
def intersections(self):
c = self.a.intersection_update(self.b)
return str(c)
def differences(self):
c = self.b.difference(self.a)
return str(c)
def symmetric(self):
c = self.a.symmetric_difference(self.b)
sorted(c)
return str(c)
def unions(self, a, b, c, d):
e = a.union(b, c, d)
return str(e)
def extends(self, x, y):
y.extend(x)
return str(y)
class order:
def __init__(self, a):
self.a = a
def whileloop(self):
i = 0
while i<5:
i+=2
print(i)
def sorting(self):
self.a.append(7)
self.a.sort()
return str(self.a)
def forloop(self):
i = 0
for i in self.a:
print(i)
i+=1
# print(add())
# print(remove())
# print(update())
# print(getvalue([1, 2, 3, 4 ,5]))
# print(popval(['a', 'b', 'c', 'd']))
# print(reversing([2, 4, 6, 8]))
# print(counting([1, 2, 3, 4, 5, 6, 7, 8]))
# print(deletingval(["Davao", "Cebu", "Manila", "Butuan"]))
# looping()
# print(check())
# print(length([1, 2, 3, 4, 5, 6]))
# print(multipleset())
# print(intersections({"a", "b", "c", "d"}, {"a", "d", "f"}))
# print(differences({"a", "b", "c", "d"}, {"a", "d", "f"}))
# print(symmetric({"a", "b", "c", "d"}, {"a", "d", "f"}))
# print(unions())
# print(extends())
# whileloop()
# print(sorting([8, 4, 5, 6]))
# forloop() | true |
3cac0579ed84aaeeb6cd68e8dba63fbfa5caefee | brentirwin/automate-the-boring-stuff | /ch7/regexStrip.py | 1,091 | 4.6875 | 5 | #! python3
# regexStrip.py
'''
Write a function that takes a string and does the same thing as the strip()
string method. If no other arguments are passed other than the string to strip,
then whitespace characters will be removed from the beginning and end of the
string. Otherwise, the characters specified in the second argument to the
function will be removed from the string.
'''
import re
def regexStrip(string, substring = None):
# No substring
if substring == None:
# Find whitespace at beginning and/or end
startSpaceRegex = re.compile(r'^\w+')
endSpaceRegex = re.compile(r'\w+$')
# Remove whitespace at beginning and/or end
string = startSpaceRegex.sub('', string)
string = endSpaceRegex.sub('', string)
return string
# Yes substring
else:
substringRegex = re.compile(substring)
return substringRegex.sub('', string)
string = input("String: ")
substring = input("Substring: ")
if substring == '':
print(regexStrip(string))
else:
print(regexStrip(string, substring))
| true |
c86a09cf6d893b85a67cf094b8fcf3e1b1e22e9b | realdavidalad/python_algorithm_test_cases | /longest_word.py | 325 | 4.375 | 4 | # this code returns longest word in a phrase or sentence
def get_longest_word(sentence):
longest_word=""
for word in str(sentence).split(" "): longest_word=word if len(word) > len(longest_word) else longest_word
return longest_word
print get_longest_word("This is the begenning of algorithm")
| true |
fa0c8bc224b3c091276166cd426bd5153edb0b73 | Lynkdev/Python-Projects | /shippingcharges.py | 508 | 4.34375 | 4 | #Jeff Masterson
#Chapter 3 #13
shipweight = int(input('Enter the weight of the product '))
if shipweight <= 2:
print('Your product is 2 pounds or less. Your cost is $1.50')
elif shipweight >= 2.1 and shipweight <= 6:
print('Your product is between 2 and 6 pounds. Your cost is $3.00')
elif shipweight >= 6.1 and shipweight <= 10:
print('Your product is between 6 and 10 pounds. Your cost is $4.00')
elif shipweight > 10:
print('Your product is over 10 pounds. Your cost is $4.75')
| true |
bec5623135d5387e7bb16e3f63d93522a2a6f69a | sbuffkin/python-toys | /stretched_search.py | 1,172 | 4.15625 | 4 | import sys
import re
#[^b]*[b][^o]*[o][^a]*[a][^t]*[t](.?)
#([^char]*[char])*(.?) <- general regex
#structure of regex, each character is [^(char)]*[(char)]
#this captures everything that isn't the character until you hit the character then moves to the next state
#you can create a "string" of these in regex to see if you can find the given string within a larger document,
#perhaps hidden somewhere
#this will find the first such occurance.
#takes in a string as input
"""
If any group is captured (even an empty one) that means we got a hit!
It might been stretched across the entire document but YAY.
"""
def regexBuild(string):
regex = ""
for char in string:
regex += "[^{0}]*[{0}]".format(char)
regex += "(.)"
p = re.compile(regex)
return p
def find(reg):
try:
filename = sys.argv[2]
except:
print('Need filename arg')
try:
f = open(filename,'r')
words = f.read()
m = reg.match(words)
print(m)
if m:
print('Found Match')
else:
print('No Match')
except:
print("File not found")
reg = regexBuild(sys.argv[1])
find(reg) | true |
b4c8c18405a914afecee69a0d7f55f57bca6aed5 | helen5haha/pylee | /game/CountandSay.py | 1,012 | 4.15625 | 4 | '''
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
Every round, when encounter a different char then stop the count of this round.
Please note that the last round, because it encounters the end of the string, so we have to force stop the round
'''
def doCountAndSay(src):
char = src[0]
num = 0
result = ""
for c in src:
if char == c:
num += 1
else:
result += (str(num) + char)
char = c
num = 1
result += (str(num) + char)
return result
def countAndSay(n):
if 0 == n:
return ""
elif 1 == n:
return "1"
result = "1"
for i in range(1,n):
result = doCountAndSay(result)
return result
countAndSay(4) | true |
5cffad649c630930892fb1bbe38c7c8b6c177b60 | Keerthanavikraman/Luminarpythonworks | /oop/polymorphism/demo.py | 1,028 | 4.28125 | 4 | ### polymorphism ...many forms
##method overloading...same method name and different number of arguments
##method overriding...same method name and same number of arguments
###method overloading example
# class Operators:
# def num(self,n1,n2):
# self.n1=n1
# self.n2=n2
# print(self.n1+self.n2)
#
# class Display(Operators):
# def num(self,n3):
# self.n3=n3
# print(self.n3)
# d=Display()
# d.num(3)
#
# class Operators:
# def num(self,n1,n2):
# self.n1=n1
# self.n2=n2
# print(self.n1+self.n2)
#
# class Display(Operators):
# def num(self,n3):
# self.n3=n3
# print(self.n3)
# d=Display()
# d.num(3,4) ## donot support
#
###method overriding example
class Person:
def printval(self,name):
self.name=name
print("inside person method",self.name)
class Child(Person):
def printval(self,class1):
self.class1=class1
print("inside child method",self.class1)
ch=Child()
ch.printval("abc")
| true |
820abce4f9d2ca4f8435512d9ad69873abb106b3 | Vani-start/python-learning | /while.py | 553 | 4.28125 | 4 | #while executes until condition becomes true
x=1
while x <= 10 :
print(x)
x=x+1
else:
print("when condition failes")
#While true:
# do something
#else:
# Condifion failed
#While / While Else loops - a while loop executes as long as an user-specified condition is evaluated as True; the "else" clause is optional
#x = 1
#while x <= 10:
# print(x)
#x += 1
#else:
# print("Out of the while loop. x is now greater than 10")
#result of the above "while" block
#1 2 3 4 5 6 7 8 9 10
#Out of the while loop. x is now greater than 10
| true |
495429537628e1b51b144775abb34d060034ac20 | Vani-start/python-learning | /convertdatatype.py | 980 | 4.125 | 4 | #Convet one datatype into otehr
int1=5
float1=5.5
int2=str(int1)
print(type(int1))
print(type(int2))
str1="78"
str2=int(str1)
print(type(str1))
print(type(str2))
str3=float(str1)
print(type(str3))
###Covert tuple to list
tup1=(1,2,3)
list1=list(tup1)
print(list1)
print(tup1)
set1=set(list1)
print(set1)
####bin, dec,hex
number=10
num_to_bin=bin(number)
print(num_to_bin)
num_to_hex=hex(number)
print(num_to_hex)
num_from_bin=int(num_to_bin,2)
print(num_from_bin)
num_from_hex=int(num_to_hex,16)
print(num_from_hex)
#Conversions between data types
#str() #converting to a string
#int() #converting to an integer
#float() #converting to a float
#list() #converting to a list
#tuple() #converting to a tuple
#set() #converting to a set
#bin() #converting to a binary representation
#hex() #converting to a hexadecimal representation
#int(variable, 2) #converting from binary back to decimal
#int(variable, 16) #converting from hexadecimal back to decimal
| true |
876792dac3431422495d8b71eb97b5faf662f201 | risabhmishra/parking_management_system | /Models/Vehicle.py | 931 | 4.34375 | 4 | class Vehicle:
"""
Vehicle Class acts as a parent base class for all types of vehicles, for instance in our case it is Car Class.
It contains a constructor method to set the registration number of the vehicle to registration_number attribute
of the class and a get method to return the value stored in registration_number attribute of the class.
"""
def __init__(self, registration_number):
"""
This constructor method is used to store the registration number of the vehicle to registration_number attribute
of the class.
:param registration_number: str
"""
self.registration_number = registration_number
def get_registration_number(self):
"""
This method is used to return the value stored in the registration_number attribute of the class.
:return: registration_number:str
"""
return self.registration_number
| true |
27e8ec33ff0f380bf54428032445ab8905d3164f | detjensrobert/cs325-group-projects | /ga1/assignment1.py | 2,273 | 4.40625 | 4 | """
This file contains the template for Assignment1. You should fill the
function <majority_party_size>. The function, recieves two inputs:
(1) n: the number of delegates in the room, and
(2) same_party(int, int): a function that can be used to check if two members are
in the same party.
Your algorithm in the end should return the size of the largest party, assuming
it is larger than n/2.
I will use <python3> to run this code.
"""
def majority_party_size(n, same_party):
"""
n (int): number of people in the room.
same_party (func(int, int)): This function determines if two delegates
belong to the same party. same_party(i,j) is True if i, j belong to
the same party (in particular, if i = j), False, otherwise.
return: The number of delegates in the majority party. You can assume
more than half of the delegates belong to the same party.
"""
return majority_party_size_helper([i for i in range(n)], same_party)[1]
def majority_party_size_helper(delegates, same_party):
# PARAM: delegates[] = indexes of delegates to check
# RETURN: tuple(index of majority party candidate, size of majority party)
if len(delegates) >= 2:
# recursively check each half of our delegate list to find the majority party of each half
mid = int(len(delegates) / 2)
(left_delegate, _) = majority_party_size_helper(delegates[:mid], same_party)
(right_delegate, _) = majority_party_size_helper(delegates[mid:], same_party)
# Count up the size of each half's majority party for the whole chunk
left_party_size = 0
right_party_size = 0
for i in delegates:
if same_party(left_delegate, i):
left_party_size += 1
if same_party(left_delegate, i):
right_party_size += 1
# who's bigger?
if left_party_size > right_party_size:
maj_delegate = left_delegate
maj_size = left_party_size
else:
maj_delegate = right_delegate
maj_size = right_party_size
return (maj_delegate, maj_size)
else: # Base case: single delegate -- only one possible majority here!
return (delegates[0], 1)
| true |
58e59338d5d1fc79374d0ce438582c4d73185949 | Neethu-Mohan/python-project | /projects/create_dictionary.py | 1,091 | 4.15625 | 4 | """
This program receives two lists of different lengths. The first contains keys, and the second contains values.
And the program creates a dictionary from these keys and values. If the key did not have enough values, the dictionary will have the value None. If
Values that did not have enough keys will be ignored.
"""
from itertools import chain, repeat
keys = []
def get_list():
keys = [item for item in input("Enter the first list items : ").split()]
values = [item for item in input("Enter the second list items : ").split()]
dictionary_ouput = create_dictionary(keys, values)
print(dictionary_ouput)
def create_dictionary(keys, values):
difference = compare_length(keys, values)
if difference <= 0:
dic_value = dict(zip(keys, values))
return dic_value
elif difference > 0:
dic_value = dict(zip(keys, chain(values, repeat(None))))
return dic_value
def compare_length(keys, values):
difference = check_length(keys) - check_length(values)
return difference
def check_length(item):
return len(item)
| true |
488675687a2660c01e9fd7d707bdf212f94abb62 | NM20XX/Python-Data-Visualization | /Simple_line_graph_squares.py | 576 | 4.34375 | 4 | #Plotting a simple line graph
#Python 3.7.0
#matplotlib is a tool, mathematical plotting library
#pyplot is a module
#pip install matplotlib
import matplotlib.pyplot as plt
input_values = [1,2,3,4,5]
squares = [1,4,9,16,25]
plt.plot(input_values, squares, linewidth = 5) #linewidth controls the thickness of the line that plot() generates.
#Title and label axes
plt.title("Square Numbers", fontsize = 24)
plt.xlabel("Value", fontsize = 14)
plt.ylabel("Square of value", fontsize = 14)
#Set size of tick labels
plt.tick_params(axis ='both', labelsize = 14)
plt.show()
| true |
9ed2d0f9f15fde3e123ea8f30c2ffa714db1460a | tristaaa/learnpy | /getRemainingBalance.py | 819 | 4.125 | 4 | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
balance = 42
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
def getMonthlyBalance(balance, annualInterestRate, monthlyPaymentRate):
'''
return: the remaining balance at the end of the month
'''
minimalPayment = balance * monthlyPaymentRate
monthlyUnpaidBalance = balance - minimalPayment
interest = monthlyUnpaidBalance * annualInterestRate / 12
return monthlyUnpaidBalance + interest
def getFinalBalance(balance, annualInterestRate, monthlyPaymentRate):
for m in range(12):
balance = getMonthlyBalance(
balance, annualInterestRate, monthlyPaymentRate)
remainingBalance = round(balance, 2)
print('Remaining balance:', remainingBalance)
getFinalBalance(balance, annualInterestRate, monthlyPaymentRate)
| true |
6df041ded350202d4e74f98a104fd3470e21683d | tristaaa/learnpy | /bisectionSearch_3.py | 910 | 4.46875 | 4 | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
# use bisection search to guess the secret number
# the user thinks of an integer [0,100).
# The computer makes guesses, and you give it input
# - is its guess too high or too low?
# Using bisection search, the computer will guess the user's secret number
low = 0
high = 100
guess = (low+high)//2
print('Please think of a number between 0 and 100!')
while True:
print('Is your secret number '+str(guess)+'?')
is_secret_num = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
if is_secret_num =='l':
low = guess
elif is_secret_num =='h':
high = guess
elif is_secret_num =='c':
break
else:
print('Sorry, I did not understand your input.')
guess = (low+high)//2
print('Game over. Your secret number was:',guess) | true |
537ddca25824fd995727cbb026fecefa5bdcaf8b | wkomari/Lab_Python_04 | /data_structures.py | 1,383 | 4.40625 | 4 | #lab 04
# example 1a
groceries = ['bananas','strawberries','apples','bread']
groceries.append('champagne')
print groceries
# example1b
groceries = ['bananas','strawberries','apples','bread']
groceries.append('champagne') # add champagne to the list of groceries
groceries.remove('bread') # remove bread from the list of groceries
print groceries
# example 1c
groceries = ['bananas','strawberries','apples','bread']
groceries.append('champagne') # add champagne to the list of groceries
groceries.remove('bread') # remove bread from the list of groceries
groceries.sort()
print groceries
# example 2a
print 'Dictionary would be used as the data type'
dict = {'Apples':'7.3','Bananas':'5.5','Bread':'1.0','Carrot':'10.0','Champagne':'20.90','Strawberries':'32.6'}
print 'Apple is', dict['Apples']
dict['Strawberries'] = 63.43
print 'The price of Strawberries in winter now is', dict['Strawberries'] # updated strawberries price
dict['chicken'] = 6.5
print dict # prints all entries in the dictionary
print 'Hehe customers we have chicken now in stock at', dict['chicken']
#example3
in_stock = ('Apples','Bananas','Bread','Carrot','Champagne','Strawberries')
always_in_stock = ('Apples','Bananas','Bread','Carrot','Champagne','Strawberries')
print 'Come to shoprite! We always sell:\n', always_in_stock[0:6]
for i in always_in_stock:
print i
#example4
| true |
5f168aeaf97ebb2100fafcbaef59928522f86d70 | sha-naya/Programming_exercises | /reverse_string_or_sentence.py | 484 | 4.15625 | 4 | test_string_sentence = 'how the **** do you reverse a string, innit?'
def string_reverser(string):
reversed_string = string[::-1]
return reversed_string
def sentence_reverser(sentence):
words_list = sentence.split()
reversed_list = words_list[::-1]
reversed_sentence = " ".join(reversed_list)
return reversed_sentence
example_1 = string_reverser(test_string_sentence)
print(example_1)
example_2 = sentence_reverser(test_string_sentence)
print(example_2)
| true |
18fae6895c6be30f0a3a87531a2fafe965a3c89f | pkdoshinji/miscellaneous-algorithms | /baser.py | 1,873 | 4.15625 | 4 | #!/usr/bin/env python3
'''
A module for converting a (positive) decimal number to its (base N) equivalent, where
extensions to bases eleven and greater are represented with the capital letters
of the Roman alphabet in the obvious way, i.e., A=10, B=11, C=12, etc. (Compare
the usual notation for the hexadecimal numbers.) The decimal number and the
base (N) are entered in the command line: baser.py <base> <decimal number to convert>
'''
import sys
#Character set for representing digits. For (base N) the set is characters[:N]
characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'
#Usage guidelines
def usage():
print('[**]Usage: baser.py <base> <number to convert>')
print(f' <base> must be less than or equal to {len(characters)}')
print(f' <number> must be a nonnegative integer')
#Get the most significant digit (MSD) of the decimal number in (base N)
def getMSD(base, number):
MSD = 1
while True:
if (base ** MSD) > number:
return MSD
MSD += 1
#Convert the decimal number to (base N)
def convert(MSD, base, number):
result = ''
for i in range(MSD - 1, -1, -1):
value = number // (base ** i)
result += chars[value]
number = number % (base ** i)
return result
def main():
#Input sanitization
try:
base = int(sys.argv[1])
except:
usage()
exit()
try:
number = int(sys.argv[2])
except:
usage()
exit()
if base > len(characters):
usage()
exit(0)
if number == 0:
print(0)
exit(0)
if number < 0:
usage()
exit(0)
global chars
chars = characters[:base] #Get the (base N) character set
print(convert(getMSD(base, number), base, number)) #Convert and output
if __name__ == '__main__':
main()
| true |
358c68067412029677c59023d1f4b35af58c54ff | yuniktmr/String-Manipulation-Basic | /stringOperations_ytamraka.py | 1,473 | 4.34375 | 4 | #CSCI 450 Section 1
#Student Name: Yunik Tamrakar
#Student ID: 10602304
#Homework #7
#Program that uses oython function to perform word count, frequency and string replacement operation
#In keeping with the Honor Code of UM, I have neither given nor received assistance
#from anyone other than the instructor.
#----------------------
#--------------------
#method to get number of words in string
def wordCount(a):
b = a.split(" ")
count = 0
for word in b:
count = count + 1
print("The number of words is {}".format(count))
#method to get the most repititive word
def mostFrequentWord(b):
c = b.split(" ")
dict = {}
#mapping word with its wordcount.
for word in c:
dict[word] = c.count(word)
max = 0
for word in dict:
if (dict[word] > max):
max = dict[word]
for word in dict:
if(dict[word] == max):
print('The word with max occurence is', word)
#method to replace the words in the string
def replaceWord(a, d ,c):
words = a.split(" ")
wordCheck = False
for word in words:
if d == word:
wordCheck = True
if wordCheck:
print("\nOriginal is ",a)
print("The new string after replacement is ",a.replace(d,c))
else:
print("Word not found")
#main method to call the functions
a= input("Enter a word\n")
wordCount(a)
mostFrequentWord(a)
b = input("\nEnter a word you want to be replaced. Separate them with a space\n")
c = b.split(" ")
#invoke the replaceWord method
replaceWord(a, c[0], c[1])
| true |
bbcdeafd4fdc92f756f93a1a4f990418d295c643 | ijoshi90/Python | /Python/variables_examples.py | 602 | 4.375 | 4 | """
Author : Akshay Joshi
GitHub : https://github.com/ijoshi90
Created on 26-Sep-19 at 19:24
"""
class Car:
# Class variable
wheels = 2
def __init__(self):
# Instance Variable
self.mileage = 20
self.company = "BMW"
car1 = Car()
car2 = Car()
print ("Wheels : {}".format(Car.wheels))
# Override the value of wheels with 4
Car.wheels = 4
print (car1.company, car1.mileage, car1.wheels)
print (car2.company, car2.mileage, car2.wheels)
# Changing values of Car 2
car2.company = "Mini"
car2.mileage = "25"
car2.wheels = "3"
print (car2.company, car2.mileage, car2.wheels) | true |
e41d966e65b740a9e95368d7e5b9286fe587f2cb | donwb/whirlwind-python | /Generators.py | 537 | 4.28125 | 4 | print("List")
# List - collection of values
L = [n ** 2 for n in range(12)]
for val in L:
print(val, end=' ')
print("\n")
print("Generator...")
# Generator - recipie for creating a list of values
G = (n ** 2 for n in range(12))
#generator created here, not up there...
for val in G:
print(val, end=' ')
# Generators can only be used once,
# but they can be stopped/started
GG = (n**2 for n in range(12))
for n in GG:
print(n, end=' ')
if n > 30: break
print("\ndoing something in between")
for n in GG:
print(n, end=' ')
| true |
d3dd23e8f5e164ca4378e7817f983fca0bf89e1b | DylanGuidry/PythonFunctions | /dictionaries.py | 1,098 | 4.375 | 4 | #Dictionaries are defined with {}
friend = {
#They have keys/ values pairs
"name": "Alan Turing",
"Cell": "1234567",
"birthday": "Sep. 5th"
}
#Empty dictionary
nothing = {}
#Values can be anything
suoerhero = {
"name": "Tony Stark",
"Number": 40,
"Avenger": True,
"Gear": [
"fast car",
"money",
"iron suit",
],
"car": {
"make": "audi",
"model": "R8"
},
"weakness": "his ego"
}
#Get values with key names:
print(suoerhero)
#Get method also works, and can have a "fallback"
print(suoerhero.get("name", "Uknown"))
#Access to all values aof all keys:
print(suoerhero.values())
#Searching for a keys in a dictionary:
if "weakness" in suoerhero:
print("bad guys might win")
else:
print("bad guys go home")
#Updating values:
suoerhero["avenger"] == "fartbutt"
print(suoerhero)
#Deleting from a dictionary:
del suoerhero["gear"]
#Accessing data:
print(suoerhero["name"])
for item in suoerhero["Gear"]:
print(item)
# for key, value in suoerhero:items():
# print(f"Suoerhero's {key} is")
# print(value) | true |
109aebf88bfac4cd1e7e097b085d3a3f909923fa | helinamesfin/guessing-game | /random game.py | 454 | 4.15625 | 4 | import random
number = random.randrange(1,11)
str_guess= input("What number do you think it is?")
guess= int(str_guess)
while guess != number:
if guess > number:
print("Not quite. Guess lower.")
elif guess < number:
print("Not quite. Guess higher.")
str_guess= input("What number do you think it is?")
guess= int(str_guess)
if guess==number:
print("Great job! You guessed right.")
| true |
11c57367b1f26d98d8ccab7ab1fc44fedfe7ca42 | IceMints/Python | /blackrock_ctf_07/Fishing.py | 1,503 | 4.25 | 4 | # Python3 Program to find
# best buying and selling days
# This function finds the buy sell
# schedule for maximum profit
def max_profit(price, fee):
profit = 0
n = len(price)
# Prices must be given for at least two days
if (n == 1):
return
# Traverse through given price array
i = 0
while (i < (n - 1)):
# Find Local Minima
# Note that the limit is (n-2) as we are
# comparing present element to the next element
while ((i < (n - 1)) and ((price[i + 1])<= price[i])):
i += 1
# If we reached the end, break
# as no further solution possible
if (i == n - 1):
break
# Store the index of minima
buy = i
buying = price[buy]
i += 1
# Find Local Maxima
# Note that the limit is (n-1) as we are
# comparing to previous element
while ((i < n) and (price[i] >= price[i - 1])):
i += 1
while (i < n) and (buying + fee >= price[i - 1]):
i += 1
# Store the index of maxima
sell = i - 1
selling = price[sell]
print("Buy on day: ",buy,"\t",
"Sell on day: ",sell)
print(buying, selling)
profit += (selling - fee - buying)
print(profit)
# sample test case
# Stock prices on consecutive days
price = [1, 3, 2, 8, 4, 9]
n = len(price)
# Fucntion call
max_profit(price, 2)
| true |
a1514c507909bd3d00953f7a8c7dd09223779ead | VEGANATO/Organizing-Sales-Data-Code-Academy | /script.py | 651 | 4.53125 | 5 | # Len's Slice: I work at Len’s Slice, a new pizza joint in the neighborhood. I am going to use my knowledge of Python lists to organize some of the sales data.
print("Sales Data")
# To keep track of the kinds of pizzas sold, a list is created called toppings that holds different toppings.
toppings = ["pepperoni", "pineapple", "cheese", "sausage", "olives", "anchovies", "mushrooms"]
# A list called "prices" is created to track how much each pizza costs.
prices = [2, 6, 1, 3, 2, 7, 2]
len(toppings)
num_pizzas = len(toppings)
print("We sell " + str(num_pizzas) + " different kinds of pizza!")
pizzas = list(zip(prices, toppings))
print(pizzas)
| true |
7df64998ce5965ba3fabcbd54cedc6751ca413c8 | gustavovalverde/intro-programming-nano | /Python/Work Session 5/Loop 4.py | 2,343 | 4.46875 | 4 | # We now would like to summarize this data and make it more visually
# appealing.
# We want to go through count_list and print a table that shows
# the number and its corresponding count.
# The output should look like this neatly formatted table:
"""
number | occurrence
0 | 1
1 | 2
2 | 3
3 | 2
4 | 2
5 | 1
6 | 1
7 | 2
8 | 3
9 | 1
10 | 2
"""
# Here is our code we have written so far:
import random
# Create random list of integers using while loop --------------------
random_list = []
list_length = 20
while len(random_list) < list_length:
random_list.append(random.randint(0, 10))
# Aggregate the data -------------------------------------------------
count_list = [0] * 11
index = 0
while index < len(random_list):
number = random_list[index]
count_list[number] += 1
index += 1
# Write code here to summarize count_list and print a neatly formatted
# table that looks like this:
"""
number | occurrence
0 | 1
1 | 2
2 | 3
3 | 2
4 | 2
5 | 1
6 | 1
7 | 2
8 | 3
9 | 1
10 | 2
"""
print count_list
print sum(count_list)
# Hint: To print 10 blank spaces in a row, we can multiply a string
# by a number "n" to print this string n number of times:
print "number | ocurrence"
index = 0
while index <= 10:
if index < 10:
print " " * 5 + str(index) + " | " + str(count_list[index] * "*")
else:
print " " * 4 + str(index) + " | " + str(count_list[index] * "*")
index += 1
print ""
print "-----------------"
print "Another approach"
print "-----------------"
print ""
print "number | occurrence"
index = 0
num_len = len("number")
while index < len(count_list):
num_spaces = num_len - len(str(index))
print " " * num_spaces + str(index) + " | " + str(count_list[index])
index = index + 1
# BONUS!
# From your summarize code you just wrote, can you make the table even
# more visual by replacing the count with a string of asterisks that
# represent the count of a number. The table should look like:
"""
number | occurrence
0 | *
1 | **
2 | ***
3 | **
4 | **
5 | *
6 | *
7 | **
8 | ***
9 | *
10 | **
"""
# Congratulations! You just created a distribution table of a list
# of numbers! This is also known as a histogram
| true |
a9bed93ff1f778a466167b06cbc8afa902dabf9e | gustavovalverde/intro-programming-nano | /Python/Problem Solving/Calc_age_on_date.py | 2,173 | 4.21875 | 4 | # Given your birthday and the current date, calculate your age
# in days. Compensate for leap days. Assume that the birthday
# and current date are correct dates (and no time travel).
# Simply put, if you were born 1 Jan 2012 and todays date is
# 2 Jan 2012 you are 1 day old.
daysOfMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def isLeapYear(year):
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
elif year % 400 != 0:
return False
else:
return True
def isDateValid(y1, m1, d1, y2, m2, d2):
if y1 < y2:
return True
elif y1 == y2:
if m1 < m2:
return True
elif m1 == m2:
if d1 <= d2:
return True
else:
print "Please enter a valid initial date"
return False
else:
print "Please enter a valid initial date"
return False
def daysinYear(y1, y2):
days = 0
if y1 < y2:
for y in range(y1, y2):
if isLeapYear(y) is True:
days += 366
else:
days += 365
return days
def daysInMonth(m1, d1, m2, d2):
birthDate = sum(daysOfMonths[0: m1 - 1]) + d1
currentDate = sum(daysOfMonths[0: m2 - 1]) + d2
currentDays = currentDate - birthDate
return currentDays
def daysBetweenDates(y1, m1, d1, y2, m2, d2):
finalDays = daysinYear(y1, y2) + daysInMonth(m1, d1, m2, d2)
if ((isLeapYear(y1) is True) and (m1 >= 3)) or (
(isLeapYear(y2) is True) and (m2 >= 3)):
finalDays += 1
print "You are " + str(finalDays) + " days old"
return finalDays
def test():
test_cases = [((2012, 1, 1, 2012, 2, 28), 58),
((2012, 1, 1, 2012, 3, 1), 60),
((2011, 6, 30, 2012, 6, 30), 366),
((2011, 1, 1, 2012, 8, 8), 585),
((1900, 1, 1, 1999, 12, 31), 36523)]
for (args, answer) in test_cases:
result = daysBetweenDates(*args)
if result != answer:
print "Test with data:", args, "failed"
print result
else:
print "Test case passed!"
test()
| true |
1018f2da0c71c59aa9491bf5ab74ab734accb09d | adirickyk/course-python | /try_catch.py | 302 | 4.3125 | 4 | #create new exception
try:
Value = int(input("Type a number between 1 and 10 : "))
except ValueError:
print("You must type a number between 1 and 10")
else:
if(Value > 0) and (Value <= 10):
print("You typed value : ", Value)
else:
print("The value type is incorrect !")
| true |
e8368e5d17e8682b1f8d59ab9466995584747627 | castacu0/codewars_db | /15_7kyu_Jaden Casing Strings.py | 1,069 | 4.21875 | 4 | from string import capwords
"""
Jaden Smith, the son of Will Smith, is the star of films such as The Karate Kid (2010) and After Earth (2013). Jaden is also known for some of his philosophy that he delivers via Twitter. When writing on Twitter, he is known for almost always capitalizing every word. For simplicity, you'll have to capitalize each word, check out how contractions are expected to be in the example below.
Your task is to convert strings to how they would be written by Jaden Smith. The strings are actual quotes from Jaden Smith, but they are not capitalized in the same way he originally typed them.
Example:
Not Jaden-Cased: "How can mirrors be real if our eyes aren't real"
def to_jaden_case(string):
# ...
"""
def to_jaden_case(string):
return print(" ".join(i.capitalize() for i in string.split()))
# split() makes a list. any whitespace is by default
# join makes a str again and takes an iterable
# Best practices
# from string import capwords
def to_jaden_case(string):
return string.capwords(string)
to_jaden_case("kou liu d'wf")
| true |
9940f02410122ddc6d0a9394479576fa0fb1a4fb | marizmelo/udacity | /CS262/lesson3/mapdef.py | 267 | 4.125 | 4 | def mysquare(x): return x * x
print map( mysquare, [1, 2, 3, 4, 5])
print map( lambda(x): x * x, [1, 2, 3, 4, 5]) # this use of lambda is sometimes called anonymous function
print [len(x) for x in ["hello", "my", "friends"]]
print [x * x for x in [1, 2, 3, 4, 5]] | true |
1451fa9c04e5ce8636d023001c663fb6a988b0bf | wajishagul/wajiba | /Task4.py | 884 | 4.375 | 4 | print("*****Task 4- Variables and Datatype*****")
print("Excercise")
print("1. Create three variables (a,b,c) to same value of any integer & do the following")
a=b=c=100
print("i.Divide a by 10")
print(a,"/",10,"=",a/10)
print("ii.Multiply b by 50")
print(b,"*",50,"=",b*50)
print("iii.Add c by 60")
print(c,"+",50,"=",b+50)
print("2.Create a String variable of 5 characters and replace the 3rd character with G")
str="ABCDE"
print("Length of the string is:",len(str))
s1="C"
s2="G"
print("new string after replacement:",str.replace(s1,s2))
print("3.Create two values (a,b) of int,float data type & convert the vise versa")
a,b=200,55.5
print("a=",a,"b=",b)
a=float(a)
b=int(b)
print("value of a and b after type conversion:")
print("a=",a,"b=",b)
print("data type of a after conversion:",type(a))
print("data type of b after conversion:",type(b))
print("-----Task 4 Completed-----")
| true |
1b139816100f6157c1492c44eb552c096fb8b32f | verma-rahul/CodingPractice | /Medium/InOrderTraversalWithoutRecursion.py | 2,064 | 4.25 | 4 | # Q : Given a Tree, print it in order without Traversal
# Example: 1
# / \
# 2 3 => 4 2 5 1 3
# / \
# 4 5
import sys
import random
# To set static Seed
random.seed(1)
class Node():
"""
Node Struct
"""
def __init__(self,val=None):
self.val=val
self.right=None
self.left=None
class BinaryTree():
def __init__(self,root=None):
self.root=root
def make_random_balnaced_tree(self,size):
"""
Constructs a random Balanced Tree &
prints as an Array
Ex: [1,2,3,4,5] => 1
/ \
2 3
/ \
4 5
"""
val=random.randint(0, 100)
self.root=Node(val)
stack=[self.root];size=size-1;arr_tree=[val]
while size>0:
node=stack.pop(0)
val=random.randint(0,100)
left=Node(val)
arr_tree.append(val)
node.left=left
stack.append(left)
size=size-1
if size>0:
val=random.randint(0,100)
right=Node(val)
node.right=right
arr_tree.append(val)
stack.append(right)
size=size-1
print("Balanced Tree as Array: ", arr_tree)
def print_inorder(self):
"""
Prints the Tree Inorder
"""
stack=[self.root]
node=self.root
print("Inorder Traversal of Tree: ")
while len(stack)>0:
if node!=None and node.left!=None:
stack.append(node.left)
node=node.left
else:
poped=stack.pop()
print(poped.val)
node=poped.right
if node!=None:
stack.append(node)
def main(args):
tree=BinaryTree()
tree.make_random_balnaced_tree(10)
tree.print_inorder()
if __name__=='__main__':
main(sys.argv[1:])
| true |
81eba7d41e0f8962458519751b02c21dc52c88a5 | Sreenidhi220/IOT_Class | /CE8OOPndPOP.py | 1,466 | 4.46875 | 4 | #Aum Amriteshwaryai Namah
#Class Exercise no. 8: OOP and POP illustration
# Suppose we want to model a bank account with support for 'deposit' and 'withdraw' operations.
# One way to do that is by Procedural Programming
# balance = 0
# def deposit(amount):
# global balance
# balance += amount
# return balance
# def withdraw(amount):
# global balance
# balance -= amount
# return balance
#The above example is good enough only if we want to have just a single account.
#Things start getting complicated if we want to model multiple accounts.
# Have multiple accounts as list or dictionary or separate variables?
def deposit(name, amount):
Accounts[name] += amount
return Accounts[name]
def withdraw(name, amount):
Accounts[name] -= amount
return balance
Accounts = {}
Accounts["Arya"] = 2000
Accounts["Swathi"] = 2000
Accounts["Urmila"] = 2000
print("Arya's balance is %d" % deposit("Arya", 200))
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
Arya = BankAccount()
Swathi = BankAccount()
Urmila = BankAccount()
Swathi.deposit(400)
Urmila.deposit(700)
print(Urmila.balance)
#Referece :https://anandology.com/python-practice-book/object_oriented_programming.html
| true |
c79f3df4eb01631e73363cd6e5e6546e15380b30 | edran/ProjectsForTeaching | /Classic Algorithms/sorting.py | 2,073 | 4.28125 | 4 | """
Implement two types of sorting algorithms: Merge sort
and bubble sort.
"""
def mergeMS(left, right):
"""
Merge two sorted lists in a sorted list
"""
llen = len(left)
rlen = len(right)
sumlist = []
while left != [] and right != []:
lstack = left[0]
while right != []:
rstack = right[0]
if lstack < rstack:
sumlist.append(lstack)
left.pop(0)
break
else:
sumlist.append(rstack)
right.pop(0)
if left == []:
sumlist += right
else:
sumlist += left
return sumlist
def mergeSort(l):
"""
Divide the unsorted list into n sublists, each containing 1
element (a list of 1 element is considered sorted). Repeatedly
merge sublists to produce new sorted sublists until there is only
1 sublist remaining. This will be the sorted list.
"""
# I actually implemented without reading any of the formal algorithms,
# so I'm not entirely sure I did a good job. I have to read up and compare
# my solution with a standard one.
if len(l) == 1:
return l
split = len(l) / 2
a = mergeMS(mergeSort(l[:split]), mergeSort(l[split:]))
return a
def bubbleSort(l):
"""
simple sorting algorithm that works by repeatedly stepping through
the list to be sorted, comparing each pair of adjacent items and
swapping them if they are in the wrong order
"""
n = list(l)
swapped = True
k = len(n) - 1
while swapped:
swapped = False
i = k
while i > 0:
u = n[i]
d = n[i - 1]
if u < d:
n[i] = d
n[i -1] = u
swapped = True
i -= 1
return n
def main():
t = raw_input("List of numbers> ")
t = eval("[" + t + "]")
r = mergeSort(t)
b = bubbleSort(t)
print "MergeSort: ", r
print "BubbleSort: ", b
if __name__ == "__main__":
main()
| true |
4b41489f518c4cbca1923440c3416cdfef345f88 | edran/ProjectsForTeaching | /Numbers/factprime.py | 657 | 4.28125 | 4 | """
Have the user enter a number and find all Prime Factors (if there
are any) and display them.
"""
import math
import sys
def isPrime(n):
for i in range(2,int(math.sqrt(n)) + 1): # premature optimization? AH!
if n % i == 0:
return False
return True
def primeFacts(n):
l = []
for i in range(1,int(math.ceil(n/2))+1):
if n % i == 0 and isPrime(i):
l.append(i)
if n not in l and isPrime(n):
l.append(n) # for prime numbers
return l
def main():
i = int(raw_input("Factors of which number? "))
print primeFacts(i)
if __name__ == "__main__":
while 1:
main()
| true |
1ab87bc5c2863c90dea96185241b0869f2259f30 | sonusbeat/intro_algorithms | /Recursion/group_exercise2.py | 489 | 4.375 | 4 | """ Group Exercise Triple steps """
def triple_steps(n):
"""
A child is running up a staircase with n steps and can hop
either 1 step, 2 steps, or 3 steps at a time.
Count how many possible ways the child can run up the stairs.
:param n: the number of stairs
:return: The number of possible ways the child can run up the stairs.
"""
if n <= 2:
return n
return triple_steps(n-1) + triple_steps(n-2) + triple_steps(n-3)
print(triple_steps(3)) | true |
ec45e6109ddd2f2f3b9984404f015b828f0ca4f1 | sonusbeat/intro_algorithms | /SearchingAlgorithms/2.binary_search.py | 1,037 | 4.28125 | 4 | """
Binary Search
- how you look up a word in a dictionary or a contact in phone book.
* Items have to be sorted!
"""
alist = [
"Australia", "Brazil", "Canada", "Denmark",
"Ecuador", "France", "Germany", "Honduras",
"Iran", "Japan", "Korea", "Latvia",
"Mexico", "Netherlands", "Oman", "Philippines",
"Qatar", "Russia", "Spain", "Turkey",
"Uruguay", "Vietnam", "Wales", "Xochimilco", "Yemen", "Zambia"
]
def binary_search(collection, target):
start = 0
end = len(collection) - 1
steps = 0
while start <= end:
mid = (start + end) // 2
steps += 1
if collection[mid] == target:
steps_message = "s" if steps > 1 else ""
return F"\"{collection[mid]}\" is at position {str(mid)} and it took {str(steps)} step{steps_message}"
elif collection[mid] < target:
start = mid + 1
else:
end = mid - 1
return F"Your country \"{target}\" is not on the list!"
print(binary_search(alist, input("What's your country? ")))
| true |
4bb0736d12da8757a76839f242d902fb08afc461 | vamsikrishna6668/python | /class2.py | 559 | 4.3125 | 4 | # w.a.p on class example by static method and static variables and take a local variable also print without a reference variable?
class student:
std_idno=101
std_name="ismail"
@staticmethod
def assign(b,c):
a=1000
print("The Local variable value:",a)
print("The static variable name:",student.std_name)
print("The static variable idno: ",student.std_idno)
print("Iam a static method")
print(b*c)
#call
student.assign(50,60)
print(student().std_idno)
print(student().std_name)
| true |
3a5908b10e1eb651085ac4dee75e344b8bb9cc83 | singzinc/PythonTut | /basic/tut2_string.py | 785 | 4.3125 | 4 |
# ====================== concat example 1 ===================
firstname = 'sing'
lastname = 'zinc '
print(firstname + ' ' + lastname)
print(firstname * 3)
print('sing' in firstname)
# ====================== concat example 2 ===================
foo = "seven"
print("She lives with " + foo + " small men")
# ====================== Concat example 3 ===================
x = 'apples'
y = 'lemons'
z = 'In the basket are %s and %s' % (x,y)
print(z)
#=============== example 2 ===================
firstname = 'Christopher Arthur Hansen Brooks'.split(' ')[0] # [0] selects the first element of the list
lastname = 'Christopher Arthur Hansen Brooks'.split(' ')[-1] # [-1] selects the last element of the list
print(firstname)
print(lastname)
# this is incorrect example
# x = 'Chris' + 2
# print(x)
x = 'Chris' + str(2)
print(x)
| true |
590b4ee6898e35551b8059ef9256d307a8bcce59 | markvakarchuk/ISAT-252 | /Python/Rock, Paper, Scissors - Linear.py | 1,891 | 4.1875 | 4 | import time
import random
# defining all global variables
win_streak = 0 # counts how many times the user won
play_again = True # flag for if another round should be played
game_states = ["rock", "paper", "scissors"]
#printing the welcome message
print("Welcome to Rock, Paper, Scissors, lets play!")
time.sleep(0.5)
input("Press Enter to continue... \n")
# this function is promted at the beginning and after every round if the user won
# def play_round():
while play_again:
# define local variables
user_move = input("Enter 'rock','paper', or 'scissors': ")
# computers turn to generate move
comp_move = random.choice(game_states)
# see if user won
# user can win with 3 different combinations
# 1) Scissors beats Paper5
# 2) Rock beats Scissors
# 3) Paper beats Rock
if comp_move == user_move: # first check if it was a time
print("Tie! Go again! \n")
play_again = True
elif comp_move == 'paper' and user_move == 'scissors': # check for combo 1
print("Scissors beats paper! Go again! \n")
win_streak += 1
play_again = True
elif comp_move == 'scissors' and user_move == 'rock': # check for combo 2
print("Rock beats scissors! Go again! \n")
win_streak += 1
play_again = True
elif comp_move == 'rock' and user_move == 'paper': # check for combo 3
print("Paper beats rock! Go again! \n")
win_streak += 1
play_again = True
else: # means computer won, print how computer won and end round
print("\n" + str(comp_move) + " beats your move of " + str(user_move))
print("Better luck next time! \n")
play_again = False
print("********************************")
print("Win streak: " + str(win_streak))
print("********************************")
print("\n")
print("Thanks for playing!")
print("\n")
print("\n") | true |
c3f3e836042df5e06d1f19b26fda1197726d2030 | mikofski/poly2D | /polyDer2D.py | 2,204 | 4.25 | 4 | import numpy as np
def polyDer2D(p, x, y, n, m):
"""
polyDer2D(p, x, y, n, m)
Evaluate derivatives of a 2-D polynomial using Horner's method.
Evaluates the derivatives of 2-D polynomial `p` at the points
specified by `x` and `y`, which must be the same dimensions. The
outputs `(fx, fy)` will have the same dimensions as `x` and `y`.
The order of `x` and `y` are specified by `n` and `m`, respectively.
Parameters
----------
p : array_like
Polynomial coefficients in order specified by polyVal2D.html.
x : array_like
Values of 1st independent variable.
y : array_like
Values of 2nd independent variable.
n : int
Order of the 1st independent variable, `x`.
m : int
Order of the 2nd independent variable, `y`.
Returns
-------
fx : ndarray
Derivative with respect to x.
fy : ndarray
Derivative with respect to y.
See Also
--------
numpy.polynomial.polynomial.polyval2d : Evaluate a 2-D polynomial at points (x, y).
Example
--------
>>> print polyVal2D([1,2,3,4,5,6],2,3,2,1)
>>> (39, 11)
>>> 1*2*2*3 + 2*3 + 4*2*2 + 5
39
>>> 1*(2**2) + 2*2 + 3
11
>>> print polyVal2D([1,2,3,4,5,6,7,8,9],2,3,2,2)
>>> (153, 98)
>>> 1*2*2*(3**2) + 2*(3**2) + 4*2*2*3 + 5*3 + 7*2*2 + 8
153
>>> 1*2*(2**2)*3 + 2*2*2*3 + 3*2*3 + 4*(2**2) + 5*2 + 6
98
"""
# TODO: check input args
p = np.array(p)
x = np.array(x)
y = np.array(y)
n = np.array(n)
m = np.array(m)
# fx = df/dx
fx = n * p[0]
for ni in np.arange(n - 1):
fx = fx * x + (n - ni - 1) * p[1 + ni]
for mi in np.arange(m):
mj = (n + 1) * (mi + 1)
gx = n * p[mj]
for ni in np.arange(n - 1):
gx = gx * x + (n - ni - 1) * p[mj + 1 + ni]
fx = fx * y + gx
# fy = df/dy
fy = p[0]
for ni in np.arange(n):
fy = fy * x + p[1 + ni]
fy = m * fy
for mi in np.arange(m - 1):
mj = (n + 1) * (mi + 1)
gy = p[mj]
for ni in np.arange(n):
gy = gy * x + p[mj + 1 + ni]
fy = fy * y + (m - mi - 1) * gy
return fx, fy
| true |
4f6c341cb5903f526d9780af9d1aa2f8b2b87e35 | JakeBednard/CodeInterviewPractice | /6-1B_ManualIntToString.py | 444 | 4.125 | 4 | def int_to_string(value):
"""
Manually Convert String to Int
Assume only numeric chars in string
"""
is_negative = False
if value < 0:
is_negative = True
value *= -1
output = []
while value:
value, i = divmod(value, 10)
output.append((chr(i + ord('0'))))
return ('-' if is_negative else '') + "".join(reversed(output))
print(int_to_string(133))
print(int_to_string(-133)) | true |
7d26e6913a4b0024fa1082e5f3ea7c9ff0cbc50b | Azab007/Data-Structures-and-Algorithms-Specialization | /algorithms on strings/week2/suffix_array/suffix_array.py | 572 | 4.21875 | 4 | # python3
import sys
from collections import defaultdict
def build_suffix_array(text):
"""
Build suffix array of the string text and
return a list result of the same length as the text
such that the value result[i] is the index (0-based)
in text where the i-th lexicographically smallest
suffix of text starts.
"""
suffix = []
for i in range(len(text)):
suffix.append((text[i:], i))
suffix.sort()
for arr, indx in suffix:
print(indx, end=' ')
if __name__ == '__main__':
text = sys.stdin.readline().strip()
build_suffix_array(text)
| true |
01aaf5aec0ca74fdfec8f95d7137979737c313a4 | JMH201810/Labs | /Python/p01320g.py | 1,342 | 4.5 | 4 | # g. Album:
# Write a function called make_album() that builds a dictionary describing
# a music album. The function should take in an artist name and an album
# title, and it should return a dictionary containing these two pieces of
# information. Use the function to make three dictionaries representing
# different albums. Print each return value to show that the dictionaries
# are storing the album information correctly.
# Add an optional parameter to make_album() that allows you to store the
# number of tracks on an album. If the calling line includes a value for
# the number of tracks, add that value to the album's dictionary.
# Make at least one new function call that includes the number of tracks on
# an album.
def make_album(artist_name, album_title, nTracks=''):
if nTracks:
d = {'artist_name':artist_name,
'album_title':album_title,
'nTracks':nTracks}
else:
d = {'artist_name':artist_name,
'album_title':album_title}
return d
d1 = make_album('Bob','Album1')
d2 = make_album('Donald','Album2')
d3 = make_album('Gertrude','Album3')
print ('\n', d1, '\n', d2, '\n', d3)
d1 = make_album('Bob','Album1')
d2 = make_album('Donald','Album2')
d3 = make_album('Gertrude','Album3', 7)
print ('\n', d1, '\n', d2, '\n', d3)
| true |
64a30bf626d62b29ae78c9ac9435dc1ca5c929f3 | JMH201810/Labs | /Python/p01320L.py | 568 | 4.15625 | 4 | # l. Sandwiches:
# Write a function that accepts a list of items a person wants on a sandwich.
# The function should have one parameter that collects as many items as the
# function call provides, and it should print a summary of the sandwich that
# is being ordered.
# Call the function three times, using a different number
# of arguments each time.
def toppings(*thing):
print ()
for t in thing:
print('-', t)
toppings('butter', 'air', 'salt')
toppings('worms', 'sand', 'rocks', 'tahini')
toppings('wallets', 'staplers')
| true |
ae64e924773c4243da27404de13e74ce2e973b56 | JMH201810/Labs | /Python/p01310j.py | 631 | 4.59375 | 5 | # Favorite Places:
# Make a dictionary called favorite_places.
# Think of three names to use as keys in the dictionary, and store one to
# three favorite places for each person.
# Loop through the dictionary, and print each person's name and their
# favorite places.
favorite_places = {'Alice':['Benton Harbor', 'Alice Springs', 'Utah'],
'Brenda':['Ann Arbor', 'Detroit', 'Eau Claire'],
'Charles':['under the couch', 'VBISD', 'Michigan']}
for person,placeList in favorite_places.items():
print("\n",person,"'s favorite places are:", sep='')
for place in placeList:
print(place)
| true |
d6c1fa3d43547d59fa10a9e6d1e51e169dac8a18 | JMH201810/Labs | /Python/p01210i.py | 924 | 4.875 | 5 | # Pizzas: Think of at least three kinds of your favorite pizza. Store these pizza
# names in a list, and then use a for loop to print the name of each pizza.
pizzaTypes = ['Round', 'Edible', 'Vegetarian']
print("Pizza types:")
for type in pizzaTypes:
print(type)
# i. Modify your for loop to print a sentence using the name of the pizza
# instead of printing just the name of the pizza. For each pizza you should
# have one line of output containing a simple statement like I like pepperoni
# pizza.
print("Using a sentence:")
for type in pizzaTypes:
print("I like",type,"pizza.")
# ii. Add a line at the end of your program, outside the for loop, that states how
# much you like pizza. The output should consist of three or more lines
# about the kinds of pizza you like and then an additional sentence, such as I
# really love pizza!
print ("I really love pizza!")
| true |
e86600435612f88fbf67e3e805f0e21e6f0f51f8 | 23-Dharshini/priyadharshini | /count words.py | 253 | 4.3125 | 4 | string = input("enter the string:")
count = 0
words = 1
for i in string:
count = count+1
if (i==" "):
words = words+1
print("Number of character in the string:",count)
print("Number of words in the string:",words) | true |
1622d36817330cc707a1a4e4c4e52810065aa222 | Whatsupyuan/python_ws | /4.第四章-列表操作/iterator_044_test.py | 1,306 | 4.15625 | 4 | # 4-10
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("The first three items in the list are" )
print(players[:3])
print()
# python3 四舍五入 问题
# 官方文档写了,round(number[, ndigits]) values are rounded to the closest multiple of 10 to the power minus ndigits;
# if two multiples are equally close, rounding is done toward the even choice
# (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).
# 就是说round(1/2)取离它最近的整数,如果2个数(0和1)离它一样近,则取偶数(the even choice)。
# 因此round(1.5)=2, round(2.5)=2, round(3.5)=4, round(4.5)=4。
# http://www.cnblogs.com/lxmwb/p/7988913.html
# 4-10-2 打印列表中间的3个元素
print("Three items from the middle of the list are:")
import decimal
half_length = len(players)
a = decimal.Decimal(half_length)/2
decimal.getcontext().rounding = decimal.ROUND_UP
half_num = round(a,0)
print(players[int(half_num-2):int(half_num+1)])
print()
# 4-10-3 打印列表尾部的3个元素
print("The last three items in the list are:")
print(players[half_length-3:])
# 4-11-1
pizzas = ["one_pizza" , "two_pizza" , "thress_pizza"]
friend_pizzas = pizzas[:]
pizzas.append("none-pizza");
print(pizzas)
print(friend_pizzas)
for p in pizzas:
print(p) | true |
3d999ca8f12348a3cb229be5af0f9cdba4ccc0b2 | ArvindAROO/algorithms | /sleepsort.py | 1,052 | 4.125 | 4 | """
Sleepsort is probably the wierdest of all sorting functions
with time-complexity of O(max(input)+n) which is
quite different from almost all other sorting techniques.
If the number of inputs is small then the complexity
can be approximated to be O(max(input)) which is a constant
If the number of inputs is large then the complexity is
approximately O(n)
This function uses multithreading a kind of higher order programming
and calls n functions, each with a sleep time equal to its number.
Hence each of the functions wake in Sorted form
But this function is not stable for very large values
"""
from time import sleep
from threading import Timer
def sleepsort(values):
sleepsort.result = []
def add1(x):
sleepsort.result.append(x)
mx = values[0]
for v in values:
if mx < v:
mx = v
Timer(v, add1, [v]).start()
sleep(mx+1)
return sleepsort.result
if __name__ == '__main__':
x = [3,2,4,7,3,6,9,1]
sorted_x=sleepsort(x)
print(sorted_x)
| true |
911d4753a01ab601346e3bc2f3b483a61d21c7ae | bspindler/python_sandbox | /classes.py | 1,180 | 4.3125 | 4 | # A class is like a blueprint for creating objects. An object has properties and methods (functions)
# associated with it. Almost everything in Python is an object
# Create Class
class User:
# constructor
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
def greeting(self):
return f'My name is {self.name} and I am {self.age}'
def increase_age(self):
self.age += 1
# Extends class
class Customer(User):
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
self.balance = 0
def set_balance(self, balance):
self.balance = balance
def greeting(self):
return f'My name is {self.name} and I am {self.age} and my balance is {self.balance}'
# Init user object
brad = User('Brad Traversy', 'brad@gmail.com', 37)
print(type(brad), brad)
janet = Customer('Janet Z', 'janet@gmail.com', 57)
print(type(janet), janet)
janet.set_balance(500)
print(janet.greeting())
# Access properties
print(brad.name, brad.email, brad.age)
# Run method on class
print(brad.greeting())
brad.increase_age()
print(brad.greeting()) | true |
c246c6a153b6bc176ed0e279a60d32f1b2100711 | ntkawasaki/complete-python-masterclass | /7: Lists, Ranges, and Tuples/tuples.py | 1,799 | 4.5625 | 5 | # tuples are immutable, can't be altered or appended to
# parenthesis are not necessary, only to resolve ambiguity
# returned in brackets
# t = "a", "b", "c"
# x = ("a", "b", "c") # using brackets is best practice
# print(t)
# print(x)
#
# print("a", "b", "c")
# print(("a", "b", "c")) # to print a tuple explicitly include parenthesis
# tuples can put multiple data types on same line
welcome = "Welcome to my Nightmare", "Alice Cooper", 1975
bad = "Bad Company", "Bad Company", 1974
budgie = "Nightflight", "Budgie", 1981
imelda = "More Mayhem", "Emilda Way", 2011
metallica = "Ride the Lightening", "Metallica", 1984
# print(metallica)
# print(metallica[0]) # print one part of tuple
# print(metallica[1])
# print(metallica[2])
# cant change underlying tuple, immutable object
# metallica[0] = "Master of Puppets"
# ca get around this like this though
imelda = imelda[0], "Emilda Way", imelda[2]
# python also evaluates the right side of this expression first, then assigns it to a new variable "imelda"
# creates a new tuple
print(imelda)
# can alter a list though
metallica2 = ["Ride the Lightening", "Metallica", 1984]
print(metallica2)
metallica2[0] = "Master of Puppets"
print(metallica2)
print()
# metallica2.append("Rock")
# title, album, year = metallica2
# print(title)
# print(album)
# print(year)
# will draw a too many values to unpack error because not enough variables assigned
# unpacking the tuple, extract values from and assign to variables
title, album, year = imelda
print(imelda)
print("Title: {}".format(title))
print("Album: {}".format(album))
print("Year: {}".format(year))
# tuples don't have an append() method
imelda.append("Rock")
# notes
# lists are intended to hold objects of the same type, tuples not necessarily
# tuples not changing can protect code against bugs
| true |
acf3384d648aa16c781ac82c61b8e3c275538bae | ntkawasaki/complete-python-masterclass | /10: Input and Output/shelve_example.py | 1,638 | 4.25 | 4 | # like a dictionary stored in a file, uses keys and values
# persistent dictionary
# values pickled when saved, don't use untrusted sources
import shelve
# open a shelf like its a file
# with shelve.open("shelf_test") as fruit: # makes a shelf_test.db file
# fruit["orange"] = "a sweet, orange fruit"
# fruit["apple"] = "good for making cider"
# fruit["lemon"] = "a sour, yellow fruit"
# fruit["grape"] = "a small, sweet fruit grown in bunches"
# fruit["lime"] = "a sour, green citrus fruit"
# when outside of the with, it closes the file
# print(fruit) # prints as a shelf and not a dictionary
# to do this with manual open and closing
fruit = shelve.open("shelf_test")
# fruit["orange"] = "a sweet, orange fruit"
# fruit["apple"] = "good for making cider"
# fruit["lemon"] = "a sour, yellow fruit"
# fruit["grape"] = "a small, sweet fruit grown in bunches"
# fruit["lime"] = "a sour, green citrus fruit"
# # change value of "lime"
# fruit["lime"] = "goes great with tequila!"
#
# for snack in fruit:
# print(fruit[snack])
# while True:
# dict_key = input("Please enter a fruit: ")
# if dict_key == "quit":
# break
#
# if dict_key in fruit:
# description = fruit[dict_key]
# print(description)
# else:
# print("We don't have a " + dict_key)
# alpha sorting keys
# ordered_keys = list(fruit.keys())
# ordered_keys.sort()
#
# for f in ordered_keys:
# print(f + " - " + fruit[f])
#
# fruit.close() # remember to close
for v in fruit.values():
print(v)
print(fruit.values())
for f in fruit.items():
print(f)
print(fruit.items())
fruit.close() | true |
fcd60015393e712316586a32f75462eff2f4543f | ntkawasaki/complete-python-masterclass | /11: Modules and Functions/Functions/more_functions.py | 2,460 | 4.125 | 4 | # more functions!
# function can use variables from main program
# main program cannot use local variables in a function
import math
try:
import tkinter
except ImportError: # python 2
import Tkinter as tkinter
def parabola(page, size):
"""
Returns parabola or y = x^2 from param x.
:param page:
:param size
:return parabola:
"""
for x_coor in range(size):
y_coor = x_coor * x_coor / size
plot(page, x_coor, y_coor)
plot(page, -x_coor, y_coor)
# modify the circle function so that it allows the color
# of the circle to be specified and defaults to red
def circle(page, radius, g, h, color="red"):
""" Create a circle. """
for x in range(g * 100, (g + radius) * 100):
page.create_oval(g + radius, h + radius, g - radius, h - radius, outline=color, width=2)
# x /= 100
# print(x)
# y = h + (math.sqrt(radius ** 2 - ((x - g) ** 2)))
# plot(page, x, y)
# plot(page, x, 2 * h - y)
# plot(page, 2 * g - x, y)
# plot(page, 2 * g - x, 2 * h - y)
def draw_axis(page):
"""
Draws a horizontal and vertical line through middle of window to be used as
the x and y axis.
:param page:
:return:
"""
page.update() # allows you to use winfo_width/height
x_origin = page.winfo_width() / 2
y_origin = page.winfo_height() / 2
page.configure(scrollregion=(-x_origin, -y_origin, x_origin, y_origin))
# create_line(x1, y1, x2, y2)
page.create_line(-x_origin, 0, x_origin, 0, fill="black") # horizontal
page.create_line(0, y_origin, 0, -y_origin, fill="black") # vertical
# shows all local variables in this function
print(locals())
def plot(page, x_plot, y_plot):
"""
Plots points on canvas from params x and y.
:param page:
:param x_plot:
:param y_plot:
:return:
"""
page.create_line(x_plot, -y_plot, x_plot + 1, -y_plot + 1, fill="red")
# window
main_window = tkinter.Tk()
main_window.title("Parabola")
main_window.geometry("640x480")
# canvas
canvas = tkinter.Canvas(main_window, width=640, height=480, background="gray")
canvas.grid(row=0, column=0)
# call function
draw_axis(canvas)
parabola(canvas, 300)
parabola(canvas, 20)
circle(canvas, 100, 100, 100, color="blue")
circle(canvas, 100, 100, 100, color="yellow")
circle(canvas, 100, 100, 100, color="green")
circle(canvas, 10, 30, 30, color="black")
main_window.mainloop()
| true |
4ccdd7851dc2177d6a35e72cb57069685d75f72c | echo001/Python | /python_for_everybody/exer9.1.py | 706 | 4.21875 | 4 | #Exercise 1 Write a program that reads the words in words.txt and stores them as
# keys in a dictionary. It doesn’t matter what the values are. Then you
# can use the in operator as a fast way to check whether a string is
# in the dictionary.
fname = input('Enter a file name : ')
try:
fhand = open(fname)
except:
print('Ther is no this file %s ' % fname)
exit()
word = dict()
for line in fhand:
line = line.rstrip()
# if line not in word:
# word[line] = 1
# else:
# word[line] = word[line] + 1 #count how many times the same word appear
word[line] = word.get(line,0) + 1 # the same as if.... else...
print(word)
| true |
19e74e3bc318021556ceec645597199996cfba98 | echo001/Python | /python_for_everybody/exer10.11.3.py | 1,251 | 4.40625 | 4 | #Exercise 3 Write a program that reads a file and prints the letters in
# decreasing order of frequency. Your program should convert all the
# input to lower case and only count the letters a-z. Your program
# should not count spaces, digits, punctuation, or anything other than
# the letters a-z. Find text samples from several different languages
# and see how letter frequency varies between languages. Compare your
# results with the tables at wikipedia.org/wiki/Letter_frequencies.
import string
fname = input('Enter a file name : ')
try:
fhand = open(fname)
except:
print('This file can not be opened. ')
exit()
letterCount = dict()
for line in fhand:
line = line.rstrip()
line = line.translate(line.maketrans('','',string.punctuation)) #delete all punctuation
linelist = line.lower()
for letter in linelist:
if letter.isdigit(): #delete all digit
continue
letterCount[letter] = letterCount.get(letter,0) + 1 #count letters from files
letterCountList = list(letterCount.items())
letterCountList.sort() #sort letters from a to z
for letter,count in letterCountList:
print(letter,count)
| true |
3168d9379b4ff8064b60ed5e6db65d504c91f5a0 | marcluettecke/programming_challenges | /python_scripts/rot13_translation.py | 482 | 4.125 | 4 | """
Function to shift every letter by 13 positions in the alphabet. Clever use of maketrans and translate.
"""
trans = str.maketrans('ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz',
'NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm')
def rot13(message):
"""
Translation by rot13 encoding.
Args:
message: string such as 'Test'
Returns:
translated string, such as 'Grfg'
"""
return message.translate(trans)
| true |
ae038beb027640e3af191d24c6c3abbb172e398e | mihaidobri/DataCamp | /SupervisedLearningWithScikitLearn/Classification/02_TrainTestSplit_FitPredictAccuracy.py | 777 | 4.125 | 4 | '''
After creating arrays for the features and target variable, you will split them into training and test sets,
fit a k-NN classifier to the training data, and then compute its accuracy using the .score() method.
'''
# Import necessary modules
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
# Create feature and target arrays
X = digits.data
y = digits.target
# Split into training and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state=42, stratify=y)
# Create a k-NN classifier with 7 neighbors: knn
knn = KNeighborsClassifier(n_neighbors = 7)
# Fit the classifier to the training data
knn.fit(X_train,y_train)
# Print the accuracy
print(knn.score(X_test, y_test))
| true |
92d2b840f03db425aaaedf22ad57d0b291bb79e6 | devmadhuu/Python | /assignment_01/odd_in_a_range.py | 505 | 4.375 | 4 | ## Program to print Odd number within a given range.
start = input ('Enter start number of range:')
end = input ('Enter end number of range:')
if start.isdigit() and end.isdigit():
start = int(start)
end = int(end)
if end > start:
for num in range(start, end):
if num % 2 != 0:
print('Number {num} is odd'.format(num = num))
else:
print('End number should be greater than start number !!!')
else:
print('Enter valid start and end range !!!') | true |
66c8afbcdd793b3817993abfb904b4ec0111f666 | devmadhuu/Python | /assignment_01/factorial.py | 410 | 4.4375 | 4 | ## Python program to find the factorial of a number.
userinput = input ('Enter number to find the factorial:')
if userinput.isdigit() or userinput.find('-') >= 0:
userinput = int(userinput)
factorial = 1
for num in range (1, userinput + 1):
factorial*=num
print('Factorial of {a} is {factorial}'.format(a = userinput, factorial = factorial))
else:
print('Enter valid numeric input') | true |
6d030f79eb3df2a3572eaadb0757401d3a330326 | amark02/ICS4U-Classwork | /Quiz2/evaluation.py | 2,636 | 4.25 | 4 | from typing import Dict, List
def average(a: float, b: float, c:float) -> float:
"""Returns the average of 3 numbers.
Args:
a: A decimal number
b: A decimal number
c: A decimal number
Returns:
The average of the 3 numbers as a float
"""
return (a + b + c)/3
def count_length_of_wood(wood: List[int], wood_length: int) -> int:
"""Finds how many pieces of wood have a specific
board length.
Args:
wood: A list of integers indicating length of
a piece of wood
wood_length: An integer that specifices what length
of wood a person is looking for
Returns:
How many pieces of wood there are for a specific
board length
e.g.,
wood = [10, 5, 10]
wood_length = 10
return 2
"""
total = 0
for piece in wood:
if piece == wood_length:
total += 1
else:
None
return total
def occurance_of_board_length(board_length: List[int]) -> Dict:
"""Returns a diciontary of the occurances of the length of a board.
Args:
board_length: A list of integers indicating the length
of a piece of wood
Returns:
Dictionary with the key being the length, and the value
being the number of times the length appeares in the list
e.g.,
board_length = [10, 15, 20, 20, 10]
return {10: 2, 15: 1, 20: 2}
"""
occurances = {}
for wood_length in board_length:
if wood_length in occurances.keys():
occurances[wood_length] += 1
else:
occurances[wood_length] = 1
return occurances
def get_board_length(board_length: Dict, wood_length: int) -> int:
"""Finds out how many pieces of wood have a specific
board length.
Args:
board_length: A dictionary with the keys being the board
length and the values being the number of boards with that
specific length
wood_length: An integer that specfies what length of wood
a person is looking for
Returns:
How many pieces of wood there are for a specific board length
"""
#correct answer
for key in board_length.keys():
if key == wood_length:
return board_length[key]
else:
return 0
"""
wrong answer:
list_of_wood = []
for key in board_length.keys():
list_of_wood.append(key)
total = 0
for piece in list_of_wood:
if piece == wood_length:
total += 1
else:
None
return total
"""
| true |
5b632636066e777092b375219a7a6cd571619157 | amark02/ICS4U-Classwork | /Classes/01_store_data.py | 271 | 4.1875 | 4 |
class Person:
pass
p = Person()
p.name = "Jeff"
p.eye_color = "Blue"
p2 = Person()
print(p)
print(p.name)
print(p.eye_color)
"""
print(p2.name)
gives an error since the object has no attribute of name
since you gave the other person an attribute on the fly
""" | true |
23ee2c8360e32e0334a31da848043cf6187cd636 | cosinekitty/astronomy | /demo/python/gravity.py | 1,137 | 4.125 | 4 | #!/usr/bin/env python3
import sys
from astronomy import ObserverGravity
UsageText = r'''
USAGE:
gravity.py latitude height
Calculates the gravitational acceleration experienced
by an observer on the surface of the Earth at the specified
latitude (degrees north of the equator) and height
(meters above sea level).
The output is the gravitational acceleration in m/s^2.
'''
if __name__ == '__main__':
if len(sys.argv) != 3:
print(UsageText)
sys.exit(1)
latitude = float(sys.argv[1])
if latitude < -90.0 or latitude > +90.0:
print("ERROR: Invalid latitude '{}'. Must be a number between -90 and +90.".format(sys.argv[1]))
sys.exit(1)
height = float(sys.argv[2])
MAX_HEIGHT_METERS = 100000.0
if height < 0.0 or height > MAX_HEIGHT_METERS:
print("ERROR: Invalid height '{}'. Must be a number between 0 and {}.".format(sys.argv[1], MAX_HEIGHT_METERS))
sys.exit(1)
gravity = ObserverGravity(latitude, height)
print("latitude = {:8.4f}, height = {:6.0f}, gravity = {:8.6f}".format(latitude, height, gravity))
sys.exit(0)
| true |
e79076cd45b6280c2046283d9a349620af0f8d70 | joshinihal/dsa | /trees/tree_implementation_using_oop.py | 1,428 | 4.21875 | 4 | # Nodes and References Implementation of a Tree
# defining a class:
# python3 : class BinaryTree()
# older than python 3: class BinaryTree(object)
class BinaryTree():
def __init__(self,rootObj):
# root value is also called key
self.key = rootObj
self.leftChild = None
self.rightChild = None
# add new as the left child of root, if a node already exists on left, push it down and make it child's child.
def insertLeft(self,newNode):
if self.leftChild == None:
self.leftChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.leftChild = self.leftChild
self.leftChild = t
# add new as the right child of root, if a node already exists on right, push it down and make it child's child.
def insertRight(self,newNode):
if self.rightChild == None:
self.rightChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.rightChild = self.rightChild
self.rightChild = t
def getLeftChild(self):
return self.leftChild
def getRightChild(self):
return self.rightChild
def setRootValue(self,obj):
self.key = obj
def getRootValue(self):
return self.key
r = BinaryTree('a')
r.getRootValue()
r.insertLeft('b')
r.getLeftChild().getRootValue()
| true |
74725fc2d2c7d06cec7bc468aa078f59e6aa21e7 | AGriggs1/Labwork-Fall-2017 | /hello.py | 858 | 4.125 | 4 | # Intro to Programming
# Author: Anthony Griggs
# Date: 9/1/17
##################################
# dprint
# enables or disables debug printing
# Simple function used by many, many programmers, I take no credit for it WHATSOEVER
# to enable, simply set bDebugStatements to true!
##NOTE TO SELF: in Python, first letter to booleans are Capitalized
bDebugStatements = True
def dprint(message):
if (bDebugStatements == True):
print(message)
#Simple function with no specific purpose
def main():
iUsr = eval(input("Gimme a number! Not too little, not too big... "))
dprint("This message is for debugging purposes")
for i in range(iUsr):
#Hmmmm, ideally we don't want a space between (i + 1) and the "!"
#GH! Why does Python automatically add spaces?
print("Hello instructor", i + 1, "!")
print("Good bye!")
dprint("End")
main()
| true |
73a9544105ca7eae0d7997aa2e0a4b74bf8723b7 | SanamKhatri/school | /teacher_delete.py | 1,234 | 4.1875 | 4 | import teacher_database
from Teacher import Teacher
def delete_teacher():
delete_menu="""
1.By Name
2.By Addeess
3.By Subject
"""
print(delete_menu)
delete_choice=int(input("Enter the delete choice"))
if delete_choice==1:
delete_name=input("Enter the name of the teacher to delete")
t=Teacher(name=delete_name)
is_deleted=teacher_database.delete_by_name(t)
if is_deleted:
print("The data is deleted")
else:
print("There was error in the process")
elif delete_choice==2:
delete_address = input("Enter the address of the teacher to delete")
t = Teacher(address=delete_address)
is_deleted = teacher_database.delete_by_address(t)
if is_deleted:
print("The data is deleted")
else:
print("There was error in the process")
elif delete_choice==3:
delete_subject = input("Enter the subject of the teacher to delete")
t = Teacher(subject=delete_subject)
is_deleted = teacher_database.delete_by_subject(t)
if is_deleted:
print("The data is deleted")
else:
print("There was error in the process") | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.