blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
85caf17aad54055d0ace73bc1f70447ba870fed1 | ibm-5150/Python-HW | /HW-2/task_1.py | 529 | 4.28125 | 4 | a = int(input("Insert a: "))
b = int(input("Insert b: "))
a_positive = bool(a > 0)
print("Number a is positive: " + str(a_positive))
a_pair = bool(a % 2 == 0)
print("Number a is pair: " + str(a_pair))
a_multiple = bool(a % 13 == 0)
print("Number a is multiple of 13: " + str(a_multiple))
a_b_pair = bool(a % 2 == 0 and b % 2 == 0)
print("Numbers a, b are pair: " + str(a_b_pair))
a_b_even_odd = bool(a % 2 == 0 and b % 2 == 0 or a % 2 != 0 and b % 2 != 0)
print("Numbers a, b are even: " + str(a_b_even_odd)) | false |
bbc4aaf7932b8895de06fdf899830298f7e5448c | shashank2123/Regular_Expression-_python | /phone_number_matching_using_re.py | 418 | 4.46875 | 4 | #import regular expression mofule
import re
pattern='\d\d\d-\d\d\d-\d\d\d\d'
#if you want to give the different pattern uncomment below statement
#pattern=input('Enter the pattern :')
#give the text in which you have to extract the phone number
message=input("drop ur message :")
phone_re=re.findall(pattern,message)
for num in phone_re:
print("Here is your number : ",num)
print("The END") | true |
46376844a9896a533dac9f8ae2dee23714736ff1 | Fabrizio99/Learning-Python | /Tipos de Datos.py | 699 | 4.21875 | 4 | # se hacen comentarios con #
#imprimir mensaje
print("do not give up")
# tipos de numeros
# enteros
x=3
print(type(x))
# flotantes
x=3.23
print(type(x))
y=23e3
print(y)
y=12E2
print(y)
z = -87.7e-3
print(z)
#complejos
#se escribe "j" como la parte imaginaria
x=3+5j
print(x)
print(type(x))
# CASTEO
#int()
# Construye un numero entero de un entero, flotante y string
x=int(1)
print(x)
x=int(2.6) #redondea al numero anterior
print(x)
x=int("3")
print(x)
#float
x=float(3)
print(x)
x=float(2.34)
print(x)
x=float("3.23")
print(x)
x=float("3")
print(x)
#str(): construye un string desde una amplia variedad de tipos de datos
x=str('cadena de texto')
print(x)
x=str(2)
print(x)
x=str(3.0)
print(x) | false |
dee1afdec993b3af139fa6d4704a615a66297ab7 | mohd-tanveer/PythonAdvance | /lecture22Assertion.py | 987 | 4.375 | 4 | #lecture22
#Assertions:
'''--------------------------
assertion is use for DeBugging Purpose as an alternative of Print statements,
if we are using print statement that should be remove after fixing the problem how ver aseert is not need to be executed based on choice we can enabled or disable the assertion statements.
#Type of assert statments:
----------------------------------
1. Simple Version
-----------------------
syntax:
assert conditional_experession
AssertionError
2. Augmented version
syntax:
assert conditional_experession,'message'
AssertionError
'''
#type1
'''
x=10
assert x=810
print(x)
#type 2
x=10
assert x>10,'here x value should be > 10 but it is not'
print(x)
'''
def squareIt(x):
return x**2
assert squareIt(2)==4,'the square of 2 should be 4'
assert squareIt(3)==9,'the square of 2 should be 9'
assert squareIt(4)==16,'the square of 2 should be 16'
print(squareIt(2))
print(squareIt(3))
print(squareIt(4)) | true |
127ea617de37032cdd252d0759d5c45ebe480f0f | jessica-younker/Python-Exercises | /exercises/tuples/zoo.py | 1,008 | 4.6875 | 5 | # Create a tuple named zoo that contains your favorite animals.
# Find one of your animals using the .index(value) method on the tuple.
# Determine if an animal is in your tuple by using for value in tuple.
# Create a variable for each of the animals in your tuple with this cool feature of Python.
# # example
# (lizard, fox, mammoth) = zoo
# print(lizard)
# Convert your tuple into a list.
# Use extend() to add three more animals to your zoo.
# Convert the list back into a tuple.
zoo = ("zebra", "monkey", "manatee", "penguin", "lion", "gorilla")
print(zoo.index("zebra"))
possible_new_animals = ("snake", "manatee", "penguin", "guinea pig")
for possible_animal in possible_new_animals:
if possible_animal in zoo:
print("yes, animal in zoo")
else:
print("nope, don't have this one")
(zebra, monkey, manatee, penguin, lion, gorilla) = zoo
print(zebra)
zoo_list = list(zoo)
print(zoo_list)
zoo_list.extend(["puma", "gopher", "turtle"])
print(zoo_list)
zoo = tuple(zoo_list)
print(zoo)
| true |
5893204d4d87c6cea3769ad555a678e2fb988213 | eduhmc/CS61A | /Teoria/Class Code/Lecture 2.py | 1,252 | 4.4375 | 4 | # python DEMO1: "Names, Assignment, and User-Defined Functions"
pi
from math import pi
pi * 71 / 223
from math import sin
sin
sin(pi/2)
# Assignment
radius = 10
radius
2 * radius
area, circ = pi * radius * radius, 2 * pi * radius
area
circ
radius = 20
# Function values
max
max(3, 4)
f = max
f
max
f(3, 4)
max = 7
f(3, 4)
f(3, max)
max = f
f
max
f = 2
# f(3, 4)
# __builtins__.max
### Three ways to bind names to values
### 1. import
from operator import add, mul
### 2. assignment (you saw above) ... abstraction!
### 3. def statement ... abstraction!
# User-defined functions
def square(x):
return mul(x, x)
square
square(10)
square(add(4, 6))
square(square(3))
def sum_squares(x, y):
return square(x) + square(y)
sum_squares(3, 4)
sum_squares(5, 12)
def area():
return pi * radius * radius
area
area()
radius
pi * 20 * 20
radius = 10
area()
### visualize DEMO2:
from math import pi
tau = 2 * pi
### visualize DEMO3: discussion question
f = min
f = max
g, h = min, max
max = g
max(f(2, g(h(1, 5), 3)), 4)
### visualize DEMO4:
from operator import mul
def square(x):
return mul(x, x)
square(-2)
### visualize DEMO5: Name conflicts
from operator import mul
def square(square):
return mul(square, square)
square(4)
| true |
677c7c2fdfeec2f5a49312b26561c267b63e009e | boconlonton/python-deep-dive | /part-2/2-iterators/2-iterator.py | 1,656 | 4.40625 | 4 | """
An object is called Iterator if it implement the following methods:
- __iter__(): return the object itself
- __next__(): return the next item or raise StopIteration
Issues:
- Exhaustion problems!
"""
class Squares:
def __init__(self, length):
self.length = length
self.i = 0
def __next__(self):
if self.i >= self.length:
raise StopIteration
else:
result = self.i **2
self.i += 1
return result
def __iter__(self):
"""Defines the iterator protocol"""
return self
# Usage
sq = Squares(5)
for item in sq:
print(item)
# Usage with comprehension
sq = Squares(5)
lst = [(item, item+1) for item in sq]
print(lst)
# Usage with enumerate
sq = Squares(5)
lst = list(enumerate(sq))
print(lst)
# Usage with sorted()
sq = Squares(5)
lst = sorted(sq, reverse=True)
print(list(lst))
class Squares:
def __init__(self, length):
self.length = length
self.i = 0
def __next__(self):
print('__next__ called')
if self.i >= self.length:
raise StopIteration
else:
result = self.i **2
self.i += 1
return result
def __iter__(self):
"""Defines the iterator protocol"""
print('__iter__ called')
return self
# How Python internally iterates an iterator
sq = Squares(5)
for item in sq:
print(item)
sq = Squares(5)
lst = [item for item in sq if item % 2 == 0]
sq = Squares(5)
sq_iterator = iter(sq)
while True:
try:
item = next(sq_iterator)
print(item)
except StopIteration:
break
| true |
6081cf27b2906e07a0d05e0476a386e53d783112 | boconlonton/python-deep-dive | /part-2/4-iteration-tools/5-chaining_teeing.py | 1,789 | 4.15625 | 4 | """Chaining & Teeing"""
from itertools import chain, tee
# Chaining
l1 = (i**2 for i in range(4))
l2 = (i**2 for i in range(4, 8))
l3 = (i**2 for i in range(8, 12))
# for gen in l1, l2, l3:
# for item in gen:
# print(item)
def chain_iterables(*iterables):
"""Demonstrate how itertools.chain() works"""
for iterable in iterables:
yield from iterable
# Usage
l1 = (i**2 for i in range(4))
l2 = (i**2 for i in range(4, 8))
l3 = (i**2 for i in range(8, 12))
# for item in chain_iterables(l1, l2, l3):
# print(item)
# Usage with chain()
l1 = (i**2 for i in range(4))
l2 = (i**2 for i in range(4, 8))
l3 = (i**2 for i in range(8, 12))
# for item in chain(l1, l2, l3):
# print(item)
l1 = (i**2 for i in range(4))
l2 = (i**2 for i in range(4, 8))
l3 = (i**2 for i in range(8, 12))
lists = [l1, l2, l3]
for item in chain(lists):
"""This simply returns the generator
NOT iterate over it"""
print(item)
for item in chain(*lists):
"""This iterate over the returned generator
BUT it is NOT lazy"""
print(item)
# Another example
# def squares():
# yield (i**2 for i in range(4))
# yield (i**2 for i in range(4, 8))
# yield (i**2 for i in range(8, 12))
#
#
# for item in chain(*squares()):
# """This iterate over the returned generator
# BUT not lazy"""
# print(item)
#
#
# # itertools.chain.from_iterable()
# c = chain.from_iterable(squares())
# for item in c:
# "Lazy evaluation"
# print(item)
#
#
# def chain_from_iterable(iterable):
# """How chain.from_iterable works"""
# for i in iterable:
# yield from i
#
#
# # tee()
# def squares(n):
# for i in range(n):
# yield i**2
#
#
# gen = squares(10)
# iters = tee(gen, 3) # Copy into 3 independent iterator
# print(iters)
| false |
16dcb28955930caff5c78e1ac0b847619574e83a | boconlonton/python-deep-dive | /part-2/3-generators/3-making_an_iterable_from_generator.py | 476 | 4.15625 | 4 | """Making an Iterable from a Generator"""
class Squares:
"""An iterable that return square result"""
def __init__(self, n):
self._n = n
def __iter__(self):
"""Iterable Protocol"""
return Squares.squares_gen(self._n)
@staticmethod
def squares_gen(n):
"""A generator that return result of n**2"""
for i in range(n):
yield i ** 2
# Usage
sq = Squares(5)
for num in sq:
print(num)
print(list(sq))
| true |
26d2b4cc58759cad51ee66c9475dca0179fdfa48 | zhuyuedlut/advanced_programming | /chapter8/define_format.py | 990 | 4.125 | 4 | format_dict = {
'ymd': '{d.year}-{d.month}-{d.day}',
'mdy': '{d.month}/{d.day}/{d.year}',
'dmy': '{d.day}/{d.month}/{d.year}'
}
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __format__(self, format_type='ymd'):
"""
:param format_type: 格式化类型,默认使用 ymd 方式
:return:
"""
if not format_type:
format_type = 'ymd'
fmt = format_dict[format_type]
return fmt.format(d=self)
curr_data = Date(2020, 5, 6)
print(f'default format: {format(curr_data)}')
print(f"use mdy format: {format(curr_data, 'mdy')}")
print(f'ymd style date is: {curr_data:ymd}')
print(f'mdy style date is: {curr_data:mdy}')
from datetime import date
curr_data = date(2020, 5, 6)
print(f'default format: {format(curr_data)}')
print(f"date info is: {format(curr_data,'%A, %B %d, %Y')}")
print(f'The date is {curr_data:%d %b %Y}')
| false |
b21a9b070f78dd7d934e65cd3bfe17b87e863078 | khalid-joomun/GuessTheNumber-game | /NumberGuessing/NumberGuessing.py | 980 | 4.34375 | 4 | # Number guessing game a.k.a HiLo
# The player enters a number. The program says whether the number to be guessed
# is higher or lower than the user's guess.
# This continues until the player guesses the right number
import random
number = random.randint(-100, 100)
attempt = 1
guess = 101
while (guess != number):
try:
guess = int(input("Enter your guess: "))
while (guess != number):
if (number > guess):
print("Number is greater than your guess. Aim higher")
guess = int(input("Enter your guess: "))
elif (number < guess):
print("Number is smaller than your guess. Aim lower")
guess = int(input("Enter your guess: "))
attempt += 1
print("Congralutions! You've guessed the number right! You have made ",
attempt, " attempts")
except(TypeError, ValueError, NameError):
print("Error! You must enter an integer number only")
| true |
49cb24a5d6d8e5ea0741bc387e22f28a5e7917b3 | dmccuk/python | /lists.py | 2,170 | 4.15625 | 4 | my_list1 = [1,2,3,4]
print(my_list1)
print(type(my_list1))
list1 = ["Dennis",3.4,5.6,"Lists are Flexible",14]
print(list1)
list2 = [1,2,3,4,5,6,7,8,9,0,0,0,5]
print(len(list2))
my_list3 = list("Hello World!")
print(my_list3)
my_list = [1,2,3,4,5,"a","b",3.14]
print(my_list)
print(my_list[0])
print(my_list[2])
print(my_list[5])
print(my_list[-1]) # print last entry in the list
print(len(my_list)) # print length of list - integer
print(my_list[len(my_list)-1]) # print last character
print(my_list[2:]) # get everything after the 2nd in the list
print(my_list[:4]) # get everything up to 4th in the list
print(my_list[::2]) # get every 2nd item from the list
print(my_list[::-1]) # Reverse list
list1 = [1,2,3]
list2 = [4,5,6]
print(list1 + list2) # concatinate both lists
print(list2 + list1) # concatinate both lists
new_list = list1 + list2
print(new_list)
print(list1 * 3) # you get 3 of the last list
list1 *= 3
print(list1) # list1 now = 3 of the same
my_list[0] = 8
print(my_list)
another_list = [1,2,3,4,5]
print(another_list)
another_list[:2] = [10,20]
print(another_list)
# METHODS
# append to a list
list4 = [1,2,3,4,5]
print(list4)
list4.append(6)
print(list4)
list4.append("python")
print(list4)
# remove elements from list
list4.pop() #last added element
print(list4)
list4.pop(1) # remove the second element
print(list4)
# using DEL for lists:
list5 = [1,2,3,4,5]
del list5 # delete the list completely
list5 = [1,2,3,4,5]
del list5[3] # delete only the 3rd (4th) element
print(list5)
del list5[1:3] # deletes elements 1-3
print(list5)
# SORT Methos
numbers = [23,456,54,232,1,2,3,67,88,7,654]
print(numbers)
numbers.sort() # sorts list into numbr order - low to high
print(numbers)
numbers.sort(reverse = True) # reverse the order
print(numbers)
cars = ["bmw","merc","audi","bugatti"]
print(cars)
cars.sort()
print(cars)
cars.sort(reverse = True)
print(cars)
# Nested lists
l = [1,2,3, [4,5], [6,7,8]]
print(l)
list1 = [1,2,3]
list2 = [4,5,6]
list3 = [7,8,9]
new_list = [list1,list2,list3]
print(new_list)
print(new_list[1]) # grab the second list (list2)
print(new_list[1][1]) # grab the second list and second number
| true |
39d8c938441d8babf1617b426d4517b7f7207d0d | ruzguz/python-stuff | /comprehension/remove_vowels.py | 201 | 4.15625 | 4 | VOWELS = 'AaEeIiOoUu'
def remove_vowels(str):
return ''.join([c for c in str if c not in VOWELS])
if __name__ == '__main__':
str = input('Type something: ')
print(remove_vowels(str))
| false |
8b62302ed392858b97950faee80d4894a4402cf0 | ruzguz/python-stuff | /17-modules/operations.py | 1,183 | 4.125 | 4 | import mathf
def print_menu():
print('1 - sum')
print('2 - subtraction')
print('3 - multiplication')
print('4 - square number')
print('5 - division')
if __name__ == '__main__':
while True:
print('Welcome to the calculator:')
print_menu()
option = input('Select an option: ')
if option == '1':
a = int(input('Introduce \'a\' value: '))
b = int(input('Introduce \'b\' value: '))
print(mathf.sum(a, b))
elif option == '2':
a = int(input('Introduce \'a\' value: '))
b = int(input('introduce \'b\' value: '))
print(mathf.subtraction(a, b))
elif option == '3':
a = int(input('Introduce \'a\' value: '))
b = int(input('Introduce \'b\' value: '))
print(mathf.mult(a, b))
elif option == '4':
a = int(input('Introduce a number: '))
print(mathf.square(a))
elif option == '5':
a = int(input('Introduce \'a\' value: '))
b = int(input('Introduce \'b\' value: '))
print(mathf.division(a, b))
else:
break
| false |
1716b42edbcbd4eabb3111947f27abd9a9d632a3 | ruzguz/python-stuff | /4-functions/test.py | 537 | 4.21875 | 4 | # -*- coding:utf8 -*-
import turtle
# Is called when the program start
def main():
window = turtle.Screen()
dave = turtle.Turtle()
# draw square
draw_square(dave)
turtle.mainloop()
# Fundtion to draw a square
def draw_square(t):
lenght = int(input('square size: '))
for i in range(4):
draw_line_and_turn(t, lenght)
# Function to draw a line and turn the turtle
def draw_line_and_turn(t, lenght):
t.forward(lenght)
t.left(90)
if __name__ == '__main__':
main()
| true |
09a889f867f388761c051331a443e5dbd97460e2 | brisa123/python_practice_programs | /fizzbuzz.py | 341 | 4.1875 | 4 | import os
#if number divisible by 3, print fizz, if divisible by 5, print buzz, if divisible by both, print fizzbuzz,else print num
for num in range(1,100):
if (num%3==0 and num%5==0):
print("fizzbuzz")
elif(num%3==0):
print("fizz")
elif(num%5==0):
print("buzz")
else:
print(num) | true |
57a086a2350cddbf305407d94b21a0e1f6ddb91b | kranthikiranm67/Second_Assignment | /02_flip_123.py | 1,164 | 4.3125 | 4 | """
You are given an integer n consisting of digits 1, 2 and 3 and
you can flip one digit to a 3.
Return the maximum number you can make.
Example 1
Input
n = 123
Output
323
Explanation
We flip 1 to 3
Example 2
Input
n = 333
Output
333
Explanation
Flipping doesn't help.
"""
import unittest
# Implement the below function and run this file
# Return the output, No need read input or print the ouput
# This approach involves more complexity with no mathematical logic
def flip_123(num):
# code here
# DO NOT TOUCH THE BELOW CODE
class TestFlip123(unittest.TestCase):
def test_01(self):
self.assertEqual(flip_123(123), 323)
def test_02(self):
self.assertEqual(flip_123(333), 333)
def test_03(self):
self.assertEqual(flip_123(3123), 3323)
def test_04(self):
self.assertEqual(flip_123(33123), 33323)
def test_05(self):
self.assertEqual(flip_123(33223), 33323)
def test_06(self):
self.assertEqual(flip_123(13333333), 33333333)
def test_07(self):
self.assertEqual(flip_123(211111111111), 311111111111)
if __name__ == '__main__':
unittest.main(verbosity=2)
| true |
b49a990f2050f7e369c9adece857d7da2682e66c | raysomnath/Python-Basics | /Class__str__repr__init__private_protected_public/public_protected_private_attributes.py | 2,516 | 4.3125 | 4 | # There are two ways to restrict the access to class attributes:
# First, we can prefix an attribute name with a leading underscore "_".
# This marks the attribute as protected. It tells users of the class not to use this attribute unless, somebody writes a subclass
# Second, we can prefix an attribute name with two leading underscores "__". The attribute is now inaccessible and invisible from outside.
# It's neither possible to read nor write to those attributes except inside of the class definition itself.
# Naming Type Meaning
# name Public These attributes can be freely used inside or outside of a class definition.
# _name Protected Protected attributes should not be used outside of the class definition, unless inside of a subclass definition.
# __name Private This kind of attribute is inaccessible and invisible. It's neither possible to read nor write to those attributes,
# except inside of the class definition itself.
class A:
def __init__(self):
self.__priv = "I am private"
self._prot = "I am protected"
self.pub = "I am public"
# >>> from public_protected_private_attributes import A
# >>> x = A()
# >>> x.pub
# 'I am public'
# >>> x._prot
# 'I am protected'
# >>> x.__priv
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# AttributeError: 'A' object has no attribute '__priv'
# >>>
class Robot:
def __init__(self, name=None,build_year=2000):
self.__name = name
self.__build_year = build_year
def say_hi(self):
if(self.__name):
print("Hi, I am " + self.__name)
else:
print("Hi, I am a robot without a name")
def set_name(self,name):
self.__name = name
def get_name(self):
return self.__name
def set_build_year(self,by):
self.__build_year = by
def get_build_year(self):
return self.__build_year
def __repr__(self):
return "Robot('"+ self.__name + "', " + str(self.get_build_year) + ")"
def __str__(self):
return "Name: " + self.__name + ", Build Year: " + str(self.__build_year)
if __name__ == "__main__":
x = Robot("Marvin", 1979)
y = Robot("Caliban", 1943)
for rob in [x, y]:
rob.say_hi()
if rob.get_name() == "Caliban":
rob.set_build_year(1993)
print("I was build in the year " + str(rob.get_build_year()) + "!")
| true |
44c75ce287e91308b7d15f743aef0b9fc7c7d919 | raysomnath/Python-Basics | /Class__str__repr__init__private_protected_public/the__init__method.py | 850 | 4.5 | 4 | # __init__ is a method which is immediately and automatically called after an instance has been created.
# This name is fixed and it is not possible to chose another name. The __init__ method is used to initialize an instance.
# The __init__ method can be anywhere in a class definition, but it is usually the first method of a class, i.e. it follows right after the class header.
class A:
def __init__(self):
print("__init__ has been executed")
x = A()
# >> __init__ has been executed
class Robot:
def __init__(self, name=None):
self.name = name
def say_hi(self):
if self.name:
print("Hi, I am " + self.name)
else:
print("Hi, I am a robot without a name")
x = Robot()
x.say_hi()
# >> Hi, I am a robot without a name
y = Robot("Marvin")
y.say_hi()
# >> Hi, I am Marvin
| true |
e30f732155cf705bfe538ee1df522859661b66b7 | raysomnath/Python-Basics | /Arithmetic_Operators.py | 1,197 | 4.3125 | 4 | import sys
numbers = 1+2*3 / 4.0
print (numbers)
remainder = 11 % 3
print(remainder)
# using two multiplication symbol makes a power relationship
squared = 7 ** 2
cubed = 2 ** 3
print(squared)
print(cubed)
#python supports string concatenation
helloworld = "hello" + " " + "world"
print(helloworld)
#Python also supports multiplying strings to form a string with a repeating sequence:
lotsofhellos = "hello" * 10
print(lotsofhellos)
#Lists can be joined with the addition operators:
even_numbers = [2,4,6,8]
odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers
print(all_numbers)
#Just as in strings, Python supports forming new lists with a repeating sequence using the multiplication operator:
print([1,2,3]*3)
x = object()
y = object()
#TODO: change this code
x_list = [x] *10
y_list = [y] *10
big_list = []
big_list = x_list + y_list
print("x_list contains %d objects" % len(x_list))
print("y_list contains %d objects" % len(y_list))
print("big_list contains %d objects" % len(big_list))
# testing code
if x_list.count(x) == 10 and y_list.count(y) == 10:
print("Almost there...")
if big_list.count(x) == 10 and big_list.count(y) == 10:
print("Great!")
| true |
174b65aa091f61e733f5c5fae74f111184a3146a | raysomnath/Python-Basics | /args_kwargs/args_kwargs.py | 1,004 | 4.46875 | 4 | import sys
# *args and **kwargs are mostly used in function definitions.
# *args and **kwargs allow you to pass a variable number of arguments to a function.
# What variable means here is that you do not know beforehand how many arguments
# can be passed to your function by the user so in this case you use these two keywords.
# *args is used to send a non-keyworded variable length argument list to the function.
# Here’s an example to help you get a clear idea:
def test_var_args(f_arg, *argv):
print('first normal arg:',f_arg)
for arg in argv:
print('another arg through *argv:',arg)
test_var_args('yasoob','python','eggs','test')
# **kwargs allows you to pass keyworded variable length of arguments to a function.
# You should use **kwargs if you want to handle named arguments in a function.
# Here is an example to get you going with it
def greet_me(**kwargs):
for key, value in kwargs.items():
print('{0} = {1}'.format(key,value))
greet_me(name="yasoob") | true |
4ba77af2125a0d44ee0ce4ac29b67afa8e89bc63 | raysomnath/Python-Basics | /Decorator/ReturningFunctoinsFromFunctions.py | 777 | 4.375 | 4 | import sys
# Python also allows you to use functions as return values.\
# The following example returns one of the inner functions from the outer parent() function:
def parent(num):
def first_child():
return "Hi I am Emma"
def second_child():
return "Call me Liam"
if num == 1:
return first_child
else:
return second_child
# Note that you are returning first_child without the parentheses.
# Recall that this means that you are returning a reference to the function first_child
first = parent(1)
second = parent(2)
print(first)
print(second)
# You can now use first and second as if they are regular functions,
# even though the functions they point to can’t be accessed directly:
print(first())
print(second()) | true |
916f03b0f1df29e5381bd2f2929d3bacf88bcb84 | brandon-todd/alien_invasion_game | /Downloads/project2/project2/main.py | 1,904 | 4.25 | 4 | """
This takes temperature of cities in 5 different days and cost of five hotels
to find the highest average temperature of a trip to each city in the dictionary and
plans hotels to stay at along the way to maximize your budget in this example of $850.
"""
from itertools import permutations, combinations_with_replacement
city_temps = {
"Casa_Grande": [76, 69, 60, 64, 69],
"Chandler": [77, 68, 61, 65, 67],
"Flagstaff": [46, 35, 33, 40, 44],
"Lake Havasu City": [71, 65, 63, 66, 68],
"Sedona": [62, 47, 45, 51, 56]
}
hotel_rates = {
"Motel 6": 89,
"Best Western": 109,
"Holiday Inn Express": 115,
"Courtyard by Marriott": 229,
"Residence Inn": 199,
"Hampton Inn": 209
}
def temp_func(route):
"""This function takes permutations of possible routes of the trip in the dictionary database
and returns the average temperature of that route"""
temp = 0
for i in range(len(route)):
temp += city_temps[route[i]][i]
return temp/days
def cost_func(hotels):
"""This function takes combinations of possible hotels for the trip in the dictionary database and
returns the total cost to stay at those hotels"""
return sum([hotel_rates[i] for i in hotels])
if __name__ == "__main__":
cities = list(city_temps.keys())
hotels = list(hotel_rates.keys())
days = len(city_temps)
HOTEL_BUDGET = 850
perms = list(permutations(city_temps, days))
best = max([(temp_func(p), p) for p in perms])
print(f'Here is your best route: {best[1]}\nthe average of the daily max temp. is {best[0]} degrees F')
combs = list(combinations_with_replacement(hotel_rates, days))
best_option = min(combs, key=lambda t: HOTEL_BUDGET - cost_func(t) if HOTEL_BUDGET >= cost_func(t) else HOTEL_BUDGET)
print(f'To max out your hotel budget, stay at these hotels: {best_option},\ntotaling ${cost_func(best_option)}')
| true |
f3272bc5d1cad2c5efd9184c2db469821e5fb671 | mohak007/adrian-github-list_and_strings | /program 11.py | 279 | 4.25 | 4 | #Write a function that merges two sorted lists into a new sorted list. [1,4,6],[2,3,5] → [1,2,3,4,5,6]. You can do this quicker than concatenating them followed by a sort.
lista=[1,4,6]
listb=[2,3,5]
lista.sort()
listb.sort()
listc=lista +listb
listc.sort()
print(listc) | true |
4bf3b3e5b97721fb459c6a799d1ff52be24e89e6 | sanchezpe/pythonproject3 | /pa3.py | 1,276 | 4.15625 | 4 | #ask user 1 for information
name1=input("Enter name of customer #1: ")
gallons1=eval(input("Enter gallons for customer #1: "))
question1=input("Is customer #1 residential or commercial? ")
print("------------------------------------------------------")
#aks user 2 for information
name2=input("Enter name of customer #2: ")
gallons2=eval(input("Enter gallons for customer #2: "))
question2=input("Is customer #2 residential or commercial? ")
#calculates cost for user 1
if question1=="residential":
cost1=1.15*gallons1/1000
elif question1=="commercial":
cost1=100+0.45*gallons1/1000
#calculates cost for user 2
if question2=="residential":
cost2=1.15*gallons2/1000
elif question2=="commercial":
cost2=100+0.45*gallons2/1000
print("------------------------------------------------------")
print()
#print output
print(format("Name",'14'),format("Type",'14'),format("Gallons",'14'),format("Charge",'14'))
print("------------------------------------------------------")
print(format(name1[0].upper()+name1[1:12],'14'),format(question1.upper(),'14'),format(gallons1,'7.0f'),format(cost1,'13.2f'))
print(format(name2[0].upper()+name2[1:12],'14'),format(question2.upper(),'14'),format(gallons2,'7.0f'),format(cost2,'13.2f'))
| true |
361253b2f7a7378f3287399f1d3e6d20d06aa725 | dchasepdx/rpg-dice-roller | /rollerFinal.py | 1,256 | 4.1875 | 4 | from random import randint
count = 1 #initialize a count. start at 1 for more intuitive print results
#get input for number of dice and sides
userRoll = input("Enter number and sides of dice like so: xdy. x is number of dice and y is number of sides: ")
dice_total = 0 #initilaze dice_total
#turn input into a list and store each index as a variable
results = userRoll.split("d")
results = [int(i) for i in results]
print(results) #print for testing
dice_num = results[0] #sets variable for number of dice
dice_sides = results[1] #sets variable for number of sides
print(dice_num) #bug testing
print(dice_sides) #bug testing
while True:
dice_sides = results[1] #sets dice_sides to equal number of sides every loop.
dice_sides = randint(1,dice_sides) #assigns the random number
dice_total = dice_total + dice_sides
print("Die", count, "is:", dice_sides) #prints the result of each die
print(dice_sides) #bug testing
count += 1 #increment the counter
#checks if all dice have been "rolled." If so, prints total and ends loop. if not, runs loop again
if count >= dice_num + 1:
print("And the total is:", dice_total)
break
| true |
a960307e51a41398e3092dfba2550339e7cdb2ef | Aitd1/learnPython | /实现各种常用算法/栈/stackTest.py | 2,033 | 4.25 | 4 | class Stack(object):
def __init__(self, limit=10):
self.stack = [] # 存放元素
self.limit = limit # 栈容量极限
def push(self, data):
'''
思路:
理解:压入push:即将新的元素放在栈顶
步骤:
1.检查栈是否溢出。溢出并抛出异常。
2.然后添加新元素。
'''
# 判断栈是否溢出
if len(self.stack) >= self.limit:
raise IndexError('超出栈容量极限')
self.stack.append(data)
def pop(self):
'''
出栈:即移出栈顶的元素。使用pop()方法,同时能获取移出的新元素。
步骤:
1.判定栈是否为空栈,if self.stack :
2.不为空则,返回移出的新元素 return self.stack.pop();为空,则抛出异常。
'''
if self.stack: # 判断列表是否为空
return self.stack.pop()
else:
raise IndexError('pop from an empty stack') # 空栈不能被弹出
#添加其他函数:
'''
需求:
1.查看栈顶的元素。
2.判断栈是否为空
3.返回栈的大小
'''
def peek(self):
if self.stack:
return self.stack[len(self.stack)-1]
# return self.stack[-1]
def is_empty(self):
#
return not bool(self.stack)
def size(self):
#返回栈的大小.
return len(self.stack)
def balanced_parentheses(parentheses):
stack = Stack(len(parentheses))
for parenthesis in parentheses:
if parenthesis == '(':
stack.push(parenthesis)
elif parenthesis == ')':
if stack.is_empty():
return False
stack.pop()
return stack.is_empty()
if __name__=='__main__':
examples = ['((()))','((())','(()))']
print('Balanced parenrheses demonstartion:\n')
for example in examples:
print(example+': '+ str(balanced_parentheses(example))) | false |
76987196ee98cd77e1f0142547fac3de5c50c885 | cglsoft/DataScience-FDSI | /Semana 1/Aula5/cast_list.py | 1,057 | 4.21875 | 4 | # Quiz: Lista do elenco de Flying Circus
# Você criará uma lista dos atores que apareceram no programa de televisão Monty Python's Flying Circus.
# Escreva uma função chamada create_cast_list, que recebe um nome de arquivo como entrada e retorna uma
# lista de nomes de atores.
# Ela será executada no arquivo flying_circus_cast.txt (essas informações foram coletadas de imdb.com).
# Cada linha desse arquivo consiste no nome de um ator, uma vírgula e, depois, algumas informações
# (desordenadas) sobre os papéis que eles desempenharam no programa. Você precisará extrair somente
# o nome e adicioná-lo a uma lista. Você pode usar o método .split() para processar cada linha.
def create_cast_list(filename):
cast_list = []
# usar with para abrir o arquivo filename
with open(filename) as f:
# use a sintaxe do laço for para processar cada linha
# e adicione o nome do ator a cast_list
for line in f:
line_data = line.split(',')
cast_list.append(line_data[0])
return cast_list | false |
9b66b129cefbe2f3dc32f33cf523504fc362e678 | daygregory/PFAB_3_2014 | /list.py | 410 | 4.125 | 4 | list1 = ['English' , 'Spanish' , 'Math' , 'Biology' , 'Computer Science' , 'Gym' , 'Music' , 'Theater']
gpas = [ 3.12 , 4.0, 2.57, 3.33, 3.01, 2.22, 1.98]
#print first member of the list list1
print list1[0]
print list1[3]
print gpas[2]
print (gpas[0] + gpas[1])/2
#Number inside the [x] is known as the index
print list1[1:4] #Start at 1 Stop BEFORE 4
print gpas[0:3] #Start at 9 Stop BEFORE 3
| true |
770b0cf4eb77bf4f7985e94a0fe100cec45dd7db | Ash0492/Python | /practice8.py | 1,771 | 4.375 | 4 |
import random
#The Game of Rock, Paper and Scissors
#Rules of the game
print('Winning rules of the game are as follows:\n'+
'Rock VS Paper => Paper wins\n'
+'Rock VS Scissor => Rock Wins\n'
+'Paper VS Scissor => Scissor wins')
while True:
print("Please enter one the below choices:\n"+ "1. Rock\n"+"2.Paper\n"+ "3.Scissors\n")
user_choice = int(input("Please enter your choice(user turn):"))
while user_choice > 3 or user_choice < 1:
user_choice = int(input("enter valid input: "))
if user_choice == 1:
choice_name = "Rock"
elif user_choice == 2:
choice_name = "Paper"
else:
choice_name = "Scissor"
print("user choice is: " + choice_name)
print("\nNow its computer turn.......")
comp_choice = random.randint(1, 3)
while comp_choice == choice:
comp_choice = random.randint(1, 3)
if comp_choice == 1:
comp_choice_name = 'Rock'
elif comp_choice == 2:
comp_choice_name = 'paper'
else:
comp_choice_name = 'scissor'
print("Computer choice is: " + comp_choice_name)
print(choice_name + " V/s " + comp_choice_name)
if((user_choice == 1 and comp_choice == 2) or
(user_choice == 2 and comp_choice ==1 )):
print("paper wins => ", end = "")
result = "paper"
elif((user_choice == 1 and comp_choice == 3) or
(user_choice == 3 and comp_choice == 1)):
print("Rock wins =>", end = "")
result = "Rock"
else:
print("scissor wins =>", end = "")
result = "scissor"
if result == choice_name:
print("<== User wins ==>")
else:
print("<== Computer wins ==>")
print("Do you want to play again? (Y/N)")
ans = input()
if ans == 'n' or ans == 'N':
break
print("\nThanks for playing")
| true |
241690cbb760e66d91eee3d5aeb6ebcd0d0d82f8 | mcorley1/Intro_Biocom_ND_319_Tutorial5 | /Exercise_5_Challenge_Complete.py | 1,667 | 4.1875 | 4 | #Completing Part 1
import pandas #loading the pandas package to use data frames
data = pandas.read_csv("wages.csv", header=0,sep=",") #loads the file
gender_yrsexp = data.iloc[:,0:2] #subsets data by selecting the first two columns
uniquegender = gender_yrsexp.drop_duplicates() #drops duplicates, like the unique function in unix
uniquegender.shape #displays shape of array
sortgender = uniquegender.sort_values(["gender","yearsExperience"])
sortgender.to_csv("part1done.txt", sep=" ")
#Completing Part 2
import pandas
df=pandas.read_csv('wages.csv')
#df=wages.csv data
#Highest earner
highest_earner=df.nlargest(1,'wage')
#output is under highest_earner (male,5,11,39.808917197)
#Lowest earner
lowest_earner=df.nsmallest(1,'wage')
#Output is under lowest_earner (female,9,11,0.07655561)
#Number of females in the top 10
num_of_females=df[df['wage']>=df['wage'].nlargest(10).iloc[-1]]['gender'].eq('female').sum()
#Output is under num_of_females (=2)
#Completing Part 3
import pandas
#Define wages
wages=pandas.read_csv('wages.csv')
#Select for the people who didn't finish school(i.e. 12yrs of school)
education12=wages[wages.yearsSchool==12]
#Calculate the minimum wage for people with 12yrs of school
minimum12=min(education12.wage)
#Select for the people who did finish school(i.e. 16yrs of school)
education16=wages[wages.yearsSchool==16]
#Calculate the minimum wage for people with 16yrs of school
minimum16=min(education16.wage)
#Calculate the difference between the minimum wage for those who finished school vs. those who didn't
print(minimum16-minimum12)
#Difference is 4.0816223772 | true |
413a12a90d2a8675efdc6d0e5a45f8d076a4cc36 | shanthanaroja/guessing_number | /number_guessing.py | 451 | 4.25 | 4 | import random
number=random.randint(1,9)
chance=0
while chance<=5:
guess=int(input("Enter a number:"))
if guess<number:
print("Your guess is too low guess a number greater than",guess)
elif guess>number:
print("Your guess is too high guess a number less than",guess)
else:
print("Congrats!! Your guess is correct")
break
chance=+1
if chance>5:
print("Your chances are over try again later")
| true |
51e5618900a8414c4cfb43eb8147c21e03db090f | markodevcic/codingbats-python | /string-1/extra_end.py | 338 | 4.3125 | 4 | # Given a string, return a new string
# made of 3 copies of the last 2 chars
# of the original string. The string
# length will be at least 2.
#
#
# extra_end('Hello') → 'lololo'
# extra_end('ab') → 'ababab'
# extra_end('Hi') → 'HiHiHi'
def extra_end(str):
if len(str) >= 2:
return str[-2:] * 3
print(extra_end('Hi')) | true |
f92443dc59f296ed7f7380219b306eba3faf25a6 | gaoxy123/Python001-class01 | /week07/my_zoo.py | 2,994 | 4.21875 | 4 | '''
背景:在使用 Python 进行《我是动物饲养员》这个游戏的开发过程中,有一个代码片段要求定义动物园、动物、猫三个类。
这个类可以使用如下形式为动物园增加一只猫:
复制代码
if __name__ == '__main__':
# 实例化动物园
z = Zoo('时间动物园')
# 实例化一只猫,属性包括名字、类型、体型、性格
cat1 = Cat('大花猫 1', '食肉', '小', '温顺')
# 增加一只猫到动物园
z.add_animal(cat1)
# 动物园是否有猫这种动物
have_cat = getattr(z, 'Cat')
具体要求:
定义“动物”、“猫”、“动物园”三个类,动物类不允许被实例化。
动物类要求定义“类型”、“体型”、“性格”、“是否属于凶猛动物”四个属性,是否属于凶猛动物的判断标准是:“体型 >= 中等”并且是“食肉类型”同时“性格凶猛”。
猫类要求有“叫声”、“是否适合作为宠物”以及“名字”三个属性,其中“叫声”作为类属性,猫类继承自动物类。
动物园类要求有“名字”属性和“添加动物”的方法,“添加动物”方法要实现同一只动物(同一个动物实例)不能被重复添加的功能。
'''
from abc import ABCMeta, abstractmethod
class Zoo(object):
def __init__(self, zoo_name):
self.zoo_name = zoo_name
self.animals = []
def add_animal(self, instance):
if instance in self.animals:
print(f'{type(instance).__name__} existed')
else:
self.animals.append(instance)
self.__dict__[type(instance).__name__] = instance
class Animals(metaclass=ABCMeta):
# def __new__(cls, *args, **kwargs):
# raise Exception('this class can not instantiate')
@abstractmethod
def __init__(self, a_type, a_size, a_character):
self.a_type = a_type
self.a_size = a_size
self.a_character = a_character
@property
def is_ferocious_animal(self):
if self.a_size != '小' and self.a_type == '食肉' and self.a_character == '凶猛':
return True
return False
class Cat(Animals):
voice = '喵~~~'
def __init__(self, name, a_type, a_size, a_character):
super(Cat, self).__init__(a_type, a_size, a_character)
self.name = name
self.is_suitable_pet = 'yes'
if __name__ == '__main__':
# 实例化动物园
z = Zoo('时间动物园')
# 实例化一只猫,属性包括名字、类型、体型、性格
cat1 = Cat('大花猫 1', '食肉', '小', '温顺')
print(f'Cat : "{Cat.voice}"')
print(f'cat1 is pet ? {cat1.is_ferocious_animal}')
print(f'cat1 is beast ? {cat1.is_ferocious_animal}')
# 增加一只猫到动物园
z.add_animal(cat1)
z.add_animal(cat1)
# 动物园是否有猫这种动物
have_cat = getattr(z, 'Cat')
print(f'zoo has cat? {bool(have_cat)}.')
c = Animals('', '', '')
| false |
4ee55da716a17407829b8e26482a779216789164 | mdtitong/ITS320 | /ITS320_CTA1_Option2.py | 449 | 4.375 | 4 | # Read two integers and print two lines. The first line should contain integer division, //, the second line
# should contain float division, /, and the third line should contain modulo division, %. You do not need to
# perform any rounding or formatting operations.
num1 = int(input("First number: "))
num2 = int(input("Second number: "))
divide = num1 // num2
fdivide = num1 / num2
modulo = num1 % num2
print(divide)
print(fdivide)
print(modulo)
| true |
8653611091f2f42ab7d3e5de445f04cd89532e57 | abir-hasan/PythonGround | /scratch_files/scratch_section_2.py | 1,351 | 4.15625 | 4 | ############### Section 2 Language Overview ################
# Example of import
import platform
version = platform.python_version()
print('this is python version: {}'.format(version))
# Example with pre-formatted and format function
name = "Abir"
# pre-formatted f
print(f"Hello worlds {name}")
# with format function
print("Hello world{}".format(name))
# Example with main function
def message():
print("Test")
if __name__ == "__main__" : message()
# Blocks and Scope
x = 45
y = 32
if x > y:
z = 55
print("x is greater than y")
print("z doesn't fall bound to the if scope and value: {}".format(z))
# Conditionals [Python doesn't have switch-case]
x = 10
y = 10
if x > y:
print("x is greater than y")
elif x < y:
print("x is less than y")
else:
print("x and y are equal")
# While Loop example
words = ['one', 'two', 'three', 'four', 'five']
n = 0
while n < 5:
print("{}".format(words[n]))
n += 1
# For Loop example
words = ['one', 'two', 'three', 'four', 'five']
for i in words:
print(i)
# Function example with default value
def function(n=5):
print(n)
function()
function(100)
# Example of a Class in Python
class Duck:
sound = "Bla"
color = "White"
def quack(self):
print(self.sound)
def look(self):
print(self.color)
duck = Duck()
duck.look()
duck.quack()
| true |
a9377c53898eeaa064f6c0a0bbac1cce184a8462 | abir-hasan/PythonGround | /course_python_essentials/Chap02/primes.py | 441 | 4.15625 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
def isprime(n):
if n <= 1:
return False
for x in range(2, n):
if n % x == 0:
return False
else:
return True
# n = 5
# if isprime(n):
# print(f'{n} is prime')
# else:
# print(f'{n} not prime')
def list_prime(n):
for x in range(n):
if isprime(x):
print(x, end=' ', flush=True)
list_prime(100)
| false |
f09c256c36edcf414cc47fcddf8bed8e1d903f62 | Smisosenkosi/mypackage | /mypackage-master/test/sorting.py | 1,068 | 4.3125 | 4 | def bubble_sort(items):
'''Return array of items, sorted in ascending order'''
for num in range(len(items)-1,0,-1):
for i in range(num):
if items[i]>items[i+1]:
temp = items[i]
items[i] = items[i+1]
items[i+1] = temp
return bubble_sort
def merge_sort(items):
'''Return array of items, sorted in ascending order'''
if len(items) < 2:
return items
result,mid = [],int(len(items)/2)
y = merge_sort(items[:mid])
z = merge_sort(items[mid:])
while (len(y) > 0) and (len(z) > 0):
if y[0] > z[0]:result.append(z.pop(0))
else:result.append(y.pop(0))
result.extend(y+z)
return result
def quick_sort(items):
'''Return array of items, sorted in ascending order'''
if len(items) <= 1:
return items
else:
return quick_sort([x for x in items[1:] if x < items[0]]) + \
[items[0]] + \
quick_sort([x for x in items[1:] if x >= items[0]])
| true |
8c7dde5fa2a03661a3bcaae698f85ca9459dc325 | felgun/BioinformaticsAlgorithms | /CountingDnaNucleotides.py | 2,097 | 4.625 | 5 | """
CountingDnaNucleotides.py
"""
import argparse
import os.path
def count_dna_nucleotides(sequence):
"""
Counts each nucleotide in the DNA sequence and prints them in the following order: A,C,G,T.
Returns a dictionary with nucleotide as key and its count as value.
Param:
sequence {str} : The DNA sequence of which nucleotides to be counted.
"""
counts = {'A':0,'C':0,'G':0,'T':0}
for i in xrange(0,len(sequence)):
if sequence[i] in counts:
counts[sequence[i]] += 1
else:
print("Warning: {0} is not part of valid DNA nucleotides: {1}".format(
sequence[i],counts.keys()))
print("{0} {1} {2} {3}".format(counts['A'],counts['C'],counts['G'],counts['T'],))
return counts
def parse_arg():
"""
Parses arguments.
"""
parser = argparse.ArgumentParser(description="Counting dna nucleotide in a sequence")
parser.add_argument("--seq",help="DNA sequence of which nucleotides to be counted", type=str, required=False)
parser.add_argument("--file",help="Path to the input file containing DNA sequence(s) of which nucleotides to be counted", type=str, required=False)
return parser.parse_args()
def main():
args = parse_arg()
# Check if the input sequence is specified using at least --seq or --file
if args.seq is None and args.file is None:
print("Error: Please specify the input sequence using at least --seq or --file. ")
else:
# Count the nucleotides from the sequence specified through --seq
if args.seq :
count_dna_nucleotides(args.seq)
print
# Count the nucleotides from the sequence specified through --file, line by line
if args.file:
# Check if the path specified is a file
if os.path.isfile(args.file):
with open(args.file) as input_file:
sequences = input_file.read().splitlines()
for line in sequences:
print(str(line))
count_dna_nucleotides(line)
print
else:
print("Error: The path specified in --file is not a file.")
if __name__ == '__main__':
main() | true |
6fe338ba5908d977c7c2e263eeabc3ac9e2accd7 | Qliangw/python_notes | /basic/ba_04_traverse_list.py | 1,380 | 4.34375 | 4 | from src import print_split_line
# for循环的使用
magicians = ['alice', 'david', 'carolina']
print("使用for打印出数组元素:")
for magician in magicians:
print(magician)
print_split_line.print_split_line('*', 20)
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print("I can`t wait to see your next trick, " + magician.title() + ".\n")
print("Thank you, everyone. That was a great magic show!")
print_split_line.print_split_line('*', 20)
# 数值列表
for value in range(1, 5):
print(value)
print_split_line.print_split_line('*', 20)
# 使用list方法自动转换为数字列表
numbers = list(range(1, 6))
print(numbers)
print_split_line.print_split_line('*', 20)
even_numbers = list(range(2, 11, 2))
print(even_numbers)
print_split_line.print_split_line('*', 20)
# squares
squares = []
for value in range(1, 11):
# square = value ** 2
# squares.append(square)
squares.append(value ** 2)
print(squares)
print_split_line.print_split_line('*', 20)
# 简单统计
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print("digits:" + str(digits))
print("min:" + str(min(digits)))
print("max:" + str(max(digits)))
print("sum:" + str(sum(digits)))
print_split_line.print_split_line('*', 20)
# 列表解析
cube = [value**3 for value in range(1, 11)]
print(cube)
"""
开始
多行注释:
测试使用
结束
"""
| true |
c9cb804afab2297f832d0adc83bd2ef19ab1ecd2 | darkalejo14/Lab_8_Funciones | /punto5.py | 740 | 4.15625 | 4 | #Solicitar al usuario un número entero y luego un dígito.
# Informar la cantidad de ocurrencias del dígito en el número,
# utiliza para ello una función que calcule la frecuencia del dígito en el número ingresado.
cond="si"
def frecuencia(numero,digito):
cantidad=0
while numero!=0:
ultDigito=numero%10
if ultDigito==digito:
cantidad+=1
numero=numero//10
return cantidad
while cond=="si":
num=int(input("ingrese un Número: "))
un_digito=int(input("ingrese un Dígito: "))
print("Frecuencia del dígito en el número:",frecuencia(num,un_digito))
cond=input("quieres volver a ingresar un numero y un digito = ¿si o no?")
if cond =="no":
print("vuelve pronto!")
| false |
83ca048aef33eb2b726d35b24a6ecef3fa6047dd | AnfisaAnisimova/Geekbrains_student | /Введение в Python/Dz_11/Task_11_7.py | 1,110 | 4.3125 | 4 | """
Реализовать проект «Операции с комплексными числами». Создать класс «Комплексное число».
Реализовать перегрузку методов сложения и умножения комплексных чисел. Проверить работу проекта.
Для этого создать экземпляры класса (комплексные числа), выполнить сложение и умножение созданных экземпляров.
Проверить корректность полученного результата.
"""
class ComplexNumber:
def __init__(self, a, b):
self.a = a
self.b = b
def __add__(self, other):
return f'Сумма равна: {self.a + other.a} + i*{self.b + other.b}'
def __mul__(self, other):
return f'Произведение равно: {self.a * other.a - self.b * other.b} + i*{self.a * other.b + other.a * self.b}'
z_1 = ComplexNumber(3, 7)
z_2 = ComplexNumber(-5, 4)
print(z_1 + z_2)
print(z_1 * z_2)
| false |
3165145b0c893d632c0c22163e0c36f05f52862d | PaulBStephens/python-challenge | /PyBank/.ipynb_checkpoints/main-checkpoint.py | 2,325 | 4.21875 | 4 | # Create dependencies
import csv
# file to load
file_to_load = "budget_data.csv"
# Read the csv and convert info into lists; the first and second columns are data given, the third to store data calculated from the second column
with open(file_to_load) as revenue_data:
reader = csv.reader(revenue_data)
# I used the 'next' function to skip first title row in csv file
next(reader)
date = []
revenue = []
# defined revenue as a float of row 1, and date as row 0
for row in reader:
revenue.append(float(row[1]))
date.append(row[0])
# printing info
print("Financial Analysis")
print("-----------------------------------")
print("Total Months:", len(date))
sum_of_revenue = '{0:.0f}'.format(sum(revenue))
print(f"Total Revenue: ${sum_of_revenue}")
#in this loop I did total of difference between all row of column "Revenue" and found total revnue change. Also found out max revenue change and min revenue change.
for i in range(1,len(revenue)):
rev_change.append(revenue[i] - revenue[i-1])
avg_rev_change = sum(rev_change)/len(rev_change)
max_rev_change = max(rev_change)
min_rev_change = min(rev_change)
max_rev_change_date = str(date[rev_change.index(max(rev_change))])
min_rev_change_date = str(date[rev_change.index(min(rev_change))])
print("Average Revenue Change: $", '{0:.2f}'.format(avg_rev_change))
print("Greatest Increase in Revenue to the Next Month:", max_rev_change_date,"($", round(max_rev_change),")")
print("Greatest Decrease in Revenue to the Next Month:", min_rev_change_date,"($", round(min_rev_change),")")
## now need to export the same info I printed to a text file
with open("outputPyBank.txt", "a") as f:
print("Financial Analysis", file=f)
print("-----------------------------------", file=f)
print("Total Months:", len(date), file=f)
print(f"Total Revenue: ${sum_of_revenue}", file=f)
print("Average Revenue Change: $", '{0:.2f}'.format(avg_rev_change), file=f)
print("Greatest Increase in Revenue to the Next Month:", max_rev_change_date,"($", round(max_rev_change),")", file=f)
print("Greatest Decrease in Revenue to the Next Month:", min_rev_change_date,"($", round(min_rev_change),")", file=f)
| true |
04aa146e5dc7454a0176eb855472d19f97065021 | RashikWasik/PythonDataStructures | /Python Data Structures/Week 3/Assignment 7.2.py | 1,000 | 4.25 | 4 | # 7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
# X-DSPAM-Confidence: 0.8475
# Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output
# as shown below. Do not use the sum() function or a variable named sum in your solution.
# You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.
fname = input("Enter file name: ")
li = list()
with open(fname,"r") as asd:
for i in asd:
if i.startswith("X-DSPAM-Confidence:"):
asd = i.split()
li.append(asd[1])
count = 0
total = 0
for a in li:
count = count + 1
total = total + float(a) # In the list all the numbers will be strings. So I have to convert it into float
average = total/count
print("Average spam confidence:",average)
| true |
e1e450bf4bff900d9e12a290706f5308c8fb97cf | sargey18/rock-paper-sicssors | /main.py | 921 | 4.3125 | 4 | import random
# 1) we need the random
# 2) we will also need a function called play
def play():
# 3) we will also need a variable to stor one of three inputs from the user
user = input("What is your choice 'r' for rock, 'p' for paper, 's' for scissor\n")
# 4) the computer also needs to choose , vatiable to store a random a list r p s
computer = random.choice(['r', 'p', 's'])
# 5) now we need to tell the computer what to do with these choices
if user == computer:
return 'tie' # 5) if user and computer choose the same its a tie
if is_win(user, computer):
return 'You won!'
return 'You lost!'
def is_win(player, opponent):
# return true is player wins
# r > s, s > p, p > r
if (player == 'r' and opponent == 's') or (player == 's' and opponent == 'p') or (player == 'p' and opponent == 'r'):
return True
print(play()) | true |
9d14085766c3a5a7a8099377970e8b843be8f665 | tabo2659-cmis/Tabo2659-cmis-cs2 | /cs2quiz3.py | 1,698 | 4.46875 | 4 |
#Section 1: Terminology
# 1) What is a recursive function?
#A recursive function is a function that calls itself until it meets the requirments of the base case where it stops.
#point
#
# 2) What happens if there is no base case defined in a recursive function?
#It will recurse infinitly or about a 1000 times depending on the computer.
#point
#
# 3) What is the first thing to consider when designing a recursive function?
# What the base case of the function is.
#point
#
# 4) How do we put data into a function call?
# Set a variable
#no
#
# 5) How do we get data out of a function call?
# Return
#
#point
#Section 2: Reading
# Read the following function definitions and function calls.
# Then determine the values of the variables q1-q20.
#a1 = 2
#a2 = 2
#a3 = -1
#1 point
#b1 = 2
#b2 = 0
#b3 = 4
#2point
#c1 = 3
#c2 = 4
#c3 = 5
#no
#d1 = 5
#d2 = 7
#d3 = 5
#no
#Section 3: Programming
#Write a script that asks the user to enter a series of numbers.
#When the user types in nothing, it should return the average of all the odd numbers
#that were typed in.
#In your code for the script, add a comment labeling the base case on the line BEFORE the base case.
#Also add a comment label BEFORE the recursive case.
#It is NOT NECESSARY to print out a running total with each user input.
#point = 6
def check(numb,avg):
if int(numb) == 1 or int + 2:
avg += int(numb)
user(avg)
def user(avg):
numb = raw_input("Next:")
# Base case
if numb == "":
check(numb,avg)
print "The average of your odd numbers was {}".format(avg)
# Recursive case
else:
check(numb,avg)
user(avg)
def main():
avg = 0
user(avg)
main()
| true |
cd0bfde949db56dc45822cfe6e06c57d3ce75bf5 | mbutkevicius/100_Days_Of_Code | /day_2.py | 2,196 | 4.1875 | 4 | # Data Types
# String
print("Hello"[4])
print("123" + "345")
# Integer
print(123 + 345)
# 123_456_789 # _ works as ,
# Float
# 3.14159
# Boolean
# True
# False
# num_char = str(len(input("What is your name?\n")))
# print("Your name has " + num_char + " characters.")
a = str(123)
print(type(a))
# 🚨 Don't change the code below 👇
two_digit_number = input("Type a two digit number: ")
# 🚨 Don't change the code above 👆
####################################
# Write your code below this line 👇
first_digit = int(two_digit_number[0])
second_digit = int(two_digit_number[1])
print(first_digit + second_digit)
print()
print(3 + 5)
print(7 - 4)
print(3 * 2)
print(type(6 / 3))
print(4 ** 4)
print(3 * (3 + 3 / 3 - 3))
# 🚨 Don't change the code below 👇
height = input("enter your height in m: ")
weight = input("enter your weight in kg: ")
# 🚨 Don't change the code above 👆
# Write your code below this line 👇
# float_height = float(height)
# float_weight = float(weight)
# bmi = int(float_weight / (float_height ** 2))
# print(bmi)
# I like this way more:
bmi = float(weight) / float(height) ** 2
bmi_as_int = int(bmi)
print(bmi_as_int)
# The comma after 3 tells how many digits to round to after decimal
print(round(8 / 3, 2))
# Makes an int
print(8 // 3)
# f-strings
score = 0
height = 1.8
is_winning = True
print(f"your score is {score}, your height is {height}, you are winning "
f"is {is_winning}")
# 🚨 Don't change the code below 👇
age = input("What is your current age?\n")
# 🚨 Don't change the code above 👆
# Write your code below this line 👇
# w = 365 * 90
# x = 52 * 90
# y = 12 * 90
# z = 90
#
# days_left = w - int(age) * 365
# weeks_left = x - int(age) * 52
# months_left = y - int(age) * 12
# years_left = z - int(age)
#
# message = f"You have {days_left} days, {weeks_left} weeks, {months_left} months, and {years_left} years left"
# print(message)
# Shorter way:
years_left = 90 - int(age)
days_left = years_left * 365
weeks_left = years_left * 52
months_left = years_left * 12
message = f"You have {days_left} days, {weeks_left} weeks, {months_left} months, and {years_left} years left"
print(message)
| true |
0c4b07f056aa9b12db0af708de3d397e4f0bcf73 | mbutkevicius/100_Days_Of_Code | /day_10.py | 2,194 | 4.1875 | 4 | # def my_function():
# return 3 * 2
#
#
# output = my_function()
# print(output)
def format_name(f_name, l_name):
"""Take first and lsat name and format it to return the title
case version of the name."""
if f_name == "" or l_name == "":
return "You didn't provide valid inputs."
formatted_f_name = f_name.title()
formatted_l_name = l_name.title()
return f"Result: {formatted_f_name} {formatted_l_name}"
# print(f"{formatted_f_name} {formatted_l_name}")
# formatted_string = format_name("MiChAeL", "BUTKEVICIUS")
# print(formatted_string)
print(format_name("MiChAeL", "BUTKEVICIUS"))
# print(format_name(input("What is your first name? "),
# input("What is your last name? ")))
def is_leap(year_to_check):
"""Checks whether the given year is a leap year."""
if year_to_check % 4 == 0:
if year_to_check % 100 == 0:
if year_to_check % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
# def days_in_month(year_to_check, month_to_check):
# month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# if not is_leap(year_to_check):
# return month_days[month_to_check - 1]
# elif is_leap(year_to_check):
# if month_days[month_to_check - 1] == 28:
# return 29
# else:
# return month_days[month_to_check - 1]
# I guess they both work the same. I thought this way might consolidate it better but guess not.
# Jk after looking at it again I can erase those unnecessary else statements
def days_in_month(year_to_check, month_to_check):
"""Tells how many days are in a month."""
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if is_leap(year_to_check):
if month_days[month_to_check - 1] == 28:
return 29
# else:
# return month_days[month_to_check - 1]
# else:
return month_days[month_to_check - 1]
# 🚨 Do NOT change any of the code below
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
days = days_in_month(year, month)
print(days)
| true |
45b9a99f04ea8582a564a791458c66e8a67ff224 | alexDavis28/udemy_python | /Python/5_36_usefull_operators_and_functions.py | 1,750 | 4.625 | 5 | #these didn't really fit into any other lecture, so are here
#range function
mylist = [1,2,3]
for num in range(10):
print(num)
#prints every number from 0 to 10
for num in range(3,10):
print(num)
#prints every number from 0 to 9, not including 10
for num in range(0,10,2):
print(num)
#prints every number from 0 to 9, not including 10, with a step size of 2
# range is a generator, so you have to cast it to a list to see it as a list, egL
print(list(range(0,10,2)))
#enumerate function
word="abcde"
for item in enumerate(word):
print(item)
# prints every item with the index position as a tuple
# eg: (0,"a")
for index,letter in enumerate(word):
print(index)
print(letter)
print('\n')
# uses tuple unpacking
#zip function
#zipps together 2 or more lists, is generator
mylist1 = [1,2,3]
mylist2 = ["a","b","c"]
for item in zip(mylist1,mylist2):
print(item)
# prints tuple of the matching items at the same index positions, eg:
#(1, "a")
mylist3 = [100,200,300,400]
for item in zip(mylist1,mylist2,mylist3):
print(item)
# prints tuple of the matching items at the same index positions, eg:
#(1, "a", 100)
#400 is not included, only zips as far as the shortest list
# to get the list:
print(list(zip(mylist1,mylist2,mylist3)))
#in operator
#checks if value in an iterable object types
if 100 in mylist3:
print("true")
#prints true, see line 45
#mathemeatical functions
#min,max functions
mylist = [10,20,30,40,100]
print(min(mylist)) #prints 10
print(max(mylist)) #prints 100
#random library
from random import shuffle
shuffle(mylist)
#randomly shuffles the list inplace
print(mylist)
from random import randint
#random int
print(randint(0,100))
#user input
#always accepts as a string
print(input("input"))
| true |
c0da33ed657b52e4c56a4a20767f547efc1ae4b5 | SaeedTaghavi/numerical-analysis | /python/02-interpolation/01-newton-forward/forward.py | 1,185 | 4.25 | 4 | # Python3 Program to interpolate using
# newton forward interpolation
# calculating u mentioned in the formula
def u_cal(u, n):
temp = u;
for i in range(1, n):
temp = temp * (u - i);
return temp;
# calculating factorial of given number n
def fact(n):
f = 1;
for i in range(2, n + 1):
f *= i;
return f;
# Driver Code
# Number of values given
n = 4;
x = [ 45, 50, 55, 60 ];
# y[][] is used for difference table
# with y[][0] used for input
y = [[0 for i in range(n)]
for j in range(n)];
y[0][0] = 0.7071;
y[1][0] = 0.7660;
y[2][0] = 0.8192;
y[3][0] = 0.8660;
# Calculating the forward difference
# table
for i in range(1, n):
for j in range(n - i):
y[j][i] = y[j + 1][i - 1] - y[j][i - 1];
# Displaying the forward difference table
for i in range(n):
print(x[i], end = "\t");
for j in range(n - i):
print(y[i][j], end = "\t");
print("");
# Value to interpolate at
value = 52;
# initializing u and sum
sum = y[0][0];
u = (value - x[0]) / (x[1] - x[0]);
for i in range(1,n):
sum = sum + (u_cal(u, i) * y[0][i]) / fact(i);
print("\nValue at", value,
"is", round(sum, 6));
# This code is contributed by mits
| true |
30057b12944c5f5fe44228f8f24c47740bbe9d3d | andre23arruda/pythonCeV | /Aula7.py | 2,183 | 4.15625 | 4 | # =============== DESAFIO 5 ===================== #
numero = int(input('Digite um numero: '))
ant_num = numero - 1
sus_num = numero + 1;
print('O numero {} possui antecessor = {} e sucessor = {} '.format(numero,ant_num,sus_num))
# ============= DESAFIO 6 =================#
numero2 = int(input('Digite um numero: '))
dobro = numero2 * numero2;
triplo = numero2 ** 3;
raiz = numero2 ** 0.5;
print('O numero {} possui dobro = {}, triplo = {} e raiz quadrada = {:.3f}'.format(numero2,dobro,triplo,raiz))
# ================= DESAFIO 7 =================== #
nota1 = int(input('Digite a nota 1: '))
nota2 = int(input('Digite a nota 2: '))
media = (nota1+nota2)/2
print('A media é: {}'.format(media))
# =============== DESAFIO 8 ================= #
print('Programa de converter medidas')
medida = int(input('Entre com a quantidade de metros: '))
print('A medida {} possui {} cm e {} milimetros' .format(medida,medida*100,medida*1000))
# ============= DESAFIO 9 ================= #
print('Calcular tabuada')
numero3 = int(input('Entre com um numero: '))
print('A tabuada de multiplicação é:\n{0} x 1 = {0} \n{0} x 2 = {1} \n{0} x 3 = {2} \n{0} x 4 = {3} \n{0} x 5 = {4}'.format(numero3,numero3*2,numero3*3,numero3*4,numero3*5))
# ============= DESAFIO 10 =================== #
print('Dinheiro na carteira')
dinheiro = int(input('Quanto dinheiro voce tem? '))
dolar = dinheiro/3.27;
print('Voce possui {} reais e pode comprar {:.3f} dólar'.format(dinheiro,dolar))
# ============= DESAFIO 11 ================ #
print('Quantidade de tinta')
largura = int(input('Digite a largura da parede: '))
altura = int(input('Digite a altura da parede: '))
tinta = largura*altura/2
print('A quantidade de tinta necessária para pintar {} m² de parede é {} litros'.format(largura*altura, tinta))
# ================= DESAFIO 12 ===================== #
print('Novo preço')
preco = int(input('Digite o preço do produto'))
print('O novo preco do produto é {}'.format(preco-0.5*preco))
# ================= DESAFIO 13 ======================= #
print('Novo salario')
salario = int(input('Digite o salario atual: '))
print('O novo salario será de {}'.format(salario+0.15*salario))
| false |
1297cab42fa902af1f9be79bb25cf2f9f58aa037 | merlose/Python-Calculator | /Basic_Calculator_v2.py | 743 | 4.21875 | 4 | while True:
num1 = float(input("Input 1st number then hit ENTER: "))
mathType = ["Select function:","(add) +","(subtract) -","(multiply) *","(divide) /"]
for type in mathType:
print (type)
mathFunction = input("then hit ENTER: ")
num2 = float(input("Input 2nd number then hit ENTER: "))
if mathFunction == "+":
answer = str(num1 + num2)
print ("Answer = " + answer)
elif mathFunction == "-":
answer = str(num1 - num2)
print ("Answer = " + answer)
elif mathFunction == "*":
answer = str(num1 * num2)
print ("Answer = " + answer)
elif mathFunction == "/":
answer = str(num1 / num2)
print ("Answer = " + answer)
| false |
7c523ddce108b50a341473deaad70cef3076cef2 | Lischero/Atcoder | /ARC044/q1.py | 620 | 4.25 | 4 | # -*- coding:utf-8 -*-
import math
def isPrime(num):
if num == 2:
return True
if num < 2 or num%2 == 0:
return False
for tmp in range(3, math.floor(math.sqrt(num))+1, 2):
if num%tmp == 0:
return False
return True
def isPrime2(num):
factor = list(map(int, list(str(num))))
if sum(factor)%3 != 0 and factor[len(factor)-1]%2 != 0 and factor[len(factor)-1] != 5:
return True
else:
return False
N = int(input())
if isPrime(N):
print('Prime')
else:
if isPrime2(N) and N != 1:
print('Prime')
else:
print('Not Prime')
| false |
058d97564362edcd5c9c2c92cab229b617e6ee2d | sandeep9889/paint-app-using-python-turtle | /python_tutorial/if_else.py | 294 | 4.25 | 4 | #short hand if else
a = int(input("enter a\n"))
b = int(input("enter b\n"))
print("a b se bda h") if(a>b) else print("b a se bda h bhai")
#here it is called short handed because it is in one line code
#we can write here firstly print statement and then we have to write conditional if statement | false |
a5ea38f82eb0747c37cc0738c17817b4e6498e50 | chawlaj100/pythoniffie | /prime_number_checker.py | 398 | 4.15625 | 4 |
prime = int(input("What number do you wanna check?"))
if prime > 1 :
for i in range(2,prime):
if (prime % i) == 0:
print("Your number is not a prime number")
print("Because "+str(prime)+" divided by "+str(i)+" is 0.")
break
else:
print(prime,"is a prime number")
break
else:
print(prime, "is not a prime number") | true |
aedb45d82ba6a352cc4898605794452debbd3d6c | asergeev79/GeekBrains | /python/lesson_3/03-01.py | 1,214 | 4.21875 | 4 | # Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
# Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
#
def input_numbers():
"""
Функция запроса данных от пользователя.
:return:
Вывод в виде кортежа 2-х действительных чисел
"""
return float(input('Введите делимое: ')), float(input('Введите частное: '))
def div_num(x, y):
"""
Функция, реализующая деление 2-х чисел
:param x:
:param y:
:return:
Вывод - частное, либо уведомление о делении на ноль
"""
try:
return x / y
except ZeroDivisionError:
return 'деление на ноль'
# if y != 0:
# return x / y
# else:
# return 'деление на ноль'
div_x, div_y = input_numbers()
print('Результат деления: ', div_num(div_x, div_y))
| false |
db30b9cfd9b06bc9ed09689fc0644af96869146b | asergeev79/GeekBrains | /python/lesson_6/06-02.py | 1,195 | 4.28125 | 4 | # 2
""" Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина).
Значения данных атрибутов должны передаваться при создании экземпляра класса.
Атрибуты сделать защищенными.
Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна.
Использовать формулу: длина * ширина * масса асфальта для покрытия одного кв метра дороги асфальтом,
толщиной в 1 см * чи сло см толщины полотна. Проверить работу метода.
Например: 20м * 5000м * 25кг * 5см = 12500 т """
#
class Road:
def __init__(self, length, width):
self.__length = length
self.__width = width
def how_much_asphalt(self, mass, thick):
return self.__length * self.__width * mass * thick
r = Road(20, 5000)
print(f'{r.how_much_asphalt(25, 5) / 1000} т')
| false |
a3a1b1797558c68a7d46eee8f1132f53d1d04b98 | Ameya-k1709/Object-Oriented-Programming-in-Python | /class.py | 1,410 | 4.4375 | 4 | # creating a class named programmers
class Employee:
company = 'Microsoft' # the company attribute is a class attirbute because every programmers is from microsoft
number_of_employees = 0
def __init__(self, name, age, salary, job_role): # This is a constructor
self.name = name # These are instance attributes as "self" is given. This will refer to the object.
self.age = age
self.salary = salary
self.job_role = job_role
Employee.number_of_employees += 1
def giveProgrammerInfo(self):
print(f'\nThe name of the programmer is {self.name}')
print(f'The age of the programmer is {self.age}')
print(f'The salary of the programmer is {self.salary}')
print(f'The job role of the programmer is {self.job_role}')
print(f'The company of the programmer is {self.company} ')
# Here objects are created using the Employee class
ameya = Employee('Ameya', 22, 200000, 'Manager - Data Scientist')
akshay = Employee('Akshay', 32, 100000, 'Senior Business Analyst')
prathamesh = Employee('Prathamesh', 25, 50000, 'Solution Architect')
nilesh = Employee('Nilesh', 30, 10000, 'Database Architect')
# here the class method is called by the objects
ameya.giveProgrammerInfo()
akshay.giveProgrammerInfo()
prathamesh.giveProgrammerInfo()
print(Employee.number_of_employees)
| true |
3834284ded0d2d975396b73b06440baf6d0d84b2 | Roopa-palani-samy/DG-Python-Assignment | /Squarethevalue.py | 397 | 4.25 | 4 | # 8. Write a program which can map() to make a list whose elements are square of numbers
# between 1 and 20 (both included).
# using map
def squared(n):
return n * n
numbers = (1, 2, 3, 4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
result = map(squared, numbers)
print(list(result))
# using lambda
result = map(lambda x, y: x * y, numbers, numbers)
print(list(result)) | true |
ab24679f7aa1e2a2e5e9d3417b3487230bfed20d | skoricky/algo | /hw02_2.py | 823 | 4.1875 | 4 | # 2. Посчитать четные и нечетные цифры введенного натурального числа. Например, если введено число 34560,
# то у него 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).
print('Введите натуральное число:')
num = input('Число = ')
def sum_even_digits(num_string, ev_sum=0, od_sum=0, inx=0):
if inx == len(num_string):
return f'четных цифр - {ev_sum}, нечетных цифр - {od_sum}'
if int(num_string[inx]) % 2 == 0:
return sum_even_digits(num_string, ev_sum + 1, od_sum, inx + 1)
else:
return sum_even_digits(num_string, ev_sum, od_sum + 1, inx + 1)
print('Во веденном числе', sum_even_digits(num))
| false |
61377a9f9ace141983b2bb6bda6b48cff0661850 | jaycoskey/IntroToPythonCourse | /PythonSrc/Unit1_HW_src/LoopExamples/1_capitalize.py | 536 | 4.4375 | 4 | #!/usr/bin/env python3
def print_with_capitalized_a(word):
for letter in word:
if letter == 'a':
print(letter.upper(), end='')
else:
print(letter, end='')
def print_with_capitalized_ends(word):
for i in range(0, len(word)):
letter = word[i]
if i == 0 or i == len(word) - 1:
print(letter.upper(), end='')
else:
print(letter, end='')
print()
print_with_capitalized_a('baaag')print_with_capitalized_ends('baaag')
| false |
9f2d4cc94b21fc2015b6be1243ed12048aab7ed5 | hdgmemory/Data-structures-and-algorithms | /二叉树/二叉树反转.py | 628 | 4.15625 | 4 | #也叫二叉树的镜像
#递归实现
class Node():
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left # 左子树
self.right = right # 右子树
def invertTree(root):
if root == None:
return None
temp = root.left
root.left = root.right
root.right = temp
print(root.value)
invertTree(root.left)
invertTree(root.right)
if __name__ == '__main__':
root = Node('4', Node('2', Node('1'), Node('3')), Node('7', Node('6'), Node('9')))
invertTree(root)
| false |
501a44392286a927a832ff513e8620de6c288c34 | Sushil-Deore/Python-Challenges | /alphabetic_patterns.py | 1,622 | 4.28125 | 4 | """
Alphabetic patterns
Description
Given a positive integer 'n' less than or equal to 26,
you are required to print the below pattern
Sample Input: 5
Sample Output :
--------e--------
------e-d-e------
----e-d-c-d-e----
--e-d-c-b-c-d-e--
e-d-c-b-a-b-c-d-e
--e-d-c-b-c-d-e--
----e-d-c-d-e----
------e-d-e------ s
--------e--------
"""
import random
n = random.choice([1,2,3,4,5,6,7,8,9])
def alphabetic_pattern(n):
for i in range(1, n+1): # i = 1,2,3,4,5
#first print --
for s in range(n-i):
print("--", end = "")
# print alphabets in decreasing order
for alp in range(i-1): # alp = 0 1 2 ... i-1
print(chr(ord('a') + n-1-alp),end ="-")
# print alp in increasing order
for alp in range(i-1):
print(chr(ord('a') + n - i + alp),end='-')
# print last alphabet separately without --
print(chr(ord('a')+n-1),end='')
# print -- here again
for s in range(n-i):
print("--",end = '')
# go to the new line
print()
for i in range(n-1, 0,-1): # printing in reverse order
#first print --
for s in range(n-i):
print("--", end = "")
# print alphabets in decreasing order
for alp in range(i-1): # alp = 0 1 2 ... i-1
print(chr(ord('a') + n-1-alp),end ="-")
# print alp in increasing order
for alp in range(i-1):
print(chr(ord('a') + n - i + alp),end='-')
# print last alphabet separately without --
print(chr(ord('a')+n-1),end='')
# print -- here again
for s in range(n-i):
print("--",end = '')
# go to the new line
print()
ans = alphabetic_pattern(n) | false |
e09901378bbb935d2c4e12fd165334748f17f4ff | tungsys/FPU | /test_bench/num_gen/IEEE_number_gen.py | 1,762 | 4.25 | 4 | from sys import argv
import struct
import random
def main():
"""
This program takes two inputs, an op code and a number.
OP Codes
1 - Convert number to IEEE
2 - Generate n random IEEE numbers and display them next to their decimal counterpart
3 - Generates and converts n random numbers and save them to a file
"""
if len(argv) < 3 or len(argv) > 4:
print "Usage: op num <file>"
exit(1)
op = argv[1]
num = argv[2]
if op == "0":
print IEEE_convert(num)
if op == "1": # Basic Conversion
print "number %s\t converstion %s" % (num, IEEE_convert(num))
if op == "2": # Generate and convert n random numbers
numbers = generate_random(int(num))
print "Number\tConversion"
for i in range(0, int(num)):
print "%s\t%s" % (numbers[i][0], numbers[i][1])
if op == "3":
if len(argv) != 4:
print "Invalid Filename"
exit(1)
filename = argv[3]
f = open(filename, "w+")
numbers = generate_random(int(num))
for i in range(0, int(num)):
f.write("%s, %s\n" % (numbers[i][0], numbers[i][1]))
f.close()
def float_convert(input_hex):
s = int(input_hex)
s = (struct.pack('>l', s))
return (struct.unpack('>f', s)[0])
def IEEE_convert(input_number):
input_number = float(input_number)
s = struct.pack('>f', input_number)
return hex(struct.unpack('>l', s)[0])
def generate_random(n):
random_numbers = []
for i in range(0, n): # Where n is the number of random numbers
rnum = random.getrandbits(32)
random_numbers.append((rnum, IEEE_convert(rnum)))
return random_numbers
if __name__ == "__main__":
main()
| true |
e7c92f95a044463f912fdc0879eb2c6fa7468dc1 | shakerabady/Python-Exericises | /temp.py | 1,161 | 4.1875 | 4 | print ('{:5} {:10} {:15}' .format("hello\n","hello\n","hello\n"))
print("orange\n"*20)
x=float(1)
y=float(2.8)
z=float("3")
w=float("4.2")
print(x,y,z,w,sep='10')
x=1
y=2.8
z=1j
o="orange"
A=True
print(type(x))
print(type(y))
print(type(z))
print(type(o))
print(type(A))
x,y="Orange",1
X1,Y1=100,-10
print(x)
print(y)
print(X1)
print(Y1)
x,y="Orange",1
X1,y1=100,-10
print(x)
print(y)
print(X1)
print(Y1)
#print("hello, World")
print("cheers,mate!") #this is the program
"""testing
the code"""
age=int(input("what is your age"))
till100=(100-age)
age100=(till100+2020)
print(age100)
base=int(input("enter the base of the triangle"))
height=int(input("enter the height of the triangle"))
triangleArea= 0.5*base*height
print(triangleArea)
# [ ]create variables to store input: name, age, get_mail with prompts
name,age,get_mail=input("enter your name: "), input("enter your age: "), input("do you want to get mail: ")
# for name, age and yes/no to being on an email list
# [ ] print a description + variable value for each variable
print("enter your first name:", name)
print("enter your age: ", age)
print("do you want to get mail: ", get_mail)
| false |
22267ec505fe058a72993238db854bf2f149ed10 | SteveEs25/SistemasExpertos_EjerciciosSA-B | /Calculadora/Index.py | 1,276 | 4.1875 | 4 | #Importamos la clase Calcu
from Calculadora import Calcu
#La variable recoge los datos de la clase Calcu
calcu = Calcu()
def Menu():
print(" ")
print(" ")
print("--CALCULADORA--")
print(" ")
print("Seleccione una opción")
print("1 - Suma")
print("2 - Resta")
print("3 - Multiplicación")
print("4 - División")
print("5 - Raiz Cuadrada")
print("6 - Elevación")
print("0 - Salir")
return int(input("Introducir opción: "))
while(True):
opcion = Menu()
if(opcion == 0):
break
else:
num1 = float(input("Digite el primer número: "))
if(opcion != 5):
if(opcion != 6):
num2 = float(input("Digite el segundo número: "))
else:
num2 = float(input("Digite el valor de la elevación: "))
#Llamando a las funciones dependiendo de la opcion seleccionada
if(opcion == 1):
calcu.Suma(num1, num2)
elif(opcion == 2):
calcu.Resta(num1, num2)
elif(opcion == 3):
calcu.Multi(num1, num2)
elif(opcion == 4):
if(num2 == 0):
print("No se puede dividir entre 0")
else:
calcu.Division(num1, num2)
elif(opcion == 5):
calcu.Raiz(num1)
elif(opcion == 6):
calcu.Elevacion(num1, num2)
else:
print("Opción incorrecta")
print("ADIOS !!!") | false |
16bbee2868d8d28bb4757ad8676ae08677d671e3 | shailymishra/EulerProject | /euler4.py | 1,469 | 4.375 | 4 | # A palindromic number reads the same both ways.
# The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
## Also in recurrsive function return the function, otherwise it will show none
## Have a palindrome function 889x11 = 9779 which then becomes largest palindrome
## This logic failed - because
## Find the max no i.e. 999x999
## Divide it by 111, and get the max number
## now keep decreasing that number, and multiply with 111 till we have a palindrome
## Logic 2 :: FAILED
## obviously for a palindrome it , one of the multiplicant will be 99,999, ...
## so just keep reducing it , and keep checking
## this also didnt work, because 999x91 = 90909, now there will be obviously better palindrome
import math
def palindrome(value):
length = len(value)
if(length>1):
if(value[0] == value[length-1]):
return palindrome(value[1:length-1])
else:
return False
else:
return True
numberOfDigit = 3
string = ''
for i in range(numberOfDigit):
string += '9'
multiplicant1 = int(string)
multiplicant2 = multiplicant1
while(True):
multiplication = multiplicant1 * multiplicant2
if(palindrome(str(multiplication))):
print('found', multiplication)
print('multiplicant1', multiplicant1)
print('multiplicant2', multiplicant2)
break
multiplicant2 -= 1
| true |
01e3add9db5b09606cf11318a41aa8c39b46bb72 | KzZe-Sama/Python_Assignment-III-1 | /QnA/Bubblesort.py | 658 | 4.28125 | 4 | # bubble sort algorithm
# the function sorts list of numbers in ascending order
def sortList(data):
for i in range(len(data)):
for j in range(len(data)):
if(j!=len(data)-1):
if data[j]>data[j+1]:
# creating temp var and storing before swapping
temp=data[j]
data[j]=data[j+1]
data[j+1]=temp
return data
# data
dataA=[3,4,6,7,9,1,2,5,8]
dataB=[30,40,60,70,90,10,20,50,80]
print("Unsorted Data:")
print(dataA)
print(dataB)
# Calling FUnction
print("Sorted List using Bubble Sort Algorithm:")
print(sortList(dataA))
print(sortList(dataB)) | true |
2d9308a0b0d941fbae26fba050313b8133f5ae83 | l4nicero/learning_python | /at_seq.py | 1,075 | 4.25 | 4 | #!/usr/bin/env python3
import random
#random.seed(1) # comment-out this line to change sequence each time
# Write a program that stores random DNA sequence in a string
# The sequence should be 30 nt long
# On average, the sequence should be 60% AT
# Calculate the actual AT fraction while generating the sequence
# Report the length, AT fraction, and sequence
#for prompt
length = 30
dna = ' '
at_count = 0
for i in range(length):
r = random.random( ) #generate a random # from [0, 1)
if r < 0.6:
r = random.randint(0, 1)
if r == 0: dna += 'A'
else: dna+= 'T'
at_count += 1
else:
r = random.randint(0, 1)
if r == 0: dna += 'C'
else: dna += 'G'
print(length, at_count / length, dna)
#extra stuff
length = 30
dna = ' '
at_count = 0
alphabet = 'ACGT'
for i in range(length):
nt = random.choice(alphabet) #generate a random character
if nt == 'A' or nt == 'T': at_count += 1
dna += nt
print(length, at_count / length, dna)
"""
30 0.6666666666666666 ATTACCGTAATCTACTATTAAGTCACAACC
"""
| true |
31f6d146a867eec1ca797913e54e1e012726505c | TheHalfling/Py3ArcadeGameClass | /Calculator.py | 2,239 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
Calculator from Chapter 1 of Program Arcade Games with Pygame
"""
def mpg():
# miles per gallon
print("This program calculates mpg.")
# Get Miles driven from user
miles_driven = float(input("Enter miles driven: "))
#get gallons used from user
gallons_used = float(input("Enter gallons used: "))
#calculate mpg and display
mpg = miles_driven / gallons_used
print("Miles per gallon: {}".format(mpg))
def kinetic_energy():
#Calculate Kinetic Energy
print("This program calculates the kinetic energy of a moving object.")
#Get Mass from user
mass = float(input("Enter the object's mass in kilograms: "))
#Get velocity from user
velocity = float(input("Enter the object's speed in meters per second: "))
#calculate and display kinetic energy
energy = 0.5 * mass * velocity * velocity
print("The object has {}".format(energy) + " joules of energy.")
def temp_conversion():
#Calculates the temp conversion
print("Thie program converts the temp from F to C")
#Get user input
f = float(input("What is the temperature in Farenheit? "))
#convert and print
c = (f-32)/1.8
print("The temperature in Celcius is {}".format(c))
def trapezoid():
#calculates the area of a trapezoid
print("Area of a trapezoid")
#get input
h = int(input("Enter the height of the trapezoid: "))
len_bottom = int(input("Enter the length of the bottom of the base: "))
len_top = int(input("Enter the length of the top base: "))
#calculate and print results
a = .5 * (len_bottom + len_top) * h
print ("The area is: {}".format(a))
def run_calc():
print("Which calculator do you wish to run?")
choice = input("Enter mpg, energy, temp, or trapezoid: ")
choice = choice.lower()
if choice == "mpg":
mpg()
elif choice == "energy":
kinetic_energy()
elif choice == "temp":
temp_conversion()
elif choice == "trapezoid":
trapezoid()
else:
print("You did not input an acceptable choice")
run_calc() | true |
e0996ed85bbb7753d9ade2645ea13b0ef81292e6 | IlonaPelerin/CTI110 | /M5HW2_RunningTotal_Pelerin.py | 713 | 4.125 | 4 | # CTI-110
# M5HW2 - Running Total
# Ilona Pelerin
# October 19, 2017
#
def main():
# declaring and initializing the variables.
number = 1.0
runningTotal = 0.0
# setting up the while loop to add numbers until a negative one is entered.
while number >= 0:
number = float(input('Enter a positive number: '))
# Check the number is positive so it does not change the value of the running total.
if number >= 0:
runningTotal = runningTotal + number
print()
# Display the running total using proper formating to round to 2 decimal places.
print()
print ('Total = ' , format(runningTotal, '.2f'))
main()
| true |
2a7cf7af13a8bb8713938f7ee609077c5e9aae08 | mundostr/adimra_introprog21_mdq | /sem3/azar.py | 715 | 4.125 | 4 | """
El uso de librerías es una práctica muy standard en todos los lenguajes de programación actuales.
En el caso de Python, la cláusula import permite insertar la librería que se desee,
para comenzar a utilizar sus métodos.
"""
# Se importa la librería random, incluída en la instalación predeterminada de Python3
# En este caso, se importa de forma completa, es decir, todos sus métodos estarán disponibles.
import random
# Se realiza el llamado a uno de los métodos (randint), que permite generar un número entero al azar.
# También se podrían utilizar otros declarados en la librería, como randrange o randbytes por ejemplo.
nro = random.randint(0, 100)
print("Entero generado al azar:", nro)
| false |
6a2ed364d4c4091a690f19d9cd19f787ba50471d | mundostr/adimra_introprog21_mdq | /sem8/clases2.py | 1,266 | 4.21875 | 4 | """
Introducción a POO (Programación Orientada a Objetos)
Ejemplo de declaración de clases que HEREDAN características de otras,
Perro y Gato en este caso, de Mascota.
Recordar que una clase es esencialmente un molde que define las características de un objeto.
"""
class Mascota:
def __init__(self, nombre, raza):
self.nombre = nombre
self.raza = raza
def mostrarNombre(self):
print(f"La mascota se llama {self.nombre}")
class Perro(Mascota):
def ladrar(self):
print(f"{self.nombre} ladra")
class Gato(Mascota):
def maullar(self):
print(f"{self.nombre} maulla")
def main():
# Instanciamos 2 objetos, un Perro y un Gato, pasando nombre y raza para inicialización
# Ambos podrán mostrar su nombre, aunque este método no se declara ni en Perro ni en Gato,
# pero se hereda de Mascota, pudiendo usarse con cualquier objeto de tipo Perro o Gato.
# El perro podrá ladrar (cuenta con un método ladrar declarado)
# pero no podrá maullar.
perro = Perro("Batuque", "Galgo")
perro.mostrarNombre()
perro.ladrar()
# Inversamente, el gato podrá maullar (cuenta con un método maullar declarado)
# pero no podrá ladrar.
gato = Gato("Travieso", "Siames")
gato.mostrarNombre()
gato.maullar()
if __name__ == '__main__':
main()
| false |
957ddea417c9ab85ca19acc451b73dacf714cf19 | RocketHTML/holbertonschool-higher_level_programming | /0x06-python-classes/4-square.py | 926 | 4.1875 | 4 | #!/usr/bin/python3
class Square:
def __init__(self, size=0):
self.size = size
@staticmethod
def __check_size(size):
if not type(size) == int:
raise TypeError("size must be an integer")
elif size < 0:
raise ValueError("size must be >= 0")
@property
def size(self):
return self.__size
@size.setter
def size(self, value):
Square.__check_size(value)
self.__size = value
def area(self):
return self.size * self.size
if __name__ == '__main__':
my_square = Square(89)
print("Area: {} for size: {}".format(my_square.area(), my_square.size))
my_square.size = 3
print("Area: {} for size: {}".format(my_square.area(), my_square.size))
try:
my_square.size = "5 feet"
print("Area: {} for size: {}".format(my_square.area(), my_square.size))
except Exception as e:
print(e)
| true |
f21e4386013fb02c8346175bc0987e272457f2c8 | RocketHTML/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 1,685 | 4.15625 | 4 | #!/usr/bin/python3
class Square:
def __init__(self, size=0, position=(0, 0)):
self.size = size
self.position = position
@staticmethod
def __check_size(size):
if not type(size) == int:
raise TypeError("size must be an integer")
elif size < 0:
raise ValueError("size must be >= 0")
@staticmethod
def __check_position(position):
if (type(position) != tuple or not
type(position[0]) == int == type(position[1])
or len(position) != 2
or position[0] < 0
or position[1] < 0):
raise TypeError("position must be a tuple of 2 positive integers")
@property
def size(self):
return self.__size
@property
def position(self):
return self.__position
@size.setter
def size(self, value):
Square.__check_size(value)
self.__size = value
@position.setter
def position(self, value):
Square.__check_position(value)
self.__position = value
def area(self):
return self.size * self.size
def my_print(self):
[print() for y in range(self.position[1])]
for i in range(self.size):
[print(' ', end='') for x in range(self.position[0])]
[print('#', end='') for i in range(self.size)]
print()
if self.size == 0:
print()
if __name__ == '__main__':
my_square_1 = Square(3)
my_square_1.my_print()
print("--")
my_square_2 = Square(3, (1, 1))
my_square_2.my_print()
print("--")
my_square_3 = Square(3, (3, 0))
my_square_3.my_print()
print("--")
| true |
d17c6d12f42b9125f5bf76fcb639b97b621f518d | idaln/INF200-2019-Exercises | /src/ida_lunde_naalsund_ex/ex_02/bubble_sort.py | 813 | 4.28125 | 4 | # -*- coding: utf-8 -*-
__author__ = "Ida Lunde Naalsund"
__email__ = "idna@nmbu.no"
def bubble_sort(data):
"""Takes a list or tuple of numbers as input.
Returns a copy of the list where the numbers are
sorted in increasing order.
:param data: List or tuple containing numbers.
:return: Sorted list.
"""
copy = list(data)
n = len(copy)
while n > 0:
i = 1
while i < n:
if copy[i] < copy[i-1]:
copy[i], copy[i-1] = copy[i-1], copy[i]
i += 1
n -= 1
return copy
if __name__ == "__main__":
for element in ((),
(1,),
(1, 3, 8, 12),
(12, 8, 3, 1),
(8, 3, 12, 1)):
print('{!s:>15} --> {!s:>15}'.format(element, bubble_sort(element)))
| true |
5b24fb3a6a665e4d0cc20c678d4a0a7fc2cb6dd5 | idaln/INF200-2019-Exercises | /src/ida_lunde_naalsund_ex/ex01/letter_counts.py | 669 | 4.25 | 4 | # -*- coding: utf-8 -*-
__author__ = 'Ida Lunde Naalsund'
__email__ = 'idna@nmbu.no'
def letter_freq(txt):
"""Function returns a dictionary with letters, symbols and digits
from input "txt" as keys and counts as values.
:param txt: Text written by user
:return: freq
"""
freq = {}
for element in txt.lower():
if element not in freq.keys():
freq[element] = 1
else:
freq[element] += 1
return freq
if __name__ == '__main__':
text = input('Please enter text to analyse: ')
frequencies = letter_freq(text)
for letter, count in frequencies.items():
print('{:3}{:10}'.format(letter, count))
| true |
fbe73ec569ec7bc54dcd3dd0b8dabce4e17d1688 | Gilbert-Adu/my_currency_converter | /proapp.py | 598 | 4.40625 | 4 | """
User interface for module currency
When run as a script, this module prompts the user for two currencies and amount.
It prints out the result of converting the first currency to the second.
Author: Gilbert Adu
Date: 7th February 2019
"""
import pro
currency_from=input('3-letter code for original currency: ')
currency_to=input('3-letter code for the new currency: ')
amount_from=input('Amount of the original currency: ')
result=pro.exchange(currency_from,currency_to,float(amount_from))
print('You can exchange '+ amount_from+' '+ currency_from +' for '+ str(result)+ ' '+currency_to+'.')
| true |
2287cc941b4798589932e8fda8ea02b9e4f0803f | rajat3105/Algorithms | /babylonian.py | 268 | 4.1875 | 4 | def root(n):
x=n
y=1
e=0.001 # e difines the accuracy level
while(x-y>e):
x=(x+y)/2
y=n/x
return x
n= int(input("Enter the number whose square root you need to found : "))
print("Root is: ", round(root(n),3))
| true |
52c4a5cd2f042de57f62d6f675eab8ee2fff14b8 | superleggera-21/BI-Class | /in-class hw.py | 2,651 | 4.59375 | 5 |
# Define a function called hotel_cost with one argument days as user input.
# The hotel costs $140 per day. So, the function hotel_cost should return 140 * days.
def hotel_cost(x):
return 140*x
# Define a function called plane_ride_cost that takes a string, city, as user input.
# The function should return a different price depending on the location, similar to the code example above.
# Below are the valid destinations and their corresponding round-trip prices."Charlotte": 183 "Tampa": 220 "Pittsburgh": 222 "Los Angeles": 475
def plane_ride_cost(city):
citydict = {"Charlotte": 183, "Tampa": 220, "Pittsburgh": 222, "Los Angeles": 475}
return citydict[city]
# Below your existing code, define a function called rental_car_cost with an argument called days.
# Calculate the cost of renting the car: Every day you rent the car costs $40.
# (cost=40*days) if you rent the car for 7 or more days, you get $50 off your total(cost-=50).
# Alternatively (elif), if you rent the car for 3 or more days, you get $20 off your total.
# You cannot get both of the above discounts. Return that cost.
def rental_car_cost(days):
if days >= 7:
cost = 40*days-50
return cost
elif days >=3:
cost = 40*days-20
return cost
else:
cost = 40*days
return cost
# Then, define a function called trip_cost that takes two arguments, city and days.
# Like the example above, have your function print the sum of calling the rental_car_cost(days),
# hotel_cost(days), and plane_ride_cost(city) functions.
def trip_cost(city, days):
cost = plane_ride_cost(city)+rental_car_cost(days)+hotel_cost(days)
print('The total cost of the trip is '+str(cost)+' dollars.')
# Modify your trip_cost function definition. Add a third argument, spending_money (also a user input).
# Modify what the trip_cost function does. Add the variable `spending_money to the sum that it prints.
def trip_cost_with_spending(city, days, spending_money):
cost = plane_ride_cost(city)+rental_car_cost(days)+hotel_cost(days)+spending_money
print('The total cost of the trip is '+str(cost)+' dollars.')
trip_cost_with_spending('Tampa',21,1200)
def trip_cost_with_spending_manual():
city = input('Which city are you going? ')
days = int(input('How many days will the vacation be? '))
spending_money = int(input('How much money will you bring? '))
cost = plane_ride_cost(city)+rental_car_cost(days)+hotel_cost(days)+spending_money
print('The total cost of the trip is '+str(cost)+' dollars.')
trip_cost_with_spending_manual() | true |
4a4c95dd1c57f74fbc66f8552c3885a4c95d6bcb | MasonJoran/U4L4 | /Lesson 4 (Turtle, L1)/Problem4.py | 332 | 4.21875 | 4 | from turtle import *
turtle = Turtle()
turtle1 = Turtle()
turtle.pensize(8)
turtle.color('red')
turtle.shape('turtle')
turtle.speed(9)
turtle1.pensize(8)
turtle1.color('blue')
turtle1.shape('turtle')
turtle1.speed(9)
for x in range(3):
turtle.forward(100)
turtle.left(120)
turtle1.backward(150)
turtle1.circle(75)
mainloop() | false |
9a687191d6e4fba72658656287b9e86877a7ffe1 | dchirag/Python | /a84.py | 1,296 | 4.21875 | 4 |
'''
This code is written to fulfil coursera assignment for the coursera
Python Data Structures
University Of Michigan, Prof. Charles Severance
Aug 2016
It is written with my own efforts and settings. You are free to use it for non-coursera works.
However, it is copywrighted material and seek my persmission and coursera permission for test Datasets
Author: Chirag Desai
'''
'''
Problem 8.4
8.4 Open the file romeo.txt and read it line by line. For each line,
split the line into a list of words using the split() method. The program should build a list of words.
For each word on each line check to see if the word is already in the list and if not append it to the list.
When the program completes, sort and print the resulting words in alphabetical order.
Desired output:
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']
'''
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line = line.rstrip()
word_in_line = line.split(" ")
for word in word_in_line:
if word not in lst:
lst.append( word )
lst.sort()
print lst
| true |
1340b8cab54e2bf2a0ac75d27d164ce52258ea68 | hyro64/Python_growth | /Chapter 10/Book Examples/pi_string.py | 1,540 | 4.4375 | 4 | """# Ver 3.0
# this version check to see if the input appears in the data specified
# After searching through the data it prints accordingly
fileName = "pi_million_digits.txt"
with open(fileName) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line. strip()
birthday = input("Enter your birthday, in the form mmddyy:")
if birthday in pi_string:
print("Your birthday appears in the first million digits of pi!")
else:
print("Your birthday does not appear in the first million digits of pi.")
"""
"""# Ver 2.0
# This version of this program creates the same methods and string as
# the previous version
# The difference is that it only prints the the first 52 digits
fileName = "pi_million_digits.txt"
with open(fileName) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line. strip()
print(pi_string[:52])
print("\nThe lenght of the text file is "+str(len(pi_string)))
"""
"""# Ver. 1.0
# The method ".readlines()" is a python library method.
# The open method adds to the varible lines
# We create a string and add the data line by line to the string while
# striping the new line in the data of the text
# We then print the entire string and the lenght of the string
filename = "pi_digits.txt"
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line. strip()
print(pi_string)
print("\nThe lenght of the text file is "+str(len(pi_string)))
"""
| true |
6bdc6b3269beb139aa315d70fd8935fe316c79a8 | Kondguleyashpal/python-programming-lab | /temperatue conversion.py | 293 | 4.125 | 4 | #Title:Temperature conversion
# Name: Yashpal Kondgule M 31
x=int(input("Enter temperature:")) #input from user
y=input("is it in 'celcius' or 'farenhite'")
if y is 'celsius': #if-else statement
f=9*x/5 + 32
print(f)
else:
c=5/9*(x-32)
print(c)
| false |
2f8f258bbd76f62e4b06aec72dc0bb5e35be6e70 | psmohammedali/pythontutorial | /loops/while2.py | 664 | 4.28125 | 4 | print("Hacker Rank Question")
# Objective
# In this challenge, we're going to use loops to help us do some simple math. Check out the Tutorial tab to learn more.
# Task
# Given an integer,
# , print its first multiples. Each multiple (where
#
# ) should be printed on a new line in the form: n x i = result.
#
# Input Format
#
# A single integer,
#
# .
#
# Constraints
#
# Output Format
#
# Print
# lines of output; each line (where ) contains the of in the form:
# n x i = result.
n = int(input("Enter any number: "))
i =1
while i <= 10:
print(str(n) + " x " + str(i) + "= " + str(i * n))
i = i+1
print("The loop ended") | true |
738f91ab0bcd7175bca49186ec7558cca1ddab94 | Shaunwei/CodingPractice | /CodeBooks/CodeRust/StarcksAndQueues/Stack.py | 765 | 4.34375 | 4 | #!/usr/bin/env python3
# Implementation of Stack using list
class Stack(object):
"""docstring for Stack"""
def __init__(self, size=0):
self._stack = list()
self._size = size
def __len__(self):
return len(self._stack)
def push(self, item):
# print('input item: %d' %item)
self._stack.append(item)
self._size += 1
def pop(self):
if len(self) > 0:
item = self._stack.pop()
#print('pop item: %d' %item)
return item
else:
print("Stack is empty.")
def is_empty(self):
return len(self._stack) == 0
def __unicode__(self):
print(self._stack)
def __str__(self):
return str(self._stack)
if __name__ == '__main__':
s = Stack()
s.push(1)
s.push(2)
s.push(3)
s.push(10)
print(s)
s.pop()
s.pop()
s.pop()
s.pop()
s.pop() | false |
74477f1d4aa19e88778c992678655b7f4d687cfe | Devika-Baddani/python-program | /amstrong.py | 240 | 4.125 | 4 | num = int(input("enter a number: "))
d_num = num
s = 0
while num>0:
r = num%10
s = s + r**3
num //= 10
if s== d_num:
print(d_num, "is an amstrong number")
else:
print(d_num, "is not an amstrong number")
| false |
f7d181b4f92a97008675f96b740a7b1e3372fd09 | henriquebafilho/PythonClasses | /045 GAME Pedra Papel e Tesoura.py | 865 | 4.28125 | 4 | '''Crie um programa que faça o computador jogar Jokenpô com você.'''
import random
usuário = int(input('''Insira o número que corresponde à sua escolha:
1 - pedra
2 - papel
3 - tesoura
'''))
while usuário < 1 or usuário > 3:
usuário = int(input("Erro! Insira um valor válido: "))
def objeto(numero):
if numero == 1:
return "pedra"
elif numero == 2:
return "papel"
else:
return "tesoura"
computador = random.randint(1, 3)
def checagem(user, pc):
if (user == 1 and pc == 2) or (user == 2 and pc == 3) or (user == 3 and pc == 1):
return "Você perdeu"
elif (user == 1 and pc == 3) or (user == 2 and pc == 1) or (user == 3 and pc == 2):
return "Você ganhou!"
else:
return "Empate"
print("A minha escolha foi {}".format(objeto(computador)))
print(checagem(usuário, computador))
| false |
7e7524c2453c777f808f8db1a2cce2492d244edf | lenaurman/py | /2.py | 2,243 | 4.125 | 4 |
# next step
# import
import turtle
import random
# color mode & screen color
turtle.colormode(255)
turtle.bgcolor(0,0,0) # background color - black
def spirala(t):
"""
Draws a spiral with a given tartle object (t)
Starting point is random
Color is random blue
Width is random
"""
t.penup()
t.setx(random.randrange(-200,200))
t.sety(random.randrange(-200,200))
t.pencolor(random.randrange(0,255),random.randrange(0,255),200)
t.width(random.randrange(2,13))
t.pendown()
for i in range(120):
t.forward(20+i)
t.left(30 - i/1.5)
# -- end of spirala(t)
def spiralaa(x,y):
"""
Draws a spiral with a given tartle object (t)
Starting point is random
Color is random blue
Width is random
"""
#print('inside')
#turtle.setx(x)
#turtle.sety(y)
#t.pendown()
turtle.home()
# Random color
turtle.pencolor(random.randrange(0,255),random.randrange(0,255),200)
# Random width
turtle.width(random.randrange(2,13))
# Random direction
turtle.setheading(random.randrange(1,360))
for i in range(70):
turtle.forward(20+i)
turtle.left(30 - i/1.5)
# -- end of spirala(t)
def turn(x,y):
t2.left(70)
t2.forward(77)
#def draw_random_spirala():
#####################
### Main ###
#####################
# init turtle
wn = turtle.Screen()
# some motion
turtle.write('Hellœ', font=18)
turtle.speed(1)
turtle.forward(200)
#spiralaa(turtle.xcor(),turtle.ycor())
#print(turtle.getpen())
#turtle.pencolor('blue')
#turtle.penup()
#turtle.home()
#turtle.pendown()
turtle.onclick(spiralaa)
#turtle.forward(100)
#turtle.onclick(spiralaa)
#t1 = turtle.Turtle()
#t1.speed(0)
#t1.shape('circle')
#spirala(t1)
#ttt = turtle.Turtle()
#spirala(ttt)
#ttt.onclick(spiralaa)
#ttt.onclick(spiralaa)
#ttt.onclick(spiralaa)
#t2 = turtle.Turtle()
#t2.shape('turtle')
#t2.pencolor('red')
#t2.forward(100)
#t2.onclick(turn)
#t2.forward(200)
#t1.onclick(spirala)
#Drawing 3 spirals with random position, color and width
#for z in range(3):
# spirala(t1)
# https://pythonprogramminglanguage.com/user-input-python/
#name = input("Enter a name: ")
#print(name)
turtle.done()
| true |
2a65af6428836391762f57871a7fdc5ef5aee6cb | cliffjsgit/chapter-12 | /exercise122.py | 1,878 | 4.375 | 4 | #!/usr/bin/env python3
__author__ = "Your Name"
###############################################################################
#
# Exercise 12.2
#
#
# Grading Guidelines:
# - No answer variable is needed. Grading script will call function.
# - Function "anagram_finder" should return a list of of all the sets of
# words that are anagrams.
# - Function "anagram_finder2" should return a list of of all the sets of
# words that are anagrams in ascending order by number of anagrams.
# - Function "anagram_bingo" should return a list containing the collection
# of 8 letters that forms the most possible bingos
#
# 1. Write a function named "anagram_finder" that reads a word list
# from a file and returns a list of all the sets of words that are anagrams.
#
# Here is an example of what the output might look like:
# [
# ['deltas', 'desalt', 'lasted', 'salted', 'slated', 'staled'],
# ['retainers', 'ternaries'],
# ['generating', 'greatening'],
# ['resmelts', 'smelters', 'termless']
# ]
#
# Hint: you might want to build a dictionary that maps from a collection of
# letters to a list of words that can be spelled with those letters. The
# question is, how can you represent the collection of letters in a way that
# can be used as a key?
#
#
# 2. Create a modified function of the above named "anagram_finder2" so that it
# prints the longest list of anagrams first, followed by the second longest,
# and so on.
#
#
# 3. In Scrabble a "bingo" is when you play all seven tiles in your rack, along
# with a letter on the board, to form an eight-letter word. Write a function
# named "anagram_bingo" that returns a list containing the collection of 8
# letters that forms the most possible bingos. Hint: there are seven.
#
def anagram_finder("words.txt"):
return
def anagram_finder2("words.txt"):
return
def anagram_bingo("words.txt"):
return | true |
c117517faab9e23db4803f6ba0eba32fa8370031 | shiva-adith/python_projects | /rock_paper_scissors/game.py | 1,341 | 4.21875 | 4 | import random
while True:
choice = input("Enter your choice or enter end to quit: ").lower()
if choice == 'end':
break
choices = ['rock', 'paper', 'scissors']
# the args for randint set the range required for the output.
# the end value is inclusive and hence one is subtracted to prevent going out of index
# computer_choice = choices[random.randint(0, len(choices)-1)]
computer_choice = random.choice(choices)
if choice in choices:
if choice == computer_choice:
print("It's a tie!")
if choice == 'rock':
if computer_choice == 'paper':
print('You lost!')
elif computer_choice == 'scissors':
print("You beat the Computer!")
if choice == 'paper':
if computer_choice == 'scissors':
print('You lost!')
elif computer_choice == 'rock':
print("You beat the Computer!")
if choice == 'scissors':
if computer_choice == 'rock':
print('You lost!')
elif computer_choice == 'paper':
print("You beat the Computer!")
else:
print("Incorrect choice, please try again!\n")
continue
print('You chose: ', choice)
print("The computer chose: ", computer_choice)
print()
| true |
2f8278d26e4a5cd3d5699b30c8988161bb977c8d | Utkarshrathore98/mysirgPythonAssignment_Solution | /Assignment_7_string/Q_4_count occurence.py | 316 | 4.15625 | 4 | '''s=input("enter string ")
e=input("enter the element you want to search")
for i in s:
if i==e:
print(e,"--",s.count(i))
break
'''
#programs to count occurrence of all elements in string
a=input("enter string ")
y=0
for i in a:
if a.index(i)==y:
print(i,"--",a.count(i))
y+=1 | false |
0402d59e632e05bbf53d074d50a4feac6fd2863c | Utkarshrathore98/mysirgPythonAssignment_Solution | /Assignment_2/greatest among three.py | 458 | 4.21875 | 4 | num_1=int(input("enter the first number "))
num_2=int(input("enter the second number"))
num_3=int(input("enter the third number "))
if num_1>num_2:
if num_1>num_3:
print("the greater number is",num_1)
else:
print("the greater number is ",num_3)
elif num_1==num_2==num_3:
print("all numbers are equal")
else:
if num_2>num_3:
print("the greate number is ",num_2)
else:
print("the greater number is ",num_3)
| true |
1a1713ecef84b1963a752e7ebe68491b5d71fd3c | cjc41042/Pig_Latin | /PygLatin.py | 410 | 4.28125 | 4 | import myfunctions
input("Hello! Welcome to the English to PigLatin Translator! Hit Enter to begin!")
word = input('Enter a word or phrase:')
while len(word) > 0:
print ("Your new word or phrase is:")
print (myfunctions.pig(word))
print ("")
print ("Hit Enter to end,")
word = input('Or enter another word or phrase:')
print ('Thanks for using the English to PigLatin Translator!')
| true |
891a2b1a83f8e8b672ce299b6d5c8e56fc865139 | anushanav/python_logical_solutions | /mirrormatrix.py | 505 | 4.25 | 4 | # Printing mirror image of the given matrix
matrix = [[1,2,3],
[4,5,6],
[7,8,9]]
mirror= [[0]*3 for i in range(3)]
rows = 3
columns = 3
for i in range(rows):
for j in range(columns):
mirror[i][j]=matrix[i][columns-1-j]
# printing a matrix that shows addition of the given matrix and its mirror
solution=[[0]*3 for i in range(3)]
for i in range(rows):
for j in range(columns):
solution[i][j]= matrix[i][j]+ matrix[i][columns-1-j]
print (solution)
| true |
c7c88b39fd14b7dc4c7754df8e4dc2a601cc594f | dorakarkut1/Music-Weather | /get_location.py | 764 | 4.125 | 4 | """Get location
This script based on IP address gets and returns location of user.
This script requires that `re, json, urllib` are installed within the Python
environment you are running this script in.
This file can also be imported as a module and contains the following
function:
* get_location - returns location of user
"""
import json
from urllib.request import urlopen
def get_location() -> str:
"""Returns location of user
Parameters
----------
None
Returns
-------
str
String which contains location (city name)
"""
url = 'http://ipinfo.io/json'
with urlopen(url) as response:
data = json.load(response)
return data['city']
if __name__ == '__main__':
print(get_location())
| true |
d3bc53895940522aa706ba220c9cef755896dfae | rishabhsam/Data-Science-Utils- | /unsupAlgoDistanceFunctions.py | 2,442 | 4.5625 | 5 | # -*- coding: utf-8 -*-
"""
Author : Rishabh Samdarshi
Excercise set 2 for W P Carey MSBA 2019-2020 Cohort
This code creates the functions for calculating multiple distances like manhattan, euclidean and minkowski
"""
a,b,c,d = [float (x) for x in input(" Enter coordinates (a,b) (c,d) separated by a space in form a b c d \n").split()]
manhattanDistance = lambda p,q,r,s: abs(p-r)+ abs(q-s)
euclideanDistance = lambda p,q,r,s: ((p-r)**2 + (q-s)**2)**0.5
minkowskiDistance = lambda p,q,r,s: ((abs(p-r))**3 + (abs(q-s))**3)**(1/3)
manDis = manhattanDistance(a,b,c,d)
eucDis = euclideanDistance(a,b,c,d)
minkDis = minkowskiDistance(a,b,c,d)
print ( " The manhattan distnce is :" , manDis,
"\n The euclidean distance is :" , eucDis,"\n The minkowski distance is :", minkDis)
"""
Now for the sake of an excercise we do this again taking the input as a list
"""
coordinateOne = [float (x) for x in input("Enter the x and y coordinate of the first point separated by spaces \n").split()]
coordinateTwo = [float (x) for x in input("Enter the x and y coordinate of the second point separated by spaces\n").split()]
manDis = manhattanDistance(coordinateOne[0],coordinateOne[1],coordinateTwo[0],coordinateTwo[1])
eucDis = euclideanDistance(coordinateOne[0],coordinateOne[1],coordinateTwo[0],coordinateTwo[1])
minkDis = minkowskiDistance(coordinateOne[0],coordinateOne[1],coordinateTwo[0],coordinateTwo[1])
"""
The above examples were for 2 dimensions. Will try to make it more generic for multiple dimensions
"""
dimension = [int(x) for x in input(" Enter the number of dimensions that you wish to calculate the distance for \n")]
xDim = [float (x) for x in input("Enter the x and y coordinate of the first point separated by spaces \n").split()]
if len(xDim) > dimension:
xDim = xDim[:dimension]
raise Exception('Items exceeds the maximum allowed length set, taking the limited dimension only ')
yDim = [float (x) for x in input("Enter the x and y coordinate of the first point separated by spaces \n").split()]
if len(xDim) > dimension:
xDim = xDim[:dimension]
raise Exception('Items exceeds the maximum allowed length set, taking the limited dimension only ')
manDisMultiDim = sum(list(map(lambda x,y: (abs(x)-abs(y)),xDim,yDim)))
eucDisMultiDim = sum(list(map(lambda x,y: (abs(x)-abs(y))**2,xDim,yDim)))**0.5
minkDisMultiDim = sum(list(map(lambda x,y: (abs(x)-abs(y))**3,xDim,yDim)))**(1/3)
| false |
0fcf6ad54dec3acfc1d4d7f8096f7f840a25298b | RodrigoMorosky/CursoPythonCV | /aula08.py | 375 | 4.25 | 4 | # aula 8 utilizando módulos
import math
num = int(input('Digite um número: '))
raiz = math.sqrt(num)
print('A raiz de {} é igual a {:.2f}'.format(num, raiz))
# dá para importar só a função desejada e não a biblioteca inteira
#from math import sqrt
#num = int(input('Digite um número: '))
#raiz = sqrt(num)
#print('A raiz de {} é igual a {:.2f}'.format(num, raiz))
| false |
fd6311b20aa6851ac1dc53420d7faa529bf5d4ab | SuguruChhaya/python-exercises | /Hackerrank 30 days of code/binary.py | 402 | 4.15625 | 4 | print(0b000000001001)
# ?binary numbers 0101 is 5, but I don't understand how a binary number can start with a 0
#!As you can see in the previous examples, the sequence between the first 1 and last 1 is what matters.
#!No matter how many 0s you add before the first 1, the value wouldn't change
#!Addionally, no matter how many 0s you add after the last 1, the number wouldn't change.
print(bin(9.5))
| true |
7c042db4f53e1b0cedcf889f8117859845705eea | Martondegz/python-snippets | /par.py | 1,050 | 4.15625 | 4 | # Write a function that return whether or not the input string has balanced parentheses
# Balanced:
# '((()))'
# '(()())'
# Not balanced:
# '((()'
# '())('
# use input for a string
from pythonds.basic.stack import Stack
def parChecker(symbolString):
s = Stack() # stack method applied
balanced = True # bool value true if par is balanced
index = 0
while index < len(symbolString) and balanced: # loops through the symbolString
symbol = symbolString[index] # assign a symbol var to the symbolString index
if symbol == "(": # condition set
s.push(symbol) # push the symbol on the stack
else:
if s.isEmpty(): # when stack is empty
balanced = False # no balance
else:
s.pop() # else remove the the symbol from the stack
index = index + 1 # start up indexing of the symbolString
if balanced and s.isEmpty():
return True
else:
return False
print(parChecker('((()))'))
print(parChecker('(('))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.