blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
fbb5cf72b35858269f21e8fd8e0803ae966bc791 | Crolabear/record1 | /Collatz.py | 1,078 | 4.1875 | 4 | # goal: write a program that does the following...
# for any number > 1, divide by 2 if even, and x3+1 if odd.
# figure out how many steps for us to get to 1
# first try:
import sys
class SomeError( Exception ): pass
def OneStep(number, count):
#number = sys.argv[0]
if type(number) is int:
if number%2 is 1:
number=number*3+1
else:
number = number/2
else:
ex= SomeError( "Input Not Integer" )
number =0
count = 0
raise ex
return (number,count+1)
def recur(number,count):
#num = sys.argv[0]
#num = 5
#ct = 0
if number ==1:
return (number,count)
else:
if number%2 ==1:
print number
return recur(number*3+1,count+1)
else:
print number
return recur(number/2,count+1)
def main():
try:
num = int(sys.argv[1])
N,count = recur(num,0)
print "The number of steps is %d" %(count)
except ValueError:
print "Not integer"
if __name__ == "__main__":
main() | true |
1540db701ceb4907f050bef4dd59922ddd8d3e44 | connorhouse/Lab4 | /lists.py | 1,855 | 4.1875 | 4 | stringOne = 'The quick brown fox jumps over the lazy dog'
print(stringOne.lower())
def getMostFrequent(str):
NO_OF_CHARS = 256
count = [0] * NO_OF_CHARS
for i in range(len(str)):
count[ord(str[i])] += 1
first, second = 0, 0
for i in range(NO_OF_CHARS):
if count[i] < count[first]:
second = first
first = i
elif (count[i] > count[second] and
count[i] != count[first]):
second = i
# return character
return chr(second)
if __name__ == "__main__":
str = "The" "quick" "brown" "fox" "jumps" "over" "the" "lazy" "dog"
res = getMostFrequent(str)
if res != '\0':
print("The most frequent character is:", res)
else:
print("No most frequent character")
def uniqueLetters(stringOne):
y = []
for b in stringOne:
if b not in y:
y.append(b)
return y
print(uniqueLetters(stringOne))
# Create a file called lists.py. Complete the following in lists.py:
# Create a list by calling the list() function with the following string "The quick brown fox jumps over the lazy dog." Convert all letters to lowercase before calling the list() function.
# Sort the list.
# Create a function called getMostFrequent() that outputs which letter(s) (excluding spaces) occurs the most often in the sentence. Indicate which letter and the in README.md.
# Create another function called uniqueLetters() that creates a list of all unique characters in the string/list. Then it should ouput each unique character in order. | true |
1a064c17ae1d941a9a055ad6c768d4ea78e7f9dc | anishverma2/MyLearning | /MyLearning/Advance Built In Functions/useofmap.py | 510 | 4.6875 | 5 | '''
The map function is used to take an iterable and return a new iterable where each iterable has been modified according to some function
'''
friends = ['Rolf', 'Fred', 'Sam', 'Randy']
friends_lower = map(lambda x: x.lower(), friends)
friends_lower_1 = (x.lower for x in friends) #can also be used as a generator comprehension
print(friends_lower) #returns that this object is a map object, and we can get the elements using next, as a generator
print(next(friends_lower))
print(next(friends_lower))
| true |
b0cd65ee2540ec7abbece259639628d808672c81 | brianjgmartin/codingbatsolutions | /String-1.py | 1,158 | 4.1875 | 4 | # Solutions to Python String-1
# Brian Martin 14/04/2014
# Given a string name, e.g. "Bob", return a greeting of the form "Hello Bob!".
def hello_name(name):
return "Hello " + name + "!"
# Given two strings, a and b, return the result of putting them together in
# the order abba, e.g. "Hi" and "Bye" returns "HiByeByeHi".
def make_abba(a, b):
return a + b + b + a
# The web is built with HTML strings like "<i>Yay</i>"
# which draws Yay as italic text. In this example, the "i" tag makes
# <i> and </i> which surround the word "Yay". Given tag and word strings,
# create the HTML string with tags around the word, e.g. "<i>Yay</i>".
def make_tags(tag, word):
return "<"+tag+">"+word+"</"+tag+">"
# Given an "out" string length 4, such as "<<>>", and a word,
# return a new string where the word is in the middle of the out string,
# e.g. "<<word>>".
def make_out_word(out, word):
return out[:2]+word+out[2:4]
# Given a string,
# return a new string made of 3 copies of the last 2 chars of the original string.
# The string length will be at least 2.
def extra_end(str):
return str[len(str)-2:len(str)]*3
| true |
7db18f6d7a61e5a2d802a5a417e5dbfc0acd6a6a | mcgarry72/mike_portfolio | /knights_tour_problem.py | 2,595 | 4.125 | 4 | # this is an example recursion problem
# classic: given a chessboard of size n, and a starting position of x, y
# can the knight move around the chessboard and touch each square once
import numpy as np
def get_dimension_input():
cont_processing = True
have_received_input = False
while not have_received_input:
chessboard_dim_string = input("Please enter chessboard dimension, or q to quit ")
if chessboard_dim_string.lower() == "q":
have_received_input = True
cont_processing = False
chessboard_dim_int = 0
else:
try:
chessboard_dim_int = int(chessboard_dim_string)
if chessboard_dim_int > 0:
have_received_input = True
else:
print("Please enter a positive integer")
except:
print("Invalid entry, please try again ")
return cont_processing, chessboard_dim_int
def get_knight_starting(dim):
cont_processing = True
have_received_input = False
while not have_received_input:
knight_row_str = input("Please enter the starting row, or q to quit ")
knight_col_str = input("Please enter the starting column, or q to quit ")
if knight_row_str.lower() == "q" or knight_col_str.lower() == "q":
have_received_input = True
cont_processing = False
knight_row = 0
knight_col = 0
else:
if not knight_row_str.isdigit() or not knight_col_str.isdigit():
print("row and column must be integers")
else:
knight_row = int(knight_row_str)
knight_col = int(knight_col_str)
if knight_row < 0 or knight_col < 0:
print("starting positions must be positive. remember, we start counting at zero")
elif knight_row >= dim or knight_col >= dim:
print("starting positions must be less than the size of the chessboard")
else:
have_received_input = True
return cont_processing, knight_row, knight_col
def try_knight_tour(x, y, z):
my_array = np.zeros((x, x))
my_array[y, z] = 1
print(my_array)
if 0 in my_array:
return False
else:
return True
continue_proc, chessboard_dim = get_dimension_input()
if continue_proc:
continue_proc, start_row, start_col = get_knight_starting(chessboard_dim)
if continue_proc:
result = try_knight_tour(chessboard_dim, start_row, start_col)
print(result)
| true |
bac727960b8e93f16d210ebc60dae8e576e8aa10 | Andida7/my_practice-code | /45.py | 2,148 | 4.46875 | 4 | """Write a program that generates a random number in the range of 1 through 100, and asks
the user to guess what the number is. If the user’s guess is higher than the random number,
the program should display “Too high, try again.” If the user’s guess is lower than the
random number, the program should display “Too low, try again.” If the user guesses the
number, the application should congratulate the user and generate a new random number
so the game can start over.
Optional Enhancement: Enhance the game so it keeps count of the number of guesses that
the user makes. When the user correctly guesses the random number, the program should
display the number of guesses."""
"""
STEPS
- should generate a random number between 1 and 100
- ask the user
- if guess is high say high
- if guess is low say low
- count the guesses made
FUNCTIONS
-main
-random_num
-dispaly
"""
import random
#create a main function
def main():
print('We created a random number between 1 and 20, try guessing it.')
num = random_num()
guess(num)
def guess(num):
stop = 'y'
count = 0
while stop == 'y' or stop == 'Y':
guess = int(input("Enter your guess: "))
if guess > num:
print('Too high, try again.')
count+=1
continue
elif guess < num:
print('Too low, try again.')
count+=1
continue
elif guess == num:
if count == 0:
print('Congrats! You get it immidietly.')
else:
print('Congrats! You get it after',count+1, 'guesses.')
stop = input("Enter 'y' if you want to play again: ")
if stop == 'y' or stop == 'Y':
count = 0
num = random_num()
print('We again created a random number between 1 and 20, try guessing it.')
continue
else: break
#create a random number
def random_num():
num = random.randint(1,20)
return num
main() | true |
164a205f30278d2ca0e01cb7e38f8fd39f481ec8 | JeffGoden/HTSTA2 | /python/homework 1-8/task3.py | 742 | 4.21875 | 4 | number1= int(input("Enter 1 number"))
number2= int(input("Enter a 2nd number"))
if(number1 == number2):
print("Its equal")
else:
print("Its notr equal")
if(number1!= number2):
print("Its not equal")
else:
print("its equal")
if(number1>number2):
print("number 1 is greater than number 2")
else:
print("number 1 is smaller than number 2")
if(number1<number2):
print("number 1 is smaller than number 2")
else:
print("number 1 is greater than number 2")
if(number1>=number2):
print("number 1 is greater or equal number 2")
else:
print("number 1 is smaller or equal number 2")
if(number1<=number2):
print("number 1 is smaller or equal number 2")
else:
print("number 1 is greater or equal number 2") | true |
2f5befb1e3213da290381566175cf6e63a1f735b | DeenanathMahato/pythonassignment | /Program4.py | 593 | 4.28125 | 4 | # Create a program to display multiplication table of 5 until the upper limit is 30
# And find the even and odd results and also find the count of even or odd results and display at the end. (using do while loop,for loop,while)
# 5 x 1 = 5
# 5 x 2 = 10
# 5 x 30 = 150
e= []
o= []
for a in range(1,31):
if (a*5)%2==0:
print(5,' X ',a,' = ',5*a,' is even')
e.append(a*5)
else:
print(5,' X ',a,' = ',5*a,' is odd')
o.append(a*5)
print('even results ',e)
print('odd results ',o)
print('count of even results ',len(e))
print('count of odd results ',len(o)) | true |
c317b5a617d4c84d83762e8f6eafe87995ad9fba | velicu92/python-basics | /04_Functions.py | 1,301 | 4.21875 | 4 |
##############################################################################
####################### creating a basic Function ##########################
##############################################################################
def sumProblem(x, y):
sum = x + y
print(sum)
sentence = 'The sum between {} and {} is {}'.format(x, y, sum)
print(sentence)
sumProblem(2, 3)
def f(x):
return x * x
print(f(3))
print(f(3) + f(4))
##### solving math problems
def CircleArea(r, measure):
pi = 3.14159265
area = pi * r*r
if measure == 'm':
message = 'The Area of an circle with radius = {} m is {} square meters'.format(r, area)
elif measure == 'cm':
message = 'The Area of an circle with radius = {} cm is {} square centimeters'.format(r, area)
print(message)
##### Arguments of the function: radius and measure.
CircleArea(3, 'cm')
#### building another function, more general aproach.
def CircleArea2(r, measure):
pi = 3.14159265
area = pi * r*r
message = 'The Area of an circle with radius r = {} {} is {} square {}'.format(r, measure, area, measure)
print(message)
##### Arguments of the function: radius and measure.
CircleArea2(3, 'cm')
CircleArea2(5, 'km')
| true |
d163ea2611bfefb44382b904d0ae992e22ca1b52 | nishantchy/git-starter | /dictionary.py | 487 | 4.3125 | 4 | # accessing elements from a dictionary
new_dict = {1:"Hello", 2:"hi", 3:"Hey"}
print(new_dict)
print(new_dict[1])
print(new_dict.get(3))
# updating value
new_dict[1] = "namaste"
print(new_dict)
# adding value
new_dict[4] = "walla"
print(new_dict)
# creating a new dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
print(squares)
# remove a particular item
print(squares.pop(4))
# remove an orbitary item
print(squares.popitem())
# delete a particular item
del squares[2]
print(squares)
| true |
9ed6b0d01e7e6329a7bf8e04ac10e426175b91f2 | Rafaelbarr/100DaysOfCodeChallenge | /day018/001_month_number.py | 2,320 | 4.15625 | 4 | # -*- coding: utf-8 -*-
def run():
# Variable declaration
months = 'JanFebMarAprMayJunJulAugSepOctNovDec'
done = False
# Starting the main loop
while done == False:
# Ask the user for a numeric input of a number
month_number = int(raw_input('Enter the number of a month to show it\'s abreviation: '))
# Validating cases:
if month_number < 1 or month_number > 13:
print('\nInvalid number, try within the range of 1 and 12')
month_number = int(raw_input('Enter the number of a month to show it\'s abreviation: '))
elif month_number == 1:
print'The month number {} is: '.format(month_number), months[0:3]
elif month_number == 2:
print'The month number {} is: '.format(month_number), months[3:6]
elif month_number == 3:
print'The month number {} is: '.format(month_number), months[6:9]
elif month_number == 4:
print'The month number {} is: '.format(month_number), months[9:12]
elif month_number == 5:
print'The month number {} is: '.format(month_number), months[12:15]
elif month_number == 6:
print'The month number {} is: '.format(month_number), months[15:18]
elif month_number == 7:
print'The month number {} is: '.format(month_number), months[18:21]
elif month_number == 8:
print'The month number {} is: '.format(month_number), months[21:24]
elif month_number == 9:
print'The month number {} is: '.format(month_number), months[24:27]
elif month_number == 10:
print'The month number {} is: '.format(month_number), months[27:30]
elif month_number == 11:
print'The month number {} is: '.format(month_number), months[30:33]
elif month_number == 12:
print'The month number {} is: '.format(month_number), months[33:36]
# Asking the user to quit the program
option = str(raw_input('Do you want to quit? [Y/N]: ')).lower()
if option.lower() == 'y':
done == True
print('Thanks for using our software!')
break
else:
continue
if __name__ == '__main__':
run() | true |
16ff87190cf9599da27b7dc5e912cb376959f1e4 | the-mba/progra | /week 5/exercise4.py | 520 | 4.3125 | 4 | valid = False
number_of_colons = 0
while not valid:
attempt = input("Please enter a number: ")
valid = True
for c in attempt:
if c == '.':
number_of_colons += 1
elif not c.isdigit():
valid = False
break
if number_of_colons > 1:
valid = False
if not valid: print("That was not a valid number.")
if number_of_colons == 1:
number = float(attempt)
else:
number = int(attempt)
print("Your number squared is: " + str(number * number))
| true |
e203bc43e7d2fac93785b8ad563c742084e80a6b | Dave-dot-JS/LPHW | /ex15.py | 376 | 4.125 | 4 | from sys import argv
script, filename = argv
# opens the specific file for later use
txt = open(filename)
# reads the designated file
print(f"Here's your file {filename}:")
print(txt.read())
# re-takes input for file name to open
print("Type the filename again:")
file_again = input("> ")
# opens new file
txt_again = open(file_again)
#reads new file
print(txt_again.read())
| true |
1e2ea00b37d89d7763805e8a7a0a57c2f1da7d3d | Socialclimber/Python | /Assesment/untitled.py | 1,684 | 4.1875 | 4 | def encryption():
print("Encription Function")
print("Message can only be lower or uppercase letters")
msg = input("Enter message:")
key = int(input("Eneter key(0-25): "))
encrypted_text = ""
for i in range(len(msg)):
if ord(msg[i]) == 32: #check if char is a space
encrypted_text += chr(ord(msg[i])) # cocncatenate back our text, space not encrypted
elif ord(msg[i]) + key > 122:
# after 'z' move back to 'a', 'a' = 97, 'z' = 122
temp = (ord(msg[i])+ key) - 122 # this will return a lower int
# we can now add 96 to tempt and convert it back to a char
encrypted_text += chr(96 + temp)
elif (ord(msg[i]) + key > 90) and (ord(msg[i]) <= 96):
# move back to 'A' after 'Z'
temp = (ord(msg[i]) + key) - 90
encrypted_text += chr(64+temp)
else:
# in case of letters a-z and A-Z
encrypted_text += chr(ord(msg[i]) + key)
print("Encripted Text: "+ encrypted_text);
# Let's implement the decryption function
def decryption():
print("Decryption Function")
print("Message can only be lower or uppercase letters")
msg = input("Enter message:")
key = int(input("Eneter key(0-25): "))
dct_msg = ""
for i in range(len(msg)):
if ord(msg[i]) == 32: #check if char is a space
dct_msg += chr(ord(msg[i])) # cocncatenate back our text, space not encrypted
elif (ord(msg[i]) - key > 90) and (ord(msg[i]) - key < 97):
# move back to 'A' after 'Z'
temp = (ord(msg[i]) - key) + 26
dct_msg += chr(temp)
elif (ord(msg[i]) - key) < 65:
temp = (ord(msg[i]) - key) + 26
dct_msg += chr(temp)
else:
# in case of letters a-z and A-Z
dct_msg += chr(ord(msg[i]) - key)
print("Decrypted Text: "+ dct_msg);
encryption()
decryption()
| true |
50a092982e0f3182094714e2c3cf565226545900 | jerster1/portfolio | /class2.py | 1,080 | 4.28125 | 4 | #lesson 1
#firstName = raw_input("what is your name? ")
#lasttName = raw_input("what is your last name? ")
#address = raw_input("what is your address? ")
#phonenumber = raw_input("what is your phone number? ")
#age = input("How old are you? ")
#
#lesson 2
#firstname = raw_input("what is ur name? ")
#
#print "Your name is %s characters long." % (len(firstname))
#
#Lesson 3
#
#userinput = raw_input("LmFaO RawR Eks DeEe")
#print userinput.lower()
#print userinput.upper()
#
#Lesson 5
#var1 = 'string ges here'
#var2 = 2
#var3 = 3.6
#
#print "your variable's type is %s" % (type(var3))
#
#print "the type of this thing is %s" % (type(str)(var2))
myList = []
num = 0
while num is not None:
try:
num = input('(blank line to quit)\nGive me a number: ')
myList.append(num)
except SyntaxError:
num = None
print "your input it %s" % (myList)
print "the biggest number is %s" % (max(myList))
print "your input backwords is %s" % (list(reversed(myList)))
print "Your input in order is %s" % (sorted(myList))
| true |
925a2c4ad9b411c4da3704b21792a5e33a024e4d | bmarco1/Python-Journey | /yup, still going.py | 1,117 | 4.21875 | 4 | def build_person(first_name, last_name):
"""Return a dictionary of information about a person."""
person = {'first': first_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
print("\n")
def build_person(first_name, last_name, age=''):
"""Return a dictionary of information about a person."""
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person
musician = build_person('jimi', 'hendrix', age=27)
print(musician)
print("\n")
def greet_users(names):
"""Print a simple greeting to each user in the list."""
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
print("\n")
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
print("\n")
def make_pizza(size, *toppings):
print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("-" + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
| true |
a702d1f6fe1d827965529dd0fe6a6abbdbf24f7b | marianopettinati/test_py_imports | /car.py | 2,303 | 4.46875 | 4 | class Car():
"""A simple attemp to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.marca = make
self.modelo = model
self.año = year
self.odometro = 0
def get_descriptive_name(self):
"""Return a neatly formatted name."""
nombre_completo = str(self.año) + ' ' + self.marca + ' ' + self.modelo
return nombre_completo.title()
def read_odometer (self):
"""Prints a statement showing the car mileage"""
print ("Este auto tiene " + str(self.odometro) + ' kms')
def update_odometer(self, kms):
"""Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back.
"""
if kms >= self.odometro:
self.odometro = kms
else:
print("You can't roll back an odometer!")
def increment_odometer(self, kms):
"""Add the given amount to the odometer reading."""
self.odometro += kms
class Battery ():
"""A simple attempt to model a battery for an electric car"""
def __init__(self, battery_size = 70):
"""Initialize th battery's attributes"""
self.battery_size = battery_size
def describe_battery (self):
"""Print a statement describing the battery size"""
print ("This car has a " + str(self.battery_size) + "-kWh battery.")
def upgrade_battery (self):
"""Checks the battery size and sets the capacity to 85"""
if self.battery_size != 85: self.battery_size =85
def get_range(self):
"""Print a statement about the range this battery provides."""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)
class ElectricCar(Car):
"""Represents the aspects of a car specific to electric vehicles"""
def __init__(self, make, model, year):
"""Initializes the attributes of the parent class.
Then initializes the attributes specific to an electric car"""
super().__init__(make, model, year)
self.battery = Battery () | true |
617cab393cb8f65cb4f60fb554452b00ef99f78e | Artimbocca/python | /exercises/python intro/generators/exercises.py | 865 | 4.21875 | 4 | # Write an infinite generator of fibonacci numbers, with optional start values
def fibonacci(a=0, b=1):
"""Fibonacci numbers generator"""
pass
# Write a generator of all permutations of a sequence
def permutations(items):
pass
# Use this to write a generator of all permutations of a word
def w_perm(w):
pass
# Use the Fibonacci generator to create another one that only generates fib numbers with a given factor
def fib_div(d):
pass
# Alternatively, write a generator expression that achieves the same result
# Write generator that puts a user-specified limit on the number of items generated by any given generator
def first(n, g):
pass
# Again, you could also write a generator expression that achieves the same result
if __name__ == "__main__":
print(*permutations(['r', 'e', 'd']))
print(*w_perm('game'))
#etc.
| true |
42a836d108a4933a59e3609c40d2502919b18f11 | Artimbocca/python | /exercises/python intro/google/calculator.py | 657 | 4.4375 | 4 | # You can use the input() function to ask for input:
# n = input("Enter number: ")
# print(n)
# To build a simple calculator we could just rely on the eval function of Python:
# print(eval(input("Expression: "))) # e.g. 21 + 12
# Store result in variable and it can be used in expression:
while True:
exp = input("Expression: ") # e.g. 21 + 12, or m - 7
m = eval(exp)
print(m)
# HOWEVER, using eval is a very bad, as in dangerous, idea. If someone were to enter: os.system(‘rm -rf /’): disaster.
# So, let's quickly get rid of this eval and make our own much more specific eval that only excepts some basic mathematical expressions
| true |
9483b859d50c28ecf5c0edaf4114a63b111eab8c | francisaddae/PYTHON | /FillBoard.py | 2,322 | 4.4375 | 4 | # NAME OF ASSIGNMENT: To display a tic-tac-toe borad on a screen and fill the borad with X
# INPUTS: User inputs of X's
# OUTPUTS: Tic-Tac-Toe board with X
# PROCESS (DESCRIPTION OF ALGORITHM): The use of nested for loops and while loops.
# END OF COMMENTS
# PLACE ANY NEEDED IMPORT STATEMENTS HERE:
import string
import random
def displayBoard(board):
print(board[0],'|',board[1],'|',board[2],'| ')
print(board[3],'|',board[4],'|',board[5],'| ')
print(board[6],'|',board[7],'|',board[8],'| ')
value = 0
i = 0
while i < len(board):
if board[i] == 'X':
value +=1
i +=1
elif board[i] != 'X':
break
return value
def filled(board):
for i in range(len(board)):
if board[i] == 'X':
return True
elif board[i] != 'X':
return False
# MAIN PART OF THE PROGRAM
def main():
board = ['_', '_', '_', '_', '_', '_', '_', '_', '_']
i = 0
while i < len(board):
board[i] = board.index(board[i]) + 1
i+=1
displayBoard(board)
Move = int(input('Enter move for x (1-9): '))
print(Move)
check = 0
while check <= 8:
if not(Move in range(1,10)):
print('Please enter a valid position number 1 through 9')
displayBoard(board)
filled(board)
Move = int(input('Enter move for x (1-9): '))
print(Move)
elif (Move in range(1,10)):
if board[Move-1] == Move:
board[Move-1] = 'X'
displayBoard(board)
filled(board)
check +=1
if check > 8:
break
else:
Move = int(input('Enter move for x (1-9): '))
print(Move)
filled(board)
elif board[Move-1] == 'X':
print('That position is filled! Try again!')
displayBoard(board)
filled(board)
Move = int(input('Enter move for x (1-9): '))
print(Move)
print('End of game!')
main()
''' This fuction works but you do have to observe the final portion of it since the instrctor did some specifications to it.
# INCLUDE THE FOLLOWING 2 LINES, BUT NOTHING ELSE BETWEEN HERE
if __name__ == "__main__":
main()
# AND HERE'''
| true |
649392e5c71d432b2c6dfb738f76bed0c4b90c42 | J4rn3s/Assignments | /MidtermCorrected.py | 2,166 | 4.375 | 4 | #################################################################
# File name:CarlosMidterm.py #
# Author: Carlos Lucio Junior #
# Date:06-02-2021 #
# Classes: ITS 220: Programming Languages & Concepts #
# Instructor: Matthew Loschiavo #
# This is a Midterm #
# Create a game to teach kindergartners how to sum #
#################################################################
def playNo():
print("If you do not play you will not get a lollipop. Do you want to play?")
# Condition if, in case of Negative answer, causing one time loop insisting the kid to play a game#
play = input("Y/N?")
play = play.upper()
return play
def playYes():
print("Let's do it kiddos!!")
firstnumber = int(input("Choose a number beween 1 and 9. Please enter your choice now!"))
secondnumber = int(input("Good job! Now choose another one."))
result = int(input("Great. Now let's sum both numbers! What is the result?"))
n = 0
score = firstnumber + secondnumber
# print(score) #Used this line for testing purposes#
# print(result) #Used this line for testing purposes#
while n != 1:
if score == result:
print("You got it and you won a lollipop! High five!")
n = 1
else:
print("")
result = int(input("Ops, this is not the right answer, try again! What is the result?"))
return
def prompttoplay():
print("Today we are going to learn Math! Let's play a game shall we?")
play = input("Y/N?")
play = play.upper() # Here I used the example for correct the lower and upper case letter answer#
return play
play = prompttoplay()
if play == "N":
play = playNo()
if play == "Y":
playYes()
if play != "N" and play != "Y":
print('You didn\'t answer Y or N')
#print("You didn't answer Y or N")
prompttoplay()
else: ## code for X to exit
print("That is so sad :( ! Good bye!!") | true |
3f9247d1c7d9538a20aa26e1dae4736284fc6b4c | mgoldstein32/python-the-hard-way-jupyer-notebooks | /ex15.py | 483 | 4.375 | 4 | #importing arguments
#assigning variables to said arguments
print "Type the filename:"
#assigning a variable called "txt" as the file being opened
txt = raw_input("> ")
#printing out the file
print "Here's your file %r" %txt
filename = open(txt)
print filename.read()
#doing it again with a different variable
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
filename.close()
txt_again.close()
| true |
9407a8304b4a4236ddc45934aea4b91bbe7da0d4 | cloudmesh-community/sp19-222-89 | /project-code/scripts/read_data.py | 1,003 | 4.21875 | 4 | #this function is meant to read in the data from the .csv file and return
#a list containing all the data. It also filters out any rows in the
#data which include NaN as either a feature or a label
"""Important note: when the data is read using the csv.DictReader,
the order of the features is changed from the original. In the
list of dictionaries, the order of features is as follows:
ISOS_Size_x, ISOS_Size_y, COST_Size_y, COST_Size_x, Coord_y, Coord_x,
ISOS_z, COST_z, Cone_Type"""
import csv
import math
def read(fpath):
#make file object
with open(fpath) as f_obj:
#make reader object
reader = csv.DictReader(f_obj, delimiter=',')
#make data list
data = []
#boolean nan to store if there's a non value or not
for row in reader:
nan = 0
for i in row.items():
if(i[1] == "NaN"):
nan = 1
if(nan == 0):
data.append(row)
return data
| true |
78ee951a2cd1745691f28bc36e674c358792a8b2 | jurentie/python_crash_course | /chapter_3/3.8_seeing_the_world.py | 420 | 4.40625 | 4 | places_to_visit = ["Seattle", "Paris", "Africa", "San Francisco", "Peru"]
print(places_to_visit)
# Print in alphabetical order
print(sorted(places_to_visit))
# Show that list hasn't actually been modified
print(places_to_visit)
# Print list in reverse actually changing the list
places_to_visit.reverse()
print(places_to_visit)
# Sort list and actually change the list
places_to_visit.sort()
print(places_to_visit)
| true |
3a69957eac67a12c16cf6e5bb2c28eb7dc87a950 | HaoMood/algorithm-data-structures | /algds/ds/deque.py | 1,541 | 4.28125 | 4 | """Implementation of a deque.
Queue is an ordered collection of items. It has two ends, a front and a rear.
New items can be added at either the front or the rear. Likewise, existing items
can be removed from either end. It provides all the capabilities of stacks and
queues in a single data structure.
"""
from __future__ import division, print_function
__all__ = ['Deque']
__author__ = 'Hao Zhang'
__copyright__ = 'Copyright @2017'
__date__ = '2017-07-26'
__email__ = 'zhangh0214@gmail.com'
__license__ = 'CC BY-SA 3.0'
__status__ = 'Development'
__updated__ = '2017-07-26'
__version__ = '1.0'
class Deque(object):
"""Implementation of a deque.
We will use list to build the internal representation of the deque.
Attributes:
_items (list)
>>> d = Deque()
>>> d.isEmpty()
True
>>> d.addRear(4)
>>> d.addRear('dog')
>>> d.addFront('cat')
>>> d.addFront(True)
>>> d.size()
4
>>> d.isEmpty()
False
>>> d.addRear(8.4)
>>> d.removeRear()
8.4
>>> d.removeFront()
True
"""
def __init__(self):
self._items = []
def isEmpty(self):
return self._items == []
def size(self):
return len(self._items)
def addRear(self, x):
self._items.insert(0, x)
def addFront(self, x):
self._items.append(x)
def removeRear(self):
return self._items.pop(0)
def removeFront(self):
return self._items.pop()
def test():
import doctest
doctest.testmod()
if __name__ == '__main__':
test()
| true |
bca0941d748df7a79930774c1e57287ddbfdc8e9 | sylwiam/ctci-python | /Chapter_4_Trees_Graphs/4.2-Minimal-Tree.py | 883 | 4.125 | 4 | """
Given a sorted (increasing order) array with unique integer elements, write
an algorithm to create a binary search tree with minimal height.
"""
from binary_tree import BinaryTree
# @param li a list of sorted integers in ascending order
# @param start starting index of list
# @param end ending index of list
def create_minimal_bst(li, start, end):
if end < start:
return None
# get the middle element of the list
middle = (start + end) / 2
n = BinaryTree(li[middle])
n.left = create_minimal_bst(li, start, middle-1)
n.right = create_minimal_bst(li, middle+1, end)
# root = BinaryTree(li[middle], create_minimal_bst(li, start, middle-1), create_minimal_bst(li, middle+1, end))
return n
if __name__ == '__main__':
binary_search_tree = create_minimal_bst([2,4,6,7,92,101,333,334,888], 0, 8)
print binary_search_tree
| true |
6767de31ed8eea4e1c0489ed5a1a7ad3b0f9bca7 | sylwiam/ctci-python | /Chapter_2_Linked_Lists/2.7_Intersection.py | 2,760 | 4.15625 | 4 | """
2.7 Intersection: Given two (singly) linked lists, determine if the two lists intersect. Return the inresecting node.
Note that the intersection is defined based on reference, not value.
That is, if the kth node of the first linked list is the exact same node (by reference) as the jth node of the
second list, then they are intersecting.
For example, the following two linked lists:
A: a1 -> a2 -> c1 -> c2 -> c3
B: b1 -> b2 -> b3 -> c1 -> c2 -> c3
begin to intersect at node c1.
Notes:
* If two linked lists have no intersection at all, return None.
* The linked lists must retain their original structure after the function returns
* You may assume there are no cycles anywhere in the entire linked structure
* Your code should preferably run in O(n) time and use only O(1) memory.
"""
from MyLinkedList import LinkedList, Node
def get_intersection_node(headA, headB):
# figure out the difference in length of the two linked lists
# then use that information to traverse the two lists in sync looking out
# for when there is an intersection
# O(n)
listA_length = 0
listB_length = 0
current_node = headA
while current_node: # get size/length of list A
listA_length = listA_length + 1
tailA = current_node
current_node = current_node.next
print "list A tail: ", tailA.data
current_node = headB
while current_node: # get size/length of list B
listB_length = listB_length + 1
tailB = current_node
current_node = current_node.next
print "list B tail: ", tailB.data
if tailA.data != tailB.data:
return None
if listA_length > listB_length:
longest = headA
shorter = headB
else:
longest = headB
shorter = headA
difference = abs(listA_length - listB_length)
print "difference: ", difference
listA_index = 0
listB_index = 0
current_node = longest
while listA_index < difference:
current_node = current_node.next
listA_index = listA_index + 1
intersection = None
current_other_node = shorter
while current_other_node:
if current_other_node == current_node:
intersection = current_other_node
break
current_other_node = current_other_node.next
current_node = current_node.next
return intersection
if __name__ == '__main__':
lA = LinkedList()
lA.insert('c3')
lA.insert('c2')
lA.insert('c1')
lA.insert('a2')
lA.insert('a1')
lB = LinkedList()
lB.insert('c3')
lB.insert('c2')
lB.insert('c1')
lB.insert('b4')
lB.insert('b3')
lB.insert('b2')
lB.insert('b1')
print "list A size: ", lA.get_size()
print "list A head: ", lA.head.data
lA.print_list2(lA.head)
print "list A size: ", lB.get_size()
print "list A head: ", lB.head.data
lA.print_list2(lB.head)
print get_intersection_node(lA.head, lB.head)
# print 'middle', lA.find_middle(lA.head) | true |
76375c4530dc177c5587eeace5e53a23df692f1e | ghj3/lpie | /untitled14.py | 691 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 17 22:13:36 2018
@author: k3sekido
"""
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
# FILL IN YOUR CODE HERE...
for c in list(secretWord):
if c not in lettersGuessed:
return False
return True
secretWord = 'durian'
lettersGuessed = ['h', 'a', 'c', 'd', 'i', 'm', 'n', 'r', 't', 'u']
print(isWordGuessed(secretWord, lettersGuessed))
| true |
dbf9328fd348044e9dda97a75e7a0ca4312ef1e4 | augustoscher/python-excercises | /hacking/picking-numbers.py | 619 | 4.25 | 4 | #
# Given an array of integers, find and print the maximum number of integers you can select
# from the array such that the absolute difference between any two of the chosen integers is less than or equal to 1
#
# Ex:
# a = [1,1,2,2,4,4,5,5,5] -> r1 = [1,1,2,2] and r2 = [4, 4, 5, 5, 5]
# result would be 5 (length of second array)
#
# Complete the 'pickingNumbers' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY a as parameter.
#
def pickingNumbers(a):
return max([sum((a.count(i), a.count(i+1))) for i in set(a)])
print(pickingNumbers([4, 6, 5, 3, 3, 1])) | true |
ac73357099eec0d42992610677661f1ee21cea38 | pokemonball34/PyGame | /quiz.py | 1,378 | 4.59375 | 5 | # A Function that asks for the initial temperature type and converts it from Celsius to Fahrenheit or vice versa
def temperature_type_def(temperature_type):
# Conditional to check if user typed in C or c to convert from C -> F
if temperature_type == 'C' or temperature_type == 'c':
# Asks the user for the temperature value
temperature = float(input('Please input the temperature value: '))
# Returns the converted value
return print(str(temperature) + "C is " + str(temperature * 1.8 + 32) + "F.")
# Conditional to check if user typed in F or f to convert from F -> C
elif temperature_type == "F" or temperature_type == "f":
# Asks the user for the temperature value
temperature = float(input('Please input the temperature value: '))
# Returns the converted value
return print(str(temperature) + "F is " + str((temperature - 32) / 1.8) + "C.")
# Recursion to reset the program if the user written an error
else:
# Prints the console that an error has occured
print('ERROR, Please try again')
# Restarts the function
return temperature_type_def(input('Please input the temperature type you are converting from (Type C or F): '))
# Calls the function
temperature_type_def(input('Please input the temperature type you are converting from (Type C or F): ')) | true |
9b5504ebd01228f23fbb55d87c0c29eb942ab25b | bwayvs/bwayvs.github.io | /Ch5_milestone.py | 2,589 | 4.15625 | 4 | print()
print("You wake up to find yourself trapped in a deep hole. How will you get out?")
print()
look = input("Type LOOK UP or LOOK DOWN for more details: ")
print()
if look.upper() == "LOOK UP":
print()
print("You see a pull string attached to the ceiling.")
pull_string = input("Maybe you should PULL STRING to find out what happen: ")
if pull_string.upper() == "PULL STRING":
print()
print("You pull the string and you hear a **CLICK*")
print()
print("A trap door opens under you and you fall down a slide.")
print(".")
print(".")
print(".")
print(".")
print("It is a long slide!")
print(".")
print(".")
print(".")
print(".")
print("You land comfortably in your own bed.")
print()
print("Was that all just a bizarre dream?")
print()
else:
print()
print("You can't do that here.")
elif look.upper() == "LOOK DOWN":
print()
print("You see a trap door on the ground.")
print()
open_trap = input("Maybe your should OPEN TRAP to see what happens: ")
if open_trap.upper() == "OPEN TRAP":
print()
print("You try to open the trap door, but it won't budge.")
look_up4 = input("Maybe LOOK UP to see if there is anything to help you: ")
if look_up4.upper() == "LOOK UP":
print()
print("You see a pull string attached to the ceiling.")
pull_string = input("Maybe you should PULL STRING to find out what happen: ")
if pull_string.upper() == "PULL STRING":
print()
print("You pull the string and you hear a **CLICK*")
print()
print("A trap door opens under you and you fall down a slide.")
print(".")
print(".")
print(".")
print(".")
print("It is a long slide!")
print(".")
print(".")
print(".")
print(".")
print("You land comfortably in your own bed.")
print()
print("Was that all just a bizarre dream?")
else:
print()
print("You can't do that here.")
else:
print()
print("You can't do that here.")
else:
print()
print("You can't do that here.")
else:
print()
print("You can't do that here.") | true |
3fa2cc87a45bc022d7f44fcf173dcc8b028d950e | FarnazO/Simplified-Black-Jack-Game | /python_code/main_package/chips.py | 900 | 4.1875 | 4 | '''
This module contains the Chips class
'''
class Chips():
'''
This class sets the chips with an initial chip of 100 for each chip object
It contains the following properties:
- "total" wich is the total number of chips, initially it is set to 100
It also contains the following methods:
- "win_bet" which adds the won chips to the total existing chips
- "lose_bet" which removes the lost chips from the total existing chips
'''
def __init__(self):
'''
Inititalises the chip object
'''
self.total = 100
def win_bet(self, bet):
'''
Adds the beted chips to the total chips
'''
self.total += bet
return self.total
def lose_bet(self, bet):
'''
Takes away the beted chips from the total chips
'''
self.total -= bet
return self.total
| true |
efd5e6e4fdaa571aea4b16c99e84e6fc3046a544 | N-SreeLatha/operations-on-matrices | /append.py | 371 | 4.375 | 4 | #appending elements into an array
import numpy as np
a=np.array(input("enter the elements for the first array:"))
b=np.array(input("enter the elements for the second array:"))
print("the first array is:",a)
print ("the second array is:",b)
l=len(b)
for i in range(0,l):
a=np.append(a,b[i])
print("the new array formed by appending the terms in array b into array a:",a)
| true |
cc1ca54cd720e9403f2bdf20ccde569838a37ffb | siddharth952/DS-Algo-Prep | /Pep/LinkedList/basic.py | 856 | 4.34375 | 4 |
# single unit in a linked list
class Element(object):
def __init__(self,value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
# If we establish a new LinkedList without a head, it will default to None
self.head = head
def append(self, new_element):
current = self.head
if self.head:
# LinkedList already has a head, iterate through the next reference in every Element until you reach the end of the list
while current.next:
current = current.next
# Set next for the end of the list to be the new_element
current.next = new_element
else:
# there is no head already, you should just assign new_element to it and do nothing else
self.head = new_element | true |
89a86ec738390178a218821719f3959213d0f1ad | R-Tomas-Gonzalez/python-basics | /list_intro_actions_methods.py | 2,863 | 4.53125 | 5 | #lists are pretty much arrays with some differences
#collections of items
#lists are Data Structures
li = [1,2,3,4,5]
li2 = ['a', 'b', 'c']
li3 = [1,2,'a',True]
# Data Structures - A way for us to organize info and data
#Shopping Cart Example
shopping_cart = [
'notebooks',
'sunglasses',
'toys',
'grapes'
]
#Accessing Cart
#prints the entire shopping_cart
print(shopping_cart)
#prints the first index of the shopping_cart
print(shopping_cart[0])
#prints the last index of the shopping_cart
print(shopping_cart[len(shopping_cart)-1])
#changing the original arrays
# shopping_cart[0] = 'laptop'
print(shopping_cart)
#list slicing creates a copy of the original list
new_cart = shopping_cart[:]
new_cart[0] = 'laptop'
print(new_cart)
##################################################
#Actions
#finding the length of a list
basket = [1,2,3,4,5]
# print(len(basket)) #5
#METHODS
#ADDING to lists
#append method
#adds to the end of the list
basket.append(100)
# print(basket)
#insert method
#inserts into list where you specify, in this case, inserts 100 into index 1
# basket.insert(1, 100)
# print(basket)
#extending a list
#takes an iterable(another list) and appends it to the end
# basket.extend([100,101])
# print(basket)
#REMOVING from lists
#pop method
#removes the last index of the list and returns the value
# basket.pop()
# #you can specify an index to remove in the index
# basket.pop(0)
# print(basket)
#remove method
#you specify what value you'd like to remove
# basket.remove(1)
# print(basket)
#clear method
#clears out the list
basket.clear()
print(basket)
##################################################
#Methods
basket = ['a','b','c','d','e']
#index method
#provides the index of the value you specify
#you can also specify which indexes to search(start and stop) within the list
# print(basket.index('c',0,4))
#in keyword
# print('b' in basket) #true
# print('x' in basket) #false
#count method
#counts how many times a value occurs in a list
# print(basket.count('d'))
#sort method
#sorts the list from a-z and modifies the original array
# basket = ['x', 'b', 'a', 'c', 'd', 'e', 'd']
# basket.sort()
# print(basket)
#sorted method
#sorts the list from a-z but makes a copy and doesn't modify the original
# basket = ['x', 'b', 'a', 'c', 'd', 'e', 'd']
# new_basket = sorted(basket)
# print('the new basket:', new_basket)
# print('the original basket:', basket)
#reverse method
#reverses the list without sorting
# basket.reverse()
# print(basket)
#join method
#joins the values in a list to make a string
# new_sentence = ' '.join(['hello', 'my', 'age', 'is', str(28)])
# print(new_sentence)
#list unpacking
#this allows you to assign a variable to individual values in a list. you can also section off certain groups of values
a,b,c,*other,d,e = [1,2,3,4,5,6,7,8,9]
print(a,b,c,other,d,e)
| true |
a71b77d255c9db65dc6e6bd7dffb6683494eb31d | bommankondapraveenkumar/PYWORK | /code45.py | 510 | 4.21875 | 4 | def squarecolor():
letter=input("enter the letter")
number=int(input("enter the number"))
evencolum=['b','f','d','h']
oddcolum=['a','c','e','g']
evenrow=[2,4,6,8]
oddrow=[1,3,5,7]
if(letter in evencolum and number in evenrow or letter in oddcolum and number in oddrow):
print("square is black")
elif(letter in evencolum and number in oddrow or letter in oddcolum and number in evenrow):
print("square is white")
else:
print("enter a letter first then a number")
squarecolor() | true |
b6be82f0a96114542689840b501cae39305b284f | bommankondapraveenkumar/PYWORK | /code38.py | 445 | 4.34375 | 4 | def monthname():
E=input("enter the month name:\n")
if(E=="january" or E=="march" or E=="may" or E=="july" or E=="august" or E=="october" or E=="December"):
print(f"31 days in {E} month")
elif(E=="february"):
print("if leap year 29 otherwise 28")
elif(E=="april" or E=="june" or E=="september" or E=="november"):
print(f"30 days in {E} month")
else:
print("check the spelling buddy, type name of months only")
monthname() | true |
bbe61dbdac5acdbd4baa422c303664481b308763 | mdeora/codeeval | /sum_of_digits.py | 422 | 4.15625 | 4 | """
Given a positive integer, find the sum of its constituent digits.
Input sample:
The first argument will be a text file containing positive integers, one per line. e.g.
23
496
Output sample:
Print to stdout, the sum of the numbers that make up the integer, one per line.
e.g.
5
19
"""
import sys
with open(sys.argv[1]) as f:
for str_num in f:
print sum(int(i) for i in str_num if i != '\n')
| true |
a7bcd098bef75d2226097d4d11f0a6ce957fd43c | sidduGIT/linked_list | /single_linked_list1.py | 734 | 4.1875 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def printlist(self):
temp=self.head
while(temp):
print(temp.data)
temp=temp.next
first=LinkedList()
first.head=Node(10)
print('after iniliazing first node')
first.printlist()
print('after adding second node')
second=Node(20)
first.head.next=second
first.printlist()
print('after adding third node')
third=Node(30)
second.next=third
first.printlist()
print('after adding third node')
fourth=Node(40)
third.next=fourth
first.printlist()
print('after adding fifth node')
fifth=Node(50)
fourth.next=fifth
first.printlist()
| true |
7f9c06979dd778bf0313bffacd4b954fe55498aa | sidduGIT/linked_list | /linked_list_all_operations.py | 1,336 | 4.125 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def insert_at_end(self,data):
new_node=Node(data)
if self.head==None:
self.head=new_node
return
cur=self.head
while cur.next!=None:
cur=cur.next
cur.next=new_node
def count_nodes(self):
count=0
cur=self.head
while cur.next!=None:
count+=1
cur=cur.next
print('number of nodes',count)
def insert_after(self,data,after):
new_node=Node(data)
cur=self.head
while cur.next!=None:
save=cur.next
if cur.data==after:
cur.next=new_node
new_node=save
else:
print(after,'node not found in a list')
def display(self):
cur=self.head
while cur.next!=None:
print(cur.data)
cur=cur.next
print(cur.data)
llist=LinkedList()
print('initial linked list')
llist.insert_at_end(10)
llist.insert_at_end(20)
llist.insert_at_end(30)
llist.insert_at_end(40)
llist.insert_at_end(50)
llist.insert_at_end(60)
llist.display()
print('linked list after adding item')
llist.insert_after(500,30)
llist.display()
| true |
06966d4ff9727c6eb910497e92654ad6eec68810 | sidduGIT/linked_list | /doubly_linkedlist_delete_at_first.py | 1,619 | 4.25 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
self.prev=None
class Doubly_linkedlist:
def __init__(self):
self.head=None
def insert_at_end(self,data):
if self.head==None:
new_node=Node(data)
self.head=new_node
return
else:
cur=self.head
new_node=Node(data)
while(cur.next!=None):
cur=cur.next
cur.next=new_node
new_node.prev=cur
def display(self):
if self.head==None:
print('list is empty')
return
cur=self.head
while(cur.next!=None):
print(cur.data)
cur=cur.next
print(cur.data)
def delete_at_first(self):
if self.head==None:
print('list is empty nothing to delete')
return
else:
self.head=self.head.next
self.prev=None
llist=Doubly_linkedlist()
llist.insert_at_end(10)
llist.insert_at_end(20)
llist.insert_at_end(30)
llist.insert_at_end(40)
llist.insert_at_end(50)
llist.insert_at_end(60)
llist.insert_at_end(70)
llist.insert_at_end(80)
print('linked list after inserting elements')
llist.display()
print('linked list after deleting first element')
llist.delete_at_first()
llist.display()
print('linked list after deleting second element')
llist.delete_at_first()
llist.display()
print('linked list after deleting third element')
llist.delete_at_first()
llist.display()
print('linked list after deleting fourth element')
llist.delete_at_first()
llist.display()
| true |
1e1b603ef227a61948ea220bbb0bf261f73ad3b9 | DarkEyestheBaker/python | /ProgramFlow/guessinggame.py | 1,290 | 4.15625 | 4 | answer = 5
print("Please guess a number between 1 and 10: ")
guess = int(input())
if guess == answer:
print("You got it on the first try!")
else:
if guess < answer:
print("Please guess higher.")
else: # guess must be greater than answer
print("Please guess lower.")
guess = int(input())
if guess == answer:
print("Well, done! You guessed it!")
else:
print("Sorry, you have not guessed correctly.")
# if guess < answer:
# print("Please guess higher.")
# guess = int(input())
# if guess == answer:
# print("Well done! You guessed it!")
# else:
# print("Sorry, you have not guessed correctly.")
# elif guess > answer:
# print("Please guess lower.")
# guess = int(input())
# if guess == answer:
# print("Well done! You guessed it!")
# else:
# print("Sorry, you have not guessed correctly.")
# else:
# print("Well done! You got it first time!")
# You can have one or more elif print blocks
# You don't have to include elif.
# If you have any elif lines, they come after the if.
# Elif also has to come before else if there is an else.
# You don't have to use else, but if you do, it must come after the if.
# It must also come after any elifs if there are any. | true |
d08f70e1711874ed57fbdc089835155e4d98bd57 | beechundmoan/python | /caesar_8.py | 1,359 | 4.3125 | 4 | """
All of our previous examples have a hard-coded offset -
which is fine, but not very flexible. What if we wanted to
be able to encode a bunch of different strings with different
offsets?
Functions have a great feature for exactly this purpose, called
"Arguments."
Arguments are specific parameters that we can set when we
call a function, and they're super versatile.
"""
def encode_string(character_offset):
string_to_encode = input("Please enter a message to encode! [ PRESS ENTER TO ENCODE ] :")
string_to_encode = string_to_encode.upper()
output_string = ""
no_translate = "., ?!"
# We don't need the following line, because we've defined it as an argument.
#character_offset = 6
for character in string_to_encode:
if character in no_translate:
new_character = character
else:
ascii_code = ord(character)
new_ascii_code = ascii_code + character_offset
if new_ascii_code > 90:
new_ascii_code -= 25
new_character = chr(new_ascii_code)
output_string += new_character
print(output_string)
print("Welcome to our second Caesar Cipher script")
print("Let's call our first argumented function!")
# Those parentheses might make a little more sense now...
encode_string(3)
encode_string(18)
encode_string(1)
# Notice that we can now specify an offset of zero, which doesn't encode at all!
encode_string(0)
| true |
fbcd09f15d85456e86ac136af36b7797f730ca94 | bhushankorpe/Fizz_Buzz_Fibonacci | /Fizz_Buzz_Fibonacci.py | 1,727 | 4.3125 | 4 | #In the programming language of your choice, write a program generating the first n Fibonacci numbers F(n), printing
#"Buzz" when F(n) is divisible by 3.
#"Fizz" when F(n) is divisible by 5.
#"FizzBuzz" when F(n) is divisible by 15.
#"BuzzFizz" when F(n) is prime.
#the value F(n) otherwise.
#We encourage you to compose your code for this question in a way that represents the quality of
#code you produce in the workplace - e.g. tests, documentation, linting, dependency management
#(though there's no need to go this far).
# >>>>>> SOLUTION <<<<<<
# Method checks if the given number is a Prime number
def checkPrime(N):
flag = False
# Try finding a factor of the number other than itself
if N > 1:
for x in range(2,N):
if (N % x) == 0:
return flag
flag = True
return flag
# This is our function F(n) described in the problem statement
def F(num):
buff = []
# Condition checks if given number is divisible by 3,5, 15 or prime.
#If not calculates Fibonacci series which reduces computations
if num%3 == 0 or num%5 == 0 or num%15 == 0 or checkPrime(num):
if num%3 == 0:
buff.append("Buzz")
if num%5 == 0:
buff.append("Fizz")
if num%15 == 0:
buff.append("FizzBuzz")
if checkPrime(num):
buff.append("BuzzFizz")
for i in buff:
print i
else:
fibo = []
a = 0
b = 1
for i in range(0,num):
if i == 0:
fibo.append(a)
if i == 1:
fibo.append(b)
if i > 1:
c = a+b
fibo.append(c)
a=b
b=c
print fibo
# Main() function
if __name__ == '__main__':
# The program takes input from the user
print "How many fibonacci numbers do you want to see? "
n = input()
F(n) | true |
fd0c0d40b181c03d4a0e3d1adcbe37ee69e31bbf | Polinq/InfopulsePolina | /HW_3_Task_6.2.py | 382 | 4.3125 | 4 | def is_a_triangle(a, b, c):
''' Shows if the triangle exsists or not. If it exsisrs, it will show "yes" and if it does not exsit it will show "no". (num, num, num) -> yes or (num, num, num) -> no.'''
if (a + c < b or a + b < c or b + c < a):
print('NO')
else:
print('YES')
# пример использования функции:
is_a_triangle(7, 9, 4) | true |
5a4f54078e1a341c9107f9efec5726b869a0fc27 | Polinq/InfopulsePolina | /HW_3_Task_6.1.py | 313 | 4.40625 | 4 | def is_year_leap(a):
'''The function works with one argument (num) and shows if the year is leap. If the year is leap it shows "True", if the year is not leap it shows "False"'''
if ((a % 4 == 0 and a % 100 != 0) or (a % 400 == 0)):
print('True')
else:
print('False')
is_year_leap(4)
| true |
df1af2c50ba4f110e76c4609518c6e9e166a1fe4 | kavyan92/code-challenges | /rev-string/revstring.py | 610 | 4.15625 | 4 | """Reverse a string.
For example::
>>> rev_string("")
''
>>> rev_string("a")
'a'
>>> rev_string("porcupine")
'enipucrop'
"""
def rev_string(astring):
"""Return reverse of string.
You may NOT use the reversed() function!
"""
# new_string = []
# for char in range((len(astring)-1), -1, -1): #[c, b, a] #[2, 1, 0]
# new_string.append(astring[char])
# return "".join(new_string)
return astring[::-1]
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED. !KROW DOOG\n")
| true |
c2b7982dc8b822a17f9d60634888c0b3ae151884 | alvas-education-foundation/spoorti_daroji | /coding_solutions/StringKeyRemove.py | 377 | 4.28125 | 4 | '''
Example
If the original string is "Welcome to AIET" and the user inputs string to remove "co" then the it should print "Welme to AIET" as output .
Input
First line read a string
Second line read key character to be removed.
Output
String which doesn't contain key character
'''
s = input('Enter The Main String: ')
a=input('Enter The Sub String: ')
print(s.replace(a, '')) | true |
0607f73a1d10f718b4dea2d28c7a6a64b73233af | SpiffiKay/CS344-OS-py | /mypython.py | 1,078 | 4.15625 | 4 | ###########################################################################
#Title: Program Py
#Name: Tiffani Auer
#Due: Feb 28, 2019
#note: written to be run on Python3 :)
###########################################################################
import random
import string
#generate random string
#adapted from tutorial on https://pynative.com/python-generate-random-string/
def myString(strLength=10):
return ''.join(random.choice(string.ascii_lowercase) for i in range(strLength))
#create strings
str1 = myString();
str2 = myString();
str3 = myString();
#print strings to screen
print(str1)
print(str2)
print(str3)
#add newline
str1+='\n'
str2+='\n'
str3+='\n'
#create files
file1 = open("file1", "w+")
file2 = open("file2", "w+")
file3 = open("file3", "w+")
#write string to files
file1.write(str1)
file2.write(str2)
file3.write(str3)
#close files
file1.close()
file2.close()
file3.close()
#generate random numbers
num1 = random.randint(1, 42)
num2 = random.randint(1, 42)
#multiply numbers
total = num1 * num2
#print numbers
print(num1)
print(num2)
print(total)
| true |
bb797f115f513f5210013037f1cda1a86aefe6df | Phazon85/codewars | /odd_sorting.py | 673 | 4.1875 | 4 | '''
codewars.com practice problem
You have an array of numbers.
Your task is to sort ascending odd numbers but even numbers must be on their places.
Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.
'''
def sort_array(source_array):
temp = sorted([i for i in source_array if i%2 != 0])
odd_int = 0
if source_array == []:
return source_array
else:
for i in range(len(source_array)):
if source_array[i] % 2 != 0:
source_array[i] = temp[odd_int]
odd_int += 1
return source_array
test = [5, 3, 2, 8, 1, 4]
print(sort_array(test)) | true |
91092e769d5b1258414d8cac0b3009a9f59b4ef3 | jk555/Python | /if.py | 1,503 | 4.25 | 4 | number = 5
if number == 5:
print("Number is defined and truthy")
text = "Python"
if text:
print("text is defined and truthy")
#Boolean and None
#python_course = True
#if python_course:
# print("This will execute")
#aliens_found = None
#if aliens_found:
# print("This will not execute")
#! operator
# number = 5
# if number != 5:
# print("This will not execute")
#
#python_course = True
#if not python_course:
# print("This will not execute")
#Multiple if conditions
#number=3
#python_course=True
#if number ==3 and python_course:
# print("This will execute")
#
#if number==17 or python_course:
# print("This will also execute")
#ternery If Statements
#a=1
#b=2
#"b is bigger than a" if a > b else "a is smallet than b"
student_names = ["Mark","Katerina","Jessica"]
print(student_names[1])
#last is -1 index
print(student_names[-1])
print(student_names[-2])
#Adding to the list: Add at the end
#student_names.append("Homer")
print(student_names)
print("Mark" in student_names)
#How many elements do we have in list
print(len(student_names))
#list can include multiple types items in the list. But try to avoid that.
#how to delete the item from the list.
#del(student_names[2])
print(student_names)
#List slicing: [1: means ignore first one and print the rest
print(student_names[1:])
#ignore first and last and print the rest of the list
print(student_names[1:-1])
| true |
137af1c6366d00b78500c8b111ad5e6b3bc6121e | rameshroy83/Learning | /Lab014.py | 227 | 4.15625 | 4 | #!/usr/bin/python2
'''
In this code we will talk about escape sequecnce \n is for a new line, \t for a tab.
\'' to print quote \\ to print backslash.
'''
a = input("Enter the string")
print("You entered the string as \n",a)
| true |
bffbe1b30baf3a918462905e96e3a853b96388a6 | for-wd/django-action-framework | /corelib/tools/group_array.py | 449 | 4.21875 | 4 | def groupArray(array, num):
"""
To group an array by `num`.
:array An iterable object.
:num How many items a sub-group may contained.
Returns an generator to generate a list contains `num` of items for each iterable calls.
"""
tmp = []
count = 0
for i in array:
count += 1
tmp.append(i)
if count >= num:
yield tmp
tmp = []
count = 0
yield tmp
| true |
0927f0c0882096fec39a956385abe8509ccabb38 | nashj/Algorithms | /Sorting/mergesort.py | 1,197 | 4.25 | 4 | #!/usr/bin/env python
from sorting_tests import test
def merge(left_list, right_list):
# left_list and right_list must be sorted
sorted_list = []
while (len(left_list) > 0) or (len(right_list) > 0):
if (len(left_list) > 0) and (len(right_list) > 0):
if left_list[0] < right_list[0]:
sorted_list.append(left_list[0])
left_list = left_list[1:]
else:
sorted_list.append(right_list[0])
right_list = right_list[1:]
elif len(left_list) > 0:
sorted_list.append(left_list[0])
left_list = left_list[1:]
else: # right_list nonempty
sorted_list.append(right_list[0])
right_list = right_list[1:]
return sorted_list
def mergesort(list):
# Lists of length <= 1 are trivially sorted
if len(list) <= 1:
return list
# Split the list in half and sort each side
left_list = mergesort( list[0:len(list)/2] )
right_list = mergesort( list[len(list)/2:] )
# Merge the newly sorted lists
return merge(left_list, right_list)
if __name__ == "__main__":
test(mergesort)
| true |
428ae6aee6bf3d0a604320a2cabe06cb0757bf42 | nashj/Algorithms | /Sorting/quicksort.py | 588 | 4.1875 | 4 | #!/usr/bin/env python
from sorting_tests import test
def quicksort(list):
# Lists of length 1 or 0 are trivially sorted
if len(list) <= 1:
return list
# Break the list into two smaller lists by comparing each value with the first element in the list, called the pivot.
pivot = list[0]
lteq_list = []
gt_list = []
for i in list[1:]:
if i <= pivot:
lteq_list.append(i)
else:
gt_list.append(i)
return quicksort(lteq_list) + [pivot] + quicksort(gt_list)
if __name__ == "__main__":
test(quicksort)
| true |
b04548acb91ff5e1a6d32b547ed68480db462f7c | TimDN/education-python | /class/basic.py | 491 | 4.34375 | 4 | class Person: # create a class with name person
first_name = "Foo" # class variable
foo = Person() # Create a Person object and assign it to the foo variable
bar = Person() # Create a Person object and assign it to the bar variable
print(foo.first_name) #prints Foo
print(bar.first_name) #prints Foo
bar.first_name = "Bar" # changing first_name of this Person instance
print(foo.first_name) #prints Foo (no change)
print(bar.first_name) #prints Bar (changed)
test = Person()
| true |
7b824c269e031a2b621ee9c69f571970ccfc5ec9 | usmannA/practice-code | /Odd or Even.py | 508 | 4.3125 | 4 | '''Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2?
Extras:
If the number is a multiple of 4, print out a different message.'''
entered_number= int(input("Please enter any number:"))
if entered_number % 2 == 0:
print ("Thats an even number")
if entered_number % 4 == 0:
print("that's also a multiple of four")
else:
print ("That's an odd number")
| true |
5def7924086f2dcfd0121f7a6979fb5cbbf47e6d | standrewscollege2018/2021-year-11-classwork-padams73 | /zoo.py | 273 | 4.25 | 4 | # Zoo program
# Start by setting a constant
# This is the age limit for a child
CHILD_AGE = 13
# Get the age of the user
age = int(input("What is your age?"))
# Check if they are a child
if age < CHILD_AGE:
print("You pay the child price")
print("Welcome to the zoo") | true |
2681d86a929e491d1bc7774d9ce8f346ab5c8161 | standrewscollege2018/2021-year-11-classwork-padams73 | /madlib.py | 333 | 4.25 | 4 | # This program is a Madlib, getting the user to enter details
# then it prints out a story
print("Welcome to my Madlib program!")
# Get their details
body_part = input("Enter a body part:")
name = input("Enter a name:")
# Print the story
print("Hello {}, you have the strangest looking {} I have ever seen".format(name, body_part)) | true |
aafa7894fa867811e663cf65282ece2445fe700e | standrewscollege2018/2021-year-11-classwork-padams73 | /for_user_input.py | 316 | 4.1875 | 4 | # In this program the user enters a starting
# value, stopping value, and step
# The program then counts up
# Get inputs from user
start_num = int(input("Start?"))
stop_num = int(input("Stop?"))
step = int(input("Change each time?"))
# Print the numbers
for num in range(start_num, stop_num+1, step):
print(num) | true |
c1c77ddd5cb6b430281603fcb29680c0181898be | VictorB1996/GAD-Python | /GAD-02/Homework.py | 432 | 4.28125 | 4 | initial_list = [7, 8, 9, 2, 3, 1, 4, 10, 5, 6]
ascending_list = sorted(initial_list)
print("Ascending order: ")
print(ascending_list)
descending_list = sorted(initial_list, reverse = True)
print("\nDescending order: ")
print(descending_list)
print("\nEven numbers using slice: ")
print(ascending_list[1::2])
print("\nOdd numbers using slice: ")
print(ascending_list[::2])
print("\nMultiples of 3: ")
print(ascending_list[2::3]) | true |
d8cf3b2cb04b117c5ed1478384723b1df83290e8 | Jangchezo/python-code-FREE-SIMPLE- | /readReverse.py | 736 | 4.125 | 4 | # readReverse.py
#test code
"""
reverseRead(file)
->print from the end of the file
"""
file = open('c:/Users/JHLee/Desktop/test.txt', 'r')
lines = file.readlines()
for i in range(0, len(lines)):
print(lines[len(lines)-i-1][0:-1])
# Real code 1
file = open('c:/Users/JHLee/Desktop/test.txt', 'r')
def reverseRead(file):
lines = file.readlines()
for i in range(0, len(lines)):
seeLine = lines[len(lines)-i-1][0:-1]
print(seeLine)
# Real code 2
file = open('c:/Users/JHLee/Desktop/test.txt', 'r')
def reverseRead(file):
lines = file.readlines()
lines = lines.reverse() # WOW! It's simple.
for seeLine in lines:
print(seeLine)
| true |
727a3fadc945279790ace65b0810de18791f0c2a | jeancarlov/python | /decisionB.py | 2,913 | 4.46875 | 4 | # ----- Design Tool - PseudoCode ---------
# Create main function and inside the main function enter the variables codes for input and output
# Display Menu options and request user to make a selection
# Enter variables with input request to the use
# print user input result
# Create if statements to check if variable number match choice selection
# Create def functions and add to each if statement
# Print result from new variables
# call main function main() for inside code to display
# ------ Comment Header -----------
# Name: Jean Carlo Valderrama
# Date : June 13, 2021
# Purpose : Decision B homework
from datetime import date
def main():
print('1. Get name then display name')
print('2. Get Age then display statement')
print("3. Today's date ")
print('4. Quit')
choice = input('Enter selection:')
if choice == '1':
displayName()
if choice == '2':
ageDisplay()
if choice == '3':
displayDate()
if choice == '4':
print('Thanks for trying program ended.')
def displayName():
userName = input('What is your name: ')
print('hello', userName, ", have a good day.")
def ageDisplay():
userAge = input('What is your age: ')
if float(userAge) <= 10:
print(' You are only', userAge, 'go to bed')
if 10 <= float(userAge) <= 20:
print(' This age would display no output')
if 21 <= float(userAge) <= 60:
print("Since you are", userAge, "let's go have a drink.")
elif float(userAge) >= 61:
print( 'Wow,', userAge, ' is really old.')
def displayDate():
today = date.today()
today = today.strftime(" %m/%d/%y")
print(" Today's date:", today)
# main()
main()
userNumberLines = input('Hi please type a number from 1 - 50: ')
print('hello', userNumberLines, ", have a good day.")
if int(userNumberLines) <= 50:
print(' Thanks your number is with in 1 - 50')
else:
print('please try again ')
userKeyword = input('Enter a character from the keyboard: ')
print('your keyboard character is :', userKeyword, )
# newResult = ''.join([char * userNumber for char in userKeyword])
# print(newResult)
for userNumberLine in userNumberLines:
print(str(userKeyword) * userNumberLine)
# print(x.replace(userNumber, userKeyword, 50))
userNumberLines = input('Hi please type a number from 1 - 50: ')
print('hello', userNumberLines, ", have a good day.")
print("Twice the number you give: {number}".format(number=userNumberLines * 2))
if int(userNumberLines) <= 50:
print(' Thanks your number is with in 1 - 50')
else:
print('please try again ')
userKeyword = input('Enter a character from the keyboard: ')
print('your keyboard character is :', userKeyword, )
# newResult = ''.join([char * userNumber for char in userKeyword])
# print(newResult)
for userNumberLine in userNumberLines:
print(str(userKeyword) * userNumberLine) | true |
cb56d6e59567c3713f2b9fff7efea89ed5d29c77 | atbohara/basic-ds-algo | /linkedlist/rearrange_pairs.py | 1,420 | 4.25 | 4 | """Rearrange node-pairs in a given linked list.
Demonstration of 'runner' technique.
"""
from linked_list import Node
from linked_list import LinkedList
def rearrange_pairs(orig_list):
"""Modifies the input list in-place.
O(N).
"""
slow_ptr = orig_list.head
fast_ptr = orig_list.head
while fast_ptr:
slow_ptr = slow_ptr.next
fast_ptr = fast_ptr.next.next # jumps two nodes every time
# When the fast_ptr reaches end, put it back at head.
# slow_ptr would be at (N/2)+1 element.
fast_ptr = orig_list.head
# Start 'weaving' the pairs.
while slow_ptr:
# Store the original next nodes in temp variables.
next1 = slow_ptr.next
next2 = fast_ptr.next
# Rearrange pointers.
fast_ptr.next = slow_ptr
if not next1: # p1 reached the last node
# Cleanup: remove unneccessary links (optional).
slow_ptr = None
fast_ptr = None
next2 = None
break
slow_ptr.next = next2
slow_ptr = next1
fast_ptr = next2
def main():
orig_items = [1, 2, 3, 4, 'a', 'b', 'c', 'd']
orig_list = LinkedList()
for item in orig_items:
orig_list.insert_at_tail(item)
print("Original list:")
orig_list.print()
rearrange_pairs(orig_list)
print("After rearranging:")
orig_list.print()
if __name__ == '__main__':
main()
| true |
b106c568098b8d4db825de07a3f6d869f4a0fc0e | abokumah/Lab_Python_02 | /solutions/extra_credit_solutions/Lab03_2.py | 828 | 4.71875 | 5 | """
Lab_Python_02
Extra Credit
Solutions for Extra Credit Question 1
"""
# getting input from the user
unencrypted = int(raw_input("Enter a number to encrypt: "))
encrypted = 0
encrypted_old = 0
while unencrypted > 0:
# multiplying both the encrypted numbers by 10
encrypted *= 10
encrypted_old *= 10
#getting the last digit of what is left of the unencrypted number
new_digit = unencrypted % 10
#adding the new digit to the old encryption method before we transform it
encrypted_old += new_digit
#transforming the new digit
new_digit = (new_digit + 7) % 10
#adding the new digit
encrypted += new_digit
# shortening the unencrypted number
unencrypted //= 10
print "Using the old method, the encrypted number is %d" % encrypted_old
print "Using the new method, the encrypted number is %d" % encrypted
| true |
1e3b15e3576fa57b0af51d37cf91cbf158d0a4a2 | cnluzon/advent2016 | /scripts/03_triangles.py | 2,969 | 4.15625 | 4 | import argparse
"""
--- Day 3: Squares With Three Sides ---
Now that you can think clearly, you move deeper into the labyrinth of hallways
and office furniture that makes up this part of Easter Bunny HQ. This must be a
graphic design department; the walls are covered in specifications for
triangles.
Or are they?
The design document gives the side lengths of each triangle it describes,
but... 5 10 25? Some of these aren't triangles. You can't help but mark the
impossible ones.
In a valid triangle, the sum of any two sides must be larger than the remaining
side. For example, the "triangle" given above is impossible, because 5 + 10 is
not larger than 25.
In your puzzle input, how many of the listed triangles are possible?
"""
class TriangleValidator:
def validate_side_list(self, sides):
result = True
if sides[0] + sides[1] <= sides[2]:
result = False
elif sides[1] + sides[2] <= sides[0]:
result = False
elif sides[0] + sides[2] <= sides[1]:
result = False
return result
def count_good_triangles(self, triangle_list):
good_triangle_count = 0
for triangle in triangle_list:
if self.validate_side_list(triangle):
good_triangle_count += 1
return good_triangle_count
def parse_input_horizontal(fi):
lines = fi.readlines()
triangles_list = []
for line in lines:
values = line.rstrip().split()
values = [int(v) for v in values]
triangles_list.append(values)
return triangles_list
def parse_input_vertical(fi):
triangle_list = []
transposed_matrix = []
lines = fi.readlines()
for line in lines:
line = line.rstrip()
values = line.split()
values = [int(v) for v in values]
transposed_matrix.append(values)
for j in range(0, len(transposed_matrix[0])):
value_list = [transposed_matrix[i][j] for i in range(len(transposed_matrix))]
for i in range(0, len(value_list), 3):
triangle_list.append(value_list[i:i+3])
return triangle_list
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Solve Advent of Code 2016 problem 03: Squares with three sides')
parser.add_argument('in_file', help='Input triangles file')
args = parser.parse_args()
validator = TriangleValidator()
fi = open(args.in_file)
triangle_list_horizontal = parse_input_horizontal(fi)
fi.close()
fi = open(args.in_file)
triangle_list_vertical = parse_input_vertical(fi)
fi.close()
good_triangles_horizontal = validator.count_good_triangles(triangle_list_horizontal)
good_triangles_vertical = validator.count_good_triangles(triangle_list_vertical)
print "In the list, there are {} good triangles".format(good_triangles_horizontal)
print "In the list (vertically), there are {} good triangles".format(good_triangles_vertical)
| true |
147db49069181bfd366e2975da98f704e3a7ca89 | Jetroid/l2c | /solutions/l2s_solution14.py | 674 | 4.4375 | 4 | #Write a program that will print out the contents of a multiplication table from 1x1 to 12x12.
# ie. The multiplication table from 1x1 to 3x3 is as follows:
# 1 2 3
# 2 4 6
# 3 6 9
#Hint: You'll probably want to use two for loops for each number.
#Reminder: To print something without putting a newline on the end, you can use print(..., end="\t").
# You might also want to use tabs so double/triple digit numbers are formatted in a nice table.
#Bonus: See if you can figure out how to print the column headers.
#Write your code below:
upperLimit = 13
for i in range(1, upperLimit):
for j in range(1, upperLimit):
print(str(i * j), end="\t")
print() | true |
a2dcded762980962a583a58af292352dcb1185b9 | Jetroid/l2c | /solutions/l2c_solution11.py | 650 | 4.4375 | 4 | #Finish the if/elif/else statement below to evaluate if myInt is divisible by 4, else evaluate if it is divisible by 3.
#Try out myInt for several different values!
#Reminder: We can use the modulo operator to get the remainder. eg: 7 % 3 is equal to 1. (because 2*3 + 1 is equal to 7)
#Hint: If a modulo result is zero, then the left hand operator is wholly divisible by the right hand operator.
#Example Solution:
myInt = 12
if myInt % 4 == 0:
print("myInt was divisible by four.")
elif myInt % 3 == 0:
print("myInt was divisible by three but not four.")
else:
print("myInt was divisible by neither three nor four.")
| true |
3383c4a85f5db4d89293ff8e43183a4e3832be83 | wa57/info108 | /Chapter8/Chapter8Ex1.py | 1,069 | 4.25 | 4 | """a) _____ Assume “choice” is a variable that references a string.
The following if statement determines whether choice is equal to ‘Y’ or ‘y’.:
if choice == ‘Y’ or choice == ‘y’:
Rewrite this statement so it only makes one comparison and does not use the or operator.
b) _____ Write a loop that counts the number of space characters that appear in
the string referenced by “myString”. myString = “The best things in life are free.”
c) _____ Write a function that accepts a string as an argument and returns
true if the argument ends with the substring “.com”. Otherwise, the function
should return false.
"""
choice = 'Y'
if choice.lower() == 'y':
print(True)
myString = 'The best things in life are free.'
emptySpaces = 0
for char in myString:
if(char == ' '):
emptySpaces += 1
print(emptySpaces)
def isURI(string):
#WA - starts at the end of the string and slices the last 4 characters (the domain)
if(string[-4:] == '.com'):
return True
return False
uri = input('URI: ')
print(isURI(uri))
| true |
98bdd82a126a576d54c51b03d9201ee1ffa22b46 | wa57/info108 | /Chapter7/AshmanLab4Problem1.py | 2,300 | 4.15625 | 4 | #Project Name: Lab 4 Homework
#Date: 4/28/16
#Programmer Name: Will Ashman
#Project Description: Lab 4 Homework
#Resource used for table formatting: http://knowledgestockpile.blogspot.com/2011/01/string-formatting-in-python_09.html
#WA - Import the math module to perform calculations
import math
def main():
#WA - Get and validate user input
loanAmount = getInput('\nEnter the amount of the loan (number greater than 0): ')
loanYears = getInput('\nEnter the number of years as an integer: ')
#WA - Pass input into calculateLoanPayments to be calculated
calculateLoanPayments(loanAmount, loanYears)
#WA - Asks user if they want another table to be created. If y is entered, main is rerun
createAnotherTable = input('\nDo you want to create another table? (y/n): ')
if(createAnotherTable == 'y'):
main()
def calculateLoanPayments(loanAmount, loanYears):
#WA - Uses replacement fields to set a maximum column width and left align column headers
print('\n{0:<8} {1:<18} {2:<16}'.format('Rate', 'Monthly Payment', 'Total Payment'))
print('-'*46)
#WA - Iterates through specified range starting with 4 and running until 8, incremented by 1 each cycle
for rate in range(4, 9, 1):
#WA - Divides annual rate by months in 1 year (12) to get percentage.
# Result is divided by 100 to obtain decimal value usable in the following formulas
monthlyRate = (rate / 12) / 100
#WA - Uses provided formulas to calculate monthlyPayment and the totalPayment for the provided rate
monthlyPayment = loanAmount * monthlyRate / (1 - math.pow(1 / (1 + monthlyRate), loanYears * 12))
totalPayment = monthlyPayment * loanYears * 12
#WA - Uses replacement fields to set a maximum column width and left align data set rows.
# Will also truncate result to 2 decimal places
print('{0:<8} {1:<18} {2:<16}'.format(str(rate) + '%', '$%.2f' % monthlyPayment, '$%.2f' % totalPayment))
#WA - Accepts a message and performs check to verify input is not a negative number,
# uses a while loop to prompt user until valid input is given
def getInput(message):
userInput = float(input(message))
while userInput < 0:
userInput = float(input(message))
return userInput
main()
| true |
cc2e5541bc5a57ca67de5109dae3f5cc976d560d | wa57/info108 | /Lab2/TestFunctions.py | 843 | 4.21875 | 4 | #WA - Gathers a positive, negative, and inclusive number between 48-122
#WA - As well as a string from the user
posInteger = float(input('Positive integer: '))
negInteger = float(input('Negative integer: '))
myChar = int(input('Integer between 48 and 122 inclusive: '))
myString = input('String: ')
#WA - outputs absolute value of postInteger and negInteger
print('Absolute value of', str(posInteger) + ':', abs(posInteger))
print('Absolute value of', str(negInteger) + ':', abs(negInteger))
#WA - output Unicode character associated with integer
print('Unicode translation of', str(myChar) + ':', chr(myChar))
#WA - output length of myString
print('Length of string', '"' + myString + '"' + ':', len(myString))
#WA - output posInteger to the power of 4
myPower = posInteger ** 4
print('Number', posInteger, 'to the power of 4:', myPower)
| true |
730667d8c9bfd1f0883a35d85468609387b33ca7 | chenhuang/leetcode | /maxSubArray.py | 1,575 | 4.1875 | 4 | #! /usr/bin/env python
'''
Maximum Subarray
Given an array of integers, find a contiguous subarray which has the largest sum.
Note
The subarray should contain at least one number
Example
For example, given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.
Maximum Subarray II
Fair Maximum Subarray II
18% Accepted
Given an array of integers, find two non-overlapping subarrays which have the largest sum.
The number in each subarray should be contiguous.
Return the largest sum.
Note
The subarray should contain at least one number
Example
For given [1, 3, -1, 2, -1, 2], the two subarrays are [1, 3] and [2, -1, -2] or [1, 3, -1, 2] and [2], they both have the largest sum 7.
'''
import os
import re
import sys
class solution:
def max_subarray(self, nums):
# Naive solution: O(n^2): iterate through all possible sub arraies.
# Better: many subproblems: sum[i][j] = sum[i][j-1]+num[j]
# sum[0][n]: max sum from 0 to n = max(sum[0][n-1]+num[n-1], sum[0][n-1])
# pre-processing: a[i] = sum(num[0] to num[i])
# then the problem would become: find max(a[j]-a[i]): stock market price problem.
def max_subarray_ii(self, nums):
# Based on solution of max_subarray, preprocessing nums such that:
# a[i] = sum(sum[0] to sum[i])
# b[i]: max (a[i]-a[0])
# c[i]: max (a[n]-a[i])
def max_subarray_iii(self, nums):
# DP:
# A[n][k]: max sum from nums[0] to nums[i]
# A[n][k] = max(A[i][k-1], max_subarray(i,n))
| true |
9ca5bf3b0e75a993f519289bbc5b50ca7e8f5b68 | chenhuang/leetcode | /insert.py | 2,143 | 4.15625 | 4 | #! /usr/bin/env python
'''
Insert Interval
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
https://oj.leetcode.com/problems/insert-interval/
'''
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
# @param intervals, a list of Intervals
# @param newInterval, a Interval
# @return a list of Interval
def insert_1(self, intervals, newInterval):
stack = []
for i in intervals:
if i.start > newInterval.end:
stack.append(newInterval)
newInterval = i
elif (newInterval.start >= i.start and newInterval.start <= i.end) or (i.start >= newInterval.start and i.start <= newInterval.end):
newInterval.start = min(newInterval.start, i.start)
newInterval.end = max(newInterval.end, i.end)
else:
stack.append(i)
stack.append(newInterval)
return stack
def insert(self, intervals, newInterval):
stack = []
for i in intervals:
if i[0] > newInterval[1]:
stack.append(newInterval)
newInterval = i
elif (newInterval[0] > i[0] and newInterval[0] < i[1]) or (i[0] > newInterval[0] and i[0]< newInterval[1]):
newInterval[0] = min(newInterval[0], i[0])
newInterval[1] = max(newInterval[1], i[1])
else:
stack.append(i)
stack.append(newInterval)
return stack
if __name__ == "__main__":
s = Solution()
print s.insert([[1,2],[3,5],[6,7],[8,10],[12,16]],[4,9])
print s.insert([[1,3],[6,9]],[2,5])
| true |
896c390f0835370f76156d3c3de4e2997a7d7522 | sauravrana1983/Python | /Challenge/Introductory/7_Print.py | 261 | 4.1875 | 4 | # Read an integer .
# Without using any string methods, try to print the following:
# Note that "" represents the values in between.
# Input Format
# The first line contains an integer .
def printAll(value):
print(*range(1,value + 1), sep='')
printAll(10) | true |
a795f444b9265560800773b2cbd980ba6eb989e6 | Abinash-giri/mypractise | /AgeCalculator.py | 761 | 4.21875 | 4 | #Program to calculate age of a person
import datetime
def calculateAge(dob):
'''Calulate's a person age'''
today = datetime.date.today()
age = today.year - dob.year
return age
def checkDate(dob):
'''Checks if date is valid or not'''
day,month,year = dob.split('/')
isvaliddate = True
try:
datetime.datetime(int(year),int(month),int(day))
except ValueError:
isvaliddate = False
return isvaliddate
if __name__ == "__main__":
dob = input('Enter Date of birth in dd/mm/yyyy format:')
isdatevalid = checkDate(dob)
if isdatevalid:
dt = datetime.datetime.strptime(dob,"%d/%m/%Y")
print('Age={} years'.format(calculateAge(dt)))
else:
print('Invalid date entered')
| true |
f57eebb51e5cf1fa20b4b2fbdecf21ecc555e5dc | HoangQuy266/nguyenhoangquy-fundamental-c4t4 | /Session04/sheep.py | 580 | 4.21875 | 4 | print ("Hello, my name is Hiepand these are my sheep size: ")
sheep = [5, 7, 300, 90, 24, 50 ,75]
print (sheep)
for i in range (3):
print("MONTH", i+1)
print ("Now one month has passed and this is my flock: ")
new_sheep = [x+50 for x in sheep]
print (new_sheep)
max_sheep = max(new_sheep)
print ("Now my biggest sheep has size", max(new_sheep), "let's shear it")
print ("After shearing, here is my flock: ")
index = new_sheep.index(max(new_sheep))
new_sheep[index] = 8
print (new_sheep)
sheep = list(new_sheep) | true |
9839709ad5c1b281e13e9cd0cbe3e3eeb736513d | ashutoshkmrsingh/Library-Management-System-Console-based- | /faculty.py | 1,334 | 4.375 | 4 | """
faculty module contains FacultyClass and faculty_list data structure.
FacultyClass used to create faculty objects.
And, faculty_list is a list data structure which stores the faculty objects,
and used for modifying faculty data and storing it in a pickle file named as "faculty_data.pkl"
"""
class FacultyClass:
"""
The FacultyClass contains information of the faculties.
FacultyClass have following attributes:
1. e_name = Contains name of the faculty.
2. e_id = Contains id of the faculty.
3. book_issued = A list data structure, stores book objects issued to the faculty.
"""
def __init__(self, e_name=None, e_id=None, book_issued=[]):
"""Initialises FacultyClass object variables with given arguments. Default arguments are None"""
self.e_name, self.e_id, self.book_issued = e_name, e_id, book_issued
def set(self, e_name=None, e_id=None, book_issued=[]):
"""Set or modify FacultyClass object variables with given arguments. Default arguments are None"""
self.e_name, self.e_id, self.book_issued = e_name, e_id, book_issued
def __str__(self):
return f'Faculty name is {self.e_name}, id is {self.e_id} and book issued are {self.book_issued}'
faculty_list = [] | true |
c2af48a092afd6f5ea2e2080b38ebc4eb099045f | symonk/python-solid-data-structures-and-algorithms | /algorithms/searching/binary_search.py | 884 | 4.25 | 4 | import random
import typing
def binary_search(arr: typing.List[int], target: int) -> int:
"""
Performs a binary search through arr. Divide and conquer the list to achieve
o(log n) performance. Pre requisites are that `arr` must be already sorted.
:param arr: The (sorted) sequence of integers.
:param target: The target number to retrieve the index of.
:return: the index of target; or -1 if target is not `in` arr.
"""
left, right = 0, len(arr) - 1
while left <= right:
pivot = (right + left) // 2
value = arr[pivot]
if value == target:
return pivot
elif value < target:
left = pivot + 1
else:
right = pivot - 1
return -1
if __name__ == "__main__":
seq, find = list(range(0, 250_000, 3)), random.choice(range(250_000))
print(binary_search(seq, find))
| true |
a8ad59d9cdb2baf7d7b33188f42bdf3af7a7d0ed | GeorgeDiNicola/blackjack-game | /application/utils.py | 790 | 4.25 | 4 | from os import system, name
def get_valid_input(prompt, possible_input, error_message):
"""Retrieve valid input from the user. Repeat the prompt if the user gives invalid input.
Keyword Arguments:
prompt (string) -- the question/input prompt for the user.
possible_input (list) -- the allowable input for the prompt.
error_message (string) -- the message to output to the user when his or her input is not in the list allowable inputs.
"""
valid = False
while not valid:
choice = input(prompt)
if choice.lower() in possible_input:
valid = True
else:
print(error_message)
return choice.lower()
def clear_window():
"""Clear all output in the console window."""
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux
else:
_ = system('clear') | true |
91f35e9fcb6f5aaaf03d1e34353a33c405c0e581 | skurtis/Python_Pandas | /Question3.py | 1,578 | 4.125 | 4 | #!/usr/bin/env python3
datafile = open("CO-OPS__8729108__wl.csv") # open the CSV file as the variable "datafile"
diffmax = 0 # starts the max difference between final and initial mean as 0
for i in datafile:
if i.startswith('Date'): # skips the first line (header) but makes sure the previous line is designated as "prevline"
prevline = i
# the previous line needs to be called as the current line before the loop begins again
continue
if prevline.startswith('Date'): # skips the first line of data since there is no preceding data to subtract
prevline = i
continue
if i[17:22].startswith(','): continue # this skips the line with missing data
date_curr = i[:10] # these positions in the line represent the date
time_curr = i[11:16] # these positions in the line represent the time
diff_curr = float(i[17:22]) - float(prevline[17:22]) # these positions in the line represent the water level
# The float command is used to convert the strings to numbers.
# The difference between the previous and current water level is calculated
if diff_curr > diffmax:
# If the difference (increase) in water level is greater than before, then update the water level difference, time, and date
diffmax = diff_curr
datemax = date_curr
timemax = time_curr
prevline = i
print("The maximum increase in water level was", round(diffmax,3), "that was observed on", datemax, "at", timemax)
# the round function is used to round the water level to three decimal points
# the max water level increase and its time and date are inputted into the print function
| true |
e48c040f638eda0e83d01e812c34386af253b29b | cspyb/Graph-Algorithms | /BFS - Breadth First Search (Iterative).py | 897 | 4.21875 | 4 | """
BFS Algorithm - Iterative
"""
#graph to be explored, implemented using dictionary
g = {'A':['B','C','E'], 'B':['D','E'], 'E':['A','B','D'], 'D':['B','E'], 'C':['A','F','G'], 'F':['C'], 'G':['C']}
#function that visits all nodes of a graph using BFS (Iterative) approach
def BFS(graph,start):
queue = [start] #add nodes yet to be checked
explored = [] #add nodes already checked
while queue: #execute while loop until the list "queue" is empty
node=queue.pop(0) #gets first element of the list "queue"
if node not in explored:
explored.append(node) #add node to the list "explored"
neighbours = graph[node] #assign neighbours of the node
for n in neighbours:
queue.append(n) #adds neighbours of the node to the list "queue"
return explored
print(BFS(g,'A'))
| true |
eb415e333c7e0db6ef2e5542b7daaf6b07813c1c | ElliotFriend/bin | /fibonacci.py | 436 | 4.15625 | 4 | #!/usr/bin/env python3
import sys
# Start the sequence. It always starts with [0, 1]
f_seq = [ 0, 1 ]
# Until the length of our list reaches the limit that
# the user has specified, continue to add to the sequence
while len(f_seq) <= int(sys.argv[1]):
# Add the last two numbers in the list, and stick
# that onto the end of the list
f_seq.append(f_seq[-1] + f_seq[-2])
# Print the list out for all to see.
print(f_seq)
| true |
040c39b646a03fb71fbae182b336d1367ffe8d8c | agermain/Leetcode | /solutions/1287-distance-between-bus-stops/distance-between-bus-stops.py | 1,298 | 4.125 | 4 | # A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n.
#
# The bus goes along both directions i.e. clockwise and counterclockwise.
#
# Return the shortest distance between the given start and destination stops.
#
#
# Example 1:
#
#
#
#
# Input: distance = [1,2,3,4], start = 0, destination = 1
# Output: 1
# Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.
#
#
#
# Example 2:
#
#
#
#
# Input: distance = [1,2,3,4], start = 0, destination = 2
# Output: 3
# Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.
#
#
#
#
# Example 3:
#
#
#
#
# Input: distance = [1,2,3,4], start = 0, destination = 3
# Output: 4
# Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4.
#
#
#
# Constraints:
#
#
# 1 <= n <= 10^4
# distance.length == n
# 0 <= start, destination < n
# 0 <= distance[i] <= 10^4
#
class Solution:
def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
total = sum(distance)
cw = sum(distance[min(start, destination):max(start, destination)])
acw = total-cw
return min(cw, acw)
| true |
486023ab94e7e490a5ca39bfa2224c26c469f617 | beth2005-cmis/beth2005-cmis-cs2 | /cs2quiz3.py | 1,645 | 4.75 | 5 | # 1) What is a recursive function?
# A function calls itself, meaning it will repeat itself when a certain line or a code is called.
# 2) What happens if there is no base case defined in a recursive function?
#It will recurse infinitely and maybe you will get an error that says your maximum recursion is reached.
# 3) What is the first thing to consider when designing a recursive function?
# You have to consider what the base case(s) are going to be because that is when and how your function will end and return something.
# 4) How do we put data into a function call?
# We put data into a function call by using parameters.
# 5) How do we get data out of a function call?
# We get data out of a function call by using parameters.
#a1 = 8
#a2 = 8
#a3 = -1
#b1 = 2
#b2 = 2
#b3 = 4
#c1 = -2
#c2 = 4
#c3 = 45
#d1 = 6
#d2 = 8
#d3 = 4
#Programming
#Write a script that asks the user to enter a series of numbers.
#When the user types in nothing, it should return the average of all the odd numbers that were typed in.
#In your code for the script, add a comment labeling the base case on the line BEFORE the base case.
#Also add a comment label BEFORE the recursive case.
#It is NOT NECESSARY to print out a running total with each user input.
def avg_odd_numbers(sum_n=0, odd_n=0):
n = raw_input("Next number: ")
#Base Case
if n == "":
return "The average of all the odd numbers are {}".format(sum_n/odd_n)
#Recursive Case
else:
if float(n) % 2 == 1:
return avg_odd_numbers(sum_n + float(n), odd_n + 1)
else:
return avg_odd_numbers(sum_n, odd_n)
print avg_odd_numbers()
| true |
31f900dde317cc4b7d78cbedca4c6beb09aa5229 | swheatley/LPTHW | /ex5.2.py | 763 | 4.34375 | 4 | print "LPTHW Lesson 5.2 \n \t Python format characters"
print '% :', "This character marks the start of the specifier"
print 'd :', "Integer/decimal"
print 'i :', "Integer/decimal"
print 'o :', "Octal value"
print 'u :', "Obsolete type- identical to 'd' "
print 'x :', "Hexadecimal(uppercase)"
print 'e :', "Floating point exponential format(lowercase)"
print 'E :', "Floating point exponential format(uppercase)"
print 'f :', "Floating point decimal format"
print 'g :', "Floating point format(lowercase)"
print 'G :', "Floating point format(uppercse)"
print 'c :', "Single character ( accepts integer or single character string)"
print 'r :', "String (converts any Python object using repr())."
print 's :', "String (converts any Python object using str())." | true |
2a0a967462c5958e31e20cbe1cfce34be2a05a93 | pjain4161/HW08 | /fun2.py | 1,139 | 4.25 | 4 | # Borrowed from https://realpython.com/learn/python-first-steps/
##############################################################################
#### Modify the variables so that all of the statements evaluate to True. ####
##############################################################################
var1 = -588
var2 = "pi banana a string"
var3 = ['hi', 'hello', "salut", 'salaam', 'namaste']
var4 = ("pooja", "says", "Hello, Python!")
var5 = {'happy': 1, 'tuna':7, 'egg':'salad'}
var6 = 11.0
###############################################
#### Don't edit anything below this comment ###
###############################################
# integers
print(type(var1) is int)
print(type(var6) is float)
print(var1 < 35)
print(var1 <= var6)
# strings
print(type(var2) is str)
print(var2[5] == 'n' and var2[0] == "p")
# lists
print(type(var3) is list)
print(len(var3) == 5)
# tuples
print(type(var4) is tuple)
print(var4[2] == "Hello, Python!")
# dictionaries
print(type(var5) is dict)
print("happy" in var5)
print(7 in var5.values())
print(var5.get("egg") == "salad")
print(len(var5) == 3)
var5["tuna"] = "fish"
print(len(var5) == 3) | true |
546ee390dfe4711bab61a6648daae43389ec8b4d | irsol/hacker-rank-30-days-of-code | /Day 9: Recursion.py | 446 | 4.3125 | 4 | """
Task
Write a factorial function that takes a positive integer,N as a parameter and prints the result
of N!(N factorial).
Note: If you fail to use recursion or fail to name your recursive function factorial or Factorial,
you will get a score of 0.
Input Format
A single integer,N (the argument to pass to factorial).
"""
def factorial(n):
if n == 1:
return 1
else:
return(n * factorial(n - 1))
print(factorial(10)) | true |
e07b328b02a76c8cc243bcf7002b07cf96f8b8fc | infractus/my_code | /RPG Dice Roller/rpg_dice_roller.py | 2,336 | 4.4375 | 4 | #Dice roller
import random
roll = True #this allows to loop to play again
while roll:
def choose_sides(): #this allows player to choose which sided die to roll
print('Hello!')
while True:
sides=(input('How many sides are the dice you would you like to roll?' ))
if sides.isdigit(): break
print('Choose a proper number of sides.')
return sides
def choose_dice_number(): #choose how many dice to roll
while True:
num_dice=input('How many of these dice would you like to roll?')
if num_dice.isdigit(): break
print('No, you must enter a whole number.')
num_dice=int(num_dice)
while num_dice <=0:
print('Enter a valid number: ')
num_dice=int(input())
return num_dice
sides=choose_sides()
num_dice=choose_dice_number()
subtotal=0
for n in range(num_dice):
result=random.randint(1, int(sides))
result=int(result)
print (result)
subtotal=result+subtotal
#choose a modifier
while True:
print('What is the modifier?')
modifier=input()
if modifier.lstrip('-').isdigit(): break # lstrip for neg number
if modifier.lstrip('+').isdigit(): break
print('No, you must enter a whole number.')
modifier=int(modifier)
resultmod=subtotal+modifier
#creates plus_or_minus variable to properly display the modifier in the results
if modifier >= 0:
plus_or_minus='+'
else:
plus_or_minus='-'
#show results
modifier=str(abs(modifier)) #sets modifier string with an absolute value (no negative)
result=str(result)
resultmod=str(resultmod)
num_dice=str(num_dice)
sides=str(sides)
subtotal=str(subtotal)
#explain what user has rolled
print('You rolled ' + num_dice + 'd' + sides + plus_or_minus + modifier +'.')
print('You rolled ' + subtotal + ' with a ' + plus_or_minus + modifier + ' modifier resulting in a ' + resultmod + '.')
while True:
again=str(input('Do you want to play again? y/n? ')).lower()
if again.startswith('n'):
roll = False
break
elif again.startswith('y'):
roll = True
break
else:
print('Enter "y" or "n".')
| true |
5bd8b16f9adeb479b29a0970406cf62d5e4a7477 | paigeweber13/exercism-progress | /python/clock/clock.py | 1,145 | 4.125 | 4 | """
contains only the clock object
"""
class Clock():
"""
represents a time without a date
"""
def __init__(self, hour, minute):
self.hour = hour
self.minute = minute
self.fix_time()
def __repr__(self):
# return str(self.hour) + ':' + "{:2d}".format(self.minute)
return str(self.hour).zfill(2) + ':' + str(self.minute).zfill(2)
def __eq__(self, other):
return bool(self.hour == other.hour
and self.minute == other.minute)
def __add__(self, minutes):
self.minute += minutes
self.fix_time()
return self
def __sub__(self, minutes):
self.minute -= minutes
self.fix_time()
return self
def fix_time(self):
"""
checks if self is a valid time and fixes it in place if not
"""
while self.minute >= 60:
self.minute -= 60
self.hour += 1
while self.hour >= 24:
self.hour -= 24
while self.minute < 0:
self.minute += 60
self.hour -= 1
while self.hour < 0:
self.hour += 24
| true |
1ac9e7c54261c2c15c3856ccba743791d2e3cd41 | amacharla/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 2,343 | 4.3125 | 4 | #!/usr/bin/python3
class Square:
def __init__(self, size=0, position=(0, 0)):
"""
Calls respective setter funciton
Args:
size: must be int and greater than 0
position: must be tuple and args of it must be int
"""
self.size = size
self.position = position
# SIZE------------------------------------------------------------------------
@property
def size(self):
"""
Getter method
Returns: size
"""
return self.__size
@size.setter
def size(self, value):
""" setter method
Args:
value: must be int and greater than 0
Raises:
TypeError: if size is not int
ValueError: size is less than 0
"""
if type(value) != int:
raise TypeError("size must be an integer")
elif value < 0:
raise ValueError("size must be >= 0")
else:
self.__size = value
# Position--------------------------------------------------------------------
@property
def position(self):
""" Getter method
Returns: position """
return self.__position
@position.setter
def position(self, position):
""" setter method
Args:
position: tuple must be 2 positive int
Raises:
TypeError: position must be a tuple of 2 positive integers
"""
if type(position) != tuple or len(position) != 2 \
or type(position[0]) != int or type(position[1]) != int:
raise TypeError("position must be a tuple of 2 positive integers")
else:
self.__position = position
# Special--------------------------------------------------------------------
def area(self):
""" Returns: current square area """
return self.__size ** 2
def my_print(self):
""" prints square visually with # at position(x, y) """
if self.__size == 0:
print()
else:
x, y = self.__position[0], self.__position[1]
[print() for i in range(y)] # goes down
for j in range(self.__size):
print(" " * x, end='') # goes right set position
print("#" * self.__size) # prints square horozantally then \n
| true |
217c17718277bd9eebc936314da74581bf1c5d07 | Kevin-Rush/CodingInterviewPrep | /Python/findMissingNumInSeries.py | 617 | 4.21875 | 4 | '''
1. Find the missing number in the array
You are given an array of positive numbers from 1 to n, such that all numbers from 1 to n are
present except one number x. You have to find x. The input array is not sorted. Look at the below array
and give it a try before checking the solution.
'''
def find_missing(input):
# calculate sum of all elements
# in input list
sum_of_elements = sum(input)
# There is exactly 1 number missing
n = len(input) + 1
actual_sum = (n * ( n + 1 ) ) / 2
return actual_sum - sum_of_elements
if __name__ == "__main__":
print(find_missing([3, 7, 1, 2, 8, 4, 5]))
| true |
958e8293912a6df866ea3b8821948db8dc3540e4 | Kevin-Rush/CodingInterviewPrep | /Python/TreeORBST.py | 712 | 4.25 | 4 | '''
6. Determine if a binary tree is a binary search tree
Given a Binary Tree, figure out whether it’s a Binary Search Tree. In a binary search tree, each
node’s key value is smaller than the key value of all nodes in the right subtree, and is greater than
the key values of all nodes in the left subtree. Below is an example of a binary tree that is a valid BST.
'''
def is_bst_rec(root, min_val, max_val):
if root == None:
return True
if root.data < min_val or root.data > max_val:
return False
return is_bst_rec(root.left, min_val, root.data) and is_bst_rec (root.right, root.data, max_val)
def is_bst(root):
return is_bst_rec(root, -sys.maxsize-1, sys.maxsize)
#tested in browser | true |
5f815d28e7ed7d3a54819698c3446cdfc6b146c8 | subashreeashok/python_solution | /python_set1/q1_3.py | 486 | 4.15625 | 4 | '''
Name : Subahree
Setno: 1
Question_no:3
Description:get 10 numbers and find the largest odd number
'''
try:
print "enter the numbers: "
max=0
#getting 10 numbers
for i in range(0,10):
num=int(raw_input())
#print(num)
#checking odd or not
for j in range(0,10):
if(num%2!=0):
if(num>max):
max=num
if(max==0):
print "numbers are not odd"
print "largest odd number: "+str(max)
except Exception as e:
print e | true |
4cbba297236116927584453cab7e9d579b93f3a1 | DeltaEcho192/Python_test | /pos_neg_0_test.py | 267 | 4.1875 | 4 | test1=1;
while test1 != 0:
test1=int(input("Please enter a number or to terminate enter 0 "))
if test1 > 1:
print("This number is positve")
elif test1 < 0:
print("This number is negative")
else:
print("This number is zero")
| true |
0c63157083ee466ff665870a7d70c3e0c09c62f6 | 15AshwiniI/PythonPractice | /Calculator.py | 570 | 4.1875 | 4 | #this is how you comment in python
print "Welcome to Calculator!"
print "Enter your first number"
a = input()
print "Enter your second number"
b = input()
print "What calculation whould you like to do?"
print "Addition, Subtraction, Multiplication, Division"
p = raw_input()
if p == "Addition":
print "Answer: "+ str(a + b)
elif p == "Subtraction":
print "Answer: "+ str(a - b)
elif p == "Multiplication":
print "Answer: "+ str(a * b)
elif p == "Division":
print "Answer: "+ str(a / b)
else:
print "Not a valid calculation"
print "goodbye!"
| true |
1d4b7b925e4c71c3bde9b6e62b7ef864f041eb33 | 2amitprakash/Python_Codes | /Grokking_Algo/quicksort.py | 494 | 4.125 | 4 | import random
def quicksort(list):
if len(list) < 2:
return list
else:
pi = random.randint(0,len(list)-1)
#pi = 0
print ("The list is {l} and random index is {i}".format(l=list,i=pi))
pivot = list.pop(pi)
less = [i for i in list if i <= pivot]
more = [i for i in list if i > pivot]
return quicksort(less) + [pivot] + quicksort(more)
#End of function
l=[2,3,6,7,4,6,9,11,-1,5]
print ("The sorted list is - ",quicksort(l))
| true |
1b076c0cac0d11470b6ee48b998ba73b20182317 | TechyAditya/COLLEGE_ASSIGNMENTS | /Python/chapter4/list_methods.py | 395 | 4.1875 | 4 | l1=[1,8,9,5,6,6] #can have same elemnets repeatedly
l1.sort() #arranges in ascending order
print(l1)
l1.reverse() #reverse the list elements
print(l1)
l1.append(10) #adds element at the end of the list
print(l1)
l1.insert(3,69) #adds element at the index mentioned, but doesn't removes the elements
print(l1)
l1.pop(2)# #removes the index
print(l1)
l1.remove(6) #removes the element
print(l1) | true |
c902d56fd3a438b0e7bab5d0df826422979ea800 | HarryBaker/Fuka | /cleanTxtFiles.py | 1,960 | 4.1875 | 4 | # A program that cleans text files when given raw input in the following manner:
# Remove all characters except letters, spaces, and periods
# Convert all letters to lowercase
__author__ = 'loaner'
from sys import argv
class Cleaner:
def __init__(self, input):
raw_file_name = raw_input(input);
file_name = raw_file_name + ".txt";
# Access the raw file
f = open(file_name, "r")
f2 = open((raw_file_name + "_intermediary.txt"), "w")
# First cleanup (by character):
# Cleaning every character that is not a letter, space, or period
# Converting all letters to lowercase
while 1:
char = f.read(1)
if not char: break
if char.isalpha() or char.isspace() or char == '.' : f2.write(char.lower());
f2 = open((raw_file_name + "_intermediary.txt"), "r")
f3 = open((raw_file_name + "_clean.txt"), "w")
wrote_word = False
# Second cleanup:
# Remove unneccessary spaces and newlines longer than one character that was not possible in the previous clean up step
# Remove words that are shorter than 2 characters
for line in f2:
line = line.rstrip()
words = line.split()
for word in words:
wrote_word = False
if len(word)>2:
f3.write(word + " ")
wrote_word = True
if(wrote_word):
f3.write("\n")
f.close()
f2.close()
f3.close()
# Works Cited:
# http://www.tutorialspoint.com/python/python_files_io.htm
# http://learnpythonthehardway.org/book/ex15.html
# http://www.java2s.com/Code/Python/File/Openafileandreadcharbychar.htm
# http://pymbook.readthedocs.org/en/latest/file.html
# http://stackoverflow.com/questions/29359401/open-a-file-split-each-line-into-a-list-then-for-each-word-on-each-line-check
| true |
0ffbe7a1cc9c186c1043d0b683f19ba6499a1602 | onestarshang/leetcode | /validate-binary-search-tree.py | 1,814 | 4.1875 | 4 | #coding: utf-8
'''
http://oj.leetcode.com/problems/validate-binary-search-tree/
Given a binary tree, determine if it is a valid binary search tree (BST).\n\nAssume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.\nOJ's Binary Tree Serialization:\nThe serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.\n
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
'''
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def isValidBST(self, root):
if not root:
return True
is_valid, _, _ = self.is_valid(root)
return is_valid
def is_valid(self, node):
if not node.left and not node.right:
return True, node.val, node.val
is_valid = True
min_val = max_val = node.val
if node.left:
left_valid, left_min, left_max = self.is_valid(node.left)
is_valid = is_valid and left_valid and left_max < node.val
min_val = left_min
if node.right:
right_valid, right_min, right_max = self.is_valid(node.right)
is_valid = is_valid and right_valid and node.val < right_min
max_val = right_max
return is_valid, min_val, max_val
| true |
f3634048b65198301168cf657d3e7ffa463ba159 | onestarshang/leetcode | /decode-string.py | 1,719 | 4.125 | 4 | '''
https://leetcode.com/problems/decode-string/
Given an encoded string, return it's decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
'''
class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
n = len(s)
def decode(start):
r = ''
i = start
while i < n:
c = s[i]
if c.isdigit():
num = 0
while s[i].isdigit():
num = num * 10 + int(s[i])
i += 1
assert s[i] == '['
w, end = decode(i + 1)
r += w * num
i = end
elif c == ']':
return r, i
else:
r += c
i += 1
return r, i
r, _ = decode(0)
return r
if __name__ == '__main__':
f = Solution().decodeString
assert f('') == ''
assert f("3[a]2[bc]") == "aaabcbc"
assert f("3[a2[c]]") == "accaccacc"
assert f("2[abc]3[cd]ef") == "abcabccdcdcdef"
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.