blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ee31c03c140160d5ec47e21eccfa56388aa93343 | Nduwal3/Python-Basics-II | /soln10.py | 926 | 4.34375 | 4 | # Write a function that takes camel-cased strings (i.e. ThisIsCamelCased), and converts them to snake case (i.e. this_is_camel_cased).
# Modify the function by adding an argument, separator, so it will also convert to the kebab case (i.e.this-is-camel-case) as well.
def snake_case_to_camel_case(camel_cased_string):
snake_cased = camel_cased_string
for char in camel_cased_string:
if(char.isupper()):
snake_cased = snake_cased.replace(char , '_' + char.lower())
print(snake_cased.strip('_'))
snake_case_to_camel_case('ThisIsSnakeCased')
def case_convert(input_string , separator):
result_string = input_string
for char in input_string:
if (char.isupper()):
result_string = result_string.replace(char , separator + char.lower())
result_string = result_string.strip(separator)
return result_string
print(case_convert("ThisIsKebabCased", '-'))
| true |
2dd2cffad194197ca43e70ed7ea2bd26a802ddf3 | Nduwal3/Python-Basics-II | /soln14.py | 719 | 4.40625 | 4 | # Write a function that reads a CSV file. It should return a list of dictionaries, using the first row as key names, and each subsequent row as values for those keys.
# For the data in the previous example it would
# return: [{'name': 'George', 'address': '4312 Abbey Road', 'age': 22}, {'name': 'John', 'address': '54 Love Ave', 'age': 21}]
import csv
def read_csv(filename):
try:
with open (filename, 'r') as csv_file:
data = csv.DictReader(csv_file, delimiter= ',')
my_list = []
for row in data:
my_list.append(row)
return (my_list)
except FileNotFoundError:
print("file not found")
print(read_csv('files/test.csv'))
| true |
e278cf23b50a47545b4032721cdf8bbe043438c7 | Nduwal3/Python-Basics-II | /soln12.py | 306 | 4.34375 | 4 | # Create a function, is_palindrome, to determine if a supplied word is
# the same if the letters are reversed.
def is_palindrome(input_string):
if( input_string == input_string[::-1]):
return True
else:
return False
print(is_palindrome("honey"))
print(is_palindrome("rotator"))
| true |
9e34b34cff0ce614ca57b94da8f64d4c8f1bf31e | yueyue21/University-of-Alberta | /INTRO TO FNDTNS OF CMPUT 2/lab2/lab2(3).py | 492 | 4.125 | 4 | import random
num=random.randint(1,20)
print(num)
count = 0
while (count<6):
a = int(input('Enter a guess (1-20):'))
if a >20 or a<1:
print ('That number is not between 1 and 20!')
elif a == num:
print('Correct! The number was',num)
break
elif a > num:
print('too high')
count = count+1
elif a < num:
print('too low')
count = count +1
print('You are out of guesses. The number was',num,'.')
| true |
1b673324f7118fa8cd04c7c9b8f99f7f61c214e7 | liuzhijielzj/Python-100-Days | /Day16-20/notes/d16-20/itertools.py | 212 | 4.1875 | 4 | """
迭代工具 - 排列 / 组合 / 笛卡尔积
"""
import itertools
for permutation in itertools.permutations('ABCD'):
print(permutation)
itertools.combinations('ABCDE', 3)
itertools.product('ABCD', '123') | false |
4223f00115a2bc41b84ccf139ff8cda8e4c2d19c | liuzhijielzj/Python-100-Days | /Day01-15/note/d2/variable.py | 1,604 | 4.28125 | 4 | #变量和类型
#整型, 处理任意大小的整数
print(0b100)
print(0o100)
print(0x100)
#浮点
print(1.2345e2)
#字符串
#原始字符串表示法、字节字符串表示法、Unicode字符串表示法
print('''
this is multi-line string
line 2
''')
#布尔
print(True)
print(False)
#复数
print(3 + 5j)
'''
变量命名:
1. 字母(广义的Unicode字符,不包括特殊字符)
、数字和下划线构成,数字不能开头.
2. 大小写敏感(大写的a和小写的A是两个不同的变量)。
3. 不要跟关键字(有特殊含义的单词,后面会讲到)和系统保留字(如函数、模块等的名字)冲突。
PEP 8要求:
用小写字母拼写,多个单词用下划线连接。
受保护的实例属性用单个下划线开头(后面会讲到)。
私有的实例属性用两个下划线开头(后面会讲到)。
'''
a = 321
b = 123
print(a // b) # 整除
print(a / b)
print(a % b)
print(a ** b) # 阶乘
'''
input: input from console
int: convert to int
用占位符格式化输出的字符串
'''
a = int(input('a = '))
b = int(input('b = '))
print('%d + %d = %d' % (a, b, a // b))
'''
type: check variable type
'''
print(type(100))
print(type(True))
'''
int():将一个数值或字符串转换成整数,可以指定进制。
float():将一个字符串转换成浮点数。
str():将指定的对象转换成字符串形式,可以指定编码。
chr():将整数转换成该编码对应的字符串(一个字符)。
ord():将一个字符转换成对应的编码(整数)。
'''
print(ord('t'))
print(chr(116))
| false |
d8365d5b438fd633fadee3c0e2a7b51c4014ca6f | margaridav27/feup-fpro | /Plays/Play02/hypotenuse.py | 230 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 13 23:30:55 2019
@author: Margarida Viera
"""
import math
def hypotenuse(n):
hypotenuse = math.sqrt(n**2 + n**2)
return round(hypotenuse, 2)
n = float(input())
print(hypotenuse(n)) | false |
b4222698736557531774de0479c227027e99c069 | spiridonovfed/homework-repository | /homework7/hw1.py | 1,841 | 4.3125 | 4 | """
Given a dictionary (tree), that can contains multiple nested structures.
Write a function, that takes element and finds the number of occurrences
of this element in the tree.
Tree can only contains basic structures like:
str, list, tuple, dict, set, int, bool
"""
from typing import Any
# Example tree:
example_tree = {
"first": ["RED", "BLUE"],
"second": {
"simple_key": ["simple", "list", "of", "RED", "valued"],
},
"third": {
"abc": "BLUE",
"jhl": "RED",
"complex_key": {
"key1": "value1",
"key2": "RED",
"key3": ["a", "lot", "of", "values", {"nested_key": "RED"}],
},
},
"fourth": "RED",
}
#######################################################
def find_occurrences(tree: dict, element: Any) -> int:
def iteritems(d, **kw):
"""Returns iterator of dictionary's items"""
return iter(d.items(**kw))
def recursion(dictionary, item):
"""Recursively searches for item and increments counter"""
nonlocal counter
if dictionary.get(item) is not None:
counter += 1
elif item in list(dictionary.values()):
counter += list(dictionary.values()).count(item)
for key, value in iteritems(dictionary):
if isinstance(value, dict):
recursion(value, item)
elif isinstance(value, list):
for list_item in value:
if hasattr(list_item, "items"):
recursion(list_item, item)
elif list_item == item:
counter += 1
counter = 0
# Applying recursive search to tree passed in
recursion(tree, element)
return counter
# if __name__ == "__main__":
# print(find_occurrences(example_tree, "RED")) # 6
| true |
50bc746e10b6ecf40fde69ffb7936620955b6dfb | spiridonovfed/homework-repository | /homework3/task01.py | 1,097 | 4.4375 | 4 | """In previous homework task 4, you wrote a cache function that remembers other function output value.
Modify it to be a parametrized decorator, so that the following code::
@cache(times=3)
def some_function():
pass
Would give out cached value up to `times` number only.
Example::
@cache(times=2)
def f():
return input('? ') # careful with input() in python2, use raw_input() instead
# >>> f()
# ? 1
# '1'
# >>> f() # will remember previous value
# '1'
# >>> f() # but use it up to two times only
# '1'
# >>> f()
# ? 2
# '2'
"""
def cache(times):
initial_times = times
def the_real_decorator(function):
def wrapper(*args):
nonlocal times
if args in memory and times:
times -= 1
return memory[args]
result = memory[args] = function(*args)
times = initial_times
return result
memory = {}
return wrapper
return the_real_decorator
@cache(times=2)
def f():
return input("? ")
| true |
9f9af6b0fd90265aab28477a233ec297c3952033 | blackplusy/0330 | /例子-0414-02.字符串操作2.py | 827 | 4.3125 | 4 | #coding=utf-8
#find和index
a='c'
str1='aabbcc'
print(str1.find(a))
a='d'
print(str1.find(a))
a='b'
print(str1.index(a))
a='d'
#print(str1.index(a))
#isalpha()和isdigit()
a='simida'
print(a.isalpha())
a='321simida'
print(a.isalpha())
a='123'
print(a.isdigit())
a='123a'
print(a.isdigit())
#upper()和lower()
name='Apple'
print(name[2].upper())
print(name.lower())
#startswith和endswith
a='aabbcc'
print(a.startswith('a'))
print(a.endswith('d'))
#count、replace、split
name='heygorGaGa'
print(name.count('a'))
print(name.replace('g','simida'))
name='1,2,3,4'
b=name.split(',')
print(b)
#引号
print('today')
print("yes")
print('''OK''')
print("i'm your papa!")
'''
这是爸爸的代码
'''
print('''
heygor memda
heygor handsome
heygor cool
''')
| false |
48827e9313f27e6a34ec3a52251e9be52e7a4902 | alanphantomz/111py | /turtle2/estado_curso.py | 2,081 | 4.125 | 4 | # -*- coding: utf-8 -*-
#!/usr/bin/python3
from turtle import Screen, Turtle
def dibuja_pedazo(radio, porcentaje, tortuga, titulo):
# Dibujo de la linea
angulo = 360 * porcentaje / 100
tortuga.left(angulo)
tortuga.forward(radio)
tortuga.backward(radio)
# Escribir el texto
tortuga.penup()
tortuga.right(angulo / 2)
tortuga.forward(radio / 2)
tortuga.write(titulo)
tortuga.backward(radio / 2)
tortuga.left(angulo / 2)
tortuga.pendown()
def dibuja_circulo(radio, tortuga):
tortuga.penup()
tortuga.goto(0, -radio)
tortuga.pendown()
tortuga.circle(radio)
tortuga.penup()
tortuga.home()
tortuga.pendown()
def main():
# Titulos
titSobre = "Sobresalientes"
titApro = "Aprobados"
titNotab = "Notables"
titSuspen = "Suspensos"
# Radio del circulo
radio = 300
# Dimenciones de la ventana
ancho = 625
alto = 625
# Lectura de datos
suspensos = float(input("Cant. Suspensos: "))
aprobados = float(input("Cant. Aprobados: "))
notables = float(input("Cant. Notables: "))
sobresalientes = float(input("Cant. Sobresalientes: "))
# Convertimos a porcentajes los datos recibidos
total_estudiantes = suspensos + aprobados + notables + sobresalientes
suspensos = (suspensos * 100) / total_estudiantes
aprobados = (aprobados * 100) / total_estudiantes
notables = (notables * 100) / total_estudiantes
sobresalientes = (sobresalientes * 100) / total_estudiantes
# Inicialización
pantalla = Screen()
pantalla.setup(ancho, alto)
pantalla.screensize(ancho - 25, alto - 25)
tortuga = Turtle()
tortuga.speed(0) # maxima velocidad
dibuja_circulo(radio, tortuga)
# Se dibuja la torta
dibuja_pedazo(radio, suspensos, tortuga, titSuspen)
dibuja_pedazo(radio, aprobados, tortuga, titApro)
dibuja_pedazo(radio, notables, tortuga, titNotab)
dibuja_pedazo(radio, sobresalientes, tortuga, titSobre)
tortuga.hideturtle()
# Salir cuando se haga click
pantalla.exitonclick()
main()
| false |
fb53aa7185a230fed83e98c64cb4928874059e5f | samirazein20/Week2_Challenge1 | /checkingbirth.py | 439 | 4.46875 | 4 | from datetime import datetime
# Prompting the user to enter their birth year
print('Enter Your Birth Year')
# Capturing the entered year from the keyboard
birthyear = int(input())
# getting the current year as an integer
thisyear = int(datetime.now().year)
# getting the persons age
diffyear = thisyear - birthyear
# checking
if(diffyear < 18):
print ("minor")
elif (diffyear > 36):
print("elder")
else:
print("youth")
| true |
4649d517881faf014a6d3ed6bbeb2afcb1fa2130 | JuBastian/ClassExercises | /exercise n+1.py | 405 | 4.125 | 4 | cost_limit = 5000000.0
duration_limit_in_years = 3.0
print("Please input the cost of the project")
cost = float(input())
print("Please input the duration of the project in years")
duration_in_years = float(input())
if (cost <= cost_limit) and (duration_in_years <= duration_limit_in_years):
print("Start the project")
else:
print("Do not start the project")
print("Thanks for using our software")
| true |
9031ec7be69abaffa5fc9c4fb93c48b712b8e085 | ayush-pradhan-bit/object-oriented-programming | /lab 1-4/arrangenumbers_0_4.py | 2,488 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
lab2 - arrangenumbers_0_4.py
Task:
-A random list of 3x3 is provided
-user provides a value to swap
-once the random list is equal to check list user have to input value
-prints "Good work" once match is found
Created on Sat Jan 23 23:15:55 2021
@author: Ayush Pradhan
import random- Generating Random Numbers in a 3x3 list
"""
import random
# checks if the list matches the tuple
def isReady(n, check):
return n == list(check)
# user inputs the value and swap is done
def move(n):
wronginput= True
while wronginput:
try:
numberInput = input('number to move:')
inputIndex = n.index(numberInput)
emptyIndex = n.index('_')
wronginput = False
n[inputIndex],n[emptyIndex]=n[emptyIndex],n[inputIndex]
break
except ValueError:
print('enter an integer btw 1 and 8')
# checks if order is solvable and returns a result
def isSolvable(n):
inversions = 0
for i in range(9):
for j in range (1,9):
if n[i] != '_' and n[j] != '_' and n[i] > n[j]:
inversions += 1
return inversions % 2 == 0
# we define the shuffle function
def shuffle(n):
for i in range(random.randint(2, 10)):
firstRandom = random.randint(0, 8)
secondRandom = random.randint(0, 8)
n[firstRandom], n[secondRandom] = n[secondRandom], n[firstRandom]
#program to give the list in 3x3 order
def printBoard(n):
listIndex = 0
for i in range(3):
for j in range(3):
if (j + 1) % 3 == 0:
print(n[listIndex], end='\n')
else:
print(n[listIndex], sep=' ', end=' ')
listIndex += 1
print('')
def create():
createdList = []
for i in range(1, 9):
createdList.append(str(i))
createdList.append('_')
return createdList
def main():
# create a list of numbers, shuffle the order and add an empty string to the end
n = create()
check = tuple(n)
# preparation loop
while True:
shuffle(n)
if isSolvable(n):
break
print('8 puzzle - arrange the numbers by swapping them with the empty place')
# the main loop
while True:
printBoard(n)
if isReady(n, check):
print('Good work!')
break
else:
move(n)
if __name__ == '__main__':
main() | true |
02df24db28632512c6bef0f2013a68ee741649af | dingleton/python_tutorials | /generators1_CS.py | 1,454 | 4.46875 | 4 | # -*- coding: utf-8 -*-
"""
Generators - sample code to test Python Generators
Taken from Corey Schafers You Tube Tutorial on Python Generators
"""
def square_numbers_1(nums):
""" function to accept a list of numbers and
return a list of the square of each number
"""
result = []
for i in nums:
result.append(i*i)
return result
def square_numbers_2(nums):
"""A Generator to accept a list of numbers and
return a list of the square of each number
"""
for i in nums:
yield(i*i)
#Create and initialise a small list (my_nums_0).
#Then generate a new list containing the squares of these numbers.
#This is done three times:
#1. fcalling function square_numbers_1 - this returns a list
#2. calling a generator square_numbers2, this is then converted to a list
#3. finally a list comprehension is used (for more practise in list comprehensions!)
my_nums_0 = [1, 2, 3, 4, 5]
my_nums_1 = square_numbers_1(my_nums_0)
my_nums_2 = list(square_numbers_2(my_nums_0))
my_nums_3 = [x*x for x in range(min(my_nums_0),max(my_nums_0)+1)]
print(my_nums_1)
print(my_nums_2)
print(my_nums_3)
#now assign the gerator function to a variable
my_nums_4 = square_numbers_2(my_nums_0)
#Print the variable i.e. the address of the **unexecuted** generator
#Next print each value by executing the generator to produce the next result
print("\nmy_nums_4 = {}".format(my_nums_4))
for j in range (0,5):
print(next(my_nums_4))
| true |
153b066ee5a40a1c8548155461352cf843e944ec | Memory-1/PythonTutorials | /1. Data Types/Projects/Project 1 - Tip Calculator.py | 845 | 4.15625 | 4 | """
Tip Calculator
In this project you will make a simple tip calculator. The result should be the bill total + the tip.
It will take two inputs from the user. I use input() which will prompt you to enter something in.
Take those two inputs. Divide the percentage by 100 to get a decimal number and then
This project will help you get familiar with numbers - both floats and integer number types.
You will be using multiplication (*), division (/), and addition (+). There are examples for these in the examples
folder
"""
# Remember - We talked about numbers and it's methods
price = input("Bill total?")
tip_percentage = input("Tip Percentage?") # This will be a number like 10 or 12.5.
# TODO: 1. Convert the tip percentage to decimal (Remember that 75% = .75)
# TODO: 2. Calculate the total price
# TODO: 3. Print out the results
| true |
d34f89ff9879cafb023df5d9e5f3924570555ee7 | Memory-1/PythonTutorials | /1. Data Types/Examples/Collections/Dictionaries.py | 1,065 | 4.34375 | 4 | """
Dictionaries are key value pairs. They're great for storing information for a particular thing and being able to quickly
access it without even knowing it's index
Once again, you can store anything for the value in the key-value pair, but the key must be either a string or an int
"""
Dictionary_1 = {} # Making one
Dict_with_items = {'a_number': 1, 'some_strimg': "I'm a string!", 'a list': [1,2,3], 'tuples!': ('a','b','c')}
Person = {"age": 30, 'name': "Joe", "children":('amy','bob','sue'), 'job': "Yellow jelly bean tester"}
"""
Accessing values in a dictionary
Technique 1: some_dict.get("key")
Technique 2: some_dict["key"]
"""
print("NAME: " + Person['name'])
print("JOB: " + Person.get('job'))
print()
""" Updating/Adding
To update there are two methods either
1. Calling the index with some_dict['name'] and assign a value
2. use the update method and enter in a new dictionary to add
"""
Ex_1 = {}
Ex_1['name'] = 'Floyd'
print(Ex_1)
print()
Ex_2 = {}
Ex_2.update({"name": "Jeff"})
print(Ex_2)
print() | true |
42fe45920032505b7a2832b0d2f584767f9e6dc8 | 22zagiva/1-1_exercises | /mpg.py | 716 | 4.34375 | 4 | #!/usr/bin/env python3
# display a welcome message
print("The Miles Per Gallon program")
print()
# get input from the user
miles_driven= float(input("Enter miles driven:\t\t"))
gallons_used = float(input("Enter gallons of gas used:\t"))
miles_gallon_cost = float(input("Enter cost per gallon:\t\t"))
# calculate miles per gallon
mpg = miles_driven / gallons_used
mpg = round(mpg, 1)
tgc = gallons_used * miles_gallon_cost
tgc = round(tgc, 1)
cpm = miles_gallon_cost * gallons_used / miles_driven
# format and display the result
print()
print("Miles Per Gallon:\t\t" + str(mpg))
print("Total Gas Cost:\t\t\t" + str(tgc))
print("Cost Per Mile:\t\t\t" + str(cpm))
print()
print("Bye")
| true |
68fc8bd40c7f35370cb5dbf1e7bf452e226f6a29 | mkramer45/PythonCluster3 | /Ch16_DefaultFunctionParameters.py | 287 | 4.125 | 4 | def optional_parameter(first_parameter = 0): # defining our function ... argument is we are defaulting first_param to 0
print(first_parameter + 8) # here is our function's command, where we are telling to print the first param of the argument + an integer (8)
optional_parameter() | true |
8a70f50cab87b0c271136685d2a1ac76cb336270 | Masoninja/python | /turtle/plot-circle-list-mka.py | 2,552 | 4.25 | 4 | '''
Test this.
https://tritech-testsite.smapply.io/
python-circle-list-assignment.py
Get the code: 10.183.1.26 code python
Plot circle data using python
- Use your data
- Change the background color
- Change the graph line colors
- Change the plot line color
- Change the plot dot color
- Label the graph with text Plotting Circumference and Diameter
- Label the axis with text (Circumference and Diameter)
- Upload to github with your name initials or name attached (plot-circle-list-cwc.py)
'''
import turtle
import math
wdth = 800; hgth = 800; bgstring = "#000980"
red = "#cc0000"; green = "#00cc00"; blue = "#00ffff"
def grid(t):
x = 0; y = 0
while (x < 400):
t.speed(0)
t.penup()
t.goto(x,y)
t.pendown()
t.goto(x,y+400)
x = x + 100
x = 0; y = 0
while (y < 400):
t.speed(0)
t.penup()
t.goto(x,y)
t.pendown()
t.goto(x+400,y)
y = y + 100
t.penup()
t.goto(0,400)
t.pendown()
t.color('#00ffff')
style = ('Courier', 30, 'bold')
t.write('Circle Circumference and Diameter Plot', font=("Arial", 15, 'normal', 'bold',))
t.hideturtle()
t.penup()
t.goto(5,-50)
t.pendown()
t.color('#00ffff')
style = ('Courier', 30, 'bold')
t.write('D i a m e t e r', font=("Arial", 15, 'normal', 'bold',))
t.hideturtle()
t.penup()
t.goto(-30, 80)
t.pendown()
t.color('#00ffff')
style = ('Courier', 30, 'bold')
t.write('C\n i\n r\n c\n u\n m\n f\n e\n r\n e\n n\n c\n e', font=("Arial", 15, 'normal', 'bold',))
t.hideturtle()
t.penup()
def plotCircles(t):
#list named d and c
d = [85, 100, 115, 35]
c = [270, 314, 360, 110]
# list dsorted and csorted
dsorted = sorted (d, key = float)
csorted = sorted(c , key = float)
t.speed(0)
t.color('#db3514')
t.goto(0,0)
t.pendown()
t.dot(3, blue)
t.goto(dsorted[0],csorted[0])
t.dot(3, blue)
t.goto(dsorted[1],csorted[1])
t.dot(3, blue)
t.goto(dsorted[2],csorted[2])
t.dot(3, blue)
t.goto(dsorted[3],csorted[3])
t.dot(3, blue)
t.penup()
t.color(green)
t.goto(0, 400)
t.pendown()
t.goto(400,400)
t.goto(400, 0)
def main():
try:
turtle.TurtleScreen._RUNNING = True
# get wdth and hgth globally
turtle.screensize(canvwidth=wdth, canvheight=hgth, bg=bgstring)
print(turtle.Screen().screensize())
w = turtle.Screen()
t = turtle.Turtle()
t.speed(0)
t.color('#11cf0f')
t.hideturtle()
grid(t)
plotCircles(t)
w.exitonclick()
finally:
turtle.Terminator()
if __name__ == '__main__':
main()
'''
# Using sorted + key
Output = sorted(Input, key = float)
# Using sorted + key
Output = sorted(Input, key = float)
'''
| true |
07885aced3e5dda43b0afc7989bdabf4e4c95cac | chenwensh/python_excrise | /graphic_test.py | 776 | 4.15625 | 4 | #This program is to test the graphic codes from the book <Python for Kids>.
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
from tkinter import *
import random
def hello():
print("hello there")
def random_rectangle(width, height):
x1 = random.randrange(width)
y1 = random.randrange(height)
x2 = x1 + random.randrange(width)
y2 = y1 + random.randrange(height)
canvas.create_rectangle(x1, y1, x2, y2)
#The tkinter main window(root window) to hold everything in tkinter.
tk = Tk()
#Define the widgets.
btn = Button(tk, text = 'Click me', command = hello)
#Add the widget to the root window.
btn.pack()
canvas = Canvas(tk, width = 500, height = 500)
canvas.pack()
for x in range(0, 10):
random_rectangle(400, 400)
#The meesage loop
tk.mainloop()
| true |
031d8fc9ce91cf12de432b2c1a1168e9cd9cb70e | lucasjurado/Alura-IO | /testa_escrita.py | 942 | 4.1875 | 4 | # Sempre que abrimos algum arquivo em modo w, o Python vai truncar o arquivo, isto é, limpará seu conteúdo.
# Para adicionar conteúdo a um arquivo sem apagar o que já está escrito, temos que utilizar o modo a.
# (+) --> mode de atualização do arquivo
arquivo_contatos = open('contatos-lista.csv', encoding='latin_1', mode='w+')
contatos = ['11,Carol,carol@gmail.com\n',
'12,Ana,ana@ana.com.br\n',
'13,Thais,thais@hotmail.com\n',
'14,Felipe,felipe@felipe.com.br\n']
# Para inserir uma Lista de contatos, devemos iterá-la
for contato in contatos:
arquivo_contatos.write(contato)
arquivo_contatos.flush() # Força a inserção dos dados no arquivo .csv
arquivo_contatos.seek(26) # Faz o ponteiro retornar para a primeira linha do arquivo .csv
arquivo_contatos.write('12,Ana,ana@ana.com.br\n'.upper()) # Sobrescrevendo a linha ana
arquivo_contatos.flush()
arquivo_contatos.seek(0)
for linha in arquivo_contatos:
print(linha, end='') | false |
090577072b196397dc6bcf7f44a4bbb7437c8e41 | RobertMcNiven/Vector-Calculator | /vector_calculatorV2.py | 1,483 | 4.3125 | 4 | import math
try:
amount_of_vectors = int(input('How many vectors would you like to add?' + '\n'))
except:
print('Please enter an integer greater than 0')
exit()
def vector_physics():
x_component = 0
y_component = 0
for numbers in range(1, amount_of_vectors+1):
vector_direction_degrees = float(input('What is the direction of vector #' + str(numbers) + '\n'))
magnitude_of_x = float(input('What is the magnitude of the x-component of vector #' + str(numbers) + '\n'))
magnitude_of_y = float(input('What is the magnitude of the y-component of vector #' + str(numbers) + '\n'))
vector_direction_radians = vector_direction_degrees*(math.pi/180)
x_component = x_component + (magnitude_of_x * math.cos(vector_direction_radians))
y_component = y_component + (magnitude_of_y * math.sin(vector_direction_radians))
r_magnitude = math.sqrt(x_component**2 + y_component**2)
print('X Comp: ' + str(x_component))
print('y Comp: ' + str(y_component))
print('Resultant vector magnitude: ' + str(r_magnitude))
try:
r_direction = y_component/x_component
print('The arc-tan of ' + str(r_direction) + " is the resultant vectors direction")
except:
print('The direction of the vector is undefined due to the x-component adding up to 0')
if amount_of_vectors > 0:
vector_physics()
else:
print('Please enter an integer greater than 0')
| true |
a76aaecaa2de87366eda6112aa83609b61711d1f | standrewscollege2018/2020-year-12-python-code-CeeRossi | /Book store/yee.py | 2,073 | 4.15625 | 4 | #This program is designed so that a user can add/ delete book titles from a list of books
print("Designed and built by Caleb Rossiter")
print("Version 1")
#User login that retains usser account after program closed
welcome = input("Do you have an acount? y/n: ")
if welcome == "n":
while True:
username = input("Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
file = open(username+".txt", "w")
file.write(username+":"+password)
file.close()
welcome = "y"
break
print("Passwords do NOT match!")
elif welcome == "y":
while True:
login1 = input("Login:")
login2 = input("Password:")
file = open(login1+".txt", "r")
data = file.readline()
file.close()
if data == login1+":"+login2:
print("Welcome",login1,)
break
print("Incorrect username or password.")
print("Please try again")
#Main menu
print("\n=====MENU=====")
print("1. Display every book")
print("2. Add a new book")
print("3. Delete a book")
print("4. Update a book detailst")
print("5. Close app")
while True:
try:
choice = int(input("Please choose a menu option: "))
break
#detect integer value not entered
except:
#display error message
print("Error: Your input must be a number")
#redisplay menu so that user can see what options are
print("\n=====MENU=====")
print("1. Display all students")
print("2. Add a student")
print("3. Delete a student")
print("4. Update a student")
print("5. Quit program\n")
if choice ==1 :
print("This Works")
elif choice ==2 :
print("This Works")
elif choice ==3 :
print("This Works")
elif choice ==4 :
print("This Works")
#exit program
elif choice ==5:
display_menu = False
#invalid menu
else:
print("invalid menu choice")
| true |
b25911f0ff7e94c38b08bdc0eb3895e597f4753c | Phoenix795/learn-homework-1 | /3_for.py | 1,865 | 4.25 | 4 | """
Домашнее задание №1
Цикл for: Оценки
* Создать список из словарей с оценками учеников разных классов
школы вида [{'school_class': '4a', 'scores': [3,4,4,5,2]}, ...]
* Посчитать и вывести средний балл по всей школе.
* Посчитать и вывести средний балл по каждому классу.
"""
from random import randint
def mean(scores):
return round(sum(scores)/len(scores), 2), len(scores)
def rand_scores(quantity, start=2, end=5):
return list(randint(start, end) for i in range(quantity))
def main(school):
common_length = 0
common_score = 0
for school_class in school:
mean_score, length = mean(school_class["scores"])
common_length += length
common_score += mean_score * length
print(f'Cредний балл по {school_class["school_class"]} классу: {mean_score}')
print('-' * 30)
print(f'Cредний балл по всей школе: {round(common_score/common_length, 2)}')
if __name__ == "__main__":
school = [
{'school_class': '4a', 'scores': [3,4,4,5,2]},
{'school_class': '4б', 'scores': rand_scores(6)},
{'school_class': '5a', 'scores': rand_scores(7)},
{'school_class': '5б', 'scores': rand_scores(9)},
{'school_class': '6a', 'scores': rand_scores(6)},
{'school_class': '6б', 'scores': rand_scores(6)},
{'school_class': '7a', 'scores': rand_scores(12,3)},
{'school_class': '8а', 'scores': rand_scores(11)},
{'school_class': '8б', 'scores': rand_scores(7)},
{'school_class': '8в', 'scores': rand_scores(14)},
{'school_class': '9a', 'scores': rand_scores(15)},
{'school_class': '9б', 'scores': rand_scores(16)},
]
main(school)
| false |
c1fc96e1ddbfa31ed8fb09dc65468ccfa6c3b8c0 | ozmaws/Chapter-3 | /Project3.8.py | 626 | 4.21875 | 4 | first = int(input("Enter a positive number: "))
second = int(input("Enter a second positive number: "))
if first > second:
larger = first
smaller = second
else:
larger = second
smaller = first
while smaller != 0:
print("")
remainder = larger % smaller
print("The remainder of dividing " + str(larger) + " by " + str(smaller) + " is " + str(remainder))
larger = smaller
smaller = remainder
print("The larger number has been changed to " + str(larger) + " and the smaller number has been changed to " + str(smaller))
print("The smaller number is now 0")
print("The GCD is " + str(larger))
| true |
c6d30d97e6d14df2e0862bf5d3e7928e20c310a4 | terchiem/Cracking-the-Coding-Interview-Python | /01 - Arrays and Strings/1-8 zero_matrix.py | 915 | 4.28125 | 4 | """
Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0,
its entire row and column are set to 0.
"""
def zero_matrix(matrix):
"""Returns the input matrix where if an element is 0, its entire row and
column are set to 0.
>>> zero_matrix([[1,1,0],[1,1,1],[1,1,1]])
[[0, 0, 0], [1, 1, 0], [1, 1, 0]]
>>> zero_matrix([[1,1,1],[1,0,1],[1,1,1]])
[[1, 0, 1], [0, 0, 0], [1, 0, 1]]
>>> zero_matrix([[1,1,0],[1,1,1],[0,1,1]])
[[0, 0, 0], [0, 1, 0], [0, 0, 0]]
"""
rows = set()
cols = set()
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == 0:
rows.add(i)
cols.add(j)
for i in rows:
for j in range(len(matrix[i])):
matrix[i][j] = 0
for i in range(len(matrix)):
for j in cols:
matrix[i][j] = 0
return matrix
| false |
bbf0fd898240ed567e7139516076256428059ec1 | terchiem/Cracking-the-Coding-Interview-Python | /01 - Arrays and Strings/1-4 valid_palindrome.py | 985 | 4.25 | 4 | """
Palindrome Permutation: Given a string, write a function to check if it is a
permutation of a palindrome. A palindrome is a word or phrase that is the same
forwards and backwards. A permutation is a rearrangement of letters. The
palindrome does not need to be limited to just dictionary words.
"""
def valid_palindrome(string):
"""Returns true/false if the input string can be rearranged into a valid
palindrome.
>>> valid_palindrome('Tact Coa')
True
>>> valid_palindrome('abcdef')
False
>>> valid_palindrome('abcab')
True
>>> valid_palindrome('aaaaa')
True
>>> valid_palindrome('')
True
"""
count = {}
simplified_string = string.replace(' ', '').lower()
for ch in simplified_string:
count[ch] = count.get(ch, 0) + 1
odd_found = False
for ch in count.keys():
if count[ch] % 2 != 0:
if odd_found:
return False
odd_found = True
return True
| true |
40c5ae75c684ee80cb4f881f91feed0304471a4e | acwajega2/googlePythonInterview | /app1.py | 628 | 4.3125 | 4 | #### MAKING A CHANGE APP
#----GET THE NUMBER OF COINS GIVEN CHANGE AS 31 CENTS
#---- 1 quarter ==>>>>>>(25 cents)
#---- 1 nickel ==>>>>>>(5 cents)
#-----1 pennies ==>>>>>(1 cent)
#------1 dime ==>>>>>(10 cents)
#EXAMPLE--GIVEN 31 cents-----you give back 3 coins in (1 quarter, 1 nickel and i pennies)
def num_coins(cents):
if cents < 1:
return 0
coins =[25,10,5,1]
num_coins = 0
coins.sort(reverse=True)
new_cents = cents
for coin in coins:
while new_cents >= coin :
new_cents = new_cents - coin
num_coins +=1
return num_coins
print(num_coins(31))
| true |
3917f66cba10e3cf97376fcffcae00f0847db0d8 | AndreiR01/Sorting-Algorithms | /QuickSort.py | 2,404 | 4.375 | 4 | from random import randrange, shuffle
#https://docs.python.org/3/library/random.html#random.randrange <-- Documentation
#QuickSort is a recursive algorithm, thus we will be having a base case and a recursive function
#We will sort our list in-place to keep it as efficient as possible. Sorting in-place means that we keep track of the sub-lists in our algorithm using pointers and swap values inside the list rather than create new lists
#Since doing this in-place, we will have two pointers:
#1. Keep track of the "lesser than" values
#2. Track progress throught the list.
#HOW TO :
# # Create the lesser_than_pointer
# Start a for loop, use 'idx' as the variable
# Check if the value at idx is less than the pivot
# If so:
# 1) swap lesser_than_pointer and idx values
# 2) increment lesser_than_pointer
# After the loop is finished...
# swap pivot with value at lesser_than_pointer
#Pointers are indicies that keep track of a portion of a list
def quicksort(list, start, end):
#Base Case
if start >= end:
return list
#select random element to be pivot
pivot_idx = randrange(start, end + 1) #+1 in order to include last element
pivot_element = list[pivot_idx]
# Swapping the the random element with the last element of the list, pivot element will always be located at the end of the list.
list[end], list[pivot_idx] = list[pivot_idx], list[end]
#tracks all elements which should be to left(lesser than) pivot
lesser_than_pointer = start
for idx in range(start, end):
#element out of place found
if list[idx] < pivot_idx:
#swap element to right-most portion of lesser elements
list[lesser_than_pointer], list[idx] = list[idx], list[lesser_than_pointer]
#tally that we have one lesser element
lesser_than_pointer += 1
#move pivot element to the right-most portion of lesser elements
list[end], list[lesser_than_pointer] = list[lesser_than_pointer], list[end]
#Calling quicksort on the left and right sub-lists
quicksort(list, start, lesser_than_pointer - 1)
quicksort(list, lesser_than_pointer + 1, end)
unsorted_list = [3,7,12,24,36,42]
shuffle(unsorted_list)
print(unsorted_list)
sorted_list = quicksort(unsorted_list, 0, len(unsorted_list)-1)
print(sorted_list)
| true |
9875a570ed15b9f49ce8a719cc4f50cbd6dc5cc8 | TiarahD18/cs | /week3/test.py | 1,539 | 4.15625 | 4 | #!/usr/bin/env python
#print ("Hello CSSI")
#print ("also Hello CSSI")
#print ("also also Hello CSSI")
# print("Hello CSSI")
#name = "Bill"
#name = 55
#print(name)
#name = raw_input("Enter your name: ")
#print("Hi there...")
#print(name)
#print("na " * 16)
#print("BATMAN")
#print("Pow!" * 3)
#user_input = raw_input("Enter anything..")
#print(You entered a " , strType(user_input))
#print("raw_input gives us strings")
#num1 = raw_input("Enter number #1: ")
#num2 = raw_input("Enter number #2: ")
#print(num1 + num2)
#print(type(num1 + num2))
#print("int(raw_input) gives us int")
#num1 = int(raw_input("Enter number #1: "))
#num2 = int(raw_input("Enter number #2: "))
#print(num1 + num2)
#print(type(num1+num2))
#num = int(raw_input("Enter a number: "))
#if num > 0:
#print("That's a positive number!")
#elif num < 0:
#print("That's a negative number!")
#else:
#print("Zero is neither positive nor negative")
#age = 18
#if age > 18:
#print("You can buy lottery tickets!")
#if age > 25:
#print("You can also rent a car!")
#print("And you can get your own credit card!")
#print("End program. ") # not inside any if statement
#x = 1
#while x <= 5:
#print(x)
#x = x + 1
#string = ['h', 'el', 'lo', 'there']
#for letter in string:
#print(letter.upper())
#name = "Brooklyn"
#for i in range(5):
#print(name[i])
my_name = "Bob"
friend1 = "Alice"
friend2 = "John"
friend3 = "Mallory"
print(
"My name is %s and my friends are %s, %s, and %s" %
(my_name, friend1, friend2, friend3)
)
| false |
bc09d6da5d27ac66704fa42eedbc9e48ff596698 | chavisam/PythonListExercies | /exercises/04.1-count_on/app.py | 222 | 4.125 | 4 |
my_list = [42, True, "towel", [2,1], 'hello', 34.4, {"name": "juan"}]
#your code go here:
hello = []
for i in my_list:
print(type(i))
if type(i) == list or type(i)== dict:
hello.append(i)
print(hello)
| false |
a3cbf087fda96dbaa949661214f09e47f66e06f2 | AmanCSE-1/Operating-System | /CPU Scheduling Algorithm/Shortest Job First Algorithm (SJF).py | 2,048 | 4.125 | 4 | # Shortest Job First Program in Python
# Function which implements SJF algorithm.
def SJF(process, n):
process = sorted(process, key=lambda x:x[1]) # Sorting process according to their Burst Time
wait= 0
waitSum, turnSum = 0,0 # Initializng Sum of Wait-Time -> 0
# Initializng Sum of Tuenaround-Time -> 0
print("Process\t Burst-Time\tWaiting-Time\tTurnaround-Time")
for i in range(n): # Iterating through all processes
turn = wait + process[i][1] # Turnaround-Time = Wait-Time + Burst-Time
print("P" + str(process[i][0]) + "\t\t" + str(process[i][1]) + "\t\t" + str(wait)+ "\t\t" + str(turn))
wait += process[i][1] # Adding wait-time with burst time of current process
waitSum += wait # Incrementing Sum of Wait-Time
turnSum += turn # Incrementing Sum of Turnaround-Time
waitSum -= wait
avgWaitTime = round(waitSum/n, 3) # Rounding Average Waiting Time upto 3 decimal places
avgTurnTime = round(turnSum/n, 3) # Rounding Average Turnaround-Time upto 3 decimal places
return (avgWaitTime, avgTurnTime)
# Driver Code
if __name__ == "__main__":
n=int(input("Enter the number of process: ")) # Number of processes
process=[]
for i in range(1, n+1): # Taking user-input for Burst-Time of process
process.append([i, int(input("Enter Burst-Time for Process-"+str(i)+": "))])
print("\n\nShortest Job First Scheduling: ")
resultTuple = SJF(process, n)
print("\nAverage Waiting-Time is", resultTuple[0])
print("Average Turnaround-Time is", resultTuple[1])
##### Note : The Output Image of the Program is also uploaded in the same directory. #####
| true |
268adf46f20f4a00e337be101af038282406a9fc | RakshithHegde/python-basics | /stringMethods.py | 1,181 | 4.4375 | 4 | #strings can sliced and we can return a range of characters by using slice
#specify the start index and end, seperated by a colon, to return part of a string
b="Hello,World!"
print(b[3:6])
c="Hello,World!"
print(c[:6])
#negative indexing
b = "Hello,World!"
print(b[-3:-1])
#modifying Strings
#Uppercase
a= "abcdoncwijdbcw"
print(a.upper())
#lowercase
f="SCHABDACBJDAQF"
print(f.lower())
#strip
A=" Hello , World! "
print(a.strip())
#replace string
a="Good Evening!"
print(a.replace("Evening","Night"))
#split()
a="What are you ,planning for today?"
print(a.split(","))
#concatenation of 2 strings
a = "Hi"
b= "Have a good day"
c = a + "!," + b
print(c)
#format
age = 20
text = "My name is rk, and I am {}"
print(text.format(age))
#we can pass multiple values through format method as it can take unlimited number of arguments
PetrolStation="Indian Oil"
Petrolrate = 104.98
PetrolAmount = 6000
Myday = "Today I went to fill petrol at {} the petrol rate was {}//l and I spent {}rs "
print(Myday.format(PetrolStation,Petrolrate,PetrolAmount))
NextDay="I paid {2}rs today at {0} as the rate of petrol was {1}//l"
print(NextDay.format(PetrolStation,Petrolrate,PetrolAmount)) | true |
9398f22588002160b3bc6ae7d680075e2bd0f7c0 | GokulShine12/PYTHON-INTERN | /TASK 8.py | 1,602 | 4.3125 | 4 | # 1. List down all the error types - using python program
#Syntax error
print "True"
#Division by zero error
try:
print(10/0)
except ZeroDivisionError:
print("Division by zero error")
#Key error
try:
a={'cse-a':'65','cse-b':'60'}
a['cse-c']
except KeyError:
print("Key not found error")
#Module not found error
try:
import mod
except ModuleNotFoundError:
print("Module not found")
# 2. calculator
def calculator():
try:
a=int(input("Number 1 : "))
b=int(input("Number 2 : "))
c=input("Operation: +,-,*,/")
if c=='+':
print(" Addition of 2 nos is :",a+b)
elif c=='-':
print(" Subtraction of 2nos is :",a-b)
elif c=='*':
print(" Multiply of 2nos is :",a*b)
elif c=='/':
try:
print(" Division of 2nos is :",a/b)
except ZeroDivisionError:
print("division by zero error")
except ValueError:
print("enter valid input")
calculator()
# 3. Print one message if the try block raises a NameError and another for other errors
try:
print(name)
except NameError:
print("Name is not defined")
except:
print("Other error has occured")
# 4. When try-except scenario is not required ?
" When our program has normal statements , there is no need for try-except "
# 5. Input inside the try catch block
try:
sport=int(input("Your favorite sport is "))
print(sport)
except:
print("An exception occurs")
| true |
241aff3e501418a3d0e87aa39432435709828362 | JaceTSM/Project_Euler | /euler003.py | 742 | 4.21875 | 4 | # !/Python34
# Copyright 2015 Tim Murphy. All rights reserved.
# Project Euler 003 - Largest Prime Factor
'''
Problem:
What is the largest prime factor for a given number N.
Input:
First line contains T, and then the following T lines contain N
for the given test case.
Constraints:
1 <= T <= 10
1 <= N <= 10**12
'''
import math
# Input T cases
cases = int(input())
# For each case, find the factors of input N.
for case in list(range(cases)):
num = int(input())
factors = [num]
# only search for factors up to the square root of a number.
for i in list(range(2,(int(math.sqrt(num)) + 1))):
while factors[-1] % i == 0:
factors.append(factors[-1]//i)
factors[-2] = i
# Print case result to screen
print(max(factors)) | true |
303f564f40fec53155e280186fb58ca0c16e8e53 | calvin0123/sc-projects | /stanCode_Projects/weather_master/quadratic_solver.py | 947 | 4.28125 | 4 | """
File: quadratic_solver.py
Name: Calvin Chen
-----------------------
This program should implement a console program
that asks 3 inputs (a, b, and c)
from users to compute the roots of equation
ax^2 + bx + c = 0
Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
import math
def main():
"""
pre-condition: enter a, b, and c
post-condition: answer of the quadratic and how many roots
"""
print("stanCode Quadratic Solver!")
a = int(input('Enter a: '))
b = int(input('Enter b: '))
c = int(input('Enter c: '))
disc = b * b - 4 * a * c # disc = discriminant
if disc > 0:
y = math.sqrt(disc)
root1 = (-b + y) / 2 * a
root2 = (-b - y) / 2 * a
print('Two roots: ' + str(root1) + ' , ' + str(root2))
elif disc == 0:
root1 = -b / 2 * a
print('One root: ' + str(root1))
else:
print('No real roots')
###### DO NOT EDIT CODE BELOW THIS LINE ######
if __name__ == "__main__":
main()
| true |
fd10cfead6759ac05de9cb364acb40e527649d04 | liuyonggg/learning_python | /leetcode/hindex.py | 1,506 | 4.25 | 4 | '''
For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3.
Note: If there are several possible values for h, the maximum one is taken as the h-index.
Note: If there are several possible values for h, the maximum one is taken as the h-index.
'''
class Solution():
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
citations.sort(reverse=True)
return max([min(k+1, v) for (k, v) in enumerate(citations)]) if citations else 0
class Solution2():
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
citation_article_table = [0]*(len(citations)+1)
for i in xrange(len(citations)):
if citations[i] > len(citations):
citation_article_table[len(citations)] += 1
else:
citation_article_table[citations[i]] += 1
s = 0
for i in xrange(len(citations), -1, -1):
s += citation_article_table[i]
if s >= i:
return i
return 0
if __name__ == '__main__':
assert (Solution().hIndex([1, 2, 3]) == 2)
assert (Solution().hIndex([1, 2, 3]) == Solution2().hIndex([1,2,3]))
| true |
2fc8c5777310146e6f92201945718056baa30eeb | PrajjwalDatir/CP | /CodeChef/ExamCodechef/3Q.py | 2,190 | 4.1875 | 4 | # Python3 program to find minimum edge
# between given two vertex of Graph
import queue
import sys
INT_MAX = sys.maxsize
# function for finding minimum
# no. of edge using BFS
def minEdgeBFS(edges, u, v, n):
# u = source
# v = destination
# n = total nodes
# visited[n] for keeping track
# of visited node in BFS
visited = [0] * n
# Initialize distances as 0
distance = [0] * n
# queue to do BFS.
Q = queue.Queue()
distance[u] = 0
Q.put(u)
visited[u] = True
while (not Q.empty()):
x = Q.get()
for i in range(len(edges[x])):
if (visited[edges[x][i]]):
continue
# update distance for i
distance[edges[x][i]] = distance[x] + 1
Q.put(edges[x][i])
visited[edges[x][i]] = 1
return distance[v]
# function for addition of edge
def addEdge(edges, u, v):
edges[u].append(v)
edges[v].append(u)
# Driver Code
# if __name__ == '__main__':
def useless():
# To store adjacency list of graph
n = 9
edges = [[] for i in range(n)]
addEdge(edges, 0, 1)
addEdge(edges, 0, 7)
addEdge(edges, 1, 7)
addEdge(edges, 1, 2)
addEdge(edges, 2, 3)
addEdge(edges, 2, 5)
addEdge(edges, 2, 8)
addEdge(edges, 3, 4)
addEdge(edges, 3, 5)
addEdge(edges, 4, 5)
addEdge(edges, 5, 6)
addEdge(edges, 6, 7)
addEdge(edges, 7, 8)
u = 0
v = 5
print(minEdgeBFS(edges, u, v, n))
# This code is contributed by PranchalK
# Driver Code
if __name__ == "__main__":
T = int(input())
for _ in range(T):
N,M,K= map(int, input().split(" "))
edges = [[] for i in range(N)]
for i in range(M):
a,b = map(int, input().split(" "))
addEdge(edges,a,b)
portal = list(map(int, input().split(" ")))
print(edges)
# print("taking input")
Q = int(input())
for __ in range(Q):
u = int(input())
if u in portal:
print("0")
# Function call
else:
for r in portal:
ans = INT_MAX
temp = minEdgeBFS(edges,u, r,N)
if temp < ans and temp != -1:
ans = temp
print(ans)
| true |
d6bb4126ee3fd4376a9c61bb0fa05abce3f5b9f8 | PrajjwalDatir/CP | /gfg/mergesort.py | 529 | 4.1875 | 4 | # merge sort
# so we need two functions one to break and one to merge
# divide and conqeror
def merge():
pass
def mergeSort(arr):
if len(arr) <= 1:
return arr
L =
def printList(arr):
for i in range(len(arr)):
print(arr[i], end =" ")
print()
# driver code to test the above code
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print ("Given array is", end ="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end ="\n")
printList(arr)
| true |
c4ce8cb096120452a9e25f7d1fb86f9a4ffb2570 | PrajjwalDatir/CP | /gfg/jug1.py | 2,795 | 4.1875 | 4 | # Question 1
"""
so we have linked list with data only equal to 0 , 1 or 2 and we have to sort them in O(n) as I think before prajjwal knows the answer of this question
"""
#so first we need linked list to start withs
class Node:
"""docstring for Node"""
def __init__(self, data):
self.data = data
self.next = None
class linkedList:
"""docstring for linkedList"""
def __init__(self):
self.head = None
def push(self, data):
temp = self.head
newnode = Node(data)
if self.head is None:
self.head = newnode
return
else:
while temp.next is not None:
temp = temp.next
temp.next = newnode
def printList(self):
temp = self.head
if self.head is None:
print("List is empty")
return 0
while temp.next:
print(temp.data, end="->")
temp = temp.next
print(temp.data)
return 1
def sortList(self):
if self.head is None:
print("Nothing to sort here.")
return
elif self.head.next is None:
return
# here zero one and two are to point at the latest 0 1 2 countered so that we can just swap with them
last_zero = None
last_one = None
last_two = None
temp = None
current = self.head
if self.head.data == 1:
last_one = current
elif self.head.data == 0:
last_zero = current
else:
last_two = current
# print(f"current is {current.data}")
# self.printList()
current = current.next
while current.next:
# print(f"current is {current.next.data}")
if current.next.data == 0:
print(f"current is {current.next.data}")
temp = current.next
if last_zero is None:
current.next = temp.next
temp.next = self.head
self.head = temp
last_zero = temp
self.printList()
else:
current.next = temp.next
temp.next = last_zero.next
last_zero.next = temp
last_zero = temp
self.printList()
elif current.next.data == 1:
# print(f"current is {current.next.data}")
# self.printList()
temp = current.next
if last_one is None:
print(f"current is {current.next.data}")
self.printList()
current.next = temp.next
if last_zero is None:
temp.next = self.head
self.head = temp
else:
temp.next = last_zero.next
last_zero.next = temp
last_one = temp
self.printList()
else:
current.next = temp.next
temp.next = last_one.next
last_one.next = temp
last_one = temp
else:
print(f"current is {current.next.data}")
self.printList()
current = current.next
ll = linkedList()
# test case : 12012010 answer should be 00011122
# bug is when we encounter 1 before encountering
ll.push(2)
ll.push(1)
ll.push(0)
# ll.push(1)
# ll.push(0)
# ll.push(2)
# ll.push(0)
# ll.push(1)
# ll.push(0)
ll.printList()
ll.sortList()
ll.printList() | true |
0b4e4d3f7fdcf1d6cd0f172a91df737821231149 | tzvetandacov/Programming0 | /n_dice.py | 347 | 4.125 | 4 | #dice = input ("Enter a digit")
#from random import randint
#result = randint (1, 6) + int(1)
#print (result)
from random import randint
n = input ("Enter sides:")
n = int (n) # This can be done as shown below
result1 = randint(1, n) # Option: result = randint (1, int(n))
result2 = randint (1, n)
print (result1 + result2)
| true |
b4955b561872e3174004ffc19fb0325288874766 | dennohpeter/Python-Projects | /sleep.py | 769 | 4.34375 | 4 | #!/usr/bin/python
##display a message based to the user based on
##the number of hours of sleep the user enters for the previous night.
##Use the following values as the basis for the decisions:
##0-4 hours of sleep- Sleep deprived!,
##more than 4 but less than 6- You need more sleep,
##6 or more but less than 8- Not quite enough,
##more than 8- Well Done!
userInput = input("Enter the number of hours of sleep you got the previous night:")
userInput = int(userInput) #Converts string to int for comparrasion ;-)
if userInput >= 0 and userInput <= 4:
print("Sleep deprived!")
elif userInput > 4 and userInput < 6:
print("You need more sleep")
elif userInput >= 6 and userInput < 8:
print("You need more sleep")
elif userInput > 8:
print("Well Done")
| true |
d42d87509e567f4917fdac8a420a0594a1bbfb89 | riteshrky/DAY-2 | /DAY 5.py | 2,966 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
def say_hello(name):
print("hello",name)
print ("how are you ")
# In[2]:
say_hello("Jam")
# In[3]:
# write a function to print sum of three numbers
def sum_of_num(x,y,z=10):#x,y are positional argumnets, and z is kerywords
print(x+y+z)
# In[4]:
sum_of_num(50,60)
# In[5]:
sum_of_num(50,60,40)#keywors assign value
# In[6]:
marks1=[50,70,88,95,75]
marks2=[40,90,60,55,80]
total=0
for i in marks1:
total=total+i
print(total)
total=0
for i in marks2:
total=total+i
print(total)
# In[10]:
def marks_sum(marks):
t1=0
for i in marks:
t1=t1+i
return(t1)
s=marks_sum(marks1)
print(s)
# In[11]:
s1=marks_sum(marks2)
print(s1)
# In[14]:
#Absoulte value
def abs_value(num):
if num<0:
return(-num)
else:
return(num)
a1=abs_value(-9)
print(a1)
# In[15]:
a2=abs_value(8)
print(a2)
# In[16]:
def name(n1,age=32):
print("hello i am {} and my age is {}".format(n1,age))
name("Rathi")
# In[17]:
name("Rathi",28)
# In[2]:
## Given a list, write a fn to calculate the sum of all even numbers and all odds numbers
lst1=[70,33,80,61,88,85,76,63,74,72]
def ev_od(lst):
ev_sum=0
od_sum=0
for i in lst:
if i%2==0:
ev_sum=ev_sum+i
else:
od_sum=od_sum+i
return(ev_sum,od_sum)
ev_od(lst1)
# In[7]:
lst1=[70,33,80,61,88,85,76,63,74,72]#
def eve_odd(lst):
if lst%2==0:# this thing not contain lists, ints
return "Even"
else:
return "odd"
s=eve_odd(55)
print(s)
# In[8]:
map(eve_odd,lst1)
# In[9]:
list(map(eve_odd,lst1))
# In[10]:
##Lamnda /anonymous function
def add(a,b):
s1=a+b
return s1
s=add(2,3)
print(s)
# In[15]:
s2=lambda a,b:a+b #lambda input and operation
s2(30,60)
# In[16]:
l1=[45,67,85]
l2=[34,56,98]
ad1=list(map(lambda x,y:x+y, l1,l2))
# In[17]:
print(ad1)
# In[18]:
ad2=map(lambda x,y:x+y,l1,l2)
print(ad2)
# In[19]:
print(list(ad2))
# In[20]:
## create 2 function to add (add_num())and multiply 2 numbers
#for addition
sum=lambda a,b:a+b
sum(45,36)
# In[23]:
#for multiplication
mul=lambda c,d:c*d
mul(4,5)
# In[8]:
##average of marks
###write a function to cal the average marks.
###write a function to cal the grade of the students based on avg marks (if,elif,else)
marks1=[70,50,97,66,99]
def avg_marks(marks):
s1=0
for i in marks:
s1=s1+i
avg=s1/len(marks)
if avg>=90:
Grade="Grade A"
elif avg>=80 and avg<=90:
Grade="Grade B"
elif avg>=70 and avg<=80:
Grade="Grade C"
else:
Grade="Grade D"
return (avg,Grade)
s1=avg_marks(marks1)
print(s1)
# In[12]:
ls=[]
for i in range(50):
if i%2==0:
ls.append(i)
print(ls)
# In[15]:
ls=[i for i in range(50) if i%3==0]
print(ls)
# In[ ]:
| false |
67371e37e8ffeb9588ff24f5249b0da36af0cf55 | wjingyuan/QuickStart | /Python开发入门14天集训营_练习题/02_19.py | 1,583 | 4.125 | 4 | '''
写代码,有如下元祖,请按照功能要求实现每一个功能。
tu = ('alex', 'eric', 'rain')
1. 计算元祖长度并输出
2. 获取元祖的第2个元素并输出
3. 获取元祖的第1-2个元素并输出
4. 请使用for输出元祖的元素
5. 请使用for、len、range输出元祖的索引
6. 请使用enumerate输出元祖元素和序号(序号从10开始)
'''
tu = ('alex', 'eric', 'rain')
print(tu)
# 1. 计算元祖长度并输出
print('第1题:计算元祖长度并输出')
length = len(tu)
print('元祖的长度为:%d \n' % length)
# 2. 获取元祖的第2个元素并输出
print('第2题:获取元祖的第2个元素并输出')
print('元祖的第2个元素为:%s \n' % tu[1])
# 3. 获取元祖的第1-2个元素并输出
print('第3题:获取元祖的第1-2个元素并输出')
answer = tu[:2]
print('元祖的第1-2个元素为:{} \n'.format(answer)) # 用%s代替tu[:2]为什么不行?因为切片后有2个元素。
# print('元祖的第1-2个元素为:%s%s \n' % answer)
# 4. 请使用for输出元祖的元素
print('第4题:请用for输出元祖的元素')
for i in tu:
print(i, end = ' ')
print()
# 5. 请使用for、len、range输出元祖的索引
print('第5题:请使用for、len、range输出元祖的索引')
for i in range(len(tu)):
print('%s的索引是:%d' % (tu[i], i))
# 6. 请使用enumerate输出元祖元素和序号(序号从10开始)
print('第6题:请使用enumerate输出元祖元素和序号(序号从10开始)')
for index, j in enumerate(tu):
print(index + 10, j) | false |
9ae5fe36a1421a9676dcd12a84348039f03a42e6 | juliandunne1234/benchmarking_g00267940 | /bubbleProject.py | 540 | 4.25 | 4 | def bubbleSort(arrays):
n = len(arrays)
for outer in range(n-1, 0, -1):
#inner loop runs one less time for each iteration to stay within loop boundaries
for inner in range(0, outer, 1):
#if the inner value is greater than value to the right then swap
if arrays[inner] > arrays[inner + 1]:
arrays[inner], arrays[inner + 1] = arrays[inner + 1], arrays[inner]
return
#Bubblesort algorithm code adapted from youtube video @ https://www.youtube.com/watch?v=g_xesqdQqvA&t=201s
| true |
3f1bd879d5b85a6d7f23b292eae0bf359697f047 | stayhungry-cn/-Python | /04 数据类型之数字.py | 1,218 | 4.34375 | 4 | #4.1 整型与浮点型
# (1) 整型:整数,包括正整数与负整数
a = 5
b = -5
# (2) 浮点型: 带小数点的数
c = 3.14
d = 0.618
# 4.2 算术运算符
# (1) 加 : +
#print(3+2)
# (2) 减 : -
#print(5-3)
# (3) 乘 : *
#print(6*3)
# (4) 除: /
#print(5/3)
# (5) 取模(取余数) : %
#print(5%2)
#print(97%3)
#print(4%2)
# (6) 取整(向下取整) //
#print(5//2)
#print(9//2)
# 4.3 str()、int()和float()函数
# (1) str():将括号里的内容转成字符串 来源: String
#print(2020)
#print("2020")
#print(str(2020))
#print('I am ' + 20 + 'years olds')
#print('I am ' + str(20) + ' years olds')
# (2) int():将括号的内容转成整型 来源:integer
#print(int("666"))
#print("666")
#print(333+"666")
#print(333+int("666"))
#print(int(33.33))
# (3) float():将括号的内容转成浮点型
#print(float("3.14"))
#print(float(3))
#print(float("3"))
# 4.4 input()函数
# 通过键盘输入,按下回车键后返回**字符串**
price_1 = input("Please enter the price of the book:")
price_2 = input()
total_price = price_1 + price_2
print(total_price)
total_price_ = int(price_1) + int(price_2)
print(total_price_) | false |
6fa110d87c9e35ff278d4ea190fbac15b85a2594 | Jay206-Programmer/Technical_Interview_Practice_Problems | /Uber/Count_Invalid_parenthesis.py | 581 | 4.5 | 4 |
#* Asked in Uber
#? You are given a string of parenthesis. Return the minimum number of parenthesis that would need to be removed
#? in order to make the string valid. "Valid" means that each open parenthesis has a matching closed parenthesis.
#! Example:
# "()())()"
#? The following input should return 1.
# ")"
def count_invalid_parenthesis(string):
count = 0
for i in string:
if i == "(" or i == "[" or i == "{":
count += 1
elif i == ")" or i == "]" or i == "}":
count -= 1
return abs(count)
print(count_invalid_parenthesis("()())()"))
# 1 | true |
5d7a2b7f00bc02d494f1c55d6eb3263d3022ddae | Mitterdini/Learning-The-Hard-Way | /Python/Scripts/string_formatting.py | 455 | 4.1875 | 4 | float = 12.5
inte = 6
strinly = "ight"
#the 3 ways of placing a variable in a string
print(f"float: {float} ; integer: {inte}; string: {strinly}") #method 1: using 'f' before the string
print("\n\nfloat: %f ; integer: %d; string: %s" % (float,inte,strinly)) #method 2: using '%' signs
words = "lets check multiple variables using .format\n{} {} {}" #method 3; using curly brackets and .format
print(words.format(float, inte, strinly))
| true |
6d96b0e936f1a8037f50b4a766a44b81fc82905e | Tarundatta-byte/PrintingShapes.py | /main.py | 1,393 | 4.3125 | 4 | import turtle
#this assigns colors to the design
#example: col=('red','blue','green','cyan','purple')
col=('red','blue','yellow','green')
#creating canvas
t=turtle.Turtle()
#here we are defining a screen and a background color with printing speed.
screen=turtle.Screen()
screen.bgcolor('black')
t.speed(50)
#this range gives number of lines for the design to be printed
#here i am printing 100 lines.
for i in range (100):
#{i%2 mentions the " number of lines i.e.,"i"}' % '{number of colors mentioned above in the 'col=('colors','colors',...)}".
#here i am taking 4 colors so i use 4 below.
t.color(col[i%4])
#this line states the space between each line of the patter printed.
t.forward(i*5)
#this line states the movement of the pattern i.e., from left-right or from right-left.
# here the value 240 prints a triangle so, replace (240) with the below values to print different patterns
t.right(240)
t.width(2)
# in t.right(240) u can replace the below values
# (180) to print a straight line like an interface of loading theme.
# (160)to print a star of 8 sides.
# (150)to print a star of 12 sides.
# (144) to print a star
# (120)to prit an inverted triangle.
# (90) or to print a square.
# (72)to print pentagon
# (60)to print hexagon
# (45)to print octagon
# give your values to print some other designs.
| true |
cdbd0ef66589e14f6999d45dab55b6ef9bdb9356 | NikhilCodes/DSA-Warehouse | /Algorithms/Sort/Bubble Sort/src.py | 512 | 4.25 | 4 | """
ALGORITHM : Bubble Sort
WORST CASE => {
PERFORMANCE: O(n^2)
SPACE: O(1)
}
"""
def bubble_sort(arr):
size = len(arr)
if size < 2:
return arr
for i in range(size-1, 0, -1):
for j in range(len(arr[:i])):
if arr[j] > arr[j+1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
if __name__ == '__main__':
array = [3, 7, 6, 5, 4, 8, 2, 1]
sorted_arr = bubble_sort(array)
print(sorted_arr)
| false |
df4658ae9d91eb1e7456a4d750081fa04f9f7b9b | WilAm1/Python-Beginner-Projects | /GuessTheNumber/main.py | 1,219 | 4.125 | 4 | """What’s My Number?
Between 1 and 1000, there is only 1 number that meets the following criteria:
The number has two or more digits.
The number is prime.
The number does NOT contain a 1 or 7 in it.
The sum of all of the digits is less than or equal to 10.
The first two digits add up to be odd.
The second to last digit is even and greater than 1.
The last digit is equal to how many digits are in the number.
"""
def isPrime(num):
"""Prime number is a natural number where the
factors are only one and itself."""
if type(num) != int:
return False
if num <=2:
return False
for n in range(3,int(num**.5+1 ),2):
if num % n == 0 :
return False
return True
for n in range(10,1001):
n_string = str(n)
if '1' in n_string or '7' in n_string:
continue
elif sum([int(digit) for digit in n_string]) > 10:
continue
elif ((int(n_string[0]) + int(n_string[1])) % 2 ==0):
continue
second = int(n_string[-2])
last = int(n_string[-1])
if isPrime(n):
if second %2 == 0 and second > 1:
if int(n_string[-1]) == len(n_string):
print(n)
| true |
d8e84e1b4c4222be341e3c4fdb54314272b62cf6 | semihPy/Class4-PythonModule-Week2 | /assignment1Week2.py | 2,676 | 4.25 | 4 | # 1.lucky numbers:
# Write a programme to generate the lucky numbers from the range(n).
# These are generated starting with the sequence s=[1,2,...,n].
# At the first pass, we remove every second element from the sequence, resulting in s2.
# At the second pass, we remove every third element from the sequence s2, resulting in s3,
# and we proceed in this way until no elements can be removed. The resulting sequence
# are the numbers lucky enough to have survived elimination.
# The following example describes the entire process for n=22:
# Original sequence: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
# Remove 2nd elements: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
# Remove 3rd elements: [1, 3, 7, 9, 13, 15, 19, 21]
# Remove 4th elements: [1, 3, 7, 13, 15, 19]
# Remove 5th elements: [1, 3, 7, 13, 19]
# We cannot remove every other 6th element as there is no 6th element.
# Input>>> 22
# Output>>> Lucky numbers are [1, 3, 7, 13, 19]
sequence = int(input("enter a number: ")) # user dan input aldim.
original_sequence = [i for i in range(1, sequence+1)] # 1 den baslayarak, input dahil sayilari listeledim.
print("Original sequence: ", original_sequence) # Original sequence
dummy_original = original_sequence # orijinal liseyi kopyasini olusturdum.(kukla ya atadim)
removed_element_index = 1 # ilk silinecek item lerin indexini(2.element) assign ettim.
while True: # else girerse while dongusunden cikar.
if len(original_sequence) > removed_element_index: # listenin len i silinecek ogenin index inden buyuk ise calis
j = removed_element_index # removed_element_index i j ye assign ettim.
for i in original_sequence: # ilgili liseyi for ile pass ettim.
if len(original_sequence) > j: # liste uzunlugu remove edilen item indexinden buyukse calisir
dummy_original.remove(dummy_original[j]) # ilgili index teki item i remove ettim.
original_sequence = dummy_original # kalan listeyi original listeye atadim.
j += removed_element_index # j yi silinecek elementin index degeri kadar artirdim.
print("Remove {}nd elements: ".format(removed_element_index + 1), original_sequence)
removed_element_index += 1
else:
removed_element_index += 1
print("there is no {}. element. we can not remove.".format(removed_element_index))
break
print("LUCKY numbers: ",original_sequence)
| true |
6393fe1c68f00f2c4e5dfb79d0b56ea80ca6d486 | nachonavarro/RSA | /rsa.py | 1,531 | 4.4375 | 4 | """
RSA is a public cryptosystem that relies on number theory.
It works for both encryption of messages as well as digital
signatures.
The main two functions to encrypt and decrypt a message.
For simplicity, we will assume that the message is already
transformed into a number ready for RSA.
It should be the case that
decrypt(encrypt(msg, public_key), private_key) == msg
"""
def encrypt(msg, public_key):
"""Encrypt the message using the public key.
In other words, given that msg is already a number,
compute msg ^ public_key.pub mod public_key.n
Args:
msg (int): Message to securely send.
public_key (namedtuple(PublicKey)): A namedtuple
consisting of two parameters, n and pub.
Returns:
int: The ciphered message as an int between 1 and n.
"""
return pow(msg, public_key.pub, public_key.n)
def decrypt(cipher, private_key):
"""Decrypt the message using the private key.
In other words, given the cipher C, compute
C ^ private_key.priv mod private_key.n.
By the discussion on keygen.py, Only you can decipher C, as
C ^ d = M ^ (ed) = M ^ (phi * k + 1) = M ^ (phi * k) * M
= 1 * M = M mod n. The key is that due to Euler's Theorem,
M ^ phi = 1 mod n.
Args:
msg (int): Message to securely send.
private_key (namedtuple(PrivateKey)): A namedtuple
consisting of two parameters, n and priv.
Returns:
int: The deciphered message as an int between 1 and n.
"""
return pow(cipher, private_key.priv, private_key.n) | true |
03317e6ab31f0821ececa4b0d41189df166162ee | RyanGoh83/flask-blog | /sql.py | 710 | 4.125 | 4 | # sql.py- Script to create db and populate with data
import sqlite3
#creates a new db if it doesn't already exist
with sqlite3.connect("blog.db") as connection:
#get a cursor obj used to execute SQL commands
c = connection.cursor()
#create the table
c.execute("""CREATE TABLE posts (title TEXT, post TEXT)""")
#insert some dummies into TABLE
c.execute('INSERT INTO posts VALUES("Good", "I\'m good.")')
c.execute('INSERT INTO posts VALUES("Well", "I\'m well.")')
c.execute('INSERT INTO posts VALUES("Excellent", "I\'m excellent.")')
c.execute('INSERT INTO posts VALUES("Okay", "I\'m okay.")')
c.execute('INSERT INTO posts VALUES("Awesome", "I\'m awesome.")')
| true |
5ed05b14f3c0e05310101ac1f181cb5276ccad4c | paulngouchet/AlgoChallenge | /reverse.py | 807 | 4.125 | 4 |
''' Input: 123
Output: 321
Input: -123
Output: -321
Input: 120
Output: 21
to reverse
do abs to find abs value
convert integer to string
loop through list of characters backward - append in new string
convert to number
do number * initial_number/abs_number'''
def reverse(initial):
if initial == 0 or (initial < -2**31) or initial > (2**31 - 1) :
return 0
abs_initial = abs(initial)
str_initial = list(str(abs_initial))
str_final = ""
#print(len(str_initial)-1)
size = len(str_initial)-1
for i in range(size, -1, -1):
str_final += str_initial[i]
abs_final = int(str_final)
if abs_final < -2**31 or abs_final > (2**31 - 1):
return 0
return int(abs_final * (1.0 * initial / abs_initial))
print(reverse(120))
| true |
b5eccdaa43cde7a48a423ec1667f553d6cc3320f | centos-zhb/PythonPractice | /字符串/Teststring.py | 766 | 4.15625 | 4 | # 0、a,b为参数。从字符串指针为a的地方开始截取字符,到b的前一个位置(因为不包含b)
var1 = "hello world"
print(var1)
# 1、如果a,b均不填写,默认取全部字符。即,下面这两个打印结果是一样的
print(var1[: ]) # hello world
print(var1) # hello world
# 2、如果a填写,b不填写(或填写的值大于指针下标),默认从a开始截取,至字符串最后一个位置
print(var1[3: ]) # lo world
# 3、如果a不填写, b填写,默认从0位置开始截取,至b的前一个位置
print(var1[: 8]) # hello wo
# 4、如果a为负数,默认从尾部某一位置,开始向后截取
print(var1[-2: ]) # ld
# 5、如果a>=b, 默认输出为空。
print(var1[3: 3])
print(var1[3: 2]) | false |
b565ba88ac04a611d00e8b8c8746da09a1b14b66 | nakuyabridget/pythonwork | /docstrings.py | 802 | 4.21875 | 4 | def print_max(x, y):
'''prints the maximum of two numbers.
The two values must be integers.'''
#conver to integers, if possible
x = int(x)
y = int(y)
if x > y:
print(x, 'is maximum')
else:
print(y, 'is maximum')
print_max(3,5)
print(print_max.__doc__)
#Autor: Nakuya bridget, a young aspiring software engineer
#The return statement is used to return from a function i.e break out of the function.We can optionally return a value from the function as well.
#The output of this code 3 but when l try running it from the command prompt, it doesnt show any erros or even any indication that the file is not found or anything like that
#YET it doesnt show me any output still...this is not the first time this happenned, it has happennd for a couple of other times, dunno waht cd be wromg really!
| true |
fcd6a113f571de3429020150f1003dfc4a9f73ff | Hadirback/python_algorithms_and_data_structures | /homework_3_pads/task_7.py | 846 | 4.125 | 4 | '''
7. В одномерном массиве целых чисел определить два наименьших элемента.
Они могут быть как равны между собой (оба минимальны), так и различаться.
'''
import random
start = 0
end = 10
num_array = [random.randint(start, end) for _ in range(5)]
first_min_value = end
second_min_value = end
for num in num_array:
if first_min_value == num:
second_min_value = num
if first_min_value > num:
second_min_value = first_min_value
first_min_value = num
elif second_min_value > num:
second_min_value = num
print(num_array)
print(f"Первый минимальный элемент - {first_min_value}")
print(f"Второй минимальный элемент - {second_min_value}") | false |
de1424f155303ecd939704f73098f122dfe7a366 | Hadirback/python_algorithms_and_data_structures | /homework_1_pads/task_8_python.py | 487 | 4.21875 | 4 | '''
8. Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого).
'''
a = int(input('Введите 1 число: '))
b = int(input('Введите 2 число: '))
c = int(input('Введите 3 число: '))
mid_value = None
if b < a < c or c < a < b:
mid_value = a
elif a < b < c or c < b < a:
mid_value = b
else:
mid_value = c
print(mid_value) | false |
ca6476ab024b7003fcbc0b7180b38437fc4e7388 | shwarma01/Projects | /Dynamic Programming/Memoization/Fibonacci/main.py | 628 | 4.15625 | 4 | """
Calculate nth fibonacci number using recursion
"""
# Brute force method
def fib(n):
if n == 1 or n == 2:
return 1
return fib(n - 1) + fib(n - 2)
print("Brute force method")
print(fib(3))
print(fib(5))
print(fib(7))
# print(fib(100)) # Takes too long
# Memoization method
def fib(n):
memo = {}
def helper(n):
if n == 1 or n == 2:
return 1
if n in memo:
return memo[n]
memo[n] = helper(n - 1) + helper(n - 2)
return memo[n]
return helper(n)
print("\nMemoization method")
print(fib(3))
print(fib(5))
print(fib(7))
print(fib(100))
| false |
f6c3d01cca78c2fcd4d5841d712e4d1773d6da4b | vadlamsa/book_practice | /8_5.py | 553 | 4.40625 | 4 | Write a function which removes all punctuation from the string, breaks the string into a list of words, and counts the number of words in your text that contain the letter “e”.
import string
def remove_punct(s):
s_without_punct=""
print(string.punctuation)
for letter in s:
if letter not in string.punctuation:
s_without_punct=s_without_punct+letter
return s_without_punct
wds=remove_punct('Hello!How are you doing?').split()
cnt=0
for i in wds:
print(i)
if 'e' in i:
cnt=cnt+1
print(cnt)
| true |
e3a0fadad25c29f8d93f0985d137aef083add085 | ZhangYajun12138/unittest | /work_hard/ex40.py | 488 | 4.1875 | 4 | # coding:utf-8
# 40.字典
cities = {"CA":"Francisco","MI":"Detroit","FL":"Jacksonville"}
cities["NY"] = "New York"
cities["OR"] = "Portland"
def find_city(themap,state):
if state in themap:
return themap[state]
else:
return "Not found."
cities["_find"] = find_city
while True:
print("State?(ENTER to quit)")
state = input("> ")
if not state:
break
else:
pass
city_found = cities["_find"](cities,state)
print(city_found) | false |
c6adeec162ad6951525a469599a89f78777caad7 | cklwblove/python-100-days-source-code | /ls5/demo2.py | 331 | 4.28125 | 4 | """
可变参数函数定义
"""
# 在参数名前面的*表示args是一个可变参数
# 即在调用 add 函数时,可以传入 0 个或多个参数
def add(*args):
total = 0
for val in args:
total += val
return total
print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
| false |
d8ece86d297203d15d4eb5dc2d13679142d3c8b3 | DK2K00/100DaysOfCode | /d16_string_reversal.py | 248 | 4.375 | 4 | #Function to reverse string using recursion
def reverse(s):
#To determine length of string
length = len(s)
if(length <= 1):
return(s)
#Recursion
return(s[length-1] + reverse(s[0:length-1]))
reverse("helloworld")
| true |
d6bc4d7b875d10e316da2c8ceecc15266b0e0873 | DK2K00/100DaysOfCode | /d28_quick_sort.py | 855 | 4.15625 | 4 | #Function to perform quick sort
def quick_sort(arr):
sort_help(arr,0,len(arr)-1)
def sort_help(arr,first,last):
if(first < last):
splitpt = partition(arr,first,last)
sort_help(arr,first,splitpt-1)
sort_help(arr,splitpt+1,last)
def partition(arr,first,last):
pivot = arr[first]
left = first+1
right = last
done = False
while(not done):
while(left <= right and arr[left] <= pivot):
left += 1
while(right >= left and arr[right] >= pivot):
right -= 1
if(right < left):
done = True
else:
temp = arr[left]
arr[left] = arr[right]
arr[right] = temp
temp = arr[first]
arr[first] = arr[right]
arr[right] = temp
return(right)
#Testing
arr = [2,1,7,4,5,6,3]
quick_sort(arr)
print(arr) | true |
e3ee965a1e35069eaa7b73ce79a2a324fe3ff381 | kesarb/leetcode-summary-python | /practice/a/min_cost_to_connect_ropes.py | 1,786 | 4.125 | 4 | """ Min Cost to Connect Ropes
https://leetcode.com/problems/minimum-cost-to-connect-sticks (premium)
Given n ropes of different lengths, we need to connect these ropes into one rope.
We can connect only 2 ropes at a time. The cost required to connect 2 ropes is
equal to sum of their lengths. The length of this connected rope is also equal
to the sum of their lengths. This process is repeated until n ropes are connected
into a single rope. Find the min possible cost required to connect all ropes.
Author: Weikun Han <weikunhan@g.ucla.edu>
Reference: https://leetcode.com/discuss/interview-question/344677
Time complexity: O(nlogn)
Space complexity: O(n)
Example 1:
Input:
ropes = [8, 4, 6, 12]
Output:
58
Explanation: The optimal way to connect ropes is as follows
1. Connect the ropes of length 4 and 6 (cost is 10). Ropes after connecting: [8, 10, 12]
2. Connect the ropes of length 8 and 10 (cost is 18). Ropes after connecting: [18, 12]
3. Connect the ropes of length 18 and 12 (cost is 30).
Total cost to connect the ropes is 10 + 18 + 30 = 58
Example 2:
Input:
ropes = [20, 4, 8, 2]
Output:
54
Example 3:
Input:
ropes = [1, 2, 5, 10, 35, 89]
Output:
224
"""
import heapq
class Solution(object):
def min_cost_to_conneect_ropes(self, ropes):
"""
:type ropes: List[int]
:rtype: int
"""
value_pq = ropes
heapq.heapify(value_pq)
res = 0
while len(value_pq) > 1:
temp_value = heapq.heappop(value_pq) + heapq.heappop(value_pq)
res += temp_value
heapq.heappush(value_pq, temp_value)
return res
def main():
ropes = [8, 4, 6, 12]
solution = Solution()
res = solution.min_cost_to_conneect_ropes(ropes)
print(res)
if __name__ == "__main__":
main() | true |
a6537888abbcc6264728190fc6f35619dce2c5fb | kesarb/leetcode-summary-python | /practice/solution/0380_insert_delete_getrandom_o1.py | 1,597 | 4.1875 | 4 | import random
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.value_list = []
self.value_dict = {}
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if not val in self.value_dict:
self.value_list.append(val)
self.value_dict[val] = len(self.value_list) - 1
return True
return False
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val in self.value_dict:
index_value = self.value_dict[val]
self.value_list[index_value] = self.value_list[-1]
self.value_dict[self.value_list[-1]] = index_value
self.value_list.pop()
self.value_dict.pop(val)
return True
return False
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
temp_value = self.value_list[random.randint(0, len(self.value_list) - 1)]
return temp_value
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom() | true |
9d3b7d788120939cdb2f03fa05f60232d4ccbe23 | sideris/putils | /python/putils/general.py | 1,267 | 4.34375 | 4 | import collections
from math import factorial
def binomial_coefficient(n, m):
"""
The binomial coefficient of any two numbers. n must always be larger than m
:param n: Upper coefficient
:param m: Lower coefficient
:returns The number of combinations
:rtype integer
"""
assert n > m
return factorial(n) / factorial(m) / factorial(n - m)
def value_units(value):
"""
Accepts a number and returns it in a named tuple that contains the number converted in
appropriate units and the unit symbol(e.g. 3214 turns to (3.214, K))
:param value: The number to be evaluated
:returns named tuple with number - unit symbol pair
:rtype namedtuple(number, unit)
"""
result = collections.namedtuple('value_units', ['value', 'unit'])
suffix = ''
suffixes = ['', 'K', 'M', 'B', 'T', 'Q']
scale = 1.0e3
for i in xrange(len(suffixes)):
if abs(value) < scale:
return result(value, suffix[i])
value /= scale
scale *= 1.0e3
def days_in_year(year):
"""
Given a year, return how many days are in that year
:param year: The year in question
:returns Number of days in the year
:rtype Integer
"""
start = datetime.date(year, 1, 1)
end = datetime.date(year, 12, 31)
return (end - start).days + 1
| true |
105602746fbb314cf0a7f8864fabc64e1822ab05 | Zaela24/CharacterCreator | /Gear/MiscItems/Items.py | 959 | 4.28125 | 4 | class Items:
"""Creates general class to contain miscelaneous items"""
def __init__(self):
self.name = "" # name of item
self.description = "" # description of item
self.price = 0 # assumed in gold piece
self.weight = 0
## THE FOLLOWING IS A DANGEROUS METHOD AND THUS HAS A PRIVATE ACCESSOR
## HOW TO USE:
## Say you initialize an item as my_item (i.e. my_item = Items())
## instead of accessing this method as my_item.__set_attr(x, y),
## you MUST write it as my_item._Items__set_attr(x, y), otherwise you
## will get an error saying the method does not exist.
def __set_attr(self, attr_name, attr_value):
"""
Takes a string attr_name, and any value you'd like for attr_value.
Sets a new custom attribute for the instance of this object:
i.e. <variable_name>.<attr_name> = <attr_value>
"""
setattr(self, attr_name, attr_value)
| true |
d0b342dd97167f07e2d39c6ff9fd68aa960890cf | luiscape/hdxscraper-wfp-mvam | /collector/utilities/item.py | 828 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
ITEM:
-----
Utility designed to print pretty things to the
standard output. It consists of a dictionary
that is called as a function with a key. A
string is then returned that helps format
terminal output.
'''
from termcolor import colored as color
def item(key='bullet'):
'''
Looks for a formatting string in a dictionary.
Parameters:
----------
A string among the ones available in the function:
- bullet
- warn
- error
- success
Returns:
-------
A byte object.
'''
dictionary = {
'bullet': color(u' →', 'blue', attrs=['bold']),
'warn': color(u' WARN:', 'yellow', attrs=['bold']),
'error': color(u' ERROR:', 'red', attrs=['bold']),
'success': color(u' SUCCESS:', 'green', attrs=['bold'])
}
return dictionary[key]
| true |
39beb68ff4681ae4037796c2bc7f60dc9db1e0a7 | Delmastro/Cryptography | /decryptAffine.py | 1,373 | 4.125 | 4 | def decrypt_affine(a, b, ciphertext):
"""Function which will decrypt an affine cipher.
Parameters:
a (int): A random integer given by "a" between 0 and the length of the alphabet
b (int) : A random integer given by "b" between 0 and the length of the alphabet
ciphertext (str): The given cipher which we want to decrypt.
Return:
decrypted_string (str): If the inverse exists, then a string with be."""
decrypted_string = ""
inverse = find_inverse(a, len(alpha))
if inverse == None:
return None
for character in ciphertext:
decrypted_character = (inverse*(char_to_int(character) - b)) % len(alpha)
decrypted_string += (int_to_char(decrypted_character))
return decrypted_string
def int_to_char(i):
return alpha[i]
def char_to_int(c):
return alpha.index(c)
def force_affine():
ciphertext = "UJGCKCXJYLJGYPJEJGOVOILKGVYPVYWOJBCASJOJVYXRCJ".lower()
for a in range(0, len(alpha)):
for b in range(0, len(alpha)):
plaintext = decrypt_affine(a,b, ciphertext)
if plaintext != None and plaintext[0:2] == "it":
return plaintext
def find_inverse(a, m):
for x in range(0, m):
if a*x %m == 1:
return x
def main():
print(force_affine())
main()
| true |
bf379b22b2da3257d520c2bbd1d9ead801bee46b | kaixiang1992/python-learning | /codes/26-tuple_demo.py | 2,657 | 4.25 | 4 | '''
@description 2019/09/11 22:53
'''
# 什么是元祖:
# 元祖的使用与列表相似。不同之处在于元祖是不可修改的,元祖使用圆括号,而列表使用中括号。
# 定义元祖
# 1.使用逗号的方法:
# a_tuple = 1,2,3
# print(a_tuple) # (1, 2, 3)
# print(type(a_tuple)) # tuple
# 2.使用圆括号的方式
# a_tuple = (1,2,3)
# print(a_tuple) # (1, 2, 3)
# print(type(a_tuple)) # tuple
# 3.使用tuple函数
# list => tuple
# a_list = [1,2,3]
# a_tuple = tuple(a_list)
# print(a_tuple) # (1, 2, 3)
# print(type(a_tuple)) # tuple
# 4.定义只有一个元素的元祖
# a_tuple = 12,
# b_tuple = (13,)
# print(a_tuple) # (12,)
# print(type(a_tuple)) # tuple
# print(b_tuple) # (13,)
# print(type(b_tuple)) # tuple
'''
@description 2019/09/11 23:26
'''
# 1.下标操作
# a_tuple = ('a','b','c')
# a = a_tuple[0]
# print(a) # a
# 2.切片操作:跟列表和字符串的切片操作一样。
# a_tuple = ('zhiliao',18,'python')
# reverse_a_tuple = a_tuple[::-1]
# print(reverse_a_tuple) # ('python', 18, 'zhiliao')
# 3.解组操作:
# 注意事项:有些时候我们只想要元祖中的某个值,不需要所有的值,那么我们通过_来作为省略
# 和`JavaScript解构赋值`类似
# a_tuple = ('zhiliao',18,'python')
# username = a_tuple[0]
# userage = a_tuple[1]
# classname = a_tuple[2]
# username,userage,classname = a_tuple
# print(username) # zhiliao
# print(userage) # 18
# print(classname) # python
# a_tuple = ('zhiliao',18,'长沙')
# ValueError:too many values to unpack (expected 2),未使用_匿名赋值
# username,userage = a_tuple
# username,userage,_ = a_tuple
# print(username) # zhiliao
# print(userage) # 18
# 4. count方法:获取元素中某个值出现的次数,和列表中的用法相同。
# a_tuple = ('zhiliao',18,'长沙')
# result = a_tuple.count('长沙') # 1
# result = a_tuple.count('杭州') # 0
# print(result)
# 5.index方法:获取元祖中某个值的下标,和列表中的用法相同。获取不到抛出异常
a_tuple = ('zhiliao',18,'长沙')
position = a_tuple.index('长沙') # 2
# ValueError:tuple.index(x): x not in tuple
# position = a_tuple.index('西湖')
print(position) # 2
# 元祖存在的意义和应用场景:
# 1.元祖在字典中可以当做key来使用,而列表是不可以的。
# 2.在函数中有时候要返回多个值,一般采用元祖的方式。
def response():
return 'zhiliao',18,'长沙'
response_data = response()
print(response_data) # ('zhiliao', 18, '长沙')
print(type(response_data)) # tuple
# 3.在一些不希望用户修改值的场景下使用元祖来代替列表。 | false |
a78ee6d38a07bdaa1a66dc000a39bbbc144b346e | amalageorge/LearnPython | /exercises/ex16.py | 637 | 4.125 | 4 | from sys import argv
script, filename = argv
print "we are going to erase %r" %filename
print "if u dont want that hit CTRL-C(^C)"
print "if u do want that, hit RETURN"
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye"
target.truncate()
print "Now i'm going to ask u for three lines"
line1 = raw_input("line 1:")
line2 = raw_input("line2:")
line3 = raw_input("line3")
print "i'm going to write these to the files"
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "And finally we close it"
target.close()
| true |
cb26fd3648f924a405f910dd8a846b650001d79c | kumailn/Algorithms | /Python/Reverse_Only_Letters.py | 1,002 | 4.21875 | 4 | #Question: Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
#Solution: Remove all non letter chars and then reverse string, then traverse original string inserting non letter chars back into original indexes
#Time Complexity: O(n)
def reverseOnlyLetters(S):
"""
:type S: str
:rtype: str
"""
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
#Construct a new list consisting of ONLY the letters in S and reverse it
s2 = [letter for letter in S if letter in alphabet][::-1]
#Loop through S and insert non letters into s2
for i, letter in enumerate(S):
if letter not in alphabet: s2.insert(i, letter)
return ''.join(s2)
def main():
#Should be "Qedo1ct-eeLg=ntse-T!"
print(reverseOnlyLetters("Test1ng-Leet=code-Q!"))
main() | true |
f024a120ea0b7d5d54cb63c1b7b50e960a88b9cf | kumailn/Algorithms | /Python/Merge_Linked_List.py | 1,024 | 4.28125 | 4 | from _DATATYPES import ListNode
#Question: Given two sorted linked lists, join them
#Solution: Traverse through both lists, swapping values to find smallest, then working backwards
#Difficulty: Easy
def mergeList(a, b):
#If the first node is null, or the second node exists and is smaller than the first node, swap the two nodes
#This ensures that a is always the smallest non null node
if not a or b and a.val > b.val: a, b = b, a
#If a is not null, then let its next value be a recursive call to its next value, and b (the smaller nodes next value will become the smaller of its current next value, or the other lists current value)
if a: a.next = mergeList(a.next, b)
#Return a's head as we never shifted a in this scope, only in subsequent recursive calls
return a
def main():
a = ListNode(4)
a.next = ListNode(23)
a.next.next = ListNode(44)
b = ListNode(5)
b.next = ListNode(11)
b.next.next = ListNode(14)
mergeList(b, a)
print(a.printList())
main() | true |
90a09a889737795e14a2fdf6def2b8e1732e3e01 | 0siris7/LP3THW | /swap.py | 324 | 4.125 | 4 | def swap_case(s):
a = list(s)
b = []
for i in a:
if i.isupper():
b.append(i.lower())
elif i.islower():
b.append(i.upper())
return(''.join(b))
if __name__ == '__main__':
s = input("Enter the string: ")
result = swap_case(s)
print(f"The result: {result}")
| true |
532fb9eb334f2b0876775bf002cde6ac8c69bc75 | r6047736/UAPython | /root/a5tests/students/lmzbonack-assignment-5/puter-1.py | 1,826 | 4.125 | 4 | #
# Author: Luc Zbonack
# Description:
# This is a simple version of a question/answer AI. It takes question in through standard input and prints out answers
# through standard output. The AI will exit after 10 questions or it will exit when the user tells it to. At this time the
# AI only responds to certain inputs.
#
import sys
from datetime import datetime
print ("PUTER: Hello and welcome! Ask me no more than 10 questions.")
# Declare counters for total questions and to keep track of color preference
questions = 1
color_count = 0
# Use while loop to track number of questions asked
while (questions <= 10):
print ("PUTER: Go ahead, ask me something:")
user_input = sys.stdin.readline().rstrip()
if (user_input == "how are you?" or user_input == "how goes it?"):
print ("PUTER: I am a computer program, so obviously I am excellent!")
elif (user_input == "what is your birthday?"):
print ("PUTER: I am a computer program! I don't have a birthday :-(")
elif (user_input == "what is your favorite color?"):
if (color_count % 3 == 0):
print("PUTER: red!")
color_count += 1
elif (color_count % 3 == 1):
print("PUTER: blue!")
color_count += 1
elif (color_count % 3 == 2):
print("PUTER: green!")
color_count += 1
elif (user_input == "what time is it?" or user_input == "what is the date?"):
print("PUTER: The current date/time is " + str(datetime.now()))
elif (user_input == "exit"):
print ("PUTER: Bye!")
sys.exit()
else:
print("PUTER: Sorry, I can't understand you!")
questions +=1
print ("PUTER: Question limit reached. Bye!")
sys.exit()
| true |
4efe57cc938192a12b13c5e90bd27ea8962545d5 | r6047736/UAPython | /root/a5tests/students/pwilkeni-assignment-5/puter-1.py | 1,456 | 4.15625 | 4 | #!/usr/bin/env python
#
# Author: Patrick Wilkening
# Description:
# a puter program that can answer some basic questions
# (up to 10 questions) before exiting.
#
import sys
import datetime
qCount = 0
color = 0
manual_exit = False
# Questions PUTER will answer
Q1 = "how are you?"
Q2 = "how goes it?"
Q3 = "what is your birthday?"
Q4 = "what is your favorite color?"
Q5 = "what time is it?"
Q6 = "what is the date?"
# get these questions wrong you are thrown off the bridge of death
print("PUTER: Hello and welcome! Ask me no more than 10 questions.")
print("PUTER: Go ahead, ask me something:")
while qCount < 10:
user_input = sys.stdin.readline().rstrip()
if user_input == Q1 or user_input == Q2:
print("PUTER: I am a computer program, so obviously I am excellent!")
elif user_input == Q3:
print("PUTER: I am a computer program! I don't have a birthday :-(")
elif user_input == Q4:
if (color % 3) == 0:
print("PUTER: red!")
elif (color % 3) == 1:
print("PUTER: blue!")
else:
print("PUTER: green!")
color += 1
elif user_input == Q5 or user_input == Q6:
time = str(datetime.datetime.now())
print ("PUTER: The current date/time is " + time)
elif user_input == "exit":
print ("PUTER: Bye!")
manual_exit = True
break
else:
print ("PUTER: Sorry, I can't understand you!")
qCount += 1
if qCount < 10:
print("PUTER: Go ahead, ask me something:")
if not manual_exit:
print("PUTER: Question limit reached. Bye!")
exit()
| true |
c3c5099c4c4e283bbf0d0046ea4f5eee939747c4 | Rohan506/Intership-task0 | /6th Question.py | 904 | 4.3125 | 4 | #Write a python program to print the Fibonacci series and
#also check if a given input number is Fibonacci number or not.
def fib(n):
a=0
b=1
if n==1:
print(a)
else:
print(a)
print(b)
for i in range(2,n):
c=a+b
a=b
b=c
print(c)
n=int(input("Enter a number"))
fib(n)
#Checking a number whether it is fibonacci or not
import math
def checkPerfectSquare(n):
sqrt = int(math.sqrt(n))
if pow(sqrt, 2) == n:
return True
else:
return False
def isFibonacciNumber(n):
res1 = 5*n*n+4
res2 = 5*n*n-4
if checkPerfectSquare(res1) or checkPerfectSquare(res2):
return True
else:
return False
num = int(input("Enter an integer number: "))
if isFibonacciNumber(num):
print (num, "is a Fibonacci number")
else:
print (num, "is not a Fibonacci number")
| true |
58e41f38f598ba54cacc09cceaa1b3d4ca241c42 | Rutuja-haridas1996/Basic-python-problems | /sphere_volume.py | 388 | 4.25 | 4 | '''
Problem Statement:
Write a function that computes the volume of a sphere when passed the radius.
Use an assert statement to test the function.
'''
def sphere_volume(radius):
try:
assert isinstance(radius,int) or isinstance(radius,float)
return ((4/3)*(3.14))*(radius**3)
except AssertionError as ae:
return 'Invalid radius'
print(sphere_volume(63)) | true |
f951d79de2d71ab3f3748e5fb15daae60e2aaf93 | Brijesh1990/python-core-adv-framwork | /string/string_operator.py | 602 | 4.125 | 4 | #operators in string
#concatenate oeprator +
# name="brijesh"
# name1="parth"
# name3="jinesh"
# print(name+" "+name1+name3)
# new line \n
# name="brijesh"
# name1="parth"
# name3="jinesh"
# print(name+"\n"+name1+"\n"+name3)
#\\ backslash
# name="brijesh"
# name1="rajesh"
# print(name+"\\"+name1)
# name="c:\\programme\\python"
# print(name)
# name11="brijesh"
# print("\\"+name11)
# name="Brijesh kumar pandey"
# print(r"name\\")
qty=2
price=255.50
pname="samsung"
print("product name is : %s\n product price is : %f product qty is : %d" %(pname,price,qty))
| false |
ebb97404d93a3f987ef0dfe68f6acf43950f5d3c | cafpereira/python-crash-course | /chapter10/exceptions.py | 1,328 | 4.25 | 4 | try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
# print("Give me two numbers, and I'll divide them.")
# print("Enter 'q' to quit.")
#
# while True:
# first_number = input("\nFirst number: ")
# if first_number == 'q':
# break
# second_number = input("Second number: ")
# try:
# answer = int(first_number) / int(second_number)
# except ZeroDivisionError:
# print("You can't divide by 0!")
# else:
# print(answer)
filename = 'alice_not_found.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
title = "Alice in Wonderland"
print(title.split())
def count_words(filename):
"""Count the approximate number of words in a file."""
try:
with open(filename, encoding='utf-8') as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass
else:
# Count approximate number of words in the file.
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
filenames = ['alice.txt', 'moby_dick.txt', 'missing_file.txt']
for filename in filenames:
count_words(filename)
| true |
af8c6cc19a947764e43fff904e154627ef2aaf83 | minyun168/programing_practice | /practice_of_python/formatted_name.py | 558 | 4.125 | 4 |
def formatted_name(first_name, last_name, middle_name = ""): #when we use default value just like middle_name="", we should make sure middle_name is the last variable when we define function
"""return formatted name""" # middle_name = "" not middle = " "
if middle_name:
full_name = first_name + " " + middle_name + " " + last_name
else:
full_name = first_name + " " + last_name
return full_name.title()
musician = formatted_name("sheeli", "arki", "habarum")
print (musician)
artist = formatted_name("shor", "ka")
print (artist)
| true |
c17615c48fb2c2c603b7a272fd7d46090f894af2 | LipsaJ/PythonPrograms | /X003PythonList/List.py | 744 | 4.375 | 4 | parrot_list = ["Blue", "Green", "Very beautiful", "is annoying"]
parrot_list.append("Red at the beak")
for state in parrot_list:
print("Parrot is " + state)
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
numbers = even + odd
# numbers.sort is a method which applies on the object it never creates it
# Below are two ways to sort but look at them carefully
# numbers.sort() #this has changed the actual object
# print(numbers)
# see the difference below if you run print(numbers.sort()),o/p is none
# print(numbers.sort())
print(sorted(numbers)) # this sorted(numbers)) create a new list
sorted_numbers_list = sorted(numbers)
print(sorted_numbers_list == numbers)
print(sorted_numbers_list == sorted(numbers))
| true |
3005c9e712bf8e6d187e95677d3cd2109a889e2a | LipsaJ/PythonPrograms | /X011dFunctions/functionsAsPrint.py | 1,104 | 4.125 | 4 | def python_food():
width = 80
text = "Spams and Eggs"
left_margin = (width - len(text)) // 2
print(" " * left_margin, text)
def centre_text(*args, sep=' ', end= '\n', file=None, flush=False):
text = ''
for arg in args:
text += str(arg) + sep
left_margin = (80 - len(text)) // 2
print(" " * left_margin, text, end=end, file=file, flush=flush)
# call the function
python_food()
# to create a file with output
with open("centered", mode='w') as centered_file: # see the first code to check output normally functions code
centre_text("Spams and eggs", file=centered_file)
# argument is the value which we pass to function in this example spams and eggs
centre_text("Spams and eggs and eggs", file=centered_file) # parameter is general term like text
centre_text(12, file=centered_file) # thats why we have added line two in the function we are converting to string
centre_text("Spams and spam and spam and eggs", file=centered_file)
centre_text("first", "Second", 3, 4, "V", sep=':', file=centered_file)
| true |
810b7962e5883f95abba2813b6e68ab41fe032c0 | LipsaJ/PythonPrograms | /createDB/contacts3.py | 488 | 4.1875 | 4 | import sqlite3
db = sqlite3.connect("contacts.sqlite")
name = input("Please enter the name: ")
#
# select_sql = "SELECT * FROM contacts WHERE name = ?"
# select_cursor = db.cursor() # we have used the cursor to update so that we can see how many rows were updated
# select_cursor.execute(select_sql, name)
# print("{} rows got selected".format(select_cursor.rowcount))
for rows in db.execute("SELECT * FROM contacts WHERE name = ?", (name,)):
print(rows)
db.close()
| true |
507100b7c21da627444ca046d13603ac64bb8b94 | Ashma-Garg/Python | /decoraterAndSortedFunction.py | 1,622 | 4.21875 | 4 | import operator
def person_lister(f):
def inner(people):
# people.sort(key=lambda x:x[2])
# sorted(people,key=lambda x:x[2])
#{sorted function can not be implemented directly on function because functions are not iterable.
#To iterate through functions we use map function.
#So if you want to use sort on functions then first use map and then sort}
return map(f, sorted(people, key=lambda x: int(x[2])))
#dont forget to use int before x[2] otherwise it will consider it as string and all cases wont pass as expected.
return res
return inner
# here @person_lister is a decorater which actually means:
# name_format=person_lister(name_format)
#whenever name_format will be called form main file then person_lister will be called which will have name_format as an its arguement.
#inner function will return to person_lister and person_lister will return to name_format
@person_lister
def name_format(person):
return ("Mr. " if person[3] == "M" else "Ms. ") + person[0] + " " + person[1]
if __name__ == '__main__':
people = [raw_input().split() for i in range(int(raw_input()))]
#above line means:
# for i in range(int(raw_input())):
# people[i]=raw_input().split()
#people will be:
#people=[[1,2,3],[4,5,6]]
#if it would have been people = raw_input().split() for i in range(int(raw_input()))
# then people would have been [1,2,3,4,5,6]
#conclusion: [] creates list on the right hand side of equation and returns list into the lsit present at left side of equation
print '\n'.join(name_format(people))
| true |
bd34d57a1a7d43d24d1c35a4479ef1f331f29e4f | Ashma-Garg/Python | /listSortingOnTheBssisOfIndexing.py | 1,791 | 4.3125 | 4 | # You are given a spreadsheet that contains a list of N athletes and their details (such as age, height, weight and so on). You are required to sort the data based on the Kth attribute and print the final resulting table. Follow the example given below for better understanding.
# Note that K is indexed from ) to M-1, where is the number of attributes.
# Note: If two attributes are the same for different rows, for example, if two atheletes are of the same age, print the row that appeared first in the input.
# Input Format
# The first line contains N and M separated by a space.
# The next N lines each contain M elements.
# The last line contains K.
# Output Format
# Print the N lines of the sorted table. Each line should contain the space separated elements. Check the sample below for clarity.
# Sample Input 0
#
# 5 3
# 10 2 5
# 7 1 0
# 9 9 9
# 1 23 12
# 6 5 9
# 1
# Sample Output 0
#
# 7 1 0
# 10 2 5
# 6 5 9
# 9 9 9
# 1 23 12
# Explanation 0
#
# The details are sorted based on the second attribute, since K is zero-indexed.
import math
import os
import random
import re
import sys
if __name__ == '__main__':
nm = input().split()
n = int(nm[0])
m = int(nm[1])
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
k = int(input())
lst=sorted(arr,key=lambda x:int(x[k]))
for l in lst:
#here print statement means print(*l,sep=' ') that means seperate the output by space. and Pointer l means ever element of l i.e. l[i]
#here for ex lst=[[7,1,0],[10,3,4],[3,7,9]]
#than output will be
#7 1 0
#10 3 4
#3 7 9
#if print state would be print(l,sep='/ ') then result would be
#[7,1,0]/
#[10,3,4]/
#[3,7,9]/
print(*l)
| true |
da56da8848e09466f831b6498e843f79fc670ecd | Ashma-Garg/Python | /SameElements.py | 934 | 4.21875 | 4 |
# Karl has an array of integers. He wants to reduce the array until all remaining elements are equal. Determine the minimum number of elements to delete to reach his goal.
# For example, if his array isarr=[1,2,2,3] , we see that he can delete the 2 elements 1 and 3 leaving arr=[2,2]. He could also delete both twos and either the 1 or the 3, but that would take 3 deletions. The minimum number of deletions is 2.
import math
import os
import random
import re
import sys
# Complete the equalizeArray function below.
def equalizeArray(arr):
d=dict()
l=list()
count=0
c=0
for a in arr:
d[a]=d.get(a,0)+1
m=(max(d.values()))
count=len(arr)-m
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
arr = list(map(int, input().rstrip().split()))
result = equalizeArray(arr)
fptr.write(str(result) + '\n')
fptr.close()
| true |
68fada0c38510aee5000ab801c61d5cb20bc4553 | bfernando1/codewars | /playing_with_digits.py | 540 | 4.28125 | 4 | #! python3
def dig_pow(n, p):
"""Finds a positive integer k, if it exists, such as the
sum of the digits of n taken to the successive powers
of p is equal to k * n.
Args:
Integer and a exponent
Returns:
A positive integer if found
Example:
>>>dig_pow(46288, 1)
51
"""
total = 0
for k, v in enumerate(str(n)):
total += pow(int(v), k + 1)
quotient = total / n
return quotient if quotient.is_integer() else -1
| true |
e80fb64c73aac67e3b843c45d192d3029c4eef50 | SakyaSumedh/dailyInterviewPro | /pascals_triangle.py | 878 | 4.4375 | 4 | '''
Pascal's Triangle is a triangle where all numbers are the sum of the two numbers above it. Here's an example of the Pascal's Triangle of size 5.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Given an integer n, generate the n-th row of the Pascal's Triangle.
Here's an example and some starter code.
def pascal_triangle_row(n):
# Fill this in.
print(pascal_triangle_row(6))
# [1, 5, 10, 10, 5, 1]
'''
import time
from math import factorial
def combination(n, r):
if r == 0 or n == r:
return 1
return int(factorial(n) / (factorial(r) * factorial(n-r)))
def pascal_triangle_row(n):
'''
each element of pascal triangle row is given by:
C(n,k) = n!/(k!(n-k)!) , where n is row-index and k is element-index
'''
return [combination(n-1, r) for r in range(n)]
start = time.time()
print(pascal_triangle_row(10))
print(time.time() - start) | true |
6c9d1bb06bee92dcf146f4c01fba2ae6921025ef | ann-peterson/hackbrightcodeappetizers | /CA1115.py | 692 | 4.4375 | 4 | # Your job is to write a Python program that converts the percentage
# grade to a letter grade. (Download the file as a .txt)
# read class_grades.txt
with open('class_grades.txt') as my_file:
grades = my_file.readlines()
for num in grades:
num = int(num)
if num >= 90:
print num, "A"
elif num >= 80 and num <= 89:
print num, "B"
# elif num >= 70 and num <= 79:
# print num, "C"
# elif num >= 60 and num <= 69:
#print num, "D"
#else:
#print num, "F"
# make grades an int
# strip invisibles off
# write conditional - if num is between 90 and 100 it's an A....
print grades
# for item in grades:
| true |
0853b01337648980e0cd46b2dba9298145dbba44 | Just-A-Engineer/TextOnlyGames | /hangman.py | 1,390 | 4.15625 | 4 | import random
words = ("python", "hangman", "xylophone", "watch", "king", "dog", "animal", "anomaly", "hospital", "exit", "entrance", "jeep", "number", "airplane", "crossing", "tattoo")
lives = None
game_won = False
print("WELCOME TO HANGMAN!!!")
print("You have three lives!")
print("Choose wisely!")
play = input("would you like to play? (y/n) ")
def play_game(lives):
mys_word = random.choice(words)
mys_letters = list(mys_word)
guess_letters = []
game_won = False
print(mys_word)
while game_won == False:
guess = input("what is your guess? ")
if guess in mys_letters:
print(f"Good job! {guess} is in the word!")
guess_letters.append(guess)
print(guess_letters)
elif guess == mys_word:
print("YOU WON! congratulations!!!")
game_won = True
else:
print(f"{guess} is not in the word! You lose a life.")
lives -= 1
if lives == 0:
print("Game Over! You Lose!!")
break
if play == "y":
play_game(5)
else:
print("Thanks for stopping by!")
play_again = input("Would you like to play again? (y/n) ")
while play_again != "n":
play_game(5)
play_again = input("Would you like to play again? (y/n)")
if play_again == "n":
print("Thanks for playing!")
break
| true |
1f87d6e40dd6710e2dbb5cb8d96828997af9adbd | LuuckyG/TicTacToe | /model/tile.py | 1,091 | 4.1875 | 4 | import pygame
class Tile:
"""Class to create the seperate tiles of the tictactoe board."""
def __init__(self, x, y, size, state='empty'):
"""Initialization of the tile.
Args:
- x: the horizontal coordinate (in px) of the tile (top left)
- y: the vertical coordinate (in px) of the tile (top left)
- size: size of the tile (in px)
- state: the state of the tile. This is either 'empty' (default), 'X' or 'O'
"""
self.x = x
self.y = y
self.size = size
self.state = state
self.rect = pygame.Rect(x, y, size, size)
# Create little space (16,67%) for the circle radius
self.radius = (self.size // 2) - (self.size // 6)
def change_state(self, symbol):
"""A player makes a move and now an empty tile becomes a filled tile,
based on the symbol of the player.
Args:
- symbol: the symbol of the player (human or AI) that makes the move,
can be either 'X' or 'O'.
"""
self.state = symbol
| true |
9a7e9bd46e734193a71ffdd69c27240dc231afe5 | Apostol095/gotham | /hw_3_2.py | 710 | 4.21875 | 4 | """Пользователь вводит порядковый номер Числа Фибоначчи - n
Программа вычисляет этот элемент ряда Фибоначчи и выводит его на экран (с вразумительным сообщением)."""
def main ():
n = input("порядковый номер элемента ряда Фибоначчи: ")
n = int(n)
res = get_fibonachi(n)
print('Элемент {} ряда Чисел Фибоначчи = {}' .format(n , res))
def get_fibonachi(n):
if n == 1:
return 1
elif n == 0:
return 0
else:
return get_fibonachi(n-1) + get_fibonachi(n-2)
main()
| false |
ccd95a8298c34bf5322bace6770fd7558f352740 | scottwedge/40_python_projects | /FibonacciCalculator_ForLoops_Challenge_4.py | 2,050 | 4.25 | 4 | #!/usr/bin/env python3
# Print welcome header.
# Calculate the first n terms of the Fibonacci sequence.
# Then calculate the ratio of consecutive Fibonacci numbers.
# Which should approach 1.618
# Functions
def header():
print("Welcome to the Fibonacci Calculator App.")
print() # blank line
def fib(last, second_last):
return last + second_last
def test_fib():
assert fib(21, 34) == 55
def get_num():
num = input("How many digits of the Fibonacci Sequence would you like to compute: ")
num = int(num) # convert input string to integer
print() # blank line
return num
def create_fib_list(num):
fib_list = [1, 1] # most common case
if num == 1:
fib_list = [1]
elif num >= 2:
for j in range(3, num+1):
fib_list.append(fib(fib_list[-1], fib_list[-2]))
else:
fib_list=[]
return fib_list
def test_create_fib_list():
assert create_fib_list(10) == [1,1,2,3,5,8,13,21,34,55]
def calculate_golden_ratio(num, fib_list):
gr = 1 # initialize return value in case num <= 2
for j in range(2, num+1):
gr = fib_list[j-1]/fib_list[j-2]
return gr
def test_calculate_golden_ratio():
assert calculate_golden_ratio(6, [1,1,2,3,5,8]) == 1.6
def main():
header()
num = get_num()
# Create list of first num Fibonacci sequence, then display it.
fib_list = create_fib_list(num)
if fib_list == []:
print("number must be integer greater than zero")
else:
print("The first {} numbers of the Fibonacci sequence are: ".format(num))
for j in range(num):
print(fib_list[j]) # print Fibonacci number from list
print() # blank line
print("The corresponding Golden Ratios are: ")
# Calculate Golden Ratio (last number divided by second last number) and print
gr = calculate_golden_ratio(num, fib_list)
print(gr)
print() # blank line
print("The ratio of consecutive Fibonacci terms approaches Phi: 1.618...")
if __name__ == "__main__":
main()
| true |
3e23862314e32d5c519a1df22c463debf51b4e3f | scottwedge/40_python_projects | /CoinToss_Conditionals_Challenge_2.py | 2,173 | 4.28125 | 4 | #!/usr/bin/env python3
# Welcome user
# Get number of coin flip attempts to do
# Ask if want to see results of each flip, or not
# Display when number of heads = number of tails
# Display summary of all results for each side: count and percentage
# Imports
import random
# Functions
def header():
print("Welcome to the Coin Toss App")
print() # blank line
def get_number():
print("I will flip a coin a set number of times.")
num = input("How many times would you like me to flip the coin: ")
num = int(num) # Convert input string type to integer type
return num
def get_see_result():
see_result = input("Would you like to see the result of each flip (y/n): ")
see_result = see_result.lower() # convert to lower case (handle Y/N)
return see_result
def flip():
# random value either 0 or 1, if 1 then "HEADS"
random.seed()
result = random.randint(0,1)
if result == 1:
return True # result of HEADS
else:
return False # result of TAILS
def summary_results(num, head_count, tail_count):
print() # blank line
print("Results of Flipping a Coin {} Times".format(num))
print() # blank line
print("Side \t\t Count \t\t Percentage")
print("Heads \t\t {}/{} \t {:.1f}".format(head_count, num, head_count/num * 100))
print("Tails \t\t {}/{} \t {:.1f}".format(tail_count, num, tail_count/num * 100))
def main():
header()
num = get_number()
see_result = get_see_result()
# Initialize counters
head_count = 0
tail_count = 0
print("Flipping...")
for j in range (num):
res = flip()
if res == True:
head_count = head_count + 1
if see_result == "y": print("HEAD")
else:
tail_count = tail_count + 1
if see_result == "y": print("TAILS")
if head_count == tail_count and see_result == "y":
print("At {} flips, the number of heads and tails were equal at {},{} each.".format(head_count + tail_count, head_count, tail_count))
# Print summary of all coin tosses
summary_results(num, head_count, tail_count)
if __name__ == "__main__":
main()
| true |
d9882c848dd09b65f97fb84d4d704492a419d1e6 | scottwedge/40_python_projects | /LetterCounter_Project_1.py | 2,069 | 4.5625 | 5 | #!/usr/bin/env python3
# Project 1:
# - prompts for user name and capitalizes it if needed
# - prompts for a line of text to be entered
# - prompts for which letter count is desired.
# - prints letter and count for that letter
# Instructions are that both upper case and lower case are counted for the same letter.
# Variables:
# name: entered name of user
# name_capitalized: capitalize name (as per example)
# line: text string to be evaluated
# line_lower: line in all lower case to simplify counting
# letter: letter to be counted in line
# letter_lower: letter in lower case to simplify counting
# count: number of occurrences of letter in line
# j: loop through line
# Functions
def cap_user_name():
name = input("What is your name? ")
return name.capitalize()
def count_letters(user_line, user_letter):
num = 0
for j in user_line:
if j == user_letter:
num = num + 1
return num
def test_count_letters_1():
assert count_letters("Evaluate this line always", "a") == 4
def test_count_letters_2():
assert count_letters("abcd abcd abcd dddd", "d") == 7
def main():
# Prompt for user name; all lower case name in example gets capitalized
name_capitalized = cap_user_name()
print("Welcome {}.".format(name_capitalized))
# Prompt for line of text
line = input("Please enter the line of text to be evaluated: ")
print("Thank you for entering:", line)
# Prompt for letter to be counted
letter = input("What letter should be counted? ")
# Convert letter to lower case to simplify counting
letter_lower = letter.lower()
letter_upper = letter.upper()
# Convert line to all lower case to simplify count
line_lower = line.lower()
# Count how many times the (upper or lower case) letter occurs in the line
count = count_letters(line_lower, letter_lower)
# Output results
print("{}, there are {} occurrences of {} or {}.".format(name_capitalized, count, letter_lower, letter_upper))
if __name__ == "__main__":
main()
| true |
9f45813b8077ccc5aabe9ce353a654acc9cbe9fe | connorS119987/CNA267-Spring-Semester-2020 | /CH02/23Lab2-2.py | 652 | 4.34375 | 4 | # Will determin the minimum length of runway an aircraft needs to take off
print("This program will determin the minimum length of runway an aircraft needs\n") # Prints introduction statement
v = eval( input("Please enter the take-off speed of the aircraft: ") ) # Obtaining the velocity of the aircraft
a = eval( input("Please enter the acceleration of the aircraft: ") ) # Obtaining the acceleration of the aircraft
""" Formula for length of runway needed is the following """
""" lenght = ( (v**2) / 2 ) * a """
length = ( v**2 / (2 * a) )
print("The minimum runway length for this aircraft is", length, "meters.")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.