blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
71ecdecf27800ad7d75cd6e119fba2697297550e | kolevatov/python_lessons | /week_2/2_16.py | 671 | 4.3125 | 4 | # Сколько совпадает чисел
"""
Даны три целых числа. Определите, сколько среди них совпадающих.
Программа должна вывести одно из чисел: 3 (если все совпадают),
2 (если два совпадает) или 0 (если все числа различны).
Формат ввода
Вводятся три целых числа.
Формат вывода
Выведите ответ на задачу.
"""
A = int(input())
B = int(input())
C = int(input())
if A == B == C:
print(3)
elif A != B != C != A:
print(0)
else:
print(2)
| false |
d53aa56fa01ed85a564a542ece3f9922d428b3a3 | kolevatov/python_lessons | /week_2/2_28.py | 815 | 4.125 | 4 | # Количество элементов, равных максимуму
"""
Последовательность состоит из натуральных чисел и завершается числом 0.
Определите, какое количество элементов этой последовательности,
равны ее наибольшему элементу.
Формат ввода
Вводится последовательность целых чисел, оканчивающаяся числом 0
Формат вывода
Выведите ответ на задачу.
"""
N = 1
max1 = 0
result = 0
while N != 0:
N = int(input())
if N > max1 and N != 0:
max1 = N
result = 1
elif max1 == N and N != 0:
result += 1
print(result)
| false |
8a67eea89f7418421671b4dd7b23a316bbab0a5f | kolevatov/python_lessons | /week5/5_7.py | 640 | 4.3125 | 4 | # Замечательные числа - 1
"""
Найдите и выведите все двузначные числа,
которые равны удвоенному произведению своих цифр.
Формат ввода
Программа не требует ввода данных с клавиатуры,
просто выводит список искомых чисел.
Формат вывода
Выведите ответ на задачу.
"""
def proc(n):
a = n // 10
b = n % 10
return a, b
for i in range(10, 100):
A, B = proc(i)
if i == A * B * 2:
print(i, end=' ')
| false |
6f348b214f3e1ca724a7fbd014fc6c9542b2430c | kolevatov/python_lessons | /week4/4_6.py | 1,089 | 4.1875 | 4 | # Проверка числа на простоту
"""
Дано натуральное число n>1. Проверьте, является ли оно простым.
Программа должна вывести слово YES, если число простое и NO,
если число составное.
Решение оформите в виде функции IsPrime(n), которая возвращает True
для простых чисел и False для составных чисел.
Количество действий в программе должно быть
пропорционально квадратному корню из n.
Формат ввода
Вводится натуральное число.
Формат вывода
Выведите ответ на задачу.
"""
def mindivisor(n):
i = 2
while i <= n ** 0.5:
if n % i == 0:
return i
i += 1
return n
def IsPrime(n):
mdiv = mindivisor(n)
return mdiv == n
N = int(input())
if IsPrime(N):
print('YES')
else:
print('NO')
| false |
51991312ddcb06ce0b84c16e8ec7f2b83725c6da | kolevatov/python_lessons | /list_management.py | 1,559 | 4.15625 | 4 | # Управление списком значений.
# Поддерживает операции: добавить элемент, удалить элемент, распечатать список, сортировать, удалить дубликаты значений
#
scores = []
menu = None
while menu != '0':
print("""
0 - Выход
1 - Добавить элемент
2 - Удалить элемент
3 - Распечатать список
4 - Сортировать список
5 - Удалить дубликаты элементов
""")
menu = input('Ваш выбор? ')
print ('Выбран пункт: ', menu)
if menu == '1':
score = int(input('Новый элемент списка: '))
scores.append(score)
elif menu == '2':
score = int(input('Удалить элемент со значением: '))
if score in scores:
scores.remove(score)
else:
print ('Элемента нет в списке!')
elif menu == '3':
print (scores)
elif menu == '4':
scores.sort()
elif menu == '5':
new_scores = []
for i in scores:
if i not in new_scores:
new_scores.append(i)
scores = new_scores
new_scores = []
elif menu == '0':
None
else:
print ('Нет такого пукта меню!')
input('Нажмите любую кнопку. Программа будет завершена')
| false |
ef5efede1db142e41aba118dc0d78efa371ad209 | vishnuk1994/ProjectEuler | /SumOfEvenFibNums.py | 1,045 | 4.46875 | 4 | #!/bin/python3
import sys
# By considering the terms in the Fibonacci sequence whose values do not exceed N, find the sum of the even-valued terms.
# creating dict to store even fib nums, it helps in reducing time at cost of extra space
# by rough estimate; it is better to use space as for high value of n, it will recalculate the series
mapOfEvenFibNum = {0:0,1:2}
# getting nth even fib num.
# formula used is based on the logic that every third element in fibonacci is even
# refer : https://www.geeksforgeeks.org/nth-even-fibonacci-number/
def getEvenFib(n):
if n in mapOfEvenFibNum:
return mapOfEvenFibNum[n]
return ( 4* getEvenFib(n-1) + getEvenFib(n-2) );
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
count = 1
reqSum = 0
num = getEvenFib(count)
# getting fib num till we reach n
# updating dict with values
while num <= n:
reqSum += num
mapOfEvenFibNum[count] = num
count += 1
num = getEvenFib(count)
print(reqSum)
| true |
f2c0bda23f4292e676e3d246d28f6f158145f7e9 | ibbur/LPTHW | /16_v4.py | 1,017 | 4.25 | 4 | print "What file would you like to open?"
filename = raw_input("> ")
print "Opening the file %r for you..." % filename
review = open(filename)
print review.read()
target = open(filename, 'w')
print "\n"
print "I will now clear the file contents..."
target.truncate()
print "I will now close the file..."
target.close()
print "I will now reopen the file so we can add new text..."
freshfile = open(filename, 'w')
print "Let's write three new lines to the file. Begin entering text..."
line1 = raw_input("1> ")
line2 = raw_input("2> ")
line3 = raw_input("3> ")
print "\n I will now write to the file..."
freshfile.write ('{}\n{}\n{}\n' .format(line1,line2,line3))
freshfile.close()
reviewagain = open(filename)
print "Let's read the file to make sure everything is as it should be..."
print "---------------"
print reviewagain.read()
print "---------------"
print "I will now clean up behind us by closing the file..."
reviewagain.close()
print "The file is now closed, and this exercise is now complete!"
| true |
3dc2910eea2580527783d8e35114c110e44b3f11 | GanSabhahitDataLab/PythonPractice | /Fibonacci.py | 661 | 4.3125 | 4 | # Find PI to the Nth Digit - Enter a number and have the program generate π (pi) up to
# that many decimal places. Keep a limit to how far the program will go
def fibonaccisequence_upton():
askForInput()
def askForInput():
n = int(input("Enter number of Fibonnacci sequence"))
fibgenerated = fibonaccialgorithm(n)
for i in fibgenerated:
print(i)
def fibonaccialgorithm(n):
generated_fib = []
for i in range(0, n):
if i > 1:
generated_fib.append(generated_fib[i - 1] + generated_fib[i - 2])
else:
generated_fib.append(i)
return generated_fib
| true |
226d0e9c413049435046484715560a1a1861dd57 | thu-hoai/daily-coding-practicing | /python/night_at_the_museum.py | 468 | 4.125 | 4 | #!/usr/bin/env python
# https://codeforces.com/problemset/problem/731/A
# Time complexity: O(n)
def calculate_rotations_number(string):
string = 'a' + string
total = 0
for i in range(len(string)-1):
num = abs(ord(string[i+1]) - ord(string[i]))
if num < 13:
total += num
else:
total += (26 - num)
return total
if __name__ == "__main__":
string = input()
print(calculate_rotations_number(string)) | false |
2651c168d0f874b4c897227b11d17cf6678032c9 | roycekumar/C168-Project | /BOOKSHELF.py | 877 | 4.25 | 4 | class Book:
def __init__(self,name,author,price,publishing_year):
self.Book_name=name
self.Book_author=author
self.Book_price=price
self.Book_year=publishing_year
def add_book(self):
print("Book Name: "+str(self.Book_name))
print("Book Author: "+str(self.Book_author))
print("Book Price: "+str(self.Book_price))
print("Book was published in : "+str(self.Book_year))
print("Book added")
def years_since_published(self):
years_ago_published=2021-self.Book_year
print("This book was published "+str(years_ago_published)+" years ago")
Harry_Potter=Book("Harry Potter and Philosopher's Stone","J. K. Rowling",1928,1997)
Harry_Potter.add_book()
Harry_Potter.years_since_published()
Wimpy_Kid=Book("Dairy of a Wimpy Kid","Jeff Kinney",700,2017)
Wimpy_Kid.add_book()
Wimpy_Kid.years_since_published()
| false |
3865e1e3cf60023a368f629cb21a3b163d61fa59 | claudiamorazzoni/problems-sheet-2020 | /Task 6.py | 435 | 4.4375 | 4 | # Write a program that takes a positive floating-point number as input and outputs an approximation of its square root.
# You should create a function called sqrt that does this.
# Please enter a positive number: 14.5
# The square root of 14.5 is approx. 3.8.
import math
num = float(input("Please enter a positive number: "))
sqrt = math.sqrt(num)
print("The square root of {} is approx. {}" .format(num, "%.1f" % sqrt)) | true |
02a11bf65defec6e1280af02fabf2411dea09e85 | Nithinnairp1/Python-Scripts | /lists.py | 1,073 | 4.25 | 4 | my_list = ['p','r','o','b','e']
print(my_list[0])
print(my_list[2])
print(my_list[4])
print(my_list[-1])
n_list = ["Happy", [2,0,1,5]]
print(n_list[0][1])
print(n_list[1][3])
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
odd = [1, 3, 5]
odd.append(7)
print(odd)
odd = [1, 3, 5]
print(odd + [9, 7, 5])
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
print(my_list)
print(my_list.pop(1))
# append() - Add an element to the end of the list
# extend() - Add all elements of a list to the another list
# insert() - Insert an item at the defined index
# remove() - Removes an item from the list
# pop() - Removes and returns an element at the given index
# clear() - Removes all items from the list
# index() - Returns the index of the first matched item
# count() - Returns the count of number of items passed as an argument
# sort() - Sort items in a list in ascending order
# reverse() - Reverse the order of items in the list
# copy() - Returns a shallow copy of the list | true |
9e76ed8832052f6d5066700f222bea4d4df69b50 | TrihstonMadden/Python | /plot-dictionary.py | 1,226 | 4.125 | 4 | # plot-dictionary.py
import tkinter as tk
import turtle
def main():
#table is a dictionary
table = {-100:0,-90:10,-80:20,-70:30,-60:40,-50:50,
-40:40,-30:30,-20:20,-10:10,0:0,
10:10,20:20,30:30,40:40,50:50,
60:40,70:30,80:20,90:10,100:0,
}
print(" KEYS ")
print(table.keys())
print(" VALUES ")
print(table.values())
#turtle graphics
twin = turtle.Screen()
twin.clear()
t = turtle.Turtle()
#tWin = turtle.Screen()
for h,k in table.items(): #get the items in the dictionary
print(h, k) # trace code
#x,y = table[n]
t.speed(.5)
t.penup()
t.goto(h,k)
t.pendown()
t.circle(5)
twin.exitonclick()
main()
"""
This code uses a dictionary with keys ranging from
-100 to 100 incrementing by 10.
Each key has a value of 0 as an integer.
To retrieve the values in the dictionary "table" a for loop is used.
The x cooridate on a python turtle screen corresponds to h while
the y value cooresponds to k.
**************************************
for h,k in table.items(): #get the items in the dictionary
print(h, k) #trace code
h and k are then ploted using
t.goto(h,k)
t.pendown()
t.circle(5)
Change the values from 0 to another integer.
Try to make something grovey.
"""
| true |
111b780e317205805f1d5c230bc16d8f9f55eb78 | jpeggreg/CP1404 | /cp1404practicals/prac_02/Automatic_password_generator_custom.py | 1,931 | 4.40625 | 4 | import random
LOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz"
UPPERCASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
SPECIAL_CHARACTERS = "!@#$%^&*()_-=+`~,./'[]<>?{}|\\"
def main():
"""Program to get password length and number of each type required."""
password_length = int(input("Enter the password length do you require? "))
count_lower = int(input("How many lowercase letters? "))
count_upper = int(input("How many UPPERCASE letters? "))
count_special = int(input("How many special characters? "))
# check the length of password is more than total number of characters user requires
if password_length < (count_lower + count_upper + count_special):
print("Password length is not long enough")
password_length = int(input("Enter the password length do you require? "))
count_lower = int(input("How many lowercase letters? "))
count_upper = int(input("How many UPPERCASE letters? "))
count_special = int(input("How many special characters? "))
else:
password = password_generator(password_length, count_upper, count_lower, count_special)
print("Your password is " + str(password))
# Randomly generates password based on user requirements and stores in a list
# Shuffles list at end and returns random password to main as a string
def password_generator(password_length, count_upper, count_lower, count_special):
password_list = []
for i in range(count_lower):
password_list.append(random.choice(LOWERCASE_LETTERS))
for i in range(count_upper):
password_list.append(random.choice(UPPERCASE_LETTERS))
for i in range(count_special):
password_list.append(random.choice(SPECIAL_CHARACTERS))
for i in range(password_length - len(password_list)):
password_list.append(random.choice(LOWERCASE_LETTERS))
random.shuffle(password_list)
password = "".join(password_list)
return password
main() | false |
0cb9dbd2051790e0992b5a5c55456efe184911d3 | Jethet/Practice-more | /python-katas/EdabPalin.py | 778 | 4.3125 | 4 | # A palindrome is a word, phrase, number or other sequence of characters which
# reads the same backward or forward, such as madam or kayak.
# Write a function that takes a string and determines whether it's a palindrome
# or not. The function should return a boolean (True or False value).
# Should be case insensitive and special characters (punctuation or spaces)
# should be ignored.
import string
def is_palindrome(txt):
exclude = set(string.punctuation)
txt = ''.join(ch for ch in txt if ch not in exclude).replace(' ','').lower()
#print(txt)
return txt == txt[::-1]
print(is_palindrome("A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal-Panama!")) # True
print(is_palindrome("Neuquen")) # True
print(is_palindrome("Not a palindrome")) # False
| true |
b447f6804b1aaf41f103aa9b75afd2814c207163 | Jethet/Practice-more | /small-projects/inverseRandNum.py | 720 | 4.21875 | 4 | import random
# instead of the computer generating a random number, the user is giving the number
def computer_guess(x):
low = 1
high = x
feedback = ""
while feedback != "c":
# you cannot have low and high be the same:
if low != high:
guess = random.randint(low, high)
else:
guess = low # could also be high because low and high are the same here
feedback = input(f"Is {guess} too high (H), too low (L), or correct (C)?".lower())
if feedback == "h":
high = guess - 1
elif feedback == "l":
low = guess + 1
print(f"The computer guessed your number, {guess} correctly!")
computer_guess(10) | true |
22800ea3b59510039284cf345034c94c1ee4b99a | Jethet/Practice-more | /python-katas/3_Sum.py | 239 | 4.1875 | 4 | # Return sum of two int, unless values are the same: then return double.
def sum_double(a, b):
if a == b:
return 2 * (a + b)
else:
return a + b
print(sum_double(1,2))
print(sum_double(3,2))
print(sum_double(2,2))
| true |
3f0aa8fd1025b9f1d919f544cbf78dbc91c44699 | Jethet/Practice-more | /python-katas/EdabAltCaps.py | 362 | 4.4375 | 4 | # Create a function that alternates the case of the letters in a string.
# The first letter should always be UPPERCASE.
def alternating_caps(txt):
print(alternating_caps("Hello")) # "HeLlO"
print(alternating_caps("Hey, how are you?")) # "HeY, hOw aRe yOu?"
print(alternating_caps("OMG!!! This website is awesome!!")) # "OmG!!! tHiS WeBsItE Is aWeSoMe!!"
| true |
394c0e41664f79b95e279ff063f7584a49f675cf | Jethet/Practice-more | /python-katas/EdabCountUniq.py | 384 | 4.28125 | 4 | # Given two strings and a character, create a function that returns the total
# number of unique characters from the combined string.
def count_unique(s1, s2):
return len(set(s1 + s2))
print(count_unique("apple", "play")) #➞ 5
# "appleplay" has 5 unique characters:
# "a", "e", "l", "p", "y"
print(count_unique("sore", "zebra")) #➞ 7
print(count_unique("a", "soup")) #➞ 5
| true |
e398b42c4309d60d59ea97a5e341532502fb0a1c | Jethet/Practice-more | /python-katas/EdabIndex.py | 686 | 4.375 | 4 | # Create a function that takes a single string as argument and returns an
# ordered list containing the indexes of all capital letters in the string.
# Return an empty array if no uppercase letters are found in the string.
# Special characters ($#@%) and numbers will be included in some test cases.
def indexOfCaps(word):
caps_list = []
for x in word:
if x.isupper() == True:
y = word.index(x)
caps_list.append(y)
return caps_list
print(indexOfCaps("eDaBiT")) # [1, 3, 5]
print(indexOfCaps("eQuINoX")) # [1, 3, 4, 6]
print(indexOfCaps("determine")) #[]
print(indexOfCaps("STRIKE")) # [0, 1, 2, 3, 4, 5]
print(indexOfCaps("sUn")) # [1]
| true |
e79e52b336b37444bcdc95b151c50e080e8ab2e3 | Jethet/Practice-more | /python-katas/28_Last2.py | 300 | 4.15625 | 4 | # Given a string, return the count of the number of times that a substring
# length 2 appears in the string and also as the last 2 chars of the string,
# so "hixxxhi" yields 1 (we won't count the end substring).
def last2(str):
x = str[-2:]
return str.count(x) - 1
print(last2('axxxaaxx'))
| true |
3837c735626d9ea89162da3f3f15e3514bcd859a | Jethet/Practice-more | /python-katas/EdabCheckEnd.py | 646 | 4.5 | 4 | # Create a function that takes two strings and returns True if the first
# argument ends with the second argument; otherwise return False.
# Rules: Take two strings as arguments.
# Determine if the second string matches ending of the first string.
# Return boolean value.
def check_ending(str1, str2):
if str1.endswith(str2):
return True
else:
return False
print(check_ending("abc", "bc")) # True
print(check_ending("abc", "d")) # False
print(check_ending("samurai", "zi")) # False
print(check_ending("feminine", "nine")) # True
print(check_ending("convention", "tio")) # False
| true |
baf3c6195df0fc2638e72ae9f9bf4be5bba73e38 | Jethet/Practice-more | /python-katas/EdabTrunc.py | 684 | 4.3125 | 4 | # Create a one line function that takes three arguments (txt, txt_length,
# txt_suffix) and returns a truncated string.
# txt: Original string.
# txt_length: Truncated length limit.
# txt_suffix: Optional suffix string parameter.
# Truncated returned string length should adjust to passed length in parameters
# regardless of length of the suffix.
def truncate(txt, txt_length, *txt_suffix):
return txt[0:txt_length]+str(txt_suffix).strip('()').replace("'", "").replace(",","")
print(truncate("CatDogDuck", 6, "Rat")) # "CatDogRat"
print(truncate("DogCat", 3)) # "Dog"
print(truncate("The quick brown fox jumped over the lazy dog.", 15, "...")) # "The quick br..."
| true |
bd0304c63470267b120d29de75b00b480960a0a7 | Jethet/Practice-more | /python-katas/EdabAddInverse.py | 333 | 4.125 | 4 | # A number added with its additive inverse equals zero. Create a function that
# returns a list of additive inverses.
def additive_inverse(lst):
print(additive_inverse([5, -7, 8, 3])) #➞ [-5, 7, -8, -3]
print(additive_inverse([1, 1, 1, 1, 1])) #➞ [-1, -1, -1, -1, -1]
print(additive_inverse([-5, -25, 35])) #➞ [5, 25, -35]
| true |
5797703b59a09ee3915451417c6e4205feb47ee5 | Marhc/py_praxis | /hello.py | 1,590 | 4.4375 | 4 | """A simple **"Hello Function"** for educational purposes.
This module explores basic features of the Python programming language.
Features included in this module:
- Console Input / Output;
- Function Definition;
- Module Import;
- Default Parameter Values;
- String Interpolation (**'fstrings'**);
- Single line and Multiline comments;
- Docstrings (**'Google Python Style Guide'**);
- 'Falsy' coalescing operator (**'or'**);
- Conditional Statements;
- Custom main entry point and exit point;
- Private function naming convention;
- Special, **'dunder'** or **'magic'** variables;
- Command line arguments handling;
"""
import sys
def hello_user(name=""):
"""Returns a greeting message with the user name.
This is an example of a parameterized function with a default value.
If no name is provided the function returns **"Hello Everyone!"** by default.
Args:
name (str): The user name typed in the Console.
Returns:
str: The greeting message.
"""
return f"Hello { name or 'Everyone' }!"
def _custom_main(argv): # Python has no a default main entry point.
"""Example of a custom main function with command line arguments handling."""
# Avoids an exception if no args. Ternary Operator is more explicit and longer.
user_name = (argv + [""])[1] or input("Type your name: ")
print(hello_user(user_name))
if __name__ == '__main__':
# Skips execution when importing the module,
# but allows it when calling the script.
sys.exit(_custom_main(sys.argv))
| true |
138598c6e37b9b525b779902f4172f40e03ca3c2 | kampanella0o/python_basic | /lesson4_home/l4_ex2.py | 515 | 4.21875 | 4 | n = '0'
while int(n) <= 0:
n = input("Please enter a natural number: ")
try:
int(n)
except ValueError:
print("You should enter a natural number!")
n = '0'
number_of_digits = len(n)
if number_of_digits == 1:
summ_of_digits = n
else:
while number_of_digits != 1:
summ_of_digits = 0
for digit in n:
summ_of_digits += int(digit)
n = str(summ_of_digits)
number_of_digits = len(str(summ_of_digits))
print(summ_of_digits)
| false |
3a18399d699248a6e85fbe96c6c853b5bacdd0ba | kampanella0o/python_basic | /lesson1/ifelse.py | 1,001 | 4.1875 | 4 | # name = "Da"
# if name == "Max":
# print(name)
# else:
# print('Its not Max')
# a = 10
# b = 15
############################################################
# if a == 10:
# c = True
# else:
# if b == 10:
# c = False
# else:
# c = True
# c = True if a == 10 else False if b == 10 else True
# c = True if a == 10 else False
###########################################################
# try:
# print(10/0)
# print(a/10)
# except ZeroDivisionError as e:
# print(e)
# print("OLOLO")
# except NameError:
# print("not defined")
# else: #выполняется если не было поймано эксептов
# print(a)
# finally: #выполняется всегда
# print('eta finish')
###################################################################
try:
a = 10
b = 0
if b!= 0:
c = a/ b
else:
raise Exception('Devision by zero!')
except Exception as e:
print(e)
print("in exception") | false |
cf3c88cf74d7f26207959aaa43329d8332c9a673 | beanj25/Leap-year-program | /jacob_bean_hw1_error_handling.py | 1,020 | 4.125 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Jacob
#
# Created: 15/01/2021
# Copyright: (c) Jacob 2021
# Licence: <your licence>
#-------------------------------------------------------------------------------
def isLeap(year):
if(year%100 == 0):
if((year >=400) and (year%400 == 0)):
return True
return False
elif(year%4 == 0):
return True
else:
return False
def main():
pass
if __name__ == '__main__':
main()
year = input("enter year to check for leep year:")
while(year.isdigit() == False):
year = input("Not valid input, please use numbers")
year = int(year)
while (year <=0):
year = int(input("Invalid Year, please enter a new year above 0:"))
print("is the year "+ str(year) +" a leap year?")
if(isLeap(year) == True):
print ("yes")
else:
print("no")
input("Press Enter to exit") | true |
33b7628e6bdb51f4f146db155335768f3d873892 | Ayesha116/piaic.assignment | /q19.py | 340 | 4.28125 | 4 | #Write a Python program to convert the distance (in feet) to inches, yards, and miles. 1 feet = 12 inches, 3 feet = 1 yard, 5280 feet = 1 mile
feet = float(input("enter height in feet: "))
print(feet,"feet is equal to",feet*12, "inches ")
print(feet, "feet is equal to",feet/3, "yards")
print(feet, "feet is equal to",feet/5280,"miles") | true |
96f67acf3b9cae1727f5ae4737edb54ea4a5f6c1 | helloprogram6/leetcode_Cookbook_python | /DataStruct/BiTree/字典树.py | 1,390 | 4.21875 | 4 | # -*- coding:utf-8 -*-
# @FileName :字典树.py
# @Time :2021/3/20 13:37
# @Author :Haozr
from typing import List
class TrieNode:
def __init__(self, val=''):
self.val = val
self.child = {}
self.isWord = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
t = self.root
for w in word:
if w not in t.child:
t.child[w] = TrieNode(w)
t = t.child[w]
t.isWord = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
t = self.root
for w in word:
if w not in t.child:
return False
t = t.child[w]
if t.isWord:
return True
return False
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
cur = self.root
for w in prefix:
if w not in cur.child:
return False
cur = cur.child[w]
return True
if __name__ == '__main__':
s = Trie()
print(s.insert("Trie"))
print(s.startsWith("a"))
| true |
7c1dfbbc1baf98904272f598608d04659b7b9053 | jorzel/codefights | /arcade/python/competitiveEating.py | 930 | 4.21875 | 4 | """
The World Wide Competitive Eating tournament is going to be held in your town, and you're the one who is responsible for keeping track of time. For the great finale, a large billboard of the given width will be installed on the main square, where the time of possibly new world record will be shown.
The track of time will be kept by a float number. It will be displayed on the board with the set precision precision with center alignment, and it is guaranteed that it will fit in the screen. Your task is to test the billboard. Given the time t, the width of the screen and the precision with which the time should be displayed, return a string that should be shown on the billboard.
Example
For t = 3.1415, width = 10, and precision = 2,
the output should be
competitiveEating(t, width, precision) = " 3.14 ".
"""
def competitiveEating(t, width, precision):
return "{:.{}f}".format( t, precision ).center(width)
| true |
72b951eebf3317d9a36822ef3056129257781ef1 | jorzel/codefights | /challange/celsiusVsFahrenheit.py | 1,549 | 4.4375 | 4 | """
Medium
Codewriting
2000
You're probably used to measuring temperature in Celsius degrees, but there's also a lesser known temperature scale called Fahrenheit, which is used in only 5 countries around the world.
You can convert a Celsius temperature (C) to Fahrenheit (F), by using the following formula:
F = 9 * C / 5 + 32
Your friend lives in Palau (where the Fahrenheit system is used), and you've been trying to find out which of you lives in a warmer climate, so you've each kept track of your respective daily temperatures for the past n days.
Given two arrays of integers yourTemps and friendsTemps (each of length n), representing the local daily temperatures (in Celsius and Fahrenheit, respectively), find how many days were hotter in Palau.
Example
For yourTemps = [25, 32, 31, 27, 30, 23, 27] and friendsTemps = [78, 83, 86, 88, 86, 89, 79], the output should be celciusVsFahrenheit(yourTemps, friendsTemps) = 3.
Converting your recorded temperatures to Fahrenheit gives the results [77, 89.6, 87.8, 80.6, 86, 73.4, 80.6], which can be compared to the temperatures your friend recorded:
your temps friend's temps
77 78
89.6 83
87.8 86
80.6 88
86 86
73.4 89
80.6 79
There were 3 days where your friend recorded hotter temperatures, so the answer is 3.
"""
def to_fahrenheit(temp):
return float(9 * temp) / 5 + 32
def celsiusVsFahrenheit(yourTemps, friendsTemps):
counter = 0
for you, friend in zip(yourTemps, friendsTemps):
if friend > to_fahrenheit(you):
counter += 1
return counter | true |
658593501932b67c86b33a4f1a0ba2a1257e2de5 | jorzel/codefights | /interview_practice/hash_tables/possibleSums.py | 876 | 4.28125 | 4 | """
You have a collection of coins, and you know the values of the coins and the quantity of each type of coin in it. You want to know how many distinct sums you can make from non-empty groupings of these coins.
Example
For coins = [10, 50, 100] and quantity = [1, 2, 1], the output should be
possibleSums(coins, quantity) = 9.
Here are all the possible sums:
50 = 50;
10 + 50 = 60;
50 + 100 = 150;
10 + 50 + 100 = 160;
50 + 50 = 100;
10 + 50 + 50 = 110;
50 + 50 + 100 = 200;
10 + 50 + 50 + 100 = 210;
10 = 10;
100 = 100;
10 + 100 = 110.
As you can see, there are 9 distinct sums that can be created from non-empty groupings of your coins.
"""
def possibleSums(values, counts):
sums = {0}
for v, c in zip(values, counts):
sums |= {i + choice
for choice in range(v, v * c + 1, v)
for i in sums}
return len(sums) - 1
| true |
4193ada270f7accddd799997c1c705545eb243f3 | jorzel/codefights | /arcade/core/isCaseInsensitivePalindrome.py | 742 | 4.375 | 4 | """
Given a string, check if it can become a palindrome through a case change of some (possibly, none) letters.
Example
For inputString = "AaBaa", the output should be
isCaseInsensitivePalindrome(inputString) = true.
"aabaa" is a palindrome as well as "AABAA", "aaBaa", etc.
For inputString = "abac", the output should be
isCaseInsensitivePalindrome(inputString) = false.
All the strings which can be obtained via changing case of some group of letters, i.e. "abac", "Abac", "aBAc" and 13 more, are not palindromes.
"""
def isCaseInsensitivePalindrome(inputString):
length = len(inputString)
for i in range(length / 2):
if inputString[i].lower() != inputString[-1 - i].lower():
return False
return True
| true |
495f3051e8737856cf1adbc0dbd601166b185ec5 | jorzel/codefights | /arcade/intro/evenDigitsOnly.py | 346 | 4.25 | 4 | """
Check if all digits of the given integer are even.
Example
For n = 248622, the output should be
evenDigitsOnly(n) = true;
For n = 642386, the output should be
evenDigitsOnly(n) = false.
"""
def evenDigitsOnly(n):
el_list = [int(i) for i in str(n)]
for p in el_list:
if p % 2 != 0:
return False
return True
| true |
051faa94e67dcb9db8c35ec2bb577d8fb0598c32 | jorzel/codefights | /arcade/intro/growingPlant.py | 704 | 4.625 | 5 | """
Each day a plant is growing by upSpeed meters. Each night that plant's height decreases by downSpeed meters due to the lack of sun heat. Initially, plant is 0 meters tall. We plant the seed at the beginning of a day. We want to know when the height of the plant will reach a certain level.
Example
For upSpeed = 100, downSpeed = 10 and desiredHeight = 910, the output should be
growingPlant(upSpeed, downSpeed, desiredHeight) = 10.
"""
def growingPlant(upSpeed, downSpeed, desiredHeight):
days = 0
height = 0
while True:
height = height + upSpeed
days += 1
if height >= desiredHeight:
return days
height = height - downSpeed
return days
| true |
455f2a51259a5c06c167a5c6560cf0a22e4f2ce3 | jorzel/codefights | /arcade/python/tryFunctions.py | 1,035 | 4.125 | 4 | """
Easy
Recovery
100
Implement the missing code, denoted by ellipses. You may not modify the pre-existing code.
You've been working on a numerical analysis when something went horribly wrong: your solution returned completely unexpected results. It looks like you apply a wrong function at some point of calculation. This part of the program was implemented by your colleague who didn't follow the PEP standards, so it's extremely difficult to comprehend.
To understand what function is applied to x instead of the one that should have been applied, you decided to go ahead and compare the result with results of all the functions you could come up with. Given the variable x and a list of functions, return a list of values f(x) for each x in functions.
Example
For x = 1 and
functions = ["math.sin", "math.cos", "lambda x: x * 2", "lambda x: x ** 2"],
the output should be
tryFunctions(x, functions) = [0.84147, 0.5403, 2, 1].
"""
def tryFunctions(x, functions):
return [eval('({})({})'.format(f, x)) for f in functions]
| true |
94c2397a4ecb9cbfbe88f8b5c7831805fc246562 | jorzel/codefights | /interview_practice/arrays/rotateImage.py | 471 | 4.46875 | 4 | """
Note: Try to solve this task in-place (with O(1) additional memory), since this is what you'll be asked to do during an interview.
You are given an n x n 2D matrix that represents an image. Rotate the image by 90 degrees (clockwise).
Example
For
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
the output should be
rotateImage(a) =
[[7, 4, 1],
[8, 5, 2],
[9, 6, 3]]
"""
def rotateImage(a):
return list([list(reversed(p)) for p in zip(*a)])
| true |
7757551f8a04e9875fd09f7cce05b1a06aafab49 | jorzel/codefights | /arcade/intro/longestDigitsPrefix.py | 439 | 4.15625 | 4 | """
Given a string, output its longest prefix which contains only digits.
Example
For inputString="123aa1", the output should be
longestDigitsPrefix(inputString) = "123".
"""
def longestDigitsPrefix(inputString):
max_seq = ""
for i, el in enumerate(inputString):
if i == 0 and not el.isdigit():
return ""
if el.isdigit():
max_seq += el
else:
break
return max_seq
| true |
bfc993bfda53b5a1e69f4b1feefc9b0eea4bdb22 | jorzel/codefights | /arcade/core/concatenateArrays.py | 282 | 4.15625 | 4 | """
Given two arrays of integers a and b, obtain the array formed by the elements of a followed by the elements of b.
Example
For a = [2, 2, 1] and b = [10, 11], the output should be
concatenateArrays(a, b) = [2, 2, 1, 10, 11].
"""
def concatenateArrays(a, b):
return a + b
| true |
cc9e43e94fd96b2407b289ef20cf5a7c04652c3d | jorzel/codefights | /interview_practice/strings/findFirstSubstringOccurence.py | 751 | 4.3125 | 4 | """
Avoid using built-in functions to solve this challenge. Implement them yourself, since this is what you would be asked to do during a real interview.
Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1.
Example
For s = "CodefightsIsAwesome" and x = "IA", the output should be
strstr(s, x) = -1;
For s = "CodefightsIsAwesome" and x = "IsA", the output should be
strstr(s, x) = 10.
"""
import re
def findFirstSubstringOccurrence(string, x):
p = re.search(x, string)
if p:
return p.start()
else:
return -1
| true |
df6930a4776a2e67381065e5dbfc8d5dfe64bf03 | jorzel/codefights | /arcade/python/isWordPalindrome.py | 374 | 4.625 | 5 | """
Given a word, check whether it is a palindrome or not. A string is considered to be a palindrome if it reads the same in both directions.
Example
For word = "aibohphobia", the output should be
isWordPalindrome(word) = true;
For word = "hehehehehe", the output should be
isWordPalindrome(word) = false.
"""
def isWordPalindrome(word):
return word == word[::-1]
| true |
d800d63f49158fcbb0f2af79a9d315061e028fdb | jorzel/codefights | /arcade/intro/biuldPalindrome.py | 575 | 4.25 | 4 | """
Given a string, find the shortest possible string which can be achieved by adding characters to the end of initial string to make it a palindrome.
Example
For st = "abcdc", the output should be
buildPalindrome(st) = "abcdcba".
"""
def isPalindrome(st):
for i in range(len(st) / 2):
if st[i] != st[-1 - i]:
return False
return True
def buildPalindrome(st):
if isPalindrome(st):
return st
rev = st[::-1]
for i in range(len(st)):
if isPalindrome(rev[:i + 1]):
index = i
return st + rev[index + 1:]
| true |
0725fe8ef04175b03de2315a61be93a6bbf4aa2e | jorzel/codefights | /arcade/intro/firstDigit.py | 414 | 4.28125 | 4 | """
Find the leftmost digit that occurs in a given string.
Example
For inputString = "var_1__Int", the output should be
firstDigit(inputString) = '1';
For inputString = "q2q-q", the output should be
firstDigit(inputString) = '2';
For inputString = "0ss", the output should be
firstDigit(inputString) = '0'.
"""
def firstDigit(inputString):
for s in inputString:
if s.isdigit():
return s
| true |
e520b1fc70883eacd427dc2b6ffe006d2f75d926 | jorzel/codefights | /interview_practice/dynamic_programming_basic/climbingStairs.py | 688 | 4.1875 | 4 | """
Easy
Codewriting
1500
You are climbing a staircase that has n steps. You can take the steps either 1 or 2 at a time. Calculate how many distinct ways you can climb to the top of the staircase.
Example
For n = 1, the output should be
climbingStairs(n) = 1;
For n = 2, the output should be
climbingStairs(n) = 2.
You can either climb 2 steps at once or climb 1 step two times.
"""
def fib(n):
if n == 0 or n == 1:
return n
old, new = 0, 1
for _ in range(n):
old, new = new, old + new
return new
def climbingStairs(n):
return fib(n)
def climbingStaircase(n, k):
if n == 0:
return [[]]
return climbing(n, k, [], []) | true |
7872f5adf499f79df9cec821fb8020c8f3bbadbb | jorzel/codefights | /arcade/core/fileNames.py | 856 | 4.15625 | 4 | """
You are given an array of desired filenames in the order of their creation. Since two files cannot have equal names, the one which comes later will have an addition to its name in a form of (k), where k is the smallest positive integer such that the obtained name is not used yet.
Return an array of names that will be given to the files.
Example
For names = ["doc", "doc", "image", "doc(1)", "doc"], the output should be
fileNaming(names) = ["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"].
"""
def fileNaming(names):
results = []
for name in names:
if name in results:
counter = 1
new_name = name
while new_name in results:
new_name = name + '(' + str(counter) + ')'
counter += 1
name = new_name
results.append(name)
return results
| true |
79907a750c9bffa2f140a3f1be68acf207da1f59 | jorzel/codefights | /interview_practice/common_techinques_basic/containsDuplicates.py | 640 | 4.15625 | 4 | """
Given an array of integers, write a function that determines whether the array contains any duplicates. Your function should return true if any element appears at least twice in the array, and it should return false if every element is distinct.
Example
For a = [1, 2, 3, 1], the output should be
containsDuplicates(a) = true.
There are two 1s in the given array.
For a = [3, 1], the output should be
containsDuplicates(a) = false.
The given array contains no duplicates.
"""
def containsDuplicates(a):
d = {}
for n in a:
if n not in d:
d[n] = 1
else:
return True
return False
| true |
388748ed56911db4eefc35817dee3e0bafe07404 | jorzel/codefights | /challange/maxPoints.py | 1,212 | 4.15625 | 4 | """
World Cup is going on! One of the most fascinating parts of it is the group stage that has recently ended. A lot of great teams face each other to reach the playoff stage. In the group stage, each pair of teams plays exactly one game and each team receives 3 points for a win, 1 point for a draw and 0 points for a loss.
You fell asleep. What a shame. While you were sleeping, your team has played a lot of games! Now you know how many matches your team has played, how many goals it has scored and how many has missed. Now you need to find out the maximum amount of points your team can have.
Example
For matches = 2, goalsFor = 1 and goalsAgainst = 2, the output should be
maxPoints(matches, goalsFor, goalsAgainst) = 3;
For matches = 2, goalsFor = 3 and goalsAgainst = 2, the output should be
maxPoints(matches, goalsFor, goalsAgainst) = 4.
"""
def maxPoints(matches, goalsFor, goalsAgainst):
points = 0
while goalsFor > 0 and matches > 1:
goalsFor -= 1
matches -= 1
points += 3
while matches > 1:
points += 1
matches -= 1
if goalsAgainst == goalsFor:
points += 1
elif goalsFor > goalsAgainst:
points += 3
return points
| true |
f17ba2ede15984ac894cb066f3605989d0116441 | NikitaPlesovskix/Susu-101 | /ex 18 | 977 | 4.1875 | 4 | # Имеются две ёмкости: кубическая с ребром A, цилиндрическая с высотой H и радиусом основания R.
# Определить, можно ли заполнить жидкостью объёма M первую ёмкость, вторую, обе.
import math
A = int(input("Ребро кубической ёмкости "))
R = int(input("Радиус основания цилиндрической ёмкости "))
H = int(input("Высота цилиндрической ёмкости "))
M = int(input("Объем жидкости "))
Sk = math.pow(A, 3)
print(Sk, "Объем куба")
Sc = ((math.pi) * (math.pow(R, 2)) * H)
print(Sc, "Объем цилиндра")
if (Sk + Sc <= M ):
print("Жидкость заполнит оба сосуда")
if (Sk <= M):
print("Жидкость заполнит куб")
if (Sc <= M):
print("Жидкость заполнит цилиндр")
| false |
c4fa448d1dcf57c6450378a81f8f465ff4bca213 | zhyordanova/Python-Fundamentals | /04-Functions/Exercise/09_factorial_division.py | 294 | 4.15625 | 4 | def calc_factorial(n):
result = 1
for num in range(2, n + 1):
result *= num
return result
number_1 = int(input())
number_2 = int(input())
factorial_1 = calc_factorial(number_1)
factorial_2 = calc_factorial(number_2)
res = factorial_1 / factorial_2
print(f"{res:.2f}")
| false |
ca8dd729003dd665c4e3fba57289fc4b315128ec | MulderPu/legendary-octo-guacamole | /pythonTuple_part1.py | 767 | 4.15625 | 4 | '''
Write a Python program to accept values (separate with comma) and store in tuple.
Print the values stored in tuple, sum up the values in tuple and display it. Print the maximum and
minimum value in tuple.
'''
user_input = input("Enter values (separate with comma):")
tuple = tuple(map(int, user_input.split(',')))
print('~~~~~~~~~~')
print("Values stored in tuple")
print("Tuple:",tuple)
print("~~~~~~~~~~")
print('Total:',sum(tuple))
print('Maximum',max(tuple))
print('Minimum',min(tuple))
number=int(input('Enter a number to see how many times it has appeared inside the tuple:'))
count = tuple.count(number)
if(count==0):
print('%i appeared %i time in tuple list.'%(number,count))
else:
print('%i appeared %i times in tuple list.'%(number, count))
| true |
71c4d79d3e982de8875def381e621b8a8dd46247 | MulderPu/legendary-octo-guacamole | /guess_the_number.py | 801 | 4.25 | 4 | import random
print('~~Number Guessing Game~~')
try:
range = int(input('Enter a range of number for generate random number to start the game:'))
rand = random.randint(1,range)
guess = int(input('Enter a number from 1 to %i:'%(range)))
i=1
while (i):
print()
if guess == 0 or guess < 0:
print('Give up? Try again next time!')
break
elif guess < rand:
print('Number too small.')
guess = int(input('Enter a number from 1 to %i:'%(range)))
elif guess > rand:
print('Number too large.')
guess = int(input('Enter a number from 1 to %i:'%(range)))
elif guess == rand:
print('Congratulation. You made it!')
break
except:
print('Wrong Input.')
| true |
35c48ed308a44a6dd4c4f2941cc0405ef609edad | kikihiter/PythonLearning | /sortingAlgorithmPython/heapSort.py | 2,764 | 4.125 | 4 | #!user/bin/env python
#python heapSort.py
#kiki 18/04/27
#保证根节点为最大的
def maxChange(heap,size,i): #分别有三个参数,heap为传入的列表,size为列表长度,i为当前根节点索引号
root = i
left = i*2+1 #左子节点
right = i*2+2 #右子节点
"""
if left<size and heap[root]<heap[left]:
heap[root],heap[left] = heap[left],heap[root]
left,root = root,left
if right<size and heap[root]<heap[right]:
heap[root],heap[right] = heap[right],heap[root]
right,root = root,right
"""
if left<size and right<size: #当左右子节点存在时,选择其中最大的
if heap[left]<=heap[right] and heap[root]<heap[right]:
heap[root],heap[right] = heap[right],heap[root]
root,right = right,root
elif heap[left]>heap[right] and heap[root]<heap[left]:
heap[root],heap[left] = heap[left],heap[root]
root,left = left,root
elif left<size and right>=size: #左子节点存在而右子节点不存在时
if heap[root]<heap[left]:
heap[root],heap[left] = heap[left],heap[root]
root,left = left,root
elif right<size and left>=size: #右子节点存在而左子节点不存在时,讲道理,完全二叉树不存在这种情况,以防万一还是写了
if heap[root]<heap[right]:
heap[root],heap[right] = heap[right],heap[root]
root,right = right,root
if root != i: #当发生交换时,将索引向下传递,继续比较下一级
maxChange(heap,size,root)
#创建堆,在这里调用的是maxChange,所以产生的是最大堆
def buildHeap(heap):
size = len(heap)
for i in range((size+1)//2-1)[::-1]: #从倒数第二层的最后一个节点开始进行比较
maxChange(heap,size,i)
#堆排序,将列表由小到大排序,说实话,python自带序列排序,直接List.sort()就行了。
def heapSort(heap):
buildHeap(heap) #首先生成一个最大堆
size = len(heap)
for i in range(size-1,0,-1): #从最后一个元素开始,不断把堆中最后一个元素与第一个元素(堆中最大的数)进行调换,调换后,最后的元素进入排序完成区,利用前面的元素再次生成最大堆
heap[0],heap[i] = heap[i],heap[0]
maxChange(heap,i,0)
if __name__ == "__main__":
a = [145, 65, 342, 341, 56, 7, 3, 56, 75, 73, 97] # 测试样例,其中65有两个
print (a)
buildHeap(a) #实际上,这里已经生成一个堆了,在下面堆排序的时候,重复了一次,但是这里是为了测试用的,去除后不影响
print (a)
heapSort(a) #时间复杂度O(nlogn)
print (a)
| false |
ce71585126ae1e765a99600203ba6e2585860f60 | ProNilabh/Class12PythonProject | /Q11_RandomGeneratorDICE.py | 307 | 4.28125 | 4 | #Write a Random Number Generator that Generates Random Numbers between 1 and 6 (Simulates a Dice)
import random
def roll():
s=random.randint(1,6)
return s
xD= str(input("Enter R to Roll the Dice!-"))
if xD=="r":
print(roll())
else:
print("Thanks for Using the Program!") | true |
014674cad94445da44a1c2f258777d6529687270 | Raghavi94/Best-Enlist-Python-Internship | /Tasks/Day 8/Day 8.py | 2,983 | 4.21875 | 4 | #TASK 8:
#1)List down all the error types and check all the errors using a python program for all errors
#Index error
#Name error
#zerodivision error
a=[0,1,2,3]
try:
print(a[1])
print(a[4],a[1]//0)
except(IndexError,ZeroDivisionError):
print('Index error and zero division error occured')
#2)Design a simple calculator app with try and except for all use cases
import math
while 1:
print ("1) Add")
print ("2) Subtract")
print ("3) Divide")
print ("4) Multiply")
print ("0) Exit")
try: # This is a try statement used to handle errors
answer = int(input("Option: "))
if answer == 1:
first = float(input("First Number: "))
second = float(input("Second Number: "))
final = first + second
print ("Answer:", float(final))
print()
elif answer == 2:
first = float(input("First Number: "))
second = float(input("Second Number: "))
final = first - second
print ("Answer:", float(final))
print()
elif answer == 3:
first = float(input("First Number: "))
second = float(input("Second Number: "))
final = first / second
print ("Answer:", float(final))
print()
elif answer == 4:
first = float(input("First Number: "))
second = float(input("Second Number: "))
final = first * second
print ("Answer:", float(final))
print()
elif answer == 0:
break
else:
print ("\nPlease select a valid option number\n")
except NameError:
print ("\nNameError: Please Use Numbers Only\n")
except SyntaxError: # SyntaxError means we typed letters or special characters i.e !@#$%^&*( or if we tried to run python code
print ("\nSyntaxError: Please Use Numbers Only\n")
except TypeError: # TypeError is if we entered letters and special characters or tried to run python code
print ("\nTypeError: Please Use Numbers Only\n")
except AttributeError: # AttributeError handles rare occurances in the code where numbers not on the list are handled outside of the if statement
print ("\nAttributeError: Please Use Numbers Only\n")
#3)print one message if the try block raises a NameError and another for other errors
try:
print(x)
except NameError:
print('NameError:x is not defined')
#4)When try-except scenario is not required?
#try-except is used for checking and validation purpose,otherwise it is not needed
#5)Try getting an input inside the try catch block
try:
n=int(input('Enter a number'))
print('Input you gave is valid')
except ValueError:
print('Invalid input')
| true |
00b75b92ccda9b8cd04760da415f1aebb5bc0e03 | nikhl/Miscellaneous | /src/multiplication_table.py | 490 | 4.28125 | 4 | # Take as input a number and print all the multiplications from 1 upto that number
def print_multiplication_table(n):
i = 1
while i<=n:
j = 1
while j<=n:
print '%d * %d = %d' % (i,j,(i*j))
j = j+1
i = i+1
# test cases
print_multiplication_table(2)
#>>> 1 * 1 = 1
#>>> 1 * 2 = 2
#>>> 2 * 1 = 2
#>>> 2 * 2 = 4
print_multiplication_table(3)
#>>> 1 * 1 = 1
#>>> 1 * 2 = 2
#>>> 1 * 3 = 3
#>>> 2 * 1 = 2
#>>> 2 * 2 = 4
#>>> 2 * 3 = 6
#>>> 3 * 1 = 3
#>>> 3 * 2 = 6
#>>> 3 * 3 = 9
| false |
19b00f3cace5617652435d104b04dc24b68513ea | ezekielp/algorithms-practice | /integer_break.py | 1,227 | 4.25 | 4 | """
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
Example 1:
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
Note: You may assume that n is not less than 2 and not larger than 58.
"""
# 23
# 5 * 5 * 5 * 5 * 3 = 1875
# 4 * 4 * 4 * 4 * 4 * 3 = 3072
# 6 * 6 * 6 * 5 = 1080
# import math
# You never need a factor greater than or equal to 4.
# Explain: If an optimal product contains a factor f >= 4, then you can replace it with factors 2 and f-2 without losing optimality, as 2*(f-2) = 2f-4 >= f.
# class Solution(object):
# def integerBreak(self, n):
# """
# :type n: int
# :rtype: int
# """
# square_root = math.sqrt(n)
# rounded_sqrt = math.floor(square_root)
# diff = n - (rounded_sqrt ** 2)
# count = 0
# sum_so_far = 0
# nums = []
# while sum_so_far < n - diff:
# count += 1
# sum_so_far += rounded_sqrt
# nums.append(rounded_sqrt)
# nums.append(diff)
# return nums.reduce()
# variable = math.sqrt(10)
# print(math.floor(variable))
| true |
679b8b24eda016b5e320624a0ead00bfdf12903b | dple/Strings-in-Python | /pangram.py | 706 | 4.15625 | 4 | """
A pangram is a string that contains every letter of the alphabet.
Given a sentence determine whether it is a pangram in the English alphabet.
Return either pangram or not pangram as appropriate.
For example:
Input: We promptly judged antique ivory buckles for the next prize
Output: pangram
"""
def pangrams(s):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
states = 26*[0]
for c in s:
if c.lower() in alphabet:
states[alphabet.index(c.lower())] = 1
for i in range(26):
if states[i] == 0:
return 'not pangram'
return 'pangram'
if __name__ == '__main__':
s= 'We promptly judged antique ivory buckles for the next prize'
print(pangrams(s)) | true |
31c86f9b3b49aca2002fa01058ca4763312c3046 | Gaurav1921/Python3 | /Basics of Python.py | 1,703 | 4.375 | 4 | """ to install any module first go in command prompt and write 'pip install flask' and then come here and write
modules are built in codes which makes our work more easier and pip is package manager which pulls modules """
import flask
""" to print something the syntax for it is """
print("Hello World")
""" using python as calculator """
print(36 + 8) # returns the addition
print(36 - 8) # returns the subtraction
print(36 * 8) # returns the multiplication
print(36 / 8) # returns the division
print(36 // 8) # returns the quotient
print(30 % 8) # returns the remainder
""" comments for multi line """
# comments for single line
""" if we don't want to add another line while printing statement use end (by default its a new line character) """
print("Gaurav is the best", end=" ") # python thinks that the space is the end of the line & starts printing new line from there
print("Do like and subscribe the channel")
""" escape sequence character """ # for more go to Quackit.com escape char
print("Gaurav\nSingh") # new line character
print("Gaurav\"Singh\"") # when extra "" used
print("Gaurav\tSingh") # extra space character
""" assigning values to a variable """
var1 = "Hello World"
var2 = 4 # we can add two integers or two strings but not strings and int
var3 = 3.4
""" to know the type of variable"""
print(type(var2))
print(type(var1))
print(type(var3))
""" doing typecast """
a = int("54") # originally 54 and 73.3 were strings but now typecasted to integers and float
b = float("73.3")
print(a+b)
""" we can multiply string with int """
print("Gaurav"*5)
| true |
d1ee3c94491b93693cd9bd09f65e7e4d31ad4511 | Enin/codingTest | /amazon/6_determine_if_a_binary_tree_is_a_binary_search_tree.py | 2,728 | 4.28125 | 4 | ###
# Given a Binary Tree, figure out whether it’s a Binary Sort Tree.
# In a binary search tree, each node’s key value is smaller than the key value of all nodes in the right subtree,
# and is greater than the key values of all nodes in the left subtree.
# Below is an example of a binary tree that is a valid BST.
import collections
class node:
def __init__(self, value):
self.value = value
self.left, self.right = None, None
class BST:
def __init__(self, head):
self.head = head
def insert(self, value):
self.current_node = self.head
while True:
if value < self.current_node.value:
if self.current_node.left != None:
self.current_node = self.current_node.left
else:
self.current_node.left = node(value)
break
else:
if self.current_node.right != None:
self.current_node = self.current_node.right
else:
self.current_node.right = node(value)
break
def check_tree(self):
self.queue = [collections.deque(), collections.deque()]
self.current_queue = self.queue[0]
self.next_queue = self.queue[1]
self.tree_level = 0
self.current_queue.append(self.head)
while self.current_queue:
self.temp = self.current_queue.popleft()
if self.temp.left is not None:
if self.temp.value < self.temp.left.value:
print("worng BST on level {}. {} < {}".format(self.tree_level, self.temp.value, self.temp.value.left.value))
return False
self.next_queue.append(self.temp.left)
if self.temp.right is not None:
if self.temp.value > self.temp.right.value:
print("worng BST on level {}. {} > {}".format(self.tree_level, self.temp.value, self.temp.value.left.value))
return False
self.next_queue.append(self.temp.right)
if not self.current_queue:
self.tree_level += 1
self.current_queue = self.queue[(self.tree_level % 2)]
self.next_queue = self.queue[(self.tree_level + 1) % 2]
print("The tree is correct BST")
return True
def create_BST(input):
for i in range(len(input)):
if i == 0:
root = node(input[i])
tree = BST(root)
else:
tree.insert(input[i])
return tree
def main():
arr = [100, 50, 200, 25, 75, 90, 350]
test_tree = create_BST(arr)
result = test_tree.check_tree()
print(result)
main() | true |
74af819f062dc0dff568fbbfdd2767be07f4f603 | Enin/codingTest | /amazon/7_string_segmentation.py | 907 | 4.375 | 4 | # You are given a dictionary of words and a large input string.
# You have to find out whether the input string can be completely segmented into the words of a given dictionary.
# The following two examples elaborate on the problem further.
import collections
# recursion과 memoization을 사용
given_dict = ['apple', 'apple', 'pear', 'pie']
input_string = ['applepie', 'applepeer']
def can_segment_string(str, dict):
for s in range(1, len(str)+1):
first_word = str[0:s]
if first_word in dict:
second_word = str[s:]
if not second_word or second_word in dict or can_segment_string(second_word, dict):
return True
return False
def test():
dict_set = set(given_dict)
if can_segment_string(input_string[1], dict_set):
print("Input string can be segmented")
else:
print("Input string can't be segmented")
test()
| true |
d3302d00ebca7dd0ff302f38cd78d1b87ccb5c1f | AdishiSood/Jumbled_Words_Game | /Jumbled_words_Game.py | 2,419 | 4.46875 | 4 | #To use the random library, you need to import it. At the top of your program:
import random
def choose():
words=["program","computer","python","code","science","data","game"]
pick=random.choice(words) #The choice() method returns a list with the randomly selected element from the specified sequence.
return pick
def jumble(word):
jumbled="".join(random.sample(word,len(word))) #The join() method takes all items in an iterable and joins them into one string.
#The sample() method returns a list with a randomly selection of a specified number of items from a sequence.
return jumbled
def thank(p1n,p2n,p1,p2):
print("========= Score board ============= ")
print(p1n,'Your score is : ',p1)
print(p2n,'Your score is : ',p2)
print('Thanks for playing')
print('Have a nice day')
print("===================================")
def main():
p1name= input('Player 1, Please enter your name') #p1name= name of player1
p2name= input('Player 2, Please enter your name') #p2name= name of player2
pp1 =0 #points of player 1
pp2 =0 #points of player 2
turn =0 #To keep track of whose turn it is let us have some variable or turn initially let it be zero i
while(1):
#computer's task
picked_word =choose()
#create question
qn=jumble(picked_word)
print (qn)
#player1
if turn%2==0:
print(p1name,'its Your turn, What is on your mind?')
ans=input()
if ans==picked_word:
pp1=pp1+1
print('Your score is : ',pp1)
else:
print("Oh! better luck next time.")
print('The correct answer is :',picked_word)
c=int(input('Press 1 to continue and 0 to quit : '))
if c==0:
thank(p1name,p2name,pp1,pp2)
break
#player2
else:
print(p2name,'its Your turn, What is on your mind?')
ans=input()
if ans==picked_word:
pp2=pp2+1
print('Your score is : ',pp2)
else:
print("Oh! better luck next time.")
print('The correct answer is :',picked_word)
c=int(input('Press 1 to continue and 0 to quit : '))
if c==0:
thank(p1name,p2name,pp1,pp2)
break
turn=turn+1
main()
| true |
bb984eb7c1ecb5e4d1407baa9e8599209ff05f3b | xASiDx/other-side | /input_validation.py | 794 | 4.25 | 4 | '''Input validation module
Contains some functions that validate user input'''
def int_input_validation(message, low_limit=1, high_limit=65536, error_message="Incorrect input!"):
'''User input validation
The function checks if user input meets set requirements'''
user_input = 0
#we ask user to enter an integer number between low_limit and high_limit
#until he enters correctly
while True:
user_input = input(message)
#if user input meets the requirments...
if user_input.isdecimal() and (int(user_input) in range(low_limit,high_limit+1)):
#we return user input
return int(user_input)
else:
#otherwise we print the error message and continue the loop
print(error_message) | true |
4996d51a0d79f44c1ed2abf236c1bcf8789bb18a | karanalang/technology | /python_examples/py_bisect.py | 1,332 | 4.15625 | 4 | # https://docs.python.org/3/library/bisect.html
# https://www.tutorialspoint.com/bisect-array-bisection-algorithm-in-python
import bisect
# data = [1, 2, 3,4 ]
#
# idx = bisect.bisect(data, 2)
# print(" bisect.bisect(data, 2) i.e. get the idx to the RIGHT of the elem 2 -> ", idx)
#
# data.insert(idx, 100)
#
# print(" data after bisect and insert -> ", data)
# data = [0, 100, 300,405]
# idx = bisect.bisect_left(data, 405)
# print(" bisect.bisect(data, 3) i.e. get the idx to the LEFT of the elem 3 -> ", idx)
# data.insert(idx, 405)
# print(" data after bidect_left and insert -> ", data)
# data = [1, 2, 3,4]
# idx = bisect.bisect_right(data, 5)
# print(" bisect.bisect(data, 2) i.e. get the idx to the RIGHT of the elem 2 -> ", idx)
# data.insert(idx, 103)
# print(" data after bidect_left and insert -> ", data)
data = [0, 100, 300,405]
idx = bisect.insort_left(data, 400)
print(" bisect.bisect(data, 3) i.e. get the idx to the LEFT of the elem 3 -> ", idx)
# data.insert(idx, 405)
print(" data after insort_left and insert -> ", data)
data = [0, 100, 300,405]
bisect.insort_right(data, 400)
print(" bisect.bisect(data, 3) i.e. get the idx to the LEFT of the elem 3 -> ", data)
data = [0, 100, 300,405]
bisect.insort(data, 400)
print(" bisect.bisect(data, 3) i.e. get the idx to the LEFT of the elem 3 -> ", data)
| false |
c276d6f87149f8a9f724e58ad95ba1a1f80296b5 | karanalang/technology | /python_examples/Python_eval.py | 1,472 | 4.21875 | 4 | from math import *
# https://www.geeksforgeeks.org/eval-in-python/
class Python_eval:
def usingEval(self, str):
res = eval(str)
print(" res -> ", res)
def secret_function(self):
return "Secret key is 1234"
def function_creator(self):
expr = input("Enter function in terms of x : ")
x = int(input(" enter val of x : "))
y = eval(expr) # evaluting the expression
# printing evaluated result
print(" y = {}".format(y))
def function_creator_safe(self):
safe_list = ['acos', 'asin', 'atan', 'atan2', 'ceil', 'cos',
'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor',
'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10',
'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt',
'tan', 'tanh']
safe_dict = dict([(k, locals().get(k, None)) for k in safe_list])
print(" safe_dict -> ", safe_dict)
# safe_dict1 = {k:None for k in safe_list}
# print(" safe_dict1 -> ", safe_dict1)
expr = input("Enter function in terms of x : ")
x = int(input(" enter val of x : "))
safe_dict['x'] = x
y = eval(expr, {"__builtins__":None}, safe_dict) # evaluting the expression
# printing evaluated result
print(" y = {}".format(y))
sol = Python_eval()
str = '2*4+5'
str1 = '5/2'
# sol.usingEval(str1)
# sol.function_creator()
sol.function_creator_safe()
| false |
d0219bd6ffe2d00bba2581b72b852b858c8c1a07 | QARancher/file_parser | /search/utils.py | 710 | 4.1875 | 4 | import re
from search.exceptions import SearchException
def search(pattern,
searched_line):
"""
method to search for string or regex in another string.
:param pattern: the pattern to search for
:param searched_line: string line as it pass from the file parser
:return: matched object of type re
:raise: SearchException if the strings invalid
"""
try:
pattern = re.compile(pattern, re.IGNORECASE)
for match in re.finditer(pattern=pattern, string=searched_line):
return match
except re.error:
raise SearchException(message="Failed compiling pattern"
" {pattern}".format(pattern=pattern))
| true |
74e87bf28436a832be8814386285a711b627dab9 | ohaz/adventofcode2017 | /day11/day11.py | 2,179 | 4.25 | 4 | import collections
# As a pen&paper player, hex grids are nothing new
# They can be handled like a 3D coordinate system with cubes in it
# When looking at the cubes from the "pointy" side and removing cubes until you have a
# plane (with pointy ends), each "cube" in that plane can be flattened to a hexagon
# This means that 3D coordinates can be used easily to get a 2D representation of a hex grid
# Examples and explanations are on https://www.redblobgames.com/grids/hexagons/
#
# x = 0
# \ n /
# nw +--+ ne
# z = 0 /y \ y = 0
# -+ x+-
# y = 0 \z / z = 0
# sw +--+ se
# / s \
# x = 0
Point = collections.namedtuple('Point', ['x', 'y', 'z'])
def add_point(p1: Point, p2: Point):
if p2 is None:
print('Did not add anything')
return p1
return Point(x=p1.x + p2.x, y=p1.y+p2.y, z=p1.z+p2.z)
def distance(p1: Point, p2: Point):
# The Manhattan distance in a hex grid is half the Manhattan distance in a cube grid.
# coincidentally this is also just the max of the three distances
return max(abs(p1.x - p2.x), abs(p1.y - p2.y), abs(p1.z - p2.z))
def calculate_solution():
with open('day11/day11_input.txt', 'r') as f:
content = f.read()
steps = content.split(',')
max_distance = 0
zero = Point(x=0, y=0, z=0)
current_pos = Point(x=0, y=0, z=0)
for step in steps:
modifier = None
# Go around clockwise and create modify vectors
if step == 'n':
modifier = Point(x=0, y=1, z=-1)
elif step == 'ne':
modifier = Point(x=1, y=0, z=-1)
elif step == 'se':
modifier = Point(x=1, y=-1, z=0)
elif step == 's':
modifier = Point(x=0, y=-1, z=1)
elif step == 'sw':
modifier = Point(x=-1, y=0, z=1)
elif step == 'nw':
modifier = Point(x=-1, y=1, z=0)
else:
print('Unknown direction', step)
current_pos = add_point(current_pos, modifier)
max_distance = max(max_distance, distance(current_pos, zero))
return distance(current_pos, zero), max_distance
| true |
9e9f9151efbe59c7e0100048c3d46f7d8786bba5 | dennis-omoding3/firstPython | /task.py | 630 | 4.15625 | 4 | taskList=[23,"jane",["lesson 23",560,{"currency":"kes"}],987,(76,"john")]
# 1. determine the type of var in task list using an inbuilt function
print(type(taskList))
# 2.print kes
print(taskList[2][2]["currency"])
# 3.print 560
print(taskList[2][1])
# 4. use a function to determine the length of taskList
print(len(taskList))
# 5. change 987 to 789 using an inbuilt method or assignment
print(str(taskList[3])[::-1] )#typecasting into a string because integer cannot be reversed
#print(a.reverse())
# 6. change the name "john" to "jane" without using assignment
#NA a tuple cannot be modified
#print(taskList.index("jane"))
| true |
6ac581ae0842787a92b863397f609236eb09d0fd | nurSaadat/pythonLearning | /talking_robot.py | 856 | 4.40625 | 4 | # В институте биоинформатики по офису передвигается робот.
# Недавно студенты из группы программистов написали для него программу,
# по которой робот, когда заходит в комнату, считает количество программистов в ней
# и произносит его вслух: "n программистов".
x = int(input())
c = x % 100
d = x % 10
if 0 <= x <= 1000:
if c == 11 or c == 12 or c == 13 or c == 14:
print(str(x) + " программистов")
elif d == 1:
print(str(x) + " программист")
elif d == 2 or d == 3 or d == 4:
print(str(x) + " программиста")
else:
print(str(x) + " программистов")
| false |
4d647b6c3147dec57dd0ab525c5bc97b94f9e459 | lwjNN/leetcode-python | /Python/sword2offer/Offer11.py | 1,044 | 4.4375 | 4 | """
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。
示例 1:
输入:[3,4,5,1,2]
输出:1
示例 2:
输入:[2,2,2,0,1]
输出:0
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from typing import List
'''[2,2,2,0,1]'''
def minArray(numbers: List[int]) -> int:
if not numbers:
return 0
start, end = 0, len(numbers) - 1
while start < end:
mid = (start + end) // 2
if numbers[mid] > numbers[end]:
start = mid + 1
elif numbers[mid] < numbers[end]:
end = mid
else:
end -= 1
return numbers[start]
print(minArray([2, 2, 2,3, 0, 1]))
| false |
ea53fb163337a49762314dbc38f2788a74846343 | SaretMagnoslove/Python_3_Basics_Tutorial_Series-Sentdex | /Lesson24_multiline_print.py | 666 | 4.5 | 4 | # The idea of multi-line printing in Python is to be able to easily print
# across multiple lines, while only using 1 print function, while also printing
# out exactly what you intend. Sometimes, when making something like a text-based
# graphical user interface, it can be quite tedious and challenging to make everything
# line up for you. This is where multi-line printing can be very useful.
print(
'''
This
is
a
test
'''
)
print(
'''
So it works like a multi-line
comment, but it will print out.
You can make kewl designs like this:
==============
| |
| |
| BOX |
| |
| |
==============
'''
) | true |
234fd73fe7facee859d6545a424d1ffcfb5fb4d0 | Ekpreet-kaur/python-files | /venv/python9.py | 216 | 4.1875 | 4 | #assignment operators
num1 = 10 #write operation/ update operation
num1 = 5
num2 = num1 #copy operation |refernce copy
#num1 = num1 + 10
num1 += 5
#print(num1)
# *=,/=,//=,*=,**=
num1 **= 2
num1 //= 2
print(num1) | false |
8d9d40f748d8351017fe52bef8296c45a8bbea76 | botaoap/python_db_proway_2021 | /aula2/class/classes.py | 943 | 4.15625 | 4 | """
classmethod - staticmethod - dcorators
"""
class MinhaClasse:
def __init__(self, nome, idade) -> None:
self.nome = nome
self.idade = idade
def __repr__(self) -> str:
return f"{self.nome}, {self.idade}"
def metodo_de_instancia(self):
print(f"Eu sou uma classe {self}")
print(f"Meu nome é {self.nome}")
# classmethod normalmente usado para cirar classes apartir dele
# o classmethod conhece o que existe dentro da class
# podendo alterar os valores da classe por exemplo o __init__
@classmethod
def metodo_de_classe(cls, nome, idade):
if idade < 18:
raise Exception("Nao pode menor de idade")
return cls(nome, idade)
minha_classe = MinhaClasse(nome="Jorge", idade=25)
# print(minha_classe.nome)
# print(minha_classe.idade)
print(minha_classe)
outra_classe = MinhaClasse.metodo_de_classe("Junior", 19)
print(outra_classe.idade) | false |
77181ee32df9fc60121bcdb41aca5717c4245405 | HarrietLLowe/python_turtle-racing | /turtle_race.py | 1,278 | 4.28125 | 4 | from turtle import Turtle, Screen
import random
is_race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a colour: ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
turtles = []
for x in range (0, 6):
new_turtle = Turtle(shape="turtle")
turtles.append(new_turtle)
num = 0
def style_turtle(turtle):
global num
turtle.color(colors[num])
num += 1
y_axis = -230
x_axis = -125
def starting_pos(turtle):
turtle.penup()
global x_axis
global y_axis
for each in turtles:
x_axis += 5
turtle.goto(y_axis,x_axis)
for each in turtles:
style_turtle(each)
starting_pos(each)
if user_bet:
is_race_on = True
while is_race_on:
for turtle in turtles:
if turtle.xcor() > 230:
winning_colour = turtle.pencolor()
is_race_on = False
if winning_colour == user_bet:
print(f"You've won! The winning turtle is {winning_colour}!")
else:
print(f"You lost! The winning turtle is {winning_colour}!")
random_distance = random.randint(0, 10)
turtle.forward(random_distance)
screen.exitonclick() | true |
becb831554b3c8e678f0450b7db618e008270fb7 | JohnRamonetti/Election_Analysis | /python_practice.py | 1,576 | 4.125 | 4 | # print("Hello World")
# print("Hello world")
# counties = ["A","B","C"]
# # print(counties[1])
# print(len(counties))
voting_data = []
voting_data.append({"county":"Arapahoe", "registered_voters":422829})
voting_data.append({"county":"Denver", "registered_voters":463353})
voting_data.append({"county":"Jefferson","regisgtered_voters":432438})
#for county_dict in voting_data:
# print(county_dict)
# for i in range(len(voting_data)):
# print(voting_data[i])
#??
# for county_dict in voting_data:
# print(county_dict["registered-voters"])
#??
# counties_dict = {"Arapahoe": 369237, "Denver":413229, "Jefferson": 390222}
# for county, voters in counties_dict.items():
# print(county + " county has " + str(voters) + " registered voters.")
# #print using an F-string
# for county, voters in counties_dict.items():
# print(f"{county} county has {voters} registered voters.")
# counties = ["Arapahoe", "Denver", "Jefferson"]
# if counties[1] == "Denver":
# print(counties[1])
# temp = int(input("What is the temperature outside?"))
# if temp > 80:
# print("Turn on the AC.")
# else:
# print("Open the window.")
candidate_votes = int(input("How many votes did the candidate get in the election? "))
total_votes = int(input("What is the total number of votes in the election? "))
message_to_candidate = (
f"You received {candidate_votes} number of votes. "
f"The total number of votes in the election was {total_votes}. "
f"You received {candidate_votes / total_votes * 100:.2f}% of the total votes.")
print(message_to_candidate) | false |
28d4c117c564ad0926fafd890f182ec7c3938c22 | Deepu14/python | /cows_bulls.py | 1,637 | 4.28125 | 4 | """ Create a program that will play the “cows and bulls” game with the user. The game works like this:
Randomly generate a 4-digit number. Ask the user to guess a 4-digit number.
For every digit that the user guessed correctly in the correct place, they have a “cow”.
For every digit the user guessed correctly in the wrong place is a “bull.” Every time the user makes a guess,
tell them how many “cows” and “bulls” they have. Once the user guesses the correct number, the game is over.
Keep track of the number of guesses the user makes throughout teh game and tell the user at the end.
Say the number generated by the computer is 1038. An example interaction could look like this:
Welcome to the Cows and Bulls Game!
Enter a number:
>>> 1234
2 cows, 0 bulls"""
import random
import string
import sys
def cows_bulls():
num = ''.join([random.choice(string.digits) for i in range(4)])
num = list(num)
#print(num)
cows = 0
bulls = 0
guess=0
attempt =0
while(num != guess):
guess = input("guess the number: ")
if(len(guess) == 4):
guess = list(guess)
else:
print("Invalid. Please enter a four digit number: ")
continue
for i in range(4):
if num[i] == guess[i]:
cows = cows + 1
elif num[i] in guess and num[i] != guess[i]:
bulls = bulls + 1
attempt = attempt + 1
print(cows,"cows")
print(bulls,"bulls")
print("number of valid attempts are: ",attempt)
if __name__ == "__main__":
cows_bulls()
| true |
25697204d6da732977cef03994324d00368ce1cb | hari1811/Python-exercises | /Quiz App/common.py | 685 | 4.15625 | 4 |
def get_int_input(prompt, high):
while(1):
print()
try:
UserChoice = int(input(prompt))
except(ValueError):
print("Error: Expected an integer input!")
continue
if(UserChoice > high or UserChoice < 1):
print("Error: Please enter a valid choice!")
else:
break
return UserChoice
def get_yes_no_input(prompt):
while(1):
print()
UserChoice = input(prompt).lower()
if(UserChoice == 'y'):
return 1
elif(UserChoice == 'n'):
return 0
else:
print("Error: Please enter y or n!")
| true |
5b0ea4f7425bc0e6a3a2a7063bd7245dbe6568cb | acheval/python | /ATBSWP/Chapter 7/strip_regex_version.py | 586 | 4.21875 | 4 | #!/bin/python3
import re
def strip_string(context, strip_character):
if strip_character == "":
regex_strip_whitespace = re.compile(r"^\s+|\s+$")
stripped_context = regex_strip_whitespace.sub("", context)
print(stripped_context)
else:
regex_strip_character = re.compile(r"[" + strip_character + "]")
stripped_context = regex_strip_character.sub("", context)
print(stripped_context)
print("Enter a string:")
string = str(input())
print("Enter a character to strip:")
character = str(input())
strip_string(string, character)
| false |
a20fc079740a8d7ff9b022fe5e491b3218b2559a | acheval/python | /python_exercices/exercice06.py | 402 | 4.3125 | 4 | #!/bin/python3
# 6. Write a Python program to count the number of characters in a string.
# Sample String : 'google.com' Expected Result : {'o': 3, 'g': 2, '.': 1, 'e':
# 1, 'l': 1, 'm': 1, 'c': 1}
string = 'google.com'
d = dict()
for letter in string:
if letter in d:
d[letter] = d[letter]+1
else:
d[letter] = 1
for key in list(d.keys()):
print(key, ": ", d[key])
| true |
358cb695ab1430599eba277be1d2873ae862ccb8 | pranavchandran/redtheme_v13b | /chapter_2_strings_and_text/numbers_dates_times/rounding_numerical_values.py | 1,408 | 4.125 | 4 | # rounding numerical values
# simple rounding
print(round(1.23, 1))
print(round(1.27, 1))
print(round(1.25362, 3))
a = 1627731
print(round(a, -1))
print(round(a, -2))
print(round(a, -3))
x = 1.23456
print(format(x, '0.2f'))
print(format(x, '0.3f'))
print('value is {:0.3f}'.format(x))
a = 2.1
b = 4.2
c = a + b
# c = round(c, 2)
# print(c)
# float they cant accurately represent base-10 decimals
print(a + b == 6.3)
# you want more performance you can use the decimal module
from decimal import Decimal
a = Decimal('4.2')
b = Decimal('2.1')
print(a + b)
print((a + b) == Decimal(6.3))
from decimal import localcontext
a = Decimal('1.3')
b = Decimal('1.7')
print(a/b)
with localcontext() as ctx:
ctx.prec = 3
print(a/b)
nums = [1.23e+18, 1, -1.23e+18]
print(sum(nums)) #1 disappears
import math
print(math.fsum(nums))
x = 1234.56789
# 2 decimal places of accuracy
print(format(x, '0.2f'))
# right justified in 10 chars, one digit accuracy
print(format(x, '>10.1f'))
# left justified
print(format(x, '<10.1f'))
# centred
print(format(x, '^10.1f'))
print(format(x, ','))
print(format(x, '0,.1f'))
print(format(x, 'e'))
print(format(x, '0.2E'))
x = 1234.56789
print(format(x, '0,.1f'))
print(format(-x, '0,.1f'))
swap_separators = {ord('.'): ',', ord(','):'.'}
print(format(x, ',').translate(swap_separators))
print('%0.2f'%x)
print('%10.1f'%x)
print('%-10.1f'%x)
| true |
f8d026245e19a202915e9cdc57dd0e9e4949760a | pranavchandran/redtheme_v13b | /chapter_2_strings_and_text/matching_string_using_shell_wild_cards/aligning _text_strings.py | 718 | 4.3125 | 4 | # Aligning of strings the ljust(), rjust() and center()
text = 'Hello World'
print(text.ljust(20))
print(text.rjust(20))
print(text.center(20))
print(text.rjust(20, '='))
print(text.center(20,'*'))
# format() function can also be used to align things
print(format(text, '>20'))
print(format(text, '<20'))
print(format(text, '^20'))
# fill the charachter other than a space
print(format(text, '=>20'))
print(format(text, '=>20'))
print(format(text, '*^20s'))
# These format codes can also be used in the format() method when formatting
# multiple values.
print('{:>10s}{:>10s}'.format('Hello', 'World'))
x = 1.2345
print(format(x, '>20'))
print(format(x, '^10.2f'))
print('%-20s'%text)
print('%20s'%text)
| true |
c791668713d4909d8c20592e729deb879e5fad38 | Alicepeach/plisplis3 | /godofredo.py | 1,100 | 4.15625 | 4 | # Calculadora
ejecutar = 1
while ejecutar == 1:
print("Este programa permite hacer una operación básica con dos números")
print("Para realizar esto, es necesario que me indiques el tipo de operación que deseas:")
print("1) Suma ")
print("2) Resta ")
print("3) Multiplicación ")
print("4) División ")
opcion = int(input("Dame la opción que deseas: "))
primero = float(input("Dame el primer número a utilizar: "))
segundo = float(input("Dame el segundo número: "))
if opcion >= 1 or opcion <=4:
if opcion == 1:
resultado = primero + segundo
print("El resultado es: ")
print("%.2f"%resultado)
elif opcion == 2:
resultado = primero - segundo
print("El resultado es: ")
print("%.2f"%resultado)
elif opcion == 3:
resultado = primero * segundo
print("El resultado es: ")
print("%.2f"%resultado)
elif opcion == 4:
resultado = primero / segundo
print("El resultado es: ")
print("%.2f"%resultado)
else:
print("Error, opcion invalida")
else:
print("Opción invalida")
ejecutar=int(input("¿Quieres volver a intentarlo? 1 = si / 2 = No")) | false |
b534e7cebb0800baf0b4f4e62da9fe3a522607a9 | Vamicc/OP | /LAB2/LAB2OP.py | 773 | 4.21875 | 4 | print("Enter the x coordinate: ")
x = int(input())
print("Enter the y coordinate: ")
y = int(input()) # просимо ввести координати точки
if x > 0 and y > 0:
result = "The point belongs to the first quadrant."
elif x > 0 and y < 0:
result = "The point belongs to the forth quadrant."
elif x < 0 and y > 0:
result = "The point belongs to the second quadrant."
elif x < 0 and y < 0:
result = "The point belongs to the third quadrant." # перевірка до якого з квадрантів належить точка
else:
result = "The point is either at the origin or on one of the axes.)" # інакше точка лежить на початку координат або на одній з її осей.
print(result)
| false |
1d34800f127f69e26a9622e5e42407420657a055 | akhilavemuganti/HelloWorld | /Exercises.py | 2,984 | 4.1875 | 4 | #Exercises
#bdfbdv ncbgjfv cvbdggjb
"""
Exercise 1: Create a List of your favorite songs. Then create a list of your
favorite movies. Join the two lists together (Hint: List1 + List2). Finally,
append your favorite book to the end of the list and print it.
"""
listSongs=["song1","song2","song3","song4"]
listMovies=["movie1","movie2","movie3","movie4"]
print(listSongs)
print(listMovies)
newList=listSongs+listMovies
print(newList)
newList.append("Book1")
print(newList)
#----------------------------------------------------------------------------------------------------------
"""
Exercise 2: There were 20 people on a bus. 10 got off. 3 came on. 15
came on. 5 came off. If there were 3 more buses, and each had 15 people
throughout the bus ride, how many people were on all the buses at the last
stop? (Should be done via one equation in Python Shell)
"""
bus=20-10+3+15-5+(3*15)
print(bus)
#----------------------------------------------------------------------------------------------------------
"""
Exercise 3: Create a small program that will take in a User’s name and last
name (Hint: varName = input(“Enter your name”)), store both in two
variables. And then print out a message saying (“Hello there, FirstName
LastName”) (Using the %s symbols)
"""
firstName=input("Enter your first name")
lastName=input("Enter your last name")
print("Hello there %s"%firstName+" "+"%s"%lastName)
#----------------------------------------------------------------------------------------------------------
"""
Exercise 1: Create a loop that prints out either even numbers, or odd
numbers all the way up till your age. Ex: 2,4,6,….,14
"""
for i in range(0,31):
if(i%2==0):
print(i)
##OR
for i in range(0,31,2):
print(i)
#----------------------------------------------------------------------------------------------------------
"""
Exercise 2: Using if statements, create a variable called day, set it to
“Tuesday”. Check to see if day is equal to “Monday” or “Tuesday”, and if it
is, print, “Today is sunny”. If it is not, print “Today it will rain”
"""
day="Tuesday"
if(day=="Monday" or day=="Tuesday"):
print("Today is sunny")
else:
print("Today it will rain")
#----------------------------------------------------------------------------------------------------------
"""
Exercise 3: The weight of a person on the moon is 1/6th the weight of a
person standing on earth. Say that your weight on earth increases by 1 kg
every year. Write a program that will print your weight on the moon every
year for the next 10 years. (Your initial weight can be anything.)
"""
weightOnEarth=140
weightOnMoon=weightOnEarth*(1/6)
for i in range(1,11):
weightOnMoon = weightOnEarth * (1 / 6)
weightOnEarth = weightOnEarth + 1
print("Weight on Earth %d" %weightOnEarth)
print("Weight on Moon %d" %weightOnMoon)
#----------------------------------------------------------------------------------------------------------
| true |
c7fd6e4f93448f7968292d7c41a2c8ccff7db848 | oloj-hub/pythondz | /lab7/ball_lib.py | 1,119 | 4.25 | 4 | class ball():
def move(self):
"""Переместить мяч по прошествии единицы времени.
Метод описывает перемещение мяча за один кадр перерисовки. То есть, обновляет значения
self.x и self.y с учетом скоростей self.vx и self.vy, силы гравитации, действующей на мяч,
и стен по краям окна (размер окна 800х600).
"""
if -self.vy<=self.gravity and -self.y+self.r >=585:
self.gravity=0
self.vy=0
self.vy-=self.gravity
if (self.x+self.vx+self.r>=800):
self.vx=-self.vx/self.k
if (self.x+self.vx-self.r<=0):
self.vx=-self.vx/self.k
if (self.y-self.vy+self.r>=585):
self.vy=-self.vy/self.k
self.vx=self.vx/self.k
if (self.y-self.vy-self.r<=0):
self.vy=-self.vy/self.k
self.x += self.vx
self.y -= self.vy
self.canv.move(self.id,self.vx,-self.vy)
| false |
6d63007d90bae6eb2137cced9d5ee0b47665d547 | rvcjavaboy/udemypythontest | /Methods_and_Functions/function_test/pro4.py | 229 | 4.15625 | 4 | def old_macdonald(name):
result=""
for c in range(0,len(name)-1):
if c==0 or c==3:
result+=name[c].upper()
else:
result+=name[c]
return result
print(old_macdonald('macdonald'))
| true |
c052133b3e1f048e9ccc60b431e599ad15ae80d1 | mihirverma7781/Python-Scripts | /chap4/exercise_two.py | 271 | 4.21875 | 4 | def greater(a,b,c):
if a>b and a>c:
return a
else:
if b>a and b>c:
return b
else:
return c
num1 = input('enter num 1 : ')
num2 = input('enter num 2 : ')
num3 = input('enter num 3 : ')
print(greater(num1,num2,num3))
| false |
d704337728a29e47b14ba1e78643b1bef7528919 | mihirverma7781/Python-Scripts | /chap16/property_setter_decorator.py | 1,033 | 4.125 | 4 |
class Phone:
def __init__(self,brand , model , price):
self.brand = brand
self.model = model
self._price = price
# if price > 0:
# self._price = price
# else:
# self._price = 0
# self.complete_info = f"{self.brand} {self.model} {self._price}"
# this is used as property decorator
@property
def complete_info(self):
return f"{self.brand} {self.model} {self._price}"
# getter and setter methods to set the values if we put the negative values
# getter declaration
@property
def price(self):n
return self._price
@price.setter
def price(self,new_price):
self._price = max(new_price,0)
def make_a_call(self,phone_number):
print(f" calling {phone_number}....")
def full_name(self):
return f"{self.brand} {self.model}"
phone1 = Phone('nokia','1100',1000)
phone1.price = -100
print(phone1._price)
print(phone1.complete_info) | false |
8d90a7edcc4d49f85ea8d35dda6d58dcb7654bd0 | PinCatS/Udacity-Algos-and-DS-Project-2 | /min_max.py | 1,298 | 4.125 | 4 | def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
if ints is None:
return None
if len(ints) == 1:
return (ints[0], ints[0])
minValue = None
maxValue = None
for e in ints:
if minValue is None or minValue > e:
minValue = e
if maxValue is None or maxValue < e:
maxValue = e
return (minValue, maxValue)
## Example Test Case of Ten Integers
import random
print("Test case 1")
l = [i for i in range(0, 10)] # a list containing 0 - 9
random.shuffle(l)
print ("Pass" if ((0, 9) == get_min_max(l)) else "Fail")
# other test cases
print("Test case 2")
l = [] # None, None
print ("Pass" if ((None, None) == get_min_max(l)) else "Fail")
print("Test case 3")
l = [1] # (1, 1)
print ("Pass" if ((1, 1) == get_min_max(l)) else "Fail")
print("Test case 4")
l = None # None
print ("Pass" if (None == get_min_max(l)) else "Fail")
print("Test case 5")
l = [-1, -5] # (-5, -1)
print ("Pass" if ((-5, -1) == get_min_max(l)) else "Fail")
print("Test case 6")
l = [1, 2, 3] # (1, 3)
print ("Pass" if ((1, 3) == get_min_max(l)) else "Fail") | true |
c1d957f7ca914ba5113124684e8b0c21663df2bd | sakshigupta1997/code-100 | /code/python/day-1/pattern15.py | 326 | 4.1875 | 4 | '''write a program to print
enter the number4
*
**
***
****'''
n=int(input("enter the number"))
p=n
k=0
for row in range(n):
for space in range(p,1,-1):
print(" ",end='')
#for star in range(row):
for star in range(row+1):
print("*",end='')
print()
p=p-1
| true |
e02ba552e441eb412b25f7f9d15299288e34ad37 | Iansdfg/9chap | /4Binary Tree - Divide Conquer & Traverse/85. Insert Node in a Binary Search Tree.py | 857 | 4.125 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: The root of the binary search tree.
@param: node: insert this node into the binary search tree
@return: The root of the new binary search tree.
"""
def insertNode(self, root, node):
# write your code here
head = dummy = TreeNode(float('-inf'))
dummy.right = root
while root:
dummy = root
if node.val > dummy.val:
root = root.right
elif node.val < root.val:
root = root.left
if node.val > dummy.val:
dummy.right = node
else:
dummy.left = node
return head.right
| true |
06129f5dd4fc8976370406d05bb3ebd6e4a18ac5 | EvelynWangai/RSA-Encryption-Decryption | /encryption.py | 1,415 | 4.3125 | 4 | # library to be imported
import math
# creating my ditionary
my_dict={'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,
'm':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,
'y':25,'z':26,' ':27}
## Creating RSA keys and encrypting a message
def generate_key_pair(p,q):
"""
function: generate 2 prime numbers
input: 2 prime numbers, phi, a random integer i, e
output: public key and private key
"""
n = p * q
phi = (p-1) * (q-1)
e = 5
i = 2
d = int((i * phi + 1)/e)
return ((e,n), (d,n))
p = int(input("Enter a prime number:"))
q = int(input("Enter a second prime number:"))
public,private = generate_key_pair(p,q)
print("Your public key is:", public,"and your private key is:",private)
def encryption(key,text):
"""
function: encryption
instruct the user to enter a message
output: encrypted message
"""
e, n=key
nw =[]
text = text.lower() # converts the text to lowercase
for letter in text:
value = int(my_dict[letter])
cipher = (value ** e) %n # formula to calculate the cipher
nw.append(cipher)
return nw
message = input("Welcome! What would you like to encrypt today?")
print("Your encrypted message is:",encryption(public,message))
| false |
399106fc8885d5f892d49b080084a393ab5dbb4a | jack-sneddon/python | /04-lists/list-sort.py | 596 | 4.46875 | 4 |
# sort - changes the order permenantly
cars = ['honda', 'suburu', 'mazda', 'acura', 'tesla']
cars.sort()
print (cars)
# reverse sort
cars.sort(reverse = True)
print (cars)
# temporary sort - sorted
cars = ['honda', 'suburu', 'mazda', 'acura', 'tesla']
print("here is the original list:")
print (cars)
print("here is the sorted list:")
print(sorted(cars))
print("here is the original list again:")
print (cars)
# reverse the order
print("here is the original list:")
print (cars)
cars.reverse()
print("here is the reverse list:")
print (cars)
cars_length = len(cars)
print (cars_length)
| true |
e7f972375ba19e5060b271fc4de2db58cfd317c7 | jack-sneddon/python | /30-data/pandas/box_chart.py | 1,615 | 4.1875 | 4 | # $ pip3 install pandas
# pip3 install matplotlib
# https://www.geeksforgeeks.org/data-visualization-different-charts-python/
# import pandas and matplotlib
import sys
import pandas as pd
import matplotlib.pyplot as plt
### Same code from Dataframe as other charts ###
# create 2D array of table given above
data = [['E001', 'M', 34, 123, 'Normal', 350],
['E002', 'F', 40, 114, 'Overweight', 450],
['E003', 'F', 37, 135, 'Obesity', 169],
['E004', 'M', 30, 139, 'Underweight', 189],
['E005', 'F', 44, 117, 'Underweight', 183],
['E006', 'M', 36, 121, 'Normal', 80],
['E007', 'M', 32, 133, 'Obesity', 166],
['E008', 'F', 26, 140, 'Normal', 120],
['E009', 'M', 32, 133, 'Normal', 75],
['E010', 'M', 36, 133, 'Underweight', 40] ]
# dataframe created with
# the above data array
df = pd.DataFrame(data, columns = ['EMPID', 'Gender',
'Age', 'Sales',
'BMI', 'Income'] )
### For each numeric attribute of dataframe ###
'''
A box plot is a graphical representation of statistical data based on the minimum,
first quartile, median, third quartile, and maximum. The term “box plot” comes from the
fact that the graph looks like a rectangle with lines extending from the top and bottom. Because of the extending lines, this type of graph is sometimes called a box-and-whisker plot. For quantile and median refer to this Quantile and median.
'''
df.plot.box()
# individual attribute box plot
plt.boxplot(df['Income'])
plt.show() | false |
9a6c909e0fec1e2b90318ed7644d97e8a1663182 | jack-sneddon/python | /04-lists/lists-while-loop.py | 2,007 | 4.40625 | 4 | # a for loop is effective for looping through a list, but you shouldn't modify a
# list inside for loop because Pything will have trouble keeping track of the items
# in the list. To modify a list as you work throuh it, use a while loop.
# Using while loops with lists and dictionaries allows you to collect, store, and
# organize lots of input to examine and report on later.
#
# move items from one list to another
#
# start with populated list and an empty list
unconfirmed_users = ['alice', 'bob', 'candice']
confirmed_users = []
# verfiy each user until there are no more unconfirmed users.
# move each verified user into the list of confirmed users.
while unconfirmed_users:
confirmed_user = unconfirmed_users.pop()
print(f"Verifying user: {confirmed_user.title()}")
confirmed_users.append(confirmed_user)
# remove all instances of a specific values from a list
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(f"\npets = {pets}")
# use the 'remove' command only removes the first instance
pets.remove('cat')
print(f"\npets = {pets}")
# use while loop
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
while 'cat' in pets :
pets.remove('cat')
print(f"\npets = {pets}")
#
# Fill out a dictionary
#
responses = {}
# Set active flag to indicate that polling is active
polling_active = True
while polling_active :
# prompt for the pserson's name and response.
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
# store the response in the dictionary
responses[name] = response
# find out if anyone else is going to take the poll.
repeat = input ("Would you like to let another person respond (yes/no) ")
if repeat == 'no':
polling_active = False
# Polling complete, Show results
print("\n --- Polling Results ---")
for name, response in responses.items() :
print(f"{name.title()} would like to climb {response.title()}")
| true |
17ff6eaf25026ada4fd159e2ae3905854fd56d2f | GeoMukkath/python_programs | /All_python_programs/max_among_n.py | 280 | 4.21875 | 4 | #Q. Find the maximum among n numbers given as input.
n = int(input("Enter the number of numbers : "));
print("Enter the numbers: ");
a = [ ];
for i in range(n):
num = int(input( ));
a.append(num);
maximum= max(a);
print("The maximum among the given list is %d" %maximum); | true |
b9a895f074168c0be5f86592214a316b46bbc98b | JLarraburu/Python-Crash-Course | /Part 1/Hello World.py | 1,574 | 4.65625 | 5 | # Python Crash Course
# Jonathan Larraburu
print ("Hello World!")
# Variables
message = "Hello Python World! This string is saved to a variable."
print(message)
variable_rules = "Variable names can contain only letters, numbers, and underscores. They can start with a letter or an underscore, but not with a number."
variable_rules_ext = variable_rules
print(variable_rules_ext)
# Strings
simple = 'strings are very simple in Python'
example_string = "I can use quotes or apostrophes 'or both'"
name = 'ada lovelace'
print(name.title())
print(name.upper())
print(name.lower())
first_name = 'jon'
last_name = 'larraburu'
full_name = first_name + ' ' + last_name
print(full_name)
print('Hello, ' + full_name.title() + '!')
print('\t This will add a tab.')
print('\nThis is add a new line. This one is very convenient if you remember c++')
print('combine the two...\n')
print('\tLanguages:\n')
print('\t\tPython!')
print('\t\tC++!')
print('\t\tJavaScript!')
stripping_whitespace = 'python '
stripping_whitespace.rstrip()
print(stripping_whitespace)
stripping_whitespace = stripping_whitespace.rstrip()
print(stripping_whitespace)
# Numbers
this_is_how_exponents_work = 2 ** 8
age = 32
happy_birthday = 'Happy ' + str(age) + 'nd birthday!'
# I know how comments work!
# We love comments!
# More comments the better!
# The main reason to write comments is to explain what your code is supposed to do and how you are making it work.
""" There is no reason you can't use this as a
multiline comment when writing python."""
# Still cleaner to just use comments imo | true |
cae06ec7c1df47570276ee34b144ad85c5f1e09a | kahee/Python-Study | /data_structure/CH3/list-stack.py | 434 | 4.125 | 4 | def push(item):
stack.append(item)
def peek():
# top 항목 접근
if len(stack) != 0:
return stack[-1]
def pop():
# 삭제 연산
if len(stack) != 0:
# 리스트의 맨 뒤에 있는 항목 제거
item = stack.pop(-1)
return item
stack = []
push('apple')
push('orange')
push('cherry')
print(stack)
print(peek())
push('pear')
print(stack)
pop()
push('grape')
print(stack)
| false |
c9c2548eb74b5375baeea0d7d526d0dd8446e653 | Varun-Mullins/Triangle567 | /Triangle.py | 1,623 | 4.46875 | 4 | # -*- coding: utf-8 -*-
"""
Updates on Friday January 31 2020
@author: Varun Mark Mullins
cwid:10456027
This file takes in three lengths of a triangle and checks the validity of the triangle and returns the type of
triangle and checks if it is a right angle triangle or not.
"""
def classifyTriangle(a, b, c):
"""Function checks the type of triangle"""
# verify that all 3 inputs are integers
# Python's "isinstance(object,type) returns True if the object is of the specified type
if not (isinstance(a, int) and isinstance(b, int) and isinstance(c, int)):
"""Checks if the input is valid"""
return 'InvalidInput'
# require that the input values be >= 0 and <= 200
if a > 200 or b > 200 or c > 200:
"""Checks if the input is within 200"""
return 'InvalidInput'
if a <= 0 or b <= 0 or c <= 0:
"""Returns an invalid input if the input is negative or zero"""
return 'InvalidInput'
if (a > (b + c)) or (b > (a + c)) or (c > (a + b)):
"""Checks if the triangle is a valid triangle or not"""
return 'NotATriangle'
# now we know that we have a valid triangle
if a == b and b == c:
"""If triangle is Equilateral"""
return 'Equilateral'
elif ((a ** 2) + (b ** 2)) == (c ** 2) or ((b ** 2) + (c ** 2)) == (a ** 2) or ((a ** 2) + (c ** 2)) == (a ** 2):
"""If not equilateral but a right angle triangle"""
return 'Right'
elif (a != b) and (b != c):
"""If the triangle is scalene"""
return 'Scalene'
else:
"""If the triangle is Isosceles"""
return 'Isosceles'
| true |
8f9de6617f089a70ac45e214091830c472fb78cb | Maaleenaa/AlleDaten | /SmartNinjaClasses/Class 8/examples/example_lists.py | 914 | 4.3125 | 4 | # initialize
newList = []
print newList
print #oder print list()
# append single elements - neue Elemente dazuhänge oder +=
newList.append('Banana')
print newList
print
# append add multiple elements with other lists
oldList = ['Milk', 'Honey']
shoppingList = newList + oldList
print shoppingList
print
# refer to elements
print shoppingList[0]
print shoppingList[-1]
print
# refer to multiple elements
print shoppingList[:-1] # slicen : (bis zu einem gewissen Bereich) Stopwert nicht dabei
print shoppingList[1:] # ab 1 bis zum Ende BSP (1:3) = 1,2 (letztes Element wird nicht geschrieben
print
# reverse
shoppingList.reverse()
print shoppingList
shoppingList.reverse()
print
# remove
shoppingList.remove('Banana')
print shoppingList
print
# loop through list
for item in shoppingList:
print item
# length
print len(shoppingList) # Anzahl der Elemente
print
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.