blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
7334abb4a4292b369af8ecbcb18980f127cbc558 | FluffyFu/UCSD_Algorithms_Course_1 | /week3_greedy_algorithms/5_collecting_signatures/covering_segments.py | 1,115 | 4.3125 | 4 | # Uses python3
import sys
from collections import namedtuple
Segment = namedtuple('Segment', 'start end')
def optimal_points(segments):
"""
Given a list of intervals (defined by integers). Find the minimum number of points,
such that each segment at least contains one point.
Args:
segments (list of namedtuples): a list of [a_i, b_i] intervals, both of them are integers
and a_i <= b_i
Returns:
a list of points that fulfills the requirement.
"""
points = []
sorted_segments = sorted(segments, key=lambda x: x.start)
end = sorted_segments[0].end
for current in sorted_segments:
if current.start > end:
points.append(end)
end = current.end
elif current.end < end:
end = current.end
points.append(end)
return points
if __name__ == '__main__':
input = sys.stdin.read()
n, *data = map(int, input.split())
segments = list(map(lambda x: Segment(
x[0], x[1]), zip(data[::2], data[1::2])))
points = optimal_points(segments)
print(len(points))
print(*points)
| true |
b85f45db7324fe4acbb6beb920cd38071e01da91 | FluffyFu/UCSD_Algorithms_Course_1 | /week2_algorithmic_warmup/8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers/fibonacci_sum_squares.py | 972 | 4.28125 | 4 | # Uses python3
from sys import stdin
def fibonacci_sum_squares_naive(n):
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
previous, current = current, previous + current
sum += current * current
return sum % 10
def fibonacci_sum_squares(n):
"""
Calculate the last digit of F(0)^2 + F(1)^2 + ... + F(n)^2
Think the square as the area of a square. And from the geometry, we have the sum is
equal to:
F(n) * (F(n) + F(n-1))
We know the last digit of F(n) has periodicity of 60. Using this fact, the last digit can
be calculated easily.
"""
if n % 60 == 0:
return 0
n = n % 60
previous = 0
current = 1
for _ in range(n-1):
previous, current = current, (previous + current) % 10
return (current * (previous + current)) % 10
if __name__ == '__main__':
n = int(stdin.read())
print(fibonacci_sum_squares(n))
| true |
763c4122695531a8de231f3982bdfb070097cf87 | AkshayLavhagale/SW_567_HW_01 | /HW_01.py | 1,585 | 4.3125 | 4 | """ Name - Akshay Lavhagale
HW 01: Testing triangle classification
The function returns a string that specifies whether the triangle is scalene, isosceles, or equilateral,
and whether it is a right triangle as well. """
def classify_triangle(a, b, c):
# This function will tell us whether the triangle is scalene, isosceles, equilateral or right triangle
try:
a = float(a)
b = float(b)
c = float(c)
except ValueError:
raise ValueError("The input value is not number")
else:
[a, b, c] = sorted([a, b, c]) # sorting the values of a, b and c so it would always remain in order
if (a + b < c and a + c < b and b + c < a) or (a or b or c) <= 0:
""" The Triangle Inequality Theorem states that the sum of any 2 sides of a triangle must be greater
than the measure of the third side. Also none of the side should be equal to zero """
return "This is not a triangle"
elif a ** 2 + b ** 2 == c ** 2:
if a != b or a != c or b != c:
return "Right and Scalene Triangle"
if a == b or a == c or b == c:
return "Isosceles and Right Triangle"
elif a == b == c:
return "Equilateral"
if a == b or a == c or b == c:
return "Isosceles"
else:
return "Scalene"
def run_classify_triangle(a, b, c):
# Invoke classify_triangle with the specified arguments and print the result
print('classify_triangle(', a, ',', b, ',', c, ')=', classify_triangle(a, b, c), sep="")
| true |
7c7d3f029730d3c2a2653c367c9dbc45fb9bcd41 | Mollocks/Day_at_the_py_shop | /Day1.py | 435 | 4.28125 | 4 | #!/usr/bin/env python3
#This is my first script :)
print("Hello World!")
x = "Passion fruit"
y = x.upper()
print(y)
#Anything I want
age = 49
txt = "My name is Hubert, and I am {}"
print(txt.format(age))
"""
This is Hubert and he is 49.
You can mix strings only using the .format function
"""
#https://www.w3schools.com/python/python_strings_format.asp
# https://www.w3schools.com/python/exercise.asp?filename=exercise_strings1
| true |
9470642703b3ac4a62e94276dcd3eb529b38fe31 | Austin-Faulkner/Basic_General_Python_Practice | /OxfordComma.py | 1,442 | 4.34375 | 4 | # When writing out a list in English, one normally spearates
# the items with commas. In addition, the word "and" is normally
# included before the last item, unless the list only contains
# one item. Consider the following four lists:
# apples
# apples and oranges
# apples, oranges, and bananas
# apples, oranges, bananas, and lemons
# Write a function that takes a list of strings as
# its only parameter. Your function should return a
# string that contains all of the items in the list
# formatted in the manner described above. Your function
# should work correctly for lists of any length. If the
# user does not enter any strings, it should print "<empty>".
# Include a main program that prompts the user for items, calls
# your function to create the properly formatted string,
# and displays the result.
def oxfordComma(lst):
oCommas = ""
if len(lst) == 0:
return "<empty>"
elif len(lst) == 1:
return str(lst[0])
elif len(lst) > 1:
for i in range(0, len(lst) - 1):
oCommas += str(lst[i]) + ", "
oCommas += "and " + str(lst[-1]) + "."
return oCommas
def main():
words = []
entry = str(input("Enter a series of words (hit 'return' to discontinue): "))
while entry != "":
words.append(entry)
entry = str(input("Enter a series of words (hit 'return' to discontinue): "))
print(oxfordComma(words))
main()
| true |
7cea87bed8615753466b2cd60712e2c22ce34fb2 | nurur/ReplaceFirstCharacter-R.vs.Python | /repFirstCharacter.py | 613 | 4.53125 | 5 | # Python script to change the case (lower or upper) of the first letter of a string
# String
a='circulating'
print 'The string is:', a
print ''
#Method 1: splitting string into letters
print 'Changing the first letter by splitting the string into letters'
b=list(a)
b[0] = b[0].upper()
b=''.join(b)
print b
print ' '
# Method 2: using regular expression
print 'Changing the first letter by using regular expression'
import re
rep = lambda f: f.group(1).upper()
b = re.sub('\A([a-z])', rep, a) #using anchor token \A
print b
b = re.sub('^([a-z])', rep, a) #using anchor token ^
print b
| true |
bd5ac9ee6116ebe863436db0dcf969b525beec5e | noahjett/Algorithmic-Number-Theory | /Algorithmic Number Theory/Binary_Exponentiation.py | 2,450 | 4.15625 | 4 | # Author: Noah Jett
# Date: 10/1/2018
# CS 370: Algorithmic Number Theory - Prof. Shallue
# This program is an implementation of the binary exponentiation algorithm to solve a problem of form a**e % n in fewer steps
# I referenced our classroom discussion and the python wiki for the Math.log2 method
import math
def main():
a,n = 2,3
for e in range(1,10):
print("e ==: ", e)
result = (PowerMod(a,e,n,1))
print("Answer: ", result)
logTest = logbase2(e)
print("2 * log base2(e) = ", logTest, "\n")
def PowerMod(a,e,n,numSteps): # a ** e % n
print("||", a,e,n, "||")
if e < 1:
print("Steps: ", numSteps)
return (a)
elif e % 2 == 0: # even case
return (PowerMod(a, e/2, n, numSteps+1)**2)%n
elif e % 2 != 0: # odd case
return (a * PowerMod(a, e-1, n,numSteps+1) % n)
# Takes input e, the exponent being calculated in powermod
# Outputs 2*log base2(e)
# I googled "python log base 2" library, and was directed (stackoverflow?) to the log2 function in the "math" library
def logbase2(e):
log = (math.log2(e))*2
return log
main()
"""
This algorithm for binary exponentiation should theoretically take <= logbase2(e) *2 steps to solve.
I tested this for exponents 1-100 for the equation 2**e % 3.
The algorithm did not consistently take <= 2logbase2(e) steps until the exponent was >= 16. With the exceptions of 31 and 63
The exponents that solved in the least steps, around 25% fewer than 2logbase2(e) were:
16,24,32,34,36,48,64,72... There was a positive correlation between even numbers and fewer steps, and an even greater one between powers of 2 and fewer steps.
Some exponents that took more steps, being only slightly better than the theoretical limit were:
19,21,23,31,47,79,95. Odd numbers and primes both seem to take more steps to solve
Why is this the case?
The first fifteen exponents exceed the theoretical upper bound. I suspect this is overhead from python or my specific code.
However, it also makes sense that this algorithm will always take at least a few steps, so it might just not work under a certain number.
It makes sense that odd numbers would be slightly slower. Algorithmically, the odd case is essentially the # of even stepe +1
Powers of 2 being faster probably has to do with having a base of 2; those numbers would divide perfectly.
"""
| true |
f14c4696cc8e4f2db90416bd8e4216a7319c3860 | Quiver92/edX_Introduction-to-Python-Creating-Scalable-Robust-Interactive-Code | /Boolean_Operators/Task1.py | 761 | 4.375 | 4 | #Boolean Operators
#Boolean values (True, False)
# [ ] Use relational and/or arithmetic operators with the variables x and y to write:
# 3 expressions that evaluate to True (i.e. x >= y)
# 3 expressions that evaluate to False (i.e. x <= y)
x = 84
y = 17
print(x >= y)
print(x >= y and x >= y)
print(x >= y or x >= y)
print(x <= y)
print(x <= y and x <= y)
print(x <= y or x <= y)
#Boolean operators (not, and, or)
# [ ] Use the basic Boolean operators with the variables x and y to write:
# 3 expressions that evaluate to True (i.e. not y)
# 3 expressions that evaluate to False (i.e. x and y)
x = True
y = False
print( x and not y )
print( x or not y )
print( y or not y )
print( not x and y)
print( not x and x and y )
print( not y and x and y )
| true |
837bebc2d9fbed6fe2ab8443f09a30bce9554478 | Quiver92/edX_Introduction-to-Python-Creating-Scalable-Robust-Interactive-Code | /File_System/Task_2.py | 908 | 4.40625 | 4 | import os.path
# [ ] Write a program that prompts the user for a file or directory name
# then prints a message verifying if it exists in the current working directory
dir_name = input("Please provide a file or directory name: ")
if(os.path.exists(dir_name)):
print("Path exists")
# Test to see if it's a file or directory
if(os.path.isfile(dir_name)):
print("It's a file")
elif (os.path.isdir(dir_name)):
print("It's a dir")
else:
print("Path doesn't exist")
# [ ] Write a program to print the absolute path of all directories in "parent_dir"
# HINTS:
# 1) Verify you are inside "parent_dir" using os.getcwd()
# 2) Use os.listdir() to get a list of files and directories in "parent_dir"
# 3) Iterate over the elements of the list and print the absolute paths of all the directories
dir_list = os.listdir()
print(dir_list)
for i in dir_list:
print(os.path.abspath(i))
| true |
655bf45e09a32b1544b54c5c938b8f5430daf4e7 | grimesj7913/cti110 | /P3T1_AreaOfRectangles_JamesGrimes.py | 733 | 4.34375 | 4 | #A calculator for calculating two seperate areas of rectangles
#September 11th 2018
#CTI-110 P3T1 - Areas of Rectangles
#James Grimes
#
length1 = float(input("What is the length of the first rectangle?:"))
width1 = float(input("What is the width of the first rectangle?:" ))
area1 = float(length1 * width1)
length2 = float(input("What is the length of the second rectangle?:"))
width2 = float(input("What is the width of the second rectangle?:"))
area2 = float(length2 * width2)
if area1 > area2:
print('Rectangle 1 has the greater area')
else:
if area2 > area1:
print('Rectangle 2 has the greater area')
else:
print('Both are the same area')
input("Press enter to close the program")
| true |
78c7fb57d30e08b0c7f0808c3272769d6f2a2726 | elnieto/Python-Activities | /Coprime.py | 1,342 | 4.125 | 4 | #Elizabeth Nieto
#09/20/19
#Honor Statement: I have not given or received any unauthorized assistance \
#on this assignment.
#https://youtu.be/6rhgXRIZ6OA
#HW 1 Part 2
def coprime(a,b):
'takes two numbers and returns whether or not they are are coprime'
#check if the numbers are divisible by 2 or if both are 2
if (a % 2 != 0 and b % 2 != 0) or (a ==2 and b ==2):
classification = 'Coprime'
else:
classification = 'Not Coprime'
return classification
def coprime_test_loop():
'Asks users for two numbers then passes these numbers to function \
coprime which identifies the nuber as coprime or not and returns \
the classification for the user. After it asks the user if they would\
like to repeat the function.'
#ask for user to enter two nums
a2, b2 = input( 'Enter two numbers seperated by a space(e.g. 34 24) \
or enter "Stop Process" to end this process.').split()
#base case to end recursion
if a2 == 'Stop':
return 'Process Stopped'
else:
a2 = int(float(a2))
b2 = int(float(b2))
#calls function coprime, format output, loop function
result = coprime(a2,b2)
print(a2, ' and ', b2, ' are ', result)
return coprime_test_loop()
#test code
print(coprime_test_loop())
| true |
07079cd63c24d88847a4b4c6a6749c8c2dca2abb | AbhijeetSah/BasicPython | /DemoHiererchialInheritance.py | 446 | 4.15625 | 4 | #hiererchial Inheritance
class Shape:
def setValue(self, s):
self.s=s
class Square(Shape):
def area(self):
return self.s*self.s
class Circle(Shape):
def area(self):
return 3.14*self.s*self.s
sq= Square()
s= int(input("Enter the side of square "))
sq.setValue(s)
print("Area of square",sq.area())
cr= Circle()
r= int(input("Enter the radius of circle "))
cr.setValue(r)
print("Area of circle : ", cr.area()) | true |
7bf3778c0dd682739cec943e2f9550e01a517538 | itssamuelrowe/arpya | /session5/names_loop.py | 577 | 4.84375 | 5 | # 0 1 2 3
names = [
"Arpya Roy",
"Samuel Rowe",
"Sreem Chowdhary",
"Ayushmann Khurrana"
]
for name in names:
print(name)
"""
When you give a collection to a for loop, what Python does is create an iterator for the
collection. So what is an iterator? In the context of a for loop, an iterator is a special
object that takes each item in the collection and gives it to the for statement.
"""
# for variable in collection:
# block
# print("index 0 => " + names[0])
# print("index 1 => " + names[1])
# print("index 2 => " + names[2])
# print("index 3 => " + names[3]) | true |
3b32018a5f493a622d5aee4bd979813c15c7c86c | vanderzj/IT3038C | /Python/nameage.py | 819 | 4.15625 | 4 | import time
start_time = time.time()
#gets user's name and age
print('What is your name?')
myName = input()
print('Hello ' + myName + '. That is a good name. How old are you?')
myAge = input()
#Gives different responses based on the user's age.
if myAge < 13:
print("Learning young, that's good.")
elif myAge == 13:
print("Teenager Detected")
elif myAge > 13 and myAge <= 26:
print("Now you're a double teenager!")
elif myAge > 26 and myAge < 34:
print("Getting older...")
else:
print("You're probably older than Python!")
#prgmAge = time the program has been running
prgmAge = int(time.time() - start_time)
print(str(myAge) +"? That's funny, I'm only " + str(prgmAge) + " seconds old.")
print(" I wish I was " + str(int(myAge) * 2) + " years old.")
time.sleep(3)
print("I'm tired. Goodnight!") | true |
b598c4d34d7f60ad2a821efaed87e47d7ed16781 | vanderzj/IT3038C | /Python/TKinter_Practice/buttons.py | 1,002 | 4.53125 | 5 | # Imports tkinter, which is a built-in Python module used to make GUIs.
from tkinter import *
# Creates the window that the content of our script will sit in.
win = Tk()
# This function is being set up to give the button below functionality with the (command=) arguement.
# The Command function should be written as (command=x) instead of as (command=x()) like most other functions. If you include the parenthesies the function will run on program start by itself.
def myClick():
lbl1 = Label(win, text="Button was clicked.")
lbl1.pack()
# Creates a button object. The arguements here are (<location of button>, <text shown on button>, <horizontal size of button>, <vertical size of button>)
btn = Button(win, text="Click Me!", padx=50, pady=50, command=myClick)
# Puts the button into win
btn.pack()
# The .mainloop() part of this command starts the window's loop. This is what allows the program to run. Clicking the "X" on the window created by this script ends the loop.
win.mainloop() | true |
1f030e2f733874480af9f92425566e9f593dfe34 | ledbagholberton/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 605 | 4.375 | 4 | #!/usr/bin/python3
def add_integer(a, b=98):
""" Function that summ two numbers integer or float.
Args:
a: First parameter (integer or float)
b: Second paramenter (integer of float)
Returns:
Summ of a & b
"""
if a is None or (type(a) is not int and type(a) is not float):
raise TypeError("a must be an integer")
elif type(a) is float:
a = int(a)
if type(b) is not int and type(b) is not float:
raise TypeError("b must be an integer")
elif type(b) is float:
b = int(b)
c = a + b
return (c)
| true |
5b82dd7f7e00b9ed2a8ee39e194384eb32ccc3f0 | green-fox-academy/MartonG11 | /week-02/day-1/mile_to_km_converter.py | 273 | 4.4375 | 4 | # Write a program that asks for an integer that is a distance in kilometers,
# then it converts that value to miles and prints it
km = float(input('Put a kilometer to convert to miles: '))
factor = 0.621371192
miles = km * factor
print("The distance in miles is: ", miles) | true |
cc328013864be876f42b1b7c25117bc3ffcccb4a | green-fox-academy/MartonG11 | /week-02/day-2/swap_elements.py | 250 | 4.34375 | 4 | # - Create a variable named `abc`
# with the following content: `["first", "second", "third"]`
# - Swap the first and the third element of `abc`
abc = ["first", "second", "third"]
def swap(x):
x[0] , x[2] = x[2] , x[0]
print(x)
swap(abc) | true |
210519003481bc2545f6a2dfeab8c81ec67df223 | green-fox-academy/MartonG11 | /week-03/day-3/rainbow_box_function.py | 767 | 4.1875 | 4 | from tkinter import *
root = Tk()
canvas = Canvas(root, width='300', height='300')
canvas.pack()
# create a square drawing function that takes 2 parameters:
# the square size, and the fill color,
# and draws a square of that size and color to the center of the canvas.
# create a loop that fills the canvas with rainbow colored squares.
size1 = 145
color1 = "red"
size2 = 120
color2 = "yellow"
size3 = 100
color3 = "green"
size4 = 80
color4 = "blue"
size5 = 60
color5 = "purple"
def square_draw(x_size, x_color):
canvas.create_rectangle(150-(x_size), 150-(x_size),150+(x_size), 150+(x_size), fill=x_color)
square_draw(size1, color1)
square_draw(size2, color2)
square_draw(size3, color3)
square_draw(size4, color4)
square_draw(size5, color5)
root.mainloop() | true |
8b6d39bb03692cc8ff81dbfdd62d59ed51b3629f | green-fox-academy/MartonG11 | /week-03/day-3/center_box_function.py | 535 | 4.34375 | 4 | from tkinter import *
root = Tk()
canvas = Canvas(root, width='300', height='300')
canvas.pack()
# create a square drawing function that takes 1 parameter:
# the square size
# and draws a square of that size to the center of the canvas.
# draw 3 squares with that function.
size1 = 130
size2 = 100
size3 = 50
def draw_square(square_size):
canvas.create_rectangle(150-(square_size), 150-(square_size),150+(square_size), 150+(square_size), fill="green")
draw_square(size1)
draw_square(size2)
draw_square(size3)
root.mainloop() | true |
b500ce44e4652624e0b5f94e19da756ad190e217 | hkscy/algorithms | /Miscellaneous Algorithms/Palindrome Checker/palindrome.py | 2,216 | 4.25 | 4 | # Chris Hicks 2020
#
# Based on Microsoft Technical Interview question:
# "Given a string, write an algorithm that will determine if it is a palindrome"
# Input: string of characters, Output: True (palindrome) False (palindrome)
#
# What is a palindrome?
# - A sequence of characters which reads the same backward as forward
# - Sentence-length palindromes may be written when allowances are made for
# adjustments to capital letters, punctuation, and word dividers
#
# Some examples are "02022020":True , "Chris":False, , "Anna":True
# "Step on no pets":True, "Lobster Stew":False
#
# Can I use libraries? if so re for regular expressions could be used
# or methods and variables from string library and e.g. string.punctuation
import string as strings
import timeit
examples = {"02022020":True , "Chris":False, "Anna":True,
"Step on no pets":True, "Lobster Stew":False,
" ":True, "":True}
# In the permissive setting, return a string with no capitalisation or whitespace
def permissive(string):
string = string.casefold() # n comparisons
string = string.replace(" ", "") # n comparisons
return string
# Simply check whether all of the "opposite" characters in string have
# the same value. Wasteful since we're duplicating our effort.
def basic_is_palindrome(string):
return string == string[::-1]
# Can we do better? We can compare just n//2 elements
def fast_is_palindrome(string):
# If string has odd length than ignore middle character
n = len(string)
if n%2 != 0:
string = string[0:n//2]+string[n//2+1:]
for idx in range(n//2):
if string[idx] != string[-idx-1]:
return False
return True
def main():
for example in examples:
# If we want to be disregard punctuation and whitespace
example_clean = permissive(example)
if basic_is_palindrome(example_clean) == examples.get(example):
print("Basic method PASS for example \"{}\"".format(example))
else:
print("Basic method FAIL for example \"{}\"".format(example))
if fast_is_palindrome(example_clean) == examples.get(example):
print("Fast method PASS for example \"{}\"".format(example))
else:
print("Fast method FAIL for example \"{}\"".format(example))
print()
if __name__ == "__main__":
main()
| true |
f4891c92ba34699fe80a9d71f66a6ae13c39a75f | JosueOb/Taller1 | /Ejercicios/Ejercicio4-6.py | 1,577 | 4.15625 | 4 | from tkinter import *
root = Tk()
v = IntVar()
Label(root,
text="""Choose a programming language:""",
justify = LEFT,
padx = 20).pack()
Radiobutton(root,
text="Python",
padx = 20,
variable=v,
value=1).pack(anchor=W)
Radiobutton(root, text="Perl",
padx = 20,
variable=v,
value=2).pack(anchor=W)
mainloop()
root = Tk()
v = IntVar()
v.set(1) # initializing the choice, i.e. Python
languages = [
("Python",1),
("Perl",2),
("Java",3),
("C++",4),
("C",5)
]
def ShowChoice():
print (v.get())
Label(root, text="""Choose your favourite programming language:""",
justify = LEFT,
padx = 20).pack()
for txt, val in languages:
Radiobutton(root,
text=txt,
padx = 30,
variable=v,
command=ShowChoice,
value=val).pack(anchor=W)
mainloop()
root = Tk()
v = IntVar()
v.set(1) # initializing the choice, i.e. Python
languages = [
("Python",1),
("Perl",2),
("Java",3),
("C++",4),
("C",5)
]
def ShowChoice():
print (v.get())
Label(root,
text="""Escoja un lenguaje de programación:""",
justify = LEFT,
padx = 20).pack()
for txt, val in languages:
Radiobutton(root,
text=txt,
indicatoron =0,
width = 20,
padx = 20,
variable=v,
command=ShowChoice,
value=val).pack(anchor=W)
mainloop()
| true |
bffba3eb19fd92bfed2563216c3d7478a8b92fed | LitianZhou/Intro_Python | /ass_4.py | 2,635 | 4.15625 | 4 | # Part 1
while True:
RATE = 1.03
while True:
print("--------------------------------------")
start_tuition = float(input("Please type in the starting tuition: "))
if start_tuition <= 25000 and start_tuition >= 5000:
break
else:
print("The starting tuition should be between 5,000 and 25,000 inclusive, please enter a valid value.")
tuition = start_tuition
year = "year"
for i in range(1,6):
tuition = tuition*RATE
print("In " + str(i) + " " + year + ", the tuition will be $" + format(tuition, ',.2f') + ".")
year = "years"
foo = input("To calculate with other start tuition, type *yes* to continue, otherwise the program ends: ")
if(foo != "yes"):
break
# Part 2
print("\n_____________Part 2_______________")
while True:
print("-----------------------------------------")
rate = 1 + float(input("Please input the increment rate per year (enter as decimals): "))
#input start_tuition and validation check
while True:
start_tuition = float(input("Please type in the starting tuition: "))
if start_tuition <= 25000 and start_tuition >= 5000:
break
else:
print("ERROR: Starting tuition should be between 5,000 and 25,000 inclusive!")
#input first year + validation check
while True:
try:
first_year = int(input("Please enter the first year you are interested: "))
except ValueError:
print("ERROR: Please input an integer!")
continue
else:
if first_year < 1:
print("ERROR: Please input a integer at least 1")
else:
break
#input last year + validation check
while True:
try:
last_year = int(input("Please enter the last year you are interested: "))
except ValueError:
print("ERROR: Please input an integer!")
continue
else:
if last_year < first_year:
print("ERROR: Please input a integer greater than first year")
else:
break
# calculate and print
tuition = start_tuition
year = "year"
for i in range(1, last_year+1):
tuition = tuition*rate
if i >= first_year:
print("In " + str(i) + " " + year + ", the tuition will be $" + format(tuition, ',.2f') + ".")
year = "years"
foo = input("To calculate with other tuition and rate, type *yes* to continue, otherwise the program ends: ")
if(foo != "yes"):
break
| true |
cd9812c4bce5cf9755e99f06cc75db716499f0e1 | edek437/LPHW | /uy2.py | 876 | 4.125 | 4 | # understanding yield part 2
from random import sample
def get_data():
"""Return 3 random ints beetween 0 and 9"""
return sample(range(10),3)
def consume():
"""Displays a running average across lists of integers sent to it"""
running_sum=0
data_items_seen=0
while True:
data=yield
data_items_seen += len(data)
running_sum += sum(data)
print('The running average is {}'.format(running_sum / float(data_items_seen)))
def produce(consumer):
"""Produces a set of values and forwards them to the pre-defined consumer function"""
while True:
data=get_data()
print('Produced{}'.format(data))
consumer.send(data)
yield
#if __name__ == '__main__':
consumer = consume()
consumer.send(None)
producer = produce(consumer)
for _ in range(10):
print('Producing...')
next(producer)
| true |
3cdbde7f1435ef0fc65ab69b325fed08e1136216 | cakmakok/pygorithms | /string_rotation.py | 209 | 4.15625 | 4 | def is_substring(word1, word2):
return (word2 in word1) or (word1 in word2)
def string_rotation(word1, word2):
return is_substring(word2*2,word1)
print(string_rotation("waterbottle","erbottlewat"))
| true |
df61bd0ca36e962e134772f6d7d50200c7a3a7aa | phuongnguyen-ucb/LearnPythonTheHardWay | /battleship.py | 2,320 | 4.34375 | 4 | from random import randint
board = []
# Create a 5x5 board by making a list of 5 "0" and repeat it 5 times:
for element in range(5):
board.append(["O"] * 5)
# To print each outer list of a big list. 1 outer list = 1 row:
def print_board(board):
for row in board:
print " ".join(row) # to concatenate all the elements inside the list into one string => to make the board look pretty
print "Let's play Battleship!"
print_board(board) # display the board
# Assign a random location (random row & column) for my ship. This location will be hidden:
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
#print ship_row
#print ship_col
# User can play 4 turns before game over (turn starts from 0 to 3):
for turn in range(4):
# Ask user to guess my ship's location:
guess_row = int(raw_input("Guess Row: "))
guess_col = int(raw_input("Guess Column: "))
# A winning case:
if guess_row == ship_row and guess_col == ship_col: # raw_input will return a string => have to make (guess_row & guess_col) become integer to compare with number
print "Congratulations! You sunk my battleship!"
break # to get out of a loop and stop a game if user wins
# Wrong cases:
else:
# If user's guess is invalid or off the board:
if guess_row > len(board)-1 or guess_col > len(board[0])-1:
print "Oops, that's not even in the ocean."
# If user already guessed a specific location:
elif board[guess_row][guess_col] == "X":
print "You guessed that one already."
# If user guess it wrong:
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X" # mark X on a location that is already guessed
# Notify user when they play all 4 turns:
if turn == 3:
print "GAME OVER!!! Too bad you just lost your last chance :(. Try again :)"
break # to end a game without displaying turn and a board
# Display user's turn:
if turn == 0:
print "You've played ", turn + 1, "turn"
else:
print "You've played ", turn + 1, "turns"
# Display the board again:
print_board(board) | true |
ac4ecdf8ffd9532f0254c6d848ba74a886122ed8 | mvoecks/CSCI5448 | /OO Project 2/Source Code/Feline.py | 2,173 | 4.125 | 4 | import abc
from Animal import Animal
from roamBehaviorAbstract import climbTree
from roamBehaviorAbstract import randomAction
''' The roaming behavior for Felines can either be to climb a tree or to do a
random action. Therefore we create two roamBehaviorAbstract variables,
climbTree and randomAction that we will set appropriately in the subclasses
for Feline.
'''
climbBehavior = climbTree()
randomBehavior = randomAction()
''' Create a abstract class Feline which extends Animal. This class sets the
doRoam behavior to the fly class, and impliments the eat and sleep functions
defined in the abstract Animal class
'''
class Feline(Animal):
__metaclass__ = abc.ABCMeta
''' Initializing a Feline object and set its name, type, and behavior in
the superclass Animal
'''
def __init__(self, name, type, behavior):
super().__init__(name, type)
super().setRoamBehavior(behavior)
''' All Felines sleep and eat the same, so initialize those function Here
'''
def sleep(self):
print(super().getType() + "-" + super().getName() +": Back to my natural state, Zzzzz.....")
def eat(self):
print(super().getType() + "-" + super().getName() +": Purrrr, some food. Don't mind if I do.")
''' Create a class for the cats, which are an extension of Felines. In this
class we initialize a cat by giving it a name and defining its behavior,
which is to do a random action. This also defines how cats make noise.
'''
class Cat(Feline):
def __init__(self, name):
super().__init__(name, 'Cat', randomBehavior)
def makeNoise(self):
print(super().getType() + "-" + super().getName() +": Meh, I'm just a cat.")
''' Create a class for the lions, which are an extension of Felines. In This
class we initialize a lion by givig it a name and defining its behavior,
which is to climb a tree. This also defines how lions make noise
'''
class Lion(Feline):
def __init__(self, name):
super().__init__(name, 'Lion', climbBehavior)
def makeNoise(self):
print(super().getType() + "-" + super().getName() +": ROAR! Behold the mighty lion!")
| true |
83424e65bc9b7240d3ff929a22884e2ebef578d3 | asvkarthick/LearnPython | /GUI/tkinter/tkinter-label-02.py | 620 | 4.25 | 4 | #!/usr/bin/python3
# Author: Karthick Kumaran <asvkarthick@gmail.com>
# Simple GUI Program with just a window and a label
import tkinter as tk
from tkinter import ttk
# Create instance
win = tk.Tk()
# Set the title for the window
win.title("Python GUI with a label")
# Add a label
label = ttk.Label(win, text = "Label in GUI")
label.grid(column = 0, row = 0)
def click_button():
button.configure(text = "Clicked")
label.configure(foreground = 'red')
label.configure(text = 'Button clicked')
button = ttk.Button(win, text = "Click Here", command = click_button)
button.grid(column = 1, row = 0)
# Start the GUI
win.mainloop()
| true |
ee3acb288c29099d6336e9d5fd0b7a54f71573fe | asvkarthick/LearnPython | /02-function/function-05.py | 218 | 4.125 | 4 | #!/usr/bin/python
# Author: Karthick Kumaran <asvkarthick@gmail.com>
# Function with variable number of arguments
def print_args(*args):
if len(args):
for i in args:
print(i);
else:
print('No arguments passed')
print_args(1, 2, 3)
| true |
8fa01eb2322cd9c2d82e043aedd950a408c46901 | optionalg/challenges-leetcode-interesting | /degree-of-an-array/test.py | 2,851 | 4.15625 | 4 | #!/usr/bin/env python
##-------------------------------------------------------------------
## @copyright 2017 brain.dennyzhang.com
## Licensed under MIT
## https://www.dennyzhang.com/wp-content/mit_license.txt
##
## File: test.py
## Author : Denny <http://brain.dennyzhang.com/contact>
## Tags:
## Description:
## https://leetcode.com/problems/degree-of-an-array/description/
## ,-----------
## | Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
## |
## | Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
## |
## | Example 1:
## | Input: [1, 2, 2, 3, 1]
## | Output: 2
## | Explanation:
## | The input array has a degree of 2 because both elements 1 and 2 appear twice.
## | Of the subarrays that have the same degree:
## | [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
## | The shortest length is 2. So return 2.
## | Example 2:
## | Input: [1,2,2,3,1,4,2]
## | Output: 6
## | Note:
## |
## | nums.length will be between 1 and 50,000.
## | nums[i] will be an integer between 0 and 49,999.
## `-----------
##
## Basic Idea:
## Complexity:
## --
## Created : <2017-10-16>
## Updated: Time-stamp: <2017-10-23 18:22:06>
##-------------------------------------------------------------------
class Solution(object):
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# find the degree and digits
digit_dict = {}
for i in range(0, len(nums)):
num = nums[i]
if digit_dict.has_key(num) is False:
digit_dict[num] = (1, [i])
else:
(count, l) = digit_dict[num]
l.append(i)
digit_dict[num] = (count+1, l)
degree = 0
for num in digit_dict.keys():
(count, _l) = digit_dict[num]
if count > degree:
degree = count
min_length = 65535
degree_digits = []
for num in digit_dict.keys():
(count, l) = digit_dict[num]
if count == degree:
start_index = l[0]
end_index = l[-1]
length = end_index - start_index + 1
if length < min_length:
min_length = length
# print "degree: %d, degree_digits: %s" % (degree, degree_digits)
# loop the example, only start from digits which are in the target list
return min_length
if __name__ == '__main__':
s = Solution()
print s.findShortestSubArray([1, 2, 2, 3, 1])
print s.findShortestSubArray([1,2,2,3,1,4,2])
## File: test.py ends
| true |
e24f2c5e5688efbfc9a8e1c041765efc22fa0cc0 | optionalg/challenges-leetcode-interesting | /reverse-words-in-a-string/test.py | 1,323 | 4.28125 | 4 | #!/usr/bin/env python
##-------------------------------------------------------------------
## @copyright 2017 brain.dennyzhang.com
## Licensed under MIT
## https://www.dennyzhang.com/wp-content/mit_license.txt
##
## File: test.py
## Author : Denny <http://brain.dennyzhang.com/contact>
## Tags:
## Description:
## https://leetcode.com/problems/reverse-words-in-a-string/description/
## ,-----------
## | Given an input string, reverse the string word by word.
## |
## | For example,
## | Given s = "the sky is blue",
## | return "blue is sky the".
## |
## | Update (2015-02-12):
## | For C programmers: Try to solve it in-place in O(1) space.
## `-----------
##
## --
## Created : <2017-10-16>
## Updated: Time-stamp: <2017-10-26 21:41:00>
##-------------------------------------------------------------------
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
## Basic Idea:
## the sky is blue
## eulb si yks eht
## blue is sky the
## Complexity: Time O(n), Space O(1)
# reverse
s = s[::-1]
res = []
for item in s.split(" "):
if item == "":
continue
res.append(item[::-1])
return ' '.join(res)
| true |
37cc4a21931e88c5558809dfb756e01e01a92d10 | brianpeterson28/Princeton_Python_SWD | /bep_exercises/chapter1.2/contcompinterest/contcompinterest.py | 2,227 | 4.3125 | 4 | '''
Author: Brian Peterson | https://github.com/brianpeterson28
Creative Exercise 1.2.21 - Intro to Programming In Python
'''
import math
import decimal
print("Calculates Future Value @ Continuously Compounded Rate.")
def askForInterestRate():
while True:
try:
interestrate = float(input("Enter interest rate: "))
while (interestrate >= 1) or (interestrate < 0):
print("Please enter the interest rate as a decimal greater than zero but less than one.")
interestrate = float(input("Enter interest rate: "))
break
except ValueError:
print("That input is not valid.")
print("Please enter the interest rate as a decimal greater than zero but less than one.")
return interestrate
def askForYears():
while True:
try:
years = int(input("Enter number of years: "))
while (years < 0) or (type(years) != type(1)):
print("The number of years must be an integer greater than zero.")
years = int(input("Enter number of years:"))
break
except ValueError:
print("That is not a valid entry.")
print("Please enter the number of years as a non-negative integer.")
return years
def askForPrincipal():
while True:
try:
principal = float(input("Enter amount of principal: "))
while principal <= 0:
print("The principal amount must be greater than zero.")
principal = float(input("Enter amount of principal: "))
break
except ValueError:
print("That is not a valid entry.")
print("Please enter a principal amount that is greater than zero.")
print("Also, please do not include any commas.")
return principal
def calculateFutureValue(interestrate, years, principal):
futureValue = principal * (math.exp(interestrate * years))
return futureValue
'''
Excellent article explaining how to use decimal package
to do math with and round floating point numbers:
https://pymotw.com/3/decimal/
'''
def displayResult(futurevalue):
futurevalue = decimal.Decimal(futurevalue)
print("The future value is ${:,.2f}.".format(futurevalue))
def main():
principal = askForPrincipal()
years = askForYears()
inerestRate = askForInterestRate()
futurevalue = calculateFutureValue(inerestRate, years, principal)
displayResult(futurevalue)
if __name__ == "__main__":
main()
| true |
ad8dd825f3f56a5773b4d0bb79f27a3738c13533 | crishabhkumar/Python-Learning | /Assignments/Trailing Zeroes.py | 299 | 4.15625 | 4 | #find and return number of trailing 0s in n factorial
#without calculation n factorial
n = int(input("Please enter a number:"))
def trailingZeros2(n):
result = 0
power = 5
while(n >= power):
result += n // power
power *= 5
return result
print(trailingZeros2(n))
| true |
60f2c7a1930e69268bd41975cc3778e545ee9100 | sudhansom/python_sda | /python_fundamentals/10-functions/functions-exercise-01.py | 306 | 4.3125 | 4 | # write a function that returns the biggest of all the three given numbers
def max_of_three(a, b, c):
if a > b:
if a > c:
return a
else:
return c
else:
if b > c:
return b
else:
return c
print(max_of_three(3, 7, 3)) | true |
10f075ee5aff42884240b0a5070d649d3c71d972 | sudhansom/python_sda | /python_fundamentals/06-basic-string-operations/strings-exercise.py | 420 | 4.21875 | 4 | # assigning a string value to a string of length more than 10 letters
string = "hello"
reminder = len(string) % 2
print(reminder)
number_of_letters = 2
middle_index = int(len(string)/2)
start_index = middle_index - number_of_letters
end_index = middle_index + number_of_letters + reminder
result = string[start_index:end_index]
print(f"Result: {result}")
# just for a prictice
r = range(0, 20,2)
print(r)
print(r[:5])
| true |
8a21cc7dc1f16ae2715479dbc875d4c5e0696f6a | sudhansom/python_sda | /python_fundamentals/00-python-HomePractice/w3resource/conditions-statements-loops/problem43.py | 386 | 4.28125 | 4 | """
Write a Python program to create the multiplication table (from 1 to 10) of a number. Go to the editor
Expected Output:
Input a number: 6
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60
"""
user_input = int(input("Enter the number: ").strip())
for i in range(1, 11):
print(f"{user_input} x {i} = {user_input * i}") | true |
8c8ba8bbd6230a3c045971542159acb1ef584596 | dlu270/A-First-Look-at-Iteration | /Problem 3-DL.py | 683 | 4.65625 | 5 | #Daniel Lu
#08/08/2020
#This program asks the user for the number of sides of a shape, the length of sides and the color. It then draws the shape and colors it.
import turtle
wn = turtle.Screen()
bob = turtle.Turtle()
sides = input ("What are the number of sides of the polygon?: ")
length = input ("What is the length of the sides of the polygon?: ")
line_color = input ("What is the line color of the polygon?: ")
fill_color = input ("What is the fill color of the polygon?: ")
bob.color(line_color)
bob.fillcolor(fill_color)
bob.begin_fill()
for i in range (int(sides)):
bob.forward (int(length))
bob.left (int(360) / int(sides))
bob.end_fill()
| true |
7ab66c17162421433ec712ebb1bbad0c0afbdd0b | Dianajarenga/PythonClass | /PythonClass/student.py | 1,075 | 4.59375 | 5 | class Student:
school="Akirachix"
#to create a class use a class keyword
#start the class name with a capital letter.if it has more than one letter capitalize each word
#do not include spaces
#many modules in a directory form a package
#when you save your code oin a .py file its called a module
#to import a class from any module use . notation eg-from module import class name (import convection) standard libraries,built in modules.
#object creation from class instance creation
#def__init__(Self,name,age) creating a class contructor self is refers to instance of class
def __init__(self,name,age,unit):
self.name=name#assignning variables to class instance
self.age=age
self.unit=unit
def speak(self):
return f"Hello my name is {self.name} and I am {self.age} years old"
def learn(self):
return f"I am studying {self.unit} in{self.school}"
#create class Car : give it 4 attributes(),behaviour()3,
#create class Dog attributes(3) ,method(1)
#bank.py class Account(3)method(2)
| true |
6096598f70d386090efba0a31f1be8a6a483a39e | johnashu/Various-Sorting-and-SEarching-Algorithms | /search/interpolation.py | 1,970 | 4.1875 | 4 | """
Interpolation search is an improved variant of binary search. This search algorithm works on the probing position of the required value. For this algorithm to work properly, the data collection should be in a sorted form and equally distributed.
Binary search has a huge advantage of time complexity over linear search. Linear search has worst-case complexity of Ο(n) whereas binary search has Ο(log n).
Step 1 − Start searching data from middle of the list.
Step 2 − If it is a match, return the index of the item, and exit.
Step 3 − If it is not a match, probe position.
Step 4 − Divide the list using probing formula and find the new midle.
Step 5 − If data is greater than middle, search in higher sub-list.
Step 6 − If data is smaller than middle, search in lower sub-list.
Step 7 − Repeat until match.
"""
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
d = {'0': '0', '1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7',
'8': '8', '9': '9', '10': 'A', '11': 'B', '12': 'C', '13': 'D', '14': 'E', '15': 'F'}
x = 0
def maf_interpolation(array, value):
"""
In this algorithm, we want to find whether element x belongs to a set of numbers stored in an array numbers[]. Where l and r represent the left and right index of a sub-array in which searching operation should be performed.
"""
err = "Not Found"
lo = 0
mid = -1
hi = len(array) - 1
while value != mid:
if lo == hi or array[lo] == a[hi]:
print("No Dice! Target NOT Found!")
break
mid = lo + ((hi - lo) // (array[hi] - array[lo])) * (value - array[lo])
if array[mid] == value:
return print("Success, Found in Index: ", mid)
break
elif array[mid] < value:
lo = mid + 1
elif a[mid] > value:
hi = mid - 1
maf_interpolation(a, x)
| true |
11a2948ed09d97d32565e20dcb6ef0f7158a879f | zosopick/mawpy | /Chapters 1 to 5/Chapter 1/1-5 Turtle spiral.py | 498 | 4.28125 | 4 | '''
Excersise 1-5: Turtle spiral
Make a funciton to draw 60 squares, turning 5 degrees after each
square and making each successive square bigger. Start at a length
of 5 and increment 5 units every square.
'''
from turtle import *
shape('turtle')
speed(10)
length=5
def turtle_spiral():
length=5
for i in range(250):
for j in range(4):
forward(length)
right(90)
right(10)
length+=5
turtle_spiral()
| true |
2e432eac8fbcb96bdd568ac0ebb83f08761bc912 | zosopick/mawpy | /Chapters 1 to 5/Chapter 5/Exercise__5_1_A_spin_cycle/Exercise__5_1_A_spin_cycle.pyde | 771 | 4.1875 | 4 | '''
Exercise 5-1: A spin cycle
Create a circle of equilateral triangles in a processing sketch and
rotate them using the rotate() function
'''
t=0
def setup():
size(1000,1000)
rectMode(CORNERS) #This keeps the squares rotating around the center
#also, one can use CORNER or CORNERS
def draw():
global t
background(255)
translate(width/2,height/2)
rotate(radians(t))
for i in range(12):
pushMatrix()
translate(200,0)
rotate(radians(5*t))#If we add this, the squares rotate faster
tri(50)
popMatrix()
rotate(radians(360/12))
t+=1
def tri(length):
triangle(0,-length, -length*sqrt(3)/2, length/2, length*sqrt(3)/2, length/2)
| true |
bf73c880b2704f1ef37080e4bb18ef0777d6ff5a | vighneshdeepweb/Turtle-corona | /Turtle-Covid/covid.py | 676 | 4.125 | 4 | import turtle
#create a screen
screen = turtle.Screen()
#create a drawer for drawing
drawer = turtle.Turtle()
#Set the background color of the screen
screen.bgcolor("black")
#For set a Background,color,speed,pensize and color of the drawer
drawer.pencolor("darkgreen")
drawer.pensize(3)
drawer1 = 0
drawer2 = 0
drawer.speed(0)
drawer.goto(0, 200)
drawer.pendown()
#Create while loop for drawing Corona Virus Shape.
while True:
drawer.forward(drawer1)
drawer.right(drawer2)
drawer1 += 3
drawer2 += 1
if drawer2 == 210:
break
drawer.ht()
# For Holding the main Screen
screen.mainloop()
| true |
d10975f40f51444b69afcee04b30a0347faf0da5 | veldc/basics | /labs/02_basic_datatypes/02_04_temp.py | 402 | 4.34375 | 4 | '''
Fahrenheit to Celsius:
Write the necessary code to read a degree in Fahrenheit from the console
then convert it to Celsius and print it to the console.
C = (F - 32) * (5 / 9)
Output should read like - "81.32 degrees fahrenheit = 27.4 degrees celsius"
'''
Farh = float(input("Enter degree Farh: "))
Celsius = (Farh-32)*(5/9)
print (Farh, "degress fahrenheid = ",Celsius, "degress celsius") | true |
776fa8276987922284cac8b4a28c8e974242f0ee | veldc/basics | /labs/02_basic_datatypes/02_05_convert.py | 799 | 4.40625 | 4 | '''
Demonstrate how to:
1) Convert an int to a float
2) Convert a float to an int
3) Perform floor division using a float and an int.
4) Use two user inputted values to perform multiplication.
Take note of what information is lost when some conversions take place.
'''
# int to float
Num = 8
Div = float(Num)
print(Div)
# float to int
Num = 8
Div = 10
devision = int(Num/Div)
print(devision)
#Floor division
NumInt = 30
NumFl = 9.3
print(NumInt//NumFl)
'''#user input int
InputUser1 = int(input("Enter number: "))
InputUser2 = int(input("Enter another number: "))
Multi=(InputUser1*InputUser2)
print(Multi)'''
#user input float
InputUser1 = float(input("Enter number: "))
InputUser2 = float(input("Enter another number: "))
Multi=int((InputUser1*InputUser2))
print(Multi) | true |
764e49079883e2419c2ed66de6d3b883f3074b10 | VanessaVanG/number_game | /racecar.py | 1,536 | 4.3125 | 4 | '''OK, let's combine everything we've done so far into one challenge!
First, create a class named RaceCar. In the __init__ for the class, take arguments for color and fuel_remaining. Be sure to set these as attributes on the instance.
Also, use setattr to take any other keyword arguments that come in.'''
class RaceCar:
def __init__(self, color, fuel_remaining, laps=0, **kwargs):
self.color = color
self.fuel_remaining = fuel_remaining
self.laps = laps
for key, value in kwargs.items():
setattr(self, key, value)
'''OK, now let's add a method named run_lap. It'll take a length argument. It should reduce the fuel_remaining attribute by length multiplied by 0.125.
Oh, and add a laps attribute to the class, set to 0, and increment it each time the run_lap method is called.'''
def run_lap(self, length):
self.fuel_remaining -= (length * 0.125)
self.laps += 1
'''Great! One last thing.
In Python, attributes defined on the class, but not an instance, are universal. So if you change the value of the attribute, any instance that doesn't have it set explicitly will have its value changed, too!
For example, right now, if we made a RaceCar instance named red_car, then did RaceCar.laps = 10, red_car.laps would be 10!
To prevent this, be sure to set the laps attribute inside of your __init__ method (it doesn't have to be a keyword argument, though). If you already did it, just hit that "run" button and you're good to go!'''
##I had already done it :)
| true |
30288a48048f82daf25da88ed697364d86d0fc4d | OliverTarrant17/CMEECourseWork | /Week2/Code/basic_io.py | 1,589 | 4.21875 | 4 | #! usr/bin/python
"""Author - Oliver Tarrant
This file gives the example code for opening a file for reading using python.
Then the code writes a new file called testout.txt which is the output of 1-100
and saves this file in Sandbox folder (see below). Finally the code gives an example of
storing objects for later use. In this example my_dictionary is stored as the file testp.p
in sandbox. Pickle is used to serialize the objects hieracy"""
########################
# FILE INPUT
########################
# Open a file for reading
f = open('../Sandbox/test.txt', 'r')
# use "implicit" for loop:
# if the object is a file, python will cycle over lines
for line in f:
print line, # the "," prevents adding a new line
# close the file
f.close()
# same example, skip blank lines
f = open('../Sandbox/test.txt', 'r')
for line in f:
if len(line.strip()) > 0: #removes trailing and leading spaces from line and determines if it is non blank
print line,
f.close()
#################
# FILE OUTPUT
#################
list_to_save = range(100)
f = open('../Sandbox/testout.txt','w')
for i in list_to_save:
f.write(str(i) + '\n') ## Add a new line at the end
f.close()
####################
# STORING OBJECTS
####################
# To save an object (even complex) for later use
my_dictionary = {"a key": 10, "another key": 11}
import pickle
f = open('../Sandbox/testp.p','wb') ## note the b: accept binary files
pickle.dump(my_dictionary, f)
f.close()
## Load the data again
f = open('../Sandbox/testp.p','rb')
another_dictionary = pickle.load(f)
f.close()
print another_dictionary
| true |
e80b0d4d97c6cce390144e17307a65a7fb0cced1 | DroidFreak32/PythonLab | /p13.py | 2,590 | 4.75 | 5 | # p13.py
"""
Design a class named Account that contains:
* A private int data field named id for the account.
* A private float data field named balance for the account.
* A private float data field named annualInterestRate that stores the current interest rate.
* A constructor that creates an account with the specified id (default 0), initial balance (default 100), and annual interest rate (default 0).
* The accessor and mutator methods for id , balance , and annualInterestRate .
* A method named getMonthlyInterestRate() that returns the monthly interest rate.
* A method named getMonthlyInterest() that returns the monthly interest.
* A method named withdraws that withdraws a specified amount from the account.
* A method named deposit that deposits a specified amount to the account.
(Hint: The method getMonthlyInterest() is to return the monthly interest amount, not the interest rate. Use this formula to calculate the monthly interest: balance*monthlyInterestRate. monthlyInterestRate is annualInterestRate / 12 . Note that annualInterestRate is a percent (like 4.5%). You need to divide it by 100 .)
Write a test program that creates an Account object with an account id of 1122, a balance of $20,000, and an annual interest rate of 4.5%. Use the withdraw method to withdraw $2,500, use the deposit method to deposit $3,000, and print the id, balance, monthly interest rate, and monthly interest.
"""
class Account:
def __init__(self,id=0,balance=100.0,annualInterestRate=0.0):
self.__id=id
self.__balance=balance
self.__annualInterestRate=annualInterestRate
def getId(self): #Accessor Functions
return self.__id
def getBalance(self):
return self.__balance
def getannualInterestRate(self):
return self.__annualInterestRate
def setId(self,id): #Mutator Fucntions
self.__id=id
def setBalance(self,balance):
self.__balance=balance
def setannualInterestRate(self,annualInterestRate):
self.__annualInterestRate=annualInterestRate
def getMonthlyInterestRate(self):
return self.__annualInterestRate/(12*100)
def getMonthlyInterest(self):
return self.__balance*self.getMonthlyInterestRate()
def withdraw(self,amt):
self.__balance-=amt
def deposit(self,amt):
self.__balance+=amt
a=Account(1122,20000,4.5)
a.withdraw(2500)
a.deposit(3000)
print("Id:",a.getId()," Balance:",a.getBalance()," Monthly Interest Rate:",a.getMonthlyInterestRate()," Monthly Interest:",a.getMonthlyInterest())
#############################################
| true |
650c23952ab2978697916954ed04761ed800330c | DroidFreak32/PythonLab | /p09.py | 592 | 4.1875 | 4 | # p09.py
'''
Consider two strings, String1 and String2 and display the merged_string as output. The merged_string should be the capital letters from both the strings in the order they appear. Sample Input: String1: I Like C String2: Mary Likes Python Merged_string should be ILCMLP
'''
String1=input("Enter string 1:")
String2=input("Enter string 2:")
merged_string=""
for ch in String1:
if ch.isupper():
merged_string=merged_string+ch
for ch in String2:
if ch.isupper():
merged_string=merged_string+ch
print(merged_string)
#############################################
| true |
64e179dae3eada5e76890da5c412dacddab81a1e | TenckHitomi/turtle-racing | /racing_project.py | 2,391 | 4.3125 | 4 | import turtle
import time
import random
WIDTH, HEIGHT = 500, 500
COLORS = ['red', 'green', 'blue', 'orange', 'yellow', 'black', 'purple', 'pink', 'brown', 'cyan']
def get_number_of_racers():
"""Input number of turtles you want to show up on the screen"""
racers = 0
while True:
racers = input("Enter the number of racers (2 - 10): ")
if racers.isdigit(): #Checks if the input is a digit for # of racers. If not prompts for another input
racers = int(racers)
else:
print('Input is not numeric... Try again.')
continue
if 2 <= racers <= 10: #Checks input of user to see if it falls between 2 & 10
return racers
else:
print('Number not in range of 2-10...Try again.')
def race(colors): #Create colored turtles
turtles = create_turtles(colors)
while True: #Randomly pass a range through each turtle to determine pixels it moves. The further apart the bigger the gap.
for racer in turtles:
distance = random.randrange(1, 20)
racer.forward(distance)
x, y = racer.pos() #Returns index of first turtle to cross the finish line and returns color value
if y >= HEIGHT // 2 -10:
return colors[turtles.index(racer)]
def create_turtles(colors): #Creates Turtle list and evenly spaces each turtle on the screen from each other.
turtles = []
spacingx = WIDTH // len(colors) + 1
for i, color in enumerate(colors):
racer = turtle.Turtle()
racer.color(color)
racer.shape('turtle')
racer.left(90) #Rotates the turtles to look up on the screen
racer.penup()
racer.setpos(-WIDTH//2 + (i + 1) * spacingx, -HEIGHT//2 + 20)
racer.pendown()
turtles.append(racer)
return turtles
def init_turtle():
"""Produces window on screen"""
screen = turtle.Screen()
screen.setup(WIDTH , HEIGHT)
screen.title('Turtle Racing!') #Sets specific name you want to display on window
racers = get_number_of_racers() #Returns the number of racers after all conditionals have been passed
init_turtle()
random.shuffle(COLORS)
colors = COLORS[:racers]
winner = race(colors)
print(f"The winner is the {winner.title()} turtle.")
time.sleep(5) #Python leaves window open for 5 seconds after race finishes so you can see results on screen
| true |
f5c0aa56ad89771487550747ea9edaa2656c0e0a | carlshan/design-and-analysis-of-algorithms-part-1 | /coursework/week2/quicksort.py | 1,554 | 4.28125 | 4 |
def choose_pivot(array, length):
return array[0], 0
def swap(array, i, j):
temp = array[i]
array[i] = array[j]
array[j] = temp
def partition(array, low, high):
pivot = array[low]
i, j = low + 1, high - 1 # initializes i to be first position after pivot and j to be last index
while True:
# If the current value we're looking at is larger than the pivot
# it's in the right place (right side of pivot) and we can move left,
# to the next element.
# We also need to make sure we haven't surpassed the low pointer, since that
# indicates we have already moved all the elements to their correct side of the pivot
while (i <= j and array[j] >= pivot):
j -= 1
# Opposite process of the one above
while (i <= j and array[i] <= pivot):
i += 1
# We either found a value for both j and i that is out of order
# in which case we swap and continue
# or i is higher than j, in which case we exit the loop
# after swapping the pivot into its rightful position
if i <= j:
swap(array, i, j)
# The loop continues
else: # everything has been partitioned
swap(array, low, j)
return j
def quicksort(array, low, high):
if high - low <= 1: return array
part = partition(array, low, high)
quicksort(array, low, part)
quicksort(array, part + 1, high)
return array
test = [3, 8, 2, 5, 1, 4, 7, 6]
print(quicksort(test, 0, len(test))) | true |
7c885c274f4103db153970a6ce1476cf415c790e | Mkaif-Agb/Python_3 | /zip.py | 398 | 4.46875 | 4 | first_name = ["Jack", "Tom", "Dwayne"]
last_name = ["Ryan","Holland", "Johnson"]
name = zip(first_name,last_name)
for a,b in name:
print(a,b)
def pallindrome():
while True:
string=input("Enter the string or number you want to check")
if string == string[::-1]:
print("It is a pallindrome")
else:
print("It is not a pallindrome")
pallindrome() | true |
0af9c97699b04830aa12069d4258c5725f8f0c35 | sheriline/python | /D11/Activities/friend.py | 562 | 4.21875 | 4 | """
Elijah
Make a program that filters a list of strings and
returns a dictionary with your friends and
foes respectively.
If a name has exactly 4 letters in it, you can
be sure that it has to be a friend of yours!
Otherwise, you can be sure he's not...
Output = {
"Ryan":"friend", "Kieran":"foe",
"Jason":"foe", "Yous":"friend"
}
"""
names = ["Ryan", "Kieran", "Jason", "Yous"]
friend_or_foe = {name: "friend" if len(name) == 4 else "foe" for name in names}
print(friend_or_foe)
# {'Ryan': 'friend', 'Kieran': 'foe', 'Jason': 'foe', 'Yous': 'friend'}
| true |
030162330c0295f35315dd1d90a688b293a39759 | sheriline/python | /D1 D2/ifstatement.py | 731 | 4.3125 | 4 | #!/usr/bin/env python3.7
#example
# gender = input("Gender? ")
# if gender == "male" or gender == "Male":
# print("Your cat is male")
# else:
# print("Your cat is female")
# age = int(input("Age of your cat? "))
# if age < 5:
# print("Your cat is young.")
# else:
# print("Your cat is adult.")
#exercises
print("""
Make a program that asks the number between 1 and 10\.
If the number is out of range the program should display "invalid number".
""")
number = input("Input a number between 1 and 10: ")
if int(number) > 10:
print("invalid number")
else:
print("valid number")
print("\n")
print("Make a program that asks a password.\n")
password = input("Please enter your password: ")
print(password)
| true |
464ddc137e89538fd0a5cc63b58bfc837bdf06c5 | scotttct/tamuk | /Python/Python_Abs_Begin/Mod3_Conditionals/3_5_Math_3.py | 787 | 4.59375 | 5 | # Task 3
# PROJECT: IMPROVED MULTIPLYING CALCULATOR FUNCTION
# putting together conditionals, input casting and math
# update the multiply() function to multiply or divide
# single parameter is operator with arguments of * or / operator
# default operator is "*" (multiply)
# return the result of multiplication or division
# if operator other than "*" or "/" then return "Invalid Operator"
# [ ] create improved multiply() function and test with /, no argument, and an invalid operator ($)
def multiply(operator):
x = float(input('Enter number 1: '))
y = float(input('Enter number 2: '))
if operator == "*":
return x * y
elif operator == "/":
return x / y
else:
return "invalid operator"
print(multiply(input("Enter '/' or '*': ")))
| true |
a8f769fc11e575144fed429fd57165f9b318ee36 | scotttct/tamuk | /Python/Python_Abs_Begin/Mod4_Nested/4_3-7_1-While_True.py | 1,132 | 4.1875 | 4 | # Task 1
# WHILE TRUE
# [ ] Program: Get a name forever ...or until done
# create variable, familar_name, and assign it an empty string ("")
# use while True:
# ask for user input for familar_name (common name friends/family use)
# keep asking until given a non-blank/non-space alphabetical name is received (Hint: Boolean string test)
# break loop and print a greeting using familar_name
# [ ] create Get Name program
# familar_name = ""
# while True:
# familiar_name = input ("Enter your commonly used name,something your friends or family use: ")
# if familiar_name.isalpha():
# print ("Hi",familiar_name.capitalize() + "!", "I am glad you are alive and well!")
# break
# elif not familiar_name.isalpha:
# print("keep going\n")
# else:
# break
#################################33
#2nd Try
def familiar_name():
while True:
name_input = input("What's a common name your friends and family use?")
if name_input.isalpha():
break
else:
print()
print()
print("Hey " + name_input.capitalize())
familiar_name() | true |
a2d480068f763e0465022ea3ed208a4b4889ac4a | scotttct/tamuk | /Homework/Homework1.py | 1,702 | 4.53125 | 5 | # Write a program that prints the numbers from 1 to 100.
# But for multiples of three print “Fizz” instead of the number
# and for the multiples of five print “Buzz”.
# For numbers which are multiples of both three and five print “FizzBuzz”."
# for i in range(0, 101):
# print(i)
# print()
# for t in range(0, 101, 3):
# print(t)
# print()
# for f in range(0, 101, 5):
# f="fizz"
# print(f)
###################################################################
# prints odd numbers as a template for creating a function to perform the task of printing by 3 and replace
# def even_numbers(number):
# for i in range(number):
# if i == 0:
# continue
# elif i%2 == 0:
# print(i)
# else:
# continue
# print(even_numbers(101))
#create a function that prints all the necessary assignment parameters
#This attempt printed biff only
# def nums(number1, number2):
# for i in range(number1, number2):
# While i in range(number1, number2, 3)
# print("biff")
# elif:
# continue
# print(nums(1,101))
#another attempt that printed all 1's
# i = 1
# while i < 101:
# print(i)
# if (i == 3):
# print("biff")
# elif (1==5):
# print("baff")
# elif (i==3 or i==5):
# print("biffbaff")
# i += 1
# trying for nested for loops, taking from python documentation and modified
for n in range(1, 101):
print(n)
if n in range(1,101,3):
print("biff")
elif n in range(1,101,5):
print('baff')
elif n in range(1, 101, 3) or n in range(1,101,5): #this line does not work
print("biffbaff")
# ... else:
# ... # loop fell through without finding a factor
# ... print(n, 'is a prime number') | true |
9f5ab86e2e150066f02dacc8d1c35defabc1115f | scotttct/tamuk | /Python/Python_Abs_Begin/Mod1/p1_2.py | 280 | 4.125 | 4 | # examples of printing strings with single and double quotes
# print('strings go in single')
# print("or double quotes")
# printing an Integer with python: No quotes in integers/numbers
print(299)
# printing a string made of Integer (number) characters with python
print("2017") | true |
ec67d5050211e27b595231fa5f5f3ae31011b821 | palaciosdiego/pythoniseasy | /src/fizzBuzzAssignment.py | 630 | 4.15625 | 4 | def isPrime(number):
# prime number is always greater than 1
if number > 1:
for i in range(2, number):
if (number % i) == 0:
return False
# break
else:
return True
# if the entered number is less than or equal to 1
# then it is not prime number
else:
return False
for num in range(1, 101):
if(num % 3 == 0):
if(num % 5 == 0):
print("FizzBuzz")
else:
print("Fizz")
elif(num % 5 == 0):
print("Buzz")
else:
print(num)
if(isPrime(num)):
print("Prime")
| true |
fbfd74756c1efd103b8958b594b2f876f9ed4876 | arefrazavi/spark_stack | /spark_sql/select_teenagers_sql.py | 1,769 | 4.15625 | 4 | from pyspark import SparkConf, SparkContext
from pyspark.sql import SparkSession, Row
def convert_to_sql_row(line):
row = line.split(',')
return Row(id=int(row[0]), name=str(row[1]), age=int(row[2]), friends_count=int(row[3]))
if __name__ == '__main__':
sc_conf = SparkConf().setMaster('local[*]').setAppName('SelectTeenagers')
sc = SparkContext(conf=sc_conf)
# Since the dataset file doesn't have a header of columns,
# we have to first create an rdd from file and them convert that to a dataframe.
dataset_rdd = sc.textFile('dataset/fakefriends.csv')
dataset_rows = dataset_rdd.map(convert_to_sql_row)
# Create a SparkSQL session.
spark = SparkSession.builder.appName('SelectTeenagers').getOrCreate()
# Create a dataframe by inferring schema from row objects.
dataset_df = spark.createDataFrame(dataset_rows).cache()
# Three ways to select teenagers by filtering rows by age column
# 1) Use filter function and conditions on dataframe object
#teenagers_df = dataset_df.filter(dataset_df.age >= 13).filter(dataset_df.age <= 19).\
# orderBy(dataset_df.friends_count, ascending=False)
# 2) Use filter function and sql-like conditions
#teenagers_df = dataset_df.filter('age >= 13 AND age <= 19').orderBy('friends_count', ascending=False)
# 3) Perform SQL query on the dataframe
# 3.1) create a view of dataframe.
dataset_df.createOrReplaceTempView('friends')
# 3.2) Run SQL query on the view
teenagers_df = spark.sql('SELECT * FROM friends WHERE age >= 12 AND age <= 19 ORDER BY friends_count DESC')
# Print row objects
for row in teenagers_df.collect():
print(row)
# Print n rows of dataframe
teenagers_df.show(n=20)
spark.stop()
| true |
b3defea1bcb2f421c1d0ba8b54faf7f4a659ea43 | EmersonPaul/MIT-OCW-Assignments | /Ps4/ps4a.py | 1,929 | 4.34375 | 4 | # Problem Set 4A
# Name: <your name here>
# Collaborators:
# Time Spent: x:xx
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part. Non-recursive solutions will not be
accepted.
Returns: a list of all permutations of sequence
Example:
>>> get_permutations('abc')
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Note: depending on your implementation, you may return the permutations in
a different order than what is listed here.
'''
if len(sequence) == 1:
return [sequence]
permutation_list = []
for letter in sequence:
index = sequence.index(letter)
for char in get_permutations(sequence[:index] + sequence[index + 1:]):
permutation_list += [letter + char]
return permutation_list
def string_permutation(string):
if len(string) == 1 or len(string) == 0:
return 1
return len(string) * string_permutation(string[1:])
if __name__ == '__main__':
# #EXAMPLE
# example_input = 'abc'
# print('Input:', example_input)
# print('Expected Output:', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'])
# print('Actual Output:', get_permutations(example_input))
# # Put three example test cases here (for your sanity, limit your inputs
# to be three characters or fewer as you will have n! permutations for a
# sequence of length n)
test_data = ['abc', 'bust', 'cd', 'rusty']
for data in test_data:
permutation_list = get_permutations(data)
print('The permutations are : ', permutation_list)
print('Expected length of list: ', string_permutation(data))
print('Actual length : ', len(permutation_list))
| true |
ee37314201ebeace70e328eabf38777faedfd212 | dairof7/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 641 | 4.15625 | 4 | #!/usr/bin/python3
"""
Module text_indentation
module to ident a text
print a text
"""
def text_indentation(text):
"""this functions print a text
insert newline where find a ".", "?", ":"
"""
if type(text) != str or text is None:
raise TypeError("text must be a string")
sw = 0
for i in text:
if i in [".", "?", ":"]:
print(i, end="\n\n")
sw = 1
else:
if sw == 0:
print(i, end="")
else:
if i == ' ':
pass
else:
print(i, end="")
sw = 0
| true |
bb3c1324e8def64fbfddcfcba51d48ce526b40ae | PriyanjaniCh/Python | /henderson_method.py | 2,980 | 4.3125 | 4 | #!/usr/bin/python3
# Purpose: To implement the Henderson method
# Execution: One argument for start number can be passed
#
# William F. Henderson III was a brilliant computer scientist who was taken from us all too soon. He had trouble falling asleep
# because there were too many thoughts running through his head. The everyday method of counting sheep didn’t work for him because
# it was too easy, leaving him too much time for other thoughts. So he invented the following method which required more calculation.
# Start with the number 1000. Subtract 1 from it repeatedly (i.e., 999, 998, etc.) until you get a number ending in 0. (That will happen at 990.)
# Then switch to subtracting 2’s, i.e., 988, 986, etc., until you again get a number ending in 0. Then switch to subtracting 3’s.
# Every time you get a number ending in 0, increment the number you are subtracting. Stop when the next subtraction would cause the number to go negative.
# This program is an implementation of the above method
import sys
print('\nNumber of arguments: ', len(sys.argv))
print('Argument List: ', str(sys.argv), '\n\n\n')
# Validating the arguments passed
if len(sys.argv) > 2:
print('Wrong number of arguments\n\n')
exit()
elif len(sys.argv) > 1:
if int(sys.argv[1]) < 0:
print('Argument passed is Negative \n\n')
exit()
start_number = int(sys.argv[1])
else:
start_number = 1000
count = 0
i = 1
total = 0 # total spoken numbers
increment = 0 # total number of increments
result = [] # list for the calculated output
initial = [] # list for first two rows
initial.append(['decrement','current','count',''])
initial.append(['',str(start_number),'',''])
number = start_number
while True:
number = number-i
count = count+1
if number % 10 == 0 :
print_count = '*'*count
result.append([i, number, count, print_count])
i = i+1
count = 0
if number-i < 0:
print_count = '*'*count
if number != 0:
result.append([i, number, count, print_count])
break
# formats for lists initial and result
format1 = '{:>10s}{:>10s}{:>10s}{}{:<14s}'
format2 = '{:>10d}{:>10d}{:>10d}{}{:<14s}'
for j in range(len(initial)):
print(format1.format(initial[j][0],initial[j][1],initial[j][2],
' ',initial[j][3]))
for j in range(len(result)):
print(format2.format(result[j][0],result[j][1],result[j][2],
' ',result[j][3]))
# calculating total spoken words and increment
increment = len(result)
for j in range(len(result)):
total = total + result[j][2]
print("\n\nThere were", total,"numbers spoken with",
increment,"different increments.")
print("Average cycles/incr = {:0.2f}.".format((total/increment)))
passed = start_number-number
print("\n\nThere were", passed, "numbers passed by with",
increment, "different increments.")
print("Average numbers/incr = {:0.2f}.".format(passed/increment))
| true |
f390a60a44262785efe169930db6f56cba694885 | hyperlearningai/introduction-to-python | /examples/my-first-project/myutils/collections/listutils.py | 982 | 4.15625 | 4 | #!/usr/bin/env python3
"""Collection of useful tools for working with list objects.
This module demonstrates the creation and usage of modules in Python.
The documentation standard for modules is to provide a docstring at the top
of the module script file. This docstring consists of a one-line summary
followed by a more detailed description of the module. Sections may also be
included in module docstrings, and are created with a section header and a
colon followed by a block of indented text. Refer to
https://www.python.org/dev/peps/pep-0008/ for the PEP 8 style guide for
Python code for further information.
"""
def convert_to_dict(my_keys, my_values):
"""Merge a given list of keys and a list of values into a dictionary.
Args:
my_keys (list): A list of keys
my_values (list): A list corresponding values
Returns:
Dict: Dictionary of the list of keys mapped to the list of values
"""
return dict(zip(my_keys, my_values))
| true |
b752e89398d424ec93433eb14083f898431ce8bd | mcp292/INF502 | /src/midterm/2a.py | 726 | 4.4375 | 4 | '''
Approach: I knew I had to run a for loop it range of the entered number to print
the asterisks. The hard part was converting user input to a list of integers.
I found out a good use for list comprehension, which made the code a one liner.
'''
nums = input("Enter 5 comma separated numbers between 1 and 20: ").split(",")
# convert list of strings to list of ints
try:
nums = [int(num) for num in nums] # list comprehension
except ValueError:
print("\nEntry must be a number!\nTerminating program...\n")
exit()
for num in nums:
if (num <= 20):
for iter in range(num):
print("*", end='')
print()
else:
print("Number out of range! {}".format(num))
| true |
c7443de044ebc3149c37b398ee230d21ca784bee | johnnymango/IS211_Assignment1 | /assignment1_part1.py | 1,969 | 4.4375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Assignment 1 - Part 1"""
def listDivide(numbers=[], divide=2):
""" The function returns the number of elements in the numbers list that
are divisible by divide.
Args:
numbers(list): a list of numbers
divide (int, default=2): the number by which numbers in the list
will be divided by.
Returns:
count(int): the count of numbers divisible by divide where remainder
= 0.
Example:
>>> listDivide([2, 4, 6, 8, 10])
5
"""
count=0
for i in numbers:
remainder = i % divide
if remainder == 0:
count=count+1
return count
class ListDivideException(Exception):
"""A custom Exception Class to be raised when errors are created."""
pass
def testListDivide():
"""A function to test the listDivide function and raise an exception when
the test fails.
Args: None
Returns: An exception when the expected result from the test fails.
Example:
Traceback (most recent call last):
File "C:/Users/Johnny/PyCharmProjects/IS211_Assignment1/assignment1_part1.py", line 62, in <module>
testListDivide()
File "C:/Users/Johnny/PyCharmProjects/IS211_Assignment1/assignment1_part1.py", line 51, in testListDivide
raise ListDivideException("Test 2 Error")
__main__.ListDivideException: Test 2 Error
"""
test1 = listDivide([1, 2, 3, 4, 5])
if test1 != 2:
raise ListDivideException("Test 1 Error")
test2 = listDivide([2,4,6,8,10])
if test2 != 5:
raise ListDivideException("Test 2 Error")
test3 = listDivide([30, 54, 63, 98, 100], divide=10)
if test3 !=2:
raise ListDivideException("Test 3 Error")
test4 = listDivide([])
if test4 != 0:
raise ListDivideException ("Test 4 Error")
test5 = listDivide([1,2,3,4,5], 1)
if test5 != 5:
raise ListDivideException ("Test 5 Error")
testListDivide() | true |
dc72e0c85760fb647f5ce64289303cbe915fdb04 | Anosike-CK/class_code | /Membership_Operartors.py | 1,389 | 4.625 | 5 | # MEMBERSHIP OPERATORS ARE USED TO CHECK FOR THE MEMBERSHIP OF A VARIABLE IN A SEQUENCE
a = 10
b = 20
num_list = [1, 2, 3, 4, 5 ]
if ( a in num_list ):
print ("Line 1 - a is available in the given num_list")
else:
print ("Line 1 - a is not available in the given num_list")
if ( b not in num_list ):
print ("Line 2 - b is not available in the given num_list")
else:
print ("Line 2 - b is available in the given num_list")
a = 2
if ( a in num_list ):
print ("Line 3 - a is available in the given num_list")
else:
print ("Line 3 - a is not available in the given num_list")
print("\n For IN operator")
name = "Adebayo"
print("x" in name) #print false because 'x' is not a member in name
print("a" in name) #print true because 'a' is in name
print("x" not in name, "after adding not logigical operator") #print true because not negates the original answer
print("\n mixing menbership operators with the logicaloperators for multiple tests\n")
test_list = [1,4,5,6,7,8]
print(1 in test_list, ", single test")
print(1 in test_list and 32 in test_list, ",multiple tests with 'AND' logical operator")
print(1 in test_list and 32 not in test_list, ",multiple tests with 'AND' logical operator and 'NOT' inverting factor")
print(1 in test_list and 32 not in test_list or 8 in test_list, ",multiple tests with 'AND' logical operator and 'NOT' inverting factor")
| true |
fd0012b59d8cda95b17f00aecef6093446defd34 | Anosike-CK/class_code | /first_thonny_practice.py | 330 | 4.25 | 4 | """website = "Apple.com"
#we re-write the program to change the value of website to programiz.com
website = "programiz.com"
print(website) """
"""#Assign multiple values to multiple variables
a,b,c = 5,3,5.2
print(a)
print(b)
print(c)"""
#Assign the same value to multiple variables
x = y = z = "hmm"
print(x)
print(y)
print(z) | true |
90e061241a1de2eb2ec544b864782218ec8d6711 | Kllicks/DigitalCraftsPythonExercises | /OddNumbers.py | 356 | 4.375 | 4 | #using while loop, print out the odd numbers 1-10 inclusive, one on a line
#initiate variable
i = 1
#while loop to cycle through and print 1-10
while i <= 10:
#if statement to check if the number is also odd
#can't use and on outer while loop because it would end the program when 2 failed
if i % 2 != 0:
print(i, "")
i += 1 | true |
5c250f4557d71212cde13a0002b7ebc8f39f4bc6 | yasar84/week1 | /lists.py | 2,166 | 4.5 | 4 | cars = ["toyota","lexus", "bmw", "merc" ]
print(cars)
# accessing the list
print("first element of cars list: " + cars[0])
print("second element of cars list: " + cars[1])
print("third element of cars list: " + cars[2])
print("fourth element of cars list: " + cars[3])
print("last element of cars list: " + cars[-1])
print("second element from last of cars list: " + cars[-2])
# IndexError expected "list index out of range"
# print("fourth element of cars list: " + cars[4])
# adding elements to the list >> append()
cars.append("range rover")
print(cars)
cars.append("mazda")
print(cars)
print("fifth element of cars list: " + cars[4])
print("sixth element of cars list: " + cars[5])
# modifying, replacing the element on certain index
# cars[3] = "bentley"
cars.extend("bentley")
print(cars)
# cars[0] = "ram"
cars.extend("ram")
print(cars)
# deleting the elements by index
del cars[0]
print(cars)
del cars[-9:]
print(cars)
# adding an element to a specific position
cars.insert(0, "audi")
print(cars)
cars.insert(3, "tesla")
print(cars)
# remove() deleting the element from the list using the value
cars.remove("range rover")
print(cars)
# pop() removes last element and returns the value
sold_cars = [] # empty list
sold_cars.append(cars.pop()) # adding the removed car to the end of the new list
sold_cars.insert(0, cars.pop()) # adding the removed car to the beginning of the new list
# adding the removed car(first car in the list) to the beginning of the new list
sold_cars.insert(0, cars.pop(0))
print(sold_cars)
print(cars)
# organize your lists
# sort()
# cars.sort() # list is sorted in ascending order
# cars.sort(reverse=True) # list is ordered in descending order
sorted_cars = sorted(cars)
print(cars)
print(sorted_cars)
sorted_cars_desc = sorted(cars, reverse=True)
print(sorted_cars_desc)
print(cars)
# cars.reverse() # does not apply ordering asc or desc, it just reverses the list
# print(cars)
# copying the list
cars.append("moskvish")
print(cars)
print(new_cars)
new_cars_copy = cars[:] # copying the list and creating independent new_cars_copy list
cars.append("lada")
print(cars)
print(new_cars)
print(new_cars_copy)
| true |
1d001ee57009334fa0394946f4b65c4f46741172 | AgguBalaji/MyCaptain123 | /file_format.py | 380 | 4.71875 | 5 | """Printing the type of file based on the extension used in saving the file
eg:
ip-- name.py
op--it is a python file"""
#input the file name along with the extension as a string
file=input("Input the Filename:")
#it is a python file if it has .py extension
if ".py" in file:
print("The extension of the file is : 'python'")
else:
print("File type cannot be identified")
| true |
af8d1a4b71460e9ecd5819fddd63a97d4ccd7bfa | cai-michael/kemenyapprox | /matrix.py | 1,382 | 4.3125 | 4 | """
Defines some matrix operations using on the Python standard library
"""
def generate_zeros_matrix(rows, columns):
"""
Generates a matrix containing only zeros
"""
matrix = [[0 for col in range(columns)] for row in range(rows)]
return matrix
def get_column_as_list(matrix, column_no):
"""
Retrieves a column from a matrix as a list
"""
column = []
num_rows = len(matrix)
for row in range(num_rows):
column.append(matrix[row][column_no])
return column
def calculate_cell(matrix_a, matrix_b, row, column):
"""
Calculates an individual cell's value after multiplication
"""
matrix_b_column = get_column_as_list(matrix_b, column)
column_length = len(matrix_b_column)
products = [matrix_a[row][i]*matrix_b_column[i] for i in range(column_length)]
return sum(products)
def matrix_multiplication(matrix_a, matrix_b):
"""
Multiplies two matrices by each other
"""
a_rows = len(matrix_a)
a_columns = len(matrix_a[0])
b_rows = len(matrix_b)
b_columns = len(matrix_b[0])
if a_columns != b_rows:
raise Exception(f'Dimension mismatch: {a_columns}, {b_rows}')
result = generate_zeros_matrix(a_rows, b_columns)
for i in range(a_rows):
for j in range(b_columns):
result[i][j] = calculate_cell(matrix_a, matrix_b, i, j)
return result
| true |
37f813e7e6974fe499252e476755e3e7411a037c | khayk/learning | /python/cheatsheet.py | 1,311 | 4.28125 | 4 | # 1. Print two strings with formatting
# see https://www.programiz.com/python-programming/input-output-import
print("Hello %s %s! You just delved into python." % (a, b))
# 2. Map each item from the input to int
integer_list = map(int, input().split())
# Creates a tuple of integers
t = tuple(integer_list)
# Creates a tuple of integers
l = list(integer_list)
# 3. Read the first string inside the command and the rest inside args
command, *args = input().split()
# 4. Locates the main function and call it
if __name__ == '__main__':
print("You are inside main")
# 5. strip returns a copy of the string with both leading and trailing characters removed (based on the string argument passed).
" hello ".strip() # result is 'hello'
# 6. Your task is to find out if the string contains: alphanumeric characters
any([char.isalnum() for char in S])
# 7. String adjustements
width = 20
'HackerRank'.ljust(width,'-') # HackerRank----------
'HackerRank'.center(width,'-') # -----HackerRank-----
'HackerRank'.rjust(width,'-') # ----------HackerRank
# 8. The textwrap module provides two convenient functions: wrap() and fill().
print(textwrap.wrap(string,8))
print(textwrap.fill(string,8))
# 9. Make the first letter uppercase
'name'.capitalize() | true |
50b86447072eac47a70ad3e35bb1a285cd5a3619 | BTHabib/Lessons | /Lesson 2 Trevot test.py | 820 | 4.21875 | 4 | """
Author: Brandon Habib
Date: 1/21/2016
"""
#Initializing the array
numbers = []
#Initializing A
A = 0
#Printing instructions for the user
print ("Give me an integer Trevor and then type \"Done\" when you are done. When all is finished I will show you MAGIC!")
#A while loop to continue adding numbers to the array
while (A != "Done"):
A = input ("Give me an integer Trevor --> ")
#If statement appending the inputs
if (A != "Done"):
numbers.append(int(A))
#Initializing the Sum
Sum = 0
#Printing updates to the user
print ("MAGICING THE NUMBERS FORM THE ARRAY")
#For loop to sum the elements in the array numbers and prints number
for number in numbers:
Sum = Sum + number
print (number)
#Prints final message and the sum of numbers
print ("THIS IS THE MAGICAL SUM " + str(Sum))
| true |
771de63fb0fd06a32f10e41fd6411f28bd3b985c | mfcarrasco/Python_GIS | /AdvGIS_Course/MyClassPractice.py | 720 | 4.15625 | 4 | class Myclass:
var = "This is class variable"
def __init__(self, name):# first parameter always self in a class
self.name = name
def funct(self):#using method and a function within aclass so ALWAYS start with self
print "This is method print", self.name
foo = Myclass("Malle") #this step is called instantiate. This instance of class assigned to foo. now foo become object
print foo.var # no parantheses because it is not an attribute and it is not a method so NO parantheses
foo.funct() #need to put parantheses becuase funct is a method; foo is the "self" becuase it has the instance of the class
foo1 = Myclass("sara")
foo2 = Myclass("bob")
foo3 = Myclass ("jeff") | true |
13ab27733b3c75d0c5f0c278698b43c3dd04d5a3 | haaruhito/PythonExercises | /Day1Question3.py | 495 | 4.125 | 4 | # With a given integral number n, write a program to generate a dictionary that
# contains (i, i x i) such that is an integral number between 1 and n (both included).
# and then the program should print the dictionary.Suppose the following input is
# supplied to the program: 8
# Then, the output should be: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
num = int(input("Enter a number: "))
dictionary = {}
for i in range (1, num+1):
dictionary[i] = i * i
print(dictionary)
| true |
c142586277e8f59719f324b7c2aea239ecc98680 | kmiroshkhin/Python-Problems | /medium_vowelReplacer.py | 622 | 4.21875 | 4 | """Create a function that replaces all the vowels in a string with a specified character.
Examples
replace_vowels("the aardvark", "#") ➞ "th# ##rdv#rk"
replace_vowels("minnie mouse", "?") ➞ "m?nn?? m??s?"
replace_vowels("shakespeare", "*") ➞ "sh*k*sp**r*"
"""
def replace_vowels(txt,ch):
vowels = ['a','e','i','o','u'];replacementlist=[];replacement=""
for i in txt:
if i in vowels:
replacementlist.append(ch)
else:replacementlist.append(i)
for i in replacementlist:
replacement+=i
return replacement
print(replace_vowels('Eurika!','#')) | true |
561b7063ef63e21a32f425e8aa2cd0060d1e3048 | kmiroshkhin/Python-Problems | /easy_recursion_Sum.py | 353 | 4.25 | 4 | """Write a function that finds the sum of the first n natural numbers. Make your function recursive.
Examples
sum_numbers(5) ➞ 15
// 1 + 2 + 3 + 4 + 5 = 15
sum_numbers(1) ➞ 1
sum_numbers(12) ➞ 78
"""
def sum_numbers(n):
addition=int()
for i in range(1,n+1):
addition+=i
return addition
print(sum_numbers(5)) | true |
9e4a81ce2ea3628967b2f2194caee577914bd1d8 | kmiroshkhin/Python-Problems | /Hard_WhereIsBob.py | 650 | 4.3125 | 4 | """Write a function that searches a list of names (unsorted) for the name "Bob" and returns the location in the list. If Bob is not in the array, return -1.
Examples
find_bob(["Jimmy", "Layla", "Bob"]) ➞ 2
find_bob(["Bob", "Layla", "Kaitlyn", "Patricia"]) ➞ 0
find_bob(["Jimmy", "Layla", "James"]) ➞ -1
"""
def find_bob(names):
counter = -1;encounterBob=False
for name in names:
if name =='Bob':
counter += 1
encounterBob=True
break
elif name !='Bob':
counter += 1
if encounterBob == True:
return counter
else:
return -1
| true |
3700278b8bb878b60eaaf97e88a321ec53e146d0 | erikayi/python-challenge | /PyPoll/main_final.py | 2,013 | 4.21875 | 4 | # Analyze voting poll using data in csv file.
# import csv and os.
import csv
import os
# define the location of the data.
election_csv = "Resources/election_data.csv"
# open the data.
with open(election_csv, 'r') as csvfile:
election_csv = csv.reader(csvfile)
header = next(election_csv)
# define the values.
vote_count = 0
popular_vote = 0
candidate_dict = {}
# find total number of votes cast.
for row in election_csv:
vote_count += 1
candidate_dict[row[2]] = candidate_dict.get(row[2], 0) + 1
# print the results using print() function.
print(f"=========================")
print(f'Election Results')
print(f'=========================')
print(f'Total Votes: {vote_count}')
print(f'=========================')
# Discover complete list of candidates received the most votes.
for candidate, vote in candidate_dict.items():
# Find the percentage of votes that each candidate received.
# Find the total number of votes each candidate won.
won_candidate = (f'{candidate}: {vote / vote_count * 100:.3f}% ({vote})')
print(won_candidate)
# Find the winner of the election based on the popular vote.
# Use If and greater than function to find who has the most votes to win the election.
if vote > popular_vote:
winner = candidate
# print the results using print() function.
print(f'=========================')
print(f'Winner: {candidate}')
print(f'=========================')
# Finalize the script and Export to a .txt. file with results.
output_file = os.path.join("Analysis.txt")
with open(output_file, "w") as text_file:
text_file.write ("Election Results\n")
text_file.write ("===========================\n")
text_file.write ("Total Votes: {}\n".format(vote_count))
text_file.write ("===========================\n")
text_file.write ("{}\n".format(won_candidate))
text_file.write ("===========================\n")
text_file.write ("Winner: {}\n".format(candidate))
| true |
9e7d6229ad3039076757cff1edf336796064b671 | Sudhijohn/Python-Learnings | /conditional.py | 388 | 4.1875 | 4 | #Conditional
x =6
'''
if x<6:
print('This is true')
else:
print('This is false')
'''
#elif Same as Else if
color = 'green'
'''
if color=='red':
print('Color is red')
elif color=='yellow':
print('Color is yellow')
else:
print('color is not red or yellow')
'''
#Nested if
if color == 'green':
if x <10:
print('Color is Green and number is lessthan 10')
| true |
60b2ea5bc3f7100de9f8f05c80dee8b0a803de46 | Aravind2595/MarchPythonProject | /Flow controls/demo6.py | 235 | 4.21875 | 4 | #maximum number using elif
num1=int(input("Enter the number1"))
num2=int(input("Enter the number2"))
if(num1>num2):
print(num1,"is the highest")
elif(num1<num2):
print(num2,"is the highest")
else:
print("numbers are equal") | true |
aa97b8e2e82b353ca5f1d3c14c97471b30d12521 | Aravind2595/MarchPythonProject | /Flow controls/for loop/demo6.py | 237 | 4.15625 | 4 | #check a given number is prime or not
num=int(input("Enter the number"))
flag=0
for i in range(2,num):
if(num%i==0):
flag=1
if(flag>0):
print(num," is not a prime number")
if(flag==0):
print(num,"is a prime number")
| true |
8a48a24a816b1693e493ddd2795f5f44aa958523 | kblicharski/ctci-solutions | /Chapter 1 | Arrays and Strings/1_6_String_Compression.py | 2,506 | 4.375 | 4 | """
Problem:
Implement a method to perform basic string compression using the counts
of repeated characters. For example, the string 'aabcccccaaa' would
become 'a2b1c5a3'. If the "compressed" string would not become smaller
than the original string, your method should return the original
string. You can assume the string has only uppercase and lowercase
letters (a-z).
Implementation:
We can return early if our string is under 3 characters long, because
there is no way that compression would benefit it. Otherwise, we need to
traverse the string and count the number of consecutive characters,
appending them to the list that stores the "tokens" of our compressed
string. We then finally join the tokens back into a string and compare
the lengths of our compressed string and our original string to determine
which should be returned.
Because we have to traverse the original string in O(N) time, and then
join the compressed string in (worst case, when we have all unique
characters) O(2N) time, the total runtime is linear.
Efficiency:
Time: O(N)
Space: O(N)
"""
def compressed_string(string: str) -> str:
"""
Compress a string using the counts of its repeated characters, if possible.
Args:
string (str): The string to be compressed.
Returns:
str: The compressed string if its size is smaller than the original.
Examples:
>>> compressed_string('aabcccccaaa')
'a2b1c5a3'
>>> compressed_string('abcdd')
'abcdd'
"""
if len(string) < 3:
return string
compressed_chars = []
count = 1
for i, c in enumerate(string):
try:
if c == string[i + 1]:
count += 1
else:
compressed_chars.append(c)
compressed_chars.append(str(count))
count = 1
except IndexError:
compressed_chars.append(c)
compressed_chars.append(str(count))
compressed_str = ''.join(compressed_chars)
if len(compressed_str) < len(string):
return compressed_str
return string
assert compressed_string('') == ''
assert compressed_string('a') == 'a'
assert compressed_string('aa') == 'aa'
assert compressed_string('aaa') == 'a3'
assert compressed_string('abc') == 'abc'
assert compressed_string('abcdefgh') == 'abcdefgh'
assert compressed_string('aabcccccaaa') == 'a2b1c5a3'
assert compressed_string('abcdd') == 'abcdd'
| true |
61a24ed9b8931c925de092f0116f780e253de52e | kblicharski/ctci-solutions | /Chapter 1 | Arrays and Strings/1_8_Zero_Matrix.py | 2,826 | 4.125 | 4 | """
Problem:
Write an algorithm such that if an element in an MxN matrix is 0,
its entire row and column are set to 0.
Implementation:
My initial, naive approach to the problem was to first find all
occurrences of zeros and add their row and column values to two lists.
Afterwards, we would check these lists and zero their respective rows and
columns. This works well, but we still need to allocate an additional
O(M+N) space for the two lists.
Instead, we can reduce this to O(1) space by storing this information of
what rows and columns to zero in the original matrix itself.
This relies on the order in which we check the values in the matrix. When
we check a value, we have checked all of the values preceding it -- the
values in all previous rows, and all previous columns of that row.
We can then set the first row at that column to zero, and the first column
at that row to zero. These two slices of our matrix will store the
information we need to zero all elements in these rows and columns. After
parsing the matrix for zeros, we then just need to parse the first row and
the first column.
Efficiency:
Time: O(MN)
Space: O(1)
"""
from typing import List
def zero_matrix(matrix: List[List[int]]) -> None:
"""
Set the contents of an element's row and column to 0 if the element is 0.
Args:
matrix (List[List[int]]): The matrix we are zeroing in-place.
"""
# Find the rows and the columns we want to zero
for row, row_slice in enumerate(matrix):
for col, value in enumerate(row_slice):
if value == 0:
matrix[row][0] = 0
matrix[0][col] = 0
# Zero the correct rows
for row in range(1, len(matrix)):
if matrix[row][0] == 0:
for col in range(len(matrix[row])):
matrix[row][col] = 0
# Zero the correct columns
for col in range(1, len(matrix[0])):
if matrix[0][col] == 0:
for row in range(len(matrix)):
matrix[row][col] = 0
# 1x1 matrix
m = [[1]]
zero_matrix(m)
assert m == [[1]]
# 1x1 matrix
m = [[0]]
zero_matrix(m)
assert m == [[0]]
# 1x2 matrix
m = [[1, 0]]
zero_matrix(m)
assert m == [[0, 0]]
# 2x1 matrix
m = [
[1],
[0]
]
zero_matrix(m)
assert m == [
[0],
[0]
]
# 2x2 matrix
m = [
[1, 1],
[0, 1]
]
zero_matrix(m)
assert m == [
[0, 1],
[0, 0]
]
# 3x3 matrix
m = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
zero_matrix(m)
assert m == [
[1, 0, 1],
[0, 0, 0],
[1, 0, 1]
]
# 4x5 matrix with two zeros
m = [
[1, 1, 1, 1, 1],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 0]
]
zero_matrix(m)
assert m == [
[1, 0, 1, 1, 0],
[0, 0, 0, 0, 0],
[1, 0, 1, 1, 0],
[0, 0, 0, 0, 0]
]
| true |
86fd334b83e5da79823e2858a504ce50d30ac10c | LevanceWam/DPW | /madlib/madlib.py | 1,650 | 4.40625 | 4 | ice_cream = raw_input("What's your flavor: ")
print "Tom was walking down the street and wanted a "+ice_cream+" Ice cream cone"
friends = ["Monster", "T-Rex", "Jello"]
print "Tom's friends wanted Ice cream too and they all had the same amount of money, Tom already has $5.00"
for f in friends:
print f + ", Has $2.00 on with them."
quest = raw_input("Please put in a random word: ")
print "The group decided to go to "+quest+ ", for Ice cream"
print "At "+quest+" their ultimate Ice cream Sundae cost $25"
print "Tom know's that he has money in his piggy bank but can't remember how much was in there but he know's it's no greater than 5"
print "Tom's friends also have some extra money but they have $2 less than he has"
print "Tom goes and checks the piggy bank"
#
piggy = raw_input("How much money was in the bank: ")
piggy = int(piggy)
if 5 < piggy:
raw_input("Please check again")
else:
print "Tom has $" + str(piggy)
#function to find how much money toms friends have
def all (a):
b = a - 2
return b
#toms friends money
returnb = all(piggy)
print "Tom's friends individually have $" + str(returnb)
#All of toms friends money all together
extra_friend_money_all = int(returnb) * 3 + 6
print extra_friend_money_all
tom_money_all = int(piggy) + 5
print "after going counting all of the money Tom had $"+str(tom_money_all)+", and his friends had $"+str(extra_friend_money_all)
tom_money_all
print "When they added it together it totaled out to $"+str(final_amount)
final_amount = int(final_amount)
if final_amount < 25 or None:
print"Sorry No Ice cream for you"
else:
print"Yay For Ice Cream"
| true |
9d9b4d12ab4445af1644d1f29f7dda9c6cfbe32e | spanneerselvam/Marauders-Map | /marauders_map.py | 1,750 | 4.25 | 4 | print("Messers Moony, Wormtail, Padfoot, and Prongs")
print("Are Proud to Present: The Marauders Map")
print()
print("You are fortunate enough to stuble upon this map. Press 'Enter' to continue.")
input()
name = input("Enter your name: ")
input2 = input("Enter your house (gryffindor, ravenclaw, hufflepuff, slytherin): ")
if input2 == "gryffindor":
print("Ahh, a fellow gryffindor! The best house in Hogwarts and where the brave at heart dwell! Welcome {}!".format(name))
print("Enjoy and remember when your done to give it a tap and say 'Mischief Managed' otherwise anyone can read it!")
print("Cheers, Mates!")
if input2 == "ravenclaw":
print("Oh look what we have here, a snobby Ravenclaw... Praised for your cleverness and wit... Hahaha.")
print("Mr. Padfoot wonders if you are all so clever then why was that prat Gilderoy Lockhart a Ravenclaw.")
print("Mr. Prongs agrees with Padfoot and believes that you should go on and read a book instead.")
if input2 == "hufflepuff":
print("Congratulations {}!".format(name))
print("You have come across the mobile version of 'Hogwarts, A History' by Bathilda Bagshot. This is a book concerning Hogwarts School of Witchcraft and Wizardry and its history. Enjoy at your pleasure.")
if input2 == "slytherin":
print("Mr. Moony presents his compliments to {} and begs {} to keep their abnormally large nose out of other people's business".format(name,name))
print("Mr. Prongs agrees with Mr. Moony and would like to add that {} is an ugly git".format(name))
print("Mr. Padfoot would like to register his astonishment that an idiot like that was even accepted to Hogwarts")
print("Mr. Wormtail bids {} good day, and advises {} to wash their hair, the slime-ball".format(name, name))
| true |
b5ec6c31ea7a394cbbdf7e2b8a0ea42640d8b1d5 | nagendrakamath/1stpython | /encapsulation.py | 715 | 4.15625 | 4 | calculation_to_unit = 24
name_of_unit ="hours"
user_input = input("please enter number of days\n")
def days_to_units(num_of_days):
return (f"{num_of_days} days are {num_of_days * calculation_to_unit} {name_of_unit}")
def validate():
try:
user_input_number = int(user_input)
if user_input_number > 0:
my_var = days_to_units(user_input_number)
print (f"your input is {user_input} days")
print(my_var)
elif user_input_number == 0:
print ("you have enterd Zero, Please correct it")
else:
print ("you have enterd -ve number, Please correct it")
except:
print ("Please enter only +ve number")
validate()
| true |
2836cf6c0a9351a3687a244b6034eb760cc2f5ba | pya/PyNS | /pyns/operators/dif_x.py | 636 | 4.1875 | 4 | """
Returns runnig difference in "x" direction of the matrix sent as parameter.
Returning matrix will have one element less in "x" direction.
Note:
Difference is NOT derivative. To find a derivative, you should divide
difference with a proper array with distances between elements!
"""
# =============================================================================
def dif_x(a):
# -----------------------------------------------------------------------------
"""
Args:
a: matrix for differencing.
Returns:
Matrix with differenced values.
"""
return (a[1:,:,:] - a[:-1,:,:]) # end of function
| true |
494cc5b447f85b112110e34dcc16e156f7ff4c2b | raveendradatascience/PYTHON | /Dev_folder/assn85.py | 1,334 | 4.3125 | 4 | #*********************************************************************************#
# 8.5 Open the file mbox-short.txt and read it line by line. When you find a line #
# that starts with 'From ' like the following line: #
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 #
# You will parse the From line using split() and print out the second word in #
# the line (i.e. the entire address of the person who sent the message). #
# Then print out a count at the endself. #
# Hint: make sure not to include the lines that start with 'From:'. #
# You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt #
# ***********************************************************************************#
fname = raw_input("Enter file name: ") # prompts use to enter file name string
fh = open(fname) # opens and reads the file name.
count = 0 # initialising counter
for line in fh: # looping line by line
nospln=line.rstrip() # stripping \n character
if nospln.startswith("From ") : # finding required line
splitwd=nospln.split() # splitting words
print splitwd[1] # printing second word
count=count+1
print "There were", count, "lines in the file with From as the first word"
| true |
652e6e20d73239960e48d9dea1ad75ce3a802cca | KaustubhDhokte/python-code-snippets | /deep&shallowCopy.py | 1,562 | 4.4375 | 4 | '''
Two types of copy operations are applied to container objects such as lists and dictionaries:
a shallow copy and a deep copy. A shallow copy creates a new object but populates
it with references to the items contained in the original object.
'''
a = [1, 2, [8, 9], 5]
print id(a)
# Output: 47839472
b = list(a)
print b
# Output: [1, 2, [8, 9], 5]
print id(b)
# Output: 47858872
# Object Id changes
a[0] = 100
print a
# Output: [100, 2, [8, 9], 5]
print b
# Output: [1, 2, [8, 9], 5]
a.append(30)
print a
# Output: [100, 2, [8, 9], 5, 30]
print b
# Output: [1, 2, [8, 9], 5]
a[1] += 3
print a
# Output: [100, 5, [8, 9], 5, 30]
print b
# Output: [1, 2, [8, 9], 5]
a[2][1] = 10
print a
# Output: [100, 5, [8, 10], 5, 30]
print b
# Output: [1, 2, [8, 10], 5]
b[2][0] = 11
print a
# Output: [100, 5, [11, 10], 5, 30]
print b
# Output: [1, 2, [11, 10], 5]
'''
In this case, a and b are separate list objects, but the elements they contain are shared.
Therefore, a modification to one of the elements of a also modifies an element of b, as
shown.
'''
'''
A deep copy creates a new object and recursively copies all the objects it contains.
There is no built-in operation to create deep copies of objects. However, the
copy.deepcopy() function in the standard library can be used.
'''
import copy
a = [1, 2, [3, 4]]
b = copy.deepcopy(a)
print id(a)
# Output: 44433160
print id(b)
# Output: 44394576
a[2][1] = 6
print a
# Output: [1, 2, [3, 6]]
print b
# Output: [1, 2, [3, 4]]
b[2][0] = 8
print a
# Output: [1, 2, [3, 6]]
print b
# Output: [1, 2, [8, 4]] | true |
11692778a4a716519e08e49f5a129ab743542f7d | KaustubhDhokte/python-code-snippets | /closures_TODO.py | 475 | 4.125 | 4 | # https://realpython.com/blog/python/inner-functions-what-are-they-good-for/
'''
def generate_power(number):
"""
Examples of use:
>>> raise_two = generate_power(2)
>>> raise_three = generate_power(3)
>>> print(raise_two(7))
128
>>> print(raise_three(5))
243
"""
# define the inner function ...
def nth_power(power):
return number ** power
# ... which is returned by the factory function
return nth_power
''' | true |
444297ec4f122e9e9419dbc4ea56e5d9752bfec3 | KaustubhDhokte/python-code-snippets | /metaclasses_TODO.py | 2,756 | 4.3125 | 4 | # https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python
'''
A metaclass is the class of a class.
Like a class defines how an instance of the class behaves, a metaclass defines how a class behaves.
A class is an instance of a metaclass.
'''
'''
When the class statement is executed,
Python first executes the body of the class statement as a normal block of code.
The resulting namespace (a dict) holds the attributes of the class-to-be.
The metaclass is determined by looking at the baseclasses of the class-to-be (metaclasses are inherited),
at the __metaclass__ attribute of the class-to-be (if any) or the __metaclass__ global variable.
The metaclass is then called with the name, bases and attributes of the class to instantiate it.
'''
'''
>>> class MyShinyClass(object):
... pass
can be created manually this way:
>>> MyShinyClass = type('MyShinyClass', (), {}) # returns a class object
>>> print(MyShinyClass)
<class '__main__.MyShinyClass'>
>>> print(MyShinyClass()) # create an instance with the class
<__main__.MyShinyClass object at 0x8997cec>
You'll notice that we use "MyShinyClass" as the name of the class and as the variable to hold the class reference. They can be different, but there is no reason to complicate things.
type accepts a dictionary to define the attributes of the class. So:
>>> class Foo(object):
... bar = True
Can be translated to:
>>> Foo = type('Foo', (), {'bar':True})
And used as a normal class:
>>> print(Foo)
<class '__main__.Foo'>
>>> print(Foo.bar)
True
>>> f = Foo()
>>> print(f)
<__main__.Foo object at 0x8a9b84c>
>>> print(f.bar)
True
And of course, you can inherit from it, so:
>>> class FooChild(Foo):
... pass
would be:
>>> FooChild = type('FooChild', (Foo,), {})
>>> print(FooChild)
<class '__main__.FooChild'>
>>> print(FooChild.bar) # bar is inherited from Foo
True
Eventually you'll want to add methods to your class. Just define a function with the proper signature and assign it as an attribute.
>>> def echo_bar(self):
... print(self.bar)
...
>>> FooChild = type('FooChild', (Foo,), {'echo_bar': echo_bar})
>>> hasattr(Foo, 'echo_bar')
False
>>> hasattr(FooChild, 'echo_bar')
True
>>> my_foo = FooChild()
>>> my_foo.echo_bar()
True
And you can add even more methods after you dynamically create the class, just like adding methods to a normally created class object.
>>> def echo_bar_more(self):
... print('yet another method')
...
>>> FooChild.echo_bar_more = echo_bar_more
>>> hasattr(FooChild, 'echo_bar_more')
True
You see where we are going: in Python, classes are objects, and you can create a class on the fly, dynamically.
This is what Python does when you use the keyword class, and it does so by using a metaclass.
''' | true |
5193aded8a6ba9ce63f4104567bd714ab6b19887 | jqnv/python_challenges_Bertelsmann_Technology_Scholarship | /caesar_cipher.py | 2,421 | 4.53125 | 5 | # Option 1 Difficulty Level: Elementary: One of the first known
# examples of encryption was used by Julius Caesar. Caesar needed
# to provide written instructions to his generals, but he didn’t want
# his enemies to learn his plans if the message slipped into their hands.
# As result, he developed what later became known as the Caesar Cipher.
# The idea behind this cipher is simple (and as a result, it provides
# no protection against modern code breaking techniques). Each letter in the
# original # message is shifted by 3 places. As a result, A becomes D,
# B becomes E, C becomes F, D becomes G, etc. The last three letters in the alphabet
# are wrapped around to the beginning: X becomes A, Y becomes B and Z becomes C.
# Non-letter characters are not modified by the cipher. Write a program that
# implements a Caesar cipher. Allow the user to supply the message and the
# shift amount, and then display the shifted message. Ensure that your program
# encodes both uppercase and lowercase letters. Your program should also support
# negative shift values so that it can be used both to encode messages and decode
# messages. (please see the attached image for more detail)
import string
from itertools import chain
def caesar_cipher():
message = input("Please enter the message to code: ")
shift = int(input("Please enter the shift to code: "))
alpha_low = list(string.ascii_lowercase)
alpha_upp = list(string.ascii_uppercase)
alpha_low.extend(alpha_upp)
if shift >= 0:
low_a, low_z, upp_a, upp_z = ord("a") + shift, ord("z") + 1, ord("A") + shift, ord("Z") + 1
code_low = list(chain(range(low_a, low_z), range(ord("a"), low_a)))
code_upp = list(chain(range(upp_a, upp_z), range(ord("A"), upp_a)))
else:
low_a, low_z, upp_a, upp_z = ord("a"), ord("z") + shift + 1, ord("A"), ord("Z") + shift + 1
code_low = list(chain(range(low_z, ord("z") + 1), range(low_a, low_z)))
code_upp = list(chain(range(upp_z, ord("Z") + 1), range(upp_a, upp_z)))
print(code_low)
code_low.extend(code_upp)
code_iter = dict(zip(alpha_low, code_low))
print(code_iter)
coded_list = []
for i in message:
if ("a" <= i <= "z") or ("A" <= i <= "Z"):
coded_list.append(chr(code_iter.get(i)))
else:
coded_list.append(i)
coded_message = ''.join(coded_list)
print(coded_message)
caesar_cipher() | true |
f88cd2ec59b884787116eb60c476374990109b9b | jqnv/python_challenges_Bertelsmann_Technology_Scholarship | /unique_characters.py | 1,124 | 4.40625 | 4 | # Create a program that determines and displays the number of unique characters in a string entered by the user.
# For example, Hello, World! has 10 unique characters while zzz has only one unique character. Use a dictionary or
# set to solve this problem
def unique_characters(text):
# Solution using dictionary
dictionary_solution(text)
# Solution using set
set_solution(text)
def dictionary_solution(text):
# Declare an empty dictionary
my_dict = {}
# Fill the dictionary with unique characters
for i in text:
my_dict.update({i: 0})
# Print unique characters in an ascendant order list
print(f"Solution using a dictionary: {sorted(list(my_dict.keys()))} {len(my_dict)} unique characters")
def set_solution(text):
# Convert test to set to get unique characters
solution1 = set(text)
# Print unique characters in an ascendant order list
print(f"Solution using a set: \t\t {sorted(list(solution1))} {len(solution1)} unique characters")
if __name__ == '__main__':
unique_characters(input("Please enter the sentence to get unique characters: "))
| true |
34e456552f63f881b56f9e06e924cbc6c4528d4b | jqnv/python_challenges_Bertelsmann_Technology_Scholarship | /license_plate.py | 1,408 | 4.59375 | 5 | #License plate
#Option 1 Difficulty Level: Elementary: In a particular jurisdiction,
# older license plates consist of three uppercase letters followed by three numbers.
# When all of the license plates following that pattern had been used, the format was
# changed to four numbers followed by three uppercase
#letters. Write a program that begins by reading a string of characters from the user.
# Then your program should display a message indicating whether the characters
# are valid for an older style license plate or a newer style license plate.
# Your program should display an appropriate message if the string entered by the user
# is not valid for either style of license plate.
def valid_plate():
plate_input=input("Please enter the license plate: ")
if len(plate_input)==6:
letters, numbers=plate_input[:3], plate_input[3:]
valid_style(letters, numbers, plate_input)
elif len(plate_input)==7:
numbers, letters = plate_input[:4], plate_input[4:]
valid_style(letters, numbers, plate_input)
else:
print(f"The plate {plate_input} is not a valid stYle for a license plate")
def valid_style(letters, numbers, plate_input):
if letters.isupper() and numbers.isdigit():
print(f"Plate {plate_input} is an valid style of plate")
else:
print(f"The plate {plate_input} is not a valid stYle for a license plate")
valid_plate() | true |
b01a758c609d2701d59a74f7bf019c7c4bd9f608 | jqnv/python_challenges_Bertelsmann_Technology_Scholarship | /calc.py | 1,676 | 4.53125 | 5 | # For this exercise I want you to write a function (calc) that expects a single argument -a string containing
# a simple math expression in prefix notation- with an operators and two numbers, your program will parse the input
# and will produce the appropriate output. For our purposes is enough to handle the six basic arithmetic operations
# in Python: addition, substraction, multiplication, division(/), modulus(%), and exponentiation(**). The normal Python
# math rules should work, such that division always result in a floating-point number.
# We will assume for our purposes that the argument will only contain one of our six operators and two valid numbers.
# But wait there is a catch -or a hint, if you prefer: you should implement each of the operations in a single function-
# and you shouldn't use an if statement to decide which function should be run. Another hint: look at the operator module
# whose functions implements many of the Python's operators
def calc(text):
op, num1, num2 = text.split()
oper = {"+": add, "-": sub, "*": mul, "/": div, "%": mod, "**": pow}
first=int(num1)
second=int(num2)
return oper[op](first,second)
# Another option is just to reorder the expresion and evaluate it
def calc2(text):
op, num1, num2 = text.split()
return eval(num1+op+num2)
def add(num1, num2):
return num1 + num2
def sub(num1, num2):
return num1 - num2
def mul(num1, num2):
return num1 * num2
def div(num1, num2):
return num1 / num2
def mod(num1, num2):
return num1 % num2
def pow(num1, num2):
return num1 ** num2
if __name__ == '__main__':
print(calc("/ 10 5"))
print(calc2("/ 10 5"))
| true |
76fddfefedace4aca36548cbc3b6f2ab6f9d3188 | jqnv/python_challenges_Bertelsmann_Technology_Scholarship | /reverse_lines.py | 814 | 4.3125 | 4 | # In this function, we do a basic version of this idea. The function takes two arguments: the names of the input
# file (to be read from) and the output file (which will be created).
def reverse_lines(orig_f, targ_f):
# Read original file storing one line at the time
with open(orig_f, mode="r") as f_input:
for line in f_input:
# Reverse the line and adding new line at the end
line = line.rstrip()[::-1] + "\n"
# Write every reversed line to a new target file
with open(targ_f, mode="a") as f_output:
f_output.write(line)
if __name__ == '__main__':
# Declaring the names of the files to be send as parameters in the function
orig_file = "orig_f.txt"
targ_file = "targ_f.txt"
reverse_lines(orig_file, targ_file)
| true |
b8ceabe1af9f24f1acb694641f32f61c05ca34a6 | jqnv/python_challenges_Bertelsmann_Technology_Scholarship | /dice_simulation.py | 2,603 | 4.53125 | 5 | # In this exercise you will simulate 1,000 rolls of two dice. Begin by writing a function that simulates rolling
# a pair of six-sided dice. Your function will not take any parameters. It will return the total that was rolled on
# two dice as its only result.
# Write a main program that uses your function to simulate rolling two six-sided dice 1,000 times. As your program runs,
# it should count the number of times that each total occurs. Then it should display a table that summarizes this data.
# Express the frequency for each total as a percentage of the total number of rolls. Your program should also display
# the percentage expected by probability theory for each total. Sample output is shown below
from random import randint
def dice_simulation():
# Create a blank dictionary
my_dict = {}
# Fill the dictionary with the possible total as keys
for i in range(2, 13):
my_dict.update({str(i): 0})
# Initialize variables to count the occurrences of each total
v_2, v_3, v_4, v_5, v_6, v_7, v_8, v_9, v_10, v_11, v_12 = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
# Simulate 2 dices rolling
for i in range(1000):
dice1 = randint(1, 6)
dice2 = randint(1, 6)
# Increase each variable according to the total obtained
if dice1 + dice2 == 2: v_2 += 1
if dice1 + dice2 == 3: v_3 += 1
if dice1 + dice2 == 4: v_4 += 1
if dice1 + dice2 == 5: v_5 += 1
if dice1 + dice2 == 6: v_6 += 1
if dice1 + dice2 == 7: v_7 += 1
if dice1 + dice2 == 8: v_8 += 1
if dice1 + dice2 == 9: v_9 += 1
if dice1 + dice2 == 10: v_10 += 1
if dice1 + dice2 == 11: v_11 += 1
if dice1 + dice2 == 12: v_12 += 1
# Filling the dictionary with a list as value
my_dict.update({"2": [v_2 / 1000 * 100, 2.78]})
my_dict.update({"3": [v_3 / 1000 * 100, 5.56]})
my_dict.update({"4": [v_4 / 1000 * 100, 8.33]})
my_dict.update({"5": [v_5 / 1000 * 100, 11.11]})
my_dict.update({"6": [v_6 / 1000 * 100, 13.89]})
my_dict.update({"7": [v_7 / 1000 * 100, 16.67]})
my_dict.update({"8": [v_8 / 1000 * 100, 13.89]})
my_dict.update({"9": [v_9 / 1000 * 100, 11.11]})
my_dict.update({"10": [v_10 / 1000 * 100, 8.33]})
my_dict.update({"11": [v_11 / 1000 * 100, 5.56]})
my_dict.update({"12": [v_12 / 1000 * 100, 2.78]})
# Print the table
print(f"Total\tSimulated\tExpected")
print(f"\t\tPercent\t\tPercent")
for k, v in my_dict.items():
print(f"{k}\t\t{format(v[0], '.2f')}\t\t{v[1]}")
if __name__ == '__main__':
dice_simulation()
| true |
d52add20d1d0518c2c3fb82ce15f9015ce91890f | jqnv/python_challenges_Bertelsmann_Technology_Scholarship | /vowel_consonant.py | 856 | 4.46875 | 4 | # Option 2: Difficulty Level: Pre-Intermediate: In this exercise
# you will create a program that reads a letter of the alphabet from the user.
# If the user enters a, e, i, o or u then your program should display a message
# indicating that the entered letter is a vowel. If the user enters y
# then your program should display a message indicating that sometimes y is a vowel,
# and sometimes y is a consonant. Otherwise your program should display a message
# indicating that the letter is a consonant.
def vowel_consonant(str):
if str == "a" or str == "e" or str == "i" or str == "o" or str == "u":
print("The entered letter is a vowel")
elif str == "y":
print("Sometimes is a vowel, and sometimes is a consonant")
else:
print("The entered letter is a consonant")
vowel_consonant(input("Please enter a letter"))
| true |
f52eb17ccbdecf837794acd87b21ee422bbdf6c5 | ak-alam/Python_Problem_Solving | /secondLargestNumberFromList/main.py | 286 | 4.21875 | 4 | '''
For a list, find the second largest number in the list.
'''
lst = [1,3,9,3,7,4,5]
largest = lst[0]
sec_largest = lst[0]
for i in lst:
if i > largest:
largest = sec_largest
largest = i
elif i > sec_largest:
sec_largest = i
print(f'Largest Number: {sec_largest}')
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.