blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
2ce4fef3120d7e8c1374011aa3ecc9ce64c780c0 | Lioger/ITMO | /Practicum_2.1.py | 1,620 | 4.15625 | 4 | """Считать отдельными операторами целочисленные ширину и высоту прямоугольника. Создать функцию (def), принимающую
в качестве параметров ширину и высоту фигуры и название функции, которую необходимо выполнить. Имя вложенной функции
передавать явным образом (например: (a,b,name='perim')).
Внутри функции создать две вложенные функции (def) по подсчету площади и периметра фигуры. Вывести одной строкой
через пробел площадь и периметр, разделенные пробелом (например, '20 18')."""
def geometry(a, b, name='perim'):
def perim(a, b):
return 2*(a+b)
def plosh(a, b):
return a*b
if name == 'perim':
return perim(a, b)
elif name == 'plosh':
return plosh(a, b)
a = int(input())
b = int(input())
x1 = geometry(a, b, 'plosh')
x2 = geometry(a, b, 'perim')
print(x1, x2)
# Можно использовать такой вариант, но он не соответствует тому уровню, какой дали к моменту этой лабы
# def func(x, y, name):
# def plosh(x, y):
# return x * y
#
# def perim(x, y):
# return (x + y) * 2
#
# return locals()[name](x, y)
#
#
# x = int(input())
# y = int(input())
# print(func(x, y, "plosh"), func(x, y, "perim"))
| false |
bf9dd9208495e662ee62112c5b48216ec069281f | EX1ST3NCE/Python_Practice_Projects | /20. Turtle Race/main.py | 1,180 | 4.375 | 4 | # Program to have a race of 6 turtles using turtle module.
from turtle import Turtle, Screen
import random
screen = Screen()
screen.setup(width=800, height=600)
colors = ["red", "green", "blue", "yellow", "orange", "purple"]
is_race_on = False
user_input = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter color: ")
y_positions = [-200, -120, -40, 40, 120, 200]
all_turtles = []
for turtle_index in range(0, 6):
new_turtle = Turtle(shape="turtle")
new_turtle.penup()
new_turtle.color(colors[turtle_index])
new_turtle.goto(x=-350, y=y_positions[turtle_index])
all_turtles.append(new_turtle)
if user_input:
is_race_on = True
while is_race_on:
for turtle in all_turtles:
if turtle.xcor() > 360:
is_race_on = False
winning_color = turtle.pencolor()
if winning_color == user_input:
print(f"You won!! {winning_color} Turtle reached finished line!")
else:
print(f"You Lost!! {winning_color} Turtle reached finished line!")
rand_distance = random.randint(0, 10)
turtle.forward(rand_distance)
screen.exitonclick()
| true |
904038d55bbdcfb11709a64bbc05f27c716a79ce | vinay4goud/python_list | /classes.py | 921 | 4.1875 | 4 |
"""
reading the class and also calling perticular data from the files which is in calsses
"""
class school_students:
student = {
'name': [ 'vinay', 'navin', 'uday'],
'age' : [20, 19, 30]
}
x = school_students()
print(x.student['name'])
"""
Create a class named Person, use the __init__() function to assign values for name and age:
"""
class stud:
def __init__(self, school ):
self.school = school
#self.age = age
school = [ 'name', 'age']
p1 = stud (school)
print (p1.school)
"""
Create a class named Person, use the __init__() function to assign values for name and age from the mutiple values :
"""
class instance:
def __init__(self, age):
self.age = age
age = {
"name" : [ 'vinay', 'navin', 'kumar'],
"b" : [ 20, 19, 18]
}
p2 = instance (age)
print (p2.age.get("b"))
| true |
b20d767474ebb5b4989c398e69605bf98eed7b6a | JagadeeshVarri/learnPython | /Basics/prob_35.py | 405 | 4.15625 | 4 | # Program that will return true if the two given integer values are equal or
# their sum or difference is 5
val1 = int(input("Enter a value : "))
val2 = int(input("Enter a value : "))
def check(val1,val2):
sum = val1+val2
dif = val1 - val2
if val1==val2:
return True
elif sum==5 or dif ==5:
return True
else:
return False
print(check(val1, val2))
| true |
02b182b1a1c52d84c60b5f49b1e29ae98743d512 | JagadeeshVarri/learnPython | /Basics/prob_27.py | 242 | 4.21875 | 4 | # Write a Python program to concatenate all elements in a list into a string and return it
def list_string(list1):
string =" "
for item in list1:
string = string + str(item)
return string
print(list_string([1,2,3,45])) | true |
eb72485dc30a1cbce9ab93a048c17ae42c50abc1 | JagadeeshVarri/learnPython | /Basics/prob_60.py | 207 | 4.15625 | 4 | # Write a Python program to calculate the hypotenuse of a right angled triangle
import math
a = 5
b=4
hyp = math.sqrt(a**2 + b**2)
print(f"hypotenuse of right angle triangle is : {round(hyp,4)}")
| true |
539f9caa76aca5d4e55b4b4836bafd2d576d9446 | JagadeeshVarri/learnPython | /Basics/prob_66.py | 238 | 4.21875 | 4 | # Write a Python program to calculate body mass index
height = float(input("Enter your height in Feet: "))
weight = float(input("Enter your weight in Kilogram: "))
print("Your body mass index is: ", round(weight / (height * height), 2))
| true |
ddfe9d075b3d341ed5dec172300c7a824f790cf7 | JagadeeshVarri/learnPython | /Basics/prob_6.py | 316 | 4.28125 | 4 | # Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers
values = input("Enter values separated by commas',' : ")
store_list = values.split(",")
store_tuple = tuple(store_list)
print('List : ',store_list)
print('Tuple : ',store_tuple) | true |
322824db2365795ba32355fc32216bf3154297a6 | upgirl/RebootPython | /class/class2-140418/a.py | 638 | 4.28125 | 4 | # List
# list is keyword, cannot be name, split string
# use [index] get value
# index 0 1 -1 -2
demo_list = [1,2,'a','b',[3,'c'],{'name':'upgirl'}]
print '==== get value by index ===='
print demo_list[0]
print demo_list[4]
print demo_list[4][1]
print demo_list[-1]
print demo_list[-1]['name']
print '==== bianli list ===='
for demo in demo_list:
print demo
print '==== in or not ===='
print 1 in demo_list
print 0 in demo_list
print '==== bianli string ===='
string = 'hello'
print string[-1]
string = '[3,4,5]'
print string[-1]
print '==== ERROR, use list as name ===='
print list('123')
list = [1,2,3]
print list('hello')
| false |
366a4990435021c92b98de52bd7daf40f35034dc | 18Arjun/python-practice- | /LESSER OF TWO EVENS.py | 562 | 4.5 | 4 | LESSER OF TWO EVENS: Write a function that returns the lesser of two given numbers if both numbers are even, but returns the greater if one or both numbers are odd
def lesser(a,b):
if a%2==0 and b%2==0:
print(min(a,b))
else:
print(max(a,b))
a=lesser(2,5)
or
def lesser(a,b):
if a%2==0 and b%2==0: #Both are even
if a<b:
return a
else:
return b
else: #both are not even
if a>b:
return a
else:
return b
print(lesser(1,7))
| true |
d9fcccf4c6c413c5913902e3a2502079083cef10 | JaeJunRyu/pythonBookStudy | /chapter4/ex04-1/list02_3.py | 287 | 4.3125 | 4 | list_a = [1, 2, 3]
list_b = [4, 5, 6]
print("list_a + list_b", list_a.extend(list_b)) #실행결과로 아무 것도 출력하지 않습니다.
print("list_a", list_a) # 앞에 입력했던 list_a 자차에 직접적인 변화가 있습니다.(파괴적 처리)
print("list_b", list_b)
| false |
c52b41118b589678608148180d5d623fdb9b3e23 | nguyenngochuy91/companyQuestions | /google/nestedListWeightSum.py | 2,255 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 8 17:13:24 2019
@author: huyn
"""
#339. Nested List Weight Sum
#
#Given a nested list of integers, return the sum of all integers in the list weighted by their depth.
#
#Each element is either an integer, or a list -- whose elements may also be integers or other lists.
#
from typing import List
class NestedInteger:
def __init__(self, value=None):
"""
If value is not specified, initializes an empty list.
Otherwise initializes a single integer equal to value.
"""
if value!=None:
self.val = value
else:
self.val = []
def isInteger(self):
"""
@return True if this NestedInteger holds a single integer, rather than a nested list.
:rtype bool
"""
return type(self.val) == int
def add(self, elem):
"""
Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
:rtype void
"""
self.val.append(elem)
def setInteger(self, value):
"""
Set this NestedInteger to hold a single integer equal to value.
:rtype void
"""
self.val = value
def getInteger(self):
"""
@return the single integer that this NestedInteger holds, if it holds a single integer
Return None if this NestedInteger holds a nested list
:rtype int
"""
if self.isInteger:
return self.val
return None
def getList(self):
"""
@return the nested list that this NestedInteger holds, if it holds a nested list
Return None if this NestedInteger holds a single integer
:rtype List[NestedInteger]
"""
if self.isInteger:
return None
return self.val
class Solution:
def depthSum(self, nestedList: List[NestedInteger]) -> int:
def dfs(myList,depth):
s = 0
for i in range(len(myList)):
item = myList[i]
if item.isInteger():
s += item.getInteger()*depth
else:
s += dfs(item.getList(),depth+1)
return s
return dfs(nestedList,1) | true |
10dc9f9a334e4fa7bd5672ac78714c28f5dff48a | curiousTauseef/python-learning-htt-book | /chapter12-chapter13/inventory.py | 1,724 | 4.1875 | 4 | # Barbara King
# HW 8-5: inventory.py
#
# Starting code for a simple inventory tracking program using
# dictionaries.
#
def getCommand():
command = input("Enter command: ")
return command
def addToInventory(dict, inventory):
for item in dict:
# if item in inventory.keys():
# inventory[item] += dict[item]
# else:
# print(dict)
# inventory[item] = dict[item]
inventory[item] = inventory.get(item,0) + dict[item]
# print(inventory)
return inventory
def viewInventory(dict):
for (k,v) in dict.items():
print("%s -- %d" % (k, v))
return
def main():
print ("Welcome to StuffMaster, v.0.47")
print("Enter a command to add, view or quit. Enter A, V, or Q: ")
inventory = {} # empty dictionary
while True: # get command, process command; quit when selected below
pass
# Get the command,
command = getCommand().upper()
# Call the appropriate function based on command
if command == "A":
invname = input("Enter item name to add: ")
qty = int(input("Enter quantity: "))
dict = {invname: qty}
inventory = addToInventory(dict, inventory)
elif command == "V":
print("item -- count")
print(viewInventory(inventory))
elif command == "Q":
break
else:
print("Not valid command, enter either A, V or Q.")
# If unknown command, complain and prompt for reentry
# here, we're quitting
print ("Quitting. Final version of inventory is:")
# print out final version of inventory
viewInventory(inventory)
print ("Exiting...")
main()
| true |
25e009404dc21c8ae24508dd71384ec815789254 | ivanbergon/Github_privado | /Data Science Academy/PythonFundamentos/Cap03/Lab02/calculadora_v1.py | 1,159 | 4.1875 | 4 | # Calculadora em Python
# Desenvolva uma calculadora em Python com tudo que você aprendeu nos capítulos 2 e 3.
# A solução será apresentada no próximo capítulo!
# Assista o vídeo com a execução do programa!
print("\n******************* Python Calculator *******************")
# escrever "Selecione o número da operação desejada:"
print("Selecione o número da operação desejada: \n")
print("1 - Soma")
print("2 - Subtração")
print("3 - Multiplicação")
print("4 - Divisão")
# pedir ao usuário para escolher a opção desejada
operacao = int(input("Digite sua opção (1/2/3/4): "))
# pedir ao usuário o primeiro número
num1 = float(input("Digite o primeiro número: "))
# pedir ao usuário o segundo número
num2 = float(input("Digite o segundo número: "))
# Fazer a operação pedida
if operacao == 1:
print("O resultado é: ", num1+num2)
elif operacao == 2:
print("O resultado é: ", num1 - num2)
elif operacao == 3:
print("O resultado é: ", num1*num2)
elif operacao == 4:
print("O resultado é: ", num1/num2)
else:
print("Selecione o tipo de operação corretamente, entre 1 e 4")
# Mostrar o resultado | false |
9e22f33ca1875870cd16563b21a3c66a68b4aad7 | marinka01126/hw_Marina | /Lesson_4/hw/text_shortener.py | 979 | 4.75 | 5 | """
Необходимо реализовать программу, которая принимает текст и удаляет из него
все, что находится в скобочках "(", ")". Скобки могут быть вложенными.
И выводит получившийся текст.
___________________________________________________________________________
Например:Программа принимает текст(вводится с клавиатуры(с помощью input())),
форматирует его(удаляет все скобочки(и их содержимое)) и выводит на экран.
Результат:
Программа принимает текст, форматирует его и выводит на экран.
"""
string = input("Текст: ")
a = string.find("(")
b = string.rfind(")")
print("Результат: ", string[:a]+string[b+1:])
| false |
0e0c1000467796cfb2ce5b94f07b9e84df4004eb | marinka01126/hw_Marina | /Lesson_3/_4_practice.py | 667 | 4.28125 | 4 | """
1. Найти наибольшую цифру числа.
2. Найти количество четных и нечетных цифр в числе.
"""
number = int(input("Число: "))
if number < 10:
print("Наибольшая цифра числа", number)
elif number > 10 and number < 100:
tmp1 = number // 10
tmp2 = number % 10
print("Наибольшая цифра числа", min(tmp1, tmp2))
elif number > 100 and number < 1000:
tmp1 = number // 100
tmp2 = number // 10 % 10
tmp3 = number % 10
print("Наибольшая цифра числа", min(tmp1, tmp2, tmp3)) | false |
f09f053eac834864907845fffd5d92e8c37a8455 | marinka01126/hw_Marina | /Lesson_1/_1_operators.py | 395 | 4.3125 | 4 | """
Арифметические операторы Python
примеры в формате:
инструкция # результат
print(2 + 2) # 4
"""
print(2 + 2)
print(2 + 1.5)
print(5 - 2)
print(-11.2 - 20)
print(-3 * 2)
print(5 * 0.5)
print(6 / 2)
print(5 / 2)
print(5 // 2)
print(-16 // 5)
print(5 % 2)
print(16 % -5)
print(3 ** 3)
print(2 ** 2 ** 3) | false |
c26ac228a736e5cf61e915de03c497905c7be156 | EZA-17/Madlibs | /main.py | 1,111 | 4.21875 | 4 | def story1():
adjetive = input("Enter an adjetive: ")
place = input("Enter a place: ")
color = input("Enter a color: ")
substance = input("Enter a substance: ")
food = input("Enter a food: ")
print("It's been a " + adjetive + " quarintine here in " +place+ ". The sky has been " +color+ ". The ground has been covered in " +substance+ ". We have all been survining on a steady diet of " +food+ ".")
def story2():
name = input("Enter a name: ")
event = input("Enter a event: ")
Time = input("Enter a time: ")
emotion = input("Enter a emotion: ")
outcome = input("Enter a outcome: ")
print("Hello my name is "+name+ ". I am preparing for the " +event+ ". I will be preparing for " +Time+ ". I'm very " +emotion+ " but I know I will " +outcome+ ".")
def randomstory():
print(story1() , story2())
def storypicker(sc):
if sc=="1":
story1()
elif sc=="2":
story2()
elif (sc == "R")or(sc == "r"):
randomstory()
def main():
print("Choose your story:")
storyChoice = input("Enter 1, 2, or (R)andom: ")
storypicker(storyChoice)
if __name__=="__main__":
main()
| false |
6663a46cba88baa13e6a5d930be9f48b684ff0e6 | ArmaanBrar08/BMI-Calculator | /BMI Calculator.py | 1,295 | 4.34375 | 4 | #Intorducing AI#
print("Hello, this program allows the user to calculate BMI");
print("B - Body, M - Mass, I - Index");
Answer_1 = input("Are you ready: ");
if Answer_1 == 'No':
input("How come: ");
print("Sorry you feel that way.");
if Answer_1 == 'Yes':
print("Ok, sounds good");
Answer_2 = input("This calculator asks for your height and weight, is that okay: ");
if Answer_2 == 'No':
input("How come: ");
print('Sorry you feel that way.');
elif Answer_2 == 'Yes':
print("Ok, sounds good");
print("If you would, convert your weight into Kilograms (kg)");
print("And your height in meters (m)");
#BMI CALCULATOR#
weight = float(input("Enter your weight in kilograms (kg): "));
height = float(input("Enter your height in meters (m): "));
bmi = weight / (height * height)
if bmi < 18.5:
print("You are underweight, you must eat more!");
elif bmi > 25:
print("You are overweight, you must eat less");
elif 18.25 < bmi < 25:
print("You are healthy, keep up the good work");
Answer_3 = input("Would you like to see your BMI: ");
if Answer_3 == 'Yes':
print("Your BMI is " + bmi);
elif Answer_3 == 'No':
print("That's okay, Have a great day"); | true |
2383cb31a81eb3515e2915ac167ec936d3e7aa39 | tom-ubaraujo/exemplos_simples | /PythonBrasil/estrutura_sequencial/Exercício3.py | 405 | 4.1875 | 4 | num1 = int(input("Informe um numero inteiro: "))
num2 = int(input("Informe outro numero inteiro: "))
num3 = float(input("Informe um numero real: "))
prod = ((num1 * 2) * (num2/2))
soma = (num1 * 3) + num3
cubo = num3**3
print("O produto do dobro do primeiro com metade do segundo: ",prod)
print("A soma do triplo do primeiro com o terceiro: ",soma)
print("O terceiro elevado ao Cubo: ",cubo)
| false |
8c23edd9c8e9e1532ea4840f0503ad18cc9af977 | Tecfil3D/Python | /lists_tuples.py | 1,465 | 4.21875 | 4 | # Lists ( en las listas los datos se pueden modificar y están contenidos entre corchetes)
lista = ['Manuel', 23, 'hola mundo', 3.14, 'Antonio']
lista[0] = 'Cambiamos de valor'
print(lista[0])
print('Todos los elementos que contiene lista', lista)
print(lista[1:4]) # Extraemos una parte del array lista, desde el index 1 al 4
print(lista[1:]) # Extraemos desde el index 1 al final de la lista
print(lista * 3) # Extraemos lista 3 veces
nueva_lista = lista * 2 # se puede crear otro array que contenga la lista * 2
print(nueva_lista)
# Concatenar listas
lista1 = ['uno', 'dos', 'tres']
lista2 = ['cuatro', 'cinco', 'seis']
lista_concatenada = lista1 + lista2
print(lista_concatenada)
# Tuples ( en las tuplas los datos no se pueden modificar y están contenidos entre paréntesis)
tuples = ('Manuel', 'Antonio', 35, 3.14)
# tuples [0] = 'cambiamos de valor' # En tuples no se pueden actualizar/modificar los elementos
print('Todos los elementos que contiene tuples', tuples)
print(tuples[1:4]) # Extraemos una parte del array tuples, desde el index 1 al 4
print(tuples[1:]) # Extraemos desde el index 1 hasta el final del tuples
print(tuples * 3) # Extraemos tuples tres veces
nuevo_tuples = tuples * 2 # se puede crear otro array que contenga tuples * 2
print(nuevo_tuples)
# Concatenar tuples
tuples1 = ['siete', 'ocho', 'nueve']
tuples2 = ['diez', 'once', 'doce']
tuples_concatenado = tuples1 + tuples2
print(tuples_concatenado)
| false |
ab4f970200d1eddd27acf4466acdbd0e5871bb51 | JaehoonKang/Computer_Science_110_Python | /3_Sin&Cos/Second_Assignment_KangJaehoon.py | 2,085 | 4.25 | 4 | '''
Kang Jaehoon
jkang36@binghamton.edu
917-724-6430
C60
Assignment 3-2
'''
'''
ANALYSIS
RESTATEMENT:
Ask a user to enter the year and decide if this year is a leap year or not
OUTPUT to monitor:
num_year (int) - either a leap year or just a year
INPUT from keyboard:
num_year_str = input("Enter a year: ")
num_year (int) - int(num_year_str)
GIVEN:
FOUR = 4
ZERO = 0
HUNDRED = 100
FOUR_HUNDRED = 400
PROCESSING:
Import required module: math
Explain a purpose of this program to a user, using a print expression
Define four constants: FOUR, ZERO, HUNDRED, FOUR_HUNDRED
Get an input value from a user: input("Enter a year: ")
Decide if the input is a leap year using if-else statment
With numbers increased by 10 From 1800 to 2100,
Decide the number is a leap year
FORMULAS:
num_year % 4 == 0
num_year % 100 == 0
num % 400 == 0
'''
# IMPORTS
import math
# CONSTANTS
FOUR = 4
ZERO = 0
HUNDRED = 100
FOUR_HUNDRED = 400
STARTING_YEAR = 1800
ENDING_YEAR = 2101
# Explain purpose of program to user
# This program to check if a input year is a leap year or not
print("This program determines if a given year is a leap year or not\n")
# DESIGN
def main():
num_year_str = input("Enter a year: ")
num_year = int(num_year_str)
#if-else statement whether the year is a leap year
# if the year is a leap
if (num_year % FOUR == ZERO) and ( num_year % HUNDRED != 0 ) or \
( num_year % FOUR_HUNDRED == ZERO):
print ("%d is a leap year \n" %num_year)
# else
else:
print ("%d is not a leap year \n" %num_year)
# Using for-loop in range from 1800 to 2100, increased by 10
for num_year in range (STARTING_YEAR, ENDING_YEAR, 10):
if (num_year % FOUR == ZERO) and ( num_year % HUNDRED != 0 ) or\
( num_year % FOUR_HUNDRED == ZERO):
print ("%d is a leap year \n" %num_year)
else:
print ("%d is not a leap year\n" %num_year)
main()
| true |
cd5b92687377933806c5f9b9b4f347ebe3fdf4cf | ingredlopes/fiaptests | /nano/algoritmos/simple_calc.py | 612 | 4.15625 | 4 | numOne = int(input('Set number one \n'))
numTwo = int(input('Set number two \n'))
operation = str();
print('\nUse * for multiplication')
print('Use + for sum')
print('use - for subtraction')
print('use / for division')
operation = input('')
if operation != '*' and operation != '+' and operation != '-' and operation != '/':
print('Invalid operation');
elif operation == '*':
print(numOne * numTwo)
elif operation == '+':
print(numOne + numTwo)
elif operation == '-':
print(numOne - numTwo)
elif operation == '/':
if numTwo == 0:
print('Division by 0 is not possible!')
else:
print(numOne / numTwo)
| true |
98c25c47723f94c09b2388a9f614529f735818ed | lizzab/List-Operations | /console_operations.py | 1,356 | 4.3125 | 4 | # Ben Lizza
# 02/11/20
# CONSOLE
import list_operations
# Make the user input 5 values that will be put into a list and manipulated
numbers = []
print("Enter five values for me to manipulate.")
for num in range(0,5):
num = int(input())
numbers.append(num)
numbers.sort()
print(f"\nThis is your list after being sorted: {numbers}")
print(f"\nThe sum of your list is: {list_operations.sum_list(numbers)}")
print(f"\nThis is the product of your list: {list_operations.product_list(numbers)}")
print(f"\nThis is the average: {list_operations.mean_list(numbers)}")
print(f"\nThis is the median of your list: {numbers[2]}")
print(f"\nThis is the mode of the list: {list_operations.mode(numbers)}")
print(f"\nThe largest number is: {numbers[-1]}")
print(f"\nThe smallest number is: {numbers[0]}")
numbers = list(set(numbers))
print(f"\nThis is your list without any duplicates: {numbers}")
print("\nThis is your list after even numbers were removed:")
list_operations.odd_list(numbers)
print("\nThis is your list after odd numbers were removed:")
list_operations.even_list(numbers)
one_more = input("\nType one more number!")
print(one_more)
if one_more in numbers:
print("Your number is in the list!")
else:
print("Your number is not in the list :(")
# BONUS
print(f"\nThis is the SECOND largest number in your list: {numbers[3]}")
| true |
3c440ae6e351670c8befa08a80fccf3ac55a8d7a | Natacha7/Python | /nivelacion_2_3/unidad_3/reto_3.py | 1,380 | 4.21875 | 4 | '''
Función que regresa la persona cuya edad es mayor, dentro de una población de N personas
-La función recibe una lista de diccionarios como parametro que contiene la población, las llaves del diccionario son 'nombre', 'edad'
-En caso de que existan edades iguales regresar la primera persona de la población con la edad igual
Parámetros: ----------- poblacion (dict): datos (nombre y edad) de la población (N personas)
Retorna: -------- str: -En caso de éxito, retorna una cadena de caracteres de la forma.
"Con {edad} años, el mayor de todos es: {nombre}."
-En caso de que el parametro no sea una lista con diccionarios "Error en los datos recibidos."
'''
"datos de prueba"
# [{'nombre':'Juan', 'edad':35}, {'nombre':'Maria', 'edad':34}, {'nombre':'Camila', 'edad':39}]
# [{'nombre':'Felipe', 'edad':43}, {'nombre':'Maria', 'edad':34}, # {'nombre':'Camila', 'edad':19}, {'nombre':'Carlos', 'edad':33},
# # {'nombre':'Juan', 'edad':43}]
def poblacion(poblacion):
edad_mayor = 0
nombre_mayor = ' '
for persona in poblacion:
if persona['edad'] > edad_mayor:
edad_mayor = persona['edad']
nombre_mayor = persona ['nombre']
return f'Con {edad_mayor} años, el mayor de todos es: {nombre_mayor}.'
print(poblacion([{'nombre':'Juan', 'edad':35}, {'nombre':'Maria', 'edad':34}, {'nombre':'Camila', 'edad':39}]))
| false |
90a4d4fc4fb332ebf1c8a504a8cb294bbbace580 | Natacha7/Python | /Ejercicios_unidad2.py/Digito_multiplo.py | 844 | 4.15625 | 4 | '''
Leer un número entero de tres digitos y leer si algún digito es múltiplo de otros
'''
s = input("Digite un número entero de tres digitos: ")
if int(s[0]) % int(s[1]) == 0:
print("El digito en la posición 0 es múltiplo del digito en la posición 1 ")
elif int(s[1]) % int(s[0]) == 0:
print("El digito en la posición 1 es múltiplo del digito en la posición 0 ")
elif int(s[0]) % int(s[2])==0:
print("El digito en la posición 0 es múltiplo del digito en la posición 2 ")
elif int(s[1]) % int(s[2])==0:
print("El digito en la posición 1 es múltiplo del digito en la posición 2 ")
elif int(s[2]) % int(s[0])==0:
print("El digito en la posición 2 es múltiplo del digito en la posición 0 ")
elif int(s[2]) % int(s[1])==0:
print("El digito en la posición 2 es múltiplo del digito en la posición 1 ")
| false |
5054e2c0e8e262fc3baeae991c1bb6e0064b2811 | Natacha7/Python | /Tuplas/Funciones_orden_superior.py | 1,462 | 4.5 | 4 | '''
FUNCIONES PARA COLECCIONES DE DATOS
Python Ofrece unas funciones , muy versatiles para trabajar con grandes
colecciones de datos, estas son funciones de orden superior.
Las funciones más utilizadas de este tipo, para realizar operaciones sobre
listas principalmente, sin utilizar ciclos, al estilo del paradigma funcional,
son las siguientes:
* Map
* Reduce
* Filter
* Zip
--------------------------------------------------------------------------
Algo interesante de las funciones en Python es que estas pueden ser
asignadas a variables.
Las funciones pueden ser utilizadas como argumento de otras funciones
Las funciones pueden retornar otras funciones.
---------------------------------------------------------------------------
'''
#funciones de orden superior
def suma(val1, val2):
return (val1+val2)
def resta(val1, val2):
return (val1-val2)
def multiplicacion(val1, val2):
return (val1*val2)
def division(val1, val2):
return (val1/val2)
#esta es la función de orden superior
def operacion(funcion, val1, val2):
return (funcion(val1,val2))
variable_suma = suma
variable_resta = resta
variable_multiplicacion = multiplicacion
variable_division = division
resultado = operacion(variable_suma, 10, 5)
resultado2 = operacion(variable_resta, 10,5)
resultado3= operacion(variable_multiplicacion, 10, 5)
resultado4 = operacion(variable_division, 10, 5)
print(resultado)
print(resultado2)
print(resultado3)
print(resultado4)
| false |
72f87aeec0b37f7ff7729758506212d381a274c3 | amoljagadambe/python_studycases | /advance-python/datastructures/heapq_tutorials.py | 1,142 | 4.21875 | 4 | import heapq
li_data = [5, 7, 9, 1, 3]
li = [5, 7, 9, 4, 3, 1]
# using heapify to convert list into heap
heapq.heapify(li_data)
heapq.heapify(li)
print(li_data)
'''
using heappush() to push elements into heap
pushes 4
'''
heapq.heappush(li_data, 4)
print(li_data)
'''
using heappop() to pop smallest element
function is used to remove and return the
smallest element from heap.
'''
print(heapq.heappop(li_data))
'''
using heappushpop() to push and pop items simultaneously
pops 2
'''
print(heapq.heappushpop(li, 2))
'''
using heapreplace() to push and pop items simultaneously
element is first popped, then element is pushed.i.e, the
value larger than the pushed value can be returned.
'''
print(heapq.heapreplace(li, 5))
'''
function is used to return the k largest elements from
the iterable specified and satisfying the key if mentioned.
returns the list
'''
largest = heapq.nlargest(3, li)
print(largest) # output: [9, 7, 5]
'''
unction is used to return the k smallest elements from
the iterable specified and satisfying the key if mentioned.
'''
smallest = heapq.nsmallest(2, li_data)
print(smallest) # output:[3, 4]
| true |
09f997d41db3db3785feda3d4c8fb94523cf2c7a | amoljagadambe/python_studycases | /oops/palindrome.py | 251 | 4.25 | 4 | def check(num):
str(num)
reverse = num[::-1]
if num == reverse:
return "palindrome"
else:
return "not a palindrome"
if __name__ == '__main__':
num = input("give the Number or string:\n")
print(check(num=num))
| true |
a008f940201d7a11beecfbf53d6068b343471308 | sgouda0412/inefficientcode | /tail.py/tail_v4.py | 508 | 4.15625 | 4 | def tail(sequence, n):
"""
Takes an input sequence and return last n elements
Sequence: List, Tuple, String, Set
n: positive integer
"""
tail = [] # define element storage
if n <= 0: # return empty list if n < 0
return tail
for element in sequence: # iterate through input
tail.append(element) # append to storage
if len(tail) > n: # reduce memory consumption by discarding if list > n
tail.pop(0)
return tail # return result
| true |
c300ed01a7bbb4e16bd8abb0ebc0e35befa46c0e | mjschuetze102/Travel-Time | /textBasedUI.py | 1,684 | 4.46875 | 4 | """
Plain Text Based User Interface for input and output values
@author Michael Schuetze
"""
from calculateTravelTime import *
"""
Creates the string that is displayed when asking for a desired distance and price of gas
@return float representing the distance to be traveled, float representing the price of gas
"""
def getUserInput():
print("=====================================================")
distance = input("Enter desired distance (mi): ")
price = input("Enter price for gas ($): ")
return distance, price
"""
Creates the string that is displayed after calculating speed/time combinations
@param travelData:tuple(int, str, float, float)- list of tuples containing speeds and times/costs associated with those speeds
"""
def displayTable(travelTimes):
print("=====================================================")
for speedTime in travelTimes:
# Inserts the speed and time into different strings
speed = "{!s} mph".format(str(speedTime[0]))
time = "{!s} Hours:Minutes".format(str(speedTime[1]))
cost = "${!s}".format(str(speedTime[2]))
moneyLost = "${!s}".format(str(speedTime[3]))
# Inserts the speed and time strings into a larger string with centered wording
print("|{:^10}|{:^22}|{:^8}|{:^8}|".format(speed, time, cost, moneyLost))
print("=====================================================")
"""
Main function for the program
Calls functions to collect user input, make calculations, and display them for the user
"""
def main():
distance, price = getUserInput()
travelTimes = runCalculations(distance, price)
displayTable(travelTimes)
if __name__ == '__main__':
main() | true |
2f3cce8d0864a1eede907ef52dd62f43aab01068 | mongoosePK/hackerrank | /python/day25RunningTimeAndComplexity.py | 510 | 4.125 | 4 | # day25RunningTimeAndComplexity.py
# william pulkownik
# borrowed from wikipedia because I wasn't interested in developing my own primality algorithm
for _ in range(int(input())):
n = int(input())
if n == 1:
print("Not Prime")
if n <= 3 and n > 1:
print(f"Prime")
if n % 2 == 0 or n % 3 == 0:
print("Not Prime")
i = 5
while i ** 2 <= n:
if n % i == 0 or n % (i + 2) == 0:
print("Not Prime")
i += 6
else:
print("Prime")
| false |
7eb4284e616645a75430ba13b6a202b6338ac308 | choiceacademy/diy-shape | /sides_game.py | 879 | 4.5 | 4 | from turtle import *
import math
t=Turtle()
t.speed(0)
colors=['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink', 'silver', 'gold']
#Create black backround
t.color("black")
t.hideturtle()
t.begin_fill()
t.hideturtle()
bgcolor("black")
t.end_fill()
t.goto(0,0)
# Ask how many sides the user wants
number_of_sides = int(input("How many sides would you like your shape to have? (1-9) "))
if number_of_sides > 9:
print("Please enter a number from 1-9.")
number_of_sides = int(input("How many sides would you like your shape to have? (1-9) "))
#(JIM) How do I make the user able to input the number of sides they want?
# Draw a spiral with the number of sides the user chose on the screen 200 times
for x in range(200):
t.pencolor(colors[x % number_of_sides])
t.forward(x*3/number_of_sides+x)
t.left(360/number_of_sides+1)
| true |
fd24d304372b6647275428c996130213323fd13e | Sanketdighe7/Sanketdighe7 | /Integers & Floats.py | 585 | 4.40625 | 4 | # Arithmetic Operators:
# Addition: 3 + 2
# Subtraction: 3 - 2
# Multiplication: 3 * 2
# Division: 3 / 2
# Floor Division: 3 // 2
# Exponent: 3 ** 2
# Modulus: 3 % 2
# Comparisons:
# Equal: 3 == 2
# Not Equal: 3 != 2
# Greater Than: 3 > 2
# Less Than: 3 < 2
# Greater or Equal: 3 >= 2
# Less or Equal: 3 <= 2
num_1 = '100'
num_2 = '200'
num_1 = int(num_1)
num_2 = int(num_2)
num = 1
num += 1
print(num_1 + num_2)
print(abs(-3))
print(round(3.75, 1))
num1 = 2
num2 = 3
print(num1 == num2) | false |
555c6e2f051fffdedd33fb2cd9f15b33c2b77880 | khakamora/pythonLearning | /lab2/task1.py | 221 | 4.125 | 4 | my_number = 3
while True:
print("Enter user_number:")
user_number = int(input())
#3 > x <= 2
if user_number >= my_number:
print("Repeat number.")
else:
print("You win!!!")
break | false |
1eca05f83b91b729a29e115a9866e2cb7ef2221c | ji3g4kami/Time | /timecount.py | 674 | 4.21875 | 4 | #! /usr/bin/env python3
import time
instructions = ' '
time_passed = 0
while True:
while instructions != 's':
instructions = input('Enter "s" to start counting:')
if instructions == 's':
startTime = time.time()
while instructions != 'p' and instructions != 'e':
instructions = input('Enter "p" to pause counting, "e" to stop counting:')
if instructions == 'p':
pauseTime = time.time()
time_passed += round(pauseTime - startTime, 2)
print(str(time_passed) + ' seconds has passed')
continue
elif instructions == 'e':
endTime = time.time()
time_passed += round(endTime - startTime, 2)
break
print(str(time_passed) + ' seconds has passed')
| true |
82ef5e40200d640dc2b5398235f81c5c928cbe86 | sohinimshah/Portfolio | /portfolio/monthspractice.py | 830 | 4.4375 | 4 | '''Write a program that indicates whether a specified month has 28, 30, or 31 days.'''
#(hint: something goes here)
def numDays(month):
January == "31"
February == "28"
March == "31"
April == "30"
May == "31"
June == "30"
July == "31"
August == "31"
September == "30"
October == "31"
November == "30"
December == "31"
if(month == "January") or (month == "March") or (month == "May") or (month == "July") or (month == "August") or (month == "October") or (month == "December"):
return "31"
elif(month == "April") or (month == "June") or (month == "September") or (month == "November"):
return "30"
elif(month == "February"):
return "28"
def main():
days = numDays(September)
print(days)
main()
| true |
e38476eb15e8af26be2dcf50f9ef9b9091d3ae20 | langdawang678/Py | /A_datatype/str_operate.py | 889 | 4.125 | 4 | """
1、字符串翻转(2种)
2、字符串中移除指定位置的字符
3、字符串作为代码执行
"""
# 1、字符串反转
# 方式1
s = "adb"
# reversed(seq) ,seq可以是 tuple, string, list 或 range。 s= reversed(str1) # 返回一个反转的迭代器。
print(s) # <reversed object at 0x02A255B0>
print(type(s)) # <class 'reversed'>
print(list(s)) # ['b', 'd', 'a']
string = 'Runoob'
print(''.join(reversed(string)))
# 方式2
string = 'Runoob'
print(string[::-1])
# 2、字符串中移除指定位置的字符
test_str = "Runoob"
# 移除第三个字符 n,索引为2
new_str = ""
for i in range(0, len(test_str)):
if i != 2:
new_str = new_str + test_str[i]
print("字符串移除后为 : " + new_str)
# 3、字符串作为代码执行
# https://www.runoob.com/python3/python3-func-exec.html
# https://www.runoob.com/python/python-func-eval.html
| false |
90a53599d2511c493a6cd172063b4c547196e3d6 | langdawang678/Py | /A_OOP/c18a18自定义属性访问.py | 2,571 | 4.3125 | 4 |
"""
官方文档:
https://docs.python.org/zh-cn/3/reference/datamodel.html#customizing-attribute-access
内置的魔术方法,在增删查时会触发,重写则可以完成特定的赋值/逻辑,
但还是要调用父类的,因为重写的只是加了逻辑,并没有增删查的实现。
(调用父类的有 object和super()两种方式,注意入参有没有 self)
"""
class Test:
def __init__(self):
self.age = 18
# 官方文档提示:当找不到属性的时候要么抛出异常
# 要么返回一个特定的数值
def __getattr__(self, item):
# 当我们访问属性的时候,属性不存在的时候触发该方法,出现AttrError
print("----这个是__getattr__方法----")
# return super().__getattribute__(item)
# return object.__getattribute__(self, item)
'''super()相当于是个实例,不用加self'''
'''object类,需要加self'''
return 100
def __getattribute__(self, item):
# 访问/查找属性的时候第一时间触发
print("----__getattribute__----")
# 返回父类查看属性的功能方法
return super().__getattribute__(item)
def __setattr__(self, key, value):
# 设置属性时,调用该方法设置属性
# print("__setattr__=", key) # 属性名称
# print("__setattr__=", value) # 属性值
# 可以重写这个设置一些干扰操作
if key == "age":
# 这样属性在外界对age的修改不会生效
return super().__setattr__(key, 18)
# 返回父类的设置属性的方法
return super().__setattr__(key, value)
def __delattr__(self, item):
# 在del obj.attr删除属性时触发
print("__delete__被触发了")
# 我们可以控制哪个属性不能被外界删除
print(item)
if item == "age":
print("不能被删除")
else:
return super().__delattr__(item)
t = Test()
# 设置属性的时候 触发__setattr__
t.name = "111"
# 先触发查找的方法,找到了不会在去触发__getattr__方法
print(t.name)
# 先触发查找方法,找不到才去触发__getattr__方法
print(t.name1)
# 设置修改age属性,触发__setattr__
t.age = 1111111
t.name = "2222222"
print(t.age) # >>>在 __setattr__方法中过滤了,还是18
print(t.name) # 会被修改
# 删除的时候触发__delattr__
del t.name
print(t.name) # 属性删除了
del t.age
print(t.age) # 过滤了这个属性不能在被外界删除了
| false |
80aea5093c478ce6c49fec8f8ca64353955723ab | bomcon123456/DSA_Learning | /Python/Chapter 2/ex4.py | 956 | 4.21875 | 4 | class Flower:
def __init__(self, name, petals, price):
self._name = name
self._petals = float(petals)
self._price = float(price)
def price(self):
return self._price
def petals(self):
return self._petals
def name(self):
return self._name
def set_name(self, name):
self._name = name
def set_petals(self, petals):
self._petals = float(petals)
def set_price(self, price):
self._price = float(price)
if __name__ == "__main__":
bucket = []
bucket.append(Flower("Rose", "10", "50"))
bucket.append(Flower("Daisy", "5", "10"))
bucket.append(Flower("Lavender", "15", "20"))
for i in range(1, 5):
bucket[0].set_price(bucket[0].price() * i)
bucket[1].set_price(bucket[1].price() * i)
bucket[2].set_price(bucket[2].price() * i)
print(bucket[0].price())
print(bucket[1].price())
print(bucket[2].price())
| false |
6bfd6b82a19b282a26db18bf6335894e2a561de6 | vkguleria/exercises | /capitalize.py | 379 | 4.28125 | 4 | # Complete the solve function below.
# input a string and it'll capitalize the initial letter of words found in the string
# input sample "Hi there 3g v3inod Vinod ji"
#
import re
def solve(s):
def do_capitalize(m):
return m.group(0).capitalize()
return re.sub(r'\w+',do_capitalize,s)
if __name__ == '__main__':
s = input()
result = solve(s)
print(result)
| true |
fb45c6f444a3af003534bda8688061e7a6b5e0a3 | HilaryAnn/Python-bootcamp | /ex1_part3_primelimits.py | 1,545 | 4.1875 | 4 | #
# Find all Prime Numbers up to N.
#
#
# function to check if a number is a prime
#
def FindPrime (test_num):
isPrime = True
sqroot_num=int(test_num**0.5)+1
#clearprint("square root",sqroot_num)
for ii in range (2,sqroot_num):
result = test_num%ii
#print(" ii ",ii,"result ", result)
if result== 0 :
isPrime=False
break
else:
isPrime = True
if isPrime:
print ("Number " + str(test_num) +" is prime" )
return True
else:
#print ("Number " + str(test_num) +" is not prime" )
return False
#
# Function to make user enter a number
#
def check_input(message):
while True:
try:
# Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
output_var = float(input(message))
except ValueError:
print("Sorry, I didn't understand that. Press CTRL Z to exit")
#better try again... Return to the start of the loop
continue
else:
#age was successfully parsed!
#we're ready to exit the loop.
break
return output_var
# ---------------------------------
# start of body of program
# -------------------------------
prime_lower = int(check_input( "Enter the lower limit for Prime Numbers "))
prime_upper = int(check_input( "Enter the upper limit for Prime Numbers "))
'''
print ("Number " + str(2) +" is prime" )
print ("Number " + str(3) +" is prime" )
prime_numbers=prime_numbers-2
'''
i=1
for i in range (prime_lower, prime_upper) :
#print(" i ", i)
result = FindPrime(i)
i=i+1
| true |
266f16638743c35b42d2997b8df36cbfa6484038 | shrutipai/CS-88 | /lab02/lab02_extra.py | 1,736 | 4.15625 | 4 | # Optional lab02 questions.
def square(x):
return x * x
def twice(f,x):
"""Apply f to the result of applying f to x"
>>> twice(square,3)
81
"""
"*** YOUR CODE HERE ***"
def increment(x):
return x + 1
def apply_n(f, x, n):
"""Apply function f to x n times.
>>> apply_n(increment, 2, 10)
12
"""
"*** YOUR CODE HERE ***"
def zero(f):
def _zero(x):
return x
return _zero
def successor(n):
def _succ(f):
def t(x):
return f(n(f)(x))
return t
return _succ
def one(f):
"""Church numeral 1: same as successor(zero)"""
"*** YOUR CODE HERE ***"
def two(f):
"""Church numeral 2: same as successor(successor(zero))"""
"*** YOUR CODE HERE ***"
three = successor(two)
def church_to_int(n):
"""Convert the Church numeral n to a Python integer.
>>> church_to_int(zero)
0
>>> church_to_int(one)
1
>>> church_to_int(two)
2
>>> church_to_int(three)
3
"""
"*** YOUR CODE HERE ***"
def add_church(m, n):
"""Return the Church numeral for m + n, for Church numerals m and n.
>>> church_to_int(add_church(two, three))
5
"""
"*** YOUR CODE HERE ***"
def mul_church(m, n):
"""Return the Church numeral for m * n, for Church numerals m and n.
>>> four = successor(three)
>>> church_to_int(mul_church(two, three))
6
>>> church_to_int(mul_church(three, four))
12
"""
"*** YOUR CODE HERE ***"
def pow_church(m, n):
"""Return the Church numeral m ** n, for Church numerals m and n.
>>> church_to_int(pow_church(two, three))
8
>>> church_to_int(pow_church(three, two))
9
"""
"*** YOUR CODE HERE ***"
| true |
7af460747fc7397c811e3cc452b1ccda8ad4aa23 | zwickers/EPI-Python | /LinkedLists/01_merge_two_sorted_lists.py | 1,080 | 4.25 | 4 | #
# Question: Consider two singly Linked Lists
# in which each node holds a number. Assume each
# list is sorted in ascending order within each list.
# The merge of the two lists is a list consisting of the
# nodes of the two lists in which numbers appear in ascending order
# Write a function takes in two such lists and returns their merge.
#
class ListNode:
def __init__(self,data=0,next=None):
self.data = data
self.next = next
# Time complexity: Time complexity : O(n+m) where n is the number of
# nodes in the first list, and m is the number of nodes in the second list
# Space complexity: O(1) because we just use the existing nodes
def merge_two_sorted_lists(head1, head2):
dummy_head = tail = ListNode()
while head1 and head2:
if head1 < head2:
tail.next = head1
head1 = head1.next
else: # head2 < head1
tail.next = head2
head2 = head2.next
tail = tail.next
# append the remaining list
tail.next = L1 or L2
return dummy_head.next
| true |
a87cd02a75e793b028d6a71589539909d21914cd | karenahuang/BackUp_PythonClassCode | /inclass11/count_words_dictionary.py | 861 | 4.28125 | 4 | # Counting letters in a word
# See textbook
word = 'brontosaurus'
d = dict()
for c in word:
if c not in d:
d[c] = 1
#at the end, dictionary has letter and frequency of it
else:
d[c] += 1
print('Counting letters in ', word ,d)
# Counting the words in a sentence
counts = dict()
myString = "I think Python is fun. I believe Python is powerful."
# words is a list
words = myString.split()
for word in words:
if word not in counts:
counts[word]= 1
else:
counts[word] += 1
print('\ncounts: ', counts)
# Advance practice
# An easier faster way to count occurence in a list
my_new = dict()
for word in words:
my_new[word] = my_new.get(word,0) + 1
print('\ncounts: ', my_new)
# Note: get returns 0 if the word is not found as a key in my_new
# if the word is in my_new then it returns the value of word
| true |
50466f1c93591519a17f2c1d1f8c0ec399fb4545 | karenahuang/BackUp_PythonClassCode | /hw2/sec2_15_exercise5.py | 569 | 4.5 | 4 | celsius = input("Please input a temperature in Celsius: ")
#user asked for temperature
celsius = float(celsius)
#input casted as float in case it was in form of decimals
fahrenheit = celsius*(9/5) + 32
#input was calculated into fahrenheit using fahrenheit formula and assigned to fahrenheit variable
celsius = str(celsius)
#celsius input was casted into string again
fahrenheit = str(fahrenheit)
#fahrenheit that was calculated is casted into string as well
print(celsius + " converted to degrees Fahrenheit is: " + fahrenheit)
#final result is printed out as string
| true |
20e49e8e1b293d4a148591c45cb4883803da0c17 | LccAckerman/Data-Structure-Work | /stack and queue/Days-old#2.py | 2,114 | 4.40625 | 4 | def nextDay(year, month, day):
"""Simple version: assume every month has 30 days"""
if day < daysInMonth(year, month):
return year, month, day + 1
else:
if month == 12:
return year + 1, 1, 1
else:
return year, month + 1, 1
def datelsBefore(year1, month1, day1, year2, month2, day2):
# if year1 > year2:
# return False
# elif year1 == year2 and month2 < month1:
# return False
# elif year2 == year1 and month1 == month2 and day1 > day2:
# return False
# else:
# return True
if year1 < year2:
return True
if year1 == year2:
if month1 < month2:
return True
if month1 == month2:
return day1 < day2
return False
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
"""Returns the number of days between year1/month1/day1
and year2/month2/day2. Assumes inputs are valid dates
in Gregorian calendar, and the first date is not after
the second."""
# YOUR CODE HERE!
assert datelsBefore(year1, month1, day1, year2, month2, day2)
days = 0
while datelsBefore(year1, month1, day1, year2, month2, day2):
year1, month1, day1 = nextDay(year1, month1, day1)
days += 1
return days
def daysInMonth(year, month):
if month in [1, 3, 5, 7, 8, 10, 12]:
return 31
elif month in [4, 6, 9, 11]:
return 30
else:
if isLeapYear(year):
return 29
else:
return 28
def isLeapYear(year):
return year % 4 == 0 and year % 100 != 0
def test():
test_cases = [((2012, 1, 1, 2012, 2, 28), 58),
((2012, 1, 1, 2012, 3, 1), 60),
((2011, 6, 30, 2012, 6, 30), 366),
((2011, 1, 1, 2012, 8, 8), 585),
((1900, 1, 1, 1999, 12, 31), 36523)]
for (args, answer) in test_cases:
result = daysBetweenDates(*args)
if result != answer:
print("Test with data:", args, "failed")
else:
print("Test case passed!")
test()
| true |
d8aac2049587578c2816ed3ab6c1a8be2bbc5a40 | sophiallen/csc110-hw | /SophiaAllen-hw2-yt.py | 1,141 | 4.1875 | 4 |
import turtle
wn = turtle.Screen()
alice = turtle.Turtle()
def sqSpiral():
sideLen = eval(input("Beginning Length:")) #starting side length, will also act as accumulator
chgLen = eval(input("Change in Length:"))
numSides = eval(input("Number of sides to draw:"))
if chgLen < 0: #If it's an inward spiral, move so that it appears in center of screen.
reposition(sideLen) #(Outward spirals automatically start from center, unless repositioned by user.)
for i in range(numSides):
alice.lt(90)
alice.fd(sideLen)
sideLen += chgLen #increase or decrease side length using pos/neg chgLen
def reposition(maxWidth):
halfDist = maxWidth/2
alice.pu()
alice.fd(halfDist) #go half the width of future spiral to the right
alice.rt(90)
alice.fd(halfDist) #and half the width down
alice.lt(90)
alice.pd() #then put down pen and point in correct direction.
def spiral(startRadius, changeFactor, times): #I made a circular spiral for fun!
times *= 6
times = int(times)
for i in range(times):
alice.circle(startRadius +(i*changeFactor),60)
| true |
f845f3bce8d8e395e56253fb8b23f492f0b9c803 | blaq-swan/alx-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 485 | 4.1875 | 4 | #!/usr/bin/python3
"""module for text_indentation method"""
def text_indentation(text):
"""Adds two lines after :?.
Args:
text: source string
Raises:
TypeError: if text is not a string
"""
if not isinstance(text, str):
raise TypeError("text must be a string")
for delimeter in "?:.":
text = (delimeter + "\n" * 2).join(
[line.strip(" ") for line in text.split(delimeter)]
)
print(text, end="")
| true |
a6cb2700aff2d285925c3b54dab1536461172511 | tran3mx/Workshop02 | /converter.py | 294 | 4.25 | 4 | print ("Temperature Conversion Program")
celsiusValue = float(input("Enter the Celsius Value:"))
fahrenheitValue = celsiusValue * 9 / 5 + 32
kelvinValue = celsiusValue + 273.15
print("celsius Value:", celsiusValue)
print("Fahrenheit Value:", fahrenheitValue)
print("Kelvin Value:", kelvinValue) | false |
a014bb7b1e3fed5bf7b5b279f1e74f30e3e358c6 | Deven-14/Python_Level_1 | /concatinatedStringToDictAndViceVersa.py | 626 | 4.1875 | 4 |
def input_concatinated_string():
return input("Enter a concatinated string: ");
def concatinated_string_to_dict(concatinated_string):
return {str1: str2 for str1, str2 in (string.split('=') for string in concatinated_string.split(';'))}
def dict_to_concatinated_string(dict_):
return ';'.join(['='.join(ele) for ele in dict_.items()])
def main():
concatinated_string = input_concatinated_string()
dict_ = concatinated_string_to_dict(concatinated_string)
print(dict_)
concatinated_string = dict_to_concatinated_string(dict_)
print(concatinated_string)
if __name__ == "__main__":
main()
| false |
a1fe01a7ce9c22e1a4750aafe1c049f4e50bc3a3 | Lovecanon/ProfessionalPython | /Chapter5Metaclass/1.py | 857 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Hello(object):
def hello(self, name='world'):
print('Hello %s.' % name)
h = Hello()
# Hello是一个class,它的类型就是type,而h是一个实例,它的类型就是class Hello。
print(type(Hello)) # <class 'type'>
print(type(h)) # <class '__main__.Hello'>
# type()函数既可以返回一个对象的类型,又可以创建出新的类型
# 通过type()函数创建的类和直接写class是完全一样的,因为Python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用type()函数创建出class
def fn(self, name='World'):
print('New Hello %s.' % name)
NewHello = type('NewHello', (object,), dict(hello=fn))
nh = NewHello()
print(type(NewHello)) # <class 'type'>
print(type(nh)) # <class '__main__.NewHello'>
nh.hello()
| false |
043364400f27e3e70d51a951dc33ec29520be649 | akanshagupta939/Python-Practice | /User.py | 333 | 4.1875 | 4 | from array import *
count=int(input("Number of names you want to enter"))
arr_name=[]
def count_text(arr_name):
c=0
for char in arr_name:
c=c+1
print("value of ",arr_name, "is ",c)
for i in range(count):
arr=input("Enter the name")
arr_name.append(arr)
count_text(arr_name)
print(arr_name)
| true |
3dbe67844dddc07986036d2075b45ae2d6a7e79f | lwm14/PythonProject | /PythonProject/main.py | 966 | 4.21875 | 4 | #Main method to run code for the qs method
"""
method to call something for if __name__ == '__main__':
main()
let's python execute code in file, whatever if written in this method will be called
"""
if __name__ == '__main__':
main()
import quicksort
quicksort.main()
""" read file function that should read the file and use qs to implement"""
def readFile(quicksort):
file = open(quicksort)
quicksort.readline()
for line in file:
print(line)
value = int(line)
print("the value is ", value)
##
"""write file function that will write to quicksort
"""
def writeFile(quicksort):
file = read(quicksort) #read from text from command line
#put into main
#read values from file
#file from values
#print results out
quicksort.close()
""" code to test """
array = [5,8,3,7,9]
n = len(array)
quicksort(array, 0,n-1)
print("sorted array is: ")
for i in range(n):
print("%d" % array[i])
| true |
604629942432d281dd8354c01a1ffd524808ea5e | osama-mohamed/python_projects | /python projects 3.6/إدخال رقم وضربه مع الأرقام الاصغر منه.py | 575 | 4.15625 | 4 | def factorial_iter(n):
result = 1
for n in range(1, n + 1):
result *= n
return result
print(factorial_iter(5))
def fact(n):
return 1 if n == 1 else n * fact(n - 1)
print(fact(5))
while True :
n = int(input('Enter a number : '))
def factorial(n):
if n == 0 :
return 1
else :
return n * factorial(n - 1)
print(factorial(n))
while True :
result = 1
a = input("Enter your factorial number : ")
if a == "":
exit()
elif a == " ":
exit()
for i in range(1, int(a)+ 1):
result *= i
print("The result is : ", result)
| false |
cefe22b4382251e430b95b860439865a5bda1794 | willyowi/codewars | /6kyu/multiplication_tables.py | 871 | 4.28125 | 4 | """Create a function that accepts dimensions, of Rows x Columns, as parameters
in order to create a multiplication table sized according to the given
dimensions. **The return value of the function must be an array, and the numbers
must be Fixnums, NOT strings.
Example:
multiplication_table(3,3)
1 2 3
2 4 6
3 6 9
-->[[1,2,3],[2,4,6],[3,6,9]]"""
def multiplication_table(row, col):
table = []
for num in range(1, row + 1):
row = []
for colum in range(1, col + 1):
row.append(num * colum)
table.append(row)
return table
def multiplication_tableV2(row, col):
table = []
for num in range(1, row + 1):
table.append([num * column for column in range(1, col + 1)])
return table
def multiplication_tableV3(row, col):
return [[num * column for column in range(1, col+1)] for num in range(1, row+1)]
| true |
522f60685302830614b238e6249d471be124e175 | junjianglin/Misc | /DesignPatterns/strategy_pattern.py | 1,776 | 4.5625 | 5 | #In strategy pattern, a class behavior or its algorithm can be changed at run time.
#For example, a class that performs validation on incoming data may use a strategy pattern to
#select a validation algorithm based on the type of data, the source of data,
#user choice, or other discriminating factors.These factors are not known for each case
#until run-time,and may require radically different validation to be performed.
#The code is borrowed from www.tutorialspoint.com/design_pattern/strategy_pattern.htm
class Strategy:
"""Abstract class concept for readability
"""
def doAlgo(self,num1,num2):
raise NotImplementedError("Strategy is supposed to be an abstract class!")
class OperationAdd(Strategy):
"""Concrete strategy class
"""
def doAlgo(self,num1,num2):
return num1+num2
class OperationSubstract(Strategy):
"""Concrete strategy class
"""
def doAlgo(self,num1,num2):
return num1-num2
class OperationMultiply(Strategy):
"""Concrete strategy class
"""
def doAlgo(self,num1,num2):
return num1*num2
class Context():
"""Context class determine which strategy to use
based on the given input
"""
def executeStrategy(self,num1,num2,input):
if input == '+':
algo = OperationAdd()
print algo.doAlgo(num1,num2)
elif input == '-':
algo = OperationSubstract()
print algo.doAlgo(num1,num2)
elif input == '*':
algo = OperationMultiply()
print algo.doAlgo(num1,num2)
else:
print "invalid input"
if __name__ == '__main__':
context = Context()
context.executeStrategy(10,18,'+')
context.executeStrategy(10,18,'-')
context.executeStrategy(10,18,'*')
| true |
7c89bc7d3e074999218d64ea5be898e6eed174e1 | junjianglin/Misc | /DesignPatterns/abstractFactory_pattern.py | 1,362 | 4.75 | 5 | # the code is borrowed and modified from
# www.tutorialspoint.com/design_pattern/abstract_factory_pattern.htm
# The difference between abstract factory and simple factory is that
# abstract factory generate different kinds of object
class Shape():
def __init__(self):
pass
class Circle(Shape):
def __init__(self):
print "creating Circle"
class Square(Shape):
def __init__(self):
print "creating Square"
class Color():
def __init__(self):
pass
class Red(Color):
def __init__(self):
print "drawing with red"
class Green(Color):
def __init__(self):
print "drawing with green"
class AbstractFactory():
def getShape(self):
pass
def getColor(self):
pass
class Factory(AbstractFactory):
def getShape(self,type):
if type == 'Square':
return Square()
elif type == 'Circle':
return Circle()
else:
print "not valid Shape"
def getColor(self,color):
if color == 'Red':
return Red()
elif color == 'Green':
return Green()
else:
print 'invalid color'
if __name__ == '__main__':
factory = Factory()
s1 = factory.getShape('Circle')
s2 = factory.getShape('Square')
c1 = factory.getColor('Red')
c2 = factory.getColor('Green')
| true |
83bc503241442f2cde9c895141d23076d35bac2a | Jangwoojin863/python | /queue.py | 879 | 4.34375 | 4 | # 리스트를 이용한 queue 자료 구조
# 큐 생성
my_queue = []
# 큐 넣기 함수
def put_queue( v ):
my_queue.append(v)
return v
# 큐 꺼내기 함수
def get_queue():
if(len(my_queue) > 0):
return my_queue.pop(0) # 0번째 요소
else:
return None
# 큐 자료 출력
def print_queue():
print("QUEUE: " + str(my_queue))
#---------------------------------------
# 메인 처리
print("PUT > " + str(put_queue(1)))
print("PUT > " + str(put_queue(2)))
print("PUT > " + str(put_queue(3)))
print("PUT > " + str(put_queue(4)))
print("PUT > " + str(put_queue(5)))
print_queue()
print("GET > " + str(get_queue()))
print("GET > " + str(get_queue()))
print("GET > " + str(get_queue()))
print("GET > " + str(get_queue()))
print("GET > " + str(get_queue()))
print("GET > " + str(get_queue()))
print_queue()
| false |
110413a8b19aedd2b51dccfda9c48cb5041db3f9 | galdauber1/Python-Projects | /Asteroids Game/ship.py | 1,427 | 4.1875 | 4 | import math
RADIUS = 1
RAD = 180
class Ship:
"""the class ship define the attributes of object from type ship
for the asteroids game"""
def __init__(self, x, y, speed_x=0, speed_y=0, degrees=0):
""" a constructor for creating a single ship object"""
self.__speed_x = speed_x
self.__x = x
self.__speed_y = speed_y
self.__y = y
self.__degrees = degrees
self.__radius = RADIUS
def get_degrees(self):
"""get the degrees"""
return self.__degrees
def set_degrees(self, degrees):
"""add degrees"""
self.__degrees += degrees
def set_speed_x(self):
"""add speed to ship in x"""
self.__speed_x += math.cos((self.__degrees * math.pi)/RAD)
def set_speed_y(self):
"""add speed to shipn in y"""
self.__speed_y += math.sin((self.__degrees * math.pi)/RAD)
def set_x(self, x):
"""set new x location"""
self.__x = x
def set_y(self, y):
"""set new y location"""
self.__y = y
def get_x(self):
"""get the x location"""
return self.__x
def get_y(self):
"""get y location"""
return self.__y
def get_speedx(self):
"""get speed_x"""
return self.__speed_x
def get_speedy(self):
"""get speed_Y"""
return self.__speed_y
def get_radius(self):
return self.__radius
| false |
8f1c57c7c014f21b32fadddb062126dd5cb141d3 | MiraiP/CS3612017 | /Python/exercise1.py | 524 | 4.28125 | 4 | print("a) 5/3 = " , 5/3)
print("The result is 1.666667, since this is float division \n")
print("b) 5%3 = " , 5%3)
print("2 is the remainder of 5/3, % is modulo \n")
print("c) 5.0/3 = " , 5.0/3)
print("Still 1.6667, because this is still float division regardless of the component types \n")
print("d) 5/3.0 = " , 5/3.0)
print("Still 1.6667, because this is still float division regardless of the component types \n")
print("e) 5.2%3 = " , 5.2%3)
print("2.2 is the remainder of 5.2/3, since % is modulo.")
| true |
c8a6696c5e6468ace1653bc000cfd82275bb1545 | amrs-tech/Caesar-Box-Cipher | /BoxCipher.py | 1,509 | 4.125 | 4 | from time import sleep
def encrypt():
instr = ''
instr = input("\nEnter the Text to Encrypt: ")
width = int(input("\nEnter the box width of your cipher : "))
instr += '$'* (width - len(instr)%width) #Making the string to fit box size
enc = ''
for x in range(0,width):
for i in range(x,len(instr),width):
enc += instr[i]
sleep(3)
print("\nEncrypted Text: "+enc+'\n')
def decrypt():
instr = input("\nEnter the Text to Decrypt: ")
Len = len(instr)
width = int(input("\nEnter the box width of your cipher : "))
#To set the box size according to the Encrypted text
if Len%width != 0:
width = int(Len/width)
width += 1
else:
width = int(Len/width)
dec = ''
for x in range(0,width):
for i in range(x,Len,width):
if instr[i] == '$':
continue
dec += instr[i]
sleep(3)
print("\nDecrypted Text: "+dec+'\n')
if __name__ == "__main__":
flag = 1
while flag:
print("\n\t\t Encrypt/Decrypt Text using Caeser Box Cipher\n")
sleep(2)
choice = input("\nEnter whether to 'encrypt' or 'decrypt': ")
if choice.lower() == 'encrypt':
encrypt()
flag = 0
elif choice.lower() == 'decrypt':
decrypt()
flag = 0
else:
print("\nWrong Choice !\n")
flag = 1
| true |
e365fdf307cb493100d3db38aaddb008c2ea07b5 | aronlg/skoli | /exams/final20/election/election.py | 1,714 | 4.15625 | 4 | def get_candidate_votes():
'''Returns a tuple consising of a name of a candidate and votes given to him/her.
Either or both of the elements of the tuple can have the value None indicating an invalid input.'''
candidate, votes = None, None
input_list = input("Candidate and votes: ").split()
if len(input_list) > 0:
candidate = input_list[0].lower()
if len(input_list) > 1:
try:
votes = int(input_list[1])
except ValueError:
pass
return candidate, votes
def add_results(result_dict, candidate, votes):
'''Adds the votes to the given to candidate in the given dictionar'''
if candidate in result_dict:
result_dict[candidate] += votes
else:
result_dict[candidate] = votes
def get_total_votes(result_dict):
'''Returns the total number of votes for the given result dictionary'''
total = 0
for candidate in result_dict:
total += result_dict[candidate]
return total
# Simpler solution
# return sum(result_dict.values())
def print_results(result_dict):
'''Prints the current results of the election in ascending order candidate names'''
for candidate in sorted(result_dict):
print("{}: {}".format(candidate, result_dict[candidate]))
# Main
election_dict = {}
candidate = ''
while candidate is not None:
candidate, votes = get_candidate_votes()
if candidate is not None:
if votes is not None:
add_results(election_dict, candidate, votes)
else:
print("Invalid no. of votes!")
print_results(election_dict)
print("Total no. of votes: {}".format(get_total_votes(election_dict)))
| true |
0302d97951f7340c04d5baf376c405d49b5b478d | jmendez1340/PRG-105-Chapter9 | /Exercise7.py | 1,248 | 4.28125 | 4 | # You don't have to choose fin. I just chose it because it is a common name for an object used for input.
fin = open('words.txt')
def is_three_consecutive_double_letters(word):
# Here is where we test what words have 3 consecutive double letters
i = 0
count = 0 # It starts at 0 and it will soon contain the total # of eligible words
while i < len(word)-1:
if word[i] == word[i+1]:
count = count + 1
if count == 3: # We only want words with 3 consecutive double letters to appear
return True # This causes only the words without an e to appear
i = i + 2 # QUESTION (As I looked for the answer from what was given, but I do not understand why this had to be a 2.
else:
count = 0
i = i + 1
return False
def find_three_consecutive_double_letters():
# Here is where the words will be printed once verified
fin = open('words.txt')
for line in fin:
word = line.strip() #Strip gets rid of the whitespace
if is_three_consecutive_double_letters(word):
print word
print 'Here are the few words in the text file that have three consecutive double letters.'
find_three_consecutive_double_letters()
print ''
| true |
463f9be2fd66f936e96418844802c684d8fdd347 | ankitniranjan/HackerrankSolutions | /Regex/Matching_Whitespace_&_Non-Whitespace_Character.py | 289 | 4.1875 | 4 | # You have a test string . Your task is to match the pattern XXaXXaXX
# Here, a denotes whitespace characters, and X denotes non-white space characters.
Regex_Pattern = r"\S{2}\s\S{2}\s\S{2}" # Do not delete 'r'.
import re
print(str(bool(re.search(Regex_Pattern, input()))).lower())
| true |
9a98339a40141529deef8ccfbe45a23b4955b43d | unw1ck3d/python18 | /Lessons/Lesson_2/example_lesson2.py | 271 | 4.125 | 4 | cars = ['volvo', 'bmw', 'citroen', [1, 2, 3]]
# print(cars)
# cars.append('opel')
# print(cars)
# print(cars[3][2])
# deleted = cars.pop(0)
# print(cars, deleted)
cars[0], cars[1] = cars[1], cars[0]
del cars[3]
# cars.remove('opel')
cars.sort()
cars.reverse()
print(cars) | false |
8951927b09bf783478526a5a63c6ea936b9db934 | Deirdre18/test-driven-development-with-python | /asserts.py | 2,322 | 4.46875 | 4 | #x = 2
#y = 1
#assert x < y, "{0} should be less than {1}".format(x, y)
#print(x + y)
#let's say,for instance, that we didn't know what the values of X and Y were going to be;
#or, rather, that we wanted to perform a test on those values and throw an error
#if a specific condition wasn't met. We can do that using the assert keyword in
#Python. As we said, this statement should return true and, if it does, the program
##will execute as normal. So, let's insert one here before our print statement. Assert X
# less than Y, and then we can put a message here in case the assert
#statement fails. So we can say that X should be less than Y. Now, when we run it
#of course the assert statement will return true because X is less than Y, 1
#is less than 2. Let's just test that to make sure that it does what we expect.
#Good! Everything seems to work as normal.
#x = 1
#y = 2
#assert x < y, "x should be less than y"
#print(x + y)
#Let's try making
#the test fail. Because, if the assertion is false then an error is
#thrown and will never actually get to our print statement. We can do that by
#changing the values of X and Y. Let's just switch them around, so that now X is
#equal to 2 and Y is equal to 1. This time, when we run our script, it should fail
#and we should get an error message. Do you see there that we get an assertion
#error telling us that X should be less than Y? That's not the
#friendliest error in the world, we can make it a little bit friendlier if we
#insert values into the assert message. So, let's do that now.
#x = 2
#y = 1
#assert x < y, "x should be less than y"
#print(x + y)
#Let's try making the test fail. Because, if the assertion is false then an error is
#thrown and will never actually get to our print statement. We can do that by
#changing the values of X and Y. Let's just switch them around, so that now X is
#equal to 2 and Y is equal to 1. This time, when we run our script, it should fail
#and we should get an error message. Do you see there that we get an assertion
#error telling us that X should be less than Y? That's not the
#friendliest error in the world, we can make it a little bit friendlier if we
#insert values into the assert message. So, let's do that now.
x = 2
y = 1
assert x < y, "{0} should be less than {1}".format(x, y)
print(x + y)
| true |
105c65d54bc932bbfe6abfaa33835f14913ac64f | bhumijaapandey248/Python-Programs-Assignments | /assignment18.1.py | 1,635 | 4.1875 | 4 | ##1. Write a program to print all prime numbers between 1 and n (entered by the user).
##5
##10
##2 3 5 7
##
##20
##2 3 5 7 11 13 17 19
##
##25
##2 3 5 7 11 13 17 19 23
##
##45
##2 3 5 7 11 13 17 19 23 29 31 37 41 43
##
##50
##2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
def prime_number(n):
for no in range(1,n+1):
temp=0
for i in range(1,no+1):
if(no%i==0):
temp=temp+1
if(temp==2):
print(no,end=" ")
print("\n")
t=int(input())
while(t>0):
n=int(input())
prime_number(n)
t=t-1
##def PrimeNumber(n):
## for no in range(1,n+1):
## temp=0
## for i in range(1,no+1):
## if(no%i==0):
## temp=temp+1
## if(temp==2):
## print(no)
##
##n=int(input())
##PrimeNumber(n)
##def PrimeNumber(n):
## t=int(input("test case"))
## while(t>0):
## temp=0
## for i in range(1,n+1):
## if(n%i==0):
## temp=temp+1
## if(temp==2):
## print("It is prime number !!")
## else:
## print("It is not prime number !!")
## t=t-1
##
##n=int(input())
##PrimeNumber(n)
##t=int(input(""))
##while(t>0):
## n=int(input(""))
##
## for no in range(1,n+1):
## temp=0
## for i in range(1,no+1):
## if(no%i==0):
## temp=temp+1
## if(temp==2):
## print(no,end=" ")
##
## print("\n")
## t=t-1
##
| false |
e4b58437a484498a88f837aa4b43c7afe4891fd1 | bhumijaapandey248/Python-Programs-Assignments | /assignment18.2.py | 626 | 4.3125 | 4 | ##2.Write a program using function that takes two numbers as input and returns the GCD.
##Input Example: -
##2
##5 10
##14 8
##Output Example: -
##5
##2
def GCD(num1,num2):
while(num2!=0):
r=num1%num2
num1=num2
num2=r
return num1
t=int(input())
while(t>0):
n=input().split()
n1=int(n[0])
n2=int(n[1])
## print("n1",n1,"n2",n2)
print(GCD(n1,n2))
t=t-1
##def GCD(num1,num2):
## while(num2!=0):
## r=num1%num2
## num1=num2
## num2=r
## return num1
##n1=int(input())
##n2=int(input())
##print(GCD(n1,n2))
| true |
7b9779c15294a2ff298e6064e56fe7642e144151 | bhumijaapandey248/Python-Programs-Assignments | /assignment15.3.py | 549 | 4.28125 | 4 | ##3. Write a program that takes a sequence of comma separated integers from console and generate a list and a tuple that contains every number.
##Input Format: The only line of input takes a sequence of comma separated integers.
##Output Format: The first line of output displays the list and second line of output displays the tuple.
##Example Input:
##34,67,55,33,12,98
str=input()
res=str.split(",")
## list return krta h
res=list(map(int,res))
print(res)
res=tuple(map(int,res))
print(res)
##res=set(map(int,res))
##print(res)
| true |
d70e374d223c5062e1391522ca790f4433fdac90 | bhumijaapandey248/Python-Programs-Assignments | /assignment20.2.py | 1,035 | 4.21875 | 4 | ##2. Write a program using function equalIndex( n, arr ) and return the value whose value is equal to that of its index value (starting with 1).
##Input Format: The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N, size of array. The second line of each test case contains array elements.
##Output Format: Print the element whose value is equal to index value. Print "Not Found" when index value does not match with value.
##Example Input:
##2
##5
##15 2 45 12 7
##1
##1
##Output:
##2
##1
##Explanation:
##In the 1st testcase, 15 is at index 1, 2 is at index 2 and so on. So, we printed 2 because index
##matches with the number.
def equalIndex( n, arr ):
for pos,element in enumerate(arr):
if(pos+1==element):
print(f"{element}")
t=int(input())
while(t>0):
n=int(input())
str=input()
lst=str.split()
arr=list(map(int,lst))
equalIndex( n, arr )
##print(arr)
| true |
298a4237a00154aafa033148b0959652b4a637a9 | monkeydminh49/py4e | /10.Tuples/Ex3.py | 901 | 4.15625 | 4 | # Exercise 3: Write a program that reads a file and prints the letters
# in decreasing order of frequency. Your program should convert all the
# input to lower case and only count the letters a-z. Your program should
# not count spaces, digits, punctuation, or anything other than the letters
# a-z. Find text samples from several different languages and see how
# letter frequency varies between languages. Compare your results with
# the tables at https://wikipedia.org/wiki/Letter_frequencies.
handle = open(input('Enter a file name: '))
d = {}
import string
for line in handle:
line.rstrip()
line = line.translate(str.maketrans('', '', string.punctuation))
line = line.lower()
words = line.split()
for word in words:
for let in word:
d[let] = d.get(let, 0) + 1
ls = sorted([(v, k) for k, v in d.items()], reverse=True)
for v, k in ls:
print(k, v)
| true |
67e30f00cc40bab93089485deec466cb996808a8 | uimran/CodingChallenges | /NestedLists.py | 1,511 | 4.25 | 4 | # the list 'students' is a nested list with all the student names with their repsective scores
students=[]
# the list 'scores' holds all the scores of students
scores=[]
# the list 'first_low' holds the first lowest scores
first_low=[]
# the list 'second_low' holds the second lowest scores
second_low=[]
for i in range(int(raw_input())):
name = raw_input()
score = float(raw_input())
# the name and score of a student are appended as a list in the list students
students.append([name,score])
scores.append(score)
for item in students:
# item[1] holds the score value for a student (item[0] holds the name), if it is the lowest in the list scores, it will be added to the first_low list
if item[1] == min(scores):
first_low.append(item)
# In order to find the second lowest grade, it is essential to first get rid of the first lowest scores from the lists students and scores. Because once it is removed, it will then consider the lowest from both the lists again (this will actually be the second lowest score now)
for item in first_low:
del students[students.index(item)]
del scores[scores.index(item[1])]
for item in students:
# item[1] holds the score value for a student (item[0] holds the name), if it is the lowest in the list scores, it will be added to the second_low list (since first lowest already removed)
if item[1] == min(scores):
second_low.append(item)
second_low.sort()
for name in second_low:
print name[0]
| true |
a2a34b4b38f258c2f5b652ec2141f93563bf998a | Chase-42/cs-module-project-algorithms | /sliding_window_max/sliding_window_max.py | 797 | 4.1875 | 4 | '''
Input: a List of integers as well as an integer `k` representing the size of the sliding window
Returns: a List of integers
'''
from collections import deque
def sliding_window_max(nums, k):
maxNums = []
Deque = deque()
for i, num in enumerate(nums):
while len(Deque) > 0 and num > Deque[-1]:
Deque.pop()
Deque.append(num)
window = i - k + 1
if window >= 0:
maxNums.append(Deque[0])
if nums[window] == Deque[0]:
Deque.popleft()
return maxNums
if __name__ == '__main__':
# Use the main function here to test out your implementation
arr = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
print(f"Output of sliding_window_max function is: {sliding_window_max(arr, k)}") | true |
1ce0b18514185be069a08b2c3001e402c3a1e383 | kylung0208/KY_whatve_u_learned | /python-not-that-simple/1-how_obj_passed_to_functions/list_manipulation.py | 1,564 | 4.21875 | 4 | def func1(list):
print(f"[func1] lst1 = {list}, id = {id(list)}")
list = [9, 11]
print(f"[func1] lst1 = {list}, id = {id(list)}")
def func2(list):
print(f"[func2] lst2 = {list}, id = {id(list)}")
list += [9, 11]
list.append(50)
list.extend([60,70])
print(f"[func2] lst2 = {list}, id = {id(list)}")
def func3(list):
print(f"[func3] lst3 = {list}, id = {id(list)}")
list = list + [9, 11]
print(f"[func3] lst3 = {list}, id = {id(list)}")
if __name__ == '__main__':
lst1 = [1,3,5,7]
lst2 = [1,3,5,7]
lst3 = [1,3,5,7]
print(f"[main (before)] lst1 = {lst1}, id = {id(lst1)}")
print(f"[main (before)] lst2 = {lst2}, id = {id(lst2)}")
print(f"[main (before)] lst3 = {lst3}, id = {id(lst3)}")
func1(lst1)
func2(lst2)
func3(lst3)
print(f"[main (after)] lst1 = {lst1}, id = {id(lst1)}")
print(f"[main (after)] lst2 = {lst2}, id = {id(lst2)}")
print(f"[main (after)] lst3 = {lst3}, id = {id(lst3)}")
"""
[main (before)] lst1 = [1, 3, 5, 7], id = 4331219784
[main (before)] lst2 = [1, 3, 5, 7], id = 4331219848
[main (before)] lst3 = [1, 3, 5, 7], id = 4331264264
[func1] lst1 = [1, 3, 5, 7], id = 4331219784
[func1] lst1 = [9, 11], id = 4331264200
[func2] lst2 = [1, 3, 5, 7], id = 4331219848
[func2] lst2 = [1, 3, 5, 7, 9, 11, 50, 60, 70], id = 4331219848
[func3] lst3 = [1, 3, 5, 7], id = 4331264264
[func3] lst3 = [1, 3, 5, 7, 9, 11], id = 4331264136
[main (after)] lst1 = [1, 3, 5, 7], id = 4331219784
[main (after)] lst2 = [1, 3, 5, 7, 9, 11, 50, 60, 70], id = 4331219848
[main (after)] lst3 = [1, 3, 5, 7], id = 4331264264
""" | false |
bb7805ffc8ea30535d92cb24f40de7b92a5c59eb | umamaheswari-prakash/test | /find_continent.py | 262 | 4.375 | 4 | dictionary={"Spain":"Europe","Japan":"Asia","India":"asia","Italy":"Europe","Thailand":"Asia","Sudan":"Africa"}
val=input("enter the continent:")
print("country name:")
for key,value in dictionary.items():
if val.upper() == value.upper():
print(key)
| false |
194971ca643b2c914f5699af9581c6b05ff8f88e | baybird/DP | /02.simple-factory.py | 821 | 4.15625 | 4 | # Filename : 02.simple-factory.py
# Author : Robert Tang
# Created : 4/5/2017
# Last Modified :
# Description : Simple Factory Pattern of Creational Patterns
# Python Version: 2.7
from abc import ABCMeta, abstractmethod
# Abstract product
class Car:
# instance of ABCMeta
__metaclass__ = ABCMeta
@abstractmethod
def getType(self):
pass
# Concrete products
class Truck(Car):
def getType(self):
return 'Truck'
class Van(Car):
def getType(self):
return 'Van'
# Factory
class Factory:
@staticmethod
def createProduct(product):
if product == 'Truck':
return Truck()
elif product == 'Van':
return Van()
else:
return None
# Test
truck = Factory.createProduct('Truck')
print truck.getType()
van = Factory.createProduct('Van')
print van.getType()
| true |
705ca131db17f8566f27ebc9517a5da5aba1df52 | timurkurbanov/InheritancePart1 | /ex.py | 1,085 | 4.40625 | 4 | class Person:
def __init__(self, name):
self.name = name
def greeting(self):
print(f"Hi, my name is {self.name}")
class Student(Person):
def learn(self):
print('I get it!')
class Instructor(Person):
def teach(self):
print('An object is an instance of a class')
nadia = Instructor('Nadia')
nadia.greeting()
nadia.teach()
print()
chris = Student('Chris')
chris.greeting()
chris.learn()
#Create a parent Person class that contains the attribute name and an __init__() method to set the name.
#instructor and student greeting, "Hi, my name is so-and-so". Where's the best place to put this common method?
#Create an instance of instructor whose name is "Nadia" and call their greeting.
#Create an instance of instructor name is "Nadia" and call their greeting.
#Create an instance of student name is "Chris" and call their greeting.
#Call the teach method instructor call the learn student.
#call the teach method on your student instance. What happens? Why doesn't that work? Leave a comment in your program explaining why. | true |
3e8beebbea8bce550de80957ff4ef6eeb9e5c0e3 | MahimaSrikanta/Python_-IQ | /app_Sum_Nums.pyw | 217 | 4.3125 | 4 | '''
Question: Write a method that takes in an integer `num` and returns the sum of
all integers between zero and num, up to and including `num`.
'''
def Sum_num(num):
return num * (num+1)//2
print(Sum_num(5))
| true |
81154b99187b77a8218826bee60201fa53e95751 | chinmaykunkikar/UDCS-Assignments | /personal_assignments/rhyme/syllable_counter.py | 751 | 4.21875 | 4 | def count_syllables(word):
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
vowel_count = 0
vowel_last = False
for itr in word:
vowel_found = False
for v in vowels:
if v == itr:
if not vowel_last: # this will filter out diphthongs
vowel_count+=1
vowel_found = vowel_last = True
break
if not vowel_found:
vowel_last = False
# other conditions
if len(word) > 1 and word[-1:] == "e": # remove e
vowel_count-=1
elif len(word) > 2 and word[-2:] == "es": # remove es
vowel_count-=1
return vowel_count
word = input("Enter a word: ").lower()
print("Number of syllables: {}".format(count_syllables(word))) | false |
6e12014287f1938811c81f45a1caea3c1d6216cb | ParthShuklaa/MDU_Sept_2020_Batch- | /For_LoopDemo.py | 533 | 4.1875 | 4 | #WAP to Display your name five times along with Date and time
"""
Step1: Enter Your name and use For for diaplying it five times
For(inilization,Condition,Increment/decrement)
for (i = 0, i<10,<i++)
When i = 0 by default or i = i+1 , Do not write here in For loop
Step2: Include Datetime Module and then diaplay it
"""
import datetime
import time
Name = input("Enter your name \n")
for i in range(10):
print(Name)
CurrentDatetime = datetime.datetime.now()
print(CurrentDatetime)
time.sleep(1)
| true |
804a897895c73f1f60359cc1e14e78d452997b02 | green-fox-academy/Bpatrik83 | /week-02/day-05/04_guess_my_number.py | 1,450 | 4.3125 | 4 | """Exercise
Write a program where the program chooses a number between 1 and 100.
The player is then asked to enter a guess. If the player guesses wrong,
then the program gives feedback and ask to enter an other guess until the guess is correct.
Make the range customizable (ask for it before starting the guessing).
You can add lives. (optional)
Example
I've the number between 1-100. You have 5 lives.
20
Too high. You have 4 lives left.
10
Too low. You have 3 lives left.
15
Congratulations. You won!"""
from random import randint
original_number = (randint(1, 100))
check = True
lives = 5
while check:
try:
guess = int(input("Enter your tip: "))
if guess < 1 or guess > 100:
raise ValueError
else:
if guess == original_number:
check = False
print("Congratulations. You won!")
if guess > original_number:
lives -= 1
if lives > 0:
print("Too high. You have", lives, "lives left.")
if guess < original_number:
lives -= 1
if lives > 0:
print("Too low. You have", lives, "lives left.")
if lives < 1:
print("You lost. No more lives left", "The number was", original_number)
check = False
except ValueError:
print("Please enter only a number between 1 and 100")
| true |
78b451417d4bf578310c4aec3a02b06579c0a228 | green-fox-academy/Bpatrik83 | /week-02/day-03/02_reverse.py | 402 | 4.375 | 4 | # Create a function called 'reverse_string' which takes a string as a parameter
# The function reverses it and returns with the reversed string
def reverse_string(str):
rev_str = ""
for i in range(len(str) - 1, -1, -1):
rev_str += str[i]
return rev_str
reversed = ".eslaf eb t'ndluow ecnetnes siht ,dehctiws erew eslaf dna eurt fo sgninaem eht fI"
print(reverse_string(reversed)) | false |
523fa2207b4fd22f0743b1580f7a36fe5fd660b6 | green-fox-academy/Bpatrik83 | /week-02/day-05/01_anagram.py | 679 | 4.34375 | 4 | # Exercise
# Create a function named is anagram following your current language's style guide.
# It should take two strings and return a boolean value depending on whether its an anagram or not.
# Examples
# input 1 input 2 output
# "dog" "god" true
# "green" "fox" false
def input_values():
in_one = input("Enter the first word: ")
in_two = input("Enter the second word: ")
sorted_one = "".join(sorted(in_one))
sorted_two = "".join(sorted(in_two))
return sorted_one, sorted_two
def check_anagram(sorted_one, sorted_two):
if sorted_one == sorted_two:
return True
return False
print(check_anagram(*input_values()))
| true |
ecbac2eb25591cfefcd1c841e22af7a698c6fbd6 | green-fox-academy/Bpatrik83 | /week-02/day-01/13_seconds_in_a_day.py | 312 | 4.21875 | 4 | current_hours = 14;
current_minutes = 34;
current_seconds = 42;
# Write a program that prints the remaining seconds (as an integer) from a
# day if the current time is represented bt the variables
day_second = 24 *60 * 60
current_day_second = 14 * 60 * 60 + 34 * 60 + 42
print(day_second - current_day_second) | true |
eabee2d75f50e6da2e746a5121b30587fedf7233 | green-fox-academy/Bpatrik83 | /week-02/day-02/19_reverse.py | 323 | 4.40625 | 4 | # - Create a variable named `aj`
# with the following content: `[3, 4, 5, 6, 7]`
# - Reverse the order of the elements in `aj`
# - Print the elements of the reversed `aj`
aj = [3, 4, 5, 6, 7]
aj.reverse()
print(aj)
aj.reverse()
rev_aj = []
for i in range(len(aj) - 1, -1, -1):
rev_aj.append(aj[i])
print(rev_aj) | true |
871a0bd8bccd563aae28b4d43ff3d2e245393534 | green-fox-academy/Bpatrik83 | /week-02/day-01/21_party_indicator.py | 940 | 4.21875 | 4 | # Write a program that asks for two numbers
# Thw first number represents the number of girls that comes to a party, the
# second the boys
# It should print: The party is exellent!
# If the the number of girls and boys are equal and there are more people coming than 20
#
# It should print: Quite cool party!
# It there are more than 20 people coming but the girl - boy ratio is not 1-1
#
# It should print: Average party...
# If there are less people coming than 20
#
# It should print: Sausage party
# If no girls are coming, regardless the count of the people
girls = input("Enter the numbers of girls: ")
boys = input("Enter the numbers of boys: ")
girls = int(girls)
boys = int(boys)
if boys == girls and girls + boys > 20:
print("The party is exellent!")
elif boys != girls and girls + boys > 20:
print("Quite cool party!")
elif girls == 0:
print("Sausage party")
elif girls + boys < 20:
print("Average party...")
| true |
e667bf02c43363259b17f856331ea82e0e6684aa | green-fox-academy/Bpatrik83 | /week-03/day-03/08_position_square.py | 775 | 4.15625 | 4 | import random
from tkinter import *
root = Tk()
canvas = Canvas(root, width="300", height="300")
canvas.pack()
# create a square drawing function that takes 2 parameters:
# the x and y coordinates of the square's top left corner
# and draws a 50x50 square from that point.
# draw 3 squares with that function.
def randomize():
rgb_random = lambda: random.randint(0, 255)
random_color = ("#%02X%02X%02X" % (rgb_random(), rgb_random(), rgb_random()))
x = random.randrange(0, 250)
y = random.randrange(0, 250)
return x, y, random_color
def square_drawing(x, y, random_color):
rectangle = canvas.create_rectangle(x, y, x + 50, y + 50, fill=random_color, width="0")
for i in range(3):
randomize()
square_drawing(*randomize())
root.mainloop() | true |
5b14f61f5e01a61d1f448d49c4a02e2511255da0 | green-fox-academy/Bpatrik83 | /week-02/day-05/06_armstrong_number.py | 1,025 | 4.28125 | 4 | """What is Armstrong number?
An Armstrong number is an n-digit number that is equal to the sum of the nth powers of its digits.
Let's demonstrate this for a 4-digit number: 1634 is a 4-digit number, raise each digit to the fourth power,
and add: 1^4 + 6^4 + 3^4 + 4^4 = 1634, so it is an Armstrong number.
For a 3-digit number: 153 is a 3-digit number, raise each digit to the third power,
and add: 1^3 + 5^3 + 3^3 = 153, so it is an Armstrong number.
Exercise
Write a simple program to check if a given number is an armstrong number. The program should ask for a number.
E.g. if we type 371, the program should print out: The 371 is an Armstrong number."""
def check_armstrong(number):
leng = len(number)
result = 0
for i in range(leng):
result += int(number[i])**leng
if result == int(number):
return "The",number , "is an Armstrong number"
return "The",number , "is not an Armstrong number"
number = input("Enter a number: ")
print(*check_armstrong(number))
| true |
b65b9b8ab57fa8ab37bd02035bfecb8cdd7ce16c | Yi-cell/Handbook-pandas | /Creating-Reading-Writing.py | 2,028 | 4.75 | 5 | import pandas as pd
#Creating data - There are two core objects in pandas: the DataFrame and the Series
'''DataFrame'''
#DataFrame is a table. It contains an array of individual entries, each of which has a certain value. Each entry corresponds to a row and a column
sample0 = pd.DataFrame({'Yes':[50,21],'No':[131,2]})
print(sample0)
#DataFrame entries are not limited to integers. For instance, here's DataFrame whose values are strings
sample1 = pd.DataFrame({'Bob':['I am fine.','It was awful.'],'Chris':['Pretty good.','Bland.']})
print(sample1)
#The list of row labels used in a DataFrame is known as an Index. We can assign values to it by using an index parameter in our constructor:
sample2 = pd.DataFrame({'Bob':['I am fine.','It was awful.'],'Chris':['Pretty good.','Bland.']},index = ['product A','product B'])
print(sample2)
'''Series'''
#A Series, by contrast, is a sequence of data values. If a DataFrame is a table, a Series is a list. And in fact you can create one with nothing more than a list:
sample3 = pd.Series([1,2,3,4,5])
print(sample3)
#A Series is, in essence, a single column of a DataFrame. So you can assign column values to the Series the same way as before, using an index parameter. However, a Series does not have a column name, it only has one overall name:
sample4 = pd.Series([30,35,40],index=['2020 Sales','2021 Sales','2022 Sales'],name = 'Product A')
print(sample4)
'''Reading data files'''
# Comma-Separated-Values - CSV
PD_reviews = pd.read_csv('US_politicians_Twitter.csv')
print(PD_reviews.shape) #Use shape attribute to check how large the resulting DataFrame is
# 2514 records split across 10 different columns.
print(PD_reviews.head()) # Using head() command, which grabs the first five rows
#To make pandas use the column for the index (instead of creating a new one from scratch), we can specify an index_col.
PD_reviews1 = pd.read_csv('US_politicians_Twitter.csv',index_col=0)
print(PD_reviews1.head())
#Save the DataFrame to disk as a csv file.
# PD_reviews1.to_csv('xxx.csv') | true |
5bd6e547656e47030ac2bdc610b10f91a5b555a3 | santoshdkolur/didactic-lamp | /palindromeAnagram.py | 712 | 4.21875 | 4 | '''
We have given a anagram string and we have to check whether it can be made palindrome o not.
Examples:
Input : abcd
Output : False
Explaination:
There is no palindrome anagram of
given string
Input : geeksgeeks
Output : Yes
Explaination:
There are palindrome anagrams of
given string. For example kgeeseegk
'''
#AUTHOR: SANTOSH D KOLUR
def anagram(n):
d={c:0 for c in set(list(n))}
for ele in list(n):
d[ele]+=1
occr=list(d.values())
even_occr=0
for ele in occr:
if ele%2==0:
even_occr+=1
if(even_occr>=len(occr)-1 and occr.count(1)<=1):
print("True")
else:
print("False")
if __name__== '__main__':
n=input()
anagram(n)
| true |
dae0ac9041ea75c623ff521e819c3bb5d668a0f0 | rastislav-halko/Miles-to-kilometers | /mi2km.py | 729 | 4.65625 | 5 | #1. prompt user to enter number of miles in a float form (decimals allowed):
miles = input('Enter a distance in miles: ')
#2. convert string input entered by user to a number (integer):
miles_float = float(miles)
#3. convert the miles-to-km multiplier from string to float:
multiplier = float(1.609344)
#4. actual conversion:
kilometers_value = (miles_float * multiplier)
#5. Final output prints out the amount of miles entered by the user in the form of a string (since we are using the miles variable instead of miles_float) plus value of kilometers converted from float back to a string. Finally the word kilometers is added to conclude the output:
print(miles + ' miles equals ' + str(kilometers_value) + ' kilometers.')
| true |
5ec5f117c94d7a266d7ac36dd213b6eed69f38d6 | tiagosm1/Pyhton_CEV | /Desafios/Desafio 037.py | 554 | 4.125 | 4 | num = int(input('Digite um número inteiro:'))
print(''' Escolha a opção para conversão:
[1] Converter para binário
[2] Converter para octal
[3] converter para hexadecimal''')
opcao = int(input('Sua Opção:'))
if opcao == 1:
print('O número {} convertido para binário é {}'.format(num, bin(num)))
elif opcao == 2:
print('O número {} convertido para octal é {}'.format(num, oct(num)))
elif opcao == 3:
print('O npumero {} convertido para hexadecimal é {}'.format(num, hex(num)))
else:
print('Esta não é uma opção válida!!') | false |
8047fef3648b673605fd955b2e61cdbf059870e2 | kroze05/Tarea_Ejercicios | /ejercicio_3.py | 749 | 4.15625 | 4 | # EJERCICIO 3.- Dados dos números, mostrar la suma, resta, división y multiplicación de ambos
val_1=float(input("coloca un número\n"))
val_2=float(input("coloca el segudo número\n"))
suma = val_1 + val_2
resta_1 = val_1 - val_2
resta_2 = val_2 - val_1
multiplicacion = val_1 * val_2
division_1 = val_1 / val_2
division_2 = val_2 / val_1
print (f"la suma de los terminos es: {suma}")
print (f"la resta de el primer termino con el segundo es: {resta_1}")
print (f"la resta de el segundo termino con el primero es: {resta_2}")
print (f"la mnultiplicacion de los terminos es: {multiplicacion}")
print (f"la division de el primer termino con el segundo es: {division_1}")
print (f"la division de el segundo termino con el primero es: {division_2}") | false |
0959b0b2a6907f6bdd2bfd2721c9c2b26ddffcc2 | walshification/exercism | /python/isogram/isogram.py | 434 | 4.28125 | 4 | import re
NON_LETTERS = re.compile("[^a-zA-Z]")
def is_isogram(phrase: str) -> bool:
"""Returns True is phrase is isogrammatic.
A phrase is isogrammatic if it doesn't use a letter more than once.
Args:
phrase (str): The phrase to check.
Returns:
bool: True if isogrammatic; otherwise, False.
"""
letters = NON_LETTERS.sub("", phrase.lower())
return len(letters) == len(set(letters))
| true |
63d7b02bf82d4621c8c16bc2ab1eb3e9f29556bb | ricardoMondardo/Snippets | /python/problem-solving/BracketCombinations.py | 623 | 4.25 | 4 | # Have the function BracketCombinations(num) read num which will be an integer greater than or equal to zero, and return the number of valid combinations that can be formed with num pairs of parentheses. For example, if the input is 3, then the possible combinations of 3 pairs of parenthesis, namely: ()()(), are ()()(), ()(()), (())(), ((())), and (()()). There are 5 total combinations when the input is 3, so your program should return 5.
def Fact(n):
if (n == 1):
return 1
else:
return n * Fact(n-1)
def BracketCombinations(num):
num = Fact(num)
return num
print(BracketCombinations(3)) | true |
66b9916cdd71cc6e02ea5c982f268010dd299a23 | JairMendoza/Python | /curso 2/ej6.py | 237 | 4.21875 | 4 | print("Vamos a sacar la media de 3 numeros.")
num1=int(input("Numero 1: "))
num2=int(input("Numero 2: "))
num3=int(input("Numero 3: "))
media=(num1+num2+num3)/(3)
print(f"La media de los tres numero ingresados es: {media}")
input() | false |
ce941a38164228ecd02505200f8e9d9d00ed26a0 | LeeTann/Data-Structures | /binary_search_tree/binary_search_tree.py | 2,466 | 4.15625 | 4 | class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
node = BinarySearchTree(value) # call the BinarySearchTree and pass in the value. set it to node.
if value < self.value: # if the insert value is less than the current value, we go left
if self.left == None: # and if there is no left node
self.left = node # then set the left node equal to the node which is BinarySearchTree(value)
else:
self.left.insert(value) # else insert value to the left node
else:
if self.right == None:
self.right = node
else:
self.right.insert(value)
def contains(self, target):
if target == self.value:
return True
if target < self.value: # if target value is less than current value go left.
if self.left: # check if we can keep going left, if we can
return self.left.contains(target) # return and keep calling contain function on left side recursively
else:
return False
if target > self.value:
if self.right:
return self.right.contains(target)
else:
return False
def get_max(self):
if self.right: # if there is a right side,
return self.right.get_max() # return and keep calling right side get_max function recursively until there is no more right side
else:
return self.value # then if no more right side child we return self.value because we know the current node is the lowest it can go and is the max value
def for_each(self, cb): # a depth first search
cb(self.value) # call the callback on self.value
if self.left: # if there is self.left side
self.left.for_each(cb) # then keep recursively calling the for_each(cb) function to go thru all the left side
if self.right:
self.right.for_each(cb)
def dft_non_recursive(self, cb):
stack: []
stack.append(self)
while(len(stack)):
current_node = stack.pop()
if current_node.left:
stack.append(current_node.left)
if current_node.right:
stack.append(current_node.right)
cb(current_node.value)
def bft_for_each(self, cb):
q = Queue()
q.enqueue(self)
while(len(q)):
current_node = q.dequeue()
if current_node.left:
q.enqueue(current_node.left)
if current_node.right:
q.enqueue(current_node.right)
cb(current_node.value) | true |
881df922921acab9bcdaec9fae5695ae2442b600 | JacobBas/leet-code | /q_0069/main.py | 1,637 | 4.1875 | 4 | import unittest
def sqrt(x: int) -> int:
"""
time complexity = O(log(n))
space complexity = constant
"""
# handling the edge case
if x < 2:
return x
# initializing the left and right values
l, r = 0, x
while l <= r:
# midpoint of the left and right sides
mid = (l+r)//2
# if x is inbetween the mid values
if mid * mid <= x < (mid+1)*(mid+1):
return mid
# if x is less than the square of the mid
elif x < mid * mid:
r = mid
# if x is greater than than mid squared
else:
l = mid
class Tests(unittest.TestCase):
def test1(self):
input = 4
output = sqrt(input)
self.assertEqual(sqrt(input), output)
def test2(self):
input = 8
output = sqrt(input)
self.assertEqual(sqrt(input), output)
def test3(self):
input = 15
output = sqrt(input)
self.assertEqual(sqrt(input), output)
def test4(self):
input = 45
output = sqrt(input)
self.assertEqual(sqrt(input), output)
def test5(self):
input = 1238
output = sqrt(input)
self.assertEqual(sqrt(input), output)
def test6(self):
input = 1230322
output = sqrt(input)
self.assertEqual(sqrt(input), output)
def test7(self):
input = 0
output = sqrt(input)
self.assertEqual(sqrt(input), output)
def test8(self):
input = 1
output = sqrt(input)
self.assertEqual(sqrt(input), output)
if __name__ == '__main__':
unittest.main()
| true |
d21cd5dc47b660e398f60de36ce5175d61e4b602 | Finansprogrammering/LearningPython | /myFirstProgram.py | 468 | 4.21875 | 4 | # This program says hello and asks for my name.
print ("Hello World")
print ("What is your name?") # This commands asks for the user's name.
myName = input() # defines the name variable.
print ("It is good to meet you, " + myName) # Greeting phrase.
print ("The length of your name is:")
print (len(myName))
print("What is your age?") # This block asks the user's age
myAge = input()
print ("You will be " + str(int(myAge) +1) + " in a year.")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.