blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0efd56aafc1c50ef62a5f830f72c268928233ac7 | EdwardCamilleri/Python-exercises | /Project4.py | 1,361 | 4.375 | 4 | # taking user input for their name and their room measurements
name = input("What is your name? ")
Length = float(input("What is the length of the room?: "))
Width = float(input("What is the width of the room?: "))
# calculating the area from the measurements and displaying it to the user
Area = Length * Width
print("The Area of your room is " + str(Area) + " Meters squared.")
# loop to compare the users area against the area limit
maxarea = open("Area Limit.txt", "r").read()
if float(Area) > float(maxarea):
print("Sorry this room size is too big and is not available.")
else:
print("This room size is available.")
# writing the users name and room area to the log file
open("Area Logs.txt", "a").write(name + " " + str(Area) + " Meters Squared room" + "\n")
# loop to give user the option to change the area limit
config = input("Would you like to change the room area limit? (Y/N) ")
if config == "Y":
open("Area Limit.txt", "w").write(input("please enter your new area limit"))
# small message to close out the program and show the user that the interaction is over
print("Area limit successfully changed, Have a nice day!")
elif config == "N":
# small message to close out the program and show the user that the interaction is over
print("All options exhausted, Have a nice day!")
| true |
5592c8d2ad9005d62dddb737d02bcacba113854c | pavoli/checkIO | /home/house_password.py | 1,537 | 4.125 | 4 | # -*- coding: utf-8 -*-
__author__ = 'p.olifer'
"""
Input: A password as a string (Unicode for python 2.7).
Output: Is the password safe or not as a boolean or any data type that can be converted and processed as a boolean.
In the results you will see the converted results.
"""
#str = 'A1213pokl'
#str = 'bAse730onE'
#str = 'asasasasasasasaas'
#str = 'QWERTYqwerty'
#str = '123456123456'
#str = 'QwErTy911poqqqq'
str = 'ULFFunH8ni'
def checkio(str):
if len(str) < 10:
return False
digit = 0
lower_str = 0
upper_str = 0
for i in str:
if i.isdigit():
digit += 1
if i.islower():
lower_str += 1
if i.isupper():
upper_str += 1
print('digit= ', digit, '| lower=', lower_str, '| upper=', upper_str)
if digit >= 1 and lower_str >= 1 and upper_str >= 1:
return True
else:
return False
"""
def checkio(data):
if len(data) < 10: return False
islower = isupper = isdigit = False
for c in data:
if "a" <= c <= "z": islower = True
if "A" <= c <= "Z": isupper = True
if "0" <= c <= "9": isdigit = True
return islower and isupper and isdigit
"""
"""
checkio = lambda s: not(
len(s) < 10
or s.isdigit()
or s.isalpha()
or s.islower()
or s.isupper()
)
"""
"""
import re
def checkio(data):
return True if re.search("^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$", data) and len(data) >= 10 else False
"""
if __name__ == '__main__':
print(checkio(str)) | true |
8bc19bc8b5f4e92d2e69058ec02dacb602eba280 | pavoli/checkIO | /elementary/first_word.py | 411 | 4.15625 | 4 | # -*- coding: utf-8 -*-
import re
#s = 'Hello world'
#s = 'greetings, friends'
#s = ' a word '
#s = "don't touch it"
#s = "... and so on ..."
s = "Hello.World"
def first_word(str):
new_str = str.replace(',', ' ')
new_str = new_str.replace('.', ' ')
for i in new_str.split(' '):
if re.search('^([a-z]|[A-Z])+',i):
return i
if __name__ == '__main__':
print(first_word(s)) | false |
6d92dc6ffd87e186b1979cd126ee7624cc827b12 | RachelAJ/movie-picker | /movie_picker.py | 2,465 | 4.28125 | 4 | # Imported random module to populate a random movie from the lists when program runs and genre is chosen.
import random
# Added help function for instructions on how to retrieve a movie suggestion
def help():
print("Hey there, looking for a movie to watch? Follow these instructions to get some great suggestions!:")
print("""
Enter one of the following genres you would like a movie suggestion from: 'Horror', 'Comedy', or 'Fantasy'.
Enter 'E' to exit program.
""")
# Added snack and drink suggestion functions when movie is picked. Both functions are called in Master Loop.
def snack_ideas():
print("Snack suggestion:", random.choice(snacks))
def drink_ideas():
print("Drink suggestion:", random.choice(drinks))
# Pre-populated lists with movies separated into genres to be retrieved when program runs.
horror_movies = ["Halloween", "Friday the 13th", "The Shining", "Trick 'r Treat", "Nightmare on Elm Street"]
comedy_movies = ["Monty Python and the Holy Grail", "School of Rock", "The Blues Brothers", "Mean Girls", "Mrs. Doubtfire"]
fantasy_movies = ["Star Wars", "Lord of the Rings", "Harry Potter", "The Chronicles of Narnia", "The Hobbit"]
# Pre-poulated lists of snacks and drinks to be retrieved when 'snack_idea()' and 'drink_idea()' functions are called
snacks = ["Popcorn", "Nachos", "Cookie Dough Bites", "Snowcaps", "Hot Dog", "Chips"]
drinks = ["Cherry Coke", "Sprite", "Root Beer", "Milkshake", "ICEE"]
# Beginning of Master Loop
help()
while True:
choose_genre = input("Enter a genre or exit program: ")
choose_genre = choose_genre.lower().replace(" ", "")
if choose_genre == "E".lower().replace(" ", ""):
break
elif choose_genre == "Horror".lower().replace(" ", ""):
print(choose_genre + ", " + "oooo spooky!")
print("You should watch", random.choice(horror_movies) + "!")
elif choose_genre == "Comedy".lower().replace(" ", ""):
print("Ahh yes, " + choose_genre + ", " + "get ready for a laugh!")
print("You should watch", random.choice(comedy_movies) + "!")
elif choose_genre == "Fantasy".lower().replace(" ", ""):
print("Time to escape reality with a", choose_genre + "!")
print("You should watch", random.choice(fantasy_movies) + "!")
else:
try:
raise ValueError
except ValueError:
print("Please choose from the 3 genres listed.")
continue
snack_ideas()
drink_ideas()
| true |
f95834e4c14fc68e697ea499c9be449ae7d38c06 | mishabulychev/lesson2 | /ex2.py | 656 | 4.5 | 4 | #Написать функцию, которая принимает на вход две строки.
#Если строки одинаковые, возвращает 1.
#Если строки разные и первая длиннее, возвращает 2.
#Если строки разные и вторая строка 'learn', возвращает 3.
def line(one,two):
if len(one) == len(two):
return 1
elif len(one) > len(two):
return 2
elif len(one) != len('learn'):
return 3
one = input ('Введите первую строку: ')
two = input ('Введите вторую строку: ')
result = line(one,two)
print (result)
| false |
16f9201fd1a1234b1cb3f7000144f19609191541 | mishabulychev/lesson2 | /ex1.py | 671 | 4.375 | 4 | #Попросить пользователя ввести возраст.
#По возрасту определить, чем он должен заниматься: учиться в детском саду, школе, ВУЗе или работать.
#Вывести занятие на экран.
age = int(input("Введите свой возраст: "))
if age <= 6:
print ("В детском саду ждет воспитатель!!")
elif age <= 18:
print ("Вы должны учиться в школе")
elif age <= 22:
print ("Вы должны учиться в ВУЗе")
elif age > 22 :
print ("Вы должны работать")
| false |
c5e6d36234e1a8f418035921ca9cc0d0a509beef | IntroGM/2017 | /teaching_material/docs/build/html/_static/ball.py | 482 | 4.21875 | 4 | z = 1.8 # Starting elevation
Vz = 15 # Initial vertical velocity
nt = 6 # In how many steps we do the calculation
tottime = 3 # Total time (s) to calculate
# The total time and the number of time steps
# together implicitly set the size of the time step, dt.
dt = tottime / nt
print ("Size of one time step is:", dt, "seconds")
print ("Time, elevation:")
for it in range(nt):
t = it * dt
z = (Vz - 0.5 * 9.81 * t**2) * dt + z
print(t+dt, z)
| true |
18997d069c235c13224e8a3c35fb968ffbf0fdcc | calvinsettachatgul/cara | /algorithms/create_phone.py | 777 | 4.3125 | 4 | # https://www.codewars.com/kata/create-phone-number/train/python
'''
Write a function that accepts an array of 10 integers (between 0 and 9),
that returns a string of those numbers in the form of a phone number.
Example:
create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) # => returns "(123) 456-7890"
The returned format must be correct in order to complete this challenge.
Don't forget the space after the closing parentheses!
'''
# TODO: create a test file
def create_phone_number(num_list):
num_str_list = list(map(str, num_list))
delimiter = ""
area_code = delimiter.join(num_str_list[0:3])
num_part1 = delimiter.join(num_str_list[3:6])
num_part2 = delimiter.join(num_str_list[6:])
return "({}) {}-{}".format(area_code, num_part1, num_part2)
| true |
b560fcb5ccd40d73e62f94e10381ec2512e927a7 | cs-richardson/mario-mando210 | /Mario Less.py | 659 | 4.28125 | 4 | '''
This program prints out a half-pyramid of a given height from the user
Miki Ando
'''
#get the height of the half-pyramid from the user
height = input("Height: ")
#If the values are not a digit or is not in the range between 0 and 23,
#the program asks the user to re-enter the height
while not(height.isdigit()) or int(height) < 0 or int(height) > 23:
height = input("Retry: ")
#height is turned into an integer
height = int(height)
#prints out the half-pyramid where 2 blocks are starting at the top
for i in range(2, height + 2):
block = "#" * i
space = " " * (height - (i - 1))
print(space + block)
| true |
14d2a3fc2ee8c1198ec58c228012bc748a4e53dc | anu1236/327983_Python-L1-Assignments | /Program20.py | 918 | 4.34375 | 4 | """Write a program to generate a Fibonacci series of numbers.
Starting numbers are 0 and 1, new number in the series is generated by adding previous two numbers in the series.
Example : 0, 1, 1, 2, 3, 5, 8,13,21,.....
a) Number of elements printed in the series should be N numbers, Where N is any +ve integer.
b) Generate the series until the element in the series is less than Max number."""
# a) Number of elements printed in the series should be N numbers, Where N is any +ve integer.
N = input("Enter number of elements you want to print:")
a = 0
b = 1
c = 0
print a
print b
for x in range(0, N-2):
c = a + b
a = b
b = c
print c
# b) Generate the series until the element in the series is less than Max number.
N = input("Enter number of elements you want to print:")
a = 0
b = 1
c = 0
print a
print b
for x in range(0, N):
c = a + b
a = b
b = c
if c < N:
print c
| true |
21ae544f6c493c34ae6d95395a5ee1cc5d7763d9 | blizzarj2671/CTI110 | /P1HW1_BlizzardJacob.py | 697 | 4.5 | 4 | # This program calculates gross pay.
def main():
# Get the number of hours worked.
hours = int(input("How many hours did you work?"))
# Get the hourly pay rate.
pay_rate = float(input("Enter your hourly pay rate:"))
#Calculate the gross pay.
gross_pay = hours + pay_rate
#Display the gross pay.
print("Gross pay: $", format(gross_pay, ",.2f"), sep="")
#Call the main function.
main()
# This program demonstrates how the range
# function can be used with a for loop.
def main():
# Print a message five times.
for x in range(5):
print ("This is your gross pay, also its Jacob Blizzard.")
# Call the main function.
main()
| true |
f4434efc3548ff30383969490bb380cbc422ff19 | Diogogrosario/FEUP-FPRO | /RE05/sumNumbers.py | 282 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 23 21:34:31 2018
@author: diogo
"""
def sum_numbers(n):
"""
returns the sum of all positive integers up to and including n
"""
sum=0
for i in range(n+1):
sum = sum + i
return sum | true |
3699d238f394b27bdf3bc9b11a64ef3ba147e231 | smmvalan/Python-Learning | /initial_file/swap.py | 781 | 4.25 | 4 | # To display the swapping numbers
'''
num1 = input('Enter First Number: ')
num2 = input('Enter Second Number: ')
print("Value of num1 before swapping: ", num1)
print("Value of num2 before swapping: ", num2)
# swapping two numbers using temporary variable
temp = num1
num1 = num2
num2 = temp
print("Value of num1 after swapping: ", num1)
print("Value of num2 after swapping: ", num2)
'''
def swapNumber (num1, num2) :
'enter the two integer numbers'
temp = num1
num1 = num2
num2 = temp
return num1,num2
def main () :
num1 = int (input ("Enter the first number before swap :"))
num2 = int (input("Enter the second number before swap :"))
print ("the number after swapping {}\t\{}".format(num1,num2))
swapNumber (num1,num2)
main ()
| true |
3205da52a54ce26105e52ca6458eb79b7bff02cd | sacheenanand/Python | /geek2.py | 223 | 4.21875 | 4 | __author__ = 'sanand'
# Given starting and end points, write a Python program to print all even numbers in that given range.
string, end = 2, 15
for num in range(2, 15):
if num % 2 == 0:
print(num, end = " ")
| true |
97d39b0a56c7603ad807de597aa08afaec16d8d7 | sacheenanand/Python | /geeks4.py | 349 | 4.15625 | 4 | __author__ = 'sanand'
# Using for loop : Iterate each element in the list
# using for loop and check if num % 2 != 0. If the condition satisfies, then only print the number.
list1 = [2, 3, 7, 9, 10, 11, 14]
for num in list1:
if num % 2 != 0:
print(num, end = ' ')
only_odd = [num for num in list1 if num % 2 == 1]
print(only_odd)
| true |
8439b7921f6cdae036bfa940f6d859103250276c | wwweiwang/classwork | /assignment3/partB.py | 245 | 4.375 | 4 | cities = ['seattle', 'kirkland', 'bellevue']
print ("I have been to:")
for city in cities:
print (city)
cities.append(input("Which city do you want to go?"))
print ("In the future, I will have been to:")
for city in cities:
print (city)
| false |
241effd980397abcab8ea967a5ebeb6f537d6cff | blackbat13/Algorithms-Python | /integers/fibonacci.py | 487 | 4.375 | 4 | def fibonacci_iterative(n: int) -> int:
if n <= 2:
return 1
f1: int = 1
f2: int = 1
for i in range(3, n + 1):
f3 = f1 + f2
f1 = f2
f2 = f3
return f2
def fibonacci_recursive(n: int) -> int:
if n <= 2:
return 1
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
n: int = int(input('Enter number to compute: '))
print(f'Iterative: {fibonacci_iterative(n)}')
print(f'Recursive: {fibonacci_recursive(n)}')
| false |
a1d0050f85aefd5c9b75ed0bff7f3ee910c64e63 | blackbat13/Algorithms-Python | /numerical/monte_carlo_pi_plot.py | 1,095 | 4.34375 | 4 | import random
import matplotlib.pyplot as plt
def monte_carlo_pi(points_count: int) -> float:
"""Computes the estimated value of PI using a Monte Carlo method.
Args:
points_count (int): number of points to draw
Returns:
float: the estimated value of PI, using a Monte Carlo approach.
"""
num_points_in_circle = 0
center_x = 1
center_y = 1
radius = 1
x = 0
y = 0
distance = 0
plot_values = []
for i in range(1, points_count + 1):
x = random.random() * 2.0
y = random.random() * 2.0
distance = ((x - center_x) ** 2) + ((y - center_y) ** 2)
if distance <= radius ** 2:
num_points_in_circle += 1
plot_values.append((4 * num_points_in_circle) / i)
plt.plot(plot_values)
plt.xlabel("Number of points")
plt.ylabel("Estimated PI value")
plt.title("Monte Carlo method for computing PI value")
return (4 * num_points_in_circle) / points_count
points_count = 1000
estimated_pi = monte_carlo_pi(points_count)
print(f"PI ~= {estimated_pi}")
plt.show()
| true |
e390b914f9270c89b339ec56b767a061fd7f1b33 | blackbat13/Algorithms-Python | /numerical/monte_carlo_pi.py | 804 | 4.28125 | 4 | import random
def monte_carlo_pi(points_count: int) -> float:
"""Computes the estimated value of PI using a Monte Carlo method.
Args:
points_count (int): number of points to draw
Returns:
float: the estimated value of PI, using a Monte Carlo approach.
"""
num_points_in_circle = 0
center_x = 1
center_y = 1
radius = 1
x = 0
y = 0
distance = 0
for _ in range(points_count):
x = random.random() * 2.0
y = random.random() * 2.0
distance = ((x - center_x) ** 2) + ((y - center_y) ** 2)
if distance <= radius ** 2:
num_points_in_circle += 1
return (4 * num_points_in_circle) / points_count
points_count = 1000
estimated_pi = monte_carlo_pi(points_count)
print(f"PI ~= {estimated_pi}")
| true |
cf41ba500f5558c226855bc8de1017f2e3f144d4 | wael20-meet/meet2018y1lab1 | /MEETinTurtle.py | 1,521 | 4.1875 | 4 |
import turtle
# Everything that comes after the # is a
# comment.
# It is a note to the person reading the code.
# The computer ignores it.
# Write your code below here...
turtle.penup() #Pick up the pen so it doesn’t
#draw
turtle.goto(-200,-100) #Move the turtle to the
#position (-200, -100)
#on the screen
turtle.pendown() #Put the pen down to start
#drawing
#Draw the M:
turtle.goto(-200,-100+200)
turtle.goto(-200+50,-100)
turtle.goto(-200+100,-100+200)
turtle.goto(-200+100,-100)
turtle.penup() #Pick up the pen so it doesn’t
#draw
turtle.goto(-200,-100) #Move the turtle to the
#position (-200, -100)
#on the screen
turtle.pendown() #Put the pen down to start
#drawing
#Draw the M:
turtle.goto(-200,-100+200)
turtle.goto(-200+50,-100)
turtle.goto(-200+100,-100+200)
turtle.goto(-200+100,-100)
turtle.penup()
turtle.goto(-50,-100)
turtle.pendown()
turtle.goto(-50,+100)
turtle.goto(+50,+100)
turtle.goto(-50,+100)
turtle.goto(-50,-15)
turtle.goto(50,-15)
turtle.goto(-50,-15)
turtle.goto(-50,-100)
turtle.goto(+50,-100)
turtle.penup()
turtle.goto(100,-100)
turtle.pendown()
turtle.goto(100,+100)
turtle.goto(200,100)
turtle.goto(100,+100)
turtle.goto(100,-10)
turtle.goto(200,-10)
turtle.goto(100,-10)
turtle.goto(100,-100)
turtle.goto(200,-100)
turtle.penup()
turtle.goto(300,-100)
turtle.pendown()
turtle.goto(300,100)
turtle.goto(225,100)
turtle.goto(375,100)
# ...and end it before the next line.
turtle.mainloop()
| true |
ad7d2a0f51c83c6decf043284d6dee6f9aa391b9 | Reeftor/python-project-lvl1 | /brain_games/games/brain_progression.py | 995 | 4.125 | 4 | # -*- coding:utf-8 -*-
"""Brain_progression game logic."""
from random import randint
GAME_DESCR = 'What number is missing in the progression?'
def generate_progression():
"""Generate arithmetic progression for brain_progression game.
Returns:
progression and missing number.
"""
num = randint(1, 100)
step = randint(1, 10)
length = 10
progression = ''
pos_to_hide = randint(0, length - 1)
for pos in range(length):
if pos == pos_to_hide:
num_to_hide = str(num)
progression += ' {0}'.format('..')
else:
progression += ' {0}'.format(num)
num += step
progression = progression[1:]
return (progression, num_to_hide)
def make_question():
"""Brain_progression game function.
Returns:
question, correct_answer
"""
progression, correct_answer = generate_progression()
question = 'Question: {0}'.format(progression)
return question, correct_answer
| true |
afdf75b4411599c8901b85fe7486ed11fff531bb | tiduswr/Algoritimos_P1_UEPB_CCEA_CAMPUS_VII | /Lista 03/lista03ex25.py | 212 | 4.15625 | 4 | print('Inverta seu Numero!\n')
num = input('Digite um inteiro: ')
numstr = str(num)
leng = len(numstr)
somastr = ''
for i in range(0, leng):
leng = leng - 1
somastr = somastr + numstr[leng]
print('\n',somastr)
| false |
c025c88446ddaefa8afd1b2677191f26b0301f8a | tiduswr/Algoritimos_P1_UEPB_CCEA_CAMPUS_VII | /Lista 03/lista03ex11.py | 348 | 4.125 | 4 | print('Saiba quantos numeros pares e inpares existem\nentre 0 ao numero que você digitar: \n')
num = int(input('Digite um numero: '))
par = 0
inpar = 0
for i in range(1,num+1,1):
calc = i % 2
if calc == 0:
par = par + 1
elif calc != 0:
inpar = inpar + 1
print('\n'' Quantidade de Pares: ',par,'\n','Quantidade de Inpares: ',inpar) | false |
2c8cb900412a0fb8aaf8d4c6051148bd20b9e88f | hunterfuchs/HFBNTest | /Fuchs_int.py | 1,663 | 4.125 | 4 |
def main():
#Describes the program
print('Enter two integers and I will tell you the relationship they satisfy.')
#User imput
firstInteger = int(input('Enter first integer: '))
secondInteger = int(input('Enter second integer: '))
#EQUAL
if firstInteger == secondInteger:
print( str(firstInteger) + ' IS equal to ' + str(secondInteger))
else:
print( str(firstInteger) + ' ISNT equal to ' + str(secondInteger))
#LESS THAN
if firstInteger < secondInteger:
print( str(firstInteger) + ' IS less than ' + str(secondInteger))
else:
print( str(firstInteger) + ' ISNT less than ' + str(secondInteger))
#LESS THAN OR EQUAL
if firstInteger <= secondInteger:
print( str(firstInteger) + ' IS less than or equal to ' + str(secondInteger))
else:
print( str(firstInteger) + ' ISNT less than or equal to ' + str(secondInteger))
#GREATOR THAN
if firstInteger > secondInteger:
print( str(firstInteger) + ' IS greator than ' + str(secondInteger))
else:
print( str(firstInteger) + ' ISNT greator than ' + str(secondInteger))
#GREATOR THAN OR EQUAL
if firstInteger >= secondInteger:
print( str(firstInteger) + ' IS greator than or equal to ' + str(secondInteger))
else:
print( str(firstInteger) + ' ISNT greator than or equal to ' + str(secondInteger))
#Play again while loop
restart=input("Do you want to compare two more numbers? [y/n]")
if restart == "y" or restart=="yes":
main()
else:
exit()
#All the current "called" code
main()
| true |
782377d87d1d4ed49d1d152de6ffaa516e33aee1 | yinghuan007/LeetCode | /009_palindrome number/palindrome number.py | 1,104 | 4.40625 | 4 |
'''Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.'''
#normal soultion
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0 or (x != 0 and x % 10 == 0):
return False
ans = 0
y = x
while(x):
ans = ans*10 + x%10
x /= 10
return ans == y
#faster solution
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0 or (x != 0 and x % 10 == 0):
return False
ans = 0
while(x>ans):
ans = ans*10 + x%10
x /= 10
return x==ans or ans//10==x
| true |
ef54f7e902b2d908b309004051c940f561da95ea | hu6360567/ProjectEuler | /problem14.py | 1,333 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
Longest Collatz sequence
Problem 14
The following iterative sequence is defined for the set of positive integers:
n ---> n/2 (n is even)
n ---> 3n+1 (n is ood)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 ->16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
'''
def getChainLength(n, dictionary):
if n in dictionary:
return dictionary.get(n)
elif n % 2 == 0:
# n is even
next = n / 2
dictionary[next] = getChainLength(next, dictionary)
return dictionary[next] + 1
else:
# n is odd
next = 3 * n + 1
dictionary[next] = getChainLength(next, dictionary)
return dictionary[next] + 1
def main():
chain_length = {1: 1}
max_result = (1, 1)
for index in xrange(1, 1000001):
result = (index, getChainLength(index, chain_length))
if result[1] > max_result[1]:
max_result = result
print max_result
if __name__ == '__main__':
main()
| true |
ba9e52a056609f5b36b810f6525522c85daa436a | hu6360567/ProjectEuler | /problem2.py | 695 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
Even Fibonacci numbers
Problem 2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
'''
def fibonacci_upper():
L = [1, 2]
while L[-1] < 4000000:
L.append(L[-1] + L[-2])
return L
def main():
L = fibonacci_upper()
sum = 0
for i in range(len(L)):
if L[i] % 2 == 0:
sum += L[i]
print sum
if __name__ == '__main__':
main()
| true |
46e0ad4e7dfa87ca1c91a7e0185b8fd67e929cc9 | aniaskudlarska/mathelp | /subsets.py | 282 | 4.1875 | 4 | from itertools import *
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
x = powerset([1,2,3])
for item in x:
print(item) | true |
989a81fc5cfe6c839d23a46643b17f666c7f4277 | matinict/Python | /GuessingGameOne.py | 1,129 | 4.40625 | 4 | ###Guessing Game One Solutions
## Generate a random number between 1 and 9 (including 1 and 9).
## Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right.
## (Hint: remember to use the user input lessons from the very first exercise)
## Extras:
## Keep the game going until the user types “exit”
## Keep track of how many guesses the user has taken, and when the game ends, print this out.
>>> def guessingGame1():
import random
number = random.randint(1,9)
guess = 0
count = 0
while guess !=number and guess !="exit":
guess = input("What your guess?: ")
if guess == "exit":
break
guess = int(guess)
count += 1
if guess <number:
print("Too Low!")
elif guess >number:
print("Too high!!")
else:
print("You got It!!")
print(" And it only took you",count,"tries!")
##>>> guessingGame1()
##What your guess?: 1
##Too Low!
## What your guess?: 9
## Too high!!
## What your guess?: 1
## Too Low!
## What your guess?: 0
## Too Low!
## What your guess?: 9
## Too high!!
## What your guess?: 7
## You got It!!
## And it only took you 6 tries!
| true |
a8f3e6c61e876c5afa3f25b152072ca4fed0e0ce | matinict/Python | /palindromeFunc.py | 418 | 4.625 | 5 | ##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.)
def palindromeTest(word):
rvs=word[::-1]
if word ==rvs:
print("This Word is Palindrome")
else:
print("This Word is not Palindrome")
##>>> palindromeTest("Matam")
##This Word is not Palindrome
##>>> palindromeTest("matam")
##This Word is Palindrome
| true |
2a9524f955198b22cd4557d6dd1df055695f7509 | DeathSlayer0675/C.S.E | /Notes/HelloWorld.py | 1,255 | 4.34375 | 4 | print("Hello World")
# This is a comment. This has no effect on the code
# but this does allow me to do things. I can:
# 1. Make notes to myself
# 2. Comment pieces of code that does not work
# 3. Make my code easier to read
print("Look at what happens here. Is there any space?")
print()
print()
print("There should be a couple blank lines here.")
# Math
print(3 + 5)
print(5 - 2)
print(3 * 4)
print(6 / 2)
print("Figure this out...")
print(6 // 2)
print(5 // 2)
print(9 // 4)
print("Here is another one...")
print(6 % 2)
print(5 % 2)
print(11 % 4) # Modulus (Reminder)
# Powers
# What is 2^20
print(2 ** 100)
# Taking input
name = input(" What is your name?")
print("Hello %s." % name)
age = input("How old are you?")
print("%s?!? You belong in a museum." % age)
print()
print("%s ir really old. They are %s years old." % (name, age))
# Variable Assignments
car_name = "The Bean Machine"
car_type = "Lamborghini"
car_cylinders = 10
car_miles_per_gallon = 2000
# Make it print "I have a car called The Bean Machine. It is a lamborghini.
print("I have a car called %s. It is a %s." % (car_name, car_type))
#Recasting
real_age = int(input("How old are you again?"))
hidden_age = real_age + 5
print("This is your real age: %d" % hidden_age)
| true |
dee36eb4e95b831cacc6b897e1b4354641dd56f6 | AGagliano/HW05 | /HW05_ex00_logics.py | 2,028 | 4.4375 | 4 | #!/usr/bin/env python
# HW05_ex00_logics.py
##############################################################################
def even_odd():
""" Print even or odd:
Takes one integer from user
accepts only non-word numerals
must validate
Determines if even or odd
Prints determination
returns None
"""
while True:
number = raw_input("Please enter an integer\n> ")
try:
number = int(number)
except:
print "Silly, that was not an integer!"
else:
if number%2 == 0:
print 'You entered an even number.'
else:
print 'You entered an odd number.'
return
def ten_by_ten():
""" Prints integers 1 through 100 sequentially in a ten by ten grid."""
beg_int = 1
end_int = 100
columns = 10
rows = (end_int - beg_int + 1)/columns
for i in range(rows):
for j in range(columns):
print beg_int,
beg_int = beg_int + 1
print
def find_average():
""" Takes numeric input (non-word numerals) from the user, one number
at a time. Once the user types 'done', returns the average.
"""
count = 0
total = 0
while True:
x = raw_input("Please enter a number. Type 'done' when you would like the average.\n> ")
if x == 'done':
if count == 0:
return 'We need some numbers to calculate an average!'
return total/count
try:
x = float(x)
except:
continue
else:
total = total + x
count = count + 1
##############################################################################
def main():
""" Calls the following functions:
- even_odd()
- ten_by_ten()
Prints the following function:
- find_average()
"""
even_odd()
ten_by_ten()
print find_average()
pass
if __name__ == '__main__':
main()
| true |
ffd5505149126bada1126caa8aa49833f5d654f3 | Cbkhare/Abstract_Data_Types | /adt_tree_binary_tree.py | 1,290 | 4.1875 | 4 | from Abstract_Data_Types.adt_tree import Tree
class BinaryTree(Tree):
"""Abstract base class for Binary Tree"""
# ----------- Abstract Methods ----------------------
def left(self, node):
"""Return the Position representing the left child Else None"""
raise NotImplementedError('Must be implemented by subclass')
def right(self, node):
"""Return the Position representing the right child Else None"""
raise NotImplementedError('Must be implemented by subclass')
# --------- Concrete Methods ----------------------
def sibling(self, node):
"""Return the Position representing the nodes sibling, None if there is
no sibling or if it is the parent"""
parent = self.parent(node)
if parent is None:
return None
else:
if node == self.left(parent):
# The node is the left child of the parent
return self.right(parent)
else:
return self.left(parent)
def children(self, node):
"""Return Left and Right child's Position, None if there is no child"""
if self.left(node) is not None:
yield self.left(node)
if self.right(node) is not None:
yield self.right(node)
| true |
333d736ead70f14a5c08b97793efe190c9d5571a | xb4dc0d3/Daily-Interview-Pro | /squareroot.py | 931 | 4.21875 | 4 | '''
Hi, here's your problem today. This problem was recently asked by Google:
Given a positive integer, find the square root of the integer without using any built in square root \
or power functions (math.sqrt or the ** operator).
Give accuracy up to 3 decimal points.
'''
import sys
sys.setrecursionlimit(1500)
# Square root helper function using Binary Search
def sqrt_func_helper(n, p, q):
mid = (p + q) / 2
multiply = mid * mid
if multiply == n:
return mid
elif multiply < n:
return sqrt_func_helper(n, mid, q)
else:
return sqrt_func_helper(n, p, mid)
def sqrt(x):
d = 1
found = False # bool check sqrt while iterate
while (found == False):
if d*d == x:
result = d
found = True
else:
result = sqrt_func_helper(x, d-1, d)
found = True
d += 1
return result
print(sqrt(5))
# 2.236
| true |
6773700e7f28cfa09e9a7ed8f129f8d5872c277f | xb4dc0d3/Daily-Interview-Pro | /transpose_matrix.py | 543 | 4.15625 | 4 | '''
Hi, here's your problem today. This problem was recently asked by Twitter:
Given a matrix, transpose it. Transposing a matrix means the rows are now the column and vice-versa.
Here's an example:
'''
def transpose(mat):
column = len(mat[0])
row = len(mat)
result = [[0 for i in range(row)] for j in range(column)]
for i in range(row):
for j in range(column):
result[j][i] = mat[i][j]
return result
mat = [
[1, 2, 3],
[4, 5, 6],
]
print(transpose(mat))
# [[1, 4],
# [2, 5],
# [3, 6]] | true |
344138de4970d66488e0e9e91a37adcb2a6a7ccb | xb4dc0d3/Daily-Interview-Pro | /majority_element.py | 545 | 4.125 | 4 | '''
Hi, here's your problem today. This problem was recently asked by AirBNB:
A majority element is an element that appears more than half the time.
Given a list with a majority element, find the majority element.
Here's an example and some starting code.
'''
def majority_element(nums):
data = {}
nums.sort()
for i in nums:
data[i] = data.get(i,0)+1
max_values = max(data.values())
return [key for key , values in data.items() if values == max_values][0]
print(majority_element([3, 5, 3, 3, 2, 4, 3]))
# 3
| true |
262d6722f4c158d0a41b22433792cdc35651d156 | TMAC135/Pracrice | /maximum_depth_of_binary_tree.py | 695 | 4.21875 | 4 | # coding=utf-8
"""
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example
Given a binary tree as follow:
1
/ \
2 3
/ \
4 5
The maximum depth is 3.
"""
"""
Definition of TreeNode:
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
"""
@param root: The root of binary tree.
@return: An integer
"""
def maxDepth(self, root):
# write your code here
if not root:
return 0
return max(self.maximum(root.left),self.maximum(root.right))+1 | true |
74cdb90a83267b35a61a8627ee5c4dc7b32f407b | TMAC135/Pracrice | /convert_binary_search_tree_to_doubly_linked_list.py | 2,307 | 4.15625 | 4 | """
Convert a binary search tree to doubly linked list with in-order traversal.
Example:
Given a binary search tree:
4
/ \
2 5
/ \
1 3
return 1<->2<->3<->4<->5
"""
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
Definition of Doubly-ListNode
class DoublyListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = self.prev = next
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class DoublyListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = self.prev = next
class Solution:
"""
@param root, the root of tree
@return: a doubly list node
refer to binary_tree_inorder_traversal.py
the key of this problem is to realize the in order traversal in
binary tree, i still not come up with the idea.
Again, i don't understand the why we use stack and cur as our
discriminent. cur is the node we want to explore, we don't know whether
it is none or not, and this is the essential for the if-else, if it is
None, well, just pop out the element from the stack, if not, we need to
keep adding the element in the stack.
Notice i first use cur.left as to judge the left node is None, which is
not working, since every time we pop out the element, we will be aigin
in this circle.
"""
def bstToDoublyList(self, root):
# Write your code here
if not root:
return None
stack=[]
cur=root
res=[]
while (stack or cur ):
if cur:
stack.append(cur)
cur=cur.left
else:
cur=stack.pop()
res.append(cur.val)
cur=cur.right
# connect the linked list given the in-order traversal of the tree
head=DoublyListNode(res[0])
prev=head
for i in xrange(1,len(res)):
cur=DoublyListNode(res[i])
prev.next=cur
cur.prev=prev
prev=cur
return head
if __name__=='__main__':
a=TreeNode(1)
b=TreeNode(2)
c=TreeNode(3)
a.right=b
b.left=c
print Solution().bstToDoublyList(a)
| true |
9592517e14a3ae7007e44d12b0ad000b31fd8b5a | DenOn79/PythonIntroOnline | /Lesson_05/rhombus_with_diagonal.py | 748 | 4.21875 | 4 |
height = int(input('Input the height of rhombus. (Please, make it even): '))
while height % 2 == 0:
height = int(input('The number is not even. Input the height of rhombus. (Please, make it even): '))
else:
width = height
for i in range(height):
for j in range(width):
if i == height//2 \
or (i == 0 and j == width//2) \
or (i == height - 1 and j == width//2) \
or (i <= height//2 and width//2 - i <= j <= width//2 + i) \
or (i == height//2 + j) \
or (i == height//2 + ((width-1) - j))\
or (j == width//2 and height//2 < i < height - 1):
print('* ', end='')
else:
print(' ', end='')
print()
| true |
f8ccd83b1e8f2956af049cf6c1ea58e0789f9abb | CodeNeverStops/Algorithms | /bubble_sort.py | 406 | 4.1875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
def bubble_sort(numbers):
nums = numbers
count = len(nums)
for i in range(1, count):
for j in range(0, count - i):
if nums[j] < nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
return nums
if __name__ == '__main__':
list1 = [1, 3, 2, 1, 4, 0, 1.5, -0.1]
ret = bubble_sort(list1)
print ret
| false |
69c8167bc4bf69cf6575649defc8c1b976f733b1 | dliofindia/Sentence_Similarity | /sentence_similarity/similarity_functions.py | 1,088 | 4.21875 | 4 | from math import *
'''calculate euclidean distance'''
def euclidean(x,y):
try:
return round(sqrt(sum(pow(a-b,2) for a, b in zip(x, y))),3)
except Exception as e:
print(e)
return None
'''calculate manhattan distance'''
def manhattan(x,y):
try:
return round(sum(abs(a-b) for a,b in zip(x,y)),3)
except Exception as e:
print(e)
return None
'''calculate minkowski distance'''
def minkowski(x,y):
try:
var=sum(pow(abs(a-b),3) for a,b in zip(x, y))
nth_root_value = 1/3
nth_root_result=var ** nth_root_value
return round(nth_root_result,3)
except Exception as e:
print(e)
return None
def square_rooted(x):
try:
return round(sqrt(sum([a*a for a in x])),3)
except Exception as e:
print(e)
return None
'''calculate cosine score'''
def cosine(x,y):
try:
numerator = sum([a*b for a,b in zip(x,y)])
denominator = square_rooted(x)*square_rooted(y)
return round(numerator/denominator,3)
except Exception as e:
print(e)
return None
| false |
6231531b341a8e4ad5b43c9b0b7026e87b7cc561 | AkshayShenvi/DailyCodingChallengeSolution | /DCC27-3-2019.py | 878 | 4.21875 | 4 | # This problem was asked by Uber.
# Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
# For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
# Follow-up: what if you can't use division?
arr = [1, 2, 3, 4, 5]
product = []
prod = 1
for i in arr:
for j in arr:
prod = prod * j
prod = prod / i
product.append(prod)
prod = 1
print("product 1")
print(product)
prod = 1
# Follow-up: what if you can't use division?
arr = [1, 2, 3, 4, 5]
product = []
for i in arr:
for j in arr:
if j == i:
continue
prod = prod * j
product.append(prod)
prod = 1
print("product 2")
print(product) | true |
b3a1b3614815836b5453c1467c00f9c43b7b790e | RobertZSun/19S-SSW567-ZheSun | /Triangle.py | 2,198 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 14 13:44:00 2016
Updated Jan 21, 2018
The primary goal of this file is to demonstrate a simple python program to classify triangles
the results come as expected.
@author: zhe sun
"""
import math
def classifyTriangle(a, b, c):
""" This function classify_triangle(a, b, c) where a, b,
and c are the lengths of the sides of the triangles.
Then returns a string with the type of triangle from
three values corresponding to the lengths of the
three sides of the Triangle.
return:
If all three sides are equal, return 'Equilateral'
If exactly one pair of sides are equal, return 'Isoceles'
If no pair of sides are equal, return 'Scalene'
If not a valid triangle, then return 'NotATriangle'
If the sum of any two sides equals the squate of the
third side, then return 'Right' this will be combined
with other type of triangle, such as "Isoceles right triangle",
"Scalene Right"
"""
# require that the input values be >= 0 and <= 200
if a > 200 or b > 200 or c > 200:
return 'NotATriangle'
if a <= 0 or b <= 0 or c <= 0:
return 'NotATriangle'
# This information was not in the requirements spec but
# is important for correctness
# the difference of any two sides must be strictly less than the third side
# of the specified shape is not a triangle
if not(((a + b) > c) and ((a + c) > b) and ((b + c) > a)):
return 'NotATriangle'
# now we know that we have a valid triangle
biggest = max(a, b, c)
lowest = min(a, b, c)
middle = sum([a, b, c]) - biggest - lowest
if a == b and b == c:
return 'Equilateral'
elif (a == b) or (b == c) or (a == c):
if round(((lowest ** 2) + (middle ** 2)), 2) == round((biggest ** 2), 2):
return 'Isosceles Right'
else:
return 'Isosceles'
elif (a != b) and (b != c) and (a != b):
if round(((lowest ** 2) + (middle ** 2)), 2) == round((biggest ** 2), 2):
return 'Scalene Right'
else:
return 'Scalene'
| true |
f720a02793e76f572216fd1af6ffae5ee97cf284 | peaches12/Python_m | /GuessNumber.py | 560 | 4.1875 | 4 | # Guess a number from 1 to 10
import random # the computer will generate random number from 1 to 10
numPC = random.randint(1,10)
print("numPC: " + str(numPC))
print("Do you want to guess a number from 1 to 10?")
print("Enter Yes/No: ")
num = int(input("Enter a number from 1 to 10: "))
print("your number: " + str(num))
#create a function
if num < numPC:
print("It is too low")
print("Try again")
elif num > numPC:
print("It is too high")
print("Try again")
else:
print("It is correct")
print("The end of the game")
| true |
51db5651d6bf853e30e84f72eee0570089adc5fb | peaches12/Python_m | /String Two First_Last Char.py | 602 | 4.21875 | 4 | # the program will concatente the first two and the last two characters of
# the input string
word = input("Enter a string here: ")
word1=word[0:2]
word2=word[len(word)-2:]
print()
print("new string: " + (word1+word2))
print('-------------------------------')
choice= input("continue? yes/no: ")
while choice.upper() =="YES":
word = input("Enter a string here: ")
word1=word[0:2]
word2=word[len(word)-2:]
print()
print("new string: " + (word1+word2))
no print()
print('-------------------------------')
choice= input("continue? yes/no: ")
print('the end')
| true |
9833005b48b67e664f7015a357ce50be6b7fa132 | peaches12/Python_m | /List_RemoveDuplicates.py | 399 | 4.125 | 4 | #the program will remove duplicates from the list
mylist = [1,1,2,2,3,4,4,5,5,6,7,7]
print('the initial list:' + str(mylist))
m = 0
while m < len(mylist):
if mylist[m] == mylist[m + 1]:
mylist.remove(mylist[m])
m = m+1
print('the final list: ' + str(mylist))
#turn the list into a tuple
mytuple = tuple(mylist)
print("my tuple: " + str(mytuple))
| true |
52c38f8b5574c2b7b6e2e50181ab82bfac514118 | s-harding/spotify_puzzles | /spotify_puzzle_1.py | 270 | 4.15625 | 4 |
# coding: utf-8
def reverse_bin(x):
bin(x)
str_x = str(bin(x))
reverse_x = str_x[::-1]
ans_bin = reverse_x[:len(reverse_x)-2]
return int(ans_bin,2)
x = input("Please enter an integer:")
print("The binary reverse of {} is {}".format(x, reverse_bin(int(x))))
| true |
bd7e199baec031afb4ede2ae31f7df5ee76980b9 | emt2017/CS5590PythonSpring2018 | /Lab1Python/Question2.py | 1,457 | 4.21875 | 4 | '''Question 2'''
'''Write a Python function that accepts a sentence of words from user and display the following: '''
#a) Middle word
#b) Longest word in the sentence
#c) Reverse all the words in sentence
'''Import Libraries'''
import string
import sys
'''Function'''
def midLongReverse(string):
#get/store string.split()
stringArray = string.split()
#a) Middle word
#divide length of array in half
arrayLength = len(stringArray)/2
#if integer display array[length/2]
if arrayLength%1==0:
print('The middle words in the sentence are: ', '[', stringArray[int(arrayLength)-1], '.',stringArray[int(arrayLength)], ']')
#else non integer is decimal then +- 0.5 display array.array
else: print('The middle words in the sentence are: ','[',stringArray[int(arrayLength)],']')
#b) Longest word in the sentence
#iterate through array compare word.length
longestWord = ''
for i in range(0,len(stringArray)):
if len(stringArray[i]) > len(longestWord):
longestWord = stringArray[i]
print('The longest word in the sentence is: ',longestWord)
#c) Reverse all the words in sentence
reverseWords = string[::-1]
reverseWords = reverseWords.split()[::-1]
reverseName = ''
for i in range(0,len(reverseWords)):
reverseName = reverseName + reverseWords[i] + ' '
print('Your sentence in reverse: ',reverseName)
midLongReverse('My name is Jacqueline fernandez Dsouza') | true |
574b1f5f2299727960808bdd451bbe420c4eefdf | monish7108/PythonProg2 | /listingthepath.py | 1,221 | 4.25 | 4 | """This program takes a path of directory as input and gives list of all the
all the files, sub-folders, files under sub-folders and so on.
==============================================================
"""
import os
file = []
dir = []
def listing(path1, pathlist1):
for items in pathlist1:
if os.path.isfile(os.path.join(path1, items)):
file.append(os.path.join(path1, items))
else:
dir.append(os.path.join(path1, items))
newpath = os.path.join(path1, items)
newpathlist = os.listdir(newpath)
listing(newpath, newpathlist)
printing_the_output(file,dir)
def printing_the_output(file,dir):
# print(len(dir))
for d in dir:
print(d)
# print(len(file))
for f in file:
print(f)
def main(userinput):
try:
os.path.isdir(userinput)
#raise NotADirectoryError("This is not a directory")
pathlist = os.listdir(userinput)
except OSError as e:
print("\n", e)
else:
listing(userinput, pathlist)
if __name__ == "__main__":
print(__doc__)
userinput = input("enter the path you want to walk through: ")
main(userinput)
#print(file) | true |
5c2240e374a1dafa9e9c2558a3336515bb993365 | monish7108/PythonProg2 | /fibonacciNumChecking.py | 1,384 | 4.28125 | 4 | """This programs check every number from command line
and tells whether number is in fibbonacci series or not.
Math: Instead of producing loop and checking the number there is a mathematical formula.
If (5*x*x)+4 or (5*x*x)-4 or both are perfect squares,
then the number is in fibonacci.
======================================================================="""
def isPerfectSquare(x):
"""if the number is not having decimal part then dividing it from int type
of same num gives 0"""
return (x**0.5) % int(x**0.5) == 0
def fibonacciSeries(userinput):
"""This function tells whether number is in fibbonacci series or not."""
try:
isinstance(int(userinput), int)
userinput = int(userinput)
except ValueError as e:
print(e)
else:
if isPerfectSquare(
(5 *
userinput *
userinput) -
4)or isPerfectSquare(
(5 *
userinput *
userinput) +
4):
return True
else:
return False
if __name__ == "__main__":
print(__doc__)
userinput = input("Enter the number you want to check: ")
if fibonacciSeries(userinput):
print("The numeber is present in fibonacci series.")
else:
print("The number is not present in fibonacci series.")
| true |
0d7e30054d26670e94d498499a80a3641fb7f1cb | 01-Jacky/PracticeProblems | /Python/c/wepay/power_number.py | 1,560 | 4.4375 | 4 | """
A PowerNumber is defined as a number greater than zero that can be expressed as X^Y, where X and Y are integers greater than one.
Create a function takes in an integer i and returns the (zero-indexed) ith power number
Write a function that returns the nth power number, where a power number is a number that can be expressed as x^y.
Note that the power number sequence is in ascending order (4, 8, 9, 16, 27, 32, ...).
"""
import math
import time
def is_power_number(n):
# e.g. to check 10, 4^2 > 10 already so we know 4 can't be a base. Therefore the biggest base we need to check is
# just floor(sqrt(n))
biggest_possible_base = int(math.sqrt(n)) + 1
for base in range(2, biggest_possible_base):
power = 1
check_ans = base
while check_ans <= n:
if check_ans == n:
# print('{}^{}'.format(base,power))
return True
check_ans *= base
power += 1
return False
def nth_power_number(n):
nth_power_number = n+1
power_nums = [None] * nth_power_number
sequential_num = 1
for i in range(len(power_nums)):
while not is_power_number(sequential_num):
sequential_num += 1
power_nums[i] = sequential_num
sequential_num += 1
# print(power_nums)
start = time.time()
nth_power_number(300)
end = time.time()
print(end-start)
# for i in range(10):
# print(is_power_number(i))
# print(is_power_number(4))
# print(is_power_number(8))
# print(is_power_number(49))
# print(is_power_number(48)) | true |
7592ee3a564ea148e7d25eb8e49cab827be82e18 | bhavsarp456-pnb/bhavsarp456 | /RockPaperScissor.py | 2,049 | 4.40625 | 4 | #user imports random function from which computer can playe random moves
from random import randint
#initialising the variables
player_wins = 0
computer_wins = 0
winning_score = 3
#for checking both variables reaches to winning score
while player_wins < winning_score and computer_wins < winning_score:
print(f"Player score:{player_wins} | Computer Scores:{computer_wins}")
print("...Rock...")
print("...Paper...")
print("...Scissors...")
rand_num = randint(0,2)#create a variable from which computer can initailise the main variables i.e. rock, paper, scissor
# user will enter the data which will converted to lower case with help of lower function and stores it to variable name 'player'
player = input("Enter the move:\n").lower()
if rand_num == 0:
computer = "rock"
elif rand_num == 1:
computer = "paper"
else:
computer = "scissors"
print(f"Computer plays {computer}")
# the conditions of the game
if player == computer:
print("its a Tie")
elif player == "rock":
if computer == "scissor":
print("PLayer Wins")
player_wins += 1
elif computer == "paper":
print("Computer Wins")
computer_wins += 1
elif player == "paper":
if computer == "rock":
print("Player Wins")
player_wins += 1
elif computer == "scissor":
print("Computer Wins")
computer_wins += 1
elif player == "scissor":
if computer == "paper":
print("Player Wins")
player_wins += 1
elif computer == "rock":
print("Computer Wins")
computer_wins += 1
else:
print("Please enter valid move")
# conditions who wins the game
if player_wins > computer_wins:
print("Congrats! You Win")
elif player_wins == computer_wins:
print("It's a Tie Bracker")
else:
print("Computer Wins the game")
#end | true |
ff6c1782715b564a73d73cd6241f55e534a696db | savimanner/100-coding-challenges | /4.py | 384 | 4.1875 | 4 | #Question: Write a program which accepts a sequence of comma-separated numbers
# from console and generate a list and a tuple which contains every number.
# Suppose the following input is supplied to the program: 34,67,55,33,12,98 Then,
# the output should be: ['34', '67', '55', '33', '12', '98'] ('34', '67', '55', '33', '12', '98')
x = input()
print(x.split(), tuple(x.split())) | true |
616fb086177e472cf92462b038170affb0e4e20f | Alexmpydev/python_learning | /Mankovsky_HW3.py | 2,549 | 4.28125 | 4 | """
1. Есть list с данными lst1 = ['1', '2', 3, True, 'False', 5, '6', 7, 8, 'Python', 9, 0, 'Lorem Ipsum'].
Напишите механизм, который формирует новый list (например lst2), который содержит только переменные
типа строка, которые есть в lst1.
"""
lst1 = ['1', '2', 3, True, 'False', 5, '6', 7, 8, 'Python', 9, 0, 'Lorem Ipsum']
def filter_list(list_to_filer):
list_to_return = []
for a in list_to_filer:
print(a)
if isinstance(a, str):
print("this is string ", a)
list_to_return.append(a)
print(list_to_return)
return list_to_return
# filter_list(lst1)
"""
2. Ввести из консоли строку. Определить количество слов в этой строке, которые начинаются на букву "а"
(учтите, что слова могут начинаться с большой буквы).
"""
def find_a(string):
input_str = input("Enter your string: ")
print(input_str)
res = input_str.lower()
my_list = res.split(" ")
print(my_list)
result = 0
for word in my_list:
if word.startswith('a'):
result = result + 1
print(result)
"""
*3. Вывести пользователю приветствие ('Hello!'). Спросить у пользователя, хочет ли он повторно его
увидеть этот текст?. Если пользователь введет Y - повторить приветствие. После каждого приветствия повторять
вопрос. Если если пользователь введет N - прекратить спрашивать. Если пользователь ввел не Y или N - попросить
ввести именно Y или N, переспрашивать пока не введет Y или N и по результату принимать решение повторять или нет.
"""
print('Hello!')
input_str = input("хочет ли он повторно его увидеть этот текст?: ")
print(input_str)
to_continue = True
while to_continue:
if input_str not in ["Y", "N"]:
input_str = input("Неверный ввод. Возможные варианты Y/N. Повторите ввод ")
if input_str == "Y":
print('Hello!')
break
elif input_str == "N":
to_continue = False
| false |
5ca7aaef5c343068ac60b7a27582fa50e420faf8 | Alexmpydev/python_learning | /Mankovskiy_HW1 (1).py | 1,482 | 4.34375 | 4 |
# 1. Создать две переменные a=10, b=30. Вывести на экран результат математического
# взаимодействия (+, -, *, / ) этих чисел.
a = 10
print(a)
b = 30
print(b)
c = a + b
print(c)
c = a - b
print(c)
c = a * b
print(c)
c = a / b
print(c)
# 2. Создать переменную и поочередно записать в нее результат сравнения (<, > , ==, !=) чисел
# из задания 1. После этого вывести на экран значение каждой полученной переменной.
my_bool_t = True
my_bool_f = False
my_bool = a < b # True
print(my_bool)
my_bool = a > b # False
print(my_bool)
my_bool = a == b # False
print(my_bool)
my_bool = a != b # True
print(my_bool)
# 3. *Создать переменную - результат конкатенации (сложения) строк str1="Hello " и str2="world". Вывести на ее экран.
my_str1 = "Hello "
my_str2 = "world"
res = my_str1 + my_str2
print(res)
# Что вы видиье для себя результатом курса?
# Сменить сферу деятельности, изучить Python
# Как собираетесь использовать этот результат?
# найти работу
# Чем готовы пожертвовать ради достижения результата?
# личным временем
| false |
314e8981ac2dd67610ba1b4e87f5937ca5fedd9b | Ziiv-git/Coursera-Python-3- | /g.py | 525 | 4.34375 | 4 | #A palindrome is a phrase that, if reversed, would read the exact same.
#Write code that checks if p_phrase is a palindrome by reversing it and then
#checking if the reversed version is equal to the original. Assign the reversed
#version of p_phrase to the variable r_phrase so that we can check your work.
#Save & RunLoad HistoryShow CodeLens
p_phrase = "was it a car or a cat I saw"
r_phase = p_phrase[::-1]
print(r_phase)
if p_phrase == r_phase:
print('Its a palindrome')
else:
print("Sorry, it ain't")
# NOTE:
| true |
6e622f756dc1f5c20421027a5596d1be9e0ad725 | vitorpio/pybible-cli | /pybible/classes/verse.py | 803 | 4.375 | 4 | class Verse:
"""A class used to represent a verse from the bible."""
def __init__(self, text: str, number: int):
"""
Initialize a `Verse` object.
:Parameters:
- `text`: sting containing the text of the verse.
- `number`: integer with the number of the verse.
"""
self.__text = text.strip()
self.__number = number
def __len__(self):
return len(self.text)
def __repr__(self):
return f'Verse(\"{self.text}\", {self.number})'
def __str__(self):
return self.text
@property
def text(self):
"""String with the text of the verse."""
return self.__text
@property
def number(self):
"""Integer with the verse's number."""
return self.__number
| true |
b19b715743c1bb852976da58db38ef681fb7d3f8 | alexshmmy/Python_Algorithms | /014.findWord2dArray.py | 1,732 | 4.1875 | 4 | # given a 2D array and a word, build a boolean function that checks if the word is in the
# array horizontally or vertically
# import packages
import numpy as np
# basic function
def findWord2DArray(array, word) :
'''gets an array and a word and checks if the word exists in the array'''
# define the length of the array
rows, columns = array.shape
# compute the length of the word
L = len(word)
# check if the length of the word is smaller than the smallest dimension
# of the array or the word is empty
if min(rows, columns) < L or L == 0 :
return False
# if the word has 2 or more characters, scan the array
for i in range(rows) :
for j in range(columns) :
# check horizontally
# k is an index parsing the word
k = 0
while (k <= L-1) :
# if the character is same with the word increase k
if j+k <= columns-1 and array[i, j+k] == word[k] :
k += 1
else :
break
if k == L and array[i, j+k-1] == word[-1] :
return True
# same procedure vertically
k = 0
while (k <= L-1) :
if i+k <= rows -1 and array[i+k, j] == word[k] :
k += 1
else :
break
if k == L and array[i+k-1, j] == word[-1]:
return True
# after parsing the matrix, the word is not found
return False
# main program
# define a word
word = 'q1fvd'
# define an 2D array of characters
array = np.array([['a', 'q', 'u', 'q', 'a'],
['b', '1', 'd', '1', 'a'],
['b', 'f', 'f', 'f', 'a'],
['a', 'x', 'l', 'v', 'a'],
['a', 'b', '1', 'd', 'a']])
# check if the word exists in the 2D array
if findWord2DArray(array, word) :
print('The word exists in the 2D array!')
else :
print('The word does not exist in the 2D array!')
| true |
d8837f7ea61778b43fbeef91a58b0c60cd1c05bb | alexshmmy/Python_Algorithms | /010.bubleSort.py | 511 | 4.21875 | 4 | # bublesort: a basic sorting algorithm in python
# input: a list of integers
# output: sorted list of integers
# time complexity: O(n^2)
# space complexity: O(1)
def bubbleSort(alist) :
'''implementation of bubblesort algorithm'''
# compute the length of the list
L = len(alist)
for i in range(0, L) :
for j in range(0, L-i-1) :
if alist[j] > alist[j+1] :
alist[j], alist[j+1] = alist[j+1], alist[j]
# main program
alist = [54,26,100,93,-5,17,77,31,44,55,-1,-100]
bubbleSort(alist)
print(alist)
| true |
165214362aeb345f2cea4ea3fe5bf4cc573107ec | katiareis/Python-Learning-Lab | /Aula07b.py | 651 | 4.25 | 4 | """
+, -, *, /, //, **, %, ()
print('Muliplicação * ', 10 * 10)
print('Adição + ', 10 + 10)
print('Subtação - ', 10 - 5)
print('Subtração - ', 10 - 5)
print('Divisão / ', 10 / 2)
# Poliformismo ou Operador de repetição - Pode realizar a repetição de valor str
print('Muliplicação * ', 10 * '10')
print('Muliplicação * ', 10 * 'Katia ')
# Contatenação - Somente strings aceitam contatenação com sinal + (para concatenar str com int é preciso usar '' ou ,)
print('Adição + ', "10" + "10")
print('Adição +', "Katia tem " + str(32) + ' anos')
"""
# Precedência com ()
print(5+2*10)
print((5+2)*10)
| false |
1fcc0a5d1ef71d5e321eac15cc0f589a506cc58a | katiareis/Python-Learning-Lab | /Aula05.py | 745 | 4.3125 | 4 | """
Formatando Valores com modificadores - Aula 5
:s - Texto (strings)
:d - Inteiros (int)
:f - Números de pronto flutuante (float)
:.(NÚMERO) Quantidade de casas decimais (float)
:(cARACTERE) (< ou > ou ^) (QUANTIDADE) (TIPO - s,d, ou f)
> - Esquerda
< - Direita
^- Centro
# num1 = input('Digite um numero: ')
# num2 = input('Digite outro numero: ')
# print(num1, num2) # contatenação
__________________________________________________________________
num_1 = 10
num_2 = 3
divisao = (num_1 / num_2)
print('{:.2f}'.format(divisao)) # O : sinaliza para o Python que vai haver uma formatação. .2 significa duas casas decimais e o f é de float.
print( f'{divisao:.2f}')
"""
nome = 'Katia'
print(f'{nome:s}') | false |
6ec92fc440a0a742088af9af1a1e4ab0826ef7ce | MattheusOliveiraBatista/Python3_Mundo03_CursoEmVideo | /Aulas Python/Aula018_01_Lista.py | 364 | 4.375 | 4 | """Nessa aula, vamos aprender o que são LISTAS e como utilizar listas em Python. As listas são variáveis compostas
que permitem armazenar vários valores em uma mesma estrutura, acessíveis por chaves individuais. """
galera = [['João', 19], ['Ana', 33], ['Joaquim', 13], ['Maria', 45]]
for p in galera:
print(f'{p[0]} tem {p[1]} anos de idade.')
| false |
ab7c7cda79252786841ad7d383ddbac66404d260 | MattheusOliveiraBatista/Python3_Mundo03_CursoEmVideo | /Aulas Python/Aula_023_Tratamentos_De_Erros_e_Exceções.py | 1,413 | 4.5 | 4 | """
Nessa aula, vamos ver como o Python permite tratar erros e criar respostas
a essas exceções. Aprenda como usar a estrutura try except no Python de uma forma simples.
"""
# x não foi inicializado, isso é uma exceção.
# print(x)
# n = int(input('Digite um número: '))
# print(f'Você digitou o número {n}')
# Não teve erro, teve uma exceção devido o tipo do input.
# ValueError: invalid literal for int() with base 10: 'Dez'.
# --------------------------------------
try:
a = int(input('Numerador: '))
b = int(input('Denominador: '))
r = a / b
# except:
# print('Deu erro! :(')
# except Exception as erro:
# print(f'Problema encontrado foi {erro.__class__}.')
except (ValueError, TypeError):
print('Tivemos um problema com os tipos de dados que você digitou.')
except KeyboardInterrupt:
print('O usuário preferiu finalizar o programa.')
except Exception as erro:
print(f'O erro encontrado foi{erro.__cause__}')
else:
print(f'A divisão é igual a {r:.1f}.')
finally:
print('Volte sempre!')
# ----------------------
# Excção ao tentar dividir por zero.
# ZeroDivisionError: division by zero.
lst = [0, 1, 2]
# print(lst[3])
# Exceção, tentar exibir o índice 3, ele não existe.
"""
try: #TENTE
operação
except # Exceção
falhou
else: # Senão
deu certo
finally:
certo/falha
"""
| false |
26d8fbc24fa4bfcdce135aa26315f2a1cfa8eb08 | MattheusOliveiraBatista/Python3_Mundo03_CursoEmVideo | /Aulas Python/Aula021_04_Funções.py | 640 | 4.375 | 4 | """
Nessa aula, vamos continuar nossos estudos de funções em Python, aprendendo mais sobre Interactive Help em Python,
o uso de docstrings para documentar nossas funções, argumentos opcionais para dar mais dinamismo em funções Python,
escopo de variáveis e retorno de resultados.
"""
def funcao():
n1 = 4
print(f'N1 dentro vale {n1}')
n1 = 2
funcao()
print(f'N1 fora vale {n1}')
print('\n\n')
def teste(b):
global a
a = 8
b += 4
c = 2
print(f'A dentro vale {a}')
print(f'B dentro vale {b}')
print(f'C dentro vale {c}')
a = 5
teste(a)
print(f'A fora vale {a}')
| false |
51fd718fd41f8699a50ad81785c178ea16897ff4 | MattheusOliveiraBatista/Python3_Mundo03_CursoEmVideo | /Aulas Python/Aula017_01_Lista.py | 874 | 4.78125 | 5 | """
Nessa aula, vamos aprender o que são LISTAS e como utilizar listas em Python. As listas são variáveis
compostas que permitem armazenar vários valores em uma mesma estrutura, acessíveis por chaves individuais.
"""
# Listas estão entre colchetes
# Lista são mutáveis
lanche = ['Hambúrguer', 'Suco', 'Pizza', 'Pudim']
print(lanche)
# Atualizando o elemento
lanche[3] = 'Picolé'
# Adicionando elemnento
lanche.append('Cooke')
# Adicionando cachorro - quente, na posição 0
# Todos os elementos serão deslocados para a direita
# Inserindo cachorro quente na posição 0
lanche.insert(0,'Cachorro quente')
# Apagando o ultimo elemento
del lanche[3]
# Apagando o ultimo elemento ou o índice que desejarmos
#lanche.pop() - O último elemento
# lanche.pop(1)
# Apagando através do valor
lanche.remove('Pizza')
print(lanche)
| false |
0892aac38ed7cb152bb0841bf0700c92ab96d747 | MattheusOliveiraBatista/Python3_Mundo03_CursoEmVideo | /Aulas Python/Aula019_01_Dicionários.py | 586 | 4.34375 | 4 | """
Nessa aula, vamos aprender o que são DICIONÁRIOS e como utilizar dicionários em Python. Os dicionários são
variáveis compostas que permitem armazenar vários valores em uma mesma estrutura, acessíveis por chaves literais.
"""
# dados = {} #
# Ou
#dados = dict()
dados = dict()
dados = {
'nome':'Pedro',
'idade': 21
}
dados['sexo'] = 'M'
print(dados)
# Deletando Idade
# del dados['idade']
# print(dados)
# Valores dos campos
print(dados.values())
# Nome dos campos
print(dados.keys())
# Valores e nomes dos campos
print(dados.keys()) | false |
dd8ca8ece32b5a6a1fa629d46e9a65b57863a708 | Akshay-Kanawade/Image_Augmentation_Tool | /tools/crop.py | 1,755 | 4.15625 | 4 | # import library
import cv2
def Read(image_path):
"""
This function basically used to read the image.It read images in form of numpy array.
:param image_path: source image
:return: ndarray
"""
# use cv2.imread() to read an images.
# syntax : cv2.imread(filename, flag=None)
return cv2.imread(image_path)
def Crop(img, x1, x2, y1, y2):
"""
crop the image as per given inputs.
:param img: ndarray
:param x1: left
:param x2: right
:param y1: bottom
:param y2: top
:return: cropped image
"""
# (y1,y2,x1,x2)(bottom,top,left,right)
h, w = img.shape[1], img.shape[0]
return img[x1:h-x2, y1:w-y2]
def Show(orignal_img, croped_image):
"""
The show function gives the input as in the form of ndarray and show the image as output.
:param orignal_img: ndarray
:param croped_image: ndarray
:return: show image as output
"""
# use imshow() function to show the images
# syntax : cv2.imshow(winname, mat)
cv2.imshow("Original_Image", orignal_img)
cv2.imshow("Croped_Image", croped_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# main function
def main():
"""
This is main function used to call other function
:return: nothing
"""
image_path = input("Enter path of image:")
# call read function to read an image
img = Read(image_path)
# give input (y1,y2,x1,x2)(bottom,top,left,right)
x1, x2, y1, y2 = map(int, input("Enter left, right, bottom, top sep by space:").split(" "))
# call crop function to crop image
croped_image = Crop(img, x1, x2, y1, y2)
# call show function to show original image and resized image
Show(img, croped_image)
if __name__ == "__main__":
main()
| true |
6256c71a3dff63febd45da9de76d78bf8918b889 | Akshay-Kanawade/Image_Augmentation_Tool | /tools/sharpen_image.py | 1,614 | 4.125 | 4 | # import library
import cv2
import numpy as np
def Read(image_path):
"""
This function basically used to read the image.It read images in form of numpy array.
:param image_path: source image
:return: ndarray
"""
# use cv2.imread() to read an images.
# syntax : cv2.imread(filename, flag=None)
return cv2.imread(image_path)
def Sharp(img):
"""
This method is used to sarp the image by applying filters.
:param img: ndarray
:return: sharpen image
"""
# use cv2.sharp() function to sharp image
# syntax : cv2.filter2D(src, depth, kernel)
kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
return cv2.filter2D(img, -1, kernel)
def Show(orignal_img, sharp_image):
"""
The show function gives the input as in the form of ndarray and show the image as output.
:param orignal_img: ndarray
:param sharp_image: ndarray
:return: show image as output
"""
# use imshow() function to show the images
# syntax : cv2.imshow(winname, mat)
cv2.imshow("Original_Image", orignal_img)
cv2.imshow("Sharp_Image", sharp_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# main function
def main():
"""
This is main function used to call other function
:return: nothing
"""
image_path = input("Enter path of image:")
# call read function to read an image
img = Read(image_path)
# call flip function to sharp the image
sharp_image = Sharp(img)
# call show function to show original image and sharp image
Show(img, sharp_image)
if __name__ == "__main__":
main()
| true |
00130ba43a30c0a2e571310432da583350dee40d | chati757/python-learning-space | /pandas/5_2_loop_dataframe_loc.py | 1,006 | 4.21875 | 4 | # import pandas package as pd
import pandas as pd
# Define a dictionary containing students data
data = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'],
'Age': [21, 19, 20, 18],
'Stream': ['Math', 'Commerce', 'Arts', 'Biology'],
'Percentage': [88, 92, 95, 70]}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Age', 'Stream', 'Percentage'])
print("Given Dataframe :\n", df)
print("\nIterating over rows using loc function :\n")
# iterate through each row and select
# 'Name' and 'Age' column respectively.
for i in range(len(df)) :
print(df.loc[i, "Name"], df.loc[i, "Age"])
'''
Given Dataframe :
Name Age Stream Percentage
0 Ankit 21 Math 88
1 Amit 19 Commerce 92
2 Aishwarya 20 Arts 95
3 Priyanka 18 Biology 70
Iterating over rows using loc function :
Ankit 21
Amit 19
Aishwarya 20
Priyanka 18
''' | false |
dc350bc67db84c61a33f07e7ae300d1165ed4f57 | PJHutson/prg105 | /4.3.py | 598 | 4.5 | 4 | # Nested loops to find the average rainfall
rainfall = 0
years = int(input("Please enter the number of years")) # convert years to integer
for year in range(1, years + 1): # set loops for the years
for month in range(1, 13): # set inner loops for months
rainfallpermonth = int(input("Please input the inches of rain this month"))
rainfall += rainfallpermonth # Total rainfall
print("The number of months is", years * 12)
print("The total inches of rainfall is", rainfall)
print("The average rainfall per month is", rainfall / (years * 12))
| true |
566d8f1d4fad789fae4e9b0b81c085aba5b62848 | Argentum462/Coursera-python | /week4/solution14.py | 539 | 4.375 | 4 | # Реализуйте алгоритм быстрого возведения в степень.
# Для этого нужно воспользоваться следующими рекуррентными соотношениями:
# aⁿ = (a²)ⁿ/² при четном n, aⁿ=a⋅aⁿ⁻¹ при нечетном n.
def power(x, y):
if y == 0:
return 1
elif y % 2 != 0:
x = x * power(x, y - 1)
else:
x = power(x * x, y / 2)
return x
a, n = float(input()), int(input())
print(power(a, n))
| false |
e975a120a5705602cf649d13614ede224d4a689f | Argentum462/Coursera-python | /week2/solution27.py | 356 | 4.15625 | 4 | # По данному числу N распечатайте все целые степени двойки, не превосходящие N,
# в порядке возрастания.Операцией возведения в степень пользоваться нельзя!
num = int(input())
i = 1
while i <= num:
print(i, end=' ')
i *= 2
| false |
4d3e328ea9213db2105598eba76f94604e9dde32 | iOSGJZ/python-100 | /tuple.py | 1,928 | 4.25 | 4 | def main():
#定义元组
t = ('郭兢哲',27,True,'河南洛阳')
print(t)
#获取元组中的元素
print(t[0])
print(t[3])
#遍历元组中的值
for member in t:
print(member)
#重新给元组赋值
#t[0] = '李狗蛋' 元组是无法改变的 TypeError
#变量t重新引用新的元组原来的元组将被垃圾回收
t = ('李狗蛋',23,False,'郑州富士康')
print(t)
#将元组转换成列表
person = list(t)
print(person)
#转换成列表后,列表是可以修改它的元素的
person[0] = '李小龙'
print(person)
#将列表转换成元组
fruits_list = ['apple','banana','orange']
fruits_tuple = tuple(fruits_list)
print(fruits_tuple)
"""
为什么需要使用元组
1.元组中的元素是无法修改的,
事实上我们在项目中尤其是多线程环境中可能更喜欢使用的是那些不变对象
一方面因为对象状态不能修改,所以可以避免由此引起的不必要的程序错误,
简单的说就是一个不变的对象要比可变的对象更加容易维护;
另一方面因为没有任何一个线程能够修改不变对象的内部状态,
一个不变对象自动就是线程安全的,这样就可以省掉处理同步化的开销。
一个不变对象可以方便的被共享访问。
所以结论就是:如果不需要对元素进行添加、删除、修改的时候,可以考虑使用元组,
当然如果一个方法要返回多个值,使用元组也是不错的选择。
2.元组在创建时间和占用的空间上面都优于列表。
我们可以使用sys模块的getsizeof函数来检查存储同样的元素的元组和列表各自占用了多少内存空间,这个很容易做到。
我们也可以在ipython中使用魔法指令%timeit来分析创建同样内容的元组和列表所花费的时间,
"""
if __name__ == '__main__':
main() | false |
a760dabf47455f175cbd9b7926aa770b034d0631 | HaymanLiron/46_python_exercises | /q10.py | 321 | 4.15625 | 4 | def overlapping(a,b):
# checks if lists a and b have at least one common element
# uses nested if-loops to satisfy the requirements of the question
# even though it's not very efficient
for elem_a in a:
for elem_b in b:
if elem_a == elem_b:
return True
return False | true |
2c766ebe972eead997f38b841a7f3c366c6dc436 | ehiaig/learn_python | /pyramid.py | 806 | 4.3125 | 4 | """
Exercise 1: Create a pyramid like below
*
***
*****
***
*
"""
for line in [1,2,3,2,1]:
#print("line {}".format(line))
for space in range(3-line):
print(" ", end="")
for stars in range(2*line-1):
print("*", end="")
print("")
#OR
line = 1
counter = 1
while line>0:
if line==3:
counter = -1
# print(line)
for space in range(3 - line):
print(" ", end="")
for stars in range(2 * line - 1):
print("*", end="")
print("")
line += counter
#and a larger pyramid
line = 1
counter = 1
while line>0:
if line==5:
counter = -1
# print(line)
for space in range(5 - line):
print(" ", end="")
for stars in range(2 * line - 1):
print("*", end="")
print("")
line += counter
| true |
fac2bd77f6c0000807e48cc1f40f354f03cc844d | ehiaig/learn_python | /second.py | 567 | 4.40625 | 4 | #For loops are for lists and ranges
my_num = [3,5,7,6,100]
for num in my_num:
print (num+3)
#Another
range(8)
#Yet another
for num in range(5):
print(num)
#For
for num in range(1,5):
print(num)
#Again
for num in range(1,10, 2):
print(num)
#Yet
for i in range(2):
for j in range(3):
print("{}*{} ={}".format(i,j,(i*j)))
"""
To get the the documanetation of each function use thes
print(range.__doc__)
OR
print
while loops are for conditions that requires a certain action to be true
and until we create a condition to make it false.
""" | true |
54e01a7410d972f4020650d10b277bdfbfba270c | im-jonhatan/hackerRankPython | /strings/stringSplitandJoin.py | 318 | 4.28125 | 4 | # Task
# You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen.
# Input Format
# The first line contains a string consisting of space separated words.
# Output Format
# Print the formatted string as explained above.
def split_and_join(line):
return line.replace(" ", "-") | true |
6224ac2e25db55ba7434d290e892e9e4c66c3d28 | im-jonhatan/hackerRankPython | /closuresandDecorators/standardizeMobileNumberUsingDecorators.py | 999 | 4.25 | 4 | # Let's dive into decorators! You are given N mobile numbers. Sort them in ascending order then print them in the standard format shown below:
# +91 xxxxx xxxxx
# The given mobile numbers may have +91, 91 or 0 written before the actual 10 digit number. Alternatively, there may not be any prefix at all.
# Input Format
# The first line of input contains an integerN , the number of mobile phone numbers.
# N lines follow each containing a mobile number.
# Output Format
# Print N mobile numbers on separate lines in the required format.
# Sample Input
# 3
# 07895462130
# 919875641230
# 9195969878
# Sample Output
# +91 78954 62130
# +91 91959 69878
# +91 98756 41230
def wrapper(f):
def fun(l):
data = [f'+91 {number[-10: -5]} {number[-5:]}' for number in l]
return f(data)
return fun
@wrapper
def sort_phone(l):
print(*sorted(l), sep='\n')
if __name__ == '__main__':
l = [input() for _ in range(int(input()))]
sort_phone(l)
| true |
c825c5457a29022d3a323154fdc1befbd7bec4e8 | im-jonhatan/hackerRankPython | /sets/introductionToSets.py | 723 | 4.125 | 4 | # Task
# Now, let's use our knowledge of sets and help Mickey.
# Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her greenhouse.
# Formula used:
# average = sum of distinct heights / total number of distinct heights
# Input Format
# The first line contains the integer,N , the total number of plants.
# The second line contains the N space separated heights of the plants.
# Constraints
# 0 < N ≤ 100
# Output Format
# Output the average height value on a single line.
def average(array):
total = 0
for item in set(array):
total += item
total = total / len(set(array))
return total | true |
aacc275071f150641187545c406118f444966844 | ed-cetera/project-euler-python | /041_solution.py | 1,184 | 4.1875 | 4 | #!/usr/bin/env python3
import math
import time
def is_prime(number):
if number < 2:
return False
for divisor in range(2, int(math.sqrt(number)) + 1):
if number % divisor == 0:
return False
return True
def is_pandigital(number):
number_str = str(number)
if len(number_str) > 9:
return False
digits = set([int(d) for d in number_str])
if len(digits) != len(number_str):
return False
if 0 in digits:
return False
for digit in range(1, len(number_str) + 1):
if digit not in digits:
return False
return True
def main():
# pandigital numbers with 2, 3, 5, 6, 8, or 9 digits are divisible by 3
for number in range(7654321, 1234567 - 1, -2):
if is_pandigital(number) and is_prime(number):
break
else:
for number in range(4321, 1234 - 1, -2):
if is_pandigital(number) and is_prime(number):
break
else:
number = None
print("Solution:", number)
if __name__ == "__main__":
start = time.time()
main()
end = time.time()
print("Duration: {0:0.6f}s".format(end - start))
| false |
90f691f13aae8688dc5fb01385463810b7b578c1 | ppapuli/Portfolio | /ThinkPythonExamples/tp1.2.py | 787 | 4.40625 | 4 | ''' How many seconds are there in 42 minutes and 42 seconds? '''
#function to convert any hours and minutes to seconds
def time_in_seconds(hours = 0, minutes = 0, seconds = 0):
if hours + minutes + seconds == 0:
hours = float(input("How many hours? "))
minutes = float(input("How many minutes? "))
seconds = float(input("How many seconds? "))
converted_time = (hours * 3600) + (minutes * 60) + (seconds * 1)
print(f"There are {converted_time} seconds in {hours} hours, {minutes} minutes, and {seconds} seconds. ")
hours = 0 # if you know the amount of hours, insert here
minutes = 0 # if you know the amount of minutes, insert here
seconds = 0 # if you know the amount of seconds, insert here
time_in_seconds(hours,minutes,seconds)
| true |
a032fb130f001d050aad637236bfbf25cf20efef | ppapuli/Portfolio | /ThinkPythonExamples/tp4.0.py | 1,178 | 4.1875 | 4 | import turtle
import math
bob = turtle.Turtle()
alice = turtle.Turtle()
def square(t, l):
for i in range(4):
t.fd(l)
t.lt(90)
def polyline(t, n, length, angle):
for i in range(n):
t.fd(length)
t.lt(angle)
def polygon(t, n, length, angle):
angle = 360.0 / n
polyline(t, n, length, angle)
def circle(t, r):
arc(t, r, 360)
def arc(t, r, arc_angle): # creates an arc based on a ratio of circumference to a full circle by creating arc segmentations based on the arc length and resolution
circumference = 2 * math.pi * r
arc_length = circumference * (arc_angle / 360)
num_side = int(arc_length / 3) + 1
edge_angle = arc_angle / num_side
arc_segment = arc_length / num_side
polyline(t, n, arc_segment, edge_angle)
#print("Enter your desired number of sides: ")
#num_side = int(input())
print("Enter your desired radius: ")
radius = int(input())
print("Enter your desired arc angle: ")
arc_angle = int(input())
#edge_angle = 360 / num_side
#length = 2
#polygon(bob, length, angle, num_side)
#circle(bob, radius)
arc(bob, radius, arc_angle)
turtle.mainloop()
| false |
7c3b76bf725e9f336fb1c5780aa455eccc177ab6 | ppapuli/Portfolio | /ThinkPythonExamples/tp9.4.py | 293 | 4.21875 | 4 | fin = open('words.txt')
# prints true if all the letters in the word only contains letters used in the string
def uses_only(word, string):
for letter in word:
if letter not in string:
return False
return True
print(uses_only("hello face", " acefhlo "))
| true |
4fba239b1aff979e45f4971332d8a4b5d92e66cc | ppapuli/Portfolio | /ThinkPythonExamples/tp5.3.py | 454 | 4.4375 | 4 | # Function that checks whether three side lengths are capable of forming a triangle
def is_triangle(s1,s2,s3):
if s1 > s2+s3 or s2 > s1+s3 or s3 > s1+s2:
print("No")
else: print("Yes")
# Prompt user for the lengths of the triangle
sideA = int(input("What is your first length? \n"))
sideB = int(input("And your second? \n"))
sideC = int(input("What about your third? \n"))
#call the function
is_triangle(sideA,sideB,sideC)
| true |
5827661449fc93e9a88a80391a264986b37396bd | hughmiller99/musical-fiesta | /date_test.py | 314 | 4.21875 | 4 | import datetime
date = input("What date would you like? Use YYYY-MM-DD :")
year = date.split("-")[0]
month = date.split("-")[1]
day = date.split("-")[2]
print(year)
print(month)
print(day)
print(date)
x = datetime.datetime(int(year), int(month), int(day))
short_month = (x.strftime("%b"))
| false |
b91fc6ebc5acebc7021d1507bdb646ee3e101c7a | nsm112/Passwordgenerator | /main.py | 2,756 | 4.21875 | 4 | # Using this symbol I can leave comments that do not effect the code.
# Below this comment I will explain the various lines of code and their function within this file
# The import function is used to import modules from python to create specific functions for later use
# I will use both the array and random functions to create an 8 character password that is both random and strong
import random
import array
# Now I tell the interpater how long the password will be
# It will be 8 characters long
# However, it can be changed to any character length
MAX_LEN = 8
# Now I will create the indexes needed to pull data for my generator
Digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
Lower_case_characters = ['a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x',
'y', 'z']
Upper_case_characters = ['A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z']
Special_characters = ['!', '@', '#', '$', '%', '^', '&', "*", '?', '/']
# My indexes are now created, future algorithms will now understand and reference these indexes for future use.
# Now I will combine my indexes so the program will have one centralized index to pull and randomize characters.
Combined_index = Digits + Lower_case_characters + Upper_case_characters + Special_characters
# Now I will tell the program to select at least one character from each list
rand_digit = random.choice(Digits)
rand_upper = random.choice(Upper_case_characters)
rand_lower = random.choice(Lower_case_characters)
rand_special = random.choice(Special_characters)
# This next line will create a temp password for future use in the combined index randomizer and array randomizer.
temp_pass = rand_digit + rand_upper + rand_lower + rand_special
# The next lines of code will now select random characters from the combined index
# the for x in range(MAX_LEN -4): will set apart 4 of the 8 characters to be randomized through the combined index
# created.
for x in range(MAX_LEN - 4):
temp_pass = temp_pass + random.choice(Combined_index)
# and then plug those characters into an array for further randomization
temp_pass_list = array.array('u', temp_pass)
random.shuffle(temp_pass_list)
# Now I take the temp password from the array and then form it into a final password
# and print it.
password = ""
for x in temp_pass_list:
password = password + x
print(password)
| true |
cce70fe0af76b0b59901051765f5bf84308c8549 | Yang-Le-321/Magic-8-Ball | /Magic.py | 1,044 | 4.21875 | 4 | import random
#Get user input
name = input("What is your name? ")
question = input("What would you like to ask? ")
answer = ""
#Generate random answer
random_number = random.randint(1,10)
if random_number == 1:
answer = "Yes - definitely."
elif random_number == 2:
answer = "It is decidedly so"
elif random_number == 3:
answer = "Without a doubt"
elif random_number == 4:
answer = "Reply hazy, try again"
elif random_number == 5:
answer = "Ask again later"
elif random_number == 6:
answer = "Better not tell you now"
elif random_number == 7:
answer = "My sources say no"
elif random_number == 8:
answer = "Outlook not so good"
elif random_number == 9:
answer = "Very doubtful"
elif random_number == 10:
answer = "Signs point to yes"
else:
answer = "Error"
#Answer question
if name == "":
print("question: " + question)
else:
print(f"{name} asks: {question}")
if question == "":
print("The Magic 8-Ball cannot provide a fortune unless you ask it something.")
else:
print("Magic 8-Ball's answer: " + answer)
| true |
aca77254c4e7315cb8f0d4c798bc0d5cc0e623d5 | willstauffernorris/cs-module-project-recursive-sorting | /src/sorting/sorting.py | 2,683 | 4.15625 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
#merged_arr = [0] * elements
merged_arr = []
#Your code here
# for element in arrA:
# merged_arr.append(element)
# for element in arrB:
# merged_arr.append(element)
"""
[1 4 7]
[2 8 9]
arrA[0] arrB[0]
[4 7]
[2 8 9]
out [1]
min arrA[0] arrB[0]
[4 7]
[8 9]
out [1 2]
min arrA[0] arrB[0]
[7]
[8 9]
out [1 2 4]
min arrA[0] arrB[0]
[]
[8 9]
out [1 2 4 7]
len(arrA)== 0
[]
[9]
out [1 2 4 7 8]
"""
while len(arrA) > 0 or len(arrB) > 0:
if len(arrA) == 0:
merged_arr.append(arrB[0])
arrB.pop(0)
elif len(arrB) == 0:
merged_arr.append(arrA[0])
arrA.pop(0)
elif arrA[0] < arrB[0]:
merged_arr.append(arrA[0])
arrA.pop(0)
print(arrA)
else:
merged_arr.append(arrB[0])
arrB.pop(0)
print(arrB)
print(f'mergedarray {merged_arr}')
return merged_arr
# TO-DO: implement the Merge Sort function below recursively
def merge_sort(arr):
# Your code here
#print(f'The Array: {arr}')
if len(arr) <= 1: ## base case
return arr
# divide in half until I have sub arrays of length 1
#print(int(len(arr)/2))
## recursively splitting the array
left_arr = arr[0:int(len(arr)//2)]
right_arr = arr [int(len(arr))//2:int((len(arr)))]
left_arr = merge_sort(left_arr)
right_arr = merge_sort(right_arr)
print(f'left arr {left_arr}')
print(f'right arr {right_arr}')
sorted_array = merge(left_arr, right_arr)
#if len(left_arr) == 0 and len(right_arr) == 0:
# if left_arr[0] < right_arr[0]:
# sorted_arr = [left_arr[0], right_arr[0]]
# else: # if right array < left array
# sorted_arr = [right_arr[0], left_arr[0]]
# print(f'sorted array {sorted_arr}')
# merge them back in, switching orders to sort
return sorted_array
## divide into two (recursion)
## until they're lists by themselves (base case)
# STRETCH: implement the recursive logic for merge sort in a way that doesn't
# utilize any extra memory
# In other words, your implementation should not allocate any additional lists
# or data structures; it can only re-use the memory it was given as input
def merge_in_place(arr, start, mid, end):
# Your code here
pass
def merge_sort_in_place(arr, l, r):
# Your code here
pass
| false |
bba479c8b086b3e196a030e115d5e42110c170a4 | toyugo/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/6-print_sorted_dictionary.py | 227 | 4.15625 | 4 | #!/usr/bin/python3
def print_sorted_dictionary(a_dictionary):
"""ls = list(a_dictionary).sort() do not work why?"""
ls = sorted(a_dictionary.keys())
for i in ls:
print("{:s}: {}".format(i, a_dictionary[i]))
| false |
7345fcd7c3d0e18ac113528cc699a0dec82096be | toyugo/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/100-matrix_mul.py | 1,188 | 4.125 | 4 | #!/usr/bin/python3
"""
Module to find the max integer in a list
"""
def matrix_mul(m_a, m_b):
"""Multiply two matrices. """
if m_a == [] or m_a == [[]]:
raise ValueError("m_a can't be empty")
if m_b == [] or m_b == [[]]:
raise ValueError("m_b can't be empty")
if not isinstance(m_a, list):
raise TypeError("m_a must be a list")
if not isinstance(m_b, list):
raise TypeError("m_b must be a list")
for i in m_a:
if not isinstance(i, list):
raise TypeError("m_a must be a list of lists")
for i in m_b:
if not isinstance(i, list):
raise TypeError("m_b must be a list of lists")
if len(m_a) == 0:
raise ValueError("m_a can't be empty")
if len(m_b) == 0:
raise ValueError("m_b can't be empty")
for i in m_a:
for j in i:
if not isinstance(j, int) and not isinstance(j, float):
raise TypeError("m_a should contain only integers or floats")
for i in m_b:
for j in i:
if not isinstance(j, int) and not isinstance(j, float):
raise TypeError("m_b should contain only integers or floats")
| false |
1198d9cd67e56de696ce9485c61d20e7b606aa9d | Saurabh2105/PythonHackerRank | /RegularExpressions/FibonacciProblem.py | 772 | 4.375 | 4 | '''
Let's learn some new Python concepts! You have to generate a list of the first fibonacci numbers, being the first number.
Then, apply the map function and a lambda expression to cube each fibonacci number and print the list.
'''
cube = lambda x: x*x*x# complete the lambda function
def fibonacci(n):
lst=list()
#lst.append(0)
#lst.append(1)
for i in range(n):
#print(i)
if(i==0):
lst.append(0)
elif(i==1):
lst.append(1)
else:
#print(i)
#print(lst[i-1])
#print(lst[i-2])
lst.append(lst[i-1] + lst[i-2])
return lst;
# return a list of fibonacci numbers
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n)))) | true |
0e7c36c49bed0cdbf31aaf1e9b16d932848b6997 | psmithxoxo43/pod3_repo | /Dario/temperature.py | 983 | 4.34375 | 4 | #converting farenheit 100 to celsius and saving it to the variable celsius_100
celsius_100 = ((100 - 32) * 5/9)
#printing celsius_100
print(celsius_100)
#converting 0 degrees farenheit to celsius and saving to variable celsius_0
celsius_0 = ((0 - 32) * 5/9)
#printing celsius_0
print(celsius_0)
#converting and printing temperature of 34.2 degrees farenheit to celsius
print((34.2 - 32) * 5/9)
#converting 5 degrees celsius to farenheit
print((5 * 9/5) + 32)
#conversion of 30.2 degrees celsius to farenheit and adding to variable farenheit_conversion
farenheit_conversion = (30.2 * 9/5) + 32
#printing 30.2 degrees celsius to farenheit conversion
print(farenheit_conversion)
#conversion of 85.1 degrees farenheit to celsius and adding to variable celsius_conversion
celsius_conversion = ((85.1 - 32) * 5/9)
#printing celsius_conversion
print(celsius_conversion)
#printing boolean statement regarding which temperature is hotter
print(bool(farenheit_conversion < celsius_conversion)) | true |
8a6e022c172e210c2411002aa59f6934fabf707b | psmithxoxo43/pod3_repo | /Paola/first_python_challenge.py | 1,561 | 4.34375 | 4 | print('1: Describe what is happening below by adding comments before each line')
# Assigning the word books to the box_1 variable
box_1 = 'books'
# Assigning the word clothes to the box_2 variable
box_2 = 'clothes'
# Assigning the word plants to the box_3 variable
box_3 = 'plants'
# Assigning the phrase kitchen stuff to the box_4 variable
box_4 = 'kitchen stuff'
print('2: Print the variables box_1, box_2, box_3, box_4')
print(box_1)
print(box_2)
print(box_3)
print(box_4)
print(box_1, box_2, box_3, box_4)
print('3.1: Declare a variable with the name "address", assign it any street name you like')
address = 'Fulton Street'
print('3.2: Print the address variable')
print(address)
print('4: Reassign variables box_2 and box_4 with some other text and print box_1, box_2, box_3, box_4 again')
# Assigning the word hearts to box_1 variable
box_1 = 'hearts'
# Assigning the word flowers to box_2 variable
box_2 = 'flowers'
# Assigning the word glitter to box_3 variable
box_3 = 'glitter'
# Assigning the word sugar to box_4 variable
box_4 = 'sugar'
print(box_1)
print(box_2)
print(box_3)
print(box_4)
print(box_1, box_2, box_3, box_4)
print('5.1: The line of code below is commented out because it produces many SyntaxErrors. Fix the problem and turn the comment back into regular Python code')
#completion message = 'Completed the first Python challenge!
completion_message = 'Completed the first Python challenge!'
print('5.2: Turn the comment below back into regular Python code')
#print(completion_message)
print(completion_message)
| true |
0ae30646a67cef2671d1a954bacaa1ee284fb91b | hamburgcodingschool/L2CX-January_new | /lesson 2/p3-revisions_3.py | 323 | 4.34375 | 4 | # CONDITIONAL OPERATORS == != > >= < <=
# result of the op is always a boolean (True/False)
age = 5
test = age >= 18
print(test)
# IF STATEMENT
if age >= 18:
print("You are old!")
print("Well not really... maybe")
else:
print("You are definitly youngn for a human")
print("THE END!")
| true |
f199348a57fcde48d49c9c1dd4306759ce52e831 | jc239964/lookIGitIt | /ex15.py | 788 | 4.25 | 4 | # use argv to get the script's name and user input
from sys import argv
script, filename = argv
# defines variable 'txt' with the open function and
# the filename which user inputs via argv
txt = open(filename)
# prints the name of the file, then uses the read function to
# print it to the command line
print "Here's your file %r:" % filename
print txt.read()
# user inputs the file name, via the raw input function
# the variable "file_again" is defined with user input from
# raw_input function
print "Type the filename again:"
file_again = raw_input("> ")
# defines txt_again variable with the open function filled with the
# file_again variable
txt_again = open(file_again)
# reads the file, which was inputted before
print txt_again.read()
txt.close()
txt_again.close()
| true |
0375a5c92e2475fd2dc2043a99cd15083cd53478 | ZL4746/Basic-Python-Programming-Skill | /First_Part/07_Deal.py | 2,111 | 4.125 | 4 | def ReturnView(Prize,Guess):
# a function to return the View
if (Prize == Guess):
if (Guess == 3):
View = 1
else:
View = Guess + 1
else:
if (Guess == 3 and Prize == 2) or (Guess == 2 and Prize ==3):
View = 1
elif (Guess == 2 and Prize ==1) or (Guess ==1 and Prize ==2):
View = 3
else:
View = 2
return View
def NewGuess(Guess,View):
#the function to return the new guess
if (Guess == 3 and View == 2) or (Guess == 2 and View ==3):
NewGuess = 1
elif (Guess == 2 and View ==1) or (Guess ==1 and View ==2):
NewGuess = 3
else:
NewGuess = 2
return NewGuess
import random
def main():
n = eval(input( "Enter number of times you want to play: " ))
print ()
n_winning = 0
#print the header
print (" Prize Guess View New Guess")
#repeat the game based on the number entered
for i in range(1,n+1):
#get the prize
Prize = random.randint(1,3)
#get the Guess
Guess = random.randint(1,3)
#get the View
View2 = ReturnView(Prize, Guess)
#get the new Guest
Next_Guest = NewGuess(Guess,View2)
#increase the winning times if new Guest is the prize
if Next_Guest == Prize:
n_winning += 1
#print the result
print("%5d%11d%11d%11d"%(Prize,Guess,View2,Next_Guest))
#get the probability required
p_switch = n_winning/n
p_keep = 1- p_switch
print()
print("Probability of winning if you switch = %.2f"%(p_switch) )
print("Probability of winning if you do not switch = %.2f"%(p_keep) )
main()
| true |
0a038c00f9cff3ccff7aa3b96e73e9acdc386087 | carlos-paniagua/Course | /Python/Basic/program1.py | 1,656 | 4.28125 | 4 | '''
ここでは変数を使った、計算を扱います。
コメントにそれがどのような計算をしているのかが書かれているので、それを参照しながらやってください。
もしわからないことがあれば、私にslackで聞いてください。
'''
a=2 #(今定義した変数である)aに2を代入
print(a) #aの値を表示
b=5 #(今定義した変数である)bに5を代入
print(b) #bの値を表示
c=a+b #cにaとbを足した時の値をcに代入
print(c) #cの値だけ表示
print("c="+str(c)) #c=(cの値を表示)
d=a-b #dにaからbを引いた時の値をdに代入
print("c="+str(d))
e=a*b #eにaとbを掛けた時の値をeに代入
print("e="+str(e))
f=b/a #fにbをaで割った時の値をfに代入
print("f="+str(f))
g=b%a #gにbをaで割ったものの「余り」をgに代入
print("g="+str(g))
h=c*e+a #計算されて代入された変数と最初に数値を代入した変数を使い、計算、それをhに代入
print("h="+str(h))
i=f/e #計算されて代入された変数同士を、計算、それをiに代入
print("i="+str(i))
#ちなみに以下のような応用的な代入の仕方もあります(下の結果はコンソールで表示されません、各自自分でやってみてください)
#c, d, e, f, g, h, i= a+b, a-b, a*b, b/a, b%a, c*e+a, f/e
#print(a, b, c, d, e, f, g, h, i)
'''
課題work1
a=25, b=12として、aを2乗したものにbを5回かけた値を出力するプログラムを作成しよう。
''' | false |
d7e70522a7912d96c6b89203265e1dd24c7b67d5 | Amagash/Udacity_Python | /CS101/rounding numbers.py | 1,131 | 4.34375 | 4 | # Given a variable, x, that stores the
# value of any decimal number, write Python
# code that prints out the nearest whole
# number to x.
# If x is exactly half way between two
# whole numbers, round up, so
# 3.5 rounds to 4 and 2.5 rounds to 3.
# You may assume x is not negative.
# Hint: The str function can convert any number into a string.
# eg str(89) converts the number 89 to the string '89'
# Along with the str function, this problem can be solved
# using just the information introduced in unit 1.
# x = 3.14159
# >>> 3 (not 3.0)
# x = 27.63
# >>> 28 (not 28.0)
# x = 3.5
# >>> 4 (not 4.0)
x = 3.14159
#ENTER CODE BELOW HERE
string_x = str(x)
print string_x
position_comma = string_x.find('.')
print position_comma
before_comma = string_x[:position_comma]
convert_int_before_comma = int(before_comma)
print before_comma
print convert_int_before_comma
after_comma = string_x[position_comma+1:]
print after_comma
first_after_comma = after_comma[0]
print first_after_comma
convert_int = int(first_after_comma)
print convert_int
if (convert_int>4):
then round_x = convert_int_before_comma + 1
print round_x | true |
d8abfba650de3dda7207eeb700fa152b4edc4f93 | Deanna2000/python-lists | /planets.py | 622 | 4.15625 | 4 | # Exercise to practice with lists
planet_list = ["Mercury", "Mars"]
print("Original list of planets ", planet_list)
planet_list.append("Jupiter")
planet_list.append("Saturn")
print("Additional planets ", planet_list)
planet_list.extend(["Uranus", "Neptune"])
print("Adding two of the last planets ", planet_list)
planet_list.insert(1, "Venus")
planet_list.insert(2, "Earth")
print("Inserting Venus and Earth ", planet_list)
planet_list.append("Pluto")
print("And last but not least, adding pluto ", planet_list)
rocky_planets = planet_list[0:4]
print ("Rocky Planets ", rocky_planets)
del planet_list[8]
print(planet_list) | false |
18c74b300a64d67319f90ebc1ee08ea1880c62bd | AbdullahiAbdulkabir/QuadraticEquation | /calcnoofdays.py | 626 | 4.125 | 4 | #Joshua Odubiro
#olayemisamuel55@gmail.com
#08162583688
#python to calculate number of days between two dates
from datetime import date
def op():
year=int(input("input the start year in integer format"))
month=int(input("input the start month in integer format"))
day=int(input("input the start day in integer format"))
endyear=int(input("input the end year in integer format"))
endmonth=int(input("input the end month in integer format"))
endday=int(input("input the end day in integer format"))
do=date(year,month,day)
d1=date(endyear,endmonth,endday)
delta=d1-do
print(delta.days+1)
op()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.