blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
e96ddad286961be9804540985a1794a3871cb484 | NMoshe/HR-Python | /Intro/leapyears.py | 398 | 4.125 | 4 | def leap(year):
if year % 100 == 0:
if year % 400 == 0:
print(year)
else:
print(f'{year} is not a leap year')
elif year % 4 == 0:
print(year)
else:
print(f'{year} is not a leap year')
if __name__ == '__main__':
leap(1900)
leap(2000)
leap(2400)
leap(2020)
leap(1990)
leap(2024)
leap(2025)
leap(8)
| false |
f171bf15850b9724867e9738efa92ac897433154 | reulan/hackerrank | /python/introduction/elif.py | 765 | 4.28125 | 4 | """
elif.py - Simple if else script in Python.
mpmsimo
1/27/17
"""
def check_if_weird(n):
"""Checks to see if a certain number is weird or not."""
# If remainder is 0 when n(modulo 2) then number is even.
if (n % 2 == 0):
# If n is even and in the inclusive range of 2 to 5, print Not Weird
if (n >= 2 and n <= 5):
print("Not Weird")
# If n is even and in the inclusive range of 6 to 20, print Weird
elif (n >= 6 and n <= 20):
print("Weird")
# If n is even and greater than 20, print Not Weird
elif (n > 20):
print("Not Weird")
else:
# If n is odd, print Weird
print("Weird")
if __name__ == "__main__":
n = int(input())
check_if_weird(n)
| true |
ee83b994582823f1782080ebe08aea159343dae2 | ScottishGuy95/advent_of_code_2020 | /12/rain.py | 2,228 | 4.15625 | 4 | #! python3
# seating.py - Handles moving the ship during the storm
# Advent Of Code 2020 - Day 12
filename = "input.txt"
actions = []
compass = {'N': 0, 'E': 0, 'S': 0, 'W': 0}
directions = 'ESWN'
# Read the input file, adding each line to a list
for line in open(filename, 'r'):
line = line.replace("\n", "") # Removes the newline that is added in the text file
actions.append(line)
def changeDir(turn, angle):
"""
Adjusts the current angle of the boat
:param turn: The direction to affect
:param angle: The angle of how much to turn by
:return: The new angle value
"""
# Converts each argument to the corrent type
turn = str(turn)
angle = int(angle)
if turn == 'L': # If Left, set the negative of the angle, and divide by 90 to get 3/2/1/0
return int(-angle / 90)
elif turn == 'R':
return int(angle / 90) # If Left, set the negative of the angle, and divide by 90 to get 3/2/1/0
def part1(theActions, aCompass, theDirections):
facing = theDirections[0] # Sets starting direction as East
for action in theActions:
# Splits the action into its Letter and its Value
ltr = action[0]
value = int(action[1:])
if ltr in theDirections: # Check if the letter is one of the directions - ESWN
aCompass[ltr] += value # Increase that direction bu its value
elif ltr in 'LR': # If the letter is left or right
# Get the current position of 'facing' from the list
# Add that to the resulting angle from changeDir
# Use modulus 4 to get the final position
facing = theDirections[(theDirections.find(facing) + changeDir(ltr, value)) % 4]
elif ltr == 'F': # If the letter is Forward
aCompass[facing] += value # Increase the facing direction by the given value
# Find the manhattan distance
return abs(aCompass['N'] - aCompass['S']) + (abs(aCompass['E'] - aCompass['W']))
def part2():
return 2
print('Part 1: ' + str(part1(actions, compass, directions)))
print('Part 2: ' + str(part2()))
| true |
1ff90ab870ab6eae1b130f0b10f39abf9afb3d77 | kanyu/Mathematical-Thinking-in-CS | /thinking-recursively.py | 2,753 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 13 12:15:24 2018
@author: Kan
"""
houses = ["Eric's house", "Kenny's house", "Kyle's house", "Stan's house"]
def deliver_iter():
for house in houses:
print("Delivering presents to", house)
def deliver_recursive(houses):
if len(houses) == 1:
print("Delivering presents to", houses[0])
else:
print("Delivering presents to", houses[0])
deliver_recursive(houses[1:])
# Each function call represents an elf doing his work
def deliver_recursive2(houses):
# Worker elf doing his work
if len(houses) == 1:
house = houses[0]
print("Delivering presents to", house)
# Manager elf doing his work
else:
mid = len(houses) // 2
first_half = houses[:mid]
second_half = houses[mid:]
# Divides his work among two elves
deliver_recursive2(first_half)
deliver_recursive2(second_half)
def factorial_recursive(n):
# Base case: 1! = 1
if n == 1:
return 1
# Recursive case: n! = n * (n-1)!
else:
return n * factorial_recursive(n-1)
"""----------------------------------------------------------------------------
Recursive Data Structures in Python
A data structure is recursive if it can be defined
in terms of a smaller version of itself.
A list is an example of a recursive data structure.
Let me demonstrate.
Assume that you have only an empty list at your disposal,
and the only operation you can perform on it is this:
----------------------------------------------------------------------------"""
# Return a new list that is the result of
# adding element to the head (i.e. front) of input_list
def attach_head(element, input_list):
return[element] + input_list
attach_head(1, # Will return [1, 46, -31, "hello"]
attach_head(46, # Will return [46, -31, "hello"]
attach_head(-31, # Will return [-31, "hello"]
attach_head("hello", [])))) # Will return ["hello"]
from functools import lru_cache
def Fibnaive(n):
print("Calculating F", "(", n, ")", sep="", end=", ")
# Base case
if n == 0:
return 0
elif n == 1:
return 1
# Recursive case
else:
return Fibnaive(n-1) + Fibnaive(n-2)
@lru_cache(maxsize = None)
def Fib(n):
print("Calculating F", "(", n, ")", sep="", end=", ")
# Base case
if n <= 2:
return n
# Recursive case
else:
return Fib(n - 1) + Fib(n - 2)
| false |
b5dca1992e5eb4ee56a7b8177ce4fa604fc4453d | eliud-kagema/100_days_of_python | /2. Day 2 - Beginner - Understanding Data Types and How to Manipulate Strings/tip_calculator.py | 877 | 4.34375 | 4 | # Tip Calculator
#1. Create a greeting for your program.
print("Welcome to the tip calculator")
#2. Ask the user to input the total bill
bill = float(input('What is the total bill? Kshs\n'))
#3. Ask the user for tip percentage of the total amount
tip = int(input('How much tip would you like to give? 10, 12 or 15?\n'))
#4. How many people are splitting the bill
people = int(input('How many people are splitting the bill?\n'))
#5. Tip as percent
tip_as_percent = tip/100
#5. Calculate total tip amount
total_tip_amount = bill * tip_as_percent
#6. Calculate total amount to be paid
total_bill = total_tip_amount + bill
#7. divide by number of people to get individual contribution
bill_per_person = total_bill / people
# Rounding off to the nerarest 2 decimal places
final_amount = round(bill_per_person, 2)
print(f'Individual Contribution {final_amount} Kshs')
| true |
0b6b856058226baf38505cb2de0feb92d412aa7f | GHEPT/VSCode_Python | /Modulo1/Exercícios Entrega Aula 16/Exercício_02.py | 926 | 4.15625 | 4 | #02 - Utilizando estruturas de repetição com variável de controle, faça um programa que receba uma string com uma frase informada pelo usuário e conte quantas vezes aparece as vogais a,e,i,o,u e mostre na tela, depois mostre na tela essa mesma frase sem nenhuma vogal.
cont = 0 # VAI CONTAR QUANTAS VOGAIS HAVERÁ NA FRASE DO USUÁRIO
a = input('\nDigite uma frase: ').lower() # NECESSÁRIO TRANSFORMAR O INPUT DO USUÁRIO PARA DAR BOM NA CONDIÇÃO
for i in a: # TODA VEZ QUE O CONTADOR PASSAR POR UM CARACTERE DA FRASE
if i in 'aáàãeéêiíoôóuú': # SE O CONTADOR ENCONTRAR QUALQUER UM DESSES CARACTERES
cont += 1 # O CONTADOR SOMA 1
a = a.replace(i, ' ') # E A FRASE DO USUÁRIO PERDE A VOGAL ENCONTRADA NAQUELA RODADA DO CONTADOR
print()
print('-=' * 30)
print(f'A sua frase contém {cont} vogais')
print('-=' * 60)
print(f'Esta mesma frase sem vogais ficaria assim: [ {a} ]')
print('-=' * 60)
| false |
c2d8da2a96c32703d37084345769cc1d443b71a6 | GHEPT/VSCode_Python | /Modulo1/Projeto Módulo 1/ProjetoMod1.py | 1,221 | 4.3125 | 4 | # Escopo do projeto
# Em grupos de 2 ou 3 pessoas, crie um jogo de ficção interativa que simule a rotina diária de um personagem. Você pode escolher entre rotinas matinais, rotinas de trabalho, rotinas de estudos, entre outras. A ideia do jogo é que o jogador faça as escolhas para o seu personagem e o conduza durante o seu dia. Cada escolha irá gerar uma consequência diferente para o seu personagem. O jogo acaba quando o dia do seu personagem acabar. Você será responsável por determinar o inicio e término do dia do seu personagem, além de avançar o tempo a cada escolha.
from random import randint
while True:
print('-=' * 40)
print('São '+str(relogio)+' do dia '+str(dia)'.
print('Você tem um encontro com o Príncipe às 18:00.')
print(personagem)
print("")
print("Ações:")
print("1 - Tomar banho e escovar os dentes")
print("2 - Fazer café da manhã")
print("3 - Pedir café da manhã")
print("4 - Tomar café da manhã")
print("5 - Tomar remédio")
print("6 - Comprar remédio")
print("7 - Ir trabalhar")
print("0 - Sair do jogo")
opcao = input("Escolha sua ação:")
| false |
ee2f78b94e2132f9c488e529e96a626c11af1e5a | GHEPT/VSCode_Python | /Modulo1/Aula07/Codelab_aula07_06.py | 874 | 4.15625 | 4 | # Exercício 6
# Um professor, muito legal, fez 3 provas durante um semestre,mas só vai levar em conta as duas notas mais altas para calcular a média. Faça uma aplicação que peça o valor das 3 notas, mostre como seria a média com essas 3 provas, a média com as 2 notas mais altas, bem como sua nota mais alta e sua nota mais baixa.
def notas(a, b, c):
med = (a + b + c) / 3
med_altas = ((a + b + c) - (min(lista))) / 2
lista = [a, b, c]
min(lista)
max(lista)
print(f'A média das três notas seria: {med}')
print(f'A média com as duas notas mais altas é: {med_altas}')
print(f'A nota mais alta foi: {max(lista)}')
print(f'Sua nota mais baixa foi: {min(lista)}')
a = float(input('Digite a nota 1: '))
b = float(input('Digite a nota 2: '))
c = float(input('Digite a nota 3: '))
notas(a, b, c)
| false |
9e46e31002326fd0a61378c7813ce1d84306ef03 | GHEPT/VSCode_Python | /Modulo1/Aula06/10 05 2021/Aula06_Ex6.py | 756 | 4.125 | 4 | # Escreva uma função que, dado um númeronotarepresentando a nota de um estudante, converte o valor de nota para um conceito (A, B, C, D, E e F).
""" Nota / Conceito
>= 9.0 / A
>= 8.0 / B
>= 7.0 / C
>= 6.0 / D
>= 5.0 / E
<= 4.0 / F """
def conceito():
global n
if n >= 9:
n = print('A')
return n
elif n >= 8:
n = print('B')
return n
elif n >= 7:
n = print('C')
return n
elif n >= 6:
n = print('D')
return n
elif n >= 5:
n = print('E')
return n
elif n >= 0 and n <= 4:
n = print('F')
return n
else:
n = print('Você digitou uma nota inválida')
return n
n = float(input('Digite sua nota: '))
conceito()
| false |
24f7455b5f3e35375401e8d1fed07073a8743e6e | vishalicious213/data-structures-and-algo-practice | /queue.py | 1,421 | 4.625 | 5 | # FIFO: first in first out
# create the abstract data type
class Queue:
def __init__(self):
# initialize it to a one dimensional array or linked list
self.queue = []
"""
Stack methods (enqueue, dequeue, peek, is_empty, size_queue)
"""
# function to check if the queue is empty O(1)
def is_empty(self):
return self.queue == []
# function to add data to the queue O(1)
def enqueue(self, data):
self.queue.append(data)
# function to remove and return the first item inserted to the queue O(N)
def dequeue(self):
# first check to make sure its not an empty queue
if self.size_queue()!= 0:
# get the first item in the queue
data = self.queue[0]
# remove it
del self.queue[0]
# return the item
return data
else:
return -1
# function to return the first item in the queue without removing it
# O(1)
def peek(self):
return self.queue[0]
# function get the size of the queue O(1)
def size_queue(self):
return len(self.queue)
"""
Using the methods
"""
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(f'Size: {queue.size_queue()}')
print(f'Dequeue: {queue.dequeue()}')
print(f'Size: {queue.size_queue()}')
print(f'Peeked item: {queue.peek()}')
print(f'Size: {queue.size_queue()}')
| true |
fd8583a587f997ccade221a351ab39ed249431d3 | Jotahm/Teoria-Basica-Python | /5.1_unamos_variables_y_cadenas.py | 1,139 | 4.1875 | 4 | #5.1
#Unamos ahora variables y cadenas y observemos el resultado
trabajadores = 2700
empresa = "Remotech"
#cadena = "Los 2700 trabajadores de la empresa Remotech recibiran paga extraordinaria"
# En este caso podemos concatenar las variables así:
#cadena = "Los" + trabajadores + "trabajadores de la empresa" + empresa + "recibiran paga extraordinaria"
#print (cadena) # da error y nos dice que no se pueden concatenar números enteros
# Para solventar este error convertimos la variable en cadena
cadena = "Los " + str(trabajadores) + " trabajadores de la empresa " + empresa + " recibiran paga extraordinaria" #no olvidamos añadir los espacios
print (cadena)
# .format es muy práctico. Evitamos tener que transformar la variable numerica a cadena. Observa
cadena = "Los {} trabajadores de la empresa {} recibiran paga extraordinaria".format(trabajadores, empresa)
print (cadena)
cadena = "Los {a} trabajadores de la empresa {b} recibiran paga extraordinaria".format(a=trabajadores, b=empresa)
print (cadena)
cadena = f"Los {trabajadores} trabajadores de la empresa {empresa} recibirán paga extraordinaria"
print (cadena)
| false |
3bf366e60220e2a4ac13c118750943b2c6cd0d0d | Tapsanchai/basic_pythom | /Quiz/quiz_reder_stair-step.py | 770 | 4.21875 | 4 | Final_round = int(input("Enter Your Number: "))
for i in range(1,Final_round+1):
for x in range(1,i+1):
print("* ",end="")
print("")
for row in range(Final_round):
for col in range(Final_round):
print("x ",end="")
print("")
# triangle pattern
"""
n = 5
k = n - 1
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number spaces
# values changing acc. to requirement
for j in range(0, k):
print(end=" ")
# decrementing k after each loop
k = k - 1
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing stars
print("* ", end="")
# ending line after each row
print("")
""" | false |
4539dc499ab48d108239c0f80b87a81b9148b222 | folivetti/PI-UFABC | /AULA_02/Python/Triangulo.py | 619 | 4.125 | 4 | # -*- coding: cp1252 -*-
'''
Triangulo.py
* Dada as trs dimenses de um tringulo
* determinar se realmente um tringulo e qual tipo ele
* Entrada: x,y,z (double)
* Sada: se tringulo e qual tipo
Autor: Fabrcio Olivetti de Frana
Disciplina Processamento da Informao
Universidade Federal do ABC
'''
x = float( raw_input("x = ") )
y = float( raw_input("x = ") )
z = float( raw_input("x = ") )
if x+y > z and x+z > y and y+z > x:
if x==y and y==z:
print "Equilatero"
elif x==y or y==z or x==z:
print "Isceles"
else:
print "Escaleno"
else:
print "No um tringulo"
| false |
2f53ae4f720956b091eef2e83c880594f14d7405 | SammyAJ/ppl | /python all progs/sort.py | 2,296 | 4.125 | 4 | #class Sort () :
# def __init__(self) :
# print "This a sorting program"
def mergeSort(alist):
# print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
# while i < len(lefthalf):
# alist[k]=lefthalf[i]
# i=i+1
# k=k+1
#while j < len(righthalf):
# alist[k]=righthalf[j]
# j=j+1
# k=k+1
#print("Merging ",alist)
def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
def quickSort(alist):
quickSortHelper(alist,0,len(alist)-1)
def quickSortHelper(alist,first,last):
if first<last:
splitpoint = partition(alist,first,last)
quickSortHelper(alist,first,splitpoint-1)
quickSortHelper(alist,splitpoint+1,last)
def partition(alist,first,last):
pivotvalue = alist[first]
leftmark = first+1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
leftmark = leftmark + 1
while alist[rightmark] >= pivotvalue and rightmark >= leftmark:
rightmark = rightmark -1
if rightmark < leftmark:
done = True
else:
temp = alist[leftmark]
alist[leftmark] = alist[rightmark]
alist[rightmark] = temp
temp = alist[first]
alist[first] = alist[rightmark]
alist[rightmark] = temp
return rightmark
alist = list(input(" enter a list \n"))
print "1) Merge Sort"
print "2) Bubble Sort"
print "3) Quick Sort"
a = input("Enter your choice");
if (a==1) :
mergeSort(alist)
print(alist)
elif (a==2) :
bubbleSort(alist)
print(alist)
elif (a==3) :
quickSort(alist)
print(alist)
| false |
77b68d8803e7751d5b790fd2ac9fe900f580c36e | pdm1/itp-w1-bubble-sort | /bubble_sort/main.py | 444 | 4.25 | 4 | """This is the entry point of the program."""
def bubble_sort(a_list):
place_holder = ""
for first in range(len(a_list)):
for second in range(len(a_list)):
if a_list[first] < a_list[second]:
place_holder = a_list[first]
a_list[first] = a_list[second]
a_list[second] = place_holder
print(a_list)
return a_list
if __name__ == '__main__':
print(bubble_sort([9, 1, 3, 11, 7, 2, 42, 111]))
| true |
3589391ade56043f643ee36fd842f31676d10cd3 | side-projects-42/DS-Bash-Examples-Deploy | /CONTENT/DS-n-Algos/ALGO/__PYTHON/TripletSearch.py | 1,041 | 4.125 | 4 | # https://www.geeksforgeeks.org/find-triplets-array-whose-sum-equal-zero/
#o(n^3)
# def Triplet(arr):
# n = len(arr)
# found = False
# for i in range(0, n - 2):
# for j in range(i + 1, n - 1):
# for k in range(j + 1, n):
# if arr[i] + arr[j] + arr[k] == 0:
# print(arr[i], arr[j], arr[k])
# found=True
#
# if not found:
# print("element not found")
#
#
# arr=[0, -1, 2, -3, 1]
#
# Triplet(arr)
# optimal soultion
#o(n^2)
def Triplet(arr):
n=len(arr)
found=True
for i in range(n-1):
l=i+1
r=n-1
x=arr[i]
while l<r:
if arr[l]+arr[r]+x==0:
print(arr[l],arr[r],x)
l+=1
r-=1
found=True
elif arr[l]+arr[r]+x<0:
l+=1
else:
r-=1
if not found:
print("triplet not found")
arr=[0, -1, 2, -3, 1]
Triplet(arr) | false |
deec4ead496a41be32a8be396a1bbc80b7b6359d | YazminFavela879/VariablesPractice | /loops/loopsDrills.py | 2,267 | 4.40625 | 4 | '''
For this assignment you should read the task, then below the task do what it asks you to do
based on what the task tells you do first.
EXAMPLE TASK:
'''
#EX) Declare a variable set to 3. Make a while loop that prints the variable
# you just created and decrements the variable by one each time through
# the loop. Meanwhile, make the loop run until the variable you created
# equals 0.
i = 3;
while i > 0:
print(i)
i -= 1
'''
END OF EXAMPLE
'''
'''
START HERE
'''
'''While Loops'''
#1) Declare a variable set to 4. Make a while loop that prints the variable
# you just created and decrements the variable by one each time through
# the loop. Meanwhile, make the loop run until the variable you created
# equals 1.
a = 4
while(a == 1):
print(a)
a = a - 1
break
#2) Declare a variable set to 14. Make a while loop that prints the variable
# you just created and increments the variable by one each time through
# the loop. Meanwhile, make the loop run until the variable you created
# equals 20.
b = 14
while(b == 20):
print(b)
b = b + 1
break
#3) Declare a variable set to 55. Make a while loop that prints the variable
# you just created. Then make an if statement that makes the loop break when
# the variable is equal to 50.
c = 55
while(c):
print(c)
if (c == 55):
break
'''For Loops'''
#4) Create a list named sports. Put three sports into the list. Create
# a for loop that prints each sport in the list
sports = ["soccer", "tennis", "football"]
for x in sports:
print (x)
#5) Create a for loop that loops through each letter in a string of one of your
# favorite songs. Each iteration should print should a letter of the word.
song = "The lazy song by Bruno Mars"
for x in song:
print(x)
#6) Create a list named movies. Put five of your favorite movies into the list.
# However, make sure one of the movies is Avatar.
# Create a for loop that iterates over the list. In the loop print the movie
# being looped over, but create an if statement that breaks out of the
# loop if it is Avatar.
movies = ["Vacation", "Hunger Games", "Harry Potter", "Divergent","Avatar"]
for x in movies:
print(x)
if (x == "Avatar"):
break
| true |
02f62d011d633ccc94ee7214fd39eb8ec02dce6d | unknownboyy/GUVI | /guvi_2_1_2.py | 342 | 4.15625 | 4 | def my_function_to_find_factorial(number_to_find_factorial):
if number_to_find_factorial==0:
return 1
return number_to_find_factorial*my_function_to_find_factorial(number_to_find_factorial-1)
number_to_find_factorial_in_main_function=int(input())
print(my_function_to_find_factorial(number_to_find_factorial_in_main_function)) | false |
d85d25b652b3967a43a57c8b549964a2e127ecf8 | hzxsoytc/TOuyang | /Python Programming/Lab2/TOuyang_Lab2.py | 2,657 | 4.21875 | 4 | ##Author: Tiancheng Ouyang
##Lab: 2
##Date: January 29,2016
##Note: This script is used to define five functions and call each one.
def compare(x,y):
if x > y:
return 1
elif x == y:
return 0
else:
return -1
x = float(raw_input("Enter value for x:"))
y = float(raw_input("Enter value for y:"))
z = compare(x,y)
print z
#Question 1, compare x and y
import math
def hypotenuse(x,y):
z = math.sqrt(x**2 + y**2)
return z
x = float(raw_input("Enter the length of the first leg:"))
y = float(raw_input("Enter the length of the other leg:"))
z = hypotenuse(x,y)
print "The hypotenuse of the right triangle is", z
#Question 2, calculate hypotenuse
def grade(x):
if x > 100:
y = "S"
elif x >= 97 and x <= 100:
y = "A+"
elif x >= 92 and x < 97:
y = "A"
elif x >= 88 and x < 92:
y = "A-"
elif x >= 85 and x < 88:
y = "B+"
elif x >= 81 and x < 85:
y = "B"
else:
y = "0"
if y == "0":
return "You did not do very well in this course!"
elif y == "S":
return "You are kidding, right?"
else:
y = "Your grade is "+y
return y
x = int(raw_input("Enter your percentaged score of the python course:"))
y = grade(x)
print y
#Question 3, Print grade
def slope(x1,y1,x2,y2):
k = (y2 - y1)/(x2 - x1)
return k
def intercept(x1,y1,x2,y2):
b = y2- (slope(x1,y1,x2,y2) * x2)
return b
x1 = float(raw_input("Enter the value of x1:"))
y1 = float(raw_input("Enter the value of y1:"))
x2 = float(raw_input("Enter the value of x2:"))
y2 = float(raw_input("Enter the value of y2:"))
print "The equation of the line that goes through the two points you entered is", " y =", slope(x1,y1,x2,y2), "*x + ", intercept(x1,y1,x2,y2)
#Question 4, calculae equation
def inorout(x):
if x == "USA":
return 1
else:
return 2
def package(x,y):
if x == 1:
if y <= 10:
z = 4 * y
return z
elif y <= 20 and y > 10:
z = 6 * y
return z
else:
z = 0
return z
else:
if y <= 10:
z = 6 * y
return z
elif y <= 20 and y > 10:
z = 10 * y
return z
else:
z = 0
return z
x = raw_input("Enter the destination of your package, 'USA' or outside:")
y = x.upper()
z = int(raw_input("Enter the weight of your package in kilograms:"))
if z > 20:
print "Your package is too heavy."
else:
a = inorout(y)
b = package(a,z)
print "The cost of your delivery will be", b
#Question 5, calculate the cost
| true |
041d3858d74879c9d6417518d51dfbe6bfb93d03 | Bobbyisbobo/LPTHW | /ex21.py | 861 | 4.15625 | 4 | def add(a, b): #定义一个加法函数
print("Adding %d + %d" % (a, b))
return(a + b)
def substract(a, b): #定义一个减法函数
print("Substracting %d - %d" % (a, b))
return(a - b)
def multiply(a, b): #定义一个乘法函数
print("Multiplying %d * %d" % (a, b))
return(a * b)
def divide(a, b): #定义一个除法函数
print("Diciding %d / %d" % (a, b))
return(a / b)
print("Let's do some math with just functions!")
age = add(30, 5) #调用加法函数
height = substract(74, 4)
weight = multiply(90, 2)
iq = divide(300, 2)
print("Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq))
#A puzzle for the extra credit, type it in anyway.
print("Here is a puzzle.")
what = add(age, substract(height, multiply(weight, divide(iq, 2))))
print("That becomes: ", what, "Can you do it by hand?")
| true |
39d4c9c38aa6ee9fbf5b604bde81b78d473ee24e | Pinkal-CrossML/Python_session_1 | /debuger.py | 2,040 | 4.125 | 4 | # This file is all about "debugging with pdb module".
import pdb
pdb.set_trace()
name = input("Enter your name :")
age = input("Enter your age :") #use int here after debuging
next_age = age + 5
print(f'hello {name} you will be {next_age} in next five years!')
# use l and n to fine the error like this :
# terminal
"""
> /home/user/crossml/python-work/debuger.py(5)<module>()
-> name = input("Enter your name :")
(Pdb) l
1 # Todo: This file is all about "debugging with pdb module".
2 import pdb
3
4 pdb.set_trace()
5 -> name = input("Enter your name :")
6 age = input("Enter your age :")
7
8 next_age = age + 5
9 print(f'hello {name} you will be {next_age} in next five years!')
10
11
(Pdb) n
Enter your name :pinkj
> /home/user/crossml/python-work/debuger.py(6)<module>()
-> age = input("Enter your age :")
(Pdb) name
'pinkj'
(Pdb) l
1 # Todo: This file is all about "debugging with pdb module".
2 import pdb
3
4 pdb.set_trace()
5 name = input("Enter your name :")
6 -> age = input("Enter your age :")
7
8 next_age = age + 5
9 print(f'hello {name} you will be {next_age} in next five years!')
10
11
(Pdb) n
Enter your age :5
> /home/user/crossml/python-work/debuger.py(8)<module>()
-> next_age = age + 5
(Pdb) n
TypeError: can only concatenate str (not "int") to str
> /home/user/crossml/python-work/debuger.py(8)<module>()
-> next_age = age + 5
(Pdb) l
3
4 pdb.set_trace()
5 name = input("Enter your name :")
6 age = input("Enter your age :")
7
8 -> next_age = age + 5
9 print(f'hello {name} you will be {next_age} in next five years!')
10
11
12
13
(Pdb) n
--Return--
> /home/user/crossml/python-work/debuger.py(8)<module>()->None
-> next_age = age + 5
(Pdb)
--Call--
Traceback (most recent call last):
File "/home/user/crossml/python-work/debuger.py", line 8, in <module>
> /usr/lib/python3.9/codecs.py(309)__init__()
-> def __init__(self, errors='strict'):
(Pdb)
"""
| false |
8736c1a58c971f4cf11645f850423cae681f3395 | stopro/think-python-solutions | /012/exercise02.py | 527 | 4.28125 | 4 | #!/usr/bin/env python
import random
def sort_by_length(words):
t = []
for word in words:
t.append((len(word),random.random(), word))
t.sort(reverse = True)
res = []
for length, rand, word in t:
res.append(word)
return res
def main():
words = ['The', 'second', 'loop', 'traverses', 'the', 'list', 'of', 'tuples', 'and', 'builds', 'a', 'list', 'of', 'words', 'in', 'descending', 'order', 'of', 'length']
print sort_by_length(words)
if __name__ == "__main__":
main()
| false |
f7308b6f67a251b32ee760880bffa0d16d0af9ff | bturcott/udemy | /s3_l21_lists.py | 703 | 4.34375 | 4 | #Lists Lesson
#Section 3 Lecture 21
my_list = [1,2,3]
print my_list
sample = ['string',3,4.21,'second string']
print sample
#Can hold different object types
print len(sample)
#Same as .append
sample += ['Hello']
print sample
sample.append('world!')
print sample
sample.pop()
print sample
#same as .pop
sample = sample[:-1]
print sample
#Reverse list
print sample[::-1]
#same as above except modifies the list permenantly
sample.reverse()
print sample
sample.sort()
print sample
#No type or size constraint
#Nested lists
nested = [[2,3,4],[2,5,1]]
print nested[0][1]
nested_faq = [1,2,[1,2]]
print nested_faq[2][1]
#List comprehensions
first_col = [x**2 for x in range(0,10,2)]
print first_col | true |
06d23bbc666d43ba51660756d53187441452b910 | akmalmuhammed/Skools_Kool | /Chapter_11/Exercise_5.py | 1,428 | 4.125 | 4 | __author__ = 'matt'
"""
Read the documentation of the dictionary method setdefault and use it to write a more concise version of invert_dict. Solution: http://thinkpython.com/code/invert_dict.py.
"""
def invert_dict(d):
inverse = dict()
for key in d:
val = d[key]
if val not in inverse:
inverse[val] = [key] # Create a singleton, a one item list
else:
inverse[val].append(key) # We've seen this source value, append the additional key
return inverse
def invert_dict_setdefault(d):
inverse = dict()
for key in d:
val = d[key]
inverse.setdefault(val, []) # check fo existence of val; Create singleton if not in inverse
inverse[val].append(key) # Append source key as new inverse value
return inverse
def invert_dict_Book(d):
# From the book
"""Inverts a dictionary, returning a map from val to a list of keys.
If the mapping key->val appears in d, then in the new dictionary
val maps to a list that includes key.
d: dict
Returns: dict
"""
inverse = {}
for key, val in d.iteritems(): # iteritems negates needing to search for a value based on a key
inverse.setdefault(val, []).append(key) # setdefault acts as a conditional test in a way
return inverse
if __name__ == '__main__':
mattDict = {'a': 1, 'p': 1, 'r': 2, 't': 1, 'o': 1}
print invert_dict_setdefault(mattDict)
| true |
516d8b8c3e42195bc83a8593f377e6e7d0b66ac6 | akmalmuhammed/Skools_Kool | /Chapter_13/Exercise_2.py | 2,326 | 4.125 | 4 | __author__ = 'matt'
"""
Go to Project Gutenberg (gutenberg.org) and download your favorite out-of-copyright book in plain text format.
Modify your program from the previous exercise to read the book you downloaded, skip over the header information at the beginning of the file, and process the rest of the words as before.
Then modify the program to count the total number of words in the book, and the number of times each word is used.
Print the number of different words used in the book. Compare different books by different authors, written in different eras. Which author uses the most extensive vocabulary?
"""
import sys, string
from collections import OrderedDict
def processLine(sin, din):
"""For a given line, append to a dictionary individual words and counts"""
line = sin.strip()
words = line.split()
for word in words:
# http://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python
word = word.translate(string.maketrans("",""), string.punctuation + string.digits)
word = word.lower()
# Works, but could be made shorter
# if word in din:
# din[word] += 1
# else:
# din[word] = 1
# Use get method to check for key. If key is not present, use value of 0.
# Reassign new key value
din[word] = 1 + din.get(word, 0)
return din
def processFile(fin, processFunc):
"""Return an ordered dictionary of distinct words and occurance counts, along with total word count"""
d = dict()
try:
myFile = open(fin, 'r')
for line in myFile.readlines():
processFunc(line, d)
distinctWords = len(d) # Get a distinct word count.
# Create an OrderedDictionary. Use t[0] to sort by key, use t[1] to sort by value.
sortedDict = OrderedDict(sorted(d.items(), key=lambda t: t[1]))
return sortedDict, distinctWords
except:
e = sys.exc_info()
print e
finally:
myFile.close()
if __name__ == '__main__':
bookFile = '/Users/matt/Documents/PyCharm/Skools_Kool/Chapter_13/Books/moby_dick.txt'
infile = '/Users/matt/Documents/PyCharm/Skools_Kool/Chapter_13/testtext.txt'
words, distinctWordCount = processFile(bookFile, processLine)
print words
print distinctWordCount
| true |
87197ee556f670a634aaf3837c7d72a9cfe48ac3 | akmalmuhammed/Skools_Kool | /Chapter_12/Exercise_2.py | 1,311 | 4.34375 | 4 | __author__ = 'matt'
"""
In this example, ties are broken by comparing words, so words with the same length appear in reverse alphabetical order. For other applications you might want to break ties at random. Modify this example so that words with the same length appear in random order. Hint: see the random function in the random module. Solution: http://thinkpython.com/code/unstable_sort.py.
"""
from random import random
def sort_by_length(words):
t = []
for word in words:
# Append with a tuple containg elements for length and the word
t.append((len(word), random(), word))
# t.append((random(),len(word), word))
# For a tuple, sort occurs based on elements from left to right
t.sort(reverse=True)
# Identify tuples with the same length
# Append a third random value to all dup length values
# Append value of 0 to all non-dups
## Oh wait don't need to do all this crap ^^^^^^^^^^^^
## because i can just salt with a random number,
## and all elements with a no matching lengths will be
## sorted by length first
res = []
for length, dupsort, word in t:
res.append(word)
return res
if __name__ == '__main__':
sortSequence = ('cat','rat','matt','fence','hair','chair')
print sort_by_length(sortSequence)
| true |
fbd6f0215ae8c6b88fdd4391dafd1377b857bdff | akash05xx/pythonProjectdemo | /lists.py | 1,172 | 4.15625 | 4 | #Creating a list
my_list =[]
print(my_list)
my_list2 =[]
print(my_list2)
#Adding elements into lists
my_list =['akash','python','AI','ML']
print(my_list)
my_list2 =list([8451092817,'1','2'])
print(my_list2)
#List indexing
my_list =['p','y','t','h','o','n']
print(my_list[0])
print(my_list[1])
print(my_list[2])
print(my_list[3])
print(my_list[4])
print(my_list[5])
#List Slicing
my_list =['p','y','t','h','o','n']
print(my_list[0:]) #['p', 'y', 't', 'h', 'o', 'n']
print(my_list[0:1]) #['p']
print(my_list[0:2]) #['p', 'y']
print(my_list[:-1]) #['p', 'y', 't', 'h', 'o']
print(my_list[::5]) #['p', 'n']
print(my_list[0:]) #['p', 'y', 't', 'h', 'o', 'n']
print(my_list[:-4]) #['p', 'y']
#Mistaken values
odd =[2,4,6,8,10]
odd[0]= 1
print(odd) #[1, 4, 6, 8, 10]
odd[1:4] = [3,5,7]
print(odd) #[1, 3, 5, 7, 10]
#Appending and extending list in python
odd =[1,3,5,7]
odd.append(9)
print(odd) #[1, 3, 5, 7, 9]
odd.extend([9,11,13,])
print(odd) #[1, 3, 5, 7, 9, 9, 11, 13]
#Concatenating & repeating lists
odd =[1,3,5,7]
print(odd+[9,11,13]) #[1, 3, 5, 7, 9, 11, 13]
print(["re"]*6) #['re', 're', 're', 're', 're', 're']
| false |
1e48b437f2b0cf696e98ff340f2d91b72df39772 | BensonMuriithi/pythonprojects | /Silly Count/sillycount/__init__.py | 2,766 | 4.34375 | 4 | """
Base convertion utility.
Bases supported are those >= 2 and <= 36
Functions:
strbase -> strbase(number [,base, frombase]) -> string
Converts a number from one base representation to another
returning the result as a string.
The range of bases supported is 2-36 inclusive.
A number can be negative or positive
getvalue -> getvalue(number [,base]) -> int
Gets the value in base 10 of a number in the specified base.
A number can be positive or negative.
Exceptions raised by both functions are ValueError.
"""
from string import uppercase
from itertools import count
__dig_to_chr = lambda num: str(num) if num < 10 else uppercase[num - 10]
def strbase(number, base = 2, frombase = 10):
"""strbase -> strbase(number [,base, frombase]) -> string
Converts a number from one base representation to another
returning the result as a string.
The range of bases supported is 2-36 inclusive.
A number can be negative or positive
Specify the base to convert from as the third argument or
woth the keyword frombase if it isn't 10.
"""
#credit for this function goes to "random guy" on stack overflow
#http://stackoverflow.com/questions/2063425/python-elegant-inverse-function-of-intstring-base
#http://stackoverflow.com/users/196185/random-guy
if not 2 <= base <= 36:
raise ValueError("Base to convert to must be >= 2 and <= 36")
if frombase != 10:
number = int(number, frombase)
if number < 0:
return "-" + strbase(-number, base)
d, m = divmod(number, base)
if d:
return strbase(d, base) + __dig_to_chr(m)
return __dig_to_chr(m)
def getvalue(number, base=10):
""" int
Gets the value in base 10 of a number in the specified base
Any number positive or negative number unless it's a float
The function is on average 10 times slower than Python's int function.
"""
if not (isinstance(base, int) or isinstance(base, long)):
raise ValueError("Invalid value : {} entered as base of number.".format(base))
if not 2 <= base <= 36:
raise ValueError("Bases to get values from must be >=2 and <= 36.")
number = str(number)
if "." in number:
raise ValueError("Cannot operate on floating point numbers.")
if number.startswith("-"):
return -getvalue(number, base)
def get_ordinance_values():
zero_ordinance = ord("0")
a_ordinance = ord("a")
for i in reversed(number.lower()):
ordinance = ord(i)
if ordinance - zero_ordinance < 10:
yield ordinance - zero_ordinance
else:
yield 10 + (ordinance - a_ordinance)
result = 0
for v, p in itertools.izip(get_ordinance_values(), count()):
if v < base:
result += (v * pow(base, p))
else:
raise ValueError("Number : {number} is too large for base {b}".format(number = number, b = base))
return result
| true |
505e61781d6764cca7e6def98b2847c3255c037f | kaka0525/Leet-code-practice | /compressString.py | 767 | 4.40625 | 4 | def compress_string(s):
"""
Implement a method to perform basic string compression using the counts of
repeated characters. For example, the string a a b c c c c c a a a would
become a2blc5a3. If the "compressed" string would not become smaller than
the original string, your method should return the original string.
"""
result = []
count = 0
last_char = ""
for char in s:
if char == last_char:
count += 1
else:
if last_char != "":
result.append(last_char + str(count))
last_char = char
count = 1
result.append(last_char + str(count))
result = ''.join(result)
if len(result) < len(s):
return result
else:
return s
| true |
87e5a615157db59d1eac4967c321829c878d00a5 | skp96/DS-Algos | /AE/Recursion/product_sum.py | 1,273 | 4.4375 | 4 | """
- input: is a 'special' array (heavily nested array)
- output: return the product sum
- notes:
- special array is a non-empty array that contains either integers or other 'special' arrays
- product sum of a special array is the sum of its elements, where 'special' arrays inside are summed themselves and then multipled by their level of depth
- logic:
- need two variables the sum and the depth; the depth will be passed on from function call to function call
- we iterate through the 'special' array
- check if it is a type int
- add to the sum
- else the element we are currently on is a 'special' array
- add to the sum the return value of recursively calling the function passing in the element and the current depth + 1
- return sum
"""
def product_sum(array):
sum = 0
depth = 1
sum += product_sum_helper(array, depth)
return sum
def product_sum_helper(array, depth):
sum = 0
for ele in array:
if type(ele) is int:
sum += ele
else:
sum += product_sum_helper(ele, depth + 1)
return depth * sum
# Time Complexity: O(n), where n is the number of nodes in the element
# Space Complexity: O(d), where d is the greatest depth of the 'special' arrays in the array
| true |
23b77546088077273096619ed753bab382473b5b | skp96/DS-Algos | /AE/Binary Tree/node_depths.py | 2,322 | 4.125 | 4 | """
- input:
- Binary Tree
- output:
- sum of the nodes' depths
- notes:
- a node's depth is the distance between the node in the Binary Tree and the tree's root node
- logic:
- recursive solution:
- base case, if node is None return 0
- starting at the root node, our depth would be 0
- we then want to add to the depth of the current node (e.g. root node), the result from recursively calling the function on the children node (node.left and node.right)
- NOTE that with each recurisive call, we are travelling down a level in the tree, so increment depth by 1
- iterative solution:
- BFS approach so use a queue --> why? when looking at the depth of a child node, we are looking a level deeper from where we are
- init a queue that will hold an object {node: root, depth: 0}
- init a variable to keep track of sum of depth
- while the length of the stack is greater than 0
- pop off the object from the stack and extrapolate node and depth keys
- if the node is None, continue with the iteration
- add depth to sum_of_depth_variable
- append {node: node.left, depth: depther + 1} and {node: node.rigth, depth: depther + 1}
- return sum_of_depth
"""
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def node_depths(root):
return node_depths_recur(root, depth=0)
def node_depths_recur(root, depth):
if root is None:
return 0
return depth + node_depths_recur(root.left, depth+1) + node_depths_recur(root.right, depth+1)
# Time Complexity: O(n), where n is the number of nodes in the Binary Tree
# Space Complexity: O(h), where h is the height of the Binary Tree
def node_depths2.0(root):
queue = [{"node": root, "depth": 0}]
sum_of_depths = 0
while len(queue) > 0:
node_info = queue.pop()
node, depth = node_info["node"], node_info["depth"]
if node is None:
continue
sum_of_depths += depth
queue.append({"node": node.left, "depth": depth + 1})
queue.append({"node": node.right, "depth": depth + 1})
return sum_of_depths
# Time Complexity: O(n), where n is the number of nodes in the Binary Tree
# Space Complexity: O(h), where h is the height of the Binary Tree
| true |
8dc7199aff34baa5fbfbc579743f4227e681fab7 | skp96/DS-Algos | /Grokking/Window Sliding Problems/length_of_longest_substring.py | 1,250 | 4.34375 | 4 | """
- Problem: Given a string with lowercase letters only, if you are allowed to replace no more than ‘k’ letters with any letter, find the length of the longest substring having the same letters after replacement.
- Examples:
- Input: String="aabccbb", k=2
- Output: 5
- Explanation: Replace the two 'c' with 'b' to have a longest repeating substring "bbbbb".
- Input: String="abbcb", k=1
- Output: 4
- Explanation: Replace the 'c' with 'b' to have a longest repeating substring "bbbb".
- Input: String="abccde", k=1
- Output: 3
- Explanation: Replace the 'b' or 'd' with 'c' to have the longest repeating substring "ccc".
"""
from collections import defaultdict
def length_of_longest_substring(str, k):
max_length, max_repeat_char_count = 0
freq_counter = defaultdict(lambda: 0)
window_start = 0
for window_end in range(len(str)):
char = str[window_end]
freq_counter[char] += 1
max_repeat_char_count = max(max_repeat_char_count, freq_counter[char])
if (window_end - window_start + 1) - max_repeat_char_count > k:
left_char = str[window_start]
freq_counter[left_char] -= 1
window_start += 1
max_length = max(max_length, window_end - window_start + 1)
return max_length | true |
70e37a6ab4edcf4c3967fc0f27658874aff4bc2e | guyShavit/Pyton_lab | /fibonacci.py | 1,092 | 4.25 | 4 | # the program checks if a list is in fibonacci order or not
while True:
fibo = []
fibo.append(int(input("enter a number to the list: ")))
fibo.append(int(input("enter a number to the list: ")))
fibo.append(int(input("enter a number to the list: ")))
addMore = input("do you want to add more numbers? y/n ")
while True:
if addMore == "y":
fibo.append(int(input("enter a number to the list: ")))
addMore = input("do you want to add more numbers? y/n ")
if addMore == "y":
continue
elif addMore == "n":
break
if addMore == "n":
break
if addMore == "n":
print("thank you for the list!")
break
print("your list is " + str(fibo) + "\n")
isFibo = True
for i in range(2,len(fibo)):
if fibo[i] == fibo[i-1] + fibo[i-2]:
continue
else:
isFibo = False
break
if isFibo:
print("the list is in Fibonacci order!\n")
else:
print("The list is not in Fibonacci order\n")
print("Thank you and Bye Bye!")
| true |
c1aec940273d5594a75d524211e7115939a15f72 | JulianLiao5/cpp_basics | /python/calc_standard_dev.py | 1,454 | 4.15625 | 4 | #!/usr/bin/env python
# coding=utf-8
from math import sqrt
import numpy as np
def standard_deviation(lst, population=True):
"""Calculates the standard deviation for a list of numbers."""
num_items = len(lst)
mean = sum(lst) / num_items
differences = [x - mean for x in lst]
sq_differences = [d ** 2 for d in differences]
ssd = sum(sq_differences)
# Note: it would be better to return a value and then print it outside
# the function, but this is just a quick way to print out the values along
# the way.
if population is True:
print('This is POPULATION standard deviation.')
variance = ssd / num_items
else:
print('This is SAMPLE standard deviation.')
variance = ssd / (num_items - 1)
sd = sqrt(variance)
# You could `return sd` here.
print('The mean of {} is {}.'.format(lst, mean))
print('The differences are {}.'.format(differences))
print('The sum of squared differences is {}.'.format(ssd))
print('The variance is {}.'.format(variance))
print('The standard deviation is {}.'.format(sd))
print('--------------------------')
s = [98, 127, 133, 147, 170, 197, 201, 211, 255]
standard_deviation(s)
standard_deviation(s, population=False)
mean_s = np.mean(s)
std_dev_s = np.std(s)
sample_std_s = np.std(s, ddof = 1)
print("mean_s: " + str(mean_s) + ", population std_dev_s: " + str(std_dev_s) + ", sample std_dev_s: " + str(sample_std_s))
| true |
4d5a8c965e9cae0e9942bcb8f35992db867a850f | ioanan11/PycharmProjects | /main.py | 910 | 4.1875 | 4 |
age = int(input("How old are you?"))
film_rating = input("What film rating do you want to watch?")
if age >= 18:
print("You can watch any movie, please proceed")
elif (age >= 15 and age < 18) and film_rating == 18 :
print("You cannot watch this film, please choose from U, PG, 12A or 15")
elif (12 <= age < 15) and (film_rating == 18 or film_rating == 15) :
print("You cannot watch this film, please choose from U, PG or 12A")
elif age >= 8 and age < 12 and film_rating == 18 or film_rating == 15 or film_rating == "12A" :
print("You cannot watch this film, please choose from U or PG")
elif age < 8 and film_rating == 18 or film_rating == 15 or film_rating == "12A" or film_rating == "PG" :
print("You cannot watch this film, please choose U rated film")
else: print("Please enter a valid input")
def additi12
on (a,b):
return (a + b)
print(addition(3,5))
print(addition(165,194))
| true |
291be4cbf770a8da7a5ef49e793284cd9c657f35 | SensehacK/playgrounds | /python/PF/Intro/Day6/Assignment40.py | 446 | 4.125 | 4 | #PF-Assgn-40
def is_palindrome(word):
#Remove pass and write your logic here
new_word = word.upper()
if len(word) <= 1:
return True
return new_word[0] == new_word[-1] and is_palindrome(new_word[1:-1])
#Provide different values for word and test your program
result=is_palindrome("MadAM")
if(result):
print("The given word is a Palindrome")
else:
print("The given word is not a Palindrome") | true |
6e95c6421d425e147a229ad93274fdc8da9cd73e | MirekPz/Altkom | /a/petle_listy/PE3.py | 382 | 4.125 | 4 | """
PE3 Stwórz listę, która będzie zawierała liczby parzyste
podzielne przez 3 i mniejsze niż 100 (liczby podzielne przez 3 mają resztę z dzielenia równą 0)
"""
# print("a\bnormal")
list1 = []
for i in range(100):
if i % 6 == 0:
list1.append(i)
print(i, end=' ')
print()
print(list1)
new_list = [x for x in range(100) if x%6 == 0]
print(new_list)
| false |
37b4e2bda6685e02a6820b97e5707ad9afa100ca | dayes/curso_Python | /SOLUCIONES/SOLUCIONES/intermedio I/funcional/lambda_listas.py | 965 | 4.15625 | 4 | # Ejemplos de funciones lambda para crear los operadores:
# car devuelve la cabeza de la lista, el primer elemento
# cdr devuelve el resto de la lista, todos menos el primero
car = lambda L: L[0]
cdr = lambda L: L[1:]
empty = lambda L: len(L)==0
def invertir(L):
if not empty(L):
invertir(cdr(L))
print (car(L))
def desanidar(L):
if empty(L):
return []
elif type(car(L))==list:
return desanidar(car(L)) + desanidar(cdr(L))
else:
return [car(L)] + desanidar(cdr(L))
# prueba de los operadores:
L = [1,2,3,4,5]
print ("car L: ")
print (car(L))
print ("cdr L: ")
print (cdr(L))
L=[]
print ("empty L: ")
print (empty(L))
print ("Invertir: ")
L=[1,2,3,4,5]
invertir(L)
print ("\nDesanidar: ")
L=[1,2,[3,4,[5,6],8],9,10]
print (L)
print (desanidar(L))
| false |
3d150ff0ebe82787574019864fe2a3494124504c | metodiev/Python-Platform | /PythonIntro/OPPInPython.py | 1,051 | 4.3125 | 4 | class Parent: # define parent class
def myMethod(self):
print
'Calling parent method'
class Child(Parent): # define child class
def myMethod(self):
print
'Calling child method'
c = Child() # instance of child
c.myMethod() # child calls overridden method
class Animal:
# initilize constructor and attributes
def __init__(self, name, weight):
self.name = name
self.weight = weight
def eat(self):
return self.name + "is eating"
def sleep(self):
return self.name + "is going to sleep!"
def wakeUp(self):
return self.name + "is waking up!"
class Gorilla(Animal):
def __init__(self, name, weight):
self.name = name
self.weight = weight
def climbTrees(self):
return self.name + " is climbing trees!"
def poundChest(self):
return self.name + "is pounding its chest!"
gorila = Gorilla("Kiro gorilata", 151)
animal = Animal("Animal", 123)
print(gorila.eat())
print(animal.eat())
print(gorila.climbTrees()) | true |
266b314951d6596d449739002e7c39c7b4c4208b | sayaka71/Python | /Practice/pra_6.py | 1,081 | 4.375 | 4 | # stack スタックの練習
# 独学プログラマー
# *argsの練習にもなった。解凍演算子の使い方次第でリストをマージできたりするけど,推奨されていない。
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, *args):
# Iterating over the Python args tuple
for item in args:
self.items.append(item)
return self.items
def pop(self):
# 1番上をとってくる。もとのやつから削除。
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.items)
st = Stack()
print(st.is_empty())
st.push(1,2,3)
# print(st.pop())
# >>> 3
# print(st.items)
# >>> [1,2]
# 数字リストを逆順にする。
gyaku = []
for i in range(st.size()):
gyaku.append(st.pop())
print(gyaku)
# 文字列を逆順に
for c in "gyaku":
st.push(c)
print(st.items)
reverse = ""
while st.size():
reverse += st.pop()
print(reverse)
| false |
f147190e4a97eebb12daf55d177728c4d357e4e3 | navneetspartaglobal/Data21Notes | /list_tuple_dict.py | 1,196 | 4.28125 | 4 | # List in Python
# shopping_list = ["eggs","milk","bread"]
#
# print(shopping_list)
#
# print(type(shopping_list))
#
# #print(shopping_list[0:3])
#
# shopping_list[0] = "Chocolate"
#
# print(shopping_list)
########## Tuples in Python ################
# # Useful to store unchangeable data
#
# shopping_tuple = ("bread", "milk", "eggs")
#
# print(shopping_tuple)
#
# print(type(shopping_tuple))
#
# shopping_tuple[0]= "Chocolate" # will throw error because tuple is immutable
######### Dictionary in python#########################
#
# student_1 = {
#
# "name" : "Navneet",
# "course" : "Data21",
# "list" : ["Value1", "Value2", "Value3"]
# }
# print(student_1)
#
# print(student_1["name"])
#
# print(student_1["list"][1])
#
# student_1["name"] = "Bob"
#
# print(student_1.values())
# print(student_1.keys())
#
# student_1["list"].remove("Value2")
# print(student_1)
#################Set in python###################
# use_case -----
# car_parts = { "Wheels", "doors", "windows"}
#
# print(type(car_parts))
#
#
# car_parts.add("headlights")
#
# print(car_parts)
#
# print(car_parts[0]) ### It will give error because set does not follow indexing ###############
| false |
1f090cb286b6ff51bcb7a6d363172ffd446c17a0 | KevoKillmonger/Petty-Mayonaise | /pet.py | 1,088 | 4.5 | 4 | #Pet Class
class Pet:
#creates attributes for name,animal type,age, and get_ for all same attributes
def __init__(self, animal_type, age, name):
self.__name = name
self.__animal_type = animal_type
self.__age = age
def set_name(self, name):
self.__name = name
def set_animal_type(self, animal_type):
self.__animal_type = animal_type
def set_age(self, age):
self.__age = age
def get_name(self):
return self.__name
def get_animal_type(self):
return self.__animal_type
def get_age(self):
return self.__age
#Write a program that creates an object of the class
#and prompts the user to enter name, type and age for
#for his or her pet.
#The data should be stored as the object's attributes.
#Use the objects accessor methods to retrieve the pets name,
#type and age, displaying this data onscreen.
| true |
8ab4033d359334e4280f25aad459070a4a1f5adb | artrous/Introduction-to-Python-Programming | /Trinomial/trinomial_roots.py | 793 | 4.40625 | 4 | # Finding Trinomial Roots
from math import sqrt
a=float(input('Give a: '))
b=float(input('Give b: '))
c=float(input('Give c: '))
if a==0:
if b!=0:
x=-c/b
print('There is a root: ', x)
elif c==0:
print('Every real number is a solution!')
else:
print('No real number is a solution!')
else:
D=b**2-4*a*c
if D>0:
x1=(-b+sqrt(D))/(2*a)
x2=(-b-sqrt(D))/(2*a)
print('The trinomial has two real roots, the: ', x1, 'and', x2)
elif D==0:
x=-b/(2*a)
print('The trinomial has a real root, the ', x)
else:
print('There are no real roots!')
c1=-b/(2*a)+(sqrt(-D))*1j
c2=-b/(2*a)-(sqrt(-D))*1j
print('The trinomial has two complex roots, the: ', c1, 'and', c2)
| false |
653c81ec5773148370a42add44999b8209378829 | kyordhel/comparesort | /comparesort/sorting/insertionsort.py | 885 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ## ###############################################################
# insertionsort.py
#
# Author: Mauricio Matamoros
# License: MIT
#
# ## ###############################################################
from comparesort.array import Array
def insertionsort(array):
"""Sorts the provided Array object using the Insertion Sort algorithm"""
if isinstance(array, list):
array = Array(array) # Converts the list to an Array
if not isinstance(array, Array):
raise TypeError("Expected a list or Array object")
# Insertion Sort Algorithm
for i in range(1, len(array)):
greatest = array[i]
# Move forward those elements in the subarray A[0...i-1]
# which are greater than 'greatest'
j = i-1
while j >= 0 and greatest < array[j]:
array[j+1] = array[j]
j-= 1
# Insert greatest in place
array[j+1] = greatest
#end for
#end def
| true |
aeb67784e6ec670be028de9f59cb6d23d9ac81c3 | takashk/hello-world | /list_exercies.py | 1,213 | 4.3125 | 4 | # my_list = [1, 2, "kitten", 4, "five"]
# # print my_list[2]
# # print my_list[3]
# # print my_list[1]
# # print my_list[-1]
# # print my_list[len(my_list)-1]
# # print my_list[4]
# # print len(my_list)
# print my_list[0]
# print my_list[1:3]
# print my_list[1:6]
# print my_list[1:10]
# print my_list[-1]
# print my_list[-1:-3]
# print my_list[-3:-1]
shopping_list = ["flour", "water", "salt"]
input = raw_input("Would you like to type '1' to add, type '2' remove, or '3' view your list? ")
def add_list():
add_list = str.lower(raw_input("What would you like to add to your list? "))
if add_list in shopping_list:
print "You already have that on your list."
else:
shopping_list.append(add_list)
print shopping_list.sort()
def order_list():
print shopping_list.sort()
def remove_item():
remove_item = str.lower(raw_input("What would you like to remove from your list?"))
if remove_item in shopping_list == False:
print "The item you entered is not there."
else:
shopping_list.remove(remove_item)
print shopping_list.sort()
input == "1"
print add_list
input == "2"
print remove_item
input == "3"
print order_list
| true |
d23e621076bf40b5a021a59180b4fc693a2bdcdb | Harshit-tech9/Random-Colour-Choosing-Project- | /Random colour.py | 664 | 4.1875 | 4 | import random
colour = ["Red", "Yellow", "Pink", "Grey", "Purple", "Orange", "Maroon", "White"]
while True:
color = colour[random.randint(0, len(colour)-1)]
guess = input("Enter the choice of your colour: ")
while True:
if (guess == color):
print("The Choice of your colour is ", color)
break
else:
guess = input("Your Guess is Incorrect, Please try again")
print("Your Guess is Correct: ", color)
try_again = input("Do you want to try again? Type 'no' to quit")
if try_again == 'no' :
break
print("Thanks for Playing with us. See you again :)")
| true |
615640c883b4375c2c3c1f78ef72f818aa18b93f | jonkoerner/Python-Fundamental | /OOP/Bike1.py | 828 | 4.125 | 4 | class Bike(object):
def __init__(self, price, max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
def displayInfo(self):
print self.price
print self.max_speed
print self.miles
def ride(self):
print 'Riding'
self.miles +=10
return self
def reverse(self):
print 'Reversing'
if self.miles >0:
self.miles -=6
return self
bike1 = Bike(200,30)
# instance1
bike1.ride().ride().ride()
bike1.reverse()
bike1.displayInfo()
# # instancec2
# bike1.ride()
# bike1.ride()
# bike1.reverse()
# bike1.reverse()
# bike1.displayInfo()
# # instance3
# bike1.reverse()
# bike1.reverse()
# bike1.reverse()
# def displayinfo():
# print self.price
| false |
470cbe172e33a94c307706928d64e214b9e5ead4 | jonkoerner/Python-Fundamental | /Basics/Compare.py | 601 | 4.15625 | 4 | list_one = [1, 2, 5, 6, 2]
list_two = [1, 2, 5, 6, 2]
list_one1 = [1, 2, 5, 6, 5]
list_two1 = [1, 2, 5, 6, 5, 3]
list_one2 = [1, 2, 5, 6, 5, 16]
list_two2 = [1, 2, 5, 6, 5]
list_one3 = ['celery', 'carrots', 'bread', 'milk']
list_two3 = ['celery', 'carrots', 'bread', 'cream']
# def Compare_Lists(arr, arr2):
arr = [1,2,5,6,2]
arr2 = [1,2,5,6,2]
def Compare_Lists(arr, arr2):
if arr == arr2:
print "The lists are the same."
else:
print "The lists are not the same."
Compare_Lists(list_one, list_two)
Compare_Lists(list_one1, list_two1)
Compare_Lists(list_one2, list_two2)
| false |
1633def2649bb06732441ce573eb61e1d0ad594a | divya369/Python-Programming-Practise | /Python Data Structures/dictionary.py | 1,526 | 4.15625 | 4 | # Dictionary are best for counting stuff
# A bag of values, each with its own label
# Dictionary allows you to do fast database like operation
# List index their entries based on the position in the List
# Dictionary are like bags, they don't have order
# you store every values with a lookup tage
color = dict() # {} will also do
color['blue'] = 12
color['india'] = "win"
color['red'] = 36
color['red'] = 36
print(color)
print('\n')
cricket = {'India':358, 'Australia':123}
for team in cricket:
print(f"Team names : {team} with score {cricket[team]}")
# humans are good when they can see the data, which computers are good when data is not seen
if 'India' in cricket:
print('True')
# get() method. Both piece of code does the same thing
# 1
counts = dict()
names = ['divya', 'bariya', 'sumit']
for name in names:
if name not in counts:
counts[name] = 1
else:
counts[name] = counts[name] + 1
print(counts)
# 2
counts = dict()
names = ['divya', 'bariya', 'sumit', 'bariya', 'sumit']
for name in names:
counts[name] = counts.get(name, 0) + 1
print(counts)
# keys in Dictionary
for key in counts:
print(f"{key} : {counts[key]}")
# converting dict to list only copies the 'keys' not the 'values'
temp = list(counts)
print(temp)
# prints only keys, values and items seperately
print(counts.keys())
print(counts.values())
print(counts.items())
# accessing keys and values in 'for' look
for key, value in counts.items(): # sequence should not be altered
print(key, value)
| true |
b99f8370fccb56835fe5cb64130af15df051a697 | Sanmarri/HomeWorks | /Homework_1_lesson/GB05.py | 1,617 | 4.3125 | 4 | # Запросите у пользователя значения выручки и издержек фирмы.
# Определите, с каким финансовым результатом работает фирма
# (прибыль — выручка больше издержек, или убыток — издержки больше выручки).
# Выведите соответствующее сообщение.
# Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке).
# Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника.
plus = int(input('Сколько ты заработал?'))
minus = int(input('А сколько потратил?'))
if plus > minus:
print('Все в порядке, дом на Канарах уже близко')
print(f'Ты заработал в {plus//minus} раз больше, чем вложил. Но это не предел!')
shtat = int(input('Сколько, говоришь, у тебя сотрудников?'))
print(f'Вот каждый из них принес {plus // shtat} бубликов. Сам реши, кого уволить')
elif minus > plus:
print('Кажется, ты что-то делаешь не так. Попробуй начать заново')
else:
print('Никакого результата. Оно тебе надо?')
| false |
e656b54af35dfe51c5f3093837a6b17903cd9997 | niteshkrsingh51/python_basics | /Lists_programs/duplicates_elements.py | 378 | 4.125 | 4 | #function to remove duplicates from a list
def duplicates_elements(num_list):
dup_lists = set()
unique_lists = []
for x in num_list:
if x not in dup_lists:
unique_lists.append(x)
dup_lists.add(x)
return dup_lists
num_lists = [1,2,6,4,5,6,5]
dupli_check = duplicates_elements(num_lists)
#diplaying the result
print(dupli_check)
| true |
585c3fa630bae0e368dcf232176039811ab25761 | niteshkrsingh51/python_basics | /loop_programs/count_digits.py | 302 | 4.21875 | 4 | #Given a number count the total number of digits in a number
#function to give the no. of digits in the given input
def count_digit(num):
count = 0
while num != 0:
num //= 10
count += 1
return count
#displaying the result
num = 2453
result = count_digit(num)
print(result) | true |
2e7030cbc3fa04370ebc5b07928025abe1a5dbbb | niteshkrsingh51/python_basics | /misc_programs/armstrong_number.py | 520 | 4.28125 | 4 | #program to check whether the number is armstring number or not
#function for the logic
def checkArmStrong(num):
sum = 0
num_list = list(num)
for items in num_list:
items_cube = int(items) * int(items) * int(items)
sum = sum + items_cube
if sum == int(num):
print('{} is a Armstring Number'.format(num))
else:
print('{} is not a Armstrong number'.format(num))
#displaying the result by calling the above function
num = input('Enter the number: ')
checkArmStrong(num) | true |
6d5e0f0338d67a3f5bce56dc7c5336ae14466755 | niteshkrsingh51/python_basics | /data_structure_programs/program4.py | 501 | 4.28125 | 4 | #Iterate a given list and count the occurrence of each element and
#create a dictionary to show the count of each element
def listTodictionary(num_list):
my_list = []
for items in num_list:
elementCount = num_list.count(items)
my_list_case = (items, elementCount)
my_list.append(my_list_case)
dictt = dict(my_list)
return dictt
num_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
displayResult = listTodictionary(num_list)
print(displayResult)
| true |
e967b69161ffa288d881db13f8cef651aee2dde5 | niteshkrsingh51/python_basics | /String_programs/program3.py | 402 | 4.21875 | 4 | #Arrange string characters such that lowercase letters should come first
#function for logic
def char_arrange(name):
lower = []
upper = []
for char in name:
if char.islower():
lower.append(char)
else:
upper.append(char)
sorted_name = ''.join(lower+upper)
return sorted_name
name = 'ANSHUhiii'
result = char_arrange(name)
print(result)
| true |
9bc412b4791b001234141b5ad332fe989de0ee10 | funnyuser97/HT_1 | /task4.py | 232 | 4.1875 | 4 | # 4. Write a script to concatenate N strings.
number=int(input('Input number of string: '))
list_string=[]
for i in range(number):
list_string.append(input())
all_string = ' '.join(list_string)
print('All strings: ' ,all_string) | true |
c5098ea5b5db37c0d95c943cb1f9d1bed35b5fa6 | VertikaJain/python-basics | /strings.py | 894 | 4.4375 | 4 | # Strings in python are surrounded by either single or double quotation marks. Let's look at string formatting and some string methods
name = "abc"
age = 37
# Concatination
# print("my name is "+name + " of " + age + " years ") #TypeError: can only concatenate str (not "int") to str
# print("my name is "+name + " of " + str(age) + " years ")
# String Formatting
# 1. arguements by position
# print("hey, my name is {name} of {age} years".format(name=name, age=age))
# 2. F-strings
# print(f"hey there, my name is {name} of {age} years.")
# String Methods
s = "fake world"
print(s.capitalize())
print(s.upper())
print(s.lower())
print(s.swapcase())
print(len(s))
print(s.replace("world", "geek"))
print(s.count('k'))
print(s.startswith("fa"))
print(s.startswith("qwe"))
print(s.endswith("qwe"))
print(s.split())
print(s.find('r'))
print(s.isalnum())
print(s.isalpha())
print(s.isnumeric())
| true |
bf36cc412c903cdd1a46109d436c6afdf187aa2c | 5l1v3r1/kinematics_py_calculator | /Calc.py | 787 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def main():
print("V")
print("D")
print("T")
choice = input ("Please make a choice: ")
if choice == "V":
print("V = D / T")
D = float( input ("D = ") )
T = float( input ("T = ") )
print("V = "),
print(D/T)
elif choice == "D":
print("D = V * T")
V = float( input ("V = ") )
T = float( input ("T = ") )
print("D = "),
print(V*T)
elif choice == "T":
print("T = D / V")
D = float( input ("D = ") )
V = float( input ("V = ") )
print("T = "),
print(D/V)
print("hours"),
print( (D/V) * 60 )
print("minutes")
else:
print("I don't understand your choice.")
main()
| false |
317a0154dc560ae0b99ba6afdf63bf2e3f8ea6ce | admacro/sicp | /python/1.2/1.9.py | 1,598 | 4.4375 | 4 | '''
E 1.9
Iterative and recursive
'''
# Recursive process
def factorial_recur(n):
return 1 if (n == 1) else n * factorial_recur(n - 1)
# Iterative process
def factorial_iter(n):
def fact_iter(counter, product):
return product if (counter > n) else fact_iter(counter + 1, counter * product)
return fact_iter(1, 1)
print(factorial_recur(5))
print(factorial_iter(6))
'''
substitution model illustration
I used add and plus (instead of +) to distinguish the two adding procedures
and the default + operator
'''
def add(a, b):
print("add(" + str(a) + ", " + str(b) + ")")
return b if (a == 0) else inc(add(dec(a), b))
def plus(a, b):
print("plus(" + str(a) + ", " + str(b) + ")")
return b if (a == 0) else plus(dec(a), inc(b))
def inc(x): return x + 1
def dec(x): return x - 1
add(4, 5)
plus(4, 5)
'''
process generated by add(4, 5)
As you can see from the steps below, inc operations are deffered,
this is recursive process. And it's linear.
add(4, 5)
inc(add(dec(4), 5))
inc(add(3, 5))
inc(inc(add(dec(3), 5)))
inc(inc(add(2, 5)))
inc(inc(inc(add(dec(2), 5))))
inc(inc(inc(add(1, 5))))
inc(inc(inc(inc(add(dec(1), 5)))))
inc(inc(inc(inc(add(0, 5)))))
inc(inc(inc(inc(5))))
inc(inc(inc(6)))
inc(inc(7))
inc(8)
9
'''
'''
process generated by plus(4, 5)
As you can see from the steps below, each state of the process can be summarized
by the state variables, this is iterative process. And it's linear.
plus(4, 5)
plus(dec(4), inc(5))
plus(3, 6)
plus(dec(3), inc(6))
plus(2, 7)
plus(dec(2), inc(7))
plus(1, 8)
plus(dec(1), inc(8))
plus(0, 9)
9
'''
| true |
fcc2236015a6ea9573951af8bbf6733f03f2112d | admacro/sicp | /python/1.1/1.6.py | 2,231 | 4.3125 | 4 | '''
Square roots by Newton's Method
Using new_if
'''
def new_if(predication, then_clause, else_clause):
if (predication):
return then_clause
else:
return else_clause
def sqroot(x):
return sqrt_iter(1.0, x)
def sqrt_iter(guess, x):
return new_if(close_enough(guess, x), guess, sqrt_iter(improve(guess, x), x))
def close_enough(guess, x):
return abs(guess - improve(guess, x)) / guess < 0.000000001
def improve(guess, x):
return avg(guess, x/guess)
def sqr(x): return x * x
def avg(x, y): return (x + y) / 2
'''
Output:
RecursionError: maximum recursion depth exceeded
'''
print(sqroot(1024000000000000))
print(sqroot(1024))
print(sqroot(0.001024))
print(sqroot(0.000000001024))
'''
Python uses applicative evaluation order which means
funtion parameters will be evaluated before being passed to
the funtion that's being called.
And function parameters are evaluated from left to right.
else_clause is always evaluated, hence the evaluation never ends.
new_if(close_enough(guess, x), guess, sqrt_iter(improve(guess, x), x))
new_if(False, guess, new_if(close_enough(guess_1, x), guess_1, sqrt_iter(improve(guess_1, x), x)))
new_if(False, guess, new_if(False, guess_1, new_if(False, guess_2, sqrt_iter(improve(guess_2, x), x))))
new_if(False, guess, new_if(False, guess_1, new_if(False, guess_2, new_if(False, guess_3, sqrt_iter(improve(guess_3, x), x))))))
...
'''
def newer_if(pred_1, pred_2, then_clause, elif_cluase, else_clause):
print("newer_if")
if (pred_1):
return then_clause
elif pred_2:
return elif_cluase
else:
return else_clause
def print_then():
print("then")
return 1
def print_elif():
print("elif")
return -1
def print_else():
print("else")
return 0
def test(x):
print("testing")
return x
def test_new_if(pred):
return new_if(test(pred), print_then(), print_else())
def test_newer_if(pred_1, pred_2):
return newer_if(test(pred_1), test(pred_2), print_then(), print_elif(), print_else())
'''
output:
testing
then
else
0
'''
print(test_new_if(False))
'''
output:
testing
testing
then
elif
else
newer_if
1
'''
print(test_newer_if(True, False))
| true |
e595f34838a8e517e776798eb5c36a532fc4179d | Eric-Audit/Python | /Python/change_Audit.py | 1,489 | 4.28125 | 4 | #!/usr/bin/env python3
print("Change Calculator")
print()
#While loop to allow user to test multiple amounts
choice = "y"
while choice.lower() == "y":
#get a dollars variable from the user
dollars = float(input("Enter dollar amount (for example, .17, 7.17): "))
print()
#convert dollars variable into cents
dollars = dollars * 100
#rename the variable so it is easier to understand
coins = dollars
#use interger divison to get a remainder that will == quarters amount
quarters = coins // 25
#use a chain function to force quarters to display as an int
print ("Quarters: " + str(int(quarters)))
#set cents to the remainder of quarters
coins = coins % 25
#use interger divison to get a remainder that will == dimes amount
dimes = coins // 10
#use a chain function to force dimes to display as an int
print ("Dimes: " + str(int(dimes)))
#set cents to the remainder of dimes
coins = coins % 10
#use interger divison to get a remainder that will == nickels amount
nickels = coins // 5
#use a chain function to force nickels to display as an int
print ("Nickels: " + str(int(nickels)))
#set cents to the remainder of nickels
coins = coins % 5
#use round and division to increase python accuracy
pennies = round (coins / 1)
print ("Pennies: " + str(pennies))
print()
choice = input("Continue? (y/n): ")
print()
print("Bye!")
| true |
86d8fa09bdc267b530f613c718635c5755dfbd61 | DevenCao/Python-Learning | /exercises/fibonacci.py | 754 | 4.46875 | 4 | '''
Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
Take this opportunity to think about how you can use functions.
Make sure to ask the user to enter the number of numbers in the sequence to generate.
(Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence
is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)
'''
#callback function
def fibonacci_generator(count = 0, first = 1, second = 1):
fibonacci_list = [first]
if count <= 1:
return fibonacci_list
fibonacci_list += fibonacci_generator(count-1, second, first + second)
return fibonacci_list
print(fibonacci_generator(10))
| true |
0b40e3b07c30a58312564d51a80ab97099372937 | matthew-meech/ICS3U-Unit4-01-Python-Addingloop | /loop.py | 576 | 4.25 | 4 | #!/usr/bin/env python3
# Created by: Matthew Meech
# Created on: Sep 2021
# This program uses a while loop
def main():
# this function uses a while loop
# this is to keep track of hw many times you go through the loop
loop_counter = 0
# input
print("\n", end="")
positive_integer = int(input("enter a postive inetger: "))
# process & output
print("\n", end="")
while loop_counter < positive_integer:
print("{0} time through loop.".format(loop_counter))
loop_counter = loop_counter + 1
if __name__ == "__main__":
main()
| true |
cdacab1b3df38a8323b676537b998ae5b20c1784 | divineo/python-exercise | /palindrome-Part2.py | 323 | 4.46875 | 4 | #code in python3
#checking if a number is a palindrome
#done using str() and sting slicing. Very easy :)
val = input("Enter the number: ")
#checking the number. string slicing is a method which reverses string.
test = str(val) == str(val)[::-1]
#Output whether true or false
print("Is it a palindrome? : " + str(test))
| true |
8a1c9aa79c1233e7d41687e9a591af6b3424e635 | osama10/NanoDegree-Data-Structure-and-Algorithms | /Problem Vs Algorithm/RearrangeArrayDigits/rearrange_digits.py | 1,752 | 4.15625 | 4 | def mergesort(items):
if len(items) <= 1:
return items
mid = len(items) // 2
left = items[:mid]
right = items[mid:]
left = mergesort(left)
right = mergesort(right)
return merge(left, right)
def merge(left, right):
merged = []
left_index = 0
right_index = 0
while left_index < len(left) and right_index < len(right):
if left[left_index] > right[right_index]:
merged.append(right[right_index])
right_index += 1
else:
merged.append(left[left_index])
left_index += 1
merged += left[left_index:]
merged += right[right_index:]
return merged
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
num1 = ""
num2 = ""
if input_list is None :
return []
if len(input_list) <= 2:
return input_list
input_list = mergesort(input_list)
for index in range(len(input_list) - 1 , -1, -2):
num1 += str(input_list[index])
if index - 1 >= 0:
num2 += str(input_list[index - 1])
return [int(num1), int(num2)]
pass
def test_function(test_case):
output = rearrange_digits(test_case[0])
solution = test_case[1]
if sum(output) == sum(solution):
print("Pass")
else:
print("Fail")
test_function([[1, 2, 3, 4, 5], [542, 31]])
test_function([[4, 6, 2, 5, 9, 8], [964, 852]])
test_function([[], []])
test_function([None, []])
test_function([[1], [1]])
test_function([[1,2], [1,2]])
test_function([[1,2,3], [31,2]])
test_function([[3,1,3,3], [31,33]])
| true |
3be910e9e30b91432df311acaad2d43271d0510a | Jokekiller/Lists | /storing names.py | 730 | 4.21875 | 4 | #Harry Robinson
#05-12-2014
#storing names
name1 = str(input("Enter the first name: "))
name2 = str(input("Enter the second name: "))
name3 = str(input("Enter the third name: "))
name4 = str(input("Enter the fourth name: "))
name5 = str(input("Enter the fifth name: "))
name6 = str(input("Enter the sixth name: "))
name7 = str(input("Enter the seventh name: "))
name8 = str(input("Enter the eigth name: "))
nameList = [name1, name2, name3, name4, name5, name6, name7, name8]
for each in nameList:
print(each)
studentToChange = str(input("Enter the new student name: "))
placeToChange = int(input("Enter where this student needs to be replaced: "))
nameList.insert(placeToChange,studentToChange)
for each in nameList:
print(each)
| true |
923e1ba57fcf4a848c23ba7da620a5284d65dd8f | RBertoCases/Automate-The-Boring-Stuff-With-Python | /dateDetection.py | 1,408 | 4.59375 | 5 | #! python3
# dateDetection.py - Write a regular expression that can detect dates in the DD/MM/YYYY format. Assume that the days range from 01 to 31, the months range from 01 to 12, and the years
# range from 1000 to 2999. Note that if the day or month is a single digit, it’ll have a leading zero.
# The regular expression doesn’t have to detect correct days for each month or for leap years; it will accept nonexistent dates like 31/02/2020 or 31/04/2021.
# Then store these strings into variables named month, day, and year, and write additional code that can detect if it is a valid date. April, June, September, and November have 30 days,
# February has 28 days, and the rest of the months have 31 days. February has 29 days in leap years. Leap years are every year evenly divisible by 4, except for years evenly divisible
# by 100, unless the year is also evenly divisible by 400. Note how this calculation makes it impossible to make a reasonably sized regular expression that can detect a valid date."""
import re
# regular expression for DD/MM/YYYY
dateRegex = re.compile(r'''(
(0[1-9]|[12]\d|3[01]) # day
\/ # forward slash
(0[1-9]|1[0-2]) # month
\/ # forward slash
([12]\d{3}) # year
)''', re.VERBOSE)
text = 'today 01/01/2020'
mo = dateRegex.search(text)
| true |
cc6401c3c29fd2fb6e8782d1ed4814bf0a27d24f | AyushSingh445132/What-I-have-learnt-so-far-in-Python | /6.0.Dictionary & It's Function Explained.py | 1,006 | 4.28125 | 4 | # Making a dicitionary?
dic1 = {'duck':'quack','cow':'mooh','tiger':'roar'}
print(dic1['cow'])
# Accesing Elements
# get vs [] for retrieving elements
my_dic = {'name':'Jack','age':'26'}
# Output : Jack
print(my_dic['name'])
# Output : 26
print(my_dic['age'])
# Changing & Adding elements
#update value
#my_dic['age']=27
# Output : {'name': 'Jack', 'age': 27}
print(my_dic)
# add item
my_dic['address'] = 'Downtown'
# Output : {'name': 'Jack', 'age': 27, 'address': 'Downtown'}
print(my_dic)
# Removing elements
# Removing element from a dicitionary
squraes = {1:1,2:4,3:9,4:16,5:25}
# removing a particular item
print(squraes.pop(4))
# removing a particular item using del function
del squraes[1]
# Output : {2: 4, 3: 9, 5: 25}
print(squraes)
#remove an arbitary item
print(squraes.popitem())
# Output : {2: 4, 3: 9}
print(squraes)
# remove all items
squraes.clear()
print(squraes) | false |
10305e8dd84f198827ac74d7992289d638b15e61 | wmfinamore/pyLab | /2_compartilhando_seu_codigo/build/lib/iteratelist.py | 1,241 | 4.34375 | 4 | """
Este é o módulo "iteratelist.py", e fornece uma função chamada
print_lol() que imprime listas que podem ou não
incluir listas aninhadas
"""
def print_lol(the_list, tab=False, level=0):
"""
Esta função requer um argumento posicional
chamdo "the_list", que é qualquer lista
Python(de possíveis listas aninhadas).
Cada item de dados na lista fornecida
é (recursivamente) impresso na tela em
sua própria linha.
Um segundo argumento indica se será usada
tabulação entre is niveis da lista(boolean).
Um terceiro argumento chamado "level"
é usado para inserir tabulações quando
uma lista aninhada é encontrada.
"""
l = level
t = tab
for each_item in the_list:
if isinstance(each_item, list):
print_lol(each_item,t, l+1)
else:
"""
Usa o valor de "level" para
controlar o número de tabulações
a serem usadas.
"""
if t:
for tab in range(l):
"""
Exiba um caracter TAB
para cada nível de recuo
"""
print("\t", end='')
print(each_item) | false |
dd67efb728b50fd14640e6a58defa291d184a70d | Amreesh92630/amreesh | /Circle_Circumference_area.py | 796 | 4.65625 | 5 | '''A class Circle has to define and we have to calcute circumference and area if radius of the circle has been given with the help of
Object Oriented programming'''
class Circle:
pi = 3.14
# Attributes of Class Circle
def __init__(self,radius=1):
self.radius = radius
# method for calculating Circumference of Circle
# defined a function for calculating circumference
def get_circumference(self):
return self.pi * self.radius * 2
# method for calculating Area of circle
# defined a function for calculating Area
def get_area(self):
return self.pi * self.radius ** 2
chotu = Circle()
print('Radius is: ',chotu.radius)
print('Area of the Circle is:',chotu.get_area())
print('Circumference of the Circle is:',chotu.get_circumference())
| true |
1f5f446c748a43109d9db454ee997b1f3b34c4bc | CaioDariva/BlueEdTech-Modulo1 | /Projetos/Estoque.py | 2,542 | 4.34375 | 4 | ### Exercício 2- Crie um programa, utilizando dicionário, que simule a baixa de estoque
# das vendas de um supermercado. Não esqueça de fazer as seguintes validações:
# Produto Indisponível
# Produto Inválido
# Quantidade solicitada não disponível
# O programa deverá mostrar para o cliente a quantidade de tipos de itens comprados e o total de itens.
estoque = {'TOMATE' : 10, 'ARROZ' : 10, 'BATATA' : 10, 'CENOURA' : 10, 'CHOCOLATE' : 10, 'LEITE' : 10}
continuação = 'SIM'
compra = dict()
compra2 = list()
print('Bem-vindo ao Mercado!')
print()
while continuação == 'SIM':
produto = str(input('O que você gostaria de comprar? ')).upper()
print()
while produto not in estoque:
print('Produto inválido.')
produto = input('O que você gostaria de comprar? ').upper()
print()
retirada = int(input('Qual a quantidade? '))
quantidade = estoque.pop(produto)
while retirada > quantidade and quantidade != 0:
print(f'Quantidade indisponível. Possuímos apenas {quantidade} unidades.')
retirada = int(input('Quantas você deseja? '))
if retirada <= quantidade:
compra[produto] = retirada
compra2.append(retirada)
estoque[produto] = (quantidade - retirada)
while quantidade == 0:
produto = input(f'Esse produto acabou.\nNós ainda temos {estoque}.\nPor favor escolha outro: ').upper()
while produto not in estoque:
print('Produto inválido.')
print()
produto = input('O que você gostaria de comprar? ').upper()
print()
retirada = int(input('Qual a quantidade? '))
quantidade = estoque.pop(produto)
while retirada > quantidade:
print(f'Quantidade indisponível. Possuímos apenas {quantidade} unidades.')
retirada = int(input('Quantas você deseja? '))
if retirada <= quantidade:
compra[produto] = retirada
compra2.append(retirada)
estoque[produto] = (quantidade - retirada)
print()
continuação = str(input('Você deseja comprar mais itens? ')).upper().replace('Ã' , 'A')
while continuação != 'SIM' and continuação != 'NAO':
continuação = str(input('Você deseja comprar mais itens, sim ou não? ')).upper().replace('Ã' , 'A')
print()
if continuação == 'NAO':
print('Obrigado pelas compras.')
print()
print(f'Você adquiriru {len(compra)} tipos de itens diferentes e um total de {sum(compra2)} unidades') | false |
ef7e1ce592c3b200770109ad99264826c4f8ed43 | CaioDariva/BlueEdTech-Modulo1 | /Projetos/JokenPo.py | 2,740 | 4.3125 | 4 | ## Utilizando os conceitos aprendidos até estruturas de repetição, crie um programa que jogue pedra,
# papel e tesoura (Jokenpô) com você.
## O programa tem que:
## • Permitir que eu decida quantas rodadas iremos fazer;
## • Ler a minha escolha (Pedra, papel ou tesoura);
## • Decidir de forma aleatória a decisão do computador;
## • Mostrar quantas rodadas cada jogador ganhou;
## • Determinar quem foi o grande campeão de acordo com a quantidade de vitórias de cada um
## (computador e jogador);
## • Perguntar se o Jogador quer jogar novamente, se sim inicie volte a escolha de quantidade de rodadas,
## se não finalize o programa.
import random
continuacao = 'SIM'
while continuacao == 'SIM':
jogos = 1
empate = 0
num_vitorias_jog = 0
num_vitorias_comp = 0
num_jogos = int(input('Vamos jogar Jokempô! Quantas rodadas iremos jogar?\n'))
while num_jogos >= jogos:
jogador = input('Ok! Vamos lá!\nJo - Kem - Pô?\n').upper()
print()
comp = random.randint(1,3)
if comp == 1:
comp = 'PEDRA'
elif comp == 2:
comp = 'PAPEL'
elif comp == 3:
comp = 'TESOURA'
print(f'Você tirou {jogador} e o computador tirou {comp}!')
print()
if jogador == comp:
print('Empatou!')
empate += 1
elif jogador == 'TESOURA' and comp == 'PAPEL':
print('Você ganhou!')
num_vitorias_jog += 1
elif jogador == 'TESOURA' and comp == 'PEDRA':
print('Você perdeu!')
num_vitorias_comp += 1
elif jogador == 'PAPEL' and comp == 'PEDRA':
print('Você ganhou!')
num_vitorias_jog += 1
elif jogador == 'PAPEL' and comp == 'TESOURA':
print('Você perdeu!')
num_vitorias_comp += 1
elif jogador == 'PEDRA' and comp == 'TESOURA':
print('Você ganhou!')
num_vitorias_jog += 1
elif jogador == 'PEDRA' and comp == 'PAPEL':
print('Você perdeu!')
num_vitorias_comp += 1
jogos += 1
print()
print(f'Você ganhou {num_vitorias_jog}x.\nO computador {num_vitorias_comp}x.\nEmpatou {empate}x.')
print()
if num_vitorias_jog > num_vitorias_comp:
print('Parabéns! Você é o rei do Jokempô!')
elif num_vitorias_jog == num_vitorias_comp:
print('Houve um empate aqui!')
elif num_vitorias_jog < num_vitorias_comp:
print('Você perdeu, que pena!')
print()
continuacao = input('Deseja jogar novamente?').upper().replace('Ã' , 'A')
print()
if continuacao == 'NAO':
print('O jogo terminou. Espero que tenha se divertido!\n') | false |
ea1724e7af9125fc4a790f41b0b3656063d7aa68 | jwiley84/netCoreClasswork | /Python/typeList.py | 1,352 | 4.15625 | 4 | #this is literally what I just did....abs
#input
l1 = ['magical unicorns',19,'hello',98.98,'world']
l2 = [2,3,1,7,4,12]
l3 = ['magical','unicorns']
strCount = 0;
intCount = 0;
newStr = '';
newTotal = 0;
#test
for item in l1:
if (type(item) is int):
intCount += 1;
newTotal += item;
elif(type(item) is float):
intCount += 1;
newTotal += item;
elif (type (item) is str):
strCount +=1;
newStr += item;
if (strCount > 0 and intCount > 0):
print("this is a mixed list")
print(newStr)
print(newTotal)
elif (intCount == 0):
print("this is a string list")
print(newStr)
else:
print("This is an integer list")
print(newTotal)
#instructions
'''
Write a program that takes a list and prints a message
for each element in the list, based on that element's
data type.
Your program input will always be a list. For each item
in the list, test its data type. If the item is a string,
concatenate it onto a new string. If it is a number, add
it to a running sum. At the end of your program print the
string, the number and an analysis of what the list contains.
If it contains only one type, print that type, otherwise,
print 'mixed'.
Here are a couple of test cases. Think of some of your own,
too. What kind of unexpected input could you get?
''' | true |
81b0ea8504cefa3af2167275aeabebb2d1c415ad | MaiBil/coding_challenges | /codewars/Split_Strings.py | 859 | 4.125 | 4 | #!/user/bin/env python
# author: Mailen Bilsky
# date: 13/09/2018
# title: Split Strings
# url: https://www.codewars.com/kata/515de9ae9dcfc28eb6000001
# difficulty: 6 kyu
# time complexity: O(n), with n being the amount of numbers in the input string
def solution(s):
"""
Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number
of characters then it should replace the missing second character of the final pair with an underscore ('_').
:param nmultiply: String of characters
:type multiply: string
:return: List of strings of two characters
:rtype: list
"""
ls = []
i = 0
if len(s) % 2 == 0:
while i < len(s)-1:
ls.append(s[i]+s[i+1])
i += 2
else:
while i < len(s)-2:
ls.append(s[i]+s[i+1])
i += 2
ls.append(s[len(s)-1]+"_")
return ls | true |
fd08950c7c6e2a7f921575dbb1b127cf5e964a19 | MaiBil/coding_challenges | /codewars/Which_are_in.py | 1,034 | 4.125 | 4 | #!/user/bin/env python
# author: Mailen Bilsky
# date: 24/09/2018
# title: Which are in?
# url: https://www.codewars.com/kata/550554fd08b86f84fe000a58
# difficulty: 6 kyu
# time complexity: O(n2), with n being the amount of numbers in the input string
def in_array(array1, array2):
"""
Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of
a1 which are substrings of strings of a2.
#Example 1: a1 = ["arp", "live", "strong"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
returns ["arp", "live", "strong"]
#Example 2: a1 = ["tarp", "mice", "bull"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
returns []
:param numbers: Two lists with string of letters
:type numbers: list, list
:return: Return a sorted list with the elements of array1 that are substrings in array2
:rtype: list
"""
a = []
for i in array1:
for j in array2:
if i not in a and i in j:
a.append(i)
return sorted(a) | true |
38272b535ea93d65d18cbb0932d9a835e489a1c7 | MaiBil/coding_challenges | /codewars/Good_vs_Evil.py | 2,820 | 4.25 | 4 | #!/user/bin/env python
# author: Mailen Bilsky
# date: 20/09/2018
# title: Good vs Evil
# url: https://www.codewars.com/kata/52761ee4cffbc69732000738
# difficulty: 6 kyu
# time complexity: O(n), with n being the amount of numbers in the input string
def goodVsEvil(good, evil):
"""
Middle Earth is about to go to war. The forces of good will have many battles with the forces of evil.
Different races will certainly be involved. Each race has a certain worth when battling against others.
On the side of good we have the following races, with their associated worth:
Hobbits: 1
Men: 2
Elves: 3
Dwarves: 3
Eagles: 4
Wizards: 10
On the side of evil we have:
Orcs: 1
Men: 2
Wargs: 2
Goblins: 2
Uruk Hai: 3
Trolls: 5
Wizards: 10
Although weather, location, supplies and valor play a part in any battle, if you add up the worth of the side
of good and compare it with the worth of the side of evil, the side with the larger worth will tend to win.
Thus, given the count of each of the races on the side of good, followed by the count of each of the races on
the side of evil, determine which side wins.
Input:
The function will be given two parameters. Each parameter will be a string separated by a single space. Each
string will contain the count of each race on the side of good and evil.
The first parameter will contain the count of each race on the side of good in the following order:
Hobbits, Men, Elves, Dwarves, Eagles, Wizards.
The second parameter will contain the count of each race on the side of evil in the following order:
Orcs, Men, Wargs, Goblins, Uruk Hai, Trolls, Wizards.
All values are non-negative integers. The resulting sum of the worth for each side will not exceed the limit
of a 32-bit integer.
:param numbers: List with numbers
:type numbers: list of ints
:return: Return "Battle Result: Good triumphs over Evil" if good wins, "Battle Result: Evil eradicates all trace of
Good" if evil wins, or "Battle Result: No victor on this battle field" if it ends in a tie.
:rtype: string
"""
good_list = good.split(" ")
evil_list = evil.split(" ")
good_total = int(good_list[0])*1 + int(good_list[1])*2 + int(good_list[2])*3 + int(good_list[3])*3 + int(good_list[4])*4 + int(good_list[5])*10
evil_total = int(evil_list[0])*1 + int(evil_list[1])*2 + int(evil_list[2])*2 + int(evil_list[3])*2 + int(evil_list[4])*3 + int(evil_list[5])*5 + int(evil_list[6])*10
if good_total > evil_total:
return "Battle Result: Good triumphs over Evil"
elif evil_total > good_total:
return "Battle Result: Evil eradicates all trace of Good"
elif good_total == evil_total:
return "Battle Result: No victor on this battle field"
| true |
5848dcd9eca360154782b2b94abd84f288257ab9 | drfiresign/lpthw | /ex8.py | 737 | 4.1875 | 4 | # defines the formatter variable using the traditional {} notation
formatter = "{} {} {} {}"
# formats using numbers
print(formatter.format(1, 2, 3, 4))
# formats using strings of numbers
print(formatter.format("one", "two", "three", "four"))
# formats using boolean expressions
print(formatter.format(True, False, False, True))
# formats using the same formatter variable turning each instance
# of the {} notation into a string with "{} {} {} {}"
print(formatter.format(formatter, formatter, formatter, formatter))
# formats a multi line argument into a single line.
# the comma , allows for the multi line structure
print(formatter.format(
"here's a short poem",
"it's about the length",
"of most poems",
"i've ever written."
))
| true |
b315b17c623cf1e49ac208ea4603dc560a6cc7cf | durguupi/python_devops | /workingwithfiles/practise_exercises/basics/exer7.py | 878 | 4.4375 | 4 | # Write a function in Python to count uppercase character in a text file.
def func_uppercase(filename):
with open(filename, 'r') as file1:
data = file1.read()
words = data.split()
count_upper = 0
count_lower = 0
for word in words:
if word[0].isupper():
count_upper += 1
print(word)
count_lower += 1
print(f"Upper case letter: {count_upper}")
print(f"Lower case letter: {count_lower}")
func_uppercase(
'python-devops/workingwithfiles/practise_exercises/basics/story.txt')
# Easy Method
def count_letter():
file = open(
'python-devops/workingwithfiles/practise_exercises/basics/story.txt', "r")
data = file.read()
count = 0
for letter in data:
if letter.isupper():
count += 1
print(count)
count_letter()
| true |
2b3eed74ba8d586f559161a8af1ab44c85cdd573 | AymanInSpace22/Python-Programs | /For_Loops.py | 767 | 4.59375 | 5 | # For Loops
# dont forget the colon
# this just prints out each element in your list
numbers = [1, 2, 3, 4, 5]
for item in numbers:
print(item)
print()
# the while loop version
i = 0
while i < len(numbers):
print(numbers[i])
i += 1
print()
# Range Function
numbers = range(3, 20)
for number in numbers:
print(number)
print()
# you can add the third value so it will count or skip by that number
numbers = range(3, 20, 3)
for number in numbers:
print(number)
print()
# another way of doing it
for number in range(5)
print(number)
# Tuples
# similar to lists
# with lists you use square brackets. With tuples you use paranthesis
# tuples are immutable. Meaning you can not change them once they are done
numbers = (1, 2, 3)
numbers.
| true |
9d5323f68e4b50421a81599e096d26886a210fe3 | MachineLearnWithRosh/FunWithPython | /Basic Projects/SnakeWaterGun_game.py | 1,587 | 4.125 | 4 | import random
from itertools import combinations
chances = 0
human_point = 1
computer_point = 1
players = ['snake', 'water', 'gun']
while chances < 10:
human_input = input("Type Snake, Water or Gun :\n")
if (human_input.lower() in players):
comp_select = random.choice(players)
if (human_input.lower() == 'water' and comp_select == 'snake'):
chances += 1
print("Computer wins you have ", 10 - chances, " chances")
print(comp_select)
computer_point += 1
elif (human_input.lower() == 'gun' and comp_select == 'water'):
chances += 1
print("Computer wins you have ", 10 - chances, " chances")
print(comp_select)
computer_point += 1
elif human_input.lower() == 'snake' and comp_select == 'gun':
chances += 1
print("Computer wins you have ", 10 - chances, " chances")
print(comp_select)
computer_point += 1
elif human_input.lower() == comp_select:
print(comp_select)
chances += 1
print("Choices draw!!")
computer_point += 1
human_point += 1
else:
print("You have won!!!")
chances += 1
human_point += 1
else:
print("Wrong Selection, Please try again!!!")
if human_point > computer_point:
print("You have won the game!!")
elif human_point < computer_point:
print("Computer have won the game!")
else:
print("Match has draw")
| true |
775d76a34315bfe34c7194e0281387bc6be0949b | EFulmer/dailyprogrammer | /challenge_140.py | 687 | 4.25 | 4 | # Challenge 140:
# Variable Notation (Easy)
import re
spaced_var = re.compile('\s')
camel_case = '0'
snake_case = '1'
snake_caps = '2'
def handle_camel(var):
return var[0] + ''.join(map(str.capitalize, var[1:]))
def handle_snake_caps(var):
return '_'.join(map(str.upper, var))
def convert_notation(notation, name):
return conversion_rules[notation](name)
conversion_rules = { camel_case : handle_camel,
snake_case : '_'.join,
snake_caps : handle_snake_caps, }
def main():
notation = input()
name = re.split(spaced_var, input())
print(convert_notation(notation, name))
if __name__ == '__main__':
main()
| false |
b700d05fc9080f218984db8cb0b78cacec758944 | lenniecottrell/Python-Projects | /Mini projects/birthday_IF_statements.py | 663 | 4.3125 | 4 | import datetime
today = datetime.date.today()
checkDate = datetime.datetime(2020, 6, 30)
allisonBday = datetime.datetime(2020, 5, 9)
print(today)
print(checkDate)
print(allisonBday)
if today.month == checkDate.month and today.day == checkDate.day:
print("Happy birthday!")
elif today.month == allisonBday.month and today.day == allisonBday.day:
print("It's Allison's birthday!")
else:
print("It's not your or Allison's birthday")
if today.month > 6:
print("You have to wait until next year")
elif today.month == 5 and today.day >= 10:
print("Your birthday is next!!")
else:
print("Allison's birthday is next!!")
| true |
c4b6840cb56d7db17c2356ae90319d29b6cca248 | prathimaautomation/python_engineering89_basics | /string_casting_concatenation.py | 1,811 | 4.5 | 4 | # Using and Managing Strings
# string casting
# string concatenation
# Casting methods
# single and double quotes
single_quotes = 'These\'re single quotes and working perfectly fine' #
double_quotes = "These're double quotes also working fine"
# print(single_quotes)
# print(double_quotes)
# concatenation
First_Name = "James"
Last_Name = 'Bond'
#print(First_Name + " "+ Last_Name)
# Create a variable called age with int value and display age in the same line as James Bond
age ="20"
# print(f'{First_Name} {Last_Name} {age}')
# print("{} {} {}".format(First_Name, Last_Name, age))
# print(First_Name + " "+ Last_Name + age)
# print(type(age))
# print(type(int(age))) # example of casting
# String slicing and Indexing (starts with 0)
greetings = "Hello World!"
#01234567891011
#print(greetings)
# To confirm the length of this string method called len()
# print(len(greetings))
# print(greetings[0:5]) # slicing the string from index 0 - 4 upto 5
# print(greetings[-1]) #slicing the string from right to left
#
# print(greetings[6:]) # slice to print World!
# print(greetings[-6:]) # slicing using negative index
white_spaces = "Lots of white spaces "
#print(str(len(white_spaces))+" including white spaces") #length of string including/with white spaces
# we have strip() that removes all the white spaces
#print(str(len(white_spaces.strip()))+" excluding white spaces") #length of string excluding/without white spaces
# some more built-in methods that we can use with strings
example_text = "here's Some text With lots of text"
print(example_text.count("text")) # count() method counts the word in the string
print(example_text.lower())
print(example_text.upper())
print(example_text.capitalize())
print(example_text.replace("With", ","))
| true |
b095be6e386dbf8e36a78a72d7ac9277fe42e50c | Hosayy/CTI110 | /P3HW2_MealTipTax_Porras.py | 1,547 | 4.3125 | 4 | #This program will calculate the total amount of a meal and tip.
#2-19-19
#CTI-110 P2HW2- Meal Tip Calculator
#Jose Porras
#Get the total amount of meal purchase
totalmealpurchased = float(input("Enter the charge for the food: "))
#Get the tip amount of the meal
tip = float(input("Enter the tip for the meal: "))
#calculate the tip(15%, 18%, 20%)
tip1 = totalmealpurchased * .15
tip2 = totalmealpurchased * .18
tip3 = totalmealpurchased * .20
#the tax after the tip
tax1 = totalmealpurchased * .15 * .7
tax2 = totalmealpurchased * .18 * .7
tax3 = totalmealpurchased * .20 * .7
#the total of the meal and tip
totalpurchased1 =(totalmealpurchased + tip1 + tax1)
totalpurchased2 =(totalmealpurchased + tip2 + tax2)
totalpurchased3 =(totalmealpurchased + tip3 + tax3)
#display the total amount of meal
print("Amount of the meal purchase :$",format(totalmealpurchased ,',.2f'))
#display the tip
print("Amount of the tip of 15% :$",format(tip1 ,',.2f'))
print("Amount of the tip of 18% :$",format(tip2 ,',.2f'))
print("Amount of the tip of 20% :$",format(tip3 ,',.2f'))
#display the tax
print("Amount of the tax of 7% :$",format(tax1 ,',.2f'))
print("Amount of the tax of 7% :$",format(tax2 ,',.2f'))
print("amount of the tax of 7% :$",format(tax3 ,',.2f'))
#display the total purchase
print("Amount of the total purchased :$",format(totalpurchased1 ,'.2f'))
print("Amount of the total purchased :$",format(totalpurchased2 ,'.2f'))
print("Amount of the total purchased :$",format(totalpurchased3 ,'.2f'))
| true |
0170387136043ffb9a70d5bd98734eed485f549f | devmacrile/algorithms | /sort-quicksort/quicksort.py | 1,181 | 4.3125 | 4 | """
Implementation of the QuickSort sorting algorithm
"""
import random
def quicksort(A, l, r, method):
"""
Requires A an array; l,r are on (0,len(A)-1) with l <= r
l,r are indices indicating which part of array A on which the recursive call should work
Effects: sorts array A using QuickSort algorithm
"""
if l < r:
pivotIndex = choose_pivot(A, l, r, method)
if pivotIndex == -1:
print "Invalid pivot type."
return
pivot = A[pivotIndex]
A[pivotIndex], A[l] = A[l], A[pivotIndex]
i = l + 1
for j in range(l+1, r+1):
if A[j] < pivot:
A[j], A[i] = A[i], A[j]
i += 1
A[i-1], A[l] = A[l], A[i-1]
quicksort(A, l, i - 2, method)
quicksort(A, i, r, method)
return A
def choose_pivot(A, l, r, method):
"""
Method to choose pivot type at run type based on parameter 'method'
"""
if method == "first":
return l
elif method == "last":
return r
elif method == "median-of-three":
mid = (r + l)/2
vals = [A[l], A[mid], A[r]]
mn = min(vals)
mx = max(vals)
for i in [l, mid, r]:
if A[i] != mn and A[i] != mx:
return i
return mid # this covers the case where r-l == 1
else:
return -1
| true |
8ee60bb89239ead21e99b21ddc20f9c077e2df9c | ThibautHurson/basic_algorithms | /stack_queue.py | 1,277 | 4.1875 | 4 | class Stack:
def __init__(self):
self.stack = []
def add(self, dataval):
# Use list append method to add element
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return False
# Use list pop method to remove element
def remove(self):
if len(self.stack) <= 0:
return ("No element in the Stack")
else:
return self.stack.pop()
# Use peek to look at the top of the stack
def peek(self):
return self.stack[-1]
AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.add("Wed")
AStack.add("Thu")
print(AStack.remove())
print(AStack.remove())
class Queue:
def __init__(self):
self.queue = list()
def addtoq(self,dataval):
# Insert method to add element
if dataval not in self.queue:
self.queue.insert(0,dataval)
return True
return False
# Pop method to remove element
def removefromq(self):
if len(self.queue)>0:
return self.queue.pop()
return ("No elements in Queue!")
def size(self):
return len(self.queue)
TheQueue = Queue()
TheQueue.addtoq("Mon")
TheQueue.addtoq("Tue")
TheQueue.addtoq("Wed")
print(TheQueue.size()) | true |
5c6a3a4a7ff52676704dd0bcc8cd314a254ec447 | sasaxopajic/Python | /exercise9.py | 397 | 4.1875 | 4 | import math
print("Tip: Grades range from 0 - 10!")
a = int(input("Algebra: "))
g = int(input("Geometry: "))
p = int(input("Physics: "))
avg = (a + g + p)/3
avg = round(avg, 2)
if avg >= 7:
print("Your average score is", avg, ". Good job!")
elif 4 <= avg <= 6:
print("Your average score is", avg, ". You need to work harder!")
else:
print("Your average score is", avg, ". Failed!") | true |
564ad9b28dbafa1839ebe1622d8482238efba349 | BenJamesbabala/PyShortTextCategorization | /shorttext/utils/textpreprocessing.py | 2,360 | 4.25 | 4 | import re
from nltk.corpus import stopwords
from nltk import word_tokenize
from nltk.stem import PorterStemmer
def preprocess_text(text, pipeline):
""" Preprocess the text according to the given pipeline.
Given the pipeline, which is a list of functions that process an
input text to another text (e.g., stemming, lemmatizing, removing punctuations etc.),
preprocess the text.
:param text: text to be preprocessed
:param pipeline: a list of functions that convert a text to another text
:return: preprocessed text
:type text: str
:type pipeline: list
:rtype: str
"""
if len(pipeline)==0:
return text
else:
return preprocess_text(pipeline[0](text), pipeline[1:])
def text_preprocessor(pipeline):
""" Return the function that preprocesses text according to the pipeline.
Given the pipeline, which is a list of functions that process an
input text to another text (e.g., stemming, lemmatizing, removing punctuations etc.),
return a function that preprocesses an input text outlined by the pipeline, essentially
a function that runs :func:`~preprocess_text` with the specified pipeline.
:param pipeline: a list of functions that convert a text to another text
:return: a function that preprocesses text according to the pipeline
:type pipeline: list
:rtype: function
"""
return lambda text: preprocess_text(text, pipeline)
def standard_text_preprocessor_1():
""" Return a commonly used text preprocessor.
Return a text preprocessor that is commonly used, with the following steps:
- removing special characters,
- removing numerals,
- converting all alphabets to lower cases,
- removing stop words, and
- stemming the words (using Porter stemmer).
This function calls :func:`~text_preprocessor`.
:return: a function that preprocesses text according to the pipeline
:rtype: function
"""
stemmer = PorterStemmer()
pipeline = [lambda s: re.sub('[^\w\s]', '', s),
lambda s: re.sub('[\d]', '', s),
lambda s: s.lower(),
lambda s: ' '.join(filter(lambda s: not (s in stopwords.words()), word_tokenize(s))),
lambda s: ' '.join(map(lambda t: stemmer.stem(t), word_tokenize(s)))
]
return text_preprocessor(pipeline) | true |
e9fed57413870f9583557c28654ecb39a47a1cbe | DrEaston/CodingNomads | /labs/07_classes_objects_methods/07_00_planets.py | 384 | 4.40625 | 4 | '''
Create a Planet class that models attributes and methods of
a planet object.
Use the appropriate dunder method to get informative output with print()
'''
class Planet():
def __init__(self, name, type):
self.name = name
self.type = type
def __str__(self):
return f"{self.name} is a {self.type}-type planet."
x=Planet("Jupiter", "gas")
print(x) | true |
59e6ce055ac6ef96bcecea866bc3ed39bbfbc21f | DrEaston/CodingNomads | /labs/03_more_datatypes/4_dictionaries/03_18_occurrence.py | 419 | 4.15625 | 4 | '''
Write a script that takes a string from the user and creates a dictionary of letter that exist
in the string and the number of times they occur. For example:
user_input = "hello"
result = {"h": 1, "e": 1, "l": 2, "o": 1}
'''
my_str=input("Pls enter a string: ")
my_dict={}
for item in my_str:
if item==" ":
pass
else:
my_dict[item]=my_str.count(item)
print(my_dict)
| true |
d1d5c8b65562930239069ff8a37dfacafe08352a | DrEaston/CodingNomads | /labs/02_basic_datatypes/2_strings/02_09_vowel.py | 600 | 4.25 | 4 | '''
Write a script that prints the total number of vowels that are used in a user-inputted string.
CHALLENGE: Can you change the script so that it counts the occurrence of each individual vowel
in the string and print a count for each of them?
'''
myString=input("Whats your string? ")
a=myString.count("a")
e=myString.count("e")
i=myString.count("i")
o=myString.count("o")
u=myString.count("u")
total=a+e+i+o+u
print("There are " + str(total) + " vowels. Breakdown by letter:")
print("a: "+str(a))
print("e: "+str(e))
print("i: "+str(i))
print("o: "+str(o))
print("u: "+str(u))
| true |
d3e9ad2071ae7c9a679ea282537388f3becf02d1 | RealHomoBulla/Beetroot_Academy_Homeworks | /Lesson_08/Lesson_8_Task_2.py | 999 | 4.375 | 4 | '''Task 2
Write a function that takes in two numbers from the user via input(), call the numbers a and b,
and then returns the value of squared a divided by b, construct a try-except block which raises an exception
if the two values given by the input function were not numbers, and if value b was zero (cannot divide by zero).'''
def strange_function():
while True:
try:
a, b = input('Please give me 2 numbers (a and b), separated by comma: ').replace(' ', '').split(',')
a = int(a)
b = int(b)
return f'"a" squared and divided by "0" equals to: {a**2/b}'
except ZeroDivisionError:
print('You are not supposed to divide by Zero. Try again: ')
continue
except ValueError:
print('Please enter TWO valid numbers. Try again: ')
continue
except:
print('Something really unexpected happened. Try again: ')
continue
x = strange_function()
print(x) | true |
702883d71dac99a5a4096385feb145a43a877aac | RealHomoBulla/Beetroot_Academy_Homeworks | /Archive/Lesson_7_Task_3.2.py | 2,901 | 4.53125 | 5 | '''Task 3
A simple calculator.
Create a function called make_operation, which takes in a simple arithmetic operator as a first parameter
(to keep things simple let it only be ‘+’, ‘-’ or ‘*’) and an arbitrary number of arguments (only numbers)
as the second parameter. Then return the sum or product of all the numbers in the arbitrary parameter.
For example:
the call make_operation(‘+’, 7, 7, 2) should return 16
the call make_operation(‘-’, 5, 5, -10, -20) should return 30
the call make_operation(‘*’, 7, 6) should return 42 '''
import operator
def take_input():
operator_input = input('Please, enter a valid operator (+ - * / ): ').replace(' ', '')
numbers_input = input('Please, enter arguments, separated by comma: ').replace(' ', '').split(',')
list_of_numbers = []
print(numbers_input)
for i in numbers_input:
if '-' in i or '.' in i or i.isdigit():
if i.replace('-', '').isdigit() == False:
print(f'Only numbers are valid input for an arithmetical operation. "{i}" was not included.')
continue
list_of_numbers.append(float(i))
else:
print(f'Only numbers are valid input for an arithmetical operation. "{i}" was not included.')
continue
first_number = list_of_numbers[0]
rest_of_numbers = list_of_numbers[1:]
return (operator_input, first_number, rest_of_numbers)
operator, arg1, *args = take_input()
def make_operation(operator, arg1, *args):
list_of_args = []
if '-' in str(arg1) or '.' in str(arg1) or str(arg1).isdigit():
result = float(arg1)
else:
'Sorry, the first argument is incorrect. '
for arg in args:
if type(arg) == list:
for n in range(len(arg)):
if '-' in str(n) or '.' in str(n) or str(n).isdigit():
list_of_args.append(float(arg[n]))
elif '-' in str(arg) or '.' in str(arg) or str(arg).isdigit():
list_of_args.append(float(arg))
else:
print(f'Only numbers are valid input for an arithmetical operation. "{arg}" was not included.')
continue
if operator == '+':
for i in list_of_args:
result += i
print(result)
if operator == '-':
for i in list_of_args:
result -= i
print(result)
if operator == '*':
for i in list_of_args:
result *= i
print(result)
if operator == '/':
for i in list_of_args:
result /= i
print(result)
make_operation(operator,arg1, *args)
make_operation('*', 7, 6)
# if operator not in '+-*/':
# print('Sorry, invalid operator. Use " + - * / "only. Try again.')
#
# else:
# operator = {
# '+': operator.add,
# '-': operator.sub,
# '*': operator.mul,
# '/': operator.truediv
# }
| true |
11f7907f6a1ec79582965a999a21860ff0794891 | RealHomoBulla/Beetroot_Academy_Homeworks | /Lesson_02/Lesson_2_Task_1.py | 998 | 4.46875 | 4 | """
Task 1
The greeting program.
Make a program that has your name and the current day of the week stored as separate variables and then prints a message like this:
“Good day <name>! <day> is a perfect day to learn some python.”
Note that <name> and <day> are predefined variables in source code.
An additional bonus will be to use different string formatting methods for constructing result string.
"""
user_name = 'Andrew'
current_day = 'Monday'
# Method 1
print(f'Good day {user_name}! {current_day} is a perfect day to learn some python.')
# Method 2
print('Good day '+ user_name + '! ' + current_day + ' is a perfect day to learn some python.')
# Method 3
print('Good day {0}! {1} is a perfect day to learn some python.'.format(user_name, current_day))
# Method 4
print('Good day %s! %s is a perfect day to learn some python.' % (user_name, current_day))
# Method 5
string = 'Good day {}! {} is a perfect day to learn some python.'
print(string.format(user_name, current_day)) | true |
b7877da8745ce68cd7b99cdc5b73960169aa6202 | RealHomoBulla/Beetroot_Academy_Homeworks | /Archive/Lesson_13_Task_3.py | 1,439 | 4.375 | 4 | '''Task 3
Write a function called `choose_func` which takes a list of nums and 2 callback functions.
If all nums inside the list are positive, execute the first function on that list and return the result of it.
Otherwise, return the result of the second one'''
# This function will be doubling every number in the list.
def double(some_list):
result = []
for num in some_list:
result.append(num * 2)
return result
# This function will be tripling every number in the list.
def triple(some_list):
result = []
for num in some_list:
result.append(num * 3)
return result
# Just to check if it works.
print(double([1, 2, 3, 4, 5]))
print(triple([1, 2, 3, 4, 5]))
print()
def choose_func(list_of_nums, func_1, func_2):
# This function will check, if ALL the numbers in the list are positive. Otherwise it returns False.
def check_the_list():
for num in list_of_nums:
# If any number is negative, func_2 will be executed (in our case, number will triple).
if num < 1:
return func_2(list_of_nums)
# If all numbers are positive, func_1 will be executed (in our case, number will double).
return func_1(list_of_nums)
return check_the_list()
# Checking - numbers should be doubled.
print(choose_func([1, 2, 3, 4, 5], double, triple))
# Checking - numbers should be tripled.
print(choose_func([1, -2, 3, 4, 5], double, triple)) | true |
05ce7aa7a6845b5c17acc26383a5c0850e9e6eba | rishavghosh605/Competitive-Coding | /daily coding problem/Google/Breadth First Printing of a tree.py | 882 | 4.15625 | 4 | """
This problem was asked by Microsoft.
Print the nodes in a binary tree level-wise. For example, the following should print 1, 2, 3, 4, 5.
1
/ \
2 3
/ \
4 5
"""
from queue import Queue
class Node(object):
def __init__(self,v=None):
self.val=v
self.left=None
self.right=None
class BinaryTree(object):
def __init__(self,start=None):
self.root=start
def printInBFS(root):
q=Queue()
q.put(root)
while(not q.empty()):
node=q.get()
print(node.val,end=" ")
if node.left!=None:
q.put(node.left)
if node.right!=None:
q.put(node.right)
if __name__=="__main__":
bt=BinaryTree()
bt.root=Node(1)
bt.root.left=Node(2)
bt.root.right=Node(3)
bt.root.right.left=Node(4)
bt.root.right.right=Node(5)
printInBFS(bt.root)
| true |
499273af0d3bb9478f2cd482d28ee33fe7cf22da | rishavghosh605/Competitive-Coding | /Other Codes/HeapInPython.py | 1,167 | 4.3125 | 4 | import heapq
#intializing heap
li=[5,7,9,1,3]
#using heapify to convert list into heap
heapq.heapify(li)
#printing created heap
print("The created heap is: ",end="")
print(list(li))
#using heappush() to push elements into heap
#pushing 4
heapq.heappush(li,4)
#printing modified heap
print("The modified heap after push is: ",end="")
print(list(li))
#using heappop() to pop smallest element
print("The popped-smallest element is: ",end="")
print(heapq.heappop(li))
#heappushpop and heapreplace functions
li1=[5,7,9,4,3]
li2=[5,9,7,4,3]
#heapifying the lists
heapq.heapify(li1)
heapq.heapify(li2)
#using heappushpop() to push and pop items simultaneously
#pops2
print("The popped item using heappushpop() is: ",end="")
print(heapq.heappushpop(li1,3))
print(li1)
#using heapreplace() to replace elements
print("The popped items using heapreplace() is: ")
print(li2)
print(heapq.heapreplace(li2,6))
print(li2)
#using nlargest and nsmallest functions
li1=[6,47,9,4,3,5,8,10,1]
heapq.heapify(li1)
print("The 3 largest numbers in heap are: ",end="")
print(heapq.nlargest(3,li1))
print("The 3 smallest numbers in heap are: ",end="")
print(heapq.nsmallest(3,li1))
| false |
97c7602c631717317c8178be0374bb33a3182bbf | rishavghosh605/Competitive-Coding | /daily coding problem/Uber/A Product Array Puzzle O(n) O(n).py | 921 | 4.34375 | 4 | # Python3 program for A Product Array Puzzle
def productArray(arr, n):
i, temp = 1, 1
# Allocate memory for the product array
prod = [1 for i in range(n)]
# Initialize the product array as 1
# In this loop, temp variable contains product of
# elements on left side excluding arr[i]
for i in range(n):
prod[i] = temp
temp *= arr[i]
# Initialize temp to 1 for product on right side
temp = 1
# In this loop, temp variable contains product of
# elements on right side excluding arr[i]
for i in range(n - 1, -1, -1):
prod[i] *= temp
temp *= arr[i]
# Print the constructed prod array
for i in range(n):
print(prod[i], end = " ")
return
# Driver Code
arr = [10, 3, 5, 6, 2]
n = len(arr)
print("The product array is: n")
productArray(arr, n)
'''Output :
The product array is :
180 600 360 300 900
Time Complexity: O(n)
Space Complexity: O(n)
Auxiliary Space: O(1)'''
| true |
84b79e4ecc284729f94590ef56fb35f7dfb368a9 | rishavghosh605/Competitive-Coding | /daily coding problem/Apple/Implementation of queue using two stacks/Incresaing dequeue cost.py | 1,355 | 4.28125 | 4 | """
This problem was asked by Apple.
Implement a queue using two stacks.
Recall that a queue is a FIFO (first-in, first-out) data structure
with the following methods: enqueue,
which inserts an element into the queue, and dequeue, which removes it.
"""
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1] if len(self.items) > 0 else None
def size(self):
return len(self.items)
class Queue:
def __init__(self):
self.s1=Stack()
self.s2=Stack()
# Time Complexity: O(1)
def enqueue(self,val):
self.s1.push(val)
# Time Complexity: O(N)
def dequeue(self):
if self.s2.size()==0:
if self.s1.size()==0:
return "Queue is Empty"
else:
while(self.s1.peek() != None):
self.s2.push(self.s1.pop())
return self.s2.pop()
if __name__=="__main__":
queue=Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print("Popped Element: ",queue.dequeue())
print("Popped Element: ",queue.dequeue())
| true |
871320f026c3ffac04ee9940de6cac0308b35c5c | rishavghosh605/Competitive-Coding | /Daily Interview Pro/Twitter/Invert a Binary Tree.py | 1,821 | 4.4375 | 4 | """
This problem was recently asked by Twitter:
You are given the root of a binary tree. Invert the binary tree in place. That is, all left children should become right children, and all right children should become left children.
Example:
a
/ \
b c
/ \ /
d e f
The inverted version of this tree is as follows:
a
/ \
c b
\ / \
f e d
Here is the function signature:
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def preorder(self):
print self.value,
if self.left: self.left.preorder()
if self.right: self.right.preorder()
def invert(node):
# Fill this in.
root = Node('a')
root.left = Node('b')
root.right = Node('c')
root.left.left = Node('d')
root.left.right = Node('e')
root.right.left = Node('f')
root.preorder()
# a b d e c f
print "\n"
invert(root)
root.preorder()
# a c f b e d
"""
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def preorder(self):
print(self.value,end=" ")
if self.left: self.left.preorder()
if self.right: self.right.preorder()
def invert(node):
if node.left==None and node.right==None:
return True
doLeftSwap=invert(node.left) if node.left!=None else True
doRightSwap=invert(node.right) if node.right!=None else True
if doLeftSwap and doRightSwap:
tempNode=node.left
node.left=node.right
node.right=tempNode
return True
return False
root = Node('a')
root.left = Node('b')
root.right = Node('c')
root.left.left = Node('d')
root.left.right = Node('e')
root.right.left = Node('f')
print("Before Inversion: ")
root.preorder()
# a b d e c f
print("\n")
invert(root)
print("After Inversion: ")
root.preorder()
# a c f b e d
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.