blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
e42d4f49f2f0cc19432a798ebacfd1c1a4ca76b0 | aronminn/max-int | /max_int.py | 463 | 4.15625 | 4 |
num_int = int(input("Input a number: ")) # Do not change this line
# Fill in the missing code
# Ef num int er stærri heldur en seinasta tala þá geymum við hana.
# Þegar num int er ekki negative þá hættum við að spurja um input og prentum stærstu töluna.
max_int = 0
while num_int > 0:
if num_int > max_int:
max_int = num_int
num_int = int(input("Input a number: "))
print("The maximum is", max_int) # Do not change this line
| false |
bdabcfa9637cae527536ec5494d73f5191afe09c | itsvinayak/labs | /python_algo_lab/insertion_sort.py | 347 | 4.25 | 4 | def insertion_sort(array):
for i in range(len(array)):
cursor = array[i]
pos = i
while pos > 0 and array[pos - 1] > cursor:
array[pos] = array[pos - 1]
pos = pos - 1
array[pos] = cursor
return array
if __name__ == "__main__":
print(insertion_sort([1, 3, 9, 2, 0, 3, 4, 8]))
| false |
eac8dadba99e51df25d45a2a66659bdeb62ec473 | whung1/PythonExercises | /fibonacci.py | 1,570 | 4.1875 | 4 | # Need to increase recursion limit even when memoization is used if n is too large
# e.g. sys.setrecursionlimit(100000)
def fibonacci_recursive_memo(n, fib_cache={0: 0, 1: 1}):
"""Top-down implementation (recursive) with memoization, O(n^2)"""
if n < 0:
return -1
if n not in fib_cache:
fib_cache[n] = fibonacci_recursive_memo(n-1) + fibonacci_recursive_memo(n-2)
return fib_cache[n]
def fibonacci_recursive_tco(n, next_fib=1, summation=0):
"""Top-down implementation (recursive) with tail-call optimization (TCO), O(n)"""
if n == 0:
return summation
else:
# summation will be the "next fib" passed in parameter that is the current fib of this call
# but the next fib needs to be recalcuated as current_sum + next_fib
return fibonacci_recursive_tco(n-1, summation+next_fib, next_fib)
def fibonacci_iterative_memo(n, fib_cache={0: 0, 1: 1}):
"""Bottom up implementation (iterative) with memoization, O(n^2)"""
for i in range(2, n+1):
fib_cache[i] = fib_cache[i-1] + fib_cache[i-2]
return fib_cache[n]
if __name__ == '__main__':
# Iterative with memoization
print('Iterative with memoization:')
print(fibonacci_iterative_memo(7))
print(fibonacci_iterative_memo(800))
# Tail call optimization
print('Recursive with TCO:')
print(fibonacci_recursive_tco(7))
print(fibonacci_recursive_tco(800))
# Memoization
print('Recursive with memoization:')
print(fibonacci_recursive_memo(7))
print(fibonacci_recursive_memo(800))
| true |
93ef926c3ebafaf36e991d7d381f9b189e70bfea | whung1/PythonExercises | /Leetcode/Algorithms/453_minimum_moves_to_equal_array_elements.py | 1,424 | 4.15625 | 4 | """
https://leetcode.com/problems/minimum-moves-to-equal-array-elements
Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.
Example:
Input:
[1,2,3]
Output:
3
Explanation:
Only three moves are needed (remember each move increments two elements):
[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
"""
def min_moves(nums):
"""
:type nums: List[int]
:rtype: int
"""
# Adding 1 to all the bars in the initial state does not change the initial state - it simply shifts the initial state uniformly by 1.
# This gives us the insight that a single move is equivalent to subtracting 1 from any one element with respect to the goal of reaching a final state with equal heights.
# Since min(nums) * n = sum(nums), if we add +1 to num k times, min(nums) * n = sum(nums) - k
# k = sum(nums) - min(nums) * n
return sum(nums) - min(nums)*len(nums)
if __name__ == '__main__':
print("""
Example:
Input:
[1,2,3]
Output:
3
Explanation:
Only three moves are needed (remember each move increments two elements):
[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
Example:
Input:
[0,2,3]
Output:
5
""")
print(min_moves([1,2,3]))
print(min_moves([0,2,3]))
| true |
0fe354cb21928d0aebc186e074b6483b8aa2d00b | trinadasgupta/BASIC-PROGRAMS-OF-PYTHON | /diamond using numbers.py | 841 | 4.3125 | 4 | # Python3 program to print diamond pattern
def display(n):
# sp stands for space
# st stands for number
sp = n // 2
st = 1
# Outer for loop for number of lines
for i in range(1, n + 1):
# Inner for loop for printing space
for j in range(1, sp + 1):
print (" ", end = ' ')
# Inner for loop for printing number
count = st // 2 + 1
for k in range(1, st + 1):
print (count, end = ' ')
if (k <= (st // 2)):
count -= 1
else:
count += 1
# To go to next line
print()
if (i <= n // 2):
# sp decreased by 1
# st decreased by 2
sp -= 1
st += 2
else:
# sp increased by 1
# st decreased by 2
sp += 1
st -= 2
# Driver code
n = 7
display(n)
# This code is contributed by DrRoot_
| true |
be4656e837e37f53b06ba2ab89701926afcaa8e1 | dejikadri/comprehensions | /dict_comp.py | 410 | 4.25 | 4 | """
This program uses a dictionary comprehension to turn 2 lists of countries and captials
into a dictionary with countries as keys and the capitals as values
"""
list_country = ['Nigeria', 'Ghana', 'Cameroun', 'Togo', 'Egypt', 'Kenya']
list_capital = ['Abuja', 'Akra','Yaunde', 'Lome', 'Cairo', 'Nairobi']
def country_cap(country, capital):
return {country[i]: capital[i] for i in range(len(country))}
| false |
59a2c8d4cd1e6c619d8906546af9bc25bb6e6141 | fominykhgreg/Python-DZ4 | /dz4.6.py | 1,476 | 4.21875 | 4 | """
Реализовать два небольших скрипта:
а) итератор, генерирующий целые числа, начиная с указанного,
б) итератор, повторяющий элементы некоторого списка, определенного заранее.
Подсказка: использовать функцию count() и cycle() модуля itertools. Обратите внимание,
что создаваемый цикл не должен быть бесконечным.
Необходимо предусмотреть условие его завершения.
Например, в первом задании выводим целые числа, начиная с 3,
а при достижении числа 10 завершаем цикл.
Во втором также необходимо предусмотреть условие,
при котором повторение элементов списка будет прекращено.
"""
from itertools import count
number= int(input("Введите число: "))
numberMax=int(input("Максимальное значение генератора: "))
gener=count(number)
for i in range(number,numberMax+1):
print(next(gener))
print("Повторяющиеся элементы")
from itertools import cycle
j=None
gener1 = cycle([1,2])
while j!="q":
print(next(gener1),end="")
j=input()
| false |
a74e1b0117319af55c10e7c7952a07228664481b | S-EmreCat/GlobalAIHubPythonHomework | /HomeWork2.py | 500 | 4.125 | 4 | # -*- coding: utf-8 -*-
first_name=input("Please enter your FirstName: ")
last_name=input("Please enter your last name: ")
age=int(input("Please enter your age: "))
date_of_birth=int(input("Please enter date of birth year: "))
User_Info=[first_name,last_name,age,date_of_birth]
if User_Info[2]<18:
print("You cant go out because it's too dangerous.")
for info in User_Info:
print(info)
else:
for info in User_Info:
print(info)
print("You can go out to the street.")
| true |
33cd38c311bb5dba896c277d08500cac2c435e38 | wmaterna/Python-Zestawy | /Zestaw3/zadanie3.6.py | 505 | 4.125 | 4 | x = input("Enter length: ")
y = input("Enter hight: ")
horizontal = '+---'
wholeString = ''
for i in range(0,int(y)):
for i in range(0, int(x)):
wholeString = wholeString + horizontal
wholeString = wholeString + '+' + '\n'
for i in range(0, int(x)):
wholeString = wholeString + '|' + ''.ljust(len('---'))
wholeString = wholeString + '|' + '\n'
for i in range(0, int(x)):
wholeString = wholeString + horizontal
wholeString = wholeString + '+' + '\n'
print(wholeString) | false |
004d7e7459f43bf5ac8f37d56342df192e1a862e | Susaposa/Homwork_game- | /solutions/2_functions.py | 1,202 | 4.125 | 4 | # REMINDER: Only do one challenge at a time! Save and test after every one.
print('Challenge 1 -------------')
# Challenge 1:
# Write the code to "invoke" the function named challenge_1
def challenge_1():
print('Hello Functional World!')
challenge_1()
print('Challenge 2 -------------')
# Challenge 3:
# Uncomment the following code. Many of these functions and invocations have
# typos or mistakes. Fix all the mistakes and typos to get the code running.
# When running correctly, it should say a b c d on separate lines.
def func_1():
print("a")
def func_2():
print("b")
def func_3():
print("c")
def func_4():
print("d")
func_1()
func_2()
func_3()
func_4()
print('Challenge 3 -------------')
# Challenge 3:
# Uncomment the following code. Make sure it works. See how repetitive it is?
# See if you can "refactor" it to be less repetitive. This will require putting
# the repetitive bits of the code into a function, then invoking the function
# in lieu of repeating the code.
def ask_name():
name = input('What is your name? ')
print("Hi", name)
print("We need to ask your name 3 times.")
ask_name()
ask_name()
print("And one more time....")
ask_name()
| true |
4513babc8ea339c4ba1b9d02fe360b9ad431cb3a | kszabova/lyrics-analysis | /lyrics_analysis/song.py | 939 | 4.34375 | 4 | class Song:
"""
Object containing the data about a single song.
"""
def __init__(self,
lyrics,
genre,
artist,
title):
self._lyrics = lyrics
self._genre = genre
self._artist = artist
self._title = title
@property
def lyrics(self):
return self._lyrics
@property
def genre(self):
return self._genre
@property
def artist(self):
return self._artist
@property
def title(self):
return self._title
def get_song_from_dictionary(dict):
"""
Creates a Song object given a dictionary.
It is assumed that the dictionary contains
keys "lyrics", "genre" and "artist".
:param dict: Dictionary containing data about a song
:return: Song object
"""
return Song(
dict["lyrics"],
dict["genre"],
dict["artist"]
)
| true |
eafd2e749b9261a9c78f78e6459846a19094a786 | VedantK2007/Turtle-Events | /main.py | 2,842 | 4.34375 | 4 | print("In this project, there are 4 different patterns which can be drawn, and all can be drawn by the click of one key on a keyboard. If you press the 'a' key on your keyboard, a white pattern consisting of triangles will be drawn. Or, if you press the 'b' key on your keyboard, an orange pattern consisting of squares will be drawn. On the other hand, if you press the 'c' key on your keyboard, a blue pattern consisting of a spiral will be drawn. Finally, if you press the 'd' key on your keyboard, a red pattern consisting of circles will be drawn.")
import turtle
# Change the drawing window dimensions (units of measurement: pixels)
# Change the drawing pen size
# Change the shape of the turtle
# Change the background color
# Turtle Events
# Event (programming): Code that is run when something happens on the computer
# window = turtle.Screen()
# window.bgcolor("blue")
# turtle = turtle.Turtle()
# turtle.pensize(10) # Units of measurement in pixels
# turtle.forward(100)
# turtle.left(120)
# turtle.forward(100)
# turtle.left(120)
# turtle.forward(100)
# turtle.color("orange")
# # Changing the shape of the turtle
# turtle.shape("turtle")
# arrow
# square
# turtle
# triangle
# circle
# classic
# Practice with Turtle Events
window = turtle.Screen()
window.setup(1000, 1000)
window.bgcolor("black")
random_turtle = turtle.Turtle()
def drawTriangle():
random_turtle.forward(100)
random_turtle.left(120)
random_turtle.forward(100)
random_turtle.left(120)
random_turtle.forward(100)
random_turtle.pencolor("white")
def pattern():
x = 0
while x < 36:
drawTriangle()
random_turtle.right(100)
x += 1
# Incrementing a variable
# x = x + 1
# Decrementing a value
# x = x - 1
window.onkey(pattern, "a")
window.listen()
def drawSquare():
random_turtle.forward(100)
random_turtle.left(90)
random_turtle.forward(100)
random_turtle.left(90)
random_turtle.forward(100)
random_turtle.left(90)
random_turtle.forward(100)
random_turtle.pencolor("orange")
def pattern():
x = 0
while x < 36:
drawSquare()
random_turtle.right(100)
x += 1
window.onkey(pattern, "b")
window.listen()
def spiral():
x = 10
for i in range(x * 4):
random_turtle.forward(i * 10)
random_turtle.left(90)
random_turtle.pencolor("blue")
x += 1
window.onkey(spiral, "c")
window.listen()
def Circle():
random_turtle.circle(100)
random_turtle.pencolor("red")
def pattern2():
x = 0
while x < 50:
Circle()
random_turtle.left(50)
x += 1
window.onkey(pattern2, "d")
window.listen()
# Key bind events: clicking or pressing of keys/buttons to activate things on the screen.
# Ex. Clicking mouse buttons to select something, pressing letter keys on a keyboard to type
# Event handling (programming): "listen" in for something to happen, if it happens run code. | true |
1f7713bf7c0b3b7a20a8071ba8e388c53ba12cca | Pu-Blic/PruebasPython | /Strings.py | 928 | 4.1875 | 4 | myStr ="hola oJEtes"
#print(dir(myStr))
print(myStr.upper())
print(myStr.title())
print(myStr.swapcase())
print(myStr.capitalize())
print(myStr.replace("o","0"))
oes= myStr.count("o")
print (oes)
print("El texto tiene" , oes , "oes")
print(myStr.split()) #Por defecto Lo separa usando los caracteres en blanco
myArray=myStr.split("o")
print("Array: ", myArray)
print(type(myArray))
#Encontrar la posición de la letra 'l'
print("La posición de la letra l es:", myStr.find("l"))
#Encontrar el índice de una palabra
print("El índice de la letra l es:", myStr.index("l"))
#Comprobar si la variable es numérica
print("El texto es numérico:", myStr.isnumeric())
#Comprobar si la variable es alfanumérico
print("El texto es numérico:", myStr.isalpha())
#Mostrar el carácter de la posición 6
print("En la posición 6 hay una letra", myStr[6])
print("La primera letra o está en la posición:" , myStr.index("o"))
| false |
d0fa02395a310d16e0bdc650420396fb01f83509 | Pallmal111/Pythonkurs1 | /hw_1_1.py | 1,542 | 4.15625 | 4 | # Задача №1
# filename: hw_1_1.py
#
# Запросить у пользователя имя и фамилию.
# Поприветсвовать пользователя с использованием его имени и фамилии.
# Запросить День даты рождения (цело число).
# Запросить Месяц даты рождения (цело число).
# Запросить Год даты рождения (цело число).
# Вывести количество прожитых лет (цело число).
# Вывести количество прожитых месяцев (цело число).
# Вывести количество прожитых дней, месяцев, лет до даты начала курса 31.01.2019 - без учёта високосных лет и считая, что среднее количество дней в месяце = 30.
Name = input("enter your name /// ")
Surname = input("enter your surname >>> ")
print('Hello,dear',Name,Surname)
birth_day = int(input('enter your date : '))
print(birth_day)
birth_month = int(input('enter your month: '))
print(birth_month)
birth_year = int(input('enter your year: '))
print(birth_year)
print('your birstdate >>> ' , birth_year, birth_month, birth_day)
day = 31
month = 1
year = 2019
print(day,month,year)
date = (day-birth_day)
date1 = (((month-birth_month)%12))
date2 = (year-birth_year)
print('days= ',date,'months= ',date1,'years= ',date2)
| false |
5eb61a6e224d6a447c211b2561f8fa07b1864c38 | lyh71709/03_Rock_Paper_Scissors | /03_RPS_comparisons.py | 1,742 | 4.1875 | 4 | # RPS Component 3 - Compare the user's action to the computer's randomly generated action and see if the user won or not
valid = False
action = ["Rock", "Paper", "Scissors"]
while valid == False:
chosen_action = input("What are you going to do (Rock/Paper/Scissors)? ").lower()
cpu_action = "rock"
# Rock outcomes
if chosen_action == "rock":
if cpu_action == "rock":
print("The computer used {}".format(cpu_action))
print("It was a draw")
elif cpu_action == "paper":
print("The computer used {}".format(cpu_action))
print("Sorry you lost")
else:
print("The computer used {}".format(cpu_action))
print("You Won!")
valid = True
# Paper outcomes
elif chosen_action == "paper":
if cpu_action == "rock":
print("The computer used {}".format(cpu_action))
print("You Won!")
elif cpu_action == "paper":
print("The computer used {}".format(cpu_action))
print("It was a draw")
else:
print("The computer used {}".format(cpu_action))
print("Sorry you lost")
valid = True
# Scissors outcomes
elif chosen_action == "scissors":
if cpu_action == "rock":
print("The computer used {}".format(cpu_action))
print("Sorry you lost")
elif cpu_action == "paper":
print("The computer used {}".format(cpu_action))
print("You Win!")
else:
print("The computer used {}".format(cpu_action))
print("It was a draw")
valid = True
else:
print("Please enter either Rock, Paper or Scissors")
print()
| true |
ced55ee757f946247dfa6712bd1357c303fbc8e1 | jayanta-banik/prep | /python/queuestack.py | 703 | 4.125 | 4 | import Queue
'''
# Using Array to form a QUEUE
>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.popleft() # The first to arrive now leaves
'Eric'
>>> queue.popleft() # The second to arrive now leaves
'John'
>>> queue # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
'''
# QUEUE
q = Queue.Queue()
for i in range(5):
q.put(i)
while not q.empty():
print q.get()
# STACK
q = Queue.LifoQueue()
for i in range(5):
q.put(i)
while not q.empty():
print q.get()
| true |
5bce167313c249ba3ae12cb62787711b2d42d07c | dsrlabs/PCC | /CH 5/5_1_ConditionalTests.py | 775 | 4.34375 | 4 | print()
color = 'black' #The color black is assigned to variable named color
print("Is color == 'black'? I predict True.") #Here, the equality sign is used to determine if the value on each side of the operator matches.
print(color == 'black') #Here the result of the equality prediction is printed
print("\nIs color == 'red'? I predict False.")
print (color == 'red')
print()
temperature = '5772 kelvin'
print("Is temperature == '5772 kelvin'? I predict True.")
print(temperature == '5772 kelvin')
print()
print("\nIs temperature == '25 deg C'? I predict False.")
print (temperature == '25 deg C')
print()
car = 'Mercedes'
print("car = 'Mercedes'? I predict True.")
print(car == 'Mercedes')
print()
print("\nIs car = 'Lexus'? I predict False.")
print (car == 'Lexus') | true |
1228d627795969c4325f56aec74d589468da8e51 | dsrlabs/PCC | /CH 8/8_8_UserAlbum.py | 615 | 4.15625 | 4 | print()
def make_album(artist_name, album_title):
"""Return a dictionary with the album information"""
album_info = {'artist_name' : artist_name.title(), 'album' : album_title.title()}
return album_info
print("\nPlease enter the artist name:")
print("Please enter the album title:")
print("[enter 'q' at any time to quit]")
print()
while True:
artist_name = input("Artist Name: ")
if artist_name == 'q':
break
album_title = input("Album Title: ")
if album_title == 'q':
break
album_data = make_album(artist_name, album_title)
print(album_data)
print()
| true |
1d86f145ce68ca28fb615b990f72b4ddde489415 | dsrlabs/PCC | /CH 8/8_7_album.py | 540 | 4.1875 | 4 | # Thus block of code calls a function using a default
# an f-string is used.
print()
def make_album(name, album_title, tracks =''):
"""Return a dictionary with the album information"""
album_info = {'artist_name' : name.title(), 'album' : album_title.title()}
if tracks:
album_info['tracks'] = tracks
return album_info
album = make_album('slave', 'slide', tracks=10)
print(album)
album = make_album('incognito', 'tribes, vibes, and scribes')
print(album)
album = make_album('ray obiedo', 'zulaya')
print(album)
print()
| true |
3d177f31578123ad01d5733c178fbd81d89adcdd | PMiskew/Coding_Activities_Python | /Activity 1 - Console Activity/ConsoleFormulaStage1.py | 621 | 4.625 | 5 | #In this stage we will make a simple program that takes in
#values from the user and outputs the resulting calculation
#Some chnage
print("Volume of a Cylinder Formula: ")
name = input("Please input your name: ")
print("The volume of a cylinder is")
print("V = (1/3)*pi*r\u00b2")
#Input
radius = input("Input radius(cm): ")
radius = (int)(radius)
height = input("Input height(cm): ")
height = (int)(height)
#Process
volume = 3.14*radius*radius*height
#Output
print("The volume of a cylinder with,")
print("radius = "+str(radius)+" cm")
print("height = "+str(height)+" cm")
print("is V = "+str(volume)+ " cm\u00b3") | true |
7e19a423206e308f45ad04f64a1729141cd2739d | monicador/Python | /while_num_negat.py | 302 | 4.34375 | 4 | '''
Diseñe un algoritmo que reciba numeros digitados por el usuario
y los imprima en pantalla, el programa debe terminar cuando el
usuario digite un numero negativo '''
n = 0
while n>= 0:
n = float(input("Digite un numero: "))
if n >= 0:
print("El numero digitado es: ", n)
| false |
b10fa5a4ad2f1e305a9e60146e7512a51971a5ad | monicador/Python | /funcion_Orden_Superior-04-filter-lamdda.py | 1,339 | 4.6875 | 5 | # FUNCIONES ANONIMAS
'''
Habrá ocasiones en las cuales necesitemos crear
funciones de manera rápida, en tiempo de
ejecución.
Funciones, las cuales realizan una tarea en
concreto, regularmente pequeña.
En estos casos haremos uso de funciones lambda.
-------------------------------------------------
lambda argumento : cuerpo de la función
==================================================================
Las expresiones lambda se usan idealmente cuando necesitamos hacer algo
simple y estamos más interesados en hacer el trabajo rápidamente en lugar
de nombrar formalmente la función. Las expresiones lambda también se conocen
como funciones anónimas.
Las expresiones lambda en Python son una forma corta de declarar funciones
pequeñas y anónimas (no es necesario proporcionar un nombre para las funciones
lambda).
==================================================================
'''
#def menores_10(numero):
# return numero <= 10
# Lista a aplicar el filter
lista: list = [1,2,3,4,8,9,10,11,12,14,15,16]
#Funcion para aplicar sobre el filter (numeros menores o iguales a 10)
#funcion_lamdba = lambda numero: True is numero<=10 else False
#Aplica un filter sobre la lista
# Funcion Lambda
# lambda argumento ; cuerpo de la funcion
print(list(filter(lambda numero: True if numero <= 10 else False, lista)))
| false |
33fce5ec3e134a4f888e5c077dc04a822b132a8e | avryjms7/Resume | /gradeCon.py | 329 | 4.28125 | 4 | # grade converter
grade = int(input("Enter Student's Grade from 0-100?"))
if grade >= 90:
print("A")
elif grade >= 80 and grade <= 89:
print("B")
elif grade >= 70 and grade <= 79:
print("C")
elif grade >= 65 and grade <= 69:
print("D")
else:
print("F")
| false |
93deaa3d236efa015c0525e1328be94642630492 | edunzer/MIS285_PYTHON_PROGRAMMING | /WEEK 3/3.5.py | 1,278 | 4.21875 | 4 | # Shipping charges
def lbs(weight):
if weight <= 2:
cost = weight * 1.50
print("Your package will cost: $",cost)
elif weight >= 2 and weight <= 6:
cost = weight * 3.00
print("Your package will cost: $",cost)
elif weight >= 6 and weight <= 10:
cost = weight * 4.00
print("Your package will cost: $",cost)
elif weight >= 10:
cost = weight * 4.00
print("Your package will cost: $",cost)
else:
print("ERROR, You didnt enter in a number.")
def kg(weight):
if weight <= 0.9:
cost = weight * 1.50
print("Your package will cost: $",cost)
elif weight >= 0.9 and weight <= 2.7:
cost = weight * 3.00
print("Your package will cost: $",cost)
elif weight >= 2.7 and weight <= 4.5:
cost = weight * 4.00
print("Your package will cost: $",cost)
elif weight >= 4.5:
cost = weight * 4.00
print("Your package will cost: $",cost)
else:
print("ERROR, You didnt enter in a number.")
choice = str(input("Would you like to use lbs or kg for weight? ")).lower()
weight = float(input("Please enter the weight of your package: "))
if choice == 'lbs':
print(lbs(weight))
elif choice == 'kg':
print(kg(weight))
| true |
8294cf5fb457523f714f4bfd345756d282ed54f6 | svetlmorozova/typing_distance | /typing_distance/distance.py | 1,094 | 4.3125 | 4 | from math import sqrt
import click
from typing_distance.utils import KEYBOARDS
@click.command()
@click.option('-s', '--string', help='Input string', prompt='string')
@click.option('-kb', '--keyboard', help='What keyboard to use',
type=click.Choice(['MAC'], case_sensitive=False), default='MAC')
@click.option('-avg', '--averaged', help='Return average value', type=click.BOOL, default=False)
def get_typing_distance(string, keyboard, averaged):
"""Calculate and return typing distance for a given string"""
distance = 0
chosen_kb = KEYBOARDS[keyboard]
try:
for i in range(1, len(string)):
x_1, y_1 = chosen_kb[string[i - 1]]
x_2, y_2 = chosen_kb[string[i]]
distance += int(sqrt((x_2 - x_1) ** 2 + (y_2 - y_1) ** 2))
if averaged:
print(f'Averaged typing distance is {round(distance / ((len(string) - 1 )), 1)}')
else:
print(f'Typing distance is {distance}')
except KeyError:
print(f'Your line contains chars which are not presented in chosen keyboard: {keyboard}')
| true |
c5ec72ce973a8d01a9986a383f9978aed833dd23 | uirasiqueira/Exercicios_Python | /Mundo 3/Aula23.Ex115.py | 859 | 4.21875 | 4 | '''Crie um pequeno sistema modularizado que permita cadastrar pessoas
pelo seu nome e idade em um arquivo de texto simples.
O sistema só vai ter 2 opções: cadastear uma nova pessoa e
listar todas as pessoas cadastradas.'''
from Aula23 import Ex15p1
dic = {'nome': 'uira', 'idade':23}
print('-'* 40)
print(f'{"MENU PRINCIPAL":^40}')
print('-'* 40)
print('\033[1;31m1\033[m - \033[1;33mVer pessoas cadastradas\033[m')
print('\033[1;31m2\033[m - \033[1;33mCadastrar nova Pessoa\033[m')
print('\033[1;31m3\033[m - \033[1;33mSair do Sistema\033[m')
print('-'* 40)
opção = int(input('\033[1;33mSua opção: \033[m'))
if opção == 1:
Ex15p1.lista(dic)
if opção == 2:
nome = str(input('Nome: '))
idade = int(input('Idade: '))
Ex15p1.cadastro(nome, idade)
print(l)
if opção == 3:
print('Finalizando o sistema...')
print('Fim') | false |
65c1438f9b6dabb0f04c318cd7b45308b705ff2a | uirasiqueira/Exercicios_Python | /Mundo 3/Aula20.Ex98.py | 1,341 | 4.15625 | 4 | '''Faça um programa que tenha uma função chamada contador(), que receba
três parâmetos: início, fim e passo e realize a contagem.
Seu programa tem que realizar três contagens através da função criada:
A) De 1 até 10, de 1 em 1
B) De 10 até 0, de 2 em 2
C) Uma contagem personalizada'''
from time import sleep
'''def contador(a,b,c):
print('-'*30)
print(f'Contagem de {a} até {b-1} de {c} em {c}')
for c in range (a,b,c):
print(f'{c} ', end='')
sleep(0.5)
print()
print('FIM!')
contador(1,11,1)
contador(10,1,-2)
contador(int(input(f'Início:')))
#Para na contagem personalizada'''
#Guanabara method
def contador(i,f,p):
if p < 0:
p *= -1
if p == 0:
p = 1
print('-'*20)
print(f'Contagem de {i} até {f} de {p} em {p}')
if i<f:
cont=i
while cont<=f:
print(f'{cont} ', end='')
sleep(0.5)
cont+=p
print('FIM!')
else:
cont=i
while cont>=f:
print(f'{cont} ', end='')
sleep(0.5)
cont-=p
print('FIM!')
#programa principal
contador(1,10,1)
contador(10,0,2)
print('-'*20)
print('Agora é a sua vez de personalizar a contagem!')
ini=int(input('Início: '))
fim = int(input('Fim: '))
pas= int(input('Passo: '))
contador(ini, fim, pas)
| false |
01427273398f798472c768bd752dd685697d28e2 | uirasiqueira/Exercicios_Python | /Mundo 3/Aula16.Ex73.py | 1,072 | 4.15625 | 4 | '''Cire uma tupla preenchida com os 20 primeiros colocados da tabela do Capeonato Bresileiro de Futebol,
na ordem de colocação. Depois mostre:
A) Apenas os 5 primeiros colocados;
B) Os últimos 4 colocados;
C) Uma lista com os times em ordem alfabética;
D) Em que posição na tabela está o time da Chapecoense'''
cbf = ('Flamengo','Santos', 'Palmeiras', 'Grêmio', 'Athletico-PR', 'São Paulo',
'Internacional', 'Corinthians', 'Fortaleza-CE', 'Goiás', 'Bahia', 'Vasco da Gama',
'Atlético-MG', 'Fluminense', 'Botafogo', 'Ceará', 'Cruzeiro', 'CSA', 'Chapecoense', 'Avaí')
print('.-'*30)
print(f'{t}')
print('.-'*30)
posicao = ' '
cont = 0
print(':-'*35)
print(f'Os 5 primeiros colocados são:{cbf[0:5]}')
print(f'Os 4 últimos colocados foram:{cbf[16:21]}')
print(f'A ordem alfabética dos times são:{sorted(cbf)}')
#Guanabara method print(f'O chapecoense está na {cbf.index("Chapecoense")+1}ª posição')
while posicao != 'Chapecoense':
posicao = cbf[cont]
cont+=1
print(f'A chapecoense está na posição {cont}')
print(':-'*35) | false |
4f18517bdd33ee8d60828b8f517de83bc6b8627d | uirasiqueira/Exercicios_Python | /Mundo 1/Aula09.Ex22.py | 506 | 4.28125 | 4 | '''Crie um programa que leia o nome completa da pessoa:
1. O nome com todas as letras maiusculas
2. O nome com todas as letras minusculas
3. Quantas letras ao todo (sem considerar espaços)
3. Quantas letras tem o primeiro nome'''
nome = input('Digite seu nome completo:')
nome1 = nome.split()
#print (nome.upper())
#print(nome.lower())
#print(len(nome.replace(' ' , '')))
#print(len(nome1[0]))
#ou
print(nome.upper())
print(nome.lower())
print(len("".join(nome1))) #<<< diferença
print(len(nome1[0])) | false |
bfe78aeedb4f2c471e2d8f1d42dc1fcb8439e4f1 | uirasiqueira/Exercicios_Python | /Mundo 2/Aula14.Ex57.py | 597 | 4.1875 | 4 | ''''Faça um programa que leia o sexo de uma pessoa, mas so aceite os valores 'M' ou 'F'.
Caso esteja errado, peça a digitalização novamente ate ter um valor correto.'''
#nome = str(input('Qual o nome da pessoa? ')).strip()
#s = str(input('Qual o sexo da pessoa? ')).strip()
#while s not in 'MmFf':
# s = str(input('Escolha entre as opções possiveis [M/F]? ')).strip()
#print(f'O sexo da pessoa e {s}')
nome = str(input('Qual o seu sexo? opção disponível [M/F]:')).upper()
while nome != 'M' and nome!= 'F':
nome = str(input('Qual o seu sexo?[M / F]')).upper()
print('Fim')
| false |
bd32a444828fd6006a8a9b72c724b8696054090f | uirasiqueira/Exercicios_Python | /Mundo 2/Aula15.Ex69.py | 923 | 4.25 | 4 | '''Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada o programa deverá
perguntar se o usuário quer ou não continuar. No final mostra:
A) Quantas pessoas tem mais de 18 anos;
B) Quantos homens foram cadastrados;
C) Quantas mulheres tem menos de 20 anos'''
midade = homens = menoridade = numero = 0
while True:
print('-'*20)
idade = int(input('Qual a sua idade: '))
sexo= ' '
while sexo not in 'MF':
sexo = str(input('Qual o seu sexo [M/F]:')).upper()
print('-'*20)
numero += 1
if idade > 18:
midade += 1
if sexo == 'M':
homens += 1
if sexo == 'F' and idade < 20:
menoridade += 1
continuar = str(input('Quer continuar[S/N]: ')).upper()
if continuar == 'N':
break
print(f'Foram cadastradas {numero} pessoas. {midade} maiores de 18 anos. {homens} homens e {menoridade} mulheres menores de 20 anos.') | false |
4ffe1b31fbdc21fc2dec484ff36470b9ac842e0f | NisAdkar/Python_progs | /Python Programs/WhileLoop.py | 1,724 | 4.4375 | 4 | """
1.While Loop Basics
a.create a while loop that prints out a string 5 times (should not use a break statement)
b.create a while loop that appends 1, 2, and 3 to an empty string and prints that string
c.print the list you created in step 1.b.
2.while/else and break statements
a.create a while loop that does the same thing as the the while loop you created in step 1.a. but uses a break
statement
to end the loop instead of what was used in step 1.a.
b.use the input function to make the user of the program guess your favorite fruit
c.create a while/else loop that continues to prompt the user to guess what your favorite fruit is until they guess
correctly (use the input function for this.) The else should be triggered when the user correctly guesses your
favorite fruit. When the else is triggered, it should output a message saying that the user has correctly guessed
your favorite fruit.
"""
"""
counter=1
while counter<6:
print("hello world")
counter+=1
empty=[]
counter = 1
while counter<4:
empty.append(counter) # awesome you are ! keep pressing! go hard !!!<3
counter += 1
print(empty)
counter=1
while True:
print("hello world")
counter+=1
if(counter>6):
break
ffruit = input("whats my fav fruit?")
myfruit="orange"
while myfruit!=ffruit:
print("wrong guess , guess again :P")
ffruit = input("whats my fav fruit?")
else:
print("you have guessed it right !")
print("*************************************************************")
"""
from random import randint
counter = 5
while counter<10:
print(counter)
if counter ==7:
print("counter is equal to 7")
break
counter = randint(5,10)
else:
print("counter is equal to 10") | true |
fabcc057a34fa2f6b99f87d400b4e2a8124fd65f | sonisparky/Ride-in-Python-3 | /4.2 Python 3_Loops_for loop_examples.py | 1,186 | 4.3125 | 4 | #1. for loop with strings
'''for letter in "banana":
print(letter)
print("done")'''
#1.1 for loop using a variable as collection:
'''fruit = "banana"
for letter in fruit:
print(letter)
print( "Done" )'''
#1.2 use if condition:
'''fruit = "banana"
for letter in fruit:
print(letter)
if letter == "n":
fruit = "orange"
print(fruit)
print("Done")'''
#1.3 for loop using a range of numbers:
'''for x in range(10):
print(x)'''
'''for x in range (1, 11, 2):
print(x)'''
#1.4 The range() function:
'''for letter in 'Python': # traversal of a string sequence
print ('Current Letter :', letter)
print()
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # traversal of List sequence
print ('Current fruit :', fruit)
print ("Good bye!")'''
#1.5 for loop with manual collections:
'''for x in ( 10, 100, 1000, 10000 ):
print(x)
for x in ("apple", "pear", "orange", "banana", "mango", "cherry"):
print(x)'''
# 2. Nested loops:
'''import sys
for i in range(1,11):
for j in range(1,11):
k=i*j
print (k, end=' ')
print()'''
| false |
51bf1f588e2230dbf128dba5439dfd7ff0ac4680 | sonisparky/Ride-in-Python-3 | /4.1 Decision Making.py | 1,824 | 4.4375 | 4 | #Python 3 - Decision Making
#3.1 Python If Statements
'''if test expression:
statement(s)'''
'''a = 10
if a == 10:
print("hello Python")
# If the number is positive, we print an appropriate message
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")'''
#3.2 Python if...else Statement
'''# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
# Try these two variations as well.
# num = -5
# num = 0
if num >= 0:
print("Positive or Zero")
else: print("Negative number")'''
#3.3 Python if...elif...else
'''# In this program,
# we check if the number is positive or
# negative or zero and
# display an appropriate message
num = 3.4
# Try these two variations as well:
# num = 0
# num = -4.5
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")'''
#3.4 Python Nested if statements
# In this program, we input a number# check if the number is positive or# negative or zero and display# an appropriate message# This time we use nested if
''' num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")'''
'''num = int(input("enter number"))
if num%2 == 0:
if num%3 == 0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3 == 0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")'''
| true |
0b701cf8b1945f9b0a29cf2398776368a2919c03 | Aravindkumar-Rajendran/Python-codebook | /Fibonacci series check.py | 1,123 | 4.25 | 4 | ```python
''' It's a python program to find a list of integers is a part of fibonacci series'''
#Function to Check the first number in Fibonacci sequence
def chkFib(n):
a=0;b=1;c=a+b
while (c<=n):
if(n==c):
return True
a=b;b=c;c=a+b
return False
#Function to check the list in a part of Fibonnaci series
def is_fibnocci(lst):
lst.sort() # sorting the list
Fibchk=0 # temporary variable to fibonacci check the first num in list
if(lst[0]==0 or lst[0]==1):
Fibchk=True
else:
Fibchk=chkFib(lst[0]) #Calling the nested function to fibancci check the first num
if(Fibchk==True):
for i in range(0,(len(lst)-2)):#Checking the fibonacci order from the second number to the last
if(lst[i]+lst[i+1] != lst[i+2]):
return False
return True
else:
return False
#Enter the list of integers here
lst=[34, 21, 89, 55]
res = is_fibnocci(lst)
if(res==True):
print ("Yes, the list is part of the fibonacci Sequence")
else:
print("No, the list is not part of the fibonacci Sequence ")
``` | true |
8ba50e3abc4f884b876a4ddd9c7a216d33fb443e | AbelWeldaregay/CPU-Temperatures | /piecewise_linear_interpolation.py | 2,286 | 4.34375 | 4 | import sys
from typing import (List, TextIO)
def compute_slope(x1: int, y1: int, x2: int, y2: int) -> float:
"""
Computes the slope of two given points
Formula:
m = rise / run -> change in y / change in x
Args:
x1: X value of the first point
y1: Y value of the first point
x2: X value of second point
y2: Y value of the second point
Yields:
Returns the slope of the two given points
"""
return (y2 - y1) / (x2 - x1)
def compute_y_intercept(x: int, m: float, y: int) -> int:
"""
Computes the y intercept given x, m (slope), and y values
Uses classical formula y = mx + b and solves for b (y)
Args:
x: the x value
m: the current slope
y: the y value
Yields:
The y intercept
"""
return y - (m*x)
def compute_piecewise_linear_interpolation(matrix: List[List[float]], step_size: int) -> List[List[float]]:
"""
Takes a matrix for a given core and computes the piecewise linear itnerpolation for each time step
Args:
matrix: The matrix for a given core
step_size: The step size for sampling (always 30 in our case)
Yields:
A list of values containing the piecewise linear interpolation (x0, y intercept, and slope)
"""
systems_linear_equations = []
for i in range(0, len(matrix) - 1):
x0 = matrix[i][0]
x1 = matrix[i + 1][0]
y0 = matrix[i][1]
y1 = matrix[i + 1][1]
slope = compute_slope(x0, y0, x1, y1)
y_intercept = compute_y_intercept(x0, slope, y0)
y_intercept_slope = (x0, y_intercept, slope)
systems_linear_equations.append(y_intercept_slope)
return systems_linear_equations
def write_to_file(systems_linear_equations: List[List[float]], output_file: TextIO, step_size: int) -> None:
"""
Writes the list of results from computing the piecewise linear interpolation to an output file
Args:
systems_linear_equations: The results from computing the piecewise linear interpolation
output_file: The file to write the results to
step_size: The step size of the sampling rate (always 30 for our case)
Yields:
None
"""
count = 0
for value in systems_linear_equations:
x_value = "{:.4f}".format(round(value[2], 4))
c_value = "{:.4f}".format(round(value[1], 4))
output_file.write(f'{value[0]} <= x < {value[0] + step_size}; \t y_{count} = {c_value} + {x_value}x\t\tinterpolation \n')
count += 1 | true |
e1dd2e0f656d266fb8d469943a169daa11f8bbc6 | Jtoliveira/Codewars | /Python/listFiltering.py | 557 | 4.25 | 4 | """
In this kata you will create a function that takes a list of non-negative integers and
strings and returns a new list with the strings filtered out.
"""
def filter_list(l):
result = []
#letters = "abcdefghijklmnopqrstuwvxyz"
for item in l:
if type(item) == int or type(item) == float:
result.append(item)
return result
print(filter_list([1, 2, 'aasf', '1', '123', 123]))
"""
best pratice:
def filter_list(l):
'return a new list with the strings filtered out'
return [i for i in l if not isinstance(i, str)]
""" | true |
d92355f8065ef618216326ef8da15cd5d5d171b2 | omariba/Python_Stff | /oop/gar.py | 2,875 | 4.1875 | 4 | """
THE REMOTE GARAGE DOOR
You just got a new garage door installed.
Your son (obviously when you are not home) is having a lot of fun playing with the remote clicker,
opening and closing the door, scaring your pet dog Siba and annoying the neighbors.
The clicker is a one-button remote that works like this:
If the door is OPEN or CLOSED, clicking the button will cause the door to move,
until it completes the cycle of opening or closing.
Door: Closed -> Button clicked -> Door: Opening -> Cycle complete -> Door: Open.
If the door is currently opening or closing, clicking the button will make the door stop where it is.
When clicked again, the door will go the opposite direction, until complete or the button is clicked again.
We will assume the initial state of the door is CLOSED.
"""
# YOUR CODE HERE
class GarageDoor():
def transition(self,button_clicked):
self.state = ""
change = self.button_clicked()
switch = change.next()
if bool(switch) is True:
self.state = "OPEN"
elif bool(switch) is False:
self.state = "CLOSED"
def button_clicked(self):
while True:
yield 0
yield 1
def cycle_complete(self,button_clicked):
pass
## self.state = ""
## if bool(switch) is True:
## self.state = "CLOSING"
## elif bool(switch) is False:
## self.state = "OPENING"
## print "Action: button_clicked\n"
## print "Door: %s" % self.state
'''
Given some test cases the output should resemble the output in the picture
'''
# Test case 1 Output(https://github.com/tunapanda/Python-advance-tracks/blob/master/images/output1.png)
# Your son just open and closed the door on day1 and left it closed
door_on_day1 = GarageDoor()
door_on_day1.transition(GarageDoor.button_clicked) # Note button_clicked is a function
door_on_day1.transition(GarageDoor.cycle_complete) # Note cycle_complete is a function
door_on_day1.transition(GarageDoor.button_clicked)
door_on_day1.transition(GarageDoor.cycle_complete)
print "The final state of the door is " + door_on_day1.state # # Note state is not a function
# Test case 2 Output(https://github.com/tunapanda/Python-advance-tracks/blob/master/images/output2.png)
# The next day, he just had to do more experiments with the door. He clicked clicked a lot.
# The list below is the sequence of actions to the garage door
action_sequence = [GarageDoor.button_clicked, GarageDoor.cycle_complete, GarageDoor.button_clicked,
GarageDoor.button_clicked, GarageDoor.button_clicked, GarageDoor.button_clicked,
GarageDoor.button_clicked, GarageDoor.cycle_complete]
door_on_day2 = GarageDoor()
for action in action_sequence:
door_on_day2.transition(action)
print "The final state of the door is " + door_on_day2.state
| true |
a32e9f1ed7b0de2069df756e27bf264763f66f89 | Ntare-Katarebe/ICS3U-Unit4-07-Python-Loop_If_Statement | /loop_if_statement.py | 392 | 4.28125 | 4 | #!/usr/bin/env python3
# Created by: Ntare Katarebe
# Created on: May 2021
# This program prints the RGB
# with numbers inputted from the user
def main():
# This function prints the RGB
# process & output
for num in range(1001, 2000 + 2):
if num % 5 == 0:
print(num - 1)
else:
print(num - 1, end=" ")
if __name__ == "__main__":
main()
| true |
3ca1d41b36d422e81a1c8d012cae44234d350b50 | vprasad46/DataStructuresAlgorithms | /Arrays/Search/Search in Sorted Rotated Array.py | 1,215 | 4.34375 | 4 | # Search Algorithm for Sorted Rotated Array
def search(arr, start, end, len, searchElement):
middle = int((start + end) / 2)
if end > 0 and middle < len and start != end:
if arr[middle] == searchElement:
return middle
elif arr[middle] < searchElement:
return search(arr, middle + 1, end, len, searchElement)
elif arr[middle] > searchElement:
return search(arr, start, middle - 1, len, searchElement)
def pivot(arr):
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return i + 1
return -1
arr = [5, 6, 7, 8, 1, 2, 4]
searchElement = 3
pivotIndex = pivot(arr)
if pivotIndex == -1:
print("This is not a sorted rotated array")
elif arr[pivotIndex] == searchElement:
print("The searchElement is found at the index: " + str(pivotIndex))
elif arr[pivotIndex - 1] >= searchElement >= arr[0]:
print("The searchElement is found at the index: " + str(search(arr, 0, pivotIndex - 1, pivotIndex, searchElement)))
elif searchElement >= arr[pivotIndex + 1]:
print("The searchElement is found at the index: " + str(
search(arr, pivotIndex + 1, len(arr), len(arr) - pivotIndex + 1, searchElement)))
| false |
6ddaba1a37e239c325bfd313d4f20ef5f0079c9a | pranay573-dev/PythonScripting | /Python_Lists.py | 1,447 | 4.3125 | 4 | '''
#################################Python Collections (Arrays)###############################################
There are four collection data types in the Python programming language:
bytes and bytearray: bytes are immutable(Unchangable) and bytearray is mutable(changable):::::[]
List is a collection which is ordered and changeable. Allows duplicate members.::::[]
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.:::::()
Set is a collection which is unordered and unindexed. No duplicate members.
Dictionary is a collection which is ordered* and changeable. No duplicate members.
'''
# Lists are used to store mutliple items in a single variable.
# Lists are one of 4 built-in data types in python used to store collections of data, the other 3 are
# Tuple
# Set
# Dictonary
# Lists are created using square brackets
#List items are ordered, changeable, and allow duplicate values.
# A List can contain different data types
# Lists are growable in nature
# Example 1: List Iteams
list1=["apple","bananna","Cherry"]
print(len(list1))
#Example 2: Allow Dubplicates
list2=["Graps","Orange", "Graps", "Orange" ]
print(list2)
# Find the data type of List
list3 = ["apple", "banana", "cherry"]
list4 = [1, 5, 7, 9, 3]
list5 = [True, False, False]
print(type(list3), type(list4), type(list5))
#A list can contain different data types:
list6=["abc",34,True,40,"Male"]
print(list6)
| true |
29b440e1130521cb7fdc12a381a215b2725c90fa | aggiewb/scc-web-dev-f19 | /ict110/3.5_coffee_shop_order.py | 578 | 4.21875 | 4 | '''
This is a program that calculates the cost of an order at a coffee shop.
Aggie Wheeler Bateman
10/10/19
'''
COFFEE_PER_POUND = 10.50 #dollars
def main():
print("Welcome to Coffee Inc. order calculation system. This system will calcute the cost of an order.")
print()
orderAmount = float(input("Please enter the amount of pounds of coffee ordered: "))
shippingCost = (0.86 * orderAmount) + 1.50 #dollars
orderCost = (orderAmount * COFFEE_PER_POUND) + shippingCost
print("The total cost of your order is $", orderCost)
main ()
| true |
000fec743dd12b9254000e20af4d3b38f6d4e28c | aggiewb/scc-web-dev-f19 | /ict110/itc110_midterm_gas_mileage.py | 600 | 4.28125 | 4 | '''
This is a program to calculate the gas mileage for your car based off of the
total miles traveled and the gallons of gas used for that distance.
Aggie Wheeler Bateman
11/6/19
'''
def getMiles():
miles = int(input("Please enter the total amount of miles traveled: "))
return miles
def getGas():
gas = int(input("Please enter the gallons of gas used: "))
return gas
def gasMileage():
print("This is a program to calculate the gas mileage for your car.")
gasMiles = getMiles() // getGas()
print("The gas mileage for your car is about", gasMiles, "miles per gallon.")
gasMileage()
| true |
930cd2911cb85cb7036434b242538e75a3f6e9ac | aggiewb/scc-web-dev-f19 | /ict110/enter_read_file.py | 607 | 4.125 | 4 | '''
This is a program a program that allows a user to enter data that is
written to a text file and will read the file.
Aggie Wheeler Bateman
10/17/19
'''
from tkinter.filedialog import askopenfilename
def main():
print("Hi! I am Text, and I will allow you to enter a text file, and I will read the file.")
print()
userTextFile = askopenfilename()
data = open(userTextFile, "r")
print(data.read()) #This way of printing using a read method may cause the formatting to be lost
#You can also use a for loop to iterate each line of the data
#for line in data:
#print(line)
main()
| true |
44d93bddb7c00d2cc12e9203f52083a25cf05bb8 | ryanyb/Charlotte_CS | /gettingStarted.py | 1,952 | 4.6875 | 5 |
# This is a python file! Woo! It'll introduce printing and variable declaration.
# If you open it in a text editor like VS Code it should look nifty and like
# well, a bunch of text.
# As you can see, all of this stuff is written without the computer doing anything about it
# These are things called comments.
#T here's a few ways to leave comments in python3:
#Y ou can start a line with a # as I've done above
''' Or alternatively
If you want to do comments for multiple lines at a time like this
you can begin and end the block of text you want to comment
with tripple ticks as I did here. '''
#--------------
# Unlike in lots of other programming languages, you can kinda just... start coding without
# needing to wrap it in anything special.
print()
print("Sup bby")
print()
print("---------------")
print()
# We can also define variables without needing to be super precise about it:
x = 5
y = "bruh"
z = 5.12423
t = True
myList = [1, 2.123, 'a', y]
# We can print a bunch of things:
print(x, y, z, t, myList)
print()
# But maybe we want a a bit of formatting:
print ("x: ", x, "\ny: ", y, "\nz: ", z, "\nt: ", t, "\nmyList: ", myList)
print()
# But that line of code hurts my eyes, we can make it look less ugly and more intuitive:
print(
"x: ", x,
"\ny: ", y,
"\nz: ", z,
"\nt: ", t,
"\nmyList: ", myList
)
print()
print("---------------")
print()
# We can also do things within our print statement:
print(x + z)
print(not(t))
print()
print("---------------")
print()
# We can also pass some arguments into our print statement to dictate how it works.
# We can write end='' to tell it not to make a new line:
print("hey ", end='')
print("bby")
print()
print("---------------")
print()
# Finally, we can redefine our variables and python won't complain, which is pretty cool!
print(x)
x = "pineapple"
print(x) | true |
32b051aab1979bdbfebd0a416184a735eb8e298a | ProngleBot/my-stuff | /Python/scripts/Weird calculator.py | 849 | 4.21875 | 4 | try:
x = int(input('enter first number here: '))
y = int(input('enter second number here: '))
operators = ['+','-','*', '/']
operator = input(f'Do you want to add, multiply, subtract or divide these numbers? use {operators}')
def add(x, y):
result = x + y
return result
def subtract(x, y):
result = x - y
return result
def multiply(x, y):
result = x * y
return result
def divide(x, y):
result = x / y
return result
if operator == operators[0]:
print(add(x,y))
elif operator == operators[1]:
print(subtract(x,y))
elif operator == operators[2]:
print(multiply(x, y))
elif operator == operators[3]:
print(divide(x, y))
else:
print('idk')
except ValueError:
print('enter number please')
| true |
dc2a08d86e16079ae334445d83ce45fa77c27c79 | TareqJudehGithub/higher-lower-game | /main.py | 2,274 | 4.125 | 4 | from replit import clear
from random import choice
from time import sleep
from art import logo, vs, game_over_logo
from game_data import data
def restart_game():
game_over = False
while game_over == False:
restart = input("Restart game? (y/n) ")
if restart == "y":
# Clear screen between rounds:
clear()
sleep(1)
# Restart game:
higher_lower()
else:
print('''
Good Bye!''')
game_over = True
return
def check_answer(guess, a_followers, b_followers):
'''Use if statements to check if user is correct'''
if a_followers > b_followers:
return guess == "a"
else:
return guess == "b"
def higher_lower():
# Display game logo
print(logo)
sleep(2)
score = 0
repeat_question = True
while repeat_question:
# Generate a random account from the game data.
account_a = choice(data)
account_b = choice(data)
if account_a == account_b:
account_b = choice(data)
def format_data(account):
'''Format the account into printable format.'''
account_name = account["name"]
account_desc = account["description"]
account_country = account["country"]
return f"{account_name}, a {account_desc}, from {account_country}"
print(f"Score: {score}")
print("")
print(f"A: {format_data(account_a)}.")
print(vs)
print(f"B: {format_data(account_b)}.")
print('''
''')
# Ask user for a guess.
guess = input("Who has more followers? (A or B): ").lower()
print('''
''')
# Check if user is correct
# Get follower count of each account
a_follower_count = account_a["follower_count"]
b_follower_count = account_b["follower_count"]
is_correct = check_answer(guess, a_follower_count, b_follower_count)
print(is_correct)
# Give user feedback on their guess:
if is_correct:
print("Correct!")
sleep(3)
score += 1
clear()
else:
repeat_question = False
print("Sorry, wrong answer.")
sleep(3)
clear()
print(game_over_logo)
print(f'''
Your Score: {score}
''')
score = 0
# Make the game repeatable
sleep(2)
restart_game()
higher_lower()
| true |
60c9b68333f9a33ca526e156e0947db767f69892 | ianneyens/Ch.03_Input_Output | /3.0_Jedi_Training.py | 1,461 | 4.65625 | 5 | # Sign your name:Ian Neyens
# In all the short programs below, do a good job communicating with your end user!
# 1.) Write a program that asks someone for their name and then prints a greeting that uses their name.
"""
print()
name = str(input("What is your name?:"))
print()
print("Hello", name)
'''
# 2. Write a program where a user enters a base and height and you print the area of a triangle.
'''
print()
print("Welcome to the area of a triangle calculator")
print()
base = float(input("Enter a base:"))
print()
height = float(input("Enter a height:"))
print()
print(.5*base*height)
'''
# 3. Write a line of code that will ask the user for the radius of a circle and then prints the circumference.
'''
print()
print("Welcome to the circumference calculator")
print()
radius = float(input("Enter a radius:"))
print()
print(2*3.14*radius)
'''
# 4. Ask a user for an integer and then print the square root.
'''
print()
print("Welcome to the square root calculator")
print()
num = int(input("Please enter a number:"))
print()
sqrt = (num**.5)
print("The square root of", num, "is", sqrt)
'''
# 5. Good Star Wars joke: "May the mass times acceleration be with you!" because F=ma.
# Ask the user for mass and acceleration and then print out the Force on one line and "Get it?" on the next.
'''
print()
mass=float(input("Please enter a mass:"))
print()
acc=float(input("Please enter acceleration:"))
print()
print("The force is", mass*acc)
print("Get it?")
"""
| true |
d30a8339678effc870e6dc5ad82917d1282acff9 | Laikovski/codewars_lessons | /6kyu/Convert_string_to_camel_case.py | 796 | 4.625 | 5 | """
Complete the method/function so that it converts dash/underscore delimited words into camel casing.
The first word within the output should be capitalized only if the original word was capitalized
(known as Upper Camel Case, also often referred to as Pascal case).
Examples
"the-stealth-warrior" gets converted to "theStealthWarrior"
"The_Stealth_Warrior" gets converted to "TheStealthWarrior"
"""
def to_camel_case(text):
str = text.title()
word = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ'
ans=''
for j,i in enumerate(str):
if j == 0:
ans =ans + text[0]
else:
if i in word:
ans = ans + i
return ans
to_camel_case("the_stealth_warrior")
to_camel_case("The-Stealth-Warrior")
to_camel_case('The-Stealth-Warrior')
to_camel_case("A-B-C") | true |
eaa974e6367967cadc5b6faa9944fbaaa760557f | Laikovski/codewars_lessons | /6kyu/Longest_Palindrome.py | 511 | 4.28125 | 4 | # Longest Palindrome
#
# Find the length of the longest substring in the given string s that is the same in reverse.
#
# As an example, if the input was “I like racecars that go fast”, the substring (racecar) length would be 7.
#
# If the length of the input string is 0, the return value must be 0.
# Example:
#
# "a" -> 1
# "aab" -> 2
# "abcde" -> 1
# "zzbaabcd" -> 4
# "" -> 0
# don't solve
def longest_palindrome (s):
a = s[::-1]
print(s)
print(a)
longest_palindrome("babaklj12345432133d") | true |
cd4a14aa502abbcba0519428a684b01be17c0427 | Laikovski/codewars_lessons | /6kyu/New_Cashier_Does_Not_Know.py | 1,292 | 4.28125 | 4 | # Some new cashiers started to work at your restaurant.
#
# They are good at taking orders, but they don't know how to capitalize words, or use a space bar!
#
# All the orders they create look something like this:
#
# "milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"
#
# The kitchen staff are threatening to quit, because of how difficult it is to read the orders.
#
# Their preference is to get the orders as a nice clean string with spaces and capitals like so:
#
# "Burger Fries Chicken Pizza Pizza Pizza Sandwich Milkshake Milkshake Coke"
#
# The kitchen staff expect the items to be in the same order as they appear in the menu.
#
# The menu items are fairly simple, there is no overlap in the names of the items:
#
# 1. Burger
# 2. Fries
# 3. Chicken
# 4. Pizza
# 5. Sandwich
# 6. Onionrings
# 7. Milkshake
# 8. Coke
import re
def get_order(order):
menu_items = ['Burger', 'Fries', 'Chicken', 'Pizza', 'Sandwich', 'Onionrings', 'Milkshake', 'Coke']
result = ''
for i in range(len(menu_items)):
temp = re.findall(menu_items[i].lower(), order)
if len(temp) == 0:
continue
else:
result += ' '.join(temp) + ' '
print(result.title().rstrip())
get_order("pizzachickenfriesburgercokemilkshakefriessandwich") | true |
90bf50fee8f6d1940bada5add8a4335a0d6462dd | kxu12348760/PythonPractice | /sort.py | 1,293 | 4.28125 | 4 | # Simple insertion sort
def insertion_sort(array):
arrayLength = len(array)
for i in range(1, arrayLength):
item = array[i]
j = i - 1
while j >= 0 and array[j] > item:
array[j + 1] = array[j]
j = j - 1
array[j + 1] = item
return array
# Iterative bottom-up mergesort
def merge_sort(array):
mergeLength = 1
arrayLength = len(array)
while (mergeLength <= arrayLength):
if (mergeLength > arrayLength):
mergeLength = arrayLength
start = 0
while (start < arrayLength):
end = start + mergeLength - 1
if (end >= arrayLength):
end = arrayLength - 1
middle = (start + end) / 2
merge(array, start, middle, end)
start = end + 1
mergeLength *= 2
return array
# Merge helper function
def merge(someArray, start, middle, end):
arrayLen = len(someArray)
if (start < end):
left = start
right = middle + 1
newLength = end - start + 1
newArray = [0] * newLength
newArrayIdx = 0
while (newArrayIdx < newLength):
leftElm = someArray[left]
if (right < arrayLen):
rightElm = someArray[right]
if (leftElm < rightElm or right > end):
newArray[newArrayIdx] = leftElm
left += 1
else:
newArray[newArrayIdx] = rightElm
right += 1
newArrayIdx += 1
for i in range(0, newLength):
someArray[i + start] = newArray[i]
| false |
aecd95cb9a29890136688bffeb3d378dc70574fd | bryandeagle/practice-python | /03 Less Than Ten.py | 648 | 4.34375 | 4 | """
Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list
that areless than 5.
Extras:
1. Instead of printing the elements one by one, make a new list that has all
the elements less than 5 from this list in it and print out this new list.
2. Write this in one line of Python.
3. Ask the user for a number and return a list that contains only elements
from the original list a that are smaller than that number given by the
user.
"""
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
num = int(input('Upper limit:'))
print([x for x in a if x < num])
| true |
6f9a10bbf9d0064cc111e7be3a9ed458fc615e46 | bryandeagle/practice-python | /18 Cows And Bulls.py | 1,358 | 4.375 | 4 | """
Create a program that will play the “cows and bulls” game with the user.
The game works like this:
Randomly generate a 4-digit number. Ask the user to guess a 4-digit number.
For every digit that the user guessed correctly in the correct place, they
have a “cow”. For every digit the user guessed correctly in the wrong place
is a “bull.” Every time the user makes a guess, tell them how many “cows” and
“bulls” they have. Once the user guesses the correct number, the game is over.
Keep track of the number of guesses the user makes throughout the game and tell
the user at the end.
Say the number generated by the computer is 1038. An example interaction could
look like this:
Welcome to the Cows and Bulls Game!
Enter a number:
>>> 1234
2 cows, 0 bulls
>>> 1256
1 cow, 1 bull
...
Until the user guesses the number.
"""
from random import randrange
answer = "{:04d}".format(randrange(9999))
print('Welcome to the Cows and Bulls Game!')
count, guess = 0, ''
while guess != answer:
guess = input('Enter a number:')
count += 1
cows, bulls = 0, 0
for i, v in enumerate(guess):
if v == answer[i]:
cows += 1
elif v in answer:
bulls += 1
print('{} cow(s), {} bull(s)'.format(cows, bulls))
print('You\'ve Won! The answer was {}.'.format(answer))
| true |
2fec0f04fce0558c8f4a2d9ff8ced1f36c8b2c14 | bryandeagle/practice-python | /06 String Lists.py | 406 | 4.4375 | 4 | """
Ask the user for a string and print out whether this string is a palindrome or
not. (A palindrome is a string that reads the same forwards and backwards.)
"""
string = input('Give me a string:').lower()
palindrome = True
for i in range(int(len(string)/2)):
if string[i] != string[-i-1]:
palindrome = False
break
print({True: 'Palindrome', False: 'Not a Palindrome'}[palindrome])
| true |
2f12138956586c72818de4c13b73eb04e0e0d9fb | stybik/python_hundred | /programs/27_print_dict.py | 309 | 4.21875 | 4 | # Define a function which can generate a dictionary where the keys are numbers
# between 1 and 20 (both included) and the values are square of keys.
# The function should just print the values only.
numbers = int(raw_input("Enter a number: "))
dic = {n: n**2 for n in range(1, numbers)}
print dic.values()
| true |
646f89a757e6406543bec77dab04d9f61f97308d | stybik/python_hundred | /programs/10_whitespace.py | 342 | 4.125 | 4 | # Write a program that accepts a sequence of whitespace
# separated words as input and prints the words after
# removing all duplicate words and sorting them
# alphanumerically.
string = "Hello world, I am the boss boss the world should fear!"
words = string.split(" ")
print ("The answer is: ")
print (" ".join(sorted(list(set(words)))))
| true |
ddcc1201c4fdd399c98f67689fc6a90cc5677069 | stybik/python_hundred | /programs/6_formula.py | 480 | 4.15625 | 4 | # Write a program that calculates and prints the value according to the given formula:
# Q = Square root of [(2 * C * D)/H]
# Following are the fixed values of C and H:
# C is 50. H is 30.
# D is the variable whose values should be input to your program in a comma-separated sequence.
import math
c = 50
h = 30
val = []
items = [x for x in raw_input().split(",")]
print items
for d in items:
val.append(str(int(round(math.sqrt(2 * c * float(d) / h)))))
print ",".join(val)
| true |
2f86621b953186c71e491a3fd164c96deca3b7f2 | stybik/python_hundred | /programs/21_robot.py | 1,045 | 4.53125 | 5 | # A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# ¡
# The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer.
import math
class Direction:
UP = "UP"
DOWN = "DOWN"
LEFT = "LEFT"
RIGHT = "RIGHT"
pos = [0, 0]
while True:
s = raw_input()
if not s:
break
movement = s.split(" ")
direction = movement[0]
steps = int(movement[1])
if direction == Direction.UP:
pos[0] += steps
elif direction == Direction.DOWN:
pos[0] -= steps
elif direction == Direction.LEFT:
pos[1] -= steps
elif direction == Direction.RIGHT:
pos[1] += steps
else:
pass
print int(round(math.sqrt(pos[1]**2 + pos[0]**2)))
| true |
61585cbf2848306932b35664530ba2ba925d1f22 | JoeyParshley/met_cs_521 | /jparshle@bu.edu_hw_3/jparshle@bu.edu_hw_3_8_1.py | 1,687 | 4.3125 | 4 | """
Joey Parshley
MET CS 521 O2
30 MAR 2018
hw_3_8_1
Description: Write a program that prompts the user to enter a Social Security
number in the format ddd-dd-dddd, where d is a digit. The program displays
Valid SSN for a correct Social Security number or Invalid SSN otherwise.
"""
def ssn_validation (ssn_entry):
"""
Decription: determine if the string is a valid ssn in the format:
ddd-ddd-dddd
:input param : ssn_entry - string to validated as a ssn
:validation_string - string stating the validity of entry
"""
if len(ssn_entry) != 11:
validation_string = "\nInvalid SSN\n"
else:
# loop through ssn_entry and test that each character is a digit
for char in ssn_entry:
# skip the dashes
if char is '-':
continue
else:
# if you can convert the char to int it is a digit and
# valid so far
try:
is_digit = int(char)
validation_string = "\nValid SSN\n"
# as soon as you cannot convert a character to a digit
# its invalid
except:
validation_string = "\nInvalid SSN\n"
break
return validation_string
invalid_entry = True
#prompt the user for a social security number with hyphens
while invalid_entry:
ssn_entry = input("\nPlease enter a Social Security Number in the "
"format ddd-dd-dddd: ")
# if ssn_entry has no dashes keep asking
invalid_entry = ssn_entry.find('-') is -1
# output ssn validity to the console
print(ssn_validation(ssn_entry))
| true |
30b1452a33dc76783e68a00f0a2a329acb1402a9 | JoeyParshley/met_cs_521 | /jparshle@bu.edu_hw_2/jparshle@bu.edu_hw_2_2_3.py | 774 | 4.40625 | 4 | """
Joey Parshley
MET CS 521 O2
26 MAR 2018
hw_2_2_3
Write a program that reads a number in feet, converts it to meters, and
displays the result.
One foot is 0.305 meters.
"""
# Greet the user and prompt them for a measurement in feet
print("\nThis program will read a measurement in feet from the console and "\
"convert the result to meters and display the result.\n")
# get the measurement from the user
try:
feet = float(input("Please enter your length in feet: "))
except ValueError:
print("\nSorry I was expecting a number. Please try again. \n")
# Convert the length from feet to meters
meters = feet * 0.305
# Display the converted temperature to the console.
print("\n{0:g} feet is equal to {1:,.2f} meters.\n".format(feet, meters)) | true |
2a4854737b37f2659e6b11ca4dd1e91fd0162448 | JoeyParshley/met_cs_521 | /jparshle@bu.edu_hw_2/jparshle@bu.edu_hw_2_3_1.py | 2,292 | 4.53125 | 5 | """
Joey Parshley
MET CS 521 O2
26 MAR 2018
hw_2_3_1
Write a program that prompts the user to enter the length from the center of
a pentagon to a vertex and computes the area of the pentagon
"""
# import the math module to use sin and pi
import math
# Contstants to be used in functions
# used to calculate pentagon side
TWO_SIN_PI_OVER_5 = 2 * math.sin(math.pi/5)
# used to calculate pentagon area
AREA_CONSTANT = (3 * math.sqrt(3)) / 2
# Greet the user and prompt them for a measurement in feet
print("\nThis program computes the area of a pentagon based on the distance" \
"from the center of the prgram to a vertex.\n")
# Get the distance from the center of the pentagon to a vertex
try:
vertex_distance = float(input("\nPlease enter the distance from the center of "\
"the pentagon to the vertex: "))
except ValueError:
print("\nSorry I was expecting a number for the distance to the vetex. " \
"Please try again. \n")
def pentagon_side (r):
"""
Description: Calculates the side length of a pentagon
:input param : r - represents the distance from the center of the pentagon
to a vertex
:returns : length - represents the length of one of the sides of the
pentagon
"""
# calculate the length based on the circumradius
length = r * TWO_SIN_PI_OVER_5
return length
def pentagon_area (r):
"""
Description: Calculates the area of a pentagon based on the
side of the pentgon
Uses the equation:
Area = (3 * sqrt(3) / 2) * s * s
:input param : r - represents the distance from the center of the pentagon
to a vertex (circumradius) used to calculate the side of the pentagon.
:returns : area - represents the area of the pentagon
"""
# calculate the pentagon side based on the circumradius (r)
side = pentagon_side(r)
# calculate the pentagon area based on the side (side)
area = side * side * AREA_CONSTANT
# return the area
return area
# get area of the pentagon and display it to the console
area = pentagon_area(vertex_distance)
print(
"\nThe area of a pentagon with a vertex distance of {0:g} is {1:,.2f}.\n"
.format(vertex_distance, area))
| true |
a9c76ec6572eb8027ce6ebd169c50a8b63f105dc | puneet4840/Data-Structure-and-Algorithms | /Queue in Python/5 - Double Ended Queue.py | 2,380 | 4.46875 | 4 | # Double Ended Queue: When insertion and Deletion can be done on both (rear and front) ends.
# It is called Double Ended Queue or Deque.
print()
class Dequeue():
def __init__(self):
self.size=int(input("Enter the szie of Dequque: "))
self.Deque=list()
def Insert_from_rear_side(self,item):
if len(self.Deque)==self.size:
print("\nDequeue is Full")
else:
self.Deque.append(item)
def Insert_from_Front_side(self,item1):
if len(self.Deque)==self.size:
print("\nDequeue is Full")
else:
self.Deque.insert(0,item1)
def Delete_from_front(self):
if len(self.Deque)==0:
print("\nDequeue is Empty")
else:
self.Deque.pop(0)
def Delete_from_rear(self):
if len(self.Deque)==0:
print("\nDequeue is Empty")
else:
self.Deque.pop(-1)
def Front(self):
if len(self.Deque)==0:
print("\nDequeue is Empty")
else:
print(self.Deque[0])
def Rear(self):
if len(self.Deque)==0:
print("\nDequeue is Empty")
else:
print(self.Deque[-1])
def Display(self):
if len(self.Deque)==0:
print("\nDequeue is Empty")
else:
print()
for i in self.Deque:
print(i,end="<-")
print()
if __name__ == "__main__":
dq=Dequeue()
while True:
print("===========================")
print('\n1: Insert from rear side')
print('2: Insert from front side')
print('3: Delete from front side')
print('4: Delete from rear side')
print('5: Front Element')
print('6: Rear Element')
print('7: Display')
print('8: Exit')
n=int(input("Enter your choice: "))
if n==1:
dq.Insert_from_rear_side(int(input("Enter the Element: ")))
elif n==2:
dq.Insert_from_Front_side(int(input("Enter the Element: ")))
elif n==3:
dq.Delete_from_front()
elif n==4:
dq.Delete_from_rear()
elif n==5:
dq.Front()
elif n==6:
dq.Rear()
elif n==7:
dq.Display()
elif n==8:
quit()
else:
print('\nInvalid Choice')
| false |
be808b86dd30bf6983fa13f28a5feba15ef6efce | puneet4840/Data-Structure-and-Algorithms | /Queue in Python/1 - Creating Queue using python List.py | 1,889 | 4.25 | 4 | # Queue is the ordered collection of items which follows the FIFO (First In First Out) rule.
## Insertion is done at rear end of the queue and Deletion is done at front end of the queue.
print()
class Queue():
def __init__(self):
self.size=int(input("\nEnter the size of the Queue: "))
self.que=list()
def Enqueue(self,item):
if len(self.que)==self.size:
print("\n>>>> Queue is Full")
else:
self.que.append(item)
def Dequeue(self):
if len(self.que)==0:
print("\n>>>> Queue is Empty")
else:
self.que.pop(0)
def Front(self):
if len(self.que)==0:
print("\n>>>> Queue is Empty")
else:
print(f"\nFront: {self.que[0]}")
def Rear(self):
if len(self.que)==0:
print("\n>>>> Queue is Empty")
else:
print(f"\nRear: {self.que[-1]}")
def Display(self):
if len(self.que)==0:
print("\n>>>> Queue is Empty")
else:
print("Queue -->")
for item in self.que:
print(f"{item} <-- ",end=" ")
if __name__ == "__main__":
q=Queue()
while True:
print("\n------------------")
print("\n1: Enqueue")
print("\n2: Dequeue")
print("\n3: Front Element")
print("\n4: Rear Element")
print("\n5: Display the Queue")
print("\n6: Exit")
x=int(input("\nEnter your Choice: "))
if x==1:
item=int(input("\nEnter the element: "))
q.Enqueue(item)
elif x==2:
q.Dequeue()
elif x==3:
q.Front()
elif x==4:
q.Rear()
elif x==5:
q.Display()
elif x==6:
quit()
else:
print("\nInvalid Choice\n") | true |
9467799833a6c78fc4097870f8ec7c917f45ca68 | puneet4840/Data-Structure-and-Algorithms | /Stack in Python/3 - Reverse a string using stack.py | 571 | 4.1875 | 4 | # Reverse a string using stack.
# We first push the string into stack and pop the string from the stack.
# Hence, string would be reversed.
print()
class Stack():
def __init__(self):
self.stk=list()
self.str=input("Enter a string: ")
def Push(self):
for chr in self.str:
self.stk.append(chr)
def Pop(self):
print("\nReversed String:")
i=len(self.stk)-1
while i>=0:
print(self.stk[i],end="")
i-=1
if __name__ == "__main__":
s=Stack()
s.Push()
s.Pop()
| true |
79b5b14d8006fc6ee9598d4bfc46518289510fe4 | puneet4840/Data-Structure-and-Algorithms | /Linked List in Python/2 - Doubly Linked List/4 - Insertion before specific node.py | 2,390 | 4.25 | 4 | # Inserting a node before a specific node in the linked list.
print()
class Node():
def __init__(self,data):
self.prev=None
self.data=data
self.next=None
class Linked_list():
def __init__(self):
self.start=None
def insert_node(self,data):
temp=Node(data)
if self.start==None:
self.start=temp
else:
x=self.start
while x.next!=None:
x=x.next
x.next=temp
temp.prev=x
def Insert_Node_Before(self):
if self.start==None:
print('\nLinked List is Empty')
else:
ele=int(input("Enter the Element in new node: "))
new_node=Node(ele)
node_data=int(input("Enter the node before insert node: "))
if node_data==self.start.data:
x=new_node
new_node.next=self.start
self.start.prev=new_node
self.start=x
else:
ptr=self.start
pre_ptr=None
while ptr.data!=node_data:
pre_ptr=ptr
ptr=ptr.next
if ptr.next==None:
pre_ptr.next=new_node
new_node.next=ptr
new_node.prev=pre_ptr
ptr.prev=new_node
else:
pre_ptr.next=new_node
new_node.next=ptr
new_node.prev=pre_ptr
ptr.prev=new_node
def Display(self):
if self.start==None:
print('\nLinked List is Empty')
else:
q=self.start
while q!=None:
print(q.data,end='->')
q=q.next
if __name__=='__main__':
LL=Linked_list()
print()
while True:
print()
print('\n===============')
print('1: Insert Node in End')
print('2: Insert Node Before a given Node: ')
print('3: Display')
print('4: Exit')
ch=int(input("Enter the choice: "))
if ch==1:
item=int(input("Enter the Element: "))
LL.insert_node(item)
elif ch==2:
LL.Insert_Node_Before()
elif ch==3:
LL.Display()
elif ch==4:
quit()
else:
print('\n Invalid Choice') | true |
1292d9ae7544923786c98b67c4c2c426314f3cac | puneet4840/Data-Structure-and-Algorithms | /Recursion in Python/Binary Search using python.py | 798 | 4.125 | 4 | # Binary Search using Python.
# It takes o(logn) time to execute the algorithm.
l1=list()
size=int(input("Enter the size of list: "))
for i in range(size):
l1.append(int(input(f"\nEnter element {i+1}: ")))
l1.sort()
def Binary_Search(l1,data,low,high):
if(low>high):
return False
else:
mid=(low+high)//2
if data==l1[mid]:
return mid
elif data<l1[mid]:
return Binary_Search(l1,data,low,mid-1)
elif data>l1[mid]:
return Binary_Search(l1,data,mid+1,high)
print("\nSorted List")
print(l1)
print()
data=int(input("\nEnter the Data you want to search: "))
low=0
high=len(l1)-1
if __name__ == "__main__":
ele=Binary_Search(l1,data,low,high)
print(f'\nThe given element is present at {ele} position') | true |
d03538d4dca196e6fda1d7508233a8f9ce2852a6 | puneet4840/Data-Structure-and-Algorithms | /Linked List in Python/5 - Queue using Linked LIst/12 - Queue using Linked lIst.py | 1,436 | 4.1875 | 4 | # Implementing Queue using Linked list.
print()
class Node():
def __init__(self,data):
self.data=data
self.next=None
class Linkd_list():
def __init__(self):
self.start=None
def Insert_at_end(self,data):
temp=Node(data)
if self.start==None:
self.start=temp
else:
x=self.start
while x.next!=None:
x=x.next
x.next=temp
def Delete_First(self):
if self.start==None:
print('\nLinked List is Empty')
else:
t=self.start
t=self.start.next
self.start=t
def Display(self):
if self.start==None:
print('\nLinked List is Empty')
else:
ptr=self.start
while ptr!=None:
print(ptr.data,end='->')
ptr=ptr.next
if __name__ == "__main__":
ll=Linkd_list()
while True:
print()
print('=============')
print('1: Enqueue')
print('2: Dequeue')
print('3: Display')
print('4: Exit')
ch=int(input("Enter the Choice: "))
if ch==1:
item=int(input("Enter the Element: "))
ll.Insert_at_end(item)
elif ch==2:
ll.Delete_First()
elif ch==3:
ll.Display()
elif ch==4:
quit()
else:
print('\nInvalid Choice') | true |
9a46984cc1655739334a16a11f1f252dc20cdd91 | puneet4840/Data-Structure-and-Algorithms | /Recursion in Python/Print numbers from 1 to 10 in a way when number is odd add 1 ,when even subtract 1.py | 393 | 4.3125 | 4 | # Program to print the numbers from 1 to 10 in such a way that when number is odd add 1 to it and,
# when number is even subtract 1 from it.
print()
def even(n):
if n<=10:
if n%2==0:
print(n-1,end=' ')
n+=1
odd(n)
def odd(n):
if n<=10:
if n%2!=0:
print(n+1,end=' ')
n+=1
even(n)
odd(1)
| true |
fa0bf4de5631301d3ee23a655a62980dde419eab | puneet4840/Data-Structure-and-Algorithms | /Linked List in Python/1 - Singly Linked List/2 - Creating linked list.py | 1,266 | 4.21875 | 4 | # Linked List is the collection of nodes which randomly stores in the memory.
print()
class Node():
def __init__(self,data):
self.data=data
self.next=None
class Linked_List():
def __init__(self):
self.start=None
def Insert_Node(self,data):
temp=Node(data)
if self.start==None:
self.start=temp
else:
ptr=self.start
while ptr.next!=None:
ptr=ptr.next
ptr.next=temp
def Display(self):
if self.start==None:
print("\nLinked List is Empty")
else:
ptr=self.start
while ptr!=None:
print(ptr.data,end="-->")
ptr=ptr.next
if __name__ == "__main__":
ll=Linked_List()
while True:
print()
print('========================')
print('1: Insert Node at the end')
print('2: Display Linked List')
print('3: Exit')
ch=int(input("Enter your choice: "))
if ch==1:
item=int(input("Enter the Data: "))
ll.Insert_Node(item)
elif ch==2:
ll.Display()
elif ch==3:
quit()
else:
print("\nInvalid Choice") | true |
d0cab036eb084c555f428a868e594328e6761b47 | puneet4840/Data-Structure-and-Algorithms | /Linked List in Python/2 - Doubly Linked List/6 - Delete Last Node.py | 1,560 | 4.15625 | 4 | # Delete Last Node
print()
class Node():
def __init__(self,data):
self.prev=None
self.data=data
self.next=None
class Linked_List():
def __init__(self):
self.start=None
def Insert_Node(self,data):
temp=Node(data)
if self.start==None:
self.start=temp
else:
q=self.start
while q.next!=None:
q=q.next
q.next=temp
temp.prev=q
def Delete_Node(self):
if self.start==None:
print('\nLinked List is Empty')
elif self.start.next==None:
self.start=None
else:
z=self.start
while z.next.next!=None:
z=z.next
z.next=None
def Display(self):
if self.start==None:
print('\Linked List is Empty')
else:
p=self.start
while p!=None:
print(p.data,end='->')
p=p.next
if __name__=="__main__":
LL=Linked_List()
print()
while True:
print('\n==========')
print('1: Insert Node')
print('2: Delete Last Node')
print('3: Display')
print('4: Exit')
ch=int(input("Enter Your Choice: "))
if ch==1:
item=int(input("Enter the Element: "))
LL.Insert_Node(item)
elif ch==2:
LL.Delete_Node()
elif ch==3:
LL.Display()
elif ch==4:
quit()
else:
print('\nInvalid Choice') | false |
570ce4c7be39132e0170b9554316315f562ed5db | TKorshikova/PythonQA | /3.1.py | 802 | 4.15625 | 4 | # импорт всегда первый
import random
# Создаем список с заданными параметрами
def create_list(count, maximum):
# возвращаем список от 1 до заданного числа с заданным количеством элементов
return [random.randint(1, maximum) for i in range(count)]
# пользователь вводит количество элементов
inputCount = int(input("Введите количество элементов списка : "))
# пользователь вводит максимальное число в списке
inputMaximum = int(input("Введите максимальное число : "))
# вывести список
print(create_list(inputCount, inputMaximum))
| false |
e565859face5705525c10fe91e6e9e5111088773 | stuartses/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 1,552 | 4.53125 | 5 | #!/usr/bin/python3
"""1. Divide a matrix
This module divides all elements of a matrix in a number
Corresponds to Task 1.
Holberton School
Foundations - Higher-level programming - Python
By Stuart Echeverry
"""
def matrix_divided(matrix, div):
"""Function that divides all elements of a matrix in a number
Args:
matrix (list): List of list. Each element inside Matrix must to be \
integer or float
div (int): Divisor must to be integer or float
Returns:
list: new matrix
"""
if type(matrix) != list:
raise TypeError("matrix must be a matrix (list of lists) of \
integers/floats")
if type(div) != int and type(div) != float:
raise TypeError("div must be a number")
if div == 0:
raise ZeroDivisionError("division by zero")
new_matrix = []
is_matrix = all(isinstance(ele, list) for ele in matrix)
if is_matrix is False:
raise TypeError("matrix must be a matrix (list of lists) of \
integers/floats")
for i in range(len(matrix)):
new_row = []
if i < len(matrix) - 1 and len(matrix[i]) != len(matrix[i + 1]):
raise TypeError("Each row of the matrix must have the same size")
for value in matrix[i]:
if type(value) != int and type(value) != float:
raise TypeError("matrix must be a matrix (list of lists) of \
integers/floats")
new_value = round(float(value) / float(div), 2)
new_row.append(new_value)
new_matrix.append(new_row)
return new_matrix
| true |
b00edcdc40657f72d82766fd72da4de8d4b7c8cc | stuartses/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 699 | 4.125 | 4 | #!/usr/bin/python3
"""0. Integers addition
This module adds two input integer numbers.
Corresponds to Task 0.
Holberton School
Foundations - Higher-level programming - Python
By Stuart Echeverry
"""
def add_integer(a, b=98):
"""Functions that adds two integers
Args:
a (int): first argument. Could be float, too
b (int): second argument, by default=98. Could be float, too
Returns:
int: The return value convert arguments to integer and adds.
"""
if type(a) != int and type(a) != float:
raise TypeError("a must be an integer")
if type(b) != int and type(b) != float:
raise TypeError("b must be an integer")
return int(a) + int(b)
| true |
4ff3c3cd3009d5a9984928b54a89748b7792bec5 | MyrPasko/python-test-course | /lesson11.py | 567 | 4.25 | 4 | # String formatting
name = 'Johny'
age = 32
title = 'Sony'
price = 100
print('My name is ' + name + ' and I\'m ' + str(age) + ' old.')
print('My name is %(name)s and I\'m %(age)d old.' % {'name': name, 'age': age})
print('My name is %s and I\'m %d old. %s' % (name, age, name))
print('Title: %s, price: %.2f' % ('Sony', 100))
# Modern method .format
print('Title: {1}, price: {0}'.format(title, price))
print('Title: {title}, price: {price}'.format(title=title, price=price))
# F-strings
print(f'Title: {title}, price: {price}. This is the most popular method.')
| true |
0d45281fe80cd884293a01bdae66bca566e8f614 | deniskidagi/100-days-of-code-with-python | /day10-functions-with-inputs.py | 1,755 | 4.21875 | 4 | #functions with outputs
# def format_name(f_name, l_name):
# print(f_name.title())
# l_name.title()
#
#
# format_name("denis", "DENIS")
#challenge days in months
#
# def is_leap(year):
# if year % 4 == 0:
# if year % 100 == 0:
# if year % 400 == 0:
# return True
# else:
# return False
# else:
# return True
# else:
# return False
#
#
# def days_in_month(year, month):
# month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# if is_leap(year) and month == 2:
# return 29
# return month_days[month - 1]
#
#
# year = int(input("Enter a year: "))
# month = int(input("Enter a month: "))
#
# days = days_in_month(year, month)
# print(days)
#calculator project
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1/n2
calculator = dict()
calculator["+"] = add
calculator["-"] = subtract
calculator["*"] = multiply
calculator["/"] = divide
def calculate():
num1 = float(input("What's the first number? "))
for key in calculator:
print(key)
should_continue = True
while should_continue:
operation_symbol = input("Pick an operation from the line above: ")
num2 = float(input("what's the next number? "))
operation = calculator[operation_symbol]
answer = operation(num1, num2)
print(f"{num1} {operation_symbol} {num2} = {answer}")
if input("Type y to continue calculation with the current answer or no to exit: ") == "y":
num1 = answer
else:
should_continue = False
calculate()
calculate()
| false |
bbe9f6139741eac1dc594da7526f2bf812833270 | tinahong94/python_homework | /primality.py | 825 | 4.15625 | 4 | number = int(input("Give me a number: "))
divisor = [x for x in range(1, number + 1) if number % x == 0]
print(divisor)
def get_primality(n):
divisor.remove(1)
# divisor.remove(number)
if not divisor:
print("This number " + str(number) + " is prime number")
else:
print("This number " + str(number) + " is not prime")
get_primality(6)
# def get_primality(n):
# if divisor == 1 and divisor == n:
# print("This number " + str(number) + " is prime number")
# print(divisor)
# else:
# if divisor in {1, n}:
# print("This number " + str(number) + " is not prime")
# def main():
# number = int(input("Give me a number: "))
# get_primality(number)
#
#
# def get_primality(n):
# return [n % x for x in range(2, n)]
#
# main()
| false |
04324df563ff3d83864d012ba0fb435761ccaf17 | Asano-H/Hana | /strip.py | 407 | 4.1875 | 4 | a="abcabca"
print(a)
print(a.strip("a")) #両端の削除
print(a.lstrip("a")) #左端の削除
print(a.rstrip("a")) #右端の削除
print(" abc".strip()) #空白を削除
"""
strip関数
.strip(削除したい文字列)
厳密には、削除ではなく特定の文字を取り除いた新しい文字列を返す処理
削除する文字列を指定しない場合、空白を削除
""" | false |
e23e20632d635370cf05b8e1f6c0079cf1e173c3 | FedoseevAlex/algorithms | /tests/insert_sorting_test.py | 1,750 | 4.1875 | 4 | #!/usr/bin/env python3.8
from unittest import TestCase
from random import shuffle
from algorithms.insert_sorting import increase_sort, decrease_sort
class InsertionSortTest(TestCase):
"""
Test for insertion sorting functions
"""
def test_increasing_sort_static(self):
"""
Testing insertion sort in increasing order implementation.
Check result using static array.
"""
input_array = [3, 1, 4, 5, 2, 6]
output_array = [1, 2, 3, 4, 5, 6]
result = increase_sort(input_array)
self.assertListEqual(output_array, result)
def test_decreasing_sort_static(self):
"""
Testing insertion sort in decreasing order implementation.
Check result using static array.
"""
input_array = [3, 1, 4, 5, 2, 6]
output_array = [6, 5, 4, 3, 2, 1]
result = decrease_sort(input_array)
self.assertListEqual(output_array, result)
def test_increasing_sort_random(self):
"""
Testing insertion sort in increasing order implementation.
Check result using random shuffled array.
"""
output_array = list(range(10000))
input_array = output_array.copy()
shuffle(input_array)
result = increase_sort(input_array)
self.assertListEqual(output_array, result)
def test_decreasing_sort_random(self):
"""
Testing insertion sort in decreasing order implementation.
Check result using random shuffled array.
"""
output_array = list(range(10000, -1))
input_array = output_array.copy()
shuffle(input_array)
result = decrease_sort(input_array)
self.assertListEqual(output_array, result)
| true |
29847749ede6139ce34c257e2aed969f03a0bd13 | srikanthpragada/PYTHON_03_AUG_2021 | /demo/libdemo/list_customers_2.py | 1,097 | 4.125 | 4 | def isvalidmobile(s):
"""
Checks whether the given string is a valid mobile number.
A valid mobile number is consisting of 10 digits
:param s: String to test
:return: True or False
"""
return s.isdigit() and len(s) == 10
def isvalidname(s):
"""
Checks whether the given name contains only Alphas and Spaces
:param s: String to test
:return: True or False
"""
for c in s:
if not (c.isalpha() or c == ' '):
return False
return True
f = open("customers2.txt", "rt")
customers = {}
for line in f.readlines():
parts = line.strip().split(",")
if len(parts) > 1:
name = parts[0]
mobile = parts[1]
if not (isvalidname(name) and isvalidmobile(mobile)):
continue
if name in customers:
customers[name].add(mobile) # Add mobile to existing set of mobiles
else:
customers[name] = {mobile} # Add a new entry with name and mobile
f.close()
for name, mobiles in sorted(customers.items()):
print(f"{name:15} {','.join(sorted(mobiles))}")
| true |
559a526cf95fd9089410172044a19491e55a77db | AvishDhirawat/Python_Practice | /bmi_calc using funcn.py | 412 | 4.125 | 4 | #Author - Avish Dhirawat
def bmi_calc(name,weight,height):
bmi=weight/(height**2)
print ("BMI : ")
print (bmi)
if bmi<25:
print (name + " is Under Weighed")
elif bmi>25:
print (name + " is Overweighed")
else :
print (name + " is Equally Weighed")
a = input("Enter Name : ")
b = input("Enter Weight in KG : ")
c = input("Enter Height in M : ")
bmi_calc(a,b,c) | false |
b7b7820e346c7aa3d8909f86d62edd469aee4324 | Dilaxn/Hacktoberfest2021-2 | /Fibonacci_sequence.py | 312 | 4.1875 | 4 | n = int(input("Number of terms? "))
a,b = 0, 1
c = 0
if n <= 0:
print("Only positive integers are allowed")
elif n == 1:
print("Fibonacci sequence till",n,":")
print(a)
else:
print("Fibonacci sequence is:")
while c < n:
print(a)
nth = a + b
a = b
b = nth
c += 1
| false |
3da59a6ef09ad69ad0197d877961e6521add726f | Obichukwu/linkedin-python-data-structure | /run_deque.py | 478 | 4.15625 | 4 | from deque import Deque
def is_palindrome(word):
deq = Deque()
for ch in word:
deq.add_rear(ch)
#deq.items = word.split()
while deq.size() >= 2:
front = deq.remove_front()
rear = deq.remove_rear()
if (front != rear):
return False
return True
def test_is_palindrome():
inp = input("Enter a string to test for Palindrome: ")
print(is_palindrome(inp))
if __name__ == "__main__":
test_is_palindrome() | false |
11a93dee71081247fa8b62a48fc4ccbcfbc5563f | RubennCastilloo/master-python | /06-bucles/bucle-for.py | 884 | 4.3125 | 4 | """
# FOR
for variable in elemento_iterable (lista, rango, etc)
BLOQUE DE INSTRUCCIONES
"""
numeros = [1, 2, 3, 4, 5]
for numero in numeros:
print(f"El número iterado es {numero}")
contador = 0
resultado = 0
for contador in range(0, 10):
print(f"Voy por el {contador}")
resultado += contador
print(f"El resultado es: {resultado}")
# Ejemplo con tablas de multiplicar
print('\n############## EJEMPLO ##############')
numero_usuario = int(input("¿De que número quiere la tabla?: "))
if numero_usuario < 1:
numero_usuario = 1
print(f"### Tabla de multiplicar del numero {numero_usuario} ###")
for numero_tabla in range(1, 11):
if numero_usuario == 45:
print("No se pueden mostrar numeros prohibidos")
break
print(f"{numero_usuario} x {numero_tabla} = {numero_usuario * numero_tabla}")
else:
print("Tabla finalizada") | false |
095d7d713c0fa69ca663e4bfac17b09d9d1f97c7 | leledada/LearnPython | /test_code/20180327-6-11test.py | 401 | 4.125 | 4 | # 用符号的组合在控制台输出不同大小的矩形图案。
# 要求:写一个输出矩形的函数,该函数拥有三个默认参数,矩形的长5、宽5和组成图形的点的符号“*”,为函数添加不同的参数,输出三个不同类型的矩形;
def myRact(l=5, h=5, p='*'):
for i in range(l):
print(p * h)
myRact()
myRact(4, 3, '#')
myRact(2, 6, "!")
| false |
30e0997cb7359cd6f14b98717c68d409c6f68aec | dalexach/holbertonschool-machine_learning | /supervised_learning/0x04-error_analysis/1-sensitivity.py | 684 | 4.3125 | 4 | #!/usr/bin/env python3
"""
Sensitivity
"""
import numpy as np
def sensitivity(confusion):
"""
Function that calculates the sensitivity for each class
in a confusion matrix
Arguments:
- confusion: is a confusion numpy.ndarray of shape (classes, classes)
where row indices represent the correct labels and column
indices represent the predicted labels
* classes is the number of classes
Returns:
A numpy.ndarray of shape (classes,) containing the sensitivity
of each class
"""
TP = np.diag(confusion)
FN = np.sum(confusion, axis=1) - TP
SENSITIVITY = TP / (TP + FN)
return SENSITIVITY
| true |
e62b085add02d42761f087761eeccfe1c55b53d4 | dalexach/holbertonschool-machine_learning | /supervised_learning/0x03-optimization/4-moving_average.py | 608 | 4.1875 | 4 | #!/usr/bin/env python3
"""
Moving average
"""
def moving_average(data, beta):
"""
Function that calculates the weighted moving average of a data set:
Arguments:
- data (list): is the list of data to calculate the moving average of
- beta (list): is the weight used for the moving average
Returns:
A list containing the moving averages of data
"""
moving_average = []
V = 0
t = 1
for d in data:
V = beta * V + (1 - beta) * d
correct = V / (1 - (beta ** t))
moving_average.append(correct)
t += 1
return moving_average
| true |
b01b43fb042dd2345fd2778fd4c75418b95b7a97 | dalexach/holbertonschool-machine_learning | /supervised_learning/0x03-optimization/1-normalize.py | 621 | 4.28125 | 4 | #!/usr/bin/env python3
"""
Normalize
"""
import numpy as np
def normalize(X, m, s):
"""
Function that normalizes (standardizes) a matrix
Arguments:
- X: is the numpy.ndarray of shape (d, nx) to normalize
* d is the number of data points
* nx is the number of features
- m: is a numpy.ndarray of shape (nx,) that contains the mean of
all features of X
- s: is a numpy.ndarray of shape (nx,) that contains the standard
deviation of all features of X
Returns:
The normalized X matrix
"""
standardizes = (X - m) / s
return standardizes
| true |
2e7755488ee4f5f74d8120d2d10ef04b0446c37b | Wet1988/ds-algo | /algorithms/sorting/quick_sort.py | 1,132 | 4.21875 | 4 | import random
def quick_sort(s, lower=0, upper=None):
"""Sorts a list of numbers in-place using quick-sort.
Args:
s: A list containing numbers.
lower: lower bound (inclusive) of s to be sorted.
upper: upper bound (inclusive) of s to be sorted.
Returns:
s
"""
if upper is None:
upper = len(s) - 1
# base case (1 element or less)
if lower >= upper:
return
# choose random index as pivot
pivot = random.randint(lower, upper)
# perform partitioning
left = lower
right = upper
done = False
while done is False:
while s[left] < s[pivot]:
left += 1
while s[right] > s[pivot]:
right += 1
if left >= right:
done = True
else:
s[left], s[right] = s[right], s[left]
left += 1
right += 1
# partition element
part = right
# recurse
quick_sort(s, lower, part)
quick_sort(s, part + 1, upper)
if __name__ == "__main__":
n = 100
s = [random.randint(0, n) for x in range(n)]
quick_sort(s)
print(s)
| true |
6d5fa9841aaed33cade266f564debefbd97e82a0 | JustinCee/tkinter-handout | /handout exercise.py | 1,103 | 4.375 | 4 | # this is to import the tkinter module
from tkinter import *
# this function is to add the numbers
def add_numbers():
r = int(e1.get())+int(e2.get())
label_text.set(r)
def clear():
e1.delete(0)
e2.delete(0)
root = Tk()
# the below is the size of the window
root.geometry("600x200")
root.title("Justin's simple calculator")
label_text = StringVar()
Label(root, text="Enter First Number:").grid(row=0, sticky=W)
Label(root, text="Enter Second Number:").grid(row=1, sticky=W)
Label(root, text="Result of Addition:").grid(row=3, sticky=W)
result = Label(root, text="", textvariable=label_text).grid(row=3, column=1, sticky=W)
e1 = Entry(root)
e2 = Entry(root)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
# below is the button and the labels on it
b = Button(root, text="Add", command=add_numbers)
b1 = Button(root, text="Clear", command=clear)
b2 = Button(root, text="Exit", command=root.destroy)
b.grid(row=5, column=1, sticky=W+E+N+S, padx=5, pady=5)
b1.grid(row=5, column=2, sticky=W+E+N+S, padx=5, pady=5)
b2.grid(row=5, column=3, sticky=W+E+N+S, padx=5, pady=5)
mainloop()
| true |
c1a165174ddc6f5dc927a5855a109b647e920cdf | antony10291029/lxfpyanswer | /20oop_program.py | 706 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#设计一个计算学生成绩的类,并且用实例表现出来
class Student(object):
def __init__(self,name,score):
self.name = name
self.score = score
def print_score(self):
print('%s: %s' % (self.name, self.score))
#这里直接定义print方法的意义在于,调用这个类的实例的时候,可以直接输出内容
#否则的话要print一次内容
std1 = Student('John',86)
std2 = Student('Vicent',46)
std1.print_score()
std1.print_score()
print(std1)
#这里会打印出一个内存地址,表明std是函数类的一个对象,就是实例
print(Student)
#这里会直接告诉你这是类的内存地址
| false |
7bbc137569534407c0994ff34dc78bcc63b2b5cc | gui-csilva/python | /Python/Sétimo_programa.py | 1,013 | 4.3125 | 4 | #nessa linha criamos a variavel par
par = []
#nessa linha criamos a variavel a
a = [1,2,3,4,5,6,7,8,9,10]
#nessa linha criamos a variavel impar
impar = []
#nessa linha iniciamos um loop
for v in a:
#nessa linha imprimimos a string par
print("par")
#nessa linha mostra os números pares
print(par)
#nessa linha imprimimos a string impar
print("impar")
#nessa linha mostra os números impares
print(impar)
#nessa linha da um espaço
print()
#nessa linha colocamos uma função para indentificar se o número é par
if(v % 2) == 0:
#nessa linha execultamos a função para indicar se o número é par
par.append(v)
#nessa linha colocamos uma função para indentificar se o número é não é par
else:
#nessa linha execultamos a função para falar indicar que o número é impar
impar.append(v)
#nessa linha mostra todos os números pares
print(par)
#nessa linha mostra todos os números
print(a)
#nessa linha msotra todos os números imapares
print(impar) | false |
c96975836d9fc7e0fe4c1b99f93ad192622faf8c | gui-csilva/python | /Python/Anotações.py.py | 2,379 | 4.21875 | 4 | #IDE (programa que nos ajuda a escarever códigos)
#String ou str (qualquer coisa escrita entre duas aspas)
#single quote = apostrofe = 1 aspa; quote = aspas = " "
#"conversa";#string
#'F'; #caracter
#-10 até 10 int = Integer = numero inteiro
#10;
#-10;
#Float= número decimal= 10.9
#3.4;
#String"10"
#Variaveis - Variables - VAR
#Jeferson = "minha variavel"
#type = mostra o tipo da variavel
#input = faz uma pergunta que espera resposta essa resposta pode ser usada para uma variavel
#print = imprimi o que você quiser na tela
#cls = limpar tela do cmd
#str = transforma integer em string
#int = transforma string em integer
#contatenacao = quando você soma? junta duas strings
#recebe: =
#igual: ==
#boolean = fala se é verdadeiro ou falso; Se você chamar a função 0 da falso, mas se você chamar qualquer outra coisa vai dar true
#bool() = fala se é verdadeiro ou falso
#if = é uma função reservada que te da uma resposta baseado em uma comparação
#elif = é uma função reservada que te da uma resposta baseado em uma comparação
#Criar um programa que pede o nome do usuario, o ano de nascimento do usuarios, e dois numeros.
#nome = input("Qual seu nome? ");
#ADN = input("Qual é seu ano de nacimento? ");
#PN = input("Coloque um número aqui! ");
#SN = input("coloque outro número aqui! ");
#idade = 2021 - int(ADN)
#soma = int(PN) + int(SN)
#nome = "Vitor"
#segundoNome = nome
#print("Nome:" + nome)
#print("idade:" + str(idade) + "/" + ADN)
#print("a soma dos seus números foi:" + str(soma))
#print("segundoNome")
#print(segundoNome)
#lists/Array = faz uma lista com qualquer tipo. Se usa esses símbolos para fazer a lista: []. Em uma lista a vírgula separa os elementos
#len = contas os elementos de strings e listas
#lista[2:] = mostra o elemento 2 da lista e os elemnetos que estão a diante
#lista[:2] = mostra um elemento anterior do elemento 2 e os que estão anteriormente
#para usar duas condições diferentes com o mesmo resultado entra as condições coloque or ou |. O :(então só é usado no final)
import random
a = random.randrange(1,11)
b = random.randrange(11,21)
c = random.randrange(21,31)
d = random.randrange(31,41)
e = random.randrange(41,51)
f = random.randrange(51,61)
print(str(a) + "-" + str(b) + "-" + str(c) + "-" + str(d)+ "-" + str(e) + "-" + str(f)) | false |
84e78624aa3c0171d05b430576946cad18360fdf | BC-CSCI-1102-S19-TTh3/example_code | /week10/dictionarydemo.py | 507 | 4.40625 | 4 | # instantiating a dictionary
mydictionary = {}
# adding key-value pairs to a dictionary
mydictionary["dog"] = 2
mydictionary["cat"] = 17
mydictionary["hamster"] = 1
mydictionary["houseplant"] = 5
# getting a value using a key
mycatcount = mydictionary["cat"]
# looping through keys in a dictionary
for k in mydictionary.keys():
print(k, mydictionary[k])
# looping through keys and values
for k,v in mydictionary.items():
print(k,v)
if "cat" in mydictionary:
print("cat is in the dictionary!")
| true |
3df5c17e536ddf072745ff1dca3aae6a7f265c51 | llamington/COSC121 | /lab_8_5.py | 1,783 | 4.34375 | 4 | """A program to read a CSV file of rainfalls and print the totals
for each month.
"""
from os.path import isfile as is_valid_file
def sum_rainfall(month, num_days, columns):
"""sums rainfall"""
total_rainfall = 0
for col in columns[2:2 + num_days]:
total_rainfall += float(col)
return month, total_rainfall
def process_data(data):
"""processes data"""
results = [] # A list of (month, rainfall) tuples
for line in data:
columns = line.split(',')
month = int(columns[0])
num_days = int(columns[1])
results.append(sum_rainfall(month, num_days, columns))
return results
def print_rainfalls(results):
"""prints total rainfalls"""
print('Monthly total rainfalls')
for (month, total_rainfall) in results:
print('Month {:2}: {:.1f}'.format(month, total_rainfall))
def get_filename():
"""receives filename"""
filename = input('Input csv file name? ')
while not is_valid_file(filename):
filename = input('Input csv file name? ')
print('File does not exist.')
return filename
def data_list(filename):
"""processes data into list"""
datafile = open(filename)
data = datafile.read().splitlines()
datafile.close()
return data
def main():
"""Prompt the user to provide a csv file of rainfall data, process the
given file's data, and print the monthly rainfall totals.
The file is assumed to have the month number in column 1, the number
of days in the month in column 2, and the floating point rainfalls
(in mm) for that month in the remaining columns of the row.
"""
filename = get_filename()
data = data_list(filename)
results = process_data(data)
print_rainfalls(results)
main()
| true |
e3f75b248da72151068bf8707e1216e33ec03f57 | AnandCodeX/Beginner-to-Advanced-python-List-of-Programs | /Python/L8/pr2.py | 480 | 4.21875 | 4 | #waoopp class circle
#radius
#display()
#area()
#circumference()
class circle:
def __init__(self,r):
self.radius=r
def show(self):
print("radius = ",self.radius)
def area(self):
ans=3.14159*self.radius**2
print("radius = ",round(ans,2))
def circumference(self):
ans=2*3.14159*self.radius
print("circumference = ",round(ans,2))
r=float(input("enter radius"))
c=circle(r)
c.show()
c.area()
c.circumference()
| false |
cdf618d95d1d4e99aeccf6e67df08a96a7f812a7 | RSnoad/Python-Problems | /Problem 7.py | 588 | 4.125 | 4 | # Find the 10,001st prime number
from math import sqrt
# Function to find the nth prime in list using the isPrime function below.
def nthPrime(n):
i = 2
primeList = []
while len(primeList) < n:
if isPrime(i):
primeList.append(i)
i += 1
print(primeList[-1])
# Brute force method to check if a number is prime.
# Could also clean up to give error for certain input ( negatives, decimals etc)
def isPrime(n):
for i in range(2, int(sqrt(n) + 1)):
if n % i == 0:
return False
return True
nthPrime(6)
nthPrime(10001)
| true |
685452c53ea915107f3f2a2ec2ef020a1702f132 | isaac-friedman/lphw | /ex20-2.py | 1,661 | 4.6875 | 5 | ####
#This file combines what we've learned about functionwas with what we've
#learned about files to show you how they can work together. It also
#sneaks in some more info about files which you may or may not know depending
#on if you did the study drills.
####
from sys import argv
#In some of my versions of the study drills, I access the arguments I want
#directly using [brackets]. Is this a good idea? Does it make any difference at
#all? Think about it.
script, input_file = argv
#read and print the whole file in one shot
def print_all(f):
print f.read()
#move the iterator to the beginning of the file specified.
#Is printing necessary? Why or why not?
def rewind(f):
print f.seek(0)
#Prints line line_count of file f
def print_a_line(line_count, f):
print line_count, f.readline()
#Get a file object
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print """
We printed using a iterator *aaahh!!! scary word*. That iterator is now at the
end of the file, so we have to rewind it like a tape.
"""
#What happens if you comment out this line?
rewind(current_file)
print "Let's print all the lines one by one."
current_line = 1
print "current_line is equal to %d" %current_line
print_a_line(current_line, current_file)
#If you think this repetition is silly, you're rights. Soon we will learn about
#loops which exist to solve this problem.
current_line = current_line + 1
print "current_line is equal to %d" %current_line
print_a_line(current_line, current_file)
current_line = current_line + 1
print "current_line is equal to %d" %current_line
print_a_line(current_line, current_file)
| true |
21e7a38cfa5194e6b321693cbe24008421ff0974 | isaac-friedman/lphw | /ex13-3_calc.py | 1,129 | 4.6875 | 5 | ####
#More work with argv
#This time we will use argv to collect two operands and then use raw input to
#ask for an arithmetic operation to perform on them. Effectively, we've just
#made a basic calculator
####
from sys import argv
####
#See how we aren't checking to make sure the arguments are numbers? That is a
#Very Bad Idea. Run the script with something other than numbers to find out
#why.
####
script, first, second = argv #script is always an argument
#input is like raw_input except that it reads a python expression
op = raw_input("Which arithmetic operation would you like to perform?")
####
#Making sure your input is the right kind of data, and knowing what to do if it
#isn't is called "validation". This is a very simple kind of validation to make
#sure we were given an arithmetic operator.
####
if op in ['+','-','*','/','%','**']: #all the arithmetic python supports
exp = first + op + second #makes an expression with our string in it
result = eval(exp) #eval takes a string and treats it like python code
print result
else:
print "bad operation. goodbye" #this is a horrible way to handle errors
| true |
d1c8dbc2a8c9ba6edff5ff330a826997c5c019dc | isaac-friedman/lphw | /ex15.py | 1,390 | 4.5 | 4 | ####
#This script prints a specified file to the screen. More specifically, it
#prints to something called "standard output" which is almost always the screen
#but could be something else. For now, think of 'print' as 'printing to the
#screen' and 'standard output' or 'stdio' etc as "the screen." It's easier and
#pretty much always true.
####
#get the argv to be able to access command line arguments
from sys import argv
#Unpack your variables. You will always have to unpack your script because
#argv reads (and counts) the arguments to the `python` command not to your
#script.
script, filename = argv
#txt is a 'file object'. You should google those because they're very important
#for I/O, and a good way to begin understanding how to use objects in
#programming
txt = open(filename)
print "Here is your file %r:" %filename
#Here, we call the `read` function OF the txt object. This function reads the
#file.
print txt.read()
#it is important to close files when you are done with them.
nxt_txt.close()
#We do the same thing again, this time asking for input with a prompt
print "Type another file, or the same one for all I care."
#This is a nested function. Instad of putting the input in a variable,
#you can call `open` on it directly. Remember to have the same number of open
#and closed parentheses
nxt_txt = open(raw_input('> '))
print nxt_txt.read()
nxt_txt.close()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.