blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
e2bfd6c98b47ac7f6c8bbcccc7c3a1b16a6468ff | riyankhan/Python-Micro-Projects | /IntegertoBinary.py | 440 | 4.625 | 5 |
#The code is optimized for Python 3
#Following program converts decimal numbers to its binary form
#It only takes input as an integer and not floating value
num = int(input("Enter an integer: "))
decimal_num = num
binary_bits=[]
while num>0:
num, remainder = divmod(num, 2)
binary_bits.append(remainder)
binary_bits= binary_bits[::-1]
print("The Binary coversion of ", decimal_num, " is: ", *binary_bits, sep='')
| true |
585e9014f3f6d6f7faeded007720bc05ddd4c370 | mmiraglio/DailyCodingProblem | /problem2.py | 1,951 | 4.21875 | 4 | # This problem was asked by Uber.
# Given an array of integers, return a new array such that each element at index i of the new array
# is the product of all the numbers in the original array except the one at i.
# For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24].
# If our input was [3, 2, 1], the expected output would be [2, 3, 6]
# Follow-up: what if you can't use division?
import numpy
def my_product_of_all_numbers(data):
"""My solution. (It uses division)"""
prod = numpy.prod(data)
result = [0] * len(data)
for i, value in enumerate(data):
result[i] = prod / value
return result
expected = [120, 60, 40, 30, 24]
assert my_product_of_all_numbers(data=[1, 2, 3, 4, 5]) == expected
expected = [2, 3, 6]
assert my_product_of_all_numbers(data=[3, 2, 1]) == expected
def gfg_product_of_all_numbers(data):
"""Solution found on the Geeks for Geeks site. (It does not use division)"""
""" https://www.geeksforgeeks.org/a-product-array-puzzle/ """
n = len(data)
# Allocate memory for temporary arrays left[] and right[]
left = [0]*n
right = [0]*n
# Allocate memory for the product array
prod = [0]*n
# Left most element of left array is always 1
left[0] = 1
# Rightmost most element of right array is always 1
right[n - 1] = 1
# Construct the left array
for i in range(1, n):
left[i] = data[i - 1] * left[i - 1]
# Construct the right array
for j in range(n-2, -1, -1):
right[j] = data[j + 1] * right[j + 1]
# Construct the product array using
# left[] and right[]
for i in range(n):
prod[i] = left[i] * right[i]
return prod
if __name__ == "__main__":
expected = [120, 60, 40, 30, 24]
assert gfg_product_of_all_numbers(data=[1, 2, 3, 4, 5]) == expected
expected = [2, 3, 6]
assert gfg_product_of_all_numbers(data=[3, 2, 1]) == expected
| true |
e5755f832cdf6543f9df82ab58f0d3ae24c24473 | SergFrolov/basics | /classes/cars.py | 2,368 | 4.59375 | 5 | # 03/28/2021 OOP
# Class and Objects
# Chapter 9
# don't put anything executable in a specifically class file
class Car:
"""This class describes model of the car"""
def __init__(self, brand, model, color):
"""this is a constructor, with required parameters."""
self.brandofthecar = brand
self.modelofthecar = model
self.colorofthecar = color
self.__odo_reader = 0 # also a gobal variable, but we dont require it to be passed as parameter
# using encapsulation(__odo_reader), to hide data
# from object(users) on the outside
def set_odometer_reader(self, miles: int):
"""will not return anything, will just update the value"""
# input control: check if entered number is a positive integer
if miles > 0:
self.__odo_reader = miles
else:
return 1
def get_description(self):
print(f"Brand of the car: {self.brandofthecar}")
print(f"Model of the car: {self.modelofthecar}")
print(f"Color of the car: {self.colorofthecar}")
print(f"You have {self.__odo_reader} miles on your car")
def drive(self):
"""driving action/ behavior"""
if self.brandofthecar.lower() == 'bmw':
print(f"You are driving FAST car plus no DL!")
else:
print(f"You are driving the car even without DL! isn't it awesome!")
def do_something(self):
print("I want to do something ......")
print("let me drive this car :) ")
self.drive()
#motor = Motorcycle()
#motor.drive()
def greet_user():
print("* hello car enthusiast *")
class ElectricCar(Car):
"""This is child class of Car() class. ElectricCar class inherits from Car class"""
def __init__(self, brand, model, color):
"""this is a constructor, with required parameters."""
# now this is for electric car init
# passing here whatever we received from object/ Increased re-usability
super().__init__(brand, model, color)
self.battery_size = 100
def get_battery_info(self):
print(f"This car has a {self.battery_size}-- kWh battery.")
def get_description(self):
"""This overwrites the parent function"""
super().get_description()
print(f"battery size of the car: {self.battery_size} ")
| true |
539da94c532507e75a1c335e688909dda784da42 | syurskyi/Python_3_Deep_Dive_Part_2 | /Section 4 Iterables and Iterators/45. Sorting Iterables.py | 1,614 | 4.25 | 4 | print('#' * 52 + ' The `sorted()` function will in fact work with any iterable, not just sequences.')
print('#' * 52 + ' Lets try this by creating a custom iterable and then sorting it.')
print('#' * 52 + ' we will create an iterable of random numbers, and then sort it.')
import random
random.seed(0)
for i in range(10):
print(random.randint(1, 10))
import random
class RandomInts:
def __init__(self, length, *, seed=0, lower=0, upper=10):
self.length = length
self.seed = seed
self.lower = lower
self.upper = upper
def __len__(self):
return self.length
def __iter__(self):
return self.RandomIterator(self.length,
seed=self.seed,
lower=self.lower,
upper=self.upper)
class RandomIterator:
def __init__(self, length, *, seed, lower, upper):
self.length = length
self.lower = lower
self.upper = upper
self.num_requests = 0
random.seed(seed)
def __iter__(self):
return self
def __next__(self):
if self.num_requests >= self.length:
raise StopIteration
else:
result = random.randint(self.lower, self.upper)
self.num_requests += 1
return result
randoms = RandomInts(10)
for num in randoms:
print(num)
print('#' * 52 + ' We can now sort our iterable using the `sorted()` method:')
print(sorted(randoms))
print(sorted(randoms, reverse=True))
| true |
58ea8234b6dc3bf14091e615b04b10b88070a65e | Edox93/ACA | /ClassWorks/test.env3.py | 255 | 4.1875 | 4 | user_input = input('insert a one char')
if len(user_input) == 0 and user_input.isalpha():
print("please insert a one character")
else:
if user_input.isupper():
print('your char is upper')
else:
print('your char is under')
| true |
4e2cd138ee3ce67dce78de201ab2ab51a76cede7 | lev-roibak/python | /String_Formatting_Exercise_-_Part_2.py | 477 | 4.40625 | 4 | """
Use the code from the previous exercise and input(), to write a short program that asks the user the following questions:
What is the name of the father?
How many sons he has?
How many daughters he has?
And prints out the answer.
"""
name = input('What is the name of the father? ')
print(name)
sons = input('How many sons he has? ')
print(sons)
daughters = input('How many daughters he has? ')
print(daughters)
print(f"{name.capitalize()} has {sons + daughters} kids.")
| true |
5e8c0781c77471d59b30630054937986f35253e6 | brucemwarren/python-programs | /99bottlesofbeer.py | 1,504 | 4.65625 | 5 | # Program to print out the lyrics to "99 Bottles of Beer (On The Wall)"
#
# The Rules:
#
# If you are going to use a list for all of the numbers, do not manually type them all in. Instead, use a built in
# function.
# Besides the phrase "take one down," you may not type in any numbers/names of numbers directly into your song lyrics.
# Remember, when you reach 1 bottle left, the word "bottles" becomes singular.
# Put a blank line between each verse of the song.
# Project from: https://www.reddit.com/r/beginnerprojects/comments/19kxre/project_99_bottles_of_beer_on_the_wall_lyrics/
def bottles_of_beer(count):
"""
Very simple function that will take a number of bottles of beer and sing the song.
:param count:
:return:
"""
if int(count) == count:
bottles = count
while bottles > 1: # While the count is greater than 1, it will print the lyric, plus a blank line.
print(bottles, "bottles of beer on the wall!", bottles, "bottles of beeeeer! Take one down and pass it around",
(bottles - 1), "bottles of beer on the wall!!!!")
print()
bottles = bottles - 1 # Adjusts the bottle count
else:
# Adjusts the lyrics for the last bottle.
print(bottles, "bottle of beer on the wall!", bottles,
"bottle of beeeeer! Take it down and pass it around, no more bottles of beer on the wall!!!!")
else:
print("Please enter a number")
bottles_of_beer(6)
| true |
50ad8664393244ea519412edccfc616561b3b1e2 | Dhanashreee-9/Python-Assignments | /Day4.api/Assignment1day4.py | 485 | 4.28125 | 4 | str1="What we think we become; we are python programmers."
len(str1)
substring = "we"
index=str1.find(substring,0,7)
index1=str1.find(substring,7,23)
index2=str1.find(substring,23,51)
count = str1.count(substring, 0, 51)
# print index and count
print("The index of first 'we' in string is:", index)
print("The index of second 'we' in string is:", index1)
print("The index of third 'we' in string is:", index2)
print("The count of occurance of 'we' in string is:", count) | true |
f8383d357cb01d27259bb8385418f204c2ddb183 | miguelr22/Lab-Activity-5 | /CSS 225 Lab Activity 5 P2.py | 533 | 4.5 | 4 | #Miguel Rodriguez
#February 25,2021
#Lab Activity 5 Problem 2
#Write a program that:
#• Imports the Turtle module
#• Creates a turtle and gives it a name
#• Gets a color from the user using the input() function
#• Uses a for loop and the Turtle module to draw a square in that color.
# ◦ Remember: Every angle inside a square is 90°.
import turtle
Mig= turtle.Turtle()
black=input("What color do you want?")
Mig.pencolor(black)
for side in range(4):
Mig.forward(50)
Mig.right(90)
| true |
c8fa988356b8b1e2561b00f7f6067acde707398c | momentum-team-5/examples | /python-examples/scratch/scratch_10_08_sets.py | 1,855 | 4.1875 | 4 | # Sets
students = {"Will", "Tom", "Nathan", "Kim", "Charlette", "Phil", "Jon", "Babacar"}
students.add("Clinton")
students.add("Hobbes")
students.remove("Clinton")
# Generators
def numbergen(start, stop):
for n in range(start, stop):
yield n
# demonstrating usage of generator
# for i in numbergen(0, 20):
# print(i)
# Comprehensions
# How would I create a list of numbers between 0 and 9
# Option 1: using functions
with_functions = list(range(10))
# print("Using a function:")
# print(with_functions)
# Option 2: using a for loop. This is the most general
with_loop = []
for i in range(10):
with_loop.append(i)
# print("Using a loop:")
# print(with_loop)
# Option 3: Using a comprehension
with_comprehensions = [i for i in range(10)]
# print("Using comprehehnsions:")
# print(with_comprehensions)
# You can use an arbitrary expression in the first part of a list comprehension
squares_with_comprehensions = [i**2 for i in range(10)]
# print(squares_with_comprehensions)
squares_with_functions = list(map(lambda x: x**2, range(10)))
squares_with_loops = []
for i in range(10):
square = i**2
squares_with_loops.append(square)
# You can filter results by including an if statement after the for statement
even_squares = [i**2 for i in range(20) if i**2 % 2 == 0]
# print(even_squares)
# You can create generator comprehensions as well by surrounding comprehension expression with parentheses
even_squares_gen_comp = (i**2 for i in range(20) if i**2 % 2 == 0)
for s in even_squares_gen_comp:
print(s)
# You can also create generator comprehensions by using a comprehension expression wherever a sequence is desired
students_names = ["Will", "Derek", "Phil", "Babacar", "Charlette", "Jon", "Nathan", "Kim", "Tom"]
students_names_lengths = set(len(s) for s in students_names)
print(students_names_lengths) | true |
0213dfed3e7ecfec31e18e14f57565848129b9e9 | wangxinhui/python-for-novice | /lesson-4/lesson-4-5.py | 682 | 4.15625 | 4 | # 元组
# 列表非常适合用于存储在程序运行期间可能变化的数据集。列表是可以修改的,这对处理网站的用户列
# 表或游戏中的角色列表至关重要。然而,有时候你需要创建一系列不可修
# 改的元素,元组可以满足这种需求。 Python 将不能修改的值称为不可变的 ,而不可变的列表被称为
# 元组 。
dimensions = (100,120)
# dimensions[0] = 123
print(dimensions)
# 虽然不能修改元组的元素,但可以给存储元组的变量赋值。因此,如果要修改前述矩形的尺寸,可重新定
# 义整个元组
dimensions =(123,333,233)
print(dimensions)
for dim in dimensions:
print(dim) | false |
abc1a08c14748f75af3111b4a7b423b38652a708 | wangxinhui/python-for-novice | /lesson-6/lesson-6-3.py | 881 | 4.28125 | 4 | # 遍历字典
user_0 = {
'username': 'efemi',
'first': 'entico',
'last': 'efemi',
}
for key,value in user_0.items():
print("\nkey: " + key)
print("value:" + value)
favorite_languages = {
'jen': 'python',
'Wang Xin Hui': 'java',
'lily': 'C',
'lucy': 'python'
}
friends = ['lucy', 'lily']
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print("Hi " + name.title()
+ ",I see your favorite language is " + favorite_languages[name].title() + ".")
if 'erin' not in favorite_languages.keys():
print("Erin,please take our poll !")
# 按顺序遍历字典中的所有键
for name in reversed(sorted(favorite_languages.keys())):
print(name.title() + " thank you for taking the poll.")
for name in favorite_languages.values():
print(name.title() + " thank you for taking the poll.")
| true |
7865ee46fcf3671cea7bda25497adf4c8f9c53f4 | A01252512/EjerciciosPrepWhile | /assignments/SumaNConsecutivos/src/exercise.py | 473 | 4.125 | 4 | #Escribe un método que reciba un número entero positivo n, después debe calcular la suma 1+2+3+...+n. Finalmente regrese el resultado de la suma y sea impreso en pantalla.
#Entrada: Un número entero positivo n
#Salida: El resultado de la suma 1+2+3...+n
def main():
#escribe tu código abajo de esta línea
n = int(input('Número: '))
i = 1
suma = 0
while i <= n:
suma += i
i+=1
print(suma)
if __name__=='__main__':
main()
| false |
9f0c0c2c6e45c6833ddd67747c3feb420455070f | pmheintz/Python3 | /conditionals.py | 378 | 4.28125 | 4 | x = 2
y = 20
if x == 1:
print("X is equal to 1")
elif x == 2:
print("X is equal to 2")
elif x == 3:
print("X is equal to 3")
else:
print("X is NOT a number from 1-3!")
"""
if x == y:
print("This print statement should not be run")
else:
print("X is NOT equal to Y!")
if y > x:
print("Y is greater than X!")
else:
print("This print statement also should not run")
"""
| true |
23826324cf37b67579847f6725cdfa3a1320672a | kosukach/algorithms-and-data-structures | /sorting/Bubblesort.py | 342 | 4.25 | 4 | def bubbleSort(array):
for i in range(len(array)- 1):
for j in range(len(array) - 1 -i):
if array[j] > array[j+1]:
temp = array[j]
array[j] = array[j + 1]
array[j + 1] = temp
return array
if __name__ == "__main__":
print(bubbleSort([1, 5 ,3, 2, 4, 8, 7])) | false |
32886749515b74ef5af8a8a7d44db70d9f76fa6f | Prasanthan16/Python-learning | /code_3_2.py | 379 | 4.21875 | 4 | print("Welcome to the Roller Coaster")
height = int(input("What's is your height? "))
if height >= 120:
print("You can ride")
age = int(input("what is your age?"))
if age < 18:
print("pay Rs.5 for the ticket")
elif age <= 18:
print("pay Rs.10 for the ticket")
else:
print(" pay Rs.20 for the ticket")
else:
print("you can't ride")
| true |
bd7e71f5d2b123a62d867b352489dc7f1bd6827c | willianjusten/python-para-zumbis | /lista-2/extra-3.py | 206 | 4.1875 | 4 | # -*- coding: utf-8 -*-
# Imprima os numeros pares entre 0 e um numero
# fornecido usando if
num = int(input('Digite um numero: '))
x = 0
while x <= num:
if x % 2 == 0:
print(x)
x = x + 1
| false |
80a117dab883dcfae9b8a743804cca22d0b08430 | codewarriors12/jobeasy-python-course | /lesson_4/homework_4_2.py | 1,072 | 4.125 | 4 | # FUNCTIONS
# Difference
# Write a function, which will calculate the difference of these two numbers
def difference(num_1, num_2):
pass
# Division
# Write a function, which will divide these two numbers
def division(num_1, num_2):
pass
# Function gets random number. If this number is more than ten, return the difference between 100 and this number,
# otherwise return this number multiplied by 10
def function_1(number):
pass
# Your function temerature_convertor gets the temperature in Fahrenheit, convert it to Celsius and return.
# Formula (32°F − 32) × 5/9 = 0°C
def temerature_convertor(fahrenheit_degree):
pass
# Taxi Fare
# In a particular jurisdiction, taxi fares consist of a base fare of $4.00, plus $0.25 for every 140 meters travelled.
# Write a function that takes the distance travelled (in kilometers) as its only parameter and returns the total fare
# as its only result rounded by 2 digits. Write a program that demonstrates the function.
def taxi_fare(distance):
pass
# examples of usage:
# taxi_fare(10) #21.86 | true |
287b857a96e7d9ac80a419a24deb00a7716c7fca | markPVale/py-turtles | /Chap_11_Lists.py | 1,986 | 4.34375 | 4 |
# 1. What is the python interpreters response to the following?
import turtle
print(list(range(10, 0, -2)))
# The three arguments to the range function are start, stop, and step, respectively.
# In this example, start is greater than stop. What happens if start < stop and step < 0?
# Write a rule for the relationships among start, stop, and step.
# >>> If start > stop then step must be a negative number, if start < stop then step must
# be positive or the result is an empty array.
# 2. Consider this fragment of code:
# turtle.setup(400, 500)
# wn = turtle.Screen()
# tess = turtle.Turtle()
# alex = tess
# alex.color("hotpink")
# # wn.mainloop()
# print(tess is alex)
# print(alex is tess)
# Both Tess and Alex refer to the same object, they are aliases of
# turtle.Turle()
# tess is alex >>> True
# alex is tess >>> True
# The name is bound to the object in the current global namespace
# (according to the python documentation)
# 3. Draw a state snapshot for a and b after the third line of the following
# python code is executed:
# a = [1, 2, 3]
# b = a[:]
# c = b[0] = 5
# a is a list consisting of elements: 1, 2, 3
# b is a close of a
# c is a clone of b that mutated the first element in the list (1) to 5
# c now equals [5, 2, 3] while a and b remain the same.
# 4. What will be the output of the following program?
this = ["I", "am", "not", "a", "crook"]
that = ["I", "am", "not", "a", "crook"]
print("Test 1: {0}".format(this is that))
print("Test 1: {0}".format(this == that))
that = this
print("Test 2: {0}".format(this is that))
# Explanation:
# Since lists are mutable, Python doesn't optimize resources by making both variales refer to
# the same object, although they have the same value. So while Test 1 will return False,
# this == that will return True.
# Test 2 however sets the value of that to be this which makes the two variables refer to the
# same object and therefore this is that >>> True.
# REMAINING EXERCISES IN vectors.py file
| true |
3c9a8a54851809d823a4a6b5545b6913f9b962ba | markPVale/py-turtles | /Chap_15_class_and_objects.py | 1,541 | 4.5625 | 5 |
# class Point:
# """ Point class represents and manipulates x, y coords."""
# def __init__(self):
# """ Create a new point at the origin """
# self.x = 0
# self.y = 0
# p = Point()
# q = Point()
# print(p.x, p.y, p.x, p.y)
# The function Point is a constructor, it creates a new object instance.
# The combined process of 'make me a new object' and 'get its settings initialized to the factory
# default settings' is called instantiation.
# We can give default values:
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def to_string(self):
return "({0}, {1})".format(self.x, self.y)
# # # The x and y paramaters are both optional in the code above. If the caller
# # # doesn't supply the arguments, the default value of 0 is used for both;
# p = Point(4, 2)
# q = Point(6, 3)
# r = Point()
# print(p.x, q.y, r.x)
# def print_point(pt):
# print('({0}, {1})'.format(pt.x, pt.y))
# print_point(p)
# Instances as return values
def midpoint(p1, p2):
""" Return the midpoint of points p1 and p2 """
mx = (p1.x + p2.x) / 2
my = (p1.y + p2.y) / 2
return Point(mx, my)
def halfway(self, target):
mx = (self.x + target.x) / 2
my = (self.y + target.y) / 2
return Point(mx, my)
p = Point(3, 4)
q = Point(5, 12)
r = halfway(p, q)
print(r.to_string())
# Exercises
# 1. Rewrite the distance function from the chapter titled Fruitful functions so that it takes two Points as
# parameters instead of four numbers
| true |
d636741f631ebda783600d4f5ffbf90ebd421958 | Nelwell/Capstone-Lab8 | /bitcoin.py | 1,457 | 4.34375 | 4 | import requests
""" Uses api.coindesk.com to get exchange rates """
def main():
dollars = 'USD'
num_bitcoin = get_bitcoin_amount()
converted = convert_btc_to_dollars(num_bitcoin, dollars)
display_result(num_bitcoin, converted)
def get_bitcoin_amount():
""" Get number of Bitcoin """
return float(input('Enter amount of Bitcoin to convert: '))
def convert_btc_to_dollars(num_bitcoin, dollars):
""" Convert amount of bitcoin to USD """
exchange_rate = get_exchange_rate(dollars)
converted = convert(num_bitcoin, exchange_rate)
return converted
def get_exchange_rate(dollars):
""" Call API and extra data from response """
response = request_rates()
rate = extract_rate(response, dollars)
return rate
def request_rates():
""" Perform API request, return response """
coindesk_url = 'https://api.coindesk.com/v1/bpi/currentprice.json'
response = requests.get(coindesk_url).json()
return response
def extract_rate(rate, dollars):
""" Process the JSON response from the API, extract rate data """
return rate['bpi'][dollars]['rate_float']
def convert(num_bitcoin, exchange_rate):
""" Convert using the given exchange rate """
return num_bitcoin * exchange_rate
def display_result(num_bitcoin, converted):
""" Format and display the result """
print(f'{num_bitcoin:.8f} BTC is equivalent to ${converted:.2f}.')
if __name__ == '__main__':
main()
| true |
208114038ad94b7a4345fdc6463f80bedd83b339 | Bedwars-coder/My_Programs | /Python_Programs/starpattern.py | 944 | 4.15625 | 4 | # using for loops
def reruncode():
try:
rows = int(input("How many rows do you want?\n"))
true_false = bool(int(input("Enter 0 or 1\n")))
if true_false == True:
for i in range(1, rows + 1 ):
for j in range(1, i + 1):
print('*',end='')
print()
elif true_false == False:
for i in range(rows, 0, -1):
for j in range(1, i + 1):
print('*',end='')
print()
else:
print("Invalid input\n")
except Exception as error1:
print("Invalid input!! You dumb!!")
choice = input("Do you want to play again?('y' or 'n')?\n")
if choice == 'y':
print("Thanks, for playing game again!")
reruncode()
elif choice == 'n':
exit("Thanks!")
else:
print("Invalid input!! You dumb!!")
reruncode()
| true |
ae2329bb9728e5e3fc521aa57529c25e49f6d184 | edwintcloud/algorithmPractice | /LeetCode/Google/Top Ten/5 - Alien Dictionary/solution.py | 2,278 | 4.25 | 4 | def alien_dict(words):
'''alien_dict finds the alphabetical order of a language derived using a-z
from the first few words that would appear in a dictionary of words for the language'''
# initialize a dictionary to hold the letters than follow each letter in list of words
graph = {}
# initialize 0 filled list of alphabet positions
alphaPositions = [0] * 26
# initialize a queue we will use to sort the letters once we establish relationships
queue = []
# initialize a list we will use to build our result string
result = []
# populate graph with each letter maping to an empty set that will hold relations
for word in words:
for c in word:
graph[c] = set()
# find the letters that follow each letter in our graph
for i in range(1, len(words)):
for j in range(min(len(words[i-1]), len(words[i]))):
if words[i-1][j] != words[i][j]:
if words[i][j] in graph[words[i-1][j]]:
break
graph[words[i-1][j]].add(words[i][j])
# mark each alpha position visited
alphaPositions[ord(words[i][j]) - 97] += 1
# add c in graph to queue if it has not been visited
for c in graph:
if alphaPositions[ord(c) - 97] == 0:
queue.append(c)
# go through queue, building result string
while len(queue) > 0:
c = queue.pop(0)
result.append(c)
# mark neighbors of current queue item as visited,
# if neighbor was previously visited then add it
# to the end of the queue
for neighbor in graph[c]:
alphaPositions[ord(neighbor)-97] -= 1
if alphaPositions[ord(neighbor)-97] == 0:
queue.append(neighbor)
# join result to string and return
return "".join(result)
## TEST ##
tests = [
[
"wrt",
"wrf",
"er",
"ett",
"rftt"
],
[
"z",
"x"
],
[
"z",
"x",
"z"
]
]
for test in tests:
for i, line in enumerate(test, 1):
if i == len(test):
print('"', line, '"]')
else:
print('["', line, '",')
print("The correct order is :", alien_dict(test))
| true |
5c9635fbd4ab5d9fd5ccd0658c20c1f886e870e3 | tpfaeffl/Python_I | /Homework_2/homework_2.py | 2,409 | 4.15625 | 4 | '''
homework_2.py
Get a letter and determine if it is a vowel. Quit if you find a
vowel or if you enter 'quit'.
'''
def AskForLetter():
ask = True
while ask == True:
input_letter = raw_input('''Enter a single letter:
Enter 'quit' to exit.\n''')
if input_letter == 'quit':
ask = False
if input_letter != 'quit' and len(input_letter) == 1:
vowel = IsVowel(input_letter)
if vowel == True:
PrintIsVowel(input_letter)
ask = False
if vowel == False:
PrintIsNotVowel(input_letter)
ask = True
def IsVowel(letter):
# get whether letter is lowercase vowel
lower_case = IsLowerCaseVowel(letter)
# get whether letter is uppercase vowel
upper_case = IsUpperCaseVowel(letter)
if lower_case == True or upper_case == True:
return True
else:
return False
def IsLowerCaseVowel(letter):
#compare input letter to see if it's a lowercase vowel
if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u':
# print 'Function IsLowerCaseVowel: letter is lower case and is a vowel'
return True
else:
# print 'Function IsLowerCaseVowel: letter is either NOT lower case or NOT a vowel'
return False
def IsUpperCaseVowel(letter):
#compare input letter to see if it's an uppercase vowel
if letter == 'A' or letter == 'E' or letter == 'I' or letter == 'O' or letter == 'U':
# print 'Function IsUpperCaseVowel: letter is upper case and is a vowel'
return True
else:
# print 'Function IsUpperCaseVowel: letter is either NOT upper case or NOT a vowel'
return False
def PrintIsVowel(letter):
print "\n The letter entered, " + letter + ", is a vowel.\n"
def PrintIsNotVowel(letter):
print "\n The letter entered, " + letter + ", is NOT a vowel.\n"
# main
AskForLetter()
| true |
c668214935f99730a4cc5edadbb893baba33f3a3 | Charrier/LPTHW | /ex20.py | 987 | 4.375 | 4 | from sys import argv
#defining the arguments used as input from the command line
script, input_file = argv
#defining the print_all function, with f pointing the a file variable that will be read
def print_all(f):
print f.read()
#defining the rewind function: it points to the beginning of the file
def rewind(f):
f.seek(0)
#defining the print_a_line function, once called, it'll
def print_a_line(line_count, f):
print line_count, f.readline()
#opening the file in read mode
current_file = open(input_file)
print "First let's print the whole file:\n"
#printing the whole content of the file previously opened in read mode
print_all(current_file)
print "Now let's rewind, kind of like a tape."
#setting the pointer to 0 in the current_file
rewind(current_file)
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file) | true |
40320759d964f64e8b49d020317a9128797af440 | Amirpatel89/Python | /List exercises.py | 521 | 4.125 | 4 | print (list(range(11)))
print (list(range(2,9)))
numbers = range(1,10)
for i in numbers:
if i%2 == 0:
print i
size = 5
square = (" * * * * * \n" * 5)
print square
print "square part 2:"
print "box"
print('* ' * 6)
print("*" + " " * 9 + "*")
print("*" + " " * 9 + "*")
print('* ' * 6)
print "multiplication table:"
n=int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1,n+1):
for col in range(1,n+1):
print(row*col, end == "144")
| true |
f1ac3b8462e014afec93e9ac366183e1ce7f8498 | yogi1426/Python-the-hard-way | /ex25.py | 899 | 4.1875 | 4 | def break_words(stuff):
return stuff.split(' ')
#return words
def sort_words(words):
return sorted(words)
def print_first_words(words):
print words.pop(0)
#print word
def print_last_word(words):
word = words.pop(-1)
return word
def sort_sentence(sentence):
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
words = break_words(sentence)
print_first_words(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
words = sort_sentence(sentence)
print_first_words(words)
print_last_word(words)
'''
inp = raw_input("Enter String:")
print "Sorted String is:"
print sort_sentence(inp)
print "First and Last word of the string:"
print print_first_and_last(inp)
print "First and last sorted words:"
print print_first_and_last_sorted(inp)
''' | true |
4b052f41a000b71d3ad9106b29ef5df6389ff64c | Oscarvch03/Pygame-Tutorial | /Ejemplos_Events_Turtle/keypress.py | 1,643 | 4.15625 | 4 | import turtle
# "turtle" es una libreria grafica que incluye python, para mas
# informacion consultar la documentacion en el siguiente link...
# "https://docs.python.org/3.3/library/turtle.html?highlight=turtle"
# Creamos la ventana en la que trabajaremos con dimensiones (ancho, alto)
turtle.setup(400, 500)
# Declaramos la ventana como un objeto de tipo "Screen"
window = turtle.Screen()
# Le ponemos un titulo a la ventana
window.title("Keypresses Events!")
# Definimos el color de fondo de la ventana
window.bgcolor("lightgreen")
# Declaramos un objeto de tipo "Turtle"
goku = turtle.Turtle()
# Definimos nuestros "Keypresses Events"
# La tortuga se mueve 30 pixeles hacia donde este apuntando
def mover(): goku.forward(30)
# La tortuga gira 45° a la izquierda
def girarIzq(): goku.left(45)
# La tortuga gira 45° a la derecha
def girarDer(): goku.right(45)
# Cerrar la ventana
def salir(): window.bye()
# Asociamos cada "Keypress Event" con una tecla determinada
# Sintaxis: "ventana".onkey("Keypress Event", "tecla")
# Asociamos el evento mover con la tecla "arriba"
window.onkey(mover, "Up")
# Asociamos el evento girarIzq con la tecla "izquierda"
window.onkey(girarIzq, "Left")
# Asociamos el evento girarDer con la tecla "derecha"
window.onkey(girarDer, "Right")
# Asociamos el evento salir con la tecla "q" en minuscula
window.onkey(salir, "q")
# Siempre que se ejecuten "Keypresses Events", se debe usar
# el comando "ventana".listen() para enlazar los eventos con
# lo que ocurre en la ventana, de otro modo no se ejecutaran
window.listen()
# "ventana".mainloop() hace que la ventana se mantenga abierta
window.mainloop()
| false |
90ff8c923ab8efdaa970a2a47b74f967b2b1c68c | willstauffernorris/hashtables | /applications/histo/histo.py | 2,033 | 4.1875 | 4 | # Your code here
#This function takes a single filename string as an argument
def histogram(filename_string):
#It should open the file, and work through it to produce the output.
with open(filename_string) as f:
words = f.read()
# Print a histogram showing the word count for each word, one hash mark
# for every occurrence of the word.
#create a dict to keep track of this
word_count = {}
## Split string
split_words = words.split()
# iterate through each word
for word in split_words:
#Case should be ignored, and all output forced to lowercase.
word = word.lower()
#Ignore each of the following characters:
word = word.strip('" : ; , . - + = / \ | [ ] { } ( ) * ^ &')
#If the input contains no ignored characters, print nothing.
if word == "":
return ""
if word in word_count:
word_count[word] += '#'
else:
word_count[word] = '#'
#print(split_words)
#sorted(word_count)
# print(word_count)
# sorted_word_counts = sorted(word_count.items()
#sorting it by first the number of ##, then the alphabetical order
sorted_word_counts = sorted(word_count.items(), key=lambda x:x[1] + x[0], reverse=False)
#print(sorted_word_counts)
# Print a histogram showing the word count for each word, one hash mark
# for every occurrence of the word.
# Output will be first ordered by the number of words, then by the word
# (alphabetically).
# The hash marks should be left justified two spaces after the longest
# word.
max_len = 0
for item in sorted_word_counts:
# if len(item)
#print(len(item[0]))
if len(item[0]) > max_len:
max_len = len(item[0])
print(max_len)
# max_len is 15
for pair in sorted_word_counts:
#print(len(pair[0]))
print(pair[0] + ((max_len - len(pair[0])+2) * " ") + pair[1])
# call the function
histogram('robin.txt') | true |
9ba481800b0b8b3d1fd33f1ebffc09b3a3be69bc | apatten001/loops | /for_loops.py | 395 | 4.40625 | 4 |
# for loops allow us to loop through something a set number of times
for x in range(10):
print(x)
# you can loop through list as well
var_1 = "Tiles"
list_1 = [21,54,76,90,"Arnold", var_1]
for y in list_1:
print(y)
# the variable in the for loop can be anything
# the third argument allows you to skip by when you are using range
for pizza in range(1,24,2):
print(pizza)
| true |
5b5730b6e5974fc12fae1f39034188505f6d354a | Jonaz80/PythonProjects | /LearnPythonHardWay/ex12argv.py | 659 | 4.375 | 4 | from sys import argv
# read sys docs, argv is the argument variable for a script's input
#The following line unpacks the command line arguemnts into variables
script, first, second, third = argv
#looks like argv is a list...
print("script name", argv[0])
#add an input line
product = input("what shall i make with these ingredients today ...? ")
print("The script is called", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
# If there is a missing variable the scipt will complain
print(f"Here is a {product} made from {first}, {second} and {third} ...")
| true |
55fd2897328a1ac8fc2e57da8531a75fdec0b940 | chriniko13/python-simple-example | /test_three.py | 1,159 | 4.125 | 4 | # Note: some more examples-plays with lists. Also list comprehensions, generator expressions and lambdas.
import math
import sys
numbers = range(5)
factorials = []
# classic way
for num in numbers:
factorials.append(math.factorial(num))
print(factorials)
# functional way
factorial2 = list(map(math.factorial, range(5)))
print(factorial2)
example = list(map(lambda x: x ** 2, range(4)))
print(example)
# list comprehensions (iterable)
someList = [math.factorial(item) for item in range(5)]
print(someList)
print('sizeof someList:', sys.getsizeof(someList))
# generator expressions (iterator protocol)
print('\n')
someBigList = (math.factorial(item) for item in range(10) if item % 2 != 0)
print('sizeof someBigList:', sys.getsizeof(someBigList))
for x in someBigList:
print(x, '\n')
# filter example
print('\n')
result = list(filter(lambda x: x >= 0, range(-10, 10)))
print(result)
print('\n')
a = [1, 2, 3, 5, 7, 9]
b = [2, 3, 5, 6, 7, 8]
print(list(filter(lambda x: x in a, b)))
result = list(map(pow, [2, 3, 4], [10, 11, 12]))
print(result)
# reduce example
from functools import reduce
print(reduce(lambda x, y: x * y, [1, 2, 3, 4]))
| true |
f132785de9a4f895f0c260f4ffb4e657da54c625 | Eudasio-Rodrigues/Linguagem-de-programacao | /lista aula 06/questao 05.py | 888 | 4.25 | 4 | #Escreva um programa que gere automaticamente uma lista com 40 inteiros e
#faça o que se pede a seguir:
#a- imprima o primeiro quarto da lista
#b -imprima o último quarto da lista
#c -imprima os 5 itens do meio da lista
#d -imprima a lista reversa
#e - Imprima o primeiro e o último item da lista
#Utilize list comprehension para :
#f - Gerar uma lista com o quadrado de cada item da lista original
#g - Gerar uma lista com apenas itens pares da lista original
lista = []
for i in range(0,41):
lista.append(i)
print(f"Lista completa {lista}\n")
print(f"a = {lista[0:10]}\n")
print(f"b = {lista[31:41]}\n")
print(f"c = {lista[18:23]}\n")
print(f"d = {lista}\n")
print(f"primeiro indice {lista[0]} ,ultimo indice {lista[-1]}\n")
lista = [item**2 for item in range(0,41)]
print(f"{lista}\n")
lista = [numero for numero in range(0,41) if numero % 2 == 0]
print(lista)
lista.reverse() | false |
8e530f5c71d24ba70a19241264e2c0ea27879efc | Eudasio-Rodrigues/Linguagem-de-programacao | /Avaliação 03/AV03.py | 2,239 | 4.3125 | 4 | #Eudasio
#Estagio na secretria da escola Pedro Jaime
class Secretaria:
def __init__(self,notas=[]):
self.notas = notas
self.n1=int(input("nota 1: "))
self.n2=int(input("nota 2: "))
self.n3=int(input("nota 3: "))
#metodo da secretaria para adicionar as notas dos alunos no sistema
def adicionar_notas (self):
self.notas.append(self.n1)
self.notas.append(self.n2)
self.notas.append(self.n3)
class Alunos():
def __init__(self):
#entrada de dados do aluno
self.matricula_aluno = int(input("Digite sua matricula: "))
self.nome_aluno = input("Digite seu nome: ")
self.dia_da_semana= input("Que dia é hoje: ")
#verificaçao sobre o dia da semana para saber se tem aula ou é final de semana
def assistir_aula(self):
if self.dia_da_semana == "sabado" or self.dia_da_semana == "domingo":
print("Oba! Hoje vou assistir desenho")
else:
print("ah nao, eu tenho mesmo que ir pra escola mãe?")
#mostra dados do aluno
def mostrar_dados(self):
print(f"nome:{self.nome_aluno}\nmatricula:{self.matricula_aluno}")
class Professores():
def __init__(self):
#pedindo dados para saber se o prfessor ja cumpriu carga horaria
self.dia_trabalhados= int(input("Dias trabalhados: "))
self.dia_letivos = 200
#metodo que verifica se o professor ainda precisa dar aula ou está de ferias
def dar_aulas(self):
if self.dia_trabalhados < self.dia_letivos:
print("Preciso planejar as aulas dessa semana")
else:
print("Finalmente férias")
class Biblioteca:
def __init__(self):
self.livro=input("Qual livro voce quer pegar: ")
def emprestar(self):
self.lista=['HP a pedra filosofal','HP e a camara secreta']
for self.livro in self.lista:
if self.livro not in self.lista:
print("o livro nao está disponivel")
else:
print("Aqui está ele. Voce tem 7 dias para devolver")
aluno = Alunos()
aluno.assistir_aula()
aluno.mostrar_dados()
sec=Secretaria()
sec.adicionar_notas()
prof=Professores()
prof.dar_aulas()
biblioteca=Biblioteca()
biblioteca.emprestar() | false |
7605edcbd6245ae341b8fcdaa6e2db6eec671cd0 | Eudasio-Rodrigues/Linguagem-de-programacao | /lista aula 03/questao 08.py | 284 | 4.1875 | 4 | #Faça uma função que receba uma lista de números inteiros e
#retorne o maior elemento desta lista. Utilize o for.
def maior_numero(numeros):
print(f"O maior numero da lista é {max(numeros)}")
numeros = [int(input("Número: ")) for i in range(5)]
maior_numero(numeros)
| false |
27f98126400d44530ccf69f26ed54f5bed2c045b | chandru-55/python_program | /questions.py | 1,694 | 4.4375 | 4 | '''
# Python If-Else condition
# Task
# Given an integer, n, perform the following conditional actions:
# If n is odd, print Weird
# If n is even and in the inclusive range of 2 to 5, print Not Weird
# If n is even and in the inclusive range of 6 to 20, print Weird
# If n is even and greater than 20, print Not Weird
# Input Format
# A single line containing a positive integer, n.
# Constraints
# 1 <= n <= 100
# Output Format
# Print Weird if the number is weird; otherwise, print Not Weird.
'''
'''
Using for loop : Iterate each element in the list using for loop and check if num % 2 != 0. If the condition satisfies, then only print the number.
2. Using While loop:
3. Using list comprehension :
4. Using lambda function :
'''
'''
the code appearing below shows two nested loops, an outer for loop over the values of i and an inner for loop over the values of j to multiply inside the inner loop all nine elements of a 3x3 matrix A by a factor f that changes according to the outer loop iteration.
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
f = 1
print(A)
for i in range(0, 3):
f *= 10
for j in range(0, 3):
A[i][j] *= f
print(A)
Therefore, the outer loop executes 3 iterations (i equal to 0, 1, and 2), and at each iteration it's executed:
The multiplication of the factor f by 10
The execution of the inner loop that has 3 iterations (j equal to 0, 1, and 2), and at each iteration the element i,j of A is multiplied by f
https://docs.python.org/3/reference/simple_stmts.html#grammar-token-nonlocal-stmt
Maps ands Lambda function
https://www.programiz.com/python-programming/methods/built-in/map
''' | true |
359e78f6b6001244b7f865ae9443651ab6df487a | JiliangLi/CS550W | /montyhall.py | 2,165 | 4.53125 | 5 | # eric li monty hall simulation
# Jan 8, 2019
# it would be better to switch because the chance of having the key behind the other two doors is 2/3.
# in other words the chance of having the key behind my door is 1/3
# when a door holding pennies gets revealed, the chance of having the key behind my door is still 1/3
# so even though now there's only two doors left, the chance is not 50-50
# rather, it should be 1/3 behind my door, and 2/3 behind the other door
# simulation where I don't switch my choice
import random
number = 0
# the revealing part doesn't affect the result because I don't switch my choice afterwards
for x in range(1000):
doors = [0,0,0]
key = random.randrange(3)
doors[key] = 1
choice = random.randrange(3)
if choice == key:
number += 1
print(number)
# simulation where I switch my choice
import random
number = 0
for x in range(1000):
doors = [0,0,0]
key = random.randrange(3)
doors[key] = 1
choice = random.randrange(3)
# if my door holds the key and I switch, I get nothing
if choice == key:
pass
# if my door does not hold the key and the other door holding pennies is revealed, I get the key when I switch my choice to the door that is not revealed
else:
number += 1
print(number)
# when I don't switch my choice, I won 338 times, about 1/3 of 1000
# when I switch my choice, I won 671 times, about 2/3 of 1000
# this is what I expected
# this happens because mathematically speaking revealing the door and switching my choice are not independent events
# in other words, when the host reveals the door he/she do not reveal it randomly
# because although it is true that the host can reveal either of the two doors when the contestant chooses the door holding the key
# the host is only able to reveal one of the two doors (the only one that does not hold the key) when the contestant chooses the door holding pennies
# (the door to be revaeled is dependent upon the door the contestant picks)
# thus this is different from choosing randomly between two options
# it is more like choosing among three options when a hint favoring the contestant is given
# thus the reasoning given at top holds true
| true |
a55ab7dda50f807881371f7bf9c392994904f6c9 | Nu2This/pybites | /8/rotate.py | 326 | 4.3125 | 4 | def rotate(string, n):
"""Rotate characters in a string.
Expects string and n (int) for number of characters to move.
"""
print(string[n:] + string[:n])
return string[n:] + string[:n]
pass
if __name__ == '__main__':
rotate('Penis and vagina', 3)
rotate('Penis and vagina', -3)
| true |
7a169add3ecd165af61ae3ff237645c7a89ed6bb | katylouise/python_the_hard_way | /ex14.py | 904 | 4.3125 | 4 | #use argument variable from sys module
from sys import argv
#unpack variables
script, user_name, age = argv
#user --> as prompt
prompt = '-->'
#print three lines using user variables
print "Hi %s, I'm the %s script. You are %r years old." % (user_name, script, age)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
#display prompt and save input as likes
likes = raw_input(prompt)
#print question using user variable
print "Where to you live %s?" % user_name
#display prompt and save input as lives
lives = raw_input(prompt)
#print question then display prompt and save input as computer
print "What kind of computer do you have?"
computer = raw_input(prompt)
#print multiple lines using inputs from above.
print """
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer)
| true |
0b87faf0058033f6dfb57b39df31b3f2905c394f | katylouise/python_the_hard_way | /ex6.py | 970 | 4.15625 | 4 | #variable x set to a string with a number variable inserted using %d
x = "There are %d types of people." % 10
#variable binary set to a string
binary = "binary"
#variable do_not set to a string
do_not = "don't"
#variable y set to a string containing the two above strings using %s.
y = "Those who know %s and those who %s." % (binary, do_not)
#print x then print y
print x
print y
#print string containing x (which also contains a number variable)
print "I said: %r." % x
#print string containining y - using %s because y only contains strings?
print "I also said: '%s'." % y
#defining variable hilarious as False
hilarious = False
#variable joke_evaluation
joke_evaluation = "Isn't that joke so funny?! %r"
#print joke_evaluation including hilarious variable inside string
print joke_evaluation % hilarious
#variables w and e defined as strings
w = "This is the left side of..."
e = "a string with a right side."
#print w and e as one string (I think)
print w + e | true |
176ad963b621227904b624c1c106939544476459 | matheus-rosario/curso-python | /pythondesafios/desafio009.py | 466 | 4.125 | 4 | #Crie um programa que leia um numero inteiro qualquer e mostre na tela
#a sua tabuada.
n = int(input('Digite um número: '))
print(f'A tabuada do número {n} é a seguinte:')
print('')
print(f'{n} * 1 = {n * 1}')
print(f'{n} * 2 = {n * 2}')
print(f'{n} * 3 = {n * 3}')
print(f'{n} * 4 = {n * 4}')
print(f'{n} * 5 = {n * 5}')
print(f'{n} * 6 = {n * 6}')
print(f'{n} * 7 = {n * 7}')
print(f'{n} * 8 = {n * 8}')
print(f'{n} * 9 = {n * 9}')
print(f'{n} * 10 = {n * 10}') | false |
b57a8f7cbd8edbb31af2adb9391bfcf2b141bf52 | otalu/ToolBox-WordFrequency | /frequency.py | 1,806 | 4.1875 | 4 | """ Analyzes the word frequencies in "The Metamorphosis" by Franz Kafka
downloaded from Project Gutenberg.
Author: Onur, the Incompetent
"""
import string
def get_word_list(file_name):
""" Reads the specified project Gutenberg book. Header comments,
punctuation, and whitespace are stripped away. The function
returns a list of the words used in the book as a list.
All words are converted to lower case.
"""
f = open(file_name, 'r')
lines = f.readlines()
curr_line = 0
while lines[curr_line].find('Copyright (C) 2002 David Wyllie.') == -1:
curr_line += 1
lines = lines[curr_line+1:1995]
for i in range(0, len(lines)):
lines[i] = lines[i][0:len(lines[i])-1]
raw_list = " ".join(lines)
punc_table = " "*len(string.punctuation)
punc_removed = raw_list.translate(str.maketrans(string.punctuation, punc_table))
lowercase = punc_removed.lower()
final_list = lowercase.split()
return final_list
def get_top_n_words(word_list, n):
""" Takes a list of words as input and returns a list of the n most frequently
occurring words ordered from most to least frequently occurring.
word_list: a list of words (assumed to all be in lower case with no
punctuation
n: the number of words to return
returns: a list of n most frequently occurring words ordered from most
frequently to least frequentlyoccurring
"""
histogram = dict()
for word in word_list:
histogram[word] = histogram.get(word, 0)+1
ordered_by_frequency = sorted(histogram.items(), key=lambda x: x[1], reverse=True)
return(ordered_by_frequency[:100])
if __name__ == "__main__":
word_list = get_word_list('metamorphosis.txt')
get_top_n_words(word_list, 100)
# print(get_top_n_words(word_list, 100))
| true |
38ef4a92ab0f9618693515c7d6d3eef39c9290f4 | houxianxu/StanfordAlgorithmPart2 | /week1/assignment1-3.py | 2,518 | 4.34375 | 4 | # Programming Assignment #1-3
# https://class.coursera.org/algo2-002/quiz/attempt?quiz_id=75
# Prim's minimum spanning tree algorithm -- MST
# file describes an undirected graph with integer edge costs.
# It has the format
# [number_of_nodes] [number_of_edges]
# [one_node_of_edge_1] [other_node_of_edge_1] [edge_1_cost]
# [one_node_of_edge_1] [other_node_of_edge_1] [edge_1_cost]
# The task is to run Prim's minimum spanning tree algorithm on this graph.
# You should report the overall cost of a minimum spanning tree.
# Question 3
# it is the naive algrithm which is not use heap data strcture
# the running time is O(m*n)
import random
def build_adjacent_graph (file_name):
""" file -> list of list
Return a list of list which represent the edges for a node
a edges is represented by a tuple which contains three number,
the first two are vertex, the last one is the weight. i.e. (vertex, vertex, weight)
example: [[(0, 2, 100), (0, 6, 1000) ...], [(1, 5, 100), (1, 7, 1000)...] ...]
"""
input_file = open (file_name, 'r')
num_vertex, num_edges = [int(i) for i in input_file.readline().strip().split()]
graph = [[] for i in range(num_vertex)]
for data in input_file:
vertex1, vertex2, weight = [int(i) for i in data.strip().split()]
edge = (vertex1 - 1, vertex2 - 1, weight)
edge_reverse = (vertex2 - 1, vertex1 - 1, weight)
graph[vertex1 - 1].append(edge)
graph[vertex2 - 1].append(edge_reverse) # be cautious to this line, because it is an undirected graph
# we should add reversed edge to the vertex
# it takes me more than an hour to debug
input_file.close()
return graph
## test
# if __name__ == '__main__':
# print build_adjacent_graph('edges.txt')
## test
VERTEX2 = 1
WEIGHT = 2
infinity = 99999999999
def prim_MST(graph):
""" list -> list
Return a list of edges which form the minimum spannig tree of graph
Using prim algorithm
"""
n = len(graph)
s = random.randint(0, n - 1)
MST = set()
visited = set() # store visited vertex
visited.add(s)
while len(visited) < n:
min_edge = (None, None, infinity)
# print 'visited-> ', visited
for vertex in visited:
for edge in graph[vertex]:
if (edge[VERTEX2] not in visited) and (edge[WEIGHT] < min_edge[WEIGHT]):
min_edge = edge
visited.add(min_edge[VERTEX2])
MST.add(min_edge)
return MST
if __name__ == '__main__':
graph = build_adjacent_graph('edges.txt')
MST = prim_MST(graph)
sum_MST = sum([weight for (vertex1, vertex2, weight) in MST])
print sum_MST
| true |
ef4dd5999419bb7ec76f24fd39ab8ae50cc55349 | cgtykarasu/GlobalAIHubPythonCourse | /Homeworks/HW4.py | 1,256 | 4.25 | 4 | __author__ = "Çağatay KARASU"
__course__ = "Introduction to Python Programming"
class Animals:
def __init__(self, color, legs, age):
self.color = color
self.legs = legs
self.age = age
# print("This animal's color is",color,",has",legs,"legs and it is",age,"years old.")
print('{}{},{}{}{}{}{}'
.format("This animal's color is ", color, " has ", legs, " legs and it is ", age," years old."))
class Dogs(Animals):
def __init__(self, color, legs, age, name, breed):
super().__init__(color, legs, age)
self.name = name
self.breed = breed
print("This dog's name is", name, "and it's breed is", breed)
@staticmethod
def make_sound():
print("Woof Woof!")
class Cats(Animals):
def __init__(self, color, legs, age, name, breed):
super().__init__(color, legs, age)
self.name = name
self.breed = breed
print("This cat's name is", name, "and it's breed is", breed)
@staticmethod
def make_sound():
print("Meow!")
animal = Animals("yellow", 4, 10)
print("# " + "=" * 78 + " #")
dog = Dogs("black", 4, 7, "Çomar", "Kangal")
dog.make_sound()
print("# " + "=" * 78 + " #")
cat = Cats("white", 4, 5, "Minnoş", "Turkish Van")
cat.make_sound()
| false |
0ed11f6ce05fb2b74f3dd88a008a437e81d663c2 | rutrut6969/Automate-The-Boring-Stuff | /Functions none keywords.py | 1,449 | 4.4375 | 4 | # This is about functions that you write on your own!
def hello():
print('Howdy!')
print('Howdy!!!')
print('Hello World')
hello()
hello()
hello()
def name(name):
print('Hello ' + name)
name('Alice')
name('Bob')
#Arguments allow us to pass values through to a variable inside the function, which is why name is in the perentheses,
#You can pass it any name and it will still work fine it doesn't have to be name. It's just a variable.
def plusOne(number):
return number + 1
newNumber = plusOne(5)
print(newNumber)
#The none value is the lack of a value, it's the only function of its type.
None
spam = print()
print(spam)
#Keyword Arguments
print('Hello' end='')
print('World')
print('cat', 'dog', 'mouse' sep='&')
#Basic Recap:
print("Functions are like a mini-program inside your program.")
print("The main point of functions is to get rid of duplicate code.")
print("The def statement defines a function")
print("The input to functions are arguments. The output is the return value")
print("The parameters are the variables in between the function's parentheses in the def statement.")
print("The return value is specified using the return statement")
print("Every function has a return value. If your functions doesn't have a return statement, the default return value is None")
print("Keyword arguments to functions are usually for optional arguments.")
print("The print() function has keyword arguments end and sep")
| true |
230ad9576afbba3da84ed9e75edb3501a4aa3255 | mrlitzinger/CTI110 | /P2HW1_BasicMath_LitzingerStephen.py | 808 | 4.21875 | 4 | # A program to take to entered values and add them as well as mu
# 02/03/2020
# CTI-110 P2HW1 - Basic Math
# Stephen Litzinger
#
def main():
#Ask user for firt and second number and store input as num1 and num2
num1 = int(input('First number please?'))
num2 = int(input('Second number please?'))
#Add num1 and num2 and store as addsum
addSum = num1 + num2
#Multiply num1 and num2 and store as multiplysum
multiplySum = num1 * num2
#Display numbers as added and multiplied values using stored values addsum and multiplysum
print('Your added total is', addSum)
print('Your multiplied total is', multiplySum)
print('The first number you entered was', num1)
print('The second number you entered was', num2)
main()
| true |
9c523def762a13936e122b5678fb39f008cbf3f6 | devopsprosiva/python | /divisors.py | 927 | 4.375 | 4 | #!/usr/bin/env python
#################################################################################################################
# Create a program that asks the user for a number and then prints out a list of all the divisors of that number.
# http://www.practicepython.org/exercise/2014/02/26/04-divisors.html
#################################################################################################################
import sys
# Ask user for input number
user_input = int(raw_input("Enter a number: "))
# Create an empty output list for divisors
divisors_output_list = []
# Loop through range from 1 to user_input and find numbers that evenly divide the user_input
# Adding 1 to the user_input in the range to include the number itself as the divisor i.e., a number will divide itself evenly
divisors_output_list = [i for i in range(1, user_input+1) if user_input % i == 0]
print (divisors_output_list)
| true |
ef5f791a0f693291520f06778c1b7f96b5d6580d | darthexter/test | /calculator.py | 1,142 | 4.15625 | 4 | #!/usr/bin/python3
# This is a Simple Calculator written in python
import sys
def addnum(num1,num2):
return num1 + num2
def subnum(num1,num2):
return num1 - num2
def multnum(num1,num2):
return num1 * num2
def divnum(num1,num2):
return num1 / num2
def main():
print("****This is a Simple Calculator****\n")
try:
num1 = int(input("Please enter a number: "))
num2 = int(input("Please enter a second number: "))
except:
print("Please enter a valid number!")
sys.exit()
menu = '''
1. Addition
2. Subtraction
3. Multiplication
4. Division
'''
print(menu)
choice = input("\nEnter choice: ")
if choice == '1':
result = addnum(num1,num2)
print("\nAnswer is: {}".format(result))
elif choice == '2':
result = subnum(num1,num2)
print("\nAnswer is: {}".format(result))
elif choice == '3':
result = multnum(num1,num2)
print("\nAnswer is: {}".format(result))
elif choice == '4':
result = divnum(num1,num2)
print("\nAnswer is: {}".format(result))
else:
print("Invalid Choice!")
sys.exit()
return 0
if __name__ == '__main__':
main()
| false |
57222c496d4c0228bf3f9145b8a06f7d18893e8c | cliu0507/CodeForFun | /Python/Reverse Integer.py | 1,026 | 4.28125 | 4 | Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
'''
Need to Consider Overflow though Python automatically extend 32 bit int to long if overflow
'''
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
MAX_VALUE_INTEGER = pow(2,31) - 1
MIN_VALUE_INTEGER = (-1)*MAX_VALUE_INTEGER - 1
if x >= 0 :
POSITIVE=True
else:
POSITIVE=False
x = x * (-1)
reverse = 0
while(x != 0):
reverse = reverse * 10 + x%10
x = x/10
if POSITIVE==True:
result=reverse
else:
result= reverse * (-1)
if result > MAX_VALUE_INTEGER or result < MIN_VALUE_INTEGER:
return 0
else:
return result | true |
798ed4fbbf760142f7609ed87ab15611293d28e5 | borko81/python_fundamental_solvess | /examples/10March2019_2/TheHuntingGame.py | 2,176 | 4.21875 | 4 | '''
First you will receive the days of the adventure, the count of the players and the group’s energy. Afterwards, you will
receive the following provisions per day for one person:
• Water
• Food
The group calculates how many supplies they’d need for the adventure and take that much water and food.
Every day they chop wood and lose a certain amount of energy. For each of the days, you are going to receive the energy
loss from chopping wood. The program should end If the energy reaches 0 or less.
Every second day they drink water, which boosts their energy with 5% of their current energy and at the same time drops
their water supplies by 30% of their current water.
Every third day they eat, which reduces their food supplies by the following amount:
{currentFood} / {countOfPeople} and at the same time raises their group’s energy by 10%.
The chopping of wood, the drinking of water, and the eating happen in the order above.
If they have enough energy to finish the quest, print the following message:
"You are ready for the quest. You will be left with - {energyLevel} energy!"
If they run out of energy print the following message and the food and water they were left with before they ran out of
energy:
"You will run out of energy. You will be left with {food} food and {water} water."
'''
day_of_campain = int(input())
players = int(input())
group_energy = float(input())
water_per_day_for_one_person = float(input())
food_per_day_for_one_person = float(input())
total_woter = day_of_campain * players * water_per_day_for_one_person
total_food = day_of_campain * players * food_per_day_for_one_person
for day in range(1, day_of_campain + 1):
group_energy -= float(input())
if group_energy <= 0 :
print(f'You will run out of energy. You will be left with {total_food:.2f} food and {total_woter:.2f} water.')
break
if day % 2 == 0:
group_energy *= 1.05
total_woter -= total_woter * 0.3
if day % 3 == 0:
group_energy *= 1.1
total_food -= total_food / players
if group_energy > 0:
print(f'You are ready for the quest. You will be left with - {group_energy:.2f} energy!') | true |
d6c8be3c39f5b5143a52b484e3d79201e73d4653 | borko81/python_fundamental_solvess | /Retake Mid Exam - 16 April 2019/01. Easter Cozonacs.py | 1,771 | 4.15625 | 4 | budget = float(input())
price_flour = float(input())
info = {
'Eggs': 1,
'Floor': 1,
'Milk': 0.250
}
make = 0
colored_eggs = 0
price_eggs = price_flour * 0.75
price_milk = (price_flour + price_flour * 0.25) / 4
total_amount = price_milk + price_eggs + price_flour
while budget > total_amount:
budget -= total_amount
make += 1
colored_eggs += 3
if make % 3 == 0:
colored_eggs -= make - 2
print(f'You made {make} cozonacs! Now you have {colored_eggs} eggs and {budget:.2f}BGN left.')
'''
Create a program that calculates how much cozonacs you can make with the budget you have. First, you will receive your
budget. Then, you will receive the price for 1 kg flour. Here is the recipe for one cozonac:
Eggs
1 pack
Flour
1 kg
Milk
0.250 l
The price for 1 pack of eggs is 75% of the price for 1 kg flour. The price for 1l milk is 25% more than price for 1 kg
flour. Notice, that you need 0.250l milk for one cozonac and the calculated price is for 1l.
Start cooking the cozonacs and keep making them until you have enough budget. Keep in mind that:
• For every cozonac that you make, you will receive 3 colored eggs.
• For every 3rd cozonac that you make, you will lose some of your colored eggs after you have received the usual
3 colored eggs for your cozonac. The count of eggs you will lose is calculated when you subtract 2 from your
current count of cozonacs – ({currentCozonacsCount} – 2)
In the end, print the cozonacs you made, the eggs you have gathered and the money you have left, formatted to the 2nd
decimal place, in the following format:
"You made {countOfCozonacs} cozonacs! Now you have {coloredEggs} eggs and {moneyLeft}BGN left."''' | true |
2ecf6261bec8c18db2f20056db42ad8e821b7c6a | borko81/python_fundamental_solvess | /29_02_2020_group2/Shopping_List.py | 1,911 | 4.28125 | 4 | '''
You will receive an initial list with groceries separated by "!".
After that you will be receiving 4 types of commands, until you receive "Go Shopping!"
• Urgent {item} - add the item at the start of the list. If the item already exists, skip this command.
• Unnecessary {item} - remove the item with the given name, only if it exists in the list. Otherwise skip this
command.
• Correct {oldItem} {newItem} – if the item with the given old name exists, change its name with the new one.
If it doesn't exist, skip this command.
• Rearrange {item} - if the grocery exists in the list, remove it from its current position and add it at the
end of the list.
'''
shoping_list = input().split('!')
def urgent(shoping_list, item):
if item not in shoping_list:
shoping_list.insert(0, item)
def unnecessary(shoping_list, item):
if item in shoping_list:
shoping_list.remove(item)
def correct(shoping_list, old_item, new_item):
if old_item in shoping_list:
shoping_list[shoping_list.index(old_item)] = new_item
def rearrange(shoping_list, item):
if item in shoping_list:
temp = shoping_list.pop(shoping_list.index(item))
shoping_list.append(temp)
while True:
command = input()
if command == 'Go Shopping!':
break
elif command.startswith('Urgent'):
command = command.split()
urgent(shoping_list, command[1])
elif command.startswith('Unnecessary'):
command = command.split()
unnecessary(shoping_list, command[1])
elif command.startswith('Correct'):
command = command.split()
correct(shoping_list, command[1], command[2])
elif command.startswith('Rearrange'):
command = command.split()
rearrange(shoping_list, command[1])
print(", ".join(shoping_list)) | true |
808cf63599c2c9cf75119962be6e05489e05d7a2 | borko81/python_fundamental_solvess | /examples/10March2019_2/the_final_quest.py | 2,115 | 4.1875 | 4 | '''
Create a program that follows given instructions. You will receive a collection of words on a single line, split by a
single space. They are not what they are supposed to be, so you have to follow the instructions in order to find the real
message. You will be receiving commands. Here are the possible ones:
• Delete {index} – removes the word after the given index if it is valid.
• Swap {word1} {word2} – find the given words in the collections if they exist and swap their places.
• Put {word} {index} – add a word at the previous place {index} before the
given one, if it is valid. Note: putting at the last index simply appends the word to the end of the list.
• Sort – you must sort the words in descending order.
• Replace {word1} {word2} – find the second word {word2} in the collection (if it exists) and replace it with
the first word – {word1}.
Follow them until you receive the "Stop" command. After you have successfully followed the instructions,
you must print the words on a single line, split by a space.
'''
text = input().split()
while True:
command = input()
if command == 'Stop':
break
if command.startswith('Delete'):
index = command.split()[1]
index = int(index) + 1
if index < len(text):
text.pop(index)
elif command.startswith('Swap'):
_, start, end = command.split()
try:
start_get = text.index(start)
end_get = text.index(end)
text[start_get], text[end_get] = text[end_get], text[start_get]
except:
pass
elif command.startswith('Put'):
_, word, index = command.split()
index = int(index) - 1
if index >= 0 and index <= len(text):
text.insert(index, word)
elif command.startswith('Sort'):
text = sorted(text, reverse=True)
elif command.startswith('Replace'):
_, first, second = command.split()
try:
index = text.index(second)
text[index] = first
except:
pass
print(" ".join(text)) | true |
96b113d747405fa8d2ced12c294c30fab3ed4156 | borko81/python_fundamental_solvess | /examples/10Mach2019_1/spring_vacation.py | 1,979 | 4.3125 | 4 | '''
Create a program that calculates travelling expenses by entering the following information:
• Days of the vacation
• Budget - its for the whole group
• The count of people
• Fuel per kilometer – the price for fuel that their car consumes per kilometer
• Food expenses per person
• Hotel room price for one night – again, for one person
If the group is bigger than 10, they receive a 25% discount from the total hotel expenses.
Every day, they travel some distance and you have to calculate the expenses for the travelled kilometers.
Every third and fifth day, they have some additional expenses, which are 40% of the current value of the expenses.
Every seventh day, their expenses are reduced, because they withdraw (receive) a small amount of money – you can calculate it by dividing the amount of the current expenses by the group of people.
If the expenses exceed the budget at some point, stop calculating and print the following message:
"Not enough money to continue the trip"
If the budget is enough:
"You have reached the destination. You have {money}$ budget left."
Print the result formatted 2 digits after the decimal separator.
'''
day_of_trip = int(input())
budjet = float(input())
people = int(input())
price_kilometer = float(input())
food = float(input())
room_price = float(input())
if people > 10:
room_price *= 0.75
trip_money = people * day_of_trip * (room_price + food)
for day in range(1, day_of_trip + 1):
day_expense = 0
km = float(input()) * price_kilometer
trip_money += km
if day % 3 == 0 or day % 5 == 0:
trip_money += trip_money * 0.4
if day % 7 == 0:
trip_money -= trip_money / people
if trip_money > budjet:
print(f'Not enough money to continue the trip. You need {(trip_money - budjet):.2f}$ more.')
break
if trip_money <= budjet:
print(f'You have reached the destination. You have {(budjet - trip_money):.2f}$ budget left.')
| true |
93e847dec6c9d2fd1da7ccf314986e62897da5a1 | hubert-wojtowicz/learn-python-syntax | /module-3/4-loops-over-list.py | 282 | 4.375 | 4 | letters = ["a", "b", "c"]
for letter in letters:
print(letter)
for letter_touple in enumerate(letters): # introducing enumerable object
print(letter_touple)
for index, letter in enumerate(letters): # touple unpacking similar to list unpacking
print(index, letter) | true |
230a6a5dcc3b81f80cb8a584f528007ae2ca1028 | TiantianWang/Leetcode | /7 Reverse Integer.py | 666 | 4.125 | 4 | """
Description
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
"""
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
intMax = 2**31-1
intMin = -2**31
rev = 0
sign = 1
if x > intMax or x < intMin:
return 0
if x < 0:
sign = -1
x *= sign
while x != 0:
pop = x % 10
x = int(x/10)
rev = rev * 10 + pop
return 0 if rev>intMax or rev<intMin else rev*sign
| true |
d7595cea3815d80423eb3c9354700f252b24fd52 | Shogo-Sakai/everybodys_ai | /python_training/branch.py | 314 | 4.1875 | 4 | a = 5
if a == 5:
print ("Hello")
else:
print ("Hi!")
b = 4
if b < 3:
print ("Hello!")
elif b < 5:
print ("Hi!")
else:
print ("Yeah!")
time = 17
if time > 5 and time < 12:
print ("Good Morning")
elif time >= 12 and time < 18:
print ("Good Afternoon")
else:
print ("Good night")
| false |
3326c24cb0fd3285789e444e02e64fc71c0a73f0 | syntax-spectrum/Math_Module | /Baird_PerformanceAssessment1_Python.py | 1,458 | 4.46875 | 4 | #Zachary Baird
#Date: 08/16/2020
#Description: Application prompts user to enter two integers
# to be modified based on the math module.
from math import gcd, remainder, pow
#Functions
def gcd_func(x, y):
#Greatest Common Denominator function from the math module
result = gcd(x, y)
return result
def remainder_func(x, y):
#Remainder function from the math module
result = remainder(x, y)
return result
def power_func(x, y):
#Power function from the math module
result = pow(x, y)
return result
#Main
choice = 0
quitter = ' '
while quitter != 'Quit' and quitter != 'quit':
x = int(input('Please enter your first value for \'x\': '))
y = int(input('Please enter your second value for \'y\': '))
#User Choice
while choice == 0:
choice = int(input('\nEnter: \n1. Greatest Common Denominator\n2. Remainder\n3. Power\nChoice: '))
if choice == 1:
answer = gcd_func(x, y)
break
elif choice == 2:
answer = remainder_func(x, y)
break
elif choice == 3:
answer = power_func(x, y)
break
else:
choice == 0
print('Please enter a valid choice, ')
continue
#Output
print('The result of the variables for ', x, ' and ', y, ' is ', answer)
choice = 0
quitter = input('Enter \'Quit\' to quit, else \'enter\' to continue: ')
| true |
6230052c75c2abe8c22405686fb2aaf06a64268b | jackerma/CS112-Spring2012 | /hw04/sect1_if.py | 722 | 4.25 | 4 | #!/usr/bin/env python
from hwtools import *
print "Section 1: If Statements"
print "-----------------------------"
# 1. Is n even or odd?
n = raw_input("Enter a number: ")
n = int(n)
m=n/2
m=int(m)
b=n/2.0
b=int(b)
if m==b:
a="odd"
else:
a="even"
print "1.", a
# 2. If n is odd, double it
if a=="odd":
v=n*2
print "2.", n
else:
print "2.", n, "(not odd)"
# 3. If n is evenly divisible by 3, add four
if n/3 == n/3.0:
print "3.", n+4
else:
print "3:", n, "(not multiple of 3)"
# 4. What is grade's letter value (eg. 90-100)
grade = raw_input("Enter a grade [0-100]: ")
grade = int(grade)
if grade>=90:
c="A"
elif grade>=80:
c="B"
elif grade>=70:
c="C"
elif grade>=60:
c="D"
else:
c="F"
print "4.", c
| false |
48a81e85a2616754f21681dec87a1a7341a3f556 | davsucks/100Projects | /Numbers/1.py | 772 | 4.4375 | 4 | # Find Pi to the Nth Digit
# ========================
# Enter a number and have the program generate PI
# up to that many decimal places.
# Keep a limit to how far the program will go.
pi = "3.141592653589793238462643383279502884197 \
16939937510582097494459230781640628620899\
86280348253421170679821480865132823066470\
93844609550582231725359408128481117450284\
10270193852110555964462294895493038196442\
88109756659334461284756482337867831652712\
0190914564856692346"
LEADING_CHARS = 2
max_length = len(pi) - LEADING_CHARS
digits = input('How many decimal places of Pi would you like me to print? ')
while digits > (max_length):
print "Sorry! Please enter a number smaller than {0}".format(max_length)
print "Here you go: {0}".format(pi[0:(digits + 2)]) | true |
469d86fd91d574c49520c7513dc3d8851f923c7d | Madhu2244/Learning-Python | /Code/Function/Lambda_functions.py | 1,081 | 4.5625 | 5 | # Lambda arguments : expression
# We need lambda functions
# Example: If you want to change the behavior of all the elements of a list using a function, but you feel like the
# function will not have any further use once it has changed the behavior of the elements
# Lambda just reduces the lines of code you have, if you are using a function once, use lambda
# Takes up less memory because less lines of code to execute
import math
def add_10(c):
c = c + 10
return c
add10 = lambda x: x + 10
print(add10(5))
mult = lambda x,y: x * y
print(mult(7,2))
points = [(1,2), (4,1), (3,5), (10,4)]
points_Sort = sorted(points, key = lambda x : math.pow(abs(x[0]-x[1]),2))
print(points_Sort)
#map(function,sequence)
a = [1,2,3,4,5]
b = map(lambda x : x*2,a)
print (a)
print (list(b))
c = [x*2 for x in a]
print (list(c))
#filter(function, sequence)
b = filter(lambda x : x % 2 != 0, a)
b = [x for x in a if x % 2 != 0]
#reduce(function,sequence)
from functools import reduce
a = [1,2,3,4,5]
b = reduce(lambda x, y: x/y, a)
print(b)
| true |
4f186b7ca4636b0dc15b46a79bc61fffb9a6f58b | rafaelgama/Curso_Python | /Udemy/Secao2/aula30.py | 287 | 4.15625 | 4 | """
While em python - Aula 30
"""
x = 0
while x < 10:
if x == 3:
x += 1
continue # funciona como o loop em ADVPL, ele pula o laço que está sendo excutado.
if x == 8:
break # funciona como o exit emADVPL, ele finaliza o loop.
print(x)
x += 1
| false |
3196266b65cc72b10797a72105456bd0a9d96324 | rafaelgama/Curso_Python | /CursoEmVideo/Mundo2/Exercicios/ex060.py | 1,511 | 4.21875 | 4 | #Faça um programa que leia um número qualquer e mostre o seu fatorial.
from math import factorial
cores = {'limpa':'\033[m',
'bverde':'\033[1;32m',
'roxo':'\033[35m',
'bvermelho': '\033[1;31m',
'pretoebranco':'\033[7:30m'}
print('-=-'*8)
print(cores['pretoebranco']+'_____INICIO_____'+cores['limpa'])
print('-=-'*8)
#Utilizando o modulo que ja existe de para calcular o Fatorial
num = int(input('Digite um número para calcular o Fatorial: '))
fator = factorial(num)
print('O Fatorial (math) de {} é {}.'.format(num,fator))
#Fazendo da maneira tradicial sem o modulo e com while para calcular o Fatorial
num = int(input('Digite um número para calcular o Fatorial: '))
calc = num
fator = 1
print('Calculando o Fatorial (WHILE) de {}! = '.format(num), end='')
while calc > 0:
print('{} '.format(calc), end='')
print(' X ' if calc > 1 else ' = ', end='')
fator = fator*calc
calc -= 1
print(fator)
#Fazendo da maneira tradicial sem o modulo e com FOR para calcular o Fatorial
num = int(input('Digite um número para calcular o Fatorial: '))
fator = 1
print('Calculando o Fatorial (FOR) de {}! = '.format(num), end='')
for calc in range(num,0,-1):
print('{} '.format(calc), end='')
print(' X ' if calc > 1 else ' = ', end='')
fator = fator*calc
print(fator)
print('-=-'*8)
print(cores['pretoebranco']+'______FIM_______'+cores['limpa'])
print(cores['pretoebranco']+'_Code by Rafael_'+cores['limpa'])
print('-=-'*8) | false |
869a3676b6b164d44415076cbcd3ebcd487c72bc | rafaelgama/Curso_Python | /Udemy/Secao3/aula63.py | 396 | 4.21875 | 4 | # Dictionary Comprehension em Python - ( compreensão de dicionários)
print('-=-'* 30)
# exemplo 1
l1 = [ ('chave1','valor1'), ('chave2','valor2'), ]
d1 = {x: y for x, y in l1}
print(d1)
print('-=-'* 30)
# exemplo 2 - Gerando SET
d1 = {x for x in range(5)}
print(d1, type(d1))
print('-=-'* 30)
# exemplo 2- Gerando DICT
d1 = {x: x**2 for x in range(5)}
print(d1, type(d1))
print('-=-'* 30)
| false |
67419a6463c33336ba9e4ce3ca886f1aba5a0443 | rafaelgama/Curso_Python | /Udemy/Secao3/aula78.py | 424 | 4.21875 | 4 | # https://docs.python.org/3/library/exceptions.html
# Levantando exceções em Python
print('-=-'* 20)
print(f'{" Exemplo com o raise ":=^40}')
def divide(n1,n2):
if n2 == 0:
raise ValueError('n2 não pode ser 0')
return n1 / n2
# para capturar a exceção
try:
print(divide(2,0))
except ValueError as error:
print('Você está tentando dividir por 0.')
print('Log:',error)
print('-=-'* 20) | false |
3e9af00427ee3ce41d5182d128c58c6633743b02 | rafaelgama/Curso_Python | /CursoEmVideo/Mundo1/Exercicios/ex022.py | 1,016 | 4.5 | 4 | #Exercício Python 022: Crie um programa que leia o nome completo de uma pessoa e mostre:
#- O nome com todas as letras maiúsculas e minúsculas.
#- Quantas letras ao todo (sem considerar espaços).
#- Quantas letras tem o primeiro nome.
nome = str(input('Digite seu nome completo: ')).strip() #Pode-se eliminar os espaços na hora da digitação
#nome = 'Rafael Gama de Macedo Junior'
print('Tudo em letras maiúsculas: {}'.format(nome.upper()))
print('Tudo em letras minúsculas: {}'.format(nome.lower()))
print('Tudo em letras Capitais: {}'.format(nome.capitalize()))
print('Tudo em letras Titulos: {}'.format(nome.title()))
print('Quantas letras existem sem espaços: {}'.format(len(nome.strip()) - nome.count(' ') )) #tira todos os espços em branco na contagem.
listado = nome.split()
print('Quantas letras existem no primeiro nome: {}'.format(len(listado[0])) ) #quantas letras tem o primeiro nome
#ou pode imprimnir até encontrar o espaço em branco
print('Quantas letras existem no primeiro nome: {}'.format( nome.find(' ') )) | false |
6de15de7f69378c6a094334c622ab417bae4fbf0 | rafaelgama/Curso_Python | /CursoEmVideo/Mundo1/Exercicios/ex018.py | 484 | 4.125 | 4 | #Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo.
import math
ang = float(input('Digite o angulo que vc deseja: '))
seno = math.radians(ang)
cos = math.radians(ang)
tan = math.radians(ang)
print('O Ângulo de {} tem o SENO de {:.2f}'.format(ang, math.sin(seno) ))
print('O Ângulo de {} tem o COSSENO de {:.2f}'.format(ang, math.cos(cos) ))
print('O Ângulo de {} tem a TANGENTE de {:.2f}'.format(ang, math.tan(tan)))
| false |
1392799817da56592a58e80ec0e90ce1d1e216c9 | rafaelgama/Curso_Python | /CursoEmVideo/Mundo1/Exercicios/ex025.py | 646 | 4.1875 | 4 | #Crie um programa que leia o nome de uma pessoa e diga se ela tem "SILVA" no nome.
nome = str(input("Qual seu nome completo: ")).strip() #Remove os espaços em branco na digitação.
#Essa resolução não trata nomes tipo silvana ou algo do tipo.
print('Seu nome tem Silva? {}'.format('SILVA' in nome.upper() ))
#essa solução pega somente o nome "Silva"
name = str(input('Digite um nome: ')).title()
name = '{} '.format(name)
teste = str(name.count('Silva ') > 0)
teste = teste.replace('False', 'não tem')
teste = teste.replace('True', 'tem')
aspas = '"'
name = name.strip()
print('{} {} {}Silva{} no nome'.format(name, teste, aspas, aspas)) | false |
81f0ccd970c30fc1ae7d2c49941040abc7b86de4 | rafaelgama/Curso_Python | /Udemy/Secao3/aula83_json.py | 951 | 4.125 | 4 |
#https://docs.python.org/3/library/functions.html#open
# Criando, lendo, escrevendo e apagando arquivos.
import json
import os # para poder apagar o arquivo
print(f'{" ARQUIVOS-JSON":=^40}')
print('-=-'* 20)
arq = 'D:\\GitHub\\Curso_Python\\Udemy\\Secao3\\json.txt'
d1 = {
'Pessoa 1':{
'nome': 'Rafael',
'idade': 40,
},
'Pessoa 2':{
'nome': 'Gama',
'idade': 35,
},
}
# Transforma em arquivo json
d1_json = json.dumps(d1,indent=True)
with open(arq, 'w+') as file:
file.write(d1_json)
print(d1_json)
print(f'{" LEITURA-JSON":=^40}')
print('-=-'* 20)
with open(arq, 'r') as file:
d1_ler = file.read()
print(d1_ler)
# Tranformar em dicionarios novamente
d1_ler = json.loads(d1_ler)
print()
print(d1_ler)
print()
for k, v in d1_ler.items():
print(k)
for k1, v1 in v.items():
print(k1, v1)
os.remove(arq) # apagando o arquivo.
print('-=-'* 20) | false |
96de7624648e80970ed79ad7635b1fb75b1292d0 | Allien01/python-challanges-uri | /begginer/average2.py | 479 | 4.28125 | 4 | '''
Read three values (variables A, B and C),
which are the three student's grades. Then,
calculate the average, considering that grade
A has weight 2, grade B has weight 3 and the
grade C has weight 5. Consider that each grade
can go from 0 to 10.0, always with one decimal place.
'''
a = float(input('Informe a primeira nota: '))
b = float(input('Informe a segunda nota: '))
c = float(input('Informe a terceira nota: '))
avg = ((a*2)+(b*3)+(c*5))/10
print('MEDIA = %.1f'%avg)
| true |
70ca51c7d3a4a9af11196ba281a37ca1805315e0 | CODE-BEASTS/LetsUpgrade_Assign | /Assign2.py | 358 | 4.40625 | 4 | #Write a program to find the prime number
#Enter a number to program and get the output "Prime" or "Not Prime"
num = int(input("Enter any number"))
if num>1:
for i in range(2, num//2) :
if (num%i) == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
| true |
e82fcb729043eda03de5552a0907f48dc4c9c6be | esthermanalu/basic-phyon-b4-c | /range.py | 490 | 4.3125 | 4 | x = range(6)
for n in x:
print(n)
#range does not include the last vairable mentioned, in this case 6, but it starts from 0
#so range = (0,1,2,3,4,5)
#range has three paramenters written like this: range (start,stop,step)
# if x = range(3,20,2) start at 3 stop at 20 step 2
print ("---------------")
x = range (3,6)
for n in x:
print (n)
print ("---------------")
x = range (3,20,2)
for n in x:
print (n)
#for this one above, so it starts from 3 and it keeps adding '2' to it until 20 | true |
014b2be3c405da3c1b4a534d70ab5b4ab735e97e | Bedrock02/General-Coding | /Math/babyGiantStep.py | 1,152 | 4.25 | 4 | #This is the Giant step Baby Step Algorithm
#What is needed for this function is a prime number a primiitve root and the goal number
import math
from inverse import*
def babyGiantStep(prime,primitiveRoot,goalNumber):
m = int(math.ceil(math.sqrt(prime-1)))
giantSteps = {}
for j in xrange(0,m):
giantSteps[pow(primitiveRoot,j,prime)] = j
#find inverse of generator
inverse = inverseByFermat(primitiveRoot,prime-2,prime)
inverseToM = pow(inverse,m,prime)
suspect = goalNumber
for i in xrange(0,m):
if suspect in giantSteps:
return i * m + giantSteps[suspect]
else:
suspect = suspect * inverseToM % prime
print "nothing"
if __name__ == '__main__':
print "The Giant Step Baby Step Algorith solves for x in the following:"
print "p being a prime number,g being a primitive root mod p, and t being a number between 1 and p (excluding p)"
print " g^x = t mod p"
prime = int(raw_input("Enter the prime number "))
primitiveRoot = int(raw_input("Enter the primitive root "))
goalNumber = int(raw_input("Enter your value of t or the target number "))
babyGiantStep(prime,primitiveRoot,goalNumber)
| true |
f05938dec7b03465d16df7458bf6b7e884e13034 | mohsenahmadi/Algorithm-Foundation-Python | /01_Checking_odd_or_even.py | 350 | 4.21875 | 4 | #Python Programm to check your enter number is odd or even
import mpmath
print("This program checking your enter number is odd or even")
number = input("Please enter your number:")
number = int(number)
if mpmath.fmod(number,2):
print("Your number is {0} and it's odd".format(number))
else:
print("Your number is {0} and it's even".format(number))
| true |
fdb9ad1154ae9b3fa9ca8377018d52e21c3fb699 | Abhyudyabajpai/test | /listMethods.py | 225 | 4.40625 | 4 | print("appending items in a list :")
l1 = [1,2,3,4]
l1.append([5,6,7])
print(l1)
print("extending a list :")
l2 = [1,2,3,4]
l2.extend([5,6,7])
print(l2)
print("insertion in a list: ")
l3 = [1,2,3,4]
l3.insert(2,5)
print(l3) | false |
c5a8994cfe07d83d6c6b4eeca18e02a9846e05fc | Shiladitya070/python-kvcob-2020 | /prime_num.py | 251 | 4.15625 | 4 | # prime not prime
number = int(input("Enter the number: "))
f = 0
for i in range(2, int(number/2)):
if (number % i) == 0:
print(f"{number} is divisible by {i}, so not prime!")
f = 1
break
if (f == 0):
print('prime!')
| true |
a170c21d2c8bd3eea0ce5c1417bb07029dc72179 | 34527/Lists | /r&r task 1.py | 538 | 4.125 | 4 | counter = 1
studentlist = []
for count in range(8):
studentlist.append(input("Please enter a students name: "))
for each in studentlist:
print("{0}. {1}".format(counter, each))
counter = counter + 1
count = 1
change = int(input("Please enter the student you wish to change: "))
true_change = change - 1
studentlist.pop(true_change)
studentlist.insert(true_change, input("please enter the new name: "))
for each in studentlist:
print("{0}. {1}".format(count, each))
count = count + 1
| true |
c57309e3fc06e3cd4d49ab55ad245e53c16c715c | rhounkpe/python-for-everybody-specialization | /course-2-python-data-structures/week-4/8-1-lists.py | 1,286 | 4.28125 | 4 | """
- A collection allows us to put many values in a single 'variable.
- A collection is nice beacause we can carry many values
around in one convenient package.
"""
friends = ['Joseph', 'Glenn', 'Sally']
carryon = ['soks', 'shirt', 'perfume']
# List Constants
"""
- List constants are surrounded by square brackets and the elements
in the list are separated by commas
- A list element can be any Python object - even another list
- A list can be empty
"""
# print([1,24, 76])
# print(['red', 'yellow', 'blue'])
# print([1, [5, 6], 7])
# print([])
# Lists and definite Loops - Best Pals
for friend in friends:
print('Happy new year:', friend)
print('Done!')
# Looking inside lists
"""
Just like strings, we can get at any single element in a list using an index
specified in square brackets
"""
print(friends[1]) # Glenn
#
# Lists are mutable
"""
- Strings are 'immutable' - we cannot change the contents of a string -
we must make a new string to make any change.
- Lists are 'mutable' - we can change an element of a list using the index operator.
"""
# A Tale of two Loops...
for friend in friends:
print(friends)
# Counted loop
for i in range(len(friends)):
friend = friends[i]
print(i, friend) | true |
dfb7a433d4f584567e0e68e8e319356416835589 | SherwinKP/intro_spring | /python/ArabicNumerals-to-RomanNumerals.py | 1,840 | 4.40625 | 4 | ##Write a python script to convert a integer to a roman numeral.
##
##Here are the preconditions:
##
## 1. Read an integer in the range
## from 1 up to 3999.
##
## 2. Use the following symbols:
##
## Symbol Value
## --------------
## I 1
## V 5
## X 10
## L 50
## C 100
## D 500
## M 1000
##
##
## 3. Abide by these rules when constructing a roman numberal:
##
## * The symbols "I", "X", "C", and "M" can be repeated three times in
## succession, but no more. "D", "L", and "V" can never be repeated.
## * "I" can be subtracted from "V" and "X" only. "X" can be subtracted from
## "L" and "C" only. "C" can be subtracted from "D" and "M" only. "V", "L",
## and "D" can never be subtracted
## * Only one small-value symbol may be subtracted from any large-value
## symbol.
## * A number written in Arabic numerals can be broken into digits.
## For example, 1903 is composed of 1, 9, 0, and 3. To write the Roman
## numeral, each of the non-zero digits should be treated separately.
## In the above example, 1,000 = M, 900 = CM, and 3 = III. Therefore,
## 1903 = MCMIII.
def numToRoman(n):
if n < 4:
return "I" * n
if n < 9:
return "V" + "I" * (n - 5)
if n = 9:
return "IX"
if n < 40:
return "X" * (n%10) + numToRoman(n - 10)
if n < 90:
return "L" + numToRoman(n - 50)
if n < 100:
return "XC" + numToRoman(n - 90)
if n < 400
return "C" * (n%100) + numToRoman(n%100)
if n < 900
return "D" + numToRoman(n - 500)
if n < 1000
return "CM" + numToRoman(n - 900)
if n < 4000
return "M" * numToRoman(n%1000) + numToRoman(n%1000)
num = input("Enter a number: ")
numToRoman(num)
| true |
5aa00ba83ad77cd1482b08c47765779e28c6fe6c | phi1ny3/CSE-212 | /Wk 1/01-prove_rotate_list_right.py | 794 | 4.375 | 4 | def rotate_list_right(data,amount):
"""
Rotate the 'data' to the right by the
'amount'. For example, if the data is
[1, 2, 3, 4, 5, 6, 7, 8, 9] and an amount
is 5 then the list returned should be
[5, 6, 7, 8, 9, 1, 2, 3, 4]. The value
of amount will be in the range of 1 and
len(data).
"""
#using negative indexing we can easily divide the two portions of the data
#that is left half and right half and combine them seperately
return data[-amount:]+data[:-amount]
#the statement below also works which is based on the constant length rearrangement
#we use modulus here so as to keep the length of the list constant
d=[1,2,3,4,5,6,7,8,9]
print(rotate_list_right(d,1))
print(rotate_list_right(d,5))
print(rotate_list_right(d,9)) | true |
bd0e3be8e7aac663532fbb2ab63f2e4b18f45805 | stevegleds/learning | /udemy/Intermediate Python/Intermediate Python/russian-peasant-server/russian-peasant.py | 1,615 | 4.125 | 4 | ## The Russian Peasant's Algorithm with testing
## I use recursion for fun
## Been around for a long time (1700s)
## Multiply two numbers together
## Requirements: multiply one by two and divide other by two
## Keep going til get to 1 on LHS
## Add up the RHS for all odd values on LHS
## Eg. 24 * 16
## 12 * 32
## 6 * 64
## 3 * 128
## 1 * 256 {round down}
## Add 128 and 256 to get the correct answer 384
## Input 2 numbers
## Calculate product
## Output 1 answer (the product)
import math # Used to use floor function to keep integar values
import time # We will use this to test efficiency
def multiply(left, right, answer): # including answer so that it isn't reset when during iteration. Don't know if this is needed or best way but it works.
if left == 1: # odd value on left so we add to total
answer += right
return answer # we have reached end of iteration
else:
if left % 2 == 1: # odd value on left so we add to total
answer += right
left = math.floor(left/2) # requires rounding down for method to work
return multiply(left, right * 2, answer) # passes right * 2 as part of the method
def test_multiply():
left = 357
right = 16
key = (left, right) # used to test if we have done this before
start_time = time.time()
print(multiply(357, 16, 0))
print("Multiply algorithm took {0} seconds ".format(time.time() - start_time))
assert multiply(357, 16, 0) == 5712
if __name__ == "__main__": # this is needed to stop the following function call running when this is imported.
test_multiply()
| true |
7939eebb759dbff11f2f2672e0b300f846023575 | stevegleds/learning | /think_python/is_power.py | 493 | 4.5 | 4 | """A number, a, is a power of b if it is divisible by b
and a/b is a power of b. Write a
function called is_power that takes parameters a and b
and returns True if a is a power of b. Note:
you will have to think about the base case."""
def is_power(a, b):
print "a is " , a , "b is " , b
if a%b != 0 and a != 1 :
return False
if a == 1 :
return True
return is_power(a/b, b)
print is_power(4, 2)
print is_power(81, 3)
print is_power(2, 2)
print is_power(5, 2)
| true |
5b0eff9d90a37f4e1655e7d4a486c9c487eb2113 | aleechoco/TKH_Repository | /assignment_4.py | 292 | 4.125 | 4 | def big_name(words):
names_list = []
for word in words:
names_list.append((len(word), word))
names_list.sort()
print("The name with the longest length is:", names_list[-1][1])
#to test it out
a = ["Oliver", "Tiffany", "Tyrone", "Fiona"]
| false |
5c3865fb988a48aa3d9bf90a5f540ce5a4348d14 | Tamim101/html | /renaim.py | 355 | 4.125 | 4 | ac = int(input("Enter the first number:"))
op = input("Enter the oprature:")
num2 = int(input("Enter the second number:"))
if op =="+":
print(ac + num2)
elif op =="-":
print(ac - num2)
elif op =="*":
print(ac * num2)
elif op =="/":
print(ac / num2)
elif op == "%":
print(ac % num2)
else:
print("Invijul number ") | false |
aaf591a1cf6f3dcd1cbba82148bce3c9fd7af2cc | GaneshaSrinivas/MCA-Python | /StudentInformation.py | 1,047 | 4.28125 | 4 | """
Create a Student class and initialize it with name and roll number. Create
methods to :
i) Display - It should display all information of the student.
ii) setAge - It should assign age to student
iii) setMarks - It should assign marks to the student.
Write the main program to access these methods.
"""
class Student():
def __init__(self,name,roll):
self.name = name
self.roll= roll
def display(self):
print("\tName:\t ",self.name)
print("\tRoll Number: ",self.roll)
print("\tAge:\t ",self.age)
print("\tMarks:\t ",self.marks)
def setAge(self):
self.age=24
def setMarks(self):
self.marks = 95
if __name__ == "__main__" :
s=Student('Ganesha','1BF18MCA06')
print("\t\tStudent Information")
s.setMarks()
s.setAge()
s.display()
"""
OutPut:
D:\MCA\4TH SEMESTER\PYTHON>python StudentInformation.py
Student Information
Name: Ganesha
Roll Number: 1BF18MCA06
Age: 24
Marks: 95
""" | true |
17f0aaebfe9edf7c35491e703474f059b48c62c9 | pedroiki/Adult_Old_Kid_tennager | /adult_oldmen_kid_tennager.py | 226 | 4.125 | 4 |
age = int(input("Tell me your age: "))
if idade >18 and idade <60:
print("adult")
elif idade <18 and idade >12:
print("teenager")
elif idade >60 :
print("Old")
else:
print("kid")
| false |
6e75f6b36769d31ad47796d70d0dfb92e5039c60 | SachinPitale/Python | /ex30.py | 459 | 4.125 | 4 |
people = raw_input("how many people ")
cars = raw_input("how many cars ")
buses = raw_input("how many buses ")
#people = 30
#cars = 40
#buses = 15
if cars > people :
print "cars is greater than people"
elif cars < people:
print "cars is less than people"
else:
print "cars and buses are same number"
if buses > cars :
print "buses is greater than cars"
elif buses < cars :
print "buses is less than cars"
else :
print "bues is same as cars"
| false |
839686721af0bd767b6464e32b8623286335f183 | EddieGabriel/CodeWars_Python | /WhereMyAnagramsAt.py | 1,447 | 4.25 | 4 | '''
What is an anagram? Well, two words are anagrams of each other if they both contain the same letters. For example:
'abba' & 'baab' == true
'abba' & 'bbaa' == true
'abba' & 'abbba' == false
'abba' & 'abca' == false
Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. For example:
anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']
anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']
anagrams('laser', ['lazing', 'lazy', 'lacer']) => []
'''
# my solution
def anagrams(word, words):
# Converting the string into a list, so i can sort it with the sort() method
word_list = list(word)
# Sorting the string
word_list.sort()
# Assign an empty list called result
result = []
# Here is the for so I can iterate in all of the "words" list
# So, for each item I'll convert into a list, and them sort it.
# if the sorted item is equal the word, then it's an anagrama
for item in words:
item_list = list(item) # converting the list
item_list.sort() # sorting the word
if word_list == item_list: # if the word is equal to the item, then append to result
result.append(item)
return result # return result
| true |
3708ded3a951282e06d95017603f38c53376a28c | JTBOMAN/min_max.py | /min_max.py | 664 | 4.21875 | 4 | # Author: Josiah Boman
# Date: 04/14/2020
# This program asks the user how many integers they would like to enter then prompt the user to enter
# that many integers. After the numbers have been entered, the program displays the largest and smallest
# of the numbers entered
print("How many integers would you like to enter?")
integer_count = int(input())
print("Please enter " + str(integer_count) + " integers.")
min = 100000000000
max = 0
counter = 0
while counter < integer_count:
num_1 = int(input())
if num_1 < min:
min = num_1
if num_1 > max:
max = num_1
counter = counter + 1
print("min: " + str(min))
print("max: " + str(max)) | true |
cbd493f9b99490c99a4ba014ab86404d49cbcec6 | TahirCanata/Class4-PythonModule-Week4 | /Calculator.py | 2,299 | 4.125 | 4 |
import math
def add(num1, num2):
return (math.ceil(num1 + num2)) # mathceil ile yuvarlamayi buradaki fonksiyonlarda yapiyorum
def subtract(num1, num2):
return (math.ceil(num1 - num2))
def multiply(num1, num2):
return (math.ceil(num1 * num2))
def divide(num1, num2):
return (math.ceil(num1 / num2))
def calculate(): # hangi islemi yapacagimizi seciyoruz
print("Please select the type of calculation -\n" \
"1. Add\n" \
"2. Subtract\n" \
"3. Multiply\n" \
"4. Divide\n")
while True:
select = input("Select type of calculation 1, 2, 3, 4 :")
try:
assert 0 < int(select) < 5 #baska sayi ve rakam girislerinde uyarip tekrar ettiriyoruz
break
except:
print("invalid entry!")
continue
while True:
number_1 = input("Enter first number: ")
number_2 = input("Enter second number: ")
try:
number_1 = float(number_1) # rakam girilmezse uyarip tekrar ettiriyoruz
number_2 = float(number_2)
break
except:
print("invalid entries")
continue
if int(select) == 1:
print(number_1, "+", number_2, "=", #islemine gore yukaridaki toplama, cikarrma vs fonsiyonlari cagiriyoruz
add(number_1, number_2))
elif int(select) == 2:
print(number_1, "-", number_2, "=",
subtract(number_1, number_2))
elif int(select) == 3:
print(number_1, "*", number_2, "=",
multiply(number_1, number_2))
elif int(select) == 4:
try:
assert number_2 != float(0)
except : # 0'a bolumde uyarip, bastan aliyoruz
print("Ooops, ZeroDivisionError!!! ")
else:
print(number_1, "/", number_2, "=",
divide(number_1, number_2))
new_operation = input("Would you like a new calculation, key y/n: ")
if new_operation == "y":
calculate()
elif new_operation == "n": # yeni islem yapmak istiyormuyuz
input("\nPress the enter key to exit")
else:
print("Invalid entry byebye..")
calculate()
| false |
e14c5eaf568fe7bee98aa5724889b276c819dc33 | ABCmoxun/AA | /AB/linux2/day15/exercise/text_process.py | 769 | 4.15625 | 4 | # 练习:
# 写一个程序,读入任意行的文字数据,当输入空行时结束输入
# 打印带有行号的输入结果:
# 如:
# 请输入: hello<回车>
# 请输入: tarena<回车>
# 请输入: bye<回车>
# 请输入: <回车>
# 输出如下:
# 第1行: hello
# 第2行: tarena
# 第3行: bye
def input_text():
"""读入键盘输入的文本数据,形成列表后返回"""
L = []
while True:
s = input("请输入: ")
if not s:
break
L.append(s)
return L
def output_text(L):
for t in enumerate(L, 1): # t= (0, "hello")
print("第%d行: %s" % t)
def main():
texts = input_text() # 得到用户输入的数据
print(texts)
output_text(texts)
main()
| false |
6dfb1ab16c62cbb69ebc30b9c946520cca5db530 | ABCmoxun/AA | /AB/linux1/day02/exercise/month.py | 545 | 4.15625 | 4 | # 2. 输入一年中的月份(1~12) 输出这个月在哪儿
# 个季度,如果输入的是其它的数,则提示您输入有错
month = int(input("请输入月份: "))
if 1 <= month <= 3: # C语言的写法:1 <= month && mond <= 3
print("春季")
# print("这是每年的第一个季节")
# print("hello")
# i = 100
# print(i)
# del i
elif 4 <= month <= 6:
print("夏季")
elif 7 <= month <= 9:
print("秋季")
elif 10 <= month <= 12:
print("冬季")
else:
print("您的输入有误!")
| false |
89b48ddf1b0de5b539b5a14f09ffc898963910fb | ABCmoxun/AA | /AB/linux2/day15/day14_exercise/ball.py | 781 | 4.1875 | 4 | # 1. 一个球从100米高度落下,每次落地后反弹高度为原高度的一半,再落下,
# 1) 写程序算出皮球从第10次落地后反弹高度是多少?
# 2) 球共经过多少米路径?
def ball_last_height(height, times):
for _ in range(times):
# 此处的语句会执行 times 次
height /= 2
return height
def ball_distance(height, times):
meter = 0 # 用来累加路程的和
for _ in range(times):
meter += height # 累加下落过程的路程
height /= 2 # 算出反弹高度
meter += height # 累加反弹过程的路程
return meter
height = ball_last_height(100, 10)
print("最终的高度是: ", height)
meter = ball_distance(100, 10)
print("球经历的路程是: ", meter) | false |
584deb529588d3d9cc24512f73f268708971049c | ABCmoxun/AA | /AB/linux1/day10/day09_exercise/03_minmax.py | 520 | 4.3125 | 4 | # 3. 写一个函数minmax, 可以给出任意个数字实参,返回这些实参的最小数和最大数,
# 要求两个数字形成元组后返回(最小数在前,最大数在后)
# 调用此函数,能得到实参的最小值和最大值
# def minmax(...):
# ....
# xiao, da = minmax(5,7,9,3,1)
# print("最小数是:", xiao)
# print("最大数是:", da)
def minmax(*args):
return (min(args), max(args))
xiao, da = minmax(5, 7, 9, 3, 1)
print("最小数是:", xiao)
print("最大数是:", da)
| false |
21fcca2c871e2b53b8452af98527bc659f251e41 | refkihidayat2/Basic_Python | /list.py | 637 | 4.28125 | 4 | #membuat list menggunakan []
name = ['Refki', 'Andra']
print(name[0])
#membuat list secara manual menggunakan append
name = []
name.append('Refki')
name.append('Andra')
print(name[0])
#pengulangan menggunakan for in untuk print secara menyeuruh
mylist = [1, 2, 3, 4, 5, 6]
mylist.append('refki')
mylist.append('andre')
for x in mylist:
print(x)
for x in range(5):
print(x)
for x in range(1,5):
print(x)
# poin ketiga dalam range adalah penambahan
for x in range(1,5,2):
print(x)
#mencetak mylist
mylist = ['andre', 'andru', 'andra', 'andro']
for x in mylist:
print(x)
for x in range(1,3):
print(mylist[x]) | false |
03b014976259feb1de19b4ae562e627a7a576c32 | openworm/neuronal-analysis | /src/dimensions_kit.py | 909 | 4.21875 | 4 | """
This is a small toolkit for mapping
one dimensional positive integers over a
closed interval onto a two dimensional
space.
So you can run a loop in one dimensions
and plot sequential points in two dimensions.
The universal solution for determining dimensionality
is sqrt[n](x), i.e. the nth root of x, and actually transforming
a point is the exact same procedure folded over n dimensions
You can also start playing around with things by setting scaling
preferences, axes ordering, etc. but I like this ad hoc solution
because it solves my problem and I don't need to think about it anymore
"""
# Returns a 2-tuple
def dimensions(n):
# Minimizes the dimensions of a grid (xy) to plot n elements
import math
s = math.sqrt(float(n))
x = int(math.ceil(s))
y = int(math.floor(s))
return (x,y)
def transform(dims, n):
x,y = dims
a = n/y
b = n%(y)
return (a,b)
| true |
eed8ace8af395343d8fc38b1b231d76759d6e7e7 | Sayakhatova/TSIS | /c3/10.arrays/b.py | 405 | 4.25 | 4 | #the length of an array
fruits=['apple', 'banana', 'cherry']
x=len(fruits)
print(x)
print('\n')
#looping array elements
for x in fruits:
print(x)
print('\n')
#adding array elements(append())
fruits.append('melon')
print(fruits)
print('\n')
#removing array element(pop())
fruits.pop(2) #at index 2
print(fruits)
print('\n')
#remove certain element
fruits.remove('banana')
print(fruits)
print('\n') | true |
0fa65363e8e36fc3e3522d2917e3154edd65e97d | Sayakhatova/TSIS | /c3/13.tuples/b.py | 415 | 4.3125 | 4 | #change tuple values
x=('apple', 'banana', 'strawberry', 'cherry')
y=list(x)
y[1]='kiwi'
y.append('orange') #add element
y.remove('apple') #remove element
x=tuple(y)
print(x)
print('\n')
#unpacking tuples
fruits=('apple', 'banana', 'cherry')
(aa, ab, ac)=fruits
print(aa, ab, ac, '\n')
#or
fruits1=('banana', 'apple', 'melon', 'strawberry', 'cherry')
(aa, *ab, ac)=fruits1
print(aa)
print(ab)
print(ac) | false |
75bb55926a4f27d939e3688276facde963493d5e | Irina-Roslaya/my_python | /my_func_sinus.py | 269 | 4.125 | 4 | import math
element=input('Введите вещественное число: ')
if element:
x=float(element)
if 0.2<=x<=0.9:
print(math.sin(x))
else:
print(1)
else:
print('Введите вещественное число!')
| false |
434b94042bcbffcdd119c0796869a570a16e654f | saurabhya/Random_Walks | /Graph Animation/Simple_1D_walk.py | 2,026 | 4.375 | 4 | """
By using Numpy we can easil simulate a simple random walk.
Given the number of steps N as an input argument, we can randomly generate N samples from the test set {+1, -1}
with an equal probability of 0.5. Then we will only use the cumsum function, to give us the cumulative sum
in every time step.
"""
import numpy as np
np.random.seed(1234)
def random_walk(N):
"""
Simulates a discrete random walk
: param int N : the numer of steps to take
"""
# event space : set of posible increments
increments = np.array([1, -1])
# the probability to generate any element
p = 0.5
# selecting values
random_increments = np.random.choice(increments, N, p)
# calculating random walk
random_walk = np.cumsum(random_increments)
return random_walk, random_increments
# generate a random walk
N = 500
X, epsilon = random_walk(N)
# normalizing the random walk using the Central Limit Theoram
X = X*np.sqrt(1./N)
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure(figsize= (20, 10))
ax = plt.axes(xlim= (0, N), ylim= (np.min(X)-0.5, np.max(X)+0.5))
line, = ax.plot([], [], lw= 2, color= 'red')
ax.set_xticks(np.arange(0, N+1, 50))
ax.set_yticks(np.arange(np.min(X)-0.5, np.max(X)+0.5, 0.2))
ax.set_title("Simple 1D random walk", fontsize= 22)
ax.set_xlabel('Steps', fontsize= 18)
ax.set_ylabel('Value', fontsize= 18)
ax.tick_params(labelsize= 16)
ax.grid(True, which= 'major', linestyle= '--', color= 'black', alpha= 0.4)
# initialization function
def init():
# creating empty plot/frame
line.set_data([],[])
return line,
# List to store x and y points
xdata, ydata = [], []
# animation function
def animate(i):
y = X[i]
xdata.append(i)
ydata.append(y)
line.set_data(xdata, ydata)
return line,
# call the animator
anim = animation.FuncAnimation(fig, animate, init_func=init, frames= N, interval =20, blit= True)
# anim.save('random_walk.gif') *error : movie writter not available
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.