blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
a356dcc894a0b5607f6f7ef547c14ef35549bb18 | rkemery/learn-python-course | /guessing-game.py | 877 | 4.375 | 4 | # if statements
# while loops
# variables
# specify secret word
# user can interact with program
# try to guess secret word
# user can keep guessing until secret word is correct
secret_word = "giraffe"
# set guess to empty string values
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
# prompt user to input secret word
# if they don't guess it correctly
# prompt to enter again
# while loop
# as long as guess does not equal secret word
# and they are not out of guesses
# keep looping through
while guess != secret_word and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("Enter guess: ")
guess_count += 1
else:
out_of_guesses = True
# if out of guesses then user ran out of guesses
# otherwise, they are not and they guessed correctly
if out_of_guesses:
print("You lose.")
else:
print("You win!") | true |
dafce4472aaf773b7390f76b9158a857a8a63d59 | tinatsaitp/2020-Spring | /CS Q31.py | 815 | 4.5 | 4 | #Name: Yun-Ting Tsai
#Email: Yun-Ting.Tsai01@myhunter.cuny.edu
#Date: March 24,2020
#This program is to make a turtle string.
import turtle
tina = turtle.Turtle()
mess = input("What is your comand string? ")
for ch in mess:
if ch == 'F':
tina.forward(50)
elif ch == 'B':
tina.backward(50)
elif ch == 'L':
tina.left(90)
elif ch == 'R':
tina.right(90)
elif ch == 'S':
tina.shape("turtle")
tina.stamp()
elif ch == 'D':
tina.dot()
elif ch == '^':
tina.penup()
elif ch == 'v':
tina.pendown()
elif ch == 'r':
tina.color("red")
elif ch == 'g':
tina.color("green")
elif ch == 'b':
tina.color("blue")
elif ch == 'p':
tina.color("purple")
else:
print("Error: do not know the command:", ch)
| false |
f31d0dee0f6a302db79b5b0a3f2ab502ba668237 | tinatsaitp/2020-Spring | /CS Q37.py | 628 | 4.21875 | 4 | #Name: Yun-Ting Tsai
#Email: Yun-Ting.Tsai01@myhunter.cuny.edu
#Date: April 04,2020
#This program is to create a character counter.
code = input("Please enter a codeword: ")
uppercount = 0
lowercount = 0
numcount = 0
specialcount = 0
for wd in code:
if 90 >= ord(wd)>= 65:
uppercount = uppercount + 1
elif 122 >= ord(wd)>= 97:
lowercount = lowercount + 1
elif 57 >= ord(wd)>= 48:
numcount = numcount + 1
else:
specialcount = specialcount + 1
print("Your codeword contains", uppercount, "uppercase letters,", lowercount, "lowercase letters,", numcount, "numbers,", "and", specialcount, "special characters.")
| true |
a98bc89c79aad07cb3b45ca3a960fe8965e729f0 | MarsIfeanyi/TASK-3 | /SumT3.py | 251 | 4.125 | 4 | #Program to sum two integers,and if the sum is between 15 to 20 it will return 20
mars=int(input("Enter first Number:>>>"))
ifeanyi=int(input("Enter second Number:>>>"))
sum= mars+ ifeanyi
if(sum in range(15,21)):
print(20)
else:
print(sum)
| true |
19282ca979f8a434ecac7cf5da2a02eaacf73c9b | uygnoh/free20210601 | /compiler/python3/oop.py | 1,499 | 4.3125 | 4 | #!/usr/bin/python3
############################################################
### python 使用面向对象方法
############################################################
# BankAccount 银行卡
# account_number 银行卡号码
# account_name 银行卡名称
# balance 余额
# input 存钱
# output 取钱
class BankAccount:
# Constructor(构造器)
def __init__(self, account_number, account_name, balance):
self.account_number = account_number
self.account.name = account_name
self.balance = balance
def input(self, amount)
self.balance = self.balance + amount
def output(self, amount)
self.balance = self.balance - amount
# 使用String方法,修改输出样式
def __str__(self)
return "({}, {})".format(self.account_name, self.balance)
# 也可以使用下面字符串拼接方法
# return "(" + str(self.account_name) + ", " + str(self.balance) + ")"
obj1 = BankAccount("12345", "Tom", 100)
obj2 = BankAccount("12345", "Jerry", 100)
obj1.output(20)
obj2.input(10)
print(obj1.balance)
print(obj2.balance)
print(obj1)
############################################################
### Lambda Expression
############################################################
# Lambda表达式,中使用一行写成的代码
fn = lambda x: x*x
print( fn(5) )
fn = lambda x, y: x+y
print( fn(5, 4) )
| false |
0a948c31891b22dfb690d21d008dd78287ad13f6 | RajVerma31/MyCaptain-August | /Task1.py | 306 | 4.28125 | 4 | #area of circle
radius = float(input("Input the radius of the circle"))
area = 3.14 * radius * radius;
print("The area of the circle with radius ",radius," is: ",area)
#extension of file
filename=input("Input the Filename :")
ext = filename.split(".")
print("The extension of the file is :",repr(ext[-1])) | true |
2c40083ba0bbe237d0777f8b061943a9e80f4b5b | almondjelly/hackbright | /calculator-2/calculator.py | 960 | 4.4375 | 4 | """A prefix-notation calculator.
Using the arithmetic.py file from Calculator Part 1, create the
calculator program yourself in this file.
"""
from arithmetic import *
# Your code goes here
def calculate():
calc_input = raw_input("> ")
tokens = calc_input.split(" ")
operator = tokens[0]
if len(tokens) > 1:
num1 = float(tokens[1])
if len(tokens) > 2:
num2 = float(tokens[2])
if operator == "q":
return ""
elif operator == "+":
return add(num1, num2)
elif operator == "-":
return subtract(num1, num2)
elif operator == "*":
return multiply(num1, num2)
elif operator == "/":
return divide(num1, num2)
elif operator == "square":
return square(num1)
elif operator == "cube":
return cube(num1)
elif operator == "pow":
return power(num1, num2)
elif operator == "mod":
return mod(num1, num2)
print calculate()
| true |
dc350f844f88144a2e160058adfd594748b5a486 | huynmela/CS161 | /Project 4/4b/fib.py | 881 | 4.25 | 4 | # Author: Melanie Huynh
# Date: 4/22/2020
# Description: This program takes a positive integer and returns the number at that position of the fibonacci sequence.
def fib(n):
"""Returns the number at the n position of the Fibonacci sequence."""
# Defines the first two integers of the special cases in the Fibonacci sequence
n_1 = 0
n_2 = 1
# These first two if statements take care of the special cases where a for loop is not needed to "build" the Fibonacci sequence for n greater than 1. Otherwise, when n is greater than 1, we utilize the for loop.
if n == 0:
return 0
elif n == 1:
return 1
elif n > 1: # When n is greater than 1, we must incrementally increase the base first two integers, summing the previous integers until reaching the desired position.
for i in range(0, n - 1):
sum_previous = n_1 + n_2
n_1 = n_2
n_2 = sum_previous
return sum_previous
| true |
7529da447598328eb4101a620552daad224304d5 | huynmela/CS161 | /Project 2/2b/temp_convert.py | 264 | 4.1875 | 4 | # Author: Melanie Huynbh
# Date: 4/8/2020
# Description: this program converts Celsius temperatures to Fahrenheit temperatures.
print("Please enter a celsius temperature.")
C = float(input())
F = (9/5) * C + 32
print("The equivalent Fahrenheit temperature is:")
print(F)
| true |
ebaf2c32b9e8d9adda98ff2f74284363dee08541 | louisalbano/Project_Euler | /Problem4.py | 427 | 4.28125 | 4 | # Find the largest palindrome made from the product of two 3-digit numbers
def largestPalindrome(num):
result = 0
for x in range(1, num):
for y in range(x, num):
product = x * y
strProduct = str(product)
if strProduct == strProduct[::-1] and product > result:
result = product
return result
if __name__ == "__main__":
print(largestPalindrome(1000)) | true |
ca484868df1f34457e2a70093ef22aadc3d02bc1 | JustinRChou/Little-Book-of-Algorithms | /Little-Book-of-Algorithms/oddEven.py | 292 | 4.28125 | 4 | def is_odd(number_in):
if int(number_in) %2 == 0:
print("The number is even")
else:
print("The number is odd")
again = True
while again:
number = input("Enter a number : ")
if number.isnumeric() :
odd = is_odd(number)
else:
again = False
| true |
e198099307e67ed80bec13d39aaf0e8c50b340e7 | green-fox-academy/belaszabo | /week-02/day-01/odd_even.py | 218 | 4.40625 | 4 | # Write a program that reads a number form the standard input,
# Than prints "Odd" if the number is odd, or "Even" it it is even.
number = int(input())
o = number % 2
if o == 0:
print('Even')
else:
print('Odd') | true |
cd403295835a78567cc886122fae4150959eaaf7 | green-fox-academy/belaszabo | /week-03/day-03/05_horizontal_lines.py | 444 | 4.375 | 4 | from tkinter import *
root = Tk()
canvas = Canvas(root, width='300', height='300')
canvas.pack()
# create a line drawing function that takes 2 parameters:
# the x and y coordinates of the line's starting point
# and draws a 50 long horizontal line from that point.
# draw 3 lines with that function.
def draw_line(x, y):
line = canvas.create_line(x, y, (x+50), y)
draw_line(40, 5)
draw_line(100, 50)
draw_line(50, 200)
root.mainloop() | true |
9cf0f6b7a6e2e26964538031cf80fd67ad9ecd08 | anatshk/SheCodes | /Exercises/lecture_13/4_arranging_layout_pack.py | 500 | 4.125 | 4 | from tkinter import *
from tkinter import ttk # themed tk
root = Tk()
one = Label(text='One', bg='red', fg='white').pack() # standard packing
two = Label(text='Two', bg='green', fg='black').pack(fill=X) # this label will be resized with the window WIDTH
three = Label(text='Three', bg='black', fg='blue').pack(side=LEFT, fill=Y) # this label will be resized with the window HEIGHT
# change window size to see how 'one' stays the same, 'two' widens and 'three' grows in height
root.mainloop()
| true |
ca9bcb7883f1acac220afb6c6f8f086a883150c5 | anatshk/SheCodes | /Exercises/lecture_12/ex_3.py | 549 | 4.3125 | 4 | """
1. Rewrite the program from the first question of exercise 2 so that it prints the text of
Python’s original exception inside the except clause instead of a custom message.
2. Rewrite the program from the second question of exercise 2 so that the exception which is
caught in the except clause is re-raised after the error message is printed.
# Answer:
1. except ValueError as e:
print(e)
2. except IndexError as e:
print('Your index ({}) exceeds list length ({})'.format(index, len(thelist)))
raise e
"""
| true |
b8796db4d2c302cf6972e9a69d469e0a388fcf99 | alphabetz/python | /loop.py | 739 | 4.125 | 4 | # loop.py
#
#Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a #valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter the numbers #from the book for problem 5.1 and Match the desired output as shown.
largest = None
smallest = None
while True:
try:
num = raw_input('Enter num: ')
if num == 'done':
break
n = int(num)
if largest < num or largest == None:
largest = num
if smallest > num or smallest == None:
smallest = num
except:
print 'invalid input'
print "Maximum is", largest
print "Minimum is", smallest
| true |
60518a8661368bab135c84ecc96d436b036d0fa5 | ywhitecat/4hoursfreecodecampyoutubeEN | /ifwithcomparisonOperators.py | 622 | 4.28125 | 4 | a=float(input("1st number: "))
b=float(input("2nd number: "))
c=float(input("3nd number: "))
#the elif executes if the previous conditions were not true
#a = 33
#b = 33
#if b > a:
# print("b is greater than a")
#elif a == b:
# print("a and b are equal")
#seach for the comparison operator at https://www.w3schools.com/python/python_operators.asp
def max_num(num1,num2,num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
print("The maximum number of the sequence is " + str(max_num(a,b,c))) | true |
0b32a6e042832df46aea09a6118e0734bb2283c3 | nkeeley/CS5010-Programming_and_Systems_for_Data_Analysis | /assignment2_Keeley.py | 879 | 4.40625 | 4 | # File: assignment2_Keeley.py
# CS 5010
# In-Class Assignment 2: Python (Python 3)
# Nicholas Keeley, ngk3pf
'''
This program takes a sentence of words and prints them with their respective
word lengths. It then attempts to sort the tuples by word length unsucessfully.
'''
# Create sentence and separate words.
sentence = "The first language I ever learned was Java because I was told Java is the best language"
words = sentence.split(" ")
# List comprehension returning word and length of word.
words = [(word,len(word)) for word in words]
f = lambda x,y: x+y
print(f(2, 3))
# Print.
print(words)
'''
# Sort tuples by word length.
max = words[1][1]
for word in words:
if max < word[1]:
max = word
max = [word for word in words if max[1] < word[1]]
print(max)
# This addresses the correct word length value in tuple.
print([words[2][1]])
'''
| true |
f461d7eea8f9c05dc7424480b974a3b2156cf17b | sushantsb1998/python_begin | /divi5.py | 229 | 4.40625 | 4 | #check weather the number is divisable by 5 or not
def if_else():
print( "enter a number" )
num = int ( input())
if ( num % 5 == 0 ):
print( " It is divisable by 5" )
else:
print(" It is not divisable by 5")
if_else()
| true |
377c8c3e25e6351e43225d1c5169fd46e4adf5da | TamasSmahajcsikszabo/Python-for-Data-Science | /learning_python/ch39_decorators.py | 1,798 | 4.21875 | 4 | # decorator = a callable that returns another callable
# automactically run code at the end of funcion and class definition statements
# augmenting function calls
# installs wrapper (a.k.a. proxy) objects to be invoked later:
# 1. call proxies: function call interception and managing
# 2. interface proxies: class decorators intercept late class creation
# decorators achieve these by automatically rebind function and class names to
# callables at the end of def and class calls
# these callables perform tasks such as tracing and timing, etc.
# other uses of decorators:
# > function managing, managing function objects; e.g. object registration to
# and API
# > managing classes and not just instance creation calls, such as adding new
# methods to classes
# they can be used to manage function/class creation/calls/instances and
# function/class objects, too
# function decorators
# runs one function through another at the end of a def statement, and rebinds
# the original function name to the results
# it's a runtime declaration
# @ + a reference to a metafunction
from decorator import decorator
def func():
t = "Hello!\n"
print(t)
return True
import pdb; pdb.set_trace()
func = decorator(func) # rebind function name to decorator result
# a decorator is a callable that returns a callablel it returns the object to
# be called later when the decorated function is invoked through its original
# name;
# the decorated function is still available in an enclosing scope; the same
# applies for classes, the original decorated function is still available in
# an instance attribute, for example
class decorator(object):
def __init__(self, func):
self.func = func # retains state
def __call__(self, *args):
# supporting method decoration
| true |
14076448b18571820f24650da7b1ed68900a0933 | jdeath777/python101 | /exercises_python/ex_4_variables.py | 839 | 4.21875 | 4 | #simple variable usage
#declaring variables
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
#doing operations on variables
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
#print statements
print("Expected output")
print(cars)
print( drivers)
print(cars_not_driven)
print(carpool_capacity)
print(passengers)
print(average_passengers_per_car)
print("Actual output")
print("There are", cars, "cars available.")
print("There are only", drivers, "driveres available.")
print("There will be", cars_not_driven, "empty cars today.")
print("We can transport", carpool_capacity, "people today.")
print("We have", passengers, "to carpool today.")
print("We need to put about", average_passengers_per_car, "in each car.")
| true |
2832f52d97e3b00686f16c3c21afa50e36e4acf5 | aadilkhhan/Dictionary-and-sets | /04_sets_method.py | 599 | 4.21875 | 4 | # Creating an empty set
b = set()
print(type(b))
# Adding values to an empty set
b.add(4)
b.add(5)
b.add(5) # Adding a value repeatedly does not changes a set
b.add(4)
b.add((4 , 5 , 6))
# b.add({4:5}) # Cannot add list or dictionary to sets
print(b)
# Length os the set
print(len(b)) # Prints the length of the set
# Removal of an items
b.remove(5) # Remove 5 from the set b
# b.remove(15) # Throws ann error while trying to remove 15 from the set which is not present in the set.
print(b)
# Delete anyone value from the set randomly.
print(b.pop())
print(b)
| true |
c75dd50ef67fcfd9da1189846132d0016574205c | benjamind2330/Stanford_Algorithms_course | /Merge_Sort_impl/Merge_Sort.py | 830 | 4.125 | 4 |
def mergesort(unsorted_array):
if (len(unsorted_array) == 1):
return unsorted_array
sortArray1 = mergesort(unsorted_array[:(int)(len(unsorted_array)/2)])
sortArray2 = mergesort(unsorted_array[(int)(len(unsorted_array)/2):])
return merge(sortArray1, sortArray2)
def merge(sorted_arr1, sorted_arr2):
output = list()
i = 0
j = 0
while (i < len(sorted_arr1) or j < len(sorted_arr2)):
#Check for i out of bounds
if (i >= len(sorted_arr1)):
#just add k
output.append(sorted_arr2[j])
j += 1
continue
if (j >= len(sorted_arr2)):
output.append(sorted_arr1[i])
i+=1
continue
if (sorted_arr1[i] < sorted_arr2[j]):
output.append(sorted_arr1[i])
i+=1
else:
output.append(sorted_arr2[j])
j+=1
return output
str_in = input("Type in your array: ")
print(mergesort(str_in))
| false |
ee64e01426bd03ee66751b1a06415f9b381a3f58 | jaineshp/TheAtom | /Birthday Paradox/birthdayparadox.py | 754 | 4.125 | 4 | from random import randint
def perform_experiment(no_of_people):
frequency = [0 for i in range(365)]
for i in range(no_of_people):
birthday = randint(0,364)
if frequency[birthday] == 1:
return 1 #Atleast one pair with same birthday
frequency[birthday] = 1
return 0 #Every person has different birth date
def main():
no_of_people = input("Enter the total number of people : ")
no_of_trials = input("Enter the number of trials : ")
success = 0 #success stores the count of trials in which atleast 2 people have same birthday
for trial in range(no_of_trials):
success += perform_experiment(no_of_people)
print "Probability of atleast 2 people with the same birthday =",(float(success)/no_of_trials)
if __name__ == "__main__":
main() | true |
ab7c95a9c5946bdc51e5bbdf3c154beecf08cef5 | amandajwright/module-2 | /ch07-debugging/ch7_amanda.py | 1,439 | 4.21875 | 4 | # -*- coding: utf-8 -*-
#Using print function
#Task 1
userInput = input("please give a number")
result = userInput - 2
print(result)
#this gives an error, because the user input is a string rather than an input:
userInput = input("please give a number")
print(type(userInput))
#to resolve this:
userInput = int(input("please give a number"))
result = userInput - 2
print(result)
#Using breakpoints
#Task 2
userInput = input("please give a number")
def simpleOperation(userInput):
intInput = int(userInput)
result = intInput - 2
return result
def nestedOperation(result):
result = simpleOperation(userInput)
result2 = result * 2
return result2
result =simpleOperation(userInput)
result2 = nestedOperation(result)
print(result2)
"""
When you've used a breakpoint you don't run the code in the normal way with the green arrow, you use the blue buttons:
1st: start running your code until the breakpoint
2nd: allows you to run your code line by line until the breakpoint
3rd: for stepping into the sections (class and functions) that you would like to dig into more and...
...4th: for you to step out when you feel that the error is not realted to the current section
5th: to go to the next breakpoint (if you have set up multiple ones)
6th: for you to exit debugging mode and go back to normal coding mode
To create a breakpoint in Spyder, double click to the left of the line number.
""" | true |
11297d0b2a3d0250f6a1aa1f6f7e4bf4c62e5e2c | amandajwright/module-2 | /ch11-whileLoops/dice_game.py | 2,110 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 18 11:47:19 2018
@author: 612436198
"""
from random import randint
def diceGame():
print("Welcome! I'm going to roll two dice and ask you to guess whether the sum of the two numbers rolled is odd or even.")
guess = ""
while type(guess) == str:
dieOne = randint(1, 6)
dieTwo = randint(1, 6)
diceTotal = dieOne + dieTwo
if diceTotal%2 == 0:
rightAnswer = "even"
else:
rightAnswer = "odd"
guess = input("Ok, dice rolled. Odd or even? If you don't want to play, type 'quit'.\n").lower()
if guess == "quit":
break
elif guess == "odd" or guess == "even":
secondGuess = input("The first die rolled a {}... would you like to change your mind (type 'y') or stick with your original guess (type 'n')?\n".format(dieOne))
if secondGuess == "quit":
break
elif guess == rightAnswer and secondGuess == "n":
print("Congratulations! The second die rolled a {}, making the sum {}. Well done for sticking to your guns.\nLet's play again.".format(dieTwo, diceTotal))
elif guess != rightAnswer and secondGuess == "y":
print("Congratulations! The second die rolled a {}, making the sum {}. Good second guessing.\nLet's play again.".format(dieTwo, diceTotal))
elif guess == rightAnswer and secondGuess == "y":
print("Argh, wrong! The second die rolled a {}, making the sum {}. First instincts can sometimes pay off.\nLet's play again.".format(dieTwo, diceTotal))
elif guess != rightAnswer and secondGuess == "n":
print("Argh, wrong! The second die rolled a {}, making the sum {}. Sometimes it pays to doubt yourself.\nLet's play again.".format(dieTwo, diceTotal))
else:
print("Not sure what happened there.\nLet's try again.")
else:
print("Whoops! Looks like there was a problem. Let's try again.")
| true |
0959c4195bdd2d9405a235ccbcf98ca0e2d9b3be | QWQ-pixel/practice_python | /calculator.py | 503 | 4.21875 | 4 | def calc(a, b, operation): # калькулятор
if operation == "+":
return a + b
elif operation == "-":
return a - b
elif operation == "*":
return a * b
elif operation == "/":
if b > 0:
return a / b
else:
return 888888
else:
return 888888
def calculator():
number_1 = float(input())
number_2 = float(input())
operation = input()
print(calc(number_1, number_2, operation))
calculator()
| false |
e405f810d7a1cbef31d15a2b5615848e12ce56c9 | tasinkhan/Dice-Simulator | /dice_simulator.py | 1,794 | 4.28125 | 4 | ''' Dice Game Simulator'''
import random
def dice_roll():
DiceRoll = random.randint(1,6)
return DiceRoll
def DiceGame():
player1 = input("Enter the name of Player 1: ")
player2 = input("Enter the name of Player 2: ")
player1_score = 0
player2_score = 0
rounds = 0
player1_wins = 0
player2_wins = 0
while rounds < 10:
player1_score = dice_roll()
print(f"{player1} rolls: {player1_score}")
player2_score = dice_roll()
print(f"{player2} rolls: {player2_score}")
rounds += 1
if player1_score == player2_score:
print(f"round {rounds} result is Draw\n")
elif player1_score > player2_score:
print(f"{player1} wins in round {rounds}\n")
player1_wins += 1
else:
print(f"{player2} wins in round {rounds}\n")
player2_wins += 1
if player1_wins == player2_wins:
print("Final result of the game is Draw")
elif player1_wins > player2_wins:
if player2_wins <=1:
print(f"{player1} wins total {player1_wins} rounds, {player2} wins total {player2_wins} round. Congratulations! {player1} is the winner of the Game\n")
else:
print(f"{player1} wins total {player1_wins} rounds, {player2} wins total {player2_wins} rounds. Congratulations! {player1} is the winner of the Game\n")
else:
if player1_wins <=1:
print(f"{player2} wins total {player2_wins} rounds, {player1} wins total {player1_wins} round. Congratulations! {player2} is the winner of the Game\n")
else:
print(f"{player2} wins total {player2_wins} rounds, {player1} wins total {player1_wins} rounds. Congratulations! {player2} is the winner of the Game\n")
DiceGame() | true |
24e111b4443c07eabfcc43656e1f4983e0341845 | dhazu/Mygit | /python_workbook/ch1/ex16.py | 759 | 4.4375 | 4 | """Exercise 16: Area and Volume
Write a program that begins by reading a radius, r , from the user. The program will
continue by computing and displaying the area of a circle with radius r and the
volume of a sphere with radius r . Use the pi constant in the math module in your
calculations."""
## Solution:
# import the pi function from the math module
from math import pi
# ask the user to enter the radius
r = float(input("Enter the radius of the circle: "))
# Calculate the area of the circle and volume of the sphere with the radius r
area = pi*r*r
vol = (4/3) * pi * (r ** 3)
# Display the result
print("""The area of the circle and volume of the sphere having radius {} unit are
{:.2f} squre unit and {:.2f} qubic unit""".format(r, area, vol))
| true |
98b82c402a68eac30578d14abeac026fa1eb0a17 | dhazu/Mygit | /python_workbook/ch1/ex30.py | 707 | 4.34375 | 4 | """Exercise 30: Units of Pressure
In this exercise you will create a program that reads a pressure from the user in kilo-
pascals. Once the pressure has been read your program should report the equivalent
pressure in pounds per square inch, millimeters of mercury and atmospheres. Use
your research skills to determine the conversion factors between these units."""
## Solution:
# ask the user to enter the pressure
k_p = float(input("Enter the pressure(in kilo pascals): "))
# Convert the pressure into pound per square inch
p_sqre_inch = k_p*0.1450377377
# Display the result
print("The equivalent pressure of {:.3f} kilo pascals is {:.3f} pounds per square inch.".format(
k_p, p_sqre_inch))
| true |
514c046664477303c07fe73545ad8370ede311e4 | dhazu/Mygit | /python_workbook/if-elif/ex48.py | 2,135 | 4.28125 | 4 | """Exercise 48: Chinese Zodiac
The Chinese zodiac assigns animals to years in a 12 year cycle. One 12 year cycle is
shown in the table below. The pattern repeats from there, with 2012 being another
year of the dragon, and 1999 being another year of the hare.
Year Animal
---- ------
2000 Dragon
2001 Snake
2002 Horse
2003 Sheep
2004 Monkey
2005 Rooster
2006 Dog
2007 Pig
2008 Rat
2009 Ox
2010 Tiger
2011 Hare
Write a program that reads a year from the user and displays the animal associated
with that year. Your program should work correctly for any year greater than or equal
to zero, not just the ones listed in the table."""
## Solution:
# ask the user to enter a year
year = int(input("Enter the year: "))
if year <= 0: # ensure a positive value is always entered
print("Enter a valid year.")
# apply the condition to get the correct answer
else:
if year % 12 == 8:
print("The animal associated with this year is Dragon.")
elif year % 12 == 9:
print("The animal associated with this year is Snake.")
elif year % 12 == 10:
print("The animal assocaited with this year is Horse.")
elif year % 12 == 11:
print("The animal associated with this year is Sheep.")
elif year % 12 == 0:
print("The animal associated with this year is Monkey.")
elif year % 12 == 1:
print("The animal associated with this year is Rooster.")
elif year % 12 == 2:
print("The animal associated with this year is Dog.")
elif year % 12 == 3:
print("The animal assocaited with this year is Pig.")
elif year % 12 == 4:
print("The animal associate with this year is Rat.")
elif year % 12 == 5:
print("The animal associated with this year is Ox.")
elif year % 12 == 6:
print("The animal associated with this year is Tiger.")
elif year % 12 == 7:
print("The year associated with this year is Hare.")
| true |
39c18eb3ac9f740f297fda19faab5873f7ef6cca | dhazu/Mygit | /python_workbook/ch1/ex7.py | 418 | 4.28125 | 4 | '''Exercise 7: Sum of the First n Positive Integers
Write a program that reads a positive integer, n, from the user and then displays the
sum of all of the integers from 1 to n. The sum of the first n positive integers can be
computed using the formula:
sum = (n)(n + 1)/ 2'''
#Solution:
n = int(input("Enter a number(positive integer): "))
sum = int(n * (n+1)/2)
print("The sum from 1 to {} is {}".format(n,sum))
| true |
f66279bc09a181295012383e08ee1369e915090b | dhazu/Mygit | /python_workbook/if-elif/ex40.py | 1,214 | 4.375 | 4 | """Exercise 40: Name that Triangle
A triangle can be classified based on the lengths of its sides as equilateral, isosceles
or scalene. All 3 sides of an equilateral triangle have the same length. An isosceles
triangle has two sides that are the same length, and a third side that is a different
length. If all of the sides have different lengths then the triangle is scalene.
Write a program that reads the lengths of 3 sides of a triangle from the user.
Display a message indicating the type of the triangle."""
## Solution:
# ask the user to enter the length of the sides of the triangle
s1 = float(input("Enter the lenghts of the first side of the triangle: "))
s2 = float(input("Enter the lenghts of the second side of the triangle: "))
s3 = float(input("Enter the lengths of the third side of the triangle: "))
# apply the condition to check the type of the triangle
if s1 == s2 == s3: # check for all sides are equal
print("The triagle is equilaterial")
elif s1 == s2 or s1 == s3 or s2 == s3: # check for any two sides are equal
print("The triagle is isosceles")
else: # all sides are different
print("The triangle is scalene")
| true |
437a23c453c78f62407710d7dc16f574cbd30634 | dhazu/Mygit | /python_workbook/loop/ex61.py | 1,706 | 4.1875 | 4 | """Exercise 61: Average
In this exercise you will create a program that computes the average of a collection
of values entered by the user. The user will enter 0 as a sentinel value to indicate
that no further values will be provided. Your program should display an appropriate
error message if the first value entered by the user is 0.
#Hint: Because the 0 marks the end of the input it should not be included in the average.
"""
## Solution:
# intialised the variables
add = 0
avg = 0
count = 0
# creat an empty list to store the numbers entered by the user
collection = []
# ask the user to enter how many numbers to be entered
num = int(input("Enter how many numbers to be entered: "))
# Ensure that the user will enter atleast one number
if num > 0:
# Now apply the for loop to calculate the result
for i in range(num):
x = int(input("Enter num{} number: ".format(i))) # prompt the user to enter the numbers
# Warn the user not to enter zero as first number or any other position
if (i == 0 and x == 0) or x == 0: # while zero is entered as first value or any other position
print("Don't enter zero")
break # zero acts as sentinel value and the program will stopped as well as loop will break
else:
collection.append(x) # insert the numbers to the lists
count += 1
add += collection[i] # add the numbers
# calculate the average
avg = add / float(count)
# display the result
if i == 0 and x == 0:
pass
else:
print("The average of the numbers = {:.2f}".format(avg))
else:
print("Need atleast one number to calculate the average")
| true |
52fe3cd9f663ee8c3e3c878f958bd6a8ff6f609e | dhazu/Mygit | /python_workbook/loop/ex63.py | 1,864 | 4.40625 | 4 | """Exercise 63: Temperature Conversion Table
Write a program that displays a temperature conversion table for degrees Celsius and
degrees Fahrenheit. The table should include rows for all temperatures between 0
and 100 degrees Celsius that are multiples of 10 degrees Celsius. Include appropriate
headings on your columns. The formula for converting between degrees Celsius and
degrees Fahrenheit can be found on the internet."""
## Solution:
#Define a function to convert degree celcius to fahrenheit
def degC_F():
print("Degree Celcius to Fahrenheit")
for i in range(1, 100): # temperature in between 0 to 100
if i % 10 == 0: # accept the temperatures those are multiples of 10
temp_F = (i * 9/5) + 32 # convert the temperature to fahrenheit
# display the result
print("""
temp(deg C) temp(deg F)
---------- ----------
{} {:>6.2f}""" .format(i, temp_F))
# Define a function to convert fahrenheit to degree celcius
def degF_C():
print("Fahenheit to degree celcius")
for i in range(1, 100):
if i % 10 == 0:
temp_C = (i - 32) * 5/9 # convert the temperature to degree celcius
# display the result
print("""
temp(deg F) temp(deg C)
----------- -----------
{} {:>6.2f}""".format(i, temp_C))
# ask the user to whether they want to do the convertion
answer = input("Now we are going to convert the temperature to fahrenheit. Do you want(Y/N)? ").upper()
if answer == 'Y':
# calling the function
degC_F()
else:
pass
answer2 = input("Do you want to convert the temperature to degree celcius(Y/N)? ").upper()
if answer2 == 'Y':
# calling the function
degF_C()
else:
pass
| true |
77e6e7b9d4d3b553fff829be30b25dbb76c7dbfb | dhazu/Mygit | /python_workbook/ch1/ex3.py | 602 | 4.40625 | 4 | """Exercise 3: Area of a Room
Write a program that asks the user to enter the width and length of a room. Once
the values have been read, your program should compute and display the area of the
room. The length and the width will be entered as floating point numbers. Include
units in your prompt and output message; either feet or meters, depending on which
unit you are more comfortable working with."""
#Solution:
w=float(input("Enter the width of the room(in feet):"))
l=float(input("Enter the length of the room(in feet):"))
area=w*l
print("The area of the room is {:.2f} sqr feet".format(area))
| true |
443e449664b0f6da17d26e666cb029cdce906def | Fhernd/PythonEjercicios | /Parte002/ex1080_hackerrank_convertir_numero_complejo_coordenadas_polares.py | 675 | 4.15625 | 4 | # Ejercicio 1080: HackerRank Convertir un número complejo a coordenadas polares.
# Task
# You are given a complex . Your task is to convert it to polar coordinates.
# Input Format
# A single line containing the complex number . Note: complex() function can be used in python
# to convert the input as a complex number.
# ...
import cmath
def convert_complex_polar_coordinates(complex_number):
r = abs(complex_number)
phase = cmath.phase(complex_number)
return r, phase
if __name__ == '__main__':
data = complex(input())
result = convert_complex_polar_coordinates(data)
print(round(result[0], 3))
print(round(result[1], 3))
| true |
a6e59241b90278c93bc290315c191df845bf7d11 | Fhernd/PythonEjercicios | /Parte002/ex1072_hackerrank_operaciones_mutables_conjunto_set.py | 738 | 4.125 | 4 | # Ejercicio 1072: HackerRank Operaciones que mutan o cambian un objeto conjunto (set).
# TASK
# You are given a set and number of other sets. These number of sets have to perform some specific mutation
# operations on set .
# Your task is to execute those operations and print the sum of elements from set .
if __name__ == '__main__':
m = int(input())
a = set(map(int, input().split()))
n = int(input())
operations = []
for _ in range(n):
command_quantity = input().split()
command = command_quantity[0]
quantity = int(command_quantity[1])
numbers = set(map(int, input().split()))
operations.append((command, quantity, numbers))
print(operations)
| true |
6bdbe2987f8dc1067c1b23bc4ebb308625c41c9b | Fhernd/PythonEjercicios | /Parte002/ex1094_hackerrank_expresion_lambda_aplicar_funcion.py | 865 | 4.28125 | 4 | # Ejercicio 1094: HackerRank Usar una expresión lambda para aplicar una función sobre un dato.
# Concept
# The map() function applies a function to every member of an iterable and returns the result. It takes two
# parameters: first, the function that is to be applied and secondly, the iterables.
# Let's say you are given a list of names, and you have to print a list that contains the length of each name.
# ...
cube = lambda x: x**3
def fibonacci(n):
fibonaccis = []
for i in range(n):
fibonaccis.append(fibonacci_recursive(i))
return fibonaccis
def fibonacci_recursive(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n))))
| true |
5572f65721080276e8fc20f00966ddcf55467d80 | Fhernd/PythonEjercicios | /Parte002/ex1121_hackerrank_puntaje_documento_xml_funcion.py | 848 | 4.28125 | 4 | # Ejercicio 1121: HackerRank Calcular el puntaje de un documento XML contando el número de atributos de los elementos.
# You are given a valid XML document, and you have to print its score. The score is calculated by the sum of
# the score of each element. For any element, the score is equal to the number of attributes it has.
# Input Format
# The first line contains , the number of lines in the XML document.
# The next lines follow containing the XML document.
# ...
import sys
import xml.etree.ElementTree as etree
def get_attr_number(node):
total = 0
for e in node.iter():
total += len(e.attrib)
return total
if __name__ == '__main__':
sys.stdin.readline()
xml = sys.stdin.read()
tree = etree.ElementTree(etree.fromstring(xml))
root = tree.getroot()
print(get_attr_number(root))
| true |
498887b8816b3ff582fb446caacaecd85a56770b | rpenn97/python_data20 | /Working_with_Files/working_with_files_intro.py | 1,230 | 4.34375 | 4 | # #File doesn't exist: file = open("order.txt")
# def open_and_print_file(file):
# try:
# #if you open a file, you MUST CLOSE IT!
# opened_file = open(file, "r")
# file_line_list = opened_file.readlines()
#
# print(file_line_list)
# for i in file_line_list:
# print (i)
#
# opened_file.close()
#
# except FileNotFoundError as msg:
# print("There is an error! Panic!")
# print(msg)
# finally:
# print("Execution complete")
#
# open_and_print_file("order.txt")
# #Another way to open files without needing to CLOSE
# def open_and_print_file(file):
# try:
# with open(file,"r") as file:
# file_line_list = file.read()
# print(file_line_list)
#
# except FileNotFoundError as msg:
# print("There is an error! Panic!")
# print(msg)
# finally:
# print("Execution complete")
#
# open_and_print_file("order.txt")
# adding items to a file
def writing_to_file(file, order_item):
try:
with open(file, "a") as file:
file.write(order_item + "\n")
except FileNotFoundError:
print("Not found!")
writing_to_file("order.txt", "gyoza dumplings")
| true |
0cc3027bd1a7828563b3c4de66ad94bc47f5bbb8 | cynnnzhang/Other-Python | /HHAfencing.py | 1,172 | 4.3125 | 4 | #Introduction
print ("Welcome to Cynthia's incredible garden fencing homework helper!")
print ("This program will tell you how much it'll cost in total")
print ("to install a fence around your rectangular garden.")
print ("*" * 30)
#Input statements
length = float(input("Enter the length of your garden in feet: "))
width = float(input("Enter the width of your garden in feet: "))
costperFence = float(input("Enter the cost per foot of fencing found at your local hardware store:$ "))
labourCost = float(input("Enter the cost for labour/installation:$ "))
#Calculations
perimeter =(length + width)*2
cost = (perimeter * costperFence)
roundedCost = round(perimeter * costperFence, 2)
totalCost = round(cost + labourCost, 2)
roundedPerimeter = round(perimeter, 2)
#Results
print ("*" * 30)
print ("Here are your results")
print ("*" * 30)
print ("The perimeter of your garden is", perimeter, "ft.")
print ("")
print ("Using the exact perimeter measurement...")
print ("The fencing will cost you","$", roundedCost)
print ("In total with labour/installation costs, it will cost you $", totalCost, "to install")
print ("fencing around your garden.")
| true |
780895b1c49b267c00d72e3ea4ff377066bffacd | pavanbhat/REST_StudentEnrollmentSystem | /ListOfStudents.py | 1,458 | 4.125 | 4 | class ListOfStudents:
'''
A class that stores a list of Student objects
'''
__slots__ = 'student_data'
def __init__(self):
'''
Default Constructor, creates a list called student_data
'''
self.student_data = []
def get_student_data(self):
'''
Gets the Student information of all students
:return: a list of Student information of all students
'''
return self.student_data
def set_student_data(self, student):
'''
Sets/Appends the list of student_data with a Student object
:param student: An object of class Student
:return: None
'''
self.student_data.append(student)
def remove_student_data(self, student_id):
'''
Removes the student information corresponding to a given student with student ID
:param student_id: id of a given student to be removed from the list
:return: None
'''
try:
if len(self.student_data) > 0:
for i in range(len(self.student_data)):
if self.student_data[i].id == student_id:
del self.student_data[i]
break
except Exception as e:
print(e)
def remove_all_student_data(self):
'''
Removes all the elements from the list of Students
:return: None
'''
self.student_data = [] | true |
920532086a31d09bf7f0970e7e2a7f698b14c8c6 | avault/cheaters-pong | /base_ball.py | 1,670 | 4.5 | 4 | # This "class", or virtual object, describes a ball.
class Ball(object):
# Everything inside here (i.e. inside this function __init__), are things that are set
# when the ball is first made.
def __init__(self, x_position, y_position, x_velocity, y_velocity, ball_color):
# This line sets how big the ball is
self.radius = 12.
# These lines set where the ball starts out (i.e. the position of the ball)
self.x_position = x_position
self.y_position = y_position
# These lines set how fast the ball is moving (i.e. the velocity of the ball)
self.x_velocity = x_velocity
self.y_velocity = y_velocity
# What color is the ball?
self.ball_color = ball_color
# This line says how fast the ball moves
self.speed = 5
# Everything inside here decides what the ball actually looks like
def draw_ball(self):
# Make sure the ball is the right color
fill(self.ball_color)
# This line actually draws the ball!
ellipse(self.x_position, self.y_position, self.radius*2., self.radius*2.)
# Everything inside here describes how we move the ball
def move_ball(self, dt):
# The ball is moved horizontally by the horizontal speed of the paddle multiplied by the time a single frame takes
self.x_position += self.x_velocity*dt
# Move the ball vertically by the vertical speed of the paddle multiplied by the time a single frame takes
self.y_position += self.y_velocity*dt
| true |
a4ff3c94a2c7ba92bf215e7c194aee67e2f64616 | Nadunnissanka/Python-List-Comprehension | /main.py | 644 | 4.34375 | 4 | # List Comprehension
# using a list example
numbers_list = [1,2,3,4,5]
new_list = [n+1 for n in numbers_list]
# print(new_list)
# output -> [2, 3, 4, 5, 6]
# using a String example
name = "Angela"
new_list = [letter for letter in name]
# print(new_list)
# output -> ['A', 'n', 'g', 'e', 'l', 'a']
# using a range as example
numbers = range(1,5)
new_list = [n*2 for n in numbers]
# print(new_list)
# output -> [2, 4, 6, 8]
# using condionals in List Comprehension
names = ["Alex","Beth","Nadun","Chamath","Freddie","udara"]
long_names = [name.upper() for name in names if len(name) > 5]
# print(long_names)
# output -> ['CHAMATH', 'FREDDIE'] | false |
63413f64a19c3cec98a2f8421d8f7feb7874d4b7 | RomanSC/Introduction-to-Programming-with-Python | /change-counter.py | 935 | 4.1875 | 4 | # this program takes your coins, adds them together, and outputs your total change
def main():
print("\nChange Counter!\n")
print("\nInput how many of each coin you have:\n")
# for each change type, asks for input of the amount of the coin
# converts them to floats for expression
quarters = float(input("Quarters:"))
dimes = float(input("Dimes:"))
nickels = float(input("Nickels:"))
pennies = float(input("Pennies:"))
# this expression takes the amount for each coin, multiplies it by the value
# for it's type, while adding the total for each type together to use in the string
total = quarters * .25 + dimes * .10 + nickels * .05 + pennies * .01
# nice string for outputting the total to the user, %s inside the string
# places %(total) inside the string, then the print() function prints to
# deliver the user their total
print("\nYou have $%s\n" %(total))
main()
| true |
6cbb358fb91bf52a0fadb543637d67b7ea0c2b2b | RomanSC/Introduction-to-Programming-with-Python | /python-calculator.py | 306 | 4.15625 | 4 | def add (x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x /y
print ("I would you like to:")
print ("1. Add")
print ("2. Subtract")
print ("3. Multiply")
print ("4. Divide")
choice = input ("Enter choice (1/2/3/4):")
| false |
72fb649182033696d00131177325c094c68d8d87 | vikramforsk2019/FSDP_2019 | /day02/days_in_month.py | 775 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 16:36:50 2019
@author: vikram
"""
"""
Make a function days_in_month to return the number of days in a specific month of a year
"""
import leap_year
def days_in_month(month):
list1=['january','march','may','july','august','octomber','december']
list2=['april','june','september','november']
list3=['february']
if (month in list1):
return '31'
elif (month in list2):
return '30'
elif(month in list3):
print(leap_year.find_year(2000))
if(leap_year.find_year(2000)=='True'):
return '28'
else:
return '29'
else:
return 'invalid month'
month_name=input('enter a month>')
day=days_in_month(month_name)
print(day) | true |
e84d84f01ed59ca7865b7c887a2bcec7d732c4d4 | vikramforsk2019/FSDP_2019 | /day02/leap_year.py | 450 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 16:18:22 2019
@author: vikram
"""
"""
# Make a function to find whether a year is a leap year or no, return True or False
"""
def find_year(year_check):
if(year_check%4==0 and year_check%100!=0) :
return 'True'
elif( year_check%400==0 ) :
return 'True'
else:
return 'False'
year_check=int(input('enter a year>'))
year_type=find_year(year_check)
print(year_type) | true |
7558d484e2663474015cac563def7cdc82e1df5c | kzeidlere/patstavigie-darbi | /patstavigais_darbs_1/4.py | 284 | 4.125 | 4 | number1 = int(input("Enter first number: "))
number2 = int(input("Enter second number: "))
print(f"{number1}+{number2}={number1+number2}")
print(f"{number1}-{number2}={number1-number2}")
print(f"{number1}*{number2}={number1*number2}")
print(f"{number1}/{number2}={number1/number2}")
| false |
b91e41a3475f1401421b0e76935edfdbbc8eb782 | 824zzy/Leetcode | /D_TwoPointers/DifferentDirection/L2_75_Sort_Colors.py | 1,261 | 4.15625 | 4 | """ https://leetcode.com/problems/sort-colors/
https://leetcode.com/problems/sort-colors/discuss/681526/Python-O(n)-3-pointers-in-place-approach-explained
two methods:
1. three pointers(dutch national flag problem)
2. two passes by two pointers
"""
# dijkstra's dutch national flag problem: https://en.wikipedia.org/wiki/Dutch_national_flag_problem
class Solution:
def sortColors(self, A: List[int]) -> None:
i, j, k = 0, 0, len(A)-1
while j<=k:
if A[j]<1:
A[i], A[j] = A[j], A[i]
i, j = i+1, j+1
elif A[j]>1:
A[j], A[k] = A[k], A[j]
k -= 1
else: j += 1
# two pass for corner cases: 1,0,1; 1,2,1
class Solution:
def sortColors(self, A: List[int]) -> None:
l, r = 0, len(A)-1
while l<r:
if A[l]>A[r]:
A[l], A[r] = A[r], A[l]
if A[l]==0: l += 1
if A[r]==2: r -= 1
if A[l]==A[r]:
l += 1
l, r = 0, len(A)-1
while l<r:
if A[l]>A[r]:
A[l], A[r] = A[r], A[l]
if A[l]==0: l += 1
if A[r]==2: r -= 1
if A[l]==A[r]:
r -= 1 | false |
502c6649a9e98744ecf8e0b71bae64f24c00ed08 | cuijian0819/sorting-algorithm | /merge_sort.py | 980 | 4.125 | 4 |
def merge_sort(input_list):
if len(input_list) <= 1:
return input_list
mid_point = len(input_list)//2
left_list = merge_sort(input_list[:mid_point])
right_list = merge_sort(input_list[mid_point:])
left_len = len(left_list)
right_len = len(right_list)
left_index = 0
right_index = 0
return_index = 0
while left_index < left_len and right_index < right_len:
if left_list[left_index] < right_list[right_index]:
input_list[return_index] = left_list[left_index]
left_index += 1
else:
input_list[return_index] = right_list[right_index]
right_index += 1
return_index += 1
while left_index < left_len:
input_list[return_index] = left_list[left_index]
left_index += 1
return_index += 1
while right_index < right_len:
input_list[return_index] = right_list[right_index]
right_index += 1
return_index += 1
return input_list
if __name__ == '__main__':
input_list = [1, 3, 5, 2, 4, 6, 7]
merge_sort(input_list)
print(input_list)
| false |
bbb02be61da2acc7b5f7c624021b076f11011a82 | tmosime247/Pre-bootcamp-coding-challenges | /task-11.py | 328 | 4.25 | 4 | #takes two strings as input, and outputs the common characters/letters that they share
def common_letters(str1, str2):
char_list = []
for char in str1:
if(str2.find(char) != -1):
char_list.append(char)
return "common letters: " + ", ".join(char_list)
print(common_letters("house", "computers"))
| true |
03d7c026a9cba267075a43288c6f8c8d3ac609c8 | AlamArbazKhan/pythonfile | /Day16_B34.py | 1,487 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
continuation of classes
# In[ ]:
classes:
methods:
attributes:
self:
objects:
# In[ ]:
#req: creating a greeting class:
1. accept the input name from the user
2. display the name
3. greet the user
# In[1]:
class Greet: # class name
"""creating an greeting class""" # doc string
def name(self,username): # method name (similar like the function outside of the class)
self.username = username # attribute (similar like the variable)
def display(self): # method
print(f"{self.username}")
def greetuser(self): # method...
print(f"Hello, {self.username}")
# In[2]:
test = Greet()
# In[3]:
test.name('naveen')
# In[4]:
test.display()
# In[ ]:
# self is a temp place holder for an object
# In[ ]:
# In[5]:
asdf = Greet()
# In[6]:
asdf.name('sadhana')
# In[7]:
asdf.display()
# In[8]:
asdf.greetuser()
# In[ ]:
# In[ ]:
introduction to constructor : (it is also called as special method or magical method)
overview : Constructor is used to automate the method in the class and is considered as the best practise to be implimented
# In[ ]:
how to define the constructor:
def __init__(self,paraml,param2) #genric way...! initi __
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
| true |
ac0640b11d5e33b794c2d6d06440932dd9c69746 | AlamArbazKhan/pythonfile | /Day11_B34.py | 1,340 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
introduction to conditional statments:
# In[ ]:
if else condition:
# In[ ]:
# general statment:
if condition:
print("something")
else:
print("someotherthing")
# In[ ]:
# In[ ]:
voting application:
age > = 18 =====> we are eligible to vote.
# In[ ]:
# In[1]:
age = 17
# In[4]:
if age >= 18:
print("you are eligible to vote")
else:
print("you are not eligible to vote")
# In[ ]:
# In[5]:
age = 25
# In[6]:
if age >= 18:
print("you are eligible to vote")
else:
print("you are not eligible to vote")
# In[ ]:
# In[7]:
if age >= 18:
print("you are eligible to vote")
print("have you registered for the voter?")
else:
print("you are not eligible to vote")
print("try next year!")
# In[ ]:
# In[ ]:
Multiple conditions validation:
# In[ ]:
# Scenario based question:
> Admission for anyone under age 4 is free.
> Admission for anyone between the ages of 4 and 18 is $25.
> Admission for anyone age 18 or older is $40.
# In[10]:
# then solution code below ====> elif ( else if )
if age < 4:
print("your entry is free")
elif age < 18:
print("your entry ticket is 25")
else:
print("you entry ticket is 40")
# In[9]:
age = 3
# In[ ]:
# In[ ]:
| true |
9935ac90156b6572bfb9d0cccf2d55b94a2c36f8 | vertig0d/PythonProgrammingExercise | /Q3L1M1.py | 479 | 4.21875 | 4 | """
With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such
that is an integral number between 1 and n (both included). and then the program should print the
dictionary.
Suppose the following input is supplied to the program:
8
Then, the output should be:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
"""
#Method1
num = input("Enter a number: ")
dicti = {}
for k in range(1, num + 1):
dicti[k] = k * k
print(dicti) | true |
4e382f7f88989eb9169482eede881b5a304839fe | GoshaYarosh/python_labs | /lab2/linearmath/linearfunction.py | 2,396 | 4.125 | 4 | class LinearFunction(object):
'''LinearFunction class
Represents a linear fucntion of the form: f(x) = Ax + B,
where A and B some coeffs
Methods:
__init__ - initialize coeffs of linear function
__call__ - if param is other linear function returns a
composition of current and other function, else
returns a substitution of value into function
__add__ - returns a sum of current and other linear functions
__sub__ - returns a substraction of current and other functions
__mul__ - returns a multiply of current function on some number
'''
def __init__(self, a, b):
self.a = a
self.b = b
def __call__(self, param):
if isinstance(param, LinearFunction):
other_function = param
composition = LinearFunction(
self.a * other_function.a,
self.a * other_function.b + self.b
)
return composition
elif isinstance(param, (int, long, float)):
point = param
return self.a * point + self.b
else:
raise TypeError('Wrong param type: {0}'.format(type(param)))
def __str__(self):
result_string = 'f(x) = '
if self.a == 0 and self.b == 0:
return result_string + '0'
else:
if self.a == 0:
result_string += ''
elif self.a == 1:
result_string += 'x'
elif self.a == -1:
result_string += '-x'
else:
result_string += '{0}x'.format(self.a)
if self.b == 0:
result_string += ''
elif self.b > 0 and self.a == 0:
result_string += '{0}'.format(self.b)
elif self.b > 0 and self.a != 0:
result_string += ' + {0}'.format(self.b)
elif self.b < 0:
result_string += ' - {0}'.format(-self.b)
return result_string
def __eq__(self, other):
return (self.a == other.a) and (self.b == other.b)
def __add__(self, other):
return LinearFunction(self.a + other.a, self.b + other.b)
def __sub__(self, other):
return LinearFunction(self.a - other.a, self.b - other.b)
def __mul__(self, number):
return LinearFunction(self.a * number, self.b * number)
| true |
768b22c3ccd6894755e5ca46f54ebfaaa05b5980 | Ujwalauk/dlithe | /assignment1/prob2.py | 295 | 4.1875 | 4 | #sum and average
#inputs
a=float(input('first number:'))
b=float(input('second nubmer:'))
c=float(input('third number:'))
# calculating sum and avg
sum=a+b+c
avg=sum/3
#printing sum and avg ans
print("sum of three number:",round(sum,2))
print("average of three number:",round(avg,2))
| true |
34f82c32eee75931ae07ea4a18472ebb0592e7d5 | marcosdemelo00/PythonForAbsoluteBeginners | /Solutions.Old/Print().py | 1,792 | 4.65625 | 5 | """
String Concatenation:
1.create a variable and assign it the phrase "hello world" by concatenating the strings "hello" and " world"
2.create a variable and assign it the integer 11
3.create a variable and assign it the integer 38
4.create a variable and use the variables from steps 2 and 3 and string concatenation to assign it the string
"1138"
"""
# type your code for "String Concatenation" below this comment and above the one below it.------------------------------
phrase = "hello " + "world"
int1 = 11
int2 = 38
intConc = str(int1) + str(int2)
print(phrase, intConc)
# ----------------------------------------------------------------------------------------------------------------------
"""
%s and input():
1.create a variable to hold a user's favorite restaurant (use input() for this.)
2.create a variable to hold the name of a place a user wants to visit.
3.create a variable to hold the user's nickname or first name if they don't have a nickname.
4.use the %s operator to assign the string "Your favorite restaurant is [name of favorite restaurant], you want
to visit
[name of place the user wants to visit], and your nickname or first name is [nickname or first name]" to a
variable
5.print that variable
"""
# type your code for "%s and input()" below this comment and above the one below it.------------------------------------
rest = input("What is your favorite restaurant?")
place = input("what is the place that you must to visit?")
nick = input("What is your nickname? If you don't have a nickname write your first name")
print("Your favorite restaurant is %s, you want to visit %s, and your nickname or first name is %s"%(rest, place, nick))
# ---------------------------------------------------------------------------------------------------------------------- | true |
c607f044b2f9643c2370aaaca608c3ee80b8bfd7 | marcosdemelo00/PythonForAbsoluteBeginners | /Solutions.New/Programming Challenge 12 - String Reverser.py | 878 | 4.59375 | 5 | '''
Programming Challenge: String Reverser
For this challenge, you will be writing a program which uses a for loop to
reverse a string.
Start by creating a variable and assigning it a string as user input using
input().
Use a for loop to reverse the string. You will need to use range with all
3 inputs for this. In addition, you should create a variable before the for
loop and assign it an empty string. The variable will be reassigned multiple
times within the for loop and end up holding the new reversed string.
Print the reversed string at the bottom of your program.
'''
def reverser(str):
reverse = ''
for l in range(0, len(str)):
reverse = str[l] + reverse
return reverse
line = input('Enter anything: \n>>> ').strip()
rline = reverser(line)
print('Reverse of {2}{0}{4} is: {3}{1}{4}'.format(line, rline, '\033[33m', '\033[35m', '\033[m')) | true |
33cd175496519c6c70870aafa9b7dbffa7aff5a3 | marcosdemelo00/PythonForAbsoluteBeginners | /Solutions.New/Programming Challenge 10 - Fizz Buzz.py | 668 | 4.25 | 4 | '''
Programming Challenge: Fizz Buzz
Write a program that prints the integers 1 through 50 using a loop.
However, for numbers which are multiples of both 3 and 5 print “FizzBuzz” in
the output. For numbers which are multiples of 3 but not 5 print “Fizz”
instead of the number and for the numbers that are multiples of 5 but not 3
print “Buzz” instead of the number.
All of the remaining numbers which are not multiples of 3 or 5 should just be
printed as themselves.
'''
for i in range(1, 51):
if i % 3 == 0:
if i % 5 == 0:
i = 'FizzBuzz'
else:
i = 'Fizz'
elif i % 5 == 0:
i = 'Buzz'
print(i)
| true |
c4fb122b61ab83d147c5171255f552bb9543a881 | NastyaZotkina/STP | /lab11.py | 640 | 4.28125 | 4 | print("Нажмите 1, если возводимое в степень число целое или нажмите 2, если оно дробное:")
x=input("Сделайте Ваш выбор ")
x=int(x)
if x==1:
a=int(input("Введите число, возводимое в степень "))
b=int(input("Введите степень "))
print("a^b=",a**b)
elif x==2:
a=float(input("Введите число, возводимое в степень "))
b=int(input("Введите степень "))
print("a^b=",a**b)
else:
print("введены некорректные данные!") | false |
9eecbaa4ce7050a9aeb3af24fefe92485e0833c0 | oeruizzz/CursoPython | /main.py | 839 | 4.21875 | 4 | #print("Hola mundo")
# Input() ingresar datos
#print("Ingrese su nombre")
#x = input() #Este es la funcion imput
#Tipos de variables
#----------------------
# 1. LISTA
x = ["ana",27,3,"Hola"]
#----------------------
# 2. STRING MULTILINEA
x= """
Hola
Mundo
"""
#-----------------------
#Errores
#SintaxError
#NameError (Este error sale es cuando el compilador no reconoce una palabra clave o no está definida una variable o funcion)
#ZeroDivisionError (Cuando el resultado de una divisio es cero)
#Potencia **
#Raiz cuadrada ** 0.5
#modulo de una division %
#Mas igual += (Sirve para string y numeros)
###### ATENCIÓN SOLO SE PUEDE CONCATENAR STRING CON STRING ######
### Para concatenar string con numeros hay que usarla funcion str(int) en la variable numerica
print("¿Cómo te llamas?")
name = input()
print("Hola " + name + "!") | false |
198bba3d559c27542c66b72cda0a1163fbf5d3a5 | poojanagrecha/100-days-of-code | /Code/Day3_Love_Calculator.py | 886 | 4.125 | 4 | # 🚨 Don't change the code below 👇
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
fullname = name1.lower() + name2.lower()
# print(fullname)
score_true = fullname.count("t") + fullname.count("r") + fullname.count("u") + fullname.count("e")
score_love = fullname.count("l") + fullname.count("o") + fullname.count("v") + fullname.count("e")
final_score = str(score_true) + str(score_love)
final_score = int(final_score)
# print(final_score)
if (final_score <10) or (final_score >90):
print(f"Your score is {final_score}, you go together like coke and mentos.")
elif (final_score >=40) and (final_score <=50):
print(f"Your score is {final_score}, you are alright together.")
else:
print(f"Your score is {final_score}.")
| true |
194d7d2a3017342f8d7296359126fea9029fac0f | mustafakamil12/Python-OOP | /Instances+-+Code/9 - House - Modifying Instance Attribute.py | 548 | 4.21875 | 4 | class House:
def __init__(self, price, square_feet, num_bedrooms, num_bathrooms):
self.price = price
self.square_feet = square_feet
self.num_bedrooms = num_bedrooms
self.num_bathrooms = num_bathrooms
my_house = House(50000, 2100, 4, 3)
# Print the current value of the 'price'
# attribute of the instance my_house
print("Current Value:", my_house.price)
# Update the value of the 'price' attribute
# of the instance my_house
my_house.price = 55000
# Print the updated value
print("New Value:", my_house.price)
| true |
79f56631f2c859002d864c924d91e5f8caecf998 | arjenbin/lpthw | /Training/exercise6.py | 985 | 4.28125 | 4 | #Assign 10 to the variable "types of people"
types_of_people = 10
hilarious = True
#assign a formatted string to variable x
x = f"There are {types_of_people} types of people"
#assign the string "binary" to the variable 'binary'
binary = "binary"
#assign the string "don't" to the variable 'do_not'
do_not = "don't"
#assign a 'double' formatted string to variable y
y = f"those who know {binary} and those who {do_not}."
print(x)
print(y)
#print formatted strings
print(f"I said: {x}")
print(f"I also said: {y}")
#assign a string to Joke eval varaible. for some reason it needs the parentheses{} at the end...
joke_eval = "Isn't that joke so funny? {}"
joke_eval2 = "Isn't that joke so funny? {}"
print(joke_eval.format(hilarious))
print(joke_eval2.format(y+x))
degreesc = 15.45 + 230
degreesmessage = "It is {} degrees celcius here"
print(degreesmessage.format(degreesc))
w="This is the left side of..."
e="a string with a right side"
print(w+e) | true |
42045ba7c8cff6599663e00cf78c901117ee18cd | dmulyalin/ttp | /ttp/group/items2dict.py | 349 | 4.21875 | 4 | def items2dict(data, key_name, value_name):
"""
Function to combine values of key_name and value_name keys in
a key-value pair.
"""
# do sanity checks
if key_name not in data or value_name not in data:
return data, False
# combine values
data[data.pop(key_name)] = data.pop(value_name)
return data, None
| true |
e416d91eb5668601f33e518c2e116057fca7df55 | etin52/python-class | /wordgame.py | 2,826 | 4.1875 | 4 | # print("welcome to word game")
# print("""
# The rules of the Game:
# 1.Try to guess a word in our system
# 3.If your word appears n times you get n*5 points
# 2.Upon getting a word correctly you get 5 points
# # # May the best guess win!
# # # """)
# # my_random_words="""Today we present you the list of 100 random words in
# # English and we’ll also give you their meanings. Keep a count of words to see how many of them you know.
# # Have you ever thought, what it would be like to know words
# # you’ve never thought you would know? Well if not, or if just now,
# # then voila! You just turned to a right piece, that’ll help you know
# # hundred random words, well why right? However, you can answer this better,being someone who’s devoting their precious time into learning and growing.
# # For the sake of an answer, I’d say to have a rich vocabulary is a great
# # thing if you’re into an academic course, that requires you to be creative with the choice of your words, or professionally to leave a moving impact on your readers, or maybe to maintain a journal with Galaxy of words, for your own happiness.
# # Sledging deeper, I would like you and I, to know some words
# # we already knew and some we never. So let’s get learning.
# # """.lower()
# # user_input=input("Enter a word\n").lower()
# # print(my_random_words.count(user_input))
# # word_occurrence=my_random_words.count(user_input)
# # score=word_occurrence*5
# # print(F"your score ia {score}")
# #### TASK ONE #####
# # get input from the user and print three line where
# # The first line is the sum of the two numbers
# # The second line contains the differnce of the two numbers
# # The third line contains the product of the two numners.
# # Given
# a=int(input("enter the first number \n"))
# b=int(input("enter the second number \n"))
# # print(a+b)
# # print(a-b)
# # print(a*b)'
# ### TASK ####
# # # converts "this is a string " to "thsi-is-s-string."
# # string="this is a string"
# # print(string)
# # list_of_string=string.split()
# # print("-".join(list_of_string))
# # ## OR
# print(string.replace(" ",'-'))
# # first_name=input("enter your first name:\n")
# # last_name=input("enter your last name :\n")
# # print(f"Hello {first_name} {last_name}! you just delved into python.")
# new_list=['this', 'brown',55 ,'oxen',True ,0.85]
print(new_list[1])
# print(new_list[1:4:2])
# # # change of value ,
# # new_list[1]="black"
# # print(new_list)
# # second_list=['yam',"egg",'fish']
# # print(new_list + second_list)
# list1 =[10,20, [300,400,[5000,6000],500],30,40]
# first_num =list1[2][2][1]
# # print(first_num)
# second_num=list1[2][3]
# print(second_num)
# print(first_num + second_num)
# third_num=list1[2][2][0]
# print(third_num)
| true |
13e2128e36b6f688ecda8d25354265c5eb5cb2ee | uncleyao/Leetcode | /254 Factor Combinations.py | 1,266 | 4.1875 | 4 | """
Numbers can be regarded as product of its factors. For example,
8 = 2 x 2 x 2;
= 2 x 4.
Write a function that takes an integer n and return all possible combinations of its factors.
Note:
You may assume that n is always positive.
Factors should be greater than 1 and less than n.
Examples:
input: 1
output:
[]
input: 37
output:
[]
input: 12
output:
[
[2, 6],
[2, 2, 3],
[3, 4]
]
input: 32
output:
[
[2, 16],
[2, 2, 8],
[2, 2, 2, 4],
[2, 2, 2, 2, 2],
[2, 4, 4],
[4, 8]
]
"""
from math import sqrt
class Solution(object):
def getFactors(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
result = []
###Use list as input to pop and append
self.dfs([n],result)
return result
def dfs(self,cur,result):
if len(cur) >1:
result.append(list(cur))
## pop it b/c the last will be used to divide
n = cur.pop()
start = 2 if not cur else cur[-1]
for i in range(start,int(sqrt(n))+1):
if n%i==0:
cur.append(i)
cur.append(n/i)
self.dfs(cur,result)
cur.pop() ##This is used for start with a new i
| true |
68bcdb7d65295a1c21bba33b2edda91296367cb4 | kvnol/studiespy | /curso-em-video/challenge-01/challenge-01.py | 817 | 4.125 | 4 |
# Crie um script Python que leia o nome de uma pessoa
# e mostre uma mensagem de boas-vindas de acordo com o valor digitado.
name = input('Qual é o seu nome? ')
print('Olá,', name, 'seja bem-vindo.')
# Crie um script Python que leia o dia, o mês e o ano de nascimento
# de uma pessoa e mostre uma mensagem com a data formatada.
day = input('Qual seu dia de nascimento? ')
month = input('Qual seu mês de nascimento? ')
year = input('Qual seu ano de nascimento? ')
print(name, ', você nasceu no dia', day, 'de', month, 'de', year)
# Crie um script Python que leia dois números
# e tente mostrar a soma entre eles:
number1 = input('Digite um número: ')
number2 = input('Digite outro número: ')
resultSum = int(number1) + int(number2)
print('A resposta da soma entre', number1, 'e', number2, 'é:', resultSum) | false |
8ec458f11ca3b24b4f52a11d3cf8f938d65f1d57 | dileepmenon/HackerRank | /Python/Data_Structures/Linked_Lists/Inserting_a_Node_into_a_Sorted_Doubly_Linked_List/solution.py | 1,044 | 4.125 | 4 | """
Insert a node into a sorted doubly linked list
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None, prev_node = None):
self.data = data
self.next = next_node
self.prev = prev_node
return the head node of the updated list
"""
def SortedInsert(head, data):
temp1 = head
if temp1:
if temp1.data > data:
k = Node(data)
k.next = temp1
temp1.prev = k
head = k
else:
while temp1 and temp1.data < data:
temp = temp1
temp1 = temp1.next
if not temp1:
temp1 = Node(data)
temp.next = temp1
temp1.prev = temp
temp1.next = None
else:
k = Node(data)
temp.next = k
k.prev = temp
k.next = temp1
temp1.prev = k
else:
head = Node(data)
return head
| true |
305283cf812e8d6ad511292bcc57722dc6586a61 | RimELMGHARI/python_bootcamp | /module00/ex04/operations.py | 276 | 4.1875 | 4 |
num1= int(input('enter first number: '))
num2= int(input('enter second number (it must be diffrent than zero): '))
print("sum: ", num1+num2)
print("difference: ", num1-num2)
print("product: ", num1*num2)
print("quotient: ", num1/num2)
print("remainder: ", num1%num2)
| false |
0e11d40ccbca3477b0c7341a0afdb45fee861ce1 | ShaliniBhattacharya/StonePaperScissors | /simple.py | 470 | 4.1875 | 4 |
import random
choices=["stone","paper","scissors"] //list of choices
print("Make your throw")
user_choice=input(" Type stone, paper or scissors : ") //user's input
if user_choice in choices:
computer_choice=random.choice(choices) //PC's choice from random
print(f "\n You threw '{user_choice}', the PC threw '{computer_choice}'") //f is used to give the {name} for the template
else:
print(f "\n You typed '{user_choice}' which is not a valid throw") | true |
ac0fdcd5688408a81bed669adeacf4ca3a805561 | alkawaiba/Binary-Calculation | /Inputs.py | 1,884 | 4.21875 | 4 | def integer_check(num):
#Exception Handling case
try:
int(num)
return True
except ValueError:
return False
#input values from the user
def number():
print("\nNOTE:You can only input numbers from 0 to 255\n")
check1 = "no"
check2 = "no"
check3 = "no"
while check3 == "no" :
while check1 == "no" :
input1 = input("Enter the first number: ") #checking the input error
if integer_check(input1) == False:
print("Data Type ERROR!\nThe Program is meant to accept integer values only.\n")
else:
num1 = int(input1)
if num1 > -1 and num1 < 256 : #checking the condition with input value
check1 = "yes"
else:
print("Data Type ERROR!\nPlease enter a number between 0 and 255 only.\n")
while check2 == "no" :
input2 = input("Enter the second number: ") #checking the input error
if integer_check(input2) == False:
print("Data Type ERROR!\nThe Program is meant to accept integer values only.\n")
else:
num2 = int(input2)
if num2 > -1 and num2 < 256 : #checking the condition with input value
check2 = "yes"
else:
print("Data Type ERROR!\nPlease enter a number between 0 and 255 only.\n")
#checking th necessary conditions to display the output
if (num1 + num2) > 255 :
print("The binary addition cannot exceed 255.Try again!")
check1 = "no"
check2 = "no"
else:
check3 = "yes"
return[num1,num2] #returning the list of two numbers
| true |
3cb28aa56ecac6a50a4ca3ac77a6a364d228011b | noeldjohnson/Guttag-2013-Finger-Exercises | /Finger_2.1.py | 1,004 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 9 15:35:16 2019
@author: astoned
"""
#Finger exercise: Write a program that examines three variables— x , y , and z —
#and prints the largest odd number among them. If none of them are odd, it
#should print a message to that effect.
#Method allows for negative numbers with
#knowledge up to Chapter 2.2
x, y, z = -11, 4, -9
text = 'The greatest odd value is'
if x%2 == 0 and y%2 == 0 and z%2 == 0:
print('There is no odd number')
elif x%2 != 0 and y%2 != 0 and z%2 != 0:
print(text, max(x,y,z))
elif x%2 != 0 and y%2 != 0 and z%2 == 0:
print(text, max(x,y))
elif x%2 != 0 and y%2 == 0 and z%2 != 0:
print(text, max(x,z))
elif x%2 != 0 and y%2 == 0 and z%2 == 0:
print(text, x)
elif x%2 == 0 and y%2 != 0 and z%2 != 0:
print(text, max(y,z))
elif x%2 == 0 and y%2 == 0 and z%2 != 0:
print(text, z)
elif x%2 == 0 and y%2 != 0 and z%2 == 0:
print(text, y) | true |
d02954b8c2c7a3b6821e5c79b2c2def7b8516059 | noeldjohnson/Guttag-2013-Finger-Exercises | /Finger_4.1.py | 663 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 14 18:42:29 2019
@author: astoned
"""
# =============================================================================
#
# Finger exercise: Write a function isIn that accepts two strings as arguments
# and returns True if either string occurs anywhere in the other, and False
# otherwise. Hint: you might want to use the built-in str operation in .
#
# =============================================================================
def isIn(string1, string2):
return bool(string1 in string2 or string2 in string1)
word1 = 'abc'
word2 = 'abcdef'
test = isIn(word1, word2)
print(test) | true |
9dc1b3b85ff6ce7505e7d8891afc2630d8d53115 | Gunjankushwaha/hackthon2 | /ng tim.py | 1,558 | 4.15625 | 4 | # time=int(input("enter the tim")
# if time>="6:00" or time<=
# if time>="6:00" or time<="7:00":
# print("morning excecied")
# time=int(input("enter the time"))
# if time=="9:00" or time=="12:00":
# print("caoding time")
# time=int(input("enter the time")
# if
# print("right time")
# else:
# print("ok")
# else:
# print("right time")
# else:
# print("not morning excecide")
# Savet he correct code in a new file and submit it.
# day==input("enter the day")
# time=input("enter the time")
# if day=="monday":
# time="brekfast":
# print("sabji roti")
# elif time=="lunch":
# print("dal chavl")
# elif time="dinner":
# print("poory")
# else:
# print("samer")
# else:
# print("error")
# day=input("enter the day")
# time=input("enter the time")
# if day=="monday":
# if time=="brekfast":
# print("sabji roti")
# elif time=="lunch":
# print("dal chavl")
# elif time=="dinner":
# print("poory")
# else:
# print("samer")
# else:
# print("error")
# day=input("enter the day:")
# time =input("enter the time:")
# if day=="monday":
# time=input("enter the time:")
# if time=="breakfast":
# print("poha")
# elif time=="lunch":
# print("dal chavl")
# elif time=="dinner":
# print("roti sabji")
# else:
# print("pav bhaji")
# else:
# print("error")
| true |
b661453f1afa18a2db514db603c6a17cc19fea0d | UrsidaeWasTaken/Daily-Coding-Problems | /Python/MarioSavePrincessOriginal.py | 1,638 | 4.1875 | 4 | # Problem
"""
Princess Peach is trapped in one of the four corners of a square grid. Mario is in the center of the grid and can move one step at a time in any of the four directions.
The goal to get Mario to the princess in as few moves as possible.
Print out the moves Mario will need to take to rescue the princess in one go. The moves must be separated by '\n', a newline. The valid moves are LEFT or RIGHT or UP or DOWN. The grid size is always odd.
Example:
---
-m-
p--
DOWN
LEFT
"""
# Solution
def displayPathtoPrincess(n,grid):
path = ""
if grid[0][0] == "p":
path += "UP\nLEFT\n" * ((n-1)//2)
elif grid[0][n-1] == "p":
path += "UP\nRIGHT\n" * ((n-1)//2)
elif grid[n-1][0] == "p":
path += "DOWN\nLEFT\n" * ((n-1)//2)
elif grid[n-1][n-1] == "p":
path += "DOWN\nRIGHT\n" * ((n-1)//2)
return path
# Explaination
"""
The princess is always located in one of the four corners of the grid, and you start in the middle. Therefore, we only ever have 4 possible paths. The path we go to depends on which corner the princess is in.
"""
# Results
test_inputs = [
(3, ["---", "-m-", "p--"]),
(5, ["p----", "-----", "--m--", "-----", "-----"]),
(7, ["-------", "-------", "-------", "---m---", "-------", "-------", "------p"])
]
test_outputs = [
"DOWN\nLEFT\n",
"UP\nLEFT\nUP\nLEFT\n",
"DOWN\nRIGHT\nDOWN\nRIGHT\nDOWN\nRIGHT\n"
]
for (test_input, test_output) in zip(test_inputs, test_outputs):
result = displayPathtoPrincess(test_input[0],test_input[1])
print(*test_input[1], sep='\n')
print(f'\n{result}{result == test_output}\n') | true |
33e2e345273955b1ac7f6ec8f3da92c8a3e480dc | DanMeloso/python | /Exercicios/ex072.py | 670 | 4.15625 | 4 | #Exercício Python 072: Crie um programa que tenha uma dupla totalmente preenchida com uma contagem por extenso,
#de zero até vinte. Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso.
numero = ('Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Quatorze',
'Quinze', 'Dezesseis', 'Dezesete', 'Dezoito', 'Dezenove', 'Vinte')
n = int(input('Digite um número entre 1 e 20: '))
while not (n >= 0 and n < 21):
n = int(input('Opção Inválida. Digite um número entre 1 e 20: '))
if n > 0:
n = n - 1
print(f'Você digitou o número {numero[n]}') | false |
dfcbfbeabab7ea29261f993ee77623207de666b2 | DanMeloso/python | /Exercicios/ex028.py | 607 | 4.375 | 4 | #Exercício Python 028: Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5
#e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador.
#O programa deverá escrever na tela se o usuário venceu ou perdeu.
import random
print('='*5, 'EXERCÍCIO 28', '='*5)
rand = random.randint(0, 5)
numero = int(input('Eu gerei um número entre 0 e 5. Você pode advinhar? '))
if rand == numero:
print(f'Uau! Você acertou!\nNúmero {rand}')
else:
print(f'Que pena pra você. Dessa vez eu venci.\nEu tinha pensando no número {rand}')
print('--FIM--')
| false |
2a5d99114d1890003b3de75c9fa24568e60743e6 | DanMeloso/python | /Exercicios/ex037.py | 540 | 4.1875 | 4 | #Escreva um programa que leia um numero inteiro qualquer e peça para o usuário escolher qual será a base de conversão:
# 1 para BINÁRIO
# 2 para OCTAL
# 3 para HEXADECIMAL
numero = int(input('Informe um número: '))
op = int(input('DIGITE\n1 para Binário\n2 para Octal\n3 para Hexadecimal '))
if op == 1:
print(f'O número {numero} em Binário é: ')
elif op == 2:
print(f'O número {numero} em Octal é: ')
elif op == 3:
print(f'O número {numero} em Hexadecimal é: ')
else:
print('Opção de conversão inválida') | false |
1a3e23ea9f163e0d4dc609283f751b2625d6dcd8 | BitBitcode/Python-Lab | /基础课程/条件结构.py | 1,991 | 4.1875 | 4 | #-*- coding: utf-8 -*-
# 自己练习研究
print("自己练习研究")
i = 3
if i>5:
print("1") # 冒号后不能没有缩进的代码,如果不缩进,则本行错误
print("缩进")
print("正常") # 不缩进的行出现代表if判断后执行的代码已经结束,不能再有缩进的代码,如果不缩进,则本行错误
print("Kiana") # 不缩进的代码相当于 else ...
#(1)if的基础功能
print("(1)if的基础功能")
age = 20
if age >= 18:
print('your age is', age)
print('adult')
# 根据Python的缩进规则,如果if语句判断是True,就把缩进的两行print语句执行了,否则,什么也不做。
#(2)if...else...
print("(2)if...else...")
age = 3
if age >= 18:
print('your age is', age)
print('adult')
else:
print('your age is', age)
print('teenager')
# 如果if判断是False,不要执行if的内容,去把else执行了
#(3)elif实现多个分支
print("(3)elif实现多个分支")
age = 20
if age >= 6:
print('teenager')
elif age >= 18:
print('adult')
else:
print('kid')
#(4)input输入后转换数据类型的问题
print("(4)input输入后转换数据类型的问题")
s = input('birth: ')
birth = int(s)
if birth < 2000:
print('00前')
else:
print('00后')
# 因为input()返回的数据类型是str,str不能直接和整数比较,必须先把str转换成整数。Python提供了int()函数来完成这件事情
#(5)BMI指数计算
print("(5)BMI指数计算")
w = input("请输入体重(/kg):")
h = input("请输入身高(/cm):")
weigh = int(w)
high = int(h)
#BMI计算方法:体重除以身高的平方
BMI = weigh/((high/100)*2)
print("你的BMI指数为:",BMI)
if BMI<=18.5 :
print("属于:过轻")
elif BMI>18.5 and BMI<=25:
print("属于:正常")
elif BMI>25 and BMI<=28:
print("属于:过重")
elif BMI>28 and BMI<=32:
print("属于:肥胖")
else:
print("属于:过度肥胖") | false |
e3f98f66d8590048b95cd273c6e936b4b9db3baa | CP1401/Practicals | /prac_06/example.py | 1,504 | 4.4375 | 4 | """
CP1401 - Example program for Practical 6 - Functions
BMI calculation example
"""
def main():
# height = float(input("Height (m): "))
# weight = float(input("Weight (kg): "))
height = get_valid_number("Height (m): ", 0, 3)
weight = get_valid_number("Weight (kg): ", 0, 300)
bmi = calculate_bmi(height, weight)
category = determine_weight_category(bmi)
print(f"This BMI is {bmi}, which is considered {category}")
def get_valid_number(prompt, low, high):
number = float(input(prompt))
while number < low or number > high:
print("Invalid input")
number = float(input(prompt))
return number
def calculate_bmi(height, weight):
return weight / (height ** 2)
def determine_weight_category(bmi):
# Note that we don't use the if, elif, else pattern here
# because we return, making "elif" and "else" redundant
if bmi < 18.5:
return "underweight"
if bmi < 25:
return "normal"
if bmi < 30:
return "overweight"
return "obese"
def run_tests():
bmi = calculate_bmi(2, 60)
print(bmi) # This should be 15.0
bmi = calculate_bmi(1.5, 100)
print(bmi) # This should be 44.4
print(determine_weight_category(16)) # This should be underweight
print(determine_weight_category(25)) # This should be overweight
height = get_valid_number("Height (m): ", 0, 3)
print(height)
weight = get_valid_number("Weight (kg): ", 0, 300)
print(weight)
# main()
# run_tests()
| true |
0a6dd033838fea5059be73a84e7b75782859cbdb | BekBrace/PYTHON_OOP_XYZ_COMPANY | /app.py | 608 | 4.15625 | 4 | #!/usr/bin/env Python3
"""
app.py - XYZ, Tokyo - JAPAN
This program allows me to manage my employees.
@author:Amir Bekhit
@version1.0 - 06.03.2020
"""
def main():
employees = []
for i in range(2):
print('employee information')
name = input('Enter Name : ')
empId = input('Enter ID: ')
department = input('Enter department: ')
employees.append([name, empId, department])
for x in range(len(employees)):
print('Company Employee')
for y in range(len(employees[x])):
print(employees[x][y])
if __name__ == "__main__":
main()
| false |
a1d231022c619a945cf2530756427c70974f0f8a | Narvienn/CodingWithIK | /Crafting A Library.py | 2,197 | 4.5 | 4 | """Create a Library class for a library that will store books. A book can have a name, ISBN number and the author
- author should be defined in a separate class.
Extras:
1) do a while loop that will add a book to the library
2) display a list of books with their names and authors (in brackets)
EXTRA:
1. napisz metodę która usunie z biblioteki książkę o podanym indeksie
2. napisz metode która usunie z biblioteki książkę o podanej nazwie
3. napis metodę która zwróci książki z biblioteki o isbn większym niż nr podany w argumencie
zadanie ekstra:
spróbuj stworzyć formularz dodawania książek np. def get_book_from_user() który
- pobierze informacje potrzebne do stworzenia obiektu Book
- stworzy obiekt klasy Book z podanymi informacjami
- zwróci obiekt book
"""
class Library():
books = None
def __init__(self, name, isbn):
self.books = []
self.name = name
def print_books(self, books):
print(books)
def add_books(self, book):
self.books.append(book)
def get_books(self):
return self.books
class Author():
author = ""
def __init__(self, name):
self.name = name
class Book():
book = []
def __init__(self, name, isbn):
self.name = name
self.isbn = isbn
def add_author(self, author):
self.book.append(author)
return author
author1 = Author("Stef Maruch")
author2 = Author("Ursula K. Le Guin")
item1 = Book("Python for Dummies", "ISBN1234",).add_author(author1)
item2 = Book("The Telling", "ISBN2345").add_author(author2)
item3 = Book("Left Hand of Darkness", "ISBN3456").add_author(author2)
# local_library = Library("MSC Library") --> jeśli to odkomentować, pętla for głupieje...?
local_library = [item1, item2, item3]
# 2) displaying books in library
for book in local_library:
del book[1] # 0 - name, 1 - isbn, 2 - author
print(book) # jak wrzucić autora w nawias...?
"""
# 1) pętla while, w której będzie się dodawać książkę
answer = input("Would you like to donate a book to the library? Y/N")
while answer == "Y":
# inputy od usera + wywołanie funkcji add_books, ale na czym i jak przekazać toto do books"""
| false |
548790c0ea5321df40ae254e6996293bc6353326 | anantbarthwal/pythonCodes | /lecture2/dictionary.py | 518 | 4.15625 | 4 | dict1 = {'Subject': 'computer science', 'class': 12}
"""
print(dict1['Subject'])
print("dic1[class]", dict1['class'])
student1 = {'name': 'abhishek', 'class': 12, 'school': 'DIS'}
print(student1['school'])
schoolName = student1['school']
print(schoolName)"""
for i in dict1:
print(dict1[i])
dict1['class'] = 11
print("dict1['class'] = ", dict1['class'])
print("len(dict1)= ", len(dict1))
str1 = str(dict1)
print(str1)
print(str1[2])
print(dict1.items())
print(dict1.values())
print(dict1.keys())
| false |
1bc6de4143d1b4bd80e9c01e31352e41d04e0543 | jgrt/programming-problems | /programs/mathematics/problem2/solution.py | 633 | 4.15625 | 4 | """
https://practice.geeksforgeeks.org/problems/series-ap/0
Given the first 2 terms A and B of an Arithmetic Series, tell the Nth term of the series.
Constraints:
-10^3 <= A, B <= 10^3
1 <= N <= 10000
Example:
For A=2, B=3 , Nth = 4 Output will be 5
"""
def arithmetic_progression(a: int, b: int, n: int):
if not (-1000 <= a <= 1000 and -1000 <= b <= 1000):
return 'choose numbers between -1000 to 1000'
if not (1 <= n <= 10000):
return 'choose nth number between 1 to 10000'
d = abs(b) - abs(a)
if d == 0:
return "Both a and b are same"
nth = a + (n - 1) * d
return nth
| true |
fb68556fb9ecbbb1139109d3645b75d8489f9265 | jgrt/programming-problems | /programs/mathematics/problem5/solution.py | 569 | 4.15625 | 4 | """
https://practice.geeksforgeeks.org/problems/print-the-kth-digit/0
Given two numbers A and B, find Kth digit from right of A^B.
Constraints:
1 <= A , B <=15
1 <= K <= |total digits in A^B|
Example:
Input: A = 3, B = 3, K = 1
Output: 7
"""
def find_kth_digit(a: int, b: int, k: int):
if not (1 <= a <= 15 and 1 <= b <= 15 and k >= 1):
return 'Provide positive integer, not neutral integer as 0'
apb = pow(a, b)
if len(str(apb)) < k:
return 'Provide integer 1 and {}'.format(len(str(apb)))
return int(str(apb)[::-1][k-1])
| true |
cf571da2d20f59142f541248a46f28507b23be29 | ilyashlyapin/learnpython | /lesson11/pratice_age.py | 632 | 4.25 | 4 | print('Доброе утро, укажите возраст:')
age = input()
def age_direction(age):
age = int(age)
if age <= 6:
print("Если ваш возраст " + format(age) + ", то Вам пора в садик")
if 7 <= age <= 17:
print("Если ваш возраст " + format(age) + ", то Вам пора в школу")
if 18 <= age <= 23:
print("Если ваш возраст " + format(age) + ", то Вам пора в ВУЗ")
else:
print("Если ваш возраст " + format(age) + ", то Вам пора на работу")
age_direction(age)
| false |
203b30c09b5e34313a6834a14d596762efd3c106 | XIEJD/mySolutions | /Algorithms/剑指offer/offer7.py | 550 | 4.15625 | 4 | # 矩形覆盖(牛客网-剑指offer)
# 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。
# 请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,
# 总共有多少种方法?
def rect_cover(n):
"""
又是斐波那契数列
"""
if n < 0:
return 'Fuck {}.'.format(n)
return n if n <= 3 else rect_cover(n-1) + rect_cover(n-2)
if __name__ == '__main__':
print(rect_cover(1))
print(rect_cover(2))
print(rect_cover(3))
print(rect_cover(4))
print(rect_cover(10))
| false |
aa015656f858e9ee2a48ae4b0bae156eb328528c | andreszohar/momentoDos_Python | /puntoCuatro.py | 1,659 | 4.21875 | 4 | for i in range(2):
class Matricula:
def __init__(self, matricula, nombre, dirrecion, telefono, curso):
self.__matricula = input("numero de matricula : ")
matricula=matricula
self.__nombre = input("nombre : ")
nombre=nombre
self.__dirrecion = input("dirrecion : ")
dirrecion=dirrecion
self.__telefono = input("telefono : ")
telefono = telefono
self.__curso = input("curso : ")
curso=curso
def get_matricula(self):
return self.__matricula
def set_matricula(self, matricula):
self.__matricula = matricula
def get_nombre(self):
return self.__nombre
def set_nombre(self, nombre):
self.__nombre = nombre
def get_dirrecion(self):
return self.__dirrecion
def set_dirrecion(self, dirrecion):
self.__dirrecion = dirrecion
def get_telefono(self):
return self.__telefono
def set_telefono(self, telefono):
self.__telefono = telefono
def get_curso(self):
return self.__curso
def set_curso(self, curso):
self.__curso = curso
print()
p1 = Matricula("","","","","")
print()
print('Datos del alumno ')
print()
print("Numero de matricula : "+p1.get_matricula())
print("Nombre del alumno : "+p1.get_nombre())
print("Dirrecion del alumno : " + p1.get_dirrecion())
print("Telefono del alumno : " + p1.get_telefono())
print("Esta en el curso : " + p1.get_curso()) | false |
836dbd44b886d82c5445fc43e7c08860b2116e08 | orhanavan/PythonMailService | /python_training6.py | 496 | 4.1875 | 4 | # string substitution
str_a = "This is a {var} string"
print(str_a)
str_b = str_a.format(var = "really really cool")
print(str_b)
# multiple string substitution
str_d = "These arguments are :{0} {1} {2}".format("one","two","three")
print(str_d)
# string type casting
str_c = str(123)
# another string substition
print("Hi there %s !" %("Justin"))
# date substitution
import datetime
today = datetime.date.today()
print(today)
now = datetime.datetime.now()
print(now)
| true |
1269d1a3c941663adf0adf07bfe336d14b888ef4 | Meghkh/dicts-restaurant-ratings | /ratings.py | 1,833 | 4.15625 | 4 | """Restaurant rating lister."""
def display_menu():
""" Displays options for user interaction and takes input
"""
print "Please select an option: "
print "1 - Display restaurant and ratings"
print "2 - Add new restaurant and rating"
print "3 - Quit program"
user_choice = raw_input("-->")
def print_sorted_dictionary(restaurant_dict):
""" Print formatted dictionary
"""
for key, value in sorted(restaurant_dict.items()):
print "{} is rated at {}.".format(key, value)
def get_restaurant_from_user(restaurant_dict):
""" Returns a dictionary with new input from user added.
"""
input_resturant = raw_input("Please enter new restaurant name: ").title()
input_rating = raw_input("Please enter restaurant rating: ")
while not input_rating.isdigit():
input_rating = raw_input("Please enter restaurant rating (from 0 to 10): ")
restaurant_dict[input_resturant] = input_rating
return restaurant_dict
def read_and_parse_data(data_file):
""" Opens file, reads and parses data, and returns a dictionary.
"""
scores_list = open(data_file)
ratings_dictionary = {}
for line in scores_list:
# strip, split and unpack into descriptive variables
restaurant_name, restaurant_rating = line.rstrip().split(":")
# add key and value pairs to ratings dictionary
ratings_dictionary[restaurant_name] = restaurant_rating
scores_list.close()
return ratings_dictionary
def run_program():
""" Runs program for complete restaurant/rating experience
"""
new_dict = {}
while True:
user_decision = display_menu
new_dict = read_and_parse_data("scores.txt")
new_dict = get_restaurant_from_user(new_dict)
print_sorted_dictionary(new_dict)
run_program()
| true |
55d7d4a32f97575adbfdc828dd8d7b1e4bf41ed3 | Tsdevendra1/Python-Design-Patterns | /Behavioural/Command.py | 1,927 | 4.40625 | 4 | """
Why: Its callbacks, but you encapsulate the call back in a class so that you already have all the information required to execute it at any given time. The
thing calling the call back also doesn't need to know what information the call back requires.
Example: You have a stock order executor class. It can call .execute() on any stock order. But the executor doesn't need to know if its a build or sell stock order.
It can call the stock orders at any given time
"""
from abc import ABC, abstractmethod
from typing import Optional
class CommandInterface(ABC):
@abstractmethod
def execute_command(self):
pass
class ConcreteCommand(CommandInterface):
def __init__(self, required_data_for_command: str):
self.__data = required_data_for_command
def execute_command(self):
print(self.__data)
class CommandExecutor:
__before_start_operation: Optional[CommandInterface]
__after_operation_end: Optional[CommandInterface]
def set_before_operation_starts_command(self, command: CommandInterface):
self.__before_start_operation = command
def important_operation(self):
before = self.__before_start_operation
after = self.__after_operation_end
if before is not None:
before.execute_command()
# IMPORTANT STUFF HAPPENS HERE...
if after is not None:
after.execute_command()
def set_after_operation_end_command(self, command: CommandInterface):
self.__after_operation_end = command
def main():
executor = CommandExecutor()
command_1 = ConcreteCommand(required_data_for_command="Hello")
command_2 = ConcreteCommand(required_data_for_command="Context unaware")
executor.set_before_operation_starts_command(command=command_1)
executor.set_after_operation_end_command(command=command_2)
executor.important_operation()
if __name__ == "__main__":
main()
| true |
367c247d3c2b6d0da397c3be4127ac4ceb632808 | Tsdevendra1/Python-Design-Patterns | /Creational/Builder.py | 1,093 | 4.125 | 4 | """
Why: You want to initiate/setup a complex class with a simple interface.
Example: You want to build a query, querying certain aspects
"""
from __future__ import annotations
class QueryOperation:
def __init__(self, something_useful_for_the_query: str):
self._property = something_useful_for_the_query
class Query:
_operations: [QueryOperation]
def __init__(self, operations: [QueryOperation]):
self._operations = operations
def run(self):
print(self._operations)
class QueryBuilder:
_operations: [QueryOperation] = []
def add_some_operation1(self, data: str) -> QueryBuilder:
self._operations.append(QueryOperation(data))
return self
def add_some_operation2(self, data: str) -> QueryBuilder:
self._operations.append(QueryOperation(data))
return self
def build(self) -> Query:
return Query(operations=self._operations)
def main():
query = QueryBuilder().add_some_operation1("data").add_some_operation2("data 2").build()
query.run()
if __name__ == "__main__":
main()
| true |
b207c5fdce446969a5583be1c0584d05e6826928 | anantkaushik/leetcode | /1134-armstrong-number.py | 800 | 4.125 | 4 | """
Problem Link: https://leetcode.com/problems/armstrong-number/
The k-digit number N is an Armstrong number if and only if the k-th power of each digit sums to N.
Given a positive integer N, return true if and only if it is an Armstrong number.
Example 1:
Input: 153
Output: true
Explanation:
153 is a 3-digit number, and 153 = 1^3 + 5^3 + 3^3.
Example 2:
Input: 123
Output: false
Explanation:
123 is a 3-digit number, and 123 != 1^3 + 2^3 + 3^3 = 36.
Note:
1 <= N <= 10^8
"""
class Solution:
def isArmstrong(self, N: int) -> bool:
temp = N
newN = 0
length = 0
while temp:
length += 1
temp //= 10
temp = N
while temp:
newN += (temp%10)**length
temp //= 10
return N == newN
| true |
146d2cdb9ada67395a7745be685c951a631495a9 | anantkaushik/leetcode | /310-minimum-height-trees.py | 2,427 | 4.15625 | 4 | """
Problem Link: https://leetcode.com/problems/minimum-height-trees/
A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words,
any connected graph without simple cycles is a tree.
Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates
that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root.
When you select a node x as the root, the result tree has height h. Among all possible rooted trees,
those with minimum height (i.e. min(h)) are called minimum height trees (MHTs).
Return a list of all MHTs' root labels. You can return the answer in any order.
The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
Example 1:
Input: n = 4, edges = [[1,0],[1,2],[1,3]]
Output: [1]
Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
Example 2:
Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
Output: [3,4]
Example 3:
Input: n = 1, edges = []
Output: [0]
Example 4:
Input: n = 2, edges = [[0,1]]
Output: [0,1]
Constraints:
1 <= n <= 2 * 104
edges.length == n - 1
0 <= ai, bi < n
ai != bi
All the pairs (ai, bi) are distinct.
The given input is guaranteed to be a tree and there will be no repeated edges.
"""
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n == 1:
return [0]
graph = {}
for edge in edges:
if edge[0] not in graph:
graph[edge[0]] = set()
if edge[1] not in graph:
graph[edge[1]] = set()
graph[edge[0]].add(edge[1])
graph[edge[1]].add(edge[0])
leaves = {node for node, child in graph.items() if len(child) == 1}
# eat the leaves approach
while n > 2:
n -= len(leaves)
new_leaves = set()
for leave in leaves:
node = graph[leave].pop()
graph[node].remove(leave)
if len(graph[node]) == 1:
new_leaves.add(node)
leaves = new_leaves
# atmost two roots in case of even number of nodes and one root in case of odd number od nodes
return list(leaves)
| true |
92d34a3d6792062dc87af83efbec9ce90f01c7c1 | anantkaushik/leetcode | /1640-check-array-formation-through-concatenation.py | 1,878 | 4.125 | 4 | """
Problem Link: https://leetcode.com/problems/check-array-formation-through-concatenation/
You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct.
Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i].
Return true if it is possible to form the array arr from pieces. Otherwise, return false.
Example 1:
Input: arr = [85], pieces = [[85]]
Output: true
Example 2:
Input: arr = [15,88], pieces = [[88],[15]]
Output: true
Explanation: Concatenate [15] then [88]
Example 3:
Input: arr = [49,18,16], pieces = [[16,18,49]]
Output: false
Explanation: Even though the numbers match, we cannot reorder pieces[0].
Example 4:
Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]]
Output: true
Explanation: Concatenate [91] then [4,64] then [78]
Example 5:
Input: arr = [1,3,5,7], pieces = [[2,4,6,8]]
Output: false
Constraints:
1 <= pieces.length <= arr.length <= 100
sum(pieces[i].length) == arr.length
1 <= pieces[i].length <= arr.length
1 <= arr[i], pieces[i][j] <= 100
The integers in arr are distinct.
The integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).
"""
class Solution:
def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:
indexes = {arr[i]: i for i in range(len(arr))}
for piece in pieces:
prev_index = None
for element in piece:
cur_index = indexes.get(element)
if (prev_index is not None and cur_index != prev_index + 1) or cur_index is None:
return False
prev_index = cur_index
indexes[element] = None
return True
| true |
8a6100b20236b082536a8a2732169ebd40a72aaf | anantkaushik/leetcode | /020-valid-parentheses.py | 859 | 4.125 | 4 | """
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
"""
class Solution:
def isValid(self, s: str) -> bool:
stack = []
d = {
')': '(',
'}': '{',
']': '['
}
for c in s:
if c in d.values():
stack.append(c)
elif (not stack) or (stack.pop() != d[c]):
return False
return len(stack) == 0
| true |
7aa9fcc2f7cf8793a63db5413a30190ec9cb934c | 3to80/Algorithm | /LeetCode/Leet#344/Leet#344.py | 553 | 4.15625 | 4 | # Write a function that takes a string as input and returns the string reversed.
#
# Example:
# Given s = "hello", return "olleh".
#java의 STRING BUILDER같은게 있을 까
class Solution:
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
# Brute
stack = ""
# stack= stack
for i in range(0, len(s)):
stack += s[-1-i]
# stack.append(s[-1-i])
return stack
if __name__ == '__main__':
s = Solution()
print(s.reverseString("qwer")) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.