blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
042bf89389289d6661e1d3aa4851ac9fd7646616 | atmanm/LeetCode | /Easy/minDepth.py | 1,012 | 4.1875 | 4 | #Given a binary tree, find its minimum depth.
#The minimum depth is the number of nodes along the shortest path from the root
#node down to the nearest leaf node.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from Tree import Tree
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
return self.getMinHeight(root)
def getMinHeight(self,root):
if root is None:
return 0
lHeight = self.getMinHeight(root.left)
rHeight = self.getMinHeight(root.right)
if root.left is None or root.right is None:
return lHeight + rHeight + 1
else:
return min(lHeight,rHeight)+1
if __name__ == "__main__":
myTree = Tree()
myTree.createTree()
print(Solution().minDepth(myTree.root))
| true |
f272a08e68f05349813f7a0daf15196bbfd8f9ae | Menadyounsi/Message-encoder-and-decoder | /encodedecoder.py | 1,344 | 4.3125 | 4 | #program to encode and decode messages
import random
#Generates random file name composed of 3 random integers
randname = str(random.randint(0, 9)) + str(random.randint(0, 9)) + str(random.randint(0, 9)) + ".txt"
#Function for displaying and choosing encode or decode
def Start():
choice = raw_input("Do you want to [e]ncode or [d]ecode a message? > ")
if choice == "e":
Encode()
elif choice == "d":
Decode()
else:
Start()
#function to save encoded or decoded message
def Sav(message, name):
file = open(name, "a")
file.write(message)
print "File has been saved to: %r" % name
exit()
#This function encodes message entered by user in rot13 cipher
def Encode():
print "Please enter your message to encode: "
message = raw_input().encode("rot13")
print "\n"
Sav(message, randname)
#This function asks foor filename to decode from rot 13 cipher
#and outputs the decoded message
def Decode():
print "Please choose a file name in file directory? > "
name = raw_input("")
file1 = (open(name, "r+")).read()
output = "\n\nYour decoded file reads:\n\n " + file1.decode("rot13")
Sav(output, name)
#output.write("\n---\nThe docoded message is as follows:\n\n%r") % output
print "This program will encode and decode messages for you. \n "
Start()
| true |
9237e6e6336ef17dc4fb27102186a2a37392707c | micnem/developers_institute | /Week4/Day3/gold/ex4.py | 297 | 4.125 | 4 | items = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
for item in items:
items[item]=[items[item], 5]
print(items)
total_value = 0
for item in items:
total_value += items[item][0]*items[item][1]
print(f"the value of all of the items is: {total_value}") | true |
d2042f72ec047b6d8cd951a377776a90418f9ec6 | aamirjankhan/BrinlyTasks | /brain11.py | 349 | 4.34375 | 4 | answer=input("Is the answer the user reported true?\nTrue or False") #prompt the user to enter a boolean value
if answer == True: #if condition to check weather the value in variable answer is true or false
print("The value was True")
else: #else condition to check weather the value in variable answer is False
print("The value was False")
| true |
100b31c34c437b611f5faddbe73a022ee6e37978 | sphilmoon/GTx_CS1301xl | /02.2.7.3_userInput.py | 1,553 | 4.46875 | 4 | #youruserinput = input("Enter an integer: ")
#input_integer = int(youruserinput) # converting the 'String' to an 'Integer'.
#print(input_integer * input_integer)
myint = 2
if myint == 2:
print(True)
# 2.2.9 Worked Example 1
#Early feedback suggests the exercise immediately following this
#is a bit difficult. You've seen everything you need to know to do
#it, but it hasn't been the focus yet. So, this worked example shows
#the solution to a similar problem to help you figure out 2.2.9 Coding
#Exercise 1.
#
#Imagine you are trying to print a person's height in the imperial
#system. You have two variables: feet and inches. You want to print
#the height in the typical style -- for example, if feet was 5 and
#inches was 4, you'd want to print 5'4. We're leaving off the
#quotation mark at the end to keep things simple.
#How would we do that?
#First, let's create the variables.
feet = 5
inches = 4
#What happens if we just add them together?
print("Just summing up: ")
print(feet + inches)
print() # blank line
#Yikes! That's not what we want. It just added 5 and 4 and got 9. We
#don't want to add them as numbers, we want to add them as text,
#putting them together.
#So, let's convert them to strings first. That will force Python to
#treat them like text instead of like numbers.
feet_str = str(feet)
inches_str = str(inches)
print("adding them as strings: ")
print(feet_str + inches_str)
print()
print("with apostrophe: ")
print(feet_str + "'" + inches_str) # 'int' + 'str' only works as the integers
# are converted to strings.
| true |
29810efe2b63bbc5b8b85e19cb5efaa245b86bc3 | noalevitzky/Intro2CS | /02/calculate_mathematical_expression.py | 1,051 | 4.3125 | 4 | # this function calculates math expressions between 2 numbers
def calculate_mathematical_expression(n1, n2, action):
n1 = float(n1)
n2 = float(n2)
action = str(action)
"""calculates legal actions (not dividing by 0 or using illegal actions"""
if action == "+":
calc = n1 + n2
elif action == "-":
calc = n1 - n2
elif action == "*":
calc = n1 * n2
elif action == "/":
if n2 == 0:
return None
else:
calc = n1 / n2
else:
return None
return calc
# the following function converts a string to the needed params for the previous function
def calculate_from_string(text_message):
"""splits a string to the needed parameters for the previous calc"""
text_message = str(text_message)
param1, action, param2 = text_message.split(' ',maxsplit=3)
action = str(action)
param1 = float(param1)
param2 = float(param2)
return calculate_mathematical_expression(param1, param2, action)
| true |
86bb58ef31abd5857220e52fadf76ab470a075ab | SamiHei/worktime_monitor | /modules/timer.py | 1,686 | 4.3125 | 4 | #! /usr/bin/python3
import time
"""
Timer module uses Python3 time standard library
state = Stopped/Running/Paused
start_time = takes time in seconds since the epoch
elapsed_time = saves measured time if timer is paused
end_time = takes new time in seconds since the epoch
"""
class TimerModule:
def __init__(self):
self.state = "Stopped"
self.start_time = 0
self.elapsed_time = 0
self.end_time = 0
def get_state(self):
return self.state
def get_elapsed_time(self):
return self.elapsed_time
"""
Takes time in seconds since the epoch and uses that as the start time
"""
def start_timer(self):
if (self.start_time == 0):
self.start_time = time.time()
self.state = "Running"
"""
Pauses the running timer
"""
def pause_timer(self):
if (self.state == "Running"):
self.state = "Paused"
self.elapsed_time += (time.time() - self.start_time)
"""
Continues the running timer if the state is paused
"""
def continue_timer(self):
if (self.state == "Paused"):
self.state = "Running"
self.start_time = time.time()
"""
Stops the timer and returns the measured time according if the timer was running or stopped
"""
def stop_timer(self):
if (self.state == "Paused"):
return self.elapsed_time
elif (self.state == "Stopped"):
return 0
else:
self.end_time = time.time()
self.state = "Stopped"
return (self.end_time - self.start_time) + self.elapsed_time
| true |
bdf7a51196c5eb23aa639c39ee8dcb1e9039cc8f | jamesnitz/python_sets | /cars.py | 1,394 | 4.375 | 4 | # A set is a collection of things, like a list,
# but the collection is both unordered, and contains no duplicate elements.
# Developers use sets to easily filter down other collections to unique elements,
# and to see if two, or more, collections share any similar items.
# # Using set() to create a set
# languages = set()
# # Using curly braces allows you to initialize the set with values
# languages = { 'english', 'mandarin chinese', 'spanish', 'english', 'spanish', 'portugese' }
# if 'spanish' in languages:
# print("true")
# a = set(["Jake", "John", "Eric"])
# b = set(["John", "Jill"])
# print("intersect and see who attended both events")
# print(a.intersection(b))
# print(b.intersection(a))
# print("symmetric difference and see who attended only one event")
# print(a.symmetric_difference(b))
# print(b.symmetric_difference(a))
# print(" difference and see which members only attened one and not the other")
# print(a.difference(b))
# print(b.difference(a))
# print(" see a list of all participants")
# print(a.union(b))
# CARS PRACTICE
showroom = {"jeep", "corvette", "subaru", "camry", "camry"}
print(len(showroom))
new_showroom = {"civic", "corolla"}
showroom.update(new_showroom)
showroom.discard("corvette")
junkyard = {"hummer", "jeep", "xplorer", "liberty", "subaru"}
print(showroom.intersection(junkyard))
showroom.union(junkyard)
print(showroom.union(junkyard)) | true |
266cfd7f1d391e9b3e9e73cb511e532d3e4d1f7d | Shruti12110310/python-projects | /randomnum.py | 1,084 | 4.1875 | 4 | import random
def guess(x):
random_num=random.randint(1,x)
guess1=0
guess1=int(input( f'guess a num between 1 and {x}:' ))
#print(guess1)
#print(random_num)
while(guess1!=random_num):
if(guess1>random_num):
print("too big!try again")
guess1=int(input("guess again:"))
if(guess1<random_num):
print("too small!try again")
guess1=int(input("guess again:"))
if(guess1==random_num):
print("found")
def computer_guess(x):
print(f'think of a number between 1 and {x}:')
feedback=''
low=1
high=x
while(feedback!='c'):
if low!=high:
guess=random.randint(low,high)
else:
guess=low
feedback=input(f'is {guess} too high(H) or too low(L) or correct(C)?').lower()
if(feedback=='h'):
high=guess-1
elif(feedback=='l'):
low=guess+1
print(f'yay the computer guessed the correct number,i.e., {guess}')
#guess(100)
computer_guess(50)
| true |
bc857da3074062de47b9c121831406fe334666b0 | manurp/Python_programs | /calkuletar.py | 821 | 4.125 | 4 | def add(x,y):
print(x+y)
def sub(x,y):
print(x-y)
def mult(x,y):
print(x*y)
def div(x,y):
print(x/y)
def calculator():
a=int(input("Enter the first number: "))
b=int(input("Enter the second number: "))
op=input("What operation do you want to perform?(+,-,*,/): ")
print("Ans= ",end='')
if op=='+':
add(a,b)
elif op=='-':
sub(a,b)
elif op=='*':
mult(a,b)
elif op=='/':
if b==0:
print("Error")
else:
div(a,b)
else:
print("Invalid operator!!")
again()
def again():
print("Do you wish to calculate again?")
c=input("Press 'y' to calculate, 'n' to exit: ")
if c=='Y':
calculator()
elif c=='N':
print("Thank you")
else:
again()
calculator()
| true |
74ee37e26855de7cab114abe7dcec707bf5588d9 | jlgrosch/PythonTraining | /numbers2.py | 578 | 4.25 | 4 | for numbers in range(1,21):
print(numbers)
numbers = list(range(1,1000001))
print(numbers)
print(min(numbers))
print(max(numbers))
print(sum(numbers))
for numbers in range(1,21,2):
print(numbers)
for numbers in range(3,31,3):
print(numbers)
cubes = []
for value in range(1,11):
cubes = value**3
print(cubes)
cubes = [value**3 for value in range(1,11)]
print(cubes)
print('The first three items in the list are ' + str(cubes[:3]))
print('The next three items on the list are '+ str(cubes[3:6]))
print('The last three items on the list are '+ str(cubes[-3:]))
| true |
064f2abca01fb8a2344f1d229ca54918ca8916bc | qimanchen/python-100days-learning | /day_04_loop_struct/homework_3.py | 539 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
打印各种三角形
"""
def print_angle(lines):
"""
"""
# 第一种
for i in range(1, lines+1):
print("*" * i)
# 第二种
for i in range(lines, 0, -1):
for j in range(1, lines+1):
if j>=i:
print("*", end="")
else:
print(" ", end="")
print()
# 第三种
# i * (i-1)*2
# (lines-1),
for j in range(1, lines + 1):
print(" "*(lines-j) + "*"* (1+(j-1)*2))
if __name__ == "__main__":
lines = int(input("请输入行数:"))
print_angle(lines)
| false |
5d4f2ba0ee5a3c26bcd813e86ce9d449c8c31bfa | jasonw80703/callia_python | /review1_4.py | 1,380 | 4.25 | 4 | # Let's review everything we've learned in the last four lessons.
# Question 1
# Print "Hello World!" as a String
print("hello world!")
# Question 2
# Print 12345 times 2
# * times
# / divide
# + add
# - subtract
print(12345 / 2)
# Question 3
# Create a variable named "food" that has the value of your favorite food.
# Print "I love to eat " and then your favorite food using your variable.
food = "ice cream"
two = "Jason loves to eat chocolate."
# "I love to eat ice cream. Jason loves to eat chocolate."
print("I love to eat " + food + "." + " " + two)
# Question 4
# Create 3 variables that contain 3 numbers.
# Print one number by adding the first two numbers, and then subtracting the last number.
rainbow = 9
heart = 8
unicorn = 6
print(rainbow + heart - unicorn)
# Question 5
# Print something with the "equals" operator that returns True.
# Print something with the "greater than" operator that returns False.
print(5 == 786)
print(986 > 7)
# Question 6
# For each below, what will it return?
print(5 != 6) # True
print(2 <= 2) # True
print(10 >= 10.5) # True
# Question 7
# Create any list of numbers. Hint: use []
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
[1]
[]
# Question 8
# Create a variable named "days" that has the value of a list of the days in a week as Strings. For example, Monday, Tuesday...
days = ["Monday", "Tuesday", "Wednesday", "Thursday"]
print(days) | true |
85df0864166109614d4adbb6ae12970be8f6d871 | cyysu/PythonDataStructure | /Struct/Stack/SqStack.py | 1,290 | 4.125 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'MrHero'
class SqStack(object):
"""
栈的线性结构
"""
def __init__(self, size):
self.data = list(None for _ in range(size))
self.max_size = size
self.top = -1
def get_length(self):
# 返回栈的长度
return self.top + 1
def push(self, elem):
# 进栈
if self.top + 1 == self.max_size:
raise IndexError("Stack is full")
else:
self.top += 1
self.data[self.top] = elem
def pop(self):
# 出栈
if self.top == -1:
raise IndexError("Stack is empty")
else:
self.top -= 1
return self.data[self.top + 1]
def get_top(self):
# 取栈顶元素
if self.top == -1:
raise IndexError("Stack is empty")
else:
return self.data[self.top]
def show_stack(self):
# 从栈顶向下开始显示栈里面的元素
j = self.top
while j >= 0:
print self.data[j]
j -= 1
def is_empty_stack(self):
return self.top == -1
if __name__ == '__main__':
sqs = SqStack(5)
sqs.push(1)
sqs.push(2)
sqs.push(3)
sqs.show_stack()
| false |
dfca19b225fa8693d2138e1d5259afc65c87d11a | madhystr/uip_prog3 | /laboratorios/sem6/quiz6.py | 774 | 4.125 | 4 | directorio = {"Maria":3997665,"Jose":2333837,"Juan":3995984}
print ("DIRECTORIO TELEFONICO")
print ("Que desea hacer? " "1: agregar, 2: buscar, 3: eliminar, 4: Imprimir")
x= int (input("ingrese el numero de lo que desea realizar"))
if x==1:
print ("ingrese los datos correctos")
directorio[input("ingrese el nombre")]= input("ingrese el numero telefonico")
print (directorio)
elif x==2:
print ("ingrese los datos correctos de la persona que desea buscar")
dic= input("Ingrese el nombre: ")
print (directorio[dic])
elif x==3:
print ("ingrese datos correctos que desea eliminar")
eli= input ("Ingrese el nombre")
del directorio [eli]
print (directorio)
else:
print ("La informacion de su directorio es: " )
print (directorio) | false |
88dfdb70e737b40a5eaa45cc97bbad12a2c3f84a | krishan-bhadana/Python | /Number Game.py | 963 | 4.21875 | 4 | """
Practice Problem 3:
Let's play a game today!
Prince and Shubham from your geek a bored of sitting at the back seat, so they decided to play a game.
The game was as follows - Given a number N the player must subtract 1, 2 or 3 from N in order to make
a number that is divisible by 4. The game will continue until any player is able to make such a number,
and the player doing so wins the game.
Prince is a generous guy and he allows Shubham to start first.
Your classmate Dhananjay now wishes to predict who is going to win the game. Your task is to help him
out in predicting the winner of the game by writing a Python program.
The program should take a number N as the input and output the name of the winner of the game.
Example:
Input: 6
Output: Shubham
"""
#Code:
N = int(raw_input("Enter the number: "))
if N % 4 == 0: # the player has to make a move, so if it is divisible by 4 prince will win
print "Prince"
else:
print "Shubham" | true |
99fcb1277ac93cf6a09dce341bc558f3f44f8447 | Whice/-PrimalNumbers | /Python/PrimalNumberKeeper.py | 1,137 | 4.125 | 4 | #Класс памяти, который содержит хранителя чисел и методы для него.
class Memory():
#Список для хранения простых чисел.
_keeper=[]
#Заполнить хранителя(список для хранения) первыми значениями.
@classmethod
def CreateKeeper(self):
self._keeper = [ 3, 5, 7 ]
#Добавить к концу хранителя список чисел.
@classmethod
def AddKeeper(self, addList):
for i in addList:
self._keeper.append(i)
#Получить хранителя(список найдены протых чисел).
@classmethod
def GetKeeper(self):
return self._keeper
#Получить хранителя(список найдены протых чисел).
@classmethod
def SetKeeper(self, newKeeper):
if len(newKeeper)>len(self._keeper):
self._keeper=newKeeper
| false |
1d442ec22ab4e64ca20095c341dff1e6ddbd1c67 | RicardoLima17/lecture | /week02/lab2.3.X/randomGenerator.py | 262 | 4.125 | 4 |
# Author Ricardo
# program that prints out a random number between 1 and 10
# import the module random
import random
# number that you need random
number = random.randint(1,10)
# print the random numbers
print ("here is a random number {}" .format(number)) | true |
a0d69204f7f733298bc4122dc15d13d93d3056f6 | RicardoLima17/lecture | /week02/lectures/helloName.py | 387 | 4.15625 | 4 | # User a variable to greet
# Author: Ricardo Rodrigues
name = "Ricardo"
print('Hello ' + name)
# String with letters and number must use ''{} .format''
age = 41
print('your age is {}' .format(age))
# String with letters and number must use ''Str''
age = 41
print('your age is ' + str(age))
# Now print name and age together
age = 41
print('your name is {} \nyour age is {}' .format(name, age)) | true |
5e586ffc5ba88be29c87eaecc2322cd84c3f56cc | huszarpp/Sorting-algorithms | /Insertion_sort.py | 292 | 4.125 | 4 | def insertion_sort(array):
for i in range(1, len(array)):
j = i
while j >= 1 and array[j] < array[j-1]:
array[j], array[j-1] = array[j-1], array[j]
j -= 1
i += 1
return array
array = [9,7,5,3,1,0,2,4,6,8]
print(insertion_sort(array))
| false |
5bd13dd3e29bb3cbc2c596eb30bfc103068c6710 | wilecoyote1/TripIntoDataStructuresAndAlgorithms | /bubblesort/bubblesort.py | 441 | 4.375 | 4 | def bubblesort(array):
"""
sort the array using the bubble sort algorithm
"""
permutation = True
while permutation:
permutation = False
for i in range(len(array)-1):
if (array[i+1]<array[i]):
permutation = True
swap(array,i,i+1)
def swap(array,i,j):
"""
swap 2 elements in an array
"""
tmp = array[i]
array[i] = array[j]
array[j] = tmp
| true |
16646be3f081afd6ad645a26919c34518ece2fe5 | eckysaroyd/python | /10 solving problems/Problem 5.py | 656 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
# PROBLEM 5
# Write a program to calculate the sum of series up to n term.
# For example, if n = 5 the series will become 2 + 22 + 222 + 2222 + 22222 = 24690
# In[4]:
# Test Case 1:
# Input : 5
# Output : 24690
def sumOfSeries(num):
sum = 0
num1 = 2
for i in range(num):
sum += num1
num1 = num1 * 10 + 2
return sum
sum = sumOfSeries(5)
print(sum)
# In[5]:
# Test Case 2:
# Input: 6
# Output: 246912
num = int(input("Enter the number: "))
sum = 0
num1 = 2
for i in range(num):
sum += num1
num1 = num1 * 10 + 2
print("Sum of ", num, "=", sum)
# In[ ]:
| true |
9605499166eb1fe35132c494de5d9d9514b6aa2a | rakeshbasavarajpatil/Concert_Entry_Decider | /Concert_entry_decider.py | 596 | 4.125 | 4 | #The program allows a concert organizer to decide on whether to allow the individual an entry to the concert based on their age and also
#validated if they can drink also.
#ask age at the counter
age = input("Please provide your age: ")
#verify proff
if age:
age = int(age)
if age >= 21:
print("Please enter and you are allowed to drink, Enjoy the concert!!")
elif age > 18:
print("Please enter and you are not allowed to drink and always wear the wrist band, Enjoy!!")
else:
print("Sorry you are too young, we cannot allow you:(")
else:
print("please provide age")
| true |
7e88a2a7875cdd69c1aa66045bade2849e85ba77 | Laavanya-Agarwal/Python-C1 | /countWords.py | 621 | 4.1875 | 4 | #this sign is used to make a comment
#filename should end with .py
yourIntro = input ('Enter your introduction')
characterCount = 0
wordCount = 1
#wordCount starts with 1, because only 3 spaces
for character in yourIntro :
characterCount = characterCount + 1
if (character == ' ') :
wordCount = wordCount + 1
if (wordCount > 20) :
print('This is a big introduction')
elif (wordCount < 20 and wordCount > 10) :
print('This is a medium introduction')
elif (wordCount < 10) :
print('This is a small introduction')
print(wordCount)
print(characterCount)
#use python3 filename to see the output | true |
cbdfbc916f0691781f79e292ec7aba25e05d340b | rasrivas-redhat/python_oop | /library_ex_encpsulation_abstraction.py | 1,688 | 4.15625 | 4 | #class => Library
# Layers of abstraction => display available books, to lend a book, to add a book
# class => Customer
# Layers of abstraction => request for a book, return a book
class Library:
def __init__(self, listOfBooks):
self.availableBooks = listOfBooks
def displayAvailableBook(self):
print()
print("Availbe Books")
for book in self.availableBooks:
print(book)
def lendBook(self, requestedBook):
if requestedBook in self.availableBooks:
print("You have borrowed the books")
else:
print("Sorry, the book is not available")
def addBook(self, returnedBook):
self.availableBook.append(returnedBook)
print("Thank you, you have retuned the book")
class Customer:
def requestBook(self):
print("Enter the name of the book need to borrow")
self.book = input()
return self.book
def returnBook(self):
print("Enter the name of the book you are returning")
self.book = input()
return self.book
library = Library(['ABC'], ['XYZ'], ['PQR'])
customer = Customer()
while True:
print("Enter 1 to display the available books")
print("Enter 2 to request a book")
print("Enter 3 to return a book")
print("Enter 4 to exit")
userChoise - int(input())
if userChoise is 1:
library.displayAvailableBooks()
elif userChoise is 2:
requestedBook = customer.requestBook()
library.lendBook(requestedBook)
elif userChoise is 3:
returnedBook = customer.returnBook()
library.addBook(returnedBook)
elif userChoice is 4:
quit()
| true |
1d87fe73cb4a05f7431ac7a2c7eb6ff6c505e8c0 | Achan40/FullStackPractice | /Python/simple_game.py | 1,214 | 4.1875 | 4 | # Rules
# Computer thinks of a 3 digit number with no repeating digits
# Player then guesses a 3 digit number
# Computer then give back clues
# Clues
# Close: guessed correct num in wrong position
# Match: guess correct num in correct position
# Nope: Haven't guessed anything correctly
import random
# Player Guess
def get_guess():
return list(input('What is your guess: '))
# Computer code
def get_code():
digits = [str(num) for num in range(10)]
# Shuffle digits, then grab the first 3
random.shuffle(digits)
return digits[:3]
# Generate Clues
def generate_clues(code, user_guess):
if user_guess == code:
return "Code Cracked!"
clues = []
for ind,num in enumerate(user_guess):
if num == code[ind]:
clues.append('Match')
elif num in code:
clues.append('Close')
if clues == []:
return ["Nope"]
else:
return clues
# Game Logic
print("Welcome")
secret_code = get_code()
clue_report = []
while clue_report != "Code Cracked!":
guess = get_guess()
clue_report = generate_clues(guess,secret_code)
print("Here is the result of your guess: ")
for clue in clue_report:
print(clue)
| true |
c238a1809ba23b701903e2c7229732b7ce3fe5e3 | yuyao-cyber/Vigenere_Visualization | /Main_Program/button_class.py | 2,341 | 4.375 | 4 | import pygame
"""
This file defines the button() class, which is used to render buttons, the text on the buttons,
and define their functionality.
"""
class button():
"""
Use this class to define buttons in the scene
"""
def __init__(self, y1, text, click_funct, x1=5, x2=150, y2=30, textOffsetx = 5, textOffsety = 5,
color_light = (170, 170, 170), color_dark = (100, 100, 100)):
"""
y1: position of the button origin on the y coordinate
text: text to be displayed onto the button. Should be a rendered font
click_funct: The function that is called when the button is clicked
x1: the position of the button origin on the x coordinate
textOffsetx: the position of the text away from the button origin on the x coordinate
textOffsety: the position of the text away from the button origin on the y coordinate
color_light: the color that is displayed when the button is being hovered on
color_dark: default color of the button
"""
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
self.textOffsetx = textOffsetx
self.textOffsety = textOffsety
self.text = text
self.click_funct = click_funct
self.color_light = color_light
self.color_dark = color_dark
def draw(self, screen):
"""
draws the button rectangle and the button text onto the scene
"""
if self.hover(pygame.mouse.get_pos()):
# print(self.text, self.x1, self.x2, self.y1, self.y2)
pygame.draw.rect(screen, self.color_light, [self.x1, self.y1, self.x2, self.y2])
else:
# print(self.text, self.x1, self.x2, self.y1, self.y2)
pygame.draw.rect(screen, self.color_dark, [self.x1, self.y1, self.x2, self.y2])
screen.blit(self.text, (self.x1 + self.textOffsetx, self.y1 + self.textOffsety))
def hover(self, mouse):
"""
When the mouse is over the button, change the color
"""
if self.x1 <= mouse[0] <= (self.x1 + self.x2) and self.y1 <= mouse[1] <= (self.y1 + self.y2):
return True
else:
return False
def click(self):
"""
When the button is clicked on, call this function
"""
self.click_funct() | true |
6eabfa4f98d255741de5d0951b695c165125e83c | tunzor/llc-python-intro-snippets | /ex4-flask-web-server.py | 2,003 | 4.625 | 5 | # Flask is a python framework for running a web application
# https://en.wikipedia.org/wiki/Flask_(web_framework)
# Import the flask library; this gives us a web server which
# we can connect to and view our website/web application
from flask import Flask
# This allows us to access date and time functions
import datetime
# Setup the app variable for flask
app = Flask(__name__)
# This sets up a path so when we navigate to our flask
# server (http://localhost:5000 from further down),
# we get the HTML document we define below
@app.route('/')
def index():
return '''
<html>
<head>
<title>This is a Flask app!</title>
</head>
<body style="background-color: LightSkyBlue;">
<h1>Hello Ladies Learning Code!</h1>
<h3>Today is <span style="color: Firebrick;">{}</span>
and the current time is <span style="color: Firebrick;">{}</span></h3>
<p>Welcome to Flask running on Python!</p>
<p>You can learn more about flask by clicking
<a href="https://en.wikipedia.org/wiki/Flask_(web_framework)">here</a>
</p>
</body>
</html>
'''.format(datetime.datetime.now().strftime('%B %d, %Y'), datetime.datetime.now().strftime('%H:%M:%S'))
# datetime.datetime.now().strftime('%B %d %Y') gets the current date/time
# and formats it as MONTH DAY, YEAR (eg. July 25, 2019);
# datetime.datetime.now().strftime('%H:%M:%S') formats the time as HH:MM:SS (eg.12:01:11)
# The format function used above takes the formatted date and substitutes it
# in for the first occurrence of the curly braces {} on this line:
# <h3>Today is <span style="color: Firebrick;">{}</span>
# and does the same for the second part for the time as 12:01:22 here:
# the current time is <span style="color: Firebrick;">{}</span></h3>
# Flask runs it's server on localhost with a default
# port of 5000
# http://localhost:5000
if __name__ == '__main__':
app.run(host='localhost')
| true |
aa2166497cc6422dd67159e055b2ac1e0326b751 | Nortmn/Python | /Les2/3.py | 606 | 4.125 | 4 | s_list = ['зима', 'весна', 'лето', 'осень']
s_dict = {1: 'зима', 2: 'весна', 3: 'лето', 4: 'осень'}
month = int(input('Введите номер месяца :'))
if month == 1 or month == 2 or month == 12:
print(s_list[0])
print(s_dict.get(1))
elif month >= 3 or month <= 5:
print(s_list[1])
print(s_dict.get(2))
elif month >= 6 or month <= 8:
print(s_list[2])
print(s_dict.get(3))
elif month >= 9 or month <= 11:
print(s_list[3])
print(s_dict.get(4))
else:
print('Некорректный номер месяца')
| false |
40821bfae8e539c8b22e70d21d613a6b461aad88 | KennySoh/PythonNotes | /Problem Set & Answers/week8_hw_3.py | 1,119 | 4.21875 | 4 | import math
#return only the derivative value without rounding
#your return value is a float, which is the approximate value of the derivative
#Tutor will compute the approximate error based on your return value
class Diff(object):
def __init__(self,f,h=1E-4):
self.f=f
self.h=h
def __call__(self,x):
return (self.f(x+self.h)-self.f(x))/self.h
"""
def f(x):
return 0.25*x**4
df = Diff(f) # make function -like object df
# df(x) computes the derivative of f(x) approximately:
for x in (1, 5, 10):
df_value = df(x) # approx value of derivative of f at point x
exact = x**3 # exact value of derivative
print "f’(%d)=%g (error=%.2E)"%(x, df_value , exact-df_value)
"""
def g(x):
return math.log(x)
df = Diff(g,0.1) # make function -like object df
# df(x) computes the derivative of f(x) approximately:
exact=0.1
df_value = df(10) # approx value of derivative of f at point x
print (df_value,exact-df_value)
"""
import math
def f(x):
return math.log(x)
df = Diff(f,1)
df_value = df(10)
print df_value
exact = 0.1
print exact-df_value
""" | true |
5d507dc648f63948bcd36eb8a822c38ba077fbd7 | Selina147/MIT-problem_set | /ps1b.py | 680 | 4.15625 | 4 | #ps_1b
annual_salary = float(input('Enter your annual salary: '))
portion_saved = float(input('Enter the percentage of your salary to save, as a dicimal: '))
total_cost = float(input('Enter the cost of your dream house: '))
semi_annual_raise = float(input('Enter the semi raise, as a dicimal: '))
current_savings = 0
portion_down_payment = 0.25
r = 0.04
months = 0
#存款大于等于首付时买房
while current_savings < total_cost *portion_down_payment:
if (months-1)>0 and (months-1) % 6 == 0:
annual_salary *= (1+semi_annual_raise)
current_savings += annual_salary/12 * portion_saved + current_savings*r/12
months +=1
print('Number of months: ',months) | true |
3378f7d635e30c86f85fa29d429890e4a5646f8f | OttilieWilliams/module2 | /ch06_command-line-and-git/ch06_OttilieWilliams.py | 969 | 4.125 | 4 |
#------------------------------------------------------------
#CHAPTER 6 - Command Line and Git with Python
#------------------------------------------------------------
# Command line: Commands
# cd - change directory
# ls - lists files within the file you are in
# pwd - prints the full file path of the directory
# mkdir - creates a new folder within the folder you are in
#------------------------------------------------------------
# Github:
# To create a new repository:
# 1. Go to github account
# 2. Click on 'repositories' tab
# 3. Click on button that says 'New'.
# 4. Give it a name and click 'Create repository'.
# Using command line to clone it to your desktop
# 1. In command line, navigate to your python course folder using cd.
# 2. Create a copy of your new GitHub repository on your laptop,
# using the command:
# git clone https://github.com/GITHUB-USERNAME/REPOSITORY_NAME.git
# Making a new file:
# Touch file_name.py
| true |
9985cce17bd38a59d78134558c15992a1dbad874 | OttilieWilliams/module2 | /ch11_while-loop/ch11_OttilieWilliams.py | 2,965 | 4.21875 | 4 |
#---------------------------------------------------
# CHAPTER 11- While loops
#---------------------------------------------------
#How to write a while loop:
# while CONDITION:
#(Indent) CODE-BLOCK
#------------------------------------
# Task 1
x = 33
while x>= 1:
print(x,':', end='')
x = x/2
print(x)
#------------------------------------
#Task 2: Creating triangular numbers
n= 5
result = 0
while n > 0:
result = result + n
n = n - 1
print(result)
#------------------------------------
# Task 3:
# Challenge: create a system to advise pupils of whether they have
# passed or failed.
# VERSION 1
#mark = 0
#
#while mark > -1:
# mark = int(input('What is your mark? '))
# if mark >= 70:
# print('FIRST CLASS')
#
# elif mark >= 40:
# print('PASS')
#
# elif mark < 40:
# print('FAIL')
#------------------------------------
#VERSION 2
didYouPass = 'Yes'
while didYouPass == 'Yes':
mark = int(input('What is your pass? '))
if mark >= 70:
print('FIRST CLASS')
elif mark >= 40:
print('PASS')
elif mark < 40:
print('FAIL')
didYouPass = input('Did you pass? ')
#------------------------------------
# VERSION 3
#didYouPass = 'YES'
#mark = 1
#
#while didYouPass == 'YES':
# didYouPass = input('Did you pass? YES or NO ')
# while mark == 1:
# mark = int(input('Please type in your mark (1-100) here: '))
# if mark >= 70:
# print('Well done - firt class!')
# elif mark >= 40:
# print('That\'s alright, a pass!')
# elif mark <= 30:
# print('Oh no, you failed this class')
#------------------------------------
# How to create a break in your code:
#i = 55
#
#while i > 10:
#
# print(i)
#
# i = i * 0.8
#
# if i == 35.2:
#
# break
#------------------------------------
# Task 4: Write an application that prints a greeting for the
# name entered, until the user enters 'Done'.
while True:
name = input('What is your name? ')
print(name)
if name == 'Done':
break
#------------------------------------
# Guessing game:
attempts = 3
from random import randint
def guess(attempts, endrange):
number = randint(1, endrange)
print("Welcome! Can you guess my secret number?", "You have ", attempts, " guesses remaining.")
while attempts > 0:
guess = int(input('Make a guess: '))
if guess == number:
print('Well done! You got it right.')
break
elif guess < number:
print('No - too low!')
attempts = attempts - 1
print('You have ', attempts, ' attempts remaining.')
elif guess > number:
print('No - too high!')
attempts = attempts - 1
print('You have ', attempts, ' attempts remaining.')
print("END OF GAME: thanks for playing! ")
| true |
3745256049de0d080387c33dca5dd833c5ce261d | OttilieWilliams/module2 | /ch03_user-input-and-functions/ch03_test.py | 1,107 | 4.3125 | 4 | #---------------------------------------------------
#CHAPTER 3 - test file - Task 1 and Import practice
#---------------------------------------------------
# Task 1: Input from a user
print ("What's your name?")
name = input()
#print ("Hello {}!".format(name))
#print (name.lower())
#name = input("What's your name? ")
#print ("Hello {}!".format(name.upper()))
#age = input("What's your age? ")
#print ("Wow, you're {} years old!".format(age))
#
#city = input("What's your city? " )
#print ("Gosh, you're from {}!".format(city))
#a = "please type your age: "
#---------------------------------------------------
# Import practice
import ch03_function
num1 = 2
num2 = 4
print (ch03_function.add_two_numbers(num1, num2))
#from ch03_function import *
#
#num1 = 2
#num2 = 4
#
#print (add_two_numbers(num1, num2))
#import ch03_function
#
#centigrade = 10
#
#print (ch03_function.convert_temperature(centigrade))
#from ch03_function import *
#
#miles = 10
#
#print (convert_distance(miles))
#print ("this" == 'this')
#print (3 >= 4)
#print (3 >= 2)
#print (5 != 3)
#print (5 != 'some string')
| true |
3c08f1654d53ad82095003da14397a76c5027c75 | OttilieWilliams/module2 | /coding-bat/string-1.py | 2,316 | 4.3125 | 4 | #-------------------------------------
#Given a string name, e.g. "Bob", return a greeting of the form "Hello Bob!".
#def hello_name(name):
# return ("Hello " + name + "!")
#-------------------------------------
#Given two strings, a and b,
#return the result of putting them together in the order abba
# e.g. "Hi" and "Bye" returns "HiByeByeHi".
#def make_abba(a, b):
# return (a + b + b + a)
#-------------------------------------
#The web is built with HTML strings like "<i>Yay</i>" which draws
#Yay as italic text. In this example, the "i" tag makes <i> and
#</i> which surround the word "Yay". Given tag and word strings,
#create the HTML string with tags around the word, e.g. "<i>Yay</i>".
#def make_tags(tag, word):
# return ("<" + tag + ">" + word + "</" + tag + ">")
#-------------------------------------
#Given an "out" string length 4, such as "<<>>", and a word,
#return a new string where the word is in the middle of the
#out string, e.g. "<<word>>".
#def make_out_word(out, word):
# return ((out[0:2]) + word + (out[2:4]))
#-------------------------------------
#Given a string, return a new string made of 3 copies of the last
# 2 chars of the original string. The string length will be at least 2.
#def extra_end(str):
# return (str[len(str)-2:])*3
#coding bat alternative
#def extra_end(str):
# end = str[-2:]
# return end + end + end
#-------------------------------------
#Given a string, return the string made of its first two chars,
#so the String "Hello" yields "He". If the string is shorter than
# length 2, return whatever there is, so "X" yields "X", and the
#empty string "" yields the empty string "".
#def first_two(str):
# return (str[:2])
#coding bat alternative
#def first_two(str):
# if len(str) >= 2:
# return str[:2]
# else:
# return str
#-------------------------------------
#first half
#def first_half(str):
# return str[0:len(str)/2]
#-------------------------------------
#Given a string of even length, return the first half. So the string "WooHoo" yields "Woo".
#def first_half(str):
# return str[0:len(str)/2]
#-------------------------------------
#Given a string, return a version without the first and last char,
#so "Hello" yields "ell". The string length will be at least 2.
return str[1:-1]
| true |
6fc13fcbb106aafd340d08a9af8f5e24698bbf5f | tylerCallaway/Vsa | /classes-notes.py | 1,116 | 4.125 | 4 | # Classes
# defining a class called Person, which is a type of object
class Person(object):
# defining the init method for the class person with a name
def __init__(self, name, age):
self.name = name
self.age = age
def setAge(self, age):
self.age = int(age)
def __str__(self):
ans = self.name + " is age "+ str(self.age)
# return a string
return ans
def getAge(self):
return self.age
person1 = Person("Ashlyn", 26)
person1.setAge(27)
print str(person1)
class VSAstudent(Person):
def set_class(self, class_name):
self.class_name = class_name
def get_class(self, class_name):
return self.class_name
def compareAge(self, otherStudent):
if self.age > otherStudent.age:
return self.name + "is older than " + otherStudent.name
else:
return self.name + "is younger than " + otherStudent.name
person2 = VSAstudent('Santosh', 15)
person2.set_class('programming')
print person2
print person2.class_name
person3 = VSAstudent('Damian', 13)
print person2.compareAge(person3)
| false |
0cca318762ffeb8f8d7eedee28bcf96fbc933a2e | tylerCallaway/Vsa | /proj02_loops/proj02_01.py | 1,000 | 4.3125 | 4 | # Name:
# Date:
# proj02: sum
# Write a program that prompts the user to enter numbers, one per line,
# ending with a line containing 0, and keep a running sum of the numbers.
# Only print out the sum after all the numbers are entered
# (at least in your final version). Each time you read in a number,
# you can immediately use it for your sum,
# and then be done with the number just entered.
#Example:
# Enter a number to sum, or 0 to indicate you are finished: 4
# Enter a number to sum, or 0 to indicate you are finished: 5
# Enter a number to sum, or 0 to indicate you are finished: 2
# Enter a number to sum, or 0 to indicate you are finished: 10
# Enter a number to sum, or 0 to indicate you are finished: 0
#The sum of your numbers is: 21
user_input = int(raw_input("Please state a number."))
sum = 0 + int(user_input)
while int(user_input) > 0:
print "Your sum is " + str(sum)
user_input=raw_input("Please state a number, enter 0 when finished.")
sum= sum + int(user_input) | true |
8d8ced9e529e66f9d7b7a7d89d39f9ef43dae404 | SamuelLangenfeld/python_practice | /tree-prune.py | 1,526 | 4.125 | 4 | # Given a binary tree and an integer k, filter the binary tree such that its leaves don't contain the value k. Here are the rules:
# - If a leaf node has a value of k, remove it.
# - If a parent node has a value of k, and all of its children are removed, remove it.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __repr__(self):
return f"value: {self.value}, \
left: ({self.left.__repr__()}), \
right: ({self.right.__repr__()})"
# Definitely want recursion right? split -> go left, go right.
# If value = k and no children, remove self
def filter(node, k):
# Fill this in.
# I can mutate node. But the parent will always point to node.
# Basically I can access/modify node's properties using its access points
# but reassigning node will only change the 'node' reference locally
if node.left:
node.left = filter(node.left, k)
if node.right:
node.right = filter(node.right, k)
if node.value == k and node.left is None and node.right is None:
# filter self
return None
return node
# 1
# / \
# 1 1
# / /
# 2 1
n5 = Node(1)
n4 = Node(2)
n3 = Node(1, n5)
n2 = Node(1, n4)
n1 = Node(1, n2, n3)
n3.identifier = 'n3'
n5.identifier = 'n5'
print(n1)
print(filter(n1, 1))
# 1
# /
# 1
# /
# 2
# value: 1, left: (value: 1, left: (value: 2, left: (None), right: (None)), right: (None)), right: (None)
| true |
1e00a5bdb76a3eb94f71d6d6a3bf975cd81095ad | srirambandarupalli/python-programming | /Beginner level/largest of 3 numbers.py | 208 | 4.1875 | 4 | x=input("enter the number:")
y=input("enter the number:")
z=input("enter the number:")
if (x>y and x>z):
print("x is largest")
elif(y>x and y>z):
print("y is largest")
else:
print("z is largest")
| false |
ec91b1dc6c57c35c050fcd293caf72c275d3fa9d | OttmanElasraoui/Elasraoui_Ottman | /Semester1/PYLesson_04/4.0/receipt.py | 805 | 4.125 | 4 | Item1 = input("Enter your first item")
Price1 = int(input("Enter the price of your first item"))
Item2 = input("Enter your second item")
Price2 = int(input("Enter the price of your second item"))
Item3 = input("Enter your third item")
Price3 = int(input("Enter the priceof your third item"))
def printFormat(Item, Price):
print("* {:<10}........{:10.2f}".format(Item, Price))
print("<<<<<<<<<<<<<<<___Recipt___>>>>>>>>>>>>>>>")
#line1
printFormat(Item1, Price1)
#line2
printFormat(Item2, Price2)
#line3
printFormat(Item3, Price3)
subtotal = Price1 + Price2 + Price3
tax = subtotal * 0.08
total = tax + subtotal
printFormat("Subtotal: ", subtotal)
printFormat("Tax: ", tax)
printFormat("Total: ", total)
print("__________________________________________")
print(" * Thank you for your support *")
| true |
b1dda91d8cfac21aa280defce49bc760df1269da | nprithviraj24/TKR-workshop | /conditions.py | 681 | 4.21875 | 4 | #declaring a variable
a = 13
#if statement
if a > 9:
print "HI."
# Meddle with the code and make your own if condition.
#if-else statement
if a%2 == 0:
print a, " is an Even number."
else:
print a, "is a Odd number."
#Task 1
print "\n\n"
print "Printing even number from a given list and adding it to a new list "
l = [1,2,3,4,5,6,7,8,9]
even_list = []
odd_list = []
print(l)
for i in l:
if i%2 == 0:
print i
even_list.append(i)
else:
odd_list.append(i)
#Task 2
#Print even_list and odd_list.
# ELIF
num = 0
if num < 0:
print "Negative number."
elif num == 0
print "Zero"
elif num > 0
print "Positive number."
#Task
| true |
8eaa7c4617ab9132044a6138047e37f37f47a938 | mkushal10/Find-Length | /find_length_of_the_sentence.py | 358 | 4.3125 | 4 | # Use a Python function that takes a list of words and returns the length of the string.
def getLongestWordLength(input_str):
len_list = []
for each in input_str:
len_list.append(len(each))
return max(len_list)
if __name__ == "__main__":
list_word = input('Enter the sentence : ').split()
print(getLongestWordLength(list_word))
| true |
f0e69ba7fcf8ce7661231768ee6eafd3bb308720 | kshestakova/homework | /3_1.py | 2,925 | 4.21875 | 4 | """ Создайте класс, который будет описывать ваш фильм. Давайте назовём его Movie.
У него должны быть следующие атрибуты: name, duration, releaseDate и rating.
Для класса Movie определите метод с именем show_info(),
который выводит на экран параметры вашего фильма, значение атрибутов объекта
(name, duration и rating).
"""
class Movie:
def __init__(self, name = "Noname", duration = 0, releaseDate = 1970, rating = 0.0):
self.name = name
self.duration = duration
self.releaseDate = releaseDate
self.rating = rating
def show_info(self):
print("Film:", self.name)
print("Duration: {h}:{m}".format(h = self.duration//60, m = self.duration%60))
print("Release date:", self.releaseDate)
print("Rating:", self.rating, "\n")
"""
Создайте 10 объектов класса Movie, это должны быть ваши самые любимые фильмы.
Информацию о них можно взять на imdb или в каком-то другом месте.
"""
movies = []
with open ("films.txt", "r") as films:
for s in films:
s = s.split(", ")
movies.append(Movie(s[0], int(s[1]), int(s[2]), float(s[3])))
"""
Создайте класс Сritic, это и будете вы.
Дадим этому классу самые базовые атрибуты - name и age.
Кроме того, будем хранить в классе список из ваших фильмов.
Создайте функции для класса Сritic:
Вывод информации о самом длинном фильме
Вывод информации о фильме с самым высоким рейтингом
Вывод суммарной длительности всех фильмов в списке
"""
class Critic:
def __init__(self, name = "Me", age = 15, movies = []):
self.name = name
self.age = age
self.movies = movies
def longest(self):
longest = self.movies[0]
for m in self.movies[1:]:
if m.duration > longest.duration:
longest = m
print("The longest movie:")
longest.show_info()
def highest(self):
highest = self.movies[0]
for m in self.movies[1:]:
if m.rating > highest.rating:
highest = m
print("Movie with the highest rating:")
highest.show_info()
def totalTime(self):
s = 0
for m in self.movies:
s += m.duration
print("Total time: {h}:{m}".format(h = s//60, m = s%60))
me = Critic("Kseniia", 34, movies)
me.longest()
me.highest()
me.totalTime()
| false |
91b40b94f58106849052b706a641a4973966f1b1 | jaequan876/cti110 | /P2HW2_ListSets_PerrinJae'Quan.py | 1,510 | 4.25 | 4 | # CTI - 110
# P2HW2 - List and Sets
# Jae'Quan Perrin
# March 10, 2021
#
# Prompt user to enter a series of ten numbers
# Display the lowest number in the list
# Display the highest number in the list
# Display the total of all the numbers in the list
# Display the average of the numbers in the list
# Convert the list into a set
# Display the set content
mylist = []
print('Please enter a number:')
num1 = float(input())
print('Please enter a second number:')
num2 = float(input())
print('Please enter a third number:')
num3 = float(input())
print('Please enter a fourth number:')
num4 = float(input())
print('Please enter a fifth number:')
num5 = float(input())
print('Please enter a sixth number:')
num6 = float(input())
print('Please enter a seventh number:')
num7 = float(input())
print('Please enter an eight number:')
num8 = float(input())
print('Please enter a ninth number:')
num9 = float(input())
print('Please enter a tenth number:')
num10 = float(input())
mylist.append(num1)
mylist.append(num2)
mylist.append(num3)
mylist.append(num4)
mylist.append(num5)
mylist.append(num6)
mylist.append(num7)
mylist.append(num8)
mylist.append(num9)
mylist.append(num10)
average = sum(mylist) / len(mylist)
print('Lowest number:', min(mylist))
print('Highest number:', max(mylist))
print('Total of numbers:', sum(mylist))
print('The average of the numbers is:', average)
mylist = str(mylist)
print('The list converted to a string is:', mylist)
| true |
474f7e511cd6ed9986c041e0c4b5fb2c0d3c40f4 | kononenkoie/CS50_examples_PYTHON | /Exceptions/handle_it.py | 1,638 | 4.28125 | 4 | # обработка исключительных ситуаций
# try/except
try:
num = float(input("1.Bвeдитe число: "))
except:
print("Пoxoжe, это не число!")
# specifying exception type
try:
num = float(input("\n2.Bвeдитe число: "))
except ValueError:
print("Этo не число!")
# handle multiple exception types
print()
for value in (None, "Hi!"):
try:
print("3.Пытаюсь преобразовать в число", value, "-->", end=" ")
print(float(value))
except (TypeError, ValueError):
print("Пoxoжe, это не число!")
print()
for value in (None, "Hi!"):
try:
print("4.Пытаюсь преобразовать в число", value, "-->", end=" ")
print(float(value))
except TypeError:
print("Я умею преобразовывать только строки и числа!")
except ValueError:
print("Я умею преобразовывать только строки, составленные из цифр!")
# get an exception's argument
try:
num = float(input("\n5.Bвeдитe число: "))
d = 1/ num
except ValueError as e:
print("Этo не число! Интерпретатор как бы говорит нам...")
print(e)
except ZeroDivisionError as i:
print("Ошибка! Интерпретатор как бы говорит нам...")
print(i)
# try/except/else
try:
num = float(input("\n6.Bвeдитe число: "))
except ValueError:
print("Этo не число!")
else:
print("Bы ввели число", num) | false |
adfaecc39508bae7396f905d5717b8ce256590cf | rahul1907935/Strings-and-Lists | /area.py | 251 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 9 11:31:58 2021
@author: rahul
"""
from math import pi
r = float (input ("Input the radius of the circle : "))
print ("The area of the circle with radius " + str(r) + " is: " + str(pi * r**2)) | false |
da53c1e166cf0190a2e156062cc2fe1d07e54965 | GabyPopolin/Estrutura_de_Decisao | /Estrutura_Decisao_exe_25.py | 1,191 | 4.3125 | 4 | '''Faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são:
"Telefonou para a vítima?"
"Esteve no local do crime?"
"Mora perto da vítima?"
"Devia para a vítima?"
"Já trabalhou com a vítima?"
O programa deve no final emitir uma classificação sobre a participação da pessoa no crime.
Se a pessoa responder positivamente a 2 questões ela deve ser classificada como "Suspeita", entre 3 e 4 como "Cúmplice"
e 5 como "Assassino". Caso contrário, ele será classificado como "Inocente".'''
print('As seguintes perguntas terão de ser respondidas apenas com "Sim" e "Não".')
print('')
perguntas = ([
'Você telefonou para a vítima? ' ,
'Você esteve no local do crime? ' ,
'Você mora perto da vítima? ' ,
'Você devia algo para a vítima? ' ,
'Já trabalhou com a vítima? '])
resposta = 0
for resp in perguntas:
resposta += (input(resp).title() == 'Sim')
if resposta == 5:
print('Você é o ASSASINO!!!')
elif resposta == 4 or resposta == 3:
print('Você é o CÚMPLICE!!')
elif resposta == 2:
print('Cuidado, você é um possível suspeito!')
else:
print('Uffa! Dessa vez você escapou. Mas estarei de olho em você.')
| false |
5fe600e3b449af179e431591c4059a034731a0e4 | GabyPopolin/Estrutura_de_Decisao | /Estrutura_Decisao_exe_06.py | 509 | 4.125 | 4 | '''Faça um Programa que leia três números e mostre o maior deles.'''
n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o segundo número: '))
n3 = int(input('Digite o terceiro número: '))
print('')
if n1 > n2 and n1 > n3:
print('O número {}, foi o maior número informado.' .format(n1))
elif n2 > n1 and n2 > n3:
print('O número {}, foi o maior número informado.' .format(n2))
elif n3 > n1 and n3 > n2:
print('O número {}, foi o maior número informado.' .format(n3)) | false |
046c47925bf469efcfc9fcf9a948d82fde75e089 | GabyPopolin/Estrutura_de_Decisao | /Estrutura_Decisao_exe_20.py | 863 | 4.3125 | 4 | '''Faça um Programa para leitura de três notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e presentar:
A mensagem "Aprovado", se a média for maior ou igual a 7, com a respectiva média alcançada;
A mensagem "Reprovado", se a média for menor do que 7, com a respectiva média alcançada;
A mensagem "Aprovado com Distinção", se a média for igual a 10.'''
n1 = float(input('Digite a nota do primeiro bimestre: '))
n2 = float(input('Digite a nota do segundo bimestre: '))
n3 = float(input('Digite a nota do terceiro bimestre: '))
media = (n1 + n2 + n3) / 3
print('')
print('A média final do aluno foi {:.2f}' .format(media))
if media == 10:
print('O aluno está Aprovado com Distinção.')
elif media == 9.9 or media >= 7:
print('O aluno está Aprovado.')
elif media <= 6.9:
print('O aluno está Reprovado.') | false |
c1a3d0fb96cb308092a43f07b5ca113b88b0152a | sbese/learn-homework-1 | /if2.py | 1,252 | 4.59375 | 5 | """
Домашнее задание №1
Условный оператор: Сравнение строк
* Написать функцию, которая принимает на вход две строки
* Проверить, является ли то, что передано функции, строками.
Если нет - вернуть 0
* Если строки одинаковые, вернуть 1
* Если строки разные и первая длиннее, вернуть 2
* Если строки разные и вторая строка 'learn', возвращает 3
* Вызвать функцию несколько раз, передавая ей разные праметры
и выводя на экран результаты
"""
def main(str_1, str_2):
if not (type(str_1) is str and type(str_2) is str):
return 0
if len(str_1) == len(str_2):
return 1
elif len(str_1) > len(str_2):
return 2
elif len(str_1) != len(str_2) and str_2 == "learn":
return 3
if __name__ == "__main__":
print(main("123","abc"))
print(main("1dg23","abc"))
print(main("123","adfdbc"))
print(main("123",1))
print(main(1,"abc"))
print(main("a","learn"))
| false |
5a664b9126d9697490440869b76ba2af1323ddc4 | edisonlz/c1_course_python | /_数据结构_/3.栈和队列.py | 1,731 | 4.40625 | 4 | 线性数据结构: 队列
队列是一种操作受限的线性表仅允许在表的一端进行插入,
而在表的另一端进行删除,队尾入队,对头出队。
队列有两种存储方式,即数组和链表。
FIFO(先进先出)
------------------------
[head] |1 | 2 | 3 | 4 | 5 | 6 | [tail]
dequeue ------------------------ enqueue
出队 入队
class Queue(object):
def __init__(self):
self.queue = []
def enqueue(self,data):
self.queue.append(data)
def dequeue(self):
if self.queue:
return self.queue.pop(0)
queue = Queue()
线性数据结构: 栈
栈是一种操作受限的线性表只允许从一端插入和删除数据。
栈有两种存储方式,即数组和链表。
LIFO(后进先出)
入栈 出栈
↑ | 5 | ↓
| 4 |
| 3 |
| 2 |
| 1 |
———————
class Stack(object):
def __init__(self):
self.stack = []
def push(self,data):
self.stack.append(data)
def pop(self):
if self.stack:
return self.stack.pop()
stack = Stack()
# class Queue(object):
# def __init__(self):
# self.queue = []
# def enqueue(self,data):
# #入队
# self.queue.append(data)
# def dequeue(self):
# #出队并返回出队的值
# if self.queue:
# return self.queue.pop(0)
# queue = Queue()
# class Stack(object):
# def __init__(self):
# self.stack = []
# def push(self,data):
# self.stack.append(data)
# def pop(self):
# if self.stack:
# return self.stack.pop()
# stack = Stack()
| false |
056f271da7df4edf24c268d9ae9d2d519b2d8bd2 | DannyLee12/dcp | /_2020/_2021/7.py | 761 | 4.3125 | 4 | """
Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the
number of ways it can be decoded.
For example, the message '111' would give 3, since it could be decoded as
'aaa', 'ka', and 'ak'.
"""
def num_encodings(s: str) -> int:
"""Return the number of possible encodings of a message"""
if len(s) <= 1:
return 1
# since aa and aaa are still only 1 possible encoding, the empty string
# is counted as 1 and not 0
total = 0
# Assuming the first 2 digits are chosen as the number
if int(s[:2]) < 27:
total += num_encodings(s[2:])
# Assume only the first letter is chosen
total += num_encodings(s[1:])
return total
if __name__ == '__main__':
print(num_encodings("111"))
| true |
8fa5da2b871fdd1a05c33b8865347e0a3270ab79 | DannyLee12/dcp | /_2020/06_June/107.py | 928 | 4.15625 | 4 | """
This is your coding interview problem for today.
This problem was asked by Microsoft.
Print the nodes in a binary tree level-wise. For example, the following
should print 1, 2, 3, 4, 5.
1
/ \
2 3
/ \
4 5
"""
from _2020 import Tree
def node_print(t: Tree) -> None:
"""Print nodes in a binary tree row-wise"""
yield t.node
queue = [t]
while queue:
n = queue.pop(0)
if isinstance(n.left, Tree):
yield n.left.node
queue.append(n.left)
else:
if n.left:
yield n.left
if isinstance(n.right, Tree):
yield n.right.node
queue.append(n.right)
else:
if n.right:
yield n.right
if __name__ == '__main__':
t1 = Tree(1, 2, Tree(3, 4, 5))
t2 = Tree(1, Tree(2, right=3), Tree(4, right=5))
print(list(node_print(t1)))
print(list(node_print(t2)))
| true |
b29f7703b07f530de628b36c900d9a148b75c8a4 | DannyLee12/dcp | /_2020/04_April/60.py | 919 | 4.21875 | 4 | """
Given a multiset of integers, return whether it can be partitioned into two
subsets whose sums are the same.
For example, given the multiset {15, 5, 20, 10, 35, 15, 10}, it would return
true, since we can split it up into {15, 5, 10, 15, 10} and {20, 35}, which
both add up to 55.
Given the multiset {15, 5, 20, 10, 35}, it would return false, since we can't
split it up into two subsets that add up to the same sum.
"""
def partition_l(l: list) -> bool:
"""Return whether the set can be split in two subsets of the same value"""
l.sort()
n = len(l)
s1 = []
while l:
s1.append(l.pop())
if sum(s1) == sum(l):
print(s1, l)
print(s1)
return True
return False
if __name__ == '__main__':
# print(partition({15, 5, 20, 10, 35, 15, 10}))
print(partition_l([15, 5, 20, 10, 35, 15, 10]))
print(partition_l([15, 5, 20, 10, 35]))
| true |
f100267658b501a41337b54923d883eab97c040f | DannyLee12/dcp | /_2020/10_October/250.py | 1,788 | 4.25 | 4 | """
A cryptarithmetic puzzle is a mathematical game where the digits of some
numbers are represented by letters. Each letter represents a unique digit.
For example, a puzzle of the form:
SEND
+ MORE
--------
MONEY
may have the solution:
{'S': 9, 'E': 5, 'N': 6, 'D': 7, 'M': 1, 'O', 0, 'R': 8, 'Y': 2}
Given a three-word puzzle like the one above, create an algorithm that finds a
solution.
"""
from random import choice
remainder = 0
def solve_cryparithmetic(l: list) -> dict:
"""Provide a solution to a cryptarithmetic problem with unique digits"""
n = len(l[0])
d = {}
e = []
letters = set()
# Start as position -1
position = 1
while position < n + 1:
l1 = l[0][-position]
l2 = l[1][-position]
l3 = l[2][-position]
letters.add(l1)
letters.add(l2)
letters.add(l3)
e.append(f"(d['{l1}'] + d['{l2}'] + rem) % 10 == d['{l3}']")
e.append(f"(d['{l1}'] + d['{l2}'] + rem) // 10")
position += 1
e.append(f"d[l[2][0]] == rem")
while 1:
c = choice(range(1, 15))
for let in letters:
while c in d.values():
c = choice(range(0, 9))
d[let] = c
b = True
counter = 0
rem = 0
for x in e:
x = x.replace("rem", str(rem))
if counter % 2 == 1:
rem = eval(x)
else:
if not eval(x):
b = False
break
counter += 1
if b:
return d
if __name__ == '__main__':
d = solve_cryparithmetic(["SEND", "MORE", "MONEY"])
print(d)
assert (d["D"] + d["E"]) % 10 == d["Y"]
assert (d["N"] + d["R"] + (d["D"] + d["E"]) // 10) % 10 == d["E"]
print(d)
| true |
71d85f06c96cfc22bcb7272d6a67b6668c9c14a1 | DannyLee12/dcp | /_2020/08_August/171.py | 1,589 | 4.21875 | 4 | """
You are given a list of data entries that represent entries and exits of groups
of people into a building. An entry looks like this:
{"timestamp": 1526579928, count: 3, "type": "enter"}
This means 3 people entered the building. An exit looks like this:
{"timestamp": 1526580382, count: 2, "type": "exit"}
This means that 2 people exited the building. timestamp is in Unix time.
Find the busiest period in the building, that is, the time with the most people
in the building. Return it as a pair of (start, end) timestamps. You can assume
the building always starts off and ends up empty, i.e. with 0 people inside.
"""
def busiest_time(l: list, flag=None) -> tuple:
"""Return the busiest time given enters and exits"""
current, max_val = 0, 0
start, end = 0, 0
for x in sorted(l, key=lambda x: x["timestamp"]):
if x["type"] == "enter":
current += x["count"]
elif x["type"] == "exit":
current -= x["count"]
if current > max_val:
flag = True # Set flag to know when to close the interval
max_val = current
start = x["timestamp"]
elif flag: # if the start has been set recently
end = x["timestamp"]
flag = False
return start, end
if __name__ == '__main__':
print(busiest_time([{"timestamp": 1, "count": 3, "type": "enter"},
{"timestamp": 2, "count": 3, "type": "exit"},
{"timestamp": 3, "count": 2, "type": "enter"},
{"timestamp": 4, "count": 2, "type": "exit"}]))
| true |
eb77e1774a0fe34af2d2d6402741cb06128e4c2d | DannyLee12/dcp | /_2020/08_August/189.py | 847 | 4.28125 | 4 | """
Given an array of elements, return the length of the longest subarray where all
its elements are distinct.
For example, given the array [5, 1, 3, 5, 2, 3, 4, 1], return 5 as the longest
subarray of distinct elements is [5, 2, 3, 4, 1].
"""
def longest_subarray(l: list) -> list:
"""Return the longest subarray containing distinct elements"""
# For each position in l, get the longest sequence
s = set()
longest_list = []
start = 0
for i, x in enumerate(l):
if x in s:
s = set()
if i - start > len(longest_list):
longest_list = l[start: i]
start = i
s.add(x)
if i + 1 - start > len(longest_list):
longest_list = l[start: i + 1]
return longest_list
if __name__ == '__main__':
print(longest_subarray([5, 1, 3, 5, 2, 3, 4, 1]))
| true |
5aa5eaa04d9d5a59d0ba5a6161adf659aefc0807 | DannyLee12/dcp | /_2020/05_May/83.py | 863 | 4.15625 | 4 | """
Invert a binary tree.
For example, given the following tree:
a
/ \
b c
/ \ /
d e f
should become:
a
/ \
c b
\ / \
f e d
"""
from _2020 import Tree
def invert(t: Tree) -> Tree:
"""Invert a binary Tree"""
if isinstance(t.left, Tree) and isinstance(t.right, Tree):
t.right, t.left = invert(t.left), invert(t.right)
elif isinstance(t.left, Tree):
t.right, t.left = invert(t.left), t.right
elif isinstance(t.right, Tree):
t.right, t.left = t.left, invert(t.right)
else:
t.left, t.right = t.right, t.left
return t
if __name__ == '__main__':
t1 = invert(Tree("a", "b", "c"))
t2 = Tree("a", "c", "b")
assert t1 == t2
t = Tree("a", Tree("b", "d", "e"), Tree("c", "f"))
tr = Tree("a", Tree("c", right="f"), Tree("b", "e", "d"))
assert invert(t) == tr
| false |
7ac46c13b059e67a385221f14887191cb92341f7 | DannyLee12/dcp | /_2020/09_September/202.py | 945 | 4.28125 | 4 | """
Write a program that checks whether an integer is a palindrome.
For example, 121 is a palindrome, as well as 888. 678 is not a palindrome.
Do not convert the integer into a string.
"""
import math
def is_pal(i: int) -> bool:
"""Return true if i is a palindrome"""
digits = int(math.log10(i)) + 1
delta = 0
if digits % 2 == 1:
delta = 1 # In the case of a number with an odd length
# add a delta to move the mod one position
def reverse_number(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n //= 10
return r
print(i // 10 ** (digits // 2))
print(reverse_number(i % 10 ** ((digits // 2) + delta)))
return i // 10 ** (digits // 2) == reverse_number(i % 10 ** ((digits // 2) + delta))
if __name__ == '__main__':
assert is_pal(121)
assert is_pal(888)
assert not is_pal(678)
assert is_pal(1122334444332211)
| true |
ff5c25684b0abb63e729da1e0404320a006ed1c8 | DannyLee12/dcp | /_2020/08_August/165.py | 932 | 4.25 | 4 | """
Given an array of integers, return a new array where each element in the new
array is the number of smaller elements to the right of that element in the
original input array.
For example, given the array [3, 4, 9, 6, 1], return [1, 1, 2, 1, 0], since:
There is 1 smaller element to the right of 3
There is 1 smaller element to the right of 4
There are 2 smaller elements to the right of 9
There is 1 smaller element to the right of 6
There are no smaller elements to the right of 1
"""
def count_smaller_elements(l: list) -> list:
"""Return a list with the number of elements smaller than the number"""
nl = []
n = len(l)
for i, x in enumerate(l):
total = 0
for j in range(i, n):
if l[j] < x:
total += 1
nl.append(total)
return nl
if __name__ == '__main__':
assert count_smaller_elements([3, 4, 9, 6, 1]) == [1, 1, 2, 1, 0]
| true |
ab614c41142519b7d02f23659b784dfd94841578 | Billyjoe3000/Year_10_Design | /Project_3_Work/queue1.py | 2,793 | 4.34375 | 4 | """
Defined attributes in __init__
self.front = POSITION of the front of the queue in the array
self.rear = POSITION of the rear of the queue in the array
self.size = Total size of the current queue
self.Q = The actual queue array
self.capacity = The maximum size of the queue parsed to the class via the __init__ function capacity variable (constant)
self.rear initial = 29 (capacity = 30)
1st enqueue self.rear = 30 % 30 = 0
2nd enqueue self.rear = 0 + 1 % 30 = 1
3rd enqueue self.rear = 1 + 1 % 30 = 2
NOTHING is ever removed from the queue entirely, the front and rear are just shifted
"""
class Queue:
# __init__ function
def __init__(self, capacity):
self.front = self.size = 0 # the starting size and the starting position of the queue is always 0
self.rear = capacity -1 # the starting position of the rear of the queue is always the capacity - 1
self.Q = [None]*capacity
self.capacity = capacity
# Queue is full when size becomes
# equal to the capacity
def isFull(self):
return self.size == self.capacity
# Queue is empty when size is 0
def isEmpty(self):
return self.size == 0
# Function to add an item to the queue.
# It changes rear and size
def EnQueue(self, item):
if self.isFull(): # check if the queue is full, if it is full it does not do the other stuff
print("Full")
return
self.rear = (self.rear + 1) % (self.capacity) # changing the position of the rear to the position of the last thing in the list
self.Q[self.rear] = item # queuing the item into the self.Q attribute
self.size = self.size + 1 # increasing the size
print("% s enqueued to queue" % str(item))
# Function to remove an item from queue.
# It changes front and size
def DeQueue(self):
if self.isEmpty():
print("Empty")
return
print("% s dequeued from queue" % str(self.Q[self.front])) # returning the item on the front
self.front = (self.front + 1) % (self.capacity) # adding +1 to the front shifting it up the queue
self.size = self.size -1 # decreasing the size
# Function to get front of queue
def que_front(self):
if self.isEmpty():
print("Queue is empty")
print("Front item is", self.Q[self.front])
# Function to get rear of queue
def que_rear(self):
if self.isEmpty():
print("Queue is empty")
print("Rear item is", self.Q[self.rear])
# Driver Code
if __name__ == '__main__':
queue = Queue(30)
queue.EnQueue(10)
queue.EnQueue(20)
queue.EnQueue(30)
queue.EnQueue(40)
queue.DeQueue()
queue.que_front()
queue.que_rear() | true |
48d9cbe7001df7bbca8d6b14ddda2f799f12c880 | vyachegrinko/my_codewars_solutions | /5kyu/rot13.py | 1,262 | 4.59375 | 5 | '''
Description:
ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar cipher.
Create a function that takes a string and returns the string ciphered with Rot13. If there are numbers or special characters included in the string, they should be returned as they are. Only letters from the latin/english alphabet should be shifted, like in the original Rot13 "implementation".
Please note that using "encode" in Python is considered cheating.
'''
##########MY SOLUTION##########
import string
from codecs import encode as _dont_use_this_
def rot13(message):
letterLstLower = ["z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y"]
letterLstUpper = ["Z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y"]
cipher = []
for char in message:
if char in letterLstLower:
cipher.append(letterLstLower[(letterLstLower.index(char) + 13)%26])
elif char in letterLstUpper:
cipher.append(letterLstUpper[(letterLstUpper.index(char) + 13)%26])
else:
cipher.append(char)
return "".join(cipher) | true |
48853d18b80d60460be74a52487a2e5c7c2d6a85 | puttym/Algorithms | /closest_points.py | 2,082 | 4.21875 | 4 | from utilities import generate_2D_points, find_distance_2D, display_matrix, matrix_to_1D_array
from bubble_sort import bubble_sort
from math import sqrt
def find_closest_points(array, distances):
"""Returns closest among the given set of points and the distance between them.
If the minimum distance is 1000000, then initialise min_dist to a much higher value
array: list of 2D points
distances: 2D matrix containing the distance between the points
"""
min_dist = 1000000 #Deliberately initialising with a large value
for i in range(len(array)):
for j in range(len(array)):
if i != j and array[i] != array[j]:
if min_dist > distances[i][j]:
min_dist = distances[i][j]
point1 = array[i]
point2 = array[j]
return min_dist, point1, point2
def verify_min_dist(array_length, array, distances):
"""Verifies the distance between the closest points.
Returns a message if test is successful. Returns False otherwise.
The upper diagonal elements of the distance matrix, excluding the diagonal
elements, are written to a 1D-array. This array is then sorted and the first element
of the sorted array is the minimum distance.
"""
min_dist, point1, point2 = find_closest_points(array, distances)
array_legth_1D, array_distances_1D = matrix_to_1D_array(array_length, distances)
array_distances_1D = bubble_sort(array_legth_1D, array_distances_1D)
if min_dist == array_distances_1D[0]:
print('\nClosest points are',point1, 'and', point2, '.')
print('\nDistance between them is', min_dist, 'units.')
return "\nDistance between the closest points is verified."
else:
return False
def main():
array_length, array = generate_2D_points()
distances = [[0 for i in range(array_length)] for j in range(array_length)]
distances = find_distance_2D(array, distances)
print(verify_min_dist(array_length, array, distances))
if __name__ == '__main__':
main() | true |
426fe22bd646f3f123b6c6a1d11e9a38f75f7b11 | lportinari/Desafios-Python-Curso-em-Video | /desafio09.py | 710 | 4.21875 | 4 | """
Exercício Python 009: Faça um programa que leia um número Inteiro qualquer e mostre na tela a sua tabuada.
"""
n = int(input('Digite um número para saber a sua tabuada: '))
a = n * 1
b = n * 2
c = n * 3
d = n * 4
e = n * 5
f = n * 6
g = n * 7
h = n * 8
i = n * 9
j = n * 10
print('{} x {} = {}'.format(n, 1, n*1))
print('{} x {} = {}'.format(n, 2, n*2))
print('{} x {} = {}'.format(n, 3, n*3))
print('{} x {} = {}'.format(n, 4, n*4))
print('{} x {} = {}'.format(n, 5, n*5))
print('{} x {} = {}'.format(n, 6, n*6))
print('{} x {} = {}'.format(n, 7, n*7))
print('{} x {} = {}'.format(n, 8, n*8))
print('{} x {} = {}'.format(n, 9, n*9))
print('{} x {} = {}'.format(n, 10, n*10))
| false |
b310130d1ae13dbbb91fc795f8bac57d15ae1150 | lportinari/Desafios-Python-Curso-em-Video | /desafio31.py | 412 | 4.125 | 4 | """
Exercício Python 031: Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem,
cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 parta viagens mais longas.
"""
print('BEM VINDO A CALCULADORA DO VIAJANTE')
d = float(input('Qual a distância da viagem? '))
v = d * 0.5 if d <= 200 else d * 0.45
print('A viagem custará R${:.2f}'.format(v))
| false |
cc9f0507474f9ea12e2801c24e1a74aa426386d1 | lportinari/Desafios-Python-Curso-em-Video | /desafio36.py | 931 | 4.25 | 4 | """
Escreva um programa para aprovar um empréstimo bancário para a compra de uma casa. O programa vai perguntar o valor
da casa, o salário do comprador e em quantos anos ele vai pagar.
Calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salário, ou então o empréstimo será negado.
"""
print('-=-' * 12)
print('CÁLCULE A MENSALIDADE DA SUA CASA')
print('-=-' * 12)
casa = float(input('Qual o valor da casa? R$'))
salario = float(input('Qual o seu salário? R$'))
tempo = int(input('A casa será parcelada em quantos anos? '))
prestação = casa / (tempo * 12)
if salario * 30 / 100 >= prestação:
print('Parabéns, o seu empréstimo foi APROVADO. A parcela será de R${:.2f}.'.format(prestação))
elif salario * 30 / 100 < prestação:
print ('Empréstimo NEGADO, a prestação da casa ficaria R${:.2f}, ultrapassando os 30% de seu salário.'.format(prestação))
| false |
1021a67048997d5e9ffca2387f0119119f0f65cd | lportinari/Desafios-Python-Curso-em-Video | /desafio71.py | 943 | 4.15625 | 4 | """
Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao usuário qual será
o valor a se sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues.
Obs. Considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1.
"""
print('=' * 25)
print('{:^25}'.format('BANCO CELINSKI'))
print('=' * 25)
saque = int(input('Que valor você quer sacar? R$'))
total = saque
cedulas = 50
cont = 0
while True:
if total >= cedulas:
total -= cedulas
cont += 1
else:
if cont > 0:
print('Total de {} cédulas de R${}.'.format(cont, cedulas))
if cedulas == 50:
cedulas = 20
elif cedulas == 20:
cedulas = 10
elif cedulas == 10:
cedulas = 1
cont = 0
if total == 0:
break
print('-'*20)
print('Volte sempre!')
| false |
4c061ac9d35b1a59f5b37e5dd6f6c6dd8a1a5121 | VasTsak/data-structures-algs | /Python/2. Basic Algorithms/2.rotated_array.py | 2,218 | 4.125 | 4 | """
Search in a Rotated Sorted Array
You are given a sorted array which is rotated at some random pivot point.
Example: [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]
You are given a target value to search. If found in the array return its index, otherwise return -1.
You can assume there are no duplicates in the array and your algorithm's runtime complexity must be in the order of O(log n).
Example:
Input: nums = [4,5,6,7,0,1,2], target = 0, Output: 4
"""
def rotated_array_search(input_list, number, start_index, end_index):
if len(input_list) == 0:
return -1
if start_index > end_index:
return -1
mid_index = (start_index + end_index) // 2
if input_list[mid_index] == number:
return mid_index
# in case the part of list we keep is sorted:
if input_list[start_index] <= input_list[mid_index]:
# it is easy for us because we do just a binary search
if number >= input_list[start_index] and number <= input_list[mid_index]:
return rotated_array_search(input_list, number, start_index, mid_index - 1)
return rotated_array_search(input_list, number, mid_index + 1, end_index)
# in case the part of list we keep is not sorted, it means that the other part is sorted
if number >= input_list[mid_index] and number <= input_list[end_index]:
start_index = mid_index + 1
return rotated_array_search(input_list, number, mid_index + 1, end_index)
return rotated_array_search(input_list, number, start_index, mid_index - 1)
def linear_search(input_list, number):
for index, element in enumerate(input_list):
if element == number:
return index
return -1
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
if linear_search(input_list, number) == rotated_array_search(input_list, number, 0, len(input_list) -1):
print("Pass")
else:
print("Fail")
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6])
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 8])
test_function([[6, 7, 8, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 10])
test_function([[], None])
test_function([[], 1])
| true |
1204906723c023f4da4343ec3bb7d84e6e23bd3e | artur-guniewicz/Python_class | /Zestaw3/Zad_3.6.py | 380 | 4.125 | 4 | height = int(input('Enter height: '))
length = int(input('Enter length: '))
output = '\n'
for i in range(height * 2 + 1):
if i % 2 == 0:
output += '+'
for j in range(length):
output += '---+'
output += '\n'
else:
output += "|"
for j in range(length):
output += ' |'
output += '\n'
print(output)
| false |
b4299ed8a1bd47246cf53aef799a28c3e123f4ca | IvanaOlvera/Mision_05 | /OperacionesAritmeticas.py | 632 | 4.21875 | 4 | #Autor: Ivana Olvera Mérida
#Escribe una función que calcula e imprime las siguientes operaciones
#usando un ciclo para cada una. Los datos deben generarse como valores numéricos.
def calcularPiramide():
n = 0
a = 0
b = 0
c = 0
for i in range(1,10): #Se va a repetir nueve veces
n = n + 1
a = a * 10 + n #Números del extremo izquierdo
b = a* 8 + n #Es la operación completa para obtener el resultado
print (a,"*8 +",n,"=",b)
for k in range(1,10):
c = c * 10 + 1
d = c * c
print(c,"*, c,"=",d)
def main():
calcularPiramide()
main()
| false |
f36a8459228a2e646067ddc534c54c864c6355ba | saipujithachandhragiri/udemy_python_practice | /77.py | 428 | 4.4375 | 4 | # Create a script that asks the user to enter their age, and the script calculates the user's year of birth and prints it out in a string like in the expected output. Please make sure you generate the current year dynamically.
# Expected output:
# We think you were born back in 1988
from datetime import datetime
age = int(input('Enter your age: '))
dob = datetime.now().year - age
print('Your date of birth is',dob) | true |
9c056aa88f771521b5570201b9e63d7c2b40bc2d | apatten001/funct_class_methods | /running_weather.py | 1,295 | 4.15625 | 4 |
temp = int(input("What is the current temperature in F°?: "))
condition = input("Is it rainy, windy, or clear outside?: ")
class BestTime:
def __init__(self,name, age):
self.name = name
self.age = age
def running_weather(self):
if temp > 48 and temp < 52:
print("This is a perfect temperature to set a record!")
elif temp > 35 and temp < 48:
print("This is good running weather to perform an optimal run")
elif temp > 49 and temp < 75:
print("This temp may have you perspire more than usual.")
else:
print("Run at your own risk!")
def conditions(self):
if condition == "rainy":
print(f"{self.name},when its raining your clothes may weigh you down\
causing you to slow down your pace.")
elif condition == "windy":
print(f"Depending on the way the wind blows {self.name}, it will increase or decrease your "
"speed on average by 10%.")
elif condition == "clear":
print(f"{self.name}, you should have a good run ahead of you!")
else:
print("Depending on the conditions you may want to wait to run")
Arnold = BestTime("Arnold", 31)
Arnold.running_weather()
Arnold.conditions() | true |
44cb590e08c09e87cf8989ac6973300fabe6e921 | SDSS-Computing-Studies/003b-more-input-ssm-0123 | /task1.py | 818 | 4.3125 | 4 | #!python3
"""
##### Task 1
The bank calculates the amount of interest you earn using the simple interest formula:
interest = principal * rate * #days in the month / 365
Ask the user to enter the amount of their principal, the number of days in the month the rate of interest expressed as a percentage. Calculate the amount of interest they would be paid.
example:
Enter your amount: 100
Enter the rate: 2.5
Enter the # of days in the month: 30
You earned $0.20 interest.
(2 points)
"""
import math
amount = input("Enter your amount")
rate = input("Enter your rate")
days = input("Enter # of days in the month")
amount = float(amount)
rate = float(rate)
days = int(days)
interst = amount * (rate/100) * days / 365
interst = round(interst, 1)
interst = str(interst)
print("You earned $"+interst,"interest.")
| true |
ef52c94d47a168f2be390ffe790faaeb01771924 | Ether0xF/Euler | /Euler001.py | 370 | 4.4375 | 4 | """
If we list all the natural numbers below 10 that are
multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def multiples(num):
result = 0
for i in range(0, num):
if i % 3 == 0 or i % 5 == 0:
result += i
return result
print(multiples(1000))
| true |
2d15afb6f6f109cbaa2948a6042f69578caa95ac | ahhampto/si506_labs | /lab_05.py | 2,938 | 4.5 | 4 | # In this lab, we use txt files. Be very careful that a line in txt files
# should contain a new line "\n" character at the end of this line.
# PROBLEM 1
# Define a function named "concatenate_name_type".
# The function accepts two arguments - one is "file_name", the other is "file_type". Both two arguments are strings.
# For given arguments, the function should return "<file_name>.<file_type>"
# Pass two defined variables "file_name", "file_type" to the function, assign the result to "full_file_name"
# Print "full_file_name".
f_name = "file1"
f_type = "txt"
full_file_name = None
def concatenate_name_type(file_name, file_type):
return f"{file_name}.{file_type}"
full_file_name = concatenate_name_type(f_name, f_type)
print(full_file_name)
# PROBLEM 2
# 2a) Define a function named "write_into_file"
# The function accepts two arguments - one is "filename", the other is "file_content"
# "filename" is a string and "file_content" is a list of strings
#
# 2b) Open the file with "full_file_name"
# 1) read all lines,
# 2) store the last two lines into the variable "last_two_lines"
# Make sure that there is a new line character "\n" at the end of each line in "last_two_lines"
# Write "last_two_lines" into a new file called "file2.txt" using the function "write_into_file"
# Print "last_two_lines"
def write_into_file(filename, file_content):
# write the variable <file_content> into the file <filename>
file_handle = open(filename, 'w') #opened filename to write
for line in file_content:
file_handle.write(line) #writing variable into file
#write/writelines similar to read/readlines...doing actions to single/multiple
file_handle.close()
#this doesn't need a return
#write_into_file("file5.txt", ["test\n", "lines\n"]) #testing
last_two_lines = []
file_handle_in = open("file1.txt", "r")
all_lines = file_handle_in.readlines()
last_two_lines = all_lines[-2:]
write_into_file("file2.txt", last_two_lines)
file_handle_in.close()
print(last_two_lines)
# PROBLEM 3
# Finally, put all you've learned together.
# 1) Open each file with file_name in "file_name_list" and "file_type",
# 1) read all lines and
# 2) store those unique lines into the variable "unique_lines".
# NOTE: Make sure that there is a new line character "\n" at the end of each line in "unique_lines".
# 2) Write "unique_lines" into a new file called "summary.txt" using the function "write_into_file".
# 3) Print "unique_lines".
file_name_list = ["file1", "file2", "file3"]
file_type = "txt"
unique_lines = []
for file_name in file_name_list:
full_file_name = concatenate_name_type(file_name, file_type)
file_handle = open(full_file_name, 'r')
all_lines = file_handle.readlines()
for line in all_lines:
if line not in unique_lines:
unique_lines.append(line)
file_handle.close()
write_into_file("summary.txt", unique_lines)
print(unique_lines)
| true |
49bb3e38b53b6fcd4764fba2cce056dae73e788a | L-seaung/python-in-action | /Add_Two_Numbers/main.py | 202 | 4.28125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
num1 = 1.3
num2 = 6.3
# add tow numbers
sum = float(num1) + float(num2)
# display the sum
print("The sum of {0} and {1} is {2}".format(num1, num2, sum))
| true |
e61df564459f807d6ad0f035c3a1525fd4fb5582 | sjain1297/Solutions | /PalindromeCheck.py | 201 | 4.25 | 4 | input_str = input("Please enter a string: ").lower()
if input_str == input_str[::-1]:
print("{} is a palindrome".format(input_str))
else:
print("{} is NOT a palindrome".format(input_str))
| false |
30d695171cb2f7844036193740eedc2bc1c188a5 | incasee/learn-A-Byte-Of-Python | /function_param.py | 210 | 4.125 | 4 | def print_max(a, b):
if a > b:
print(a,'is maximun')
elif a == b:
print(a,'is equal to', b)
else:
print(b,'is maxmum')
print_max(3, 4)
x = 6
y = 9
print_max(x, y)
| false |
23aecd0437525b6a2232d27048dba12100f50c0b | jasoncortella/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 1,937 | 4.34375 | 4 | #!/usr/bin/python3
class Square:
"""A class to define a square."""
def __init__(self, size=0, position=(0, 0)):
"""Initialize the class."""
self.size = size
self.position = position
@property
def size(self):
"""Gets size."""
return self.__size
@property
def position(self):
"""Gets position."""
return self.__position
def area(self):
"""Returns the area of the square."""
return (self.__size ** 2)
def my_print(self):
"""Prints the square, accounting for size and position"""
if self.__size == 0:
print()
return
print('\n' * self.__position[1], end='')
for i in range(self.__size):
print(' ' * self.__position[0] + '#' * self.__size)
def __valid_size(self, size):
"""Checks if a variable is a positive integer."""
if isinstance(size, int):
if size >= 0:
return True
else:
raise ValueError("size must be >= 0")
else:
raise TypeError("size must be an integer")
return False
def __valid_position(self, position):
"""Checks if a variable is a tuple of 2 positive integers."""
if isinstance(position, tuple):
if len(position) == 2:
if isinstance(position[0], int):
if isinstance(position[1], int):
if position[0] >= 0 <= position[1]:
return True
raise TypeError("position must be a tuple of 2 positive integers")
return False
@size.setter
def size(self, value):
"""Sets size."""
if self.__valid_size(value):
self.__size = value
@position.setter
def position(self, value):
"""Sets position."""
if self.__valid_position(value):
self.__position = value
| true |
633530b015cf0668a8509253f1a41765a5ba394e | jasoncortella/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 554 | 4.375 | 4 | #!/usr/bin/python3
def add_integer(a, b=98):
"""
add_integer - Adds and returns two integers
*** Floats are cast to ints before addition ***
Args:
a: The first parameter.
b: The second parameter.
Returns:
The sum of a and b
Raises:
- TypeError if a or b are not and int or float
"""
if not isinstance(a, (int, float)):
raise TypeError("a must be an integer")
if not isinstance(b, (int, float)):
raise TypeError("b must be an integer")
return int(a) + int(b)
| true |
0d73676e413024b5f3f17fb0dbd50fcf4a3a8482 | jasoncortella/holbertonschool-higher_level_programming | /0x0B-python-input_output/8-load_from_json_file.py | 344 | 4.125 | 4 | #!/usr/bin/python3
"""Function to create an object from a JSON file"""
import json
def load_from_json_file(filename):
"""creates object from JSON file)
Args:
filename (str): String containing filename
Returns:
Created object
"""
with open(filename, encoding="utf-8") as myFile:
return json.load(myFile)
| true |
264ebdf1b2bf86020549bd76c8b217dcea453bc0 | yash-markad/Python-Competitive-Programming | /Trie_using_Dictionary.py | 1,271 | 4.34375 | 4 | #Trie Data structure
# '$' denotes the end of the word
class Trie:
'''Creates a Trie Data Stucture.'''
def __init__(self):
self.Trie = {}
def insert(self, key):
'''Inserts a word/key into the Trie.'''
t = self.Trie
for i in key:
if i not in t:
t[i] = {}
t = t[i]
#Marking the end of the word
t['$'] = '$'
def search(self, key):
'''Returns True is given word is present in the Trie, else returns False.'''
t = self.Trie
for i in key:
if i not in t:
return False
t = t[i]
if '$' in t:
return True
return False
def startsWith(self, key):
'''Returns True if given word is present as a prefix in the Trie, else returns False.'''
t = self.Trie
for i in key:
if i not in t:
return False
t = t[i]
return True
#Driver Code
keys = ['the', 'their', 'there', 'they', 'these', 'thesis', 'apple', 'appy', 'cat', 'catfish', 'cattle', 'cats']
#Creating a Trie Object
t = Trie()
#Inserting Keys into the Trie
for key in keys:
t.insert(key)
| true |
ce566ecd1b12b6146408281562c0657ebe4701fa | amirothman/scikit-learn-course | /SckitLearn-tertiary-courses/exercises/module3_3_regression.py | 1,127 | 4.28125 | 4 | # Code guide for Python Scikit Learning Essential Training
# Copyright: Tertiary Infotech Pte Ltd
# Author: Dr Alfred Ang
# Date: 25 Dec 2016
# Module 3.3: Regression
# Create a simple dataset
# import numpy as np
# X = np.linspace(1,20,100).reshape(-1,1)
# y = X + np.random.normal(0,1,100).reshape(-1,1)
#import matplotlib.pyplot as plt
# plt.scatter(X,y)
# plt.show()
# from sklearn import linear_model
# lm = linear_model.LinearRegression()
# lm.fit(X, y)
# plt.scatter(X,y)
# plt.plot(X,lm.predict(X),'-r')
# plt.show()
# Challenge: Boston dataset
# boston = datasets.load_boston()
# X,y = boston.data, boston.target
# print(boston.data.shape)
# print(boston.feature_names)
# print(boston.target.shape)
# Boston Housing Price Challnege
# from sklearn import datasets
# boston = datasets.load_boston()
# X,y = boston.data,boston.target
# from sklearn.preprocessing import scale
# X = scale(X)
# from sklearn import linear_model
# lm = linear_model.LinearRegression()
# lm.fit(X,y)
# import matplotlib.pyplot as plt
# plt.scatter(y,lm.predict(X))
# plt.xlabel('Price')
# plt.ylabel('Predict Price')
# plt.show()
| false |
fc68b33ee8d02da44353ec34e740f27e82592215 | prhuft/python-examples | /animation_canvasdraw.py | 1,104 | 4.28125 | 4 | """ Simple animation example with numpy. uses fig.canvas.draw() instead of
matplotlib.animation
"""
## LIBRARIES
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import math as m
from random import random as rand
xpts = np.array(np.linspace(0,10,100))
ypts = np.sin(xpts)+2
# initialize the figure
fig = plt.figure()
# build an axes object that will show the plot in our figure
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
ax.set_xlim(0,10)
ax.set_axis_off()
ax.set_aspect(aspect='equal')
ax.set_facecolor('black')
# add the axes object to the figure, and change the forecolor
fig.add_axes(ax)
fig.patch.set_facecolor('black')
# the initial plot line. note the comma after the variable name
line, = ax.plot(xpts,ypts,color='red',lw=3)
# Set "interactive mode" on (required for animation to work), and show the plot
plt.ion()
plt.show()
# Run 100 frames of the animation
iters = 100
for i in range(0,iters):
# update the y-position
ypts = np.sin(xpts+i)+5
line.set_data(xpts,ypts)
# update the plot
fig.canvas.draw()
fig.canvas.flush_events()
| true |
66a9e4ba27de4b239654e6b5aaf91c50476e398a | 2unde001/zignature_look | /python_tutoria/mit_edx/guess_a_secret_number.py | 867 | 4.1875 | 4 | print("Please think of a number between 0 and 100!")
low = 0
high = 100
secret_guess = 68
guessing = False
while not guessing :
user_input = (low + high)//2
print("is your secret number? " + str(round(user_input)))
you_guess = input("Enter 'h' to indicate the guess is too high."+"h"
" Enter 'l' to indicate the guess is too low."
"Enter 'c' to indicate I guess correctly")
if you_guess == "h":
high = user_input
print("guess correctly. " + you_guess)
elif you_guess == "l":
low = user_input
print("guess correctly. " + you_guess)
elif (you_guess == "c") and round(user_input) == secret_guess:
print("guess correctly. " + you_guess)
guessing = True
else:
print("Sorry, I did not understand your input")
print("Game over. Your secret number was:", round(user_input))
| true |
7375539ce5c522bc17c82b48e0061724e3a511d0 | 2unde001/zignature_look | /python_tutoria/rock_paper_scissors.py | 1,085 | 4.125 | 4 | """
Rock paper scissors
"""
import random
import simplegui
# Global variables that all functions know about.
# DO NOT EDIT THESE GLOBAL VARIABLES
# OR YOUR GAME WILL BREAK.
COMPUTER_SCORE = 0
HUMAN_SCORE = 0
human_choice = ""
computer_choice = ""
def choice_to_number(choice):
"""Convert choice to number."""
return {"rock": 0, "paper": 1, "scissors": 2}[choice]
def number_to_choice(number):
"""Convert number to choice."""
return {0: 'rock', 1: 'paper', 2: 'scissors'}[number]
def random_computer_choice():
"""Choose randomly for computer."""
return random.choice(['rock', 'paper', 'scissors'])
def choice_result(human_choice, computer_choice):
"""Return the result of who wins."""
global COMPUTER_SCORE
global HUMAN_SCORE
human_number = choice_to_number(human_choice)
computer_number = choice_to_number(computer_choice)
if (human_number - computer_number) % 3 == 1:
COMPUTER_SCORE = COMPUTER_SCORE +1
elif human_number == computer_number:
print("Tie")
else:
HUMAN_SCORE = HUMAN_SCORE + 1
| false |
596ed49e5a7b4570db010449365330748b972919 | Sarang-1407/CP-LAB-SEM01 | /CP Lab/Lab3/Sample 4.py | 1,302 | 4.34375 | 4 | # Lab Project by Sarang Dev Saha
# LAB_03 QUE_04
#Write a program to input electricity unit charge and calculate the total electricity bill according to the given conditions...An additional surcharge of 20% is added to the bill
#Taking the input from the user
e_unit=float(input("Enter the Electricity Unit Charge consumed:"))
#If the input is less than equal to 0 the bill is also ₹0
if e_unit<=0:
print("The total electricity bill including 20% surcharge is ₹0")
#If the input is between 0 and 50
if e_unit>0 and e_unit<=50:
amount=e_unit*0.50
amount_tax=1.2*amount
print("The total electricity bill including 20% surcharge is ₹",amount_tax)
#If the input is between 50 and 150
if e_unit>50 and e_unit<=150:
amount=(50*0.50)+(e_unit-50)*0.75
amount_tax=1.2*amount
print("The total electricity bill including 20% surcharge is ₹",amount_tax)
#If the input is between 150 and 250
if e_unit>150 and e_unit<=250:
amount=(50*0.50)+(100*0.75)+(e_unit-150)*1.20
amount_tax=1.2*amount
print("The total electricity bill including 20% surcharge is ₹",amount_tax)
#If the input is greater than 250 (else command can also be used, but triggers some glitch)
else:
amount=e_unit*1.50
amount_tax=1.2*amount
print("The total electricity bill including 20% surcharge is ₹",amount_tax) | true |
a38de3f50eaa4703f04fceb1692186f67f7dbba7 | Sarang-1407/CP-LAB-SEM01 | /CP Lab/Lab2/7_1.py | 712 | 4.125 | 4 | # Lab Project by Sarang Dev Saha
# LAB_02 QUE_07
#Take a string of 10 characters from the user and another string with 5 characters.Then print a string such that it conrains the first 5 characters from the first string and latter 5 characters from the second string.
#taking word from user
str1=input("Enter the 10 alphabet word here: ")
#error if limit exceeds or input is insufficient
if len(str1)>10:
print("Error: The word should have exactly 10 alphabets")
elif len(str1)<10:
print("Error: The word should have exactly 10 alphabets")
#printing the final strings
else:
part2=input("Enter the next 5 alphabets for the next word: ")
str2=str1[0:5]+part2
print(str1)
print(str2) | true |
14dfa83814afa945920926e5cd1331ca6f0e4d3a | Sarang-1407/CP-LAB-SEM01 | /CP Lab/Lab1/6.py | 697 | 4.1875 | 4 | # Lab Project by Sarang Dev Saha
# LAB_01 QUE_06
# The perimeter of a circle, square and an equilateral triangle is the same and taken from the user, calculate their respective areas.
#Taking input from the user
perimeter=float(input("Enter the Perimeter in meters:"))
#Formulating area of a Circle
area_circle=(perimeter**2)/(4*22/7)
#Formulating area of a Square
area_square=(perimeter**2)/16
#Formulating area of an equilateral triangle
area_triangle=(perimeter**2)/(432**0.5)
print("Area of the required Circle=",area_circle,"sq. meters")
print("Area of the required Square=",area_square,"sq. meters")
print("Area of the required Equilateral Triangle=",area_triangle,"sq. meters")
| true |
15adbeb454b70e36ac7a3750c5dce7c502c32134 | Sarang-1407/CP-LAB-SEM01 | /CP Lab/Lab1/7.py | 699 | 4.5 | 4 | # Lab Project by Sarang Dev Saha
# LAB_01 QUE_07
#A 30 kg boulder was initially moving at a velocity of 10 m/s, in order to stop it 10N of resistive force is applied on it. After how much time will the boulder come to rest
#Letting the user enter the above data
mass=float(input("Enter the mass of the object in kg:"))
initial_velocity=float(input("Enter the initial velocity of the object in m/s:"))
force=float(input("Enter the retarding force on the object in N:"))
#Formulating acceleration of the boulder
acceleration=(force/mass)
#Formulating time after which the boulder comes to rest.
time=(initial_velocity)/acceleration
print("The object requires",time,"seconds to come to rest")
| true |
948a4ba3a72395f07c70325260cb976151718cc5 | koriisabellaa/Python | /sorting/pop_sort.py | 1,579 | 4.125 | 4 | """
Pop Sort
Pop Sort merupakan metode pengurutan dengan menggunakan pendekatan Tower of Homa
yaitu mengambil nilai dari paling luar sebuah array kemudian disusun kembali
dalam array baru.
"""
def pop_sort(arr):
# Inisialisasi data
arrA = arr
arrB = []
arrC = []
print("Data sebelum disort:", arrA, end="\n\n")
# Kita loop hingga data di $a kosong
while len(arrA) > 0:
# Keluarkan nilai paling atas dari array $a
top = arrA.pop()
print("Data yang diambil:", top)
print("Array A:", arrA)
# Apabila array B ada isinya dan isi paling atas dari array B
# lebih kecil dari array A, kita pindahkan semua nilai-nilai yang
# cocok dengan kondisi tersebut ke array C
# Pada bagian statement kedua, anda dapat mengganti "<" menjadi ">"
# sesuai keinginan anda.
# Catatan:
# Kita harus menghitung isi array terlebih dahulu sebelum mengambil
# data array lebih utama agar menghindari error "Undefined index"
while len(arrB) > 0 and top > arrB[len(arrB) - 1]:
arrC.append(arrB.pop())
# Setelah aman, kita masukkan data dari $a ke $b
arrB.append(top)
print("Array B:", arrB)
print("Array C:", arrC)
# Apabila isi $c ada, kita balikkan lagi ke $b secara berurutan.
while len(arrC) > 0:
arrB.append(arrC.pop())
print("Hasil sementara:", arrB, end="\n\n")
print("Data setelah disort:", arrB)
if __name__ == "__main__":
pop_sort([83, 10, 54, 92, 62, 47, 15, 72])
| false |
0698eb2e97835025c80cf9147e070131fcea74ed | mcoutt/itstep_8_2 | /Bondarenko Leonid/Project_3/Conf/Digital watch.py | 683 | 4.15625 | 4 | # Дано число n. С начала суток прошло n минут. Определите, сколько часов и минут будут показывать
# электронные часы в этот момент. Программа должна вывести два числа: количество часов (от 0 до 23)
# и количество минут (от 0 до 59). Учтите, что число n может быть больше, чем количество минут в сутках.
print('Введите входные данные: ')
x = int(input())
часы = x % (60*24)//60
минуты = x % 60
print(часы)
print(минуты) | false |
8c295aa3c9eab981321ccc2fd459bfd6a54f0a4b | Soe-Htet-Naung/CP1404PPrac | /Prac01/shop_calculator.py | 848 | 4.1875 | 4 | def main():
numbers_of_items = int(input("Please Enter the numbers of items : "))
calculateTotal(numbers_of_items)
while numbers_of_items < 0:
print("Invalid number of items!")
numbers_of_items = int(input("Please Enter the numbers of items : "))
calculateTotal(numbers_of_items)
def calculateTotal(numbers_of_items):
numbers_of_items = numbers_of_items
totalPrice = 0
for i in range(numbers_of_items):
print("Item number", i + 1)
price = float(input("Please Enter the price of item : "))
totalPrice = totalPrice + price
if totalPrice > 100:
discount = (totalPrice / 100) * 10
totalPrice = totalPrice - discount
else:
totalPrice = totalPrice
print("Total Price is : {:.2f} $".format(totalPrice))
if __name__ == '__main__':
main()
| true |
0b10dad6584c4305c47b21a7d49b1897baf28094 | ochsec/HackerRank | /Algorithms/Python/sherlock_and_the_beast.py | 2,765 | 4.125 | 4 | #!/bin/python3
#Sherlock Holmes suspects his archenemy, Professor Moriarty, is once again plotting something diabolical.
#Sherlock's companion, Dr. Watson, suggests Moriarty may be responsible for MI6's recent issues with their supercomputer,
#The Beast.
#Shortly after resolving to investigate, Sherlock receives a note from Moriarty boasting about infecting The Beast with
#a virus; however, he also gives him a cluea number, N. Sherlock determines the key to removing the virus is to
#find the largest Decent Number having N digits.
#A Decent Number has the following properties:
# 1. Its digits can only be 3's and/or 5's.
# 2. The number of 3's it contains is divisible by 5.
# 3. The number of 5's it contains is divisible by 3.
# 4. If there are more than one such number, we pick the largest one.
#Moriarty's virus shows a clock counting down to The Beast's destruction, and time is running out fast. Your task is to
#help Sherlock find the key before The Beast is destroyed!
#Constraints
# 1 <= T <= 20
# 1 <= N <= 100000
#Input Format
#The first line is an integer, T, denoting the number of test cases.
#The T subsequent lines each contain an integer, N, detailing the number of digits in the number.
#Output Format
#Print the largest Decent Number having digits; if no such number exists, tell Sherlock by printing -1.
#Sample Input
# 4
# 1
# 3
# 5
# 11
#Sample Output
# -1
# 555
# 33333
# 55555533333
#Explanation
#For N=1, there is no decent number having 1 digit (so we print -1).
#For N=3, 555 is the only possible number. The number 5 appears three times in this number, so our count of 5's
#is evenly divisible by 3 (Decent Number Property 3).
#For N=5, 33333 is the only possible number. The number 3 appears five times in this number, so our count of 3's
#is evenly divisible by 5 (Decent Number Property 2).
#For N=11, 55555533333 and all permutations of these digits are valid numbers; among them, the given number
#is the largest one.
import sys
def decent(n):
fives = 0
threes = 0
while n > 5 and n > 3:
if ((n-3)%3 == 0 or (n-3)%5 == 0):
n = n - 3
threes += 1
else:
n = n - 5
fives += 1
else:
if n == 3:
threes += 1
print_result(threes, fives)
elif n == 5:
fives += 1
print_result(threes, fives)
else:
print('-1')
def print_result(threes, fives):
result = ''
while threes > 0:
result = result + '555'
threes = threes - 1
while fives > 0:
result = result + '33333'
fives = fives - 1
print(result)
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
decent(n)
| true |
1012c68c314103bfd3ce255cdbe3074bbb438e6e | jiarmy1125/Kata | /You're_a_square!.py | 747 | 4.28125 | 4 | # is_square(-1), False, "-1: Negative numbers cannot be square numbers"
# is_square( 0), True, "0 is a square number"
# is_square( 3), False, "3 is not a square number"
# is_square( 4), True, "4 is a square number"
# is_square(25), True, "25 is a square number"
# is_square(26), False, "26 is not a square number"
def is_square(n):
if n<0:
return False
else:
a=round(n**0.5,2)
b=(a)**2
# print(a)
# print(b)
if b == n:
# print(b)
bool=True
else :
# print(b)
bool=False
return bool
# is_square( 0)
print(is_square( 1454521440))
print(is_square( -1))
# print(is_square( 25))
# print(is_square(26))
#比較餘數
# print(3.33333 % 1)
# print(3 % 1) | false |
801e3d10644515bd7239df4169077bd895c41cb8 | jiarmy1125/Kata | /Sort_odd_and_even_numbers_in_different_order.py | 856 | 4.1875 | 4 | # Your task is to sort odd numbers within the array in ascending order, and even numbers in descending order.
# Note that zero is an even number. If you have an empty array, you need to return it.
# sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 8, 4, 5, 2]
def sort_array(a):
odd = []
even = []
new = []
for i in a: #分奇數偶數
if i%2==0:
odd.append(i)
else:
even.append(i)
odd_reverse = sorted(odd,reverse=True) #將偶數降冪排列
even_sort = sorted(even) #將奇數升冪排列
j=0
k=0
for i in a: #將數字重新放回原陣列中
if i%2==0:
new.append(odd_reverse[j])
j += 1
else:
new.append(even_sort[k])
k += 1
return new
result = sort_array([5, 3, 2, 8, 1, 4])
print(result)
| true |
40e20d4d45e8f762938f4af3bef10af57b0f74e7 | Dreamingnoisy/PythonLearning_Notes | /ch16/Time.py | 1,541 | 4.5 | 4 | class Time:
"""Represents the time of a day.
attributes: hour, minute, second"""
def print_time(t):
'''takes a Time object and prints the time'''
print("%.2d:%.2d:%.2d"%(t.hour, t.minute, t.second))
def time2int(t):
seconds = (t.hour*60 + t.minute) *60 + t.second
return seconds
def int2time(seconds):
t =Time()
t.hour,t.minute,t.second= seconds // 3600, (seconds % 3600) // 60 ,(seconds % 3600) % 60
return t
def is_after(t1,t2):
'''takes two Time objects and
return True if t1 follows t2 chronologically
'''
time1 = time2int(t1)
time2 = time2int(t2)
return time1 > time2
def increment(t,seconds):
'''takes a Time object and a number of seconds,
add the given number to the object.
'''
#modifier
t_seconds = time2int(t)
seconds = t_seconds + seconds
t.hour,t.minute,t.second= seconds // 3600, (seconds % 3600) // 60 ,(seconds % 3600) % 60
def p_increment(t,seconds):
'''takes a Time object and a number of seconds,
add the given number to the object and returns
a new Time object without modifying the input object
'''
#pure function
t_seconds = time2int(t)
seconds = t_seconds + seconds
return int2time(seconds)
def main():
t1 = Time()
t1.hour, t1.minute, t1.second = 11 , 59 , 30
t2 = Time()
t2.hour, t2.minute, t2.second = 2 , 30 , 0
print_time(p_increment(t2,3661))
increment(t2,3661)
print_time(t2)
if __name__ == "__main__":
main()
| true |
302ec1f32b2dd7e419056c300a9b44524f2ca373 | reneejeanbaptiste/BridgeUp | /DataViz/code/0816_CropMapFinal_RJ.py | 408 | 4.15625 | 4 | import csv
def menu():
choice = raw_input(" Learn whether there is a connection between UV radiation and the worlds agriculture. To see the Choropleth Map that shows the UV radiation choose A. To see the Choropleth Map that shows the agricultural production of the world choose B.").upper()
if choice=="A":
elif choice=="B":
else:
print("The variable you have typed is not A or B. Type A or B")
| true |
2f5a28117756d3d2e20c0ef729fba9deca22db88 | reneejeanbaptiste/BridgeUp | /Python/1307_moonFunctions_RJ.py | 545 | 4.15625 | 4 | #This function caluculates weight on the moon
def divide(x,y):
return x/6
a = divide(120,6)
print(a)
#The diameter of the moon is 2159 miles.The distance from the earth and the moon is 238900. This function tells you hwo many moons can fit in the distance between the earth and the moon.
MOON_DIAMETER = 2159
MOON_EARTH_DISTANCE = 238900
def divide2 (x,y):
return x/y
a = divide2 (MOON_EARTH_DISTANCE,MOON_DIAMETER)
print(a)
#calc dist travelled
def divide3 (x,y):
return (x/y)
a = divide3 (1423000,27)
print (a)
| true |
fe8456222c19a69ba064876e03c84c80d542a174 | Arcrammer/21.-DPWP | /Final Exam/Inheritance.py | 1,346 | 4.15625 | 4 | #!/usr/bin/env/python
# --------------------------
#
# Final Exam
# Thursday, 27 August, 2015
# Alexander Rhett Crammer
# Full Sail University
#
# --------------------------
#
''' Inheritance '''
class Tree(object):
def __init__(self):
self._produces_edibles = False # Protected properties will be given to child classes
self._family = None # Family of the trees' species
self._genus = None # Genus of the trees' species
self.__age = 0 # Private properties will not be inherited by subclasses.
self.__lives = True # Trees die sometimes, right? This is also private so it won't be inheritable
def grow(self):
# TODO: Make the tree taller within this method
pass
def die(self):
# TODO: Kill the tree within this method
pass
class Spruce(Tree):
'''
This is a subclass, child class, or inheriting class
of 'Tree'. To declare a class the child of another
class just pass the name of your desired superclass
between the parenthesis after the 'class' keyword.
Now this object has all of the methods and properties
defined in the 'Tree' class.
'''
def __init__(self):
self._family = "Pinaceae" # All Spruce trees are of the 'Pinaceae' family, so we can override that property from the superclass
self._genus = "Picea"
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.