blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
56df42f25fc0a3dddd57a8d70c63d7a3a4754900
|
devmadhuu/Python
|
/assignment_01/check_substr_in_str.py
| 308
| 4.34375
| 4
|
## Program to check if a Substring is Present in a Given String:
main_str = input ('Enter main string to check substring :')
sub_str = input ('Enter substring :')
if main_str.index(sub_str) > 0:
print('"{sub_str}" is present in main string - "{main_str}"'.format(sub_str = sub_str, main_str = main_str))
| false
|
92d2b840f03db425aaaedf22ad57d0b291bb79e6
|
devmadhuu/Python
|
/assignment_01/odd_in_a_range.py
| 505
| 4.375
| 4
|
## Program to print Odd number within a given range.
start = input ('Enter start number of range:')
end = input ('Enter end number of range:')
if start.isdigit() and end.isdigit():
start = int(start)
end = int(end)
if end > start:
for num in range(start, end):
if num % 2 != 0:
print('Number {num} is odd'.format(num = num))
else:
print('End number should be greater than start number !!!')
else:
print('Enter valid start and end range !!!')
| true
|
020278f3785bb409de5cd0afd67c4ccaf295e011
|
devmadhuu/Python
|
/assignment_01/three_number_comparison.py
| 1,464
| 4.21875
| 4
|
## Program to do number comparison
num1 = input('Enter first number :')
if num1.isdigit() or (num1.count('-') == 1 and num1.index('-') == 0) or num1.count('.') == 1:
num2 = input('Enter second number:')
if num2.isdigit() or (num2.count('-') == 1 and num2.index('-') == 0) or num2.count('.') == 1:
num3 = input('Enter third number:')
if num3.isdigit() or (num3.count('-') == 1 and num3.index('-') == 0) or num3.count('.') == 1:
if num1.count('.') == 1 or num2.count('.') == 1 or num3.count('.') == 1:
operand1 = float(num1)
operand2 = float(num2)
operand3 = float(num3)
else:
operand1 = int(num1)
operand2 = int(num2)
operand3 = int(num3)
if operand1 > operand2 and operand1 > operand3:
print('{operand1} is greater than {operand2} and {operand3}'.format(operand1 = operand1, operand2 = operand2, operand3 = operand3))
elif operand2 > operand1 and operand2 > operand3:
print('{operand2} is greater than {operand1} and {operand3}'.format(operand1 = operand1, operand2 = operand2, operand3 = operand3))
else:
print('{operand3} is greater than {operand1} and {operand2}'.format(operand1 = operand1, operand2 = operand2, operand3 = operand3))
else:
print('Enter valid numeric input')
else:
print('Enter valid numeric input')
| false
|
66c8afbcdd793b3817993abfb904b4ec0111f666
|
devmadhuu/Python
|
/assignment_01/factorial.py
| 410
| 4.4375
| 4
|
## Python program to find the factorial of a number.
userinput = input ('Enter number to find the factorial:')
if userinput.isdigit() or userinput.find('-') >= 0:
userinput = int(userinput)
factorial = 1
for num in range (1, userinput + 1):
factorial*=num
print('Factorial of {a} is {factorial}'.format(a = userinput, factorial = factorial))
else:
print('Enter valid numeric input')
| true
|
83c5184a88d030bfd7d873e728653ac1f0248245
|
alee86/Informatorio
|
/Practic/Estructuras de control/Condicionales/desafio04.py
| 1,195
| 4.28125
| 4
|
'''
Tenemos que decidir entre 2 recetas ecológicas.
Los ingredientes para cada tipo de receta aparecen a continuación.
Ingredientes comunes: Verduras y berenjena.
Ingredientes Receta 1: Lentejas y apio.
Ingredientes Receta 2: Morrón y Cebolla..
Escribir un programa que pregunte al usuario que tipo de receta desea,
y en función de su respuesta le muestre un menú con los ingredientes
disponibles para que elija. Solo se puede eligir 3 ingrediente
(entre la receta elegida y los comunes.) y el tipo de receta.
Al final se debe mostrar por pantalla la receta elegida y todos los ingredientes.
'''
ingredientes_receta1 = "Lenjetas y Apio"
ingredientes_receta2 = "Morrón y Cebolla"
print ("""
*******************************
Menu:
Receta 1: Lentejas y Apio.
Receta 2: Morrón y Cebolla.
*******************************
""")
receta = int(input("Indique si quiere la receta (1) o (2): "))
comun = int(input("Queres agregar Verduras (1) o Berenjenas (2)?"))
if comun == 1:
comun = "Verduras"
else:
comun = "Berenjenas"
if receta == 1:
receta = ingredientes_receta1
else:
receta = ingredientes_receta2
print(f"Su plato tiene los siguientes ingredientes: {comun}, {receta}.")
| false
|
77329d1eb28a5d3565a346a30047871d2306abc6
|
alee86/Informatorio
|
/Practic/Estructuras de control/Repetitivas/desafio01.py
| 1,484
| 4.21875
| 4
|
'''
DESAFÍO 1
Nos han pedido desarrollar una aplicación móvil para reducir comportamientos inadecuados para el ambiente.
a) Te toca escribir un programa que simule el proceso de Login. Para ello el programa debe preguntar
al usuario la contraseña, y no le permita continuar hasta que la haya ingresado correctamente.
b) Modificar el programa anterior para que solamente permita una cantidad fija de intentos.
'''
enter_pass ="1"
true_pass = "123"
user_name = ""
intento = 1
enter_user_name = input("Ingresa tu usuario: ")
enter_pass = str(input("Ingresa tu pass: "))
if enter_pass == true_pass:
print("""
#########################################
Pass correcto... Ingresando a tu cuenta
#########################################""")
else:
print(f"El pass ingresado no es correcto. Tenes 2 intentos más")
enter_pass = str(input("Ingresa tu pass: "))
if enter_pass == true_pass:
print("""
#########################################
Pass correcto... Ingresando a tu cuenta
#########################################""")
else:
print(f"El pass ingresado no es correcto. Tenes 1 intentos más")
enter_pass = str(input("Ingresa tu pass: "))
if enter_pass == true_pass:
print("""
#########################################
Pass correcto... Ingresando a tu cuenta
#########################################""")
else:
print("""
#########################
No tenes mas intentos.
Tu cuenta esa bloqueada.
#########################""")
| false
|
6d030f79eb3df2a3572eaadb0757401d3a330326
|
amark02/ICS4U-Classwork
|
/Quiz2/evaluation.py
| 2,636
| 4.25
| 4
|
from typing import Dict, List
def average(a: float, b: float, c:float) -> float:
"""Returns the average of 3 numbers.
Args:
a: A decimal number
b: A decimal number
c: A decimal number
Returns:
The average of the 3 numbers as a float
"""
return (a + b + c)/3
def count_length_of_wood(wood: List[int], wood_length: int) -> int:
"""Finds how many pieces of wood have a specific
board length.
Args:
wood: A list of integers indicating length of
a piece of wood
wood_length: An integer that specifices what length
of wood a person is looking for
Returns:
How many pieces of wood there are for a specific
board length
e.g.,
wood = [10, 5, 10]
wood_length = 10
return 2
"""
total = 0
for piece in wood:
if piece == wood_length:
total += 1
else:
None
return total
def occurance_of_board_length(board_length: List[int]) -> Dict:
"""Returns a diciontary of the occurances of the length of a board.
Args:
board_length: A list of integers indicating the length
of a piece of wood
Returns:
Dictionary with the key being the length, and the value
being the number of times the length appeares in the list
e.g.,
board_length = [10, 15, 20, 20, 10]
return {10: 2, 15: 1, 20: 2}
"""
occurances = {}
for wood_length in board_length:
if wood_length in occurances.keys():
occurances[wood_length] += 1
else:
occurances[wood_length] = 1
return occurances
def get_board_length(board_length: Dict, wood_length: int) -> int:
"""Finds out how many pieces of wood have a specific
board length.
Args:
board_length: A dictionary with the keys being the board
length and the values being the number of boards with that
specific length
wood_length: An integer that specfies what length of wood
a person is looking for
Returns:
How many pieces of wood there are for a specific board length
"""
#correct answer
for key in board_length.keys():
if key == wood_length:
return board_length[key]
else:
return 0
"""
wrong answer:
list_of_wood = []
for key in board_length.keys():
list_of_wood.append(key)
total = 0
for piece in list_of_wood:
if piece == wood_length:
total += 1
else:
None
return total
"""
| true
|
5b632636066e777092b375219a7a6cd571619157
|
amark02/ICS4U-Classwork
|
/Classes/01_store_data.py
| 271
| 4.1875
| 4
|
class Person:
pass
p = Person()
p.name = "Jeff"
p.eye_color = "Blue"
p2 = Person()
print(p)
print(p.name)
print(p.eye_color)
"""
print(p2.name)
gives an error since the object has no attribute of name
since you gave the other person an attribute on the fly
"""
| true
|
23ee2c8360e32e0334a31da848043cf6187cd636
|
cosinekitty/astronomy
|
/demo/python/gravity.py
| 1,137
| 4.125
| 4
|
#!/usr/bin/env python3
import sys
from astronomy import ObserverGravity
UsageText = r'''
USAGE:
gravity.py latitude height
Calculates the gravitational acceleration experienced
by an observer on the surface of the Earth at the specified
latitude (degrees north of the equator) and height
(meters above sea level).
The output is the gravitational acceleration in m/s^2.
'''
if __name__ == '__main__':
if len(sys.argv) != 3:
print(UsageText)
sys.exit(1)
latitude = float(sys.argv[1])
if latitude < -90.0 or latitude > +90.0:
print("ERROR: Invalid latitude '{}'. Must be a number between -90 and +90.".format(sys.argv[1]))
sys.exit(1)
height = float(sys.argv[2])
MAX_HEIGHT_METERS = 100000.0
if height < 0.0 or height > MAX_HEIGHT_METERS:
print("ERROR: Invalid height '{}'. Must be a number between 0 and {}.".format(sys.argv[1], MAX_HEIGHT_METERS))
sys.exit(1)
gravity = ObserverGravity(latitude, height)
print("latitude = {:8.4f}, height = {:6.0f}, gravity = {:8.6f}".format(latitude, height, gravity))
sys.exit(0)
| true
|
e79076cd45b6280c2046283d9a349620af0f8d70
|
joshinihal/dsa
|
/trees/tree_implementation_using_oop.py
| 1,428
| 4.21875
| 4
|
# Nodes and References Implementation of a Tree
# defining a class:
# python3 : class BinaryTree()
# older than python 3: class BinaryTree(object)
class BinaryTree():
def __init__(self,rootObj):
# root value is also called key
self.key = rootObj
self.leftChild = None
self.rightChild = None
# add new as the left child of root, if a node already exists on left, push it down and make it child's child.
def insertLeft(self,newNode):
if self.leftChild == None:
self.leftChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.leftChild = self.leftChild
self.leftChild = t
# add new as the right child of root, if a node already exists on right, push it down and make it child's child.
def insertRight(self,newNode):
if self.rightChild == None:
self.rightChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.rightChild = self.rightChild
self.rightChild = t
def getLeftChild(self):
return self.leftChild
def getRightChild(self):
return self.rightChild
def setRootValue(self,obj):
self.key = obj
def getRootValue(self):
return self.key
r = BinaryTree('a')
r.getRootValue()
r.insertLeft('b')
r.getLeftChild().getRootValue()
| true
|
74725fc2d2c7d06cec7bc468aa078f59e6aa21e7
|
AGriggs1/Labwork-Fall-2017
|
/hello.py
| 858
| 4.125
| 4
|
# Intro to Programming
# Author: Anthony Griggs
# Date: 9/1/17
##################################
# dprint
# enables or disables debug printing
# Simple function used by many, many programmers, I take no credit for it WHATSOEVER
# to enable, simply set bDebugStatements to true!
##NOTE TO SELF: in Python, first letter to booleans are Capitalized
bDebugStatements = True
def dprint(message):
if (bDebugStatements == True):
print(message)
#Simple function with no specific purpose
def main():
iUsr = eval(input("Gimme a number! Not too little, not too big... "))
dprint("This message is for debugging purposes")
for i in range(iUsr):
#Hmmmm, ideally we don't want a space between (i + 1) and the "!"
#GH! Why does Python automatically add spaces?
print("Hello instructor", i + 1, "!")
print("Good bye!")
dprint("End")
main()
| true
|
f2794e3c31b085db9b10afa837d6026848ef1318
|
lucasferreira94/Python-projects
|
/jogo_da_velha.py
| 1,175
| 4.25
| 4
|
'''
JOGO DA VELHA
'''
# ABAIXO ESTAO AS POSIÇÕES DA CERQUILHA
theBoard = {'top-L':'', 'top-M':'', 'top-R':'',
'mid-L':'','mid-M':'', 'mid-R':'',
'low-L':'', 'low-M':'', 'low-R':''}
print ('Choose one Space per turn')
print()
print(' top-L'+' top-M'+ ' top-R')
print()
print(' mid-L'+' mid-M'+ ' mid-R')
print()
print(' low-L'+' low-M'+ ' low-R ')
print()
# FUNÇÃO PARA PRINTAR A CERQUILHA NA TELA
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] +'|' + board['top-R'])
print('+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
# O JOGO INICIA PELA VEZ DO 'X'
turn = 'X'
for i in range(9):
printBoard(theBoard)
print('Turn for ' + turn + '. Move on wich space? ') # INDICA A VEZ DO JOGADOR
move = input() # O JOGADOR DEVERÁ COLOCAR A POSIÇÃO QUE QUER JOGAR
theBoard[move] = turn # ASSOCIA A JOGADA AO JOGADOR
print()
# CONDICIONAL PARA REALIZAR A MUDANÇA DE JOGADOR
if turn == 'X':
turn = 'O'
else:
turn = 'X'
printBoard(theBoard)
| false
|
a9746ae70ae68aefacd3bb071fae46e949a7e29f
|
YangYishe/pythonStudy
|
/src/day8_15/day8_2.py
| 683
| 4.40625
| 4
|
"""
定义一个类描述平面上的点并提供移动点和计算到另一个点距离的方法。
"""
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
def move(self, x, y):
self._x += x
self._y += y
def distance_between(self, other_point):
return ((self._x - other_point._x) ** 2 + (self._y - other_point._y) ** 2) ** 0.5
def desc(self):
return '{x:%f,y:%f}' % (self._x, self._y)
def main():
p1 = Point(2, 4)
p2 = Point(3, 8)
p1.move(5, -10)
print(p1.desc())
print(p2.desc())
print(f'distance:{p1.distance_between(p2)}')
pass
if __name__ == '__main__':
main()
| false
|
73a9544105ca7eae0d7997aa2e0a4b74bf8723b7
|
SanamKhatri/school
|
/teacher_delete.py
| 1,234
| 4.1875
| 4
|
import teacher_database
from Teacher import Teacher
def delete_teacher():
delete_menu="""
1.By Name
2.By Addeess
3.By Subject
"""
print(delete_menu)
delete_choice=int(input("Enter the delete choice"))
if delete_choice==1:
delete_name=input("Enter the name of the teacher to delete")
t=Teacher(name=delete_name)
is_deleted=teacher_database.delete_by_name(t)
if is_deleted:
print("The data is deleted")
else:
print("There was error in the process")
elif delete_choice==2:
delete_address = input("Enter the address of the teacher to delete")
t = Teacher(address=delete_address)
is_deleted = teacher_database.delete_by_address(t)
if is_deleted:
print("The data is deleted")
else:
print("There was error in the process")
elif delete_choice==3:
delete_subject = input("Enter the subject of the teacher to delete")
t = Teacher(subject=delete_subject)
is_deleted = teacher_database.delete_by_subject(t)
if is_deleted:
print("The data is deleted")
else:
print("There was error in the process")
| true
|
b86433902a7cf3e9dcba2d7f254c4318656ca7f7
|
heba-ali2030/number_guessing_game
|
/guess_game.py
| 2,509
| 4.1875
| 4
|
import random
# check validity of user input
# 1- check numbers
def check_validity(user_guess):
while user_guess.isdigit() == False:
user_guess = input('please enter a valid number to continue: ')
return (int(user_guess))
# 2- check string
def check_name(name):
while name.isalpha() == False:
print('Ooh, Sorry is it your name?!')
name = input('Please enter your name: ')
return name
# begin the game and ask the user to press yes to continue
print(f'Are you ready to play this game : Type Yes button to begin: ')
play = input(f' Type Yes or Y to continue and Type No or N to exit \n ').lower()
if play == 'yes' or play == 'y':
# get user name
name = check_name(input('Enter your name: \n'))
# get the number range from the user
first = check_validity(input('enter the first number you want to play: \n first number: '))
last = check_validity(input('enter the last number of range you want to play: \n last number: '))
# tell the user that range
print (f'Hello {name}, let\'s begin! the number lies between {first} and {last} \n You have 5 trials')
number_to_be_guessed = random.randint(first, last)
# print(number_to_be_guessed)
# Number of times for the guess game to run
run = 1
while run <= 5:
run += 1
user_guess = check_validity(input('what is your guess: '))
# if user guess is in the range
if user_guess in range(first, last):
print('Great beginning, you are inside the right range')
# 1- if the user guess is true
if user_guess == number_to_be_guessed:
print(f'Congratulation, you got it, the number is: {number_to_be_guessed}')
break
# 2- if the guess is high
elif user_guess > number_to_be_guessed:
print(f' Try Again! You guessed too high')
# 3 - if the guess is small
else:
print(f'Try Again! You guessed too small')
# # if the user guess is out of range
else:
print (f'You are out of the valid range, you should enter a number from {first} to {last} only!')
# # when the number of play is over
else:
print(f'{name}, Sorry \n <<< Game is over, Good luck next time , the guessed number is {number_to_be_guessed} >>>')
# # when user type no:
else:
print('Waiting to see you again, have a nice day')
| true
|
01a31344d5f0af270c71baa134890070081a1d5c
|
ColgateLeoAscenzi/COMPUTERSCIENCE101
|
/LAB/Lab01_challenge.py
| 898
| 4.28125
| 4
|
import time
import random
#Sets up the human like AI, and asks a random question every time
AI = random.randint(1,3)
if AI == 1:
print "Please type a number with a decimal!"
elif AI == 2:
print "Give me a decimal number please!"
elif AI == 3:
print "Please enter a decimal number!"
#defines the response and prompts the user to enter a number
response = float(raw_input())
#defines the rounded response and does the math
rounded_response = int(response)+1
#makes the computer seem more human
a = "."
print "Calculating"
time.sleep(0.5)
print(a)
time.sleep(0.5)
print(a)
time.sleep(0.5)
print(a)
time.sleep(1)
#prints the users number rounded up
print "Response calculated!"
time.sleep(1)
print"The rounded up version of your number is: %s" % rounded_response
#adds a delay at the end for the user to reflect upon their answer
time.sleep(3)
| true
|
bc9b0e89b907507970b187a44d0bfc3ecf2d4142
|
ColgateLeoAscenzi/COMPUTERSCIENCE101
|
/LAB/lab03_vowels.py
| 273
| 4.21875
| 4
|
#Leo Ascenzi
#sets up empty string
ohne_vowels = ""
#gets response
resp = str(raw_input("Enter a message: "))
#for loop to check if character is in a string
for char in resp:
if char not in "aeiouAEIOU":
ohne_vowels += char
print ohne_vowels
| false
|
676f4845dc145feee1be508213721e26f2e55b2a
|
ColgateLeoAscenzi/COMPUTERSCIENCE101
|
/HOMEWORK/hw3_leap.py
| 2,055
| 4.15625
| 4
|
# ----------------------------------------------------------
# -------- PROGRAM 3 ---------
# ----------------------------------------------------------
# ----------------------------------------------------------
# Please answer these questions after having completed this
# program
# ----------------------------------------------------------
# Name: Leo Ascenzi
# Hours spent on this program: 0.66
# Collaborators and sources:
# (List any collaborators or sources here.)
# ----------------------------------------------------------
def is_leap_year(y):
if y%4 == 0:
return True
else:
return False
#Anything under 1582 is invalid
invalidrange = range(1582)
#defines start and endyears for future rearranging
startyear = 0
endyear = 0
def main():
#gets inputs
year1 = int(raw_input("Enter a year: "))
year2 = int(raw_input("Enter a second year: "))
#checks valid range
if year1 in invalidrange or year2 in invalidrange:
print "The range must start after or at 1582"
#checks which year is bigger
else:
if year1>year2:
startyear = year2
endyear = year1
elif year2>year1:
startyear = year1
endyear = year2
else:
startyear = year1
endyear = year2
#for all the years more than the start year in the endyear range, print leapyear or nah
for years in range((endyear+1)):
if years<startyear:
pass
else:
if is_leap_year(years):
print years, "is a leap year"
else:
print years, "is a normal year"
# finally, call main. Which makes the code work
main()
| true
|
7004bc9b49acc1a75ac18e448c2256cbec808cf4
|
CodyPerdew/TireDegredation
|
/tirescript.py
| 1,350
| 4.15625
| 4
|
#This is a simple depreciation calculator for use in racing simulations
#Users will note their tire % after 1 lap of testing, this lets us anticipate
#how much any given tire will degrade in one lap.
#From there the depreciation is calculated.
sst=100 #Set tire life to 100%
st=100
mt=100
ht=100
print("when entering degredation use X.XX format")
#Have the user enter their degredation figures after a test lap for each type of tire.
laps = int(input("How many laps to show?")) #how many laps in the race?
ss = float(input("What is the degredation on SuperSoft tires?"))
s = float(input("on Softs?"))
m = float(input("on Medium?"))
h = float(input("on Hards?"))
laps += 1
print("Here's your expected tire life after each lap")
lapcount = 1
while laps > 1: #multiply tire-left * degredation, subtract that amount from tire-left
ssdeg = sst * ss
sst = sst - ssdeg
sdeg = st * s
st = st - sdeg
mdeg = mt * m
mt = mt - mdeg
hdeg = ht * h
ht = ht - hdeg
#print the expected tire life after X laps, ':<5' used for formatting
print("AFTER LAP: {:<5} SST:{:<5} ST:{:<5} MT:{:<5} HT:{:<5}".format(lapcount, round(sst, 1), round(st, 1), round(mt, 1), round(ht, 1)))
laps -= 1
lapcount += 1
| true
|
f0afa65944197e58bad3e76686cef9c2813ab16d
|
chrismlee26/chatbot
|
/sample.py
| 2,521
| 4.34375
| 4
|
# This will give you access to the random module or library.
# choice() will randomly return an element in a list.
# Read more: https://pynative.com/python-random-choice/
from random import choice
#combine functions and conditionals to get a response from the bot
def get_mood_bot_response(user_response):
#add some bot responses to this list
bot_response_happy = ["omg! great!", "Keep smiling!", "I love to see you happy!"]
bot_response_sad = ["im here for you", "sending good vibes", "Ok is fine"]
if user_response == "happy":
return choice(bot_response_happy)
elif user_response == "sad":
return choice(bot_response_sad)
elif user_response == "ok":
return choice(bot_response_sad)
else:
return "I hope your day gets better"
print("Welcome to Mood Bot")
print("Please enter how you are feeling")
user_response = ""
#TODO: we want to keep repeating until the user enters "done" what should we put here?
while True:
user_response = input("How are you feeling today?: ")
# Quits program when user responds with 'done'
if user_response == 'done':
break
bot_response = get_mood_bot_response(user_response)
print(bot_response)
# Create a function called get_bot_response(). This function must:
# It should have 1 parameter called user_response, which is a string with the users input.
# It should return a string with the chat bot’s response.
# It should use at least 2 lists to store at least 3 unique responses to different user inputs. For example, if you were building a mood bot and the user entered “happy” for how they were feeling your happy response list could store something like “I’m glad to hear that!”, “Yay!”, “That is awesome!”.
# Use conditionals to decide which of the response lists to select from. For example: if a user entered “sad”, my program would choose a reponse from the of sad response list. If a user entered “happy”, my program would choose a reponse from the of happy response list.
# Use choice() to randomly select one of the three responses. (See example from class.)
# Greet the user using print() statements and explain what the chat bot topic is and what kind of responses it expects.
# Get user input using the input() function and pass that user input to the get_bot_response() function you will write
# Print out the chat bot’s response that is returned from the get_bot_response() function
# Use a while() loop to keep running your chat bot until the user enters "done".
| true
|
5225e5adf912762cc349331c4276b978190c8bf9
|
kcpedrosa/Python-exercises
|
/ex005.py
| 222
| 4.1875
| 4
|
#faça um programa que fale de sucessor e antecessor
numero = int (input('Digite um numero: '))
ant = numero - 1
suc = numero + 1
print('Urubusevando {}, seu antecessor é {} e seu sucessor é {}'.format(numero, ant, suc))
| false
|
034be106f76495593e2d2acaa5683960bd3be045
|
kcpedrosa/Python-exercises
|
/ex075.py
| 565
| 4.125
| 4
|
#Análise de dados em uma Tupla
numeros = (int(input('Digite o 1º numero: ')), int(input('Digite o 2º numero: ')),
int(input('Digite o 3º numero: ')), int(input('Digite o 4º numero: ')))
print(f'Você digitou os valores {numeros}')
print(f'O valor 9 foi digitado {numeros.count(9)} vez(es)')
if 3 in numeros:
print(f'O primeiro numero 3 está na {numeros.index(3)+1}ª posição')
else:
print(f'O numero 3 não foi digitado')
print('Os numeros pares digitados foram', end=' ')
for n in numeros:
if n % 2 == 0:
print([n], end=' ')
| false
|
e8642c64ba0981f3719635db11e52a0823e89b68
|
league-python/Level1-Module0
|
/_02_strings/_a_intro_to_strings.py
| 2,954
| 4.6875
| 5
|
"""
Below is a demo of how to use different string methods in Python
For a complete reference:
https://docs.python.org/3/library/string.html
"""
# No code needs to be written in this file. Use it as a reference for the
# following projects.
if __name__ == '__main__':
# Declaring and initializing a string variable
new_str = "Welcome to Python!"
# Getting the number of characters in a string
num_characters = len(new_str)
# Getting a character from a string by index--similar to lists
character = new_str[2] # 'l'
print(character)
# Check if a character is a letter or a number
print('Is ' + new_str[2] + ' a letter: ' + str(new_str[2].isalpha()))
print('Is ' + new_str[2] + ' a digit: ' + str(new_str[2].isdigit()))
# Removing leading and trailing whitespace from a string
whitespace_str = ' This string has whitespace '
print('original string .......: ' + whitespace_str + ' ' + str(len(whitespace_str)))
print('leading spaces removed : ' + whitespace_str.lstrip() + ' ' + str(len(whitespace_str.lstrip())))
print('trailing spaces removed: ' + whitespace_str.rstrip() + ' ' + str(len(whitespace_str.rstrip())))
print('leading and trailing spaces removed: ' + whitespace_str.strip() + ' ' + str(len(whitespace_str.strip())))
# Find the number of times a substring (or letter) appears in a string
num_character = new_str.count('o') # 3 occurrences
num_substring = new_str.count('to') # 1 occurrences
print('\'o\' occurs ' + str(num_character) + ' times')
print('\'to\' occurs ' + str(num_substring) + ' times')
# Making a copy of a string
str_copy = new_str[:]
# Convert string to all upper case or lower case
print(str_copy.upper())
print(str_copy.lower())
print(new_str)
# Getting a substring from a string [<stat>:<end>], <end> is NOT inclusive
new_substring1 = new_str[0:7] # 'Welcome'
new_substring2 = new_str[8:10] # 'to
new_substring3 = new_str[11:] # 'Python!'
print(new_substring1)
print(new_substring2)
print(new_substring3)
# Finding the index of the first matching character or substring
index = new_str.find('o')
print('\'o\' 1st appearance at index: ' + str(index))
index = new_str.find('o', index+1)
print('\'o\' 2nd appearance at index: ' + str(index))
# Converting a string to a list
new_str_list = list(new_str)
print(new_str_list)
# Converting a list to a string
back_to_string = ''.join(new_str_list)
print(back_to_string)
# Converting a list to a string with a separator (delimiter)
back_to_string = '_'.join(new_str_list)
print(back_to_string)
# Replacing characters from a string
back_to_string = back_to_string.replace('_', '')
print(back_to_string)
# Splitting a string into a list of strings separated by a space ' '
split_str_list = new_str.split(' ')
print(split_str_list)
| true
|
f17492efff4bbe8ce87a626abfece629c0297a83
|
prajjwalkumar17/DSA_Problems-
|
/dp/length_common_decreasing_subsequence.py
| 1,918
| 4.375
| 4
|
""" Python program to find the Length of Longest Decreasing Subsequence
Given an array we have to find the length of the longest decreasing subsequence that array can make.
The problem can be solved using Dynamic Programming.
"""
def length_longest_decreasing_subsequence(arr, n):
max_len = 0
dp = []
# Initialize the dp array with the 1 as value, as the maximum length
# at each point is atleast 1, by including that value in the sequence
for i in range(n):
dp.append(1)
# Now Lets Fill the dp array in Bottom-Up manner
# Compare Each i'th element to its previous elements from 0 to i-1,
# If arr[i] < arr[j](where j = 0 to i-1), then it qualifies for decreasing subsequence and
# If dp[i] < dp[j] + 1, then that subsequence qualifies for being the longest one
for i in range(0, n):
for j in range(0, i):
if(arr[i] < arr[j] and dp[i] < dp[j] + 1):
dp[i] = dp[j] + 1
# Now Find the largest element in the dp array
max_len = max(dp)
return max_len
if __name__ == '__main__':
print("What is the length of the array? ", end="")
n = int(input())
if n <= 0:
print("No numbers present in the array!!!")
exit()
print("Enter the numbers: ", end="")
arr = [int(x) for x in input().split(' ')]
res = length_longest_decreasing_subsequence(arr, n)
print("The length of the longest decreasing subsequence of the given array is {}".format(res))
"""
Time Complexity - O(n^2), where 'n' is the size of the array
Space Complexity - O(n)
SAMPLE INPUT AND OUTPUT
SAMPLE I
What is the length of the array? 5
Enter the numbers: 5 4 3 2 1
The length of the longest decreasing subsequence of the given array is 5
SAMPLE II
What is the length of the array? 10
Enter the numbers: 15 248 31 66 84 644 54 84 5 88
The length of the longest decreasing subsequence of the given array is 4
"""
| true
|
8c2ae6eaa09ff199ed5dcf711ef7ad9edad03d2a
|
huanhuan18/test04
|
/learn_python/列表练习.py
| 1,081
| 4.25
| 4
|
# 一个学校,有3个办公室,现在有8个老师等待工位的分配,请编写程序完成随机的分配
import random
# 定义学校和办公室
school = [[], [], []]
def create_teachers():
"""创建老师列表"""
# 定义列表保存老师
teacher_list = []
index = 1
while index <= 8:
# 创建老师的名字
teacher_name = '老师' + str(index)
# 把老师装进列表里
teacher_list.append(teacher_name)
index += 1
return teacher_list
teachers_list = create_teachers()
# print(id(teachers_list))
# teachers_list2 = create_teachers()
# print(id(teachers_list2))
# 函数调用多次,每次返回一个新的对象
# 分配老师
for teacher in teachers_list:
# 产生一个办公室编号的随机数
office_number = random.randint(0, 2)
# 给老师随机分配办公室
school[office_number].append(teacher)
# 查看下各个办公室的老师
for office in school:
for person in office:
print(person, end=' ')
print()
| false
|
9686cb889247f42481db72c01407a13fa8f03a49
|
ElTioLevi/mi_primer_programa
|
/adivina_numero.py
| 1,726
| 4.15625
| 4
|
number_to_guess = int((((((((2*5)/3)*8)/2)*7)-(8*3))))
print("El objetivo del juego es adivinar un número entre 1 y 100, tienes 5 intentos")
number_user = int(input("Adivina el número: "))
if number_user == number_to_guess:
print ("Has acertado!!!")
else:
if number_to_guess < number_user:
print("Has fallado, el número a adivinar es menor")
else:
print("Has fallado, el número a adivinar es mayor")
number_user = int(input("Adivina el número: "))
if number_user == number_to_guess:
print("Has acertado!!!")
else:
if number_to_guess < number_user:
print("Has fallado, el número a adivinar es menor")
else:
print("Has fallado, el número a adivinar es mayor")
number_user = int(input("Adivina el número: "))
if number_user == number_to_guess:
print("Has acertado!!!")
else:
if number_to_guess < number_user:
print("Has fallado, el número a adivinar es menor")
else:
print("Has fallado, el número a adivinar es mayor")
number_user = int(input("Adivina el número: "))
if number_user == number_to_guess:
print("Has acertado!!!")
else:
if number_to_guess < number_user:
print("Has fallado, el número a adivinar es menor")
else:
print("Has fallado, el número a adivinar es mayor")
number_user = int(input("Adivina el número: "))
if number_user == number_to_guess:
print("Has acertado!!!")
else:
print("Has perdido el juego")
| false
|
97174dfe60fdb0b7415ba87061573204d41490bc
|
rosa637033/OOAD_project_2
|
/Animal.py
| 597
| 4.15625
| 4
|
from interface import move
class Animal:
#Constructor
def __init__(self, name, move:move):
self.name = name
self._move = move
# any move method that is in class move
def setMove(self, move) -> move:
self._move = move
# This is where strategy pattern is implemented.
def move(self):
self._move.run()
def wake(self):
print("I am awake")
def noise(self):
print("aw")
def eat(self):
print("I am eating")
def roam(self):
print("aw")
def sleep(self):
print("I am going to sleep")
| true
|
fb05fad10a27e03c50ef987443726e2acd11d49a
|
adamchainz/workshop-concurrency-and-parallelism
|
/ex4_big_o.py
| 777
| 4.125
| 4
|
from __future__ import annotations
def add_numbers(a: int, b: int) -> int:
return a + b
# TODO: time complexity is: O(_)
def add_lists(a: list[int], b: list[int]) -> list[int]:
return a + b
# TODO: time complexity is O(_)
# where n = total length of lists a and b
def unique_items(items: list[int]) -> list[int]:
unique: list[int] = []
for item in items:
if item not in unique:
unique.append(item)
return unique
# TODO: time complexity is O(_)
# where n = length of list items
def unique_items_with_set(items: list[int]) -> list[int]:
unique: set[int] = set()
for item in items:
unique.add(item)
return list(unique)
# TODO: time complexity is O(_)
# where n = length of list items
| true
|
12daf4f361701b49e3a14820d6bb91d337497de1
|
bjskkumar/Python_coding
|
/test.py
| 1,591
| 4.28125
| 4
|
# name = "Jhon Smith"
# age = 20
# new_patient = True
#
# if new_patient:
# print("Patient name =", name)
# print("Patient Age = ", age)
#
# obtaining Input
name = input("Enter your name ")
birth_year = input (" Enter birth year")
birth_year= int(birth_year)
age = 2021 - birth_year
new_patient = True
if new_patient:
print("Patient name =", name)
print("Patient Age = ", age)
# String
# Name = "Saravana Kumar"
# print(Name.find("Kumar"))
# print(Name.casefold())
# print(Name.replace("Kumar", "Janaki"))
# print("Kumar" in Name)
# Arithmetic Operations
# X = (10 +5) * 5
# print(X)
# Comparison
# X = 3 > 2
#
# if X:
# print("Greater")
# Logical Operators
# age = 25
#
# print(age >10 and age <30)
#
# print(age>10 or age <30)
#
# print( not age > 30)
# If statements
# Temp = 30
#
# if Temp >20:
# print("its hot")
# elif Temp < 15:
# print("its cool")
#while loops
# i = 1
# while i <= 5:
# print(i * '*')
# i = i+1s
# Lists
# names = ["saravana", "Kumar", "Balakrishnan", "Janaki"]
# print(names[0])
# print(names[1:4])
# for name in names:
# print(name)
# List functions
#
# names = ["saravana", "Kumar", "Balakrishnan", "Janaki"]
# names.append("jhon")
# print(names)
# names.remove("jhon")
# print(names)
# print("Kumar" in names)
# print(len(names))
# for loops
# names = ["saravana", "Kumar", "Balakrishnan", "Janaki"]
#
# for name in names:
# print(name)
#
# for name in range(4):
# print(name)
#
# number = range(4,10)
# for i in number:
# print(i)
# Tuples , immutable
# numbers = (1,2,3)
# print(numbers[0])
| false
|
7c4b8a424c943510052f6b15b10a06a402c06f08
|
prasadnaidu1/django
|
/Adv python practice/QUESTIONS/10.py
| 845
| 4.125
| 4
|
#Question:
#Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically.
#Suppose the following input is supplied to the program:
#hello world and practice makes perfect and hello world again
#Then, the output should be:
#again and hello makes perfect practice world
#Hints:
#In case of input data being supplied to the question, it should be assumed to be a console input.
#We use set container to remove duplicated data automatically and then use sorted() to sort the data.
str=input("enter the data :")
lines=[line for line in str.split()]
#print(" ".join(sorted(list(set((lines))))))
l1=sorted(lines)
print(l1)
l2=list(lines)
print(l2)
l3=sorted(l1)
print(l3)
l4=set(lines)
print(l4)
l5=" ".join(sorted(list(set(lines))))
print(l5)
| true
|
11b760a6ae93888c812d6d2912eb794d98e9c3e0
|
mohadesasharifi/codes
|
/pyprac/dic.py
| 700
| 4.125
| 4
|
"""
Python dictionaries
"""
# information is stored in the list is [age, height, weight]
d = {"ahsan": [35, 5.9, 75],
"mohad": [24, 5.5, 50],
"moein": [5, 3, 20],
"ayath": [1, 1.5, 12]
}
print(d)
d["simin"] = [14, 5, 60]
d.update({"simin": [14, 5, 60]})
print(d)
age = d["mohad"][0]
print(age)
for keys, values in d.items():
print(values, keys)
d["ayath"] = [2]
d.update("ayath")
# Exercises
# 1 Store mohad age in a variable and print it to screen
# 2 Add simin info to the dictionary
# 3 create a new dictionary with the same keys as d but different content i.e occupation
# 4 Update ayath's height to 2 from 1.5
# 5 Write a for loop to print all the keys and values in d
| true
|
b6ba17928cbcb5370f5d144e64353b9d0cd8fcbd
|
Mohsenabdn/projectEuler
|
/p004_largestPalindromeProduct.py
| 792
| 4.125
| 4
|
# Finding the largest palindrome number made by product of two 3-digits numbers
import numpy as np
import time as t
def is_palindrome(num):
""" Input : An integer number
Output : A bool type (True: input is palindrome, False: input is not
palindrome) """
numStr = str(num)
for i in range(len(numStr)//2):
if numStr[i] != numStr[-(i+1)]:
return False
return True
if __name__ == '__main__':
start = t.time()
prods = (np.reshape(np.arange(100, 1000), (1, 900)) *
np.reshape(np.arange(100, 1000), (900, 1)))[np.tril_indices(900)]
prods = np.sort(prods)[::-1]
for j in multiples:
if is_palindrome(j):
print(j)
break
end = t.time()
print('Run time : ' + str(end - start))
| true
|
82aff3d2c7f6ad8e4de6df39d481df878a7450f7
|
sree714/python
|
/printVowel.py
| 531
| 4.25
| 4
|
#4.Write a program that prints only those words that start with a vowel. (use
#standard function)
test_list = ["all", "love", "and", "get", "educated", "by", "gfg"]
print("The original list is : " + str(test_list))
res = []
def fun():
vow = "aeiou"
for sub in test_list:
flag = False
for ele in vow:
if sub.startswith(ele):
flag = True
break
if flag:
res.append(sub)
fun()
print("The extracted words : " + str(res))
| true
|
8d6df43f43f157324d5ce3012252c3c89d8ffba4
|
superyaooo/LanguageLearning
|
/Python/Learn Python The Hard Way/gpa_calculator.py
| 688
| 4.15625
| 4
|
print "Hi,Yao! Let's calculate the students' GPA!"
LS_grade = float(raw_input ("What is the LS grade?")) # define variable with a string and input, no need to use "print" here.
G_grade = float(raw_input ("What is the G grade?")) # double (()) works
RW_grade = float(raw_input ("What is the RW grade?"))
Fin_grade = float(raw_input ("What is the Final exam grade?"))
# raw_input deals with string. needs to be converted into a floating point number
Avg_grade = float((LS_grade*1 + G_grade*2 + RW_grade*2 + Fin_grade*2)/7)
# the outer () here is not necessary
print ("The student's GPA is:"),Avg_grade # allows to show the variable directly
| true
|
86902979397a947dd5d85874129c8d1aab949ac6
|
Vladyslav92/Python_HW
|
/lesson_2/3_task.py
| 536
| 4.21875
| 4
|
# На ввод подается строка. Нужно узнать является ли строка палиндромом.
# (Палиндром - строка которая читается одинаково с начала и с конца.)
enter_string = input('Введите строку: ').lower()
lst = []
for i in enter_string:
lst.append(i)
lst.reverse()
second_string = ''.join(lst)
if second_string == enter_string:
print('Это Палиндром!')
else:
print('Это не Палиндром!')
| false
|
6cefa99cdb92c9ed5738d4a40855a78b22e23b1b
|
Vladyslav92/Python_HW
|
/lesson_8/1_task.py
| 2,363
| 4.34375
| 4
|
# mobile numbers
# https://www.hackerrank.com/challenges/standardize-mobile-number-using-decorators/problem
# Let's dive into decorators! You are given mobile numbers.
# Sort them in ascending order then print them in the standard format shown below:
# +91 xxxxx xxxxx
# The given mobile numbers may have +91, 91 or 0 written before the actual digit number.
# Alternatively, there may not be any prefix at all.
# Input Format
# The first line of input contains an integer, the number of mobile phone numbers.
# lines follow each containing a mobile number.
# Output Format
# Print mobile numbers on separate lines in the required format.
#
# Sample Input
# 3
# 07895462130
# 919875641230
# 9195969878
#
# Sample Output
# +91 78954 62130
# +91 91959 69878
# +91 98756 41230
def phones_fixer(func):
def wrapper(nlist):
result_list = []
for numbr in nlist:
result = list(numbr)
if '+91' in numbr:
if 10 < len(numbr) < 12:
result.insert(3, ' ')
result.insert(-5, ' ')
else:
return 'The number is not correct'
elif len(numbr) == 11:
result.insert(0, '+')
result.insert(1, '9')
result.insert(2, '1')
result.insert(3, ' ')
result.remove(result[4])
result.insert(-5, ' ')
elif len(numbr) == 12:
result.insert(0, '+')
result.insert(3, ' ')
result.insert(-5, ' ')
elif len(numbr) == 10:
result.insert(0, '+')
result.insert(1, '9')
result.insert(2, '1')
result.insert(3, ' ')
result.insert(-5, ' ')
else:
return 'The number is not correct'
result_list.append(''.join(result))
return func(result_list)
return wrapper
@phones_fixer
def sort_numbers(numbers_list):
return '\n'.join(sorted(numbers_list))
def read_numbers():
n = int(input('Количество номеров: '))
numbers = []
for i in range(n):
number = input('Введите номер: ')
numbers.append(number)
return numbers
if __name__ == '__main__':
numbers = read_numbers()
print(sort_numbers(numbers))
| true
|
a1d76dd2a74db5557596f2f3da1fbb2bf70474d2
|
chavadasagar/python
|
/reverse_string.py
| 204
| 4.40625
| 4
|
def reverse_str(string):
reverse_string = ""
for x in string:
reverse_string = x + reverse_string;
return reverse_string
string = input("Enter String :")
print(reverse_str(string))
| true
|
86643c2fe7599d5b77bdcbe3e6c35aa88ba98ecc
|
aemperor/python_scripts
|
/GuessingGame.py
| 2,703
| 4.25
| 4
|
## File: GuessingGame.py
# Description: This is a game that guesses a number between 1 and 100 that the user is thinking within in 7 tries or less.
# Developer Name: Alexis Emperador
# Date Created: 11/10/10
# Date Last Modified: 11/11/10
###################################
def main():
#A series of print statements to let the user know the instructions of the game.
print "Guessing Game"
print ""
print "Directions:"
print "Think of a number between 1 and 100 inclusive."
print "And I will guess what it is in 7 tries or less."
print ""
answer = raw_input ("Are you ready? (y/n): ")
#If the user inputs that "n", no, he is not ready, prompt him over and over
while (answer != "y"):
answer = raw_input ("Are you ready? (y/n): ")
#If the user inputs yes, start the program
if (answer == "y"):
count = 1
hi = 100
lo = 1
mid = (hi+lo)/2
print "Guess",count,": The number you thought was:",mid
correct = raw_input ("Enter 1 if my guess was high, -1 if low, and 0 if correct: ")
while (correct != "0"):
#Iterate a loop that resets when correct isn't equal to zero
while (count < 7):
#Iterate a loop that stops the program when count gets to 7
if (correct == "0"):
print "I win! Thank you for playing the Guessing Game."
break
#If correct == 0 then the program wins
if (correct == "1"):
#If correct == 1 then reset the values of hi and lo to take a new average
hi = mid
lo = lo + 1
mid = (hi+lo)/2
count = count + 1
print "Guess",count, ": The number you thought was:",mid
correct = raw_input ("Enter 1 if my guess was high, -1 if low, and 0 if correct: ")
if (correct == "-1"):
#If correct == -1 then reset the values of hi and lo to take a new average
hi = hi + 1
lo = mid - 1
mid = (hi+lo)/2
count = count + 1
print "Guess",count, ": The number you thought was:",mid
correct = raw_input ("Enter 1 if my guess was high, -1 if low, and 0 if correct: ")
if (count >= 7):
#If count exceeds 7 then the user is not thinking of a number between 1 and 100.
print "The number you are thinking of is not between 1 and 100."
break
main()
| true
|
4978f92dab090fbf4862c4b6eca6db01150cf0b7
|
aemperor/python_scripts
|
/CalcSqrt.py
| 1,059
| 4.1875
| 4
|
# File: CalcSqrt.py
# Description: This program calculates the square root of a number n and returns the square root and the difference.
# Developer Name: Alexis Emperador
# Date Created: 9/29/10
# Date Last Modified: 9/30/10
##################################
def main():
#Prompts user for a + number
n = input ("Enter a positive number: ")
#Checks if the number is positive and if not reprompts the user
while ( n < 0 ):
print ("That's not a positive number, please try again.")
n = input ("Enter a positive number: ")
#Calculates the initial guesses
oldGuess = n / 2.0
newGuess = ((n / oldGuess) + oldGuess) / 2.0
#Loops the algorithm until the guess is below the threshold
while ( abs( oldGuess - newGuess ) > 1.0E-6 ):
oldGuess = newGuess
newGuess = ((n / oldGuess) + oldGuess) / 2.0
#Calculates the difference between the actual square and guessed
diff = newGuess - (n ** .5)
#Prints the results
print 'Square root is: ', newGuess
print 'Difference is: ', diff
main()
| true
|
a7eda8fb8d385472dc0be76be4a5397e7473f724
|
petyakostova/Software-University
|
/Programming Basics with Python/First_Steps_in_Coding/06_Square_of_Stars.py
| 237
| 4.15625
| 4
|
'''Write a console program that reads a positive N integer from the console
and prints a console square of N asterisks.'''
n = int(input())
print('*' * n)
for i in range(0, n - 2):
print('*' + ' ' * (n - 2) + '*')
print('*' * n)
| true
|
3f25e4489c087b731396677d6337e4ad8633e793
|
petyakostova/Software-University
|
/Programming Basics with Python/Simple-Calculations/08-Triangle-Area.py
| 317
| 4.3125
| 4
|
'''
Write a program that reads from the console side and triangle height
and calculates its face.
Use the face to triangle formula: area = a * h / 2.
Round the result to 2 decimal places using
float("{0:.2f}".format (area))
'''
a = float(input())
h = float(input())
area = a * h / 2;
print("{0:.2f}".format(area))
| true
|
87f5fd7703bafe4891fb042de2a7f1770c602995
|
BreeAnnaV/CSE
|
/BreeAnna Virrueta - Guessgame.py
| 771
| 4.1875
| 4
|
import random
# BreeAnna Virrueta
# 1) Generate Random Number
# 2) Take an input (number) from the user
# 3) Compare input to generated number
# 4) Add "Higher" or "Lower" statements
# 5) Add 5 guesses
number = random.randint(1, 50)
# print(number)
guess = input("What is your guess? ")
# Initializing Variables
answer = random.randint(1, 50)
turns_left = 5
correct_guess = False
# This describes ONE turn (This is the game controller)
while turns_left > 0 and correct_guess is False:
guess = int(input("Guess a number between 1 and 50: "))
if guess == answer:
print("You win!")
correct_guess = True
elif guess > answer:
print("Too high!")
turns_left -= 1
elif guess < answer:
print("Too low!")
turns_left -= 1
| true
|
6a59184a4ae0cee597a190f323850bb706c09b11
|
BreeAnnaV/CSE
|
/BreeAnna Virrueta - Hangman.py
| 730
| 4.3125
| 4
|
import random
import string
"""
A general guide for Hangman
1. Make a word bank - 10 items
2. Pick a random item from the list
3. Add a guess to the list of letters guessed Hide the word (use *) (letters_guessed = [...])
4. Reveal letters already guessed
5. Create the win condition
"""
guesses_left = 10
word_bank = ["Environment", "Xylophone", "LeBron James", "Kobe", "Jordan", "Stephen Curry", "Avenue", "Galaxy",
"Snazzy", "The answer is two"]
word_picked = (random.choice(word_bank))
letters_guessed = []
random_word = len(word_picked)
# print(word_picked)
guess = ''
correct = random.choice
while guess != "correct":
guess = ()
for letter in word_picked:
if letter is letters_guessed:
print()
| true
|
6f3f133dbbc8fc6519c54cc234da5b367ee9e80d
|
stark276/Backwards-Poetry
|
/poetry.py
| 1,535
| 4.21875
| 4
|
import random
poem = """
I have half my father's face
& not a measure of his flair
for the dramatic. Never once
have I prayed & had another man's wife
wail in return.
"""
list_of_lines = poem.split("\n")
# Your code should implement the lines_printed_backwards() function.
# This function takes in a list of strings containing the lines of your
# poem as arguments and will print the poem lines out in reverse with the line numbers reversed.
def lines_printed_backwards(list_of_lines):
for lines in list_of_lines:
list_of_lines.reverse()
print(list_of_lines)
def lines_printed_random(list_of_lines):
"""Your code should implement the lines_printed_random() function which will randomly select lines from a list of strings and print them out in random order. Repeats are okay and the number of lines printed should be equal to the original number of lines in the poem (line numbers don't need to be printed). Hint: try using a loop and randint()"""
for lines in list_of_lines:
print(random.choice(list_of_lines))
def my_costum_function(list_of_lines):
""""Your code should implement a function of your choice that rearranges the poem in a unique way, be creative! Make sure that you carefully comment your custom function so it's clear what it does."""
# IT's going to delete the last line
for lines in list_of_lines:
list_of_lines.pop()
print(list_of_lines)
lines_printed_backwards(list_of_lines)
lines_printed_random(list_of_lines)
my_costum_function(list_of_lines)
| true
|
955d4bebf2c1c01ac20c697a2bba0809a4b51b46
|
patilpyash/practical
|
/largest_updated.py
| 252
| 4.125
| 4
|
print("Program To Find Largest No Amont 2 Nos:")
print("*"*75)
a=int(input("Enter The First No:"))
b=int(input("Enter The Second No:"))
if a>b:
print("The Largest No Is",a)
else:
print("The Largest No Is",b)
input("Enter To Continue")
| true
|
9302fbf822224f10935dc423d35b283bf41b2609
|
MinhTamPhan/LearnPythonTheHardWay
|
/Exercise/Day5.3/ex42.py
| 1,371
| 4.34375
| 4
|
## Animal is-a object (yes, sort of confusing) look at the extra credit
class Animal(object):
pass
## Dog is-a object
class Dog(Animal):
def __init__(self, name):
## set attribul name = name
self.name = name
## Cat is-a object
class Cat(object):
def __init__(self, name):
## set name of Cat
self.name = name
## Person is-a object
class Person(object):
def __init__(self, name):
## set name of person
self.name = name
## Person has-a pet of some kind
self.pet = None
## Employee is-a object
class Employee(Person):
def __init__(self, name, salary):
## ?? hm what is this strage magic
super(Employee, self).__init__(name)
## set salary = salary
self.salary = salary
## Fish is-a object
class Fish(object):
pass
## Salmon is-a object
class Salmon(Fish):
pass
## Hailibut is-a object
class Hailibut(Fish):
pass
## rover is-a Dog
rover = Dog("Rover")
## satan is-a Cat
satan = Cat("Satan")
## mary is-a Person
mary = Person("Mary")
## mary has-a pet is satan
mary.pet = satan
## frank is-a Employee has-salary is 120000
frank = Employee("Frank", 120000)
## frank has-a pet is rover and it is a Dog
frank.pet = rover
## flipper is-a fish()
flipper = Fish()
## crouse is-a Salmon
crouse = Salmon()
## harry is-a halibut
harry = Hailibut()
print "Name: ", frank.name , "Pet: ",
print frank.pet.name ,"salary: ", frank.salary
| false
|
b939c070c0cbdfa664cea3750a0a6805af4c6a10
|
Yatin-Singla/InterviewPrep
|
/Leetcode/RouteBetweenNodes.py
| 1,013
| 4.15625
| 4
|
# Question: Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
# Explanation
"""
I would like to use BFS instead of DFS as DFS might pigeonhole our search through neighbor's neighbor whereas the target
might the next neighbor
Additionally I'm not using Bi-directional search because I'm not sure if there is a path from target to root,
Worst case scenario efficiency would be the same
"""
# Solution:
from queue import LifoQueue as Queue
def BFS(start, finish) -> bool:
if not start or not finish:
return False
Q = Queue()
# marked is a flag to indicate that the node has already been enqueued
start.marked = True
Q.enqueue(start)
# process all nodes
while not Q.isEmpty():
node = Q.dequeue()
if node == target:
return True
for Neighbor in node.neighbors:
if not Neighbor.marked:
Neighbor.marked = True
Q.enqueue(Neighbor)
return True
| true
|
e92e09888bff7072f27d3d24313f3d53e37fc7dc
|
Yatin-Singla/InterviewPrep
|
/Leetcode/Primes.py
| 609
| 4.1875
| 4
|
'''
Write a program that takes an integer argument and returns all the rpimes between 1 and that integer.
For example, if hte input is 18, you should return <2,3,5,7,11,13,17>.
'''
from math import sqrt
# Method name Sieve of Eratosthenes
def ComputePrimes(N: int) -> [int]:
# N inclusive
ProbablePrimes = [True] * (N+1)
answer = []
for no in range(2,N+1):
if ProbablePrimes[no] == True:
answer.append(no)
for i in range(no*2, N+1, no):
ProbablePrimes[i] = False
return answer
if __name__ == "__main__":
print(ComputePrimes(100))
| true
|
b9a12d0975be4ef79abf88df0b083da68113e76b
|
Yatin-Singla/InterviewPrep
|
/Leetcode/ContainsDuplicate.py
| 730
| 4.125
| 4
|
# Given an array of integers, find if the array contains any duplicates.
# Your function should return true if any value appears at least twice in the array,
# and it should return false if every element is distinct.
# * Example 1:
# Input: [1,2,3,1]
# Output: true
# * Example 2:
# Input: [1,2,3,4]
# Output: false
# * Example 3:
# Input: [1,1,1,3,3,4,3,2,4,2]
# Output: true
def isDuplicates(nums):
if not nums:
return False
if len(nums) == 1:
return False
unique = set()
for item in nums:
if item not in unique:
unique.add(item)
else:
return True
return False
def containsDuplicate(nums):
return True if len(set(nums)) < len(nums) else False
| true
|
b459e8a597c655f68401d3c8c73a68decfba186e
|
Yatin-Singla/InterviewPrep
|
/Leetcode/StringCompression.py
| 1,090
| 4.4375
| 4
|
'''
Implement a method to perform basic string compression using the counts of repeated characters.
For example, the string aabccccaa would become a2b1c5a3.
If the compressed string would not become smaller than the original string,
you method should return the original string. Assume the string has only uppercase and lowercase letters.
'''
def StringCompression(charString):
counter = 1
result = []
for index in range(1,len(charString)):
if charString[index] == charString[index-1]:
counter += 1
else:
# doubtful if ''.join would work on int type list
result.extend([charString[index-1],str(counter)])
counter = 1
result.extend([charString[-1], str(counter)])
return ''.join(result) if len(result) < len(charString) else charString
# more efficient solution would be where we first estimate the length the length of the compressed string
# rather than forming the string and figuring out which one to return.
if __name__ == "__main__":
print(StringCompression("aabccccaaa"))
| true
|
74d654a737cd20199860c4a8703663780683cea4
|
quanzt/LearnPythons
|
/src/guessTheNumber.py
| 659
| 4.25
| 4
|
import random
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')
#Ask the player to guess 6 times.
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low')
elif guess > secretNumber:
print('Your guess is too high')
else:
break
if guess == secretNumber:
print(f'Good job. You are correct. The secret number is {str(secretNumber)}')
else:
print('Sorry, your guess is wrong. The secret number is {}'.format(secretNumber))
#
# for i in range(20):
# x = random.randint(1, 3)
# print(x)
| true
|
0a5d7f42c11be6f4fb2f9ede8340876192080d8d
|
Dana-Georgescu/python_challenges
|
/diagonal_difference.py
| 631
| 4.25
| 4
|
#!/bin/python3
''' Challenge from https://www.hackerrank.com/challenges/diagonal-difference/problem?h_r=internal-search'''
#
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
def diagonalDifference():
arr = []
diagonal1 = diagonal2 = 0
n = int(input().strip())
for s in range(n):
arr.append(list(map(int, input().rstrip().split())))
for i in range(n):
diagonal1 += arr[i][i]
diagonal2 += arr[i][-(i+1)]
return abs(diagonal1 - diagonal2)
print(diagonalDifference())
| true
|
537eb97c8fa707e1aee1881d95b2bf497123fd67
|
jeffsilverm/big_O_notation
|
/time_linear_searches.py
| 2,520
| 4.25
| 4
|
#! /usr/bin/env python
#
# This program times various search algorithms
# N, where N is the size of a list of strings to be sorted. The key to the corpus
# is the position of the value to be searched for in the list.
# N is passed as an argument on the command line.
import linear_search
import random
import sys
corpus = []
value_sought_idx = -1
def random_string( length ):
"""This function returns a random ASCII string of length length"""
s = ''
for i in range(length ):
# Generate a random printable ASCII character. This assumes that space is a
# printable character, if you don't like that, then use ! )
s = s + ( chr( random.randint(ord(' '), ord('~') ) ) )
return str( s )
def create_corpus(N):
"""This function returns a corpus to search in. It generates a sorted list
of values which are random strings. It then sorts the list. Once the corpus
is created, it gets saved as a global variable so that it will persist"""
global corpus
global value_sought_idx
for i in range(N):
corpus.append( random_string(6))
# corpus.sort() # linear search does not need the corpus to be sorted
value_sought_idx = random.randint(0,N-1)
return
def call_linear_search(value_sought):
"""Call the iterative version of the binary search"""
# We need to do make a subroutine call in the scope of time_searches so we can
# pass the global variable corpus. corpus is out of scope of the actual
# binary search routine, so we have to pass it (it gets passed by reference,
# which is fast)
linear_search.linear_search(corpus, value_sought)
N = int(sys.argv[1])
create_corpus(N)
if __name__ == '__main__':
import timeit
number = 100 # number of iterations
tq = '"""' # Need to insert a triple quote into a string
value_sought = corpus[value_sought_idx]
# This is a little pythonic trickery. The input to the timeit.timeit method is
# a snippet of code, which gets executed number of times. In order to
# parameterize the code, use string substitution, the % operator, to modify the
# string. Note that this code has to import itself in order to get the
# subroutines in scope.
linear_call_str = "time_linear_searches.call_linear_search( " + \
tq + value_sought + tq + ")"
linear_time = timeit.timeit(linear_call_str, \
setup="import time_linear_searches", number=number)
print "linear search: %.2e" % linear_time
| true
|
abbb02f14ecbea14004de28fc5d5daddf65bb63e
|
jeffsilverm/big_O_notation
|
/iterative_binary_search.py
| 1,292
| 4.1875
| 4
|
#! /usr/bin/env python
#
# This program is an implementation of an iterative binary search
#
# Algorithm from http://rosettacode.org/wiki/Binary_search#Python
def iterative_binary_search(corpus, value_sought) :
"""Search for value_sought in corpus corpus"""
# Note that because Python is a loosely typed language, we generally don't
# care about the datatype of the corpus
low = 0
high = len(corpus)-1
while low <= high:
mid = (low+high)//2
if corpus[mid] > value_sought: high = mid-1
elif corpus[mid] < value_sought: low = mid+1
else: return mid # Return the index where the value was found.
return -1 # indicate value not found
if "__main__" == __name__ :
import time_searches # We need this to create the corpus and value_sought
value_sought = time_searches.corpus[time_searches.value_sought_idx]
print "The value sought is %s" % value_sought
print "The size of the corpus is %d" % len ( time_searches.corpus )
answer_idx = iterative_binary_search(time_searches.corpus, value_sought)
print "The answer is at %d and is %s" % ( answer_idx,
time_searches.corpus[answer_idx] )
print "The correct answer is %d" % time_searches.value_sought_idx
| true
|
0fd4177666e9d395da20b8dfbfae9a300e53f873
|
jhoneal/Python-class
|
/pin.py
| 589
| 4.25
| 4
|
"""Basic Loops
1. PIN Number
Create an integer named [pin] and set it to a 4-digit number.
Welcome the user to your application and ask them to enter their pin.
If they get it wrong, print out "INCORRECT PIN. PLEASE TRY AGAIN"
Keep asking them to enter their pin until they get it right.
Finally, print "PIN ACCEPTED. YOU HAVE $0.00 IN YOUR ACCOUNT. GOODBYE."""
pin = 9999
num = int(input("Welcome to this application. Please enter your pin: "))
while num != pin:
num = int(input("INCORRECT PIN. PLEASE TRY AGAIN: "))
print("PIN ACCEPTED. YOU HAVE $0.00 IN YOUR ACCOUNT. GOODBYE.")
| true
|
51d409c780d13e35d3a4626a10273ef0d32e03a6
|
Raivias/assimilation
|
/old/vector.py
| 1,173
| 4.25
| 4
|
class Vector:
"""
Class to use of pose, speed, and accelertation. Generally anything that has three directional components
"""
def __init__(self, a, b, c):
"""
The three parts of the set
:param a: x, i, alpha
:param b: y, j, beta
:param c: z, k, gamma
"""
self.a = a
self.b = b
self.c = c
def __add__(self, other):
a = self.a + other.a
b = self.b + other.b
c = self.c + other.c
return Vector(a, b, c)
def __sub__(self, other):
a = self.a - other.a
b = self.b - other.b
c = self.c - other.c
return Vector(a, b, c)
def __mul__(self, other):
if other is Vector:
return self.cross_mul(other)
def cross_mul(self, other):
"""
Cross multiply
:param other: Another Vector
:return: Cross multiple of two matices
"""
a = (self.b * other.c) - (self.c * other.b)
b = (self.c * other.a) - (self.a * other.c)
c = (self.a * other.b) - (self.b * other.a)
return Vector(a, b, c)
def scalar_mul(self, other):
pass
| false
|
bf92d64a05ccf277b13dd50b1e21f261c5bba43c
|
NikitaBoers/improved-octo-sniffle
|
/averagewordlength.py
| 356
| 4.15625
| 4
|
sentence=input('Write a sentence of at least 10 words: ')
wordlist= sentence.strip().split(' ')
for i in wordlist:
print(i)
totallength= 0
for i in wordlist :
totallength =totallength+len(i)
averagelength=totallength/ len(wordlist)
combined_string= "The average length of the words in this sentence is "+str(averagelength)
print(combined_string)
| true
|
292ad196eaee7aab34dea95ac5fe622281b1a845
|
LJ1234com/Pandas-Study
|
/06-Function_Application.py
| 969
| 4.21875
| 4
|
import pandas as pd
import numpy as np
'''
pipe(): Table wise Function Application
apply(): Row or Column Wise Function Application
applymap(): Element wise Function Application on DataFrame
map(): Element wise Function Application on Series
'''
############### Table-wise Function Application ###############
def adder(ele1, ele2):
return ele1 + ele2
df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3'])
print(df)
df2 = df.pipe(adder, 2)
print(df2)
############### Row or Column Wise Function Application ###############
print(df.apply(np.mean)) # By default, the operation performs column wise
print(df.mean())
print(df.apply(np.mean,axis=1)) # operations can be performed row wise
print(df.mean(1))
df2 = df.apply(lambda x: x - x.min())
print(df2)
############### Element wise Function Application ###############
df['col1'] = df['col1'].map(lambda x: x * 100)
print(df)
df = df.applymap(lambda x:x*100)
print(df)
| true
|
e45c11a712bf5cd1283f1130184340c4a8280d13
|
LJ1234com/Pandas-Study
|
/21-Timedelta.py
| 642
| 4.125
| 4
|
import pandas as pd
'''
-String: By passing a string literal, we can create a timedelta object.
-Integer: By passing an integer value with the unit, an argument creates a Timedelta object.
'''
print(pd.Timedelta('2 days 2 hours 15 minutes 30 seconds'))
print(pd.Timedelta(6,unit='h'))
print(pd.Timedelta(days=2))
################## Operations ##################
s = pd.Series(pd.date_range('2012-1-1', periods=3, freq='D'))
td = pd.Series([ pd.Timedelta(days=i) for i in range(3) ])
df = pd.DataFrame(dict(A = s, B = td))
print(df)
## Addition
df['C']=df['A'] + df['B']
print(df)
## Subtraction
df['D']=df['C']-df['B']
print(df)
| true
|
4c4d5e88fde9f486210ef5bd1595775e0adce53c
|
aiworld2020/pythonprojects
|
/number_99.py
| 1,433
| 4.125
| 4
|
answer = int(input("I am a magician and I know what the answer will be: "))
while (True):
if answer < 10 or answer > 49:
print("The number chosen is not between 10 and 49")
answer = int(input("I am choosing a number from 10-49, which is: "))
continue
else:
break
factor = 99 - answer
print("Now I subtracted my answer from 99, which is " + str(factor))
friend_guess = int(input("Now you have to chose a number from 50-99, which is: "))
while (True):
if friend_guess < 50 or friend_guess > 99:
print("The number chosen is not between 50 and 99")
friend_guess = int(input("Now you have to chose a number from 50-99, which is: "))
continue
else:
break
three_digit_num = factor + friend_guess
print("Now I added " + str(factor) + " and " + str(friend_guess) + " to get " + str(three_digit_num))
one_digit_num = three_digit_num//100
two_digit_num = three_digit_num - 100
almost_there = two_digit_num + one_digit_num
print("Now I added the hundreds digit of " + str(three_digit_num) + " to the tens and ones digit of " + str(three_digit_num) + " to get " + str(almost_there))
final_answer = friend_guess - almost_there
print("Now I subtracted your number, " + str(friend_guess) + " from " + str(almost_there) + " to get " + str(final_answer))
print("The final answer, " + str(final_answer) + " is equal to my answer from the beginning, " + str(answer))
| true
|
5608d39b85560dc2ea91e943d60716901f5fe88b
|
longroad41377/selection
|
/months.py
| 337
| 4.4375
| 4
|
monthnames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
month = int(input("Enter month number: "))
if month > 0 and month < 13:
print("Month name: {}".format(monthnames[month-1]))
else:
print("Month number must be between 1 and 12")
| true
|
087a85027a5afa03407fed80ccb82e466c4f46ed
|
ch-bby/R-2
|
/ME499/Lab_1/volumes.py
| 2,231
| 4.21875
| 4
|
#!\usr\bin\env python3
"""ME 499 Lab 1 Part 1-3
Samuel J. Stumbo
This script "builds" on last week's volume calculator by placing it within the context of a function"""
from math import pi
# This function calculates the volumes of a cylinder
def cylinder_volume(r, h):
if type(r) == int and type(h) == int:
float(r)
float(h)
if r < 0 or h < 0:
return None
# print('you may have entered a negative number')
else:
volume = pi * r ** 2 * h
return volume
elif type(r) == float and type(h) == float:
if r < 0 or h < 0:
return None
else:
volume = pi * r ** 2 * h
return volume
else:
# print("You must have entered a string!")
return None
# This function calculates the volume of a torus
def volume_tor(inner_radius, outer_radius):
if type(inner_radius) == int and type(outer_radius) == int:
float(inner_radius)
float(outer_radius)
if inner_radius < 0 or outer_radius < 0:
return None
else:
if inner_radius > outer_radius:
return None
elif inner_radius == outer_radius:
return None
else:
r_mid = (inner_radius + outer_radius) / 2 # Average radius of torus
r_circle = (outer_radius - inner_radius) / 2 # Radius of donut cross-section
volume = (pi * r_circle ** 2) * (2 * pi * r_mid)
return volume
elif type(inner_radius) == float and type(outer_radius) == float:
if r < 0 and h < 0:
return None
else:
if inner_radius > outer_radius:
return None
elif inner_radius == outer_radius:
return None
else:
r_mid = (inner_radius + outer_radius) / 2 # Average radius of torus
r_circle = (outer_radius - inner_radius) / 2 # Radius of donut cross-section
volume = (pi * r_circle ** 2) * (2 * pi * r_mid)
return volume
else:
return None
if __name__ == '__main__':
print(cylinder_volume(3, 1))
print(volume_tor(-2, 7))
| true
|
d571d28325d7278964d45a25a4777cf8f121f0ce
|
ch-bby/R-2
|
/ME499/Lab4/shapes.py
| 1,430
| 4.46875
| 4
|
#!/usr/bin/env python3#
# -*- coding: utf-8 -*-
"""
****************************
ME 499 Spring 2018
Lab_4 Part 1
3 May 2018
Samuel J. Stumbo
****************************
"""
from math import pi
class Circle:
"""
The circle class defines perimeter, diameter and area of a circle
given the radius, r.
"""
def __init__(self, r):
if r <= 0:
raise 'The radius must be greater than 0!'
self.r = r
def __str__(self):
return 'Circle, radius {0}'.format(self.r)
def area(self):
return pi * self.r ** 2
def diameter(self):
return 2 * self.r
def perimeter(self):
return 2 * pi * self.r
class Rectangle:
"""
The rectangle class has attributes of a rectangle, perimeter and area
"""
def __init__(self, length, width):
if length <= 0 or width <= 0:
raise 'The length and width must both be positive values.'
self.length = length
self.width = width
def __str__(self):
return 'Rectangle, length {0} and width {1}'.format(self.length, self.width)
def area(self):
return self.length * self.width
def perimeter(self):
return self.length * 2 + self.width * 2
if __name__ == '__main__':
c = Circle(1)
r = Rectangle(2, 4)
shapes = [c, r]
for s in shapes:
print('{0}: {1}, {2}'.format(s, s.area(), s.perimeter()))
| true
|
13238ec3b96e2c1297fa1548f14d19860fbe222d
|
GeeB01/Codigos_guppe
|
/objetos.py
| 1,007
| 4.3125
| 4
|
"""
Objetos -> São instancias das classe, ou seja, após o mapeamento do objeto do mundo real para a sua
representação computacional, devemos poder criar quantos objetos forem necessarios.
Podemos pensar nos objetos/instancia de uma classe como variaveis do tipo definido na classe
"""
class Lampada:
def __init__(self, cor, voltagem, luminosidade):
self.__cor = cor
self.__voltagem = voltagem
self.__luminosidade = luminosidade
def mostra_cor(self):
print(self.__cor)
class ContaCorrente:
contador = 1234
def __init__(self, limite, saldo):
self.__numero = ContaCorrente.contador + 1
self.__limite = limite
self.__saldo = saldo
ContaCorrente.contador = self.__numero
class Usuario:
def __init__(self, nome, sobrenome, email, senha):
self.__nome = nome
self.__sobrenome = sobrenome
self.__email = email
self.__senha = senha
lamp1 = Lampada('qazu', '110', 'aaa')
lamp1.mostra_cor()
| false
|
d8e32ee5aed3b8c943bbaf05545f547e2f27d464
|
AnnKuz1993/Python
|
/lesson_02/example_03.py
| 1,893
| 4.25
| 4
|
# Пользователь вводит месяц в виде целого числа от 1 до 12.
# Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
# Напишите решения через list и через dict.
month_list = ['зима', 'весна', 'лето', 'осень']
month_dict = {1: 'зима', 2: 'весна', 3: 'лето', 4: 'осень'}
num_month = int(input("Введите номер месяца от 1 до 12 >>> "))
if num_month == 1 or num_month == 2 or num_month == 12:
print("Время года для этого месца >>> ", month_dict.get(1))
elif num_month == 3 or num_month == 4 or num_month == 5:
print("Время года для этого месца >>> ", month_dict.get(2))
elif num_month == 6 or num_month == 7 or num_month == 8:
print("Время года для этого месца >>> ", month_dict.get(3))
elif num_month == 9 or num_month == 10 or num_month == 11:
print("Время года для этого месца >>> ", month_dict.get(4))
else:
print("Ввели неверное число! Такого месяца не существует!")
if num_month == 1 or num_month == 2 or num_month == 12:
print("Время года для этого месца >>> ", month_list[0])
elif num_month == 3 or num_month == 4 or num_month == 5:
print("Время года для этого месца >>> ", month_list[1])
elif num_month == 6 or num_month == 7 or num_month == 8:
print("Время года для этого месца >>> ", month_list[2])
elif num_month == 9 or num_month == 10 or num_month == 11:
print("Время года для этого месца >>> ", month_list[3])
else:
print("Ввели неверное число! Такого месяца не существует!")
| false
|
96cd937cfe7734c8fae5348b53517271e3c59321
|
AnnKuz1993/Python
|
/lesson_03/example_01.py
| 791
| 4.125
| 4
|
# Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
# Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
def num_division():
try:
a = int(input("Введите первое число: "))
b = int(input("Введите второе число: "))
return print("Результат деления первого числа на второе →",a / b)
except ZeroDivisionError:
return "На 0 делить нельзя!"
except ValueError:
return "Ввели неверное значение!"
num_division()
| false
|
393dffa71a0fdb1a5ed69433973afd7d6c73d9ff
|
neelismail01/common-algorithms
|
/insertion-sort.py
| 239
| 4.15625
| 4
|
def insertionSort(array):
# Write your code here.
for i in range(1, len(array)):
temp = i
while temp > 0 and array[temp] < array[temp - 1]:
array[temp], array[temp - 1] = array[temp - 1], array[temp]
temp -= 1
return array
| true
|
df11433519e87b3a52407745b274a6db005d767c
|
jtquisenberry/PythonExamples
|
/Interview_Cake/hashes/inflight_entertainment_deque.py
| 1,754
| 4.15625
| 4
|
import unittest
from collections import deque
# https://www.interviewcake.com/question/python/inflight-entertainment?section=hashing-and-hash-tables&course=fc1
# Use deque
# Time = O(n)
# Space = O(n)
# As with the set-based solution, using a deque ensures that the second movie is not
# the same as the current movie, even though both could have the same length.
def can_two_movies_fill_flight(movie_lengths, flight_length):
# Determine if two movie runtimes add up to the flight length
# And do not show the same movie twice.
lengths = deque(movie_lengths)
while len(lengths) > 0:
current_length = lengths.popleft()
second_length = flight_length - current_length
if second_length in lengths:
return True
return False
# Tests
class Test(unittest.TestCase):
def test_short_flight(self):
result = can_two_movies_fill_flight([2, 4], 1)
self.assertFalse(result)
def test_long_flight(self):
result = can_two_movies_fill_flight([2, 4], 6)
self.assertTrue(result)
def test_one_movie_half_flight_length(self):
result = can_two_movies_fill_flight([3, 8], 6)
self.assertFalse(result)
def test_two_movies_half_flight_length(self):
result = can_two_movies_fill_flight([3, 8, 3], 6)
self.assertTrue(result)
def test_lots_of_possible_pairs(self):
result = can_two_movies_fill_flight([1, 2, 3, 4, 5, 6], 7)
self.assertTrue(result)
def test_only_one_movie(self):
result = can_two_movies_fill_flight([6], 6)
self.assertFalse(result)
def test_no_movies(self):
result = can_two_movies_fill_flight([], 2)
self.assertFalse(result)
unittest.main(verbosity=2)
| true
|
fcbb62045b3d953faf05dd2b741cd060376ec237
|
jtquisenberry/PythonExamples
|
/Jobs/maze_runner.py
| 2,104
| 4.1875
| 4
|
# Alternative solution at
# https://www.geeksforgeeks.org/shortest-path-in-a-binary-maze/
# Maze Runner
# 0 1 0 0 0
# 0 0 0 1 0
# 0 1 0 0 0
# 0 0 0 1 0
# 1 - is a wall
# 0 - an empty cell
# a robot - starts at (0,0)
# robot's moves: 1 step up/down/left/right
# exit at (N-1, M-1) (never 1)
# length(of the shortest path from start to the exit), -1 when exit is not reachable
# time: O(NM), N = columns, M = rows
# space O(n), n = size of queue
from collections import deque
import numpy as np
def run_maze(maze):
rows = len(maze)
cols = len(maze[0])
row = 0
col = 0
distance = 1
next_position = deque()
next_position.append((row, col, distance))
# successful_routes = list()
while len(next_position) > 0:
array2 = np.array(maze)
print(array2)
print()
current_row, current_column, current_distance = next_position.popleft()
if current_row == rows - 1 and current_column == cols - 1:
return current_distance
# successful_routes.append(current_distance)
maze[current_row][current_column] = 8
if current_row > 0:
up = (current_row - 1, current_column, current_distance + 1)
if maze[up[0]][up[1]] == 0:
next_position.append(up)
if current_row + 1 < rows:
down = (current_row + 1, current_column, current_distance + 1)
if maze[down[0]][down[1]] == 0:
next_position.append(down)
if current_column > 0:
left = (current_row, current_column - 1, current_distance + 1)
if maze[left[0]][left[1]] == 0:
next_position.append(left)
if current_column + 1 < cols:
right = (current_row, current_column + 1, current_distance + 1)
if maze[right[0]][right[1]] == 0:
next_position.append(right)
return -1
if __name__ == '__main__':
maze = [
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 1, 0]]
length = run_maze(maze)
print(length)
| true
|
ba8395ab64f7ebb77cbfdb205d828aa552802505
|
jtquisenberry/PythonExamples
|
/Interview_Cake/arrays/reverse_words_in_list_deque.py
| 2,112
| 4.25
| 4
|
import unittest
from collections import deque
# https://www.interviewcake.com/question/python/reverse-words?section=array-and-string-manipulation&course=fc1
# Solution with deque
def reverse_words(message):
if len(message) < 1:
return message
final_message = deque()
current_word = []
for i in range(0, len(message)):
character = message[i]
if character != ' ':
current_word.append(character)
if character == ' ' or i == len(message) - 1:
# Use reversed otherwise extend puts characters in the wrong order.
final_message.extendleft(reversed(current_word))
current_word = []
if i != len(message) - 1:
final_message.extendleft(' ')
for i in range(0, len(message)):
message[i] = list(final_message)[i]
return list(final_message)
# Tests
class Test(unittest.TestCase):
def test_one_word(self):
message = list('vault')
reverse_words(message)
expected = list('vault')
self.assertEqual(message, expected)
def test_two_words(self):
message = list('thief cake')
reverse_words(message)
expected = list('cake thief')
self.assertEqual(message, expected)
def test_three_words(self):
message = list('one another get')
reverse_words(message)
expected = list('get another one')
self.assertEqual(message, expected)
def test_multiple_words_same_length(self):
message = list('rat the ate cat the')
reverse_words(message)
expected = list('the cat ate the rat')
self.assertEqual(message, expected)
def test_multiple_words_different_lengths(self):
message = list('yummy is cake bundt chocolate')
reverse_words(message)
expected = list('chocolate bundt cake is yummy')
self.assertEqual(message, expected)
def test_empty_string(self):
message = list('')
reverse_words(message)
expected = list('')
self.assertEqual(message, expected)
unittest.main(verbosity=2)
| true
|
9adfabfbc83b97a11ee5b2f23cea5ec2eb357dd5
|
jtquisenberry/PythonExamples
|
/Interview_Cake/sorting/merge_sorted_lists3.py
| 1,941
| 4.21875
| 4
|
import unittest
from collections import deque
# https://www.interviewcake.com/question/python/merge-sorted-arrays?course=fc1§ion=array-and-string-manipulation
def merge_lists(my_list, alices_list):
# Combine the sorted lists into one large sorted list
if len(my_list) == 0 and len(alices_list) == 0:
return my_list
if len(my_list) > 0 and len(alices_list) == 0:
return my_list
if len(my_list) == 0 and len(alices_list) > 0:
return alices_list
merged_list = []
my_index = 0
alices_index = 0
while my_index < len(my_list) and alices_index < len(alices_list):
if my_list[my_index] < alices_list[alices_index]:
merged_list.append(my_list[my_index])
my_index += 1
else:
merged_list.append(alices_list[alices_index])
alices_index += 1
if my_index < len(my_list):
merged_list += my_list[my_index:]
if alices_index < len(alices_list):
merged_list += alices_list[alices_index:]
return merged_list
# Tests
class Test(unittest.TestCase):
def test_both_lists_are_empty(self):
actual = merge_lists([], [])
expected = []
self.assertEqual(actual, expected)
def test_first_list_is_empty(self):
actual = merge_lists([], [1, 2, 3])
expected = [1, 2, 3]
self.assertEqual(actual, expected)
def test_second_list_is_empty(self):
actual = merge_lists([5, 6, 7], [])
expected = [5, 6, 7]
self.assertEqual(actual, expected)
def test_both_lists_have_some_numbers(self):
actual = merge_lists([2, 4, 6], [1, 3, 7])
expected = [1, 2, 3, 4, 6, 7]
self.assertEqual(actual, expected)
def test_lists_are_different_lengths(self):
actual = merge_lists([2, 4, 6, 8], [1, 7])
expected = [1, 2, 4, 6, 7, 8]
self.assertEqual(actual, expected)
unittest.main(verbosity=2)
| true
|
148c6d9d37a9fd79e06e4371a30c65a5e36066b2
|
jtquisenberry/PythonExamples
|
/Jobs/multiply_large_numbers.py
| 2,748
| 4.25
| 4
|
import unittest
def multiply(num1, num2):
len1 = len(num1)
len2 = len(num2)
# Simulate Multiplication Like this
# 1234
# 121
# ----
# 1234
# 2468
# 1234
#
# Notice that the product is moved one space to the left each time a digit
# of the top number is multiplied by the next digit from the right in the
# bottom number. This is due to place value.
# Create an array to hold the product of each digit of `num1` and each
# digit of `num2`. Allocate enough space to move the product over one more
# space to the left for each digit after the ones place in `num2`.
products = [0] * (len1 + len2 - 1)
# The index will be filled in from the right. For the ones place of `num`
# that is the only adjustment to the index.
products_index = len(products) - 1
products_index_offset = 0
# Get the digits of the first number from right to left.
for i in range(len1 -1, -1, -1):
factor1 = int(num1[i])
# Get the digits of the second number from right to left.
for j in range(len2 - 1, -1, -1):
factor2 = int(num2[j])
# Find the product
current_product = factor1 * factor2
# Write the product to the correct position in the products array.
products[products_index + products_index_offset] += current_product
products_index -= 1
# Reset the index to the end of the array.
products_index = len(products) -1;
# Move the starting point one space to the left.
products_index_offset -= 1;
for i in range(len(products) - 1, -1, -1):
# Get the ones digit
keep = products[i] % 10
# Get everything higher than the ones digit
carry = products[i] // 10
products[i] = keep
# If index 0 is reached, there is no place to store a carried value.
# Instead retain it at the current index.
if i > 0:
products[i-1] += carry
else:
products[i] += (10 * carry)
# Convert the list of ints to a string.
#print(products)
output = ''.join(map(str,products))
return output
class Test(unittest.TestCase):
def setUp(self):
pass
def test_small_product(self):
expected = "1078095"
actual = multiply("8765", "123")
self.assertEqual(expected, actual)
def test_large_product(self):
expected = "41549622603955309777243716069997997007620439937711509062916"
actual = multiply("654154154151454545415415454", "63516561563156316545145146514654")
self.assertEqual(expected, actual)
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
| true
|
b8b7d0a3067b776d6c712b2f229ef65448b9a4d9
|
jtquisenberry/PythonExamples
|
/Interview_Cake/arrays/reverse_words_in_list_lists.py
| 2,120
| 4.375
| 4
|
import unittest
from collections import deque
# https://www.interviewcake.com/question/python/reverse-words?section=array-and-string-manipulation&course=fc1
# Solution with lists only
# Not in place
def reverse_words(message):
if len(message) < 1:
return
current_word = []
word_list = []
final_output = []
for i in range(0, len(message)):
character = message[i]
if character != ' ':
current_word.append(character)
if character == ' ' or i == len(message) - 1:
word_list.append(current_word)
current_word = []
# print(word_list)
for j in range(len(word_list) - 1, -1, -1):
final_output.extend(word_list[j])
if j > 0:
final_output.extend(' ')
# print(final_output)
for k in range(0, len(message)):
message[k] = final_output[k]
return
# Tests
class Test(unittest.TestCase):
def test_one_word(self):
message = list('vault')
reverse_words(message)
expected = list('vault')
self.assertEqual(message, expected)
def test_two_words(self):
message = list('thief cake')
reverse_words(message)
expected = list('cake thief')
self.assertEqual(message, expected)
def test_three_words(self):
message = list('one another get')
reverse_words(message)
expected = list('get another one')
self.assertEqual(message, expected)
def test_multiple_words_same_length(self):
message = list('rat the ate cat the')
reverse_words(message)
expected = list('the cat ate the rat')
self.assertEqual(message, expected)
def test_multiple_words_different_lengths(self):
message = list('yummy is cake bundt chocolate')
reverse_words(message)
expected = list('chocolate bundt cake is yummy')
self.assertEqual(message, expected)
def test_empty_string(self):
message = list('')
reverse_words(message)
expected = list('')
self.assertEqual(message, expected)
unittest.main(verbosity=2)
| true
|
1aa6ba8516a4e996c07028bc798bdb13064add85
|
jaeyun95/Algorithm
|
/code/day05.py
| 431
| 4.1875
| 4
|
#(5) day05 재귀를 사용한 리스트의 합
def recursive(numbers):
print("===================")
print('receive : ',numbers)
if len(numbers)<2:
print('end!!')
return numbers.pop()
else:
pop_num = numbers.pop()
print('pop num is : ',pop_num)
print('rest list is : ',numbers)
sum = pop_num + recursive(numbers)
print('sum is : ',sum)
return sum
| false
|
4b8c656ea711a2274df26c044ec6a7d7ce7b33bc
|
bojanuljarevic/Algorithms
|
/BST/bin_tree/bst.py
| 1,621
| 4.15625
| 4
|
# Zadatak 1 : ručno formiranje binarnog stabla pretrage
class Node:
"""
Tree node: left child, right child and data
"""
def __init__(self, p = None, l = None, r = None, d = None):
"""
Node constructor
@param A node data object
"""
self.parent = p
self.left = l
self.right = r
self.data = d
def addLeft(self, data):
child = Node(self, None, None, data)
self.left = child
return child
def addRight(self, data):
child = Node(self, None, None, data)
self.right = child
return child
def printNode(self):
print(self.data.a1, self.data.a2)
'''if(self.left != None):
print("Has left child")
else:
print("Does not have left child")
if (self.right != None):
print("Has right child")
else:
print("Does not have right child")'''
class Data:
"""
Tree data: Any object which is used as a tree node data
"""
def __init__(self, val1, val2):
"""
Data constructor
@param A list of values assigned to object's attributes
"""
self.a1 = val1
self.a2 = val2
if __name__ == "__main__":
root_data = Data(48, chr(48))
left_data = Data(49, chr(49))
right_data = Data(50, chr(50))
root = Node(None, None, None, root_data)
left_child = root.addLeft(left_data)
right_child = root.addRight(right_data)
root.printNode()
left_child.printNode()
right_child.printNode()
left_child.parent.printNode()
| true
|
5f5e0b19e8b1b6d0b0142eb63621070a50227142
|
steven-liu/snippets
|
/generate_word_variations.py
| 1,109
| 4.125
| 4
|
import itertools
def generate_variations(template_str, replace_with_chars):
"""Generate variations of a string with certain characters substituted.
All instances of the '*' character in the template_str parameter are
substituted by characters from the replace_with_chars string. This function
generates the entire set of possible permutations."""
count = template_str.count('*')
_template_str = template_str.replace('*', '{}')
variations = []
for element in itertools.product(*itertools.repeat(list(replace_with_chars), count)):
variations.append(_template_str.format(*element))
return variations
if __name__ == '__main__':
# use this set to test
REPLACE_CHARS = '!@#$%^&*'
# excuse the bad language...
a = generate_variations('sh*t', REPLACE_CHARS)
b = generate_variations('s**t', REPLACE_CHARS)
c = generate_variations('s***', REPLACE_CHARS)
d = generate_variations('f*ck', REPLACE_CHARS)
e = generate_variations('f**k', REPLACE_CHARS)
f = generate_variations('f***', REPLACE_CHARS)
print list(set(a+b+c+d+e+f))
| true
|
cc3a1d58b9a459e87baba1db1667b8c3eafaed7a
|
jackjyq/COMP9021_Python
|
/ass01/poker_dice/hand_rank.py
| 1,577
| 4.21875
| 4
|
def hand_rank(roll):
""" hand_rank
Arguements: a list of roll, such as [1, 2, 3, 4, 5]
Returns: a string, such as 'Straight'
"""
number_of_a_kind = [roll.count(_) for _ in range(6)]
number_of_a_kind.sort()
if number_of_a_kind == [0, 0, 0, 0, 0, 5]:
roll_hand = 'Five of a kind'
elif number_of_a_kind == [0, 0, 0, 0, 1, 4]:
roll_hand = 'Four of a kind'
elif number_of_a_kind == [0, 0, 0, 0, 2, 3]:
roll_hand = 'Full house'
elif number_of_a_kind == [0, 0, 0, 1, 1, 3]:
roll_hand = 'Three of a kind'
elif number_of_a_kind == [0, 0, 0, 1, 2, 2]:
roll_hand = 'Two pair'
elif number_of_a_kind == [0, 0, 1, 1, 1, 2]:
roll_hand = 'One pair'
elif number_of_a_kind == [0, 1, 1, 1, 1, 1]:
if (roll == [0, 2, 3, 4, 5] or
roll == [0, 1, 3, 4, 5] or
roll == [0, 1, 2, 4, 5] or
roll == [0, 1, 2, 3, 5]):
# According to https://en.wikipedia.org/wiki/Poker_dice,
# there are only four possible Bust hands
roll_hand = 'Bust'
else:
roll_hand = 'Straight'
return roll_hand
# Test Codes
if __name__ == "__main__":
roll = [1, 1, 1, 1, 1]
print(hand_rank(roll))
roll = [1, 1, 1, 1, 2]
print(hand_rank(roll))
roll = [1, 1, 1, 3, 3]
print(hand_rank(roll))
roll = [1, 1, 1, 2, 3]
print(hand_rank(roll))
roll = [1, 1, 2, 2, 3]
print(hand_rank(roll))
roll = [0, 2, 3, 4, 5]
print(hand_rank(roll))
roll = [1, 2, 3, 4, 5]
print(hand_rank(roll))
| false
|
8dbfcde0a480f44ea8f04d113a5214d7ddb9d290
|
jgkr95/CSPP1
|
/Practice/M6/p1/fizz_buzz.py
| 722
| 4.46875
| 4
|
'''Write a short program that prints each number from 1 to num on a new line.
For each multiple of 3, print "Fizz" instead of the number.
For each multiple of 5, print "Buzz" instead of the number.
For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
'''
def main():
'''Read number from the input, store it in variable num.'''
num_r = int(input())
i_i = 1
while i_i <= num_r:
if (i_i%3 == 0 and i_i%5 == 0):
print("Fizz")
print("Buzz")
elif i_i%3 == 0:
print("Fizz")
elif i_i%5 == 0:
print("Buzz")
else:
print(str(i_i))
i_i = i_i+1
if __name__ == "__main__":
main()
| true
|
86c07784b9a2a69756a3390e8ff70b2a4af78652
|
Ashishrsoni15/Python-Assignments
|
/Question2.py
| 391
| 4.21875
| 4
|
# What is the type of print function? Also write a program to find its type
# Print Funtion: The print()function prints the specified message to the screen, or other
#standard output device. The message can be a string,or any other object,the object will
#be converted into a string before written to the screen.
print("Python is fun.")
a=5
print("a=",a)
b=a
print('a=',a,'=b')
| true
|
6575bbd5e4d495bc5f8b5eee9789183819761452
|
Ashishrsoni15/Python-Assignments
|
/Question1.py
| 650
| 4.375
| 4
|
#Write a program to find type of input function.
value1 = input("Please enter first integer:\n")
value2 = input("Please enter second integer:\n")
v1 = int(value1)
v2 = int(value2)
choice = input("Enter 1 for addition.\nEnter 2 for subtraction.\nEnter 3 for multiplication:\n")
choice = int(choice)
if choice ==1:
print(f'you entered {v1} and {v2} and their addition is {v1+ v2}')
elif choice ==2:
print(f'you entered {v1} and {v2} and their subtraction is {v1 - v2}')
elif choice ==3:
print(f'you entered {v1} and {v2} and their multiplication is {v1 * v2}')
else:
print("Wrong Choice, terminating the program.")
| true
|
ea4c7aaefa309e8f0db99f4f43867ebd1bd52282
|
Shahriar2018/Data-Structures-and-Algorithms
|
/Task4.py
| 1,884
| 4.15625
| 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 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
print("These numbers could be telemarketers: ")
calling_140=set()
receving_140=set()
text_sending=set()
text_receiving=set()
telemarketers=set()
def telemarketers_list(calls,texts):
global calling_140,receving_140,text_sending,text_receiving,telemarketers
m=len(calls)
n=len(texts)
# making a list of calling/reciving numbers
for row in range(m):
if '140'in calls[row][0][:4]:
calling_140.add(calls[row][0])
if '140'in calls[row][1][:4]:
receving_140.add(calls[row][1])
# making a list of sending/receiving texts
for row in range(n):
if '140'in texts[row][0][:4]:
text_sending.add(calls[row][0])
if '140'in texts[row][1][:4]:
text_receiving.add(calls[row][1])
#Getting rid of unnecessary numbers
telemarketers=calling_140-receving_140-text_sending-text_receiving
telemarketers=sorted(list(telemarketers))
# Printing all the numbers
for i in range(len(telemarketers)):
print(telemarketers[i])
return ""
telemarketers_list(calls,texts)
| true
|
05d3835f466737814bb792147e8d7b34a28d912f
|
qiqi06/python_test
|
/python/static_factory_method.py
| 1,038
| 4.1875
| 4
|
#-*- coding: utf-8 -*-
"""
练习简单工厂模式
"""
#建立一工厂类,要用是,再实例化它的生产水果方法,
class Factory(object):
def creatFruit(self, fruit):
if fruit == "apple":
return Apple(fruit, "red")
elif fruit == "banana":
return Banana(fruit, "yellow")
class Fruit(object):
def __init__(self, name, color):
self.color = color
self.name = name
def grow(self):
print "%s is growing" %self.name
class Apple(Fruit):
def __init__(self, name, color):
super(Apple, self).__init__(name, color)
class Banana(Fruit):
def __init__(self, name, color):
super(Banana, self).__init__(name, color)
self.name = 'banana'
self.color = 'yellow'
def test():
#这里是两个对象, 一个是工厂,一个是我要订的水果
factory = Factory()
my_fruit = factory.creatFruit('banana')
my_fruit.grow()
if __name__ == "__main__":
print "The main module is running!"
test()
| false
|
deae850e32102c9f22d108c817cfd69eebd4344f
|
szzhe/Python
|
/ActualCombat/TablePrint.py
| 854
| 4.28125
| 4
|
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
# 要求输出如下:
# apples Alice dogs
# oranges Bob cats
# cherries Carol moose
# banana David goose
def printTable(data):
str_data = ''
col_len = []
for row in range(0, len(data[0])): # row=4
for col in range(0, len(data)): # col=3
col_len.append(len(data[col][row]))
max_col_len = max(col_len)
print("列表各元素长度为:", col_len)
print("列表中最大值为:", max_col_len) # 8
for row in range(0, len(data[0])):
for col in range(0, len(data)):
print(data[col][row].rjust(max_col_len), end='')
print()
return str_data
f_data = printTable(tableData)
print(f_data)
| false
|
c6d84e1f238ac03e872eea8c8cb3566ac0913646
|
Cpeters1982/DojoPython
|
/hello_world.py
| 2,621
| 4.21875
| 4
|
'''Test Document, leave me alone PyLint'''
# def add(a,b):
# x = a + b
# return x
# result = add(3, 5)
# print result
# def multiply(arr, num):
# for x in range(len(arr)):
# arr[x] *= num
# return arr
# a = [2,4,10,16]
# b = multiply(a,5)
# print b
'''
The function multiply takes two parameters, arr and num. We pass our arguments here.
for x in range(len(arr)) means
"for every index of the list(array)" and then "arr[x] *= num" means multiply
the indices of the passed in array by the value of the variable "num"
return arr sends arr back to the function
*= multiplies the variable by a value and assigns the result to that variable
'''
# def fun(arr, num):
# for x in range (len(arr)):
# arr[x] -= num
# return arr
# a = [3,6,9,12]
# b = fun(a,2)
# print b
'''
Important! The variables can be anything! Use good names!
'''
# def idiot(arr, num):
# for x in range(len(arr)):
# arr[x] /= num
# return arr
# a = [5,3,6,9]
# b = idiot(a,3)
# print b
# def function(arr, num):
# for i in range(len(arr)):
# arr[i] *= num
# return arr
# a = [10, 9, 8, 7, 6]
# print function(a, 8)
# def avg(arr):
# avg = 0
# for i in range(len(arr)):
# avg = avg + arr[i]
# return avg / len(arr)
# a = [10,66,77]
# print avg(a)
# Determines the average of a list (array)
weekend = {"Sun": "Sunday", "Sat": "Saturday"}
weekdays = {"Mon": "Monday", "Tue": "Tuesday", "Wed": "Wednesday", "Thu": "Thursday",
"Fri": "Friday"}
months = {"Jan": "January", "Feb": "February", "Mar": "March", "Apr": "April",
"May": "May", "Jun": "June", "Jul": "July",
"Aug": "August", "Sep": "September", "Oct": "October", "Nov": "November",
"Dec": "December"}
# for data in months:
# print data
# for key in months.iterkeys():
# print key
# for val in months.itervalues():
# print val
# for key,data in months.iteritems():
# print key, '=', data
# print len(months)
# print len(weekend)
# print str(months)
# context = {
# 'questions': [
# { 'id': 1, 'content': 'Why is there a light in the fridge and not in the freezer?'},
# { 'id': 2, 'content': 'Why don\'t sheep shrink when it rains?'},
# { 'id': 3, 'content': 'Why are they called apartments when they are all stuck together?'},
# { 'id': 4, 'content': 'Why do cars drive on the parkway and park on the driveway?'}
# ]
# }
# userAnna = {"My name is": "Anna", "My age is": "101", "My country of birth is": "The U.S.A", "My favorite language is": "Python"}
# for key,data in userAnna.iteritems():
# print key, data
| true
|
44b81e47c1cd95f7e08a8331b966cf195e8c514d
|
gersongroth/maratonadatascience
|
/Semana 01/02 - Estruturas de Decisão/11.py
| 1,156
| 4.1875
| 4
|
"""
As Organizações Tabajara resolveram dar um aumento de salário aos seus colaboradores e lhe contraram para desenvolver o programa que calculará os reajustes.
Faça um programa que recebe o salário de um colaborador e o reajuste segundo o seguinte critério, baseado no salário atual:
salários até R$ 280,00 (incluindo) : aumento de 20%
salários entre R$ 280,00 e R$ 700,00 : aumento de 15%
salários entre R$ 700,00 e R$ 1500,00 : aumento de 10%
salários de R$ 1500,00 em diante : aumento de 5% Após o aumento ser realizado, informe na tela:
o salário antes do reajuste;
o percentual de aumento aplicado;
o valor do aumento;
o novo salário, após o aumento.
"""
salario = float(input("Informe o salário: R$ "))
aumento = 0
if salario <= 280.0:
aumento = 20
elif salario < 700.0:
aumento = 15
elif salario < 1500:
aumento = 10
else:
aumento = 5
valorAumento = salario * (aumento / 100)
novoSalario = salario + valorAumento
print("Salario original: R$ %.2f" % salario)
print("Porcentagem de aumento: %d%%" % aumento)
print("Valor do aumento: R$ %.2f" % valorAumento)
print("Salario após reajuste: R$ %.2f" % novoSalario)
| false
|
e6536e8399f1ceccd7eb7d41eddcc302e3dda66b
|
guv-slime/python-course-examples
|
/section08_ex04.py
| 1,015
| 4.4375
| 4
|
# Exercise 4: Expanding on exercise 3, add code to figure out who
# has the most emails in the file. After all the data has been read
# and the dictionary has been created, look through the dictionary using
# a maximum loop (see chapter 5: Maximum and Minimum loops) to find out
# who has the most messages and print how many messages the person has.
# Enter a file name: mbox-short.txt
# cwen@iupui.edu 5
# PASSED
# Enter a file name: mbox.txt
# zqian@umich.edu 195
# PASSED
# file_name = 'mbox-short.txt'
file_name = 'mbox.txt'
handle = open(file_name)
email_dic = dict()
for line in handle:
if line.startswith('From'):
words = line.split()
if len(words) < 3:
continue
else:
email_dic[words[1]] = email_dic.get(words[1], 0) + 1
most_mail = None
for email in email_dic:
if most_mail is None or email_dic[most_mail] < email_dic[email]:
# print('DA MOST AT DA MOMENT =', email, email_dic[email])
most_mail = email
print(most_mail, email_dic[most_mail])
| true
|
f93dd7a14ff34dae2747f7fa2db22325e9d00972
|
guv-slime/python-course-examples
|
/section08_ex03.py
| 690
| 4.125
| 4
|
# Exercise 3: Write a program to read through a mail log, build a histogram
# using a dictionary to count how many messages have come from each email
# address, and print the dictionary.
# Enter file name: mbox-short.txt
# {'gopal.ramasammycook@gmail.com': 1, 'louis@media.berkeley.edu': 3,
# 'cwen@iupui.edu': 5, 'antranig@caret.cam.ac.uk': 1,
# 'rjlowe@iupui.edu': 2, 'gsilver@umich.edu': 3,
# 'david.horwitz@uct.ac.za': 4, 'wagnermr@iupui.edu': 1,
# 'zqian@umich.edu': 4, 'stephen.marquard@uct.ac.za': 2,
# 'ray@media.berkeley.edu': 1}
file_name = 'mbox-short.txt'
handle = open(file_name)
email_dic = dict()
for line in handle:
if line.startswith('From'):
words = line.split()
if len(words) < 3:
continue
else:
email_dic[words[1]] = email_dic.get(words[1], 0) + 1
print(email_dic)
| false
|
f9a66f5b0e776d063d812e7a7185ff6ff3c5615f
|
maryamkh/MyPractices
|
/ReverseLinkedList.py
| 2,666
| 4.3125
| 4
|
'''
Reverse back a linked list
Input: A linked list
Output: Reversed linked list
In fact each node pointing to its fron node should point to it back node ===> Since we only have one direction accessibility to a link list members to reverse it I have to travers the whole list, keep the data of the nodes and then rearrange them backward.
Example:
Head -> 2-> 3-> 9-> 0
Head -> 0-> 9-> 3-> 2
Pseudocode:
currentNode = Head
nodeSet = set ()
While currentNode != None:
nodeSet.add(currentNode.next)
currentNode = currentNode.next
reversedSet = list(reverse(set))
currentNode = Head
while currentNode != None:
currentNode.value = reversedSet.pop()
currentNode = currentNode.next
Tests:
Head -> None
Head -> 2
Head -> 0-> 9-> 3-> 2
'''
class node:
def __init__(self, initVal):
self.data = initVal
self.next = None
def reverseList(Head):
currNode = Head
nodeStack = []
while currNode != None:
#listSet.add(currNode)
#nodeStack.append(currNode.data)
nodeStack.append(currNode)
currNode = currNode.next
# currNode = Head
# print (nodeStack)
# while currNode != None:
# #currNode.value = listSet.pop().value
# currNode.value = nodeStack.pop().data
# print (currNode.value)
# currNode = currNode.next
if len(nodeStack) >= 1:
Head = nodeStack.pop()
currNode = Head
#print (currNode.data)
while len(nodeStack) >= 1:
currNode.next = nodeStack.pop()
#print (currNode.data)
currNode = currNode.next
#print (currNode.data)
def showList(Head):
#print(f'list before reverse: {Head}')
while Head != None:
print(f'{Head.data}')
Head = Head.next
print(f'{Head}')
#Head = None
#print(f'list before reverse:\n')
#showList(Head)
#reverseList(Head)
#print(f'list after reverse:\n')
#showList(Head)
def reverse(Head):
nxt = Head.next
prev = None
Head = reverseList1(Head,prev)
print(f'new head is: {Head.data}')
def reverseList1(curr,prev):
#Head->2->3->4
#None<-2<-3<-4
if curr == None:
return prev
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return reverseList1(curr, prev)
n1 = node(2)
Head = n1
#print(f'list before reverse:\n')
#showList(Head)
#reverseList(Head)
#print(f'list after reverse:\n')
#showList(Head)
n2 = node(0)
n3 = node(88)
n4 = node(22)
n1.next = n2
n2.next = n3
n3.next = n4
Head = n1
print(f'list before reverse:\n')
showList(Head)
##reverseList(Head)
reverse(Head)
Head = n4
print(f'n1 value: {Head.data}')
showList(Head)
| true
|
145413092625adbe30b158c21e5d27e2ffcfab50
|
maryamkh/MyPractices
|
/Squere_Root.py
| 1,838
| 4.1875
| 4
|
#!/usr/bin/python
'''
Find the squere root of a number. Return floor(sqr(number)) if the numebr does not have a compelete squere root
Example: input = 11 ===========> output = 3
Function sqrtBinarySearch(self, A): has time complexity O(n), n: given input: When the number is too big it becomes combursome
'''
class Solution:
def sqrt(self, A):
n = 1
while n*n <= A:
n += 1
if A == n*n: return n
elif n < (n-.5) * (n-.5): return n-1
else: return n+1
def sqrtBinarySearch(self, A):
searchList = []
#print range(A)
for i in range(A):
searchList.append(i+1)
for i in range(len(searchList)):
mid = len(searchList)/2
#if mid > 0:
number = searchList[mid-1]
sqrMid = number * number
sqrMidPlus = (number+1) * (number+1)
#print 'sqrMid...sqrMidPlus...', sqrMid, sqrMidPlus
if sqrMid == A: return number
elif sqrMid > A: #sqrt is in the middle left side of the array
searchList = searchList[:mid]
#print 'left wing...', searchList
elif sqrMid < A and sqrMidPlus > A: # sqrMid< sqrt(A)=number.xyz <sqrMidPlus==> return floor(number.xyz)
print
if (number + .5) * (number + .5) > A: return number
return number+1
else:
searchList = searchList[mid:]
#print 'right wing...', searchList
def main():
inputNum = int(input('enter a number to find its squere root: '))
sqroot = Solution()
result = sqroot.sqrt(inputNum)
result1 = sqroot.sqrtBinarySearch(inputNum)
print result
print result1
if __name__ == '__main__':
main()
| true
|
8b9f850c53a2a020b1deea52e301de0d2b6c47c3
|
CodingDojoDallas/python_sep_2018
|
/austin_parham/user.py
| 932
| 4.15625
| 4
|
class Bike:
def __init__(self, price, max_speed, miles):
self.price = price
self.max_speed = max_speed
self.miles = miles
def displayInfo(self):
print(self.price)
print(self.max_speed)
print(self.miles)
print('*' * 80)
def ride(self):
print("Riding...")
print("......")
print("......")
self.miles = self.miles + 10
def reverse(self):
print("Reversing...")
print("......")
print("......")
self.miles = self.miles - 5
# def reverse(self):
# print("Reversing...")
# print("......")
# print("......")
# self.miles = self.miles + 5
# Would use to not subtract miles from reversing
bike1 = Bike(200,120,20000)
bike1.ride()
bike1.ride()
bike1.ride()
bike1.reverse()
bike1.displayInfo()
bike2 = Bike(600,150,5000)
bike2.ride()
bike2.ride()
bike2.reverse()
bike2.reverse()
bike2.displayInfo()
lance = Bike(4000,900,60000)
lance.reverse()
lance.reverse()
lance.reverse()
lance.displayInfo()
| true
|
36a4f28b97be8be2e7f6e20965bd21f554270704
|
krismosk/python-debugging
|
/area_of_rectangle.py
| 1,304
| 4.6875
| 5
|
#! /usr/bin/env python3
"A script for calculating the area of a rectangle."
import sys
def area_of_rectangle(height, width = None):
"""
Returns the area of a rectangle.
Parameters
----------
height : int or float
The height of the rectangle.
width : int or float
The width of the rectangle. If `None` width is assumed to be equal to
the height.
Returns
-------
int or float
The area of the rectangle
Examples
--------
>>> area_of_rectangle(7)
49
>>> area_of_rectangle (7, 2)
14
"""
if width:
width = height
area = height * width
return area
if __name__ == '__main__':
if (len(sys.argv) < 2) or (len(sys.argv) > 3):
message = (
"{script_name}: Expecting one or two command-line arguments:\n"
"\tthe height of a square or the height and width of a "
"rectangle".format(script_name = sys.argv[0]))
sys.exit(message)
height = sys.argv[1]
width = height
if len(sys.argv) > 3:
width = sys.argv[1]
area = area_of_rectangle(height, width)
message = "The area of a {h} X {w} rectangle is {a}".format(
h = height,
w = width,
a = area)
print(message)
| true
|
dacaf7998b9ca3a71b6b90690ba952fb56349ab9
|
Kanthus123/Python
|
/Design Patterns/Creational/Abstract Factory/doorfactoryAbs.py
| 2,091
| 4.1875
| 4
|
#A factory of factories; a factory that groups the individual but related/dependent factories together without specifying their concrete classes.
#Extending our door example from Simple Factory.
#Based on your needs you might get a wooden door from a wooden door shop,
#iron door from an iron shop or a PVC door from the relevant shop.
#Plus you might need a guy with different kind of specialities to fit the door,
#for example a carpenter for wooden door, welder for iron door etc.
#As you can see there is a dependency between the doors now,
#wooden door needs carpenter, iron door needs a welder etc.
class Door:
def get_descricao(self):
raise NotImplementedError
class WoodenDoor(Door):
def get_descricao(self):
print('Eu sou uma porta de Madeira')
def IronDoor(Door):
def get_descricao(self):
print('Eu sou uma porta de Ferro')
class DoorFittingExpert:
def get_descricao(self):
raise NotImplementedError
class Welder(DoorFittingExpert):
def get_descricao(self):
print('Eu apenas posso colocar portas de ferro')
class Carpenter(DoorFittingExpert):
def get_descricao(self):
print('Eu apenas posso colocar portas de madeira')
class DoorFactory:
def fazer_porta(self):
raise NotImplementedError
def fazer_profissional(self):
raise NotImplementedError
class WoodenDoorFactory(DoorFactory):
def fazer_porta(self):
return WoodenDoor()
def fazer_profissional(self):
return Carpenter()
class IronDoorFactory(DoorFactory):
def fazer_porta(self):
return IronDoor()
def fazer_profissional(self):
return Welder()
if __name__ == '__main__':
wooden_factory = WoodenDoorFactory()
porta = wooden_factory.fazer_porta()
profissional = wooden_factory.fazer_profissional()
porta.get_descricao()
profissional.get_descricao()
iron_factory = IronDoorFactory()
porta = iron_factory.fazer_porta()
profissional = iron_factory.fazer_profissional()
porta.get_descricao()
profissional.get_descricao()
| true
|
ab049070f8348f4af8caeb601aee062cc7a76af2
|
Kanthus123/Python
|
/Design Patterns/Structural/Decorator/VendaDeCafe.py
| 1,922
| 4.46875
| 4
|
#Decorator pattern lets you dynamically change the behavior of an object at run time by wrapping them in an object of a decorator class.
#Imagine you run a car service shop offering multiple services.
#Now how do you calculate the bill to be charged?
#You pick one service and dynamically keep adding to it the prices for the provided services till you get the final cost.
#Here each type of service is a decorator.
class Cofe:
def get_custo(self):
raise NotImplementedError
def get_descricao(self):
raise NotImplementedError
class CafeSimples(Cafe):
def get_custo(self):
return 10
def get_descricao(self):
return 'Cafe Simples'
class CafeComLeite(self):
def __init__(self, cafe):
self.cafe = cafe
def get_custo(self):
return self.cafe.get_custo() + 2
def get_descricao(self):
return self.cafe.get_descricao() + ', leite'
class CafeComCreme(Cafe):
def __init__(self, cafe):
self.cafe = cafe
def get_custo(self):
return self.cafe.get_custo() + 5
def get_descricao(self):
return self.cafe.get_descricao() + ', creme'
class Capuccino(Cafe):
def __init__(self, cafe):
self.cafe = cafe
def get_custo(self):
return self.cafe.get_custo() + 3
def get_descricao(self):
return self.cafe.get_descricao() + ', chocolate'
if __name__ == '__main__':
cafe = CafeSimples()
assert cafe.get_custo() == 10
assert coffee.get_description() == 'Cafe Simples'
cafe = CafeComLeite(cafe)
assert coffee.get_cost() == 12
assert coffee.get_description() == 'Cafe Simples, Leite'
cafe = CafeComCreme(cafe)
assert coffee.get_cost() == 17
assert coffee.get_description() == 'Cafe Simples, Leite, Creme'
cafe = Capuccino(cafe)
assert coffee.get_cost() == 20
assert coffee.get_description() == 'Cafe Simples, Leite, Chocolate'
| true
|
32c5ca8e7beb18feafd101e6e63da060c3c47647
|
russellgao/algorithm
|
/data_structure/binaryTree/preorder/preoder_traversal_items.py
| 695
| 4.15625
| 4
|
# 二叉树的中序遍历
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 迭代
def preorderTraversal(root: TreeNode) ->[int]:
result = []
if not root:
return result
queue = [root]
while queue:
root = queue.pop()
if root:
result.append(root.val)
if root.right:
queue.append(root.right)
if root.left:
queue.append(root.left)
return result
if __name__ == "__main__":
root = TreeNode(1)
root.right = TreeNode(2)
root.right.left = TreeNode(3)
result = preorderTraversal(root)
print(result)
| false
|
861fab844f5dcbf86c67738354803e27a0a303e9
|
russellgao/algorithm
|
/dailyQuestion/2020/2020-05/05-31/python/solution_recursion.py
| 950
| 4.21875
| 4
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 递归
def isSymmetric(root: TreeNode) -> bool:
def check(left, right):
if not left and not right:
return True
if not left or not right:
return False
return left.val == right and check(left.left, right.right) and check(left.right, right.left)
return check(root, root)
if __name__ == "__main__":
# root = TreeNode(1)
# root.left = TreeNode(2)
# root.right = TreeNode(2)
#
# root.left.left = TreeNode(3)
# root.left.right = TreeNode(4)
#
# root.right.left = TreeNode(4)
# root.right.right = TreeNode(3)
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(2)
root.left.left = TreeNode(3)
root.right.right = TreeNode(3)
result = isSymmetric(root)
print(result)
| true
|
21f1cf35cd7b3abe9d67607712b62bfa4732e4ce
|
russellgao/algorithm
|
/dailyQuestion/2020/2020-05/05-01/python/solution.py
| 944
| 4.125
| 4
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def reverseList(head):
"""
递归 反转 链表
:type head: ListNode
:rtype: ListNode
"""
if not head :
return None
if not head.next :
return head
last = reverseList(head.next)
head.next.next = head
head.next = None
return last
def reverseList_items(head) :
"""
迭代 反转 链表
:type head: ListNode
:rtype: ListNode
"""
pre = None
current = head
while current:
tmp = current.next
current.next = pre
pre = current
current = tmp
return pre
if __name__ == '__main__':
node = ListNode(1)
node.next = ListNode(2)
node.next.next = ListNode(3)
node.next.next.next = ListNode(4)
node.next.next.next.next = ListNode(5)
result = reverseList(node)
print()
| false
|
ecfa4146a927249cf7cb510dbf14432cd2bb84a7
|
wulinlw/leetcode_cn
|
/剑指offer/30_包含min函数的栈.py
| 1,296
| 4.125
| 4
|
#!/usr/bin/python
#coding:utf-8
# // 面试题30:包含min函数的栈
# // 题目:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min
# // 函数。在该栈中,调用min、push及pop的时间复杂度都是O(1)。
class StackWithMin:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, node):
# write code here
self.stack.append(node)
if not self.min_stack:
self.min_stack.append(node)
else:
if self.min_stack[-1] < node:
self.min_stack.append(self.min_stack[-1])
else:
self.min_stack.append(node)
def pop(self):
# write code here
self.stack.pop(-1)
self.min_stack.pop(-1)
def top(self):
# write code here
if self.stack:
return self.stack[-1]
else:
return []
def min(self):
# write code here
return self.min_stack[-1]
def debug(self):
print(self.stack)
print(self.stack_min)
print("\n")
s = StackWithMin()
s.push(2.98)
s.push(3)
s.debug()
s.pop()
s.debug()
s.push(1)
s.debug()
s.pop()
s.debug()
s.push(1)
s.push(2)
s.push(3)
s.debug()
s.push(0)
s.debug()
| false
|
93980a2f1b9d778ff907998b6fb722722ec28d73
|
wulinlw/leetcode_cn
|
/递归/recursion_1_1.py
| 1,304
| 4.15625
| 4
|
#!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/orignial/card/recursion-i/256/principle-of-recursion/1198/
# 反转字符串
# 编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
# 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
# 你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。
# 示例 1:
# 输入:["h","e","l","l","o"]
# 输出:["o","l","l","e","h"]
# 示例 2:
# 输入:["H","a","n","n","a","h"]
# 输出:["h","a","n","n","a","H"]
class Solution(object):
# 递归
def reverseString(self, s):
def recur(tmp):
if len(tmp)<=1:
return tmp
else:
return recur(tmp[1:])+[tmp[0]]
s[:] = recur(s)
# 递归+双指针
def reverseString2(self, s):
"""
:type s: str
:rtype: str
"""
def recur_(s, i,j):
if i>=j:
return
else:
s[i],s[j] = s[j],s[i]
recur_(s,i+1,j-1)
recur_(s,0,len(s)-1)
s = ["h","e","l","l","o"]
S = Solution()
deep = S.reverseString2(s)
print("deep:",deep)
| false
|
bacfbc3a4a068cf87954be2a53e0a6ab44ba41bc
|
wulinlw/leetcode_cn
|
/链表/linked-list_5_3.py
| 2,469
| 4.125
| 4
|
#!/usr/bin/python
# coding:utf-8
# https://leetcode-cn.com/explore/learn/card/linked-list/197/conclusion/764/
# 扁平化多级双向链表
# 您将获得一个双向链表,除了下一个和前一个指针之外,它还有一个子指针,可能指向单独的双向链表。这些子列表可能有一个或多个自己的子项,依此类推,生成多级数据结构,如下面的示例所示。
# 扁平化列表,使所有结点出现在单级双链表中。您将获得列表第一级的头部。
# 示例:
# 输入:
# 1---2---3---4---5---6--NULL
# |
# 7---8---9---10--NULL
# |
# 11--12--NULL
# 输出:
# 1-2-3-7-8-11-12-9-10-4-5-6-NULL
# 以上示例的说明:
# 给出以下多级双向链表:
# 我们应该返回如下所示的扁平双向链表:
# Definition for a Node.
class Node(object):
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
class Solution(object):
def list_generate(self, lst):
"""
生成链表
"""
if not lst:
return None
list_node = Node(lst[0])
if len(lst) == 1:
list_node.next = None
else:
list_node.next = self.list_generate(lst[1:])
return list_node
# 测试打印
def printList(self, list_node):
re = []
while list_node:
re.append(list_node.val)
list_node = list_node.next
print(re)
def flatten(self, head):
"""
:type head: Node
:rtype: Node
"""
p = rst = Node(None, None, None, None) # 初始化结果链表及其指针
visited = head and [head] # 初始化栈
while visited:
vertex = visited.pop()
if vertex.next:
visited.append(vertex.next)
if vertex.child:
visited.append(vertex.child)
p.next = vertex # pop出来的节点就是所需节点
p, p.prev, p.child = p.next, p, None # 设定节点属性
# p = p.next后相当于右移一位后,p.prev就是p了
if rst.next:
rst.next.prev = None # rst是要返回的头,rst.next的prev属性要设为None
return rst.next
l = [1, 2, 6, 3, 4, 5, 6]
node = 6
obj = Solution()
head = obj.list_generate(l)
obj.printList(head)
r = obj.flatten(head)
obj.printList(r)
| false
|
1926f0d51153da212fbfd132588b7547ca9b9e9d
|
wulinlw/leetcode_cn
|
/初级算法/linkedList_4.py
| 1,718
| 4.25
| 4
|
#!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/6/linked-list/44/
# 合并两个有序链表
# 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
# 示例:
# 输入:1->2->4, 1->3->4
# 输出:1->1->2->3->4->4
# 新建链表,对比两个链表指针,小的放新链表中,直到某条链表结束,
# 将另一条链表剩余部分接入新链表
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
newHead = ListNode(0)
pre = newHead
while l1 and l2:
if l1.val<l2.val:
pre.next = l1
l1 = l1.next
else:
pre.next = l2
l2 = l2.next
pre = pre.next
if l1:
pre.next = l1
elif l2:
pre.next = l2
return newHead.next
def createListnode(self, list):
head = ListNode(list[0])
p = head
for i in list[1:]:
node = ListNode(i)
p.next = node
p = p.next
return head
def dump(self, head):
while head:
print (head.val),
head = head.next
print("")
s = Solution()
# 有序链表
head1 = s.createListnode([1,2,3])
head2 = s.createListnode([4,5,6])
s.dump(head1)
s.dump(head2)
res = s.mergeTwoLists(head1,head2)
s.dump(res)
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.