blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ce4f654a997c0416526e5ff5c182f8cfdc3c4bce | bekzod886/Python_darslari | /dictianary/maxsusMasala2.py | 546 | 4.125 | 4 | person1yoshi = int(input("Person1: "))
person2yoshi = int(input("Person2: "))
person1 = {
"name": "John",
"father": "Bill",
"mother": "Anna",
"married": 0
}
person2 = {
"name": "Kate",
"father": "Pet",
"mother": "Maria",
"married": 0
}
person3 = {}
person1["married"]=person1yoshi
person2["married"]=person2yoshi
print(person1)
print(person2)
if person1["married"]==person2["married"]:
person3.update({"name":"Dote","father":"John","mother":"Kate"})
print(person3)
else:
print("Ular turmush qurmagan")
| false |
784bb535d6c61d3c472a9c97e28036ce90ccc571 | diamondsky/Python-Programs | /format_output.py | 812 | 4.25 | 4 | #format_output.py
def main():
temperature_str = input("Enter the temperature: ")
temperature = float(temperature_str)
count = int(input("Enter the number of students: "))
print("The temperature is " + str(temperature))
print("The number of students is " + str(count))
print("Students = " + format(count, '5d'))
print("Temperature = " + format(temperature, '7.2f'))
print("Temperature = " + format(temperature, '5.3e') + \
" count = " + format(count, '2d'))
print("The number of students is {0:5d}".format(count))
print("The number of students is {:5d}".format(count))
print("Students is {0:5d}, Temperature is {1:7.2f}"\
.format(count, temperature))
print("Temperature = {1:5.3f} count = {0:0d}"\
.format(count,temperature))
main()
| true |
cf89bd90db0f7c22dbde753c825c6f25c80dcca5 | YManjunath/Python | /Guess-Number-Challenge-12/main.py | 1,196 | 4.15625 | 4 | from random import randint
from art import logo
print(logo)
easy_level = 10
hard_level = 5
# Checking the user guess against the answer
def check_answer(guess,answer,turns):
"""Checks the guess against answer and returns the remaining attempts """
if guess > answer:
print("Too high")
return turns -1
elif guess < answer:
print("Too low")
return turns -1
else:
print(f"You got it, the answer was {answer}")
# set the difficulty level
def dif_level():
dif = input("Choose a dificulty level, Type 'easy' or 'hard': ")
if dif == 'easy':
return easy_level
else:
return hard_level
def game():
print("Welcome to the number guessing game!")
print("I'm thinking of a number between 1 and 100")
# Choosing a number between 1 and 100
answer = randint(1,101)
turns = dif_level()
guess = 0
while guess != answer:
print(f"You have {turns} attempts remaining to guess a number")
# Let the user guess the number
guess = int(input("Make a guess : "))
turns = check_answer(guess,answer,turns)
if turns == 0:
print("You lost your attempts you lose!")
return
elif guess != answer:
print("Guess again")
game() | true |
58cdc9bdd0450221daa56633e2d55811a4ebc0ef | novinary/Data-Structures | /heap/max_heap.py | 2,664 | 4.125 | 4 | '''
In a max heap, each child node is less than or equal to parent node
'''
class Heap:
def __init__(self):
self.storage = []
# insert adds the input value into the heap; this method should ensure that the inserted value is in the correct spot in the heap
def insert(self, value):
self.storage.append(value)
self._bubble_up(len(self.storage) - 1)
print(self.storage)
# delete removes and returns the 'topmost' value from the heap; this method needs to ensure that the heap property is maintained after the topmost element has bee
def delete(self):
deleted_value = self.storage[0]
self.storage[0] = self.storage[len(self.storage)-1]
self.storage.pop(len(self.storage)-1)
if len(self.storage) > 0:
self._sift_down(0)
return deleted_value
# get_max returns the maximum value in the heap in constant time.
def get_max(self):
return self.storage[0]
# get_size returns the number of elements stored in the heap.
def get_size(self):
return len(self.storage)
# _bubble_up moves the element at the specified index "up" the heap by swapping it with its parent
# if the parent's value is less than the value at the specified index.
def _bubble_up(self, index):
# in worst case elem will need to make way to top of heap
while index > 0:
# get parent elem of this index
parent = (index - 1) // 2
# check if elem at index is higher priority than parent elem
if self.storage[index] > self.storage[parent]:
# if it is then swap them
self.storage[index], self.storage[parent] = self.storage[parent], self.storage[index]
# update index to be new spot that swapped elem now resides at
index = parent
else:
# otherwise, our elem is at a valid spot in the heap
# we no longer need to bubble up
break
# _sift_down grabs the indices of this element's children and determines which child has a larger value.
# If the larger child's value is larger than the parent's value, the child element is swapped with the parent.
def _sift_down(self, index):
while index * 2 + 1 <= len(self.storage) - 1:
if index * 2 + 2 > len(self.storage) - 1:
biggest_child = index * 2 + 1
else:
biggest_child = index * 2 + \
1 if self.storage[index * 2 +
1] > self.storage[index * 2 + 2] else index * 2 + 2
if self.storage[index] < self.storage[biggest_child]:
self.storage[index], self.storage[biggest_child] = self.storage[biggest_child], self.storage[index]
index = biggest_child
| true |
ec4c173b29ecab6b394c40b8be77aed312b7d083 | raja21068/Machine-Learning-Toturials | /49_Multiclass_Logistic_Regression.py | 2,155 | 4.40625 | 4 | #Logistic regression can also be used to predict the dependent or target variable with
#multiclass. Let’s learn multiclass prediction with iris dataset, one of the best-known
#databases to be found in the pattern recognition literature. The dataset contains 3 classes
#of 50 instances each, where each class refers to a type of iris plant. This comes as part
#of the scikit-learn datasets, where the third column represents the petal length, and the
#fourth column the petal width of the flower samples. The classes are already converted to
#integer labels where 0=Iris-Setosa, 1=Iris-Versicolor, 2=Iris-Virginica.
from sklearn import datasets
import numpy as np
import pandas as pd
iris = datasets.load_iris()
X = iris.data
y = iris.target
print('Class labels:', np.unique(y))
#Normalize Data
#The unit of measurement might differ so let’s normalize the data before building the model
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
sc.fit(X)
X = sc.transform(X)
#Split data into train and test. Whenever we are using random function it’s advised to use a
#seed to ensure the reproducibility of the results
# split data into train and test
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,random_state=0)
#train logistic regression model traning and evloution
from sklearn.linear_model import LogisticRegression
# l1 regularization gives better results
lr = LogisticRegression(penalty='l1', C=10, random_state=0)
lr.fit(X_train, y_train)
from sklearn import metrics
# generate evaluation metrics
print ("Train - Accuracy :", metrics.accuracy_score(y_train, lr.predict(X_train)))
print ("Train - Confusion matrix :",metrics.confusion_matrix(y_train,lr.predict(X_train)))
print ("Train - classification report :", metrics.classification_report(y_train, lr.predict(X_train)))
print ("Test - Accuracy :", metrics.accuracy_score(y_test, lr.predict(X_test)))
print ("Test - Confusion matrix :",metrics.confusion_matrix(y_test,lr.predict(X_test)))
print ("Test - classification report :", metrics.classification_report(y_test, lr.predict(X_test)))
| true |
b654aaf835cb1328ba2ef9907278663be0bb8f0e | JDanielHarvey/cms_tutorials | /Python_SQLite_Tutorial.py | 1,769 | 4.75 | 5 | """
Python SQLite Tutorial: Complete Overview - Creating a Database, Table, and Running Queries
https://www.youtube.com/watch?v=pd-0G0MigUA&t=37s
"""
import sqlite3
# conn_mem = sqlite3.connect(':memory:')
conn = sqlite3.connect('employee.db')
c = conn.cursor()
# c.execute("""CREATE TABLE employees (
# first_name text,
# last_name text,
# pay integer
# )""")
# c.execute("INSERT INTO employees VALUES ('Diane', 'McCabe', 50000)")
# employees = [('Rebecca', 'Winter', 70000),('John', 'Marsh', 1000000)]
# def insert_employees(first, last, pay):
# with conn:
# c.execute("""INSERT INTO employees
# VALUES (:first, :last, :pay)""", {'first': first, 'last': last, 'pay': pay})
#
#
# for index, emp in enumerate(employees):
# # int_ind = int(index)
# fn = employees[index][0]
# ln = employees[index][1]
# py = employees[index][2]
#
# insert_employees(fn, ln, py)
# conn.commit()
# c.execute("SELECT * FROM employees WHERE last_name = ?", ('McCabe',))
# c.execute("SELECT * FROM employees WHERE last_name = :first", {'first': 'McCabe'})
# c.execute("DELETE FROM employees WHERE last_name = 'McCabe'")
c.execute("SELECT * FROM employees")
rng = len(c.fetchall())
payload = c.fetchall()
print(payload)
print(rng)
# for i in range(rng):
# print(payload)
c.execute("SELECT * FROM employees WHERE last_name LIKE :last", {'last': '%Mc%'})
# employees_last = ['Harvey', 'McCabe']
#
def select_employees(lastname):
c.execute("SELECT * FROM employees WHERE last_name LIKE :last", {'last': lastname})
return c.fetchall()
# c.fetchone()
# c.fetchmany()
# for employee in employees_last:
# print(select_employees(employee))
conn.commit()
conn.close()
| false |
b93c3d8e6f5bfc9288a0dec2e90bd47883ea3afd | oWlogona/SS_exercise | /char_freq.py | 469 | 4.21875 | 4 | """Write a function char_freq() that takes a string and builds a
frequency listing of the characters contained in it. Represent the frequency
listing as a Python dictionary. Try it with something like
char_freq("abbabcbdbabdbdbabababcbcbab")."""
def char_freq(line=''):
if len(line):
ans_dict = {item: 0 for item in line}
for item in line:
ans_dict[item] += 1
return ans_dict
return 'empty'
if __name__ == "__main__":
print(char_freq("aaaa00fdfdlrk")) | true |
cd1527a54199641f65d3b09750825a611e45af89 | anastasiia42/Interview-practice | /check_if_binary_search_tree.py | 1,685 | 4.21875 | 4 | # check if a binary tree is a binary search tree
class BinaryTreeNode(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert_left(self, value):
self.left = BinaryTreeNode(value)
return self.left
def insert_right(self, value):
self.right = BinaryTreeNode(value)
return self.right
def check_if_binary_search_tree(root, min, max):
if not root:
return True
return check_if_binary_search_tree(root.left, min, root.value) and \
check_if_binary_search_tree(root.right, root.value, max) and max >= root.value >= min
def if_binary_search_tree(root):
return check_if_binary_search_tree(root, -float('inf'), float('inf'))
def test_non_binary():
tree = BinaryTreeNode(5)
left = tree.insert_left(8)
right = tree.insert_right(6)
left.insert_left(1)
left.insert_right(2)
right.insert_left(3)
right.insert_right(4)
assert if_binary_search_tree(tree) is False
def test_one_leaf_binary_search():
tree = BinaryTreeNode(5)
tree.insert_left(4)
assert if_binary_search_tree(tree) is True
def test_one_leaf_not_binary_search():
tree = BinaryTreeNode(5)
tree.insert_left(9)
assert if_binary_search_tree(tree) is False
def test_one_node():
tree = BinaryTreeNode(5)
assert if_binary_search_tree(tree) is True
def test_larger_binary_search():
tree = BinaryTreeNode(5)
left = tree.insert_left(2)
right = tree.insert_right(8)
left.insert_left(1)
left.insert_right(3)
right.insert_left(6)
right.insert_right(9)
assert if_binary_search_tree(tree) is True
| true |
96aa84fc0b6ad809030616df64f99268b18d37c1 | sarah-fitzgerald/pands-problem-sheet | /collatz.py | 863 | 4.46875 | 4 | #This program asks user to input any positive integer
#Then outputs the successive values
#Author: Sarah Fitzgerald
#https://www.w3resource.com/python-exercises/challenges/1/python-challenges-1-exercise-23.php
x = int(input("Please enter a positive number: ")) # Asks user to input a positive number
def collatz(x): #Defines the funcition and the number is the parameter
if x % 2 == 0: #If the remainder number is divided by 2 is 0 then it is even
return x // 2 #This returns the result to the function
else: #If the remainder number divided by 2 is not 0 then it is odd
return x * 3 + 1
while x != 1: #Loop to print until the number is 1
print (x)
x = collatz(int(x)) #The collatz function passes the number until it gets to 1: https://stackoverflow.com/questions/33508034/making-a-collatz-program-automate-the-boring-stuff | true |
6c0e49392b047a2687624460a7d36dcb356ed99c | basfl/data-science | /ml/Regression/Simple Linear Regression/GPA_SAT/app.py | 1,187 | 4.15625 | 4 | from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataset = pd.read_csv("./resources/gpa-sat.csv")
"""
our DV is gpa and our IV is sat
"""
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=1/3, random_state=0)
# Fitting Simple Linear Regression to the Training set
regressor = LinearRegression()
regressor.fit(X_train, y_train)
"""
here we are going to predict
given SAT=1844 what would be GPA
"""
y_pred_v = regressor.predict([[1844]])
print(f"predicted GPA for SAT=1844 is {y_pred_v}")
y_pred = regressor.predict(X_test)
# Visualising the Training set results
plt.scatter(X_train, y_train, color='red')
plt.plot(X_train, regressor.predict(X_train), color='blue')
plt.title('SAT vs GPA (Training set)')
plt.xlabel('SAT')
plt.ylabel('GPA')
plt.show()
# Visualising the Test set results
plt.scatter(X_test, y_test, color='red')
plt.plot(X_train, regressor.predict(X_train), color='blue')
plt.title('SAT vs GPA (Test set)')
plt.xlabel('SAT')
plt.ylabel('GPA')
plt.show()
| true |
01ad2ae9be1fd114b3821c355322bf3d288dd5ab | lyl0521/lesson-0426 | /lesson/day03/list_test.py | 668 | 4.375 | 4 | names = ['Tom','Jerry']
print(names)
print(names[0])
print(names[-1]) # last element
print(names[-2])
print(len(names))
names.append('Spike')
print(names)
names.insert(2,'Tyke')
print(names)
names[3] = 'Spike'
print(names)
names.pop() # 默认删除最后一个元素
names.pop(0) # 写入参数删除对应元素
print(names)
superstar = ['Tom','Jerry']
names = [superstar,'Spike']
print(names)
names.clear()
print(names)
names = superstar.copy()
print(names)
names.append('Spike')
print(superstar.index('Jerry'))
names.remove('Spike')
names.reverse()
print(names)
names.sort(reverse=True)
print(names)
for name in names:
print(name) | false |
b640a0cf4f8c3e30f4bdab9abe852262aa2ccfe9 | ArtisanGray/python-exercises | /else-if.py | 377 | 4.34375 | 4 | # This program will take a numerical grade and give a letter grade output
grade = int(input("Enter your grade: "))
if (grade >= 90) and (grade <=100):
print("A")
elif (grade >=80)and(grade <=89):
print("B")
elif(grade >=70)and(grade <=79):
print("C")
elif(grade >=60)and(grade <= 69):
print("D")
else:
print("F")
# Use an else if statement to check for each letter grade
| true |
dd8d121d8ba32dd8001e341f4bc5b8641a1f863e | ArtisanGray/python-exercises | /tic-tac-toe-pt3-UNFINISHED.py | 1,340 | 4.375 | 4 | print ("TIC TAC TOE board. Rows and Columns starting from 1,1")
print ("Game board is printed each time to show progress!")
# Declare the blank game
game=[[0,0,0],
[0,0,0],
[0,0,0]]
count = 0
# create the print gameboard function
def print_game(game):
print ("\n")
for i in range(3):
print (str(game[i]) + "\n")
board_size = int(input("What size of game board? "))
def print_horiz_line():
x = 0
print(" ---" * board_size)
def print_vert_line():
z = 0
print("| "*(board_size + 1))
for y in range(0,board_size):
print_horiz_line()
print_vert_line()
else:
print_horiz_line()
# Insert the checkWin function here.
# Now lets start the game
while True:
#Insert the code from Step 6
if count%2==0:
print ("\nPlayer 1's Turn!")
if game[row][column] == 0: # Make sure the spot is blank
game[row][column] = 'X' # if it's blank, mark an X
else:
print ("Try Again!") # if it's not blank, try again
count-=1 # this will reset the counter, so you can try again
print_game(game) # print your new game board
else:
# Now do the same thing for player 2 as you did for player 1
# Player 2 is an 'O'
#Increase your count
#check for a win using your function that you created
print ("Game Over!")
| true |
d422f486d04edc5f363c4c144a077d1954b47309 | ArtisanGray/python-exercises | /check-elements-of-input-array.py | 669 | 4.125 | 4 | # Use your code from the last exercise.
# Now check to see how many of a number are in the array.
# Hint: use the code from the examples in class.
# Use your code from the last exercise.
numbers = []
input_len = int(input("How many elements do you want?: ") )
# Now use a for loop to add to the array.
for index in range(0, input_len):
input_add = int(input("Enter next number: "))
numbers.append(input_add)
else:
print(numbers)
count = 0
print("Enter a number 0 - 9:")
elem = int(input("Which number do you want to find?"))
for index in range(0,input_len):
if numbers[index] == elem:
count+=1
else:
print("There are " , count, elem,"'s in the array")
| true |
5685876f0ed8c7c70d5fa262ce6558f0a786fd03 | susansfy/pythonBasic | /爬虫/get请求.py | 333 | 4.125 | 4 |
'''
特点:把数据
优点:速度快
缺点:承载的数据小,不安全
'''
import urllib.request
url = ""
response = urllib.request.urlopen(url)
data = response.read().decode("utf-8")
print(data) #字符串类型
#但实际上响应数据大多数是json格式的字符串
#json viwer软件,查看json的层次
| false |
17d710df2cf9ababbe9ca0939c89d21ad721e981 | TanakitInt/Python-Year1-Archive | /In Class/Week 14/Palindrome.py | 328 | 4.125 | 4 | """Palindrome"""
def main():
"""start"""
text = str(input())
text_invert = list(text)
text_invert = text_invert[::-1]
new = ''
new = new.join(text_invert)
text_invert = new
if text == text_invert:
print(text, "is Palindrome.")
else:
print("This is not Palindrome")
main()
| false |
74631801eb5e74b9edb65763a68e0d5f6af863eb | TanakitInt/Python-Year1-Archive | /In Class/Week 3/quadratic solve issue when crash (q14 HW).py | 2,200 | 4.34375 | 4 | #--------------------------Information------------------------------#
#Tanakit Intaniyom DSBA
#Assignment Week 3
#Question number 14
#Last updated on 26/08/2017 at 02.44 am
#-------------------------------------------------------------------#
# quadratic.py
# A program that computes the real roots of a quadratic equation.
# Illustrates use of the math library.
# Note: this program crashes if the equation has no real roots.
#def main():
#print("This program finds the real solutions to a quadratic\n")
#coeff_a = int(input("Please enter the coefficients a: "))
#coeff_b = int(input("Please enter the coefficients b: "))
#coeff_c = int(input("Please enter the coefficients c: "))
# computing square root
#temp = square_root(coeff_b * coeff_b - 4 * coeff_a * coeff_c)
#root1 = (-coeff_b + temp) / (2 * coeff_a)
#root2 = (-coeff_b - temp) / (2 * coeff_a)
#print("The solutions are:", root1, root2 )
#main()
#-------------------The upper is original code----------------------#
#start fixing an error
# the error will cause when x == (-b +-(sqrt(b**2-4*a*c))/2*a is
#not in real number path
def main():
num_a = int(input("Please enter the coefficients a: "))
num_b = int(input("Please enter the coefficients b: "))
num_c = int(input("Please enter the coefficients c: "))
#start computation
#A +- symbol is currently not found in python module by me
#then split it into two equation
import math
#insert a condition that inside a square root must not less than 0 and
#2*a is not equal 0 too. There would be an error occured.
if num_b**2-4*num_a*num_c >= 0 and 2*num_a != 0:
#for plus
x_plus = (-num_b+(math.sqrt(num_b**2-4*num_a*num_c)))/2*num_a
#for minus
x_minus = (-num_b-(math.sqrt(num_b**2-4*num_a*num_c)))/2*num_a
#start printing an answer of x if x is real number path
print("Your answer for x is : ", x_plus, x_minus)
else:
#start printing an error of x if x is not real number path
print("Ummm... that was maybe an imaginary path \
answer or invalid square root or invalid input for a or b or c")
main()
#finish fixing an error
| true |
b9aac0c9b30875d909bf13d6157799c6668d86b9 | TanakitInt/Python-Year1-Archive | /In Class/Week 5/max_speed.py | 663 | 4.21875 | 4 | """Max speed"""
def traffic():
"""go drive!"""
speed_limit = int(input())
current_speed = int(input())
fine = 0
#when drive illegal but not more than 90
if current_speed > speed_limit and current_speed <= 90:
fine = 50 + abs((speed_limit-current_speed)*5)
print("The speed is illegal, your fine is $"+'%.2f'%fine)
#when drive illegal and more than 90
elif current_speed > speed_limit and current_speed > 90:
fine = 50 + abs((speed_limit-current_speed)*5) + 200
print("The speed is illegal, your fine is $"+'%.2f'%fine)
#when drive legal
else:
print("Your speed is legal.")
traffic()
| true |
e0d5e2f0e7509f1415756a6749a9c4383d6333da | Afterives/LearnPython | /dayFour.py | 901 | 4.125 | 4 | # Dzień 4 z pythonem
# Sety, czyli zbiory
# Zbiór to lista, w której nie ma dwóch identycznch elementów
thisset = {"apple", "banana", "cherry"}
print(thisset)
# Nie możemy uzyskać dostępu poprzez odwołanie się do indeksu setu, za to możemy wypisać elementy dzięki pętli for
for x in thisset:
print(x)
# Dodawanie elementu do setu
thisset.add("orange")
print(thisset)
# Żeby dodać więcej elemetów do setu używamy update()
thisset.update(["mango", "grapes"])
print(thisset)
# Długość setu
print(len(thisset))
# Usuwanie elementów
thisset.remove("banana")
print(thisset)
thisset.discard("apple") # discard robi to samo co remove, ale nie wywoła błędu, jeśli już nie istnieje element
thisset.discard("apple")
print(thisset)
# Pop
print(thisset)
x = thisset.pop() # usuwa ostatni element setu i zapisuje do zmiennej, możemy wtedy go wywołać
print(thisset)
print(x) | false |
b2b1ec727846ee12bef756ae51d873de04af9410 | robertz23/code-samples | /python scripts and tools/palindrome_prime.py | 1,359 | 4.40625 | 4 | """
Find the highest palindromic prime
number between 1 and 1000
"""
def is_prime(num):
"""
Checks if a number is prime
"""
prime_counter = 1
for x in range(1, num):
if num % x == 0:
prime_counter += 1
if prime_counter > 2:
return False
return True
def is_palindrome(prime_number):
"""
Checks if a prime number, validated by the is_prime
function through the is_palindrome_prime function,
is a palindrome
"""
prime_num_str = str(prime_number)
prime_len = len(prime_num_str) - 1
inverted_prime = ""
while prime_len >= 0:
inverted_prime += prime_num_str[prime_len]
prime_len -= 1
if prime_num_str == inverted_prime:
return True
else:
return False
def is_palindrome_prime(num_range):
"""
Main function. Handles the logic of calling helper
functions is_palindrome and is_prime in order
to return the biggest palindrome in a series of numbers
"""
c = 0
biggest_palindrome = 0
while c <= num_range:
if is_prime(c) and is_palindrome(c):
if biggest_palindrome < c:
biggest_palindrome = c
c += 1
return biggest_palindrome
if __name__ == "__main__":
print is_palindrome_prime(1000)
| true |
4400a20127476249bbc6ea7240e6718d792aa260 | McLeedle/python-projects | /Example4 Conditionals/example4.py | 738 | 4.125 | 4 | print "This is our forth example and will cover conditionals and control flow"
# create function storestock with a variable of instock
def storestock(instock):
print "This store has %s Items in stock." % (str(instock))
# conditional parameters to evaluate if instock is true and prints if true
if instock == 400:
return "Store's stock is full"
elif instock > 400:
return "Store's stock is overflowing "
elif instock < 200 and instock > 0:
return "Store's stock is half full"
else:
return "Store is out of stock"
# these statements change the value of instock to test and make all statements true
print storestock(400)
print storestock(800)
print storestock(150)
print storestock(0) | true |
69e21a1b59751503111f0903d93d6e90a8392d16 | csgray/IPND_lesson_4 | /lesson_4-4.py | 1,861 | 4.34375 | 4 | """Lesson 4.4: Modulus & Dictionaries
Modulus Operator %
<number> % <modulus> -> <remainder>
14 % 12 -> 2
"""
"""Lesson 4.4: Dictionaries
Dictionaries are another crucial data structure to learn in Python in
addition to lists. These data structures use string keywords to access
data rather than an index number in lists. Using string keywords gives
programmers more flexibility and ease of development to use a string
keyword to access an element in this data structure.
https://www.udacity.com/course/viewer#!/c-nd000/l-4181088694/m-3919578552
"""
# Strings vs List vs Dictionary Demo
s = "hello"
p = ["alpha", 23]
d = {"hydrogen": 1, "helium": 2}
# Accessing items
print s[2]
print p[1]
print d["hydrogen"]
# Replacing values
# s[2] = "a" # Will produce error
p[1] = 999
d["hydrogen"] = 49
"""Different Types of data
String: sequence of characters, immutable, s[i]
List: list of elements, mutable, p[i]
Dictionary: set of <key, value> pairs, mutable, d["k"]
"""
elements = {"hydrogen": 1, "helium": 2, "carbon": 6}
print elements
print "lithium" in elements
elements["lithium"] = 3
elements["nitrogen"] = 8
print elements["lithium"]
print elements["nitrogen"]
elements["nitrogen"] = 7
print elements["nitrogen"]
# Define a Dictionary, population,
# that provides information
# on the world's largest cities.
# The key is the name of a city
# (a string), and the associated
# value is its population in
# millions.
# Key | Value
# Shanghai | 17.8
# Istanbul | 13.3
# Karachi | 13.0
# Mumbai | 12.5
population = {"Shanghai": 17.8, "Istanbul": 13.3, "Karachi": 13.0,
"Mumbai": 12.5}
elements = {}
elements["H"] = {"name": "Hydrogen", "number": 1, "weight": 1.00794}
elements["He"] = {"name": "Helium", "number": 2, "weight": 4.002602,
"noble gas": True}
print elements["He"]["noble gas"]
| true |
e0b42545cf9394ae335d92d6e9d8dc2a1e6a8143 | UrszulaP/Learning-JavaScript-30days | /04 - Array Cardio Day 1/python_version.py | 1,424 | 4.125 | 4 | # 1. Filter the list of inventors for those who were born in the 1500's
result = list(filter(lambda x: x["year"] >= 1900 and x["year"] < 2000, inventors))
print(result)
# ZMIENIĆ NA LISTĘ STRINGÓW
# 2. Give us an array of the inventors first and last names
result = list(map(lambda x: {x["first"], x["last"]}, inventors))
print(result)
# REVERSE = FALSE ?
# 3. Sort the inventors by birthdate, oldest to youngest
result = sorted(inventors, key=(lambda x: x["year"]), reverse=True) # sorted() creates a new list
# WRONG: result = inventors[:].sort(reverse=True, lambda x: x["year"]) - sort() doesn`t work on list copy
print(result)
# REDUCE, SUMA ŻYCIA WSZYSTKICH, NIE WSPÓLNY CZAS
# 4. How many years did all the inventors live all together?
first_dead = min(list(map(lambda x: x["passed"], inventors)))
last_born = max(list(map(lambda x: x["year"], inventors)))
result = first_dead - last_born
print(result)
# OD NAJDŁUŻEJ DO NAJKRÓCEJ
# 5. Sort the inventors by years lived
result = sorted(inventors, key=(lambda x: x["passed"] - x["year"]))
print(result)
# 6. create a list of Boulevards in Paris that contain 'de' anywhere in the name
# https://en.wikipedia.org/wiki/Category:Boulevards_in_Paris
# LISTA PEOPLE, NIE INVENTORS
# 7. Sort the people alphabetically by last name
result = sorted(inventors, key=(lambda x: x["last"]))
print(result)
# 8. Reduce Exercise, Sum up the instances of each of these
| true |
7c8ec39deea879435ea3166fd31fa71d17d854ec | aba00002/Lab3-Python | /Lab3_Exercise10.py | 305 | 4.375 | 4 | #Program that will compute MPG (Miles covered Per Gallon used) for a car
#Where M is miles driven and G is gallon used
M = int(input("enter the number of miles driven"))
G = float(input("enter the number of gallons used"))
MPG = (M / G)
print("Dear driver, the mile per gallon rate of your car is", MPG)
| true |
396012585de01ddc15a212334393e736cf3238ff | satishr01k/Python_Tasks | /variablestask.py | 1,981 | 4.59375 | 5 |
#1. Create three variables in a single line and assign different values to them and make sure their data types are different. Like one is int, another one is float and the last one is a string.
a, b, c=10, 11.5, 'satish'
print(a)
print(b)
print(c)
# 2. Create a variable of value type complex and swap it with another variable whose value is an integer.
x,y=10,2+7j
print(x)
print(y)
print(type(y))
x,y=y,x
print(x)
print(y)
print(type(y))
# 3. Swap two numbers using the third variable as the result name and do the same task without using any third variable.
x=10
y=20
z=0 #third variable
x,z=z,x
# print(x)
# print(z)
y,z=z,y
# print(y)
# print(z)
x,z=z,x
print(x)
print(y)
print(z)
#without third variable
x,y=y,x
# 4. Write a program to print the value given by the user by using both Python 2.x and Python 3.x Version.
#python3
x=input('Enter a value: ')
print(x)
#python2
#x=raw_input('enter a value : ')
#print('x')
# 5. Write a program to complete the task given below:
# Ask the user to enter any 2 numbers in between 1-10 and add both of them to another variable call z.
# Use z for adding 30 into it and print the final result by using variable results.
x=input('Enter first number between 1-10: ')
y=input('Enter second number between 1-10: ')
#add exception handling. if number not in range or not int
z=int(x)+int(y)
z=z+30
print('final result: ' ,z)
# 6. Write a program to check the data type of the entered values.
# HINT: Printed output should say - The input value data type is: int/float/string/etc
print(type(x))
print(type(y))
# 7. If one data type value is assigned to ‘a’ variable and then a different data type value is assigned to ‘a’ again.
# Will it change the value. If Yes then Why?
a=15
print('a before: ',a)
a='satish'
print('a after: ',a)
#Ans: Yes. It will change. because the value of a variable is mutable.
# after the value/data type is changed the new value is created in the memory and named as 'a'
| true |
5ca48e454b86c5e709b3d4a698937776e014c04d | PePPers258/PRIMER-PROGRAMA | /Adivina_tu_numero.py | 475 | 4.125 | 4 | number_to_guess = 0
number_to_guess = int(input("Para continuar, introduce un numero para que alguien mas lo adivine, fijate que no lo vea (numeros entre el 1 y 100): "))
user_number = int(input("Adivina un numero: "))
while number_to_guess < user_number or number_to_guess > user_number:
print("Has fallado, intentalo de nuevo")
user_number = int(input("Adivina un numero: "))
print("¡felicidades, adivinaste el nuemro, el numero era {}" .format(number_to_guess)) | false |
954e5771d75b2a1122c3d92cc7985d308402320a | mik-79-ekb/Python_start | /Lesson_2/HW_2.3.py | 791 | 4.15625 | 4 | """
Task 2.3
"""
year_list = ["Зима", "Зима", "Весна", "Весна", "Весна", "Лето", "Лето", "Лето", "Осень", "Осень", "Осень", "Зима",]
year_dic = {1: "Зима",
2: "Зима",
3: "Весна",
4: "Весна",
5: "Весна",
6: "Лето",
7: "Лето",
8: "Лето",
9: "Осень",
10: "Осень",
11: "Осень",
12: "Зима",}
month = int(input("Введите номер месяца: "))
print(f"Ваше время года: {year_dic.get(month)}. Это вариант через dict")
print(f"Ваше время года: {year_list[month-1]}. Это вариант через list")
| false |
969f76a0b45f7aee2e017b12579d8cd3cad1f68b | LouJi/PyUnitTest2 | /functionz.py | 1,915 | 4.25 | 4 | from math import *
def add (x,y):
#Add function
if type(x) in [bool]:
raise TypeError('The operands must be a real number')
if type(y) in [bool]:
raise TypeError('The operands must be a real number')
#if type(x, y) not in [int, float, str]:
#raise TypeError('The operands must be a real number')
return x + y
def subtract (x, y):
#Subtract function
if type(x) not in [int, float]:
raise TypeError('The operands must be a real number')
if type(y) not in [int, float]:
raise TypeError('The operands must be a real number')
#if type(x, y) not in [int, float]:
#raise TypeError('The operands must be a real number')
return x - y
def multiply(x,y):
#Multiply function
if type(x) not in [int, float]:
raise TypeError('The operands must be a real number')
if type(y) not in [int, float]:
raise TypeError('The operands must be a real number')
#if type(x, y) not in [int, float]:
#raise TypeError('The operands must be a real number')
return x * y
def divide (x,y):
#Dividefunction
if type(x) not in [int, float]:
raise TypeError('The operands must be a real number')
if type(y) not in [int, float]:
raise TypeError('The operands must be a real number')
if y == 0:
raise ValueError ('Cannot divide by zero.')
return x/y
def containMethod1 (x):
#if a string contains a value prints True or False
if type(x) not in [str]:
raise TypeError('Input must be a string.')
str1= 'Hello there, this is a example.'
return x in str1
def containMethod2 (x):
#check id a string contains a value. Print start index or -1 if does not contain.
if type(x) not in [str]:
raise TypeError('Input must be a string.')
str2= 'No fear, this too is an example.'
return str2.find(x)
#if str2.find(x) == -1
| true |
5add4ae6f07d5713cca14f0b251bdb2941377379 | AymaneZizi/dailyreader | /common/stemming.py | 705 | 4.1875 | 4 | alphabets={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}
def is_not_alphanumeric(word):
option=0
returnValue=1
while option<len(word):
if word[option] in alphabets:
returnValue=0
option=option+1
if len(word)<3:
returnValue=1
return returnValue
def stem_word(word):
if not (word.count('"')>0 or word.count("'")>0 or word.count("#")>0 or len(word.split(" "))>1 or is_not_alphanumeric(word)):\
return word.lower()
else:
return "" | false |
c7dd3e6d4d38ced899bd5ff4be66a456252b0fd3 | AnDr10wA/tms-21 | /Task_7_full/task_7full_6.py | 503 | 4.46875 | 4 | """
Создать функцию, которая принимает на вход
неопределенное количество аргументов и возвращает их
сумму и максимальное из них.
"""
def func(*args):
print(args)
sum1 = sum(args)
max1 = max(args)
return sum1, max1
func1 = func(1, 4, 5 ,23, 23, 11, 21)
print(f"Сумма элементов равна {func1[0]}")
print(f"Максимальный элемент {func1[1]}")
| false |
5ef08a06702238a16fb0148ad228bfa4712c2814 | young-geng/leet_code | /problems/170_two-sum-iii-data-structure-design/main.py | 1,417 | 4.15625 | 4 | # https://leetcode.com/problems/two-sum-iii-data-structure-design/
# Design and implement a TwoSum class. It should support the following operations: add and find.
#
# add - Add the number to an internal data structure.
# find - Find if there exists any pair of numbers which sum is equal to the value.
#
# For example,
# add(1); add(3); add(5);
# find(4) -> true
# find(7) -> false
from collections import defaultdict
class TwoSum(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.counter = defaultdict(int)
def add(self, number):
"""
Add the number to an internal data structure..
:type number: int
:rtype: void
"""
self.counter[number] += 1
def find(self, value):
"""
Find if there exists any pair of numbers which sum is equal to the value.
:type value: int
:rtype: bool
"""
for num in self.counter.keys():
to_find = value - num
# one test case is add(0), add(0), find(0) --> True
# you have to make sure you have enough numbers to add it up
if to_find in self.counter and (to_find != num or self.counter[num] > 1):
return True
return False
# Your TwoSum object will be instantiated and called as such:
# obj = TwoSum()
# obj.add(number)
# param_2 = obj.find(value)
| true |
a9048140fd89a0ddd754998f28406df67c157237 | nshirajee/pythonLab9 | /Lab9_07.py | 698 | 4.375 | 4 | #function to calculate Fibonacci sequence
def fibonaccisequence(number):
#Initialize variable
#second seq starts with 1
firstseq = 0
secondseq = 1
#loop through number of sequence parameter
for x in range(number):
#only print second seq, first time it'll print 1, after that it'll print bothseq variable
print(secondseq)
#sum of first abd second seq and store in variable
bothSeq = firstseq + secondseq
# switch first seq to second seq
firstseq = secondseq
# set second seq to variable which is first + second seq
secondseq = bothSeq
#
userInput = int(input("Enter an Integer:"))
fibonaccisequence(userInput)
| true |
47e9a81d6f11a776c21a0212c1ca562c77fd2eae | gujunwuxichina/python_basic | /com/gujun/变量和简单类型/number/float.py | 323 | 4.1875 | 4 | # 浮点型
# 浮点型数值表示带有小数点的数值
# 两种表示形式:
# 1.十进制,浮点数必须包含一个小数点,否则会被当成整型;
# 2.科学计数法,3.14e12,只有浮点型才能使用科学计数法;
a=1.
print(type(a)) # <class 'float'>
b=100e5
print(type(b)) # <class 'float'> | false |
6457791201c288cedf1fed76ebb1d8d84c0d2a62 | Ahsank01/Python-Crash-Course | /String/String.py | 1,407 | 4.5 | 4 | # Name: Ahsan Khan
# Date: 09/15/2020
# Description: Using string and its built-in functions, and manipulating the string.
# the function .title() will make the first initial a capital letter
name = "ahsan khan"
print(name.title())
#------------------------------------------------------------------#
# the function .upper() will make the whole string an uppercase string
# the function .lower() will make the whole struing a lowercase string
print(name.upper())
print(name.lower())
#------------------------------------------------------------------#
# f-string is for formatting the data.
first_name = "ahsan"
last_name = "khan"
full_name = f"{first_name} {last_name}"
print(full_name)
print(f"Hello, {full_name.title()}!")
message = f"Hello, {full_name.title()}!"
print(message)
#------------------------------------------------------------------#
# the function .rstrip() will erase all the useless whitespace from the right side
# the function .lstrip() will erase all the useless whitespace from the left side
# the function .strip() will erase all the useless whitespace from the left and right side
message = "ahsan "
print(f"'{message}'")
message = message.rstrip()
print(f"'{message}'")
message = " ahsan"
print(f"'{message}'")
message = message.lstrip()
print(f"'{message}'")
message = " ahsan "
print(f"'{message}'")
print(f"'{message.strip()}'")
| true |
5b4450467c870a1b744ffae3002531f8d2c201aa | Ahsank01/Python-Crash-Course | /User Input and While loop/Introducing_while_loops.py | 2,380 | 4.15625 | 4 | # Name: Ahsan Khan
# Date: 10/06/20
# Description: Intro to while loops and user input
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
# ================================================================ #
prompt = "\nTell me something, and I will repeat it back to you. "
prompt += "\nEnter 'quit' to end the program: "
message = " "
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
# ================================================================ #
# Use flag with while loop
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
# ================================================================= #
# Usng break to exit the loop
while True:
message = input(prompt)
if message == 'quit':
break
else:
print(message)
# ================================================================== #
# Using continue in a loop
current_number = 0
while current_number < 10:
current_number +=1
if current_number % 2 == 0:
continue
print(current_number)
# ================================================================== #
# Use lists with while loops
print()
unconfirmed_users = ['ahsank20', 'ak231', 'koke21']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print(f"Verifying user: {current_user}.")
confirmed_users.append(current_user)
print()
for users in confirmed_users:
print(f"Verified User: {users}")
# ================================================================== #
# Use while loop to remove all instances of specific values from a list
my_list = ['cat','dog', 'tiger', 'cat', 'cat','elephant', 'cat']
print(my_list)
while 'cat' in my_list:
my_list.remove('cat')
print(my_list)
# ================================================================== #
# Use dictionary with user input and while loop
responses = {}
polling_actice = True
while polling_actice:
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
responses[name] = response
repeat = input("Would you like to let another person respond? (Y/N) ")
if repeat == 'n':
polling_actice = False
print("\nPoll Results\n")
for name, response in responses.items():
print(f"{name} would like to climb {response}")
print(responses)
| true |
e7fef2eedf81f18684d7189811f2c4b880c84953 | Ahsank01/Python-Crash-Course | /Dictonaries/Exercises/Polling.py | 822 | 4.1875 | 4 | # Name: Ahsan Khan
# Date: 09/29/20
# Description: Make a list of people who should take the favorite language poll.
# Loop through the list of people who should take the poll.
# If they have already taken the poll, print a message thanking them for responding.
# If they haven't yet taken the poll, print a message inviting them to take the poll.
favorite_language = {
'sarah':'python',
'edward':'c++',
'ahsan':'python',
'john':'javascript',
}
names = ['jim', 'tom'] # empty variable to store names
for name in favorite_language.keys():
names.append(name)
for name in sorted(names):
if name in favorite_language.keys():
print(f"{name.title()}, thanks for being part of the poll.")
else:
print(f"{name.title()}, please take the poll ASAP. Thank You!") | true |
0bcb649346aeb69b41da7c9e562fad76306d2fc2 | Ahsank01/Python-Crash-Course | /IF_Statement/if_statement.py | 2,343 | 4.21875 | 4 | # Name: Ahsan Khan
# Date: 09/23/20
# Description: Get familiar with Python IF STATEMENT
cars = ['honda', 'mercedes', 'toyota', 'bmw']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
# --------------------------------------------------------- #
#Checking for inequality
requested_topping = 'mushrooms'
print( )
if requested_topping != 'anchovies':
print("Hold the anchovies")
answer = 17
if answer != 42:
print("\nThat is not the correct answer! Please try again.")
# --------------------------------------------------------- #
#Using AND to check multiple conditions
age_0 = 22
age_1 = 18
answer = True
if age_0 >=21 and age_1 >= 21:
print(answer)
else:
answer = False
print(answer)
print()
# --------------------------------------------------------- #
# Using OR to check multiple conditions
age_0 = 22
age_1 = 18
if age_0 >= 21 or age_1 >= 21:
print(True)
else:
print(False)
print()
# ---------------------------------------------------------- #
# Checking weather a value is in a list
requested_toppings = ['mushrooms', 'onions', 'chicken']
if 'olives' in requested_toppings:
print(True)
else:
print(False)
print()
# ---------------------------------------------------------- #
# Checking weather a value is not in the list
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(f"{user.title()}, you may post a comment.")
else:
print("You are banned!")
print()
# ---------------------------------------------------------- #
# Simple if-else statement
age = 17
if age >= 18:
print("You are old enough to vote.")
print("Have you registered to vote yet?")
else:
print("Sorry, you are too young to vote.")
print("Come back in", 18-age, "year(s). ")
print()
# ---------------------------------------------------------- #
# if-elif-else
#amusement park entry cost
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age <= 18:
print("Your admission cost is $25.")
else:
print("Your admission cose is $40.")
print()
# Using multiple elif blocks
age = 35
price = 0
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
else:
price = 20
print(f"Your admission cost is ${price}.") | true |
18500750e494ad9f454ea29482444551832087db | Gafanhoto742/Python-3 | /Python (3)/Ex_finalizados/ex027.py | 369 | 4.15625 | 4 | # Exercício Python 027: Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o último nome separadamente.
nome = str(input('Digite o seu nome completo: ')).strip().upper()
n = nome.split()
print ('Muito prazer em te conhecer!')
print('Seu primeiro nome é:{}' .format(n[0]))
print('Seu último nome é:{}'.format(n[len(n)-1]))
| false |
a33768e96dcdca65b8cfcc4719693a09d5ce1ced | Gafanhoto742/Python-3 | /Python (3)/Ex_finalizados/ex095.py | 1,935 | 4.28125 | 4 | '''Aprimore o desafio 93 para que ele funcione com vários jogadores,
incluindo um sistema de visualização de detalhes do aproveitamento de cada jogador.'''
jogador = {}
ngols = [] # número de gols
ljogadores = [] # Lista de jogadores
soma = j = 0
print ('='*60)
print (f'\033[7;30;39m{"CADASTRO DE JOGADOR":^60}\033[m')
print ('='*60)
while True:
jogador.clear()
j += 1
jogador['Nome'] = str(input(f'Nome do {j}º Jogador: ')).strip().upper()
npart = int(input(f'Quantas partidas que \033[2;33m{jogador ["Nome"]}\33[m participou?: ')) #numero de partidas
ngols.clear()
for c in range(0, npart):
c +=1
ngols.append(int(input(f'Quantos Gols que \033[3;33m{jogador["Nome"]}\33[m fez na {c}º partida: ')))
jogador['Gols'] = ngols[:]
jogador['Saldo de gols'] = sum(ngols)
ljogadores.append(jogador.copy())
print('='*60)
while True:
resp = str(input('Deseja cadastrar outro jogador? [S/N]')).strip().upper()[0]
if resp in "SN":
break
print(f'[ERRO] - Digite S ou N: ')
if resp == "N":
break
print('='*60)
print ('Cód', end=' ')
for i in jogador.keys():
print(f'{i:<15}', end='')
print()
print('='*60)
for k, v in enumerate(ljogadores):
print(f'{k:>2}',end=' ')
for d in v.values():
print(f'{str(d):<15}', end='')
print()
print('='*60)
while True:
perg = int(input('Quer saber os dados de qual jogador? [999-parar Consulta]'))
if perg == 999:
break
if perg >= len(ljogadores):
print(f'[ERRO!] - Não existe esse jogador na lista, digite um código válido {perg}')
else:
print(f' \033[7;30;39m---- LEVANTAMENTO DO JOGADOR \033[3;33m{ljogadores[perg]["Nome"]}\033[m:')
for i, g in enumerate(ljogadores[perg]['Gols']):
print(f' No {i+1}º jogo fez {g} gols')
print('='*60)
print(f'{"==* PROGRAMA ENCERRADO *==":^30}')
| false |
0586323efb3299b119d17034d91e0a8553c72be9 | ortizjs/algorithms_ | /python-practice/command_line_calendar.py | 2,660 | 4.53125 | 5 | """In this project, we'll build a basic calendar that the user will be able to interact with from the command line. The user should be able to choose to:
View the calendar
Add an event to the calendar
Update an existing event
Delete an existing event
The program should behave in the following way:
Print a welcome message to the user
Prompt the user to view, add, update, or delete an event on the calendar
Depending on the user's input: view, add, update, or delete an event on the calendar
The program should never terminate unless the user decides to exit
"""
from time import sleep, strftime
name = "Jonnatan"
calendar = {}
def welcome():
print "Welcome, %s!" %(name)
print "The calendar is opening..."
sleep(1)
print "The current date is: " + strftime("%A %B %d %Y")
print "The current time is: " + strftime("%H:%M:%S")
print "What would you like to do next? "
def start_calendar():
welcome()
start = True
while start:
user_choice = raw_input("A to Add, U to Update, V to View, D to Delete, X to Exit: ")
user_choice = user_choice.upper()
if user_choice == "V":
if len(calendar.keys()) == 0:
print "The calendar is currently empty..."
else:
print calendar
elif user_choice == "U":
date = raw_input("What date? ")
update = raw_input("Enter the update: ")
print "The calendar is updating..."
calendar[date] = update
sleep(1)
print "The calendar has updated successfully!"
print calendar
elif user_choice == "A":
event = raw_input("Enter Event: ")
date = raw_input("Enter date(MM/DD/YYYY): ")
if len(date) > 10 or (int(date[6:] < int(strftime("%Y")))):
print "The date provided is not in the accepted format!"
try_again = raw_input("Would you like to try again? Y for Yes, N for No: ")
try_again = try_again.upper()
if try_again == "Y":
continue
else:
start = False
else:
calendar[date] = event
print "The event was successfully added to the calendar! "
elif user_choice == "D":
if len(calendar.keys()) == 0:
print "The calendar is empty and there is nothing to delete! "
else:
event = raw_input("What event? ")
for date in calendar.keys():
if event == calendar[date]:
del calendar[date]
print "The event was successfully deleted!"
print calendar
else:
print "The event provided is incorrect"
elif user_choice == "X":
start = False
else:
print "Invalid command was entered! "
start_calendar()
| true |
7fc53c96a3cfdadd93c48fffd1c1179c52119ef4 | ortizjs/algorithms_ | /InterviewCakeProblems/reverse_words.py | 1,853 | 4.125 | 4 | # def reverse_words(message):
# mess1 = "".join(message)
# # print mess1
# mess2 = mess1.split(" ")
# # print mess2
# lower = 0
# upper = len(mess2) - 1
# while lower < upper:
# temp = mess2[lower]
# mess2[lower] = mess2[upper]
# mess2[upper] = temp
# lower += 1
# upper -= 1
# return " ".join(mess2)
def reverse_words(message):
# First we reverse all the characters in the entire message
reverse_characters(message, 0, len(message)-1)
# This gives us the right word order
# but with each word backward
# Now we'll make the words forward again
# by reversing each word's characters
# We hold the index of the *start* of the current word
# as we look for the *end* of the current word
current_word_start_index = 0
for i in xrange(len(message) + 1):
# Found the end of the current word!
if (i == len(message)) or (message[i] == ' '):
reverse_characters(message, current_word_start_index, i - 1)
# If we haven't exhausted the message our
# next word's start is one character ahead
current_word_start_index = i + 1
return "".join(message)
def reverse_characters(message, left_index, right_index):
# Walk towards the middle, from both sides
while left_index < right_index:
# Swap the left char and right char
message[left_index], message[right_index] = \
message[right_index], message[left_index]
left_index += 1
right_index -= 1
print reverse_words(['c', 'a', 'k', 'e', ' ',
'p', 'o', 'u', 'n', 'd', ' ',
's', 't', 'e', 'a', 'l'])
print reverse_words(['t', 'h', 'e', ' ', 'e', 'a', 'g', 'l', 'e', ' ',
'h', 'a', 's', ' ', 'l', 'a', 'n', 'd', 'e', 'd'])
| true |
a4ee1cb6352cb07b932d1b8c0540c2326a02fdd9 | ortizjs/algorithms_ | /python-practice/permutation_palindrome.py | 788 | 4.28125 | 4 | # Write an efficient function that checks whether any permutation of an input string is a palindrome.
# You can assume the input string only contains lowercase letters.
# Examples:
# "civic" should return True
# "ivicc" should return True
# "civil" should return False
# "livci" should return False
def permutation_palindrome(string):
unpaired_chars = set()
for char in string:
if char not in unpaired_chars:
unpaired_chars.add(char)
else:
unpaired_chars.remove(char)
return len(unpaired_chars) <= 1
print(permutation_palindrome('civic'))
print(permutation_palindrome('ivicc'))
print(permutation_palindrome('civil'))
print(permutation_palindrome('mom'))
print(permutation_palindrome('dad'))
print(permutation_palindrome('father'))
| true |
0e8619e739be81640b2d3ceefd204b3b1cc719e8 | dmellors/raspberry_pi_projects | /led_dice.py | 2,066 | 4.25 | 4 | # Simulate a random dice roll with LED's
import RPi.GPIO as GPIO
import time
import random
# list containing LED GPIO pin numbers
LED = [18,23,24,25]
button = 7
# set GPIO mode of operation to BCM
GPIO.setmode(GPIO.BCM)
# disable GPIO warning events if pin already in use
GPIO.setwarnings(False)
# Initialise the operational state of each GPIO pin note button pin is set to IN as will recieve an input when button is pressed.
GPIO.setup(LED[0], GPIO.OUT, initial = 0)
GPIO.setup(LED[1], GPIO.OUT, initial = 0)
GPIO.setup(LED[2], GPIO.OUT, initial = 0)
GPIO.setup(LED[3], GPIO.OUT, initial = 0)
GPIO.setup(button, GPIO.IN)
print ("Press the button to roll the dice!")
try:
while True:
# if button is pressed then:
if GPIO.input(button) == 1:
# first reset/turn off all LED's that were showing any previous result
for x in range (4):
GPIO.output(LED[x], 0)
# Sleep for half a second to allow user to release button otherwise mulitple results are displayed.
time.sleep(0.5)
# Generate a random number between 1 and six if the button is pressed and display correct LED dice pattern
rolled_number = random.randrange(1,7)
print ("You rolled a: ", rolled_number)
print ("Press the button to roll dice again!")
# Light up the appropiate LEDs to display the result
# if a 1 is thrown
if rolled_number == 1:
GPIO.output(LED[1], 1)
# if a 2 is thrown
if rolled_number == 2:
GPIO.output(LED[3], 1)
# if a 3 is thrown
if rolled_number == 3:
GPIO.output(LED[1], 1)
GPIO.output(LED[3], 1)
# if a 4 is thrown
if rolled_number == 4:
GPIO.output(LED[0], 1)
GPIO.output(LED[2], 1)
# if a 5 is thrown
if rolled_number == 5:
GPIO.output(LED[0], 1)
GPIO.output(LED[1], 1)
GPIO.output(LED[2], 1)
# if a 6 is thrown
if rolled_number == 6:
GPIO.output(LED[0], 1)
GPIO.output(LED[2], 1)
GPIO.output(LED[3], 1)
# if user exits program by pressing control-C then exit and reset all GPIO pins on the raspberry pi
except KeyboardInterrupt:
GPIO.cleanup() | true |
a345653ad591247131defb6abcffe2a27112104c | zingpython/february2018 | /day_one/Exercise5.py | 257 | 4.1875 | 4 | side1 = input("Enter a side: ")
side2 = input("Enter a side: ")
side3 = input("Enter a side: ")
if side1 == side2 and side2 == side3:
print("Equilateral")
elif side1 == side2 or side2 == side3 or side1 == side3:
print("Isosceles")
else:
print("Scalene") | false |
e336c02a69906b8398611692056c7321f42a1403 | zingpython/february2018 | /day_six/insertionSort.py | 1,201 | 4.40625 | 4 | #Create function for insertion sort. This takes in a list to be sorted
def insertionSort(starting_list):
#Index is the current index we are comparing and sorting
index = 0
#Run the code until every index has been sorted
while index < len(starting_list):
print(starting_list)
#FOr each index check every index before it
for back_index in range(index,-1,-1):
#If the value at index is greater than the value at back_index
if starting_list[index] > starting_list[back_index]:
#insert the value at index after back_index
temp_value = starting_list.pop(index)
starting_list.insert( back_index+1, temp_value )
#Once we find the value to insert after end the for loop
break
#If the value at index is less than all other values and back index is the last index
elif back_index == 0 and starting_list[index] < starting_list[back_index]:
#Insert the value at the begining of the list
temp_value = starting_list.pop(index)
starting_list.insert(0, temp_value)
#After sorting index move on the the next index
index = index + 1
#WHen the while loop finishes return the sorted list
return starting_list
print( insertionSort( [10,15,1,-7,8,10,108] ) ) | true |
d7301742aa00db6f8eb207b5927db0cc43e472d3 | jsong00505/CodingStudy | /coursera/algorithms/part1/week2/stacks_and_queues/permutation.py | 401 | 4.1875 | 4 | from coursera.algorithms.part1.week2.stacks_and_queues.randomized_queue import RandomizedQueue
class Permutation:
def __init__(self, k, s):
self.k = k
self.s = s.split()
def permutation(self):
queue = RandomizedQueue()
for i in self.s:
queue.enqueue(i)
it = queue.iterator()
for i in range(self.k):
print(it.next())
| false |
08f30ed72d62fc7864c105c3c4297c081cf69343 | ArhamChouradiya/Python-Course | /07dictionary.py | 359 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 4 02:15:36 2019
@author: arham
"""
dict={1:"John",2:"Bob",3:"Bill"}
#print(dict)
#print(dict.items())
k=dict.keys()
for i in k: #access keys
print(i)
v=dict.values()
for i in v: #access values
print(i)
#print(dict[3])
del dict[2] #delete element
| false |
835bc940203b3a7ce1d71ac96d756409334c5c18 | Dallas-Johnson-Dev/AlgorithmsLowestCostPath | /lowestcost.py | 2,030 | 4.125 | 4 | """
Python Program written to find the lowest cost path from the bottom row of a grid to the top.
Written by Dallas Johnson
Requires one input which is the size of the grid. The grid is an N x N size grid, so only one positive integer is needed.
"""
import random
from sys import argv
class GridTile:
value = None
cache = None
def __init__(self):
self.value = random.randrange(1, 20)
def __add__(self, other):
return self.value + other.value
def main():
if len(argv) < 1:
print("Usage: python3 lowestcost.py size")
print("Grid size needed for algorithm to run on.")
return
grid = buildGrid(4)
print("our answer should be: ")
print(findLowestPath(grid,0,0,4))
print(str(grid))
def buildGrid(size):
algorithmgrid = [[0 for x in range(size)] for x in range(size)]
for x in range(0, size):
for y in range(0, size):
algorithmgrid[x][y] = GridTile()
return algorithmgrid
def findLowestPath(grid,x,y,size):
if y == size:
return
lowestx = x
lowestvalue = grid[x][y].value
for i in range(0,size-1):
if grid[i+1][y].value < lowestvalue:
lowestvalue = grid[i+1][y].value
lowestx = i+1
else:
return lowestvalue + solveLowestPath(grid, lowestx, y+1, size)
def solveLowestPath(grid, x, y, size):
lowestValue = grid[x][y].value
lowestx = x
if x-1 in range(-1,size):
if grid[x-1][y].value < lowestValue:
lowestValue = grid[x][y].value
lowestx = x-1
if x+1 in range(-1,size):
if grid[x+1][y].value < lowestValue:
lowestValue = grid[x+1][y].value
lowestx = x+1
if y+1 == size:
return lowestValue
else:
return lowestValue + solveLowestPath(grid, lowestx, y+1, size)
def printGrid(gridToPrint, size):
for x in range(0,size):
print("\n")
for y in range(0,size):
print(gridToPrint[x][y].value)
if __name__ == "__main__":
main()
| true |
205c589c1f5b97c86b5fa75481d6b87577f6457f | Preetpalkaur3701/Python | /bitonic_sort.py | 1,616 | 4.28125 | 4 | # Python program for Bitonic Sort. Note that this program
# works only when size of input is a power of 2.
# The parameter direction indicates the sorting direction, ASCENDING
# or DESCENDING; if (a[i] > a[j]) agrees with the direction,
# then a[i] and a[j] are interchanged.
def compAndSwap(array, i, j, direction):
if (
direction == 1 and array[i] > array[j]
) or (
direction == 0 and array[i] < array[j]
):
array[i], array[j] = array[j], array[i]
# if direction = 1, and in descending order otherwise (means direction=0).
# The sequence to be sorted starts at index position low,
# the parameter array_length is the number of elements to be sorted.
def bitonic_merge(array, low_index, array_length, direction):
if array_length > 1:
k = int(array_length / 2)
for i in range(low_index, low_index + k):
compAndSwap(array, i, i + k, direction)
bitonic_merge(array, low_index, k, direction)
bitonic_merge(array, low_index + k, k, direction)
# sorting its two halves in opposite sorting orders, and then
# calls bitonic_merge to make them in the same order
def bitonic_sort(a, low_index, array_length, direction):
if array_length > 1:
k = int(array_length / 2)
bitonic_sort(a, low_index, k, 1)
bitonic_sort(a, low_index + k, k, 0)
bitonic_merge(a, low_index, array_length, direction)
if __name__ == "__main__":
array = [2, 3, 4, 6, 10, 1, 8, 7, 9, 5]
low_index = 0
array_length = 10
direction = 1
bitonic_sort(array, low_index, array_length, direction)
print(array)
| true |
09bfa0b20170187deeef2b87220cd36f6bcfe7e4 | Preetpalkaur3701/Python | /order.py | 375 | 4.3125 | 4 | # Append Dictionary Keys and Values ( In order ) in dictionary
from itertools import chain
# initializing dictionary
my_dict = {"I" : 1, "am" : 3, "the" : 2, "BEST" : 4}
print("The original dictionary is : " + str(my_dict))
#appending the dictionary
new_dict = list(chain(my_dict.keys(), my_dict.values()))
print("The ordered keys and values : " + str(new_dict))
| true |
a1e87853999274b199f412078a7f4dba9c5fb440 | shills112000/django_course | /PYTHON/DATE-CALENDAR/patch_tuesday.py.old | 2,199 | 4.3125 | 4 | #!/usr/bin/python3.6
import calendar
import datetime
#https://www.w3schools.com/python/python_datetime.asp
x = datetime.datetime.now()
#print(x)
#print(x.year)
#print(x.month)
#print(x.day)
#print(x.strftime("%A")) # FULL DAY
#print(x.strftime("%b")) # short month
#print(x.strftime("%B")) # full month
# Show every month
for month in range(1, 13):
cal = calendar.monthcalendar(2020, month)
first_week = cal[0]
second_week = cal[1]
third_week = cal[2]
# If a Tuesday presents in the first week, the second Tuesday
# is in the second week. Otherwise, the second Tuesday must
# be in the third week.
if first_week[calendar.TUESDAY]:
patch_tuesday = second_week[calendar.TUESDAY]
else:
patch_tuesday = third_week[calendar.TUESDAY]
# print(f"patch_tuesday :{patch_tuesday}")
# print('%3s: %2s' % (calendar.month_abbr[month], patch_tuesday))
def path_day_calc(day,month,year,patch_day_plus=0): # = this puts a default value
print (f"day: {day}")
print (f"month: {month}")
print (f"year: {year}")
print (f"path_day_plus: {patch_day_plus}")
day = day + patch_day_plus
print (f"new patch day: {day}")
day = day + patch_day_plus
if ( month == 12) :
print ("set month to Jan 2021")
year +=1
month = 1
print (f"month: {month}")
print (f"year: {year}")
else:
month = month+1
cal = calendar.monthcalendar(year, month)
first_week = cal[0]
second_week = cal[1]
third_week = cal[2]
# If a Tuesday presents in the first week, the second Tuesday
# is in the second week. Otherwise, the second Tuesday must
# be in the third week.
if first_week[calendar.TUESDAY]:
patch_tuesday = second_week[calendar.TUESDAY]
else:
patch_tuesday = third_week[calendar.TUESDAY]
patch_tuesday_plus_date = patch_day_plus + patch_tuesday
print(f"patch_tuesday = {patch_tuesday}")
print(f"patch_tuesday_plus_date = {patch_tuesday_plus_date}")
print(f"checking month = {month} ")
print(f"checking year = {year}")
today_date = datetime.datetime.now()
path_day_calc(today_date.day,12,today_date.year,2)
| true |
9487d17d790c6f66438d80d4cedba7b778d105a7 | shills112000/django_course | /PYTHON/STATEMENTS_WHILE_FOR_IF/useful_operators.py | 1,733 | 4.15625 | 4 | #!/usr/local/bin/python3.7
mylist = [1,2,3]
#range (start,stop[,step[])
# This will pring all number up to 10 starting at 0
for num in range(10):
print (num)
for num in range(3,10): # start are 3 go up to 10
print (num)
for num in range(0,10,2): # start at 0 going to up to 10 steping two at a time , even numbers
print (num)
mylist= list(range(0,11,2)) # cast the range to a list start at 0 up to 11 stepping 2
for num in mylist:
print (num)
index_count = 0
for letter in 'abcde':
print (f"At index {index_count} the letter is {letter}")
index_count +=1
# to do the above use the enumerate counter
index_count = 0
word = 'abcde'
for item in enumerate(word):
print (item) # show in tuple
for count,letter in enumerate(word):
print (f"number is {count}")
print (f"letter is {letter}")
# zip function , zip togher two list
mylist1 =[1,2,3,4]
mylist2 =['a','b','c']
for item in zip(mylist1,mylist2):
print (item)
# can use 3 lists or more with zip
mylist3 = [100,200,300]
for item in zip(mylist1,mylist2,mylist3):
print (item)
print ("put in to new_list a zip")
new_list=list(zip(mylist1,mylist2,mylist3))
for entry in new_list:
print (entry)
# in keyword searches for the entry in the list
if 1 in [1,2,3]:
print (" 1 is in the list")
if 'a' in 'is it an animal':
print (" a is in the word")
if 'mykey' in {'mykey':3}:
print ("mykey is in the dictionary")
d={'mykey':345}
if 345 in d.values():
print ("345 is in dictionary value")
if 'mykey' in d.keys():
print ("mykey is in the dict")
#min : show the minimum value
mylist = [10,20,30,40]
print (min(mylist))
# max : show max value
mylist = [10,20,30,40]
print (max(mylist))
# IMPOT
| true |
8302bfb9bcb5228c8a0ac92d63bbafcf7937adb9 | shills112000/django_course | /PYTHON/OBJECT_ORIENTATED_PROGRAMING/polymorphism.py | 993 | 4.25 | 4 | #!/usr/local/bin/python3.7
#Inheritance
#form new classes using classes that have already been defined.
# polymophism , refers to the way in different object classes can share same method name.
class Animal(): # Base class
def __init__(self,name):
self.name = name
def speak(self):
raise NotImplementedError("subclass must implement this abstract method")
class Dog():
def __init__(self,name):
self.name = name
def speak(self):
return self.name + " says woof!"
class Cat():
def __init__(self,name):
self.name = name
def speak(self):
return self.name + " says meow!"
max = Dog("max")
felix = Cat("felix")
print (f"{max.speak()}")
print (f"{felix.speak()}")
for pet in [max,felix]:
print (type(pet))
print (type(pet.speak()))
print (pet.speak())
def pet_speak(pet):
print (f"function pet_speak {pet.speak()}")
pet_speak(max)
pet_speak(felix)
my_animal=Animal('Fred')
my_animal.speak()
| true |
c1aa7cef2ceb1b17887c45cf442ef7b6ece52ceb | shills112000/django_course | /PYTHON/STATEMENTS_WHILE_FOR_IF/boolean_comparisons.py | 740 | 4.15625 | 4 | #!/usr/local/bin/python3.7
print( 2 == 2) # True
print( 2 == 1) # False
print ( 'hello' == 'bye') # False
print ('2' == 2 ) # False as one is a string, one is a number
print (2.0 == 2 ) # True even when using ints and floating points
print (3 != 3) # False as 3 is = 3
print (4 != 5) # true 4 is not equal to 5
print ( 2 > 1) # False
print ( 1 > 2) # True
print ( 1 < 2) # true
print ( 2 < 5) # true
print (2 >= 2) # ture as equal to
print (4 <= 6) # true
print (1 < 2 and 2 > 3) # False
print ('h' == 'h' and 2 == 2 ) # True
print ( 2 > 3 or 5 > 6) # False
print ( 2 > 3 or 5 > 6) # False
print ( 2 > 1 or 5 > 6) # True
print ( 1 > 2 or 5 > 4) # True
print ( not (1==1)) # It reverese the oposite boolean eg False
| true |
89e3818196b7c7364fc2e5b4369eb63213be9471 | juliocesardiaz/lpthw | /ex33/ex33.py | 479 | 4.15625 | 4 | def looper(x, increment):
i = 0
numbers = []
while i < x:
print "At the top i is %d" % i
numbers.append(i)
i += increment
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
def for_looper(x):
numbers = range(x)
print "The numbers: "
for num in numbers:
print num
looper(6, 1)
looper(3, 1)
looper(20, 2)
for_looper(6) | true |
9679509720a8f00a1fc92285f6bc4110dd1ec9e4 | karolinanikolova/SoftUni-Software-Engineering | /3-Python-Advanced (May 2021)/02-Tuples-and-Sets/02_Exercises/02-Sets-of-Elements.py | 859 | 4.15625 | 4 | # 2. Sets of Elements
# Write a program that prints a set of elements. On the first line, you will receive two numbers - n and m,
# which represent the lengths of two separate sets. On the next n + m lines you will receive n numbers,
# which are the numbers in the first set, and m numbers, which are in the second set.
# Find all the unique elements that appear in both and print them on separate lines (the order does not matter).
# For example:
# Set with length n = 4: {1, 3, 5, 7}
# Set with length m = 3: {3, 4, 5}
# Set that contains all the elements that repeat in both sets -> {3, 5}
n, m = input().split()
n = int(n)
m = int(m)
first_set = set()
second_set = set()
for _ in range(n):
first_set.add(input())
for _ in range(m):
second_set.add(input())
intersection = first_set.intersection(second_set)
[print(el) for el in intersection] | true |
be15efd47f50e86e0f1a2c10ad0aa47372b34fc1 | karolinanikolova/SoftUni-Software-Engineering | /3-Python-Advanced (May 2021)/04-Comprehensions/02_Exercises/07-Flatten-Lists.py | 497 | 4.375 | 4 | # 7. Flatten Lists
# Write a program to flatten several lists of numbers, received in the following format:
# String with numbers or empty strings separated by '|'.
# Values are separated by spaces (' ', one or several)
# Order the output list from the last to the first received, and their values from left to right as shown below.
result = [string.split() for string in input().split('|')][::-1]
flatten_result = [el for sublist in result for el in sublist]
print(*flatten_result) | true |
85261586cefefbe35e2d0bb6949de0e17d85dbf9 | karolinanikolova/SoftUni-Software-Engineering | /3-Python-Advanced (May 2021)/01-Lists-as-Stacks-and_Queues/02_Exercises/07-Robotics-NOT-DONE.py | 2,424 | 4.125 | 4 | # 7. *Robotics
# Somewhere in the future, there is a robotics factory. The current project is assembly line robots.
# Each robot has a processing time – it is the time in seconds the robot needs to process a product.
# When a robot is free it should take a product for processing and log his name, product and processing start time.
# Each robot processes a product coming from the assembly line. A product is coming from the line each second
# (so the first product should appear at [start time + 1 second]). If a product passes the line and there is not a
# free robot to take it, it should be queued at the end of the line again.
# The robots are standing on the line in the order of their appearance.
from collections import deque
from datetime import datetime, timedelta
data = input().split(';')
time = datetime.strptime(input(), '%H:%M:%S')
robots = []
available_robots = deque()
products = deque()
for el in data:
robot_data = el.split('-')
robot = {}
robot['name'] = robot_data[0]
robot['processing_time'] = int(robot_data[1])
robot['available_at'] = time
robots.append(robot)
available_robots.append(robot)
product = input()
while not product == 'End':
products.append(product)
product = input()
time = time + timedelta(seconds=1)
while products:
current_product = products.popleft()
if available_robots:
current_robot = available_robots.popleft()
current_robot['available_at'] = time + timedelta(seconds=current_robot['processing_time'])
robot = [el for el in robots if el == current_robot][0]
robot['available_at'] = time + timedelta(seconds=current_robot['processing_time'])
print(f"{robot['name']} - {current_product} [{time.strftime('%H:%M:%S')}]")
else:
for r in robots:
if time >= robot['available_at']:
available_robots.append(r)
if not available_robots:
products.append(current_product)
else:
current_robot = available_robots.popleft()
current_robot['available_at'] = time + timedelta(seconds=current_robot['processing_time'])
robot = [el for el in robots if el == current_robot][0]
robot['available_at'] = time + timedelta(seconds=current_robot['processing_time'])
print(f"{robot['name']} - {current_product} [{time.strftime('%H:%M:%S')}]")
time = time + timedelta(seconds=1) | true |
d241f7c3c5539d110722527a197dba0560112b18 | karolinanikolova/SoftUni-Software-Engineering | /2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/00-Exam-Prep/01_Mid_Exam_Prep/03-Programming-Fundamentals-Mid-Exam-Retake/01-Counter-Strike.py | 1,467 | 4.25 | 4 | # Problem 1. Counter Strike
# Write a program that keeps track of every won battle against an enemy.
# You will receive initial energy.
# Afterwards you will start receiving the distance you need to go to reach an enemy until the "End of battle" command is given, or until you run out of energy.
# The energy you need for reaching an enemy is equal to the distance you receive.
# Each time you reach an enemy, your energy is reduced. This is considered a successful battle (win).
# If you don't have enough energy to reach an the enemy, print:
# "Not enough energy! Game ends with {count} won battles and {energy} energy"
# and end the program.
# Every third won battle increases your energy with the value of your current count of won battles.
# Upon receiving the "End of battle" command, print the count of won battles in the following format:
# "Won battles: {count}. Energy left: {energy}"
initial_energy = int(input())
command = input()
energy = initial_energy
count_won_battles = 0
while command != "End of battle" and initial_energy > 0:
distance = int(command)
if distance > energy:
print(f"Not enough energy! Game ends with {count_won_battles} won battles and {energy} energy")
break
energy -= distance
count_won_battles += 1
if count_won_battles % 3 == 0:
energy += count_won_battles
command = input()
if command == "End of battle":
print(f"Won battles: {count_won_battles}. Energy left: {energy}")
| true |
2ada51562fcc5a4ca7001ec06c36fe59cfeb906a | karolinanikolova/SoftUni-Software-Engineering | /2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/06-Objects-and-Classes/02_Exercises/06-Inventory.py | 1,311 | 4.1875 | 4 | # 6. Inventory
# Create a class Inventory. The __init__ method should accept only the capacity of the inventory.
# The capacity should be a private attribute (__capacity). You can read more about private attributes here.
# Each inventory should also have an attribute called items, where all the items will be stored. The class should also have 3 methods:
# • add_item(item) - adds the item in the inventory if there is space for it. Otherwise, returns
# "not enough room in the inventory"
# • get_capacity() - returns the value of __capacity
# • __repr__() - returns "Items: {items}.\nCapacity left: {left_capacity}". The items should be separated by ", "
class Inventory:
def __init__(self, capacity):
self.__capacity = capacity
self.items = []
def add_item(self, item):
if len(self.items) < self.__capacity:
self.items.append(item)
else:
return "not enough room in the inventory"
def get_capacity(self):
return self.__capacity
def __repr__(self):
return f"Items: {', '.join(self.items)}.\nCapacity left: {self.__capacity - len(self.items)}"
inventory = Inventory(2)
inventory.add_item("potion")
inventory.add_item("sword")
print(inventory.add_item("bottle"))
print(inventory.get_capacity())
print(inventory)
| true |
e2440695bc953bf52f81cdc173fd65332e977049 | karolinanikolova/SoftUni-Software-Engineering | /2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/01-Basic-Syntax-Conditional-Statements-and-Loops/02_Exercises/04_Double-Char.py | 269 | 4.25 | 4 | # 4. Double Char
# Given a string, you have to print a string in which each character (case-sensitive) is repeated.
text = input()
# for char in text:
# print(char * 2, end='')
result_text = ''
for char in text:
result_text += 2 * char
print(result_text)
| true |
07163e679661baceb76c37114044834ae6399e59 | karolinanikolova/SoftUni-Software-Engineering | /2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/09-Regular-Expressions/02_Exercises/01-Capture-the-Numbers.py | 470 | 4.34375 | 4 | # 1. Capture the Numbers
# Write a program that finds all numbers in a sequence of strings.
# The output is all the numbers, extracted and printed on a single line – each separated by a single space.
import re
text_line = input()
pattern = r"\d+"
all_numbers = []
# while not text_line == "":
while text_line:
numbers = re.findall(pattern, text_line)
all_numbers.extend(numbers)
text_line = input()
# print(" ".join(all_numbers))
print(*all_numbers) | true |
c5d08c23be0a89c4ab2bfffbe278b44f47b21b56 | karolinanikolova/SoftUni-Software-Engineering | /1-Python-Programming-Basics (Sep 2020)/Course-Exercises-and-Exams/04_For-Loop/01.Lab-05-Character-Sequence.py | 386 | 4.28125 | 4 | # 5. Поток от символи
# Напишете програма, която чете текст(стринг), въведен от потребителя и печата всеки символ от текста на отделен ред.
text = input()
for i in range(0, len(text)):
print(text[i])
# # Other method:
# text = input()
#
# for i in text:
# print(i)
| false |
abbfbafe78e9d27763b339725b8ec35a4a46d1c9 | karolinanikolova/SoftUni-Software-Engineering | /1-Python-Programming-Basics (Sep 2020)/Course-Exercises-and-Exams/01_First-Steps-in-Coding/03.More-Exercise-10-Weather-Forecast-Part-2.py | 862 | 4.46875 | 4 | # 10. Прогноза за времето – част 2
# Напишете програма, която при въведени градуси (реално число) принтира какво е времето, като имате предвид следната таблица:
# Градуси Време
# 26.00 - 35.00 Hot
# 20.1 - 25.9 Warm
# 15.00 - 20.00 Mild
# 12.00 - 14.9 Cool
# 5.00 - 11.9 Cold
# Ако се въведат градуси, различни от посочените в таблицата, да се отпечата "unknown".
weather = float(input())
if 26.00 <= weather <= 35.00:
print(f"Hot")
elif 20.1 <= weather <= 25.9:
print(f"Warm")
elif 15.00 <= weather <= 20.00:
print(f"Mild")
elif 12.00 <= weather <= 14.9:
print(f"Cool")
elif 5.00 <= weather <= 11.9:
print(f"Cold")
else:
print("unknown") | false |
4c071d858db81b95e975f8a0343ecf822b5015f7 | karolinanikolova/SoftUni-Software-Engineering | /1-Python-Programming-Basics (Sep 2020)/Course-Exercises-and-Exams/01_First-Steps-in-Coding/02.Exercise-02-Rad-to-Deg.py | 627 | 4.25 | 4 | # 2. Конзолен конвертор: от радиани в градуси
# Напишете програма, която чете ъгъл в радиани (rad) и го преобразува в градуси (deg). Принтирайте получените градуси като цяло число използвайки math.floor.
# Използвайте формулата: градуси = радиани * 180 / π. Числото π в Python може да достъпите чрез модула
from math import pi
from math import floor
rad = float(input())
deg = rad * 180 / pi
print(floor(deg))
| false |
d9412baec333d4eeca3624fbff2282a1e7b47e26 | karolinanikolova/SoftUni-Software-Engineering | /1-Python-Programming-Basics (Sep 2020)/Course-Exercises-and-Exams/03_Conditional-Statements-Advanced/00.Book-Exercise-4.1-04-Fruit-or-Vegetables.py | 656 | 4.34375 | 4 | # плод или зеленчук
# Нека проверим дали даден продукт е плод или зеленчук. Плодовете "fruit" са banana, apple, kiwi, cherry, lemon и grapes.
# Зеленчуците "vegetable" са tomato, cucumber, pepper и carrot. Всички останали са "unknown"
product = input()
if product == 'banana' or product == 'apple' or product == 'kiwi' or product == 'cherry' or product == 'lemon' or product == 'grapes':
print('fruit')
elif product == 'tomato' or product == 'cucumber' or product == 'pepper' or product == 'carrot':
print('vegetable')
else:
print('unknown') | false |
1f38f6f6c5589bb6af149a195593be239f59de2d | karolinanikolova/SoftUni-Software-Engineering | /3-Python-Advanced (May 2021)/04-Comprehensions/01_Lab/01-ASCII-Values.py | 298 | 4.28125 | 4 | # 1. ASCII Values
# Write program that receives a list of characters separated by ", " and creates a dictionary with each character
# as a key and its ASCII value as a value. Try solving that problem using comprehensions.
dictionary = {ch: ord(ch) for ch in input().split(', ')}
print(dictionary) | true |
c84a065c48fcf55dfb3b9cabef4b7ebb3a5daa30 | karolinanikolova/SoftUni-Software-Engineering | /1-Python-Programming-Basics (Sep 2020)/Course-Exercises-and-Exams/01_First-Steps-in-Coding/00.Book-Exercise-2.1-09-Celsius-to-Fahrenheit.py | 409 | 4.5 | 4 | # cantilever converter - from degrees ° C to degrees ° F
# Write a program that reads degrees on the Celsius scale (° C) and converts them to degrees on the Fahrenheit scale (° F).
# Search the Internet for a suitable formula to perform the calculations. Round the result to 2 characters after the decimal point .
celsius = float(input())
fahrenheit = round(((celsius * 9 / 5) + 32), 2)
print(fahrenheit) | true |
8ab62ad0f771f7a9ff9584f8658ba95b43e9eeca | karolinanikolova/SoftUni-Software-Engineering | /1-Python-Programming-Basics (Sep 2020)/Course-Exercises-and-Exams/01_First-Steps-in-Coding/00.Book-Exercise-2.1-02-Inch-to-cm.py | 216 | 4.5 | 4 | # transfer from inches to centimeters
# Let's write a program that reads a fractional number in inches and turns it into centimeters:
inches = float(input('Inches = '))
cm = inches * 2.54
print('Centemeters = ', cm) | true |
8234875c60ac230a706483af3dafb4607ee676a2 | karolinanikolova/SoftUni-Software-Engineering | /2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/05-Lists-Advanced/02_Exercises/01-Which-are-in.py | 544 | 4.125 | 4 | # 1. Which Are In?
# Given two lists of strings print a new list of the strings that contains words from the first list which are substrings
# of any of the strings in the second list (only unique values)
first_string = input().split(", ")
second_string = input().split(", ")
result = []
result = [el_1 for el_1 in first_string for el_2 in second_string if el_1 in el_2]
# for el_1 in first_string:
# for el_2 in second_string:
# if el_1 in el_2:
# result.append(el_1)
print(sorted(set(result), key = result.index)) | true |
a0789b7ead629decb63e12a02a564f5714f3662f | karolinanikolova/SoftUni-Software-Engineering | /2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/01-Basic-Syntax-Conditional-Statements-and-Loops/01_Lab/02_Number-Definer.py | 655 | 4.375 | 4 | # 2. Number Definer
# Write a program that reads a floating-point number and prints "zero" if the number is zero.
# Otherwise, print "positive" or "negative". Add "small" if the absolute value of the number is less than 1,
# or "large" if it exceeds 1 000 000.
number = float(input())
if number == 0:
print('zero')
if number > 0:
if number > 1000000:
print('large positive')
elif number < 1:
print('small positive')
else:
print('positive')
if number < 0:
if abs(number) > 1000000:
print('large negative')
elif abs(number) < 1:
print('small negative')
else:
print('negative')
| true |
ab300331451196893a2ee98a123402acfcf8ac20 | karolinanikolova/SoftUni-Software-Engineering | /3-Python-Advanced (May 2021)/01-Lists-as-Stacks-and_Queues/02_Exercises/06-Balanced-Parentheses.py | 1,592 | 4.125 | 4 | # 6. Balanced Parentheses
# You will be given a sequence consisting of parentheses. Your job is to determine whether the expression is balanced.
# A sequence of parentheses is balanced if every opening parenthesis has a corresponding closing parenthesis that occurs
# after the former. There will be no interval symbols between the parentheses. You will be given three types of parentheses: (, {, and [.
# {[()]} - Parentheses are balanced.
# (){}[] - Parentheses are balanced.
# {[(])} - Parentheses are NOT balanced.
parentheses = input()
is_balanced = True
opening = []
mapper = {'{': '}', '[': ']', '(': ')'}
for p in parentheses:
if p in "{[(":
opening.append(p)
else:
if opening:
current_opening_p = opening.pop()
if not mapper[current_opening_p] == p:
is_balanced = False
break
else:
is_balanced = False
if is_balanced:
print("YES")
else:
print("NO")
# # Solution 2
# from collections import deque
#
# string = deque(input())
#
# stack = []
#
# is_balanced = True
#
# mapper = {'}': '{', ']': '[', ')': '('}
#
# while string:
# string_first_character = string.popleft()
# if string_first_character in "{[(":
# stack.append(string_first_character)
# else:
# if stack:
# stack_last_character = stack.pop()
# if not mapper[string_first_character] == stack_last_character:
# is_balanced = False
# else:
# is_balanced = False
# if is_balanced:
# print("YES")
# else:
# print("NO") | true |
a99ae46ca13a1dc80d2c1f8e9ccda8c1bb8d7186 | karolinanikolova/SoftUni-Software-Engineering | /2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/00-Exam-Prep/01_Mid_Exam_Prep/04-Programming-Fundamentals-Mid-Exam/02-Shopping-List.py | 1,797 | 4.21875 | 4 | # Problem 2. Shopping List
# It’s the end of the week and it is time for you to go shopping, so you need to create a shopping list first.
# Input
# You will receive an initial list with groceries separated by "!".
# After that you will be receiving 4 types of commands, until you receive "Go Shopping!"
# • Urgent {item} - add the item at the start of the list.
# If the item already exists, skip this command.
# • Unnecessary {item} - remove the item with the given name, only if it exists in the list.
# Otherwise skip this command.
# • Correct {oldItem} {newItem} – if the item with the given old name exists, change its name with the new one.
# If it doesn't exist, skip this command.
# • Rearrange {item} - if the grocery exists in the list, r
# move it from its current position and add it at the end of the list.
shopping_list = input().split("!")
command_data = input()
while command_data != "Go Shopping!":
command_data = command_data.split()
command = command_data[0]
if command == "Urgent":
item = command_data[1]
if item not in shopping_list:
shopping_list.insert(0, item)
elif command == "Unnecessary":
item = command_data[1]
if item in shopping_list:
shopping_list.remove(item)
elif command == "Correct":
old_item = command_data[1]
new_item = command_data[2]
if old_item in shopping_list:
index = shopping_list.index(old_item)
shopping_list[index] = new_item
elif command == "Rearrange":
item = command_data[1]
if item in shopping_list:
index = shopping_list.index(item)
shopping_list.pop(index)
shopping_list.append(item)
command_data = input()
print(*shopping_list, sep=", ")
| true |
12a2374d1ad6933ce1c608be3db936c602be1563 | karolinanikolova/SoftUni-Software-Engineering | /2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/05-Lists-Advanced/02_Exercises/04-Office-Chairs.py | 2,135 | 4.1875 | 4 | # 4. Office Chairs
# So you've found a meeting room - phew! ' \
# 'You arrive there ready to present, and find that someone has taken one or more of the chairs!! ' \
# 'You need to find some quick.... check all the other meeting rooms to see if all of the chairs are in use.
# You will be given a number n representing how many rooms there are.
# On the next n lines for each room you will get how many chairs there are and how many of them will be taken.
# The chairs will be represented by "X"s, then there will be a space " " and a number representing the taken places.
# Example: "XXXXX 4" (5 chairs and 1 of them is left free). Keep track of the free chairs, you will need them later.
# However if you get to a room where there are more people than chairs, print the following message:
# "{needed_chairs_in_room} more chairs needed in room {number_of_room}". If there is enough chairs in each room print: \
# "Game On, {total_free_chairs} free chairs left"
# rooms_count = int(input())
#
# free_chairs_in_each_room = []
# enough_chairs_in_each_room = True
#
# for room in range(1, rooms_count + 1):
# room_chairs = input().split()
# free_chairs_in_room = len(room_chairs[0]) - int(room_chairs[1])
# if free_chairs_in_room < 0:
# print(f"{abs(free_chairs_in_room)} more chairs needed in room {room}")
# enough_chairs_in_each_room = False
# else:
# free_chairs_in_each_room.append(free_chairs_in_room)
#
# if enough_chairs_in_each_room:
# print(f"Game On, {sum(free_chairs_in_each_room)} free chairs left")
rooms_count = int(input())
free_chairs_in_each_room = []
enough_chairs_in_each_room = True
for room in range(1, rooms_count + 1):
room_chairs, n_people = input().split()
free_chairs_in_room = len(room_chairs) - int(n_people)
if free_chairs_in_room < 0:
print(f"{abs(free_chairs_in_room)} more chairs needed in room {room}")
enough_chairs_in_each_room = False
else:
free_chairs_in_each_room.append(free_chairs_in_room)
if enough_chairs_in_each_room:
print(f"Game On, {sum(free_chairs_in_each_room)} free chairs left") | true |
74894d7a10bd1878b8975413aa84e9eff487c2e0 | karolinanikolova/SoftUni-Software-Engineering | /2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/04-Functions/02_Exercises/01-Smallest-of-Three-Numbers.py | 415 | 4.34375 | 4 | # 1. Smallest of Three Numbers
# Write a function which receives three integer numbers and returns the smallest. Use appropriate name for the function.
def smallest_of_three_numbers(num1, num2, num3):
return min(num1, num2, num3)
first_number = int(input())
second_number = int(input())
third_number = int(input())
result = smallest_of_three_numbers(first_number, second_number, third_number)
print(result) | true |
72e0d3596a600d4c1366bd720c0048b3e7497a40 | karolinanikolova/SoftUni-Software-Engineering | /2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/04-Functions/01_Lab/01-Grades.py | 695 | 4.3125 | 4 | # Write a function that receives a grade between 2.00 and 6.00 and prints the corresponding grade in words
# • 2.00 – 2.99 - "Fail"
# • 3.00 – 3.49 - "Poor"
# • 3.50 – 4.49 - "Good"
# • 4.50 – 5.49 - "Very Good"
# • 5.50 – 6.00 - "Excellent"
def convert_grade_to_text_grade(grade_as_num):
if 2 <= grade_as_num <= 2.99:
return "Fail"
elif 3 <= grade_as_num <= 3.49:
return "Poor"
elif 3.5 <= grade_as_num <= 4.49:
return "Good"
elif 4.5 <= grade_as_num <= 5.49:
return "Very Good"
elif 5.5 <= grade_as_num <= 6:
return "Excellent"
grade = float(input())
result = convert_grade_to_text_grade(grade)
print(result)
| true |
5d085e1b34012f7a8ae1ce129a77bd77c51bbad3 | karolinanikolova/SoftUni-Software-Engineering | /1-Python-Programming-Basics (Sep 2020)/Course-Exercises-and-Exams/03_Conditional-Statements-Advanced/00.Book-Exercise-4.1-02-Small-Shop.py | 1,351 | 4.15625 | 4 | # квартално магазинче
# Предприемчив българин отваря по едно квартално магазинче в няколко града с различни цени за следните продукти:
#
# По даден град (стринг), продукт (стринг) и количество (десетично число) да се пресметне цената.
product = input()
city = input()
quantity = float(input())
price = 0
if city == 'Sofia':
if product == 'coffee':
price = 0.50
elif product == 'water':
price = 0.80
elif product == 'beer':
price = 1.20
elif product == 'sweets':
price = 1.45
elif product == 'peanuts':
price = 1.60
elif city == 'Plovdiv':
if product == 'coffee':
price = 0.40
elif product == 'water':
price = 0.70
elif product == 'beer':
price = 1.15
elif product == 'sweets':
price = 1.30
elif product == 'peanuts':
price = 1.50
elif city == 'Varna':
if product == 'coffee':
price = 0.45
elif product == 'water':
price = 0.70
elif product == 'beer':
price = 1.10
elif product == 'sweets':
price = 1.35
elif product == 'peanuts':
price = 1.55
sum = price * quantity
print(f'{sum}') | false |
65d9e7e6eb505218efc0da6b5ff7fbe8f7797d46 | shivamrastogi4/MyProject | /Matrix.py | 1,109 | 4.1875 | 4 | from numpy import *
arr = array([('shivam', 22, 3, 4), (1, 2, 3, 4)])
arr1 = array([
[1, 2, 3, 4, 5, 6],
[5, 6, 7, 8, 9, 10]
])
arr11 = array([
[1, 2, 3, 4],
[5, 6, 7, 8]
])
# print(arr.dtype) print(arr1.ndim) print(arr.shape)
print(arr.size) # size of entire block i.e. how manny elements are present
# print(arr1.__sizeof__())
# how to create an array2 with all the elements of array 1 but arr2 will be 1D array
arr2 = arr1.flatten()
print(arr2)
arr3 = arr2.reshape(3, 4) # reshape the arr2 array which is in 2D to give arr3 of size 3*4 3 rows and 4 columns
print(arr3)
# arr4=arr2.reshape(3,2,2) #it will create 3 subarrays of size 2*2 from arr2 which is 1D array of 12 elements
# (3,2,2) will have three 2D arrays and each 2D array will have 2 1D arrays and each 1D array will habe 2 values
# print(arr4)
# converting 2D array in matrix format
m = matrix(arr11) # in this we can do matrix operations
print(m)
m1=matrix('1,2,3;4,5,6;7,8,9')
m2=matrix('1,2,3;4,5,6;7,8,9')
print(m1)
print(diagonal(m1)) #it prints diagonal elements of matrix
print(m1*m2) | true |
3adb3e9b17f458acec92bbbeb30f66846ed55d4a | SACHSTech/ics2o-livehack1-practice-Tyler-Ku | /minutes_days.py | 667 | 4.3125 | 4 | """
-------------------------------------------------------------------------------
Name: minutes_days.py
Purpose: Write a program that lets you enter a number of minutes, and that will calculate
the number of days, hours and minutes that represents (Hint: use the modulus operator).
Author: Ku.T
Created: 02/09/2021
------------------------------------------------------------------------------
"""
minutes = int(input("Minutes: "))
days = minutes//1440
days_remainder = minutes % 1440
hours = days_remainder//60
hours_remainder = days_remainder
minutes
print(days, hours)
#print("There are", days, "days and", remainder,"hours in", hours, "hours") | true |
02590ed7b8c9120798df10e7182a9afc2a1e35ca | Lormenyo/Data-Structures-And-Algorithms | /linkedlist.py | 2,357 | 4.4375 | 4 | # singly linked list is a collection of nodes
# head and tail of a linkedlist
# going through the nodes is called traversing the linkedlist(link hopping or pointer hopping)
# Linked list does not have a predetermined fixed size
# It uses space proportionally to the number of elements
# nodes are pointers in python
# the data and address of the next location of the data element is stored.
# Inserting elements in a linked list involves reassigning the pointers from the existing nodes to newly inserted node.
class Node:
def __init__(self, ele):
self.ele = ele
self.next_ele = None
class Linkedlist:
def __init__(self):
self.head = None
def traverse(self):
first_ele = self.head
while first_ele is not None:
print(first_ele.ele)
first_ele = first_ele.next_ele
# insert node at the beginning
def insertBegin(self, new_ele):
new_node = Node(new_ele)
new_node.next_ele = self.head # change the new_node's next element to the existing head
self.head = new_node
# insert node at the end
def insertEnd(self, new_ele):
new_node = Node(new_ele)
if self.head is None:
self.head = new_node
return
last_ele = self.head
while (last_ele.next_ele):
last_ele = last_ele.next_ele
# assign last element to te new node
last_ele.next_ele = new_node
def InsertBetween(self, new_ele, existing_node):
if existing_node is None:
print("Node is absent")
return
new_node = Node(new_ele)
# the next node of the existing node is referenced by the new node
new_node.next_ele = existing_node.next_ele
existing_node.next_ele = new_node
a = Node(1)
b = Node(2)
c = Node(3)
llist = Linkedlist()
llist.head = a
# Link first node to the seond node
llist.head.next_ele = b
# link the second node to the third node
b.next_ele = c
# insert node at the beginning
llist.insertBegin(7)
# insert node at the end
llist.insertEnd(8)
# insert node after the second node
llist.InsertBetween(9, llist.head.next_ele)
# traverse through the linked list
llist.traverse()
| true |
ab122b9bc224e4f975015703d25328507ddf681a | SEEVALAPERIYA/python | /palindrome or not .py | 288 | 4.15625 | 4 | num=input('enter any number:')
try:
val=int(num)
if num==str(num)[::-1]:
print('the given number is palindrome')
else:
print('the given number is not palindrome')
except value error:
print("that' 5 not a valid number,try again!")
| true |
55cdc37d569e34e14015d514f9cf82701915a070 | ebnezerdaniel/PythonPractise | /CircleArea.py | 400 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[9]:
#solving directly using the formula
# In[12]:
Circle=float(input('Radius of Circle:'))
Area=(22/7)*(Circle**2)
print('Area of a circle', Area)
# In[ ]:
# In[10]:
#importing math package and pi function
# In[11]:
from math import pi
Circle=float(input('Radius of Circle:'))
Area=(pi)*(Circle**2)
print('Area of a circle', Area)
| true |
e7534d1e0ccaf9b3818a4d2852c2a6780805899b | game-racers/Python-Projects | /Computer Science 131/Lab4/Lab4Q1 RPS.py | 2,784 | 4.1875 | 4 | import random
userWins = 0
compWins = 0
ties = 0
playing = "yes"
cF = 1
while playing == "yes" or playing == "Yes" or playing == "y":
while cF == 1:
player = str(input("Rock, Paper, or Scissors? "))
if player == "rock" or player == "Rock":
cF = 0
player = "Rock"
elif player == "paper" or player == "Paper":
cF = 0
player = "Paper"
elif player == "scissors" or player == "Scissors":
cF = 0
player = "Scissors"
#Converts player to first capital letter if possible and checks if correct format
cpu = random.randint(1,3)
if cpu == 1:
computer = "Rock"
elif cpu == 2:
computer = "Paper"
elif cpu == 3:
computer = "Scissors"
#above lets the computer choose values and what roll it does
#the line above is only there to separate the second line and the
#line below this one.
if player == "Rock":
if computer == "Rock":
print("You and the Machine chose Rock!")
print("This match is a tie.")
ties += 1
elif computer == "Paper":
print("You chose", player, "and The Machine chose", computer)
print("You Lose. Get Gud.")
compWins += 1
elif computer == "Scissors":
print("You chose", player, "and The Machine chose", computer)
print("You Win!")
userWins += 1
elif player == "Paper":
if computer == "Paper":
print("You and the Machine chose Paper!")
print("This match is a tie.")
ties += 1
elif computer == "Scissors":
print("You chose", player, "and The Machine chose", computer)
print("You Lose. Get Gud.")
compWins += 1
elif computer == "Rock":
print("You chose", player, "and The Machine chose", computer)
print("You Win!")
userWins += 1
elif player == "Scissors":
if computer == "Scissors":
print("You and the Machine chose Scissors!")
print("This match is a tie.")
ties += 1
elif computer == "Rock":
print("You chose", player, "and The Machine chose", computer)
print("You Lose. Get Gud.")
compWins += 1
elif computer == "Paper":
print("You chose", player, "and The Machine chose", computer)
print("You Win!")
userWins += 1
cF = 1
print("Your wins:", userWins)
print("Computer wins:", compWins)
print("Ties:", ties)
playing = str(input("Continue Playing? (Yes or No)"))
player = "pineapple"
print("Loop is over")
| true |
76bcdf6d4d3ee2ebeefff6d67e251ff771086103 | iAbhishek91/algorithm | /basics/20_for.py | 240 | 4.5 | 4 | # for loops are used for special purpose, looping through collection for example
for char in "cat":
print(char)
for item in [10, 20, 30]:
print(item)
for index in range(5):
print(index)
for num in range(3, 8):
print(num) | true |
e2abc9a3b5f54cd6699b37968bd9ebd06907ff56 | siuols/Python-Basics | /strings.py | 2,216 | 4.21875 | 4 | def init():
input_string = input("Enter a string: ")
count = 0
upper_string(input_string)
lower_string(input_string)
count_string(input_string)
convertion_to_list(input_string)
indexing(input_string)
count_string(input_string)
reverse(input_string)
slicing(input_string)
start_end(input_string)
split(input_string)
def upper_string(input_string):
upper = input_string.upper()
print("String {} is uppered case.".format(upper))
def lower_string(input_string):
lower = input_string.lower()
print("String {} is lowered case.".format(lower))
def count_string(input_string):
print("the total length of {} is : {}".format(input_string, len(input_string)))
def convertion_to_list(input_string):
string_list = list(input_string)
print(string_list)
def indexing(input_string):
#this method only recognizes the first 'o'.
print("number of 'o' is {} is: {}".format(input_string, input_string.index("o")))
def count_string(input_string):
#this method counts the all 'l or L' in the string
print("number of 'l' is {} is: {}".format(input_string,input_string.count("l")))
def reverse(input_string):
reverse_word = ""
i = len(input_string)-1
while(i != -1):
reverse_word += input_string[i]
i-=1
print("The reverse string of {} is {}".format(input_string, reverse_word))
def slicing(input_string):
#This prints the characters of string from 3 to 7 skipping one character. This is extended slice syntax. The general form is [start:stop:step].
print("string from 3 to 7 skipping one character is: " + input_string[3:7:1])
def start_end(input_string):
#This is used to determine whether the string starts with something or ends with something, respectively. The first one will print True,
print("if the inputted string starts with 'hello' it will return to : {}".format(input_string.startswith("Hello")))
print("if the inputted string starts with 'hello' it will return to : {}".format(input_string.endswith("world")))
def split(input_string):
#This splits the string into a bunch of strings grouped together in a list.
word = input_string.split(" ")
print(word)
init() | true |
87301903697605cf31598371c50d0ca080f70a40 | tigju/Data-Structures | /stack/stack.py | 2,016 | 4.1875 | 4 | """
A stack is a data structure whose primary purpose is to store and
return elements in Last In First Out order.
1. Implement the Stack class using an array as the underlying storage structure.
Make sure the Stack tests pass.
2. Re-implement the Stack class, this time using the linked list implementation
as the underlying storage structure.
Make sure the Stack tests pass.
3. What is the difference between using an array vs. a linked list when
implementing a Stack?
"""
### 1. implementation using arrays
# class Stack:
# def __init__(self):
# self.size = 0
# self.storage = []
# def __len__(self):
# return len(self.storage)
# def push(self, value):
# self.storage.append(value)
# return self.storage
# def pop(self):
# if self.__len__() > 0:
# x = self.storage.pop()
# return x
# else:
# return None
## 2. Re-implement using LinkedList class
from singly_linked_list import LinkedList
class Stack(LinkedList):
def __init__(self):
super().__init__()
self.size = 0
# def __str__(self):
# temp = self.head
# stk = []
# while temp:
# stk.append(temp)
# temp = temp.get_next()
# return f"{[v.get_value() for v in stk]}"
def __len__(self):
return self.size
def push(self, value):
# use inherited add_to_tail() of a LinkedList class
self.add_to_tail(value)
self.size += 1
def pop(self):
if self.size == 0:
return None
self.size -= 1
# use inherited remove_tail() from LinkedList class
return self.remove_tail()
def peek(self):
return f"{self.tail.get_value()}"
# stack1 = Stack()
# stack1.push(10)
# stack1.push(15)
# print(stack1.head)
# print(len(stack1))
# print(stack1.peek())
# print(stack1)
| true |
77b7c59fe238344aa47f0bc163b949029bec514b | roseleonard/Calculator | /clac.py | 2,554 | 4.25 | 4 | # print("Hello calculator")
# #Add 2 numbers
# number1 = input("Give me a number.")
# number2 = input("What's the second number?")
# def addition(number1,number2):
# step1 = int(number1) + int(number2)
# return step1
# def mulitplication(number1,number2):
# step1 = int(number1) * int(number2)
# return step1
# def division(number1,number2):
# step1 = int(number1) / int(number2)
# return step1
# def subtraction(number1,number2):
# step1 = int(number1) - int(number2)
# return step1
# #2 function calculator
# function = input("""
# What operation would you like to perform?
# a = addition
# b = multiplication
# c = division
# d = subtraction"""
# )
# if function == "a":
# print(addition(number1,number2))
# elif function == "b":
# print(mulitplication(number1,number2))
# elif function == "c":
# print(division(number1,number2))
# elif function == "c":
# print(subtraction(number1,number2))
# else:
# print("Please enter a,b,c,or d")
birth_month = input("What is your birth month? (mm)")
birth_date = input("What is your birthday? (dd)")
if int(birth_month + birth_date) >= 120 and int(birth_month + birth_date) <= 218:
print("You are an Aquarius!")
elif int(birth_month + birth_date) >= 219 and int(birth_month + birth_date) <= 320:
print("You are a Pisces!")
elif int(birth_month + birth_date) >= 321 and int(birth_month + birth_date) <= 419:
print("You are an Aries!")
elif int(birth_month + birth_date) >= 420 and int(birth_month + birth_date) <= 520:
print("You are a Taurus!")
elif int(birth_month + birth_date) >= 521 and int(birth_month + birth_date) <= 620:
print("You are a Gemini!")
elif int(birth_month + birth_date) >= 621 and int(birth_month + birth_date) <= 722:
print("You are a Cancer!")
elif int(birth_month + birth_date) >= 723 and int(birth_month + birth_date) <= 822:
print("You are a Leo!")
elif int(birth_month + birth_date) >= 823 and int(birth_month + birth_date) <= 922:
print("You are a Virgo!")
elif int(birth_month + birth_date) >= 923 and int(birth_month + birth_date) <= 1022:
print("You are a Libra!")
elif int(birth_month + birth_date) >= 1023 and int(birth_month + birth_date) <= 1121:
print("You are a Scorpio!")
elif int(birth_month + birth_date) >= 1122 and int(birth_month + birth_date) <= 1221:
print("You are a Sagittarius!")
elif int(birth_month + birth_date) >= 119 or int(birth_month + birth_date) <= 1222:
print("You are a Capricorn!")
| true |
0504ecb6223a0ddeeac88283648cedc4a4245be8 | AdriGeaPY/programas1ava | /zprimero/IF/5.simbolo.py | 270 | 4.3125 | 4 | print("digame un simbolo")
simbolo=input()
if simbolo == "1"or simbolo =="2"or simbolo =="3"or simbolo =="4"or simbolo =="5"or simbolo =="6"or simbolo =="7"or simbolo =="8"or simbolo =="9"or simbolo =="0":
print("esto es un digito")
else:
print("esto es un simbolo") | false |
48855e160b7e907ba6f977f791d3214bde446487 | nidhi76/PPL20 | /assign4/shapes/s-p/inhe14.py | 683 | 4.5625 | 5 | # draw color filled circle in turtle
import turtle
# creating turtle pen
t = turtle.Turtle()
# taking input for the radius of the circle
r = int(input("Enter the radius of the circle: "))
# taking the input for the color
col = input("Enter the color name or hex value of color(# RRGGBB): ")
# set the fillcolor
t.fillcolor(col)
# start the filling color
t.begin_fill()
# drawing the circle of radius r
t.circle(r)
# ending the filling of the color
t.end_fill()
t.penup()
t.forward(150)
t.pendown()
# start the filling color
t.begin_fill()
# drawing the circle of radius r
t.circle(r)
# ending the filling of the color
t.end_fill()
turtle.done()
| true |
cc20bebc598d46425282f7fea40b75d09d2a005c | tapanprakasht/Simple-Python-Programs | /palindrome.py | 420 | 4.375 | 4 | #!/usr/bin/python3
# Program to check the given string is palindrome or not
def main():
str=input("Enter the string:")
length=len(str)
length=length-1
i=0
flag=True
while i<=length:
if str[i]!=str[length]:
flag=False
break
i+=1
length-=1
if flag==False:
print("{} is not palindrome".format(str))
else:
print("{} is palindrome".format(str))
if __name__=="__main__":main() | true |
72e1c0f68d30f93c2a3f3c6cbee42dfc803e226d | tapanprakasht/Simple-Python-Programs | /Amstrong.py | 595 | 4.15625 | 4 | #!/usr/bin/python3
# Program to check whether the given number is amstrong or not
class Amstrong:
def __init__(self):
self.num=0
def getNumber(self):
self.num=int(input("Enter the number:"))
def checkNumber(self):
n=self.num
mod=0
s=0
while n>0:
mod=n%10
s=s+(mod*mod*mod)
n=n//10
if self.num == s:
print("{} is an Amstrong number".format(self.num))
else:
print("{} is not an Amstrong number".format(self.num))
def main():
a=Amstrong()
a.getNumber()
a.checkNumber()
if __name__=="__main__":main()
| true |
ae546e105853163ff1287d0ac57f364b6052407c | tapanprakasht/Simple-Python-Programs | /Calc.py | 1,134 | 4.21875 | 4 | #!/usr/bin/python3
# Simple calculator program in Python
class Calc:
def __init__(self):
self.num1=0
self.num2=0
def getNumber(self):
self.num1=int(input("Enter the first number:"))
self.num2=int(input("Enter the second number:"))
def showMenu(self):
print("\nSimple Calculator\n1.Add\n2.Subtract\n3.Multiply\n4.Divide\n5.Exit")
def findSum(self):
return self.num1+self.num2
def findDiff(self):
return self.num1-self.num2
def findMul(self):
return self.num1*self.num2
def findDiv(self):
return self.num1/self.num2
def main():
c=Calc()
c.showMenu()
choice=int(input("Enter your choice:"))
while choice!=5:
c.getNumber()
if choice==1:
print("{} + {} = {}".format(c.num1,c.num2,c.findSum()))
elif choice==2:
print("{} - {} = {}".format(c.num1,c.num2,c.findDiff()))
elif choice==3:
print("{} * {} = {}".format(c.num1,c.num2,c.findMul()))
elif choice==4:
print("{} / {} = {}".format(c.num1,c.num2,c.findDiv()))
c.showMenu()
choice=int(input("Enter your choice:"))
if __name__=="__main__":main() | false |
70b93e79428b23c6689a33ed1e295ee3562395b5 | allualexander333/Python-Workshop | /BB-Level1-Assignment.py | 993 | 4.28125 | 4 | #!/usr/bin/env python
#Print the current date and time at the start of the program (hint: use the datetime library and search the internet)
import datetime
now = datetime.datetime.now()
print ("Current date and time using str method of datetime object : ")
print (now)
#Print out all the even numbers from the below given list of numbers. Write the solution into a function and have it called in your main block for the requested answer (hint: use loops)
def even(l):
enumerate = []
for a in l:
if a % 2 == 0:
enumerate.append(a)
return enumerate
print(even([951,402,984,651,360,69,408,319,601,485,980,507,725,547,544,615,83,165,141,501,263,617,865,575,219,390,984,592,236,105,942,941,386,462,47,418,907,344,236,375,823,566,597,978,328,615,953,345,399,162,758,219,918,237,412,566,826,248,866,950,626,949,687,217,815,67,104,58,512,24,892,894,767,553,81,379,843,831,445,742,717,958,609,842,451,688,753,854,685,93,857,440,380,126,721,328,753,470,743,527]))
| true |
984eb23b3b158cc488aecdbaea5c7982e20bffb1 | Vickykathe/ejerciciosPython | /1 Generalidades inicio Python.py | 1,973 | 4.46875 | 4 | # Comentarios de una sola linea
""" comentarios multi linea
con triple comilla doble
al principio y final """
''' comentarios multi linea
con triple comilla doble
al principio y final '''
# una funcion es un subprograma que realiza una accion especifica ... nombreFuncion(informacionRequerida)
# print() ... es la funcion que presenta en pantalla la informacion del parentesis (datos, variables, etc) ... SALIDAS
# type() ... es la funcion que determina el tipo o natrualeza del dato del parentesis.
# Algunos Tipos de datos: TEXTO (String ... Str), NUMERICOS (int y float) , Booleanos (True , False)
# El tupe() por si solo en ejecucion no presenta ninguna respuesta
type("Juan Perez")
print("Juan Perez")
print(type("Juan Perez"))
print(10)
print(type(10))
print(10000000)
print(type(10000000))
print(1.75)
print(type(1.75))
print(True)
print(type(False))
# Variables ... consideraciones a tener en cuenta en la definicion de nombres de variables
'''camel case
nombreEstudiante'''
#nombre_estudiante
nombre="Juan Perez"
print(nombre)
print(type(nombre))
edad=10
print(edad)
print(type(edad))
estatura=1.75
print(estatura)
print(type(estatura))
soltero=True
print(soltero)
print(type(soltero))
''' La funcion input() ... permite ingresar datos por teclado. Esta informacion es de tipo texto
si quisieramos tratarla de tipo numerico (entero o decimal) ... se debe convertir. '''
''' La funcion int() convierte un dato tipo texto en uno numerico entero
la funcion float() convierte un dato tipo texto en uno numerico decimal '''
nombre=input("Digite nombre del estudiante: ")
print(nombre)
print(type(nombre))
peso=input("Digite el peso del estudiante: ")
print(peso)
print(type(peso))
print(peso*2)
edadEstudiante=int(input("Digite edad del estudiante "+nombre+" : "))
print(edadEstudiante)
print(type(edadEstudiante))
print(edadEstudiante*2)
estatura=float(input("Digite estatura del estudiante: "))
print(estatura)
print(type(estatura))
print(estatura/2) | false |
01a0a97d8baf150e6e2a7d587192440ee134760d | sageetemple/Templeton_Sage | /Py.Lesson04/average_global.py | 344 | 4.15625 | 4 | num1=float(input("What is your first number: "))
num2=float(input("What is your second number: "))
num3=float(input("What is your third number: "))
avg=0
def average():
global avg
avg =(num1+num2+num3)/3
def display():
print("The average of", num1, ",", num2, ", and", num3, "is", "{:00.5f}".format(avg))
average()
display()
| true |
86b10245d0bec09d06900d1a6cbfc5ae0ad734ef | psavery/python-ci-test | /python_ci_test/dot_product.py | 488 | 4.28125 | 4 | #!/usr/bin/env python3
"""
Calculate the dot product of two lists.
"""
def dot_product(list_a, list_b):
"""
Calculate the dot product of two lists.
Args:
list_a: the first list
list_b: the second list
Returns: The dot product of the two lists.
"""
if len(list_a) != len(list_b):
raise ValueError('The lists must be of the same length')
sum = 0
for i in range(len(list_a)):
sum += list_a[i] * list_b[i]
return sum
| true |
342893be942041b1bc3a7a15ee61fbcb154c1a5d | rkechols/Advent2020 | /day23/cup_game.py | 2,545 | 4.15625 | 4 | import time
from typing import Dict, Tuple
STARTING_CUP_ORDER = "916438275"
SECTION_SIZE = 3
BIGGEST_CUP_NUMBER = 1000000
MOVE_COUNT = 10000000
def get_starting_cup_dict(big: bool) -> Tuple[Dict[int, int], int, int, int]:
cups_list = [int(label) for label in STARTING_CUP_ORDER]
biggest = max(cups_list)
if big:
cups_list += list(range(biggest + 1, BIGGEST_CUP_NUMBER + 1))
n = len(cups_list)
to_return = dict()
for i in range(n):
i_next = (i + 1) % n
to_return[cups_list[i]] = cups_list[i_next]
return to_return, cups_list[0], min(cups_list), max(cups_list)
def make_move(cups: Dict[int, int], current: int, lowest: int, highest: int) -> Tuple[Dict[int, int], int]:
# take out the 3 cups
temp = current
removed = list()
for _ in range(SECTION_SIZE):
temp = cups[temp]
removed.append(temp)
first_after_removed = cups[temp]
cups[current] = first_after_removed
# figure out what cup we'll put them after
# try "current - 1"
destination_label = current - 1
if destination_label < lowest: # wrap to the highest label
destination_label = highest
while destination_label in removed:
# not available; try the next one down
destination_label -= 1
if destination_label < lowest: # wrap to the highest label
destination_label = highest
# put the 3 cups after the destination cup
after_destination = cups[destination_label]
cups[destination_label] = removed[0]
cups[removed[-1]] = after_destination
# return the cup after the current cup the new current cup
return cups, cups[current]
if __name__ == "__main__":
# part 1
time_start = time.time()
cup_circle, current_cup, low, high = get_starting_cup_dict(big=False)
for _ in range(100):
cup_circle, current_cup = make_move(cup_circle, current_cup, low, high)
cup_circle_list = list()
c = cup_circle[1]
while c != 1:
cup_circle_list.append(c)
c = cup_circle[c]
answer = "".join([str(c) for c in cup_circle_list])
print(f"PART 1: order after 1: {answer}")
time_end = time.time()
print(f"time elapsed for part 1: {time_end - time_start} sec")
print()
# part 2
time_start = time.time()
cup_circle, current_cup, low, high = get_starting_cup_dict(big=True)
for _ in range(MOVE_COUNT):
cup_circle, current_cup = make_move(cup_circle, current_cup, low, high)
after_1 = cup_circle[1]
after_that = cup_circle[after_1]
# this takes, like, 8 days. so, run it in Java?
print(f"PART 2: product of 2 cup labels just after 1: {after_1 * after_that}")
time_end = time.time()
print(f"time elapsed for part 2: {time_end - time_start} sec")
| true |
16b799364af10c38349da2505583deef599a0e14 | Chenkehan21/Learn-Python-with-Crossin | /小组作业三.py | 486 | 4.15625 | 4 | # 字符串拼接
# 通过 % 将 name, age, code 拼接成一句话
# 输出 Crossin is 18, he writes Python.
name = 'Crossin'
age = 18
code = 'Python'
print("%s is %d, he writes %s" % (name, age, code))
# 类型转换
num1 = '3.3'
num2 = 2.5
num1 = float(num1)
print(num1 + num2)
# bool
print(bool(-123))
print(bool(0)) # pay attention!
print(bool('abc'))
print(bool('False'))
print(bool(''))
print(bool([]))
print(bool({}))
print(bool(['']))
print(bool(None)) | false |
04a646303d7f530ef9f49333b6a3c777c36d3b8a | joseeden/notes-cbt-nuggets-devasc | /Notes_0-9/4-Observer.py | 1,652 | 4.21875 | 4 |
#******************************************************************************************************************#
# 4-Observer.py
#******************************************************************************************************************#
# 2021-01-04 05:43:06
# This is the code used in '2-Understanding_Design_Patterns.txt'
class Observer():
# This is the function called whenever the subject updates.
def update(self, subject):
print("Observer: My subject just updated and told me about it.")
print("Observer: It's states is now - " + str(subject._state))
class Subject():
_state = 0
_observers = [] # this list will contain all the observer objects
# Add observer to the list
def attach(self, observer):
self._observers.append(observer)
# Remove observer from the list.
def detach(self, observer):
self._observers.remove(observer)
# goes thru the list and update
def notify(self):
print("Subject: I'm notifying my observers ...")
for observer in self._observers:
observer.update(self)
# Updates state, which changes the _state to variable n.
# This also calls the notify() function.
def updateState(self, n):
print("Subject: I have received a state update!")
self._state = n
self.notify()
# Creating the objects
s = Subject()
obj1 = Observer()
obj2 = Observer()
obj3 = Observer()
# Attach the observer objects to the single Subject object.
s.attach(obj1)
s.attach(obj2)
s.attach(obj3)
s.updateState(5)
| true |
a920371734dc8a37ddb9632212616fcd5049cb95 | Oliveira-Renato/ThinkPythonExercices | /ch01/exer1.py | 824 | 4.3125 | 4 | #1. In a print statement, what happens if you leave out one of the parentheses, or both?
#print('Hello, World!'
#R:SyntaxError: invalid syntax
#2. If you are trying to print a string, what happens if you leave out one of the quotation marks,or both?
#print('Here we go)
#R: EOL while scanning string literal
#3. You can use a minus sign to make a negative number like -2. What happens if you put a plussign before a number? What about 2++2?
#print(2++2)
#R: Imprime 4 como resultado,sem erros, muito estranho
#4. In math notation, leading zeros are ok, as in 09. What happens if you try this in Python?What about 011?
#print(011)
#R: leading zeros in decimal integer literals are not permitted;
#5. What happens if you have two values with no operator between them?
#print(5 6)
#R: SyntaxError: invalid syntax
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.