blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
47abb2cb7a63f713e2e3e6ef9f501cbaf080bfc0 | 12reach/PlayWithPython | /classes/fish.py | 2,156 | 4.78125 | 5 | #!/usr/bin/python3
# this is fish class and we will have some base classes from it
class fishClass:
pass
class ChildFish(fishClass):
print("Hi I am a child fish and I came from troubled water.")
fan1 = ChildFish()
print(fan1)
# the output looks like thsi Hi I am Salman Khan and I am a fish from troubled water.
# <__main__.salmanFish object at 0xb7275b4c>
# now we are going to change the fish class a little bit
class myFishClass:
fin = "I am fin and I come to use when a fish swims."
def __init__(self):
print("Hi I am a parent fish of all child classes.")
def swim(self, distance, time):
self.distance = distance
self.time = distance * time
return distance, time
# print("The fish takes", time, "minutes to swim ", distance, "KMs.")
# let us have some instances of myFish
fish1 = myFishClass()
# once we crate this instance,
print("What does the fins do?")
print(fish1.fin)
# now this is attribute or a property of a fish
# there could be more attributes like this
# let us see whether fish can swim or not and what time it takes to traverse a certain distance
# this is the method or function part of the class which has already got a blueprint
print("To swim 1 KM the first fish takes 10 minutes.")
print("Fish1 : ")
fish1.swim(10, 10)
print("To travel ", fish1.distance, "kms")
print("Fish1 takes", fish1.time, "minutes.")
print("Suppose the fish1 starts with 10 kms per minute speed. But with the increase of each km it starts reducing 1 minute"
"in its speed and loses breadth.")
print("Give any number and see what happens.")
inputs = input(">>>>>>>")
# print(inputs)
fish1.distance = 0
for fish1.distance in range(0, int(inputs)):
# if the fish starts with 10 kms per minute
# and with the increase of each km it starts reducing 1 minute
fish1.time = 10
fish1.time = fish1.time - fish1.distance
if fish1.time == 0:
# it loses its breadth at the point of
print("After", fish1.distance, "kms, it gets drowned. The fish is dead.")
break
else:
continue
if fish1.time <= 10:
print("Upto 10 kms the fish is saved.") | true |
e8857f1f96a62700814b618a58e77c0a284b02c3 | jzferreira/algorithms | /algorithms/sort/sorts.py | 1,416 | 4.15625 | 4 | from algorithms.helpers import generate_random_list
def bubble_sort(elems: list) -> list:
size_elems = len(elems)
for i in range(size_elems - 1):
for j in range(size_elems - i - 1):
if (elems[j] > elems[j+1]):
# troca
elems[j], elems[j + 1] = elems[j + 1], elems[j]
return elems
def insertion_sort(elems: list) -> list:
for i in range(1, len(elems)):
j = i - 1
aux = elems[i]
while j > -1 and elems[j] > aux:
elems[j+1] = elems[j]
j -= 1
elems[j+1] = aux
return elems
def selection_sort(elems: list) -> list:
for i in range(len(elems) - 1):
current = i
for j in range(i+1, len(elems)):
if (elems[j] < elems[current]):
current = j
elems[i], elems[current] = elems[current], elems[i]
return elems
if __name__ == "__main__":
elems = generate_random_list(10)
print(f'Bubble Sort - Vetor original: \n -> {elems}')
print('-----------------------')
print(bubble_sort(elems))
elems = generate_random_list(10)
print(f'Insertion Sort - Vetor original: \n -> {elems}')
print('-----------------------')
print(insertion_sort(elems))
elems = generate_random_list(10)
print(f'Selection Sort - Vetor original: \n -> {elems}')
print('-----------------------')
print(selection_sort(elems))
| false |
0f7c3256ea06e9ebc2ce49911531b2ded494fdc8 | genesisazor/homework | /Chapter6/question3.py | 408 | 4.25 | 4 | def day_num(day_name):
"""takes a day name and returns a number 0-6"""
if day_name == "Sunday":
return 0
elif day_name == "Monday":
return 1
elif day_name == "Tuesday":
return 2
elif day_name == "Wednesday":
return 3
elif day_name == "Thursday":
return 4
elif day_name == "Friday":
return 5
elif day_name == 6:
return 6 | true |
36b7883049cca2cb6cbeb6eb35f5ebf4bd6cabda | ddmin/CodeSnippets | /PY/Playground/strip.py | 466 | 4.21875 | 4 | import re
def strip(string, chr = '\s'):
"""
Implementation of Python's Strip Method.
Parameters:
string (String): Target string.
chr (String): Character(s) to strip. Defaults to whitespace character.
Returns:
String: A string with the characters stripped away.
"""
pattern = re.compile(f'(^[{chr}]*)(.+?)([{chr}]*$)')
ret = pattern.sub(r'\2', string)
return ret
| true |
1e4468fbb0a6bbcd95737b3edfc77e7c51299e55 | yasir-web/pythonprogs | /recursion.py | 202 | 4.25 | 4 | #wap to find the factorial of given number using recurssion
def fact(n):
if n==0 or n==1:
return 1
else:
return n*fact(n-1)
x=int(input("Enter the number: "))
f=fact(x)
print(f)
| true |
c65d07396bfd58be933ca0edc17e9cbb02920471 | yasir-web/pythonprogs | /hierarchial.py | 503 | 4.46875 | 4 | #WAP to demonstrate concept of hierarchial Inheritence
class figure:
def setvalue(self,s):
self.s=s
class square(figure):
def area(self):
return self.s*self.s
class cube(figure):
def volume(self):
return self.s*self.s*self.s
#Now we test the class
sq=square()
cu=cube()
side=int(input("Enter side of square: "))
sq.setvalue(side)
a=sq.area()
print("Area of square=",a)
side=int(input("Enter side of cube: "))
cu.setvalue(side)
b=cu.volume()
print("Volume of cube=",b) | true |
3a238c088626cbea712db233924a841d90a616d2 | Z3DDev/DatabaseManagement | /Assignment2/assign2.py | 2,459 | 4.21875 | 4 | # Zach Jagoda
# Student ID: 2274813
# Student Email: jagod101@mail.chapman.edu
# CPSC408 Database Management
# Assignment 2: SQLite Lab
import sqlite3
conn = sqlite3.connect('studentdb.db')
c = conn.cursor()
loop = 1
while loop == 1:
print("Please Select An Option")
text = input("1. Display All Students, 2. Create Students, 3. Update Students, or 4. Delete Students ")
# Display all Students and their Attributes
if text == 1:
c.execute("SELECT * FROM student")
all_rows = c.fetchall()
for r in all_rows:
print(r)
# Create Students
elif text == 2:
# All Required Info to Create a New Student
fName = raw_input("First Name: ")
lName = raw_input("Last Name: ")
grade = input("GPA: ")
major_ = raw_input("Major: ")
fAdvisor = raw_input("Faculty Advisor: ")
input_param = (fName, lName, grade, major_, fAdvisor,)
c.execute("INSERT INTO student('FirstName', 'LastName', 'GPA', 'Major', 'FacultyAdvisor')"
"VALUES (?, ?, ?, ?, ?)", (fName, lName, grade, major_, fAdvisor))
print(fName + " " + lName + " Has Been Created")
# Update Students
elif text == 3:
changeOption = input("What Would You Like to Change About Student?"
" 1. Major, 2. Faculty Advisor ")
sIDUpdate = input("What is the Student's ID Number: ")
if changeOption == 1:
majorUpdate = raw_input("New Student Major: ")
c.execute("UPDATE student SET Major = ? WHERE StudentId = ?", (majorUpdate, sIDUpdate))
elif changeOption == 2:
fAdvisorUpdate = raw_input("New Faculty Advisor: ")
c.execute("UPDATE student SET FacultyAdvisor = ? WHERE StudentId = ?", (fAdvisorUpdate, sIDUpdate))
print("Student Has Been Updated")
# Delete Students
elif text == 4:
removeID = input("What is the Student ID you would like to remove: ")
c.execute("DELETE FROM student WHERE StudentId = ?", (removeID,))
print("Student Has Been Removed")
conn.commit()
loopOption = input("(0 = No, 1 = Yes) Would You Like to Exit: ")
if loopOption == 0:
loop == 1
elif loopOption == 1:
loop == 0
break
conn.close()
| true |
7bbff704ba253fb8419225cf47ba7be3b17c15bb | nayyanmujadiya/ML-Python-Handson | /src/pandas/dict_to_pd.py | 982 | 4.21875 | 4 | import pandas as pd
#dict is given
sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000}
obj3 = pd.Series(sdata)
print(obj3)
'''
When you are only passing a dict, the index in the resulting Series will
have the dict’s keys in sorted order. You can override this by passing
the dict keys in the order you want them to appear in the resulting
Series:
'''
states = ['California', 'Ohio', 'Oregon', 'Texas']
obj4 = pd.Series(sdata, index=states)
print(obj4)
'''
no value for California
'''
#to detect missing data
print(pd.isnull(obj4))
print(pd.notnull(obj4))
# on instance
obj4.isnull()
'''
I discuss working with missing data in more detail in class.
'''
# Arithmetic operations
print(obj3)
print(obj4)
print(obj3 + obj4)
'''
Data alignment features will be addressed in more detail later. If
you have experience with databases, you can think about this as being
similar to a join operation.
'''
obj4.name = 'population'
obj4.index.name = 'state'
print(obj4)
| true |
728c03ca26f01391b06c7ffed4708ff07bd9c2a1 | nayyanmujadiya/ML-Python-Handson | /src/basic_index_np.py | 688 | 4.34375 | 4 | import numpy as np
arr = np.arange(10)
print(arr)
print(arr[5])
print(arr[5:8])
# assign scalar to slice
arr[5:8] = 12
print(arr)
'''
An important first distinction from Python’s built-in lists is that array slices are views on the original array. This means that the data is not copied, and any modifications to the view will be reflected in the source array.
'''
arr_slice = arr[5:8]
print(arr_slice)
arr_slice[1] = 12345
print(arr)
'''
The “bare” slice [:] will assign to all values in an array:
'''
arr_slice[:] = 64
print(arr)
'''
If you want a copy of a slice of an ndarray instead of a view, you will need to explicitly copy the array for example, arr[5:8].copy().
'''
| true |
64c894b1c64a64cfd791de76e4e17e99abda7750 | nayyanmujadiya/ML-Python-Handson | /src/ml/baseball_mult_reg.py | 2,785 | 4.125 | 4 | #Step 1: Import libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
'''
data source:
https://college.cengage.com/mathematics/brase/understandable_statistics/7e/students/datasets/mlr/frames/frame.html
'''
'''
A random sample of major league baseball players was obtained.
The following data (X1, X2, X3, X4, X5, X6) are by player.
X1 = batting average
X2 = runs scored/times at bat
X3 = doubles/times at bat
X4 = triples/times at bat
X5 = home runs/times at bat
X6 = strike outs/times at bat
'''
'''
Step 2: Read the dataset
'''
df = pd.read_csv("major_league_baseball_players.csv")
df.columns = ['x1','x2','x3','x4','x5','x6']
print(df.describe())
'''
In our dataset x1 is the output variable, which stores the batting average of baseball players. So, we consider all columns except x1 as input X and 0th column(x1) as output Y.
'''
'''
In train_test_split() function, we used test_size as 0.2, which means we use 20% of the data for testing and the remaining 80% for training.
'''
X = df.iloc[:,df.columns != 'x1']
Y = df.iloc[:, 0]
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state= 0)
'''
Step 3: Train the model
'''
model = linear_model.LinearRegression()
model.fit(X_train, Y_train)
'''
We use X_train and Y_train for train the linear regression model. The X_test use for predict the output Y.
'''
coeff_df = pd.DataFrame(model.coef_, X.columns, columns=['Coefficient'])
print(coeff_df)
'''
This means that for a unit increase in x3(doubles/times at bat), there is an increase of 1.02 units in the x1(batting average). Similarly, for a unit increase in the x6(strike outs/times at bat), there is a decrease of 0.24 in x1.
'''
'''
Step 4: Predict the output
'''
y_pred = model.predict(X_test)
df = pd.DataFrame({'Actual': Y_test, 'Predicted': y_pred})
print(df.head(10))
df.plot(kind='bar',figsize=(10,8))
plt.grid(which='major', linestyle='-', linewidth='0.5', color='green')
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
plt.show()
'''
Step 4: Evaluation
'''
# Root Mean Squared Deviation
rmsd = np.sqrt(mean_squared_error(Y_test, y_pred)) # Lower the rmse(rmsd) is, the better the fit
r2_value = r2_score(Y_test, y_pred) # The closer towards 1, the better the fit
print("Y-Intercept: \n", model.intercept_)
print("Root Mean Square Error(rmsd) \n", rmsd)
print("R^2 Value: \n", r2_value)
'''
Here the R² value is 0.8356, which shows the model is almost accurate and can make good predictions. R² value can range from 0 to 1. As the R² value close to 1, the model will make better predictions.
'''
| true |
c0fe2894662d81ae0bd815acee999bdc4b2684ed | rtduany/personal-development | /Insert.py | 459 | 4.5625 | 5 | # Dash Insert
# Using python, have the function DashInsert(str) insert dashes ('-') between each two odd numbers in string.
# For example: if str is 454793 the output should be 4547-9-3. Don't count zero as an odd number.
def DashInsert(str):
#first lets iterate thru the function
for i in str:
#turn the string to int
i = int(i)
#check if the incoming argument or i is odd
if (i % 2 != 0):
str.append("-")
return str
print DashInsert("454793")
| true |
139561d8c1b225843bee56fd00dd2e356894b021 | macknilan/Cuaderno | /Python/ejemplos_ejercicios/caja_negra_testing.py | 1,567 | 4.28125 | 4 | import unittest
def suma(num_1, num_2):
return num_1 + num_2
class CajaNegraTest(unittest.TestCase):
"""Las pruebas de caja negra se basan en la especificación de la función o el programa,
aquí debemos probas sus inputs y validar los outputs. Se llama caja negra por que no
necesitamos saber necesariamente los procesos internos del programa, solo contrastar sus resultados.
Estos tipos de pruebas son muy importantes para 2 tipos de test:
Unit testing: se realizan pruebas a cada uno de los módulos para determinar su correcto funcionamiento.
Integration testing: es cuando vemos que todos los módulos funcionan entre sí.
Es una buena práctica realizar los test antes de crear tus lineas de código,
esto es por que cualquier cambio que se realice a futuro los test estarán
incorporados para determinar si los cambios cumplen lo esperado.
En Python existe la posibilidad de realizar test gracias a la librería unittest.
Puede ser que el siguiente código no lo entiendas en su totalidad, pero en
una próxima guía detallare mas el tema de clases en programación.
https://docs.python.org/3.9/library/unittest.html
"""
def test_suma_dos_positivos(self):
num_1 = 10
num_2 = 5
resultado = suma(num_1, num_2)
self.assertEqual(resultado, 15)
def test_suma_dos_negativos(self):
num_1 = -10
num_2 = -7
resultado = suma(num_1, num_2)
self.assertEqual(resultado, -17)
if __name__ == "__main__":
unittest.main()
| false |
09c8ec2a5c0dc092337fa7337f399533d0f3cf7a | macknilan/Cuaderno | /Python/Code_examples/05_iterators/iterator_basics.py | 1,581 | 4.34375 | 4 | from dataclasses import dataclass
@dataclass
class Item:
name: str
weight: float
def main() -> None:
inventory = [
Item("laptop", 1.5),
Item("phone", 0.5),
Item("book", 1.0),
Item("camera", 1.0),
Item("headphones", 0.5),
Item("charger", 0.5),
]
inventory_iterator = iter(inventory)
print(next(inventory_iterator))
print(next(inventory_iterator))
print(next(inventory_iterator))
print(next(inventory_iterator))
print(next(inventory_iterator))
print(next(inventory_iterator))
# print(next(inventory_iterator)) # this raises a StopIteration exception
# alternatively, we can use a for loop
for item in inventory:
print(item.weight)
# a for loop creates an iterator object and executes the next() method for each iteration
# behind the scenes, the for loop is equivalent to the following code:
inventory_iterator = iter(inventory)
while True:
try:
item = next(inventory_iterator)
except StopIteration:
break
else:
print(item.weight)
# you can also call iter with a sentinel value
# this is useful when you want to iterate over a stream of data
# for example, you can read a file line by line
# the sentinel value is a value that indicates the end of the stream
# in this case, the sentinel value is an empty string
with open("countries.txt") as f:
for line in iter(f.readline, ""):
print(line, end="")
if __name__ == "__main__":
main()
| true |
9a5fbf2c455e1e64e9e11bd6e56dba8ddef1c98a | macknilan/Cuaderno | /Python/ejemplos_ejercicios/palindromo.py | 870 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""palindromo.py"""
def palindrome2(word):
reversed_word = word[::-1]
if reversed_word == word:
return True
return False
def palindrome(word):
reversed_letters = []
for letter in word:
reversed_letters.insert(0, letter)
reversed_word = "".join(reversed_letters)
if reversed_word == word:
return True
return False
# return reversed_word
if __name__ == "__main__":
word = str(input("Escribe una palabra: "))
result = palindrome2(word)
if result is True:
print("{} Si es un palindromo.".format(word))
else:
print("{} Si no es palindromo.".format(word))
# print('Palabra {} ').format(result)
# reves = []
# for letter in 'Python':
# reves.insert(0, letter)
# print ('Current Letter {}: {}').format(letter, reves)
| false |
edb0b8978dbc60c27acd9f164f0a763c1c953cd5 | macknilan/Cuaderno | /Python/ejemplos_ejercicios/poo_abstract_base_classes_ejem_01.py | 818 | 4.15625 | 4 | # abstract base classes
import abc
class Vehicle(abc.ABC):
"""
Declaracion de la clase abstracta
"""
@abc.abstractmethod
def go(self):
pass
@abc.abstractmethod
def stop(self):
pass
class Car(Vehicle):
"""
Clase heredada de -Vehicle-
"""
def go(self):
print("You drive the car")
def stop(self):
print("This car is stopped")
class Motorcycle(Vehicle):
"""
Clase heredada de -Vehicle-
"""
def go(self):
print("You ride the motorcycle")
def stop(self):
print("This motorcycle is stopped")
# vehicle = Vehicle()
car = Car()
motorcycle = Motorcycle()
# vehicle.go()
car.go()
motorcycle.go()
# vehicle.stop()
car.stop()
motorcycle.stop()
| false |
41068a9aa46eb97b3cee209cef947c9f52538a54 | harut0601/youtube-videos | /video2/problem3.py | 459 | 4.25 | 4 | temperature = int(input("The outside temperature: "))
unit = input("(C)elsius or (F)ahrenheit: ")
if unit.upper() == "C":
final_temperature = (temperature * 1.8 + 32)
elif unit.upper() == "F":
final_temperature = ((temperature - 32) * 5/9)
else:
print("Please try again!")
final_temperature = "Not defined"
if unit.upper() == "C":
unit = "Fahrenheit"
elif unit.upper() == "F":
unit = "Celsius"
print(final_temperature, unit) | true |
7ef4b9293d5060777f8d3a4b424c025e7d10180f | rajilaxmi/python | /functions/6.cases.py | 450 | 4.34375 | 4 | # to coount the number of uppercase and lowercase alphabet in a string
def counting(str1):
d={"upper":0,"lower":0}
for c in str1:
if c.isupper():
d["upper"]+=1
elif c.islower():
d["lower"]+=1
else:
pass
print "Number of uppercase alphabets: %d"%d["upper"]
print "Number of lowercase alphabets: %d"%d["lower"]
str1="The Quick Brown Fox"
counting(str1)
'''
Number of uppercase alphabets: 4
Number of lowercase alphabets: 12
'''
| true |
daa01efd4345099884bf2c7b6722ef029759ad8f | Alex760164/home_work | /home_work_30/home_work_30.py | 1,226 | 4.28125 | 4 | """
Имеется строка вида: AABABBAABBBAB. Необходимо написать функцию которая заменит буквы A на B, и B,
соответственно, на A. Замену можно производить ТОЛЬКО используя функцию replace().
В результате применения функции к исходной строке, функция должна вернуть строку: BBABAABBAAABA
Использовать циклы и оператор IF запрещено.
"""
def replace_string(string, old_char, new_char):
tmp_1 = string.replace(old_char, 'tmp_char')
tmp_2 = tmp_1.replace(new_char, old_char)
res = tmp_2.replace('tmp_char', new_char)
return res
chars = input('Введите строку: ').upper()
old_symbol = input('Введите заменяемый символ: ').upper()
new_symbol = input('Введите новый символ: ').upper()
print('ОТВЕТ:\n\tВходная строка: ', chars)
print('\tСтарый символ: ', old_symbol, '\n\tНовый символ: ', new_symbol, )
print('\tВыходная строка:', replace_string(chars, old_symbol, new_symbol))
| false |
c7da4dd6f9fcf37b7189247eee9e0ceffd4903af | Sashagrande/Faculty-of-AI | /Lesson_1/task_3.py | 224 | 4.125 | 4 | n = input('Введите число ')
a = (n, n * 2, n * 3) # для отображения "n + nn + nnn в ответе
nn = int((n * 2))
nnn = int(n * 3)
n = int(n)
print(a[0], '+', a[1], '+', a[2], '=', n + nn + nnn)
| false |
a27469903e1dd03705ad938807acbfac708fe8c8 | halasdhowre/TTA-halasdhowre | /HLT 3.py | 2,237 | 4.15625 | 4 | #################################Home Learning Task 3
#Q1
#Write a program that allows you to enter 4 numbers and stores them in a file called “Numbers”
#• 3
#• 45
#• 83
#• 21
#Have a go at ‘w’ ‘r’ ‘a’
file_1 = open("GitHub/TTA-halasdhowre/Submitted HLT/Numbers.txt", "r")
print(file_1.read())
file_1.close()
#Q2
#Write a program to ask a student for their percentage mark and convert this to a grade.
def mark_grade (precentage):
print("Hello, to findout your grade follow the instructions:")
name= input("Please enter your name:")
percentage=int(input("Please Enter your percentage mark:"))
if percentage <30 or percentage <= 39:
print("Unfortunatly,", name +" ,you have not passed this module:" "grade: Fail")
elif percentage > 39 and percentage <49:
print(name +" ,you have have passed the module:" "grade: Pass")
elif percentage >=50 and percentage <69:
print(name+",you have passed the module:" "grade: Merit")
elif percentage >=70 and percentage <= 100:
print("Excellent", name+", you have succesfully passed the module:""grade: Distinction")
else:
print("Error")
return name
x = mark_grade("name")
print(x)
#Q3
#(1)Create a 1D array of numbers from 0 to 9
import numpy as np
array = np.array([0,1,2,3,4,5,6,7,8,9])
print(array)
#(2)Create a 3×3 NumPy array of all Boolean value Trues
array = np.array([True, False, True, 3, 2, False, 5, True, 9])
new_array = array.reshape(3,3)
print(new_array)
#(3)Extract all odd numbers from array of 1-10
array = np.array([1,2,3,4,5,6,7,8,9])
array[array % 2 == 1]
#(4)Replace all odd numbers in an array of 1-10 with the value -1
array = np.array([1,2,3,4,5,6,7,8,9])
array[array % 2 == 1] = -1
#(5)Convert a 1D array to a 2D array with 2 rows
array = np.array([0,1,2,3,4,5,6,7,8,9])
print('1D Numpy array:')
print(array)
array_2d = np.reshape(array, (2, 5))
print('2D Numpy array:')
print(array_2d)
#(6)Create two arrays a and b, stack these two arrays vertically use the np.dot and np.sum to calculate totals
a=np.array([3,7,9])
b=np.array([2,1,8])
c=np.dot(a,b)
sum=np.sum(c)
print(c)
| true |
86f49db5f9e996f883c843ed8457b49dfd679963 | KavitaPatidar/100DaysPythonCode_BeginnerLevel | /HangMan.py | 869 | 4.1875 | 4 | import random
from design import word_list, logo, stages
print(logo)
word= random.choice(word_list)
print(word)
display=[]
for letter in word:
# or display+= "_"
display.append("_")
# print(display)
guess_continue= True
lives=6
while guess_continue:
guess= input("guess a letter: ").lower()
if guess in display:
print(f"You have already guessed {guess}.")
for n in range(len(word)):
letter=word[n]
if guess==letter:
display[n]=guess
print(f"{' '.join(display)}")
if not guess in word:
lives-=1
print(f"Wrong guess. Now you have {lives} life rest.")
if lives==0:
print(f"The right word was {word}.")
print("You lose!")
guess_continue= False
if not "_" in display:
print("You won!")
guess_continue= False
print(stages[lives])
| true |
50aaa7b8ea7b522fa3bdf039ac413149a0798500 | choisoonsin/python3 | /design_pattern/decorators/classmethod.py | 697 | 4.375 | 4 | class Person:
population = 0
def __init__(self, name, age):
self.name = name
self.age = age
Person.population += 1
@classmethod
def get_population(cls):
return cls.population
if __name__ == '__main__':
"""
In this example, we define a Person class with a population attribute
and an __init__ method that increments the population attribute every time
a new Person object is created.
Reference:
https://medium.com/@mkuhikar/python-decorators-advanced-67420a5b7278
"""
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
print(Person.get_population()) # Output: 2
| true |
6b84eabc00ee49c5a3334f182865ac48ed1d015e | JingYiTeo/2019_ALevel_CP_Notes | /Sorting/Bubble Sort (Not Optimized).py | 714 | 4.21875 | 4 | def bubble_sort(A):
#assume not sorted
swapped = True
#while swapped: as long as its not swapped
while swapped:
swapped = False
#for loop: iterate through all the elements from index 1 to end
for i in range(1, len(A)):
#if the previous element > element after it
if A[i-1] > A[i]:
#swap their places
A[i-1], A[i] = A[i], A[i-1]
#swapped is done for this element
swapped = True
#and it goes back to the next element in the for loop
#return the sorted array/list
return A
#main
A = [4,5,3,123,32,6,2]
print(bubble_sort(A))
| true |
95270ce3b015709f114eb1fda9eac6dbad6394a2 | JingYiTeo/2019_ALevel_CP_Notes | /Searching/Binary Search.py | 926 | 4.34375 | 4 | #binary search needs the data/array/list to be sorted before it can search.
def binary_search(elements, target, low, high):
#define the middle item index
mid = (high + low) // 2
if low > high: # not found
return -1
#target is exactly in the middle of array
elif elements[mid] == target: #found
return mid
#binary search divides the problem case by half each time
elif target < elements[mid]: #recursive case 1 : target is smaller than middle so its on the left of array (from low to mid -1)
return binary_search(elements, target, low, mid-1)
else: #recursive case 2: target is larger than middle so its on the right of array (from mid+1 to high)
return binary_search(elements, target, mid+1, high)
#main
items = [1,2,3,4,5,6,7,8]
print(binary_search(items, 2, 0, len(items)-1)) #it will print the index of target in the array.
| true |
f8809724342461be3a1269d8bc275ed4e1fa82c9 | srusher/Python-for-Data-Science-and-Machine-Learning | /4. Pandas/6_Pandas_GroupBy.py | 861 | 4.25 | 4 | import numpy as np
import pandas as pd
from numpy.random import randn
np.random.seed(101)
# think of the GroupBy function in Pandas as the GroupBy clause in SQL
## In SQL: typically used for aggregate functions and returns values for each distinct row
# Create dataframe
data = {'Company':['GOOG','GOOG','MSFT','MSFT','FB','FB'],
'Person':['Sam','Charlie','Amy','Vanessa','Carl','Sarah'],
'Sales':[200,120,340,124,243,350]}
df = pd.DataFrame(data)
print(df)
byComp = df.groupby('Company')
print(byComp.mean())
print(byComp.sum())
print(df.groupby('Company').sum().loc['MSFT'])
# .describe() gives you a bunch of useful info about the dataframe
print(df.groupby('Company').describe())
# you can also use .transpose() to alter the way the resulting table looks
print(df.groupby('Company').describe().transpose())
| true |
15fe34a8bf17cad25a3d2c9af5d34abb2f23d96a | abhi8893/Intensive-python | /exercises/get_initials.py | 757 | 4.15625 | 4 | # Write a program that takes a full name, prints the initials of the first,
# middle, and last name. If the middle name is “NA”, then the program
# should print only the initials of the first and the last name.
def get_initials(name):
""" Return initials of first, last and middle name.
If the middle name is 'NA', return only the initials of the first and the last name.
>>> get_initials("Alfred E. Newman")
'A.E.N.'
>>> get_initials("John NA Smith")
'J.S.'
"""
names_lst = name.split(' ')
res = ''.join(list(map(lambda x: f'{x[0]}.' if x != 'NA' else '',
names_lst)))
return(res)
def main():
print(get_initials("Alfred NA Newman"))
if __name__ == '__main__':
main()
| true |
315d4db0cfcf49ba4a8ea2f389a91df1cf48d257 | abhi8893/Intensive-python | /exercises/3D_to_2D_lists.py | 1,097 | 4.5 | 4 | ''' Define a function that takes a 3-D list and
converts it to a 2-D list in-place. '''
def get_2D(lst):
""" Convert the list to 2-D in-place.
my_list = [[['item1','item2']],[['item3', 'item4']]]
>>> get_2D(my_list)
[['item1', 'item2'], ['item3', 'item4']]
"""
lst = lst.copy()
for i, item in enumerate(lst):
lst[i] = item[0]
return(lst)
# Do not make any changes to the code below
# Function used in main() to print
# what each function returns vs. what it's supposed to return
def test(returned, expected):
if returned == expected:
prefix = ' OK '
else:
prefix = ' X '
print('{0} returned: {1} expected: {2}'.format(prefix, repr(returned), repr(expected)))
# Do not make any changes to the code below
# Calls the above functions with interesting inputs.
def main():
my_list = [[['item1','item2']],[['item3', 'item4']]]
print('get_2D')
test(get_2D(my_list), [['item1', 'item2'], ['item3', 'item4']])
print(my_list)
if __name__ == '__main__':
main()
| true |
df49417c2647d7e197a6965086c38432c65b69b3 | abhi8893/Intensive-python | /exercises/conv_to_unqouted_str.py | 791 | 4.125 | 4 | # Convert a string such that it is not surrounded by quotes.
def unquoted_str(s: str):
'''Converts a string into an unquoted string'''
# TODO: use regex
# NOTE: Not requiring an s argument, as it seems cleaner
# and also unneccesary if function is just for
# internal consumption.
def quotedAt(at):
quotes = ["'", '"']
if at == 'start':
i = 0
elif at == 'end':
i = -1
return(True if s[i] in quotes else False)
# NOTE: Avoiding unneccessary function calls
# by checking if s[0] == s[-1]
while s[0] == s[-1] and quotedAt('start') and quotedAt('end'):
s = s[1:-1]
return(s)
if __name__ == "__main__":
s = "''asas'''"
res = unquoted_str(s)
print(res)
| true |
794ab61657f537357dcc1791d3bd1151d781e0ab | abhi8893/Intensive-python | /exercises/first_vowel_in_each_word.py | 566 | 4.125 | 4 | def find_first_vowel(S: str) -> str:
""" Return the first vowel in each word of a string.
>>> find_first_vowel("The sky's the limit")
'e, e, i'
"""
vowels = ['a', 'e', 'i', 'o', 'u']
words = S.split(' ')
res = []
for w in words:
for l in w:
if l in vowels:
res.append(l)
break
else: continue
res = ', '.join(res)
return(res)
def main():
print(find_first_vowel("The sky's the limit"))
if __name__ == '__main__':
main()
| false |
b9b2511443d106aaf24b70eacd9a46936ad55375 | DRMPN/PythonCode | /CS50/ProblemSet6/dna/dna.py | 2,496 | 4.15625 | 4 | # program that identifies a person based on their DNA
import sys
import csv
def main():
# correct usage check
if len(sys.argv) != 3:
sys.exit("Usage: python dna.py data.csv sequence.txt")
# list of dictionaries
database = []
# read people's dna from a database
with open(sys.argv[1]) as file:
reader = csv.DictReader(file)
for line in reader:
database.append(line)
# string of dna sequence
sequence = ''
# read dna sequence from a file
with open(sys.argv[2]) as file:
for line in file:
sequence = line
# calculate used tandems in sequence
tandems = request_tandems(database[0], sequence)
# try to find a person to match tandem repeats
result = database_search(database, tandems)
print(result)
# produces a list of locations of first element of tandem
def locate_tandems(sequence, tandem, tandem_length):
tandem_list = []
for i in range(len(sequence)):
if sequence[i:i+tandem_length] == tandem:
tandem_list.append(i)
return tandem_list
# calculates amount of tandem in a list of tandemes
def count_tandems(tandem_list, tandem_length):
# empty list case
if not tandem_list:
return 0
count = 1
max_count = 1
for i in range(len(tandem_list) - 1):
if tandem_list[i] == tandem_list[i+1] - tandem_length:
count += 1
else:
count = 1
max_count = max(max_count, count)
return max_count
# calculates amount of particular tandem in sequence
def find_tandem_amount(sequence, tandem):
tandem_length = len(tandem)
tandem_list = locate_tandems(sequence, tandem, tandem_length)
amount = count_tandems(tandem_list, tandem_length)
return amount
# produces amount of tandems in sequence
def request_tandems(db_dic, sequence):
tandem_dic = {}
for tandem in list(db_dic)[1:]:
tandem_dic[tandem] = find_tandem_amount(sequence, tandem)
return tandem_dic
# linear search over all persons in database
def database_search(database, tandems):
for person in database:
if compare_tandems(person, tandems):
return person['name']
return "No match"
# compares person's tandems to sequence tandems
def compare_tandems(db_dic, tandem_dic):
for tandem in list(tandem_dic):
if int(db_dic[tandem]) != tandem_dic[tandem]:
return False
return True
if __name__ == "__main__":
main() | true |
f7f0310b9d3e118087b5695466303ba02e9057c7 | CCG-Magno/Tutoriales_Python | /looping_sample.py | 1,245 | 4.15625 | 4 | def while_loop_example():
print("This is a while loop example...\n")
i=0
while i < 5:
print(f"[{i}] Hello world!")
print()
return
def for_loop_example():
print('This is a for loop example...\n')
for i in range(5):
print(f"[{i}] Hello World!")
print()
return
def loop_sample():
# i=0
# while i <= 5:
# print(i)
# i+= 1
# print("Termina loop")
# key_pressed = False
# while not key_pressed :
# if i == 5:
# # key_pressed = True
# break
# print(f"[{i}] Hello World")
# i += 1
# print("Game Start!")
# names = ["a","b", "c"]
# for i in names:
# print(f" Hello: [{i}]")
# if i == 'b':
# continue
# i = i + 1
# Esto es un foreach -> un iterador para atravesar una coleccion de objetos
# [0, 4]
# # names = ["a","b", "c"]
# for i in range(0,5, 2):
# print(f" Hello : [{i}]")
# # if i == 'b':
# # break
while_loop_example()
for_loop_example()
return
def main():
# print("Hello world!")
loop_sample()
pass
if __name__ == "__main__":
main() | false |
e8493faf5241aba6e1e41f37fafc1588ab1647f1 | leon541/Tom | /a-List.py | 607 | 4.4375 | 4 | def printList(list):
print("----")
for i in list:
print(i)
print("----")
foods = ["apple","banana","pie","pear"]
print(foods[2])
print("----")
for x in foods:
print(x)
print("--append apple--")
foods.append("apple")
for x in foods:
print(x)
print("--remove pie--")
foods.remove("pie")
for i in foods:
print(i)
print("----")
print("len: ", len(foods))
foods.insert(0, "dragonfruit")
printList(foods)
foods.reverse()
printList(foods)
print("apple index:" , foods.index("apple"))
print("pear index:" , foods.index("pear"))
print("----")
foods.clear()
print(foods)
| false |
58c4b69005958b9e0045fe641743d35de724104d | Hassan-Farid/PyTech-Review | /Python Intermediate/Sequences and Iterables/Naming Slices.py | 2,775 | 4.28125 | 4 | '''
Assume that we want to extract a certain slice from a particular long list
'''
#Suppose we are provided a large list with lots and lots of numbers and you want to get the sum of a particular bunch
#We can take a random list of numbers using the random.randint() method and then sum the specified slices
#Normally we can extract the slices by using compact numbers as indexes
from random import randint
random_list = []
for i in range(100):
random_list.append(randint(0,100))
print(random_list)
#Suppose we want to sum up the slices yielded from the 40 to 50 indexes and 70 to 80 indexes
total = sum(random_list[40:50]) + sum(random_list[70:80])
print('The required total under given conditions is: {}'.format(total))
#Writing complicated slice indexes within the formula is little bit code complication
#To avoid this we can name the slices using the slice object and then use it in the formula
first_slice = slice(40,50)
second_slice = slice(70,80)
newtotal = sum(random_list[first_slice]) + sum(random_list[second_slice])
print('The required total under given conditions is: {}'.format(newtotal))
#This slice object can be used wherever a slice is allowed i.e. strings, lists, ranges, etc.
#Suppose we are given a list of students final practical exams marks based on the project, with index of list representing their roll numbers
#Turns out that the roll numbers from 12 to 15 have been assigned the wrong marks and they are to be adjusted
studMarks = []
for i in range(50):
studMarks.append(randint(20,100))
print('The marks obtained by the respective 50 students are: {}'.format(studMarks) )
#Now we want to adjust the marks of students from 12-15 in accordance with the adjusted marks list
adjustList = [67,78,91]
adjustSlice = slice(12,15)
studMarks[adjustSlice] = adjustList
print('The marks after adjusting obtained by the respective 50 students are: {}'.format(studMarks))
#The teacher found out that even though the marks were assigned to the students, the last 10 students were not under her consideration
#And their projects had to be judged by some other teacher so they would have to be removed from the given list
removeSlice = slice(40,50)
del studMarks[removeSlice]
print('The marks after removing obtained by the respective 40 students are: {}'.format(studMarks))
print(len(studMarks))
#Suppose the teacher only wants to display the marks obtained by the students with even roll number from 16-32
#For such a case we need to provide the slice method with three parameters, the third one being the gap in slice
#Using the indices() method for a slice object we can get the required result as displayed
selectSlice = slice(16,33,2)
for i in range(*selectSlice.indices(len(studMarks))):
print(studMarks[i]) | true |
74ca3e8d21e709ac9128421aaed93259e8081059 | Hassan-Farid/PyTech-Review | /Python Intermediate/Sequences and Iterables/Implementing Priority Queue.py | 1,794 | 4.375 | 4 | '''
Assume you want to implement a priority queue that sorts items in a queue based on their priority
'''
#A priority queue is an ADT similar to a queue which functions the same way as a queue (FIFO order) but pops/deques elements based on priority
#We will now create a class PriorityQueue and use another class Marks to insert marks into the Queue so that they can be dequeued with priority
#We use the heapq module to implement the following mentioned above
import heapq
class PriorityQueue():
def __init__(self):
self._queue = []
self._index = 0
#Push would require a certain priority integer value which would represent the order in which the students have to be dequeued
def push(self, item, priority):
heapq.heappush(self._queue, (priority, self._index, item))
self._index += 1
#Pop would remove a value from the queue like a normal pop using the FIFO method
def pop(self):
return heapq.heappop(self._queue)[-1]
class Marks():
def __init__(self, name, marks):
self.name = name
self.marks = marks
def __repr__(self):
return '{} has {} marks'.format(self.name, self.marks)
#Now lets use the priority queue by pushing the Students and their Marks and then popping them out
if __name__ == "__main__":
q = PriorityQueue()
q.push(Marks('Touseef', 86), 86)
q.push(Marks('Hasan', 79), 79)
q.push(Marks('Adnan', 89), 89)
q.push(Marks('Moiz', 69), 69)
q.push(Marks('Abdul Wahab', 100), 100)
print(q.pop())
print(q.pop())
print(q.pop())
print(q.pop())
print(q.pop())
#As we can see from the result, the student with the lowest priority was popped out first and the student with the highest priority
#was popped out last | true |
de812795776b9ea6083669adb85e0002bb8d7e27 | Hassan-Farid/PyTech-Review | /Python Intermediate/Sequences and Iterables/Sorting List of Dictionaries using Common Key.py | 1,298 | 4.40625 | 4 | '''
Assume you want to sort a list of dictionaries with one or more of its keys
'''
#Suppose an institute conducts a test based on Maths and English marks and assigns positions to students based on their marks in these two subjects
#Suppose we are provided a list containing the json data for the students and the marks they obtained in subjects of English and Maths
studMarks = [
{'name':'Touseef', 'maths':85, 'eng':82},
{'name':'Darain', 'maths':91, 'eng':75},
{'name':'Hassan', 'maths':100, 'eng':71},
{'name':'Usman', 'maths':68, 'eng':83},
{'name':'Daniyal', 'maths':95, 'eng':95}
]
#Now to sort the dictionary based on the common key values we can use the itemgetter class from the built-in operator module
from operator import itemgetter
#Lets sort the names based on the marks obtained in Maths (in descending order)
pos_by_maths = sorted(studMarks, key=itemgetter('maths'), reverse=True)
print(pos_by_maths)
#Let sort the names based on the marks obtained in English (in descending order)
pos_by_eng = sorted(studMarks, key=itemgetter('eng'), reverse=True)
print(pos_by_eng)
#Since the exam need to position the students based on overall marks from both Maths and English (in descending order)
pos = sorted(studMarks, key=itemgetter('maths','eng'))
print(pos)
| true |
fac8e73dca7850bef6a22dfc2794756083c10686 | Hassan-Farid/PyTech-Review | /Python Basics/Iteration Statements/NestedLooping.py | 1,713 | 4.5625 | 5 | '''
Sometimes a single loop is not enough for the application we have to peform, thus, we need to use loops within loops
This use of loops within loops is known as Nested Looping and is quite used in application development
'''
#Using nested looping to find a palindrome
text = "level"
isPalindrome = False
for i in range(len(text)): #Starts checking characters of text from beginning
for j in range(len(text) - i - 1, -1, -1): #Starts checking characters of text from the end
if text[i] == text[j]:
isPalindrome = True #Is assigned True for every match
else:
isPalindrome = False #Is assigned False for every non-match
print("Is {} a palindrome: {}".format(text, isPalindrome))
#Using nested looping to perform matrix multiplication
A = [[1,2,3], [4,5,6], [7,8,9]]
B = [[9,8,7], [6,5,4], [3,2,1]]
C = [[0] * len(B[0])] * len(A) #The matrix yielded as a product has rows equal to first matrix and columns equal to second matric
for i in range(len(A)): #Looping for the rows of the first matrix
for j in range(len(B[0])): #Looping for the columns of the second matrix
for k in range(len(C)): #Looping for the length of the resulting matrix
C[i][j] += A[i][k] * B[k][j]
print(C)
'''
Task: Once done with this stuff, you can perform the following task to check if you got it or not
Create a program that uses nested looping to sort elements of a list
Enter the elements of a list (seperated by commas): ___________________ (Input comes in blank)
Once the input has been entered, the program should return the inputted list in sorted order:
Enter the elements of a list: 4,5,11,7,16,3,14,19
Sorted List: [3,4,5,7,11,14,16,19]
''' | true |
237de905fac906dea8f4fd0439a4ebe71e79ab9c | Hassan-Farid/PyTech-Review | /Python Intermediate/Text Processing/String Matching using WildCard Patterns.py | 1,777 | 4.25 | 4 | '''
Assume you want to match text using commonly used Unix wildcard characters
'''
#Suppose a company has a list of different file formats and they want to obtain only the ones with .csv in the end
#We can use the Unix wildcard pattern with the list of files using the fnmatch module
#fnmatch provides functionalities fnmatch() and fnmatchcase() which can help us in this task
from fnmatch import fnmatch, fnmatchcase
fileList = [
'data.csv',
'Test.html',
'newdata.txt',
'players.csv',
'neat.CSV',
'nice.txt',
'scripts.py',
'simple.py'
]
#Now we can use the basic expression '*.csv' to match whether the file is csv or not
for file in fileList:
if fnmatch(file, '*.csv') == True:
print(file)
#Although the above gives us the correct result, but assume that the company accepts lowercase extension files only
#In such case, we have to also look for the case instead of just string matching.
for file in fileList:
if fnmatchcase(file, '*.csv') == True:
print(file)
#As another example, lets assume we have been provided with a list of phone numbers belonging to Pakistani citizens
#As per the code 033- and the fact that the number is 11 digits long, we need to find all the numbers that use the Ufone SIM card
phoneList = [
'03311111111',
'03122222222',
'03033333333',
'0334444444444',
'03455555555',
'03266666666666',
'902946656575676756',
'03399999999',
'03100000000'
]
#Now checking for valid phone numbers and listing them
ufoneNumList = []
for phone in phoneList:
if len(phone) == 11:
if fnmatch(phone, '033*'):
ufoneNumList.append(phone)
print('The valid Ufone Numbers in the provided list are: {}'.format(ufoneNumList)) | true |
499bc6dc2a5430049a5002fd54df3afb4fbbfc95 | DemonsHacker/learntf | /python/mo_fan/01_python3/02_if_else.py | 219 | 4.21875 | 4 | x = 1
y = 2
z = 3
if x<y:
print('x is less than y')
else:
print('y is less than x')
if x<y and y<z:
print('x is less than y,and y is less than z')
x = 2
y = 2
z = 0
if x == y:
print("x is equal to y") | false |
a7792b1a3a562cd2acca963f99822b16d0de629f | aggressiveapple5/problemSet0 | /ps0.py | 2,118 | 4.1875 | 4 | #0
def is_even(number):
''' Takes user input and returns True if number is even and False if odd'''
while number > 1:
number -= 2
if number == 1:
even = False
else:
even = True
return(even)
#1
def number_digits(number):
'''Takes a non-negative number as input and returns the number of digits in the number'''
digits = []
number = str(number)
for digit in number:
digits.append(digit)
length = len(digits)
return length
#2
def sum_digits(number):
'''Takes a non-negative number and adds its digits together'''
digits = []
number = str(number)
for digit in number:
digits.append(digit)
sum = 0
for digit in digits:
sum += int(digit)
return sum
#3
def sum_less_ints(number):
'''Takes a non-negative number as input and adds all the numbers less than that number.'''
numbers = range(0 , number)
outcome = 0
for interger in numbers:
outcome += interger
return outcome
#4
def factorial(number):
'''Finds the factorial of a given number.'''
numbers = range(1 , number + 1)
outcome = 1
for digit in numbers:
outcome *= digit
return outcome
#5
def factor(x, y):
'''Takes 2 numbers as arguments and if x is a factor of y, True will be returned. If not, then True.'''
x = x % y
if x == 0:
return True
else:
return False
#6
def is_prime(number):
'''Returns True if number is prime and False if not.'''
list = range(2, number)
for factor in list:
prime = number % factor
if prime == 0:
return False
exit()
return True
#7
def perfect_number(number):
'''Checks whether the number is perfect or not.'''
list = range(1, number)
perfectFactors = []
for factor in list:
remainder = number % factor
if remainder == 0:
perfectFactors.append(factor)
output = 0
for possiblePerfect in perfectFactors:
output += possiblePerfect
if output == number:
return True
else:
return False
#8
def sum_digit_factor(number):
'''Checks if he sum of the digits of the number divides evenly into the number then true, false otherwise.'''
sum = sum_digits(number)
factor = number % sum
if factor == 0:
return True
else:
return False | true |
9687dd20d0579cb75056693ad133d32fded15488 | rahulgupta020/bscit-practical | /4c.py | 271 | 4.15625 | 4 | #Write a Python program to clone or copy a list
#Method1
original_list=[1,2,3,4,5]
print("Original List = ",original_list)
new_list=list(original_list)
print("New List = ",new_list)
print()
#Method
og=[6,7,8,9,10]
print("OG = ",og)
copy=og.copy()
print("COPY = ",copy) | true |
2351a19868108f4b61bd32fcf805f16ae0b6ae8e | eranandagarwal/callbacks | /more_callback.py | 1,909 | 4.28125 | 4 | import time
def slow_calculation(cb = None):
res = 0
for i in range(5):
res += i * i
time.sleep(1)
if cb:
cb(i)
return res
# what if we do not define a function for callback, instead use lambda for same
slow_calculation(lambda num: print (f"Yay !! we have reached {num} iteration"))
# What if we do ot want to write "Yay !!" always and now want to send the exclamation as an argument. we will have to change the callback in slow_calculation fntion as 2 argument. But we can do without that
def show_progress(exclamation,num):
print (f"{exclamation} we are in {num} iteration")
#now we can call slow calculation passing lambda in below way
slow_calculation(lambda num: show_progress("Awesome !!", num))
# we can do the same without lambda, with a proper function
def show_progress_as_closure(exclamation):
_inner = lambda iteration: print (f"{exclamation} we are in {iteration} iteration")
return _inner
slow_calculation (show_progress_as_closure("Nice !!"))
# instead of _inner having the function we can have a fiunction defined as well.
def show_progress_as_function(exclamation):
def _inner(iteration):
print (f"{exclamation} we are in {iteration} iteration")
return _inner
slow_calculation (show_progress_as_function("cool !!"))
# now we can use the above closure function to store a function with a excalmation
f = show_progress_as_function("great !!")
slow_calculation(f)
# another thing that we can do to make a function that excets 2 argument to take 1 argument is to use partial from functools
from functools import partial
# show_progress is a function that takes 2 argument, exclamation and num.
f1 = partial (show_progress , "partial !!") # this convert the function to 1 argument where the 1st one is "partial !!"
slow_calculation(f1) | true |
ccee0cfb15b744983325e9557b73dfc55f99f63e | group6bse1/BSE-2021 | /src/chapter3/exercise2.py | 749 | 4.28125 | 4 | #handling any errors that might occur during execution if user input is wrong
try:
# accepting Hours from user which is an integer
hours = float(input('Please enter hours: '))
# accepting rate per hour from the user which is float value-
rate = float(input('please enter rate :'))
if hours > 40:
#calculating the gross pay if hours worked are more than 40
pay = hours * (1.5 * rate)
else:
#calculating the gross pay if hours are less than 40
pay = hours * rate
#printing the gross pay after the above computation
print('Gross pay: ', pay)
#below is my capture of any errors that will occur during execution or wrong user input
except:
print('INVALID INPUT, Enter a numerical value!!')
| true |
37613fa2186eaa07a55b0fbf99bf7164165fe78c | group6bse1/BSE-2021 | /src/chapter2/excercise5.py | 341 | 4.40625 | 4 | # x is the temperature in degrees celsius to be input
x = float(input('Enter temperature in \N{DEGREE SIGN}C :'))
#y is the temperature in fahranheit
# formula for computing the conversion
y = (9/5)*x+32
print("Converting...", x, "\N{DEGREE SIGN}C to Fahrenheit")
print("Temperature is: ", y, "\N{DEGREE SIGN}F") #printing the conversion
| true |
a5a47ec2a87e4db6d6e284b99f6ae38ae5634d29 | group6bse1/BSE-2021 | /src/chapter3/exercise1.py | 465 | 4.28125 | 4 | #accepting Hours from user which is an integer
hours = float(input('Please enter hours: '))
#accepting rate per hour from the user which is float value-
rate = float(input('please enter rate :'))
if hours > 40:
#calculating the gross pay if hours worked are more than 40
pay = hours * (1.5 * rate)
else:
#calculating the gross pay if hours are less than 40
pay = hours * rate
#printing the gross pay after the above computation
print('Gross pay: ', pay)
| true |
31e06eb0baf27a658a4637eff8fd38c5878d0d28 | ariana124/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/6-print_sorted_dictionary.py | 277 | 4.1875 | 4 | #!/usr/bin/python3
"""
Module that contains the function print_sorted_dictionary
"""
def print_sorted_dictionary(a_dictionary):
""" prints a dictionary by ordered keys """
for key in sorted(a_dictionary.keys()):
print("{}: {}".format(key, a_dictionary[key]))
| true |
ca3516edbf5c86ed923c27a7f870f43da53dc6f0 | ariana124/holbertonschool-higher_level_programming | /0x03-python-data_structures/10-divisible_by_2.py | 432 | 4.375 | 4 | #!/usr/bin/python3
"""
Module containing the function divisible_by_2
"""
def divisible_by_2(my_list=[]):
""" returns a new list with True or False, depending on whether the integer
at the same position in the original list is a multiple of 2 """
new_list = []
for number in my_list:
if number % 2 == 0:
new_list.append(True)
else:
new_list.append(False)
return new_list
| true |
4d2ee71bb0efbec3cdab08b8d4f04f88dad574d6 | arya-hemanshu/algorithms | /merge_sort.py | 1,387 | 4.375 | 4 |
"""
A python implementation of merge sort,
complexity of merge sort is O(NlogN)
Args:
unsorted array of numbers or letters
Output:
sorted array of number or letters
How to use:
python merge_sort.py <space seperated numbers or letters>
"""
def merge_sort(list_to_sort):
if len(list_to_sort) == 1:
return
pivot = len(list_to_sort) // 2
first = list_to_sort[:pivot]
second = list_to_sort[pivot:]
merge_sort(first)
merge_sort(second)
left, right, index = 0, 0, 0
while left < len(first) and right < len(second):
if first[left] < second[right]:
list_to_sort[index] = first[left]
left += 1
else:
list_to_sort[index] = second[right]
right += 1
index += 1
while left < len(first):
list_to_sort[index] = first[left]
index += 1
left += 1
while right < len(second):
list_to_sort[index] = second[right]
index += 1
right += 1
return list_to_sort
def main(args):
import sys
if not args:
print('Need array to sort')
sys.exit(1)
else:
try:
int(args[0])
a = [int(e) for e in args]
print(merge_sort(a))
except ValueError:
print(merge_sort(args))
if __name__ == '__main__':
import sys
main(sys.argv[1:])
| true |
6465a846fcbb8d5f07f0e54f2a6069b0d0603e15 | arthurDz/algorithm-studies | /leetcode/binary_tree_paths.py | 670 | 4.125 | 4 | # Given a binary tree, return all root-to-leaf paths.
# Note: A leaf is a node with no children.
# Example:
# Input:
# 1
# / \
# 2 3
# \
# 5
# Output: ["1->2->5", "1->3"]
# Explanation: All root-to-leaf paths are: 1->2->5, 1->3
def binaryTreePaths(self, root):
if not root: return
def path(node):
if not node.left and not node.right: return [str(node.val)]
res = []
if node.right:
res += ['%s->%s' % (node.val, i) for i in path(node.right)]
if node.left:
res += ['%s->%s' % (node.val, i) for i in path(node.left)]
return res
return path(root) | true |
a0a67d39beea8a413918c846ebc0c188f8797a6c | arthurDz/algorithm-studies | /linkedin/binary_tree_upside_down.py | 1,247 | 4.21875 | 4 | # Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.
# Example:
# Input: [1,2,3,4,5]
# 1
# / \
# 2 3
# / \
# 4 5
# Output: return the root of the binary tree [4,5,2,#,#,3,1]
# 4
# / \
# 5 2
# / \
# 3 1
# Clarification:
# Confused what [4,5,2,#,#,3,1] means? Read more below on how binary tree is serialized on OJ.
# The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
# Here's an example:
# 1
# / \
# 2 3
# /
# 4
# \
# 5
# The above binary tree is serialized as [1,2,3,#,#,4,#,#,5].
def upsideDownBinaryTree(self, root: TreeNode) -> TreeNode:
if not root: return
def traverse(node, prev, prev_l):
temp, next = node.right, node.left
node.right = prev
node.left = prev_l
if not next:
return node
else:
return traverse(next, node, temp)
return traverse(root, None, None) | true |
94ab33ed9269014316effea13fc61a468cbac5bb | arthurDz/algorithm-studies | /leetcode/valid_palindrome.py | 502 | 4.1875 | 4 | # Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
# Note: For the purpose of this problem, we define empty string as valid palindrome.
# Input: "A man, a plan, a canal: Panama"
# Output: true
def isPalindrome(s):
if s == "":
return True
s = ''.join([i for i in s if i.isalpha() or i.isdigit()]).lower()
for i in range(int(len(s) / 2)):
if s[i] != s[len(s) - i - 1]:
return False
return True | true |
454abe0ec9c3efc65f263290f62d498ad6311a83 | arthurDz/algorithm-studies | /leetcode/number_of_operations_to_make_network_connected.py | 2,209 | 4.15625 | 4 | # There are n computers numbered from 0 to n-1 connected by ethernet cables connections forming a network where connections[i] = [a, b] represents a connection between computers a and b. Any computer can reach any other computer directly or indirectly through the network.
# Given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected. If it's not possible, return -1.
# Example 1:
# Input: n = 4, connections = [[0,1],[0,2],[1,2]]
# Output: 1
# Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3.
# Example 2:
# Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
# Output: 2
# Example 3:
# Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
# Output: -1
# Explanation: There are not enough cables.
# Example 4:
# Input: n = 5, connections = [[0,1],[0,2],[3,4],[2,3]]
# Output: 0
# Constraints:
# 1 <= n <= 10^5
# 1 <= connections.length <= min(n*(n-1)/2, 10^5)
# connections[i].length == 2
# 0 <= connections[i][0], connections[i][1] < n
# connections[i][0] != connections[i][1]
# There are no repeated connections.
# No two computers are connected by more than one cable.
def makeConnected(self, n, connections):
num_connected = num_extra = 0
visited = set()
graph = collections.defaultdict(set)
for i, v in connections:
graph[i].add(v)
graph[v].add(i)
for i in range(n):
if i in visited: continue
q = collections.deque([i])
visited.add(i)
while q:
node = q.popleft()
for next in graph[node]:
graph[next].remove(node)
if next in visited:
num_extra += 1
else:
q.append(next)
visited.add(next)
num_connected += 1
if num_connected - 1 > num_extra:
return -1
else:
return num_connected - 1 | true |
204096f4c74c5445b2d154f8d086102530108a9d | arthurDz/algorithm-studies | /leetcode/display_table_of_food_orders_in_a_restaurant.py | 2,957 | 4.46875 | 4 | # Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders.
# Return the restaurant's “display table”. The “display table” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.
# Example 1:
# Input: orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]]
# Output: [["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]]
# Explanation:
# The displaying table looks like:
# Table,Beef Burrito,Ceviche,Fried Chicken,Water
# 3 ,0 ,2 ,1 ,0
# 5 ,0 ,1 ,0 ,1
# 10 ,1 ,0 ,0 ,0
# For the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche".
# For the table 5: Carla orders "Water" and "Ceviche".
# For the table 10: Corina orders "Beef Burrito".
# Example 2:
# Input: orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]]
# Output: [["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]]
# Explanation:
# For the table 1: Adam and Brianna order "Canadian Waffles".
# For the table 12: James, Ratesh and Amadeus order "Fried Chicken".
# Example 3:
# Input: orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]]
# Output: [["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]]
# Constraints:
# 1 <= orders.length <= 5 * 10^4
# orders[i].length == 3
# 1 <= customerNamei.length, foodItemi.length <= 20
# customerNamei and foodItemi consist of lowercase and uppercase English letters and the space character.
# tableNumberi is a valid integer between 1 and 500.
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
d = collections.defaultdict(collections.Counter)
f = set()
for _, x, y in orders:
d[x][y] += 1
f.add(y)
res = []
res.append(["Table"] + sorted(list(f)))
for key in sorted(d.keys(), key=int):
temp = [key]
for i in range(1, len(res[0])):
temp.append(str(d[key][res[0][i]]))
res.append(temp)
return res | true |
01232d78e27044360a9bc8d0cb3c3a8f158266f6 | arthurDz/algorithm-studies | /linkedin/print_binary_tree.py | 2,633 | 4.28125 | 4 | # Print a binary tree in an m*n 2D string array following these rules:
# The row number m should be equal to the height of the given binary tree.
# The column number n should always be an odd number.
# The root node's value (in string format) should be put in the exactly middle of the first row it can be put. The column and the row where the root node belongs will separate the rest space into two parts (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size. Even if one subtree is none while the other is not, you don't need to print anything for the none subtree but still need to leave the space as large as that for the other subtree. However, if two subtrees are none, then you don't need to leave space for both of them.
# Each unused space should contain an empty string "".
# Print the subtrees following the same rules.
# Example 1:
# Input:
# 1
# /
# 2
# Output:
# [["", "1", ""],
# ["2", "", ""]]
# Example 2:
# Input:
# 1
# / \
# 2 3
# \
# 4
# Output:
# [["", "", "", "1", "", "", ""],
# ["", "2", "", "", "", "3", ""],
# ["", "", "4", "", "", "", ""]]
# Example 3:
# Input:
# 1
# / \
# 2 5
# /
# 3
# /
# 4
# Output:
# [["", "", "", "", "", "", "", "1", "", "", "", "", "", "", ""]
# ["", "", "", "2", "", "", "", "", "", "", "", "5", "", "", ""]
# ["", "3", "", "", "", "", "", "", "", "", "", "", "", "", ""]
# ["4", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]]
# Note: The height of binary tree is in the range of [1, 10].
def printTree(self, root: TreeNode) -> List[List[str]]:
stack = [(root, 1, 1)]
d = collections.defaultdict(dict)
max_level = 1
while stack:
node, ind, level = stack.pop()
max_level = max(level, max_level)
d[level][ind] = node.val
if node.left:
stack.append((node.left, 2 * (ind - 1) + 1, level + 1))
if node.right:
stack.append((node.right, 2 * (ind - 1) + 2, level + 1))
res = [[""] * (2 ** (max_level) - 1) for _ in range(max_level)]
def traverse(level, ind, i, j):
if level not in d or ind not in d[level]: return
res[level - 1][(i + j) // 2] = str(d[level][ind])
traverse(level + 1, 2 * (ind - 1) + 1, i, (i + j) // 2 - 1)
traverse(level + 1, 2 * (ind - 1) + 2, (i + j) // 2 + 1, j)
traverse(1, 1, 0, len(res[0]) - 1)
return res | true |
f65a9d54eb9db6eb1b51e4b4732f3dcad8d65e34 | arthurDz/algorithm-studies | /CtCl/Bit Manipulation/conversion.py | 741 | 4.28125 | 4 | # Conversion: Write a function to determine the number of bits you would need to flip to convert integer A to integer B.
# EXAMPLE
# Input: 29 (or: 11101), 15 (or: (1111) Output: 2
def conversion(num1, num2):
count = 0
while num1 and num2:
if (num1 & 1) ^ (num2 & 1) == 1:
count += 1
num1 = num1 >> 1
num2 = num2 >> 1
temp = num1 if num2 == 0 else num1
while temp:
if temp & 1 == 1:
count += 1
temp = temp >> 1
return count
# better approach: use xor and count number of 1
def conversion(num1, num2):
temp = num1 ^ num2
count = 0
while temp:
if temp & 1 == 1:
count += 1
temp = temp >> 1
return count | true |
0778a363d71d0d111be0d516ca5368f76a439f32 | arthurDz/algorithm-studies | /leetcode/path_with_minimum_effort.py | 2,138 | 4.21875 | 4 | # You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.
# A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.
# Return the minimum effort required to travel from the top-left cell to the bottom-right cell.
# Example 1:
# Input: heights = [[1,2,2],[3,8,2],[5,3,5]]
# Output: 2
# Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.
# This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.
# Example 2:
# Input: heights = [[1,2,3],[3,8,4],[5,3,5]]
# Output: 1
# Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].
# Example 3:
# Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
# Output: 0
# Explanation: This route does not require any effort.
# Constraints:
# rows == heights.length
# columns == heights[i].length
# 1 <= rows, columns <= 100
# 1 <= heights[i][j] <= 106
import collections
def minimumEffortPath(heights) -> int:
d = {(0, 0): 0}
queue = collections.deque([(0, 0)])
while queue:
x, y = queue.popleft()
for dx, dy in [[0, 1], [1, 0], [0, -1], [-1, 0]]:
if 0 <= x + dx < len(heights) and 0 <= y + dy < len(heights[0]):
cost = max(d[x, y], abs(heights[x + dx][y + dy] - heights[x][y]))
if cost < d.get((x + dx, y + dy), float('inf')):
d[x + dx, y + dy] = cost
if (x + dx, y + dy) != (len(heights) - 1, len(heights[0]) - 1):
queue.append((x + dx, y + dy))
return d[len(heights) - 1, len(heights[0]) - 1] | true |
bd332ff87b40738895782ee99864ea8b7142ed71 | arthurDz/algorithm-studies | /amazon/most_common.py | 2,449 | 4.21875 | 4 | # Amazon is partnering with the linguistics department at a local university to analyze important works of English literature and identify patterns in word usage across different eras. To ensure a cleaner output, the linguistics department has provided a list of commonly used words (e.g., "an", "the", etc.) to exclude from the analysis. In the context of this search, a word is an alphabetic sequence of characters having no whitespace or punctuation. Write an algorithm to find the most frequently used word in the text excluding the commonly used words.
# Input
# The input to the function/method consists of two arguments -
# literatureText, a string representing the block of text;
# wordsToExclude , a list of strings representing the commonly used words to be excluded while analyzing the word frequency.
# Output
# Return a list of strings representing the most frequently used word in the text or in case of a tie, all of the most frequently used words in the text.
# Note
# Words that have a different case are counted as the same word. The order of words does not matter in the output list. All words in the wordsToExclude list are unique.
# Any character other than letters from the English alphabet should be treated as white space.
# Example
# Input:
# literatureText = “Jack and Jill went to the market to buy bread and cheese. Cheese is Jack's and Jill’s favorite food.”
# wordsToExclude = ["and", "he", "the", "to", "is", "Jack", "Jill"]
# Output:
# ["cheese", “s”]
# Explanation:
# The word “and” has a maximum of three frequency but this word should be excluded while analyzing the word frequency.
# The words “Jack”, “Jill”, “s”, "to" and "cheese” have the next maximum frequency(two) in the given text but the words “Jack”, "to" and “Jill” should be excluded as these are commonly used words which you are not interested to include.
# So the output is ["cheese", “s”] or [“s”, "cheese"] as the order of words does not matter.
import re
import collections
def mostCommon(text, exclude):
text = re.split('[^a-z]', text.lower())
text = list(filter(lambda x: x != '', text))
d = collections.Counter(text)
res = []
max_occur = 0
for k, v in d.items():
if not k in exclude:
if v > max_occur:
res = [k]
max_occur = v
elif v == max_occur:
res.append(k)
print(d)
return res | true |
a4b5e62a31da15b84ddef1a9fa93ceae17f41d45 | arthurDz/algorithm-studies | /leetcode/subtree_of_another_tree.py | 1,395 | 4.28125 | 4 | # Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
# Example 1:
# Given tree s:
# 3
# / \
# 4 5
# / \
# 1 2
# Given tree t:
# 4
# / \
# 1 2
# Return true, because t has the same structure and node values with a subtree of s.
# Example 2:
# Given tree s:
# 3
# / \
# 4 5
# / \
# 1 2
# /
# 0
# Given tree t:
# 4
# / \
# 1 2
# Return false.
def isSubtree(self, s, t):
def check(node1, node2):
if not node1 and not node2: return True
if (not node1 and node2) or (node1 and not node2): return False
res = False
if node1.val == node2.val:
res = check_all(node1.left, node2.left) and check_all(node1.right, node2.right)
update = check(node1.left, node2) or check(node1.right, node2)
return res or update
def check_all(node1, node2):
if not node1 and not node2: return True
if (not node1 and node2) or (node1 and not node2): return False
return node1.val == node2.val and check_all(node1.left, node2.left) and check_all(node1.right, node2.right)
return check(s, t) | true |
5e8dd2b8d5369f05f43d508e96517d7eea2cfede | arthurDz/algorithm-studies | /leetcode/N-ary_tree_level_order_traversal.py | 872 | 4.1875 | 4 | # Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
# For example, given a 3-ary tree:
# We should return its level order traversal:
# [
# [1],
# [3,2,4],
# [5,6]
# ]
# Note:
# The depth of the tree is at most 1000.
# The total number of nodes is at most 5000.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
def levelOrder(self, root):
if not root: return
stack = collections.deque([(root, 0)])
res = []
while stack:
node, level = stack.popleft()
if len(res) < level + 1:
res.append([node.val])
else:
res[level].append(node.val)
for i in node.children:
stack.append((i, level + 1))
return res | true |
6493d4b06546bc81380bb48ed82e1e01b791044c | arthurDz/algorithm-studies | /leetcode/reverse_string.py | 617 | 4.25 | 4 | # Reverse String
# Write a function that reverses a string. The input string is given as an array of characters char[].
# Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
def reverse_string(str1):
i = 0
j = len(str1) - 1
while i < j:
temp = str1[i]
str1[i] = str1[j]
str1[j] = temp
i += 1
j -= 1
return str1
def reverseString(self, s: List[str]) -> None:
for i in range(len(s) // 2):
s[i], s[len(s) - i - 1] = s[len(s) - i - 1], s[i]
return s | true |
e337a457a6c871894ffe9afa713297dc1c44fc3f | arthurDz/algorithm-studies | /leetcode/sort_colors.py | 1,486 | 4.1875 | 4 | # Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
# Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
# Note: You are not suppose to use the library's sort function for this problem.
# Example:
# Input: [2,0,2,1,1,0]
# Output: [0,0,1,1,2,2]
# Follow up:
# A rather straight forward solution is a two-pass algorithm using counting sort.
# First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
# Could you come up with a one-pass algorithm using only constant space?
def sortColors(self, nums):
if not nums: return
ind = [0] * 3
for k, v in enumerate(nums):
if k > ind[v]:
temp = nums.pop(k)
nums.insert(ind[temp], temp)
ind[v:] = [i + 1 for i in ind[v:]]
# inplace O(N)
def sortColors(self, nums: List[int]) -> None:
heads = [-1] * 3
for i in range(len(nums)):
temp = org = nums[i]
while temp + 1 < len(heads):
if heads[temp + 1] >= 0:
if heads[org] < 0: heads[org] = heads[temp + 1]
nums[heads[temp + 1]], nums[i] = nums[i], nums[heads[temp + 1]]
heads[temp + 1] += 1
temp += 1
if heads[org] < 0: heads[org] = i
return nums | true |
de1508b94a92598f03f91b60797d12fcf0d4edca | arthurDz/algorithm-studies | /leetcode/intersection_of_two_arrays_2.py | 1,022 | 4.15625 | 4 | # Given two arrays, write a function to compute their intersection.
# Example 1:
# Input: nums1 = [1,2,2,1], nums2 = [2,2]
# Output: [2,2]
# Example 2:
# Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
# Output: [4,9]
# Note:
# Each element in the result should appear as many times as it shows in both arrays.
# The result can be in any order.
# Follow up:
# What if the given array is already sorted? How would you optimize your algorithm?
# What if nums1's size is small compared to nums2's size? Which algorithm is better?
# What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
import collections
def intersect(self, nums1, nums2):
if len(nums1) != len(nums2):
nums1, nums2 = min(nums1, nums2, key=len), max(nums1, nums2, key=len)
d = collections.Counter(nums1)
intersect = []
for i in nums2:
if i in d and d[i] > 0:
intersect.append(i)
d[i] -= 1
return intersect
| true |
1cc2990421174b6a7161da1fbe745a8d3c73ca25 | arthurDz/algorithm-studies | /bloomberg/insertion_sort_list.py | 2,481 | 4.34375 | 4 | # Sort a linked list using insertion sort.
# A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
# With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
# Algorithm of Insertion Sort:
# Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
# At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
# It repeats until no input elements remain.
# Example 1:
# Input: 4->2->1->3
# Output: 1->2->3->4
# Example 2:
# Input: -1->5->3->4->0
# Output: -1->0->3->4->5
def insertionSortList(self, head):
if not head: return
def unlinkNode(node):
if not node.prev:
node.next.prev = None
elif not node.next:
node.prev.next = None
else:
node.prev.next, node.next.prev = node.next, node.prev
node.next = None
node.prev = None
def insert(node, pos):
if pos.next:
pos.next.prev = node
node.prev = pos
node.next, pos.next = pos.next, node
i, t = None, head
while t:
t.prev = i
i, t = t, t.next
start = head.next
while start:
temp = start.next
prev = start.prev
unlinkNode(start)
while prev:
if start.val < prev.val:
prev = prev.prev
else:
break
if not prev:
head, start.next= start, head
head.next.prev = head
else:
insert(start, prev)
start = temp
return head
def insertionSortList(self, head: ListNode) -> ListNode:
if not head: return
prev, node = head, head.next
while node:
next = node.next
prev.next = None
i, j = None, head
while j and j.val < node.val:
i, j = j, j.next
if i:
i.next = node
else:
head = node
if j:
node.next = j
while j.next:
j = j.next
j.next = next
prev = j
else:
node.next = next
prev = node
node = next
return head | true |
0e6a395dff87b5199a26b8594f6920d6c3265f99 | arthurDz/algorithm-studies | /linkedin/find_leaves_of_binary_tree.py | 978 | 4.25 | 4 | # Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.
# Example:
# Input: [1,2,3,4,5]
# 1
# / \
# 2 3
# / \
# 4 5
# Output: [[4,5,3],[2],[1]]
# Explanation:
# 1. Removing the leaves [4,5,3] would result in this tree:
# 1
# /
# 2
# 2. Now removing the leaf [2] would result in this tree:
# 1
# 3. Now removing the leaf [1] would result in the empty tree:
# []
def findLeaves(self, root: TreeNode) -> List[List[int]]:
if not root: return
d = collections.defaultdict(list)
def traverse(node):
if not node: return 0
level = max(traverse(node.left), traverse(node.right)) + 1
d[level].append(node.val)
return level
l = traverse(root)
return [d[i] for i in range(1, l + 1)] | true |
fd27e4a692f2fa5a901f68b255bcca58bf830d36 | arthurDz/algorithm-studies | /CtCl/Bit Manipulation/binary_to_string.py | 572 | 4.28125 | 4 | # Binary to String: Given a real number between 8 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print "ERROR:'
def printBinary(num):
if num <= 0 or num >= 1: return "ERROR"
init = '0.'
count = -1
while num:
if len(init) > 32:
return "ERROR"
if num < 2 ** count:
init += '0'
else:
num -= 2 ** count
init += '1'
count -= 1
return init | true |
80624c401ab0cbc7c815b486db5f341432a97c71 | arthurDz/algorithm-studies | /leetcode/largest_multiple_of_three.py | 2,126 | 4.25 | 4 | # Given an integer array of digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order.
# Since the answer may not fit in an integer data type, return the answer as a string.
# If there is no answer return an empty string.
# Example 1:
# Input: digits = [8,1,9]
# Output: "981"
# Example 2:
# Input: digits = [8,6,7,1,0]
# Output: "8760"
# Example 3:
# Input: digits = [1]
# Output: ""
# Example 4:
# Input: digits = [0,0,0,0,0,0]
# Output: "0"
# Constraints:
# 1 <= digits.length <= 10^4
# 0 <= digits[i] <= 9
# The returning answer must not contain unnecessary leading zeros.
def largestMultipleOfThree(self, digits: List[int]) -> str:
remainder = sum(digits) % 3
digits.sort(key = lambda x: -x)
if remainder == 0:
temp = "".join(map(str, digits))
if not temp: return temp
return str(int(temp))
elif remainder == 1:
for i in range(len(digits) - 1, -1, -1):
if digits[i] % 3 == 1:
digits.pop(i)
temp = "".join(map(str, digits))
if not temp: return temp
return str(int(temp))
c = 0
for i in range(len(digits) - 1, -1, -1):
if digits[i] % 3 == 2:
digits.pop(i)
c += 1
if c == 2:
temp = "".join(map(str, digits))
if not temp: return temp
return str(int(temp))
elif remainder == 2:
for i in range(len(digits) - 1, -1, -1):
if digits[i] % 3 == 2:
digits.pop(i)
temp = "".join(map(str, digits))
if not temp: return temp
return str(int(temp))
c = 0
for i in range(len(digits) - 1, -1, -1):
if digits[i] % 3 == 1:
digits.pop(i)
c += 1
if c == 2:
temp = "".join(map(str, digits))
if not temp: return temp
return str(int(temp))
return "" | true |
462d331a410f7020f847e42ca27e4799f5041c34 | arthurDz/algorithm-studies | /amazon/solve_the_equation.py | 1,698 | 4.15625 | 4 | # Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.
# If there is no solution for the equation, return "No solution".
# If there are infinite solutions for the equation, return "Infinite solutions".
# If there is exactly one solution for the equation, we ensure that the value of x is an integer.
# Example 1:
# Input: "x+5-3+x=6+x-2"
# Output: "x=2"
# Example 2:
# Input: "x=x"
# Output: "Infinite solutions"
# Example 3:
# Input: "2x=x"
# Output: "x=0"
# Example 4:
# Input: "2x+3x-6x=x+2"
# Output: "x=-1"
# Example 5:
# Input: "x=x+2"
# Output: "No solution"
def solveEquation(self, equation):
p1, p2 = equation.split('=')
def decompose(eq):
eq = eq.split('+')
params = [0, 0]
for i in eq:
temp = i.split('-')
for ind, val in enumerate(temp):
if not val:
continue
elif val[-1] == 'x':
pre = int(val[:-1]) if len(val) > 1 else 1
if ind == 0:
params[0] += pre
else:
params[0] -= pre
else:
if ind == 0:
params[1] += int(val)
else:
params[1] -= int(val)
return params
a1, b1 = decompose(p1)
a2, b2 = decompose(p2)
if a1 == a2:
if b1 == b2:
return "Infinite solutions"
else:
return "No solution"
else:
return "x=%s" % str((b1 - b2) / (a2 - a1)) | true |
16aa4d50a4366e29bddf4f01626e3db25fbd352d | adargut/CompetitiveProgramming | /BinaryTrees/Trie/trie.py | 1,327 | 4.125 | 4 | class Trie(object):
def __init__(self):
"""
Represents root node.
"""
self.sons = {}
self.val = None
self.mark = False # means a word ends there
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: None
"""
for char in word:
if char not in self.sons:
self.sons[char] = Trie()
if self.val:
self.sons[char].val = self.val + char
else:
self.sons[char].val = char
self = self.sons[char]
self.mark = True
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
for char in word:
if char in self.sons:
self = self.sons[char]
else:
return False
return self.mark
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
for char in prefix:
if char in self.sons:
self = self.sons[char]
else:
return False
return True
| true |
f7451bae519ecb3dcb8a39c5b024bed4bee80f3f | clarizamayo/JupyterNotebooks | /Class Material/Week-07/script.py | 1,847 | 4.21875 | 4 | # from random import randint
# class GuessingGame:
# """
# max_guess = 3
# guesses = 0
# """
# def __init__(self):
# self.max_guess = 3
# self.guesses = 0
# self.random_number = randint(1,3)
# @staticmethod
# def welcome_message():
# print("Welcome to guessing game")
# def start(self):
# GuessingGame.welcome_message()
# win = self.handle_guesses()
# if win:
# print("You have won")
# else:
# print("You have lost")
# def handle_guesses(self):
# while self.guesses < self.max_guesses:
# guesss = input("Enter a guess")
# if int(guess) == self.random_number:
# return True
# self.guesses +=1
# return False
# if __name__ == '__main__':
# game = GuessingGame()
# game.start()
from random import randint
class GuessingGame:
"""
max_guess = 3
guesses = 0
"""
def __init__(self):
self.max_guesses = 3
self.guesses = 0
self.random_number = randint(1,3)
@staticmethod
def welcome_message():
print("Welcome to guessing game")
def start(self):
GuessingGame.welcome_message()
win = self.handle_guesses()
if win:
print("You have won")
else:
print("You have lost")
def handle_guesses(self):
while self.guesses < self.max_guesses:
guess = input("Enter a guess")
if int(guess) == self.random_number:
return True
self.guesses += 1
return False
if __name__ == '__main__': #letting me call the name of file
game = GuessingGame()
game.start()
| true |
90afb3429e48cb3102abd07693897319ba2a644f | singularitea/python-programming-exercises | /question_002.py | 401 | 4.40625 | 4 | # Write a program which can compute the factorial of a given numbers.
# The results should be printed in a comma-separated sequence on a single line.
# Suppose the following input is supplied to the program:
# 8
# Then, the output should be:
# 40320
print('Enter your factorial:')
print('')
f = input()
fa = 1
if f == 0:
print(0)
else:
for i in range(1,int(f)):
fa += fa*i
print(fa)
| true |
09aa834efc0a24c6edffa4bbd2b93305a3ce7e93 | GiulianoSoria/CS50x | /pset6/sentimental/caesar/caesar.py | 1,609 | 4.34375 | 4 | from cs50 import get_string
import sys
# Converts into an integer the value entered as a key in the command-line
k = int(sys.argv[1])
# Checks if the key is greater than zero
if k > 0:
# Prompts the user to enter the text that wants ciphered
s = get_string("plaintext: ")
print("ciphertext: ", end="")
# Iterates over every character in the string
for i in s:
# Checks if the character is a character from the alphabet
if i.isalpha():
# Checks if the character is lowercase
if i.islower():
# Checks if when we add the character and the key, the value is greater than the one from the 'z', if it is, it wraps around back to 'a'
if (ord(i) + k) > ord('z'):
j = (ord(i) - 97 + k) % 26
print(chr(j + 97), end="")
# Prints the character plus the key
else:
print(chr(ord(i) + k), end="")
# Checks if the character is uppercase
elif i.isupper():
# Checks if when we add the character and the key, the value is greater than the one from the 'Z', if it is, it wraps around back to 'A'
if (ord(i) + k) > ord('Z'):
j = (ord(i) - 65 + k) % 26
print(chr(j + 65), end="")
# Prints the character plus the key
else:
print(chr(ord(i) + k), end="")
# If the character is not from the alphabet, it is printed just as is
else:
print(i, end="")
print()
| true |
76631622928186aff0efeb14c7b3f07175406a86 | Michellecp/Python | /python_teste/meuprograma.py | 2,301 | 4.21875 | 4 | '''
Módulo que contém a classe Entrevista
Essa classe sera utilizada para instanciar e guardar cada Entrevista
feita pelo programa, mais as entrevistas guardadas em disco.
Os dados dessa instancia serão usados para fazer estatisticas.
'''
from datetime import date
class Entrevista():
'''Classe Entrevista'''
def __init__(self, nome = '', idade = 0, ano = 0):#precisa dos valores padrões
'''Entra com os valores iniciais, Variaveis do Sistema
nome= nome informado pelo entrevistado
ano = ano de nascimento informado pelo entrevistado
idade = é a idade calculada do entrevistado
'''
super(Entrevista, self).__init__()
self.nome = nome
self.idade = idade
self.ano_inf = ano
def pergunta_nome(self):
'''Pergunta o nome do entrevistado. Retorna uma String.'''
nome_ok = False
while nome_ok == False:
self.nome=input('Qual é o seu nome?(Digite "parar" para encerrar)')
if self.nome:
nome_ok = True
if self.nome.lower() != 'parar':
print(f'Seu nome é {self.nome}')
self.nome=self.nome.title()
return self.nome
def pergunta_idade(self):
'''
Pergunta o ano de nacimento e valida a idade.
Valida o valor entre 1900 e o ano atual, através do
date.today().year.
Se validado calcula a idade.
'''
ano_atual = date.today().year
ano_ok = False
while ano_ok == False:
try :
self.ano_inf = int(input('Ei {}, qual é o seu ano de nascimento:'.format(self.nome)))
ano_ok=True
except:
continue
else:
if self.ano_inf >= 1900 and self.ano_inf<= ano_atual:
pass
else:
ano_ok = False
self.idade=ano_atual-self.ano_inf
print(f'Sua idade é {self.idade}')
def __str__(self):
'''Retorna uma descrição amigável do objeto'''
return '{}/{}'.format(self.nome, self.idade)
def __repr__(self):
'''Retorna uma descrição precisa e unica do objeto'''
return 'input()={} input()= int({})'.format(self.nome, self.idade) | false |
c6e27c4d4212035ac6a3161db72021e4443515ab | TheNoobProgrammer22/Birthday-Recorder | /main.py | 718 | 4.34375 | 4 | dict = {}
while True:
print("------------Birthday App----------")
print("1.Show Birthday")
print("2.Add to Birthday List")
print("3.Exit")
choice = int(input("Enter the choice"))
if choice == 1:
if len(dict.keys())==0:
print("Nothing to show")
else:
name=input("Enter name to look for birthday")
birthday=dict.get(name,"No data found")
print(birthday)
elif choice == 2:
name=input("Enter Friend's Name")
date=input("Enter Birthdate")
dict[name]=date
print("Birthday Added")
elif choice == 3:
break
else:
print("Choose a valid option")
| true |
62b242b7c7a76663b380b7c8e29930db58c12149 | Muhammed-Moinuddin/Python1 | /beginner.py | 2,679 | 4.25 | 4 | a = int(input("Please enter first number: "))
b = int(input("Please enter Second number: "))
if a > b : print('{0} is the largest'.format(a))
else : print('{0} is the largest'.format(b))
#First input Positive or negative
if a > 0 : print('{0} is Positive'.format(a))
else : print('{0} is Negative'.format(a))
#First input greater or smaller than 100
if a > 100 : print('{0} is greater than 100'.format(a))
else : print ('{0} is smaller than 100'.format(a))
#First input even or odd
if a % 2 == 0 : print ('{0} is even'.format(a))
else : print ('{0} is odd'.format(a))
#First input divisible by 5 or not
if a % 5 == 0 : print ('{0} is divisible by 5'.format(a))
else : print ('{0} is not divisible by 5'.format(a))
#First input multiple of 7 or not
if a % 7 == 0 : print ('{0} is multiple of 7'.format(a))
else : print ('{0} is not multiple of 7'.format(a))
#Comparision of input
if a > b : print('{0} > {1}'.format(a,b))
elif a < b : print('{0} < {1}'.format(a,b))
else : print('{0} = {1}'.format(a,b))
#Program for grading
roll_num = int(input("Please enter roll number: "))
marks_1 = int(input("Please enter obtained marks for first subject : "))
marks_2 = int(input("Please enter obtained marks for second subject : "))
marks_3 = int(input("Please enter obtained marks for third subject : "))
total_marks = marks_1+marks_2+marks_3
avg = total_marks/3
print("Total marks:",total_marks)
print("Average:",avg)
print("RESULT:")
if avg >= 80 : print("Grade A+")
elif avg >= 70 : print("Grade A")
elif avg >= 60 : print("Grade B")
elif avg >= 50 : print("Grade c")
elif avg == 49 or avg <= 49 : print("Fail")
#Age convertor
age = int(input("Please enter Age in year: "))
months = age*12
print ('Age :{0} months old'.format(months))
days = age*365
print ('Age :{0} days old'.format(days))
#On Input providing corresponding Month
i = int(input("Please enter number of the month: "))
if i == 1 : print("January")
elif i == 2 : print("February")
elif i == 3 : print("March")
elif i == 4 : print("April")
elif i == 5 : print("May")
elif i == 6 : print("June")
elif i == 7 : print("July")
elif i == 8 : print("August")
elif i == 9 : print("September")
elif i == 10 : print("Octuber")
elif i == 11 : print("November")
elif i == 12 : print("December")
else : print("Invalid Number")
#On Single Value Input providing corresponding Month
i = int(input("Please enter number of the month: "))
if i == 1 : print("January")
elif i == 2 : print("February")
elif i == 3 : print("March")
elif i == 4 : print("April")
elif i == 5 : print("May")
elif i == 6 : print("June")
elif i == 7 : print("July")
elif i == 8 : print("August")
elif i == 9 : print("September")
else : print("Invalid Number") | true |
47c1ef429d4b92e975304a5140678a7a7bea0bac | k18a/algorithms | /classical_algorithms/sort_insertion.py | 1,718 | 4.5 | 4 | """
insertion sort
"""
def insertion_sort(array, verbose=False):
# define verboseprint function
verboseprint = print if verbose else lambda *a, **k: None
verboseprint('array to be sorted is {}'.format(array))
# iterate over unsorted array, first element is always sorted
for unsorted_index, unsorted_value in enumerate(array[1:],1):
verboseprint('currently sorting {} at index {}'.format(unsorted_value, unsorted_index))
# initialize sorted index and value at 1 less than unsorted
sorted_index = unsorted_index-1
sorted_value = array[sorted_index]
# reverse loop through sorted array until value less than unsorted value is found
while sorted_index >= 0 and unsorted_value < sorted_value :
# move value greater than unsorted value by 1 to the right
array[sorted_index + 1] = array[sorted_index]
# reinitialize sorted index and sorted value
sorted_index -= 1
sorted_value = array[sorted_index]
# place unsorted value in the sorted array
array[sorted_index + 1] = unsorted_value
verboseprint('array after {} insertions is {}'.format(unsorted_index, array))
return array
if __name__ == "__main__":
array = [12, 11, 13, 5, 6]
insertion_sort(array, verbose=True)
"""
output:
array to be sorted is [12, 11, 13, 5, 6]
currently sorting 11 at index 1
array after 1 insertions is [11, 12, 13, 5, 6]
currently sorting 13 at index 2
array after 2 insertions is [11, 12, 13, 5, 6]
currently sorting 5 at index 3
array after 3 insertions is [5, 11, 12, 13, 6]
currently sorting 6 at index 4
array after 4 insertions is [5, 6, 11, 12, 13]
""" | true |
7d3c4d3a9c5384f83bdb3468d686ec4731de7758 | k18a/algorithms | /classical_algorithms/sort_radix.py | 2,224 | 4.21875 | 4 | """"
radix sort
"""
from sort_counting import counting_sort
def radix_sort(array, verbose = False):
# get array maximum
maximum = max(array)
# initialize exponent
exponent = 1
# check if exponent is greater than max
while exponent < maximum:
# count sort array for the given exponent
counting_sort(array,inplace=True,exponent=exponent,verbose=verbose)
# multiply exponent by 10
exponent *= 10
return array
if __name__ == "__main__":
array = [170,45,90,802,24,2,66]
radix_sort(array, verbose=True)
"""
output:
array to be sorted is [170, 45, 90, 802, 24, 2, 66]
count array for exponent 1 is [2, 2, 4, 4, 5, 6, 7, 7, 7, 7]
index 6 in input array goes to index 6 in output array
index 5 in input array goes to index 3 in output array
index 4 in input array goes to index 4 in output array
index 3 in input array goes to index 2 in output array
index 2 in input array goes to index 1 in output array
index 1 in input array goes to index 5 in output array
index 0 in input array goes to index 0 in output array
sorted array is [170, 90, 802, 2, 24, 45, 66]
array to be sorted is [170, 90, 802, 2, 24, 45, 66]
count array for exponent 10 is [2, 2, 3, 3, 4, 4, 5, 6, 6, 7]
index 6 in input array goes to index 4 in output array
index 5 in input array goes to index 3 in output array
index 4 in input array goes to index 2 in output array
index 3 in input array goes to index 1 in output array
index 2 in input array goes to index 0 in output array
index 1 in input array goes to index 6 in output array
index 0 in input array goes to index 5 in output array
sorted array is [802, 2, 24, 45, 66, 170, 90]
array to be sorted is [802, 2, 24, 45, 66, 170, 90]
count array for exponent 100 is [5, 6, 6, 6, 6, 6, 6, 6, 7, 7]
index 6 in input array goes to index 4 in output array
index 5 in input array goes to index 5 in output array
index 4 in input array goes to index 3 in output array
index 3 in input array goes to index 2 in output array
index 2 in input array goes to index 1 in output array
index 1 in input array goes to index 0 in output array
index 0 in input array goes to index 6 in output array
sorted array is [2, 24, 45, 66, 90, 170, 802]
""" | true |
917637e7e8823fbcf0d920386dd405dbed14843a | delta94/Code_signal- | /Arcade/Intro/Smooth Sailing/commonCharacterCount.py | 498 | 4.3125 | 4 | """"
Given two strings, find the number of common characters between them.
Example
For s1 = "aabcc" and s2 = "adcaa", the output should be
commonCharacterCount(s1, s2) = 3.
Strings have 3 common characters - 2 "a"s and 1 "c".
""""
def commonCharacterCount(s1, s2):
count = 0
for ch1 in s1 :
line = s2[:]
for ch2 in line :
if ch1 == ch2:
s2 = s2.replace(ch2,'',1)
count += 1
break
return count
| true |
26b8671c5e2844257179cf441f1152ac658d3d33 | delta94/Code_signal- | /Arcade/Intro/Dark Wilderness/digitDegree.py | 676 | 4.25 | 4 | """
Let's define digit degree of some positive integer as the number of times we need to replace this number with the sum of its digits until we get to a one digit number.
Given an integer, find its digit degree.
Example
For n = 5, the output should be
digitDegree(n) = 0;
For n = 100, the output should be
digitDegree(n) = 1.
1 + 0 + 0 = 1.
For n = 91, the output should be
digitDegree(n) = 2.
9 + 1 = 10 -> 1 + 0 = 1.
"""
def digitSum(num):
return sum([int(char) for char in str(num)])
def digitDegree(n):
if n/10 ==0:
return 0
counter = 0
while int(n/10) != 0:
n = digitSum(n)
counter +=1
return counter
| true |
09c38e6dd37874bf0abaaec9b37c8cf37cc9c56c | delta94/Code_signal- | /Arcade/Intro/Dark Wilderness/bishopAndPawn.py | 659 | 4.21875 | 4 | """
Given the positions of a white bishop and a black pawn on the standard chess board, determine whether the bishop can capture the pawn in one move.
The bishop has no restrictions in distance for each move, but is limited to diagonal movement. Check out the example below to see how it can move:
https://codesignal.s3.amazonaws.com/tasks/bishopAndPawn/img/bishop.jpg?_tm=1551432802825
Example
For bishop = "a1" and pawn = "c3", the output should be
bishopAndPawn(bishop, pawn) = true.
"""
def bishopAndPawn(bishop, pawn):
if (abs(ord(bishop[0]) - ord(pawn[0])) == abs(ord(bishop[1]) - ord(pawn[1]))):
return True
return False
| true |
81b52cb363dea20d99e8fcf563ef763b8510df13 | delta94/Code_signal- | /Arcade/Intro/Erruption of light/mac48Address.py | 1,239 | 4.71875 | 5 | """
A media access control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment.
The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits (0 to 9 or A to F), separated by hyphens (e.g. 01-23-45-67-89-AB).
Your task is to check by given string inputString whether it corresponds to MAC-48 address or not.
Example
For inputString = "00-1B-63-84-45-E6", the output should be
isMAC48Address(inputString) = true;
For inputString = "Z1-1B-63-84-45-E6", the output should be
isMAC48Address(inputString) = false;
For inputString = "not a MAC-48 address", the output should be
isMAC48Address(inputString) = false.
"""
def isMAC48Address(inputString):
st = inputString.split('-')
if len(inputString)!=17:
return False
for i in range(6):
if len(st[i])!=2:
return False
else :
if ((ord(st[i][0]) in range(48,59)) or (ord(st[i][0]) in range(ord('A'), ord('F')+1))) and ((ord(st[i][1]) in range(48,59)) or (ord(st[i][1]) in range(ord('A'), ord('F')+1))):
pass
else:
return False
return True
| true |
31d79443971ae591803b9bdefe61e8dc8c6fc129 | delta94/Code_signal- | /Arcade/The core/Intro Gates/3. LargestNumber.py | 325 | 4.15625 | 4 | """
Given an integer n, return the largest number that contains exactly n digits.
Example
For n = 2, the output should be
largestNumber(n) = 99.
"""
def largestNumber(n):
p = 0
for i in range(n):
if i != n-1:
p += 9*(10**(n-i-1))
if i == n-1:
p +=9
return p
| true |
1789d3e8b1376870bfe428e08381b26ce1b8fb21 | nervig/Starting_Out_With_Python | /Chapter_2_programming_tasks/task_7.py | 323 | 4.21875 | 4 | #!/usr/bin/python
covered_destination = float(input("Enter the covered destination: "))
fuel_consumption_in_liters = float(input("Enter the fuel consumption in liters: "))
fuel_consumption =float(fuel_consumption_in_liters / covered_destination)
print("The fuel consumption of your car equals {}".format(fuel_consumption))
| true |
c596d5d929c58dc817516001ab4d759fd670b4ab | nervig/Starting_Out_With_Python | /Chapter_5_programming_tasks/task_1.py | 280 | 4.125 | 4 | def main():
distance = float(input("Enter a distance in kilometer: "))
distance_in_mile = kilometer_to_mile(distance)
print("The distance in miles equals %f" % float(format(distance_in_mile, '.2f')))
def kilometer_to_mile(number):
return number * 0.6214
main() | false |
75d9f72c5c9b9a6108ba02b6fc63e6ef047058aa | nervig/Starting_Out_With_Python | /Chapter_6_programming_tasks/record_students_list.py | 759 | 4.25 | 4 | # creating a file and adding some records
def main():
# create a variable for manage of cycle
the_flag = 'y'
# open the students.txt file in adding mode
adding_students = open("students.txt", "a")
while the_flag == 'y' or the_flag == 'Y':
print("Enter an information are students about: ")
name_student = input("Name of student: ")
score_student = int(input("Enter a score of student: "))
# add data to file
adding_students.write(name_student + '\n')
adding_students.write(str(score_student) + '\n')
print("Do you want to add else data? 'y' if yes, 'n' if not: ")
the_flag = input()
# close the file
adding_students.close()
print("The data are added")
main()
| true |
4e3c43805358f8cd12750a3ceb93535032198f90 | DarishkaAMS/Py_Bootcamp_Task-COAX_Tryout | /question1_reversed_string.py | 494 | 4.21875 | 4 | #direct reversing
s = "string"
print(s[::-1])
#using length and slicing
s = "string"
reversed_s = s[len(s)::-1]
print (reversed_s)
#using function call
s = "string"
def reversing_function(x):
return x[::-1]
print(reversing_function(s))
#using join and reversed
s = "string"
s_reversed=''.join(reversed(s))
print(s_reversed)
#using while loop and length
s = "string"
reversed_s = ""
coef_s = len(s)
while coef_s > 0:
reversed_s += s[coef_s - 1]
coef_s -= 1
print(reversed_s) | true |
13c7e0cb44617fb8603a0bf69323009f1f69bc39 | kanhaichun/ICS4U | /hhh/Alice/area caculation.py | 2,177 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 15 13:27:35 2018
Program:Area Caculation
purpose:
(1) Find the area under y = sin(x) from x=0 to x = PI.
(2) Find the area under y = 2^x from x = 1 to x = 10
(3) Find the area under a curve of your choice on a range of your choice.
@author: haichunkan
"""
n = 1000000 #This is the number of rectangles
Area = [0.0,0.0,0.0] #This is the total area
#Name: Alice
#Date: January 15, 2018
#Program Title: Area Calculator
#Program Function: This program calcuates the area under curves (mathematical functions)
from math import *
def calculateCurveAreaf():
#Variables:
a = 1.0 #This is the starting x value
b = 5.0 #This is the ending x value
#This is the function to use in the area calculation
def f(x):
return x*x
for i in range(1,n+1):
#Find xi, the current x value
xi = a+i*(b-a)/n
#Find the area of the rectangle, Ai, using the function
Aif = f(xi)*(b-a)/n
#Add it to the total area, "Area"
Area[0] +=Aif
#Print the area here
print("The curve area for f(x) from a to b is",Area[0])
def calculateCurveAreag():
#Variables:
a = 0.0 #This is the starting x value
b = pi #This is the ending x value
def g(x):
return sin(x)
for i in range(1,n+1):
#Find xi, the current x value
xi = a+i*(b-a)/n
#Find the area of the rectangle, Ai, using the function
Aig = g(xi)*(b-a)/n
#Add it to the total area, "Area"
Area[1] +=Aig
#Print the area here
print("The curve area for g(x) from a to b is",Area[1])
def calculateCurveAreah():
#Variables:
a = 1.0 #This is the starting x value
b = 10.0 #This is the ending x value
def h(x):
return 2**x
for i in range(1,n+1):
#Find xi, the current x value
xi = a+i*(b-a)/n
#Find the area of the rectangle, Ai, using the function
Aih = h(xi)*(b-a)/n
#Add it to the total area, "Area"
Area[2] +=Aih
#Print the area here
print("The curve area for g(x) from a to b is",Area[2])
#Run the program.
calculateCurveAreaf()
calculateCurveAreag()
calculateCurveAreah() | true |
221a34394fc4b1e0b84c55ba7ce76f2796a3d57c | kanhaichun/ICS4U | /Toxicbug/Tony/area calculator.py | 1,482 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 16 02:25:04 2018
@author: 11256
"""
#Name: Tony
#Date: January 15, 2018
#Program Title: Area Calculator
#Program Function: This program calcuates the area under curves (mathematical functions)
from math import *
#Variables:
x = 0.0 #This is the starting x value
x1 = 3.1 #This is the ending x value
n = 1000000 #This is the number of rectangles
Area = 0.0 #This is the total area
#This is the function to use in the area calculation
def f(x):
return (sin(x))
for i in range(1,n+1):
#Find xi, the current x value
xi = (x+((x1-x)/n)*i)
#Find the area of the rectangle, Ai, using the function
Ai = (x+((x1-x)/n)*i)*((x1-x)/n)
#Add it to the total area, "Area"
Area += Ai
print (Area)
#Print the area here
a = 1.0
b = 10.0
n = 1000000
Area = 0.0
def f(a):
return (2**a)
for i in range(1,n+1):
#Find xi, the current x value
xi = (a+((b-a)/n)*i)
#Find the area of the rectangle, Ai, using the function
Ai = (a+((b-a)/n)*i)*((b-a)/n)
#Add it to the total area, "Area"
Area += Ai
print (Area)
a = 5.0
b = 10.0
n = 1000000
Area = 0.0
def f(a):
return (2**a*2)
for i in range(1,n+1):
#Find xi, the current x value
xi = (a+((b-a)/n)*i)
#Find the area of the rectangle, Ai, using the function
Ai = (a+((b-a)/n)*i)*((b-a)/n)
#Add it to the total area, "Area"
Area += Ai
print (Area)
| true |
5d4b9f87dc3c6f40d962c569eb6bc5cd2c77ddca | kanhaichun/ICS4U | /hhh/Angel/assignment9.py | 2,969 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 5 12:40:11 2018
@author: hailankan
(1) Create two functions: prime1(n) and prime2(n) that take a number that represents the set of integers from which to find prime numbers. For example, n=1000 specifies that the function will look for primes up to 1000.
(2) Find out how to measure elapsed time in Python
(3) Write a program that determines the amount of time taken to find primes up to the following values: n=[10000,20000,30000,40000,50000]
(4) Output of the program:
First algorithm:
n time
10000 2.23
20000 4.67
30000 7.88
40000 11.34
50000 14.44
Second algorithm:
n time
10000 2.23
20000 14.67
30000 117.88
40000 211.34
50000 11214.44
(5) Bonus: Have Python graph the results using pyplot / matplotlib
Title: find primes
"""
import matplotlib.pyplot as plt
import time
n=[10000,20000,30000,40000,50000,100000,150000]
def FirAl():
totalTime1=[]
print('First algorithm:')
print('n time')
for item in n:#loop for each value in the n list
start_time = time.time()
prime=[2]
for i in range(3,item):
for j in prime:
if i % j == 0:
break#stop for multiples
if j == prime[-1]:
prime.append(i)#append primes
elapsed_time = time.time() - start_time
totalTime1.append(elapsed_time)
print(item, elapsed_time)
plt.plot(n,totalTime1)
#add title
plt.title('Algorithm1')
#add x and y labels
plt.xlabel('n')
plt.ylabel('time')
plt.show()
def SecAl():
totalTime2=[]
print('Second algorithm:')
print('n time')
for item in n:
start_time = time.time()
prime = [2]
for i in range(3,item):
for j in range(0,len(prime)):
if i % prime[j]== 0:
break
if j == len(prime)-1:
prime.append(i)
elapsed_time = time.time() - start_time#measure the time
totalTime2.append(elapsed_time)
print(item, elapsed_time)#print time used
plt.plot(n,totalTime2)
plt.title('Algorithm2')
plt.xlabel('n')
plt.ylabel('time')
plt.show()
def ThiAl():
totalTime3=[]
print('Third algorithm:')
print('n time')
for item in n:
start_time = time.time()
prime=[]
number=[]
for i in range(2,item):
number.append(i)
for j in range(0,len(number)):
j = i
while j < len(number):
if j > i:
number[j] = 0
j+=i
for i in range(2,len(number)):
if number[i]!=0:
prime.append(i)
elapsed_time = time.time() - start_time
totalTime3.append(elapsed_time)
print(item, elapsed_time)
plt.plot(n,totalTime3)
plt.title('Algorithm2')
plt.xlabel('n')
plt.ylabel('time')
plt.show()
FirAl()
SecAl()
ThiAl()
| true |
48bbcc29f747463ca19a87de64d90f71f8791d63 | kanhaichun/ICS4U | /hhh/Angel/assignment4.py | 1,540 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''Name: Angel Kan
Date: January 15, 2018
Program Title: Area Calculator
Program Function: This program calcuates the area under curves (mathematical functions)'''
from math import *
#Variables:
a = 0.0 #This is the starting x value
b = pi #This is the ending x value
n = 1000000 #This is the number of rectangles
Area = 0.0 #This is the total area
#This is the function to use in the area calculation
def f(x):
return sin(x)
for i in range(1,n+1):
#Find xi, the current x value
xi = a + (b - a)/ n * i
#Find the area of the rectangle, Ai, using the function
Ai = (b - a)/ n * f(xi)
#Add it to the total area, "Area"
Area += Ai
print(Area)
a = 1.0 #starting value
b = 10.0 #ending value
def g(x):
return 2**x
for i in range(1,n+1):
xi = a + (b - a)/ n * i
Ai = (b - a)/ n * g(xi)
Area += Ai
print(Area)
a = 0.0 #starting value
b = 100.0 #ending value
def h(x):
return x**x
for i in range(1,n+1):
xi = a + (b - a)/ n * i
Ai = (b - a)/ n * h(xi)
Area += Ai
print(Area)
#try to simplify
def f1(x):
return x
def f2(x):
return sin(x)
def f3(x):
return 2**x
function=[f1,f2,f3]#put all functions in a list
def AreaCalculator(a,b,j):
Area=0.0
n=100000
for i in range(1,n+1):
xi = a + (b - a)/ n * i
Ai = (b - a)/ n * function[j](xi)
Area += Ai
print(Area)
AreaCalculator(1.0,2.0,0)
AreaCalculator(0.0,pi,1)
AreaCalculator(1.0,10.0,2) | true |
5daf8a269117a751e02d890c590b5c91bed7ec89 | kanhaichun/ICS4U | /Shutupandbounce/Aurora/aurora2.py | 1,062 | 4.125 | 4 | ucn#(a)assignment2
"""
Write a program that does the following:
(a) Let the user input two numbers.
(b) Convert the numbers to integers
(c) Print the sum, difference, product and quotient of the numbers.
(d) Repeat (b) and (c) for floating point
(e) Convert the numbers to strings.
(f) Output the four results as strings as follows: The sum of a and b is 5.667, etc. for subtraction, multiplication and division.
"""
# 2018/01/11,Aurora Hou
#mixedCase variable names
woW = (input("please input a number: "))
xxX = (input("please input another number: "))
woW = int(woW)
xxX = int(xxX)
print(woW + xxX)
print(woW - xxX)
print(woW * xxX)
print(woW / xxX)
woW = float(woW)
xxX = float(xxX)
print(woW + xxX)
print(woW - xxX)
print(woW * xxX)
print(woW / xxX)
string1 = str(woW + xxX)
string2 = str(woW - xxX)
string3 = str(woW * xxX)
string4 = str(woW / xxX)
print("The sum of two numbers is "+string1+".")
print("The difference of two numbers is "+string2+".")
print("The product of two numbers is "+string3+".")
print("The quotient of two numbers is "+string4+".")
| true |
a064f2589130b5f59dd4cc65cc7283e5d8ad6cfa | kanhaichun/ICS4U | /hhh/Mark/assignment9.py | 1,993 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Name: Song, Jiwei (Mark)
Date: 2018-02-06
Program Title: Benchmarking Algorithms
Purpose:
(1) Create two functions: prime1(n) and prime2(n) that take a number that represents the set of integers from which to find prime numbers. For example, n=1000 specifies that the function will look for primes up to 1000.
(2) Find out how to measure elapsed time in Python
(3) Write a program that determines the amount of time taken to find primes up to the following values: n=[10000,20000,30000,40000,50000]
(4) Output of the program:
First algorithm:
n time
10000 2.23
20000 4.67
30000 7.88
40000 11.34
50000 14.44
Second algorithm:
n time
10000 2.23
20000 14.67
30000 117.88
40000 211.34
50000 11214.44
(5) Bonus: Have Python graph the results using pyplot / matplotlib
"""
import time
n=[10000,20000,30000,40000,50000]
a1times = []
a2times = []
for x in range (0,5):
print(n[x])
start1 = time.time()
prime1 = [1]*(n[x]+1)
for i in range(2,len(prime1)):
j = i
while j < len(prime1):
if j>i:
prime1[j]=0
j+=i
for i in range(2,len(prime1)):
if prime1[i] != 0:
print(i)
end1 = time.time()
elapsed1 = end1 - start1
a1times.append(elapsed1)
start2 = time.time()
prime2 = [2]
maxj = 2
for i in range(3,n[x]+1):
isPrime = True
for j in prime2:
if i % j == 0:
isPrime = False
if isPrime == True:
prime2.append(i)
print(prime2)
end2= time.time()
elapsed2 = end2 - start2
a2times.append(elapsed2)
print()
print('First Algorithm time(n=[10000,20000,30000,40000,50000]):')
for k in range (0,5):
print(str(n[k])+' '+str(a1times[k]))
print()
print('Second Algorithm time(n=[10000,20000,30000,40000,50000]):')
for k in range (0,5):
print(str(n[k])+' '+str(a2times[k]))
| true |
f091b967c81053bbe74c5c97bf464a8d25db7a38 | kanhaichun/ICS4U | /FRC/intro.py | 813 | 4.125 | 4 | #This file is to introduce the basics of Python.
from math import *
from random import *
#a and b are integer variables
a = 5
b = 6
#numeric variables like integers can be used in
#arithmetic expressions
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(sin(a/b)+cos(b*a))
print(sqrt(b))
print(b**a)
#friends is a text variable in the form of a list
friends = ["Joe", "Ted", "Sue", "Wendy", "Gina", "Fred"]
friends.append("George")
print(friends)
print(friends[0])
print(friends[1])
#We can use a loop to repeat similar operations.
for i in range(0, 7):
print(i, friends[i])
for i in range(0,100):
n1 = int(6*random()+1)
n2 = int(6*random()+1)
n3 = n1+n2
if n3 == 12:
print("Winner!")
else:
print("Try again!")
print(n1,n2,n3)
n = 0
print(n)
while n < 1000000:
n = 3*(n+1)
print(n)
| true |
31f54338963c78716d330fa64f177b69e02077da | kanhaichun/ICS4U | /hhh/Chris/Assignment 12.py | 1,525 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
Assignment 12 - Recursive Algorithms - Towers of Hanoi
Coding convention:
(a) lower case file name
(b) Name, Date, Title, Purpose in multiline comment at the beginning
(c) mixedCase variable names
(1) Create a class with functions for three recursive algorithms.
Include factorials, the Towers of Hanoi and any other recursive
function. Allow the user to choose any of the three functions
and then interact with the function. The program should provide
adequate instructions and output to be useful.
"""
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))
def hanoi(n, source, helper, target):
if n > 0:
# move tower of size n - 1 to helper:
hanoi(n - 1, source, target, helper)
# move disk from source peg to target peg
if source:
target.append(source.pop())
# move tower of size n-1 from helper to target
hanoi(n - 1, helper, source, target)
source = [4,3,2,1]
target = []
helper = []
hanoi(len(source),source,helper,target)
print(source, helper, target)
def fib(n):#The Fibonacci numbers are defined by:
#Fn = Fn-1 + Fn-2
#with F0 = 0 and F1 = 1
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
n=int(input("input a number to compute the fibonacci:"))
print(fib(n)) | true |
fb7b68c1f50ff3c5dfb13828c78920f607ef0852 | kanhaichun/ICS4U | /Ivy232/Lily/A6Jan19.py | 1,909 | 4.125 | 4 | '''
Assignment 6 - Program in a Class
Coding convention:
(a) assignment6
(b) Lily, Jan.18th 2018, Title, Purpose in multiline comment at the beginning
(c) mixedCase variable names
Option A - Make a more complete quiz program using a class structure
(a) Have the program ask for the user's name.
(b) Record the results of each quiz in a file. The results should include the user's name, the score on the quiz and the percentage achieved. The name of each file should be as follows: QuizyyyymmddhhmmssAB.txt where:
yyyymmdd is the current date. January 16 would be 20180116 for example
hhmmss is the current hour, minute and time.
A and B are the first and last initials of the user.
Option B - Write the Stock Ticker program in a class structure.
(a) Store the results of each game in a file. The results should include the date and time, the names of each player and the total networth achieved at the end. The players should be listed in the order of their networth. The name of each file should be as follows: STyyyymmddhhmmss.txt where:
yyyymmdd is the current date. January 16 would be 20180116 for example
hhmmss is the current hour, minute and time.
'''
import time
filename = "quiz"+str(time.strftime("%Y%m%d%H%M%S")) + ".txt"
name = (input("what is your name?"))
print(name)
question={"Are you happy?":"yes!","How r u today?":"good!", "Want to chat?":"of course!","I am sad...":"chins up!","What's the weather?":"sunny!"}
key1=list(question.keys())
value1=list(question.values())
score = 0
i = 0
for i in range (0,len(key1)):
questionprint = key1[i]
print (questionprint)
answer = input("")
answerprint = value1[i]
if answer == answerprint:
score = score +1
stringName = str(score) + " " + str(score/5 * 100) + "%"
myfile = open(filename, 'w')
myfile.write(stringName)
myfile.close()
| true |
6e5fc847fa9f80fb1634a70803b7df650d930d93 | kanhaichun/ICS4U | /Toxicbug/Jeffrey/assignment1Jeffrey.py | 428 | 4.25 | 4 | """
Author: Jeffrey
Date: 10th January 2018
Title: division
Function: Loop through 1000 numbers, and find the numbers that are divisible by 3 or 19.
"""
#loop from 0 to 1000:
for number in range(0,1000):
if number%3 == 0: #find the number that is divisible by 3
print(number, "is divisible by 3.")
elif number%19 == 0: #find the number that is divisible by 19
print(number, "is multiple of 19.")
| true |
890607721b60fc8994c44f9719116c96ca1d6def | mail2vels/VelsPythonCode | /2ndlargenumber.py | 1,045 | 4.5625 | 5 | print '''
1. Write a program to implement a method which takes a list as an argument and returns second largest number.
read from standard input and write to standard output.
'''
print "Option 1"
print "========="
print "To find Out Second Largest Number Using Array Sort"
print '---------------------------------------------------'
numbers=[1,4,3,6,5]
print "\nArray Values is = " + str(numbers)
numbers.sort()
print "\nAfter Sorting the Array Value is = " +str(numbers)
print "\nThe Second Largest Number is = " + str(numbers[-2])
numbers.sort(reverse=True)
print "\nAfter Reverse Sorting the Array Value is = " +str(numbers)
print "\nThe Second Largest Number is = " + str(numbers[1]) + "\n"
print "Option 2"
print "========"
print "To find Out Second Largest Number without Array Sort"
print '-----------------------------------------------------'
numbers=[6,4,3,3,8,-6]
print "\nArray Values is = " + str(numbers)
SLN = max(n for n in numbers if n!=max(numbers))
print "\nThe Second Largest Number is = " + str(SLN) + "\n"
| true |
1e116bc82ab891199eba6a54aead90d5fbc383ff | parkjuj/E02a-Control-Structures | /main10.py | 2,213 | 4.28125 | 4 | #!/usr/bin/env python3
import sys, random
assert sys.version_info >= (3,7), "This script requires at least Python 3.7"
print('Greetings!') # prints greetings!
colors = ['red','orange','yellow','green','blue','violet','purple'] # defines what colors are
play_again = '' # defines what the play_again variable is
best_count = sys.maxsize # defines the best_count variable # the biggest number
while (play_again != 'n' and play_again != 'no'): # begins the code with a while statment that all else will fall under
match_color = random.choice(colors) # picks a color from the set randomly
count = 0 # sets variable count to 0
color = '' # defines variable color
while (color != match_color):
color = input("\nWhat is my favorite color? ") # prompts the player on a new line to answer the query #\n is a special code that adds a new line
color = color.lower().strip() #pulls the player's input from the area where the answer is typed
count += 1 # adds 1 to the count for each guess
if (color == match_color): # determines what the correct answer is based off of the color randomly picked
print('Correct!') # prints correct if the player was correct
else: # begins else statement
print('Sorry, try again. You have guessed {guesses} times.'.format(guesses=count)) # tells the player they were incorrect, as well as defines the variable guesses as the count
print('\nYou guessed it in {} tries!'.format(count)) # tells the player that they were correct and displays the amount of guesses
if (count < best_count): # if statement saying if the count was lower than best_count variable to begin an action
print('This was your best guess so far!') # prints that this was the best guess so far if aforementioned count was lower than best_count
best_count = count # defines best_count once again as the new best_count IF the player had their best count so far
play_again = input("\nWould you like to play again (yes or no)? ").lower().strip() # asks the player if they would like to play again, resets or does not based on input
print('Thanks for playing!') # standard goodbye message, terminates | true |
97a2447fd0651a89a16a57a352c71bfe6e2cb56d | Swathi-Swaminathan/Swathi-Swaminathan | /allprograms/uppercase for first and last letter in a string.py | 227 | 4.25 | 4 | #Python program to display the first and last letter in a string in capital letters
a=input("Enter the String:")
a1=a.title()
w=a1.split()
r=""
for i in w:
r=r+i[:-1]+i[-1].upper()+" "
print("New string:",r[:-1])
| false |
dbcf0f68a0fb99dd1ef6c1e4a96551b79d06a9d3 | MaryemHaytham/AITasks | /task4.py | 390 | 4.21875 | 4 | #task4
num1 = float(input("Enter your first number : "))
num2 = float(input("Enter your second number : "))
operator = input("please Enter your operator : ")
if operator == "+":
print (num1 + num2)
elif operator == "-":
print (num1 - num2)
elif operator == "/":
print (num1 / num2)
elif operator == "*":
print (num1 * num2)
else:
print("please enter correct operator")
| false |
2125a79698aa524b6fb99b27de5dcaad490d8667 | LeoDemon/pythonlab | /PythonNow/src/Person.py | 1,867 | 4.71875 | 5 | # filename: Persion.py
# learning python class
class Person:
'''Represents a person'''
population = 0
def __init__(self, name):
'''Initializes the person's data'''
self.name = name
print 'Initializing %s...' % self.name
# When this person is created, he/she adds to the population
Person.population += 1
def __delete__(self):
'''Erase this person'''
print '%s says bye-bye...' % self.name
Person.population -= 1
if Person.population == 0:
print 'I am the last one...'
else:
print 'There are still %d people left...' % Person.population
def sayHi(self):
'''Greeting by the person.
Really, that's all it does.'''
print 'Hi, my name is %s...' % self.name
def howMany(self):
'''Prints the current population'''
if Person.population == 1:
print 'I am the only person here...'
else:
print 'We have %d persons here...' % Person.population
if __name__ == '__main__':
Leo = Person('LeoDemon')
Leo.sayHi()
Leo.howMany()
print 'Leo\'s information:(%s,%s)...' % (Leo.name, Leo.population)
print '-----------------separation line--------------------'
Kinly = Person('Kinly')
Kinly.sayHi()
Kinly.howMany()
print 'Kinly\'s information:(%s,%s)...' % (Kinly.name, Kinly.population)
print '-----------------separation line--------------------'
Jack = Person('Jack')
Jack.sayHi()
Jack.howMany()
print 'Jack\'s information:(%s,%s)...' % (Jack.name, Jack.population)
print '-----------------separation line--------------------'
Kinly.__delete__()
Kinly.howMany()
else:
print 'being imported by another module...'
| true |
bbe1256760868f9de36b8bd7c1e4ab0f5622051b | lperri/CTCI-Practice-Problems | /chVI_bigO/examples/ex_10.py | 983 | 4.375 | 4 | # check if a number is prime by checking for divisibility on numbers less than it.
# only need to go up to SQRT(n) because if n is divisble by a number greater than its SQRT,
# then it is divisible by something smaller than it.
from math import sqrt
def is_prime(n: int) -> bool:
''' Use while loop '''
x = 2
while x <= sqrt(n):
if n % x == 0:
return False
x += 1
return True
# def is_prime(n: int) -> bool:
# '''
# Use for loop:
# key #1 is to convert sqrt(n) to int -- if prime, won't be an int!
# key #2 is to make sure to +1 to the end of the range, otherwise
# range(2,2) if n=4 => returns True, wrong!
# '''
# for x in range(2, int(sqrt(n))+1):
# print('x: ', x)
# if n % x == 0:
# return False
# return True
print(is_prime(4))
print('4: ', is_prime(4))
print('7: ', is_prime(7))
print('36: ', is_prime(36))
print('17: ', is_prime(17))
# time complexity: O(SQRT(n)) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.