blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
cfaea52ac9969a85717b253d7b31fc89e38d6f5c | angelocesar1/htx-immersive-08-2019 | /01-week/3-thursday/labs/angelo/fizz-buzz1.py | 258 | 4.25 | 4 | while True:
number = int(input("Pick a number!"))
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz!")
elif number % 3 == 0:
print("Fizz!")
elif number % 5 == 0:
print("Buzz!")
else:
print("Neither!") | false |
27ab6806486ba77b527015d214c5f21ba886b2f9 | Detroit-the-Dev/candy_exercise | /candy_problem/main.py | 949 | 4.25 | 4 | '''
DIRECTIONS
==========
1. Given the list `friend_favorites`, create
a new data structure in the function `create_new_candy_data_structure`
that describes the different kinds of candy paired with a list of friends that
like that candy.
friend_favorites = [
[ "Sally", [ "lollipop", "bubble gum", "laffy taffy" ]],
[ "Bob", [ "milky way", "licorice", "lollipop" ]],
[ "Arlene", [ "chocolate bar", "milky way", "laffy taffy" ]],
[ "Carlie", [ "nerds", "sour patch kids", "laffy taffy" ]]
]
2. In `get_friends_who_like_specific_candy()`, return friends who like lollipops.
3. In, `create_candy_set()`, return a set of all the candies from
the data structure made in `create_new_candy_data_structure()`.
4. Write tests for all of the functions in this exercise.
'''
def create_new_candy_data_structure(data):
pass
def get_friends_who_like_specific_candy(data, candy_name):
pass
def create_candy_set(data):
pass
| true |
9a86124292d6124b7478a25d892a3fe497c9e681 | Kilburn3G/capstonerepo | /dev_interfacing/piserver/working/Plotting.py | 2,036 | 4.1875 | 4 | import matplotlib.pyplot as plt
import matplotlib.animation as animation
############################################
########### PLOTTING #######################
############################################
def initplots():
'''
Used to get fig, ax plots
Return : fig, ax
'''
return plt.subplots()
def resetStartPos():
global start_pos
start_pos = 0;
# Parameters
X_LEN = 500 # Number of points to display
Y_RANGE = [0, 0.3] # Range of possible Y values to display
# Create figure for plotting
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
xs = list(range(0, X_LEN))
ys = [0] * X_LEN
ax.set_ylim(Y_RANGE)
# Create a blank line. We will update the line in animate
line, = ax.plot(xs, ys)
def updateList(ys,data):
global start_pos, next_start
ys_len = len(ys)
data_len = len(data)
next_start = start_pos+data_len
if next_start >= ys_len:
start_pos=0
else:
for i in range(data_len):
ys[start_pos+i] = data[i]
start_pos=next_start
return ys
def animate(i, ys):
# Add y to list
data = readByte()
ys = updateList(ys,parseDataList(data))
print(ys)
# # Limit y list to set number of items
# ys = ys[-X_LEN:]
# Update line with new Y values
line.set_ydata(ys)
return line,
def plotSegments(V, peaks , fig, ax):
'''
Plots segments overtop of eachother. Needs initialized fig and ax
V : Dataframe of our signal
peaks : list of locations for peaks
'''
if len(peaks) > 0:
avg_samples = np.sum(np.diff(peaks))/len(np.diff(peaks))
print('Average Samples between peaks : %d' %avg_samples)
for i in range(0,len(peaks)):
pdb.set_trace()
if peaks[i] - avg_samples > 0 and peaks[i]+avg_samples < len(V):
ax.plot(V.loc[peaks[i]-avg_samples/2:peaks[i]+avg_samples/2])
plt.show()
else:
print('Could not plot, no peaks found')
| true |
e7a5e30af743bbfc9893aef207b96b0abcd37e8b | MTShaon/python-basic-problem-solve | /basic part 1.85.py | 301 | 4.375 | 4 | # Write a Python program to check if a file path is a file or a directory
import os
path = "abc.txt"
if os.path.isdir(path):
print("\n It is a directory")
elif os.path.isfile(path):
print("\n this is a normal file")
else:
print("It is a special file (socket, FIFO, device file)")
| true |
0fd59198be9e85ba8380c193200bc30d5f8959ad | MTShaon/python-basic-problem-solve | /basic part 1.83.py | 245 | 4.21875 | 4 | # Write a Python program to test whether all numbers of a list is greater than a certain number.
list = [34,57,43,67,68,9,76,44,33]
n=5
def check(n):
for i in list:
if i < n :
return i>n
return i>n
print(check(n)) | true |
d06501d8c20dc835a6dec7487cb307a6995b2958 | MTShaon/python-basic-problem-solve | /basic part 1.18.py | 242 | 4.15625 | 4 | #WAP to calculate the sum of three given numbers, if the values are equal then return three times of their sum
def sum_(x,y,z):
sum =x+y+z
if x==y==z:
sum=sum*3
return sum
print(sum_(1,2,3))
print(sum_(3,3,3)) | true |
ce04a338836b6c9037f4ba05f2b35d5eb242346b | DongHyukShin93/BigData | /python/python03/Python03_02_AddOddEven_신동혁.py | 372 | 4.15625 | 4 | #Python03_02_AddOddEven_신동혁
#1~10까지의 합
add = 0
for i in range(1,11) :
add = add+i
print("1~10까지의 합",add)
#1~10까지의 홀수합
odd = 0
for i in range(1,11,2) :
odd = odd + i
print("1~10까지의 홀수합",odd)
#1~10까지의 짝수합
even = 0
for i in range(2,11,2) :
even = even + i
print("1~10까지의 짝수합",even) | false |
f1832070ff80fb3e5470c44ee6f929f55328974d | reemahs0pr0/Daily-Coding-Problem | /Problem22 - Balanced Brackets Check.py | 983 | 4.375 | 4 | # Given a string of round, curly, and square open and closing brackets,
# return whether the brackets are balanced (well-formed).
# For example, given the string "([])[]({})", you should return true.
# Given the string "([)]" or "((()", you should return false.
string1 = "([])[]({})"
string2 = "([)]"
string3 = "((()"
def check(string):
open_set = {"(", "{", "["}
checklist = []
for c in string:
if len(checklist) == 0 or c in open_set:
checklist.append(c)
else:
if checklist[len(checklist)-1] == "(" and c == ")":
del checklist[-1]
elif checklist[len(checklist)-1] == "[" and c == "]":
del checklist[-1]
elif checklist[len(checklist)-1] == "{" and c == "}":
del checklist[-1]
else:
return False
if len(checklist) == 0:
return True
return False
print(check(string1))
print(check(string2))
print(check(string3)) | true |
2fc09a717e1f3a9ceeb0bddd7cbca9e9b6c5899f | reemahs0pr0/Daily-Coding-Problem | /Problem20 - Running Median.py | 578 | 4.125 | 4 | # Compute the running median of a sequence of numbers. That is, given a
# stream of numbers, print out the median of the list so far on each new
# element.
# Recall that the median of an even-numbered list is the average of the
# two middle numbers.
arr = [2, 1, 5, 7, 2, 0, 5]
for i in range(1, len(arr)+1):
new_arr = arr[:i]
new_arr.sort()
if i == 1:
print(new_arr[0])
elif i%2 == 0:
median = (new_arr[int(i/2)] + new_arr[int(i/2)-1])/2
print(int(median) if median%2 == 0 else median)
else:
print(new_arr[int((i-1)/2)]) | true |
508f75b32ea7038bcd2b4f9d0ec48dd39b93d17b | reemahs0pr0/Daily-Coding-Problem | /Problem56 - Array Permutation.py | 722 | 4.4375 | 4 | # A permutation can be specified by an array P, where P[i] represents the location of the element at i in the permutation. For example, [2, 1, 0] represents the permutation where elements at the index 0 and 2 are swapped.
# Given an array and a permutation, apply the permutation to the array. For example, given the array ["a", "b", "c"] and the permutation [2, 1, 0], return ["c", "b", "a"].
def permute_array(arr, permutation):
result = []
dict = {}
for i in range(len(arr)):
dict[i] = arr[i]
for i in range(len(permutation)):
result.append(dict[permutation[i]])
return result
P = ["a", "b", "c"]
permutation = [2, 1, 0]
permuted_P = permute_array(P, permutation)
print(permuted_P) | true |
9878a677e6db143a59d3a45a080719d7b74ca453 | reemahs0pr0/Daily-Coding-Problem | /Problem59 - Find Starting Indices of Pattern.py | 538 | 4.1875 | 4 | # Given a string and a pattern, find the starting indices of all occurrences of the pattern in the string. For example, given the string "abracadabra" and the pattern "abr", you should return [0, 7].
def find_pattern(string, pattern):
result = []
pattern_length = len(pattern)
i = 0
while i < len(string)-(pattern_length-1):
if (string[i:i+3] == pattern):
result.append(i)
i += 3
i += 1
print(result)
string = 'abracadabrabcdeabr'
pattern = 'abr'
find_pattern(string, pattern) | true |
dc01dbb37d85d4d84efde6c0a0ccfc173aebce6c | BBK-PiJ-2015-10/ActiveMQBook | /python-course-eu/.idea/pythoncourse/ClassAndInheritanceExamples.py | 1,744 | 4.21875 | 4 | class A:
a = "I am a class attribute"
x = A()
y = A()
#print(x.a)
#print(y.a)
#print(A.a)
x.a = "This creates a new instance attribute for x"
#print(y.a)
#print(A.a)
#print(x.a)
#print(x.__dict__)
#print(y.__dict__)
#print(A.__dict__)
"""
class Robot:
Three_Laws = (
"Love your self",
"Love God"",
"Love Others"
)
def __init__(self, name, build_year):
self.name = name
self.build_year = build_year
#other methods as usual
for number, text in enumerate(Robot.Three_Laws):
print(str(number+1) +":\n" + text)
class C:
counter = 0
def __init__(self):
type(self).counter +=1
def __del__(self):
type(self).counter -=1
if __name__ == "__main__":
x = C()
print("Number of instances: : " +str(C.counter))
y = C()
print("Number of instances: : " +str(C.counter))
del x
print("Number of instances: : " +str(C.counter))
del y
print("Number of instances: : " +str(C.counter))
"""
class Robot:
__counter = 0
def __init__(self):
type(self).__counter +=1
@staticmethod
def RobotInstances():
return Robot.__counter
@classmethod
def RobotTypes(cls):
return cls, Robot.__counter
#print(Robot.RobotInstances())
#x = Robot()
#print(x.RobotInstances())
class Pets:
name ="pet animals"
@staticmethod
def about():
print("This will always yield {}!".format(Pets.name))
@classmethod
def materia(cls):
print("This will change to {}".format(cls.name))
class Dogs(Pets):
name = "dogs"
class Cats(Pets):
name = "cats"
p = Pets()
d = Dogs()
c = Cats()
p.about()
p.materia()
d.about()
d.materia()
c.about()
c.materia() | true |
1caccdf22ca5ae33e69ad2501309f223cddafc40 | radaras/Clasespython | /menu.py | 1,947 | 4.15625 | 4 | # ===================Funciones
def bienvenida():
text = '''
Menu de opciones
=================
1. Sumar 2 numeros
2. Mayor de 3 numeros
3. Menor de 3 numeros
4.Ver la nota del Alumno A,B,C,AD
5.Salio del programa
Ingrese un opcion para continuar...
'''
print(text)
def seleleccionarOpcion():
opcion = int(input("Ingrese la opcion: "))
seleccionarOperacio(opcion)
def mayor3num():
a = int(input("Ingrese a: "))
b = int(input("Ingrese b: "))
c = int(input("Ingrese c: "))
mayor=0
if a >= b and a >= c:
mayor=a
if b >= a and b >= c:
mayor=b
if c >= a and c >= b:
mayor=c
print("El mayor:" + str(mayor))
inicio()
def menor3num():
a = int(input("Ingrese a: "))
b = int(input("Ingrese b: "))
c = int(input("Ingrese c: "))
menor = 0
if a <= b and a <= c:
menor = a
if b <= a and b <= c:
menor = b
if c <= a and c <= b:
menor = c
print("El menor:" + str(menor))
inicio()
def seleccionarOperacio(opcion):
if opcion == 1:
sumar()
if opcion == 2:
mayor3num()
if opcion == 3:
menor3num()
if opcion == 4:
nota()
if opcion == 5:
print("Salió del Programa")
def inicio():
bienvenida()
seleleccionarOpcion()
def nota():
nota = (int(input("Ingrese nota1 : ")))
if nota > 11 and nota < 14:
print("la persona a aprovado con B")
if nota > 14 and nota < 17:
print("La persona a aprovado con A")
if nota > 17 and nota < 20:
print("La persona a aprovado con AD")
else:
print("La persona a desaprovado con c")
inicio()
def sumar():
a = int(input("Ingrese a: "))
b = int(input("Ingrese b: "))
resultado = a + b
print(" El resultado de a + b es :" + str(resultado))
inicio()
# ===================utilizo las funciones para jejcutar
inicio() | false |
61eaff28cf8d539f76dd09d8bc0b3adca645ed6f | anessaa/DojoAssignments | /Python/makingAndReadingFromDictionaries.py | 231 | 4.15625 | 4 | info = {"name": "Anessa", "age": 26, "country of birth": "The United States", "favorite language": "Python"}
def readingDictionary():
for input in info.keys():
print "My", input, "is", info[input]
readingDictionary()
| true |
87b03645239c838deb299b0b5ffb23c88381e4ee | anessaa/DojoAssignments | /Python/multiples.sum.average.py | 823 | 4.625 | 5 | #Multiples
#part 1-Write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use a list to do this exercise.
#part 2-Create another program that prints all the multiples of 5 from 5 to 1,000,000.
for count in range(1,1000): #for loop to find odd numbers from 1 to 1000
if count % 2 !=0:
print count
for mul in range(0,1000000,5): #for loop to print multiples of 5 from 5 to 1000000
print mul
#Sum List
#Create a program that prints the sum of all the values in the list: a = [1, 2, 5, 10, 255, 3]
a = [1, 2, 5, 10, 255, 3]
sum = 0
for item in a:
sum += item
print sum
#Average List
#Create a program that prints the average of the values in the list: a = [1, 2, 5, 10, 255, 3]
a = [1, 2, 5, 10, 255, 3]
sum = 0
for item in a:
sum += item
avg = sum / len(a)
print avg
| true |
259f9f58482ed10cf7bbad379ae5711a3d9bd583 | ACGNnsj/compuational_physics_N2014301020001 | /Final Project/Final Project2-2.py | 1,255 | 4.1875 | 4 | import turtle
from random import randint
turtle.speed(16) # Set turtle speed to slowest
turtle.title('2D lattice random walk')
# Draw 16 by 16 lattices
turtle.color("gray") # Color for lattice
x = -320
for y in range(-320, 320 + 1, 10):
turtle.penup()
turtle.goto(x, y) # Draw a horizontal line
turtle.pendown()
turtle.forward(640)
y = 320
turtle.right(90)
for x in range(-320, 320 + 1, 10):
turtle.penup()
turtle.goto(x, y) # Draw a vertical line
turtle.pendown()
turtle.forward(640)
turtle.pensize(3)
turtle.color("red")
turtle.penup()
turtle.goto(0, 0) # Go to the center
turtle.pendown()
x = y = 0 # Current pen location at the center of lattice
while abs(x) < 320 and abs(y) < 320:
r = randint(0, 3)
if r == 0:
x += 10 # Walk east
turtle.setheading(0)
turtle.forward(10)
elif r == 1:
y -= 10 # Walk south
turtle.setheading(270)
turtle.forward(10)
elif r == 2:
x -= 10 # Walk west
turtle.setheading(180)
turtle.forward(10)
elif r == 3:
y += 10 # Walk north
turtle.setheading(90)
turtle.forward(10)
turtle.done() | true |
94379e5fed5992cb8efb55d7ada1db6486c96091 | Rauldsc/ExercisesPython | /basic1/ex5.py | 278 | 4.21875 | 4 | """
Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them.
"""
firstName = input("Input your firs name: ")
lastName = input("Input your last name: ")
print("Your name is: " + lastName + " " + firstName) | true |
cea2d88d1e63f148901acacda9ef7a5b39230705 | Rauldsc/ExercisesPython | /basic1/ex144.py | 291 | 4.25 | 4 | """
Write a Python program to check whether variable is of integer or string.
"""
#My code
x = 12
print(type(x))
#Sample code
"""
print(isinstance(25,int) or isinstance(25,str))
print(isinstance([25],int) or isinstance([25],str))
print(isinstance("25",int) or isinstance("25",str))
""" | true |
a18225c86b7fe524d640394d283a733c4e468f02 | antdinodev/pythonfun01 | /pythonlearn16-oop.py | 669 | 4.21875 | 4 | #oop for beginners
#tutorial - https://www.youtube.com/watch?v=JeznW_7DlB0
#haro I am vietnamesu programma i'm going to teach you oop in python todayy, let's get started
class Dog:
def __init__(self,name, age):
self.name = name
self.age = age
#@property #this is called a dunder property, it will let you access the name without using get_name().
#example d2.getname
def get_name(self):
return self.name
def get_age(self):
return self.age
def add_one(self,x):
return x +1
def bark(self):
print("bark")
d = Dog("Tim")
d2 = Dog("Bill")
print(d.name)
print(d2.name)
print(d2.get_name)
| true |
a00f93d3b1f4cdf325f992b21b5715737ef28a2a | antdinodev/pythonfun01 | /pythonlearn14-higherlower.py | 510 | 4.34375 | 4 | import game_data
import art
#tackle problem
#to do list
#pick easiest thing to do first
#break it into comment
# Python3 code to iterate over a list
list = [1, 3, 5, 7, 9]
# getting length of list
length = len(list)
# Iterating the index
# same as 'for i in range(len(list))'
for i in range(length):
print(list[i])
print(art.logo)
print(art.vs)
#display art
#generate a random account form the game data
#format account data into a printable format
#ask user for a guess
#check if user is correct | true |
870a60980ac1f7440453ca74b614687ff43f63c3 | rohanwarange/Accentures | /program3.py | 1,208 | 4.125 | 4 | # # -*- coding: utf-8 -*-
# """
# Created on Fri Jun 25 09:47:55 2021
# @author: ROHAN
# """
# Implement the following Function
# def ProductSmallestPair(sum, arr)
# The function accepts an integers sum and an integer array arr of size n. Implement the function to find the pair, (arr[j], arr[k]) where j!=k, Such that arr[j] and arr[k] are the least two elements of array (arr[j] + arr[k] <= sum) and return the product of element of this pair
# NOTE
# Return -1 if array is empty or if n<2
# Return 0, if no such pairs found
# All computed values lie within integer range
# Example
# Input
# sum:9
# Arr:5 2 4 3 9 7 1
# Output
# 2
# Explanation
# Pair of least two element is (2, 1) 2 + 1 = 3 < 9, Product of (2, 1) 2*1 = 2. Thus, output is 2
# Sample Input
# sum:4
# Arr:9 8 3 -7 3 9
# Sample Output
# -21
arr=[4,2,4,3,9,7,1]
def ProductSmallestPair(sum,arr):
if len(arr)<2:
return 0
else:
total=0
for i in arr:
for j in arr:
if i+j<=sum:
total+=1
p=i*j
return f"their are {total} sums and product is {p}"
print(ProductSmallestPair(9,arr))
| true |
bfea8b08b67687f493e81c9ed17d362c0b142353 | sanghvip/LearnPythonHardWayExercise | /ex8.py | 767 | 4.375 | 4 | formatter = "%r %r %r %r"#%r gives the raw representation of the variable to be printed.
print(formatter % (1, 2, 3, 4))
print(formatter % ("one", "two", "three", "four"))
print(formatter % (True, False, False, True))
print(formatter % (formatter, formatter, formatter, formatter))#output:'%r %r %r %r' '%r %r %r %r' '%r %r %r %r' '%r %r %r %r'[1]
print(formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight."
))
'''
[1]The output contains many %r because while printing we are passing the formatter variable to variable before the %.Moreover the formatter is then referring to '%r %r %r %r'.So in place of each %r formatter var value i.e '%r %r %r %r' will be printed .Hence we have 16 %r.
''' | true |
a3aabbfdb4a91001166be4f09fa381b217159b41 | yelaura/python-assignments | /Python Programming/Laura Ye X442.3 Assignment 7.py | 1,698 | 4.375 | 4 |
# coding: utf-8
# In[ ]:
import string
'''
Suppose you want to determine whether an arbitrary text string can be converted to a number. Write a function that uses a try/except clause to solve this problem. Can you think of another way to solve this problem?
'''
def str_to_int(strInput):
try:
intOutput = float(strInput)
return intOutput
except ValueError as errormsg:
print("Input is not a convertible string")
return None
'''
Another way to solve this problem would be to iterate through the string input.
If every character is part of the built-in string.digits, then it's convertible
If there is one character that is not part of the built-in string.digits or a decimal point), then it's not convertible
'''
def str_to_int1(strInput):
digits = string.digits + "."
for i in strInput:
if i not in digits:
print ("Input is not a convertible string")
return None
return float(strInput)
# In[ ]:
'''
The input function will read a single line of text from the terminal. If you wanted to read several lines of text, you could embed this function inside a while loop and terminate the loop when the user of the program presses the interrupt key (Ctrl-C under UNIX, Linux and Windows.) Write such a program, and note its behavior when it receives the interrupt signal. Use a try/except clause to make the program behave more gracefully.
'''
import sys
def inputText():
while 1:
try:
text = input("Some text you want: ")
print ("\nWhat I got: ", text)
except KeyboardInterrupt:
print ("\nOkay we're done here.")
sys.exit()
inputText()
| true |
6b09e7275aae9ce7a44de50acdbbc8acbc3fb87a | jamesl33/210CT-Course-Work | /task8/part 1/unit_test.py | 1,301 | 4.125 | 4 | #!/usr/bin/python3
""" unit_test.py: Unit testing for levenshtein string distance function
"""
import unittest
from string_converter import levenshtein
class UnitTest(unittest.TestCase):
"""UnitTest: Unit testing class for testing that levenshtein is working as expexted
"""
def test_known_values(self):
"""test_known_values: Test values for vanilla string distance (levenshtein distance)
"""
self.assertEqual(levenshtein('abc', 'abcd'), 1)
self.assertEqual(levenshtein('abd', 'ab'), 1)
self.assertEqual(levenshtein('abd', 'abc'), 1)
self.assertEqual(levenshtein('kitten', 'sitting'), 3)
self.assertEqual(levenshtein('hill', 'hello'), 2)
def test_afaik_correct_values(self):
"""test_afaik_correct_values: This function does work for calculating the string
distance but i'm not 100% sure when the weights are changed
"""
self.assertEqual(levenshtein('abc', 'abcd', 3, 4, 5), 4)
self.assertEqual(levenshtein('abd', 'ab', 3, 4, 5), 3)
self.assertEqual(levenshtein('abd', 'abc', 3, 4, 5), 5)
self.assertEqual(levenshtein('kitten', 'sitting', 3, 4, 5), 13)
self.assertEqual(levenshtein('hill', 'hello', 3, 4, 5), 9)
if __name__ == '__main__':
unittest.main()
| true |
87322c71c80f5262403e0c766c44be3a9092949e | jamesl33/210CT-Course-Work | /task1/part 1/factorials.py | 820 | 4.59375 | 5 | #!/usr/bin/python3
"""factorials.py: contains the functions to calculate the factorial of a number
and to test dividing equally with a factorial number
"""
def factorial(num):
"""factorial
:param num: Number which you would like the factorial of
"""
assert isinstance(num, int)
if num == 0:
return 1
return num * factorial(num - 1)
def test_divides(num_a, num_b):
"""test_divides
:param num_a: Number we calculate the factorial of and then is tested if
divides by 'b' equally
:param num_b: 'a!' is divided by this number
"""
assert isinstance(num_a, int)
assert isinstance(num_b, int)
if factorial(num_a) % num_b:
return("{0} does not divide by {1}!".format(num_b, num_a), False)
return("{0} divides by {1}!".format(num_b, num_a), True)
| true |
8a243ce5c45f3cbdf4986940239ca189586f249f | jtrieudang/CodingDojo-Python | /FakeBankPractice.py | 1,579 | 4.1875 | 4 | class User:
def __init__(self):
self.name = "Jimmy"
self.email = "trieujimmy@yahoo.com"
self.account_balance = 0
guido = User()
monty = User()
print(guido.name) # output: Jimmy
print(monty.name) # output: Jimmy
guido.name = "Guido"
monty.name = "Monty"
# -----------------------------------------------------------------------------------
class User:
def __init__(self, username, email_address):# now our method has 2 parameters!
self.name = username # and we use the values passed in to set the name attribute
self.email = email_address # and the email attribute
self.account_balance = 0 # the account balance is set to $0, so no need for a third parameter
jenny = User("Jenny Tree", "tree_jenny@yahoo.com")
johnny = User("Johnny Tree", "tree_johnn@yahoo.com")
print(jenny.name)
print(johnny.email)
# -------------------------------------------------------------------------------------
class User: # here's what we have so far
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
# adding the deposit method
def make_deposit(self, amount): # takes an argument that is the amount of the deposit
self.account_balance += amount # the specific user's account increases by the amount of the value received
guido = User("Guido van Rossum", "guido@python.com")
monty = User("Monty Python", "monty@python.com")
guido.make_deposit(100)
guido.make_deposit(200)
monty.make_deposit(50)
print(guido.account_balance) # output: 300
print(monty.account_balance) # output: 50
| true |
8a79b272412ceed845adbeac0a02ff051b8b6cb3 | jtrieudang/CodingDojo-Python | /Function_Intermediate_1.py | 1,111 | 4.1875 | 4 | import random
def randInt(min=0, max=100):
if max != 100: #2
return round(random.random()*(max-min)+min) #with the function alone, 50 can replace (max-min)+min
if min !=0: #3
return round(random.random()*(max-min)+min)
if min != 0 and max != 100: #4
return round(random.random())
num = round(random.random()*100) #1
return num
print(randInt())# should print a random integer between 0 to 100
print(randInt(max=50))# should print a random integer between 0 to 50
print(randInt(min=50))# should print a random integer between 50 to 100
print(randInt(min=50, max=500))# should print a random integer between 50 and 500
# If no arguments are provided, the function should return a random integer between 0 and 100.
# If only a max number is provided, the function should return a random integer between 0 and the max number.
# If only a min number is provided, the function should return a random integer between the min number and 100
# If both a min and max number are provided, the function should return a random integer between those 2 values. | true |
edf5e4d25e13314e63760efe1f956e8ca0fb9895 | huynhkGW/ICS-Python-Notes | /notes/23 - exceptions/basic-input-example.py | 789 | 4.25 | 4 | #-----------------------------------------------------------------------------
# Name: Catching Exceptions (try-except.py)
# Purpose: To provide example of a simple input loop using try-catch
#
# Author: Mr. Brooks
# Created: 01-Oct-2020
# Updated: 01-March-2021
#-----------------------------------------------------------------------------
while True: #Start an infinite loop
value = input('Enter a number between -100 and 100: ') #Get a value from the user
try:
value = int(value) #Convert the value to an int
except Exception as e:
print(f'Something went wrong: {e}') #You should probably add a nicer error message
else:
#No exception was thrown, so break out of the infinite loop
break | true |
d0b1bc538baa9957bc4fbec577818caa5205c36d | huynhkGW/ICS-Python-Notes | /notes/34 - time/time_ex.py | 1,857 | 4.78125 | 5 | #-----------------------------------------------------------------------------
# Name: Time Example (time_ex.py)
# Purpose: To provide examples of how to use the time library.
#
# Author: Mr. Brooks
# Created: 26-Oct-2021
# Updated: 27-Oct-2021
#-----------------------------------------------------------------------------
import time
endCount = 5 #number of times to count
delayTime = 1 #Time for each delay (in seconds)
#If we want to count up every x seconds, there are a couple of ways to do it.
# #Method 1: time.sleep
# #time.sleep() is blocking. What this means is that when you use time. sleep() ,
# #you'll block the main thread from continuing to run while it waits for the sleep() call to end.
#
# counter = 0;
# while True: #Create a never-ending loop
# if counter < endCount:
# counter += 1;
# else:
# break
#
# print(counter, end='... ')
# time.sleep(delayTime) #pauses the execution of the ENTIRE PROGRAM
# #Due to it's blocking method using time.sleep isn't always optimal if you want to do anything else at the same time
# print(time.time())
#
#Method 2 - Storing a time.time() value
print('\r\nCurrent Time = ', time.time())
futureTime = time.time() + delayTime #Set the
print(futureTime)
counter = 0;
while True: #Create a never-ending loop
if futureTime < time.time():
if counter < endCount:
counter += 1;
futureTime = time.time() + delayTime
else:
break
print(counter, end='... ')
#Almost the exact same functionality EXCEPT this method is non-blocking
#print(time.time())
#Method 3,4,5 etc
# https://pygame-zero.readthedocs.io/en/stable/builtins.html#clock
# https://realpython.com/python-sleep/#adding-a-python-sleep-call-with-decorators
| true |
af00db0bf7cb8bebe425928c9e82594f402dc708 | kongqiwei/ML_related_kongqiwei | /ganeral.py | 730 | 4.34375 | 4 | #复用性很高的通用代码
##完美读取二维结构的数据,分离出第一行和第一列的标题,单独读取出数据
def readfile(filename):
file=open(filename)
lines=[line for line in file]
# First line is the column titles
colnames=lines[0].strip().split('\t')[1:]
rownames=[]
data=[]
for line in lines[1:]:
p=line.strip().split('\t')
# First column in each row is the rowname
rownames.append(p[0])
# The data for this row is the remainder of the row
data.append([float(x) for x in p[1:]])
return rownames,colnames,data
blognames,word,data=readfile('C:/Users/USER/testdata.txt')###这里一定要把本地txt文件的后缀txt三个字母去掉
print(blognames,word,data)
| false |
7f01c0caaec7acca8f7cdd9bdc21ddd9400469a4 | robin8a/udemy_raspberry_machine_learning | /Codes/Course_codes_image/4.2-Scaling.py | 1,363 | 4.125 | 4 | # Scaling (Resizing) Images - Cubic, Area, Linear Interpolations
# Interpolation is a method of estimating values between known data points
# Import Computer Vision package - cv2
import cv2
# Import Numerical Python package - numpy as np
import numpy as np
# Read the image using imread built-in function
image = cv2.imread('image_2.jpg')
# Display original image using imshow built-in function
cv2.imshow("Original", image)
# Wait until any key is pressed
cv2.waitKey()
# cv2.resize(image, output image size, x scale, y scale, interpolation)
# Scaling using cubic interpolation
scaling_cubic = cv2.resize(image, None, fx=.75, fy=.75, interpolation = cv2.INTER_CUBIC)
# Display cubic interpolated image
cv2.imshow('Cubic Interpolated', scaling_cubic)
# Wait until any key is pressed
cv2.waitKey()
# Scaling using area interpolation
scaling_skewed = cv2.resize(image, (600, 300), interpolation = cv2.INTER_AREA)
# Display area interpolated image
cv2.imshow('Area Interpolated', scaling_skewed)
# Wait until any key is pressed
cv2.waitKey()
# Scaling using linear interpolation
scaling_linear = cv2.resize(image, None, fx=0.5, fy=0.5, interpolation = cv2.INTER_LINEAR)
# Display linear interpolated image
cv2.imshow('Linear Interpolated', scaling_linear)
# Wait until any key is pressed
cv2.waitKey()
# Close all windows
cv2.destroyAllWindows()
| true |
64174981d7f036f5e25bbc28268e0cd07301a753 | sonia650/rock_paper_scissors | /pythongame.py | 2,307 | 4.15625 | 4 | import random
from ascii import simpson
def computer_random():
c = ["rock", "paper", "scissors"]
computer = random.choice(c)
return computer
def player_moves():
print ("Please play one of the following")
player1 = raw_input(" Rock, Paper, Scissors:\n").lower()
return player1
def find_winner(player1,computer):
if player1 == "scissors":
if computer == "scissors":
return "Computer picked scissors too!\nLOL, Tie!"
elif computer == "rock":
return "Computer chose rock.....\n YOU LOSE BABY"
elif computer == "paper":
return "Computer chose paper....\nYOU WIN BABY!"
else:
return "DO YOU EVEN KNOW HOW TO PLAY?"
elif player1 == "paper":
if computer == "paper":
return "Seriously, It\'s a Tie!"
elif computer == "rock":
return "Computer chose rock.....YOU WIN BOO"
elif computer == "scissors":
return "Computer chose scissors, You LOSE!"
else:
return "wtf is going on?"
elif player1 == "rock":
if computer == "rock":
return "Computer picked Rock Too! UGH, Tie!"
elif computer == "paper":
return "Computer chose paper....YOU\'RE A LOSER"
elif computer == "scissors":
return "Computer chose scissors, You win"
else:
return "WTF ARE YOU DOING"
def options():
print "Please choose from the following:"
print "1 - Play Again"
print "2 - Quit"
choices = int(raw_input())
return choices
def main():
raw_input("\nAre you ready to play?\n")
print simpson
raw_input('''\nWe're going to play Rock, Paper, Scissors\n
\nSimpsons Edition\n
PRESS ENTER TO PLAY''')
print '''\nRULES OF THE GAME:
\n1)Rock Breaks Scissors,
\n2)Scissors Cuts Paper,
\n3)Paper Covers Rock\n'''
choices = 1
while True:
if choices == 1:
player1_move = player_moves()
computer_move = computer_random()
print find_winner(player1_move,computer_move)
elif choices == 2:
print "BYE FELICIA!"
break
choices = options()
if __name__ == '__main__':
main()
| true |
a0577c2cf6f2b77cde8ea693e11e37996e63191a | AngXuDev/Sorting | /src/iterative_sorting/iterative_sorting.py | 1,642 | 4.15625 | 4 | # TO-DO: Complete the selection_sort() function below
arr = [1, 5, 8, 4, 2, 9, 6, 0, 3, 7]
def selection_sort(arr):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# print(smallest_index)
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
# cur_index = arr.index(min(arr[i:]))
for k in range(i, len(arr)):
if (arr[k] < arr[smallest_index]):
smallest_index = k
# Why does this work?
# for k in range(1, len(arr[i:])):
# if (arr[k+i] < arr[smallest_index]):
# smallest_index = k+i
# TO-DO: swap
arr[smallest_index], arr[cur_index] = arr[cur_index], arr[smallest_index]
return arr
print(selection_sort(arr))
# TO-DO: implement the Bubble Sort function below
arr = [1, 5, 8, 4, 2, 9, 6, 0, 3, 7]
def bubble_sort(arr):
# check if need to continue to loop
counter = len(arr)-1
while counter > 0:
counter = len(arr)-1
# loop through elements
for i in range(0, len(arr) - 1):
# print(f"index: {i}, list: {arr}, counter: {counter}")
# compare element against neighbor:
if(arr[i] > arr[i+1]):
# if larger, swap positions
arr[i], arr[i+1] = arr[i+1], arr[i]
# decrease counter by 1 every time there is no swap
else:
counter -= 1
return arr
print(bubble_sort(arr))
# STRETCH: implement the Count Sort function below
def count_sort(arr, maximum=-1):
return arr
| true |
7d802a47c67abfff336a4b8232e1373e638e39ed | dishashetty5/Python-for-Everybody-tuples-. | /chap 10 1.py | 904 | 4.15625 | 4 | #Exercise 1: Revise a previous program as follows: Read and parse the
#“From” lines and pull out the addresses from the line. Count the number of messages from each person using a dictionary.
#After all the data has been read, print the person with the most commits
#by creating a list of (count, email) tuples from the dictionary. Then
#sort the list in reverse order and print out the person who has the most
#commits.
#Sample Line:
#From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
#Enter a file name: mbox-short.txt
#cwen@iupui.edu 5
#Enter a file name: mbox.txt
#zqian@umich.edu 195
filename=input("enter a file name: ")
fhand=open(filename)
days={}
for line in fhand:
if line.startswith("From "):
day=line.split()[1]
days[day]=days.get(day,0)+1
list=[]
for key,value in days.items():
list.append((value,key))
list.sort(reverse=True)
tuple=list[0]
print(tuple[1],tuple[0])
| true |
41b6192f4c9770b8f2e2bc7ab9f563545f2ea0fe | patpatpatpatpat/pythonista | /python_cookbook/ch01.py | 2,072 | 4.5625 | 5 | """
Chapter 1
1. Use Python "star expressions" to unpack elements from iterables of arbitrary length.
2. Use `collections.deque` to store the last few items during iteration or during some processing.
3. Use `heapq` to get the list of largest or smallest N items in a collection
4. Use `collections.defaultdict` and initialize the first value so you can focus on adding items.
5. Use `collections.OrderedDict` when creating a dictionary where you can control the order of items when iterating
6. Use `zip` to group items together
7. You can use `key` argument when using `min` and `max` functions
8. Use set operations to find out what two dicts (keys or values) have in common: &, -
9. Use `set` and generators to remove duplicates from a sequence while maintaining order
10. Use `slice` class to avoid mysterious hardcoded indices
11. Use `collections.Counter` class when determining most frequently occuring items in a sequence. You can also use mathematical operations in instances of them
12. Use `operator.itemgetter` to sort list of dicts based on one or more of the dict values.
`lambda` expressions can be used too, though (but the former is faster).
13. Use `operator.attrgetter` to sort objects of the same class, but don't natively support comparison operations.
14. Use `itertools.groupby` (after sorting the data according to the field of interest) to
iterate over data in groups
15. Use list comprehensions or `filter` when you need to extract values or reduce the sequence
using some criteria.
You can also transform the data at the same time!
Example: you can replace the values that don't meet the criteria with a new value instead
of discarding them.
Also: look into `itertools.compress`
16. Use dictionary comprehensions when creating a dictionary that is a subset of another dict.
17. `collections.namedtuple` to improve readability when accessing list or tuple elements by
position! However, they are immutable.
18. Use `collections.ChainMap` to perform lookups under multiple dictionaries (without merging them)
"""
| true |
50fa7787bac0b4846f545cef32f10824edf90656 | jsjambar/INFDEV01-1_0907663 | /Assignment4_Exc1/Assignment4_Exc1/Assignment4_Exc1b.py | 674 | 4.34375 | 4 | # Get number
celsius = input("What number do you want to convert?")
# Convert to float
celsius = float(celsius)
# Formula for Celsius to Kelvin is celsius + 273.15
kelvin = celsius + 273.15
# Kelvin keeps getting updated in this while, so if it's below 0 after the first time it keeps running till it is above 0
while(kelvin < 0):
celsius = input("This is below absolute zero. Please enter another number.")
kelvin = float(celsius) + 273.15
# Convert back to strings to show in a print
celsius = str(celsius)
kelvin = str(kelvin)
# Print the string with fahrenheit to celsius convertion
print(celsius + " celsius is " +kelvin+ " Kelvin")
| true |
e6f0492ab6da782a2809154f054fc3e796c77493 | jsjambar/INFDEV01-1_0907663 | /Assignment4_Exc1/Assignment4_Exc1/Assignment4_Exc1c.py | 489 | 4.1875 | 4 | # Get number
value = input("Enter a number.")
# Let's remove all '-'-characters method
nasty_value = value.replace("-", "")
# Convert to float
value = float(value)
# Lazy method
absolute_value = abs(value)
# Fancy if-statement?
# Convert the floated values to strings
value = str(value)
absolute_value = str(absolute_value)
print("Absolute value is:"+value)
print("Lazy non-if method: "+absolute_value)
print("Nasty remove '-' method: "+nasty_value) | true |
658b64516e7b02a686a6b49bdde5ad7a3e37972b | k45hish/Catenation | /Extra task/8.py | 569 | 4.125 | 4 | even_list = []
odd_list = []
c = 0
while c<5:
c += 1
x=int(input("Enter a number between 1 and 50 :"))
if x%2==0 and x<=50:
print("Valid number.")
even_list.append(x)
elif x%2!=0 and x<=50:
print("Valid number.")
odd_list.append(x)
else:
print("this is not a valid number.")
c -= 1
print("Even list:",even_list,",\n Sum of even list :",sum(even_list), ",\n Max of even list", max(even_list))
print("Odd list",odd_list, ",\nSum of odd list :", sum(odd_list), ",\n Max of odd lsit", max(odd_list)) | true |
91945805fb1e8e1a6c23124e53fe5a763a773189 | agvs03/internity-intern | /day3.py | 1,623 | 4.4375 | 4 | # simple python code to check whether a number is even or odd
def evenOdd(x):
if (x % 2 == 0):
print ("even")
else:
print ("odd")
# Driver code to call the function
if __name__=="__main__":
a = int(input("Enter a number"))
evenOdd(a)
# importing sqrt() and factorial from the
# module math
from math import sqrt, factorial
# if we simply do "import math", then
# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))
#List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc.
def listcomp(str):
List = []
for character in str:
List.append(character)
print(List)
if __name__=="__main__":
str = input("What do you want to add in list")
listcomp(str)
#iterators
def itera(val):
iter_obj = iter(val)
while True:
try:
item = next(iter_obj)
print(item)
except StopIteration:
break
if __name__=="__main__":
val = input("enter the data you want to iterate\n")
itera(val)
#generators
"""Generator-Function : A generator-function is defined like a normal function,
but whenever it needs to generate a value, it does so with the yield keyword
rather than return. If the body of a def contains yield, the function
automatically becomes a generator function."""
def nextsquare():
i=1;
while True:
yield i*i
i+=1
if __name__=="__main__":
it = int(input("Enter a number upto what number you need squares"))
for num in nextsquare():
if num>it:
break
print(num)
| true |
1a4cec9d2b2fb456f50204b8c533272c6ec87359 | qiweiii/LP-from-Automate-python-book | /collatz.py | 424 | 4.125 | 4 | # this is a Automate Boring Stuff in Python practice in Chap 3
def collatz(number):
if number % 2 == 0:
print('number / 2 = %s' %(number/2))
return number/2
else:
print('number * 3 + 1 = %s' %(number * 3 + 1))
return number*3 + 1
print ('Enter number')
userInput = int(input())
print('shit 1')
num = collatz(userInput)
while num != 1:
num = collatz(num)
| true |
a5522751e0fdd25406ab2b429a3348efdb0d8801 | qiweiii/LP-from-Automate-python-book | /bulletPointAdder.py | 698 | 4.125 | 4 |
#! python3
# bulletPointAdder.py - Adds Wikipedia bullet points to the start
# of each line of text on the clipboard.
import pyperclip
text = pyperclip.paste()
# TODO: Separate lines and add stars.
# Separate lines and add stars.
lines = text.split('\n')
for i in range(len(lines)): # loop through all indexes in the "lines" list
lines[i] = '* ' + lines[i] # add star to each string in "lines" list
text = '\n'.join(lines)
pyperclip.copy(text)
"""
When this program is run,
it replaces the text on the clipboard with text
that has stars at the start of each line. Now the program is complete,
and you can try running it with text copied to the clipboard.
"""
| true |
21ab5e60c07ffe71e607e253e8015846b507e930 | andresbebe/Python | /Unidad 1/ejercicio2unidad1.py | 944 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#Intercambio de variables:
#Se declara una variable auxiliar,
#se guarda la edad1 temporal, se pisa la edad 1
#con la edad 2 y se pisa la edad2 con el la variable auxiliar.
nombre1 = raw_input ("Ingrese el nombre de la primera persona: ")
nombre2 = raw_input ("Ingrese el nombre de la segunda persona: ")
edad1 = raw_input ("Ingrese la edad de la primera persona: ")
edad2 = raw_input ("Ingrese la edad de la segunda persona: ")
print ("El nombre de la primera persona es: " + " " + nombre1 + "" + " y su edad es " + edad1 + " años")
print ("El nombre de la segunda persona es: " + " " + nombre2 + "" + " y su edad es " + edad2 + " años")
aux = edad1
edad1 = edad2
edad2 = aux
print ("El nombre de la primera persona es: " + " " + nombre1 + "" + " y su edad es " + edad1 + " años")
print ("El nombre de la segunda persona es: " + " " + nombre2 + "" + " y su edad es " + edad2 + " años") | false |
585ec1c6241cc27d1918ca53e9a67b096fa7611a | dougscohen/DS-Unit-3-Sprint-1-Software-Engineering | /module2-oop-code-style-and-reviews/Assignment/dc_lambdata/mod2.py | 627 | 4.15625 | 4 | # dc_lambdata\mod2.py
import pandas as pd
def split_date(df):
"""
Creates 3 new columns with year, month, and day
Params: dataframe with column called "date" which has the date in the
format "MM/DD/YYYY"
"""
df = df.copy()
df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day
return df
if __name__ == "__main__":
df3 = pd.DataFrame({"date": ["01/02/2018", "03/17/2004", "03/31/1990", "10/24/1960"]})
full_df3 = split_date(df3)
print(full_df3.head())
| true |
300add2b3c34871e160c0be3bcef6269d20355c9 | alessandrome/udacity-nanodegree-data-structures-n-algorithms-basic-algorithms | /src/p1_root.py | 1,280 | 4.125 | 4 | def isqrt(n):
# Handle negative numbers
if n < 0:
return None
# Handle base case
if n < 2:
return n
shift = 2
n_shifted = n >> shift
# We check for n_shifted being n, since some implementations perform shift operations modulo the word size.
while n_shifted != 0 and n_shifted != n:
shift = shift + 2
n_shifted = n >> shift
shift = shift - 2
# Find digits of result.
result = 0
while shift >= 0:
result = result << 1
candidate_result = result + 1
if candidate_result * candidate_result <= (n >> shift):
result = candidate_result
shift = shift - 2
return result
print("Pass" if (3 == isqrt(9)) else "Fail")
print("Pass" if (0 == isqrt(0)) else "Fail")
print("Pass" if (4 == isqrt(16)) else "Fail")
print("Pass" if (1 == isqrt(1)) else "Fail")
print("Pass" if (5 == isqrt(27)) else "Fail")
print("Pass" if (isqrt(-25) is None) else "Fail") # negative number are invalid
print("Pass" if (10000 == isqrt(100000000)) else "Fail") # negative number are invalid
print("Pass" if (10000 == isqrt(100000001)) else "Fail") # negative number are invalid
print("Pass" if (100000000 == (isqrt(10000000000000000))) else "Fail") # negative number are invalid
| true |
0dff503662d5a554c980584107d004951cf80bcc | amari-at4/Password_Hacker | /Topics/Custom generators/Fibonacci sequence/main.py | 351 | 4.15625 | 4 | def fibonacci(n):
i = 1
first_value = 0
second_value = 1
while i <= n:
if i == 1:
yield 0
elif i == 2:
yield 1
else:
new_value = first_value + second_value
first_value = second_value
second_value = new_value
yield new_value
i += 1
| false |
dcc4b61e732c961507d6d6a573e55f4c087b87ce | ProjectBasedLearning/submissions | /tusharnankani/week1/1. Hangman/hangman.py | 2,761 | 4.1875 | 4 | # For randomly choosing a word;
import random
# For error handling;
import sys
word_list = ['apple', 'banana', 'cat', 'dog', 'elephant', 'frog']
# Welcome message
print('~~~~~~~~~~~~~~~~~~~')
print("Let's play hangman!")
print('~~~~~~~~~~~~~~~~~~~')
def get_word():
# Better Implementation
return random.choice(word_list).upper()
def play(word):
word_completion = "_" * len(word)
guessed = False
guessed_letters = []
guessed_words = []
tries = 6
print(word_completion)
print("\n")
while not guessed and tries > 0:
guess = input("Please guess a letter or word: ").upper()
# if the user's guess is a letter and is from alphabets;
if len(guess) == 1 and guess.isalpha():
if guess in guessed_letters:
print("You already guessed the letter", guess +".")
elif guess not in word:
print(guess, "is not in the word.")
tries -= 1
guessed_letters.append(guess)
else:
print("Good job,", guess, "is in the word!")
guessed_letters.append(guess)
word_as_list = list(word_completion)
indices = [i for i, letter in enumerate(word) if letter == guess]
for index in indices:
word_as_list[index] = guess
word_completion = "".join(word_as_list)
if "_" not in word_completion:
guessed = True
# if the user's guess is a word and is equal to random's word's length;
elif len(guess) == len(word) and guess.isalpha():
if guess in guessed_words:
print("You already guessed the word", guess)
elif guess != word:
print(guess, "is not the word.")
tries -= 1
guessed_words.append(guess)
else:
guessed = True
word_completion = word
else:
print("Not a valid guess.")
print('---------------')
print(word_completion)
print('---------------')
print("\n")
print("You have", tries, "guesses left.")
print("\n")
if guessed:
print("CONGRATULATIONS! You guessed the word! You win!")
else:
print("Sorry, you ran out of tries. The word was", word + ". Maybe next time!")
def main():
# getting a random word from `get_word` function;
word = get_word()
# Starting the game;
play(word)
while input("\nPlay Again? (Y/N): ").upper() == "Y":
# loop for infinite game play;
word = get_word()
play(word)
print("THE END!")
if __name__ == "__main__":
main() | true |
a78f0fb1169c58d7357b207538502b6f9f0ac586 | Carlos-DOliveira/cursoemvideo-python3 | /pacote-download/d037 - conersão de base.py | 472 | 4.21875 | 4 | ''' 037 Escreva um programa que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão
1 - binário
2 - octal
3 - hexadecimal'''
num = int(input('Digite um número: '))
conversao = int(input('''Escolha a base que quer converter:
[ 1 ] binário,
[ 2 ] octal,
[ 3 ] hexadecimal'''))
print('Qual a opção? ')
if conversao == 1:
print(bin(num)[2:])
elif conversao ==2:
print(oct(num)[2:])
else:
print(hex(num)[2:])
| false |
078ffc4ce4a71e1150147ebe8b3d25de8a82452a | Carlos-DOliveira/cursoemvideo-python3 | /pacote-download/d104 - validando entrada de dados em Python.py | 626 | 4.28125 | 4 | ''' 104 Crie um programa que tenha a função leiaInt(), que vai funcionar de froma semelhante à função input() do Python, só que fazendo a validação para aceitar
apenas um valor numérico.
ex: n=leiaInt('Digite um n')'''
def leiaInt(msg):
num = input(msg)
if num.isnumeric():
return num
else:
while True:
print('\033[31m ERRO! Digite um número inteiro válido. \033[m')
num = input(msg)
if num.isnumeric():
return num
break
n = leiaInt('Digite um número inteiro: ')
print(f'Você acabou de digitar o número: {n}') | false |
c9a1861c8c490c71c47913ce10243e37c3a52f3a | Pramodtony/python_learning | /program9.py | 214 | 4.1875 | 4 | # program to determine the factors of a number
number=int(input('enter your number'))
list=[]
for i in range(1,number+1):
if number%i==0:
list.append(i)
print("factors of {} is {}".format(number,list))
| true |
df1712969ef588037bd51b1928b73a9ce4e8e1c5 | Pramodtony/python_learning | /program20.py | 490 | 4.3125 | 4 | # program to find second largest element of an array
lst=[]
n=int(input("enter the no of elements you want to insert"))
for i in range(1, n+1):
a=input("enter the value no {} :".format(i))
lst.append(a)
large=lst[0]
for i in lst:
if i>=large:
large=i
print("largest element in the given array is",large)
s_large=lst[0]
for i in lst:
if i>=s_large and i<large:
s_large=i
print("second largest element in the given array is",s_large) | true |
c942a91346dbd07058eef2e7a0e1eeef76208400 | D-Katt/Coding-examples | /Advent_of_Code_2021/day_3_puzzle_1.py | 2,506 | 4.34375 | 4 | """Advent of code: https://adventofcode.com/2021/day/3
Day 3 Puzzle 1
The submarine diagnostic report (input file) consists of a list of binary numbers.
The first parameter to check is the power consumption.
You need to use the binary numbers in the diagnostic report to generate two new binary numbers
(called the gamma rate and the epsilon rate). The power consumption can then be found
by multiplying the gamma rate by the epsilon rate.
Each bit in the gamma rate can be determined by finding the most common bit
in the corresponding position of all numbers in the diagnostic report.
For example, given the following diagnostic report:
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
Considering only the first bit of each number, there are five 0 bits and seven 1 bits.
Since the most common bit is 1, the first bit of the gamma rate is 1.
Following this procedure, the gamma rate is the binary number 10110, or 22 in decimal.
The epsilon rate is calculated in a similar way; rather than use the most common bit,
the least common bit from each position is used. So, the epsilon rate is 01001, or 9 in decimal.
Multiplying the gamma rate (22) by the epsilon rate (9) produces the power consumption, 198.
Use the binary numbers in your diagnostic report to calculate the gamma rate and epsilon rate,
then multiply them together. What is the power consumption of the submarine?
(Be sure to represent your answer in decimal, not binary.)
"""
file_path = 'day_3_data.txt'
# We need to know how many characters each line in the input file contains.
with open(file_path, 'r') as file_handler:
line = file_handler.readline()
n_chars = len(line) - 1 # Without end of line symbol
# Index positions in the list correspond to index positions
# of characters in the binary numbers.
counter = [[0, 0] for _ in range(n_chars)]
with open(file_path, 'r') as file_handler:
for line in file_handler:
for idx, char in enumerate(line.strip()):
counter[idx][int(char)] += 1
# Reconstruct gamma and epsilon comparing number of zeroes and ones
# at every index position.
gamma = ''
epsilon = ''
for zeros, ones in counter:
if zeros > ones:
gamma = gamma + '0'
epsilon = epsilon + '1'
else:
gamma = gamma + '1'
epsilon = epsilon + '0'
# Convert to integers and multiply.
gamma = int(gamma, 2)
epsilon = int(epsilon, 2)
mtpl = gamma * epsilon
print(mtpl)
| true |
2dbfc0f473a62f4a2dcb2ed65872980fba91fb36 | Mmckelve45/Python | /generators.py | 1,190 | 4.25 | 4 |
def create_cubes(n):
result = []
for x in range(n):
result.append(x**3)
return result
create_cubes(10)
#here we only needed one value at a time. Does not need to create a giant list of memory
for x in create_cubes(10):
print(x)
#create_cubes is way more memory efficient this way
def create_cubes(n):
for x in range(n):
yield x**3
for x in create_cubes(10):
print(x)
#yielding it is much more memory efficient
list(create_cubes(10))
#you can hold things in memory (store in list) or yield it for later use
def gen_fibon(n):
a = 1
b = 1
#output = []
for i in range(n):
yield a
#output.append(a)
a,b = b,a+b
#return output
for number in gen_fibon(10):
print(number)
def simple_gen():
for x in range(3):
yield x
for num in simple_gen():
print(number)
g = simple_gen()
print(next(g))
#remembers the previous number
print(next(g))
#remembers the previous number
print(next(g))
# automatically iterate through object
s = "Hello"
for letter in s:
print(letter)
next(s) #error. The string object needs to be converted into an iterable object
s_iter = iter(s)
next(s_iter) | true |
3b091cda0b246a4e1f355e25b88810719f44ef1c | Mmckelve45/Python | /mortgage_calculator.py | 1,681 | 4.34375 | 4 | #Mortgage Calculator - Calculate the monthly payments of a fixed term mortgage over given Nth terms at a given interest rate.
#Also figure out how long it will take the user to pay back the loan.
#For added complexity, add an option for users to select the compounding interval (Monthly, Weekly, Daily, Continually).
#monthly_pmt = int(input("What is your monthly Payment? "))
#Don't need this function but can use it inside of the mortgage calc instead of using parameters or use for reference instead.
def questions():
borrowed = int(input("How much money did you borrow? "))
int_rate = int(input("What is the annual interest rate? "))
total_months = int(input("How many months will you be repaying this mortgage? "))
return borrowed, int_rate, total_months
def mortgage_calc(borrowed, int_rate, total_months):
months_remaining = total_months
interest = int_rate/12
total_remaining = borrowed
monthly_principal_pmt = borrowed / total_months
monthly_interest_pmt = interest * total_remaining
total_monthly_pmt = monthly_principal_pmt + monthly_interest_pmt
for i in range(1,total_months+1):
print(f"{i}. Your total monthly principal payment is ${round(monthly_principal_pmt,2)}")
print(f"{i}. Your total monthly interest payment is ${round(monthly_interest_pmt,2)}")
print(f"{i}. Your total payment for the month is ${round(total_monthly_pmt,2)}")
total_remaining -= monthly_principal_pmt
monthly_interest_pmt = interest * total_remaining
total_monthly_pmt = monthly_principal_pmt + monthly_interest_pmt
print(f"{i}. ${round(total_remaining,2)} remaining principal to pay off!")
print("\n \n")
| true |
50c18133185eb8c5cd0274ef2176749011499525 | MarcianoPazinatto/TrabalhosdePython | /aula21/aula21exer1.py | 1,369 | 4.3125 | 4 | # Aula 21 - 06-12-2019
# Como Tratar e Trabalhar Erros!!!
# 1 - Crie um arquivo que leia 2 números inteiros e imprima a soma,
# multiplicação, divisão e subtração com uma f-string.
# 2 - Crie um while que pergunte se deseja continuar. Se digitar 's' o
# programa termina.
#################### até aqui tudo bem! ##########################
# 3 - faça um tratamento de exceção para que ao digitar o valor que
# não seja inteiro, ele avise o usuário para ele digitar denovo.
# 4 - Faça outro tratamento de exceção para evitar que divida um numero
# por zero.
controle='n'
while controle !='s':
try:
num1=int(input('Digite o primeiro numero: '))
num2=int(input('Digite o segundo número: '))
except ValueError:
print('Erro, você não digitou um número')
else:
print(f' {num1}+ {num2} = {num1+num2}')
print(f' {num1}- {num2} = {num1-num2}')
print(f' {num1}x {num2} = {num1*num2}')
try:
print(f' {num1}/ {num2} = {num1/num2}')
except:
print('erro impossível de dividir para 0')
controle=input(f's para sair ')
# while True:
# try:
# print('3213213')
# numero= int(input('digite um numero: '))
# print('22222')
# except ValueError:
# print('Erro')
# else:
# print('THE END')
# break
| false |
9e8f328e5a6322f8bcd92715c728de8011d3343b | cscitutorials/Data-Structures-and-Algorithms-in-Python | /Searching_an_array/Bitwise XOR/Number occurring odd number of times.py | 422 | 4.3125 | 4 | """
Find the Number Occurring Odd Number of Times
Given an array of positive integers. All numbers occur even number of times
except one number which occurs odd number of times. Find the number in O(n)
time & constant space.
"""
def odd_number(arr):
res = 0
n = len(arr)
for i in range(0, n):
res ^= arr[i]
return(res)
def main():
arr = [1, 2, 3, 2, 3, 1, 3]
print(odd_number(arr))
main()
| true |
212feaf88b8b79ac1ce8b1729ff7fd7133a4048e | cscitutorials/Data-Structures-and-Algorithms-in-Python | /Searching_an_array/Linear Search/Right to Left traversals/Leaders in an array.py | 609 | 4.34375 | 4 | """
Write a program to print all the LEADERS in the array.
An element is leader if it is greater than all the elements to its right
side. And the rightmost element is always a leader.
For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2.
Let the input array be arr[] and size of the array be size.
"""
def leaders_in_array(arr):
n= len(arr)-1
max_value = arr[n]
print(max_value)
for i in range(n, -1, -1):
if arr[i] > max_value:
max_value = arr[i]
print(max_value)
def main():
arr = [19, 17, 4, 3, 5, 2]
leaders_in_array(arr)
main()
| true |
c017a55244abf2b6d0ea3805df6d3a60dc3d74d2 | mayor-william/automatas-2-ejercicios-python | /triangulos.py | 946 | 4.28125 | 4 | # saber que triangulo es
#funcion para identificar triangulo
def identificar(l1,l2,l3):
if(l1 == l2 and l1 == l3):
print(" el triangulo es equilatero: ", l1, ",", l2, ",", l3 )
elif (l1==l2 or l1==l3 or l2==l3 ):
print(" el triangulo es isoceles: ", l1, ",", l2, ",", l3)
elif(l1!=l2 or l1!=l3 or l2!=l3):
print(" el triangulo es escaleno: ", l1, ",", l2, ",", l3)
def main():
ciclo = True
while ciclo == True:
lado1 = float(input("ingrese el primer lado"))
lado2 = float(input("ingrese el segundo lado"))
lado3 = float(input("ingrese el tercer lado"))
#invocar funcion
identificar(lado1,lado2,lado3)
resp = input("Desea hacer otro calculo: (s/n)?")
if (resp == "S" or resp == "s"):
ciclo = True
else:
ciclo = False
else:
print("FIN DEL PROGRAMA")
if __name__ == "__main__":
main() | false |
a49ce33f2aa527b6b2e0824c6e7631cdd83cc8b7 | gradyk2/MyFirstRepo | /personality_survey_GK.py | 1,199 | 4.125 | 4 | print("What's your favorite sport?")
sport = input()
if sport == "Hockey":
print("That's my favorite sport too!")
elif sport == "Tennis":
print("Tennis is my other favorite sport to play!")
elif sport == "lacrosse":
print("Woah I love lacrosse! You do too? Awesome!")
else:
print(sport + " sounds fun to play.")
print("What's your favorite food?")
food = input()
if food == "Chicken Joes":
print("Oh, the potato cones are my favorite!")
elif food == "Pizza":
print("Oh, I enjoy pizza too!")
else:
print(food + " tastes delicious too!")
print("What's your favorite subject?")
subject = input()
if subject == "Math" or subject == "Latin":
print("I love math and latin!")
else:
print(subject + " is a great class too.")
print("What's your favorite TV show?")
tvshow = input()
if tvshow == "The Flash":
print("That's my favoirte too!")
elif tvshow == "Gotham":
print("What's your favorite episode?")
episode = input()
if episode == ("Episode 7, Season three."):
print("Mine too!")
else:
print("Oh, Thats a good one!")
else:
print(tvshow + " is a great show too!")
| true |
171fd636e5990d2d3fdf65956cadcc4e9456b90b | SamOsman/Manipulating_student_records | /student_record.py | 2,459 | 4.3125 | 4 |
students = dict()
students = {"marcus": [71, 85], "tommy": [56, 75], "belle": [75, 81]}
counter = 0
repeat = True
ask = "return to main menu {press 1}, quit {press 2}"
while repeat:
userChoice = input("\nMain menu: \n 1.add student \n 2.delete student \n 3.find student \n 4.view all students "
"\n 5.update student grade \n 6.exit")
if userChoice == "1": # add student
newName = input("new students name:")
newMidterm = input("midterm mark:")
newFinal = input("Final mark:")
# add a new student to the dict
students[newName.lower()] = [newMidterm, newFinal]
reply = input(ask)
if reply == "1":
repeat = True
else:
repeat = False
elif userChoice == "2": # delete student
removeStudent = input("Enter name of student to remove:")
students.pop(removeStudent.lower())
print("student record has been deleted")
elif userChoice == "3": # find student
findStudent = input("Search for a student:")
if findStudent.lower() in students:
print("student record exists")
else:
print("Student record does NOT exist")
elif userChoice == "4": # view all students
for k, v in students.items():
print("Student: {0}".format(k))
print("mid-term:" + str(v[0]) + ", final: " + str(v[1]))
reply = input(ask)
if reply == "1":
repeat = True
else:
repeat = False
elif userChoice == "5": # update student record
student_name = input("Enter name of student to be updated:")
while True:
if student_name.lower() in students:
mid_term = input("new mid term mark {leave empty if no updates}: ")
final_term = input("new final term mark {leave empty if no updates}: ")
if not mid_term == "":
students[student_name][0] = mid_term
print("Midterm upgraded for " + student_name)
if not final_term == "":
students[student_name][1] = final_term
print("Final upgraded for " + student_name)
break
else:
student_name = input("student record does not exist, please enter another student name:")
continue
else:
print("goodbye")
repeat = False
| true |
768f73fcb6856f7cc4a532f06917c56b7cc013ed | Chaitanya90-dev/Training_Session_Codes | /2nd June 2021/Counting_Occurances_of_digits_from_given_No.py | 841 | 4.125 | 4 | Q)Find total occurrences of each digits (0-9) using function.
-----------------------------------------------------------------------------
#Language used - python
number=int(input("Enter any Number: "))
print("Digit\tFrequency")
def countOccurrances(number):
for i in range(0,10):
count=0;
temp=number;
while temp>0:
digit=temp%10
if digit==i:
count=count+1
temp=temp//10;
if count>0:
print(i,"\t",count)
countOccurrances(number)
----------------------------------------------------------------------------
#Output
Enter any Number: 12345664558859963321147889665422
Digit Frequency
1 3
2 4
3 3
4 4
5 5
6 5
7 1
8 4
9 3
| true |
2d7a19692a4ce27df1b95948197c57eae9ae24ad | hkhairinas/Python-learning | /Modul 2/input.py | 1,697 | 4.1875 | 4 | # input no 1
print("Tell me anything...")
anything = input()
print("Hmm...", anything, "... Really? \n")
# input test 2
anything = input("Tell me anything...")
print("Hmm...", anything, "...Really? \n")
# # input wrong
# anything = input("Enter a number: ")
# something = anything ** 2.0
# print(anything, "to the power of 2 is", something)
# input right
anything = float(input("Enter a number: "))
something = anything ** 2.0
print(anything, "to the power of 2 is", something, "\n")
# Hypotenuse
leg_a = float(input("Input first leg length: "))
leg_b = float(input("Input second leg length: "))
hypo = (leg_a**2 + leg_b**2) ** .5
print("Hypotenuse length is", hypo, "\n") # as same as print("Hypotenuse length is", (leg_a**2 + leg_b**2) ** .5)
# Hypotenuse Using str without commas
leg_a = float(input("Input first leg length: "))
leg_b = float(input("Input second leg length: "))
print("Hypotenuse length is " + str((leg_a**2 + leg_b**2) ** .5))
# string input
fnam = input("May I have your first name, please? ")
lnam = input("May I have your last name, please? ")
print("Thank you.")
print("\nYour name is " + fnam + " " + lnam + ".")
# Replication
print("+" + 10 * "-" + "+")
print(("|" + " " * 10 + "|\n") * 5, end="")
print("+" + 10 * "-" + "+")
# Final
a = 6.0
b = 3.0
# output the result of addition here
add = a+b
# output the result of subtraction here
sub = a-b
# output the result of multiplication here
mul = a*b
# output the result of division here
div = a/b
print("Result is : Add = ",add," Sub = ",sub," Multiply = "+str(mul)+" Div = "+str(div))
print("\nThat's all, folks!")
# TestLAB
x = float(input("Enter value for x: "))
y = 1/(x+1/(x+1/(x+1/x)))
print("y =", y) | true |
0727f02cbb983ddb4434044b8ecf9b7666c7d290 | swp0023/test1 | /game1/GuessMyPassword.py | 1,064 | 4.125 | 4 | # guess my passworld.py
import random
resp1="try again"
resp2="possible, but not exact"
resp3="uncollect. it is easy that my password"
resp4="good job"
MY_PASSWORD="my password" #변수가 아닌 상수에는 대문자
def is_correct(guess, password):
if guess == password:
guess_correct =True
else:
guess_correct=False
return guess_correct
#user_input = input("type text")
#print(user_input)
#############start
print("hi\n")
users_guess = input("type you guessed password")
#CHECKING PASSWORD
true_or_false = is_correct(users_guess, MY_PASSWORD)
#GAME RE START UTIL USER TYPE EXACT PASSWORD
while true_or_false == False:
computer_response = random.randint(1,3)
if computer_response ==1:
print(resp1)
elif computer_response==2:
print(resp2)
else:
print(resp3)
users_guess = input("\n what is next password?")
true_or_false = is_correct(users_guess, MY_PASSWORD)
print(resp4)
input("\n type enter and than game will be end")
| true |
b02cf04969b4b0fe3de1a479e42cf159cf605212 | nave1n0x/Python | /abstractclss.py | 768 | 4.15625 | 4 | #here in this progrma we are going to discus about yur abstract class is a class which used to make a class abstract nothing but if you want to initiate that particular class or methods in subclass is it a mandantory/compulsory so we have to use abstract clas to make it mandatory to use other wise it will gives an error
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
def perimieter(self):
pass
class Square(Shape):
def __init__(self, side):
self.__side = side
def area(self):
return self.__side * self.__side
def perimeter(self):
return 4 * self.__side
square = Square(5)
print(square.area())
print(square.perimeter())
| true |
33f0a5eae0c22a3bb9da150a2fbc602930106590 | naokiur/Python-tutorial | /t_4_more_control_flow_tool/t_4_6_defining_functions/__init__.py | 571 | 4.1875 | 4 | def feb(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b
print()
# Print None.
print(feb(2000))
def feb2(n):
"""Return a list containing the Fibonacci series up to n."""
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a + b
return result
print(feb2(200))
arg = 0
def add(n):
"""Add 1."""
return n + 1
print('Call Function \'add\' with arg:', add(arg))
print('Print arg. Arguments of function is call by value:', arg)
| true |
d491a8ceb59cc5a213d467af2dc29be564c6c5ba | naokiur/Python-tutorial | /t_4_more_control_flow_tool/t_4_3_rangefunction/__init__.py | 390 | 4.40625 | 4 | for i in range(5):
print(i)
print(list(range(5, 10)))
print(list(range(0, 10, 3)))
print(list(range(-10, -100, -30)))
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
print(i, a[i])
for i, v in enumerate(a):
print(i, v)
print(range(0, 10), '# Behavior of range() is like a list, but range() is not list. We call it \'iterable\'')
print(list(range(0, 10)))
| false |
f38bd1fd3e0d4daf15fbd57bf11350dde29a4e19 | REClements/PFI | /chapter 8 /ex84.py | 711 | 4.34375 | 4 | #Exercise 4: Download a copy of the file from www.py4e.com/code3/romeo.txt Write a program to open the
#file romeo.txt and read it line by line. For each line,
#split the line into a list of words using the split function.
#For each word, check to see if the word is already in a list. If the word is not in
#the list, add it to the list.
#When the program completes, sort and print the resulting words in alphabetical order.
try:
fhand = open(input('Enter a file '))
poetry = list()
w1 = list()
for line in fhand:
w2 = line.split()
w1.extend(w2)
for i in range(len(w1)):
if w1 [i] in poetry: continue
poetry.append(w1[i])
poetry.sort()
print(poetry)
except:
print('Please enter a valid file') | true |
adaf48003f86ce8a880bf2177864dc6472329976 | REClements/PFI | /chapter 8 /ex86.py | 709 | 4.28125 | 4 | #Exercise 6: Rewrite the program that prompts the user for a
#list of numbers and prints out the maximum and minimum of the numbers at
#the end when the user enters “done”. Write the program to store the numbers
#the user enters in a list and use the max() and min() functions to
#compute the maximum and minimum numbers after the loop completes.
numlist = list()
while True:
try:
inp = input('Enter a number or done to exit. ')
numinp = float(inp)
#print('debug',numinp,numlist)
numlist.append(numinp)
except:
if inp == 'done':
break
else:
print('Error, please enter numeric input.')
continue
high = max(numlist)
low = min(numlist)
print('maximum: ',high,'\nminimum: ',low)
| true |
b64e792c05f708ca9b4df943fff809302c599aaa | alangan17/LeetCode-Practice | /python/find-numbers-with-even-number-of-digits.py | 949 | 4.28125 | 4 | '''
Given an array nums of integers, return how many of them contain an even number of digits.
Example 1:
Input: nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.
Example 2:
Input: nums = [555,901,482,1771]
Output: 1
Explanation:
Only 1771 contains an even number of digits.
Constraints:
1 <= nums.length <= 500
1 <= nums[i] <= 10^5
'''
class Solution:
def findNumbers(self, nums: List[int]) -> int:
evenCnt = 0
for idx, val in enumerate(nums):
# print(f"val = {val} | digit = {len(str(val))}")
if (len(str(val)) % 2) == 0:
evenCnt = evenCnt + 1
return evenCnt | true |
44d9302c0450dd3b587af8a25bce40afc97d559c | rounaksalim95/Code-Ignite-High-School-Program | /Exercises/number_guess.py | 1,878 | 4.5 | 4 | # Think of a number from 1 to 100 and I'll guess your number
# Usage : python number_guess.py
# Flag used to keep track of whether or not we've guessed the user's number (used to iterate using the while loop)
number_guessed = False
lower_bound = 1 # Lower bound for number that can be guessed
upper_bound = 101 # Upper bound for the number that can be guessed (101 so that we accomodate for 100 as a user guessed number; using our current logic if the user thinks of the number 100 then we'll be stuck on 99 as a guess)
guess = 50 # Initial guess
print("Think of a number between 1 and 100 and I'll guess your number!")
# Keep looping until we've guessed the number
while(not number_guessed):
user_answer = raw_input("Is your number " + str(guess) + "? (y/n)")
# If the user thought of this number then we're done, so set the flag accordingly
if (user_answer == "y"):
number_guessed = True
# If we didn't guess the number correctly then ask the user whether the number is lesser than or greater than our guess
else:
lesser_or_greater = raw_input("Is your number lesser than or greater than " + str(guess) + "? (l/g)")
# If the number is lesser than our guess then set the upper bound to our guess since we know it's not larger than that number
# and set the guess as the number between the new upper and lower bound
if (lesser_or_greater == "l"):
upper_bound = guess
guess = (lower_bound + upper_bound) / 2
else:
# Same thing as above except this time we update the lower bound since the number is greater than our guess
lower_bound = guess
guess = (lower_bound + upper_bound) / 2
# If we're our of the loop then that means that we've guessed the user's number correctly!
print("I've guessed your number! It's " + str(guess)) | true |
2e6202c8bef9da120b8e07f0e5b203d8378079e0 | Tanya-Lev/PythonLabs | /Лаб1_Python/Task_11.py | 434 | 4.125 | 4 | def frange(start, end, step):
while start < end:
yield round(start, 3)#типа ретурн(вып то, что после нее)
start += step
for i in frange(1, 6, 0.1):
print(i)
#Напишите генератор frange как аналог range() с дробным шагом.
#Пример вызова:
#for x in frange(1, 5, 0.1):
#print(x)
# выводит 1 1.1 1.2 1.3 1.4 … 4.9 | false |
975d182e3615487025ddedd899ffd2e855cb53ae | Tanya-Lev/PythonLabs | /Лаб1_Python/Task_6.py | 555 | 4.34375 | 4 | #Напишите программу, позволяющую ввести с клавиатуры текст
#предложения и вывести на консоль все символы, которые входят в этот
#текст ровно по одному разу.
text = input("Введите текст: ")
for i in text:
if text.count(i) == 1:
print(i)
# chars = {}
# for char in text:
# chars[char] = chars.get(char, 0) + 1
# for key, value in chars.items():
# if value == 1:
# print(key)
| false |
66cc2006cf163f35329c96f8072c36fe2979a851 | mundleanupam/PythonSamples | /Samples/RockPaperScissor.py | 1,924 | 4.53125 | 5 | import random
# Algorithm
# Player 1 - Manually accept input
# Player 2 - Computer to get random integer between 1and 3
# Rock vs paper-> paper wins
# Rock vs scissor-> Rock wins
# paper vs scissor-> scissor wins.
# Count the number of wins and whoever reaches first 3 wins is the winner
player_win_count = 0
comp_win_count = 0
print """Game of Rock/Paper/Scissor Rules -
Rock vs paper-> paper wins
Rock vs scissor-> Rock wins
paper vs scissor-> scissor wins."""
while player_win_count < 3 and comp_win_count < 3:
choice_dict = {1: "ROCK", 2: "PAPER", 3: "Scissor"}
print ""
print "Select 1.Rock 2.Paper 3.Scissor"
choice = int(input("User Turn: "))
while choice > 3 or choice < 1:
choice = int(input("Enter valid input: "))
if choice in choice_dict:
print("User choice is: " + choice_dict.get(choice))
else:
print("Choose 1.Rock 2.Paper 3.Scissor")
comp_choice = random.randint(1, 3)
if comp_choice in choice_dict:
print("Computer choice is: " + choice_dict.get(comp_choice))
if (choice == 2 and comp_choice == 1) or (choice == 1 and comp_choice == 2):
print(choice_dict.get(2) + " Wins!")
if choice == 2:
player_win_count += 1
else:
comp_win_count += 1
elif (choice == 1 and comp_choice == 3) or (choice == 3 and comp_choice == 1):
print(choice_dict.get(1) + " Wins!")
if choice == 1:
player_win_count += 1
else:
comp_win_count += 1
elif (choice == 2 and comp_choice == 3) or (choice == 3 and comp_choice == 2):
print(choice_dict.get(3) + " Wins!")
if choice == 3:
player_win_count += 1
else:
comp_win_count += 1
else:
print("It is a Tie")
if player_win_count > comp_win_count:
print ("USER WINS THE ROUND")
else:
print ("COMPUTER WINS THE ROUND")
| true |
220b04f82d245bf15274f88d8aea5b2ae77ee94c | PriscylaSantos/estudosPython | /TutorialPoint/04 - Loops/8 - IteratorAndGenerator.py | 761 | 4.34375 | 4 | #!usr/bin/python3
import sys
list=[6,21,33,64]
it = iter(list) # this builds an iterator object
print(next(it)) #prints next available element in iterator
print()
#Iterator object can be traversed using regular for statement
for x in it:
print (x, end=" ")
#or using next() function
print()
while True:
try:
print (next(it))
except StopIteration:
sys.exit() #you have to import sys module for this
print()
def fibonacci(n): #generator function
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
# yield a
a, b = b, a + b
counter += 1
f = fibonacci(5) #f is iterator object
while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit() | true |
62dfaa990563bf07f2167eedf2343c2f7773fe32 | PriscylaSantos/estudosPython | /TutorialPoint/01 - Variable Types/7 - PythonTuples.py | 646 | 4.34375 | 4 | #!/usr/bin/python3
tuple = ( 'Anne', -7.86 , 2.23, 'Jorge', 70.2 )
tupleTwo = (23, 'Lures', 90)
print (tuple) # Prints complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tupleTwo * 2) # Prints tuple two times
print (tuple + tupleTwo) # Prints concatenated tuple
print()
tuple = ( 'Anne', -7.86 , 2.23, 'Priscyla', 70.2 )
list = [ 'Anne', -7.86 , 2.23, 'Priscyla', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list | true |
f369e58a6ff8871185b96062b12ddd3d941b86e5 | PriscylaSantos/estudosPython | /TutorialPoint/06 - Strings/02 - center().py | 402 | 4.15625 | 4 | #!/usr/bin/python3
#The method center() returns centered in a string of length width. Padding is done using the specified fillchar. Default filler is a space.
#str.center(width[, fillchar])
str = "this is string example....wow!!!"
print ("str.center(40, 'a') : ", str.center(40, 'b'))
str2 = "priscyla"
str2 = str2.capitalize()
print(str2)
y = len(str2)
print(y)
a = str2.center(y + 10, 'K')
print(a) | true |
09d7561d937bfa1529a4d1fe31b46dd6b313c166 | PriscylaSantos/estudosPython | /Livro/ControleDeFluxo/IfElseElif.py | 1,279 | 4.3125 | 4 | valor = 5
if 5 > valor:
print('5 é maior que variável valor')
elif 5 < valor:
print('5 é menor que variável valor')
else:
print('5 é igual a variável valor')
numero = 550
if numero < 0:
print('A variável numero é negativa')
elif numero >= 0 and numero <= 99:
print('A variavel numero está entre 0 e 99')
elif numero >= 100 and numero <= 199:
print('A variavel numero está entre 100 e 199')
elif numero >= 200 and numero <= 299:
print('A variavel numero está entre 200 e 299')
elif numero >= 300 and numero <= 399:
print('A variavel numero está entre 300 e 399')
elif numero >= 400 and numero <= 499:
print('A variavel numero está entre 400 e 499')
elif numero >= 500 and numero <= 599:
print('A variavel numero está entre 500 e 599')
elif numero >= 600 and numero <= 699:
print('A variavel numero está entre 600 e 699')
elif numero >= 700 and numero <= 799:
print('A variavel numero está entre 700 e 799')
elif numero >= 800 and numero <= 899:
print('A variavel numero está entre 800 e 899')
elif numero >= 900 and numero <= 999:
print('A variavel numero está entre 900 e 999')
elif numero >= 1000:
print('A variavel numero é igual a 1000')
else:
print('A variavel numero é maior que 1000')
| false |
086aafbb2fa790d59245bd8e9324d1e37530451f | PriscylaSantos/estudosPython | /Livro/ControleDeFluxo/OperComparacao.py | 901 | 4.34375 | 4 | # Comparando o inteiro 42 com a string 42
print("42 == '42'")
print(42 == '42')
print()
# Comparando inteiros
print('42 == 49')
print(42 == 49)
print()
print('2 != 3')
print(2 != 3)
print()
print('2 != 2')
print(2 != 2)
print()
# Comparando flutuantes com inteiro
print('5 != 5.0')
print(5 != 5.0)
print()
print('4.0 == 4')
print(4.0 == 4)
print()
print('3.5 != 3')
print(3.5 != 3)
print()
# Comparando string
print("'olá' == 'olá'")
print('olá' == 'olá')
print()
print("'olá' == 'Olá'")
print('olá' == 'Olá')
print()
print("'gato' != 'cachorro'")
print('gato' != 'cachorro')
print()
#
print('2 < 2')
print(2 < 2)
print()
print('32 > 23')
print(32 > 23)
print()
# Comparanto uma variavel com um número
numero = 2
valor = 87
print('variaveis: numero = 2 e valor = 87')
print()
print('numero >= 2')
print(numero >= 2)
print()
print('100 <= valor')
print(100 <= valor)
print()
| false |
24eb102ff9b1d54f72f3fde4a1e4d68e9ebf139d | RithickDharmaRaj-darkCoder/TestCryption | /txtcryption.py | 474 | 4.21875 | 4 | print(" *** Text Encryption & Decryption ***")
from decryption import *
# Getting optional answer from user...
def yes_no():
yes_no_ans = input("Do you want to Decrypt the Encrypted message [Y/N] : ").upper()
if yes_no_ans == "Y":
decrypt(encrypted)
elif yes_no_ans == "N":
print()
else:
print("WARNING! *Invalid Answer*")
yes_no()
yes_no()
#Personal Greetings...
print("\nThank You!\n -darkCoder \U0001F43E") | true |
d2aa26f041914dedc73212c5ae4affa19934de45 | michal0janczyk/udacity_data_structures_and_algorithms_nanodegree | /Project_1/Task0.py | 1,053 | 4.21875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open("texts.csv", "r") as f:
first_line_texts = f.readline()
print(
"First record of texts",
first_line_texts.split(",", 2)[0],
"texts",
first_line_texts.split(",", 2)[1],
"at time",
first_line_texts.split(",", 2)[2],
)
with open("calls.csv", "r") as c:
last_line_calls = c.readlines()[-1]
print(
"Last record of calls",
last_line_calls.split(",", 3)[0],
"calls",
last_line_calls.split(",", 3)[1],
"at time",
last_line_calls.split(",", 3)[2],
", lasting",
last_line_calls.split(",", 3)[3],
"seconds",
)
"""
TASK 0:
What is the first record of texts and what is the last record of calls?
Print messages:
"First record of texts, <incoming number> texts <answering number> at time <time>"
"Last record of calls, <incoming number> calls <answering number> at time <time>, lasting <during> seconds"
"""
| true |
06e2cfa78088e1555afdeba4527e5d54df1752ae | WorasitSangjan/afs505_u1 | /assignment2/ex3_1.py | 959 | 4.5 | 4 | # The purpose of this section
print("I will now count my chickens:")
# Calculate the number of Hens
print("Hens", 25 + 30 / 6)
# Calculate the numbers of roosters
print("Roosters", 100 - 25 * 3 % 4)
# The purpose of this section
print("Now I will count the eggs:")
# Calculate the number of eggs
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
# The math question
print("Is it true that 3 + 2 < 5 - 7?")
# Calculate and compare the condition
print(3 + 2 < 5 - 7)
# The math questions and calculation
print("What is 3 + 2?", 3 + 2)
# The math questions and calculation
print("What is 5 - 7?", 5 - 7)
# The conclusion from the calculation
print("Oh, that's why it's False.")
# Other math question section
print("How about some more.")
# The math questions and calculation
print("Is it greater?", 5 > -2)
# The math questions and calculation
print("Is it greater or equal?", 5 >= -2)
# The math questions and calculation
print("Is it less or equal?", 5 <= -2)
| true |
7ae9341a1a196063aff188866ddfcd0fc89225eb | ThuraAung1601/Programming_Basic | /Day2/age.py | 343 | 4.125 | 4 | age = eval(input("Enter your age:"))
print(age)
if age >= 18:
print("Welcome to the party!!!")
elif age >= 16:
print("Do ur parents know ???")
response = input("Y for Yes/N for No:")
if response == "Y":
print("Welcome to the party !!!")
else:
print("Then go for discussion.")
else:
print("Not for kids") | true |
00ba88fdd44b6857755c10a27a5f9a09f81925d1 | wongcyrus/ite3101_introduction_to_programming | /lab/lab02/ch02_t15_string_formatting_with_percentage_2.py | 277 | 4.125 | 4 | name = input("What is your name? ")
quest = input("What is your quest? ")
color = input("What is your favorite color? ")
# Uncomment the below 2 line of code!
# print("Ah, so your name is ___, your quest is ___, "
# "and your favorite color is ___." ___ (name, quest, color))
| true |
c47c9a925886a4135d053869d246df076fc56dd3 | tommparekh/PythonExcercises | /p2.py | 243 | 4.25 | 4 | # http://www.practicepython.org/solution/2014/02/15/02-odd-or-even-solutions.html
num_str = input("enter any number")
num = int(num_str)
if num % 2 == 0:
print(num_str + " is an even number")
else:
print(num_str + " is an odd number") | false |
3295f241d2ca1444415b055d049b8ba6036a4fe0 | jdodinh/DCP | /completed/DCP_37.py | 1,696 | 4.59375 | 5 | """
The power set of a set is the set of all its subsets. Write a function that, given a set, generates its power set.
For example, given the set {1, 2, 3}, it should return {{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}.
You may also use a list or array to represent a set.
"""
#####################################################
def find_power_set(lst):
new_set = []
if len(lst) == 1:
new_set.append(lst) # If list length is 1, we return the list in a list
return new_set
for i in range(len(lst)): # for all elements in that list, we find powersets of
lst_cpy = lst.copy() # the list with the element removed, and then add it
el = lst[i] # to the powerset, along with each element combined with
lst_cpy.remove(el) # the element that has been removed.
pw_sub_st = find_power_set(lst_cpy)
for e in pw_sub_st:
exp = e + [el]
exp.sort()
e.sort()
if e not in new_set:
new_set.append(e)
if exp not in new_set:
new_set.append(exp)
return new_set
def main():
main_set = {1, 2, 3}
main_set = list(main_set)
print(main_set)
pwst = find_power_set(main_set) # recursive function call to find power set of given set
pwst.append([]) # add the empty set
pwst.sort(key=len) # sort based on subset length
print(pwst)
if __name__ == '__main__':
main()
| true |
290dcaae12fa0c17d4be6ead974be687c49bfe61 | StaceyCarter/calculator-1 | /arithmetic.py | 1,271 | 4.4375 | 4 | """Math functions for calculator."""
def add(num1, num2):
"""Return the sum of the two inputs."""
return num1 + num2
def subtract(num1, num2):
"""Return the second number subtracted from the first."""
return num1 - num2
def multiply(num1, num2):
"""Multiply the two inputs together."""
return num1 * num2
def divide(num1, num2):
"""Divide the first input by the second and return the result."""
return num1 / num2
def square(num1):
"""Return the square of the input. To use type square()"""
return num1 ** 2
def cube(num1):
"""Return the cube of the input. To use type cube()"""
return num1 ** 3
def power(num1, num2):
"""Raise num1 to the power of num2 and return the value. To use type pow()"""
return num1 ** num2
def mod(num1, num2):
"""Return the remainder of num1 / num2. To use type mod()"""
return num1 % num2
def add_mult(num1, num2, num3):
"""Adds the first 2 numbers, then multiplies the answer with the third.
Given the syntax x+ num1 num2 num3
"""
return multiply(add(num1, num2), num3)
def add_cubes(num1, num2):
"""Adds together the cubes of num1 and num2.
Given the syntax cubes+ num1 num2
"""
return add(cube(num1), cube(num2))
| true |
b3c2bf376cb01c4a786d05d3b248c4a469947aa9 | WinyNafula/Andela_Wk2Challenges | /Variable.py | 490 | 4.40625 | 4 |
year_of_birth =input("enter year of birth: ") #creating a variable that holds the year that is entered by a user
year = int(year_of_birth)
age = 2019 - year
if age < 18:
print("this person is a minor") #displays you as minor if the condition is true
elif age >= 18 and age <= 36:
print("the person is a youth")#displays you as youth if the condition is true
else:
print("the person is an elder")#displays you as an eleder if non of the above conditions are true
| true |
70d7604452201866969af1601c64249de97c7eed | yanzhen74/pycookbook | /ch01/draw_n_angles.py | 273 | 4.125 | 4 | import turtle
n_edge = int(input("Enter edge number:"))
angle = 180 - ((n_edge - 2) * 180) / n_edge
color = input("Enter color name:")
turtle.fillcolor(color)
turtle.begin_fill()
for i in range(n_edge):
turtle.forward(100)
turtle.right(angle)
turtle.end_fill()
| true |
9b9566d69f130018030e5138339112f68ba8abca | yerbolnaimanov/lessons | /lesson2_task_B.py | 1,147 | 4.46875 | 4 | #Напишите программу которая попросит ввести ваше имя, фамилию, возраст, пол и выведит
#приветствие на основе введенных данных с условием что обращение будет меняться в
#зависимости от возраста и пола. + очищает ввод от лишних пробелов и левых символов
name = input("Как Вас зовут? ")
surname = input("Ваша фамилия? ")
sex = input("Ваш пол? Введите М или Ж: ").lower()
age = int(input("Сколько Вам лет? "))
if age<25 and sex=="м":
print("Привет {0}, возможно вас заинтересует раздел об автомобилях".format(name+" "+surname))
elif age<25 and sex=="ж":
print("Привет {0}, позвольте вам рассказать о тенденциях в мире моды".format(name+" "+surname))
elif age>=25:
print("Здравствуйте {0}, представляем вам список горящих туров".format(name+" "+surname))
| false |
b3c7821382987b1fe9ac85db436c31600eab457d | ironmanscripts/py_scripts | /ironman_py_scripts37.py | 318 | 4.1875 | 4 | #!/bin/bash/python
# Author - IronMan
# September 8th 2017, Time 10:33pm, Friday
# While Loops;
i = 0
numbers = []
while i < 6 :
print "At the top i is %d" %i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d "%i
print "The numbers:"
for num in numbers:
print num
| false |
6d3289ccd5cb264b1285a02bb617eca605904741 | ironmanscripts/py_scripts | /ironman_py_scripts26.py | 771 | 4.15625 | 4 | #!/bin/bash/python
#function and files in python
from sys import argv
script , input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
current_file = open(input_file)
print "First let's print the whole file: \n"
print_all(current_file)
print "Now let's rewind , kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
#be careful about intendation errors
#you are repeating mistakes again and again
#please be awak while typing the code
| true |
b280f5e33f25472a12f894ccab3becadcee7a0e3 | zachseibers/PythonTheHardWay | /Ex16 Reading and Writing Files.py | 1,061 | 4.28125 | 4 | #Ex16 Reading and Writing Files
from sys import argv
script, filename = argv
print("We're going to erase %r." % filename)
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")
input("?")
print("Opening the file...")
target = open(filename, 'w') #opens the target file so that the program can use it, notice it is stored as a variable
# In the above line, w means open the file in write mode
print("Truncating the file. Goodbye!")
target.truncate() #Empties the contents of the file, not to be used carelessly
print("Now I'm going to ask you for three lines.")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to the new file.")
target.write(line1) #Writes variable or string to file, note that in this case target is the variable of the open file
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally, we close it")
target.close() #Closes the file, similar to close & save in a text editor | true |
809a4434fb5376bea57ba7313102a14b7d8f4341 | MeganM-3/hello_world | /Program-9.py | 2,947 | 4.28125 | 4 | def intro():
print('Requirement 1:\nThis is Program 9 - Megan Weir')
print('\n\nRequirement 2:\nThis program keeps track of Pokemon'
' characters, saves the data to a file, and displays the data from the file.\n\n')
# Pokemon class definition
class Pokemon:
# __init__ called AUTOMATICALLY when an object is created
def __init__(self, name, ability):
# Assign argument 'name' to instance variable 'self.__name'
self.__name = name
# Assign argument 'ability' to instance variable 'self.__ability'
self.__ability = ability
# Get INSTANCE VARIABLE self.__name
def get_name(self):
return self.__name
# Get INSTANCE variable self.__ability
def get_ability(self):
return self.__ability
def display_data(file_name):
print('\nProduce output')
pokemon_number = 1
for line in file_name:
file_name.read
print('\nName of Pokemon #{}: {}'.format(pokemon_number, file_name(line)))
print('\nAbility of Pokemon #{}: {}'.format(pokemon_number, file_name(line)))
pokemon_number += 1
# main() function
def main():
file_name = "my_pokemon.txt"
intro()
save_data(file_name)
display_data(file_name)
print('\n############### In main () ###############')
print("\nRequirement 3\n--calling 'save_data()' function--")
print("\nRequirement 4\n--calling 'display_data()' function--")
feedback()
# add_pokemon() function
def save_data(file_name):
print("\nIn add_pokemon()")
file_data = open(file_name, "w+")
# Create new list to hold pokemon characters
pokemon_list = []
# Counter used in loop
pokemon_number = 1
more_pokemon = input("\nDo you have a pokemon to enter? (y/n): ").lower()
while more_pokemon == 'y':
# Get the name of the pokemon from user
pokemon_name = input('\nEnter name for Pokemon #{}: '.format(pokemon_number))
# Get the ability of the pokemon from user
pokemon_ability = input('\nEnter ability for Pokemon #{}: '.format(pokemon_number))
# Create a new pokemon object with pokemon_name and pokemon_ability
new_pokemon = Pokemon(pokemon_name, pokemon_ability)
# Add new_pokemon to list
pokemon_list.append(new_pokemon)
file_data.write('pokemon_list')
# Increment counter
pokemon_number += 1
more_pokemon = input("\nAnother pokemon to enter? (y/n): ").lower()
return pokemon_list
def feedback():
print('\nRequirement 5\n XXXXXXX.')
# Determine if program is run as the main or a module
if __name__ == '__main__':
# This program is being run as the main program
main()
else:
pass
# Do nothing. This module has been imported by another
# module that wants to make use of the functions,
# classes, and/or other items it has defined.
| true |
76e46dd82319dd229f6ecbf4157d2df92f53aac3 | mani5a3/python | /break_continue.py | 314 | 4.1875 | 4 | # break statement example
str="test"
for i in str:
if i == 's':
break #it exits from the loop when i is equal to 's'
print(i)
# continue statement example it skips the current iteration when i is equal to 3
list=[1,2,3,4,5]
for i in list:
if i == 3:
continue
print(i)
| true |
8a2b276c6d554be02446d13d5c98d9fdda95cac1 | ikosenn/project-euler | /problem2.py | 426 | 4.15625 | 4 | #a program to calculate sum of even numbers
#in a fibonnaci sequence
def fibonacci(lower, upper, limit = 0, even_sum = 0):
'''A program to calculate fibonacci numbers
not beyond a certain limit'''
total = lower + upper
if total <= limit:
if total % 2 == 0:
even_sum += total
return fibonacci(upper,total,limit, even_sum)
return "The sum of all even fib numbers to is %d"%even_sum
print fibonacci(0,1,4000000) | true |
c7f11b295119020668d82c257062612d6b2ba92f | CatchTheDog/python_crash_course | /src/chapter_3/list_test_3.py | 294 | 4.25 | 4 | for value in range(1,5):
print(value)
numbers = list(range(1,6))
print(numbers)
numbers = list(range(1,12,3))
print(numbers)
squares = []
for value in range(1,11,1):
squares.append(value ** 2)
print(squares)
#列表解析
squares = [value**2 for value in range(1,11,1)]
print(squares)
| true |
f75e478aab1fd5706a35df3a8103e2015e8b6a85 | tawatchai-6898/tawatchai-6898 | /Lab03/Problem2V2.py | 361 | 4.1875 | 4 | fruits_list = ["Grapefruit", "Longan", "Orange", "Apple", "Cherry"]
print(f"The fruits are {fruits_list} \nAfter converting fruits to uppercase letters, fruits are")
fruits_list = [i.upper() for i in fruits_list]
[print(f"{val + 1}. {i}") for val, i in enumerate(fruits_list)]
fruits_list.sort()
print(f"After sorting fruits, fruits are \n{fruits_list}")
| false |
25abca4134a1f958b3620458e44fae3657bc1547 | ApurvaJogal/python_Assignments | /Assignment1/Assignment1_10.py | 203 | 4.125 | 4 |
#Write a program which accept name from user and display length of its name.
#Input : Marvellous Output : 10
# Author : Apurva Anil Jogal
# Date : 13th March 2019
x=input("Enter the string\n");
print(len(x));
| true |
693a4244ab4aac79f43a1ba3c4bf9d6919fc8a78 | ApurvaJogal/python_Assignments | /Assignment2/Assignment2_1.py | 1,302 | 4.25 | 4 |
#Create on module named as Arithmetic which contains 4 functions as Add() for addition, Sub() for subtraction, Mult() for multiplication and Div() for division.
#All functions accepts two parameters as number and perform the operation. Write on python program which call all the functions from Arithmetic module by accepting the parameters from user.
# Author : Apurva Anil Jogal
# Date : 14th March 2019
#we can import modules in 3 ways shown below (use any one)
#1
import Assignment2_1Module
#2
#import Assignment2_1Module as MyModule
#3
#from Assignment2_1Module import*
#accepting 2 inputs from user
num1=input("Enter first number\n");
num2=input("Enter second number\n");
# to access methods using #1
add= Assignment2_1Module.Add(num1,num2);
sub= Assignment2_1Module.Sub(num1,num2);
mult= Assignment2_1Module.Mult(num1,num2);
div= Assignment2_1Module.Div(num1,num2);
# to access methods using #2
#add= MyModule.Add(num1,num2);
#sub= MyModule.Sub(num1,num2);
#mult= MyModule.Mult(num1,num2);
#div= MyModule.Div(num1,num2);
# to access methods using #3
#add= Add(num1,num2);
#sub= Sub(num1,num2);
#mult=Mult(num1,num2);
#div= Div(num1,num2);
print("Addition is"),
print(add);
print("Subtraction is"),
print(sub);
print("Multiplication is "),
print(mult);
print("Division is "),
print(div);
| true |
c2eeec50e495a8052c58a43ffbcf7f923cf6080b | ApurvaJogal/python_Assignments | /Assignment8/Assignment8_4.py | 1,336 | 4.5 | 4 | #Design python application which creates three threads as small, capital, digits.
#All the threads accepts string as parameter.
#Small thread display number of small characters
#capital thread display number of capital characters
#and digits thread display number of digits.
#Display id and name of each thread.
# Author: Apurva Anil Jogal
# Date : 4th April 2019
from threading import *
def calcSmall (string1):
countSmall=0;
for i in string1:
if i.isupper():
countSmall += 1;
print("small =",countSmall);
def calcCapital (string2):
countCapital=0;
for i in string2:
if i.islower():
countCapital += 1;
print("capital =",countCapital);
def calcDigit (string3):
countDigit=0;
for i in string3:
if i.isdigit():
countDigit +=1;
print("digit =",countDigit);
def main():
stringInput= input("Enter the string\n");
small = Thread(target=calcSmall, args=(stringInput,));
capital = Thread(target=calcCapital, args=(stringInput,));
digits = Thread(target=calcDigit, args=(stringInput,));
# Will execute three threads in parallel
small.start();
capital.start();
digits.start();
# Joins threads back to the parent process, which is this program.
small.join();
capital.join();
digits.join();
print("Exit from main");
if __name__ == "__main__":
main();
| true |
bb91c482e21a07f11f3b3fd57456b18dda38b0e9 | ApurvaJogal/python_Assignments | /Assignment4/Assignment4_2.py | 336 | 4.125 | 4 | #Write a program which contains one lambda function which accepts two parameters and return its multiplication.
#Input : 4 3 Output : 12
#Input : 6 3 Output : 18
# Author : Apurva Anil Jogal
# Date : 20th March 2019
result = lambda a,b: a*b;
no1=input("Enter first number:");
no2=input("Enter second number:");
print( result(no1,no2));
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.