blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b3df16f0d17b6d56abfffc73b0de4b1c443b5f12 | justiniansiah/10.009-Digital-Word | /00 Finals/2014/2014_Q1.4.py | 2,503 | 4.1875 | 4 | '''Develop a Python class to represent polylines. A polyline is a piecewise linear curve - one can
think of it as a series of connected line segments. The polyline class will build upon the two
classes below, which represents points and vectors.'''
import math
class Point2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return 'Point2D(' + str(self.x) + ',' + str(self.y) + ')'
def add(self,val):
return Point2D(self.x+val.dx,self.y+val.dy)
class Vector2D:
def __init__(self, dx, dy):
self.dx = dx
self.dy = dy
def length(self):
return math.sqrt(self.dx**2 + self.dy**2)
class Polyline2D:
def __init__(self,startP,segments):
self.startPoint = startP
self.segments = segments
def addSegment(self,new_v):
self.segments.append(new_v)
def length(self):
total_length = 0.0
for vec in self.segments:
total_length += vec.length()
return total_length
def vertex(self,idx):
cur_point = self.startPoint
for i in range(idx):
cur_vec = self.segments[i]
cur_point = cur_point.add(cur_vec)
return cur_point
''' 1.4 : Define a new class ClosedPolyline2D that has the same functionality as Polyline2D. Closed
polylines form a closed loop in 2D. ClosedPolyline2D can have the same representation as
Polyline2D, with segments added to it in exactly the same way. The difference is that, implic-
itly, the very last vertex is connected to the starting vertex, thus that last segment need not be
added to the segment list explicitly.
The ClosedPolyline2D class must support all of the methods of the Polyline2D class addSegment, vertex, length. This new class must make use of Polyline2D and should
contain as little new code as possible.'''
class ClosedPolyline2D(Polyline2D):
def length(self):
total_length = Polyline2D.length(self)
end_point = self.startPoint
n = len(self.segments)
start_point = self.vertex(n)
last_dx = end_point.x - start_point.x
last_dy = end_point.y - start_point.y
last_vec = Vector2D(last_dx, last_dy)
total_length += last_vec.length()
return total_length
cpline = ClosedPolyline2D(Point2D(1,2), [Vector2D(3,1)])
cpline.addSegment(Vector2D(1,0))
cpline.addSegment(Vector2D(0,2))
print cpline.length() #11.1622776602
| true |
bddc65022b3e0200140d277f2f3c94f75cfe5690 | Persifer/Machine_Learning_Training | /first_algorithm/first_ml_code.py | 2,750 | 4.34375 | 4 | #preloaded dataset that contains information about terrains and prices in Boston
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
# the regressor is an algorithm which has, as output, a number that indicates
# the estimate of what we are anticipating like the number of goal of a soccer player
def print_description(dataset):
#printing a description of the dataset
print(dataset['DESCR'])
#printig all the data of the dataset
for data in dataset['data']:
print(data)
print()
def first_code(dataset):
# matrix which contains the features of the houses in Boston
X = dataset['data']
# matrix which contains the price to predict
y = dataset['target']
# creating the model
model = LinearRegression()
# training the model starting from the data. the model will try to find the pattern between the data
# the fit must have done only one time before evalute the model. It can ben done more times, but only when
# the data are too much and, with one fit, we can not do it
model.fit(X, y)
# list that contains the predictions generated by the model
predictions = model.predict(X)
# it takes in input the real data and the predictions created by the model and, his ouput, is a number that
# indicates how good is the model. More big it is, less the model is good
mae = mean_absolute_error(y, predictions)
print('MAE: '+str(mae))
# this function will show how to train a ml algorithm
def training_function(dataset):
# matrix which contains the features of the houses in Boston
X = dataset['data']
# matrix which contains the price to predict
y = dataset['target']
# the train_test_split() function returns a tuple with four elements which will be represented by the four
# variables declared. With this function we divide the dataset into the dataset for the training and the dataset
# to test the training
X_train, X_test, y_train, y_test = train_test_split(X, y)
model = LinearRegression()
# we give in input only a part of dataset for the training, with which the model will train
model.fit(X_train, y_train)
predict_train = model.predict(X_train)
predict_test = model.predict(X_test)
mae_train = mean_absolute_error(y_train, predict_train)
mae_test = mean_absolute_error(y_test, predict_test)
print('MAE train: ' + str(mae_train))
print('MAE test: ' + str(mae_test))
if __name__ == '__main__':
# load the Boston's dataset into the var dataset
dataset = load_boston()
first_code(dataset)
training_function(dataset)
| true |
e97540a4ae8d000cb52e43555c3d95305ce87ee8 | TheCaptainFalcon/DC_Week2 | /Objects_Basics.py | 1,138 | 4.28125 | 4 | class Person :
def __init__(self, name, email, phone):
self.name = name
self.email = email
self.phone = phone
def greet(self, other_person):
return("Hello {}, I am {}:".format(other_person.name, self.name))
def print_contact_info(self):
print(f"{self.name}'s email: {self.email}, {self.name}'s phone number: {self.phone}")
def add_friend(self, new_friend):
self.friends.append(new_friend)
sonny = Person("Sonny", "sonny@hotmail.com", "483-485-4948")
jordan = Person("Jordan", "jordan@aol.com", "495-586-3456")
print(sonny.greet(jordan))
print(jordan.greet(sonny))
print(sonny.email, sonny.phone)
print(jordan.email, jordan.phone)
sonny.print_contact_info()
#Make your own Vehicle class
class Vehicle:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def print_info(self):
return("{} {} {}").format(self.year, self.make, self.model)
#Links to class Vehicle - which then gets formatted based on print_info
#to be year, Make, Model
car = Vehicle("Nissan", "Leaf", "2015")
print(car.print_info())
| false |
dd9b9f4cfec95542607537b68edc13418fdb4fc3 | Naohiro2g/robruzzo_Raspberry-Pi-Projects | /pi-servo.py | 2,781 | 4.21875 | 4 | # Use Raspberry Pi to control Servo Motor motion
# Tutorial URL: http://osoyoo.com/?p=937
import RPi.GPIO as GPIO
import time
import os
GPIO.setwarnings(False)
# Set the layout for the pin declaration
GPIO.setmode(GPIO.BOARD)
# The Raspberry Pi pin 11(GPIO 18) connect to servo signal line(yellow wire)
# Pin 11 send PWM signal to control servo motion
GPIO.setup(11, GPIO.OUT)
# menu info
print "l = move to the left"
print "r = move to the right"
print "m = move to the middle"
print "t = test sequence"
print "q = stop and exit"
while True:
# Now we will start with a PWM signal at 50Hz at pin 18.
# 50Hz should work for many servos very will. If not you can play with the frequency if you like.
Servo = GPIO.PWM(11, 50)
# This command sets the left position of the servo
Servo.start(2.5)
# Now the program asks for the direction the servo should turn.
input = raw_input("Selection: ")
# You can play with the values.
# 7.5 is in most cases the middle position
# 12.5 is the value for a 180 degree move to the right
# 2.5 is the value for a -90 degree move to the left
if(input == "t"):
print "move to the center position:"
Servo.ChangeDutyCycle(7.5)
time.sleep(1)
print "move to the right position:"
Servo.ChangeDutyCycle(12.5)
time.sleep(1)
print "move to the left position:"
Servo.ChangeDutyCycle(2.5)
time.sleep(1)
# this stops the PWM signal
print "Move back to start position."
Servo.stop()
# direction right
if(input == "r"):
# how many steps should the move take.
steps = raw_input("steps (1 - 10): ")
print steps, "steps to the right"
stepslength = 12.5 / int(steps)
for Counter in range(int(steps)):
Servo.ChangeDutyCycle(stepslength * (Counter + 1))
print stepslength * (Counter + 1)
time.sleep(0.5)
time.sleep(1)
# PWM stop
print "Move back to start position."
Servo.stop()
# move to the center position
elif(input == "m"):
print "Move back to the center position."
Servo.start(7.5)
time.sleep(1)
# PWM stop
#print "Move back to start position."
Servo.stop()
# move to the left
elif(input == "l"):
print "Move to the max right position and then to the left position."
Servo.start(12.5)
# how many steps...
steps = raw_input("steps (1 - 10): ")
print steps, "steps to the right"
stepslength = 12.5 / int(steps)
for Counter in range(int(steps)):
Servo.ChangeDutyCycle(12.5 - (stepslength * (Counter + 1)))
print (12.5 - (stepslength * (Counter + 1)))
time.sleep(0.5)
time.sleep(1)
# PWM stop
print "Move back to start position."
Servo.stop()
# close program
elif(input == "q"):
print "stop the program and exit......"
os._exit(1)
Servo.stop()
GPIO.cleanup()
# input not valid
else:
print "input not valid!"
| true |
dfcb229e75954558251f176184894986699b35bd | juliovt-07/Exercicios-Python | /Condicional 30.py | 872 | 4.1875 | 4 | #Faça um programa que receba três números e mostre-os em ordem crescente.
n1 = int(input("1º Número: "))
n2 = int(input("2º Número: "))
n3 = int(input("3º Número: "))
if n1 == n2 and n2 == n3:
print("{}\n{}\n{}".format(n1,n2,n3))
elif n1 > n2 and n1 > n3:
if n2 > n3:
print("{}\n{}\n{}".format(n3,n2,n1))
if n3 > n2:
print("{}\n{}\n{}".format(n2,n3,n1))
if n2 == n3:
print("{}\n{}\n{}".format(n2,n3,n1))
elif n2 > n1 and n2 > n3:
if n1 > n3:
print("{}\n{}\n{}".format(n3,n1,n2))
if n3 > n1:
print("{}\n{}\n{}".format(n1,n3,n2))
if n1 == n3:
print("{}\n{}\n{}".format(n1,n3,n2))
elif n3 > n1 and n3 > n2:
if n1 > n2:
print("{}\n{}\n{}".format(n2,n1,n3))
if n2 > n1:
print("{}\n{}\n{}".format(n1,n2,n3))
if n2 == n1:
print("{}\n{}\n{}".format(n1,n2,n3)) | false |
f59e9cb69c1136d884aa183444b424824242f69b | juliovt-07/Exercicios-Python | /Condicional 34.py | 1,218 | 4.25 | 4 | #Leia a nota e o número de faltas de um aluno, e escreva seu conceito.
#De acordo com a tabela abaixo, quando o aluno tem mais de 20 faltas
#ocorre uma redução de conceito.
nota = float(input("Nota do aluno: "))
faltas = int(input("Faltas do aluno: "))
if nota < 0:
print("Nota Inválida!")
elif nota >= 9 and nota <= 10:
if faltas < 0:
print("Valor Inválido!")
elif faltas > 0 and faltas <= 20:
print("A")
elif faltas > 20:
print("B")
elif nota >= 7.5 and nota <= 8.9:
if faltas < 0:
print("Valor Inválido!")
elif faltas > 0 and faltas <= 20:
print("B")
elif faltas > 20:
print("C")
elif nota >= 5 and nota <= 7.4:
if faltas < 0:
print("Valor Inválido!")
elif faltas > 0 and faltas <= 20:
print("C")
elif faltas > 20:
print("D")
elif nota >= 4 and nota <= 4.9:
if faltas < 0:
print("Valor Inválido!")
elif faltas > 0 and faltas <= 20:
print("D")
elif faltas > 20:
print("E")
elif nota >= 0 and nota <= 3.9:
if faltas < 0:
print("Valor Inválido!")
elif faltas > 0 and faltas <= 20:
print("E")
elif faltas > 20:
print("Morreu") | false |
275ec55e14c490e8ede6c86a810c37dc9bcf8232 | felipeamodio/tupla_python | /Aula8.py | 1,054 | 4.15625 | 4 | #Listas em Python
import sys
nome = "Felipe Alves"
idade = 24
peso = 90.5
# o getsizeof verifica o tamanho da memória ram do computador de qualquer objeto
print("A variável nome é do tipo {} e tem {} bytes".format(type(nome), sys.getsizeof(nome)))
print("A variável idade é do tipo {} e tem {} bytes".format(type(idade), sys.getsizeof(idade)))
print("A variável peso é do tipo {} e tem {} bytes".format(type(peso), sys.getsizeof(peso)))
# tupla são parecidos com as listas mas todos os dados armazenados permanecera2o sempre nas mesmas posições
# enquanto listas sa2o criadas com [] as tuplas são criadas com ()
filmes = ("Avengers", "Avatar", "Toy Story", "Interestelar", "Bad Boys")
for filme in filmes:
print(filmes)
print(filmes[1])
print(filmes[3])
listaVazia = []
tuplaVazia = ()
print("O objeto listaVazia é do tipo {} e ocupa {} bytes de memória".format(type(listaVazia), sys.getsizeof(listaVazia)))
print("O objeto tuplaVazia é do tipo {} e ocupa {} bytes de memória".format(type(tuplaVazia), sys.getsizeof(tuplaVazia))) | false |
bcbbdc25716defff358f949d7e4be011d9833aa3 | SimpleLogic96/cs_problem_sets | /a07_definite_loop/a07_clock.py | 2,724 | 4.21875 | 4 | #Pt II: Simple Clock
#Time formatter
def format_time(current_hour, current_min):
#if current minute is greater than 60
if(current_min > 60):
current_hour += 1
current_min = current_min - 60
#if current minute is equal to 60
elif(current_min == 60):
current_hour += 1
current_min = 0
#if current minute is within valid range
else:
current_hour = current_hour
current_min = current_min
#if current hour is one digit long
if(int(current_hour) <= 9):
#if current minute is one digit long
if(int(current_min) <= 9):
formatted_time = '0' + str(current_hour) + ':' + '0' + str(current_min)
return formatted_time
#if current minute is two digits long
else:
formatted_time = '0' + str(current_hour) + ':' + str(current_min)
return formatted_time
#if current hour is two digit long
elif(int(current_hour) > 9):
#if current minute is one digit long
if(current_min <= 9):
formatted_time = str(current_hour) + ':' + '0' + str(current_min)
return formatted_time
#if current minute is two digit long
else:
formatted_time = str(current_hour) + ':' + str(current_min)
return formatted_time
#Print out intervals of hours and minutes within a specified period of time
def print_times(start_hour, stop_hour, increment):
#if start hour is greater than 24
if(start_hour > 24):
print('Error, your start hour is greater than 24!')
#if stop hour is greater than 24
elif(stop_hour > 24):
print('Error, your stop hour is greater than 24!')
#if the increment is not a factor of 60
elif(60 % increment != 0):
print('Error, your increment is not a factor of 60!')
#if the start and stop hours are within range and the increment is a factor of 60
else:
#Hour Loop
for current_hour in range(start_hour, stop_hour + 1):
#Minute Loop
for min_times_counter in range(60//increment):
#Add to current minute counter
current_min = increment * min_times_counter
#if current_hour exceeds the stop hour, print Time's Up! and break from loop
if(current_hour > stop_hour and current_min != 0):
print('Times Up!')
break
#if current hour are equal and the current minute is 0, display the current hour with 0 as minutes
elif(current_hour == stop_hour and current_min == 0):
print(format_time(int(current_hour), 0))
print('Times Up!')
#if current_hour is within range, display the current time
elif(current_hour < stop_hour):
print(format_time(int(current_hour), current_min))
start_hour = int(raw_input('Enter the start hour: '))
stop_hour = int(raw_input('Enter the stop hour: '))
increment = int(raw_input('Enter the increment: '))
print_times(start_hour, stop_hour, increment)
| true |
048f4d4ab9aaeb7227d4d7c600e40768a638c219 | WHJR-G8/G8-C7_TA_1 | /Sol_TA_1.py | 458 | 4.1875 | 4 | import turtle
n1 = int(input("Enter the no of the sides of the polygon : "))
l1 = int(input("Enter the length of the sides of the polygon : "))
for _ in range(n1):
turtle.forward(l1)
turtle.right(360 / n1)
turtle.penup()
turtle.goto(80,40)
turtle.pendown()
n2 = int(input("Enter the no of the sides of the polygon : "))
l2 = int(input("Enter the length of the sides of the polygon : "))
for _ in range(n2):
turtle.forward(l2)
turtle.right(360 / n2)
| false |
0d81e12471342954d05f0926606c9053d9fba2d4 | shinji-python/TaxCalculator | /TaxCalculator.py | 849 | 4.21875 | 4 | def tax_calculator(amount,tax_rate):
tax_amount= str(round(amount + (tax_rate*amount),2))
print('Your value including tax is: $',tax_amount)
def input_value():
amount = int(input('What is your value amount?'))
return amount
def input_tax():
tax = float(input('What is your tax rate?'))
return tax * .01
while True:
print('Welcome to the Tax Calculator!')
# Ask the user the input the amount
amount = input_value()
# Ask the user to provide the country or state tax rate
tax_rate = input_tax()
# Calculate the total amount taxed
tax_calculator(amount, tax_rate)
# Ask if the user wants another calculation
new_calculation = input('Do you want another calculation? Y or N')
if new_calculation == 'Y':
continue
else:
print('Thanks for Calculating!')
break | true |
3d0b170cd47bdeb9a9af3533fe302db476d35bac | brandonlyon24/Python-Projects | /python_if.py | 960 | 4.125 | 4 |
num1 = 12
key = False
if num1 == 12:
if key:
print('num1 is equal to 12 and they have the key')
else:
print('num1 is equal to 12 and they do not have the key')
elif num1 < 12:
print('num1 is less than 12')
else:
print('num1 is not equal to 12')
a = 100
b = 50
if a > b:
print('A is bigger than b')
elif a == b:
print('A and B are equal')
else:
print('B is bigger than a')
#Nested statement
x = 60
if x > 40:
print('x is bigger than 40')
if x > 50:
print('Its not 50 so it must be 60!')
else:
print('number is bigger than 60')
print(bool('Hello'))
print(isinstance(x,int))
i = 0
while i < 12 :
print("{} iteration through the loop.".format(i))
if i == 6:
i += 1
while i < 10:
print(i)
if i == 5:
break
i += 1
while i < 10:
i += 1
if i == 5:
continue
print(i)
i = 1
while i < 6:
print(i)
i += 1
else:
print("hello")
| true |
131a77d98c19966369e51659ba5bba20f1510e4f | SeungpilHan/Python_Tutorial | /Desktop/Coding/Jump to Python/dictionary.py | 640 | 4.15625 | 4 | """
대응관계를 나타내는 자료형
연관 배열 또는 해쉬라고 한다
키값을 통해 value값을 얻는다.
"""
a = {1: 'hi'}
print(a)
a = {1: 'a'}
a[2] = 'b'
print(a)
a['name'] = 'pay'
print(a)
del a[1]
print(a)
grade = {'pay': 10, 'julliet': 99}
print(grade['pay'])
print(grade['julliet'])
a = {'a':1, 'b':2}
print(a['a'])
print(a['b'])
dic = {'name':'han', 'age':28, 'birthday':19980801}
print(dic.keys())
for k in dic.keys():
print(k)
print(list(dic.keys()))
print(dic.items())
dic = {'name': 'han', 'age': 28, 'birthday': 19980801}
print(dic.get('name'))
print(dic.get('bar', 'good'))
print('name' in dic) | false |
275f20aa39213a166b62af5bb1ac9db5007ad192 | Daredevil2117/DSA_GFG | /Sorting/Gfg Learning/05. Merge Function of Merge Sort.py | 1,049 | 4.28125 | 4 | '''
Given three indices low mid and high and an array elements in array from low to mid are sorted
and mid+1 to high are sorted. sort these elements from low to high together.
'''
def MergeFunction(arr,low,mid,high):
n1=mid-low+1;n2=high-mid # Counting number of sorted elements in both the part
left=[]
right=[]
for i in range(n1):
left.append(arr[low+i])
for j in range(n2):
right.append(arr[mid+1+j])
i=0;j=0;k=low
while(i<n1 and j<n2):
if left[i]<=right[j]:
arr[k]=left[i]
i+=1
k+=1
else:
arr[k]=right[j]
j+=1
k+=1
while(i<n1):
arr[k]=left[i]
i+=1
k+=1
while(j<n2):
arr[k]=right[j]
j+=1
k+=1
return arr
arr=[8,6,1,2,3,4,5,3,4,5,9,8] # array is sorted from 2 to 6 and then 7 to 9 so low=2 mid=6 high=9
print(MergeFunction(arr,2,6,9))
'''
Time Complexity: O(n)
Space Complexity:O(n) # as total size of new arrays left + right is n
''' | true |
667cc5de2a100c1fe23d3a5cb63b414d78c160e0 | Rahul-Kumar-Tiwari/Hactoberfest2020-1 | /NumGuessGame.py | 1,377 | 4.15625 | 4 | # Guess_a_number
#Script of a game that asks the player to guess the number in specific number of attempts.
import random
print("What is your name?") #Asking player to enter name.
name = str(input()) #Taking input from player.
print("Hey " + name + ",I was thinking of a number between 1 to 20.Can you guess it???")
secret_number = random.randint(1, 20) #Generating a random number for player to guess.
#Taking input of guess from player
for guess_taken in range(1, 7):
if guess_taken == 1:
print("Guess the number ")
elif guess_taken == 6:
print("This is your last chance.")
else:
print("Give another try")
guess = int(input())
if guess > secret_number:
print("Your guess is too high.")
elif guess < secret_number:
print("Your guess is too low.")
else:
break #This condition is for correct guess!
if guess == secret_number:
if guess_taken == 1:
print("Amazing!!! You guessed the number in just one guess.")
else:
print("Good job " + name + "! You guessed my number in " + str(guess_taken) + " guesses.") #Executes when player guess the number.
else:
print("Nope.The number I was thinking of was " + str(secret_number) + ".Better luck next time!!!") #Executes when player fails to guess the number in given chances.
| true |
c61868881bca8ad83ebca3bd0a497651bba16d08 | bluezzyy/LearnPython | /Codes/ex18.py | 761 | 4.40625 | 4 | # -*- coding: utf-8 -*-
# Exercise 18: Names, Variables, Code, Functions
# 名称,变量,代码,函数
# Learn Python the Hard Way ---- 第二天
# Date: 2017/01/05 9:40 am
# this one is like your script with argv
def print_two(*args): # 多个参数的第一种方法
arg1, arg2 = args
print "arg1 : %r, arg2: %r" %(arg1, arg2)
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2): # 多个参数的第二种方法
print "arg1: %r, arg2: %r" % (arg1, arg2)
# this just takes ont arguments
def print_one(arg1):
print "arg1 : %r" %arg1
# this one takes no arguments
def print_none():
print "I got nothin'."
print_two("Blue","Hobert")
print_two_again("Blue","Hobert")
print_one("Blue")
print_none()
| true |
506c84fcb371ca6e67155ac39ce199e13f85df35 | bluezzyy/LearnPython | /Codes/ex14.py | 1,043 | 4.3125 | 4 | # -*- coding: utf-8 -*-
# Exercise 14: Prompting and Passing
# 通过argv来设置user_name 并且通过raw_input()函数输入问题的答案
# Learn Python the Hard Way ---- 第一天
# Date: 2017/01/04
''' -----------------------------------
心得: |
这个真的是太好玩了 支持中文输入哦 哈哈哈~ |
------------------------------------'''
from sys import argv
script, user_name = argv
# prompt = ">" #用于接受输入时的提示符号
prompt = "%s Input Here:" %user_name
print "Hi, I'm the %s script" % user_name
print "I'd like to ask you some questions."
print "Do you like me ? %s " % user_name # 你喜不喜欢我!
likes = raw_input(prompt)
print "Where do you live? %s" % user_name # 你家在哪!
lives = raw_input(prompt)
print "What kind of computer do you have? %s" %user_name
computer = raw_input(prompt) # 你的新Mac呢!
print"""
Ok, now I do know you say %s about liking me, you are living on %s,
and you have a %s computer. 你这个逗逼!
""" %(likes,lives,computer) | false |
e83f578e92c5da22e366b2d0431a3baeaf1c67b2 | Programmer-RD/Other-Projects | /Greater or less or equal.py | 782 | 4.28125 | 4 | import time
print(" > |!Welcome to Greater or equal or less Calculator!| < ")
time.sleep(0.30)
Name = input(" > What is your Name ? ")
How_Much = int(input(" > How many times do you want to see which it is greater or less or equal"))
for i in range(0,How_Much) :
entersone = int(input(" > Enter First Number... \n > "))
enterstwo = int(input(" > Enter Second Number... \n > "))
if entersone > entersone :
print(f" > {entersone} is greater than {enterstwo}... ")
elif entersone < enterstwo :
print(f" > {enterstwo} is greater than {entersone}... ")
elif entersone == enterstwo :
print(f" > {entersone} and {enterstwo} are equal... ")
else :
print(" > An error occured...")
print(" > Try again later...")
print(f"Bye {Name}")
print("See you later..") | false |
bfe4077630690b6fe1800df6247bd5fc8da8f71e | VasiliyRom/Python-test-repo-phase-1 | /test_lessoon.py | 2,060 | 4.15625 | 4 | # Наш перший коментар
int_value = 1 # Ціле число, integer or int
negative_int_value = -1 # Ціле відємне число, integer or int
print(int_value)
print(negative_int_value)
float_value = 1.234 # Float, дробове число або чисо з плаваючою точкою
print(float_value)
print()
string_value = 'Text' # String or str стрічка with quotes
print(string_value)
string_second = "Text 2" # String or str стрічка with double quotes
print(string_second)
print()
meaningful_sentence = "Once upon a time .... don't"
print(meaningful_sentence)
meaningful_sentence_two = 'Once upon a time .... don\'t \\m/'
print(meaningful_sentence_two)
print()
meaningful_sentence_three = 'The First line \n\tThe Second one'
print(meaningful_sentence_three)
print()
very_long_string = 'Very long long long sentence without any sence or context' +\
'but stil this one is very long and hardly readable'
print(very_long_string)
print()
paragraph_text = """First line
second line
third line
...
last line"""
print(paragraph_text)
print()
paragraph_text_single_quotes = '''First line
second line
third line
...
last line'''
print(paragraph_text_single_quotes)
print()
negative_statement = False # False actually is 0
positive_statement = True # True actually 1
print(negative_statement)
print(positive_statement)
print()
#Calculations
x = 1
y = 2
print(x + y)
print(x - y)
print(x / y)
print(x * y)
print(x % y)
print(x // y)
print(f'Sum: {x} + {y} = {x + y}')
print(f'Ext: {x} - {y} = {x - y}')
print(f'Div: {x} / {y} = {x / y}')
print(f'Mult: {x} * {y} = {x * y}')
print(f'Modulo: {x} mod {y} = {x % y}')
print(f'Integer division: {x} // {y} = {x // y}')
print(f'Text: {paragraph_text_single_quotes}')
x = 3
y = 3
comparison_result = x == y
print(f'Comparing {x} and {y}: {comparison_result}')
print(f'Is {x} more than {y}: {x > y}')
print(f'Is {x} less than {y}: {x < y}')
print(f'Is {x} more or equal than {y}: {x >= y}')
print(f'Is {x} less or equal than {y}: {x <= y}')
| false |
429438621d712c5cbf86ef9df83ac2c049a97731 | adrianlievano/unscramble_problems_bigO_exercises | /Task4.py | 1,316 | 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.
"""
#check calls database
#gets only callers
unique_num_callers = []
i = 0
j = 0
for i in range(len(calls)):
if calls[i][0] not in unique_num_callers:
unique_num_callers.append(calls[i][0])
sender_texts = []
for j in range(len(texts)):
if texts[j][0] not in sender_texts:
sender_texts.append(texts[j][0])
sorted(sender_texts)
sorted(unique_num_callers)
for ele in sender_texts:
if ele in unique_num_callers:
unique_num_callers.remove(ele)
tele_nums = sorted(unique_num_callers)
print("These numbers may be telemarkers: ")
for i in tele_nums:
print('{}'.format(i))
| true |
db8f7b022b3f7e4a5a264f3293166130799898cf | gay88358/PythonRealApplication | /course1/data_structure/list.py | 474 | 4.125 | 4 |
# 用來註解,當編譯器執行到這行,不會執行
if __name__ == '__main__':
data = [ 2, 3, 4, 1, 2, 3 ] # integer list
name = ['apple', 'htc', 'samsung', 'asus', 'acer'] # string list
#indexing of list
print(data[0]) # 2 first element
print(data[-1]) # last element
print(data[2:4]) # 4 2
print(data[:4]) # 2 3 4 1
print(data[1:-1]) # 3 4 1 2
print(data[0:]) # all element
data.append(100) # append
print(data)
| false |
a246003a977ae6265f8312c887efa5b803756b23 | chvillap/URI | /utils/generate_fibonot.py | 702 | 4.125 | 4 | import sys
def fibonacci():
a, b = 0, 1
yield b
while True:
yield a + b
a, b = b, a + b
if __name__ == '__main__':
if len(sys.argv) > 1:
k = int(sys.argv[1])
fibonot = []
f_gen = fibonacci()
a = next(f_gen)
b = next(f_gen)
while len(fibonot) < k:
print(a, b)
if b - a > 1:
i = a + 1
while i < b and len(fibonot) < k:
fibonot.append(i)
i += 1
a = b
b = next(f_gen)
print(fibonot)
print('last fibonacci number: {}'.format(b))
else:
print('Usage: {} k'.format(sys.argv[0]))
| false |
4287f994a9a39520b791bc9767028de474b6521f | LeeSM0518/TIL | /python/Python_5ch_Class_and_Module/random_modul.py | 1,137 | 4.125 | 4 | # random 모듈 : 난수 발생시키는 모듈
print('random 모듈\n')
import random
# random.random() : 0.0 에서 1.0 사이의 실수 중에서 난수값을 리턴
print('random.random() = ', random.random())
# random.randint(1,10) : 1에서 10 사이의 정수 중에서 난수값 리턴
print('\nrandom.randint(1,10) = ',random.randint(1,10))
# random example function
print('\nrandom example function')
def random_pop(data):
number = random.randint(0, len(data) - 1)
return data.pop(number)
if __name__ == '__main__':
data = [1,2,3,4,5]
while data: print(random_pop(data))
# random.choice() : 입력으로 받은 리스트에서 무작위로 하나를 선택하여 리턴.
print('\nrandom.choice() 이용')
def random_pop(data):
number = random.choice(data)
data.remove(number)
return number
if __name__ == '__main__':
data = [1,2,3,4,5]
while data : print(random_pop(data))
# random.shuffle() : 리스트의 항목을 무작위로 섞는다.
data = [1,2,3,4,5]
print('\ndata = ', data )
random.shuffle(data)
print('random.shuffle(data) = ', data)
| false |
77f3a8dd014e0de07cf9464cd3ae4ff3e497b99c | Hemapriya485/guvi | /Factorial.py | 236 | 4.125 | 4 | def factorial_of_n(n):
fact=1
for x in range(1,n+1):
fact=fact*x
return fact
print("Enter a number:")
n=int(input())
print(n)
factorial=factorial_of_n(n)
print("Factorial of "+str(n)+" is "+str(factorial))
| true |
c021e9e72c3cbb74ca79dcc9c53e3912cae72b0e | mirigonza/funciones_python | /ejercicios_practica/ejercicio_5.py | 1,593 | 4.375 | 4 | # Funciones [Python]
# Ejercicios de práctica
# Autor: Inove Coding School
# Version: 2.0
# IMPORTANTE: NO borrar los comentarios
# que aparecen en verde con el hashtag "#"
# Ejercicios con funciones y módulos
import random
# --------------------------------
# Aquí dentro definir la función contar
# Aquí copiar la función lista_aleatoria
# ya elaborada
# --------------------------------
if __name__ == '__main__':
print("Bienvenidos a otra clase de Inove con Python")
inicio = 0
fin = 9
cantidad = 5
# Alumno: Crear la función "contar"
# Utilice la función "lista_aleatoria" creado antes
# para generar una lista de 5 números en
# un rango de 1 a 9 inclusive
# lista_numeros = lista_aleatoria(inicio, fin, cantidad)
# Generar una una nueva funcion que se llame "contar",
# que cuente la cantidad de veces que un elemento pasado
# por parámetro se repite en la lista también pasada por parámetro
# Para saber cuantas veces se repiten el elemento pasado
# en la lista pueden usar el método nativo de list "count"
# Por ejemplo creo una lista de 5 elemtnos
# Luego quiero averiguar cuantas veces se repite el numero 3
# cantidad_tres = contar(lista_numeros, 3)
# Luego de crear la función invocarla en este lugar:
# Averiguar cuantas veces se repite el numero 3
# cantidad_tres = contar(lista_numeros, 3)
# Imprimir en pantalla "cantidad_tres" que informa
# cuantas veces se repite el tres en la lista
# print(cantidad_tres)
print("terminamos")
| false |
37fcd66b7532aa8b4cb8482004b0bf858b995d77 | sensactive/algo_and_structures_python | /Lesson_7/1.py | 2,019 | 4.125 | 4 | """
1. Отсортируйте по убыванию методом "пузырька" одномерный целочисленный массив,
заданный случайными числами на промежутке [-100; 100). Выведите на экран
исходный и отсортированный массивы. Сортировка должна быть реализована в
виде функции. По возможности доработайте алгоритм (сделайте его умнее).
"""
import timeit
from random import randint
def sort(arr):
for i in range(0, len(arr)):
for j in range(i+1, len(arr)):
if arr[i] < arr[j]:
arr[i], arr[j] = arr[j], arr[i]
return arr
def sort_1(arr):
for i in range(0, len(arr)):
for j in range(i+1, len(arr) - i):
if arr[i] < arr[j]:
arr[i], arr[j] = arr[j], arr[i]
return arr
def sort_2(arr):
i = 0
t = True
while t:
t = False
for j in range(i+1, len(arr) - i):
if arr[i] < arr[j]:
arr[i], arr[j] = arr[j], arr[i]
t = True
return arr
arr = [randint(-100, 100) for _ in range(0, 15)]
print(arr)
print(sort(arr))
print(sort_1(arr))
print(sort_2(arr))
print(timeit.timeit(f'sort({arr})', setup="from __main__ import sort", number=10000))
print(timeit.timeit(f'sort_1({arr})', setup="from __main__ import sort_1", number=10000))
print(timeit.timeit(f'sort_2({arr})', setup="from __main__ import sort_2", number=10000))
'''
Второй способ работает в полтора раза быстрее, т.к. мы не проходим по тем элементам, которые уже "всплыли".
Третий способ работает в 10 раз быстрее первого, т.к. + ко 2-му способу цикл завершается, если не произошло
ни одной замены элементов.
''' | false |
a020b0cdde92111044bea07c5161543413f8cf1b | sayalimahadik/python_practise | /prime.py | 221 | 4.125 | 4 | print("enter your input: ")
a=int(input())
if a==2:
print(f"{a} is prime number")
for i in range(2,a):
if a%i==0:
print(f"{a} not prime number")
break
if i>=(a-1):
print(f"{a} prime number") | false |
95e69bbe5455875784486479d901b129ba018019 | hansknecht/PythonSandbox | /PythonSandbox/sqlroot.py | 594 | 4.375 | 4 | #!/usr/bin/env python3
def sqrt(input_s):
''' Compute square root using the method of Heron of Alexandria.
Args:
x: The number of which the square root is to be computed
Returns:
The square root of x.
Raises:
ValueErro: if x is negative.
'''
if input_s < 0:
raise ValueError("Cannot compute square root of "
"negative number {}".format(input_s))
guess = input_s
i = 0
while guess * guess != input_s and i < 20:
guess = (guess + input_s / guess) / 2.0
i += 1
return guess
| true |
f2177c1468c610c224a98d9bfbe6b746d8684844 | rasareachan/text-adventure | /feminism1.py | 2,142 | 4.1875 | 4 | name = input("Insert strong, independent name (aka your name bc you're a strong, independent woman)\n")
print("Welcome " + name + "! This your life.\n\nYour mom wants you to be a doctor, but you've always wanted to be an engineer.\n")
q1 = input("Do you a: 'listen to your mom' or b: 'pursue your dreams'? (Please only press 'a' or 'b'!)\n")
# if choose to listen to mom
if q1 == "a":
print("You will live an unhappy life.\n")
# end game here; come back to this later lol
# if choose to pursue dreams
elif q1 == "b":
print("You get it, girl!\n")
print("While you are out here pursing your dreams, you also have a boyfriend of five years named Jake.")
print("He feels threatened that you are a woman going into the engineering field; he is very unhappy.\n")
q2 = input("Do you a: 'stay with him' or b: 'keep doing you and following your dreams'?\n")
# if choose stay with him
if q2 == "a":
print("You will live an unhappy life.\n")
elif q2 == "b":
print("Congratulations! You got rid of your obstacle. You didn't need him anyway!\n")
print("You graduate from college at the top of your class and land an opportunity to intern at Apple!")
print("However, you see that all the workers are old White men who don't understand what you're doing there as a woman.\n")
q3 = input("Do you a: 'get intimidated and choose to never come back to the industry' or b: 'continue to persevere through the struggles', as you've been doing, girl?\n")
if q3 == "a":
print("You will live an unhappy life.\n")
elif q3 == "b":
print("You continue with the internship and eventually get a position at the company!\n")
print("Five years later, you have a happy life with a supportive husband (or wife!!) who doesn't think you threaten his masculinity!")
print("You are also now the CEO of your own company that teaches girls how to code!")
print("Your daughter sees you as an example and now wants to be as strong as you.\n")
print("You go, fam!!! You have succeeded in life, girl #empowerment")
| true |
48090935c800fcf07ff12597adc8d943a9fbcfc0 | byfuls/python | /namedtuple/namedtuple-dict.py | 982 | 4.125 | 4 | from collections import namedtuple
class data:
def __init__(self, name):
self.__name = name;
self.__value1 = 1;
self.__value2 = 2;
@property
def name(self):
return self.__name
@property
def val1(self):
return self.__value1
@property
def val2(self):
return self.__value2
# prepare input data
a = data('a');
b = data('b');
c = data('c');
d = data('d');
# prepare namedtuple
titles = namedtuple('titles', 'a b c d')
# input class data to namedtuple
namedtuple_dict = titles(a,b,c,d)
# show input data
print(namedtuple_dict)
# get input data
print(f'a data: {namedtuple_dict.a}')
print(f'a data.name: {namedtuple_dict.a.name}')
print(f'a data.val1: {namedtuple_dict.a.val1}')
print(f'a data.val2: {namedtuple_dict.a.val2}')
print(f'b data: {namedtuple_dict.b}')
print(f'b data.name: {namedtuple_dict.b.name}')
print(f'b data.val1: {namedtuple_dict.b.val1}')
print(f'b data.val2: {namedtuple_dict.b.val2}') | false |
bc0a1a22dbebe78ed7e2df192f9d056390e46da8 | ggdecapia/raindrops | /raindrops.py | 569 | 4.40625 | 4 | def convert(number):
# initialize string output variable
string_output = ""
# check if number is a multiple of 3
if number % 3 == 0:
string_output = "Pling"
# check if number is a multiple of 5
if number % 5 == 0:
string_output = string_output + "Plang"
# check if number is a multiple of 7
if number % 7 == 0:
string_output = string_output + "Plong"
# if number is NOT a multiple of 3, 5, 7 return the number
if string_output != "":
return string_output
else:
return str(number) | true |
307bcd423f522f6b799843bace5306ece9d95a1b | zimindkp/pythoneclipse | /PythonCode/src/Exercises/palindrome.py | 853 | 4.4375 | 4 | # K Parekh Feb 2021
# Check if a string or number is a palindrome
#function to check if number is prime
def isPalindrome(n):
# Reverse the string
# We create a slice of the string that starts at the end and moves backwards
# ::-1 means start at end of string, and end at position 0 (the start), move with step -1 (1 step backwards)
litmus = n[::-1]
# Here is an example slice that starts from position 0 and goes till character 4
litmus2 = n[:4]
print(litmus, "is the reversed string")
print(litmus2, "is another string")
if (litmus == n):
return True
else:
return False
# Driver Program
# Enter number here
tester = input("Enter a string\n")
#Run the command
if (isPalindrome(tester)):
print (tester, "is a Palindrome")
else:
print (tester, "is NOT a Palindrome")
| true |
f18eaa34cbb4b2dfb3d04aafdac81d4665c7678a | HassanBahati/python-sandbox | /strings.py | 973 | 4.4375 | 4 | '''
strings in python are surrounded by either single or double quotation marks. lets look at string formatting and some string methods
'''
name = 'joe'
age = 37
#concatenate
print('Hello, my name is ' + name + ' and I am ' + str(age))
#string formatting
#f-string
print(f'My name is {name} and i am {age}')
#string methods
s = 'hello world'
l = 'HELLO WORLD'
#capitalize
print(s.capitalize())
#make all uppercase
print(s.upper())
#make all lower case
print(l.lower())
#swap case -alternate case
print(s.swapcase())
#get length
print(len(s))
#replace
print(s.replace('world', 'everyone'))
#count number of a given character in the string
sub = 'h'
print(s.count(sub))
print(s.count('h'))
#starts with
print(s.startswith('hello'))
#ends with
print(s.endswith('d'))
#split into a list
print(s.split())
#find position
print(s.find('r'))
#is all alphanumeric
print(s.isalnum())
#is all aphabetic
print(s.isalpha())
#is all numeric
print(s.isnumeric())
| true |
d09944125d070ccedf9f2b6582a9a374489e6796 | chenweizhe/PythonCode | /test27.py | 1,844 | 4.1875 | 4 | #!/usr/bin/env python3
# 排序算法
# 排序也是在程序中经常用到的算法。无论使用冒泡排序还是快速排序,排序的核心是比较两个元素的大小。
# 如果是数字,我们可以直接比较,但如果是字符串或者两个dict呢?直接比较数学上的大小是没有意义的,因此,比较的过程必须通过函数抽象出来
# python 内置sorted()函数可以对list进行排序
sorted([1,2,-5,69,7])
# 此外,sorted()函数也是一个高阶函数 可以接受一个key函数实现自定义排序
# 例:按绝对值排序
list = [36,5,-12,9]
print(sorted(list,key=abs))
# key指定的函数将作用于list的每一个元素上,并根据key函数返回的结果进行排序
'''默认情况下,对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a',结果,大写字母Z会排在小写字母a的前面。
现在,我们提出排序应该忽略大小写,按照字母序排序。要实现这个算法,不必对现有代码大加改动,只要我们能用一个key函数把字符串映射为忽略大小写排序即可。忽略大小写来比较两个字符串,实际上就是先把字符串都变成大写(或者都变成小写),再比较。
这样,我们给sorted传入key函数,即可实现忽略大小写的排序:'''
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower))
# 要反向排序,不必改动key函数 可以传入第三个参数reverse = True
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower,reverse=True))
# 高阶函数的抽象能力是非常强大的,而且,核心代码可以保持得非常简洁
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
return t[0].lower()
print(sorted(L,key=by_name))
def by_score(t):
return t[1]
print(sorted(L,key=by_score)) | false |
934abfc927a7b4ed8c5282da76630eab4cc035b9 | chenweizhe/PythonCode | /test18.py | 640 | 4.25 | 4 | #! /usr/bin/env python3
# 迭代循环 for...in...
d = {'a':1,'b':2,'c':3}
for key in d:
print(key)
for n in 'casucsabkjcbsak':
print(n)
# 如何判断一个对象是可迭代对象呢?方法是通过collections模块的Iterable类型判断:
from collections import Iterable
print(isinstance('agb',Iterable))
print(isinstance(12345,Iterable))
# for循环里,同时引用了两个变量,在Python里是很常见的
# Python内置的enumerate函数可以把一个list变成索引-元素对,
# 这样就可以在for循环中同时迭代索引和元素本身:
for i,value in enumerate(['A','B','C']):
print(i,value)
| false |
c9555f2d23d9e3ffcd5c4626d0de85c1f6657450 | chenweizhe/PythonCode | /test12.py | 412 | 4.15625 | 4 | #! /usr/bin/env python3
dictts = {'dage':88,'erge':77,'sange':66}
print(dictts)
print(dictts['dage'])
if 'erge' in dictts:
print(dictts.get('erge'))
dictts.pop('dage')
print(dictts)
# dict的key为不可变对象
#set的使用
setts = set([1,2,3])
print(setts)
setts.add(4)
print(setts)
setts.remove(2)
print(setts)
# list是可变对象 所以我们才能改变set元素 但是set是不可变对象
| false |
4e0ffda7b9a7e07e772de7c5142ce25d7466f740 | chenweizhe/PythonCode | /test39.py | 978 | 4.40625 | 4 | #! /usr/bin/env python3
# _*_ coding:utf-8 _*_
# 实例属性和类属性
# python是动态语言,根据类创建的实例变量,或者通过self变量:
class Student(object):
name = 'Student' #类属性
def __init__(self,name):
self.name = name
s = Student('Bob')
s.score = 90 #实例属性
# 在编写程序的时候,千万不要对实例属性和类属性使用相同的名字,因为相同名称的实例属性将屏蔽掉类属性,但是当你删除实例属性后,再使用相同的名称,访问到的将是类属性。
class AddDog(object):
count = 0
def __init__(self,name):
self.name = name
AddDog.count += 1 #正确写法
def print_cou(self):
print(self.count)
a = AddDog('a')
print(AddDog.count)
b = AddDog('b')
print(AddDog.count)
c = AddDog('c')
print(AddDog.count)
# 当我们定义了一个类属性后,这个属性虽然归类所有,但类的所有实例都可以访问到。
| false |
afb92535521c4dd595c0d8c6a1bf60c674fff392 | mh70cz/py | /misc/tangent_lines.py | 1,136 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 14 23:06:16 2018
http://math-physics-problems.wikia.com/wiki/Graphing_Tangent_Lines_with_Python
@author: mh70
"""
import matplotlib.pyplot as plt
import numpy as np
def deriv(f, x):
h = 0.000_000_001 #step-size
return (f(x+h) - f(x))/h #definition of derivative
def deriv_left(f, x):
h = 0.000_000_001 #step-size
return (f(x) - f(x-h))/h #definition of derivative
def tangent_line(f, x_0, a, b):
x = np.linspace(a, b, 200)
y = f(x)
y_0 = f(x_0)
y_tan = deriv(f, x_0) * (x - x_0) + y_0
#plotting
plt.plot(x, y, "r-")
plt.plot(x, y_tan, "b-")
plt.axis([a, b, a, b])
plt.xlabel("x")
plt.ylabel("y")
plt.title("Plot of function with tangent line")
plt.show()
def f1(x):
return x**2
def f2(x):
return np.exp(-x**2)
tangent_line(f1, 1, -2, 2)
tangent_line(f2, -1.5, -2, 2)
d1 = deriv(f1, 1)
d1_left = deriv_left(f1, 1)
max([deriv(f1, x) - deriv_left(f1, x) for x in np.linspace(-2, 2, 200)])
max([deriv(f2, x) - deriv_left(f2, x) for x in np.linspace(-2, 2, 200)]) | false |
cd25867ac252dfc56aacf55f0fa823bca17a9834 | WinterDing/leetcode | /69-Sqrt(x).py | 668 | 4.21875 | 4 | """
Questions:
Implement int sqrt(int x).
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
"""
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
left, right = 0, (x+1)//2
#left, right = 0, (x//2)+1 also okay
while left <= right:
mid = (left+right)//2
sq = mid**2
if sq < x:
left = mid + 1
elif sq == x:
return mid
else:
right = mid - 1
return right | true |
47ce39f555faa2fcfdb9866fad5333739300dbd6 | mairiigomez/Practice-Challenges | /practicando_classes.py | 1,215 | 4.25 | 4 | class Vehicles:
"""Modeling a vehicle maximun speed and milage"""
def __init__(self, name, max_speed, mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage
self.color = 'White'
def description_vehicle(self):
print(f"color: {self.color}, vehicle: {self.name} maximun speed: {self.max_speed} mileage: {self.mileage}")
def capacity(self, capacity):
print(f"The seating capacity of a {self.name} is {capacity} passengers")
def fare(self):
capacity = int(self.capacity)
print(capacity * 100)
class Bus(Vehicles):
"""Bus class inheritance from vehicles"""
def __init__(self, name, max_speed, mileage):
super().__init__(name, max_speed, mileage)
self.seating_capacity = 50
def capacity(self, capacity = 50):
print(f"The seating capacity of a {self.name} is {capacity} passengers")
def fare(self):
print(self.capacity * 100)
small_car = Vehicles('mazda', 120, 3000)
small_car.description_vehicle()
small_car.capacity(4)
small_car.fare()
scolar_bus = Bus('bus',200, 2000)
scolar_bus.description_vehicle()
scolar_bus.capacity()
scolar_bus.fare()
| true |
59235210a401b8b57c005854e7339c0e1b1d3c2c | mairiigomez/Practice-Challenges | /student_calification.py | 1,492 | 4.3125 | 4 | """Give 3 notes of one student, all of them in the same line
split() storage them in the appropriate variable
*variable: can storage many values in a list
Convert all the elements to float with the map function and storage to a list
storage to a super dictionary , with the name as a key and the score as values
Then ask for a student that they would like to note the score of"""
if __name__ == '__main__':
n = int(input('Range for the function: '))
#open a empty dictionary
student_marks = {}
for _ in range(n):
# The first input goes to line and if there are more the
# get storage in line
name, *line = input('Give name a 3 scores: ').split()
#map convert all the values in the variable line in float
#this is save in a list
scores = list(map(float, line))
#Way to assing key and values to the dictionary
#name are the keys and score the values
student_marks[name] = scores
query_name = input("Query name: ")
# Looking for the student in the dictionary
if query_name in student_marks:
namelookupfor = query_name
#the key within [] looks for the value and store it in the variable
scores_query = student_marks[namelookupfor]
totalsq = sum(scores_query)
percentage = totalsq/3
#print the result with 2 decimals
print('%.2f' %percentage)
else:
print('That student is not in this school')
| true |
78fbcc0e9227a8fe2b0d0dfea64b1be8774392c4 | aseemang/Python-Tutorial-projects | /Building_a_Guessing_Game.py | 620 | 4.125 | 4 |
secret_word = "giraffe"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
#must use while loop to continuously ask person to guess word until they get it right
while guess != secret_word and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("Enter Guess: ")
guess_count += 1
else:
out_of_guesses = True
#two possibile ways loop can end: either guess correctly or out of guesses, so:
if out_of_guesses:
print("Out of Guesses, YOU LOSE!")
else:
print("You Win!")
#can make a better game than this though, let's set limit
| true |
355d1257fee997acaa1cca3e64eb7f039a497155 | NathanClark-GitHub/keyEncryption | /main.py | 1,913 | 4.25 | 4 | # Encryption/Decryption Algorithm using Keys #
# Developed by Nathan Clark #
def encrypt_text():
print("-----Encrypt Function-----")
print("Enter the encryption key:")
user_key: str = input()
print("Enter text to encrypt:")
user_text: str = input()
i = 0
new_output = ""
for i in range(0, len(user_text)):
mod = i % len(user_key)
num = ((ord(user_key[mod]) + ord(user_text[i])) % 122)
if num < 32:
new_output += chr(((ord(user_key[mod]) + ord(user_text[i])) % 122) + 32)
else:
new_output += chr((ord(user_key[mod]) + ord(user_text[i])) % 122)
i += 1
print("-----Encrypted Text Below-----")
print(new_output)
display_choices()
choice_prompt()
def decrypt_text():
print("-----Decrypt Function-----")
print("Enter the decryption key:")
user_key: str = input()
print("Enter text to decrypt:")
user_text: str = input()
i = 0
new_output = ""
for i in range(0, len(user_text)):
mod = i % len(user_key)
#print(ord(user_text[i]))
premod_num = 122 + ord(user_text[i])
#print(premod_num)
enc_num = premod_num - ord(user_key[mod])
if enc_num == 64:
enc_num = 32
#print(enc_num)
new_output += chr(enc_num)
print(new_output)
def display_choices():
print("\nPress 1 to encrypt")
print("Press 2 to decrypt")
print("Press 3 to exit")
def choice_prompt():
is_running = True
while is_running:
choice = input()
if choice == '1':
encrypt_text()
elif choice == '2':
decrypt_text()
elif choice == '3':
is_running = False
print("Program closing....")
exit()
else:
print("Invalid Input. Try Again")
if __name__ == "__main__":
display_choices()
choice_prompt()
| false |
00042ff379871170397cc9fdd5520b4346a7be04 | AbrarAlzubaidi/amman-python-401d7 | /class-10/demo/stack_and_queue/stack_and_queue/queue.py | 562 | 4.125 | 4 | from stack_and_queue.node import Node
class Queue:
"""
a class that implements the Queue Data structure
"""
def __init__(self):
self.front = None
self.rear = None
def enqueue(self, value):
node=Node(value)
if not self.rear:
self.front = node
self.rear = node
else:
self.rear.next = node
self.rear = node
def dequeue(self):
pass
def peek(self):
pass
def is_empty(self):
return self.front == None | true |
f4aca8b8bf8f6422d55b1d3de39837c43de9822e | annthurium/practice | /warmup_problems.py | 1,552 | 4.1875 | 4 | def factorial(n):
"""Returns n!"""
if n <= 1:
return n
else:
return n * factorial(n - 1)
print factorial(5)
# output a string in reverse
def reverse_string(string):
"""takes a string as input, returns reversed string as output"""
return string[-1::-1]
print reverse_string('pool')
reversed_string = []
def reverse_string_recursive(string):
"""takes a string as input, outputs reversed string"""
# base case is an empty string
# pop letters off of string in reverse order until string is empty
if len(string) == 0:
return string
else:
return string[-1] + reverse_string_recursive(string[:-1])
def reverse_string(str):
"""Takes a string, returns reversed string as output."""
new_str = ""
for i in range (0, len(str)):
new_str += str[-1-i]
print new_str
return new_str
# reverse_string('')
listy_doo = ['p', 'o', 'o', 'l']
def reverse_list_recursively(list):
"""Takes a list, returns list sorted in reverse order."""
new_list = []
def recursive(list):
if len(list) > 0:
new_list.append(list.pop())
recursive(list)
else:
return
recursive(list)
return new_list
# print reverse_list_recursively(listy_doo)
# output fibonacci sequence up to letter n
def print_fibonacci(n):
"""prints fibonacci sequence up to nth letter"""
base = [0, 1]
for i in range(0, n):
base = (base[1], sum(base))
print base[0]
def fibonacci(n):
base = [0, 1]
list = []
for i in range(0, n):
temp = base[1]
base[1] = base[0] + base[1]
base[0] = temp
list.append(base[0])
return list
print fibonacci(12) | true |
9cfe2b4ff8ff04d87a9448633bc5ab8e3adbddda | sunilvarma9697/Code-Basics | /Generator.py | 302 | 4.125 | 4 | #Generator = it is used to create your own iterator and it is special type of functtion and it does not returns single value.
#yield keyword is used rather than return.
def Topten():
n = 1
while n <= 10:
sq = n * n
yield sq
n += 1
values = Topten()
for i in values:
print(i) | true |
7f58c1581d33b024b6debdaa5252e9ca895287f9 | sunilvarma9697/Code-Basics | /Dictionary.py | 495 | 4.34375 | 4 | #Dictionary - Dictionarys are used to store data in keys:values.
#Dictionary is a collection which is ordered.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
print(len(thisdict))
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
x = thisdict.get("model")
print(x)
| true |
0bfaba8c91042f8013741cf20227a724c6ee6139 | williamife/portfolio | /prime_or_not.py | 459 | 4.25 | 4 | #5. Write a program that asks a user for a number and then tests whether it is prime or not and prints out...
# “The number is prime” or “The number is not prime”.
number = int(input("Enter a number: "))
if number > 1:
for i in range(2,number):
if (number % i) == 0:
print(number, "is not a prime number")
break
else:
print(number, "is a prime number")
else:
print(number, "is not a prime number") | true |
df4fafdd59859214bcfe659e7b590723311dd950 | The-Bioinformatics-Group/gbg-python-user-group | /examples/return_or_not_return.py | 496 | 4.25 | 4 | #!/usr/bin/python
# Example of functions that returns a value, prints or don't return a value.
# 1. Define the functions
# Do the calcultation but return nothing.
def return_nothing(x):
y = x + 1
# Do the calculation print the value but return nothing.
def print_no_return(x):
x = x + 1
print x
# Do the calculation and return the value.
def return_value(x, i):
x = x + 1 + i
return x
# 2. Run the code
x = 10
z = 42
j = 2
#return_nothing(x)
#print_no_return(x)
#return_value(z, j)
| true |
229a6224054ca5ff638437083452b66ec5ccdb17 | Evardanyan/Phone-number | /main.py | 366 | 4.25 | 4 | import re
string = input()
# your code here
string_regex = re.match(r'^\+(\d)[\s-]?(\d{3})[\s-]?(\d{3}[\s-]?\d{2}[\s-]?\d{2})$', string)
if string_regex:
print(f"Full number: {string_regex[0]} ")
print(f"Country code: {string_regex[1]} ")
print(f"Area code: {string_regex[2]} ")
print(f"Number: {string_regex[3]} ")
else:
print("No match")
| false |
75dae321701c250673475b187ad8019d5600bbd4 | jabhij/MITx-6.00.1x-PYTHON | /Week-4/Prob4h.py | 2,054 | 4.1875 | 4 | def compChooseWord(hand, wordList, n):
"""
Given a hand and a wordList, find the word that gives
the maximum value score, and return it.
This word should be calculated by considering all the words
in the wordList.
If no words in the wordList can be made from the hand, return None.
hand: dictionary (string -> int)
wordList: list (string)
returns: string or None
"""
maxScore = 0
bestWord = None
for word in wordList:
if isValidWord(word, hand, wordList) == True:
wordScore = getWordScore(word, n)
if wordScore > maxScore:
maxScore = wordScore
bestWord = word
return bestWord
def compPlayHand(hand, wordList, n):
"""
Allows the computer to play the given hand, following the same procedure
as playHand, except instead of the user choosing a word, the computer
chooses it.
1) The hand is displayed.
2) The computer chooses a word.
3) After every valid word: the word and the score for that word is
displayed, the remaining letters in the hand are displayed, and the
computer chooses another word.
4) The sum of the word scores is displayed when the hand finishes.
5) The hand finishes when the computer has exhausted its possible
choices (i.e. compChooseWord returns None).
"""
totalScore = 0
while calculateHandlen(hand) > 0:
print ('Current Hand: ' ),
displayHand(hand)
word = compChooseWord(hand, wordList, n)
if word == None:
print ('Total score: ' + str(totalScore) + ' points.')
break
else:
totalScore = getWordScore(word, n) + totalScore
print ('"' + str(word) + '"' + ' earned ' + str(getWordScore(word, n)) + ' points. Total: ' + str(totalScore) + ' points')
hand = updateHand(hand, word)
if calculateHandlen(hand) == 0:
print ('Total score: ' + str(totalScore) + ' points.')
else:
print (' ')
| true |
ed919c956673ad96c51ed96bebe41c95831e6afb | PetraGuy/CMEECourseWork | /Week2/Code/lc2.py | 1,727 | 4.53125 | 5 | #!usr/bin/python
"""Chapter 5 Practicals, modify lc2.py, Petra Guy
Writing list comprehensions and for loops to extract elements from a list"""
__author__ = "Petra Guy, pg5117@ic.ac.uk"
__version__ = "2.7"
#imports
#constants
#functions
# Average UK Rainfall (mm) for 1910 by month
# http://www.metoffice.gov.uk/climate/uk/datasets
rainfall = (('JAN',111.4),
('FEB',126.1),
('MAR', 49.9),
('APR', 95.3),
('MAY', 71.8),
('JUN', 70.2),
('JUL', 97.1),
('AUG',140.2),
('SEP', 27.0),
('OCT', 89.4),
('NOV',128.4),
('DEC',142.2),
)
# (1) Use a list comprehension to create a list of month,rainfall tuples where
# the amount of rain was greater than 100 mm.
# (2) Use a list comprehension to create a list of just month names where the
# amount of rain was less than 50 mm.
# (3) Now do (1) and (2) using conventional loops (you can choose to do
# this before 1 and 2 !).
# ANNOTATE WHAT EVERY BLOCK OR IF NECESSARY, LINE IS DOING!
# ALSO, PLEASE INCLUDE A DOCSTRING AT THE BEGINNING OF THIS FILE THAT
# SAYS WHAT THE SCRIPT DOES AND WHO THE AUTHOR IS
#Here are the list comprehension methods. In the first, since we need each tuple
#element its just x for x in rainfall.
#For the second only want the first item in each element, hence x[0] for x in rainfall
rainfall_over100mm = [x for x in rainfall if x[1] > 100.0]
print rainfall_over100mm
months_less50mm = [x[0] for x in rainfall if x[1] < 50]
print months_less50mm
#The above with for loops
rain_over100mm = list()
for months in rainfall:
if (months[1] > 100):
rain_over100mm.append(months[0])
print rain_over100mm
| true |
85ebc00234881e48c7cde853facb44fde20c77f4 | alecheil/exercises | /chapter-3/exercise-3-1.py | 1,387 | 4.59375 | 5 | # Programming Exercise 3-1
#
# Program to display the name of a week day from its number.
# This program prompts a user for the number (1 to 7)
# and uses it to choose the name of a weekday
# to display on the screen.
# Variables to hold the day of the week and the name of the day.
# Be sure to initialize the day of the week to an int and the name as a string.
# Get the number for the day of the week.
# be sure to format the input as an int
<<<<<<< HEAD
day_number = input("enter day of the week as a number (1-7): ")
# Determine the value to assign to the day of the week.
# use a set of if ... elif ... etc. statements to test the day of the week value.
if day_number == 1:
print("sunday")
elif day_number == 2:
print("monday")
elif day_number == 3:
print("tuesday")
elif day_number == 4:
print("wednesday")
elif day_number == 5:
print("thursday")
elif day_number == 6:
print("friday")
elif day_number == 7:
print("saturday")
elif day_number > 7:
print("error 420: number too high")
=======
# Determine the value to assign to the day of the week.
# use a set of if ... elif ... etc. statements to test the day of the week value.
>>>>>>> upstream/master
# use the final else to display an error message if the number is out of range.
# display the name of the day on the screen.
| true |
62eeac788d6bb92cb7093c7a560d8a1016ea6e6e | vladislav-karamfilov/Python-Playground | /SoftUni-Python-Programming-Course/Exam-Preparation/most_common_character_in_string.py | 671 | 4.125 | 4 | # Problem description: http://python3.softuni.bg/student/lecture/assignment/56b5f1b37e4f59b649b7e611/
import operator
def get_most_common_character_in_string(string):
if not string or string.isspace():
return 'INVALID INPUT'
char_occurrences = {}
for char in string:
if char in char_occurrences:
char_occurrences[char] += 1
else:
char_occurrences[char] = 1
most_common_char = max(char_occurrences.items(),
key=operator.itemgetter(1))[0]
return most_common_char
def main():
print(get_most_common_character_in_string(input()))
if __name__ == '__main__':
main()
| false |
dafefe8765271ca7bcfd81ac6a4b5852818dae88 | vladislav-karamfilov/Python-Playground | /HackBulgaria-Programming-101-with-Python-Course/week01/First-Steps/number_to_list_of_digits.py | 500 | 4.1875 | 4 | """
Implement a function, called to_digits(n), which takes an integer n and returns a list, containing the digits of n.
"""
def to_digits(n):
if n < 0:
n = -n
elif n == 0:
return [0]
digits = []
while n != 0:
digits.append(n % 10)
n //= 10
digits.reverse()
return digits
def main():
n = int(input('Enter a number to get a list of its digits: '))
digits = to_digits(n)
print(digits)
if __name__ == '__main__':
main()
| true |
ca66044405a497e119b19a137de3372c1eb33c9d | flyingsl0ths/Python-OOP-Examples | /Property Decorators/PartSix.py | 1,829 | 4.1875 | 4 | # Python Object-Oriented Programming: Property Decorators - Getters, Setters, and Deleters
import random
class Employee(object):
# self is the first argument a class always takes
# self refers to the instance of said object
# self is used for accessing fields or methods(functions) within a class
def __init__(self, first_name, last_name):
# The initialiser method/ contructor, __init__ for short
# is the blueprint for what variables/fields every instance
# of said object must be passed to it before it can be created
# this is alot more efficient than doing it manually as noted below
self.first_name = first_name
self.last_name = last_name
@property
# Allows the use of methods as class fields
def email(self):
return "{}{}{}@email.com".format(self.first_name, self.last_name, str(random.randint(0, 100)))
@property
def FullName(self):
# Methods must also take self as the first argument
# in order to know which object to operate on, they
# can be accessed without self as well
return "{} {}".format(self.first_name, self.last_name)
@FullName.setter
# Allows a given method with a property decorator
# to accepted arguments sytanx is as follows
# @method_name.setter
def FullName(self, name):
self.first_name, self.last_name = name.split(' ')
@FullName.deleter
# Allows a given method with a property decorator
# to "delete" class fields via "del" keyword
# @method_name.deleter
def FullName(self):
print("Deleted Name")
self.first_name, self.last_name = None, None
emp_1 = Employee("John", "Smith")
emp_1.FullName = "Jim Smith"
print(emp_1.first_name)
print(emp_1.email)
print(emp_1.FullName)
del emp_1.FullName
print(emp_1.FullName)
| true |
2498c5c5a7089c4551252570ced41bf91ded3701 | msharath90/PythonTutorials | /Multiple_Inheritance_Example.py | 1,353 | 4.21875 | 4 | # Below code demonstrates multiple inheritance and also Global and Local variables
company = 'CTS' # Global Variable
city = 'Hyd'
class A:
def __init__(self):
self.name = 'Sharath'
self.study = 'Python'
def printName(self):
print("Name from Class A: ", self.name)
print("Study from Class A: ", self.study)
print("Company from Class A: ", company)
print("City from Class A: ", city)
class B:
def __init__(self):
self.name = 'Gaurav'
self.study = 'Java'
global company # Always use global keyword to use the global variable
company = 'TR'
def printName(self):
print("Name from Class B: ", self.name)
print("Study from Class B: ", self.study)
print("Company from Class B: ", company)
print("City from Class B: ", city)
class C(A, B):
def __init__(self):
super().__init__()
def printName(self):
newcity = 'Pune'
# Values will come from A: In case of multiple inheritance, values will be used from Left class towards Right
print("Name from Class C: ", self.name)
print("Study from Class C: ", self.study)
print("Company from Class C: ", company)
print("City from Class C: ", newcity)
a = A()
a.printName()
b = B()
b.printName()
c = C()
c.printName()
| false |
c72dae4b4d8695951e6889ec0372b92e71f6d460 | pengshao1942/learning_python | /eleventh_day/module_test.py | 930 | 4.125 | 4 | '''
这是我们编写的第一个模块,该模块包含以下内容
my_book: 字符串变量
say_hi: 简单的函数
User: 代表用户的类
'''
print('这是module 1')
my_book = '疯狂Python讲义'
def say_hi(user):
print('%s,您好,欢迎学习Python' % user)
class User:
def __init__(self, name):
self.name = name
def walk(self):
print('%s正在慢慢地走路' % self.name)
def __repr__(self):
return 'User[name=%s]' % self.name
#以下部分是该模块中成员的测试代码
def test_my_book():
print(my_book)
def test_say_hi():
say_hi('孙悟空')
say_hi(User('Charlie'))
def test_User():
u = User('白骨精')
u.walk()
print(u)
#防止调用该模块时执行模块内的测试代码;即只允许 python module1.py 该模块自己才能执行模块内的测试代码
if __name__ == '__main__':
test_my_book()
test_say_hi()
test_User()
| false |
2d3471b62e18b4c572d44ddcf59f0f0ad4018b27 | liming870906/PythonOOP | /oop_test_demo/D001_OOP.py | 890 | 4.34375 | 4 | """
类型及相关内容
注意: 函数中的self代表成名的对象实体。
"""
class Bar :
def __init__(self):
"""
构造方法
"""
print(self)
def __init__(self,name, age, gender):
"""
带参数构造方法
:param name:
:param age:
:param gender:
"""
self.name = name
self.age = age
self.gender = gender
def foo(self, content):
"""
输出方法
:param name:
:param age:
:param gender:
:param content:
:return:
"""
print(self.name,self.age,self.gender,content)
# bar = Bar()
# bar.name = 'james'
# bar.foo('JamesLM',18,'man','hello world')
# bar2 = Bar()
# bar2.foo('JamesLM-11111',18,'man','hello world')
bar3 = Bar('LM',12,'nv')
bar3.foo('test')
# bar4 = Bar()
# bar4.foo('test') | false |
6cce75ecdad0efc8af93748e312a579064bda760 | angelguevara24/cyberbootcamp | /Lectures/Week 10 - Python 2/Day 2/Activities/09-Ins_OSWalk/OSWalk.py | 1,259 | 4.25 | 4 | # import the os library to use later
import os
folder_path = os.path.join("Resources", "DiaryEntries")
# The os.walk() function is used to navigate through a collection of folders/files
# This function returns three values for each step it takes: root, dirs, and files
for root, dirs, files in os.walk(folder_path):
# The root is the folder that is currently being searched through
print("Currently inside of... " + root)
# The dirs list stores all of the names of the folders inside the current root
print("The folders in here are..." + str(dirs))
# The files list stores all of the names of the files inside the current root
print("The files in here are..." + str(files))
print("~~~~~~~~~~")
print("--------------")
# In order to construct the file path to use dynamically...
for root, dirs, files in os.walk("Resources"):
# Loop through all of the files in the current root
for file_name in files:
# Create a path by combining (joining) the root and the file name
current_file_path = os.path.join(root, file_name)
print(current_file_path)
# We can then check that the file exists through using os.path.isfile()
print("EXISTS: " + str(os.path.isfile(current_file_path)))
| true |
aa64619e392f839e9b7a13990d4c8dbec83486a6 | angelguevara24/cyberbootcamp | /Lectures/Week 9 - Python 1/Day 2/Activities/02-Ins_SimpleConditionals/SimpleConditionals.py | 682 | 4.1875 | 4 | x = 1
y = 10
# == evaluates to True if the two values are equal
if (x == 1):
print("x is equal to 1")
# != evaluates to True if the two values are NOT equal to each other
if (y != 1):
print("y is not equal to 1")
# Checks if one value is less than another
if (x < y):
print("x is less than y")
# Checks that one value is greater than another
if (y > x):
print("y is greater than x")
# Checks that a value is less than or equal to another
if (x >= 1):
print("x is greater than or equal to 1")
# If - Else statement
# The else block of code will only ever run when the if statement is False
if (x > 5):
print("x is large")
else:
print("x is small")
| true |
5bc1ec7112c5155cf7e578f386ad8e79a6589c78 | angelguevara24/cyberbootcamp | /Lectures/Week 9 - Python 1/Day 3/Activities/01-Stu_InventoryCollector/Solved/inventory_collector.py | 1,253 | 4.4375 | 4 | # Create an empty dictionary, called inventory
inventory = {}
# Ask the user how many items they have in their inventory
# Convert to integer since input's value is a string
item_count = int(input("How many items do you have in your inventory? "))
# Use `range` and `for` to loop over each number up to the inventory number
for x in range(item_count):
# Prompt the user for the name of an item in their inventory ("What's the item? ")
item_name = input("What's the item? ")
# Prompt the user for the price of that item ("How much does it cost? ")
item_price = input("What's its price? ")
# Put the item into the dictionary as the key, and associate it with its price
inventory[item_name] = float(item_price)
# Creating separation between each new item prompt
print("--------")
# Use `items` to loop through the dictionary and print the info to the screen
for item, price in inventory.items():
print("The price of " + item + " is $" + str(price))
# Check if the price of the item is less than five
if (price < 5):
# If the price is less than five, print out "This item is on sale!"
print("This item is on sale!")
# Creating separation between each item
print("--------")
| true |
03c63c2749e52cd1524c7e86b1d0e52e59fa9620 | angelguevara24/cyberbootcamp | /Lectures/Week 9 - Python 1/Day 2/Activities/12-Par_KidInCandyStore/Solved/KidInCandyStore.py | 942 | 4.4375 | 4 | # The list of candies to print to the screen
candyList = ["Snickers", "Kit Kat", "Sour Patch Kids", "Juicy Fruit",
"Swedish Fish", "Skittles", "Hershey Bar", "Skittles", "Starbursts", "M&Ms"]
# The amount of candy the user will be allowed to choose
allowance = 5
# Create an empty list to store all the candies selected
candyCart = []
# Print all the candies to the screen and their index in brackets
for candy in candyList:
print("[" + str(candyList.index(candy)) + "] " + candy)
# Run through a loop which allows the user to choose which candies to take home with them
for x in range(allowance):
selected = input("Which candy would you like to bring home? ")
# Add the candy at the index chosen to the candyCart list
candyCart.append(candyList[int(selected)])
# Loop through the candyCart to print what candies were brought home
print("I brought home with me...")
for candy in candyCart:
print(candy)
| true |
0cf367f6d24d5a540f13fd1e9981de2d53922395 | 315181690/THC | /OK/Python/Figuras geométricas.py | 1,605 | 4.3125 | 4 | #!/usr/bin/python3.7
#
#David Alonso Garduño Granados
#Python(3.7.4)
# Figuras geométricas
#01/12/19
#01/12/19
#Las coordenadas de un triangulo de lado 2 sabiendo que uno de sus vertices en el origen y su lados està sobre el eje de las x, y su lado es 2.
from math import sqrt
A=0
B=2
t = sqrt(-((B/2)**2)+(B**2))
C=1
print("""triángulo eq de lado
2 con un vértice en el
origen en el cuadrante I
y un lado sobre el eje
de las x.
Las coordenadas del triángulo son:
A=(%g,%g)
B=(%g,%g)
C=(%g,%g)"""%(A,A,B,A,C,t))
# Las coordenadas de un cuadrado de lado 2 sabiendo que uno de sus vertices en el origen y su lados està sobre el eje de las x.
ax=A
ay=A
bx=B
by=A
cx=ax+by
cy=bx+ay
dy=B
dx=B
print("""Cuadrado de lado
2 con un vértice en el
origen en el cuadrante I
y un lado sobre el eje
de las x.
Las coordenadas del cuadrado son
A=(%g,%g)
B=(%g,%g)
C=(%g,%g)
D=(%g,%g)"""%(ax,ay,bx,ax,cx,cy,dx,dy))
# las coordenadas de un rectángulo de lado 2 sabiendo que uno de sus vertices en el origen y su lado está sobre el eje de las x, y su lado es 2.
bx=6
dx=6
print("""Rectángulo de lado
2 con un vértice en el
origen en el cuadrante I
y un lado sobre el eje
de las x.
A=(%g,%g)
B=(%g,%g)
C=(%g,%g)
D(%g,%g)"""%(ax,ay,bx,by,cx,cy,dx,dy))
# las coordenadas de un paralelogramo de base 2, con uno de sus vertices en el origen y su base en eje de las x.
ax=A
ay=A
bx=B
by=A
cx=B
cy=B
dx=bx+bx
dy=cy
print("""Paralelogramo de lado
2 con un vértice en el
origen en el cuadrante I
y un lado sobre el eje
de las x.
Las coordenadas del paralelogramo son:
A=(%g,%g)
B=(%g,%g)
C=(%g,%g)
D=(%g,%g)"""%(ax,ay,bx,by,cx,cy,dx,dy))
| false |
7f87dc499314066fc895ddf05c566e24b4ae8783 | 315181690/THC | /Python/Conteo.py | 257 | 4.1875 | 4 | #!/usr/bin/python3.7
#
#David Alonso Garduño Granados
#Python(3.7.4)
#01/12/19
#01/12/19
#Cuenta el numero de veces que se repite un elemento en una lista
l1=("M","E")
for l in l1:
print("El número de veces que se repite el elemento")
print(l)
print("es")
print(l1.count(l))
| false |
92373b3b8cbf9ee201a114348d5fd8a8062aecdb | 315181690/THC | /OK/Python/HackerRank/Practice/sWAP_cASE.py | 367 | 4.1875 | 4 | #!/usr/bin/python3.7
#
#David Alonso Garduño Granados
#Python(3.7.4)
#01/12/19
#01/12/19
def swap_case(s):
a = list(s)
b = []
for i in a:
if i.islower():
b.append(i.upper())
else:
b.append(i.lower())
return("".join(b))
print(swap_case(input()))
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
| false |
0ff40b513f0791cdfd009addbd8961b550f57115 | intheltif/TechTalentSouth | /data_science/python/module_2/assignments/q4.py | 657 | 4.46875 | 4 | """
Exercise 4 of Module 2.
Slices a provided list into three equal chunks and reverses each list.
Author: Evert Ball
Date: July 7th, 2020
"""
import math
def main():
"""
The main entry point into the program.
"""
sampleList = [11, 45, 8, 23, 14, 12, 78, 45, 89]
newList = splitList(sampleList, 3)
for lst in newList:
# The below statement reverses a list
print(lst[::-1])
def splitList(lst, n):
"""
Using float arithmetic, splits a list into n equal parts.
"""
div = len(lst) / float(n)
return [lst[round(div * i):round(div * (i + 1))] for i in range(n)]
if __name__ == "__main__":
main()
| true |
911e42419a5b6ea30c851acdb87ac6621db2bbbd | intheltif/TechTalentSouth | /data_science/python/module_6/group_exercise_2.py | 1,048 | 4.25 | 4 | """
Group Exercise 2 from the Jupyter Notebooks for GS Jackson's TTS Data Science
course.
Finds all files in the given directory from command line argument and prints
them to the screen in a sorted order.
Author: Evert Ball
Date: 20 July 2020
"""
import sys
import os
def main():
" The main entry point into the program. "
dirName = sys.argv[1]
listOfFiles = getListOfFiles(dirName)
for f in sorted(listOfFiles):
print(f)
def getListOfFiles(dirName):
# create a list of file and sub directories
# names in the given directory
listOfFile = os.listdir(dirName)
allFiles = list()
# Iterate over all the entries
for entry in listOfFile:
# Create full path
fullPath = os.path.join(dirName, entry)
# If entry is a directory then get the list of files in this directory
if os.path.isdir(fullPath):
allFiles = allFiles + getListOfFiles(fullPath)
else:
allFiles.append(fullPath)
return allFiles
if __name__ == "__main__":
main()
| true |
70ed26405395b580f7b8c0d14bc280dd293a9816 | limjiayi/Project_Euler | /euler_problem001.py | 303 | 4.21875 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
total = 0
num = 0
while num < 1000:
if num % 3 == 0 or num % 5 == 0:
total += num
num += 1
print(total) | true |
2000b6df1aed2237596fb07e992f1d2e9bd31334 | rjshk013/pythonlearning | /fib2.py | 568 | 4.15625 | 4 | # Enter number of terms needed #0,1,1,2,3,5....
n=int(input("Enter the terms? "))
first=0 #first element series
second=1 #second elementseries
if n<=0:
print("Please enter positive integet greater than 0")
elif n == 1:
print("Fibonacci sequence upto",first,":")
print(first)
else:
print(first,second,end=" ")
for x in range(2,n):
next=first+second
print(next,end=" ")
first=second
second=next
| true |
0e7ff76af5d671e2e40285af3291416685c9b0a1 | jmchema/CursoPython | /Dia2/Ejercicio8.py | 748 | 4.125 | 4 | #! /usr/bin/env python
""" Para cada una de las cadenas de texto almacenadas en una lista, imprimir por
pantalla el indice y la cadena en si e indicar si la palabra es demasiado
corta (cinco o menos caracteres) o larga (mas de cinco caracteres) """
frase = """ Programmers are, in their hearts, architects, and the first thing
they want to do when they get to a site is to bulldoze the place
flat and build something grand """
listado = frase.split() # listado = ["Programmers", "are", ",",...]
for i,palabra in enumerate(listado):
print("La palabra {} esta en la posicion {}".format(i,palabra))
if (len(palabra)<=5):
print("Es corta")
else:
print("Es larga")
print("-----")
| false |
e69a498a216a0388533c4552652ee76aac3c80db | JustineTang10/python-class | /1-10-2021.py | 1,386 | 4.125 | 4 | def secret_number():
import random
goalnumber = random.randint(1, 50)
numberoftries = 0
while True:
chosennumber = int(input("What number (from 1-50) would you like to choose? "))
if chosennumber > 50 or chosennumber < 1:
print("Invalid option, try again")
elif chosennumber == goalnumber:
print("That's the number, you win!")
numberoftries += 1
break
elif chosennumber < goalnumber:
print("That number is too low")
numberoftries += 1
else:
print("That number is too high")
numberoftries += 1
tryword = "try" if numberoftries == 1 else "tries"
print("\nIt took you",numberoftries,tryword,"to guess the number")
# Version WITH recursion
import random
def secret_number2(goal, tries):
chosennumber = int(input("What number (from 1-50) would you like to choose? "))
won = False
if chosennumber > 50 or chosennumber < 1:
print("Invalid option, try again")
elif chosennumber == goal:
print("That's the number, you win!")
tries += 1
won = True
elif chosennumber < goal:
print("That number is too low")
tries += 1
else:
print("That number is too high")
tries += 1
if won:
tryword = "try" if tries == 1 else "tries"
print("\nIt took you",tries,tryword,"to guess the number")
else:
secret_number2(goal, tries)
secret_number2(random.randint(1, 50), 0)
| true |
c9ffabfb4745082b275f3b7e49ca5cc1aabdd80f | brunobord/wthr | /wthr.py | 2,607 | 4.3125 | 4 | #!/usr/bin/env python
"""wthr is a Python script for checking the weather from the command line.
"""
from urllib2 import urlopen
import json
from xml.etree.ElementTree import XML as parse_xml
from sys import argv
class Wthr:
"""Main Wthr class. Computes location and sends weather information to the
user.
"""
def _get_ip(self):
"Fetch the user IP Address"
return urlopen('http://icanhazip.com').read()[:-1]
def _get_woeid(self, place):
"Get Weather information"
yql_query = 'select * from geo.places where text%3D%22' + place + '%22'
yql_query = yql_query.replace(' ', '%20')
url = 'http://query.yahooapis.com/v1/public/yql?q=%s&format=json' \
% yql_query
response = json.loads(urlopen(url).read())
woeid = response['query']['results']['place'][0]['woeid']
return woeid
def _get_location(self):
"Get location from IP"
ip_addr = self._get_ip()
loc = urlopen('http://api.hostip.info/get_html.php?ip=%s' % ip_addr).read()
location = loc[loc.find('City: ') + 6: loc.find('IP: ') - 1]
if location == '(Unknown City?)':
print 'Could not automatically find your location. Please enter a location instead.'
return None
return location
def get_weather(self, place, unit):
"""Get Weather information.
Use the argument 'place' to say which city you want to know about. if
the place argument is "here", it'll fetch your place from your IP.
"""
if place == 'here':
place = self._get_location()
woeid = self._get_woeid(place)
url = 'http://weather.yahooapis.com/forecastrss?w=%s&u=%s' % (woeid, unit)
response = parse_xml(urlopen(url).read())
title = response.find('channel/description').text[7:] + \
' on ' + response.find('channel/item/pubDate').text + ':\n'
raw = response.find('channel/item/description').text
start = 'Forecast:</b><BR />'
end = '<a href'
weather = raw[raw.find(start) + len(start): raw.find(end) - 1].replace('<br />', '')[:-1]
return title + weather
def main():
"Main program"
if len(argv) > 1:
place = argv[1]
unit = argv[2] if len(argv) > 2 and argv[2] in 'cf' else 'c'
else:
place = None
if place:
print Wthr().get_weather(place, unit)
else:
print 'Please specify a location'
if __name__ == '__main__':
main()
| true |
9faeac4e3000acc4c12feb209d9b842d38e719be | Brupez/Text-Adventure-Game | /textAdventure.py | 1,093 | 4.15625 | 4 | while True:
answer = input("Would you like to play? (yes/no) ")
#take answer and show it with lowercase letters and strip the text behind (yes or no)
if answer.lower().strip() == "yes":
answer = input("\nYou see a person asking for help, it seems he is injured, would you like to help him?\n").lower().strip()
if answer == "yes":
answer = input("\nIt seems that a snake bite his leg! Will you give him 'medicine' or 'carry him'?\n")
if answer == "medicine":
print("\nCongratulations! you saved him")
elif answer == "carry him":
print("\nThe snake appears and poison you too, you died. Shame...")
else:
print("\nInvalid choice, you lost!")
elif answer == "no":
print("\nThe guy needing help saw you ignore him so he draws a pistol and shoot you where you stand, GAME OVER you horrible person!")
else:
print("\nInvalid choice, you lost!")
else:
print("\nThat's to bad!")
break | true |
029fcde7064f511ca7e828feb67ce4dccde1d1ea | Sabertoothtech/Text-Preprocessing-Cleaning-Data | /stopwordsremoval.py | 592 | 4.15625 | 4 | from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
#learn more about corpus library
text = "This an example of tokenize and stop words stop words are those words which has no role in analysing sentiment of text"
stop_words = set(stopwords.words("english"))
#print stop_words
text_token = word_tokenize(text)
#filter tokenized sentence
filtered_text = []
'''for text in text_token:
if text not in stop_words:
filtered_text.append(text)
print ("filtering done!") '''
filtered_text = [w for w in text_token if w not in stop_words]
print (filtered_text)
| false |
c8fefc38670bd237ea1eeeecc5469087add08b9e | deepashreeKedia/Solutions | /secret_number | 698 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 14 15:50:57 2018
@author: deep
"""
# Paste your code into this box
print("Please think of a number between 0 and 100!")
low = 0
high = 100
while True:
guess = (low + high) // 2
print("Is your secret number {}?".format(guess))
ans = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
if ans == 'l':
low = guess
elif ans == 'h':
high = guess
elif ans == 'c':
print("secret number is", guess)
break
else:
print("Sorry, I did not understand your input.")
| true |
8be3499871065c922a316b067795ab9317e423f4 | Carra1g/Cooking_time_calculator | /cooking_times.py | 2,082 | 4.125 | 4 | #Cooking times
#user the app again
def again():
again_input = str(input("Do you need to run the app again: y/n: "))
for choice_input in again_input:
#convers input to lower for error handling.
if choice_input.lower() == "y":
time_helper()
else:
choice_input.lower() == "n"
print("Good Bye!")
break
def time_helper():
meat_option = ""
print("What are you cooking:\n1 = Beef.\n2 = Chicken.\n3 = Lamb.\n4 = Pork.")
#take user input.
user_input = int(input("\nPick an option: "))
if user_input == 1:
meat_option = "Beef"
weight = float(input("\nHow much does it weight?: "))
print(f"\nYour {meat_option} weighs {weight}kg's")
cook_time = (weight * 50) + 20# calculate cooking time
print (f"\n\tCooking time of {meat_option}(Well Done) weighing {weight}kg is {cook_time} minutes.\n")
again()
elif user_input == 2:
meat_option = "Chicken"
weight = float(input("\nHow much does it weight?: "))
print(f"\nYour {meat_option} weighs {weight}kg's")
cook_time = (weight * 45) + 20# calculate cooking time
print (f"\n\tCooking time of {meat_option} weighing {weight}kg is {cook_time} minutes.\n")
again()
elif user_input == 3:
meat_option = "Lamb"
weight = float(input("\nHow much does it weight?: "))
print(f"\nYour {meat_option} weighs {weight}kg's")
cook_time = (weight * 60) + 30# calculate cooking time
print (f"\n\tCooking time of {meat_option} weighing {weight}kg is {cook_time} minutes.\n")
again()
else:
meat_option = "Pork"
weight = float(input("\nHow much does it weight?: "))
print(f"\nYour {meat_option} weighs {weight}kg's")
cook_time = (weight * 70) + 35# calculate cooking time
print (f"\n\tCooking time of {meat_option} weighing {weight}kg is {cook_time} minutes.\n")
again()
time_helper()
| true |
b587c5942dda335394d1acc387bac76dc721320e | ArnoldNawezi/StringSolution | /String.py | 484 | 4.59375 | 5 | string = input(str("Enter a string here: ")) # Getting a string from the user
def reverse(string): # defining a function
str = "" #
for i in string: # Using the loop to define every sing element of the string
str = i + str # Calling the function to iterate every element and join them
return str
print ("Your reversed string here: ",reverse(string))
| true |
552e861537aaa5ed2bb56d1402297b492d0841c0 | Dorkond/stepik-python-course | /Module 1/1.8.4.py | 717 | 4.1875 | 4 | # Задание 2
# Коля каждый день ложится спать ровно в полночь и недавно узнал, что оптимальное время для его сна составляет X минут.
# Коля хочет поставить себе будильник так, чтобы он прозвенел ровно через X минут после полуночи,
# однако для этого необходимо указать время сигнала в формате часы, минуты.
# Помогите Коле определить, на какое время завести будильник.
x = int(input())
print(x // 60)
print(x % 60)
| false |
08af95d816eb624e86b95f51010b3b0f69fda79a | Dorkond/stepik-python-course | /Module 2/2.5.7.py | 616 | 4.25 | 4 | '''
Иногда в программе есть необходимость сохранить таблицу или матрицу.
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Двумерный список можно представить в виде матрицы (в нашем случае это 3x3)
a[1] = [4, 5, 6]
a[1][1] = 5
Генерация двумерных списков
n = 3
a = [[0] * n] * n
a = [0][0] = 5
А также
a = [[0] * n for i in range(n)]
a = [[0 for j in range(n)] for i in range(n)]
'''
n = 3
a = [[int(input()) for i in range(n)] for j in range(n)]
print(*a)
| false |
5684c18f370433b701c75ef92ae3c8da93e5168a | 0yykk/PythonSpider | /1-4Example_output.py | 375 | 4.25 | 4 | #小实例:输出乘法口诀
#end="" 代表不换行
#顺向输出
print("顺向输出")
for i in range(0,10):
for j in range(1,i+1):
print(str(i)+"*"+str(j)+"="+str(i*j),end=" ")
print()
#逆向输出
print(" ")
print("逆向输出")
for i in range(9,0,-1):
for j in range(i,0,-1):
print(str(i)+"*"+str(j)+"="+str(i*j),end=" ")
print()
| false |
8b6aea319e2abacd4831472da3733f4aa70f6e75 | olashayor/class_code | /operator2.py | 750 | 4.21875 | 4 | x = {1,2,3,4,5}
y = {6,7,2,8,9}
z = x and y
print("z = ", z)
name = "J"
if len(name) < 3:
print("\nname must not be less than 3 letters")
elif len(name) > 15:
print("\nname must be maximum of 15 letter")
else:
print("\nname is good to go")
name = "Jacob olatunde felix"
if len(name) < 3:
print("\nname must not be less than 3 letters")
elif len(name) > 15:
print("\nname must be maximum of 15 letter")
else:
print("\nname is good to go")
name = "olatunde sayo"
if len(name) < 3:
print("\nname must not be less than 3 letters")
elif len(name) > 15:
print("\nname must be maximum of 15 letter")
else:
print("\nname is good to go")
weight: 45
temperature = 35
if temperature == 30:
print("go")
else:
print("don't go ") | true |
a4d4f7ca5a3b2b6503d4461ebd89cc4bd8a0f3fa | MunafHajir/Learning | /close-to-perfection.py | 1,387 | 4.15625 | 4 | """
Geek likes this girl Garima from his neighborhood, and wants to impress her so that she may go on a date with him. Garima is a Perfectionist and likes only PERFECT things .This makes Geek really nervous, and so Geek asks for your Help.!
Geek has baked a cake for Garima, which is basically an array of Numbers. Garima will take only a Perfect Piece of the cake.
A Perfect Piece is defined as - a subarray such that the difference between the minimum and the maximum value in that range is at most 1. Now, Since garima just loves cake, She wants a Perfect Piece Of Maximum length possible. Help Geek go on a date.!
Input
The first line of the input contains an integer T denoting the number of test cases.
The first line of each test case contains an integer n-denoting the length of the array.
The second line contains n space separated integers -denoting the cake
Output
For each testcase, output a single line containing the maximum Possible length of the subarray which is a Perfect piece
"""
"""
Example:
Input:
4
8 8 8 8
5
1 2 3 3 2
11
5 4 5 5 6 7 8 8 8 7 6
Output:
4
4
5
"""
import numpy as np
a = [5,4,5,5,6,7,8,8,8,7,6]
max_diff = 1
sub_arrays = [x for x in [a[i:j] for i in range(len(a)) for j in range(i+1, len(a))] if (max(x)-min(x) <= max_diff)]
max_sub_array = sub_arrays[np.argmax([len(sa) for sa in sub_arrays])]
print(max_sub_array)
print(len(max_sub_array))
| true |
b96096c122cf1f88b194efc99741e21fe5833356 | Sen2k9/Algorithm-and-Problem-Solving | /leetcode_problems/401_Binary_Watch.py | 2,099 | 4.125 | 4 | """
A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).
Each LED represents a zero or one, with the least significant bit on the right.
For example, the above binary watch reads "3:25".
Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.
Example:
Input: n = 1
Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
Note:
The order of output does not matter.
The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00".
The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02".
"""
class Solution:
def readBinaryWatch(self, num: int):
# result = []
# if num > 10 or num < 1:
# return result
# for i in range(12):
# for j in range(60):
# if bin(i).count("1") + bin(j).count("1") == num:
# h = str(i)
# if j < 10:
# m = "0" + str(j)
# else:
# m = str(j)
# result.append(h + ":" + m)
# return result
# Solution 2: backtracking
import itertools
def dfs(num, hours, result):
if hours > num:
return
for hour in itertools.combinations([1, 2, 4, 8], hours):
h = sum(hour)
if h >= 12:
continue
for minute in itertools.combinations([1, 2, 4, 8, 16, 32], num - hours):
m = sum(minute)
if m >= 60:
continue
result.append("%d:%02d" % (h, m))
dfs(num, hours + 1, result)
result = []
dfs(num, 0, result)
return result
sol = Solution()
num = 3
print(sol.readBinaryWatch(num))
| true |
9e792bf0c28eaaa1619282d8885c51fa4bea960a | Sen2k9/Algorithm-and-Problem-Solving | /CTCI/2.8_Loop_Detection.py | 887 | 4.15625 | 4 | """
Given a circular linked list, implement an algorithm that returns the node at the beginning of the loop.
DEFINITION
Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so as to make a loop in the linked list.
"""
from collections import defaultdict
class Node:
def __init__(self, val):
self.val = val
class Solution:
def loop(self, head):
# node_dic = defaultdict(int)
# while head:
# if id(head) in node_dic:
# return node_dic[id(head)]
# node_dic[id(head)] = head
# two pointer
slow = head
fast = head
while slow and fast:
slow = slow.next
fast = fast.next.next
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return fast
| true |
63f28e4fb1802ab7ef5554827a8acc07bb3d7f60 | Sen2k9/Algorithm-and-Problem-Solving | /leetcode_problems/1189_Maximum_Number_of_Balloons.py | 2,349 | 4.125 | 4 | """
Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.
You can use each character in text at most once. Return the maximum number of instances that can be formed.
Example 1:
Input: text = "nlaebolko"
Output: 1
Example 2:
Input: text = "loonbalxballpoon"
Output: 2
Example 3:
Input: text = "leetcode"
Output: 0
Constraints:
1 <= text.length <= 10^4
text consists of lower case English letters only.
"""
class Solution:
def maxNumberOfBalloons(self, text: str):
# Solution 1: self, using dictionary, horribly slow
# if len(text) < 7:
# return 0
# # "balloon"
# dic = {}
# dic["b"] = 0
# dic["a"] = 0
# dic["l"] = 0
# dic["o"] = 0
# dic["n"] = 0
# count = 0
# for each in text:
# dic[each] = dic.get(each, 0) + 1
# if dic["b"] >= 1 and dic["a"] >= 1 and dic["l"] >= 2 and dic["o"] >= 2 and dic["n"] >= 1:
# count += 1
# dic["b"] -= 1
# dic["a"] -= 1
# dic["l"] -= 2
# dic["o"] -= 2
# dic["n"] -= 1
# # print(dic)
# return count
# Solution 2: using counter intelligently, faster
# from collections import Counter
# dic = Counter(text) # O(n)
# l = list("balloon")
# output = 0
# while True:
# if not l:
# output += 1
# l = list("balloon")
# key = l.pop()
# if dic.get(key, 0) == 0:
# break
# else:
# dic[key] -= 1
# return output
# Solution 3: fastest and optimize
from collections import Counter
counts = Counter(text)
return min(
counts['b'],
counts['a'],
counts['l'] // 2,
counts['o'] // 2,
counts['n']
)
sol = Solution()
text = "krhizmmgmcrecekgyljqkldocicziihtgpqwbticmvuyznragqoyrukzopfmjhjjxemsxmrsxuqmnkrzhgvtgdgtykhcglurvppvcwhrhrjoislonvvglhdciilduvuiebmffaagxerjeewmtcwmhmtwlxtvlbocczlrppmpjbpnifqtlninyzjtmazxdbzwxthpvrfulvrspycqcghuopjirzoeuqhetnbrcdakilzmklxwudxxhwilasbjjhhfgghogqoofsufysmcqeilaivtmfziumjloewbkjvaahsaaggteppqyuoylgpbdwqubaalfwcqrjeycjbbpifjbpigjdnnswocusuprydgrtxuaojeriigwumlovafxnpibjopjfqzrwemoinmptxddgcszmfprdrichjeqcvikynzigleaajcysusqasqadjemgnyvmzmbcfrttrzonwafrnedglhpudovigwvpimttiketopkvqw"
print(sol.maxNumberOfBalloons(text))
"""
corner case:
1. text length at least 7
tips:
break out of a condition is faster than waiting to meet a condition ( see above two example)
reference:
https://leetcode.com/problems/maximum-number-of-balloons/discuss/383163/PythonPython3-Two-lines-using-a-Counter
"""
| true |
a2ce90d03831f7e1c7d77d76f0a1799ae16b595d | Sen2k9/Algorithm-and-Problem-Solving | /leetcode_problems/763_Partition_Labels.py | 1,343 | 4.15625 | 4 | """
A string S of lowercase English letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
Example 1:
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
Note:
S will have length in range [1, 500].
S will consist of lowercase English letters ('a' to 'z') only.
"""
from collections import defaultdict
class Solution:
def partitionLabels(self, S: str):
char_dic = defaultdict(int)
for i, char in enumerate(S):
char_dic[char] = i # last occurance of char in the string
ans = []
# print(char_dic)
i = 0
offset = 0
for j, char in enumerate(S):
i = max(i, char_dic[char])
if i == j:
#print(offset, j)
ans.append(j - offset + 1)
offset = j + 1
#print(offset)
return ans
sol = Solution()
S = "ababcbacadefegdehijhklij"
print(sol.partitionLabels(S))
| true |
b4058074b0317f3bb63ff86e68cf469afc8c2ca9 | Sen2k9/Algorithm-and-Problem-Solving | /leetcode_problems/374_Guess_Number_Higher_or_Lower.py | 1,144 | 4.40625 | 4 | """
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I'll tell you whether the number is higher or lower.
You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
-1 : My number is lower
1 : My number is higher
0 : Congrats! You got it!
Example :
Input: n = 10, pick = 6
Output: 6
"""
# The guess API is already defined for you.
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num: int) -> int:
class Solution:
def guessNumber(self, n: int):
if n < 2:
return n
i = 1
j = n
while i <= j:
mid = (i+j)//2
if guess(mid) ==-1:
j = mid-1
elif guess(mid) == 1:
i = mid+1
elif guess(mid) == 0:
return mid
print(mid)
def guess(n, pick=1):
if pick < n :
return - 1
elif pick > n:
return 1
else:
return 0
sol = Solution()
n = 2
pick = 1
print(sol.guessNumber(n))
| true |
166f024552faabbc9506483ed80316ea7d3858d0 | Sen2k9/Algorithm-and-Problem-Solving | /leetcode_problems/371_Sum_of_Two_Integers.py | 839 | 4.125 | 4 | """
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = -2, b = 3
Output: 1
"""
class Solution:
def getSum(self, a: int, b: int):
while b:
#print(bin(a), bin(b))
tmp = a ^ b
print(bin(tmp))
b = (a & b) << 1
print(bin(b))
a = tmp & 0xffffffff
print(bin(a))
print(a >> 31)
print(bin(a ^ 0xffffffff))
return a if a >> 31 == 0 else ~(a ^ 0xffffffff)
sol = Solution()
a = -2
b = 3
print(sol.getSum(a, b))
"""
reference:
https://sciencing.com/convert-negative-numbers-binary-5124016.html
https://leetcode.com/problems/sum-of-two-integers/discuss/293945/one-python-solution-with-bit-manipulation
"""
| true |
8cf78e66be8fe091c0e2aaa46cfa1bf69a6c8efe | Sen2k9/Algorithm-and-Problem-Solving | /leetcode_problems/55_Jump_Game.py | 2,059 | 4.1875 | 4 | """
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Example 1:
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
Constraints:
1 <= nums.length <= 3 * 10^4
0 <= nums[i][j] <= 10^5
"""
class Solution:
def canJump(self, nums) -> bool:
#brute-force approch with memorization
# time complexity O(n^2)
# space complexity O(n)
# self.memo = [0] * len(nums)
# self.memo[len(nums)-1] = 1
# return self.canJumpfrom(0, nums)
# def canJumpfrom(self, position, nums):
# if self.memo[position] != 0:
# if self.memo[position] == -1:
# return False
# else:
# return True
# #print(self.memo)
# furthest_move = min(position + nums[position], len(nums) - 1)
# #print(position, furthest_move)
# for nextPosition in range(position + 1, furthest_move + 1):
# if self.canJumpfrom(nextPosition, nums):
# self.memo[position] = 1
# return True
# self.memo[position] = -1
# return False
# optimal solution
# Time complexity : O(n)
# Space complexity: O(1)
last_jump = len(nums) - 1
for position in range(len(nums) - 2, -1, -1):
if position + nums[position] >= last_jump:
last_jump = position
return last_jump == 0
sol = Solution()
nums = [3,2,1,0,4]
print(sol.canJump(nums))
nums = [2,3,1,1,4]
print(sol.canJump(nums))
nums = [2]
print(sol.canJump(nums))
nums = [0, 0]
print(sol.canJump(nums)) | true |
2af13aae0daec47f7f828a0a16ddf57a590adf22 | Sen2k9/Algorithm-and-Problem-Solving | /leetcode_problems/205_Isomorphic_Strings.py | 1,479 | 4.125 | 4 | """
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
Example 1:
Input: s = "egg", t = "add"
Output: true
Example 2:
Input: s = "foo", t = "bar"
Output: false
Example 3:
Input: s = "paper", t = "title"
Output: true
Note:
You may assume both s and t have the same length.
"""
class Solution:
def isIsomorphic(self, s: str, t: str):
# Solution 1: self, inefficient
# from collections import Counter
# dic_s = {}
# dic_t = {}
# for i in range(len(s)):
# if s[i] in dic_s:
# dic_s[s[i]].append(i)
# else:
# dic_s[s[i]] = [i]
# for i in range(len(t)):
# if t[i] in dic_t:
# dic_t[t[i]].append(i)
# else:
# dic_t[t[i]] = [i]
# for i in range(len(s)):
# #print(dic_s[s[i]], dic_t[t[i]])
# if dic_s[s[i]] != dic_t[t[i]]:
# return False
# return True
# Solution 2: very efficient and clever
z = zip(s, t)
# print(set(z))
return len(set(z)) == len(set(s)) == len(set(t))
sol = Solution()
s = "foo"
t = "bar"
print(sol.isIsomorphic(s, t))
| true |
5ca5ce3bb5456537334320122fd2f7af94237724 | Sen2k9/Algorithm-and-Problem-Solving | /leetcode_problems/893_Groups_of_Special_Equivalent_Strings.py | 2,040 | 4.15625 | 4 | """
You are given an array A of strings.
A move onto S consists of swapping any two even indexed characters of S, or any two odd indexed characters of S.
Two strings S and T are special-equivalent if after any number of moves onto S, S == T.
For example, S = "zzxy" and T = "xyzz" are special-equivalent because we may make the moves "zzxy" -> "xzzy" -> "xyzz" that swap S[0] and S[2], then S[1] and S[3].
Now, a group of special-equivalent strings from A is a non-empty subset of A such that:
Every pair of strings in the group are special equivalent, and;
The group is the largest size possible (ie., there isn't a string S not in the group such that S is special equivalent to every string in the group)
Return the number of groups of special-equivalent strings from A.
Example 1:
Input: ["abcd","cdab","cbad","xyzz","zzxy","zzyx"]
Output: 3
Explanation:
One group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings are all pairwise special equivalent to these.
The other two groups are ["xyzz", "zzxy"] and ["zzyx"]. Note that in particular, "zzxy" is not special equivalent to "zzyx".
Example 2:
Input: ["abc","acb","bac","bca","cab","cba"]
Output: 3
Note:
1 <= A.length <= 1000
1 <= A[i].length <= 20
All A[i] have the same length.
All A[i] consist of only lowercase letters.
"""
class Solution:
def numSpecialEquivGroups(self, A):
result = set()
for S in A:
#print(S[::2], S[1::2])
temp = "".join(sorted(S[::2])) + "".join(sorted(S[1::2]))
result.add(temp)
# print(result)
return len(result)
sol = Solution()
A = ["abc", "acb", "bac", "bca", "cab", "cba"]
print(sol.numSpecialEquivGroups(A))
"""
concept:
as all the strings are consist of lowercase letters, each group has their unique signature. So using set store the signature
corner case:
Reference:
https://leetcode.com/problems/groups-of-special-equivalent-strings/discuss/345036/Python-Solution
"""
| true |
94bb330be10118b3d98761b53f17fe206f9aaa8f | Sen2k9/Algorithm-and-Problem-Solving | /leetcode_problems/1042_Flower_Planting_With_No_Adjacent.py | 2,183 | 4.3125 | 4 | """
You have N gardens, labelled 1 to N. In each garden, you want to plant one of 4 types of flowers.
paths[i] = [x, y] describes the existence of a bidirectional path from garden x to garden y.
Also, there is no garden that has more than 3 paths coming into or leaving it.
Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.
Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)-th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists.
Example 1:
Input: N = 3, paths = [[1,2],[2,3],[3,1]]
Output: [1,2,3]
Example 2:
Input: N = 4, paths = [[1,2],[3,4]]
Output: [1,2,1,2]
Example 3:
Input: N = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]
Output: [1,2,3,4]
Note:
1 <= N <= 10000
0 <= paths.size <= 20000
No garden has 4 or more paths coming into or leaving it.
It is guaranteed an answer exists.
"""
class Solution:
def gardenNoAdj(self, N, paths):
if not paths and N == 1:
return [1]
if len(paths) == 1 and N == 1:
return [1]
import collections
"""
:type N: int
:type paths: List[List[int]]
:rtype: List[int]
"""
g = collections.defaultdict(list)
plantdict = {}
for i in range(1, N + 1):
plantdict[i] = 0
for a, b in paths:
g[a].append(b)
g[b].append(a)
for garden in g:
flower = set(range(1, 5))
for neighbours in g[garden]:
if plantdict[neighbours] != 0 and plantdict[neighbours] in flower:
flower.remove(plantdict[neighbours])
plantdict[garden] = flower.pop()
return [plantdict[x] if plantdict[x] != 0 else 1 for x in range(1, N+1)]
sol = Solution()
N = 3
paths = [[1, 2], [2, 3], [3, 1]]
print(sol.gardenNoAdj(N, paths))
"""
corner case:
1. no path
2. one garden but self loop
reference:
https://leetcode.com/problems/flower-planting-with-no-adjacent/discuss/290930/Python-Greedy-Concise-%2B-Explanation
"""
| true |
3d3e94cb76e19cd5c0af047333b87b09c3da5687 | Tanmay53/cohort_3 | /submissions/sm_110_mihir/week_13/day_4/check_superset.py | 203 | 4.15625 | 4 | set1={1,2,3,10}
set2={1,2,3,4,5,6}
flag=True
for item in set1:
if item not in set2:
print("set2 is not a superset of set1")
flag=False
if flag:
print("set2 is a superset of set1") | true |
c3ff745ba3d84c512bfae7be2f593e142ce3121e | Tanmay53/cohort_3 | /submissions/sm_012_gaurav/week_14/day_3/evaluation/brick_wall.py | 416 | 4.25 | 4 | def brick_wall(width, height):
for i in range(height):
if i%2 == 0:
printEvenRow(width)
else:
printOddRow(width)
def printEvenRow(width):
s = '|___'*width + '|'
print(s)
def printOddRow(width):
s = '__'+'|___'*(width - 1) + '|__'
print(s)
width, height = list(map(int, input("Enter Width, Height(Space Seperated): ").split()))
brick_wall(width, height) | false |
f9be1b61829bc7e14be93a8727ad085b48d9d501 | Tanmay53/cohort_3 | /submissions/sm_103_apoorva/week_13/day_5/tax_calculator.py | 1,303 | 4.125 | 4 | income = int(input("Enter your Income amount: "))
saving = int(input("Enter your saving amount: "))
# print(income,saving)
rebate,taxableIncome,s,tax = 0,0,0,0
#Calculation of taxable Income
if income <= 250000:
print("No Tax")
elif income > 1000000:
if saving > 500000:
rebate = 50000
taxableIncome = income-rebate
else:
rebate = saving * 0.1
taxableIncome = income - rebate
elif 250000 < income < 500000:
if saving > 100000:
rebate = 50000
taxableIncome = income - rebate
else:
rebate = saving * 0.5
taxableIncome = income - rebate
elif 500000 <= income <= 1000000:
if saving > 166666:
rebate = 50000
taxableIncome = income - rebate
else:
rebate = saving * 0.3
taxableIncome = income - rebate
# print(taxableIncome)
#Calculation of Tax
if taxableIncome > 1000000:
s = (taxableIncome - 1000000)*0.3
#125000 = 0.2*500000 + 0.1*250000
tax = s + 125000
elif 500000 < taxableIncome < 1000000:
s = (taxableIncome - 500000)*0.2
#25000 as it 0.1% of 250000
tax = s + 25000
elif 250000 < taxableIncome < 500000:
s = (taxableIncome - 250000)*0.1
tax = s
else:
rebate = 0
tax = 0
print("Your Rebate is: ",rebate)
print("Your Tax amount: ",tax) | false |
931b0405af3e64489598ed42d0b68a77d6a589de | Tanmay53/cohort_3 | /submissions/sm_108_krishna-kant/week_13/day_5/tax_calculator.py | 1,668 | 4.125 | 4 | print("Enter Total Income")
total_income = int(input())
tax = 0
taxable_income = 0
taxable_amount = 0
rebate = 0
print("Enter your savings")
savings = int(input())
# Checking if savings is not greater than total income
if savings > total_income:
print("Savings can't be more than total Income")
else :
# Calculating Rebate
if total_income < 500000 :
rebate = 0.5 * savings
elif total_income < 1000000 :
rebate = 0.3 * savings
elif total_income > 1000000:
rebate = 0.1 * savings
# Checking if rebate is more than capping
if rebate > 50000:
rebate = 50000
# Calculating taxable income
taxable_income = total_income - rebate
# Calculating Taxes
if taxable_income < 250000 :
print("No tax applied!, Your total income is below taxation slab")
elif taxable_income > 250000 and taxable_income <= 500000:
taxable_amount = taxable_income - 250000
tax = 0.1 * taxable_amount
print( f" Total Income : {total_income} \n Rebate : {rebate} \n Taxable Amount : {taxable_amount} \n Tax Percentage : 10% \n Tax Amount : {tax}")
elif 500000 < taxable_income <= 1000000 :
taxable_amount = taxable_income - 500000
tax = 0.2 * taxable_amount + 0.1 * 250000
print( f" Total Income : {total_income} \n Rebate : {rebate} \n Taxable Amount : {taxable_amount} \n Tax Percentage : 20% \n Tax Amount : {tax}")
elif taxable_income > 1000000 :
taxable_amount = taxable_income - 1000000
tax = 0.3 * taxable_amount + 0.2 * 500000 + 0.1 * 250000
print( f" Total Income : {total_income} \n Rebate : {rebate} \n Taxable Amount : {taxable_amount} \n Tax Percentage : 30% \n Tax Amount : {tax}") | true |
366a0d851d1a0fc2509323f283e48e0e9322e498 | Tanmay53/cohort_3 | /submissions/sm_104_asheeh/week_19/day_4/session1/rotate_the_link_list.py | 1,485 | 4.28125 | 4 | class Node:
# constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# function to make the empty linkedlist
def __init__(self):
self.head = None
# function to insert the node at
# the head of the linkedlist
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# function to print the linkedlist
def printList(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next
def rotate(self, k):
if k == 0:
return
current = self.head
count = 1
while current and count < k: # <------
current = current.next
count += 1
# if current is None, k is greater
# than or equal to count of nodes
# in linked list. Don't change the
# list in this case.
if current is None:
return
# current points to kth node
kthNode = current
while current.next:
current = current.next
current.next = self.head
self.head = kthNode.next
kthNode.next = None
llist = LinkedList()
# llist.push(60)
# llist.push(50)
for i in range(60, 0, -10):
llist.push(i)
print('given linkedlist: ')
llist.printList()
llist.rotate(3)
print('rotated list: ')
llist.printList()
| true |
7bcf53d7396c3ad6f3993a860b08a256ac32ffd5 | Tanmay53/cohort_3 | /submissions/sm_102_amit/week_14/day_3/evaluation/sets_intersection.py | 629 | 4.21875 | 4 | # Set intersection
input_1 = input("Enter first set: ")
input_2 = input("Enter second set: ")
input_3 = input("Enter third set: ")
set_1 = set(input_1.split())
set_2 = set(input_2.split())
set_3 = set(input_3.split())
result = set()
for x in set_1:
if x in set_2 and x in set_3:
result.add(x)
print("# Set 1: ", set_1)
print("# Set 2: ", set_2)
print("# Set 3: ", set_3)
print("# ", result)
# Sample Case:
'''
Enter first set: a b c d e
Enter second set: a e f h k
Enter third set: a b c z m
# Set 1: {'b', 'a', 'd', 'e', 'c'}
# Set 2: {'f', 'a', 'h', 'k', 'e'}
# Set 3: {'m', 'b', 'z', 'a', 'c'}
# {'a'}
'''
| false |
f777b0ba6016efa84309aedfecb28772bbc7193d | Tanmay53/cohort_3 | /submissions/sm_112_soumik/week_13/day_4/session_1/union_sets.py | 208 | 4.25 | 4 | input1 = input("Enter a word")
input2 = input("Enter second word")
my_set = {""}
for letter in input1:
my_set.add(letter)
for letter in input2:
my_set.add(letter)
print("union is", "".join(my_set))
| true |
25c974572883afaa2a8c697fa7522ecd3b53491c | Tanmay53/cohort_3 | /submissions/sm_001_aalind/week_14/day_3/evaluation/sets_intersection.py | 957 | 4.21875 | 4 | # splits string by given character and returns a set
def split_string(split_by, given_string):
new_set = set()
temp_str = ''
for char in given_string:
if char != ',':
temp_str += char
else:
new_set.add(temp_str)
temp_str = ''
new_set.add(temp_str)
return new_set
# finds common between two sets
def find_common(set1, set2):
new_set = set()
for val in set1:
if val in set2:
new_set.add(val)
return new_set
set1 = input('Enter comma(,) separated elements without quotes(\') for set1: ')
set2 = input('Enter comma(,) separated elements without quotes(\') for set2: ')
set3 = input('Enter comma(,) separated elements without quotes(\') for set3: ')
set1 = split_string(',', set1)
set2 = split_string(',', set2)
set3 = split_string(',', set3)
sets_common = find_common(set1, set2)
sets_common = find_common(sets_common, set3)
print(sets_common) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.