blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
4b1cc0240dab583f935b1fafd5870315cdaa19f7 | shilpavijay/Algorithms-Problems-Techniques | /Puzzles/Hourglass_2D_array.py | 1,387 | 4.21875 | 4 | '''
Given a 6X6 2D Array:
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
An hourglass is a subset of values with indices falling in this pattern as a graphical representation:
a b c
d
e f g
An hourglass sum is the sum of an hourglass' values.
Calculate the hourglass sum for every hourglass in the array, then print the maximum hourglass sum.
The array will always be 6X6
'''
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'hourglassSum' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
def hourglassSum(arr):
# Write your code here
x = 6
y = 6 #can convert to numpy array and use numpy.shape()
result_arr = []
for i in range(0,4):
for j in range(0,4):
sum = 0
for k in range(j,j+3):
sum += arr[i][k] + arr[i+2][k]
sum += arr[i+1][math.floor((j+j+3)/2)]
result_arr.append(sum)
print(result_arr)
result_arr.sort()
return result_arr[-1]
pass
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
arr = []
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
result = hourglassSum(arr)
fptr.write(str(result) + '\n')
fptr.close()
| true |
8d1ab59b617dee1f643021aa2a7c5f762198fa7c | coolcoder786/python-mini-projects | /BMI.py | 357 | 4.25 | 4 | height=float(input("enter your height in foot\n"))
height_meters=height*0.305
weight=int(input("enter your weight in kg\n"))
BMI=weight/height_meters**2 # bmi=weight/square of your height in meters
print("BMI -",BMI)
if BMI>25:
print("you are over weight")
elif BMI<18:
print("you are under weight")
else:
print("you are FIT")
| true |
80701091a09b1b5c1fd3a520ba4515f78f836c4d | emilgab/bubble-sort | /bubble_sort.py | 2,270 | 4.40625 | 4 | # imports regular expressions for processing data strings
import re
# imports sys module for accepting command-line arguments
import sys
def data_process(in_file):
'''
Returns a list of words found in the file as lowercase and without punctuation.
'''
# A list we store our words in
our_words = []
# Opens the file, splits by word and uses regular expressions on each word.
file_opened = open(in_file, mode="r")
for word in file_opened.read().split():
# reassigns 'word' to be lowercase and exclude punctuation
word = re.sub("\W", "", word).lower()
our_words.append(word)
return our_words
def bubble_sort(my_list):
'''
Takes a list as input and return this list as sorted by length using bubble sort.
If words have equal length, then we sort them lexicographically.
'''
for number in range(len(my_list)-1,0,-1):
for item in range(number):
# Swaps the words if the length of the current word is bigger than the next word
# This will sort it by increasing length
if len(my_list[item]) > len(my_list[item+1]):
my_list[item],my_list[item+1] = my_list[item+1],my_list[item]
# In Python, the string "B" is of greater value than the string "A"
# We can therefore compare them in order to sort them lexicographically.
# If the current word is of equal length than the next word,
# and the word value is greater than the next, we swap them.
elif len(my_list[item]) == len(my_list[item+1]) and my_list[item] > my_list[item+1]:
my_list[item],my_list[item+1] = my_list[item+1],my_list[item]
return my_list
if __name__ == "__main__":
try:
# Allows for command-line arguments,
if len(sys.argv) == 2:
file = sys.argv[1]
for word in bubble_sort(data_process(file)):
print(word)
# will ask for filename if no arguments given.
else:
file = input("What is the name of the file? ")
for word in bubble_sort(data_process(file)):
print(word)
except:
print("File not found") | true |
44858854ba9e3cedd4ee60936622a274a15dd51c | KarthikGandrala/DataEncryption | /XORCipher/XOREncrypt.py | 1,774 | 4.1875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Function to encrypt message using key is defined
def encrypt(msg, key):
# Defining empty strings and counters
hexadecimal = ''
iteration = 0
# Running for loop in the range of MSG and comparing the BITS
for i in range(len(msg)):
temp = ord(msg[i]) ^ ord(key[iteration])
# zfill will pad a single letter hex with 0, to make it two letter pair
hexadecimal += hex(temp)[2:].zfill(2)
# Checking if the iterations of the key are 1
iteration += 1
if iteration >= len(key):
# once all of the key's letters are used, repeat the key
iteration = 0
# Returning the final value
return hexadecimal
def decrypt(msg, key):
# Defining hex to uni string to store
hex_to_uni = ''
# Running for loop to the length of message
for i in range(0, len(msg), 2):
# Decoding each individual bytes from hex
hex_to_uni += bytes.fromhex(msg[i:i + 2]).decode('utf-8')
decryp_text = ''
iteration = 0
# For loop running for the length of the hex to unicode string
for i in range(len(hex_to_uni)):
# Comparing each individual bit
temp = ord(hex_to_uni[i]) ^ ord(key[iteration])
# zfill will pad a single letter hex with 0, to make it two letter pair
decryp_text += chr(temp)
iteration += 1
if iteration >= len(key):
# once all of the key's letters are used, repeat the key
iteration = 0
# FInally return the decrypted text string
return decryp_text
| true |
c208203d552110c598cf56a022fa91c6131a8596 | vedant-c/Data-Structures | /LinkedList/nth_last.py | 1,063 | 4.125 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class Linkedlist:
def __init__(self):
self.head=None
def print_list(self):
cur_node=self.head
while cur_node:
print(cur_node.data)
cur_node=cur_node.next
def append(self,data):
new_node=Node(data)
if self.head is None:
self.head=new_node
return
last_node=self.head
while last_node.next:
last_node=last_node.next
last_node.next=new_node
def nth_last(self,n):
p=self.head
q=self.head
count=0
while q and count<n:
q=q.next
count+=1
if q is None:
print( str(n) + "is greater than number of nodes")
return
while p and q:
p=p.next
q=q.next
print(p.data)
llist=Linkedlist()
llist.append("a")
llist.append("b")
llist.append("c")
llist.append("d")
llist.append("e")
llist.nth_last(3)
# llist.print_list()
| true |
0ea37010373ce73162241a2a53b2b35a960154ce | SmirnovaT/pythonProject | /Классы/Class композиция.py | 1,411 | 4.15625 | 4 | # Наследование
#class BookShelf:
# def __init__(self, quantity):
# self.quantity = quantity
# def __str__(self):
# return f"BookShelf with {self.quantity} books."
#shelf = BookShelf(300)
#class Book(BookShelf):
# def __init__(self, name, quantity):
# super().__init__(quantity)
# self.name = name
# def __str__(self):
# return f"Book {self.name}"
#book = Book("Hary Potter", 120)
#print(book)
# Композиция
class BookShelf:
def __init__(self, *books):
self.books = books
def __str__(self):
return f"BookShelf with {len(self.books)} books."
class Book:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Book {self.name}"
book = Book("Hary Potter")
book2 = Book("Python")
shelf = BookShelf(book, book2)
print(shelf)
class WinDoor:
def __init__(self, x, y):
self.square = x * y
class Room:
def __init__(self, x, y, z):
self.square = 2 * z * (x + y)
self.wd = []
def addWD(self, w, h):
self.wd.append(WinDoor(w, h))
def workSurface(self):
new_square = self.square
for i in self.wd:
new_square -= i.square
return new_square
r1 = Room(6, 3, 2.7)
print(r1.square) # выведет 48.6
r1.addWD(1, 1)
r1.addWD(1, 1)
r1.addWD(1, 2)
print(r1.workSurface()) # выведет 44.6 | false |
8b26cb0b45c53ee96eac5544951a878496061422 | abhijithneilabraham/Data-structures-Cpp-python | /The self Identifier./self.py | 1,674 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 8 23:43:40 2019
@author: abhijithneilabraham
"""
class CreditCard:
def __init__(self,customer,bank,acnt,limit):
self.customer=customer
self.bank=bank
self.account=acnt
self.limit=limit
self.balance=500
def customer_name(self):
return self.customer
def bank_details(self):
return self.bank
def account_details(self):
self.account
def get_limit(self):
return self.limit
def charge(self,price):#price is recieved to the card
if price+self.balance>self.limit:
return False
else:
self.balance+=price
return True
def payment(self,amount):
self.balance-=amount
def mybalance(self):
return self.balance
'''
self :
self represents the instance of the class.
By using the "self" keyword we can access the attributes and methods of the class in python.
__init__ :
"__init__" is a reseved method in python classes.
It is known as a constructor in object oriented concepts. This method called when
an object is created from the class and it allow the class to initialize the attributes of a class.
'''
'''
Now I am gonna test the class
the tests are enclosed within a conditional if __name__=='__main__'
which makes it to be execuuted as the main program
'''
if __name__=='__main__':
wallet=CreditCard('Abhijith','SBI',12002100,10000)#constructor to create a new creditcard instance
val=100
wallet.charge(val)
print(wallet.mybalance())
wallet.payment(300)
print(wallet.mybalance())
| true |
50e7d1e71d52a5c949ce6068c4bcdb4f25a3858f | marcellalcantara/python-para-zumbis | /07-temperatura.py | 290 | 4.15625 | 4 | #Converta uma temperatura digitada em Celsius para Fahrenheit.
#F = 9*C/5 + 32
temperaturaCelsius = float(input('Qual a temperatura em Celsius? '))
temperaturaFahrenheit = 9 * temperaturaCelsius / 5 +32
print('A temperatura em Fahrenheit será ' + str( temperaturaFahrenheit) + '°F')
| false |
2302557d839c2bcd185c3f347600f36eaba7f129 | jacobwojcik/codewars-algorithms | /python/weIrDStRiNgCaSe.py | 821 | 4.4375 | 4 | # Write a function toWeirdCase (weirdcase in Ruby) that accepts a string,
# and returns the same string with all even indexed characters in each word
# upper cased, and all odd indexed characters in each word lower cased.
# The indexing just explained is zero based, so the zero-ith
# index is even, therefore that character should be upper cased.
# The passed in string will only consist of alphabetical characters
# and spaces(' '). Spaces will only be present if there are multiple words.
# Words will be separated by a single space(' ').
def to_weird_case(string):
result=[]
v=0
for i in string:
if v%2==0:
result.append(i.upper())
else:
result.append(i.lower())
if i.isspace():
v=0
else:
v+=1
return ("").join(result) | true |
01276439c227b8aa7e813a0237e5f7ff8103317a | jorgegabrielti/learn-python | /python-brasil-exercises/EstruturaSequencial/5.py | 258 | 4.21875 | 4 | # Faça um Programa que converta metros para centímetros.
# 1 mt => 1000 cm
print('********** CONVERSOR DE MEDIDAS **********')
mt = int(input('Digite a medida em metros: '))
# Processo de conversao
# 1mt = 100cm
cm = mt * 100
print(f'{mt}mt => {cm}cm')
| false |
c1a067618b53b1b4c1240c9bfeb299b1a538af67 | jorgegabrielti/learn-python | /python-brasil-exercises/EstruturaDeDecisao/20.py | 1,342 | 4.3125 | 4 | '''
Faça um Programa para leitura de três notas parciais de um aluno.
O programa deve calcular a média alcançada por aluno e presentar:
A mensagem "Aprovado", se a média for maior ou igual a 7, com a respectiva média alcançada;
A mensagem "Reprovado", se a média for menor do que 7, com a respectiva média alcançada;
A mensagem "Aprovado com Distinção", se a média for igual a 10.
'''
'''
Faça um programa para a leitura de duas notas parciais de um aluno. O programa deve calcular a média
alcançada por aluno e apresentar:
A mensagem "Aprovado", se a média alcançada for maior ou igual a sete;
A mensagem "Reprovado", se a média for menor do que sete;
A mensagem "Aprovado com Distinção", se a média for igual a dez.
'''
print('********** MÉDIA DE NOTAS **********')
nota1 = float(input('Digite a nota nº 1: '))
nota2 = float(input('Digite a nota nº 2: '))
nota3 = float(input('Digite a nota nº 3: '))
media = (nota1 + nota2 + nota3) / 3
if media < 7:
situacao = 'Reprovado'
elif media >= 7 and media < 10:
situacao = 'Aprovado'
else:
situacao = 'Aprovado com distinção'
print(
f'******* RESULTADO *******\n\n'
f'Notas: \n'
f'1º: {nota1}\n'
f'2º: {nota2}\n'
f'3ª: {nota3}\n'
'------------\n'
f'Média final: {media} => ### {situacao} ###'
) | false |
87241a6f9b08a917b3c82ae8e8845d5e996910a2 | Nafisa-Tasneem/Problem-solving | /ex33.py | 664 | 4.28125 | 4 | # i = 0
# numbers = [] # taking an empty list
#
# while i < 6:
# print("At the top i is %d" % i)
# numbers.append(i)
#
# i = i + 1
# print("Numbers now: ", numbers)
# print("At the bottom i is %d" % i)
#
# print("the numbers: ") # loop shesh hole eta kaj korbe
#
# for num in numbers:
# print(num, end=" ")
def add_to_list(ip): # trying with fn
number = [] # array er name number
for i in range (0,ip + 1,2):
number.append(i)
print(number)
add_to_list(7)
def add_while(x,increment):
number = []
j = 0
while j <= x:
number.append(j)
j = j + increment
print(number)
add_while(8,2)
| false |
b1758431a04b340e14359484b767907d44ca54f2 | Tracer64/Homework_and_Other_Work_Done_from_Home | /dog03_(me).py | 947 | 4.34375 | 4 | class Dog:
""" This is the beginning of a class for the humble house dog """
def __init__(self, name):
self.name = name
def add_weight(self, weight):
self.weight = weight
x = Dog('One of my dogs name is Baxter. His weight was 101 until a week ago when it increased to 110.')
#x.name = "Baxter"
d = Dog('One of my other dogs name is Worf, his weight was 40, until today when within a two week period, he gained 9 more pounds of weight and his total was then 49 lb.')
#d.name = "Worf"
x.add_weight(101)
#x.add_weight(101)
d.add_weight(40)
#x.addweight(40)
print(d.name)
print(d.weight)
print(x.name)
print(x.weight)
d.add_weight(9)
#d.add_weight(9) will add 9 to the original function for weight set at 40 to set the current weight to 49
x = weight(101)
x.add_weight(9)
#x.add_weight(9) will add 9 to the original function for weight set at 101 to set the current weight to 110
| true |
f9644ab0f8cea59193dc2d4f3cc78c749f6f9950 | lucasguerra91/some-python | /Guia_Ejercicios/6/6_1.py | 1,499 | 4.25 | 4 | """
Ejercicio 6.8.1. Escribir funciones que dada una cadena de caracteres:
a) Imprima los dos primeros caracteres.
b) Imprima los tres últimos caracteres.
c) Imprima dicha cadena cada dos caracteres. Ej.: 'recta' debería imprimir 'rca'
d) Dicha cadena en sentido inverso. Ej.: 'hola mundo!' debe imprimir '!odnum aloh'
e) Imprima la cadena en un sentido y en sentido inverso. Ej: 'reflejo' imprime
'reflejoojelfer'
"""
def dos_primeros(c):
""" Recibe una cadena y nos devuelve los dos primeros caracteres de la misma"""
new_c1 = c[0:2]
return new_c1
def tres_ultimos(c2):
""" Recibe una cadena y nos devuelve los tres ultimos caracteres de la misma"""
new_c2 = c2[len(c2)-3:]
return new_c2
def salteando(c3):
""" Recibe una cadena y nos devuelve una nueva cadena salteando la anterior de 2 en 2"""
new_c3 = (c3[::2])
return new_c3
def inverso(c4):
""" Recibe una cadena y nos devuelve la misma invertida"""
new_c4 = c4[::-1]
return new_c4
def normal_inverso(c5):
""" Recibe una cadena y nos devuelve la misma cadena concatenada a su inverso"""
invertida = inverso(c5)
new_c5 = c5 + invertida
return new_c5
def inversa_clase(cadena):
cr = ''
for i in range(1, len(cadena)):
cr += cadena[-i]
print(cr)
cadena = input('Ingrese la cadena :')
print(dos_primeros(cadena))
print(tres_ultimos(cadena))
print(salteando(cadena))
print(inverso(cadena))
print(normal_inverso(cadena))
inversa_clase(cadena) | false |
9bf7bfa42927d268fe33f51e96286ca0b93ff3b6 | lucasguerra91/some-python | /Guia_Ejercicios/3/3_1.py | 853 | 4.15625 | 4 | """
a) que escriba la duracion en segundos de un intervalo dado en h m s
b) al reves
"""
def a_hms():
""" Dada una duracion entera en segundos
se la convierte a horas, minutos y segundos """
segundos = int(input('\nIngrese el intervalo expresado en segundos:'))
h = segundos // 3600
m = (segundos % 3600) // 60
s = (segundos % 3600) % 60
print('\nSu equivalente es {}:{}:{}'.format(h, m, s))
def a_segundos():
""" Transforma a segundos una medida de tiempo expresada en h, m y s"""
print('\nIngrese el intervalos expresado en hh:mm:ss')
horas = int(input('\nHoras:'))
minutos = int(input('\nMinutos:'))
segundos = int(input('\nSegundos:'))
convertido = int(3600 * horas + 60 * minutos + segundos)
print('\nSu equivalente es : {} segundos'.format(convertido))
a_hms()
a_segundos()
| false |
af8037882b5b9cd779f9d7cc0a06e7e7f6386acf | lucasguerra91/some-python | /src/exceptions.py | 1,043 | 4.15625 | 4 | try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by Zero!")
# Ejemplo de try dentro de divisiones
print("Give me two numbers, and i will divide them")
print("Enter 'q' to quit. ")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
if second_number == 'q':
break
try:
answer = float(first_number) / float(second_number)
except ZeroDivisionError:
print("You can't divide by Zero!")
else:
print(answer)
# Ejemplo de try para file not found
filename = 'alice.txt'
try:
with open(filename) as file_obj:
contents = file_obj.read()
except FileNotFoundError:
msg = "\n\nSorry, the file " + filename + " does not exist. "
print(msg)
else:
#Count the approximate number of words in the file
words = contents.split()
num_words = len(words)
print("The file " + filename + "has about " + str(num_words) + " words.")
# me quede en la pagina 204 | true |
5ebde3ef036c975d77eb76fb41090184a4cd8eaf | lucasguerra91/some-python | /Apunte_Teorico/Capitulo_14/objetos.py | 1,493 | 4.40625 | 4 | class Punto:
"""
Representacion de un punto en un plano de coordenadas cartesianas (x, y)
"""
def __init__(self, x, y):
""" Constructor del punto """
self.x = validar_numero(x)
self.y = validar_numero(y)
def distancia(self, otro):
return self.restar(otro).norma()
def restar(self, otro):
"""Devuelve el Punto que resulta de la resta
entre dos puntos."""
return Punto(self.x - otro.x, self.y - otro.y)
def norma(self):
"""Devuelve la norma del vector que va desde el origen
hasta el punto. """
return (self.x * self.x + self.y * self.y) ** 0.5
def __str__(self):
return f"({self.x},{self.y})"
def __repr__(self):
"""Devuelve la representación formal del Punto como
cadena de texto."""
return "Punto({}, {})".format(self.x, self.y)
def __add__(self, otro):
"""Devuelve la suma de ambos puntos."""
return Punto(self.x + otro.x, self.y + otro.y)
def __sub__(self, otro):
"""Devuelve la resta de ambos puntos."""
return Punto(self.x - otro.x, self.y - otro.y)
def validar_numero(valor):
if not isinstance(valor, (int, float, complex)):
raise TypeError(f"{valor} no es un valor numerico")
return valor
# Ejecucion
punto = Punto(5, 7)
print(type(punto))
punto1 = Punto(10, 3)
print(type(punto1))
print(punto.distancia(punto1))
print(punto.norma())
print(punto)
print(repr(punto)) | false |
fa42264fb9c20eb2e0ba9f43d0387a60569f2a36 | lucasguerra91/some-python | /Parcialitos/Tercero/reducir_cola.py | 1,378 | 4.40625 | 4 | class Cola:
"""Representa a una cola, con operaciones de encolar y
desencolar. El primero en ser encolado es también el primero
en ser desencolado."""
def __init__(self):
""" Crea una cola vacia """
self.items = []
def __str__(self):
return str(self.items)
def encolar(self, x):
""" Encola el elemento x """
self.items.append(x)
def desencolar(self):
""" Elimina el primer elemento de la cola y devuelve su valor,
Si la cola esta vacía, levanta ValueError """
if self.esta_vacia():
raise ValueError("La cola esta vacía.")
return self.items.pop(0)
def esta_vacia(self):
""" Devuelve True si la cola esta vacía, False si no """
return len(self.items) == 0
def reducir(cola, funcion):
"""
:param cola:
:param funcion:
:return:
"""
if cola.esta_vacia():
return
try:
while not cola.esta_vacia():
a = cola.desencolar()
b = cola.desencolar()
c = funcion(a, b)
cola.encolar(c)
except:
return a
def suma(a, b):
return a + b
# test
cola1 = Cola()
cola1.encolar(1)
cola1.encolar(1)
cola1.encolar(1)
cola1.encolar(1)
cola1.encolar(1)
cola1.encolar(1)
cola1.encolar(1)
cola1.encolar(1)
print(cola1)
print(reducir(cola1, suma)) | false |
94cebb745ec38f5855034cb4a5dc05fcaed72f58 | TheWhiteOrao/CPC | /CPC_ROL_PIT_YAW/Control_Penta_Copter/Led_Control.py | 900 | 4.28125 | 4 | from N2.leds import Led()
# LED Control, can be used to turn on the led in one color and visualize that the program is running
# Static LED, can be used to turn on the led in one color
# Looping LED, can be used to visualize that the program is running, through the flashing LED in different colors
led = Led()
loop_counter = 0
def static_LED(set_first_color):
led.setColor(set_first_color)
def looping_LED(set_first_color, set_second_color, set_interval=200):
global loop_counter
if loop_counter > set_interval * 2:
loop_counter = 0
if loop_counter < set_interval:
led.setColor(set_first_color)
if loop_counter >= set_interval and loop_counter < set_interval * 2:
led.setColor(set_second_color)
loop_counter += 1
if __name__ == '__main__':
for i in range(1400):
looping_LED("Black", "Cyan", 100)
static_LED("Magenta")
| true |
d7db6e925921b64c2ba95a6e8355854ab019b594 | xrlie/pirple_python | /homeworks/homework_5/main.py | 2,502 | 4.40625 | 4 | # # # # # # # # # # # # # # # # # # # # # # #
# Homework Assignment #5: Basic Loops #
# # # # # # # # # # # # # # # # # # # # # # #
"""
You're about to do an assignment called "Fizz Buzz", which is one of the
classic programming challenges. It is a favorite for interviewers, and a
shocking number of job-applicants can't get it right. But you won't be one
of those people. Here are the rules for the assignment (as specified by
Imran Gory):
Write a program that prints the numbers from 1 to 100.
But for multiples of three print "Fizz" instead of the number and
for the multiples of five print "Buzz".
For numbers which are multiples of both three and five print "FizzBuzz".
For extra credit, instead of only printing "fizz", "buzz", and "fizzbuzz",
add a fourth print statement: "prime". You should print this whenever you
encounter a number that is prime (divisible only by itself and one).
As you implement this, don't worry about the efficiency of the algorithm
you use to check for primes. It's okay for it to be slow.
"""
# First part of the homework:
# I used a for to print all the numbers from 1 to 100
for number in range(1,101):
# First we check if the number is divisible by 3 and 5
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
# Second, if the previous condition wasn't fulfilled, we check if it is only divisible by 3
elif number % 3 == 0:
print("Fizz")
# Third, if the previous condition wasn't fulfilled, we check if it is only divisible by 5
elif number % 5 == 0:
print("Buzz")
# Fourth, if none of the previous condition was fulfilled, then we just print the number.
else:
print(number)
### Extra credit
# I define a function to check if the number is prime or not comparing it with the first 100 numbers
def is_prime(number):
counter = 0
for divisor in range (1,101):
if counter == 3:
break
else:
if number >= divisor :
if number % divisor == 0:
counter += 1
else:
continue
else:
continue
if counter == 1 or counter == 3:
return False
else:
return True
# Then I use the same code from the first part of this homework just that I add the new function in the loop.
for number in range(1,101):
if is_prime(number):
print("prime")
else:
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
else:
print(number) | true |
c5d459f27a9b6dd1a9e77d2af54d8dfb4ee1beed | jovanimtzrico/DSANanodegree | /Arrays and Linked Lists/flattening_a_nested_linked_list.py | 2,867 | 4.125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class LinkedList:
def __init__(self, head):
self.head = head
def append(self, value):
if self.head is None:
self.head = Node(value)
return
node = self.head
while node.next is not None:
node = node.next
node.next = Node(value)
def merge(list1, list2):
# TODO: Implement this function so that it merges the two linked lists in a single, sorted linked list.
merged = LinkedList(None)
if list1 is None:
return list2
if list2 is None:
return list1
list1_node = list1.head
list2_node = list2.head
while list1_node or list2_node:
if list1_node is None:
merged.append(list2_node.value)
list2_node = list2_node.next
elif list2_node is None:
merged.append(list1_node.value)
list1_node = list1_node.next
elif list1_node.value <= list2_node.value:
merged.append(list1_node.value)
list1_node = list1_node.next
else:
merged.append(list2_node.value)
list2_node = list2_node.next
return merged
class NestedLinkedList(LinkedList):
def flatten(self):
# TODO: Implement this method to flatten the linked list in ascending sorted order.
return self.do_flatten(self.head)
pass
def do_flatten(self, node):
if node.next is None:
return merge(node.value, None)
return merge(node.value, self.do_flatten(node.next))
# First Test scenario
linked_list = LinkedList(Node(1))
linked_list.append(3)
linked_list.append(5)
nested_linked_list = NestedLinkedList(Node(linked_list))
second_linked_list = LinkedList(Node(2))
second_linked_list.append(4)
nested_linked_list.append(second_linked_list)
presolution = nested_linked_list.flatten()
solution = []
node = presolution.head
print("This will print 1 2 3 4 5")
while node is not None:
#This will print 1 2 3 4 5
print(node.value)
solution.append(node.value)
node = node.next
assert solution == [1,2,3,4,5]
# Second Test Scenario
linked_list = LinkedList(Node(1))
linked_list.append(3)
linked_list.append(5)
second_linked_list = LinkedList(Node(2))
second_linked_list.append(4)
merged = merge(linked_list, second_linked_list)
node = merged.head
print("\nThis will print 1 2 3 4 5")
while node is not None:
#This will print 1 2 3 4 5
print(node.value)
node = node.next
# Lets make sure it works with a None list
merged = merge(None, linked_list)
node = merged.head
print("\nThis will print 1 3 5")
while node is not None:
#This will print 1 3 5
print(node.value)
node = node.next
| true |
abe84ba22cd9f1c6e65d1699d36f382dadffb5f5 | jovanimtzrico/DSANanodegree | /Arrays and Linked Lists/even_after_odd.py | 2,725 | 4.40625 | 4 | # Problem Statement
# Given a linked list with integer data, arrange the elements in such a manner that all nodes with even numbers are placed after odd numbers. Do not create any new nodes and avoid using any other data structure. The relative order of even and odd elements must not change.
# Example:
# linked list = 1 2 3 4 5 6
# output = 1 3 5 2 4 6
class Node:
def __init__(self, data):
self.data = data
self.next = None
def even_after_odd(head):
"""
:param - head - head of linked list
return - updated list with all even elements are odd elements
"""
current_node = head
odd_node = None
if current_node.data % 2 != 0:
odd_node = current_node
previus_node = current_node
current_node = current_node.next
while current_node:
if current_node.data % 2 != 0:
if odd_node is None:
odd_node = current_node
else:
temp_node = current_node.next
previus_node.next = current_node.next
current_node.next = odd_node.next
odd_node.next = current_node
odd_node = odd_node.next
current_node = odd_node
previus_node = current_node
current_node = current_node.next
return head
# helper functions for testing purpose
def create_linked_list(arr):
if len(arr)==0:
return None
head = Node(arr[0])
tail = head
for data in arr[1:]:
tail.next = Node(data)
tail = tail.next
return head
def print_linked_list(head):
while head:
print(head.data, end=' ')
head = head.next
print()
def test_function(test_case):
head = test_case[0]
solution = test_case[1]
node_tracker = dict({})
node_tracker['nodes'] = list()
temp = head
while temp:
node_tracker['nodes'].append(temp)
temp = temp.next
head = even_after_odd(head)
temp = head
index = 0
try:
while temp:
if temp.data != solution[index] or temp not in node_tracker['nodes']:
print("Fail")
return
temp = temp.next
index += 1
print("Pass")
except Exception as e:
print("Fail")
#Test 1
arr = [1, 2, 3, 4, 5, 6]
solution = [1, 3, 5, 2, 4, 6]
head = create_linked_list(arr)
test_case = [head, solution]
test_function(test_case)
#Test 2
arr = [1, 3, 5, 7]
solution = [1, 3, 5, 7]
head = create_linked_list(arr)
test_case = [head, solution]
test_function(test_case)
#Test 3
arr = [2, 4, 6, 8]
solution = [2, 4, 6, 8]
head = create_linked_list(arr)
test_case = [head, solution]
test_function(test_case)
| true |
2b4711c09d1466697b59315227bc4bb89f1219c2 | jovanimtzrico/DSANanodegree | /Arrays and Linked Lists/linked_list.py | 1,576 | 4.1875 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
def print_list_nodes(head):
current_node = head
while current_node is not None:
print(current_node.value)
current_node = current_node.next
def create_linked_list(input_list):
"""
Function to create a linked list
@param input_list: a list of integers
@return: head node of the linked list
"""
head = None
current = None
for value in input_list:
if head is None:
head = Node(value)
current = head
else:
current.next = Node(value)
current = current.next
return head
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
if self.head is None:
self.head = Node(value)
return
# Move to the tail (the last node)
node = self.head
while node.next:
node = node.next
node.next = Node(value)
return
def to_list(self):
# TODO: Write function to turn Linked List into Python List
list_nodes = []
current_node = self.head
while current_node:
list_nodes.append(current_node.value)
current_node = current_node.next
return list_nodes
linked_list = LinkedList()
linked_list.append(3)
linked_list.append(2)
linked_list.append(-1)
linked_list.append(0.2)
print ("Pass" if (linked_list.to_list() == [3, 2, -1, 0.2]) else "Fail")
| true |
e3c2bab780f67febdca1242f3bcb7afcc6db7b2c | Hupeng7/pythondemo | /coredemo/py3/demo2.py | 1,669 | 4.34375 | 4 | #!/usr/bin/python3
# Python3 基础语法
# 数字(Number)类型
'''
python中数字有四种类型:整数、布尔型、浮点数和复数。
int (整数), 如 1, 只有一种整数类型 int,表示为长整型,没有 python2 中的 Long。
bool (布尔), 如 True。
float (浮点数), 如 1.23、3E-2
complex (复数), 如 1 + 2j、 1.1 + 2.2j
'''
# 字符串(String)
'''
python中单引号和双引号使用完全相同。
使用三引号(\''' 或 """)可以指定一个多行字符串。
转义符 \
反斜杠可以用来转义,使用r可以让反斜杠不发生转义。。 如 r"this is a line with \n" 则\n会显示,并不是换行。
按字面意义级联字符串,如"this " "is " "string"会被自动转换为this is string。
字符串可以用 + 运算符连接在一起,用 * 运算符重复。
Python 中的字符串有两种索引方式,从左往右以 0 开始,从右往左以 -1 开始。
Python中的字符串不能改变。
Python 没有单独的字符类型,一个字符就是长度为 1 的字符串。
字符串的截取的语法格式如下:变量[头下标:尾下标:步长]
'''
str = '123456789'
print(str)
print(str[0:-1])
print(str[0])
print(str[2:5])
print(str[2:])
print(str[1:5:2])
print(str * 2)
print(str + '你好')
# 等待用户输入
# input("\n\n按下 enter 键后退出。")
# 同一行显示多条语句
import sys;
x = 'hello';
sys.stdout.write(x + '\n')
# print 输出
# print 默认输出是换行的,如果要实现不换行需要在变量末尾加上 end="":
x = "a"
y = "b"
# 换行输出
print(x)
print(y)
print('--------')
# 不换行输出
print(x, end=" ")
print(y, end=" ")
print()
| false |
a8347e1b8482e05ac03759fa9e65c3410bd309fe | Hupeng7/pythondemo | /coredemo/py3/demo1.py | 902 | 4.1875 | 4 | #!/usr/bin/python3
'''
注释
Python中单行注释以 # 开头,
多行注释可以用多个 # 号,还有 \''' 和 """:
'''
# 第一个注释
print("Hello,Python!") # 第二个注释
# 第一个注释
# 第二个注释
'''
第三个注释
第四个注释
'''
"""
第五个注释
第六个注释
"""
print("Hello,Python!again")
'''
行与缩进
python最具特色的就是使用缩进来表示代码块,不需要使用大括号 {} 。
缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数。实例如下:
'''
if True:
print("True")
else:
print("False")
'''
多行语句
Python 通常是一行写完一条语句,但如果语句很长,我们可以使用反斜杠 \ 来实现多行语句,例如:
'''
item_one = 'a'
item_two = 'b'
item_three = 'c'
total = item_one + \
item_two + \
item_three
print(total)
| false |
8d2a0d749479acd79f1840da058387352d5c8eb0 | devqueue/python-exercises | /program5/program5.py | 225 | 4.28125 | 4 | '''
Write a Python program to read a text file line by line and display each word seperated by a #.
'''
with open('story.txt', 'r') as f:
for line in f:
for word in line.split():
print(word, end="#")
| true |
6bbec674b71b85f6c9e7b44fe27e1d03838fe42b | devqueue/python-exercises | /program3/program3.py | 210 | 4.21875 | 4 | '''
Write a Python program to read a text file ( story.txt) line by line and print it.
'''
story = "story.txt"
with open(story, "r") as f:
lines = f.readlines()
for line in lines:
print(line)
| true |
5ed67926f1abc5a7b688422b739b4f511de4849c | mgiolando/SoftwareDesign | /chap12/anagram_sets.py | 1,188 | 4.34375 | 4 | def letters(word):
"""This section sorts a string by the letters that make it up and returns them as a string.
word: string
returns: string
"""
l=list(word)
l.sort()
l=''.join(l)
return l
def anagram_dict():
"""Creates a dictionary of all anagrams by the letters that make them up
returns: dict
"""
d={}
fin=open('words.txt')
for line in fin:
entry=line.strip().lower()
l=letters(entry)
if l not in d:
d[l]=[entry]
else:
d[l].append(entry)
return d
def print_anagram_dict():
"""Prints all anagrams as created by a dictionary.
"""
for vals in d.values():
print vals
def largest_anagram(d):
""" Sorts a dictionary by the size of the length of their key
d: dict
returns: list
"""
t=[]
for vals in d.values():
t.append((len(vals),vals))
t.sort(reverse=True)
return t
def bingo(d):
"""Returns the set of letters that allow for the most bingo wins.
d: dict
returns: string
"""
res=[]
for key, value in d.iteritems():
if len(key)==8:
res.append((len(value),key))
res.sort(reverse=True)
num,letters =res[0]
return letters
if __name__ == '__main__':
d=anagram_dict()
print_anagram_dict()
print largest_anagram(d)
print bingo(d)
| true |
ea5a817023695c4b6ebdef1269425657e57f6559 | RadoslawNowak3/PythonUni | /Set4/4.3.py | 218 | 4.1875 | 4 | def factorial(n):
result=1
if n==0 or n==1:
return result
else:
for i in range(2,n+1):
result*=i
return result
factor = int(input("Input factor: "))
print(factorial(factor)) | true |
aa52ce62acafeaec8378e55d9d663f66431934b3 | pszals/lpthw | /Dropbox/Programming/ex6.py | 1,304 | 4.375 | 4 | # Defines variable x as a phrase, inserts a number inside of phrase via format character %d,
# which can be used for numbers but not text
x = "There are %d types of people." % 10
# Defines variable binary
binary = "binary"
# Defines variable do_not as a contraction
do_not = "don't"
# Defines variable y as phrase with two format characters,
# then lists them to the right using open parentheses, variable, separating comma,
# second variable, closed parentheses
y = "Those who know %s and those who %s." % (binary, do_not)
# Prints previously defined variable "x"
print x
# Prints previously defined variable "y"
print y
# Prints phrase string exactly x, which includes single quotation
print "I said: %r." % x
# Prints phrase string y
print "I also said: '%s'." % y
# Defines new variable 'hilarious' as False
hilarious = False
# Defines new variable as a string with a format character %r, print exactly this
joke_evaluation = "Isn't that joke so funny?! %r"
# Prints variable, defines variable hilarious as that which will substitute for the %r
# format character in string
print joke_evaluation % hilarious
# Defines new string variable
w = "This is the left side of..."
# Defines new string variable
e = "a string with a right side."
# Prints two strings, combining them with a plus
print w + e
| true |
4aff897503452f585f8acd452ea29589f824e420 | pszals/lpthw | /Dropbox/Programming/ex20.py | 1,781 | 4.5625 | 5 | # We import our 'argv' function from sys
from sys import argv
# Here we name the two variables for 'argv'
script, input_file = argv
# Define 1st function with one variable that takes the 'f' from below
def print_all(f):
# Reads file 'f' and puts it into the print_all() function
print f.read()
# Defines 2nd function, again with only one variable taking from below
def rewind(f):
# Seeks to the beginning of the 'f' file
f.seek(0)
# Defines 3rd function, this time with two variables
def print_a_line(line_count, f):
# Takes line_count (user-inputed variable) and the current line
# being read, and inputs into the 'print_a_line' function
print line_count, f.readline()
# Defines variable 'current_file' as the opening of the user-inputed file
current_file = open(input_file)
# Displays text with a new line after it
print "First let's print the whole file:\n"
# Uses function 'print_all' that reads and displays the user-inputed file
print_all(current_file)
# Displays another line of text
print "Now let's rewind, kind of like a tape."
# Uses the rewind function 'rewind' to put the reader at the beginning of the file
rewind(current_file)
# Displays more text
print "Let's print three lines:"
# Assigns 'current_line' variable value of 1 to the line count
current_line = 1
# Calls function 'print_a_line' and gives two variables
print_a_line(current_line, current_file)
# Assigns 'current_line' the value of the former 'current_line' plus 1
current_line += 1
# Calls function 'print_a-line' and gives two variables
# (The current_file opens the inputed file)
print_a_line(current_line, current_file)
# x += y works as x = x + y
# adds 1 to current line and defines current line variable at the same time
current_line += 1
print_a_line(current_line, current_file) | true |
6ba9140f831f4434f00a61047aabc14d49b93636 | gotoc/hc180-udemy-ultimate-python | /chapter11/chap11ex2.py | 338 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" chap11ex2.py - Chapter 11, Exercise 2 """
def fact(number):
""" computes the factorial of a number """
product = 1
for i in range(1, number+1):
product *= i
return product
print 'Enter a number: '
NUM = int(input())
print str(NUM) + '! equals ' + str(fact(NUM))
| true |
d4af84c0ddd076d37ab88b017a2008cf3d07c478 | pr0PM/c2py | /1.py | 904 | 4.21875 | 4 | # Write a program that accepts the marks of 5 subjects and
#find the sum and percentage obtained by the student.
print('________Marks Calculator_______')
print('Enter the max. marks possible in a subject:')
w = int(input())
print('Enter the marks of the following subjects:')
a = int(input('Maths:'))
b = int(input('English:'))
c = int(input('Physics:'))
d = int(input('Chemistry:'))
e = int(input('Computer Science:'))
# SUM
q = a+b+c+d+e
#PERCENT
p = q/(5*w)*100
print('_________')
print('Sum :' + str(q) + ' marks out of' + str(w*5) )
print('Percent : '+str(round(p,5))+' %')
#####################################
# To add funtionality
# 1 Check the input to be under the max marks limit
# 2 Take the subjects to be input
# 3 Verify the sum and percentage to be under the maximum limit
# 4 Check for the input max marks not to be zero so that we can keep a check on the ZeroDivisionError
# 5
| true |
b8a99ff603f8a746599ed19bf715175ed24bc2a7 | RafaelaHenemann/Curso-Python-Mundo-1 | /Desafios/ex009_tabuada.py | 784 | 4.28125 | 4 | # Faça um programa que leia um número inteiro qualquer e mostre sua tabuada.
num = int(input('Digite um número para ver sua tabuada: '))
print('-' * 12)
print('{} x {:2} = {}'.format(num, 1, num*1))
print('{} x {:2} = {}'.format(num, 2, num*2))
print('{} x {:2} = {}'.format(num, 3, num*3))
print('{} x {:2} = {}'.format(num, 4, num*4))
print('{} x {:2} = {}'.format(num, 5, num*5))
print('{} x {:2} = {}'.format(num, 6, num*6))
print('{} x {:2} = {}'.format(num, 7, num*7))
print('{} x {:2} = {}'.format(num, 8, num*8))
print('{} x {:2} = {}'.format(num, 9, num*9))
print('{} x {:2} = {}'.format(num, 10, num*10))
print('-' * 12)
# O código das linhas 3 e 14 insere linhas no terminal;
# O :2 nas linhas da tabuada definem dois dígitos para que todas as linhas fiquem alinhadas; | false |
f06d9c608a386b68774ba6a4bb450cfe030aac30 | pushker-git/LeetCodeTopInterviewQuestions | /Codesignal and Geekforgeeks Combined/sortZeroOneTwoList.py | 1,490 | 4.15625 | 4 | Note: Try to solve this task in linear time, since this is what you'll be asked to do during an interview.
Given a singly linked list consisting only of 0, 1, and 2, return it sorted in ascending order.
Example
For l = [2, 1, 0], the output should be
sortZeroOneTwoList(l) = [0, 1, 2];
For l = [0, 1, 0, 1, 2, 0], the output should be
sortZeroOneTwoList(l) = [0, 0, 0, 1, 1, 2].
Solution:
# Singly-linked lists are already defined with this interface:
# class ListNode(object):
# def __init__(self, x):
# self.value = x
# self.next = None
#
def sortZeroOneTwoList(head):
if head == None or head.next == None:
return head
# 1. Create three nodes
zeroD = ListNode(0)
oneD = ListNode(0)
twoD = ListNode(0)
zero = zeroD
one = oneD
two = twoD
current = head
while(current):
# If we find value zero move to zero, if 1 move to one , if 2 move to two
if current.value == 0:
zero.next = current
zero = zero.next
current = current.next
elif current.value == 1:
one.next = current
one = one.next
current = current.next
else:
two.next = current
two = two.next
current = current.next
# Attach three node
if (oneD.next):
zero.next = oneD.next
else:
zero.next = twoD.next
one.next = twoD.next
two.next = None
head = zeroD.next
return head
| true |
4d751fc83bae20100670b0037d8c03faead7de3b | pushker-git/LeetCodeTopInterviewQuestions | /AugustDailyChallenge/15_Non_OverLapping_Intervals.py | 1,581 | 4.21875 | 4 | Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Example 3:
Input: [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
Note:
You may assume the interval's end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
Solution:1
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
if not intervals:
return 0
intervals.sort(key=lambda x: x[1])
end = intervals[0][0]
rmCount = 0
for s, e in intervals:
if s >= end:
end = e
else:
rmCount += 1
return rmCount
Solution: 2
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
if intervals == []:
return 0
intervals.sort(key = lambda x:x[1])
remove = 0
end = intervals[0][0]
for times in intervals:
start = times[0]
if start < end:
remove += 1
else:
end = times[1]
return remove
| true |
5e954ed1b9c613a9249ae03ef2a99af396a7c39d | pushker-git/LeetCodeTopInterviewQuestions | /Codesignal and Geekforgeeks Combined/findProfession.py | 1,151 | 4.125 | 4 | Consider a special family of Engineers and Doctors. This family has the following rules:
Everybody has two children.
The first child of an Engineer is an Engineer and the second child is a Doctor.
The first child of a Doctor is a Doctor and the second child is an Engineer.
All generations of Doctors and Engineers start with an Engineer.
We can represent the situation using this diagram:
E
/ \
E D
/ \ / \
E D D E
/ \ / \ / \ / \
E D D E D E E D
Given the level and position of a person in the ancestor tree above, find the profession of the person.
Note: in this tree first child is considered as left child, second - as right.
Example
For level = 3 and pos = 3, the output should be
findProfession(level, pos) = "Doctor".
Solution:
def findProfession(level, pos):
if level == 1:
return "Engineer"
if (findProfession(level-1, (pos+1)//2) == "Doctor"):
if pos % 2:
return "Doctor"
return "Engineer"
if pos % 2:
return "Engineer"
return "Doctor"
| true |
4c83a14e04c8c02cfbdd46955dd4016282201d72 | bstraa/dsp | /python/q8_parsing.py | 949 | 4.375 | 4 | #The football.csv file contains the results from the English Premier League.
# The columns labeled 'Goals' and 'Goals Allowed' contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in 'for' and 'against' goals.
import csv
import pandas as pd
def read_data(data):
# COMPLETE THIS FUNCTION
with open(data) as f:
f = pd.read_csv(f)
f['Difference'] = f['Goals'] - f['Goals Allowed']
ff = f.loc[f['Difference'].idxmax()]
print(ff[0])
#def get_min_score_difference(self, parsed_data):
# COMPLETE THIS FUNCTION
#def get_team(self, index_value, parsed_data):
# COMPLETE THIS FUNCTION
def main():
input = 'football.csv'
read_data(input)
if __name__ == '__main__':
main()
| true |
f902fe50bdb39a68593f54f421f8122634b1320c | KyleWalkerley/Python_Bible | /cinema.py | 611 | 4.125 | 4 | movies = {
"Fourius 9":[18,8],
"Spiderman":[13,12],
"Borat":[16,4],
"Ben 10":[3,24]
}
while True:
choice = input("What movie do you want to watch today?: ").strip()
if choice in movies:
age = int(input("Please enter your age here.").strip())
#Check user age
if age >= movies[choice][0]:
#check seats available
if movies[choice][1]>0:
print("Welcome and enjoy!")
movies[choice][1] = movies[choice][1] -1
else:
print("Sorry we are sold out.")
else:
print("You are too young for the film.")
else:
print("We are not showing that movie currently.") | true |
a2c1de1e3c5b473c25560e45c802d9c1d2f22f45 | mlennon3/Learn-Python-The-Hard-Way | /ex15.py | 659 | 4.28125 | 4 | #grabs arguments from terminal input
#from sys import argv
#there will be two arguments, script and filename
#script, filename = argv
#the variable txt is the opened file given into terminal
#txt = open(filename)
# prints the name of the file
#print "Here's your file %r:" %filename
#reads the open file in the variable txt, prints it
#print txt.read()
print "Type the filename again:"
#makes new variable file_again, which is filled from raw_input
file_again = raw_input("> ")
#txt_again is the opened file typed into on line 17
txt_again = open(file_again)
#reads and prints the file given by user on line 18
print txt_again.read()
txt_again.close()
| true |
a1ca2e1d8ac07365431ec2bbc79dd28da1b885b1 | willzhaoy/reporting-with-python | /samples/rps.py | 1,379 | 4.15625 | 4 | """
This is a simple script intended to test your comprehension--I don't expect you to write it, so it does use some features that we haven't talked about in class, but you should be able to read it and figure out what's going on.
Please annotate it with comments for each line (comments are lines starting with a # character) that explain what the script is doing. When in doubt, err on the side of verbosity.
Note: this script is actually broken in a non-obvious way! It will run, but it will end up with incorrect results. Can you figure out why? If you can figure out the error, either fix it in place or leave a comment at the end describing the bug.
"""
import random
player_one = 0
player_two = 0
choices = ["rock", "paper", "scissors"]
while player_one + player_two < 3:
p1 = random.choice(choices)
p2 = random.choice(choices)
print("Player one chose:" + p1)
print("Player two chose:" + p2)
if (p1 == "rock" and p2 == "scissors") or (p1 == "paper" and p2 == "rock") or (p1 == "scissors" and p2 == "paper"):
print("Player one scores a point.")
player_one = player_one + 1
else:
print("Player two scores a point.")
player_two = player_two + 1
print("Current score: " + str(player_one) + " vs " + str(player_two))
if player_one > player_two:
print("Player one wins!")
else:
print("Player two wins!") | true |
4737039e75504df1ca3b3e988832b6cc73accc49 | frey-norden/py4e | /ex_05_02.py | 544 | 4.15625 | 4 | #!/usr/bin/env python3
# File: ex_05_02.py
# takes a series of numbers from input and returns
# max and min values
max = None
min = None
num = 0
total = 0.0
while True :
val = input('Enter a number: ')
if val == 'done' :
break
try:
val = int(val)
except:
print('Invalid input')
continue
if min is None :
min = val
elif val < min :
min = val
if max is None :
max = val
elif val > max :
max = val
print('Maximum is', max)
print('Minimum is', min)
| true |
3c4c84f429e81518cd15d17df64780a827b4ff87 | hendry33/programming_practice | /week05/week05_4.py | 1,186 | 4.21875 | 4 | """Напишите функцию, которая на вход принимает квадратную матрицу (например, в виде списка списков).
Вычисляет сумму элементов главной или побочной диагонали в зависимости от выбора пользователя.
Сумма элементов любой диагонали должна вычисляться в одной и той же отдельной функции"""
# первая строка ввода - это количество строк массива
def main():
n = int(input("Dimension of matrix: "))
print("Enter matrix: ")
a = []
for i in range(n):
row = input().split()
for i in range(n):
row[i] = int(row[i])
a.append(row)
traceq = input("main trace/side trace: ")
if traceq == 'main trace':
trace(0, 1, n, a)
if traceq == 'side trace':
trace(n - 1, -1, n, a)
def trace(k, p, n, a):
sum = 0
for t in range(n):
sum += a[k + p * t][t]
print(sum)
if __name__== "__main__":
main() | false |
0d53f669cbf18ce8d9a4e97c62bcde7bc6419595 | vlb19/CMEECourseWork | /Week2/code/lc2.py | 2,224 | 4.625 | 5 | #!/usr/bin/env python3
""" Use a list comprehension to create a list of month,
rainfall tuples where the amount of rain was greater than 100 mm.
Then use a list comprehension to create a list of just month names where the
amount of rain was less than 50 mm. Then do it all again using
conventional loops"""
# Average UK Rainfall (mm) for 1910 by month
# http://www.metoffice.gov.uk/climate/uk/datasets
rainfall = (('JAN',111.4),
('FEB',126.1),
('MAR', 49.9),
('APR', 95.3),
('MAY', 71.8),
('JUN', 70.2),
('JUL', 97.1),
('AUG',140.2),
('SEP', 27.0),
('OCT', 89.4),
('NOV',128.4),
('DEC',142.2),
)
# 1) Create list of month, rainfall tuples where
# the amount of rain is greater than 100mm
print ("Months where rainfall exceeded 100 mm") #tells the user what to expect
Months_above_100 = [row[0] for row in rainfall if row[1] > 100]
Values_above_100 = [row[1] for row in rainfall if row[1] > 100]
print (Months_above_100 + Values_above_100)
# 2) A a list of just month names where the
# amount of rain was less than 50 mm.
print ("Months where rainfall was less than 50 mm") #tells the user what to expect
Months_below_50 = [row[0] for row in rainfall if row[1] < 50]
Values_below_50 = [row[1] for row in rainfall if row[1] < 50]
print (Months_below_50 + Values_below_50)
# (3) Now do (1) and (2) using conventional loops (you can choose to do
# this before 1 and 2 !).
For_Month_above_100 = [] #creates new empty dictionary
for row in rainfall: #searches each value in rainfall
if row[1] > 100: #if the second column value is larger than 100
For_Month_above_100.append(row[0]) #add the corresponding month to the dictionary
For_Month_above_100.append(row[1]) #and add the rainfall value
print ("Months where rainfall exceeded 100 mm") #tells the user what to expect
print (For_Month_above_100) #prints dictionary
For_Month_below_50 = []
for row in rainfall:
if row[1] < 50:
For_Month_below_50.append(row[0])
For_Month_below_50.append(row[1])
print ("Months where rainfall was less than 50 mm")
print (For_Month_below_50)
| true |
6c4938c32e35a509f657dec16f0350483fe44980 | vlb19/CMEECourseWork | /Week2/code/tuple.py | 1,015 | 4.25 | 4 | #!/usr/bin/env python3
# Author: Victoria Blanchard vlb19@imperial.ac.uk
# Script: tuple.py
# Date: 3 December 2019
""" Birds is a tuple of tuples of length three: latin name, common name, mass.
This is a script to print these on a separate line or output block by species """
# OUTPUT
# Prints latin name, common name, and mass of each individual within the
# dictionary on a separate line
### Dictionary of birds with latin name, common name, and mass
birds = ( ('Passerculus sandwichensis','Savannah sparrow',18.7),
('Delichon urbica','House martin',19),
('Junco phaeonotus','Yellow-eyed junco',19.5),
('Junco hyemalis','Dark-eyed junco',19.6),
('Tachycineata bicolor','Tree swallow',20.2),
)
print ("Information on birds in dictionary")
# print each piece of information in a separate output block
for birdinfo in birds:
print( "The latin name is: ", birdinfo[0])
print( "The common name is: ", birdinfo[1])
print( "The average species mass is: ", birdinfo[2], "\n")
| true |
00198dcbf7dd23ea0db438fe513a12d1acd29e49 | gzgdouru/python_study | /exercise/git_exercises/demo11.py | 629 | 4.125 | 4 | # 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights
def get_filtered_words():
return open("filtered_words.txt", "r", encoding="utf8").read()
def is_warning_word(word, filteredWords):
return (filteredWords.find(word) != -1)
if __name__ == "__main__":
filteredWords = get_filtered_words()
word = input("enter a word: ")
while word:
if is_warning_word(word, filteredWords):
print("Human Rights!")
else:
print("Freedom")
word = input("enter a word: ") | false |
b82e7c62ccbd433a59b771a053f9aa65d149f10f | gzgdouru/python_study | /fluentpython/chapter20/demo02.py | 715 | 4.15625 | 4 | '''
一个简单的描述符
'''
class Quantity:
def __init__(self, storage_name):
self.storage_name = storage_name
def __set__(self, instance, value):
if value > 0:
instance.__dict__[self.storage_name] = value
else:
raise TypeError("value must be > 0")
class LineItem:
weight = Quantity("weight")
price = Quantity("price")
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
if __name__ == "__main__":
truffle = LineItem("White truffy", 100, 1.34)
print(truffle.subtotal())
| true |
3210bb4d5a341e4f98c8b32230608441b7ede09d | featherko/epythopam | /homework/hw1/task3_minmax.py | 849 | 4.5625 | 5 | """Task 3.
Write down the function, which reads input line-by-line, and find maximum and minimum values.
Function should return a tuple with the max and min values.
For example for [1, 2, 3, 4, 5], function should return [1, 5]
We guarantee, that file exists and contains line-delimited integers.
To read file line-by-line you can use this snippet:
with open("some_file.txt") as fi:
for line in fi:
...
"""
from typing import Tuple
def find_maximum_and_minimum(file_name: str) -> Tuple[int, int]:
"""Find max and min.
Function that reads input line by line and then returns minimum and maximum values
:param file_name: Input file
:return: : Min, Max
"""
with open(file_name) as fi:
lines = fi.readlines()
lines = list(map(int, lines))
lines.sort()
return lines[0], lines[-1]
| true |
afce0a96d33a8791cc74cd9345128ab5239547ac | featherko/epythopam | /homework/hw4/task4_doctest.py | 2,097 | 4.46875 | 4 | """Task 4.
Write a function that takes a number N as an input and returns N FizzBuzz numbers*
Write a doctest for that function.
Write a detailed instruction how to run doctests**.
That how first steps for the instruction may look like:
- Install Python 3.8 (https://www.python.org/downloads/)
- Install pytest `pip install pytest`
- Clone the repository <path your repository>
- Checkout branch <your branch>
- Open terminal
- ...
Definition of done:
- function is created
- function is properly formatted
- function has doctests
- instructions how to run doctest with the pytest are provided
You will learn:
- the most common test task for developers
- how to write doctests
- how to run doctests
- how to write instructions
* https://en.wikipedia.org/wiki/Fizz_buzz
** Энциклопедия профессора Фортрана page 14, 15, "Робот Фортран, чисть картошку!"
"""
from typing import List
def fizzbuzz(n: int) -> List[str]:
"""Fb.
fizzbuss some numbers
:param n: numbers to fizzbuzz
:return: fizzbuzzed
>>> fizzbuzz(5)
['1', '2', 'fizz', '4', 'buzz']
>>> fizzbuzz(1)
['1']
"""
fb = []
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
fb.append("fizz buzz")
elif i % 3 == 0:
fb.append("fizz")
elif i % 5 == 0:
fb.append("buzz")
else:
fb.append(f"{i}")
return fb
""" - Install Python 3.8 (https://www.python.org/downloads/)
- Install pytest `pip install pytest`
- Clone the repository <path your repository>
- Checkout branch <your branch>
- Open file, in wich tested function is located
- Create docstring for tested function
- At the end of docstring press Enter twice
- Write down <function name>(arg), where function name - function to be tested
and arg - argument that should be used for test
- Press Enter
- Write down supposed output of tested function
- Press Enter
- Check that selected docstring quotes are closed
- Open terminal in IDE
- Write pytest, press Enter
"""
| true |
2a2aa1e14a8edf1ecad53bffdb43d3f180d831db | featherko/epythopam | /homework/hw2/task5.py | 1,338 | 4.125 | 4 | """Task 5.
Some of the functions have a bit cumbersome behavior when we deal with
positional and keyword arguments.
Write a function that accept any iterable of unique values and then
it behaves as range function:
import string
assert = custom_range(string.ascii_lowercase, 'g') == ['a', 'b', 'c', 'd', 'e', 'f']
assert = custom_range(string.ascii_lowercase, 'g', 'p') == ['g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']
assert = custom_range(string.ascii_lowercase, 'p', 'g', -2) == ['p', 'n', 'l', 'j', 'h']
"""
from typing import Any, List, Sequence
def custom_range(
iterable: Sequence, start: Any, stop: Any = None, step: int = 1
) -> List[Any]:
"""Customrange.
Function that behaves as range function with given iterable of unique values.
:param iterable: Given iterable
:param start: Optional. An integer number specifying at which position to start. Default is 0
:param stop: Required. An integer number specifying at which position to stop(not included)
:param step: Optional. An integer number specifying the incrementation. Default is 1
:return: returns a sequence
"""
if stop is None:
start, stop = iterable[0], start
if step < 0:
start, stop = stop, start
return [
iterable[i] for i in range(iterable.index(start), iterable.index(stop), step)
]
| true |
e610955100fdd37097f557e1fb27bf8ec5d19c70 | dfarfel/QA_Learning_1 | /Fuction_ex/function_task_1_9.py | 332 | 4.28125 | 4 | def check_age(age):
age_group=""
if 0<=age<=18:
age_group="Child"
elif 19<=age<=60:
age_group="Adult"
elif 61<=age<=120:
age_group="Senior"
else:
age_group="ERROR!"
return age_group
for i in range(5):
user_age=int(input("Enter your age: "))
print(check_age(user_age)) | false |
aee4be430b4a68bb7d0a734e2726cd0a0f98acc5 | dfarfel/QA_Learning_1 | /While/While_for_task2_7.py | 330 | 4.21875 | 4 | #dividing of float number without % and //
num_1=int(input("Enter first number: "))
num_2=int(input("Enter second number: "))
if num_1>num_2:
divide_num=num_1/num_2
print(f'Dividing dose is {int(divide_num)}')
print(f'Rest is {num_1-num_2*int(divide_num)}')
else:
print("First number must be bigger than second")
| true |
ade5f82dbe73f98cd2cbdafe8ca6417ee72b0a30 | dfarfel/QA_Learning_1 | /While/while_ex_4.py | 254 | 4.28125 | 4 | age=int(input("Please enter your age: "))
while 0<=age<=120:
if 0<=age<=18:
print("Child")
elif 19<=age<=60:
print("adult")
else:
print("senior")
age = int(input("Please enter your age: "))
print("Age is invalid")
| false |
3433dca8311f0aedc0e47c61eda434242423548f | elevin14/exercises | /clrs/chapter-02/2_2.py | 1,165 | 4.1875 | 4 | import math
# CLRS exercises from chapter 2.2
# 2.2-1
# n^3... is equivalent to theta(n^3)
# 2.2-2 selection sort.
# The loop invariant is that the array before the current index holds the x lowest items.
# It only needs to run for n-1 elements because the last element will be the largest by definition.
# Best case theta(n^2). Worst case theta(n^2)
def selection_sort(arr):
for j in range(0,len(arr)-1):
min_val = arr[j]
min_index = j
for i in range(j+1,len(arr)):
if arr[i] < min_val:
min_val = arr[i]
min_index = i
arr[min_index], arr[j] = arr[j], arr[min_index]
return arr
print(selection_sort([6,3,6,7,1,6]))
print(selection_sort([31,41,59,26,41,58]))
# 2.2-3
# For linear search, on average, it will take n/2 time to find the element. Worst case would be n (the entire array
# needs to be checked before the element is found, or the element is not in the array). Average and worst-case in theta
# notation are theta(n).
# 2.2-4
# Almost any algorithm can be modified to give a constant time return for a specific input. Thereby, that would be the
# best case run-time. | true |
a9671c144552f52047ec9010eac801fb4e0164eb | Andreya9520/Python-Essential- | /Clase3Ejercicio2 | 1,142 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 24 20:54:54 2021
@author: andreavergara
"""
# Create a list of the BRICS countries
country = [
"Brazil",
"Russia",
"India",
"China",
"South Africa"
]
"""Create a dictionary of BRICS capitals.
Note that South Africa has
3 capitals. Therefore, we embed a list inside
the dictionary.
"""
capitals = {
"Brazil": "Brasilia",
"Russia": "Moscow",
"India": "New Delhi",
"China": "Beijing",
"South Africa": [
"Pretoria",
"Cape Town",
"Bloemfontein"
]
}
# Print the list and dictionary
print( country) #habian comillas innecesarias
print( capitals)
"""
What response did you get?
Why did the list and dictionary
contents not print? Comillas extras
Fix the code and run the script again.
"""
print( capitals["South Africa"][1])
"""
Why did you get an error for the
2nd capital of South Africa? #me hacia falta un corchete
Hint: Check the syntax for the index value.
"""
| true |
753f724d47364cdc3ca6fdc4edf8a04c91e5856b | evagravin/p4-kangaroos | /TheSmack/minilabs/risa_minilab.py | 2,408 | 4.15625 | 4 | import math
class Calculations:
# Initializing
def __init__(self, num):
self._num = num
# Degrees Calculation (Celsius to Fahrenheit)
@property
def cel2far(self):
return round((self._num - 32) * 5 / 9, 2)
# Weight Calculation (Pounds to Grams)
@property
def lbs2g(self):
return round((self._num * 454), 2)
# Length Calculation (Yards to Meters)
@property
def y2m(self):
return round((self._num / 1.094), 2)
# Weight Calculation (Grams to Ounces)
@property
def g2oz(self):
return round((self._num / 28.35), 2)
# Weight Calculation (Kilograms to Pounds)
@property
def kg2lbs(self):
return round((self._num * 2.205), 2)
# Fibonacci Series
@property
def fibonacci(self):
# Initializing a list for the first two fibonacci numbers
list = [0, 1]
# Producing the nth number (self._num) in the fibonacci sequence
for r in range(2, self._num + 1):
list.append(list[r - 2] + list[r - 1])
# Returning the nth number in the fibonacci sequence
return list[self._num]
@property
def newton(self):
# Initializing variables for newton, math.sqrt is a function that runs through the math package
x = math.sqrt(self._num)
# Local variable, How many decimal points to calculate the square root to
limit = .0001
# To count the number of times the process would be repeated until a correct outcome is reached (iterations)
number = 0
# Loop continues until accuracy reaches limit
while True:
number += limit
# Keeps calculating answer until the accurate square root is found
answer = 0.5 * (x + (self._num / x))
# Testing if the answer-x is less than limit
if abs(answer - x) < limit:
break
# Updates answer
x = answer
# Returns the final answer
return answer
@property
def num(self):
return self._num
# Tester
if __name__ == "__main__":
calculations = Calculations(6)
print(f"{calculations.cel2far}")
print(f"{calculations.lbs2g}")
print(f"{calculations.y2m}")
print(f"{calculations.g2oz}")
print(f"{calculations.kg2lbs}")
print(f"{calculations.fibonacci}")
print(f"{calculations.newton}")
| false |
f65d75dc4da1e16977a68eaff0df2776f11cf5c6 | NithinGudala/python3_stuff | /py3_concepts/your_own_Iterator.py | 1,012 | 4.28125 | 4 | '''
how to create your own iter/Range function.
iterator.__iter__()
Return the iterator object itself. This is required to allow both containers and iterators
to be used with the for and in statements. This method corresponds to the tp_iter slot of the
type structure for Python objects in the Python/C API.
iterator.__next__()
Return the next item from the container. If there are no further items,raise the StopIteration exception.
This method corresponds to the tp_iternext slot of the type structure for Python objects in the Python/C API.
lets try to create our own range function with return x2(x*x) of the each element x
'''
class myRange():
def __init__(self,range):
self.range = range
def __iter__(self):
self.x = 0
return self
def __next__(self):
x= self.x
if x >self.range:
raise StopIteration
self.x = x+1
return x*x
for i in myRange(10):
print(i)
'''
O/P:
0
1
4
9
16
25
36
49
64
81
100
'''
| true |
fc354e1f13413171d1f5c4c2e0b46828f17f149d | barbarakovacic/python-projects | /Freeform-Projects/RGB-HEX-Converter.py | 1,634 | 4.75 | 5 | """
1. Prompt the user for the type of conversion they want
2. Ask the user to input the RGB or Hex value
3. Use Bitwise operators and shifting in order to convert the value
4. Print the converted value to the user
"""
def rgb_hex():
invalid_msg = "Invalid values were entered!"
red = int(raw_input("Please enter the red value: "))
if red < 0 or red > 255:
print invalid_msg
return
green = int(raw_input("Please enter the green value: "))
if green < 0 or green > 255:
print invalid_msg
return
blue = int(raw_input("Please enter the blue value: "))
if blue < 0 or blue > 255:
print invalid_msg
return
val = (red << 16) + (green << 8 ) + blue
#converting the RGB value to a hex value
print "%s" % (hex(val)[2:]).upper()
def hex_rgb():
hex_val = raw_input("Please enter the hexadecimal value: ")
if len(hex_val) != 6:
print "Invalid Value was entered!"
return
else:
#16: indicates that hex_val is in base 16
hex_val = int(hex_val, 16)
two_hex_digits = 2**8
blue = hex_val % two_hex_digits
hex_val = hex_val >> 8
green = hex_val % two_hex_digits
hex_val = hex_val >> 8
red = hex_val % two_hex_digits
print "Red: %s Green: %s Blue: %s" % (red, green, blue)
def convert():
while True:
option = raw_input("Enter 1 to convert RGB to HEX. Enter 2 to convert HEX to RGB. Enter X to Exit: ")
if option == "1":
print "RGB tp Hex ..."
rgb_hex()
elif option == "2":
print "Hex to RGB ..."
hex_rgb()
elif option == "X" or option == "x":
break
else:
print "Error! Invalid user input!"
convert()
| true |
e3edb791da6b8f2bd5f1e396fb61ae758c8f79c8 | Deepu561/Python | /reverse.py | 333 | 4.3125 | 4 | string = input("Enter a long String :\n")
result = string.split()
result_1 = result[::-1]
result_1 = " ".join(result_1)
print(result_1)
#Reverse Word Order with function
def reverse_word(string):
return " ".join(string.split()[::-1])
string = input("Enter a long String\n")
print("Reversed String is\n",reverse_word(string))
| true |
44c6b507cc8d53297c592aae8656bdf0690271d5 | mlhaus/KCC-Intro-Mon-Night | /kurt.py | 824 | 4.40625 | 4 | primaryColor1 = input( "Enter primary color 1: ")
primaryColor2 = input( "Enter primary color 2: ")
if ( primaryColor1 == "red" and primaryColor2 == "blue" ) or \
( primaryColor1 == "blue" and primaryColor2 == "red" ):
print( primaryColor1 + " mixed with " + primaryColor2 + " is purple" )
elif ( primaryColor1 == "red" and primaryColor2 == "yellow" ) or \
( primaryColor1 == "yellow" and primaryColor2 == "red" ):
print( primaryColor1 + " mixed with " + primaryColor2 + " is orange" )
elif ( primaryColor1 == "yellow" and primaryColor2 == "blue" ) or \
( primaryColor1 == "blue" and primaryColor2 == "yellow" ):
print( primaryColor1 + " mixed with " + primaryColor2 + " is green" )
else:
print( "One of your colors, " + primaryColor1 + " or " + \
primaryColor2 + " is not a primaryColor" ) | false |
6b898e84e86c51812632570633a3448a71200895 | itsrawlinz-jeff/Python-Short-Projects | /Python-master/Python-master/KTC/tmp.py | 654 | 4.375 | 4 | import turtle
t = turtle.en()
turtle.bgcolor("black")
colors = ["red", "yellow", "blue", "green"]
#ask the user's name using turtle's textinput pop-up window
yourName = turtle.textinput("Enter your name", "What is your name?")
#draw a spiral of the name on the screen written 100 times:
for x in range(100):
t.pencolor(colors[x%4])#rotate through the four colors
t.penup()#don't draw the regular spiral lines
t.forward(x*4)#just move the turtle on the screen
t.pendown()#write the inputted name, bigger each time
t.write(yourName, font = ("Arial", int( (x + 4) / 4), "bold"))
t.left(92)#turn left, just as in our other spirals | true |
b53ea926b36a55e01ee3683103df203e132193ec | gr3grisch/awesomePython | /code/compound-interest.py | 769 | 4.125 | 4 | from decimal import Decimal
"""
A person invests $1000 in a savings account yielding 5% interest. Assuming that
the person leaves all_nums interest on deposit in the account, calculate and display the
amount of money in the account at the end of each year for 10 years. Use the following
formula for determining these amounts:
a = p(1 + r)n
where
p is the original amount invested (i.e., the principal),
r is the annual interest rate,
n is the number of years and
a is the amount on deposit at the end of the nth year.
"""
principal = Decimal('1000.00')
interest_rate = Decimal('0.05')
number_of_years = 10
amount = 0
for year in range(1, 11):
amount = principal * (1 + interest_rate) ** year
print(f'year {year:>2}: {amount:>10.2f}')
| true |
10303df0e7c3aeaf24f5200f6823850b8ffc7dec | fmaticSRB/Python | /ArraySwap/ArraySwap.py | 517 | 4.15625 | 4 | ##########################################################
# Author: Filip Matic
# Title: ArraySwap.py
# Description: Program swaps the first and last elements
# of an array
##########################################################
# Swap function
def swapList(newList):
size = len(newList)
# Swapping
temp = newList[0]
newList[0] = newList[size - 1]
newList[size - 1] = temp
return newList
# Driver code
newList = [12, 35, 9, 56, 24]
print(swapList(newList))
| true |
3d9bbed4a580f02f4c36cf8979be40e3e8e6be52 | epurpur/100-days-of-code | /Day19TrafficLight.py | 1,542 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 17 09:41:19 2018
@author: ep9k
"""
"""The idea is to cycle (hint) through different colors of a set of traffic lights (red, amber, green) printing
the name of the color every time the cycle occurs.
For bonus points: traffic lights normally cycle between green and red based on traffic levels so you never
know exactly when that will happen. This is a chance to throw some randomness into your script."""
import itertools
import time
import sys
import random
colors = 'green yellow red'.split()
colors2 = ['green', 'yellow', 'red'] #cycle also iterates through list
traffic_light = itertools.cycle(colors2)
max_width = max(map(len, colors2))
while True:
sys.stdout.write('\r' + next(traffic_light).ljust(max_width))
sys.stdout.flush()
time.sleep(random.uniform(.1, 3.0)) #random.uniform(a, b) takes floats as arguments
#####Julian's traffic light app###
colors = 'red green yellow'.split()
rotation = itertools.cycle(colors)
def rg_timer():
return random.randint(3, 7)
def light_rotation(rotation):
for color in rotation:
if color == 'yellow':
print('Caution! the light is %s' % color)
itertools.sleep(3)
elif color == 'red':
print('STOP! The light is %s' % color)
itertools.sleep(rg_timer())
else:
print('Go! The light is %s' % color)
itertools.sleep(rg_timer())
if __name__ == '__main__':
light_rotation(rotation) | true |
70c6f6067dba5f68295ae48b3eafe4645ad89361 | NatsubiSogan/comp_library | /Python/math/prime.py | 1,057 | 4.125 | 4 | import math
# 素数列挙
def prime_numbers(x: int) -> list:
if x < 2:
return []
prime_numbers = [i for i in range(x)]
prime_numbers[1] = 0
for prime_number in prime_numbers:
if prime_number > math.sqrt(x):
break
if prime_number == 0:
continue
for composite_number in range(2 * prime_number, x, prime_number):
prime_numbers[composite_number] = 0
return [prime_number for prime_number in prime_numbers if prime_number != 0]
# 素数判定
def is_prime(x: int) -> bool:
if x < 2: return False
if x == 2 or x == 3 or x == 5: return True
if x % 2 == 0 or x % 3 == 0 or x % 5 == 0: return False
prime_number = 7
difference = 4
while prime_number <= math.sqrt(x):
if x % prime_number == 0: return False
prime_number += difference
difference = 6 - difference
return True
# 素因数分解
def prime_factorize(n: int) -> list:
res = []
while n % 2 == 0:
res.append(2)
n //= 2
f = 3
while f ** 2 <= n:
if n % f == 0:
res.append(f)
n //= f
else:
f += 2
if n != 1:
res.append(n)
return res | false |
8c62d2c1728737f2a92c8ce7655f0d76d4c775de | sarapalomares/Web-Fundamentals | /Python/oddeven.py | 382 | 4.34375 | 4 | # Create a function that counts from 1 to 2000. As it loops through each number, have your program generate the number and specify whether it's an odd or even number.
count = 0
while count < 2000:
count +=1
if (count % 2 == 1):
print "Number is {}. This is an odd number.".format(count)
else:
print "Number is {}. This is an even number.".format(count)
| true |
522eca5b8e6a5ef0cd78165cfe0fb717bea9a876 | 720315104023/phython-program | /avg.py | 228 | 4.1875 | 4 | list = []
value1 = int(input("enter the count value"))
print("enter the values")
for i in range(value1):
value = int(input(" "))
list.append(value)
sum= sum(list)
average = sum/value1
print("The average value is ",average)
| true |
e5f98726df4269a2f022d0b6ec5bb2db98f8e44b | JohnnyGOX17/python-lib | /data_structures/stack/ArrayStack.py | 1,277 | 4.125 | 4 | #!/usr/bin/env python3
class ArrayStack:
"""
Last-In First-Out (LIFO) Stack implementation which uses native python list
as the underlying storage
"""
def __init__(self):
"""Creates an empty stack"""
self._data = []
def __len__(self):
"""Return the number of elements currently in the stack"""
return len(self._data)
def is_empty(self):
"""Returns True if stack is empty"""
return len(self._data) == 0
def push(self, e):
"""Adds element 'e' to the top of the stack"""
self._data.append(e) # NOTE: new item stored at the end of list
def top(self):
"""
Returns- but does not remove- the element currently at the top of the
stack.
Raise Empty exception if the stack is empty.
"""
if self.is_empty():
raise Empty("Stack is empty!")
return self._data[-1] # give last item in list (top of the stack)
def pop(self):
"""
Remove and return the element from the top of the stack
Raise Empty exception if the stack is empty.
"""
if self.is_empty():
raise Empty("Stack is empty!")
return self._data.pop() # give last item in list and remove it
| true |
1633d800554f0f2c2070e448a375356a7485ea01 | JohnnyGOX17/python-lib | /basics/OOP/cc.py | 2,422 | 4.4375 | 4 | #!/usr/bin/env python3
class CreditCard:
""" A basic Credit Card example class"""
def __init__(self, customer, bank, accnt, limit):
""" Creates a new credit card instance.
Initial balance is 0.
customer: name of the customer (e.x. 'John Doe')
bank: name of the bank (e.x. 'Chase')
accnt: account identifier (e.g. '1234 5678 90')
limit: credit limit (in USD)
"""
self._customer = customer
self._bank = bank
self._account = accnt
self._limit = limit
self._balance = 0
def get_customer(self):
"""Return name of the customer"""
return self._customer
def get_bank(self):
"""Return bank's name"""
return self._bank
def get_account(self):
"""Return the CC #"""
return self._account
def get_limit(self):
"""Return current credit limit"""
return self._limit
def get_balance(self):
"""Return current CC balance"""
return self._balance
def charge(self, price):
"""Charge to account balance 'price' amount, assuming sufficient credit
limit.
Returns True if charge was processed, False if charge was declined due
to insufficient credit.
"""
if price + self._balance > self._limit:
return False # charge exceeds credit limit
else:
self._balance += price
return True
def make_payment(self, amount):
"""Customer payment to reduce balance"""
self._balance -= amount
if __name__ == '__main__':
wallet = []
wallet.append(CreditCard('John Doe', 'Cali Savings',
'12345 6789 10', 2500) )
wallet.append(CreditCard('John Doe', 'Cali Savings',
'12345 6789 11', 3500) )
wallet.append(CreditCard('John Doe', 'Cali Savings',
'12345 6789 12', 5000) )
print(f"Number of CCs is {len(wallet)}")
for val in range(1, 17):
for i in range(len(wallet)):
wallet[i].charge(val*(i+1))
for i in range(len(wallet)):
print(f'Customer:\t{wallet[i].get_customer()}')
print(f'Bank:\t\t{wallet[i].get_bank()}')
print(f'Account:\t{wallet[i].get_account()}')
print(f'Limit:\t\t{wallet[i].get_limit()}')
print(f'Balance:\t{wallet[i].get_balance()}')
| true |
3bcf436ac9a10b1a57f7ecf1a3a370ff5db68bcd | jenjnif/py4e | /Ex-6-14.py | 2,174 | 4.5 | 4 | # CHAPTER 6:
# 6.14 exercises
# 1 - Write a while loop that starts at the last character in the string and works its way backwards to the
# first character in the string, printing each letter on a separate line, except backwards.
print('ex 1')
fruit = 'strawberry'
index = len(fruit)-1
while index >= 0:
spelling = fruit[index]
print(spelling)
index = index - 1
#Another way to write a traversal is with a for loop:
fruit = 'pear'
for char in fruit:
print(char)
# 2 - Given that fruit is a string, what does fruit[:] mean?
print('ex 2')
fruit = 'apple'
print(fruit[:])
# it prints the whole string
# 3 - Encapsulate this code in a function named count, and generalize it so that it
# accepts the string and the letter as arguments.
print('ex 3')
def count(word,letter):
count = 0
for char in word:
if char == letter:
count = count + 1
print(count)
character_count = count('potato','o')
# 4 - There is a string method called count that is similar to the function in the
# previous exercise. Read the documentation of this method at
# https://docs.python.org/3.5/library/stdtypes.html#string-methods and
# write an invocation that counts the number of times the letter a occurs in “banana”.
print('ex 4')
fruit = 'banana'
char_count = fruit.count('n')
print(char_count)
# 5 - Take the following Python code that stores a string:‘
str = 'X-DSPAM-Confidence:0.8475'
# Use find and string slicing to extract the portion of the string after the colon
# character and then use the float function to convert the extracted string into a
# floating point number.
start = str.find(':')
code = float(str[start+1:])
print(code)
# 6 - Read the documentation of the string methods at
#https://docs.python.org/3.5/library/stdtypes.html#string-methods
#You might want to experiment with some of them to make sure you understand how
# they work. strip and replace are particularly useful.
# The documentation uses a syntax that might be confusing.
# For example, in find(sub[, start[, end]]), the brackets indicate optional arguments.
# So sub is required, but start is optional, and if you include start,
# then end is optional. | true |
ebc144204b6bf8e63f4c0d9dea2a6865eeda7d9a | nataliyamiller/night_class_pdxguild | /list.py | 320 | 4.15625 | 4 | list = ['apple', 'orange', 40, 'grapes', 'last item']
for items in range (0, len(list)):
print list[items]
for items in list:
print items
ind = len(list)
print list[ind -2]
# num = 0
# for items in list:
# num +=1 # means num = num + 1
# print num
# print num
num = 0
white num < 100:
num +=1
print num | false |
ff8ee93cda2cf51b77a2ab354d0fdc3b0ee46029 | CrazyAlan/codingInterview | /cc150/chapter3/5.py | 808 | 4.28125 | 4 | '''
1. Using 2 stacks to mimic the queue
2. We push new elements into s1
3. For dequeue, we pop out elements from s2, as when s2 is empty, we pop out
elements from s1 to s2
'''
class MyQueue():
"""docstring for MyQueue"""
def __init__(self):
self.s1 = []
self.s2 = []
def enqueue(self, value):
self.s1.append(value)
def dequeue(self):
if self.s2:
return self.s2.pop()
else:
while self.s1:
self.s2.append(s1.pop())
if self.s2:
return self.s2.pop()
def peek(self):
if self.s2:
return self.s2[-1]
else:
while self.s1:
self.s2.append(self.s1.pop())
if self.s2:
return self.s2[-1]
if __name__ == '__main__':
testQue = MyQueue()
for x in xrange(1,10):
testQue.enqueue(x)
print testQue.s1
testQue.peek()
print testQue.dequeue()
print testQue.s1
| false |
90a6074b844dec053b4cd61bc614a4341749b2b6 | Rika0101/pythonLearning | /demo_tuple.py | 1,712 | 4.15625 | 4 | """元组的创建方式"""
"""第一种创建方式,使用()"""
t=("python","rabblt",98)
t2="python","rabbit",98 #可以省略小括号()
print(t2)
print(type(t2))
print(t)
print(type(t))
"""第一种创建方式,使用内置函数tuple()"""
t1=tuple(("python","rabblt",98))
print(t1)
print(type(t1))
print("----只包含一个元素的元组,需要使用逗号和小括号----")
t3=("python")
print(t3)
print(type(t3))
t3=("python",)
print(t3)
print(type(t3))
"""空元组的创建"""
lst=[]
lst1=list()
d={}
d1=dict()
t=()
t1=tuple()
print("空列表",lst,lst1)
print("空字典",d,d1)
print("空元组",t,t1)
print("----为什么要将元组设计成不可变序列----")
t=(2,[2,33],5)
print((t),type(t))
print(t[0],type(t[0]),id(t[0]))
print(t[1],type(t[1]),id(t[1]))
print(t[2],type(t[2]),id(t[2]))
#t[1]=100 #元组是不允许修改元素的
#可以向列表中添加元素,并且列表的内存地址不变
t[1].append(100)
print(t[1],type(t[1]),id(t[1]))
print("----元组的遍历----")
t=("rabbit",34,[3,5,6])
print(t[0])
print(t[1])
print(t[2])
#print(t[3]) IndexError: tuple index out of range
"""遍历元组"""
for item in t:
print(item)
print("----集合的创建方式----")
"""集合是没有value的字典,使用大括号{}"""
s={1,2,2,3,4,4,5} #集合中的元素不允许重复
print(s)
"""第二种创建方式,使用set()"""
s1=set(range(6))
print(s1,type(s1))
s2=set([1,2,3,3,4,5,5,6])
print(s2,type(s2))
s3=set((1,2,4,4,5,65))
print(s3,type(s3)) #集合中的元素是无序的
s4=set("rabbit")
print(s4,type(s4))
s5=set({1,2,2,34,56,6})
print(s5,type(s5))
print("----定义一个空集合----")
s6={} #dict字典类型
print(s6,type(s6))
s7=set()
print(s7,type(s7))
| false |
94ba5df8ea7d5282adfe34c1dd6de3a6f1d6536e | LorenzoVaralo/ExerciciosCursoEmVideo | /Mundo 3/Ex083.py | 454 | 4.1875 | 4 | #Crie um programa onde o usuario digite uma expressão qualquer que use parenteses.
# Seu aplicativo deverá analisar se a expressão passada está com os parenteses abertos e fechados em ordem correta.
c = 0
exp = str(input('Digite uma expressão: '))
for dig in exp:
if dig == '(':
c += 1
elif dig == ')':
c -= 1
if c == 0:
print('Sua expressão está correta!')
else:
print('Sua expressão está errada!') | false |
2d1cb0c39b56a5be7e9fd8c6e31059048a91d577 | LorenzoVaralo/ExerciciosCursoEmVideo | /Mundo 2/Ex037.py | 800 | 4.34375 | 4 | #Escreva um programa que leia um numero inteiro qualquer e peça para o usuario escolher qual será a base de coversao:
# 1 para binario
# 2 para octal
# 3 para hexadecimal
num = int(input('Digite um numero: '))
escolha = int(input('''Escolha uma das opçoes de conversão:
[ 1 ] Conversor para Binario
[ 2 ] Conversor para OCTAL
[ 3 ] Conversor para Hexadecimal
Sua opção: '''))
if escolha > 3 or escolha < 1:
print('ERRO. Digite uma das escolhas.')
elif escolha == 1:
num_bi = bin(num)
print('O numero {} em binario é {}.'.format(num, num_bi[2:]))
elif escolha == 2:
num_oc = oct(num)
print('O numero {} em Octal é {}.'.format(num, num_oc[2:]))
else:
num_hexa = hex(num)
print('O numero {} em Hexadecimal é {}.'.format(num, num_hexa[2:])) | false |
d3ce465d082a610e0832e9e754a0bbac761e8718 | LorenzoVaralo/ExerciciosCursoEmVideo | /Mundo 3/Ex099.py | 599 | 4.15625 | 4 | '''Faça um programa que tenha uma função chamada maior(), que receba vários
parametros com valores inteiros.
Seu programa tem que analizar todos os valores e dizer qual deles é maior.'''
from time import sleep
def maior(*num):
print('-='* 30,'\nAnalizando os valores passados...')
for x in num:
print(x, end=' ', flush=True)
sleep(0.1)
if len(num) > 0:
maior = max(num)
else:
maior = 0
print(f'Foram informados {len(num)} valores ao todo.\nO maior valor informado foi {maior}.')
maior(2,9,4,5,7,1)
maior(4,7,0)
maior(1,2)
maior(6)
maior() | false |
b0272c7678af4b592aa54321380b7e93ffcba771 | IsidoreDelpierro/numerical-methods | /example_bisection_steemit.py | 1,587 | 4.28125 | 4 | #Bisection Algorithm (from Steemit)
#https://steemit.com/mathematics/@dkmathstats/the-bisection-method-with-python-code
'''
Pseudocode For Bisection Method
if f(a)*f(b) > 0
print("No root found")
#Both f(a) and f(b) are the same sign
else
while(b - a)/2 > tolerance
c = (b+a)/2 #c is like a midpoint
if f(c) == 0
return(midpoint) #The midpoint is the root such that f(midpoint) = 0
else if f(a)*f(c) < 0
b = c #Shrink interval from right
else
a = c
return(c)
'''
# Bisection Method In Python
# Goal: Finding Roots to Polynomials
# Inputs: Function, a and b for interval [a, b], a guess in [a, b]
# Output: Roots/Zeroes To Polynomials
# Reference: Tim Sauer - Numerical Analysis Second Edition
# http://code.activestate.com/recipes/578417-bisection-method-in-python/
# https://stackoverflow.com/questions/6289646/python-function-as-a-function-argument
def f(x):
return (x**2 - 11)
def bisection_method(a, b, tol):
if f(a)*f(b) > 0:
#end function, no root
print("No root found.")
else:
while(b-a)/2.0 > tol:
midpoint = (a+b)/2.0
if f(midpoint) == 0:
return(midpoint) #The midpoint is the x-intercept/root.
elif f(a)*f(midpoint) < 0: #Increasing but below 0 case
b = midpoint
else:
a = midpoint
return(midpoint)
answer = bisection_method(-1, 5, 0.0001)
print("Answer: ", round(answer, 3))
#Answer: 3.317
| true |
7efde878348466a2d2a9c0a72c45ff97a118294b | JohnDoddy/python_challenges | /11_check_if_number_in_list.py | 478 | 4.21875 | 4 | # this program should check if an issued number is on a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def check(numbers):
check = int(input("Enter the number you want to check: "))
found = bool
for i in numbers:
if i == check:
found = True
print("Yes, that number is on the list")
elif check not in numbers:
found = False
print("No, the number is not on the list")
break
check(numbers) | true |
6c440900f4bb28ff49120e3d32c125097a0413b1 | rhitik26/python | /DXCTraining/Examples/8Iterators,Generators/iterators/IterateSecond.py | 624 | 4.125 | 4 | class Myrange:
def __init__(self, n):
self.n = n
def __iter__(self):
return Myrange_iter(self.n)
class Myrange_iter:
def __init__(self, n):
self.i = 0
self.n = n
def __next__(self):
while(self.i < self.n):
i = self.i
self.i += 1
if i%7==0 :
return i
else:
continue
else:
raise StopIteration()
m1=Myrange(100)
for x in m1:
print(x)
"""
for x in Myrange(10):
print(x)
"""
"""
Myrange is Iterable ,Myrange_iter is the Iterator ,Iterators are Iterable
Reverse iterate a list.
create a sort_iter for a list.
Iterate a list of names in alphabetical order
""" | false |
f6a568b52bbb13d8e0952066d78bf7a148f8072f | dipens/python_sandbox | /python_sandbox_starter/classes.py | 1,117 | 4.15625 | 4 | # A class is like a blueprint for creating objects. An object has properties and methods(functions) associated with it. Almost everything in Python is an object
class User:
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
def greeting(self):
return f'My name is {self.name} and I am {self.age}'
def has_birthday(self):
self.age += 1
return self.age
class Customer(User):
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
self.balance = 0
def setBalance(self, balance):
self.balance = balance
def greeting(self):
return f'My name is {self.name} and I am {self.age} and my balance is {self.balance}'
dipen = User('Dipen Shah', 'dipen@mail.com', 30)
print(dipen.name)
print(dipen.email)
print(dipen.age)
print(dipen.greeting())
print(dipen.has_birthday())
print(dipen.greeting())
janet = Customer('Janet', 'janet@mail.com', 25)
janet.setBalance(500)
print(janet.greeting())
print(janet.has_birthday())
print(janet.greeting())
| true |
acbe44b902b7476793b1e2a8fa2ab39b22117666 | mkbarna/Pytony | /ex30.py | 445 | 4.21875 | 4 | people = 30
cars = 40
buses = 15
if cars > people:
print "We should take the cars"
elif cars < people:
print "We should not take the cars"
else:
print "We can't decide."
if buses > cars:
print "That's too many buses."
elif buses < cars:
print " Maybe we could take the buses.."
else:
print "We still can't decide"
if people > buses < people > buses:
print "Alright, Lets take the buses"
else:
print "Fine lets jsut stay home then." | true |
7527b61d4264cce6e975e165e8d51b3ebfb4c1e4 | mkbarna/Pytony | /ex7.py | 1,083 | 4.25 | 4 | print "Mary had a little lamb" #this print a string of our fav nursery rhyme
print "Its fleece was white as %s." % 'snow'# this prints uses a format operator to add a tring to the end kind of unec
print "And everywhere that Mary went." # another printed string
print "." * 10 #Multiplied the '.' by 10 so ten periods wil appear
end1 = "C"# sets variable end1 = C
end2 = "h"#sets end2 equal to h
end3 = "e"#sets end2 equal to h
end4 = "e"#sets end2 equal to h
end5 = "s"#sets end2 equal to h
end6 = "e"#sets end2 equal to h
end7 = "B"#sets end2 equal to h
end8 = "u"#sets end2 equal to h
end9 = "r"#sets end2 equal to h
end10 = "g"#sets end2 equal to h
end11 = "e"#sets end2 equal to h
end12 = "r"#sets end2 equal to h
# watch that comma at the end. try removing it and see what happens
print end1 + end2 + end3 + end4 + end5 + end6 # prints all the variables we just set to make the word Cheese
print end7 + end8 +end9 + end10 + end11 + end12 #prints all the variables we just set to spell Burger
#removing the comma adds in a line break. So , = no line break and !, = line break | true |
cfd2a0c4f5964992fd8886e840058e3f3d704157 | joinalahmed/University_of_Michigan_Python_for_Informatics_Certificate | /1_Programming_for_Everybody/Week5_Ch3_Conditional_Code/overtime.py | 721 | 4.34375 | 4 | # 3.1 Write a program to prompt the user for hours and rate per hour using
# raw_input to compute gross pay. Pay the hourly rate for the hours up to 40
# and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours
# and a rate of 10.50 per hour to test the program (the pay should be 498.75). You
# should use raw_input to read a string and float() to convert the string to a number.
# Do not worry about error checking the user input - assume the user types numbers properly.
hours = raw_input('Enter hours: ')
rate = raw_input('Enter rate: ')
h = float(hours)
r = float(rate)
if h > 40:
pay = (40 * r) + ((h-40) * r * 1.5)
else:
pay = h * r
print pay
# Expected output: 498.75 | true |
c8398cb97fa75da77184c529e68d4b55de888895 | syou-code/Imma_learn_python | /dictionary.py | 862 | 4.53125 | 5 | # a dictionary is similar to a set, but it's key value
# a set i just all keys.
# dictionary is a key-value pairs.
# {<key>: <value>}
d = {'name': 'Sailun', 'dob': '08141989'}
print('dictionary', d)
# you can only have 1 unique key. BUT you can have duplicate values
name = {'first_name': 'Nguyen', 'last_name': 'Nguyen'}
print('first and last name', name)
# i can change the vaue of the key
name['first_name'] = 'Sailun'
name['last_name'] = 'You'
print('my new name', name)
# but what happens if i don't have a key doesn't exist
# it will add middle_name key to the name dictionary
name['middle_name'] = 'cool'
print('my new name', name)
print('my first name is', name['first_name'])
print('my last name is', name['last_name'])
# second_middle_name is not defined. that's why it errors out.
print('my second middle name', name['second_middle_name']) | true |
14b9c7039298d3d3d5007fe23b65769a4378f536 | hspaul92/Python | /GeeksForGeeks/Dictionary/RemoveItemUsingValue.py | 1,977 | 4.25 | 4 | #Solution:1 Using del() function
def removeItemUsingValue(d):
print("Before Remove:",d)
v = input("Enter Element You Want To Remove:")
if v not in d.values():
print("Specified Item is not present in dictonary !!!")
else:
for key,value in d.items():
if value==v:
del d[key]
break
print("After Remove:",d)
dic1 ={2001:'Apple',2002:'Samsung',2003:'Sony',2004:'Huwaie'}
removeItemUsingValue(dic1)
#Solution:2 Using pop() function
def removeItemUsingValue2(d):
print("Before Remove:",d)
v = input("Enter Element You Want To Remove:")
if v not in d.values():
print("Specified Item is not present in dictonary !!!")
else:
for key,value in d.items():
if value==v:
d.pop(key)
break
print("After Remove:",d)
dic1 ={2001:'Apple',2002:'Samsung',2003:'Sony',2004:'Huwaie'}
removeItemUsingValue2(dic1)
#Note: Problem With Above approach
#---------------------------------
#Here We are removing given key,value pair while executing iteration.
#So once item removed we need to come out of iteration using 'break'.
#The reason is here once the item removed the size of dictionary chaged
#in between iteration.So it will give runtime exception as below.
# 'RuntimeError: dictionary changed size during iteration'
#So Above two approach won't work if dictionary has more than one same values.
#Solution:3
def removeItemUsingValue2(d):
print("Before Remove:",d)
v = input("Enter Element You Want To Remove:")
if v not in d.values():
print("Specified Item is not present in dictonary !!!")
else:
result ={ x:y for x,y in d.items() if y != v}
print("After Remove:",result)
dic1 ={2001:'Apple',2002:'Samsung',2003:'Sony',2004:'Huwaie'}
removeItemUsingValue2(dic1)
dic2 ={2001:'Apple',2002:'Samsung',2003:'Sony',2004:'Huwaie',2005:'Sony'}
removeItemUsingValue2(dic2)
| false |
4d688d3eaefaaee590b562756b60c99dd90e0d28 | hspaul92/Python | /GeeksForGeeks/Basic/FactorialOfNumber.py | 1,152 | 4.40625 | 4 | # Write a Python Program to find factorial of a number
# Explanation : Factorial of 0 is 1 , for any other number .. n * (n-1) * (n-2) * (n-3) ..... 1
# Scenario1 : Input:6 >> Output:720
# Scenario2 : Input:0 >> Output:1
# Solution:1 Using Iteration with decreasing value
def factOfNumber1(n):
mul= 1
if n != 0:
while (n!=0):
mul = mul*n
n=n-1
return mul
else:
return 1
# Solution:2 Using Iteration with increasing value
def factOfNumber2(n):
mul =1
startvalue=1
if n!= 0:
while (startvalue<=n):
mul =mul *startvalue
startvalue=startvalue+1
return mul
else:
return 1
# Solution:3 Using recursion
def factOfNumber3(n):
if n == 0:
return 1
else:
return n*factOfNumber3(n-1)
# Driver Code
number = int(input("Enter A Non Negative Number:"))
print("Using Solution1: Factorial of {} is {}".format(number, factOfNumber1(number)))
print("Using Solution2: Factorial of {} is {}".format(number, factOfNumber2(number)))
print("Using Solution3: Factorial of {} is {}".format(number, factOfNumber3(number)))
| true |
00098b2ed409db22b56ea34e8b49378991a5faef | hspaul92/Python | /GeeksForGeeks/Tuple/CountingDuplicateInListOfTuple.py | 812 | 4.375 | 4 | # Question: Counting Duplicate Element in list OF Tuple
# Input : [('a', 'e'), ('b', 'x'), ('b', 'x'), ('a', 'e'), ('b', 'x'')]
# Output :('a', 'e') – 2 ('b', 'x') – 3
# Solution:1 Using dict() and list comprehension
def countingDuplicateInListOfTuple1(l):
s = dict()
for x in l :
s[x] = s.get(x,0)+1
print("Duplicate Elements :", [(x,y) for x,y in s.items() if y>1])
# Solution:2 Using dict() and list comprehension
from collections import Counter
def countingDuplicateInListOfTuple2(l):
t = Counter(l)
print("Duplicate Elements :", [(x,y) for x,y in t.items() if y>1])
input_list1 = [('a', 'e'), ('b', 'x'), ('b', 'x'), ('a', 'e'), ('b', 'x')]
print("Input List :",input_list1)
countingDuplicateInListOfTuple1(input_list1)
countingDuplicateInListOfTuple2(input_list1) | false |
e013c3e65b568f66de78a5174c9378f7dcb130fc | priyanga-181/blind-auction | /main.py | 630 | 4.21875 | 4 | from replit import clear
from art import logo
#HINT: You can call clear() to clear the output in the console.
print(logo)
the_end=False
new_dict={}
while not the_end:
print("Welcome to the Secret Auction program!")
name=input("What is your name? ")
bid=int(input("What's your bid? $"))
new_dict[name]=bid
others=input("Are there any other bidder? Type 'yes' or 'No' ")
if others=="yes":
clear()
elif others=="no":
the_end=True
smallest=-1
for key in new_dict:
value=new_dict[key]
if value>smallest:
smallest=value
key_name=key
print(f"{key_name} is the winner with ${smallest}")
| true |
3dbb405ca65947487cf3fc6c6876e0630556010e | Kyle-Pu/Python-Data-Science-Projects | /Python_Fundamentals/dictionaries.py | 436 | 4.125 | 4 | #Ask for a starting phrase!
phrase = input("What string would you like to deconstruct?!?!?!? ")
#Split the string by whitespace
splitUp = phrase.split()
#Create a dictionary using dictionary comprehension
#Use the first letter of each word as the key
#Use the actual word as the value
#No periods or commas at the end of each word is allowed
dictionary = {word.strip(".,")[0]: word.strip(",.") for word in splitUp}
print(dictionary)
| true |
0d7d96ac9687f389e9b53a90504aa8afa5a55249 | DINESH-KUMAR-7/Talentpy-Assgn4 | /Python/playwithstr.py | 1,298 | 4.5625 | 5 | """
Create three functions as follows -
1. def remove_vowels(string) - which will remove all vowels from the given
string. For example if the string given is “aeiru”, then the return value should
be ‘r’
2. def remove_consonants(string) - which will remove all consonants from
given string. For example, if the string given is “aeri”, then the return value
should be ‘aei’.
3. def caller -> This function should 2 parameters
1. Function to call
2. String argument
This caller function should call the function passed as a parameter, by
passing second parameter as the input for the function. Example: caller(remove_vowles,
“aeiru”) should call remove_vowels function and should return ‘r’ as the output.
"""
def caller(func,string):
result = func(string)
return result
def remove_vowels(string):
#using list join method vowels are removed and other words are stored
up_str ="".join([word for word in string if word not in 'aeiouAEIOU'])
return up_str
def remove_consonants(string):
#using list join method , vowels in string are collected and stored
# at update_str
update_str ="".join([word for word in string if word in 'aeiouAEIOU'])
return update_str
print(caller(remove_vowels,"aeiru"))
print(caller(remove_consonants,"aeiru")) | true |
f0b1d35f78c75b1e3d07ec5905c2b72046072c6b | CraigDevJohnson/AutomateTheBoringStuffWithPython | /if_example.py | 961 | 4.375 | 4 | # if examples
# Basic if name is Alice
name = 'Alice'
if name == 'Alice':
print('Hi, ' + name + '!')
else:
print('Oh, I was expecting Alice... Still nice to met you ' + name + '!')
print('Done')
# Basic if name isn't Alice
name = 'Bob'
if name == 'Alice':
print('Hi, ' + name + '!')
else:
print('Well, hello there ' + name + '!')
print('Done')
# Basic else if statement
name = 'Bob'
if name == 'Alice':
print('Hi, ' + name + '!')
elif name == 'Bob':
print('Hi there, ' + name + '!')
else:
print('Well, hello there ' + name + '!')
print('Done')
# Truthy value
print('Enter a name please:')
name = input()
if name:
print('Thank you fer entering your name, ' + name + '!')
else:
print('You did not enter a name... Rude!')
# Better to be more explicit
print('Enter a name please:')
name = input()
if name != '':
print('Thank you fer entering your name, ' + name + '!')
else:
print('You did not enter a name... Rude!') | true |
34fb7eedf5a5ea5421fbccf360730e3afa75a71a | BlankIndex/MachineProblem-PYTHON- | /Problem_2Python.py | 1,367 | 4.15625 | 4 | from math import sqrt
def Circle(a1, b1, a2, b2, a3, b3):
a12 = a1 - a2;
a13 = a1 - a3;
a31 = a3 - a1;
a21 = a2 - a1;
b12 = b1 - b2;
b13 = b1 - b3;
b31 = b3 - b1;
b21 = b2 - b1;
# solve for Xx, Yy, Z
w = pow(a1, 2) - pow(a3, 2);
x = pow(b1, 2) - pow(b3, 2);
y = pow(a2, 2) - pow(a1, 2);
z = pow(b2, 2) - pow(b1, 2);
d = (((w) * (a12) + (x) * (a12) + (y) * (a13) + (z) * (a13)) // (2 * ((b31) * (a12) - (b21) * (a13))));
e = (((w) * (b12) + (x) * (b12) + (y) * (b13) + (z) * (b13)) // (2 * ((a31) * (b12) - (a21) * (b13))));
c = (-pow(a1, 2) - pow(b1, 2) - 2 * e * a1 - 2 * d * b1);
h = -e;
k = -d;
print("Centre = (", h, ", ", k, ")"); # print the center coordinates
r_sqrt = h*h+k*k-c;
r = round(sqrt(r_sqrt), 5);
print("Radius = ", r); # print the radius
l=[2*e,2*d,c]
print("vector[D,E,F]",l) # print the vector
# Input 3 Coordinates
a1,b1 = map(int,input('Input the First Coordinates: ').split())
a2,b2 = map(int,input('Input the Second Coordinates: ').split())
a3,b3 = map(int,input('Input the Third Coordinates: ').split())
Circle(a1, b1, a2, b2, a3, b3) | false |
86499fd60c8651e2c2479c80b651c58e5800ed13 | NirmalSilwal/Udacity_Data-Structure_Nanodegree_Projects | /1. Unscramble Computer Science Problems/Task1.py | 806 | 4.1875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 1:
How many different telephone numbers are there in the records?
Print a message:
"There are <count> different telephone numbers in the records."
"""
def count_phone_num(text, call):
record_total = []
for text_detail, call_detail in zip(text, call):
record_total.extend([text_detail[0], text_detail[1], call_detail[0], call_detail[1]])
return len(set(record_total))
total_records = count_phone_num(texts, calls)
print(f"There are {total_records} different telephone numbers in the records.") | true |
3a4722d1600a920a7d416cde9b1b2960931fe54e | amalong/sierra_python_module06 | /5_format.py | 2,230 | 4.625 | 5 | # The format() method
# The string format() method formats text, similar to the string-formatting % operator. The format() method was initially introduced in Python 2.6
# and was meant to eventually replace the % syntax completely. However, the % syntax is so pervasive in Python programs and libraries that the language
# still supports both techniques.
# The format() method and % string-formatting syntax behave very similarly, each using value placeholders within a string literal.
# Each pair of braces {} is a placeholder known as a replacement field. A value from the format() arguments is inserted into the string depending
# on the contents of a replacement field. Three methods exist to fill in a replacement field:
# Positional: An integer that corresponds to the value's position.
# 'The {1} in the {0}'.format('hat', 'cat')
# The cat in the hat
# Inferred positional: Empty {} assumes ordering of replacement fields is {0}, {1}, {2}, etc.
# 'The {} in the {}'.format('cat', 'hat')
# The cat in the hat
# Named: A name matching a keyword argument.
# 'The {animal} in the {headwear}'.format(animal='cat', headwear='hat')
# The cat in the hat
# The first two methods are based on the ordering of the values within the format() argument list.
# Placing a number inside of a replacement field automatically treats the number as the position of the desired value.
# Empty braces {} indicate that all replacement fields are positional, and values are assigned in order from left-to-right as {0}, {1}, {2}, etc.
# The positional and inferred positional methods cannot be combined. Ex: '{} + {1} is {2}'.format(2, 2, 4) is not allowed.
# The third method allows a programmer to create a keyword argument in which a name is assigned to a value from the format() keyword argument list.
# Ex: animal='cat' is a keyword argument that assigns 'cat' to {animal}. Good practice is to use the named method when formatting strings with many replacement
# fields to make the code more readable.
# A programmer can include a brace character { or } in the resulting string by using a double brace {{ or }}. Ex: '{0} {{x}}'.format('val') produces the string 'val {x}'. | true |
842ca3b685789391400274f3bf8a799da7c66432 | Hamooud92/Hamoud | /python 22.py | 722 | 4.21875 | 4 | def spy(nums):
code=[0,0,7,'x']
for num in nums :
if num==code[0]:
code.pop(0) # each time pop element from the list until it contains just 'x'
return len(code)==1
print(spy([0,0,1,2,4,7,3]))
def count_primes(num):
primes=[2]
x=3 #start examine the numbers start of 3
if num<2 : #to test 1 and 2 case 1 and 2 by convention is primary
return 0
while num>=x: # bigger than 3
for y in range(3,x,2):
if x%y==0: # not primary
x+=2
break
else:
primes.append(x) # add to the primary list
x+=2
print(primes)
return len(primes)
print(count_primes(35)) | true |
2d0371528e3a2671ba636e82f27a797972fef5c8 | essienmichael4/Intro_To_Python | /intro/Advanced.py | 515 | 4.1875 | 4 | #Function to return true only if numbers are even
def is_even(x):
return x % 2 == 0
is_even()
#Function to returns even numbers from a list
def is_even():
numbers = [1,52,234,87,4,76,24,69,90,135]
x = []
for a in numbers:
if a % 2 ==0:
x.append(a)
print(x)
is_even()
#Using Lambda
numbers = [1, 56, 234, 87, 4, 76, 24, 69, 90, 135]
print(list(filter(lambda a:a % 2 == 0, numbers)))
#Using Lambda
numbers = [1, 56, 234, 87, 4, 76, 24, 69, 90, 135]
print(list(filter(lambda a:a % 2 == 1, numbers)))
| true |
8b22106c7f8260064ece3038f5e523aa02d7a67d | Tasmiah-James/Variables-and-control-structures | /compulsory task.py | 2,132 | 4.3125 | 4 | import math
interest = 0
#Task: a program that allows the user to access two different financial calculators: an investment calculator and a home loan repayment calculator.
#Objective: Ask the user to choose which calculation they want to do between an investment and bond calculation
calculation_type = input("Would you like to do a bond or investment calculation?: ")
#Prompt the user for input if they choose investment
#Objective2: process when the user chooses investment or bond
if calculation_type.upper() == "INVESTMENT":
money_amount = float(input("How much money are you depositing?: "))
interest_rate = float(input("How much percentage of interest should be applied?: "))
years_investing = float(input("How many years do you plan on investing for?: "))
interest = input("Would you like simple or compound interest?: ")
#If the user chooses interest the program will calculate and print the amount
if interest.upper() == "SIMPLE" :
interest_calculation = interest_rate/int(100)
simple_investment_total = (money_amount) * (1 + (interest_calculation) * (years_investing))
print(simple_investment_total)
elif interest.upper() == "COMPOUND" :
interest_calculation = interest_rate/int(100)
compound_investment_total = (money_amount) * (math.pow((int(1) + (interest_calculation)), (years_investing)))
print(compound_investment_total)
#If the user chooses bond the program will calculate how much and print the amount
elif calculation_type.upper() == "BOND" :
house_value = float(input("What is the current value of the house?: ")) #Prompt the user for input if they choose bond
interest_rate_house = float(input("What is the interest rate?: "))
months_repayment = float(input("How many months do you wish to take in order to repay the bond?: "))
interest_rate_house_calculation = interest_rate_house/int(100) / 12
bond_total = (house_value * interest_rate_house_calculation) / (1 - math.pow((int(1) + interest_rate_house_calculation), - months_repayment))
print("You will need to pay " + str(bond_total) + " per month.") | true |
60f64e79849ca7ef38b5347843115166e055417b | ianWangKang/Hello-World- | /homework3.py | 2,689 | 4.1875 | 4 | # _*_ conding:utf-8 _*_
#import random
#def rall_dice(number=3, points=None):
# print('<<< ROLL THE DICE! >>>')
# if points is None:
# points = []
# while number > 0:
# point = random.randrange(1,7)
# points.append(point)
# number = number - 1
# return points
#def roll_result(total):
# isBig = 11 <= total <=18
# isSmall = 3 <= total <=10
# if isBig:
# return 'Big'
# elif isSmall:
# return 'Small'
#def start_game():
# your_money = 1000
# while your_money > 0:
# print('<<< GAME START! >>>')
# choices = ['Big','Small']
# your_chioce = input('Big or Small:')
# if your_chioce in choices:
# your_bet = int(input('how much you wanna bet ? - '))
# points = rall_dice()
# total = sum(points)
# youWin = your_chioce == roll_result(total)
# if youWin:
# print('The points are',total,'you win!')
# print('you gained {},you have {} now'.format(your_bet,your_money + your_bet))
# your_money = your_money + your_bet
# else:
# print('The points are',total,'you lose!')
# print('you lost {},you have {} now'.format(your_bet,your_money - your_bet))
# your_money = your_money - your_bet
# else:
# print('Invalid mords')
# else:
# print('GAME OVER')
#start_game()
def number_test():
while True:
number = input('Enter your number:')
CN_mobile = [134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705]
CN_union = [130,131,132,155,156,185,186,145,176,1709]
CN_telecom = [133,153,180,181,189,177,1700]
first_three = int(number[0:3])
first_four = int(number[0:4])
if len(number) == 11:
if first_three in CN_mobile or first_four in CN_mobile:
print('Operator: China Mobile')
print('We\'re sending verification code via text to your phone:',number)
break
elif first_three in CN_telecom or first_four in CN_telecom:
print('Operator: China telecom')
print('We\'re sending verification code via to your phone:',number)
break
elif first_three in CN_union or first_four in CN_union:
print('Operator: China Union')
print('We\re sending verification code via to your phone:',number)
break
else:
print('No such a operator')
else:
print('Invalid length ,your number should be in 11 digits')
number_test()
| true |
c5a67e7cf8f9c4f8c29d8dd4de76accd4708debd | rain-mua-le/EarlyPsychosisInterventionComputation | /survey.py | 2,619 | 4.3125 | 4 | #This Python program will output a survey and have users input their responses and record the responses in a file. The program will then create a Prolog program to track in which stage of psychosis the user is in
import os
import pickle
def getInput():
"""
This function receives the user's input and bound checks it
"""
num = int(input("Type in a rating (1-5) and press ENTER: "))
while num < 1 or num > 5:
num = input("Invalid rating. Please try again (1-5): ")
return num
if os.path.isfile("results.p"):
infile = open("results.p", "rb")
results = pickle.load(infile)
infile.close()
else:
results = {"one": [], "two": [], "three": [], "four": [], "five": [], "six": [], "seven": [], "eight": [], "nine": []}
#Survey
print("Please rate how much you agree with the following statements with 1 being strongly disagree and 5 being strongly agree.")
print("-------------------------------------------------------------------")
print("I had felt down or depressed consistently in the last week.")
results["one"].append(getInput())
print("I had felt anxious or uneasy consistently in the last week.")
results["two"].append(getInput())
print("I had difficulty thinking or concentrating in the last week.")
results["three"].append(getInput())
print("I had withdrew from social activity in the last week.")
results["four"].append(getInput())
print("I had felt more irritable over the last week.")
results["five"].append(getInput())
print("I had felt suspicious or paranoid over the last week.")
results["six"].append(getInput())
print("I had strange perceptual experiences in the last week.")
results["seven"].append(getInput())
print("I had trouble maintaining daily living tasks over the last week.")
results["eight"].append(getInput())
print("I had thoughts that my thoughts are being controlled in the last week.")
results["nine"].append(getInput())
#Save results to file
outfile = open("results.p", "wb")
pickle.dump(results, outfile)
outfile.close()
#Create prolog program
prologProgram = open("list.pl", "w")
for key, value in results.items():
string = ""
for elements in value:
string += str(elements) + ","
prologProgram.write(key + "([" + string[: -1] + "]).\n")
if len(value) >= 2:
string = ""
for elements in value[-2 :]:
string += str(elements) + ","
prologProgram.write(key + "_2([" + string[: -1] + "]).\n")
if len(value) >= 4:
string = ""
for elements in value[-4 :]:
string+= str(elements) + ","
prologProgram.write(key + "_4([" + string[: -1] + "]).\n")
| true |
3b87cb2e096ea2f6108ea62ecd7eac084f574d0c | epsilonxe/python | /Lectures/20_function_return.py | 253 | 4.375 | 4 | def absolute(x):
if x >= 0:
abs_x = x
else:
abs_x = -x
return abs_x
print("Finding absolute value")
input_number = float(input("Enter a number: "))
abs_val = absolute(input_number)
print(f"Absolute value of {input_number} is {abs_val}")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.