blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
2de9437f4bb2df0f0928ac1928e62efb8e1eaafa | Nihilnia/reset | /Day 16 - Simple Game_Number Guessing.py | 1,782 | 4.21875 | 4 | # Simple Game - Number Guessing
from time import sleep
from random import randint
rights = 5
number = randint(1, 20)
hintForUser = list()
userChoices = list()
for f in range(number - 3, number + 3):
hintForUser.append(f)
print("Welcome to BASIC Number Guessing Game!")
while rights != 0:
print("You have {} rights for find the number!".format(rights))
userChoice = int(input("What's your choice?\n"))
if userChoice in range(1, 21):
if rights == 1:
if userChoice != number:
print("Let me check..")
sleep(2)
rights -= 1
userChoices.append(userChoice)
print("Game is Over baby. Number was", number)
print("And your choices was:", userChoices)
else:
print("Let me check..")
userChoices.append(userChoice)
sleep(2)
print("Well done! Number was", number)
print("Your choices was:", userChoices)
break
elif userChoice == number:
print("Let me check..")
userChoices.append(userChoice)
sleep(2)
print("Well done! Number was", number)
break
elif userChoice in hintForUser:
print("Let me check..")
userChoices.append(userChoice)
sleep(2)
print("\nClose! Try again!\n")
rights -= 1
else:
print("Let me check..")
userChoices.append(userChoice)
sleep(2)
print("\nNot even close!.. Try again!\n")
rights -= 1
else:
print("Mate.. You should give me a number between 1 - 20!") | true |
622934e84d6a56e6a1b627272ff1b4eaf1b62e12 | Nihilnia/reset | /Day 14 - Parameters at Functions.py | 685 | 4.21875 | 4 | # Parameters at Functions
# if we wanna give any parameters to a Function
#we should insert a value while using.
def EvilBoy(a, b):
print("Function 'EvilBoy' Worked!")
return a + b
print(EvilBoy(2, 3))
# that was a classic function as we know.
# But we can make it some default parameters.
def DoosDronk(a = 2, b = 3):
print("Function 'DoosDrunk' Worked!")
return a + b
# Now we have deafult values of parameters.
#If we don't give values while using that function
#Our default values works.
# Using without parameters:
print("Without Parameters:", DoosDronk())
#Using With Parameters:
print("With Parameteres:", DoosDronk(4, 8)) | true |
4e9f13a8c7ecab8c17168286a77e91f07b0c9d73 | favour-22/holbertonschool-higher_level_programming | /0x06-python-classes/5-square.py | 1,124 | 4.34375 | 4 | #!/usr/bin/python3
"""Module containing the Square class"""
class Square:
"""The Square class"""
def __init__(self, size=0):
"""Initializing an instance of Square
Args:
size (int): The size of the Square instance. Default value is 0.
"""
self.size = size
@property
def size(self):
"""int: Value of 'size'"""
return self.__size
@size.setter
def size(self, size):
if not isinstance(size, int):
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
self.__size = size
def area(self):
"""Returns the current square area of the instance
Returns:
int: Value of 'size'
"""
return self.__size ** 2
def my_print(self):
"""Prints a square with hashtags using the 'size'"""
if self.__size is not 0:
for i in range(self.__size):
for j in range(self.__size):
print("#", end="")
print("")
else:
print("")
| true |
867215b59920586cda5067058b049d1373502c6a | skm2000/OOPS- | /Python/Assignment 2/Exercise20/controller.py | 1,907 | 4.25 | 4 | '''
@author: < add your name here >
'''
from tkinter import *
from quiz import Quiz
class Controller:
''' Drive an interactive quiz GUI '''
def __init__(self, window):
''' Create a quiz and GUI frontend for that quiz '''
self.quiz = Quiz()
self.question_text = Text(window, font="arial 16", width = 40, height = 4, wrap = WORD)
self.question_text.insert(1.0, self.quiz.ask_current_question())
self.question_text.pack()
self.answer = StringVar()
self.answerEntry = Entry (window, textvariable = self.answer)
self.answerEntry.pack(side = LEFT)
self.answerEntry.focus_set()
self.answerEntry.bind("<Return>", self.check_answer)
self.instructions = StringVar()
self.instructions.set('\u21D0 Enter your answer here')
self.instrLabel = Label(window, textvariable = self.instructions)
self.instrLabel.pack(side = LEFT)
def check_answer(self, event):
''' Check if the user's current answer is correct '''
if self.quiz.check_current_answer(self.answer.get()):
#Got it right!!
self.instructions.set("Good job! Next question ...")
else:
self.instructions.set("Sorry, the answer was " + self.quiz.get_current_answer())
self.answer.set('')
#Go to the next question if it exists
self.question_text.delete(1.0, END)
if (self.quiz.has_next()):
self.quiz.next()
self.question_text.insert(1.0, self.quiz.ask_current_question())
else:
self.question_text.insert(1.0, 'Sorry, there are no more questions.')
self.answerEntry.configure(state='disabled')
if __name__ == '__main__':
root = Tk()
root.title('Simple Quiz')
app = Controller(root)
root.mainloop()
| true |
6a658a044bee82ceaf20b137cd32ffdc110d1a6b | Aabha-Shukla/Programs | /Aabha_programs/9.py | 300 | 4.34375 | 4 | #Write a program that accepts sequence of lines as input and prints the
#lines after making all characters in the sentence capitalized.
#Suppose the following input is supplied to the program:
str=input('Enter a string:')
if str.lower():
print(str.upper())
else:
print(str.upper())
| true |
691ce469febbe5b4404a3e0fb6e0d65681ab0e2c | Khokavim/Python-Advanced | /PythonNumpy/numpy_matrix_format.py | 497 | 4.53125 | 5 | import numpy as np
matrix_arr =np.array([[3,4,5],[6,7,8],[9,5,1]])
print("The original matrix {}:".format(matrix_arr))
print("slices the first two rows:{}".format(matrix_arr[:2])) # similar to list slicing. returns first two rows of the array
print("Slices the first two rows and two columns:{}".format(matrix_arr[:2, 1:]))
print("returns 6 and 7: {}".format(matrix_arr[1,:2]))
print("Returns first column: {}".format(matrix_arr[:,:1])) #Note that a colon by itself means to take the entire axis
| true |
8801ca4c2ab7197cb3982477f37ed8f743ccac3c | MaineKuehn/workshop-advanced-python-hpc | /solutions/021_argparse.py | 715 | 4.25 | 4 | # /usr/bin/env python3
import argparse
import itertools
import random
CLI = argparse.ArgumentParser(description="Generate Fibonacci Numbers")
CLI.add_argument('--count', type=int, default=random.randint(20, 50), help="Count of generated Numbers")
CLI.add_argument('--start', type=int, default=0, help="Index of first generated Numbers")
def fibonacci():
"""Generate Fibonacci numbers"""
a, b = 0, 1
while True:
yield a
a, b = b, a + b
def main(): # ask me about __main__!
options = CLI.parse_args()
start, count = options.start, options.cout
for value in itertools.islice(fibonacci(), start, start + count):
print(value)
if __name__ == "__main__":
main()
| true |
08f5b82ba5051d45de9dee198e9e50cdd2b47e0a | sadath-ms/ip_questions | /unique_char.py | 523 | 4.15625 | 4 | """
UNIQUE CHARCTER IN A STRING
Given a string determines, if it is compresied of all unique characters,for example
the string 'abcde' has all unique characters it retrun True else False
"""
def unique_char(st):
return len(set(st)) == len(st)
def unique_char_v2(st):
chars = set()
for u in st:
if u in chars:
return False
else:
chars.add(u)
return True
if __name__ == '__main__':
st = "sadath"
result = unique_char_v2(st)
print(result)
| true |
97f80fb49430024d4d1e7d5742ad5f2ba5e73e59 | rishabhworking/python | /takingInputs.py | 293 | 4.34375 | 4 | # Python Inputs
print('Enter the number: ')
num1 = int(input()) # This is how to take an input
print('Enter the power: ')
num2 = int(input())
power=num1**num2
print(num2,'th power of',num1,'is:',power) # This is how you print vars with strs
# int(input())
# float(input())
# str(input())
| true |
5273a16984fb7298dc231b4cdff161d4529ab76b | ja-vu/SeleniumPythonClass | /Class1/onlineExercises/Q6/StringList.py | 537 | 4.40625 | 4 | """
Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.)
https://www.practicepython.org/exercise/2014/03/12/06-string-lists.html
"""
word = input("Give me a word and I will check if this is a palindrome or not: ")
#laval
isPalindrome = False
if word == word[::-1]:
isPalindrome = True
print(word + " is a Palindrome")
else:
print(word + " is not a Palindrome")
print(word + " in reverse order is: " + word[::-1])
| true |
e0d350abd7dc0c984321314ecc148c6b48b4becd | jbhowsthisstuffwork/python_automateeverything | /Practice Projects/theCollatzSequence.py | 968 | 4.375 | 4 | # Create a program that allows a user to input an integer that calls a collatz()
# function on that number until the function returns the value 1.
import time,
userInput = ''
stepsToComplete = 0
def collatz(number):
global userInput
evaluateNumber = number % 2
if evaluateNumber == 0:
userInput = number // 2
print(number)
elif evaluateNumber == 1:
userInput = 3 * number + 1
print(number)
while userInput == '':
try:
userInput = int(input('Enter an integer other than 1.'))
except ValueError:
print('Not a valid integer. Please enter an integer other than 1.')
while userInput != 1:
collatz(userInput)
stepsToComplete = stepsToComplete + 1
# time.sleep(.25) #Pause for .25 seconds
else:
print('You reached', userInput,'and it took',stepsToComplete,'steps to complete.')
#if number = even, then print number // 2
#if number = odd, then print 3 * number + 1
| true |
892c6518f5cd2648b1279998c02168a4c1a00214 | parkjungkwan/telaviv-python-basic | /intro/_12_iter.py | 848 | 4.3125 | 4 | # ***********************
# -- 이터
# ***********************
'''
list = [1,2,3,4]
it = iter(list) # this builds an iterator object
print (next(it)) #prints next available element in iterator
Iterator object can be traversed using regular for statement
!usr/bin/python3
for x in it:
print (x, end=" ")
or using next() function
while True:
try:
print (next(it))
except StopIteration:
sys.exit() #you have to import sys module for this
'''
import sys
def fibonacci(n): #generator function
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(5) #f is iterator object
while True:
try:
print (next(f), end=" ") # 0 1 1 2 3 5
except StopIteration:
sys.exit() | true |
c6453dc21a3783d471a24360a8f96b9f64c89e6e | Edinburgh-Genome-Foundry/DnaFeaturesViewer | /dna_features_viewer/compute_features_levels.py | 2,402 | 4.28125 | 4 | """Implements the method used for deciding which feature goes to which level
when plotting."""
import itertools
import math
class Graph:
"""Minimal implementation of non-directional graphs.
Parameters
----------
nodes
A list of objects. They must be hashable.
edges
A list of the form [(n1,n2), (n3,n4)...] where (n1, n2) represents
an edge between nodes n1 and n2.
"""
def __init__(self, nodes, edges):
self.nodes = nodes
self.neighbors = {n: [] for n in nodes}
for n1, n2 in edges:
self.neighbors[n1].append(n2)
self.neighbors[n2].append(n1)
def compute_features_levels(features):
"""Compute the vertical levels on which the features should be displayed
in order to avoid collisions.
`features` must be a list of `dna_features_viewer.GraphicFeature`.
The method used is basically a graph coloring:
- The nodes of the graph are features and they will be colored with a level.
- Two nodes are neighbors if and only if their features's locations overlap.
- Levels are attributed to nodes iteratively starting with the nodes
corresponding to the largest features.
- A node receives the lowest level (starting at 0) that is not already
the level of one of its neighbors.
"""
edges = [
(f1, f2)
for f1, f2 in itertools.combinations(features, 2)
if f1.overlaps_with(f2)
]
graph = Graph(features, edges)
levels = {n: n.data.get("fixed_level", None) for n in graph.nodes}
def collision(node, level):
"""Return whether the node placed at base_level collides with its
neighbors in the graph."""
line_factor = 0.5
nlines = node.data.get("nlines", 1)
for neighbor in graph.neighbors[node]:
neighbor_level = levels[neighbor]
if neighbor_level is None:
continue
neighbor_lines = neighbor.data.get("nlines", 1)
min_distance = line_factor * (nlines + neighbor_lines)
if abs(level - neighbor_level) < min_distance:
return True
return False
for node in sorted(graph.nodes, key=lambda f: -f.length):
if levels[node] is None:
level = 0
while collision(node, level):
level += 0.5
levels[node] = level
return levels
| true |
26be85957e8f376c3c24c368451c3b5676a75faa | sanketsoni/practice | /practice/even_first_array.py | 685 | 4.46875 | 4 | """ Reorder array entries so that even entries appear first
Do this without allocating additional storage
example-
a = 3 2 4 5 3 1 6 7 4 5 8 9 0
output = [0, 2, 4, 8, 4, 6, 7, 1, 5, 3, 9, 5, 3]
time complexity is O(n), Space complexity is O(1)
"""
def even_first_array(a):
next_even, next_odd = 0, len(a) - 1
while next_even < next_odd:
if a[next_even] % 2 == 0:
next_even += 1
else:
a[next_even], a[next_odd] = a[next_odd], a[next_even]
next_odd -= 1
print(a)
if __name__ == '__main__':
my_array = [int(x) for x in input("Enter Numbers: ").split()]
even_first_array(my_array)
| true |
778862869cc7e90380b8953d186d59de6b49c950 | Banehowl/MayDailyCode2021 | /DailyCode05102021.py | 950 | 4.3125 | 4 | # ------------------------------------------------
# # Daily Code 05/10/2021
# "Basic Calculator (again)" Lesson from edabit.com
# Coded by: Banehowl
# ------------------------------------------------
# Create a function that takes two numbers and a mathematical operator + - / * and will perform a
# calculation with the given numbers.
# calculator(2, "+", 2) -> 4
# calculator(2, "*", 2) -> 4
# calculator(4, "/", 2) -> 2
def calculator(num, operator, num2):
solution = 0
if operator == "+":
solution = num + num2
elif operator == "-":
solution = num - num2
elif operator == "*":
solution = num * num2
elif operator == "/":
if num2 == 0:
return "Can't Divide by 0!"
else:
solution = num / num2
return solution
print calculator(2, "+", 2)
print calculator(2, "*", 2)
print calculator(4, "/", 2)
print calculator(4, "/", 0) | true |
8f872ae832a6b0a8c3296c46581eb390fca1c4e4 | expelledboy/dabes-py-ddd-example | /domain/common/constraints.py | 701 | 4.15625 | 4 |
def create_string(field_name: str, constructor: function, max_len: int, value: str):
"""
Creates a string field with a maximum length.
:param field_name: The name of the field.
:param constructor: The constructor function.
:param max_len: The maximum length of the string.
:param value: The value of the field.
:return: The constructed field.
"""
# check if the value is not empty
if value is None or value == '':
raise ValueError(f'{field_name} cannot be empty.')
# check if the value is not too long
if len(value) > max_len:
raise ValueError(f"{field_name} must be at most {max_len} characters long.")
return constructor(value) | true |
b763671aa6e2edab48338ca9250b4ec7d1039944 | NFellenor/AINT357_Content | /P3_Recursion_Dynamic_Programming/P3_Recursion_Dynamic_Programming/P3_Recursion_Dynamic_Programming.py | 729 | 4.25 | 4 | #Practical 3: Recursion and dynamic programming:
#Recursivley compute numbers 1-N:
def sumOf(n):
if (n <= 1):
return 1
return n + sumOf(n - 1) #Recursive line
print("Input value for n.")
n = int(input()) #Set value for n by user
print("Sum of values from 1 - n:")
print(sumOf(n))
#Recursively compute largest value in array:
def arraySearch(arrayInp, arrayLength):
if (arrayLength == 1):
return arrayInp[0]
return max(arrayInp[arrayLength - 1], arraySearch(arrayInp, arrayLength - 1)) #Tail recursion
arrayInp = [1, 5, 15, 22, 13, 17]
print("Largest value in array:")
print(arraySearch(arrayInp, 6)) #Pass array length as int. BE CAREFUL it MUST be same as actual array's length
| true |
22dc7651851f3296a2eac7d6d7e035a212ad885a | Nishad00/Python-Practice-Solved-Programs | /Validating_Roman_Numerals.py | 588 | 4.1875 | 4 | # You are given a string, and you have to validate whether it's a valid Roman numeral. If it is valid, print True. Otherwise, print False. Try to create a regular expression for a valid Roman numeral.
# Input Format
# A single line of input containing a string of Roman characters.
# Output Format
# Output a single line containing True or False according to the instructions above.
# Constraints
# The number will be between
# and
# (both included).
# Sample Input
# CDXXI
# Sample Output
# True
regex_pattern = r"^M{0,3}(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[VX]|V?I{0,3})$"
| true |
35f10ea897580ce47d4fd020aa9bb9781b1a87e4 | Trent-Farley/All-Code | /Python1/Train Ride/yourturn.py | 621 | 4.40625 | 4 | #Create a trapezoid Calculator-- Here is the formula ((a+b)/2)*h
#USER input
#Create a test to see if an in is even use % (mod) to test
#divisible by zero. USER INPUT
#Find the remainder of a number -- Number can be your choice
#Find the volume and area of a circle from user input
#volume = 4/3 *pi*r^3
#Area = 4 * pi * r^2
bill = "Starter"
while type(bill) != int:
try:
bill = input("What is the bill?\n\n ::")
bill = int(bill)
except:
print("Sorry, wrong data type")
def tip(bill):
tip = bill * .15
return tip
print(f"The tip for a bill of ${bill} is {tip(bill)}")
| true |
9a7a7be1657ff95c6ad6eba58bb1bce27adce8c5 | Trent-Farley/All-Code | /Python1/Old stuff/Assignemt2.py | 671 | 4.375 | 4 | # Farley, Trent
# Assignemt 2
# Problem Analysis: Write a program to calculate the volume
# and surface area of a sphere.
# Program specifications: use the formualas to create a program
# that asked for a radius and outputs the dimensions.
# Design:
# I need to create a float input value. Once that value is calculated,
# I will use the math function to input the radius into the formulat
# Testing:
# if input is 2, the output should be 33 for volume and 50 for area
r=float(input("What is the radius?"))
import math
pi=math.pi
rv=r**3
volume= 4/3 * pi * rv
print(f"This is the volume {volume}")
ra= r ** 2
area= 4* pi* ra
print(f"This is the area {area}") | true |
2b8eb76b4162442da56ba1aaf0ff755e076e7501 | Menda0/pratical-python-2021 | /7_data_structures_exercises.py | 1,228 | 4.40625 | 4 | # 1. Create a list with 5 people names
# 2. Create a tuple with 5 people names
'''
1. Create 6 variables containing animals
(Example: Salmon, Eagle, Bear, Fox, Turtle)
2. Every animal must have the following information
2.1 Name, Color, Sound
3. Create 3 variables for animal families
(Example: Bird, Mamals, Reptiles, Fish)
4. Print on the screen the 3 family animals
5. Print on the screen all the animals
6. Print on the screen 3 equal animals
(Example: 3 Eagles, 3 Bears, 3 Foxes)
'''
# Diogo
salmon = {
"name":"Salmon",
"color":"salmon",
"sound":"gurrp"
}
eagle = {
"name":"eagle",
"color":"brown",
"sound":"pii"
}
bear = {
"name":"bear",
"color":"brown",
"sound":"uaaah"
}
fox = {
"name":"fox",
"color":"orange",
"sound":"lol"
}
whale = {
"name":"Whale",
"color":"Blue",
"sound":"mmmmmmmm"
}
tiger ={
"name":"Tiger",
"color":"Orange",
"sound":"sneaky"
}
mammals = [tiger,bear,whale,fox]
bird = [eagle]
fish = [salmon]
#animals=[salmon,eagle,bear,fox,whale,tiger]
animals=mammals+bird+fish
print("Animals: ", animals)
bears=[bear]*3
print(bears)
list_bear=[bear,bear,bear]
print(list_bear) | true |
7404f874819261a132afccf8937de39a39860cf7 | stahura/school-projects | /CS1400/Projects/rabbits_JRS.py | 2,774 | 4.28125 | 4 | '''
Jeffrey Riley Stahura
CS1400
Project: Rabbits, Rabbits, Rabbits
Due March 10th 2018
Scientists are doing research that requires the breeding of rabbits.
They start with 2 rabbits, 1 male, 1 female.
Every pair reproduces one pair, male and female.
Offspring cannot reproduce until after a month.
Offspring cannot have babies until the following month.
Steps:
Everything must print in a formatted table.
1.Print the following.
A. Months that have passed.
B. Adult rabbit PAIRS(not individuals)(An adult is over 1 month old)
C. Baby rabbit pairs produced in given month(Always a male and female)
D. Total number of rabbit pairs(Adult pairs + baby pairs)
2. Calculate how many months it takes until there are too many rabbits for cages
(There are 500 cages)
3. Don't print any more rows when rabbits exceed cages
4. Print how many months it will take to run out of cages.
* I was stumped on how to remove babies from the baby counter while still adding it to adults
* The solution was creating another variable "lastmonthbabies" and adding that to adults while
* subtracting latmonthbabies from adults to keep the babies variable at the number it should be.
*
*
'''
def main():
print("-----------------------\nRabbits Rabbits Rabbits \n-----------------------")
print("Month Adults Babies Total")
#initialize variables for adults, babies, total, month and last monthbabies
adults = 1
babies = 0
total = adults + babies
month = 1
lastmonthbabies = 0
while total <= 500:
#Print out rows
#Go to next month
#Lastmonth babies needs to be added to adults as part of the new month before babies
# are added to again in the for loop
print("%3d " % month," ", adults," ", babies," ", total, "\n")
month = month + 1
lastmonthbabies = babies
adults = adults + lastmonthbabies
#After the first month, add 1 more baby to babies PER Adult
#Since a baby is no longer a baby after a a month, subtract last months babies
# from adults to get the correct number of babies after each month
#Tally the total amount so that the while loop can stop once it reaches 500
for each in range(1, adults +1):
babies = babies +1
babies = adults - lastmonthbabies
total = adults + babies
#Exited While Loop, print final row and tell user how many months they have.
print("%3d " % month," ", adults," ", babies," ", total, "\n")
print("\nYou will have more rabbits than cages in", month, "months")
main()
| true |
e99e3544eed9a000f67f50aac98fb08c6519c64d | johnsogg/cs1300 | /code/py/lists.py | 482 | 4.125 | 4 | my_empty_list = []
print type(my_empty_list)
my_list = [ 1, 7, 10, 2, 5 ]
my_stringy_list = [ "one", "three", "monkey", "foo"]
my_mixed_list = [ 42, "forty two", True, 61.933, False, None ]
for thing in my_list:
print "My thing is:" + str(thing)
print ""
for thing in my_stringy_list:
print "My stringy thing is: " + thing
squares = []
for num in my_list:
print "num squared is: " + str(num * num)
square = num * num
squares.append(square)
print squares
| true |
12183c6d111eed9b38757e939c3e28ba0051cd01 | tannerbender/E01a-Control-Structues | /main10.py | 1,789 | 4.21875 | 4 | #!/usr/bin/env python3
import sys, utils, random # import the modules we will need
utils.check_version((3,7)) # make sure we are running at least Python 3.7
utils.clear() # clear the screen
print('Greetings!') #printing the word "greetings"
colors = ['red','orange','yellow','green','blue','violet','purple'] #creates a list of colors
play_again = ''
best_count = sys.maxsize # the biggest number
while (play_again != 'n' and play_again != 'no'): #will play again if not correct
match_color = random.choice(colors) #program runs a random color within
count = 0 #creating count
color = '' #allowing user to input a color
while (color != match_color): #color equals match_color
color = input("\nWhat is my favorite color? ") #\n is a special code that adds a new line
color = color.lower().strip() #color is lower case and strip eliminates space issues before and after word
count += 1 # each time the game is played it will ad one to the count prior to getting it correct
if (color == match_color): #if color is correct
print('Correct!')#will print correct
else:
print('Sorry, try again. You have guessed {guesses} times.'.format(guesses=count))#otherwise it will print try again and tell you how many times you guessed
print('\nYou guessed it in {0} tries!'.format(count))
if (count < best_count): #if it was the best guess
print('This was your best guess so far!') #will print this if it is your best and closest guess
best_count = count
play_again = input("\nWould you like to play again? ").lower().strip()#typing play_again will allow you to restart game
print('Thanks for playing!')#ends by saying "thanks for playing" | true |
36cc2b81e8c17f789d8c1271e9edb497fb9b3b28 | FilipposDe/algorithms-structures-class | /Problems vs. Algorithms/problem_2.py | 2,625 | 4.3125 | 4 | def rotated_array_search(input_list, number):
"""
Find the index by searching in a rotated sorted array
Args:
input_list(array), number(int): Input array to search and the target
Returns:
int: Index or -1
"""
if len(input_list) == 0:
return -1
return search(input_list, 0, len(input_list) - 1, number)
def search(arr, left_index, right_index, target):
if left_index > right_index:
return -1
mid_index = (left_index + right_index) // 2
mid_element = arr[mid_index]
if mid_element == target:
return mid_index
if arr[left_index] <= mid_element:
# Leftmost item is smaller than middle element,
# pivot cannot be in left part, so it is sorted
# (equality: there is no left part)
if arr[left_index] <= target and target < mid_element:
# Target is located in the left part
return search(arr, left_index, mid_index - 1, target)
else:
# Target is located in the right part
return search(arr, mid_index + 1, right_index, target)
elif mid_element <= arr[right_index]:
# Rightmost item is bigger than middle element,
# pivot cannot be in right part, so it is sorted
# (equality: there is no right part)
if mid_element <= target and target < arr[right_index]:
# Target is located in the right part
return search(arr, mid_index + 1, right_index, target)
else:
# Target is located in the right part
return search(arr, left_index, mid_index - 1, target)
return -1
print('\n\n___________ TEST 1 ___________')
def linear_search(input_list, number):
for index, element in enumerate(input_list):
if element == number:
return index
return -1
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
print(f'Returned: {linear_search(input_list, number)}, Expected: {rotated_array_search(input_list, number)}')
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6])
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 8])
test_function([[6, 7, 8, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 10])
print('\n\n___________ TEST 2 ___________')
print(rotated_array_search([], 5))
# Expected: -1
print('\n\n___________ TEST 3 ___________')
print(rotated_array_search([2, 3, 4, 1], 1))
# Expected: 3
| true |
94c6d0c3e3b41e61e93a07bff3efb13f19864891 | StefanFischer/Deep-Learning-Framework | /Exercise 3/src_to_implement/Layers/ReLU.py | 1,211 | 4.5 | 4 | """
@description
The Rectified Linear Unit is the standard activation function in Deep Learning nowadays.
It has revolutionized Neural Networks because it reduces the effect of the "vanishing gradient" problem.
@version
python 3
@author
Stefan Fischer
Sebastian Doerrich
"""
import numpy as np
class ReLU:
def __init__(self):
"""
Construct a ReLU-function object.
"""
self.input_tensor = None
def forward(self, input_tensor):
"""
Forward pass for using the ReLU(Rectified Linear Unit)-function.
:param input_tensor: Input tensor for the current layer.
:return: Input tensor for the next layer.
"""
self.input_tensor = input_tensor
relu_passed_input_tensor = np.maximum(0, input_tensor)
return relu_passed_input_tensor
def backward(self, error_tensor):
"""
Backward pass for using the ReLU(Rectified Linear Unit)-function.
:param error_tensor: Error tensor of the current layer.
:return: Error tensor of the previous layer.
"""
relu_passed_error_tensor = np.where(self.input_tensor > 0, error_tensor, [0])
return relu_passed_error_tensor
| true |
4460227115e90388f6b97735aff31ee75e45dc5b | marymarine/sem5 | /hometask2/task2.py | 824 | 4.1875 | 4 | """Task 2: The most popular word"""
def get_list_of_words():
"""return list of input words"""
list_of_words = []
while True:
new_string = input()
if not new_string:
break
list_of_words.extend(new_string.split())
return(list_of_words)
#transform text to list of words
text = get_list_of_words()
#create the dictionary
dictionary = {}
for word in text:
count = dictionary.get(word, 0)
dictionary[word] = count + 1
#find the most popular word
max_count = 0
is_popular = 1
for word in dictionary:
if max_count < dictionary[word]:
max_count = dictionary[word]
popular_word = word
is_popular = 1
elif max_count == dictionary[word]:
is_popular = 0
#print the answer
if is_popular:
print(popular_word)
else:
print("-")
| true |
2cd1ed48f5ae3a42ed397974fd56366d82cc733f | zingpython/kungFuShifu | /day_four/23.py | 1,289 | 4.28125 | 4 |
#Convert an interger to a binary in the form of a string
def intToBinary(number):
#Create empty string to hold our new binary number
binary_number = ""
#While our number is greater than 0 Keep dividing by 2 and adding the remainder to binary_number
while number > 0:
#Divmod divindes the 1st number by the 2nd number and returns a tuple with the format (quotient, remainder)
temp_number = divmod(number, 2)
#Set number equal to the quotient from divmod
number = temp_number[0]
#Next add the remainder to the front of binary_number
binary_number = str( temp_number[1] )+ binary_number
#return binary_number
return binary_number
#Convert a binary string to an integer
def binaryToInteger(binary):
#Create a total that will be returned at the end
total = 0
#Increase is the number to increase the total by if the digit of the binary string is a 1
increase = 1
#For each digit in the binary string we will iterate over it backwards
for index in range(len(binary)-1, -1 ,-1 ):
#If the current digit is a 1 then we need to increase total by the variable increase
if binary[index] == "1":
total = total + increase
#Double increase
increase = increase * 2
#return total
return total
print( intToBinary(2000) )
print( binaryToInteger("11111010000") ) | true |
a37cee394a218707cb0ed3b273b2b37316d7aad1 | zingpython/kungFuShifu | /day_four/7.py | 1,651 | 4.28125 | 4 | import math
class SpaceShip:
target = [] #2 values, X and then Y
coordinate = [] #2 values X and then Y
speed = float()
name = ""
def __init__(self, coordinate, target, speed, name):
self.coordinate = coordinate
self.target = target
self.speed = speed
self.name = name
#To find the distence calculate the hypotenuse and divide by the speed
def calculateSteps(self):
#Get the two sides of out "triangle"
difference_x = self.target[0] - self.coordinate[0]
difference_y = self.target[1] - self.coordinate[1]
#Find the hypotenuse
hypotenuse = math.sqrt( (difference_x ** 2) + (difference_y ** 2) )
#Divide by speed and return the result
return hypotenuse / self.speed
def moveSpeed(self):
#Get the two sides of our "triangle"
difference_x = self.target[0] - self.coordinate[0]
difference_y = self.target[1] - self.coordinate[1]
#Find the hypotenuse
hypotenuse = math.sqrt( (difference_x ** 2) + (difference_y ** 2) )
#Find the angle of our new triangle
angle = math.asin( difference_y / hypotenuse )
#using the angle and speed as out hypotenuse calculate the opposite side of the new triangle
change_y = math.sin(angle) * self.speed
#using the angle and speed as our hypotenuse caclute the adjacent sisde of the new triable
change_x = math.cos(angle) * self.speed
#Add the sides of the new triangle to our x and y coordinates to get our new location
self.coordinate[0] = self.coordinate[0] + change_x
self.coordinate[1] = self.coordinate[1] + change_y
my_ship = SpaceShip([1,1], [5,5], 3, "Enterprise")
print( my_ship.calculateSteps() )
my_ship.moveSpeed()
print(my_ship.coordinate) | true |
ff7553d909f1de5f201c5967b9b0a3a4ba62196f | annanymaus/babysteps | /fibrec.py | 952 | 4.375 | 4 | #!/usr/bin/env python3
#program to find the nth fibonacci number using recursion (and no for loops)
import sys
#function definition
def fib(p):
if (p == 0):
return 0
elif (p == 1):
return 1
else:
#recursive equation
c = fib(p-1) + fib(p-2)
return c
#take an input
print ("Enter a number : ")
n = input()
print() #print empty line
print("˜˜˜˜˜˜˜˜˜˜˜") #aesthetic element
print() #print empty line
#if the input is a negative integer
try:
if (int(n) < 0):
print("i don't need this kind of negativity in my life.")
sys.exit(2) #program ends
#if the input is any other character apart from numbers
except SystemExit: #to handle SystemExit exception thrown by sys.exit() in try
sys.exit(2)
except:
print("input is clearly not a number -___- ")
sys.exit(3) #program ends
#printing the final result
print(fib(int(n)))
sys.exit(4)
| true |
cbbd52a5f99ae5018930bbaa3adf865f6e54fefd | prabhatcodes/Python-Problems | /Placement-Tests/Interview-Prep-Astrea/DS.py | 585 | 4.15625 | 4 | # Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None # Null
class LinkedList:
def __init__(self):
self.head = None
if __name__=="__main__":
llist = LinkedList()
llist.head = Node(1)
second = Node(2)
third = Node(3)
llist.head.next = second # link first node with second
second.next = third # Link second node with the third node
# Linked List traversal
def __init__(self):
temp = self.head
while (temp):
print (temp.data)
temp = temp.next | true |
2762945abefafb8b1bd35f556a8a313c174dad99 | prabhatcodes/Python-Problems | /Data_Structures/Queues/ArrayQueue.py | 1,182 | 4.125 | 4 | class ArrayQueue:
"""FIFO queue implementation using a Python list as underlying
storage"""
DEFAULT_CAPACITY = 10 # moderate capacity for all new queues
def __init__(self):
"""Create an empty queue"""
self._data = [None]*ArrayQueue.DEFAULT_CAPACITY
self._size = 0
self._front = 0
def __len__(self):
"""Return the number of elements in the queue"""
return self._size
def is_empty(self):
"""Return True if the queue is empty"""
return self._size == 0
def first(self):
"""Return (but do not remove) the element from the front
Raise Empty Exception if the Queue is empty"""
if self.is_empty():
raise Empty('Queue is empty')
return self._data[self._front]
def dequeue(self):
"""Remove & Return the first element of the queue(ie FIFO
Raise Empty Exception if the queue is empty"""
if self.is_empty():
raise Empty("Queue is empty")
answer = self._data[self._front]
self._data[self._front]
self._data = (self._front+1)%len(self._data)
self._size-=1
return answer | true |
b94e21fffffeede85942ca87aab41a1ce47a0dfc | sjaney/PDX-Code-Guild---Python-Fullstack-Solution | /python/lab9v2.py | 409 | 4.125 | 4 | # Lab 9v2 ROT Cipher
import string
print('Encrypt your word into a ROT Cipher.')
user = input('Enter a word(s) you would like to encrypt: ')
move = int(input('Enter an amount for rotation: '))
alphabet = string.ascii_lowercase
encryption = ''
for char in user:
if char in alphabet:
new_encrypt = alphabet.index(char) + move
encryption += alphabet[new_encrypt % 26]
print(encryption) | true |
03d19cf620451f9f7d2da74b76cacb689846bdad | holmanapril/Assessment_Quiz | /how_many_questions_v1.py | 456 | 4.1875 | 4 | # Asks how many questions user would like to play
question_amount = int(input("How many questions would you like to play? 10, 15 or 20?"))
# If questions_amount is equal to 10, 15 or 20 it print it
if question_amount == 10 or question_amount == 15 or question_amount == 20:
print("You chose {} rounds".format(question_amount))
# If questions_amount it not one of the choices print please enter 10, 15 or 20
else:
print("Please enter 10, 15 or 20")
| true |
5c4e35cc40030d343bc1cd5504da985827569aa7 | XUMO-97/lpthw | /ex15/ex15.py | 1,610 | 4.375 | 4 | # use argv to get a filename
from sys import argv
# defines script and filename to argv
script, filename = argv
# get the contents of the txt file
txt = open(filename)
# print a string with format characters
print "Here's your file %r:" % filename
# print the contents of the txt file
print txt.read()
txt.close()
# print a sentence
print "Type the filename again:"
# assigns the variable file_again with user's input
file_again = raw_input("> ")
# assigns the variable txt_again with the contents of the txt file
txt_again = open(file_again)
# print the contents of txt_again
print txt_again.read()
txt_again.close()
# study drills 1:Above each line, write out in English what that line does.
# study drills 4:Get rid of the part from lines 10- 15 where you use raw_input and try the script then.
# just print the txt once
# study drills 5:Use only raw_input and try the script that way. Think of why one way of getting the filename would be better than another.
# print "Type the filename again:"
# file_again = raw_input("> ")
# txt_again = open(file_again)
# print txt_again.read()
# if don't use raw_input I needn't to print the filename in python just in command line.
# study drills 7:Start python again and use open from the prompt. Notice how you can open fi les and run read on them right there?
# read=open("C:/Users/18402/lpthw/ex15/ex15_sample.txt")
# read.read()
# read.close()
# study drills 8:Have your script also do a close() on the txt and txt_again variables. It’s important to close fi les when you are done with them.
# ok | true |
457605325a3338e41c9e802600e7b1788b26d476 | ketkiambekar/data-structures-from-scratch | /BFS.py | 728 | 4.3125 | 4 | # Using a Python dictionary to act as an adjacency list
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = set() # Set to keep track of visited nodes of graph.
queue=[]
def bfs(visited, graph, node):
visited.add(node)
queue.append(node)
while queue:
m = queue.pop(0)
print(m)
for neighbour in graph[m]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling
#OUTPUT
# Following is the Breadth-First Search
# 5
# 3
# 7
# 2
# 4
# 8
| true |
e358ecfabb655068f2fb70954677d220ad1104cd | cwalker4/youtube-recommendations | /youtube_follower/db_utils.py | 2,024 | 4.15625 | 4 | import sqlite3
from sqlite3 import Error
def create_connection(db_path):
"""
Creates the sqlite3 connection
INTPUT:
db_path: (str) relative path to sqlite db
OUTPUT:
conn: sqlite3 connection
"""
try:
conn = sqlite3.connect(db_path)
except Error as e:
print(e)
return conn
def create_record(conn, table, data):
"""
Inserts "data" into "table"
INTPUT:
conn: sqlite3 connection
table: (str) table name
data: (str) string or iterable of strings containing data
OUTPUT:
search_id: (int) returns iff table == "searches", id of newly created record
"""
cur = conn.cursor()
if table == "searches":
sql = '''
INSERT INTO searches
(root_video, n_splits, depth, date, sample, const_depth)
VALUES (?,?,?,?,?,?)'''
cur.execute(sql, data)
# return the id of the newly created record
sql = 'SELECT max(search_id) FROM searches'
search_id = cur.execute(sql).fetchone()[0]
return search_id
elif table == "videos":
sql = '''
INSERT INTO videos
(video_id, search_id, title, postdate, description, category,
channel_id, likes, dislikes, views, n_comments)
VALUES (?,?,?,?,?,?,?,?,?,?,?)'''
elif table == "channels":
sql = '''
INSERT INTO channels
(channel_id, search_id, name, country, date_created,
n_subscribers, n_videos, n_views)
VALUES (?,?,?,?,?,?,?,?)
'''
elif table == "recommendations":
sql = '''
INSERT INTO recommendations
(video_id, search_id, recommendation, depth)
VALUES (?,?,?,?)
'''
elif table == "channel_categories":
sql = '''
INSERT INTO channel_categories
(channel_id, search_id, category)
VALUES (?,?,?)
'''
cur.executemany(sql, data)
def record_exists(conn, table, col, val):
"""
Checks whether 'col':'val" exists in 'table'
INPUT:
conn: sqlite3 connection
table: (str) table name
col: (str) column name
val: value
OUTPUT:
bool for whether record exsits
"""
sql = ("SELECT * FROM {} WHERE {} = {}"
.format(table, col, val))
cur = conn.cursor()
return bool(cur.execute(sql).fetchall())
| true |
e37406cab1e981fa6fac68b16cdd9dba407020dd | FrauBoes/PythonMITx | /midterm/midterm str without vowels.py | 621 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 7 14:30:50 2017
@author: thelma
"""
def print_without_vowels(s):
'''
s: the string to convert
Finds a version of s without vowels and whose characters appear in the
same order they appear in s. Prints this version of s.
Does not return anything
'''
s = 'a'
answer = ''
for x in s:
if x != 'a' and x != 'e' and x != 'i' and x != 'o' and x != 'u' and x != 'A' and x != 'E' and x != 'I' and x != 'O' and x != 'U':
answer += x
print(answer)
print_without_vowels("Julia ist klasse bombe") | true |
9888442f8b0c95a2076f5da795ca2e9773a55bd5 | FrauBoes/PythonMITx | /list largest int odd times.py | 583 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 26 15:42:29 2017
@author: thelma
"""
def largest_odd_times(L):
""" Assumes L is a non-empty list of ints
Returns the largest element of L that occurs an odd number
of times in L. If no such element exists, returns None """
L_work = sorted(L)
while len(L_work) > 0 and L_work.count(max(L_work)) % 2 == 0:
del L_work[-(L_work.count(max(L_work))):]
if len(L_work) == 0:
return None
else:
return max(L_work)
print(largest_odd_times([3, 3, 2, 0]))
| true |
213c8884c28e68a3786eecb730f0d4672b031a32 | FrauBoes/PythonMITx | /max value tuple.py | 662 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 31 10:12:33 2017
@author: thelma
"""
def max_val(t):
""" t, tuple or list
Each element of t is either an int, a tuple, or a list
No tuple or list is empty
Returns the maximum int in t or (recursively) in an element of t """
max_int = 0
for element in t:
if type(element) == int:
if element > max_int:
max_int = element
else:
if max_val(element) > max_int:
max_int = max_val(element)
return max_int
print(max_val(([[2, 1, 5], [4, 2], 6], ([2, 1], (7, 7, 5), 6)))) | true |
8bd6ed86b4ea0f992b531f5b229b7026525125c4 | shovals/PythonExercises | /max of 3.py | 307 | 4.34375 | 4 | # max of 3 show the largest number from 3 numbers
One = input('Enter first number: ')
Two = input('Enter second number: ')
Third = input('Enter third number: ')
if One > Third and One > Two:
print 'Max is ', One
elif Two > One and Two > Third:
print 'Max is ', Two
else:
print 'Max is', Third | true |
d5336239b5db506f80269d85f8b0b4bb6ca9f4ab | dcragusa/LeetCode | /1-99/70-79/75.py | 2,062 | 4.34375 | 4 | """
Given an array with n objects colored red, white or blue (represented by integers 0, 1, and 2), sort them in-place so
that objects of the same color are adjacent, with the colors in the order red, white and blue.
Note: You are not suppose to use the library's sort function for this problem.
Example:
Input: [2, 0, 2, 1, 1, 0], Output: [0, 0, 1, 1, 2, 2]
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate over the array counting the number of 0's, 1's, and 2's, then overwrite the array.
Could you come up with a one-pass algorithm using only constant space?
"""
"""
This is a one-pass algorithm with constant space: we iterate over the array, keeping two indices to the front and back
of the array respectively. We make a loop for each element, swapping 0s to the front of the array and 2s to the back,
breaking if we find a 1 or we are moving to the current index. We can stop iterating when we reach the index to the
back of the array, as we know the rest consists of 2s.
"""
def sort_colors(nums):
idx, low, high = 0, 0, len(nums) - 1
while idx <= high:
while True:
val = nums[idx]
if val == 0:
if idx == low:
break
nums[idx], nums[low] = nums[low], nums[idx]
low += 1
elif val == 2:
if idx == high:
break
nums[idx], nums[high] = nums[high], nums[idx]
high -= 1
else:
break
idx += 1
return nums
assert sort_colors([0]) == [0]
assert sort_colors([0, 0]) == [0, 0]
assert sort_colors([0, 1]) == [0, 1]
assert sort_colors([0, 2]) == [0, 2]
assert sort_colors([1, 2]) == [1, 2]
assert sort_colors([2, 1]) == [1, 2]
assert sort_colors([2, 0, 1]) == [0, 1, 2]
assert sort_colors([2, 2, 1, 1, 0, 0]) == [0, 0, 1, 1, 2, 2]
assert sort_colors([2, 0, 2, 1, 1, 0]) == [0, 0, 1, 1, 2, 2]
assert sort_colors([1, 2, 2, 2, 2, 0, 0, 0, 1, 1]) == [0, 0, 0, 1, 1, 1, 2, 2, 2, 2]
| true |
bd42aae37e10dd6af40b2f9deaef942a5bfa4218 | dcragusa/LeetCode | /100-199/110-119/112.py | 1,419 | 4.1875 | 4 | """
Given the root of a binary tree and an integer `target_sum`, return `True` if the tree has a root-to-leaf path
such that adding up all the values along the path equals `target_sum`. A leaf is a node with no children.
Example 1:
Input: root = [5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, 1], target_sum = 22, Output: true (5 + 4 + 11 + 2)
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
Example 2:
Input: root = [1, 2, 3], target_sum = 5, Output: false
1
/ \
2 3
Example 3:
Input: root = [1, 2], target_sum = 0, Output: false
1
/
2
"""
"""
We decrement target_sum as we recur down the list. If we find a leaf node equal to target_sum, then there is a path.
"""
from shared import list_to_tree
def has_path_sum(root, target_sum):
if root is None:
return False
if root.left is None and root.right is None and root.val == target_sum:
return True
return has_path_sum(root.left, target_sum - root.val) or has_path_sum(root.right, target_sum - root.val)
assert has_path_sum(list_to_tree([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, 1]), 22) is True
assert has_path_sum(list_to_tree([1, 2, 3]), 5) is False
assert has_path_sum(list_to_tree([1, 2]), 0) is False
assert has_path_sum(list_to_tree([-2, None, -3]), -5) is True
assert has_path_sum(list_to_tree([8, 9, -6, None, None, 5, 9]), 7) is True
| true |
6b1914ee8aab2ad9a6d4dacc0ade2581acaf5894 | dcragusa/LeetCode | /1-99/90-99/98.py | 1,908 | 4.3125 | 4 | """
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume 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.
Example 1:
2
/ \
1 3
Input: [2, 1, 3], Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Input: [5, 1, 4, None, None, 3, 6], Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
"""
"""
For each node, we obtain the min and max of the left and right side values respectively. If the left max is larger or
the right min is smaller than the node, the tree is invalid. We then propagate the min and max of the node val and the
previously obtained min/maxes upwards. We take when returning the result that a tuple evaluates to True.
"""
from shared import list_to_tree
def is_valid_bst(root):
if root is None or root.val is None:
return True
def recur(node):
vals = [node.val]
if node.left:
recur_left = recur(node.left)
if not recur_left or recur_left[1] >= node.val:
return False
vals.extend(recur_left)
if node.right:
recur_right = recur(node.right)
if not recur_right or recur_right[0] <= node.val:
return False
vals.extend(recur_right)
return min(vals), max(vals)
return bool(recur(root))
assert is_valid_bst(None) is True
assert is_valid_bst(list_to_tree([None])) is True
assert is_valid_bst(list_to_tree([2, 1, 3])) is True
assert is_valid_bst(list_to_tree([5, 1, 4, None, None, 3, 6])) is False
# 10
# / \
# 5 15
# / \
# 6 20
assert is_valid_bst(list_to_tree([10, 5, 15, None, None, 6, 20])) is False
| true |
ab4cde1297d67e70cf920c2288309e179085cdf8 | dcragusa/LeetCode | /1-99/20-29/24.py | 1,823 | 4.34375 | 4 | """
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
"""
"""
Firstly we swap the first two elements. We then iterate across the list, copying the nodes into temporary variables
so as not to mess the order, and reassigning the next params as needed.
From current -> current.next -> current.next.next -> current.next.next.next, we need to swap the central two elements.
We end up with current -> current.next.next -> current.next -> current.next.next.next, then we just move current
two elements along and repeat.
"""
from shared import python_list_to_linked_list, linked_list_to_python_list
def swap_pairs(head):
if not head or not head.next:
return head
current = head
head = head.next
current.next = current.next.next
head.next = current
while current and current.next and current.next.next:
n = current.next
n_n = n.next
n_n_n = n_n.next
n.next = n_n_n
n_n.next = n
current.next = n_n
current = current.next.next
return head
assert linked_list_to_python_list(swap_pairs(None)) == []
head = python_list_to_linked_list([1])
assert linked_list_to_python_list(swap_pairs(head)) == [1]
head = python_list_to_linked_list([1, 2])
assert linked_list_to_python_list(swap_pairs(head)) == [2, 1]
head = python_list_to_linked_list([1, 2, 3])
assert linked_list_to_python_list(swap_pairs(head)) == [2, 1, 3]
head = python_list_to_linked_list([1, 2, 3, 4, 5, 6])
assert linked_list_to_python_list(swap_pairs(head)) == [2, 1, 4, 3, 6, 5]
head = python_list_to_linked_list([1, 2, 3, 4])
assert linked_list_to_python_list(swap_pairs(head)) == [2, 1, 4, 3]
| true |
efd2f12aa8c7ab9bc45d150e747852c70010529f | dcragusa/LeetCode | /1-99/70-79/70.py | 2,026 | 4.28125 | 4 | """
You are climbing a staircase with n steps. Each time you can either climb 1 or 2 steps.
In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2, Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3, Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
"""
"""
We can either set up the base cases for 1 and 2 steps, then recur downwards, adding and memoizing as we go.
Alternatively, we can realise that this is the number of unique permutations of a multiset of varying quantities
of 1s and 2s. For example, for n=6 we must find the unique permutations of the multisets {1, 1, 1, 1, 1, 1},
{2, 1, 1, 1, 1}, {2, 2, 1, 1}, and {2, 2, 2}. The number of unique permutations of a multiset is, as we examined in
problem 62, the multinomial coefficient (n_a + n_b + ... )! / n_a! * n_b! * ... Therefore we just have to calculate
the multinomial coefficients of the multisets with the number of 2s varying from 0 to n // 2.
"""
from math import factorial
from functools import lru_cache
@lru_cache()
def climb_stairs_slow(n):
if n == 1:
return 1
elif n == 2:
return 2
else:
return climb_stairs_slow(n-1) + climb_stairs_slow(n-2)
def climb_stairs_fast(n):
combinations = 1
twos = 1
while twos * 2 <= n:
ones = n - 2*twos
combinations += factorial(twos + ones) // (factorial(twos) * factorial(ones))
twos += 1
return combinations
assert climb_stairs_slow(2) == climb_stairs_fast(2) == 2
assert climb_stairs_slow(3) == climb_stairs_fast(3) == 3
assert climb_stairs_slow(4) == climb_stairs_fast(4) == 5
assert climb_stairs_slow(5) == climb_stairs_fast(5) == 8
assert climb_stairs_slow(6) == climb_stairs_fast(6) == 13
assert climb_stairs_slow(10) == climb_stairs_fast(10) == 89
assert climb_stairs_slow(38) == climb_stairs_fast(38) == 63245986
| true |
1e941dff165827fd643b735fb82593730409c85b | dcragusa/LeetCode | /100-199/110-119/113.py | 1,532 | 4.125 | 4 | """
Given the root of a binary tree and an integer `target_sum`, return `True` if the tree has a root-to-leaf path
such that adding up all the values along the path equals `target_sum`. A leaf is a node with no children.
Example 1:
Input: root = [5, 4, 8, 11, None, 13, 4, 7, 2, None, None, 5, 1], target_sum = 22
Output: [[5, 4, 11, 2], [5, 8, 4, 5]]
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Example 2:
Input: root = [1, 2, 3], target_sum = 5, Output: []
1
/ \
2 3
Example 3:
Input: root = [1, 2], target_sum = 0, Output: []
1
/
2
"""
"""
Similar to 112, except we keep track of the path as we recur down the tree, and append it to a list of results
when we find a matching leaf node.
"""
from shared import list_to_tree
def path_sum(root, target_sum):
results = []
def helper(node, path, target_sum):
if node is None:
return
if node.left is None and node.right is None and node.val == target_sum:
results.append(path + [node.val])
if node.left:
helper(node.left, path + [node.val], target_sum - node.val)
if node.right:
helper(node.right, path + [node.val], target_sum - node.val)
helper(root, [], target_sum)
return results
assert path_sum(list_to_tree([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, 5, 1]), 22) == [[5, 4, 11, 2], [5, 8, 4, 5]]
assert path_sum(list_to_tree([1, 2, 3]), 5) == []
assert path_sum(list_to_tree([1, 2]), 0) == []
| true |
9fbc99a4530e82bbeb3d7e3b378e840ad23a5662 | dcragusa/LeetCode | /100-199/140-149/144.py | 1,042 | 4.15625 | 4 | """
Given the root of a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: root = [1, None, 2, 3], Output: [1, 2, 3]
1
\
2
/
3
Example 2:
Input: root = [], Output: []
Example 3:
Input: root = [1], Output: [1]
Example 4:
Input: root = [1, 2], Output: [1, 2]
1
/
2
Example 5:
Input: root = [1, None, 2], Output: [1, 2]
1
\
2
"""
"""
For preorder traversal, do value, left child, right child.
"""
from shared import list_to_tree
def preorder_traversal(root):
results = []
def helper(node):
if node is None:
return
results.append(node.val)
helper(node.left)
helper(node.right)
helper(root)
return results
assert preorder_traversal(list_to_tree([1, None, 2, 3])) == [1, 2, 3]
assert preorder_traversal(list_to_tree([])) == []
assert preorder_traversal(list_to_tree([1])) == [1]
assert preorder_traversal(list_to_tree([1, 2])) == [1, 2]
assert preorder_traversal(list_to_tree([1, None, 2])) == [1, 2]
| true |
7e6d0cac3b718470e86944b508f19fda5343da79 | dcragusa/LeetCode | /1-99/40-49/43.py | 958 | 4.5625 | 5 | """
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2,
also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3", Output: "6"
Example 2:
Input: num1 = "123", num2 = "456", Output: "56088"
Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contain only digits 0-9.
Both num1 and num2 do not contain any leading zero, except the number 0 itself.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
"""
"""
Fairly trivial to convert strings to numbers indirectly using ord(), also helpful is Python's infinite integers.
"""
def str_to_num(s):
num = 0
for pow_10, digit in enumerate(reversed(s)):
num += (ord(digit) - ord('0')) * 10**pow_10
return num
def multiply(num1, num2):
return str(str_to_num(num1) * str_to_num(num2))
assert multiply('2', '3') == '6'
assert multiply('123', '456') == '56088'
| true |
58df73678cbd095fea3ed3c477f05cbe81eebf9d | dcragusa/LeetCode | /1-99/60-69/67.py | 528 | 4.1875 | 4 | """
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1", Output: "100"
Example 2:
Input: a = "1010", b = "1011", Output: "10101"
"""
"""
This is fairly trivial to do by converting the arguments into integers and the result back into a string.
"""
def add_binary(a, b):
return bin(int(a, 2) + int(b, 2))[2:]
assert add_binary('11', '1') == '100'
assert add_binary('1010', '1011') == '10101'
| true |
c1b6ad529f2be7716814c1a16d4afd51c4aeeddb | dcragusa/LeetCode | /1-99/20-29/22.py | 1,998 | 4.3125 | 4 | """
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
['((()))', '(()())', '(())()', '()(())', '()()()']
"""
"""
We start with one pair of parentheses, which can only be (). For each additional pair, we add an open bracket
to the front [(()], then iterate across the solutions inserting a close bracket after every available open
bracket [()(), (())]. Via recursion we can apply this method to any number of parentheses.
"""
def generate_parentheses(n):
if n == 0:
return set()
if n == 1:
return {'()'}
else:
solutions = set()
for solution in generate_parentheses(n-1):
for idx, char in enumerate(solution := '(' + solution):
if char == '(':
solutions.add(solution[:idx+1]+')'+solution[idx+1:])
return solutions
assert generate_parentheses(0) == set()
assert generate_parentheses(1) == {'()'}
assert generate_parentheses(2) == {'()()', '(())'}
assert generate_parentheses(3) == {'((()))', '(()())', '(())()', '()(())', '()()()'}
assert generate_parentheses(4) == {
'(((())))', '((()()))', '((())())', '((()))()', '(()(()))', '(()()())', '(()())()',
'(())(())', '(())()()', '()((()))', '()(()())', '()(())()', '()()(())', '()()()()'
}
assert generate_parentheses(5) == {
'((((()))))', '(((()())))', '(((())()))', '(((()))())', '(((())))()', '((()(())))', '((()()()))', '((()())())',
'((()()))()', '((())(()))', '((())()())', '((())())()', '((()))(())', '((()))()()', '(()((())))', '(()(()()))',
'(()(())())', '(()(()))()', '(()()(()))', '(()()()())', '(()()())()', '(()())(())', '(()())()()', '(())((()))',
'(())(()())', '(())(())()', '(())()(())', '(())()()()', '()(((())))', '()((()()))', '()((())())', '()((()))()',
'()(()(()))', '()(()()())', '()(()())()', '()(())(())', '()(())()()', '()()((()))', '()()(()())', '()()(())()',
'()()()(())', '()()()()()'
}
| true |
27419cc9188daaf8cf78d2be008f21ce35b4d98c | dcragusa/LeetCode | /1-99/30-39/38.py | 1,668 | 4.28125 | 4 | """
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively,
in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1, Output: "1"
Explanation: This is the base case.
Example 2:
Input: 4, Output: "1211"
Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1",
"2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11",
so the answer is the concatenation of "12" and "11" which is "1211".
"""
"""
We can avoid expensive function calls by simply copying over the list with the next iteration of the sequence.
"""
def count_and_say(n):
digits = [1]
for i in range(2, n+1):
new_digits = []
count = 0
last_digit = None
for digit in digits:
if last_digit and digit != last_digit:
new_digits.extend([count, last_digit])
count = 0
count += 1
last_digit = digit
new_digits.extend([count, last_digit])
digits = new_digits
return ''.join(map(str, digits))
assert count_and_say(1) == '1'
assert count_and_say(4) == '1211'
assert count_and_say(12) == '3113112221232112111312211312113211'
| true |
a7642a80d728d5c5ed8b717e02f31973c13c997d | dcragusa/LeetCode | /1-99/90-99/92.py | 1,845 | 4.21875 | 4 | """
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4, Output: 1->4->3->2->5->NULL
"""
"""
We obtain the first node we are reversing (current), along with the node before that (reversal_head). Then we iterate
along the nodes we are reversing, adding them to a stack. Finally, we go back down the stack, adding the last node to
reversal_head and advancing reversal_head. (If m is 1, that means the head itself is being reversed, so reversal_head
is the first node popped off the stack). Finally, we set the next node to be the continuation of the original list.
"""
from shared import python_list_to_linked_list, linked_list_to_python_list
def reverse_between(head, m, n):
current = head
if m == 1:
reversal_head = None
else:
for _ in range(m-2):
current = current.next
reversal_head = current
current = current.next
stack = []
for _ in range(n-m+1):
stack.append(current)
current = current.next
while stack:
if reversal_head:
reversal_head.next = stack.pop()
reversal_head = reversal_head.next
else:
reversal_head = stack.pop()
head = reversal_head
reversal_head.next = current
return head
assert linked_list_to_python_list(reverse_between(python_list_to_linked_list([1, 2, 3, 4, 5]), 4, 5)) == [1, 2, 3, 5, 4]
assert linked_list_to_python_list(reverse_between(python_list_to_linked_list([1, 2, 3, 4, 5]), 1, 5)) == [5, 4, 3, 2, 1]
assert linked_list_to_python_list(reverse_between(python_list_to_linked_list([1, 2, 3, 4, 5]), 1, 2)) == [2, 1, 3, 4, 5]
assert linked_list_to_python_list(reverse_between(python_list_to_linked_list([1, 2, 3, 4, 5]), 2, 4)) == [1, 4, 3, 2, 5]
| true |
1f30fbf51386a7dff9fdf22a6032fb0f554578e2 | dcragusa/LeetCode | /1-99/50-59/50.py | 1,934 | 4.1875 | 4 | """
Implement pow(x, n), which calculates x raised to the power n (x^n).
Example 1:
Input: 2.00000, 10, Output: 1024.00000
Example 2:
Input: 2.10000, 3, Output: 9.26100
Example 3:
Input: 2.00000, -2, Output: 0.25000, Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
-100.0 < x < 100.0, n is a 32-bit signed integer, within the range [−2^31, 2^31 − 1]
"""
"""
Of course this is batteries included with Python. An alternative implementation is provided below. We cannot keep
multiplying in a range over n as n can be huge. Instead we realise that we can use binary decomposition but
representing powers instead of integers. For example bin(13)=b1101. We go through the binary representation backwards,
representing a power of 13 as powers of 1, 4, 8 multiplied together. The next power in the sequence can be trivially
calculated from the previous one (e.g. power of 8 = power by 4 * power by 4). We just have to watch out for
float precision constraints. Floats generally round out at 17dp so we check this after every iteration of the power
sequence and terminate early if appropriate. We also have to watch out for the negative sign if present.
"""
def my_pow(x, n):
if n < 0:
x = 1/x
sign = -1 if (x < 0 and n % 2) else 1
res, last_power = 1, 0
for pow_2, bit in enumerate(reversed(bin(abs(n))[2:])):
power = abs(x) if not pow_2 else last_power * last_power
last_power = power
if bit == '1':
res *= power
if 0 < last_power < 10**-17:
return 0
elif last_power > 10**17:
return float('inf') * sign
return res * sign
assert my_pow(10.0, 0) == 1
assert my_pow(10.0, 5) == 100000
assert my_pow(10.0, -1) == 0.1
assert my_pow(2.00000, 10) == 1024.00000
assert my_pow(2.10000, 3) == 9.261000000000001
assert my_pow(2.00000, -2) == 0.25000
assert my_pow(-2.0, 2) == 4.0
assert my_pow(-13.62608, 3) == -2529.9550389278597
| true |
9e13c18fc3efdb57e2b52a035f8449b1288e312e | dcragusa/LeetCode | /1-99/70-79/71.py | 2,137 | 4.25 | 4 | """
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the
directory up a level. Note that the returned canonical path must always begin with a slash /, and there must be only
a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /.
Also, the canonical path must be the shortest string representing the absolute path.
Example 1:
Input: '/home/', Output: '/home'
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: '/../', Output: '/'
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:
Input: '/home//foo/', Output: '/home/foo'
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Example 4:
Input: '/a/./b/../../c/', Output: '/c'
Example 5:
Input: '/a/../../b/../c//.//', Output: '/c'
Example 6:
Input: '/a//b////c/d//././/..', Output: '/a/b/c'
"""
"""
Fairly simple, we just split on / and ignore any . or empty spaces as these are repeated slashes or the same directory.
We append any directories to a stack and if there are any .. we pop an item off the stack, if present. Then at the end
we merely join the items from the stack back up again to form the canonical path.
"""
def simplify_path(path):
stack = []
for item in path.split('/'):
if item in ['', '.']:
continue
elif item == '..':
if stack:
stack.pop()
else:
stack.append(item)
return '/' + '/'.join(stack)
assert simplify_path('/home/') == '/home'
assert simplify_path('../../') == '/'
assert simplify_path('') == '/'
assert simplify_path('/a/./.') == '/a'
assert simplify_path('/home//foo/') == '/home/foo'
assert simplify_path('/a/./b/../../c/') == '/c'
assert simplify_path('/a/../../b/../c//.//') == '/c'
assert simplify_path('/a//b////c/d//././/..') == '/a/b/c'
| true |
5f5faa9ed086ea1741a7ac316ecc196fb6ebe763 | dcragusa/LeetCode | /100-199/120-129/129.py | 1,552 | 4.21875 | 4 | """
You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree
represents a number. For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123. Return the total
sum of all root-to-leaf numbers. A leaf node is a node with no children.
Example 1:
Input: root = [1, 2, 3], Output: 25
Explanation: 1->2 represents the number 12. 1->3 represents the number 13. sum = 12 + 13 = 25.
1
/ \
2 3
Example 2:
Input: root = [4, 9, 0, 5, 1], Output: 1026
Explanation: 4->9->5 = 495. 4->9->1 = 491. 4->0 represents the number 40. sum = 495 + 491 + 40 = 1026.
4
/ \
9 0
/ \
5 1
"""
"""
A naive solution might be to pass the path taken down until reaching a leaf node, but a better solution is to realise
that since going down a level shifts the number left, it is equivalent to multiplying by 10. Hence we just have to keep
multiplying by 10 as we go down the path, summing to the total when we reach a leaf node.
"""
from shared import list_to_tree
def sum_numbers(root):
total_sum = 0
def helper(node, path_sum):
nonlocal total_sum
if node is None:
return
path_sum += node.val
if not node.left and not node.right:
total_sum += path_sum
return
helper(node.left, path_sum * 10)
helper(node.right, path_sum * 10)
helper(root, 0)
return total_sum
assert sum_numbers(list_to_tree([1, 2, 3])) == 25
assert sum_numbers(list_to_tree([4, 9, 0, 5, 1])) == 1026
| true |
2016b3800a0096045b21c9268298c6ebdd011527 | dcragusa/LeetCode | /1-99/40-49/49.py | 886 | 4.375 | 4 | """
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [["ate", "eat", "tea"], ["nat", "tan"], ["bat"]]
Note:
All inputs will be in lowercase. The order of your output does not matter.
"""
"""
Firstly we sort each string in the given array - this will allow us to make direct comparisons for anagrams. We then
append each string to a defaultdict with the key being the sorted string. Finally, we return the values of the dict.
"""
from collections import defaultdict
def group_anagrams(strs):
anagrams = defaultdict(list)
for idx, sorted_strs in enumerate(map(lambda x: ''.join(sorted(x)), strs)):
anagrams[sorted_strs].append(strs[idx])
return list(anagrams.values())
assert group_anagrams(['eat', 'tea', 'tan', 'ate', 'nat', 'bat']) == [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
| true |
881e3c309d3efcbe76537c5bea6454795674d692 | dargen3/matematika-a-programovani | /1-lesson/games_with_number/collatz_sequence.py | 573 | 4.21875 | 4 | def collatz_sequence(n): # return number of steps of collatz sequence for n
count = 0
while n != 1:
if n % 2 == 0:
n = n / 2
else:
n = n * 3 + 1
count += 1
return count
def largest_sequence(max): # print number from interval (2, max) which have highest number of collatz steps
num_of_steps = 0
number = 0
for x in range(2, max):
count = collatz_sequence(x)
if count > num_of_steps:
num_of_steps = count
number = x
print(number)
largest_sequence(10000)
| true |
6c2d06066c0e0fcf57ed491e3638a3d56bb92d07 | Swarnabh3131/sipPython | /sip/sipF05_DFsortcreate.py | 413 | 4.15625 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
#https://thispointer.com/pandas-sort-rows-or-columns-in-dataframe-based-on-values-using-dataframe-sort_values/
#df creation
matrix = [(222, 16, 23),(333, 31, 11)(444, 34, 11), ]
matrix
# Create a DataFrame object of 3X3 Matrix
dfObj = pd.DataFrame(matrix, index=list('abc'))
dfObj
dfObj.sort_values(by='b', axis=1)
dfObj.sort_values(by='b', axis=1, ascending=False)
| true |
fd721bc36a9bce2cea562e277cb8ba50a2d155d1 | sewayan/Study_Python | /ex25.py | 1,620 | 4.28125 | 4 | # function will be imported & executed in python
# """ Insert comment text """ -> 'documentation comment'
#if code is run in interpreter, documentation comment = help txt
def break_words(stuff):
"""This func will break up words for us."""
"""put a space between the sperators -> '' """
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off,"""
word = words.pop(0)
print word
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
print word
def sort_sentence(sentence):
"""Takes in full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and the last words of the sentence"""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first & the last one"""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
# below the python-lines
# import ex25
#sentence = "All good things come to those who wait."
#words = ex25.break_words(sentence)
#words
#sorted_words = ex25.sort_words(words)
#sorted_words
#ex25.print_first_word(words)
#ex25.print_last_word(words)
#words
#ex25.print_first_word(sorted_words)
#ex25.print_last_word(sorted_words)
#sorted_words
#sorted_words = ex25.sort_sentence(sentence)
#sorted_words
#ex25.print_first_and_last(sentence)
#ex25.print_first_and_last_sorted(sentence) | true |
45ddd16506befea1a06a2b46f73abd88461a4a1f | shiv-konar/Python-GUI-Development | /FocusingandDisablingWidgets.py | 1,211 | 4.3125 | 4 | import tkinter as tk
from tkinter import ttk # For creating themed widgets
win = tk.Tk() # Create an instance of the Tk class
win.title("Python GUI") # Set the title of the window
win.resizable(0, 0) # Disable resizing the GUI
aLabel = ttk.Label(win, text='Enter a name:') # Create a named Label instance to be used later
aLabel.grid(column=0, row=0) # Create a Label object and pass the win instance
def clickMe(): # Called when the button is clicked
ttk.Label(text='Hello ' + aTextBox.get()).grid(column=0, row=2)
aButton = ttk.Button(win, text='Click Me!',
command=clickMe) # Creates a button and binds an event handler to handle the click
aButton.configure(state='disabled') # Disables the button
aButton.grid(column=1, row=1)
aTextBox = tk.StringVar() # Create a placeholder to hold the value being entered in the textbox
textEntered = ttk.Entry(win,
textvariable=aTextBox) # Create a textbox and set the variable name which will hold the value
textEntered.focus() # Focuses on the textbox i.e. adds a blinking cursor to add focus
textEntered.grid(column=0, row=1)
win.mainloop() # The event which makes the window appear on screen
| true |
b315920c07eed5a3baa4c35ce5d583dac0e1ac23 | Chetali-3/python-coding-bootcamp | /session-9/Strings/hello.py | 450 | 4.34375 | 4 | #Types of functions
"""
# finding out length
name = input("Enter your name")
length = len(name)
print(length)
"""
"""
# capitalising
name = input("Enter your name")
new_name = name.capitalize()
print(new_name)
"""
"""
#finding out a letter
name = input("Enter your name")
new_name = name.find(input("enter the word you wanna find"))
print(new_name)
"""
#replacing
name = input("Enter your name")
new_name = name.replace("li", "na")
print (new_name)
| true |
59bf443228d622dfe3cab82e3d1498ffbfba5dd9 | moses-mugoya/Interview-Practical | /second_largest_number.py | 802 | 4.1875 | 4 | def find_second_largest():
n = input("Enter the value of n: ")
if (int(n) > 10 or int(n) < 2):
print("The value of n should be between 2 and 10")
return
else:
numbers = input("Enter {} numbers separated by a space: ".format(n))
num_list = numbers.split(" ")
num_list = num_list[:int(n)] #slice according to the value of n
largest = num_list[0]
runners_up = num_list[0]
for i in range(len(num_list)):
if num_list[i] > largest:
largest = num_list[i]
for i in range(len(num_list)):
if(num_list[i] > runners_up) and num_list[i] != largest:
runners_up = num_list[i]
return runners_up
runnners_up = find_second_largest()
print("\n")
print(runnners_up) | true |
45aa263197f2257470a192294cce88680e8c839d | Aishwarya-11/Python-learnings | /program2.py | 454 | 4.15625 | 4 | def list() :
print ("Creating a list and performing insertion and deletion operations\n ")
print ("Enter the length :")
length = int(input())
print("Enter the values :")
list1 = []
for i in range(length) :
value = input()
list1.append(value)
print (list1)
print ("Enter the value to insert :")
num1 = input()
list1.insert(0,num)
print (list1)
print (list1.pop())
del list1[-1]
print (list1)
list1.insert(3,list1.pop(2))
print (list1)
| true |
e0d5492aa7d98d9e968aacbdcb6b36d8a057d91b | patilvikas0205/python-Exercise | /Assignment_No_15.py | 568 | 4.4375 | 4 | '''
15. Define a class named Shape and its subclass Square.
The Square class has an init function which takes a length as argument.
Both classes have a area function which can print the area of the shape
where Shape's area is 0 by default.
'''
class Shape:
def area(self):
print("Area Of Shape is: ",0)
class Square(Shape):
def __init__(self,l):
self.length=l
print("Length is: ",self.length)
def area(self):
print("Area of Square is: ",self.length*self.length)
sh=Shape()
sq=Square(5)
sq.area() | true |
6f6ed62f8f510fa72eaaf6120570334ceed1c78c | patilvikas0205/python-Exercise | /Assignment_No_11.py | 853 | 4.28125 | 4 | '''
11. Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
Suppose the following input is supplied to the program:
New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
Then, the output should be:
2 :2
3. :1
3? :1
New :1
Python :5
Read :1
and :1
between :1
choosing :1
or :2
to :1
'''
def summary(text):
count=dict()
words = text.split()
words.sort()
#words.sort(key=str)
for word in words:
if word in count:
count[word]+=1
else:
count[word]=1
return count
text="New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3."
word_fre=summary(text)
#print(word_fre)
for x,y in word_fre.items():
print(x,":",y)
| true |
fd174f0aee0488cd3be6a50bd2da5990fe2fa0c8 | tuanphandeveloper/practicepython.org | /divisors.py | 459 | 4.3125 | 4 |
# Create a program that asks the user for a number and then prints out a list of all the divisors
# of that number. (If you don’t know what a divisor is, it is a number that divides evenly into another
# number. For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)
number = int(input("Please enter a number "))
x = range(1, number)
for num in x:
if (number % num) == 0:
print(str(num) + " is a divisor of " + str(number))
| true |
c2497c1c1f430f290d1eee2c230a26abcd6ab338 | tuanphandeveloper/practicepython.org | /listEnds.py | 356 | 4.15625 | 4 |
# Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25])
# and makes a new list of only the first and last elements of the given list. For practice,
# write this code inside a function.
import random
a = [5, 10, 15, 20, 25]
b = random.sample(range(100), 20)
print(b)
c = []
c.append(b[0])
c.append(b[len(b)-1])
print(c) | true |
51bcb2204eedf71f3a7cf0c7c5ec7c9612919904 | Genius98/HackerrankContestProblem | /Football Points.py | 356 | 4.28125 | 4 | #Create a program that takes the number of wins, draws and losses and calculates the number of points a football team has obtained so far.
WIN = int(input("Enter win match: "))
DRAWS = int(input("Enter draws match: "))
LOSSES = int(input("Enter losses match: "))
points = WIN * 3 + DRAWS * 1 + LOSSES * 0
print("Final pints is = {0}".format(points)) | true |
f8e095325f58a1aa00b659cf173c623738f51014 | Gautam-MG/SL-lab | /pgm6.py | 581 | 4.5625 | 5 | #Concept: Use of del function to delete attributes of an object and an object itself
class Person:
def __init__(self,name,age):#This is the constructor of the class Person
self.name = name;
self.age = age;
p1 = Person("Suppandi",14)
print("\n Name of Person #1 is",p1.name)
print("\n age of a Person #1 is",p1.age)
print("\n *** Printing after deleting age attribute for p1*** ")
del p1.age # Deleting the age attribute for p1 object
print("\n Name of Person #1 is",p1.name)
print("\n*** Printing after Deleting p1***")
del p1
print("\n Name of Person #1 is",p1.name)
| true |
122ce533b91ca38868f0c31ec49c17162500453d | ProgressBG-Python-Course/ProgressBG-VMware-Python-Code | /lab3/comparison_operators.py | 1,306 | 4.21875 | 4 | """
Notes:
Lexicographical Comparison:
First the first two items are compared, and if they differ this determines the outcome of the comparison.If they are equal, the next two items are compared, and so on, until either sequence is exhausted
Comparison operator Chaining:
https://docs.python.org/3/reference/expressions.html#comparisons
"""
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# example 1
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
print('"9" > "10000" = {}'.format("9" > "10000") )
# what Python is doing is like:
# print(ord("9") > ord("1"))
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# example 2
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
print('"12" > "1000" = {}'.format("12" > "1000"))
# what Python is doing is like:
# print(ord("2") > ord("0")),
# as the first symbols are the same
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# example 3
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
print('1<5<10 = {}'.format(1<5<10))
# equivalent to: 1<5 and 5<10
print('1<5>10 = {}'.format(1<5>10))
# equivalent to: 1<5 and 5>10
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# example 4
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# next will throw a TypeError, as Python3
# will not compare "oranges" with "apples"
# Python2 will be ok with that
print('"3" > 2 = {}'.format("3" > 2)) | true |
8443ae90b2b72e1f1a91c6fdc098df29528dd82d | USussman/rambots-a19 | /Classes/driver.py | 2,514 | 4.125 | 4 | #!/usr/bin/env python3
"""
Driver class module
Classes
-------
Driver
interface with wheels for holonomic drive
"""
from .motor import Motor
import math
class Driver:
"""
A class for driving the robot.
Methods
-------
drive(x, y, r)
drive with directional components and rotation.
rDrive(a, v, r)
wrapper on drive for angle, velocity, rotation
spin(r)
wrapper to rotate at given speed
halt()
drive wrapper to stop robot
"""
def __init__(self, *pins):
"""
Creates motor object attributes.
"""
self.motors = tuple(Motor(*pin_set) for pin_set in pins)
def drive(self, x, y, r):
"""
Drive the robot with direction components.
:param x: x velocity
:param y: y velocity
:param r: rotation
"""
mpowers = [0, 0, 0, 0]
x = min(max(x, -100), 100)
y = min(max(y, -100), 100)
mpowers[0] = y + x + r
mpowers[1] = -y + x + r
mpowers[2] = -y - x + r
mpowers[3] = y - x + r
max_power = max(abs(m) for m in mpowers)
if max_power > 0:
scale = 100 / max_power
else:
scale = 0
mpowers = tuple(m * scale for m in mpowers)
for i in range(4):
self.motors[i].run(mpowers[i])
def drive_angle(self, a, v, r=0):
"""
Wrapper for driving in direction at speed.
:param a: angle relative to robot's front, 0-360 degrees
:param v: velocity, 0-100% of full speed
:param r: clockwise rotation, 0-100% of full speed
"""
rad = (a - 90) * math.pi / 180
x = v * math.cos(rad)
y = v * math.sin(rad) * -1
self.drive(int(x), int(y), r)
def spin(self, r):
"""
Spin the robot on spot
:param r: clockwise rotation, 0-100% of full speed
"""
self.drive(0, 0, r)
def halt(self):
"""
Stops all wheels.
"""
self.drive(0, 0, 0)
def drive_angle2(self, a, v, r, offset):
"""
Wrapper for rotating while driving in a straight line
:param a: angle relative to forward direction, 0-360 degrees
:param v: velocity, 0-100% of full speed
:param r: clockwise rotation, 0-100% of full speed
:param offset: offset from forward from compass
"""
self.drive_angle((a + offset) % 360, v, r)
| true |
d3075a86a63b8fa4b649aefaacee1ff999cd6138 | HakujouRyu/School | /Lab 5/nextMeeting.py | 1,084 | 4.3125 | 4 | todaysInt = 8
while todaysInt < 0 or todaysInt > 7:
try:
todaysDay = input("Assuming Sunday = 0, and Saturday = 6, please enter the day of the week: ")
todaysInt = int(todaysDay)
except ValueError:
if todaysDay == "help":
print("Monday 0")
print("Tuesday 1")
print("Wednesday 3")
print("Thursday 4")
print("Friday 5")
print("Saturday 6")
todaysInt = 8
else:
print("Error: Please enter valid day code.")
print("Type 'help' to see day codes.")
todaysInt = 8
daysLeft = int(input("How many more days until your next meeting? "))
meetingDay = ((todaysInt + daysLeft) % 7)
dict = {
0: "Sunday",
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday"
}
todaysInt = dict[todaysInt]
meetingDay = dict[meetingDay]
print("Today is ", todaysInt, ".", sep='')
print("You have ", daysLeft, " until your next meeting. ", sep= '')
print("Meeting Day is ", meetingDay, ".", sep='')
| true |
fe703b6364b1835b433410da896166adaf129654 | elijahsk/cpy5python | /practical04/q05_count_letter.py | 509 | 4.1875 | 4 | # Name: q05_count_letter.py
# Author: Song Kai
# Description: Find the number of occurences of a specified letter
# Created: 20130215
# Last Modified: 20130215
# value of True as 1 and value of False as 0
def count_letter(string,char):
if len(string)==1: return int(string[0]==char)
return int(string[0]==char)+count_letter(string[1:],char)
# input the string and char
string=input("Enter a string: ")
char=input("Enter a specific char you want to serach: ")
# print
print(count_letter(string,char))
| true |
66488b56ef595a4ce86f4936262ce9c47c2030d0 | elijahsk/cpy5python | /practical03/q08_convert_milliseconds.py | 813 | 4.1875 | 4 | # Name: q08_convert_milliseconds.py
# Author: Song Kai
# Description: Convert milliseconds to hours,minutes and seconds
# Created: 20130215
# Last Modified: 20130215
# check whether the string can be converted into a number
def check(str):
if str.isdigit():
return True
else:
print("Please enter a proper number!")
return False
# the convert process
def convert_ms(n):
string=""
# calculate the number of hours
string+=str(n//3600000)
n%=3600000
# calculate the number of minutes
string+=":"+str(n//60000)
n%=60000
# calculate the number of seconds
string+=":"+str(n//1000)
return string
# input the time
n=input("Enter the time in milliseconds: ")
while not check(n):
n=input("Enter the time in milliseconds: ")
# print
print(convert_ms(int(n)))
| true |
6dce3c4965f32564385623ffb9ef1528a180a016 | siddk/hacker-rank | /miscellaneous/python_tutorials/mobile_number.py | 469 | 4.125 | 4 | """
mobile_number.py
Given an integer N, and N phone numbers, print YES or NO to tell if it is a valid number or not.
A valid number starts with either 7, 8, or 9, and is 10 digits long.
"""
n = input()
for i in range(n):
number = raw_input()
if number.isdigit():
number = int(number)
if (len(str(number)) == 10) and (int(str(number)[0]) in [7,8,9]):
print "YES"
else:
print "NO"
else:
print "NO"
| true |
b90e89de330807f02410bee5f6faa321376c0a26 | siddk/hacker-rank | /miscellaneous/python_tutorials/sets.py | 684 | 4.3125 | 4 | """
sets.py
You are given two sets of integers M and N and you have to print their symmetric difference in ascending order. The first line of input contains the value of M followed by M integers, and then N and N integers. Symmetric difference is the values that exist in M or N but not in both.
"""
m = input()
m_lis = raw_input()
n = input()
n_lis = raw_input()
m_list = m_lis.split()
m_list = list(map(int, m_list))
n_list = n_lis.split()
n_list = list(map(int, n_list))
m_set = set(m_list)
n_set = set(n_list)
intersect = m_set.intersection(n_set)
for i in intersect:
m_set.remove(i)
n_set.remove(i)
union = m_set.union(n_set)
for i in sorted(union):
print i
| true |
cbb33de2960bed126ad694a163a15aca703bc40a | askwierzynska/python_exercises | /exercise_2/main.py | 702 | 4.125 | 4 | import random
print('-----------------------------')
print('guess that number game')
print('-----------------------------')
print('')
that_number = random.randint(0, 50)
guess = -1
name = input("What's your name darling? ")
while guess != that_number:
guess_text = input('Guess number between 0 an 50: ')
guess = int(guess_text)
if guess < that_number:
print('{0}Your guess of {1} was too low. Keep trying!'.format(name, guess))
elif guess > that_number:
print('{0}Your guess of {1} was too big. Keep trying!'.format(name, guess))
else:
print('Huge congrats {0}! {1} was that number!'.format(name, guess))
print('')
print('done. thanks ;)')
| true |
1607baf5554044a4870c9402e79c1ae0867faa0e | obayomi96/Algorithms | /Python/simulteneous_equation.py | 786 | 4.15625 | 4 | # solving simultaneous equation using python
print('For equation 1')
a = int(input("Type the coefficient of x = \n"))
b = int(input("Type the coefficient of y = \n"))
c = int(input("Type the coefficient of the constant, k = \n"))
print("For equation 2")
d = int(input("Type the coefficient of x = \n"))
e = int(input("Type the coefficient of y = \n"))
f = int(input("Type the coefficient of the constant, k = \n"))
def determinant():
return((a*e) - (b*d))
x = determinant()
# print(x) to output: a*e - b*d
def cofactors():
return((e*c) + (-1 * d * f)) / determinant(), ((-1 * b * c) + (a * 5)) / determinant()
z = cofactors()
#print(z) output: (e*c) + (-1 * d * f) / determinant(), ((-1 * b * c) + (a * 5)) / determinant()
print("Answer = (x,y)")
print(cofactors())
| true |
9b6acd981eb913452c020d5bd66aac70f329fd6c | heyhenry/PracticalLearning-Python | /randomPlays.py | 1,096 | 4.15625 | 4 | import random
randomNumber = random.randint(1, 10)
randomNumber = str(randomNumber)
print('✯ Welcome to the guessing game ✯')
username = input('✯ Enter username: ')
guessesTaken = 0
print(username, 'is it? \nGreat name! \nOkay, the rules are simple.\n')
print('⚘ You have 6 attempts. \n⚘ Enter a number ranging between 1 - 10. \n⚘ Heed the warnings after each attempt.\n')
while guessesTaken < 6:
guess = input('Guess the number:')
guess = str(guess)
guessesTaken += 1
if guess < randomNumber:
print("A little higher...")
elif guess > randomNumber:
print("A little lower...")
elif guess == randomNumber:
print("\nCongratulations! You guessed it right!")
break
if guess != randomNumber:
print('\nOh no! You ran out of attempts. The correct number was', randomNumber + '.\n')
print('Taking you to the stats screen now...\n')
print('\nStats: ')
print('The actual number: ', randomNumber, '\nLast guess: ', guess, '\nAttempts taken: ', guessesTaken)
print('\nThank you. Come again ( ͡👁️ ͜ʖ ͡👁️)✊!')
| true |
39f360ae4828952b4da6249bacfadda4671911d2 | aryashah0907/Arya_GITSpace | /Test_Question_2.py | 454 | 4.40625 | 4 | # 3 : Write a Python program to display the first and last colors from the following list.
# Example : color_list = ["Red","Green","White" ,"Black"].
# Your list should be flexible such that it displays any color that is part of the list.
from typing import List
color_list = ["Red", "Green", "White", "Black", "Pink", "Azure", "Brown"]
newColorlist = color_list[0]
finalColorlist = color_list[len(color_list) - 1]
print(newColorlist + finalColorlist)
| true |
ac9de1f5797579203874fef062220415cc7a3c13 | cvhs-cs-2017/sem2-exam1-LeoCWang | /Function.py | 490 | 4.375 | 4 | """Define a function that will take a parameter, n, and triple it and return
the result"""
def triple(n):
n = n * 3
return (n)
print(triple(5))
"""Write a program that will prompt the user for an input value (n) and print
the result of 3n by calling the function defined above. Make sure you include
the necessary print statements and address any issues with whitespace. """
def usertriple(n):
n = 3 *n
return n
print (usertriple(float(input('Please enter a number'))))
| true |
1712892d8d87ea7ffc0532bedeb31afd088c47bc | damianserrato/Python | /TypeList.py | 693 | 4.46875 | 4 | # Write a program that takes a list and prints a message for each element in the list, based on that element's data type.
myList = ['magical unicorns',19,'hello',98.98,'world']
mySum = 0
myString = ""
for count in range(0, len(myList)):
if type(myList[count]) == int:
mySum += myList[count]
elif type(myList[count]) == str:
myString += myList[count]
myString = "String: " + myString
print myString
mySum = "Sum: " + myString
if mySum > 0 and len(myString) > 1:
print "The list you entered is of a mixed type"
elif mySum > 0 and len(myString) == 0:
print "The list you entered is of an integer type"
else:
print "The list you entered is of a string type" | true |
2d5273b86616f827bed2a4496b4fe6854acf5ac3 | damianserrato/Python | /FindCharacters.py | 388 | 4.15625 | 4 | # Write a program that takes a list of strings and a string containing a single character, and prints a new list of all the strings containing that character.
word_list = ['hello','world','my','name','is','Anna']
char = 'o'
newList = []
for count in range(0, len(word_list)):
for c in word_list[count]:
if c == "o":
newList.append(word_list[count])
print newList | true |
8a833841f94024fa0c6e5185a78d4b404716ba8c | Hikareee/Phyton-exercise | /Programming exercise 1/Area of hexagon.py | 266 | 4.3125 | 4 | import math
#Algorithm
#input the side
#calculate the area of the hexagon
#print out the area
#input side of hexagon
S = eval(input("input the side of the hexagon: "))
#area of the hexagon
area=(3*math.sqrt(3)*math.pow(S,2))/2.0
#print out the area
print (area) | true |
0fd112e01e2545fb78af3211f1f1d12dd0159d24 | Lukhanyo17/Intro_to_python | /Week7/acronym.py | 538 | 4.15625 | 4 | def acronym():
acro = ''
ignore = input("Enter words to be ignored separated by commas:\n")
title = input("Enter a title to generate its acronym:\n")
ignore = ignore.lower()
ignore = ignore.split(', ')
title = title.lower()
titleList = title.split()
titleList.append("end")
for k in range(len(titleList)-1):
if(not titleList[k] in ignore):
word = titleList[k]
acro += word[0]
print("The acronym is: "+acro.upper())
acronym()
| true |
a51357020c8422857735e9092ed7b35fa3992060 | samvelarakelyan/ACA-Intro-to-python | /Practicals/Practical5/Modules/pretty_print.py | 667 | 4.25 | 4 |
def simple_print(x:int):
"""
The function gets an integer and just prints it.
If type of function argument isn't 'int' the function print 'Error'.
"""
if isinstance(x,int):
print("Result: %d" %x)
else:
print("Error: Invalid parametr! Function parametr should be integer")
def pro_print(x:int):
"""
The function gets an integer and just prints it.
If type of function parametr isn't 'int' the function print 'Error'.
"""
if isinstance(x,int):
print("The result of the operation is %d" %x)
else:
print("Error: Invalid parametr! Function parametr should be integer")
| true |
6ca26100985fc23524b13578e97cde54a42f2f70 | twhay/Python-Scripts | /Dice Simulator.py | 509 | 4.21875 | 4 | # Python Exercise - Random Number Generation - Dice Generator
# Import numpy as np
import numpy as np
# Set the seed
np.random.seed(123)
# Generate and print random float
r = np.random.rand()
print(r)
# Use randint() to simulate a dice
dice = np.random.randint(1,7)
print(dice)
# Starting step
step = 50
# Finish the control construct
if dice <= 2 :
step = step - 1
elif dice <=5 :
step = step + 1
else :
step = step + np.random.randint(1,7)
# Print out dice and step
print(dice)
print(step) | true |
6065b6d6ecb45e18d532a5a3bcf765851e97d1eb | iMeyerKimera/play-db | /joins.py | 929 | 4.34375 | 4 | # -*- coding: utf-8 -*-
# joining data from multiple tables
import sqlite3
with sqlite3.connect("new.db") as connection:
c = connection.cursor()
# retrieve data
c.execute("""
SELECT population.city, population.population,
regions.region FROM population, regions
WHERE population.city = regions.city ORDER BY population.city ASC
""")
rows = c.fetchall()
for r in rows:
print "City: " + r[0]
print "Population: " + str(r[1])
print "Region: " + r[2]
print
# Take a look at the SELECT statement.
# Since we are using two tables, fields in the SELECT statement must adhere
# to the following format: table_name.column_name (i.e., population.city ).
# In addition, to eliminate duplicates, as both tables include the city name,
# we used the WHERE clause as seen above.
# finally organize the outputted results and clean up the code so it’s more compact | true |
2909e9da710ee8da8f33f9c67687f697c8db7385 | lorenanicole/abbreviated-intro-to-python | /exercises/guessing_game_two.py | 1,143 | 4.34375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import random
"""
ITERATION THREE: Now that you have written a simple guessing
game, add some logic in that determines if the game is over
when either:
* user has correctly guesses the number
* user has reached 5 guesses
Let's use two functions:
* is_guess_correct
* display_user_output
STRETCH: In the case user loses, show correct number.
In the case user wins tell them how many guesses it took for
them to win. Both situations show user all guesses they made.
"""
def display_user_output(num_to_guess, guessed_num):
"""
:param: guessed_num - number user guessed
:param: num_to_guess - number the user has to guess
:returns string saying if the guess is too high, too low, or match
"""
def is_guess_correct(num_to_guess, guessed_num):
"""
:param: guessed_num - number user guessed
:param: num_to_guess - number the user has to guess
:returns boolean True if correct else False
"""
game_not_over = False
turns = 0
while game_not_over:
# TODO: ask for user input
# determine what message to show user
# determine if guess is correct | true |
b9a599544b5dbf2e0cf855cfe9b848f3fec098eb | juliakyrychuk/python-for-beginners-resources | /final-code/oop/car.py | 777 | 4.25 | 4 | class Car:
"""Represents a car object."""
def __init__(self, colour, make, model, miles=0):
"""Set initial details of car."""
self.colour = colour
self.make = make
self.model = model
self.miles = miles
def add_miles(self, miles):
"""Increase miles by given number."""
self.miles += miles
def display_miles(self):
"""print the current miles value."""
print(
f'{self.make} {self.model} ({self.colour}) '
f'has driven {self.miles} miles.'
)
astra = Car('Red', 'Vauxhall', 'Astra')
astra.display_miles()
astra.add_miles(100)
astra.display_miles()
prius = Car('Blue', 'Toyota', 'Prius', 1000)
prius.display_miles()
prius.add_miles(50)
prius.display_miles() | true |
70504fde426af3e446033709871f1d5219844539 | Farmerjoe12/PythonLoanLadder | /pythonLoanLadder/model/Loan.py | 1,234 | 4.1875 | 4 | import numpy
import math
class Loan:
""" A representation of a Loan from a financial institution.
Loans are comprised of three main parts, a principal
or the amount for which the loan is disbursed, an interest rate
because lending companies are crooked organizations which charge
you money for borrowing their money, and a term for which
the repayment period is defined.
Fields:
name: A descriptive name for a loan
interest_rate: The interest rate given by a lender (%5.34)
principal: The amount of money that is lent
term: the repayment period (in years)
"""
def __init__(self, name, interest_rate, principal):
self._name = name
self._interest_rate = interest_rate
self._principal = principal
def get_interest_rate(self):
return self._interest_rate
def get_principal(self):
return self._principal
def get_name(self):
return self._name
def to_string(self):
result = "Loan Name: {}\n".format(self._name)
result += "Principal: {}\n".format(self._principal)
result += "Interest Rate: %{}".format(self._interest_rate)
return result | true |
0a0558e50b0bd8f9f41348596aae5c06ac66c7e7 | LIZETHVERA/python_crash | /chapter_7_input_while/parrot.py | 788 | 4.3125 | 4 | message = input ("Tell me something, and i will repetar it back to you: ")
print (message)
name = input ("please enter your name: ")
print ("hello, "+ name + "!")
prompt = "If you tell us who you are, we can personalize the messages you see"
prompt += "\nWhat is your first name?"
name = input (prompt)
print ("\nHello," + name + "!")
prompt = "Tell me something, and i will repeat the message to you: "
prompt += "\nEnter 'quit' to end the program. ?"
message = ""
while message != "quit":
message = input (prompt)
print (message)
prompt = "Tell me something, and i will repeat the message to you: "
prompt += "\nEnter 'quit' to end the program. ?"
message = ""
while message != "quit":
message = input (prompt)
if message != "quit":
print (message)
| true |
f25f1e4333a6c8a4ef1f22eb18a430ad3be862ab | olsgaard/adventofcode2019 | /day01_solve_puzzle1.py | 801 | 4.5 | 4 | """
Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
For example:
For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.
For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2.
For a mass of 1969, the fuel required is 654.
For a mass of 100756, the fuel required is 33583.
"""
def calculate_fuel(mass):
return int(mass / 3) - 2
assert calculate_fuel(12) == 2
assert calculate_fuel(14) == 2
assert calculate_fuel(1969) == 654
assert calculate_fuel(100756) == 33583
with open("input.txt01") as f:
lines = f.readlines()
result = sum([calculate_fuel(int(mass)) for mass in lines])
print(result)
| true |
77da7fdefd5a5ddc68ce5652094f4ad1b627d3a3 | stefantoncu01/Pizza-project | /pizza_project.py | 2,981 | 4.125 | 4 | class Pizza:
"""
Creates a pizza with the attributes: name, size, ingredients
"""
def __init__(self, name, size):
self.name = name
self.size = size
self.ingredients = None
@property
def price(self):
"""
Calculates the price based on size and ingredients
"""
price_per_ingredient = 3
size_price = {
"small": 1,
"medium": 1.2,
"large": 1.5
}
return size_price[self.size] * len(self.ingredients) * price_per_ingredient
class VeganPizza(Pizza):
"""
Creates a vegan pizza by inheriting attributes from Pizza class
"""
def __init__(self, name, size):
super().__init__(name, size)
self.ingredients = ['tomato_sauce', 'pepper', 'olives']
class CarnivoraPizza(Pizza):
"""
Creates a carnivora pizza by inheriting attributes from Pizza class
"""
def __init__(self, name, size):
super().__init__(name, size)
self.ingredients = ['tomato_sauce', 'cheese', 'chicken', 'parmesan', 'spinach']
class PepperoniPizza(Pizza):
"""
Creates a pepperoni pizza by inheriting attributes from Pizza class
"""
def __init__(self, name, size):
super().__init__(name, size)
self.ingredients = ['tomato_sauce', 'cheese', 'salami', 'habanero_pepper']
class HawaiianPizza(Pizza):
"""
Creates a hawaiian pizza by inheriting attributes from Pizza class
"""
def __init__(self, name, size):
super().__init__(name, size)
self.ingredients = ['tomato_sauce', 'cheese', 'pineapple', 'coocked_ham', 'onion']
class Client:
"""
Creates a client with the attributes name, address, has_card(bool)
"""
def __init__(self, name, address, has_card=True):
self.name = name
self.address = address
self.has_card = has_card
class Order:
"""
Creates an order based on the Client class and products (a list of Pizza objects)
"""
def __init__(self, client, products):
self.client = client
self.products = products
@property
def total_price(self):
"""
Calculates the total price of the order based on products attributes. If the client has_card a 10% discount should be applied.
"""
price = sum([product.price for product in self.products])
if self.client.has_card:
return price * 0.9
return price
@property
def invoice(self):
"""
Table formatted string containing all products associated with this order, their prices, the total price, and client information
"""
result ='\n'.join([f'{product.name} - {product.price}' for product in self.products])
result += f'\nThe total price is {self.total_price}! \nThe delivery will be in {self.client.address}!'
return result
| true |
e378f29d1bd2dbf43f88f0a0d2333f811150be2f | scvetojevic1402/CodeFights | /CommonCharCount.py | 660 | 4.15625 | 4 | #Given two strings, find the number of common characters between them.
#Example
#For s1 = "aabcc" and s2 = "adcaa", the output should be
#commonCharacterCount(s1, s2) = 3.
#Strings have 3 common characters - 2 "a"s and 1 "c".
def commonCharacterCount(s1, s2):
num=0
s1_matches=[]
s2_matches=[]
for i in range(0,len(s1)):
if i not in s1_matches:
for j in range(0,len(s2)):
if j not in s2_matches:
if s1[i]==s2[j]:
num+=1
s1_matches.append(i)
s2_matches.append(j)
break
return num
| true |
c2d0e8489e7783edf1fc6a5548825a77da605e57 | dayanandtekale/Python_Basic_Programs | /basics.py | 1,303 | 4.125 | 4 | #if-else statements:
#score=int(input("Enter your score"))
#if score >=50:
# print("You have passed your exams")
# print("Congratulations")
#if score <50:
# print("Sorry,You have failed Exam")
#elif statements:
#score=109
#if score >155 or score<0:
# print("Your score is invalid")
#elif score>=50:
# print("You have passed your exam")
# print("Congratulations!")
#else:
# print("Sorry,You have failed Exam")
#while loop:
#count= 5
#while count <=10:
# print(count)
# count= count + 1
#number = int(input("Enter a number: "))
#count = 1
#while count >= 10:
# product = number * count
# print(number, "x" ,count, "=", product)
# count = count + 1
#for loop in python:
#text = "Python"
#for character in text:
# print(character)
#languages = ["English","French","German"]
#for language in languages:
# print(language)
#count=1
#while count <= 5:
# print(count)
# count = count + 1
#using for loop in 1 sentence we get same op:
#for count in range(1,6):
# print(count)
#for table of any number in (1-11)
#number = int(input("Enter an integer: "))
#for count in range(1,11):
# product = number * count
# print(number, "X", count, "=", product)
| true |
613a833ae062123c4f5a81af2e957fb28fea74cd | cxdy/CSCI111-Group4 | /project1/GroupProect1 BH.py | 1,054 | 4.40625 | 4 | firstname1 = input("Enter a first name: ")
college = input("Enter the name of a college: ")
business = input("Enter the name of a business: ")
job = input("Enter a job: ")
city = input("Enter the name of a city: ")
restaurant = input("Enter the name of a restaurant: ")
activity1 = input("Enter an activity: ")
activity2 = input("Enter another activity: ")
animal = input("Enter a type of animal: ")
firstname2 = input("Enter a different first name: ")
store = input("Enter the name of a store: ")
# Display the paragraph with all the inputs in the console
print(f"There once lived a person named {firstname1} who recently graduated from {college}. After accepting a job with {business} as a(n) {job}, {firstname1} decided to first take a vacation to {city}. Upon arriving in {city}, {firstname1} planned to visit {restaurant} before enjoying an evening of {activity1} and {activity2}. The next day, {firstname1} adopted a(n) {animal} named {firstname2} found in front of an abandoned {store}. {firstname1} and {firstname2} lived happily ever after .")
| true |
10e396f5019fd198a588d543c6746a642867496c | DSR1505/Python-Programming-Basic | /04. If statements/4.05.py | 309 | 4.15625 | 4 | """ Generate a random number between 1 and 10. Ask the user to guess the number and print a
message based on whether they get it right or not """
from random import randint
x = randint(1,10)
y = eval(input('Enter a number between 1 and 10: '))
if(x == y):
print('You get it right')
else:
print('Try again') | true |
4c590e8a0ff2058228a40e521d4dc31b1978ee9e | DSR1505/Python-Programming-Basic | /02. For loops/2.14.py | 276 | 4.34375 | 4 | """ Use for loops to print a diamond. Allow the user to specify how high the
diamond should be. """
num = eval(input('Enter the height: '))
j = (num//2)
for i in range(1,num+1,2):
print(' '*j,'*'*i)
j = j - 1
j = 1
for i in range(num-2,0,-2):
print(' '*j,'*'*i)
j = j + 1 | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.