blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
47dbe1afe497cd782da601861888775c94cb3e7c | brandonmorren/python | /C3 iteratie/oefIteratie/oefening 5.py | 619 | 4.25 | 4 | number = int(input("enter a number: "))
if number != 0:
smallest_number = number
highest_number = number
difference = 0
while number != 0:
if number < smallest_number:
smallest_number = number
else:
if number > highest_number:
highest_number = number
difference = highest_number - smallest_number
number = int(input("enter a number: "))
print("the difference between the largest number " + str(highest_number) + " and the smallest number " + str(smallest_number) + " = " + str(difference))
else:
print("no numbers entered") | true |
8ae7e1a9e691f66b965f09644bf849f4938d5506 | brandonmorren/python | /C10 set/OefeningenSet/oef 5.py | 479 | 4.4375 | 4 | months_days = {"January": 31, "February": 28, "March": 31,
"April": 30, "May": 31, "June": 30, "July": 31,
"August": 31, "September": 30, "October": 31,
"November": 30, "December": 31}
input_month = input("Month (press enter for an overview of all months): ")
if input_month == "":
for month in months_days:
print(month, "\t", months_days[month])
else:
print(months_days.get(input_month, "this month does not exist")) | true |
12a0e490f5025bca17f7957ae7cf6a7677bfd7fe | naldridge/algorithm_exercises | /algorithm_exercise.py | 1,468 | 4.25 | 4 | # Algos
## 1. Bubble Sort
Write a program to sort a list of numbers in ascending order, comparing and swapping two numbers at a time.
```python
[3,1,4,2]
[1,3,4,2]
[1,3,2,4]
[1,2,3,4]
```
## 2. Candies
Given the list `candies` and the integer `extra_candies`, where `candies[i]` represents the number of candies that the `ith` kid has.
For each kid, check if there is a way to distribute the `extra_candies` amount to the kids such that they can have the greatest numhber of candies among them. Notice that multiple kids can have the greatest number of candies.
```python
candies = [2,3,5,1,3]
extra_candies = 3
expected output: [True,True,True,False,True]
```
## 3. Shuffle
Given a string `s` and an integer list of `indices` of the same length, shuffle the string such that the character at the `ith` position moves to `incices[i]`.
Return the shuffled string.
```python
s = "odce"
indices = [1,2,0,3]
return "code"
```
## 4. Primes
Write a program that returns a list of all prime numbers up to a given max(inclusive).
A prime is a number that only has two factors; itself and 1.
```python
n=12
[2,3,5,7,11]
```
## 5. FizzBuzz
A classic; write a program that prints out a sequential string of numbers.
If divisible by 3, output `"Fizz`.
If divisible by 5, output `"Buzz`.
If divisible by both 3 and 5, output `FizzBuzz`.
Otherwise, print out the string.
```python
Between 1 and 5, output:
"1"
"2"
"Fizz"
"4"
"Buzz"
```
| true |
6d4c8d2e2843896ebe132366a5a5e3b35064a0c7 | ydj515/python-cleancode | /Chapter6/not_use_descriptor.py | 1,013 | 4.1875 | 4 | #-*- coding: utf-8 -*-
"""
속성을 가진 이란적인 클래스인데 속성의 값이 달라질 때마다 추적
속성의 setter 메소드에서 값이 변경될 때 검사하여 리스트와 같은 내부 변수에 값을 저장
"""
class Travller:
def __init__(self, name, current_city):
self.name = name
self._current_city = current_city
self._cities_visited = [current_city]
@property
def current_city(self):
return self._current_city
@current_city.setter
def current_city(self, new_city):
if new_city != self._current_city:
self._cities_visited.append(new_city)
self._current_city = new_city
@property
def cities_visited(self):
return self._cities_visited
def main():
alice = Travller("Alice", "Barcelona")
alice.current_city = "Paris"
alice.current_city = "Brussels"
alice.current_city = "Amsterdam"
print(alice.cities_visited)
if __name__ == "__main__":
main() | false |
a1c49869e7026c54009ebac29d8b485fcc570072 | WesleyPereiraValoes/Python | /Curso em Python Mundo 3/ex113.py | 672 | 4.21875 | 4 | while True:
try:
num = int(input('Digite um número inteiro: '))
except KeyboardInterrupt:
num = 0
print('Usuario desistiu de inserir um valor!')
break
except:
print(f'ERROR: Digite um número inteiro válido!')
else:
print(f'O número digitado foi {num}.')
break
while True:
try:
real = float(input('Digite um número real: '))
except KeyboardInterrupt:
real = 0
print('Usuario desistiu de inserir um valor!')
break
except:
print(f'ERROR: Digite um número real válido!')
else:
print(f'O número digitado foi {real}.')
break | false |
440aad874dfa186c0419813799507b6f4a31debb | midathanapallivamshi/Saloodo | /Question one challange( return reverse of string)/reversestring.py | 988 | 4.28125 | 4 | #!/usr/bin/env python3
import random
# Json module import only if we are reading json input reading and currently we are not reading json input and hence commenting out
# import json
def reverse_string(str_input):
"""
This method is used to reverse a string
"""
reverse_string = str_input[1:]
return reverse_string
def generate_random_number():
"""
This method is used to generate random number between 1 and 10000
"""
random_number = random.randint(1,10000)
return random_number
# defining in dict format and later required to replace with json input readable code.
input_json = {"message": "abcdef"}
# empty dict to store output
output = {}
# Get reverse string
get_reverse_str = reverse_string(input_json["message"])
output["message"] = get_reverse_str
# Get a random number
random_number = generate_random_number()
output["random"] = random_number
# Print output to console
print(json.dumps(output))
| true |
4187ba4726a9bd9feda1d72edf9a0a7215f9bdbf | saipavandarsi/Python-Learnings | /FileSamples/ReverseFileContent.py | 344 | 4.3125 | 4 | #File content Reversing
#Using read()
file = open('myfile.txt', 'r')
content = file.read()
print content
print content[::-1]
# Using ReadLines
file = open('myfile.txt', 'r')
content_lines = file.readlines()
#content_lines[::-1] is to reverse lines
for line in content_lines[::-1]:
#print characters in reverse
print line[::-1] ,
| true |
f387d5872cd714e4f672fa9cd08e788072c4cd99 | jldroid25/DevOps | /Python_scripting/Review_Python/Foundation/1-BasicPython/integers_floats.py | 683 | 4.125 | 4 | ''' ------ Working with Integers and Floats in Python -----
There are two Python data types that could be used for numeric values:
- int - for integer values
- float - for decimal or floating point values
You can create a value that follows
the data type by using the following syntax:
'''
x = int(4.7) # x is now an integer of 4
y = float(4) # y is now a float of 4.0
print(x)
print(type(x))
print(y)
print(type(y))
'''
In general, there are two types of errors to look out for
Exceptions and Syntax errors
An Exception: is a problem that occurs when the code is running.
A 'Syntax Error' is a problem detected when Python checks
the code before it runs it.
'''
| true |
d32d3cfd34306257a27952348fa9c647a504ecb1 | jldroid25/DevOps | /Python_scripting/Review_Python/Foundation/2-DataStructures/dictionaries.py | 1,178 | 4.125 | 4 | # Dictionary :
'''
A Data Type for mutable object that store pairs or mappings of unique keys to values.
'''
elements = {'hydrogen': 1, 'helium': 2, 'carbon': 6 }
elements['lithium']= 3
print("\n\n")
print(elements)
print("\n\n")
# We can also use " in" in dictionaries to check if an element is present.
print("Jl" in elements)
print("\n\n")
# Get() methods , looks up dictionary's values in a dictionary, it returns none or default value
# you had provided if the value is not found.
print(elements.get("DevOps", "DevOps is Not Found"))
print("\n\n")
# You can check if a dictionary's Key returns "none" with the identity "is" operator
# & manage code from there to preven a crash
jobDesc = elements.get('Site Reliability')
#is_null = jobDesc is None
# "is not" the opposite operator of "is"
is_null = jobDesc is not None
print(is_null)
print("\n\n")
VTXAS = {'MICOS': 133, 'Tesla': 1540, 'Appl': 850, 'Lyft': 345}
VNQ = {'MICOS': [133, -6.51], 'Tesla': [1540, 0.78], 'Appl': [850, 17.01], 'Lyft': [345, 0.79] }
print("VTXAS index fund Stocks & Prices\n", VTXAS)
print("\n")
print("VNQ index fund Stock, Price, & Yield of returns:\n",VNQ)
print("\n\n")
| true |
dbdc1a6706be097b1727dcfa8d72c3511011dbbd | jldroid25/DevOps | /Python_scripting/Review_Python/Foundation/6-iterator-generator/iterator-generator.py | 2,954 | 4.78125 | 5 | import numpy as np
'''
--Iterators And Generators
- Iterables: are objects that can return one of their elements at a time,
such as a list. Many of the built-in functions we’ve used so far,
like 'enumerate,' return an iterator.
- An iterator: is an object that represents a "stream of data".
This is different from a list, which is also an iterable,
but is not an iterator because it is not a stream of data.
- Generators are a simple way to create iterators using functions.
You can also define iterators using classes,
which you can read more about
Here is an example of a generator function called my_range,
which produces an iterator that is a stream of numbers from 0 to (x - 1).
'''
def my_range(x):
i = 0
while i < x:
#Yield is a generator , allow function to generate one value at a time
yield i
i += 1
'''
Notice that instead of using the return keyword, it uses yield.
This allows the function to return values one at a time, and start
where it left off each time it’s called.
This yield keyword is what differentiates a generator from a typical function.
Remember, since this returns an iterator, we can convert it to a list
or iterate through it in a loop to view its contents. For example, this code:
'''
for x in my_range(5):
print(x)
'''
Why Generators?
Generators are a lazy way to build iterables.
They are useful when the fully realized list would not fit in memory,
or when the cost to calculate each list element is high and you
want to do it as late as possible. But they can only be iterated over once.
'''
# Quiz Implement my_enumerate
lessons = [
"Why Python Programming", "Data Types and Operators",
"Control Flow", "Functions", "Scripting"
]
def my_enumerate(iterable, start=0):
count = start
for element in iterable:
yield count, element
count += 1
for i, lesson in my_enumerate(lessons, 1):
print("Lesson {}: {}".format(i, lesson))
print('\n')
# write a chunker
def chunker(iterable, size):
"""Yield successive chunks from iterable of length size."""
for i in range(0, len(iterable), size):
yield iterable[i:i + size]
for chunk in chunker(range(25), 4):
print(list(chunk))
print('\n')
# Same as above but much simplier
def chunks(l, n):
n = max(1, n)
return (l[i:i+n] for i in range(0, len(l), n))
for chunk2 in chunks(range(30), 4):
print(list(chunk2))
# see numpy (as np) import above file
lst = range(50)
print(np.array_split(lst, 5))
'''
--Generator Expressions
Here's a cool concept that combines generators and list comprehensions!
You can actually create a generator in the same way you'd normally write a
list comprehension, except with parentheses instead of square brackets.
For example:
'''
sq_list = [x**2 for x in range(10)] # this produces a list of squares
sq_iterator = (x**2 for x in range(10)) # this produces an iterator of squares
| true |
8b03d7b5c1edd3313ff972108fa7fc3173cc2a01 | jldroid25/DevOps | /Python_scripting/Review_Python/Foundation/5-Scripting/ScriptingRawInput.py | 571 | 4.3125 | 4 | # -------------Scripting Raw Input ------------------#
#using the input() function
name = input("Enter a name: ")
#print("Welcome come in ", name.title())
# When using the the input() with numbers
# you must include the data type "int()" or "float()" funtion
# else python will throw an error
print('\n')
num = int(input('enter a number: '))
#print('What\'s number ?', num )
print("Wow expensive {} chages {} per hour".format(name, num))
# ---- We can also use eval() to evaluate a string as a line of Python
num = 30
x = eval('num + 42')
print(x)
print("\n")
| true |
8e77e139517c1ed083f00c390ed2bcc29d29654d | jldroid25/DevOps | /Python_scripting/Review_Python/Foundation/2-DataStructures/CompoundDataStruct.py | 1,279 | 4.1875 | 4 | # Compound DataStructure is a combination of dictionary inside another
# to have elements names to another dictionary that stores that collection data.
# Essentially it's a nested dictionary
print("\n\n")
elements = {
'hydrogen': {'number': 1, 'weight': 1.000794, 'Symbol' : 'H'} ,
'helium': {'number': 2, 'weight': 3.1007, 'Symbol' : 'He'} ,
'carbon': {'number': 6, 'weight': 4.200, 'Symbol' : 'Ca'}}
print(elements)
print("\n\n")
print("Hydrogen:", elements['hydrogen'])
print("helium:", elements['helium'])
print("number:", elements['carbon'])
print("\n")
VTSAX = {
'Apple': {'Sticker':'APPL', 'Price': 1056, 'Yield': 0.679} ,
'Tesla': {'Sticker': 'TesT', 'Price': 3006, 'Yield': 790.89} ,
'Lyft': {'Sticker': 'LYT', 'Price': 56, 'Yield': 0.0023}
}
print("Apple Stock info :", VTSAX['Apple'])
print("Tesla Stock Info:", VTSAX['Tesla'])
print("Lyft Stock Info :", VTSAX['Lyft'])
print("\n\n")
# We can also use get() method to find elements by their key
print(elements.get('calcium', 'There\'s no such element'))
print("\n")
print(VTSAX.get('Microsoft', 'There\'s no such stock info'))
print("\n\n")
# we can also look up by more keys with []
print("Hydrogen:", elements['hydrogen']['weight'])
print("Lyft:", VTSAX['Lyft']['']) | false |
fe263deeeb9e60830db38532633f728b325271c6 | Zachary3352/reading-journal-Zachary3352 | /shapes.py | 2,162 | 4.375 | 4 | import turtle
#------------------------------------------------------------------------------
# Make some shapes
# Work through exercises 1-4 in Chapter 4.3.
#------------------------------------------------------------------------------
# Square
# NOTE: for part 2 of 4.3, you will add another parameter to this function
def square(t, length):
"""
Draw a square using Turtle t
>>> don = turtle.Turtle()
>>> square(don, 200)
"""
t.fd(length)
t.rt(90)
t.fd(length)
t.rt(90)
t.fd(length)
t.rt(90)
t.fd(length)
turtle.mainloop()
## Polygon
def polygon(t, n, length):
"""
Draw a polygon using Turtle t
>>> don = turtle.Turtle()
>>> polygon(don, 7, 200)
"""
for i in range(n):
t.fd(length)
t.rt(360/n)
turtle.mainloop()
## Circle
def circle(t, r):
"""
Draw a circle using Turtle t
>>> don = turtle.Turtle()
>>> circle(don, 50)
"""
for i in range(150):
t.fd((r*3.1415926*2)/150)
t.rt(360/150)
turtle.mainloop()
# john = turtle.Turtle()
# square(john,100)
# polygon(john,7,100)
# circle(john,10) # This file calls all three functions with these lines uncommented, but because of some Tkinter error that I think is outside the scope of this RJ (_tkinter.TclError: invalid command name ".!canvas"), it only runs one of these three lines before the program quits.
#------------------------------------------------------------------------------
# Make some art
# Complete *at least one of* Exercise 2, 3, 4, or 5 in `shapes.py`.
#------------------------------------------------------------------------------
# If you come up with some cool drawings you'd like to share with the rest of the class, let us know!
def hyperbolic_spiral(t, lines):
"""
Draw a hyperbolic spiral using Turtle t
>>> don = turtle.Turtle()
>>> hyperbolic_spiral(don, 360)
"""
for i in range(lines):
t.fd(1)
t.lt(lines/(i+1))
turtle.mainloop()
# if __name__ == "__main__":
# import doctest
# doctest.testmod()
# doctest.run_docstring_examples(square, globals(), verbose=True)
| false |
95657382a090f8341cfe2aebfad9cb5dadb3e75f | antonio00/blue-vscode | /MODULO 01/AULA 10/EX01.PY | 328 | 4.15625 | 4 | # Escreva um programa que pede a senha ao usuário,
# e só sai do looping quando digitarem corretamente a senha
senha = '5467'
tentativa=input("Digite a senha:")
while senha != tentativa:
print("Senha Incorreta! Tente novamente!")
tentativa=input("Digite a senha:")
print("Senha correta. Acesso liberado...")
| false |
4445febfb60cfa94adc57d490b02afe4d66c2397 | GaborBakos/codes | /CCI/Arrays_and_Strings_CHP1/1_string_compression.py | 1,037 | 4.375 | 4 | '''
Implement a method to perform basic string compression using the counts of repeated characters.
EXAMPLE:
Input: aabcccccaaa
Output: a2b1c5a3
If the "compressed" string would not become smaller than the original return the original.
You can assume the string has only uppercase and lowercase letters (a-z).
'''
def compress(string):
new_string = string[0]
count = 1
for i in range(len(string)-1):
if string[i] == string[i+1]:
count+=1
else:
new_string += str(count)
new_string += string[i+1]
count = 1
new_string += str(count)
if len(new_string) >= len(string):
return string
return new_string
print('Testing:')
string1 = 'aabcccccaaa'
string2 = 'bbbgaobgoaoaooooooooooooooooooooooooooooooog'
string3 = 'goahgnpajngpangoinsokgnobng'
print('{} --> {}'.format(string1, compress(string1)))
print('{} --> {}'.format(string2, compress(string2)))
print('{} --> {}'.format(string3, compress(string3)))
| true |
08871a22ab49d1750f9d5ccdda7d90686b751e42 | Nao801/opp | /kadai.py | 1,626 | 4.46875 | 4 | '''
課題1:円オブジェクト
次のコードが正しく動作するようなCircleクラスを実装すること
areaは面積、perimeterは周囲長という意味
#半径1の円
Circle1 = Circle(radius=1)
print(circle1.area()) #3.14
print(circle1.perimeter()) #6.28
#半径3の円
Circle3 = Circle(radius=3)
print(circle3.area()) #28.27
print(circle3.perimeter()) #18.85
'''
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return f'{math.pi * (self.radius ** 2):.2f}'
def perimeter(self):
return f'{math.pi * (self.radius * 2):.2f}'
circle1 = Circle(radius=1)
print(circle1.area())
print(circle1.perimeter())
circle3 = Circle(radius=3)
print(circle3.area())
print(circle3.perimeter())
'''
課題2:長方形オブジェクト
次のコードが正しく動作するようなRectangleクラスを実装すること
diagonalは対角線(の長さ)という意味
rectangle1 = Rectangle(height=5, width=6)
rectangle1.area() #30.00
rectangle1.diagonal() #7.81
rectangle2 = Rectangle(height=3, width=3)
rectangle2.area() #9.00
rectangle2.diagonal() #4.24
'''
class Rectangle:
def __init__(self, height, width):
self.height= height
self.width = width
def area(self):
return f'{self.height * self.width:.2f}'
def diagonal(self):
return f'{math.sqrt(self.height ** 2 + self.width ** 2):.2f}'
rectangle1 = Rectangle(height=5, width=6)
print(rectangle1.area())
print(rectangle1.diagonal())
rectangle2 = Rectangle(height=3, width=3)
print(rectangle2.area())
print(rectangle2.diagonal())
| false |
5b6c99aa27f6d2c4c7466dff79492c41882f8fda | BeahMarques/Workspace-Python | /Seção 3/exercicio26/app.py | 310 | 4.21875 | 4 | Categoria = int(input("Qual sua categoria: "))
if Categoria == 1:
print("Voce escolheu a categoria BOLSA!")
elif Categoria == 2:
print("Voce escolheu a categoria TENIS!")
elif Categoria == 3:
print("Voce escolheu a categoria MOCHILA!")
else:
print("Essa categoria não foi encontrada") | false |
aff2467f53cb555016ebfd476cec773bbb316f7f | Spandan-Dutta/Snake_Water_Gun_Game | /SNAKE_WATER_GUN_GAME.PY | 2,988 | 4.21875 | 4 | """
So the game is all about that:
1) If you choose Snake and computer choose Gun, you loose as computer shots the snake with a gun.
2) If you choose Gun and computer choose water, you loose as gun is thrown in the water.
3) If you choose Snake and computer choose Water, you wins as Snake drinks the water.
"""
import random
print("Welcome to Snake, Water and Gun Game")
print("Total number of attempts is 10")
attempts = 1
human_score = 0
computer_score = 0
while (attempts <= 10):
print("Choices are: Snake, Water and Gun")
inp = input("Enter your choice: ")
l = ["Snake", "Water", "Gun"]
ran = random.choice(l)
if inp == "Snake" and ran == "Snake":
print("It's a Tie....")
print("You and computer both chose Snake!")
elif inp == "Water" and ran == "Water":
print("It's a Tie....")
print("You and computer both chose Water!")
elif inp == "Gun" and ran == "Gun":
print("It's a Tie....")
print("You and computer both chose Gun!")
elif inp == "Gun" and ran == "Snake":
human_score = human_score + 1
print("Congratulations!!!! You Won....")
print("You chose Gun and computer chose Snake")
print("You got 1 point")
elif inp == "Gun" and ran == "Water":
computer_score = computer_score + 1
print("You Loose!!!")
print("You chose Gun and computer chose Water")
print("Computer gets 1 point")
elif inp == "Snake" and ran == "Gun":
computer_score = computer_score + 1
print("You Loose!!!")
print("You chose Snake and computer chose Gun")
print("Computer gets 1 point")
elif inp == "Snake" and ran == "Water":
human_score = human_score + 1
print("Congratulations!!!! You Won....")
print("You chose Snake and computer chose Water")
print("You got 1 point")
elif inp == "Water" and ran == "Snake":
computer_score = computer_score + 1
print("You Loose!!!")
print("You choose Water and computer chose Snake")
print("Computer gets 1 point")
elif inp == "Water" and ran == "Gun":
human_score = human_score + 1
print("Congratulations!!!! You Won....")
print("You choose Water and computer chose Gun")
print("You got 1 point")
else:
print("Invalid Input")
print("Type the first digit as capital")
continue
# Logic to tell how many attempts are left
print(f"Number of attempts left are {10-attempts}")
attempts = attempts + 1
if attempts > 10:
print("Game Over")
print(f"Your Score:{human_score}", end = ",")
print(f"Computer Score:{computer_score}")
if computer_score > human_score:
print("Computer wins")
elif human_score > computer_score:
print("You Win this game buddy!!!!")
else:
print("It was Tie!!!")
| true |
04fd2d654936f8cc705f5a362a4326f175995ddc | standrewscollege2018/2020-year-11-classwork-Bmc9529 | /For loop example.py | 366 | 4.1875 | 4 | """ for loop example, for loops run up to but not the final number"""
i = 1
#in for loops we set a start, enging and increment valu
for i in range(1,1001):
if i % 3 == 0 and i % 5 == 0:
print("fizzbuzz")
elif i % 3 == 0 and not i % 5 == 0:
print("fizz")
elif i % 5 == 0 and not i % 3 == 0:
print("buzz")
else:
print(i) | false |
464c3b7fcfd0409dc72f9a238227af789aed4aa0 | Asmithasharon/Python-Programming | /square_root.py | 409 | 4.375 | 4 | '''
To find the square root of a number using newton's method.
'''
def sq_root(number, precision):
sqroot = number
while abs(number - (sqroot * sqroot)) > precision :
#'''abs() is to get the absolute value'''
sqroot = (sqroot + number / sqroot) / 2
return sqroot
number = int(input("Enter a number: "))
precision = 10 ** -4
print(sq_root(number , precision))
| true |
0425427f405ff360a9b61b66dd26ecfd25f1ba28 | pawnwithn0name/Python-30.03-RaKe | /py_07_04_second/decision_making/if-demo.py | 386 | 4.1875 | 4 | num = float(input("Enter a floating-point: "))
var = int(input("Enter an integer: "))
if num > 100:
print("Numbers entered: {}, {} is greater than 100.".format(num, var))
print("Numbers entered: {1}, {0} is greater than 100.".format(num, var))
print(f"Numbers entered: {num}, {var} is greater than 100.")
print("Numbers entered: %d, %f is greater than 100." %(num, var)) | true |
faa9cc5542f7bb23f5c8e60b779a089381ae319d | BitanuCS/Python | /College-SemV/07. occurrence of each letter.py | 270 | 4.125 | 4 |
#Count the occurrence of each letter in "Maharaja Manindra Chandra College".
str = 'Maharaja Manindra Chandra College'
freq = {}
for i in str:
if i in freq:
freq[i] += 1
else:
freq[i] = 1
print("Frequencies of {} is:\n {}".format(str,freq))
| false |
6829fda3257b5e28f7d54f699bfedabb1ef6da06 | BitanuCS/Python | /College-SemV/10. vehicle class with max_speed and mileage attributes.py | 437 | 4.25 | 4 |
# creat a vehicle class with max_speed and mileage attributes.
class Vehicle:
def __init__(self,max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage
print("Max. Speed of your car is: {}\nMileage is: {}".format(max_speed,mileage))
max_speed = float(input("What is the max_speed of your car? "))
mileage = float(input("What is the mileage of your car? "))
car = Vehicle(max_speed,mileage) | true |
56354c5fcf9292ceaae13f4455af5ec3437d7c5e | pksingh786/BETTER-CALCULATOR | /BETTER CALCULATOR.py | 601 | 4.25 | 4 | #this is a better calculatorin comparison of previous one
first_num=float(input("enter first number:"))
second_num=float(input("enter second number:"))
print("press + for addition")
print("press - for subtraction")
print("press * for Multiplication")
print("press / for division")
input=input("enter the symbol for which you want to perform a operation")
if input=="+":
print(first_num+second_num)
elif input=="-":
print(first_num-second_num)
elif input=="*":
print(first_num*second_num)
elif input=="/":
print(first_num/second_num)
else:
print("invalid symbol")
| true |
2b53d5961c27ba0e1144b4eb74065e29bf6e7471 | mochapup/LPTHW | /ex20_SD5.py | 1,078 | 4.28125 | 4 | # Functions and files
# import argv
from sys import argv
# Scripr and argument input
script, input_file = argv
# defining function that prints all of file
def print_all(f):
print(f.read())
# defining a function to rewind to character 0 of file
def rewind(f):
f.seek(0)
# defining a function to print each line seperately with its line count.
def print_a_line(line_count, f):
print(line_count, f.readline())
# opening argument file
current_file = open(input_file)
# reading and printing the argument file
print("First let's print the whole file:\n")
print_all(current_file)
# Moving to line 0 of the file
print("Now let's rewind, kind of like tape.")
rewind(current_file)
# Printing each line starting with line one
print("Let's print three lines:")
# defining current line, in argument file, and adding itself 1 each succesion.
#Then running the print_a_line function with current_line.
current_line = 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
| true |
e40e0d6fb683e2da5b75fbe9ad8f3385b7ad7617 | alfrash/git_1 | /Pandas/Pandas_1.py | 763 | 4.28125 | 4 | import pandas as pd
groceries = pd.Series(data=[30,6,'yes','no'],index=['eggs', 'apples', 'milk', 'bread'])
print(groceries)
print(groceries.shape)
print(groceries.ndim)
print(groceries.size)
print(groceries.values)
print(groceries.index)
print('banana' in groceries)
# lesson 5 - Accessing and Deleting Elements in Pandas Series
print(groceries['eggs'])
print(groceries[['milk','bread']])
print(groceries[0])
print(groceries[-1])
print(groceries[[0,1]])
print(groceries.loc[['eggs','apples']])
print(groceries.iloc[[2,3]])
# modify
groceries['eggd'] = 2
print(groceries)
# deleting
x = groceries.drop('apples') # create a new list dose not delete from the origenal
print('x =',x)
# deleting in place
groceries.drop('apples', inplace=True)
print(groceries) | true |
413300290ba3ef27daa57ef52f45af5189bef2a6 | IvanyukStas/different_lessons | /reverse_every_acdeting.py | 1,099 | 4.125 | 4 | def reverse_ascending(items):
# your code here
temp_items = []
new_items = []
for i in range(len(items)):
if i == len(items)-1:
temp_items.append(items[i])
temp_items.reverse()
for j in temp_items:
new_items.append(j)
continue
if items[i] < items[i+1]:
temp_items.append(items[i])
else:
temp_items.append(items[i])
temp_items.reverse()
new_items.extend(temp_items)
temp_items = []
print(temp_items)
print(new_items)
return new_items
if __name__ == '__main__':
print("Example:")
assert list(reverse_ascending([5, 7, 10, 4, 2, 7, 8, 1, 3])) == [10, 7, 5, 4, 8, 7, 2, 3, 1]
assert list(reverse_ascending([5, 4, 3, 2, 1])) == [5, 4, 3, 2, 1]
assert list(reverse_ascending([])) == []
assert list(reverse_ascending([1])) == [1]
assert list(reverse_ascending([1, 1])) == [1, 1]
assert list(reverse_ascending([1, 1, 2])) == [1, 2, 1]
print("Coding complete? Click 'Check' to earn cool rewards!")
| false |
9fa1c6ab1f961cce3d2464b1e8079a2bd407c631 | chetangargnitd/Python-Guide-for-Beginners | /Factorial/iterativeFactorial.py | 442 | 4.40625 | 4 | # Python program to find the factorial of a given number
# input the number to find its factorial
num = int(input("Enter a number: "))
factorial = 1
if num < 0: #factorial doesn't exist for a negative number
print("Please enter a valid number!")
elif num == 0: #factorial of 0 is 1
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print "The factorial of",num,"is",factorial | true |
63a8f0dfb92e74e4fa574f3048f810823893b820 | gabrielavirna/python_data_structures_and_algorithms | /my_work/ch3_stacks_and_queues/bracket_matching_app.py | 1,856 | 4.15625 | 4 | """
Bracket-matching application
----------------------------
- using our stack implementation, verify whether a statement containing brackets --(, [, or {-- is balanced:
whether the number of closing brackets matches the number of opening brackets
- It will also ensure that one pair of brackets really is contained in another
Run Time Complexity: O(1) - the push and pop operations of the stack data structure
The stack data structure usage: The back & forward buttons on the browser; undo & redo functionality in word processors
"""
from projects.python_data_structures_algorithms.my_work.ch3_stacks_and_queues.stack import Node, Stack
def check_balanced_brackets(statement):
stack = Stack()
# parses each character in the statement passed to it
for ch in statement:
# If it gets an open bracket, it pushes it onto the stack
if ch in ('{', '[', '('):
stack.push(ch)
# If it gets a closing bracket, it pops the top element off the stack
if ch in ('}', ']', ')'):
last = stack.pop()
# and compares the two brackets to make sure their types match: (), [], {}
if last is '{' and ch is '}':
# continue parsing
continue
elif last is '[' and ch is ']':
continue
elif last is '(' and ch is ')':
continue
else:
return False
if stack.size > 0:
# if the stack is not empty, then we have some opening bracket which does not have a matching closing bracket
return False
else:
return True
sl = (
"{(foo)(bar)}[hello](((this)is)a)test",
"{(foo)(bar)}[hello](((this)is)atest",
"{(foo)(bar)}[hello](((this)is)a)test))"
)
for s in sl:
m = check_balanced_brackets(s)
print("{}: {}".format(s, m))
| true |
b14bab37f60ba19116cf36475643ac4e7e4a1cd6 | gabrielavirna/python_data_structures_and_algorithms | /my_work/ch2_lists_and_pointer_structures/lists_and_pointers.py | 2,302 | 4.34375 | 4 | """
Pointers
--------
Ex:
a house that you want to sell;
a few Python functions that work with images, so you pass high-resolution image data between your functions.
Those large image files remain in one single place in memory. What you do is create variables that hold the locations
of those images in memory. These variables are small and can easily be passed around between different functions.
Pointers: allow you to point to a potentially large segment of memory with just a simple memory address.
In Python, you don't manipulate pointers directly (unlike C/Pascal).
s = set()
We would normally say that s is a variable of the type set. That is, s is a set. This is not strictly true, however.
The variable s is rather a reference (a "safe" pointer) to a set. The set constructor creates a set somewhere in memory
and returns the memory location where that set starts. This is what gets stored in s.
Python hides this complexity from us. We can safely assume that s is a set and that everything works fine.
Array
------
- a sequential list of data;
- sequential = each element is stored right after the previous one in memory
If array is really big & you're low on memory => might be impossible to find large enough storage to fit entire array
Benefits:
Arrays are very fast: Since each element follows from the previous one in memory, there is no need to jump around
between different memory locations => important when choosing between a list and an array in real-world applications.
Pointer structures
------------------
- Contrary to arrays, pointer structures are lists of items that can be spread out in memory.
- Each item contains one or more links to other items in the structure
- Type of links are dependent on the type of structure:
for linked lists => links to the next (and possibly previous) items in the structure,
for a tree => parent-child links as well as sibling links
in a tile-based game whith a game map built up of hexes, each node will have links to up to 6 adjacent map cells.
Benefits:
They don't require sequential storage space;
They can start small and grow arbitrarily as you add more nodes to the structure
But: for a list of ints, each node needs the space of an int & an additional int for storing the pointer to next node.
""" | true |
28920f935d378841ec8750148075236777dfe2b1 | gabrielavirna/python_data_structures_and_algorithms | /my_work/ch2_lists_and_pointer_structures/circular_lists.py | 2,502 | 4.15625 | 4 | """
Circular lists
---------------
- a special case of a linked list
- It is a list where the endpoints are connected: the last node in the list points back to the first node
- Circular lists can be based on both singly and doubly linked lists
- In the case of a doubly linked circular list, the first node also needs to point to the last node.
"""
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class CircularSinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.count = 0
# make sure that the new node points back to the tail node
def append(self, data):
node = Node(data)
if self.head:
self.head.next = node
self.head = node
else:
self.tail = node
self.head = node
# only this line added, compared to append method for class SingleLinkedList
self.head.next = self.tail
self.count += 1
def delete(self, data):
current = self.tail
prev = self.tail
# this while changes, compared to 'while current:' for class SingleLinkedList
# we cannot loop until current becomes None, since that will never happen
while prev == current or prev != self.head:
if current.data == data:
if current == self.tail:
self.tail = current.next
# make sure the head points to the tail
# this line added, compared to delete method for class SingleLinkedList
self.head.next = self.tail
else:
prev.next = current.next
self.count -= 1
return
prev = current
current = current.next
def iter(self):
current = self.tail
while current:
val = current.data
current = current.next
yield val
def contains(self, data):
for node_data in self.iter():
if data == node_data:
return True
return False
words = CircularSinglyLinkedList()
words.append('egg')
words.append('ham')
words.append('spam')
words.delete('ham')
print(words.contains('ham'))
print(words.count)
# List traversal: need to put in an exit condition, otherwise program will get stuck in a loop
counter = 0
for word in words.iter():
print(word)
counter += 1
if counter > 1000:
break
| true |
0ffa31e363ce141ddc7d5a7f5526aadd74046f7d | gabrielavirna/python_data_structures_and_algorithms | /my_work/ch10_design_techniques_&_strategies/coin_counting_greedy.py | 2,416 | 4.46875 | 4 | """
Greedy algorithms
- make decisions that yield the largest benefit in the interim.
- Aim: that by making these high yielding benefit choices, the total path will lead to an overall good solution or end.
Coin-counting problem
---------------------
In some arbitrary country, we have the denominations 1 GHC, 5 GHC, and 8 GHC.
Given an amount such as 12 GHC, find the least possible number of denominations needed to provide change.
Using the greedy approach:
- pick the largest value from our denomination to divide 12 GHC -> * yields the best possible means by which we can
reduce the amount 12 GHC into lower denominations. The remainder, 4 GHC, cannot be divided by 5, so try the 1 GHC
denomination and realize that we can multiply it by 4 to obtain 4 GHC.
=> the least possible number of denominations to create 12 GHC is to get a one 8 GHC and four 1 GHC notes.
"""
# Greedy algorithm: returns the respective denominations
def basic_small_change(denominations, total_amount):
sorted_denoms = sorted(denominations, reverse=True)
no_of_denoms = []
# starts by using the largest denomination
for denom in sorted_denoms:
# the quotient
div = int(total_amount / denom)
# updated to store the remainder for further processing
total_amount = total_amount % denom
if div > 0:
no_of_denoms.append((denom, div))
return no_of_denoms
# Better greedy algorithm: returns a list of tuples that allow to investigate the better results
def optimal_small_change(denominations, total_amount):
sorted_denoms = sorted(denominations, reverse=True)
series = []
# to limit the denominations from which we find the solution
for j in range(len(sorted_denoms)):
# slicing [5, 4, 3] => [5,4,3], [4,3], [3]
term = sorted_denoms[j:]
no_of_denoms = []
local_total = total_amount
for den in term:
div = int(local_total / den)
local_total = local_total % den
if div > 0:
no_of_denoms.append((den, div))
series.append(no_of_denoms)
return series
print(basic_small_change([1, 5, 8], 12))
print(optimal_small_change([1, 5, 8], 12))
# algorithm fails: doesn't give the optimal solution
print(basic_small_change([1, 5, 8], 14))
# The right optimal solution: two 5 GHC and two 1 GHC denominations
print(optimal_small_change([1, 5, 8], 14))
| true |
da4dd699a4259d0df6e34bb1f2edc256b504b1da | aadyajha12/Covid19-SmartAlarm | /CA3/time_conversion.py | 965 | 4.21875 | 4 | from datetime import datetime
def minutes_to_seconds(minutes) -> int:
"""Converts minutes to seconds"""
return int(minutes) * 60
def hours_to_minutes(hours) -> int:
"""Converts hours to minutes"""
return int(hours) * 60
def hhmm_to_seconds(hhmm: str):
if len(hhmm.split(':')) != 2:
print('Incorrect format. Argument must be formatted as HH:MM')
return None
return minutes_to_seconds(hours_to_minutes(hhmm.split(':')[0])) + \
minutes_to_seconds(hhmm.split(':')[1])
def hhmmss_to_seconds(hhmmss: str):
if len(hhmmss.split(':')) != 3:
print('Incorrect format. Argument must be formatted as HH:MM:SS')
return None
else:
return minutes_to_seconds(hours_to_minutes(hhmmss.split(':')[0])) + \
minutes_to_seconds(hhmmss.split(':')[1]) + int(hhmmss.split(':')[2])
def time_now():
now = datetime.now()
current_time = now.strftime("%H:%M")
return current_time | false |
912d8a64e49846144609746390f49caba462873c | zhangler1/leetcodepractice | /树与图/Trie Tree/Implement Trie (Prefix Tree)208.py | 1,552 | 4.125 | 4 | class TrieNode:
def __init__(self):
"""
Initialize your Node data structure here.
"""
self.children=[None]*26
self.endcount=0
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.head=TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node=self.head
for ch in word:
if node.children[ord(ch)-ord("a")] is None: # if none
node.children[ord(ch)-ord("a")]=TrieNode()
node=node.children[ord(ch)-ord("a")]
node.endcount+=1
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
node=self.head
for ch in word:
if node.children[ord(ch)-ord("a")] is not None:
node=node.children[ord(ch)-ord("a")]
else:
return False
return bool(node.endcount)
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
node=self.head
for ch in prefix:
if node.children[ord(ch)-ord("a")] is not None:
node=node.children[ord(ch)-ord("a")]
else:
return False
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
| true |
55d07ac39edf980053d80525264424d8eaf416fc | mokrunka/Classes-and-Objects | /countcapitalconsonants.py | 992 | 4.375 | 4 | #Write a function called count_capital_consonants. This
#function should take as input a string, and return as output
#a single integer. The number the function returns should be
#the count of characters from the string that were capital
#consonants. For this problem, consider Y a consonant.
#
#For example:
#
# count_capital_consonants("Georgia Tech") -> 2
# count_capital_consonants("GEORGIA TECH") -> 6
# count_capital_consonants("gEOrgIA tEch") -> 0
def count_capital_consonants(string):
cap_cons = 0
for char in string:
if char.istitle() and char not in ['A', 'E', 'I', 'O', 'U']:
cap_cons += 1
else:
pass
return cap_cons
#The lines below will test your code. Feel free to modify
#them. If your code is working properly, these will print
#the same output as shown above in the examples.
print(count_capital_consonants("Georgia Tech"))
print(count_capital_consonants("GEORGIA TECH"))
print(count_capital_consonants("gEOrgIA tEch"))
| true |
de8d4a940fb3c2098f2e4b6ff689f5a1a69e749f | mushamajay/PythonAssignments | /question8.py | 345 | 4.21875 | 4 | def maximum(numOne, numTwo):
if numOne>numTwo:
return numOne;
else:
return numTwo;
numOne = float(input("Enter your first number: "))
numTwo = float(input("Enter your second number: "))
print("You entered: {} {} " .format(numOne,numTwo))
print("The larger of the two numbers is: {} " .format(maximum(numOne,numTwo)))
| true |
50384a3fafcc828dcd563081d8c458c4965d523b | IgorToro/mi_primer_proyecto | /comer_helado.py | 1,587 | 4.21875 | 4 | apetece_helado_input = input("¿Te apetece un helado? (Si / No):").upper()
if apetece_helado_input == "SI":
apetece_helado = True
elif apetece_helado_input == "NO":
apetece_helado = False
else:
print("Te he dicho que digas Si o No, no se que me has dicho, cuento como que no quieres un helado")
apetece_helado = False
tienes_dinero_input = input("¿Tienes dinero? (Si / No):").upper()
if tienes_dinero_input == "SI":
tienes_dinero = True
elif tienes_dinero_input == "NO":
tienes_dinero = False
else:
print("Te he dicho que digas Si o No, no se que me has dicho, cuento como que no tienes dinero")
tienes_dinero = False
senor_helados_input = input("¿Esta el heladero? (Si / No):").upper()
if senor_helados_input == "SI":
senor_helados = True
elif senor_helados_input == "NO":
senor_helados = False
else:
print("Te he dicho que digas Si o No, no se que me has dicho, cuento como que no esta el heladero")
senor_helados = False
tu_tia_input = input("¿Esta tu tia? (Si / No):").upper()
if tu_tia_input == "SI":
tu_tia = True
elif tu_tia_input == "NO":
tu_tia = False
else:
print("Te he dicho que digas Si o No, no se que me has dicho, cuento como que no esta tu tia")
tu_tia = False
apetece_helado = apetece_helado_input == "SI"
tienes_dinero = tienes_dinero_input == "SI"
senor_helados = senor_helados_input == "SI"
tu_tia = tu_tia_input == "SI"
puede_permitirselo = tienes_dinero or tu_tia
if apetece_helado and puede_permitirselo and senor_helados:
print("Pues comete un helado")
else:
print("Pues nada")
| false |
aa27be886488997a3f89d12ca493d0b1162360fa | mary-tano/python-programming | /python_for_kids/book/Projects/fenster8.py | 945 | 4.21875 | 4 | # Разметка окна
from tkinter import *
class Window() :
# Инициализация
def __init__(self, Titel) :
self.Window = Tk()
self.Window.title(Titel)
self.Window.config(width=260, height=120)
self.Display = Label(self.Window, text="Как это сделать?")
self.Display.place(x=50, y=20, width=160, height=30)
self.Button1 = Button(self.Window, text="Хорошо", \
command=self.button1Click)
self.Button2 = Button(self.Window, text="Плохо", \
command=self.button2Click)
self.Button1.place(x=20, y=70, width=100, height=30)
self.Button2.place(x=140, y=70, width=100, height=30)
self.Window.mainloop()
# Метод
def button1Click(self) :
self.Display.config(text="Это радует!")
def button2Click(self) :
self.Display.config(text="Это огорчает!")
# Основная программа
Window = Window("Привет")
| false |
18a6899c57c124e3763853d806b282f1dacfab8c | Elena-Yasch/GB_Python_Homework | /task1.py | 465 | 4.125 | 4 | #1. Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел
# и строк и сохраните в переменные, выведите на экран.
name = input('Enter your first name:\n')
print(name)
last_name = input('Enter your last name:\n')
print(last_name)
age = int(input('Enter your age:\n'))
print(age)
| false |
7924ab943291d81d40280a3e46e35b0fbcaffda3 | anayatzirojas/lesson6python | /lesson6/problem3/problem3.py | 483 | 4.15625 | 4 | name = input ('What is your name?')
print ('Hi' + name + ','' ' 'my name is Girlfriend Bot!''<3')
mood = input ('How was your day, Lover?')
print ('Hmm I am looking up the meaning of' + mood +' ' 'just one minute.')
press= input ('I have a surprise for you. Click the screen and type okay.')
print ('HACKED! VIRUSES IS INSTALLED NOW!')
name = input ('What is your name?')
print ('Hi' + name + ','' ' 'my name is HATEBOT!''</3')
print ('I HATE YOU' + name.upper() + ' ' 'GET OUT OF MY LIFE!') | true |
e98f404d2cdb6b1a7cbc0f6172da400fdb305ca2 | renankemiya/exercicios | /2.Estrutura_De_Decisão_wiki.Python/estrutura_de_decisão_5.py | 913 | 4.21875 | 4 | # Faça um programa para a leitura de duas notas parciais de um aluno.
# O programa deve calcular a média alcançada por aluno e apresentar:
# A mensagem "Aprovado", se a média alcançada for maior ou igual a sete;
# A mensagem "Reprovado", se a média for menor do que sete;
# A mensagem "Aprovado com Distinção", se a média for igual a dez.
nota_1 = float(input('Insira a nota: '))
nota_2 = float(input('Insira outro número: '))
media = (nota_1 + nota_2) / 2
if media == 10:
print('Aprovado com Distinção')
elif media >= 7:
print('Aprovado')
elif media < 7:
print('Reprovado')
# Correção da internet
nota1 = input("digite sua primeira nota ---> ")
nota2 = input("digite sua segunda nota ---> ")
media = (float(nota1) + float(nota2)) / 2
if media >= 7.0:
if media == 10.0:
print("Aprovado con distincao!")
else:
print("Aprovado")
else:
print("Reprovado")
| false |
67f0a9da8deef35de2945f9810b7faf7dbd50018 | renankemiya/exercicios | /2.Estrutura_De_Decisão_wiki.Python/estrutura_de_decisão_15.py | 1,774 | 4.28125 | 4 | # Faça um Programa que peça os 3 lados de um triângulo. O programa deverá informar se os valores
# podem ser um triângulo. Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno.
# Dicas:
# Três lados formam um triângulo quando a soma de quaisquer dois lados for maior que o terceiro;
# Triângulo Equilátero: três lados iguais;
# Triângulo Isósceles: quaisquer dois lados iguais;
# Triângulo Escaleno: três lados diferentes;
t_lado1 = float(input('Insira um lado do triângulo: '))
t_lado2 = float(input('Insira outro lado do triângulo: '))
t_lado3 = float(input('Insira o último lado do triângulo: '))
if t_lado1 >= t_lado2 + t_lado3 or t_lado2 >= t_lado1 + t_lado3 or t_lado3 >= t_lado1 + t_lado2:
print('Os lados inseridos não podem ser um triângulo')
elif t_lado1 == t_lado2 == t_lado3:
print('Esse triângulo é um Equilátero')
elif t_lado1 == t_lado2 or t_lado1 == t_lado3 or t_lado2 == t_lado3:
print('Esse triângulo é um Isósceles')
elif t_lado1 != t_lado2 != t_lado3:
print('Esse triângulo é um Escaleno')
# Correção da internet
print("| Verifique se é um triângulo e qual seu tipo | ")
lado1 = float(input(" Digite o valor do primeiro lado: "))
lado2 = float(input(" Digite o valor do segundo lado: "))
lado3 = float(input(" Digite o valor do terceiro lado: "))
if (lado1 + lado2) > lado3:
if lado1 == lado2 and lado2 == lado3 and lado1 == lado3:
print(" Triângulo Equilátero")
elif lado1 == lado2 or lado1 == lado3 or lado2 == lado3:
print(" Triângulo Isósceles")
elif lado1 != lado2 and lado3 or lado2 != lado1 and lado3:
print(" Triângulo Escaleno")
else:
print(" Os valores informados não correspondem a um triângulo")
| false |
f364eb5a8a75807803b802aecfb0b17ee9e94724 | renankemiya/exercicios | /3.Estrutura_De_Repetição_wiki.Python/estrutura_de_repetição_1.py | 405 | 4.21875 | 4 | # Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor seja inválido e continue
# pedindo até que o usuário informe um valor válido.
nota = float(input('Insira um nota entre 0 a 10: '))
while nota < 0 or nota > 10:
print('Nota Inválida')
nota = float(input('Insira um nota entre 0 a 10: '))
if nota >= 0 or nota <= 10:
print('Nota Válida', nota)
| false |
ef1ab96d6b4dd0eb988a31bf3e15b13528e9678b | lohib/Programming--language | /hack3.py | 243 | 4.15625 | 4 | def is_leap(year):
leap=False
if year%4==0:
if year%100==0 and not year%400==0:
leap=False
else:
leap=True
return leap
year=2004
print(is_leap(year))
year=1990
print(is_leap(year))
year=1996
print(is_leap(year))
| false |
32ff4110bcd5bc8c2d1bb1455216581a0e68bc1b | oshrishaul/lesson1 | /Lesson2/Assignment_Class2/Extra2.py | 700 | 4.21875 | 4 | # # Create a nested for loop to create X shape (width is 7, length is 7):
# i=0
# j=4
# for row in range(5):
# for col in range(5):
# if row==i and col==j:
# print("*",end="")
# i=i+1
# j=j-1
# elif row==col:
# print("*",end="")
# else:
# print(end=" ")
# print()
# x=0
# y=0
# for row in range(5):
# for col in range(5):
#
# print()
# n = 5
for i in range(0, 5):
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i + 1):
# printing stars
print("* ", end="")
# ending line after each row
print("\r")
# Driver Code
| true |
69e4baa9758d9808ac6f72cfe90059b76b874da8 | standrewscollege2018/2020-year-12-python-code-JustineLeeNZ | /credit_manager.py | 2,896 | 4.40625 | 4 | """ Manage student info about L1 NCEA credits - Ms Lee. """
def display_all_students():
""" Display all students in a list. """
print("\nLIST OF STUDENTS")
for index in range(0, len(students)):
print("{}. {} Credits: {}".format(index+1, students[index][0], students[index][1] ))
# stores initial student details (note you could start with an empty list but this makes testing easier)
students = [["Justine Lee",50], ["Bryn Lewis",20], ["Meredith Lewis",10], ["Rhys Lewis",5],["Phil Adams",100],["Wilj Dekkers",3]]
#students = []
# menu will keep displaying while this variable is True
display_menu = True
# display menu until user decides to quit
while display_menu == True :
print("\n=====MENU=====")
print("1. Display all students")
print("2. Add a student")
print("3. Delete a student")
print("4. Update a student")
print("5. Quit program\n")
# get selected menu option which should be an integer
while True:
# check if integer value entered
try:
# get menu choice
choice = int(input("Please choose a menu option: "))
break
# detect integer value not entered
except:
# display error message
print("Error: invalid input - it must be an integer")
# redisplay menu so that user can see what options are
print("\n=====MENU=====")
print("1. Display all students")
print("2. Add a student")
print("3. Delete a student")
print("4. Update a student")
print("5. Quit program\n")
# display all student
if choice == 1:
display_all_students()
# add a student
elif choice == 2:
# add a student
student_name = input("Enter the name of a student: ")
student_credit_total = int(input("Enter total NCEA level 1 credits: "))
new_student = [student_name, student_credit_total]
students.append(new_student)
# delete a student
elif choice == 3:
display_all_students()
student_num = int(input("Enter number of student to delete: "))
del(students[student_num-1])
# change student details
elif choice == 4:
display_all_students()
# get details of which student to change and what the updated name is
student_num = int(input("Enter number of student to change: "))
new_name = input("Enter updated name: ")
new_total = int(input("Enter new total: "))
# change student details
students[student_num-1][0] = new_name
students[student_num-1][1] = new_total
# exit program
elif choice ==5 :
display_menu = False
# capture invalid menu option
else:
print("invalid menu choice")
print("Bye")
| true |
88627a52218cf3c4fff7d39f34f565f9f39990ee | AssafR/sandbox | /generators.py | 2,172 | 4.375 | 4 | def with_index(itr):
"""This is the same as builtin function enumerate. Don't use this except as an exercise.
I changed the name, because I don't like overriding builtin names.
Produces an iterable which returns pairs (i,x) where x is the value of the original,
and i is its index in the iteration, starting from 0.
"""
i=0
for x in itr:
yield (i,x)
i = i+1
#TODO
def fibonacci():
"""An infinite generator for the fibonacci series, where:
Fib[0] = 0
Fib[1] = 1
Fib[n+2] = Fib[n] + Fib[n+1]
"""
prev=0
curr=1
while True:
yield prev
(prev,curr) = (curr,prev+curr)
def product(*seqs):
"""Same as itertools.product - Don't use this except as an exercise.
Returns a generator for the cartesian product of all sequences given as input.
If called with N sequences, then each returned item is a list of N items - one from each sequence.
For example, product([1,2,3],'ABC',[True,False]) produces the following items:
[1,'A',True]
[1,'A',False]
[1,'B',True]
...
See my blog for discussion of this implementation:
http://www.ronnie-midnight-oil.net/2008/05/ok.html
"""
#TODO
if len(seqs)==0:
yield []
elif len(seqs)==1:
for elem in seqs[0]:
yield [elem]
else:
for elem in seqs[0]:
# print "elem=",elem,"\n"
# print "calling recurse with:",seqs[1:]
for prod in product(*seqs[1:]):
# print "returned prod=",prod,",concatente with:",elem
result = [elem] + prod
# print "returning: result=",result
yield result
#for (i,t) in with_index(range(2,8)):
# print "i=",i,"t=",t
#for i in fibonacci():
# print i
# if i>400:
# break
#lst = list(product([1,2,3],'XY'))
lst=list(product([1,2,3],'XY',[True,False],['well','now']))
#lst=list(product())
#print "lst=",lst
#product([1,2,3],'ABC',[True,False])
| true |
18f595f69bafa2de6f12e3e22e85efc24ab91d82 | knowledgeforall/Big_Data | /Big Data/arrays.py | 935 | 4.125 | 4 |
#create empty array
A = []
print("Array A: ", A)
#create a "populated" array
B = [12, 23, 56, 17, 23]
print("Array B: ", B)
#Add an element to an array
print("Before adding to A: ", A)
A.append(90)
print("After adding to A: ", A)
#access the 2nd element in array B
print("The second element in Array B is: ", B[1])
print("\nChanging the second element in B:")
print(B)
B[1] = 72
print(B)
#computing the average over all values stored in B
print("Computing the average over all elements in B:")
total=0
for i in range( 0, len(B) ):
total = total + B[i]
print("Sum = ", total)
print("Avg = ", total/len(B) )
#read some value from the user
x = int ( input("Enter a number to search for it in Array B: ") )
#sequential search of an array
found=False
for i in range(0, len(B) ):
if B[i] == x:
print(x, "found at index", i)
found = True
break
if not found:
print(x, "not found")
| true |
ae879397835b9f1a95459a6bdc70d12252a3754a | baraluga/programming_sandbox | /python/miscellaneous/binary_tree_optimizer.py | 2,117 | 4.34375 | 4 | '''
Recall that a full binary tree is one in which each node is either a leaf
node, or has two children. Given a binary tree, convert it to a full one by
removing nodes with only one child.
For example, given the following tree:
0
/ \
1 2
/ \
3 4
\ / \
5 6 7
You should convert it to:
0
/ \
5 4
/ \
6 7
'''
class BinaryTree:
def __init__(self, fruit_value: int, left_leaf=None, right_leaf=None):
self.fruit_value = fruit_value
self.left_leaf = left_leaf
self.right_leaf = right_leaf
def __str__(self):
return (
f"\n================================\n"
f"Fruit Value: {self.fruit_value}\n"
f"Left leaf: {self.left_leaf}\n"
f"Right leaf: {self.right_leaf}"
)
INPUT = BinaryTree(0,
# Left Branch
BinaryTree(1, BinaryTree(3, None, BinaryTree(5))),
# Right Branch
BinaryTree(2, None, BinaryTree(4, BinaryTree(6),
BinaryTree(7))))
def prune_dead_branches(infected_tree: BinaryTree):
# Clean up left branch
left_leaf = infected_tree.left_leaf
if left_leaf and bool(left_leaf.left_leaf) != bool(left_leaf.right_leaf):
print(f"Pruning {left_leaf.fruit_value} leaf as it only have 1 leaf")
infected_tree.left_leaf = left_leaf.left_leaf or left_leaf.right_leaf
prune_dead_branches(infected_tree)
# Clean up right branch
right_leaf = infected_tree.right_leaf
if right_leaf and bool(right_leaf.right_leaf) != \
bool(right_leaf.left_leaf):
print(f"Pruning {right_leaf.fruit_value} leaf as it only have 1 leaf")
infected_tree.right_leaf = right_leaf.right_leaf or \
right_leaf.left_leaf
prune_dead_branches(infected_tree)
return infected_tree
if __name__ == "__main__":
print("Initial tree:")
print(INPUT)
print("Pruned bitch:")
print(prune_dead_branches(INPUT))
| true |
bce7773067afd0c81466166e792751c5be04d7ec | chenlifeng283/learning_python | /7-handling conditions/code_challenge_and_solution.py | 529 | 4.40625 | 4 | # Fix the mistakes in this code and test based on the description below
# if I enter 2.00 I should see the message "The tax rate is: 0.07"
# if I enter 1.00 I should see the message "The tax rate is :0.07"
# if I enter 0.5 I should see the message "The tax rate is: 0"
price = input('How much did you pay?')
price = float(price) # Converting the string to a mumber
if price >= 1.00:
tax = 0.07
print('The tax rate is:' + str(tax))
else: # Do not forget the ':'
tax = 0
print('The tax rate is:' +str(tax))
| true |
0e123b02dca275d099869084f1ed52a9a18d571c | chenlifeng283/learning_python | /1-print/ask_for_input.py | 244 | 4.28125 | 4 | #The input function allows you to prompy the user for a value
#You need to declare a variable to hold the value entered by the user
name=input("What's your name?") #if string has single quotes,it must be enclosed in double quotes.
print(name)
| true |
84594d387e3c44e7e3cd50cf6e33b210e27a865a | BenDataAnalyst/Practice-Coding-Questions | /leetcode/67-Easy-Add-Binary/answer.py | 618 | 4.21875 | 4 | #!/usr/bin/env python
#-------------------------------------------------------------------------------
# Cheaty Python way :)
# Other way would be to add each digit bit by bit, and having a carry bit when > 1
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
# Sum the two by converting to int
sum = int(a,2)+int(b,2)
# Convert back to binary and return excluding the leading '0b'
return(bin(sum)[2:])
#-------------------------------------------------------------------------------
# Testing
| true |
615668717c061bcdcfcc4c3f7dbe4130aeb6401b | JHHXYZ/DSCS2020 | /Assignments/Assignment 2/part3.py | 2,574 | 4.5625 | 5 | # building a ml model with sklearn
import numpy as np
import pandas as pd
"""
1. Load your data from part 2
Create two lists. One should contain the name of the features (i.e. the input
variables) you want to use to train your model, the other should contain the
column name of the labels
"""
# your code
"""
2. Divide your column into a training and testing set like we did in class. The
fraction of the training size should be somewhere between 70 and 80 percent.
Before you split the dataframe, make sure to shuffle the row order.
"""
# your code
"""
3. The sklearn actually has a function for this called 'train_test_split'. Redo
the split by using the function. Note that it will require you to feed in model
variables and labels separately.
"""
# your code
"""
4. Using the Create a multiple linear regression model using sklearn package.
Create predictions for your test set that you generated in the previous step
Linear regression model:
https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html
"""
# your code
"""
5. In class we simply used the accuracy as a measure of quality for our model. In
this case this won't work as we are not making categorical predictions, but
numerical ones instead.
Therefore we want to calculate the so-called mean squared error (MSE). We do
this as follows:
mse = average of all rows for ((model_predictions - labels)^2)
Calculate the mean squared error for our model predictions. In a second step,
compare this with a "model" that would have just predicted all rows to be the
average of the 'quality' column in the training data. Which MSE error is lower?
(a lower value is generally better)
Detailed formula in case the one above isn't clear:
https://www.statisticshowto.com/mean-squared-error/
Short explanation of why we use the MSE can be found here:
https://peltarion.com/knowledge-center/documentation/modeling-view/build-an-ai-model/loss-functions/mean-squared-error
Longer explanation:
https://stats.stackexchange.com/questions/127598/square-things-in-statistics-generalized-rationale/128619
"""
# your code
"""
6. Sometimes, when we've created a model we want to save it as a file so that we
can just load it into another file at another point.
Save your regression model to your local folder. Test whether it worked
by re-loading the model as a new instance and make some predictions (e.g. again
on the test dataset)
Hint: have a look at this link
https://machinelearningmastery.com/save-load-machine-learning-models-python-scikit-learn/
"""
# your code
#
| true |
0bb19fcdb98d6c46c174347921246fe25cf69777 | BillyRockz/Magic-8-Ball | /main.py | 1,215 | 4.125 | 4 | '''This is a game of 8-Ball where you can ask Yes/No Questions and get answers'''
alpha = True
while alpha == True:
name = input("What is your name?: ")
if name.isalpha() and name.strip():
alpha = False
beta = True
while beta == True:
question = input("Ask a (Yes/No) question: ")
beta = False
else:
print("Your name has to be all letters and contain no spaces.")
answer = ""
import random
random_number = random.randint(1,9)
if random_number == 1:
answer = "Magic 8-Ball says: Yes - definitely."
elif random_number == 2:
answer = "Magic 8-Ball says: It is decidedly so"
elif random_number == 3:
answer = "Magic 8-Ball says: Without a doubt."
elif random_number == 4:
answer = "Magic 8-Ball says: Reply hazy, try again."
elif random_number == 5:
answer = "Magic 8-Ball says: Ask again later."
elif random_number == 6:
answer = "Magic 8-Ball says: Better not tell you now."
elif random_number == 7:
answer = "Magic 8-Ball says: My sources say no."
elif random_number == 8:
answer = "Magic 8-Ball says: Outlook not so good."
elif random_number == 9:
answer = "Magic 8-Ball says: Very doubtful."
else:
answer = "Error"
print(name + " asks: " + question)
print(answer)
| true |
6a8130d24de307de61d263b0bdc358a602cfd985 | khelryst/Learning-Python | /gradechecker.py | 444 | 4.21875 | 4 | grade = input('Enter your grade: ')
try:
grade = float(grade)
except:
grade = input('Enter a number from 0.0 - 1.0: ')
if float(grade) >= 0.9:
grade = 'A'
elif float(grade) >=0.8:
grade = 'B'
elif float(grade) >= 0.7:
grade = 'C'
elif float(grade) >= 0.6:
grade = 'D'
elif float(grade) < 0.6:
grade = 'F'
else:
grade = input('Enter a number from 0.0 - 1.0: ')
print(grade)
input('Press Enter to Continue...') | false |
0e89f43161009efc79d682584518c8cce89196d6 | ngovanuc/UDA_NMLT_Python_chapter06 | /page_203_project_03.py | 925 | 4.3125 | 4 | """
author : Ngô Văn Úc
date: 30/08/2021
program: 3. Elena complains that the recursive newton function in Project 2 includes an extra
argument for the estimate. The function’s users should not have to provide this
value, which is always the same, when they call this function. Modify the definition
of the function so that it uses a keyword argument with the appropriate
default value, and call the function without a second argument to demonstrate
that it solves this problem.
solution:
...
"""
def newton(number, estimate = 1.0):
tolerance = 0.0000000001
difference = abs(number - estimate ** 2)
if difference <= tolerance:
return estimate
else:
return newton(number, (estimate + number/estimate)/2)
print("enter 'quit' to exit")
while True:
number = input("enter a number: ")
if not number.isnumeric():
break
print(newton(float(number)))
| true |
0c99a8c25c99644fbaddb94b22a7146aad09b854 | ngovanuc/UDA_NMLT_Python_chapter06 | /page_199_exercise_03.py | 477 | 4.3125 | 4 | """
author : Ngô Văn Úc
date: 30/08/2021
program: 2. Write the code for a filtering that generates a list of the positive numbers in a list
named numbers. You should use a lambda to create the auxiliary function.
solution:
- sử dụng bộ loc filter
"""
word = ["a", "hello", "Uc", "handsome", "b", "c", "d"]
def length(aword):
if len(aword) == 1: return True
else: return False
lilterword = filter(lambda x: length(x), word)
print(list(lilterword)) | true |
cb9ad2b4f192f67206af6f565a7cb50a36b13f40 | jjena560/Data-Structures | /strings/strings.py | 656 | 4.15625 | 4 | def createStack():
stack = []
return stack
def push(stack, item):
stack.append(item)
def pop(stack):
return stack.pop()
def reverse(string):
n = len(string)
try:
stack = createStack()
for i in range(n):
push(stack, string[i])
string = ""
for i in range(n):
string += pop(stack)
print(string)
except IOError:
print("invalid input")
string = input("enter the string you want to reverse: ")
print("string before getting reversed: ", end="")
print(string)
print("string after getting reversed: ", end="")
print(reverse(string))
| true |
61813e43dbfb6c4be84104f9e042207ef3beeb2e | sohitmiglani/Applications-in-Python | /Max Heaps.py | 931 | 4.125 | 4 | # This is the algorithm for building and working with heaps, which is a tree-based data structure.
# It allows us to build a heap from a given list, extract certain element, add and remove them.
def max_heapify(A, i):
left = 2 * i + 1
right = 2 * i + 2
largest = i
if left < len(A) and A[left] > A[largest]:
largest = left
if right < len(A) and A[right] > A[largest]:
largest = right
if largest != i:
A[i], A[largest] = A[largest], A[i]
max_heapify(A, largest)
def build_max_heap(A):
for i in range(len(A) // 2, -1, -1):
max_heapify(A, i)
def heap_extract_max(list):
build_max_heap(list)
max = list[0]
list = list[1:]
build_max_heap(list)
return max, list
def max_heap_push(list,x):
list.append(x)
build_max_heap(list)
return list
def max_heap_pop(list):
list.remove(min(list))
build_max_heap(list)
return list
| true |
a1e1308263ba36420c3b7095ae682addf3898b33 | sohitmiglani/Applications-in-Python | /Hash Tables.py | 1,391 | 4.40625 | 4 | # This is an algorithm to produce hash tables and implement hashing functions for efficient data storage and retrieval.
# It also has 4 examples of hashing functions that can be used to store strings.
import random
import string
def randomword(length):
return ''.join(random.choice(string.lowercase) for i in range(length))
def empty_hash_table(N):
return [[] for n in range(N)]
def add_to_hash_table(hash_table, item, hash_function):
N = len(hash_table)
hash_table[hash_function(item)] = str(item)
return hash_table
def contains(hash_table, item, hash_function):
N = len(hash_table)
if hash_table[hash_function(item)] == item:
return True
else:
return False
# return true if the item has already been stored in the hash_table
def remove(hash_table, item, hash_function):
if not contains(hash_table, item, hash_function):
raise ValueError()
else:
hash_table.remove(item)
return hash_table
def hash_str1(string):
ans = 0
for chr in string:
ans += ord(chr)
return ans
def hash_str2(string):
ans = 0
for chr in string:
ans = ans ^ ord(chr)
return ans
def hash_str3(string):
ans = 0
for chr in string:
ans = ans * 128 + ord(chr)
return ans
def hash_str4(string):
random.seed(ord(string[0]))
return random.getrandbits(32)
| true |
fab8ea8638fbb524c1b423a6aac64cca4e692cbd | nzrfrz/praxis-academy | /novice/01-02/list_comprehension.py | 1,529 | 4.28125 | 4 | from math import pi
print("using math lib to calculate pi: ")
print(
[str(round(pi, i)) for i in range(1, 6)]
)
print("")
# Create a list of squares
squares = []
for x in range(10):
squares.append(x ** 2)
# Creates or overwrite 'x' after loop
squares = list(map(lambda x: x ** 2, range(10)))
# Simple version of code above is below :
squares = [x ** 2 for x in range(10)]
print(squares)
print("")
# Combine 2 lists if they are not equal
print(
[(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
)
# Code above is equal to nested loop below
combs = []
for x in [1, 2, 3]:
for y in [3, 1, 4]:
if x != y:
combs.append((x, y))
print(combs)
print("")
# List comprehension contain complex expressions
# and nested functions
vec = [-4, -2, 0, 2, 4]
print("create a new list with the values doubled: ")
print(
[x * 2 for x in vec]
)
print("")
print("filter the list to exclude negative numbers: ")
print(
[x for x in vec if x >= 0]
)
print("")
print("apply a function to all the elements: ")
print(
[abs(x) for x in vec]
)
print("")
print("call a method on each element: ")
freshfruit = [' banana', ' loganberry ', 'passion fruit ']
print(
[weapon.strip() for weapon in freshfruit]
)
print("")
print("create a list of 2-tuples like (number, square): ")
print(
[(x, x**2) for x in range(6)]
)
print("")
print("flatten a list using a listcomp with two 'for': ")
vec2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(
[num for elem in vec2 for num in elem]
)
| true |
c41456a23f31788093696b4433813bc63d57b5d4 | Devanshiq/Python-Programs | /rectangle.py | 1,460 | 4.1875 | 4 | # class rectangle():
# pass
#
#
# r1=rectangle()
# r2=rectangle()
#
#
# r1.height=40
# r1.width=60
#
# r2.height=60
# r2.width=30
#
# print(r1.height*r1.width)
# print(r2.height*r2.width)
# class rectangle():
# def __init__(self,height,width):
# print(height*width)
# self.height=height
#
# print("The __init__ method is called ")
#
# r1=rectangle(40,60)
# r2=rectangle(50,30)
#
# print(r1.height)
# print(r2.height)
# class rectangle():
# def __init__(self,*args,**kwargs):
# self.name="daanshi"
# self.age=10
# r1=rectangle()
#
# class rectangle():
# def __init__(self,name):
# self.a=10
# self._b=20
# self.__c=30
#
# r1=rectangle('name')
# print(r1.a)
# print(r1._b)
# print(r1.__c) #private as double underscores are there
class rectangle():
def __init__(self,height,width):
self.__height=height
self.__width=width
def set_height(self,value):
self.__height=value
def get_height(self):
return self.__height
def set_width(self, value):
self.__width = value
def get_width(self):
return self.__width
def get_area(self):
return self.__height*self.__width
r1=rectangle(40,30)
r2=rectangle(60,50)
print(r1.get_height())
print("Area of the rectangle r1 is ",r1.get_height()*r1.get_width())
print(r2.get_area())
| false |
23083506114f10882ec02b046f74a4fe502d042f | Devanshiq/Python-Programs | /car.py | 2,450 | 4.125 | 4 | # class car:
# pass
#
# ford=car()
# honda=car()
# audi=car()
# ford.speed=200
# honda.speed=400
# audi.speed=100
# ford.color='black'
# honda.color='blue'
# audi.colour='maroon'
# print(ford.speed)
# print(audi.colour)
# print(honda.color)
# class car():
# def __init__(self,speed,color):
# print(speed)
# print(color)
# self.speed=speed
# self.color=color # assignment of attribute to self object(deoting current object)
# print("The __init__ is called")
#
# ford=car(47,"blut") #creating objects
# honda=car(50,"black")
# audi=car(90,"brown")
#
# print(ford.speed)
# print(audi.color)
#
# class car():
# def __init__(self,speed,color):
# self.__speed=speed
# self.__color=color
# def set_speed(self,value):
# self.__speed=value
# def get_speed(self):
# return self.__speed
#
# def set_color(self, value):
# self.__color = value
#
# def get_color(self):
# return self.__color
#
# ford=car(47,"blut") #creating objects
# honda=car(50,"black")
# audi=car(90,"brown")
#
# ford.__color="magenta"
# #ford.set_speed(500)
# ford.__speed=200
#
# print(ford.get_speed())
# print(ford.get_color())
#OPERATOR OVERLOADING
import math
class circle:
def __init__(self,radius):
self.__radius=radius
def get_radius(self):
return self.__radius
def area(self):
return math.pi*self.__radius**2
def __add__(self, circle_object):
return (self.__radius+circle_object.__radius)
def __mul__(self, c_obj):
return (self.__radius*c_obj.__radius)
def __lt__(self, c_obj): #less than
return (self.__radius<c_obj.__radius)
def __gt__(self, c_obj): #greater than
return (self.__radius>c_obj.__radius)
def __str__(self):
return "circle area = "+ str(self.area())
c1=circle(3)
c2=circle(2)
#c3=circle()
#print(c1)
#print(c2)
print(c1.get_radius())
print(c2.get_radius())
c3=c1+c2
print(c3)
#print(c3.get_radius()) # WHY SHOWING ERROR #for this you have to write return circle(self.radius+circle_object) in the overloaded addition method
c4=c1*c2*c3
print(c4)
print(c1>c2) #greater than
print(c1<c2) #less than
print(str(c1))
print(dir(c1)) #to implement the functions | true |
f093c70bedeaf48c1a139c49a2252224b515d27c | ziGFriedman/My_programs | /Single_double_positive_negative_digit.py | 658 | 4.28125 | 4 | '''Какое число: однозначное или двухзначное, положительное или отрицательное?'''
def digit(n):
if n == 0:
print('Ноль - однозначное число')
else:
if n > 0:
print('Положительное', end=' ')
else:
print('Отрицательное', end=' ')
if abs(n) < 10:
print("однозначное число")
elif (10 <= abs(n) < 100):
print('двузначное число')
else:
print('трехзначное или более число')
digit(378)
| false |
52258bb913b812c121a1eb90466fd018ac6fb643 | ziGFriedman/My_programs | /Area_and_perimeter_of_a_right_triangle.py | 1,267 | 4.71875 | 5 | '''Найти площадь и периметр прямоугольного треугольника'''
# Найти площадь и периметр прямоугольного треугольника по двум заданным катетам.
# Площадь прямоугольного треугольника равна половине площади прямоугольника, стороны которого равны
# длинам катетов.
# Периметр находится путем сложения длин всех сторон треугольника. Поскольку известны только катеты,
# гипотенуза вычисляется по теореме Пифагора:
# c2 = a2 + b2
# Чтобы извлечь квадратный корень в Python, можно воспользоваться функцией sqrt() из модуля math.
import math
AB = float(input("Длина первого катета: "))
AC = float(input("Длина второго катета: "))
BC = math.sqrt(AB ** 2 + AC ** 2)
S = (AB * AC) / 2
P = AB + AC + BC
print("Площадь треугольника: {0:.2f}".format(S))
print("Периметр треугольника: {0:.2f}".format(P))
| false |
35a77aa042a95f8f956fc013e68efc9d3f1da89c | 656021898/python_project | /homework/homework_1018/User.py | 1,009 | 4.375 | 4 | # 1:创建一个名为 User 的类:
# 1)其中包含属性 first_name 和 last_name,还有用户简介通常会存储的其他几个属性,均是自定义, 请放在初始化函数里面。
# 2)在类 User 中定义一个名为 describe_user()的方法,它打印用户信息摘要;
# 3)再定义一个名为 greet_user()的方法,它向用户发出个性化的问候。:
# 请创建多个表示不同用户的实例,并对每个实例都调用上述两个方法。
class User:
def __init__(self,first_name,last_name,sex="男",age=25):
self.first_name = first_name
self.last_name = last_name
self.sex = sex
self.age = age
def describe_user(self):
print("姓名:{0}·{1}".format(self.last_name,self.first_name))
print("性别:{0}".format(self.sex))
print("年龄:{0}".format(self.age))
def greet_user(self):
print("hello,{0}·{1},欢迎你来到柠檬班!".format(self.last_name,self.first_name))
| false |
06413d33de4cb40afd3c7109cf3baf084693b74a | korn13r/RTR105 | /dgr_20181015.py | 1,222 | 4.28125 | 4 | # Conditional steps
x = 5
if x < 10:
print('Smaller')
if x > 20:
print('Bigger')
print ('Finish')
# Comparison operators
x = 5
if x == 5:
print('Equals 5')
if x > 4:
print('Greater than or Equals 5')
if x < 6:
print('Less than or Equals 5')
if x != 6:
print('Not Equals 6')
# one way decisions
x = 5
print('Before 5')
if x == 5:
print('Is 5')
print('Is Still 5')
print('Third 5')
print('Afterwards 5')
print('Before 6')
if x == 6:
print('Is 6')
print('Is Still 6')
print('Third 6')
print('Afterwards 6')
x = 5
if x > 2:
print('Bigger than 2')
print('Still bigger')
print('Done with 2')
x = 5
if x > 2:
print('Bigger than 2')
print('Still bigger')
print('Done with 2')
for i in range(5):
print(i)
if i > 2:
print('Bigger than 2')
print('Done with i',i)
print('All Done')
# Nested decisions
x = 42
if x > 1:
print('More than one')
if x < 100:
print('Less than 100')
print('All Done')
# two way decisions with 'else'
x = 4
if x > 2:
print('Bigger')
else:
print('Smaller')
print('All done')
# Multi-way
x = 0
if x < 2:
print('small')
elif x < 10:
print('Medium')
else:
print('LARGE')
print('All done')
| false |
75df350c68c6ff04cf879d80be5d97f2a75f48f0 | byn3/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 575 | 4.21875 | 4 | #!/usr/bin/python3
""" this is my add_integer module """
def add_integer(a, b=98):
"""Function that returns the addition of a + b
Args:
a: should be an int. if not throw error
b: second int. if not throw error. default val is 98.
Returns:
The addition of a + b or a raised TypeError
"""
if type(a) is int or type(a) is float:
if type(b) is int or type(b) is float:
return int(a + b)
else:
raise TypeError("b must be an integer")
else:
raise TypeError("a must be an integer")
| true |
0e6ca5815e21b5a3d5225dc2934d1ba0f390708e | ag-ds-bubble/projEuler | /solutions/solution6.py | 821 | 4.125 | 4 | """
Author : Achintya Gupta
Date Created : 22-09-2020
"""
"""
Problem Statement
------------------------------------------------
Q) The sum of the squares of the first ten natural numbers is, 385
The square of the sum of the first ten natural numbers is, 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is . 2640
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
"""
from utils import timing_decorator, find_factors
import numpy as np
@timing_decorator
def find_min_prod(N=100):
prod = ((N)*(N+1))/2
prod *= (3*(N**2) - N -2)/6
print(f'Difference between the sum of the squares of the first {N} natural numbers and the square of the sum: {prod}')
find_min_prod()
| true |
e81ed59d35f3094800cf2c92ad860dfa50fd3dbd | ag-ds-bubble/projEuler | /solutions/solution4.py | 924 | 4.1875 | 4 | """
Author : Achintya Gupta
Date Created : 22-09-2020
"""
"""
Problem Statement
------------------------------------------------
Q) 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.
"""
from utils import timing_decorator, check_palindrome
import numpy as np
@timing_decorator
def find_Lpal(N=3):
maxN = 10**N-1
minN = 10**(N-1)
max_product = 0
palin_list = []
for i in reversed(range(minN,maxN+1)):
for j in reversed(range(minN,maxN+1)):
prod = i*j
if prod<max_product:
break
if check_palindrome(prod) and prod > max_product:
palin_list.append(prod)
max_product = prod
print(f'Largest palindrome : {max(palin_list)}')
find_Lpal(3)
| true |
99a4a4fd4f46f677d72f1a41c11fa89d404f9497 | arkaris/gb_python_basic | /lesson1/task1.py | 368 | 4.1875 | 4 | user_input = input('Введите 3-значное число: ')
numbers = map(int, user_input)
numbers_sum = 0;
for number in numbers:
numbers_sum += number
print("Сумма цифр:", numbers_sum)
numbers_mul = 1;
for number in numbers:
numbers_mul *= number
print("Произведение цифр:", numbers_mul)
input('Работа завершена.') | true |
29ede9877a7ecd003c6320b86aa65c0a5a19dfd9 | BillyCussen/CodingPractice | /Python/Data Structures & Algorithms Module - Python/Revision/SearchAndSortAlgorithms/BubbleSort1.py | 296 | 4.125 | 4 | """
BubbleSort1.py
Billy Cussen
09/02/2021
"""
def bubbleSort(list):
for i in range(len(list)):
for j in range(len(list)-1):
if list[j] > list[j+1]:
list[j], list[j+1] = list[j+1], list[j]
myList = [10,8,4,2,6]
bubbleSort(myList)
for i in myList:
print(i) | false |
5d8b1ceb96d3447722a3bafccb880d1809b8be49 | BillyCussen/CodingPractice | /Python/Data Structures & Algorithms Module - Python/Revision/SearchAndSortAlgorithms/BubbleSort.py | 310 | 4.125 | 4 | """
BubbleSort.py
Billy Cussen
09/02/2021
"""
def bubbleSortArray(arr):
for i in range (len(arr)):
for j in range (len(arr)-1):
if(arr[j]>arr[j+1]):
arr[j], arr[j+1] = arr[j+1], arr[j]
arr1 = [5,4,2,3,1]
bubbleSortArray(arr1)
for i in range(len(arr1)):
print(arr1[i]) | false |
6f2b7477d373945c06ebb7adccb9ff8b5489e841 | BillyCussen/CodingPractice | /Python/Data Structures & Algorithms Module - Python/Week7/Factorial.py | 358 | 4.125 | 4 | """
Factorial.py
Billy Cussen
17/11/2020
"""
def factorial(num):
res = num
while num != 1:
num-=1
res*=num
return res
def factorialRecursion(num):
if num == 1 or num == 0:
return num
return num * factorialRecursion(num-1)
print("Factorial: "+str(factorial(5)))
print("Factorial Recursion: "+str(factorialRecursion(5))) | false |
acc7a33673cb8edc553e7ab7337c425259c187a5 | mmayes3/Projects | /Tree-Node/Tree-node.py | 1,289 | 4.25 | 4 | class TreeNode(object):
def __init__(self, value):
self.value = value
self.left = None
self.middle = None
self.right = None
def insert_node(self, new_value):
if new_value < self.value:
if self.left == None:
self.left = TreeNode(new_value)
else:
self.left.insert_node(new_value)
elif new_value == self.value:
if self.middle == None:
self.middle = TreeNode(new_value)
else:
self.middle.insert_node(new_value)
else: # case when new_value > self.value:
if self.right == None:
self.right = TreeNode(new_value)
else:
self.right.insert_node(new_value)
def traverse_LMRW(self):
if self.left != None:
self.left.traverse_LMRW()
if self.middle != None:
self.middle.traverse_LMRW()
if self.right != None:
self.right.traverse_LMRW()
print(self.value)
def ternary_tree(L):
T = TreeNode(L[0])
for value in L[1:]:
T.insert_node(value)
return T
def main():
T = ternary_tree([4, 1, 2, 2, 3, 1, 0, 4, 6, 5, 6, 4])
print("ternary tree")
T.traverse_LMRW()
main()
| false |
d607dcb8b0da5dcbf7e7cded267b4c58ff70cb7e | coder562/python | /83-exercise 18.py | 271 | 4.1875 | 4 | # define a function that takes a number(n)
# return a dictionary containing cube of numbers from 1 to n
# example
# cube_finder(3)
# {1:1,2:8,3:27}
def cube_finder(n):
cubes={}
for i in range(1,n+1):
cubes[i]=i**3
return cubes
print(cube_finder(10)) | true |
fef7dce0af13470cf2e11f12163e5d14624a5f1a | coder562/python | /74-more about tuples.py | 827 | 4.5 | 4 | #looping in tuple
# tuple with one element
# tuple without parenthesis
# tuple unpacking
# list inside tuple
# some functions that you can use with tuples
mixed=(1,2,3,4.5)
# for loop and tuple
# for i in mixed:
# print(i)
#we can use while loop too
# tuple with one element
nums=(1,) #, is important as python detects tuple by comma
words=('word1',)
print(type(nums))
print(type(words))
# tuple without parenthesis
guitars='yamaha','baton rouge','taylor'
print(type(guitars))
# tuple unpacking
guitarists = ('maneli','jjjhhshhs','jjsjhshh')
guitarist1,guitarist2,guitarist3=(guitarists)
print(guitarist1)
# list inside tuple
favourites =('mangolia',['ujjhhh','kjjjhh'])
favourites[1].pop()
favourites[1].append("we made it")
print(favourites)
# min(),max(),sum
print(min(mixed))
print(max(mixed))
print(sum(mixed))
| true |
b61f899f7e22db47f9793d4f8e4d2f4750f6e729 | coder562/python | /65-more about lists.py | 547 | 4.21875 | 4 | #generate lists with range function
# something more about pop method
# index method
# pass list to a function
# numbers = list(range(1,10))
numbers=[1,2,3,4,5,6,7,8,9,10,1]
# print(numbers)
# print(numbers.pop()) #pop returns the value popped
# print(numbers)
# print(numbers.index(1)) #by defalut search from 0th position
print(numbers.index(1,3,14)) #3-start from 3rd position and search 1 14-stop argument
def negative_list(l):
negative=[]
for i in l:
negative.append(-i)
return negative
print(negative_list(numbers))
| true |
d75bc9a6e32a78551ff8eae7e4bb75adb2226659 | coder562/python | /88-list comprehenstion.py | 734 | 4.21875 | 4 | #list compreshension
# with the help of list comprehension we can create of list in one line
#create a list of squares from 1 to 10
# squares=[]
# for i in range(1,11):
# squares.append(i**2)
# print(squares)
#by using list comprehension
# square2=[i**2 for i in range(1,11)]
# print(square2)
# cretate list of negative numbers
# negative=[]
# for i in range(1,11):
# negative.append(-i)
# print(negative)
#by list comprehension
# new_negative = [-i for i in range(1,11)]
# print(new_negative)
names = ['vaishali','rohit','mogit']
# new_list=['v','r','m']
# new_list=[]
# for name in names:
# new_list.append(name[0])
# print(new_list)
# by list comprehension
new_list2=[name[0] for name in names]
print(new_list2)
| true |
42e3bb8b71a449580d8b7699b45b76965e89dc41 | coder562/python | /52-variable scope.py | 390 | 4.125 | 4 | x=5 #global variable which is defined outside the function
def func():
global x #to change the value of global variable we use term global
x=7 #the variable defined inside the function are called local variables
return x #x has only scope upto func() not in func2() x cant be used outside func() function
print(func()) #this can be print
print(x) #cant print outside of function | true |
ed20bbc58702b64ae4b1724646dd431d41f2fcaa | coder562/python | /68-exercise 14.py | 343 | 4.5625 | 5 | # define a function that take list of words as argument and
# return list with reverse of every element in that list
# example
# ['abc','tuv','xyz']--->['cba','vut','zyx']
def reverse_elements(l):
elements = []
for i in l:
elements.append(i[::-1])
return elements
words=['abc','tuv','xyz']
print(reverse_elements(words))
| true |
b6dbcf61531c5ec98deaac7f4c4a5b405316acc3 | coder562/python | /46-function practice.py | 951 | 4.125 | 4 | # def last_char(name):
# return name[-1]
# print(last_char("vaishali"))
# last_char(9) #error
# define function and check number is even or odd
# def odd_even(num):
# if num%2==0: #% is used to check reminder
# return "even"
# else:
# return "odd"
# print(odd_even(10))
#another method
# def odd_even(num):
# if num%2==0:
# return "even"
# return "odd"
# print(odd_even(7))
#def is even
# def is_even(num):
# if num%2==0:
# return True #T is always capital
# return False
# print(is_even(9))
#anther method
def is_even(num): #when we define function it is called parameter
return num%2==0
# print(is_even(12)) when we call function and pass the value is called arguments
# important
# when we define function it is called parameter
#when we call function and pass the value is called arguments
#function with no paramenters
# def song():
# return "hiiiihkkk"
# print(song())
| true |
774e4fb24567730de3c894550630a51245ed94d0 | Ernestoc14/Python | /pila.py | 795 | 4.3125 | 4 | # Implementacion de Pilas en Python Basico y Sencillo para ERDD con LIFO
pila = [1,2,3] #Creacion de PILA con tres elementos
print('La pila es:') #Impresion de PILA
print(pila)
#Agregamos elementos por el final
print ('Agregamos los numeros 4 y 5 a la Pila')
pila.append(4) #Agregamos el elemento 4 a la PILA
pila.append(5) #Agregamos el elemento 5 a la PILA
print('La pila con los numeros 4 y 5 agregados es: ')
print(pila) #Imprimimos la PILA que mostrara los elementos tambien agregados, 4 y 5
#Sacamos elementos por el Final
s = pila.pop() #Sacara el ultimo elemento de la PILA y lo guardara en s
print( "Sacando el elemento",s ) #Mostramos el numero que fue extraido de la PILA
print('La pila quedaria asi: ')
print(pila) #Imprimira la PILA sin el untimo elemento porque ha sido sacado | false |
45c4c66ff2ccb6042a070256a5056ba573708575 | nkhanhng/namkhanh-fundamental-c4e15 | /session4/homework/turtle_excersise/ex2.py | 344 | 4.15625 | 4 | from turtle import *
def draw_rectangle(m,n):
for i in range(2):
forward(m)
left(90)
forward(n)
left(90)
shape("turtle")
speed(1)
colors = ['red', 'blue', 'brown', 'yellow', 'grey']
for j in colors:
color(str(j))
begin_fill()
draw_rectangle(50,100)
forward(50)
end_fill()
mainloop()
| true |
bd8b9b509d2fe919f97a8685cc8145d1c75b883f | nkhanhng/namkhanh-fundamental-c4e15 | /session6/calc.py | 640 | 4.21875 | 4 | def eval(x,y,op):
result = 0
if op == "+":
result = x + y
elif op == "-":
result = x - y
elif op == "*":
result = x * y
elif op == "/":
result = x // y
return result
# x = int(input("x = "))
# oper = input("Operation(+,-,*,/): ")
# y = int(input("y = "))
# eval(x,y,oper)
# x = int(input("x = "))
# oper = input("Operation(+,-,*,/): ")
# y = int(input("y = "))
#
# if oper == "+":
# result = x + y
# elif oper == "-":
# result = x - y
# elif oper == "*":
# result = x * y
# elif oper == "/":
# result = x / y
#
# print("{0} {1} {2} = {3}".format(x,oper,y,result))
| false |
7c207be73a0defe569ec799b188b5b3544bec62b | RavinderSinghPB/data-structure-and-algorithm | /array/Find the number of sub-arrays having even sum.py | 1,132 | 4.15625 | 4 | def countEvenSum(arr, n):
# A temporary array of size 2. temp[0] is
# going to store count of even subarrays
# and temp[1] count of odd.
# temp[0] is initialized as 1 because there
# a single even element is also counted as
# a subarray
temp = [1, 0]
# Initialize count. sum is sum of elements
# under modulo 2 and ending with arr[i].
result = 0
sum = 0
# i'th iteration computes sum of arr[0..i]
# under modulo 2 and increments even/odd
# count according to sum's value
for i in range(n):
# 2 is added to handle negative numbers
sum = ((sum + arr[i]) % 2 + 2) % 2
# Increment even/odd count
temp[sum] += 1
# Use handshake lemma to count even subarrays
# (Note that an even cam be formed by two even
# or two odd)
result = result + (temp[0] * (temp[0] - 1) // 2)
result = result + (temp[1] * (temp[1] - 1) // 2)
return (result)
if __name__ == "__main__":
T = int(input())
for _ in range(T):
n = int(input())
arr = [int(x) for x in input().split()]
print(countEvenSum(arr, n)) | true |
a822bde45c53e20f84c19e17ef0abb4b8923cc27 | RavinderSinghPB/data-structure-and-algorithm | /puzzle/range of comp no.py | 442 | 4.125 | 4 | def factorial(n):
a = 1
for i in range(2, n + 1):
a *= i
return a
# to print range of length n
# having all composite integers
def Range(n):
a = factorial(n + 2) + 2
b = a + n - 1
if n==(b-a+1):
return 1
else:
return 0
#print("[" + str(a) + ", " + str(b) + "]")
if __name__ == '__main__':
t=int(input())
for _ in range(t):
n=int(input())
print(Range(n)) | false |
7c54a34f8b6476b7ebef606d1416b911b525a135 | devodev/cracking_the_coding_interview_practice | /8.recursion/8.4.py | 957 | 4.3125 | 4 |
def get_subsets(s):
if not s:
return None
return _get_subsets(s, 0)
def _get_subsets(s, n):
all_subsets = None
if len(s) == n:
all_subsets = []
all_subsets.append(set())
else:
all_subsets = _get_subsets(s, n+1)
item = s[n]
more_subsets = []
for subset in all_subsets:
new_subset = subset.copy()
new_subset.add(item)
more_subsets.append(new_subset)
all_subsets.extend(more_subsets)
return all_subsets
if __name__ == '__main__':
'''
Power Set: Write a method to return all subsets of a set.
'''
subsets = {
'a': [0, 1, 2, 3, 4],
'b': [0, 1, 2, 3],
'c': [0, 1, 2],
'd': [0, 1],
'e': [0],
}
asc_sort = lambda x: len(x)
for key, subset in subsets.items():
print('{}. P({}) = {}'.format(key, str(subset), str(sorted(get_subsets(subset), key=asc_sort)))) | true |
2b1a3141594ad6c66dfa4ce3491b62f7551dccb6 | Adem54/Python-Tutorials | /Günün Soruları/3.soru.py | 787 | 4.28125 | 4 | """
Kullanicidan bir kelime alan, ve bu kelimedeki sesli harflerin toplam sayisini ve sesli harflerin kelimenin
kacinci harfleri oldugunu ekrana yazdiran python programini yaziniz.
Kullanicinin sadece kucuk harfleri kullanidigini varsayabilirsiniz.
Ornek Program Outputu:
====================================
lutfen bir kelime giriniz: merhaba
girdiginiz kelimede 3 tane sesli harf var
e kelimenin 2. harfidir
a kelimenin 5. harfidir
a kelimenin 7. harfidir
"""
kelime1 = input("Bir kelime giriniz")
kelime = kelime1.lower()
sesli = "aeıioöuü"
sayac = 1
count = 0
for eleman in kelime:
if eleman in sesli:
count += 1
print(eleman + " kelimenin " + str(sayac) + ". harfidir")
sayac += 1
print("girdiginiz kelimede " + str(count) + " tane sesli harf var")
| false |
c8143a9de01ab254cd4cd68b21dbc4962be490ef | Adem54/Python-Tutorials | /Günün Soruları/slice_methdou.py | 1,553 | 4.25 | 4 | a = [10, 12, 13, 17, 19, 21, 24, 27, 31, 34]
print(a[:2])
# add 1 number
# a[:0] = [30]
# add two numbers
# a[:0] = [40, 50]
# print(a)
b = a[:] # Bir listenin kopyasını almak içi kullanırız
print(b)
# Normalde parmetre olarak 3 eleman alır a[star,stop,step] şekllindedir ve star başlangıç indisi stop duracağı
# indis ve step ise adım sayısnı gösterir
a[3:5:1] = ["Kemal"] # 3.indise kadar olan elemanları yazıyor sonra 3.indise Kemal i yazar sonra da
# ama 3.indisten sonra 5.indise kadar olan elemanları yazmaz 5.indisten itibaren elemanları yazmaya devam eder
a[3:3:1] = ["Kemal"] # bu şekilde de "Kemal" elemanı ekstra liste içerisine ekliyor çünkü 3.indise kadar elemanları
# alıyor daha sonra elemanımız ekliyor ve sonrasında tekrardan 3.indsten başlayarak devam ediyor ve bu şekilde
# listemizin içerisine listeden eleman silmeden elemean eklemiş oluruz
print(a)
print(a[3:5:1]) # 3.indisten alarak başla 5.indise kadar 5 dahil değil 1 er 1er al yaz demek
a[0:3] # demek 0.indisten 3 dahil değil 3 e kadar a listesinin elemnlarını alır
a[3:] # 3.indisten başlar ve a listesinin elemanlarının 3.indisten başlayarak listenin sonuna kadar alır
a[:2] # Burda da 2.indise kadar elemanları alır 2.indis dahill değil yani a nın 0 ve 1.indisini alır
b = a[:] # Bir listenin kopyasını almak içi kullanırız
x = [2, 6, 9, 7, 12, 14, 16]
# Dikkat edersek burda biz x listesinden bir elemanı silmiş oluyoruz aslında
first_list = x[:2]
second_list = x[3:]
print(first_list + second_list)
| false |
efeb5601c4525d64eab0adf492fafe131ed921a1 | Adem54/Python-Tutorials | /3.Week/python9.py | 1,219 | 4.3125 | 4 | # Kullanıcıya while döngüsü 3 kere doğru pin girme şansı verin.Hatalı girişler için ekrana "Hatalı Giriş.
# Tekrar PIN girin" yazdırın
# 3 girişten birinde doğru pin girilirse "PIN Kabul Edildi. Hesabınıza Erişebilirsiniz." yazdırın.
# 3 girişte de yanlış girilirse "3'den Fazla Giriş Hakkınız Yok. Hesabınız Kilitlendi!" yazdırın
print("ACME Bankası Uygulamasına Hoşgeldiniz.")
deneme_sayisi = 0
pin_kodu = 1234
giris = input("PIN kodunu girin")
deneme_sayisi = deneme_sayisi + 1
while deneme_sayisi < 3:
if giris != "1234":
print("Hatalı Giriş. Tekrar PIN girin")
giris = input("PIN kodunu girin")
deneme_sayisi = deneme_sayisi + 1
elif giris == "1234":
print("PIN Kabul Edildi. Hesabınıza Erişebilirsiniz.")
break # Eğer kodu girince orda artık sayacı durdurmasını istersek o zaman doğrdudan break kodunu kullanırız
# ya da biz sayacı bitirmek için koşulu false yapacak birşey yapmalıyız o da belki koşul etkileyen değişken
# koşula girmeyecek sayıya eşitleyebiliriz
if deneme_sayisi == 3 and giris != "1234":
print("3'den Fazla Giriş Hakkınız Yok. Hesabınız Kilitlendi!")
| false |
e765fb185b8d55cb1c1a37595e229a1e047ea78c | Adem54/Python-Tutorials | /sinav/9.py | 521 | 4.21875 | 4 | """
Verilen iki liste arasındaki farklı elemanları bulan ve bunlardan yeni bir liste oluşturan program yazınız.
Örnek:
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
Çıktı:
[1, 2, 5, 6]
"""
def farkli_elemanlari_bul(liste1, liste2):
liste = []
for eleman1 in liste1:
if eleman1 not in liste2:
liste.append(eleman1)
for eleman2 in liste2:
if eleman2 not in liste1:
liste.append(eleman2)
return liste
print(farkli_elemanlari_bul([1, 2, 3, 4], [3, 4, 5, 6])) | false |
7228c8f644f982b022646dff0c24af3ba0b031c1 | Suka91/RS | /CodeArena/CodeArena/Resources/Leap_Year/version3/Leap_Year.py | 440 | 4.34375 | 4 | def leap_year(year):
if(...)==0:
if(...)== 0:
if(...) == 0:
print("{0} is a leap year".format(year))
return 1
else:
print("{0} is not a leap year".format(year))
return -1
else:
print("{0} is a leap year".format(year))
return 1
else:
print("{0} is not a leap year".format(year))
return 1
| true |
1c3ed6a743b865524ff8f21fd85105f92996407f | AntonioRafaelGarcia/LPtheHW | /ex20/ex20.py | 1,581 | 4.375 | 4 | # makes argv available in this script
from sys import argv
# uses argv to assign user input when calling script
script, input_file = argv
# defines function to read and print input variable file
def print_all(f):
print(f.read())
# defines function to go to very first line of inputted variable file
def rewind(f):
f.seek(0)
# defines a function to take designated count and file variables and print the count and associated line
def print_a_line(line_count, f):
print(line_count, f.readline())
# opens and assigns the argv-designated file variable to a new variable
current_file = open(input_file)
# prints string and newline escape sequence
print("First let's print the whole file:\n")
# calls function print_all using the opened argv-designated file variable
print_all(current_file)
# prints string
print("Now let's rewind, kind of like a tape.")
# calls function rewind using the opened argv-designated file variable
rewind(current_file)
# prints string
print("Let's print three lines:")
# thrice calls function print_a_line using the opened argv-designated file variable, iterating up from 1
current_line = 1
# current_line is 1, passed as line_count variable into function print_a_line
print_a_line(current_line, current_file)
# iterates current_line up 1 to 2, passed as line_count variable into function print_a_line
current_line += current_line
print_a_line(current_line, current_file)
# iterates current_line up 1 to 3, passed as line_count variable into function print_a_line
current_line += current_line
print_a_line(current_line, current_file)
| true |
63dbc6ca29923a63a42477c45d138a7c29d7c26e | AntonioRafaelGarcia/LPtheHW | /ex12.py | 312 | 4.28125 | 4 | # string prompts and directly assigns to three separate variables
age = input("How old are you? ")
height = input("How tall are you? ")
weight = input("How much do you weigh? ")
# f prints a string statement seeded with those prompted variables
print(f"So, you're {age} old, {height} tall and {weight} heavy.")
| true |
b56b81731cb6a6cacbbdaf7d45d645ea040a10ef | mkwak73/probability | /chapter 1/exercises/exercise1.py | 1,183 | 4.4375 | 4 | # Chapter 1 - Exercise 1
# Author: Michael Kwak
# Date: December 26 2016
#######################################################
#
# random () - return the next random floating point number in the range [0.0, 1.0)
#
import random
#
# get input for number of tosses for this simulation
#
n = int(input("Enter the value of n: "))
print()
#
# initialize head and tail counters to zero
# initialize number of tosses to zero
#
heads = 0
tails = 0
tosses = 0
#
# run simulation by generating heads or tails
# using random number generator
#
for index in range (1,n+1):
if (random.random() < 0.5):
heads = heads + 1
tosses = tosses + 1
else:
tails = tails + 1
tosses = tosses + 1
#
# print every 100 times:
# a. the proportion of heads minus 1/2
# b. the number of heads minus half the number of tosses
#
if (tosses % 100 == 0):
proportion_of_heads = heads / tosses
approach_to_zero_1 = proportion_of_heads - 0.5
approach_to_zero_2 = heads - int(tosses / 2)
print("Number of tosses: ", tosses)
print("Proportion of heads minus 0.5: ", approach_to_zero_1)
print("Number of heads minus half the number of tosses: ", approach_to_zero_2)
print()
| true |
a7a9e67983effa2597e33420b34085c55e0ed2b7 | mkwak73/probability | /chapter 1/exercises/exercise9.py | 2,743 | 4.125 | 4 | # Chapter 1 - Exercise 9 - Labouchere system
# Author: Michael Kwak
# Date: January 4 2016
#######################################################################################
#
# random () - return the next random floating point
# number in the range [0.0, 1.0)
#
import random
from math import floor
#
# define roulette function which returns a value of [1,38]
#
def roulette():
r = random.random()
num = floor(38 * r) + 1
return num
#
# define bet function which returns the sum
# of the first and last numbers of the list
#
def sum(list):
if (len(list) == 1):
sum = list[0]
else:
last = len(list) - 1
sum = list[0] + list[last]
return sum
#
# define delete function which removes
# the first and last numbers from the list
#
def delete(list):
if (len(list) == 1):
del list[0]
else:
last = len(list) - 1
# delete last number (first!!)
del list[last]
# delete first number
del list[0]
return list
#
# check to see that list is not empty
# return 1 if not empty
# return 0 if empty
#
def not_empty(list):
if (len(list) > 0):
return 1
elif (len(list) == 0):
return 0
#######################################################################################
#
# define variables to tally wins and losses
# initialize to zero
#
wins = 0
losses = 0
#
# define initial list
#
list = [1,2,3,4]
print("list: ", list)
#
# define variable to tally winnings in dollar amount
# initialize to zero
#
winnings = 0
#
# total number of turns that occurred in a single game
# initialize to zero
#
turns = 0
#######################################################################################
#######################################################################################
while not_empty(list):
bet = sum(list)
print("bet: ", bet)
slot = roulette()
print("slot: ", slot)
# green or red; win
if ((slot == 1) or (slot == 2) or (slot > 20)):
winnings = winnings + bet
list = delete(list)
wins = wins + 1
print("Won - modified list after delete: ", list)
print("Winnings: ", winnings)
print()
# black; lose
elif ((slot < 21) and (slot > 2)):
winnings = winnings - bet
list.append(bet)
losses = losses + 1
print("Lost - modified list after append: ", list)
print("Winnings: ", winnings)
print()
#increment turn per 1 interation of while loop
turns = turns + 1
#######################################################################################
print("Total winnings for this game: ", winnings)
print()
print("Total number of turns: ", turns)
print("Total number of wins: ", wins)
print("Total number of losses: ", losses)
print("Win ratio: ", wins / turns)
print("Loss ratio ", losses / turns)
| true |
6b39f64cd03f762d6f7a8bfb79842a845fac5107 | Kowenjko/Python_Homework_13_Kowenjko | /test_2.py | 2,973 | 4.15625 | 4 | """
Examples:
triangle = Triangle([3, 3, 3])
Use classes TriangleNotValidArgumentException and TriangleNotExistException
Create class TriangleTest with parametrized unittest for class Triangle
test data:
"""
import unittest
import math
class Triangle:
def __init__(self, t):
self.t = t
def input_value(self):
return self.t
def perimetr(self):
p = 0
for i in self.t:
p += i
return p
def square(self):
p = self.perimetr()/2
s = round(math.sqrt(p*(p-self.t[0])*(p-self.t[1])*(p-self.t[2])), 2)
return s
valid_test_data = [[3, 4, 5], [10, 10, 10], [6, 7, 8], [7, 7, 7], [50, 50, 75], [
37, 43, 22], [26, 25, 3], [30, 29, 5], [87, 55, 34], [120, 109, 13], [123, 122, 5]]
rezultat_test_data = [6.0, 43.3, 20.33, 21.22,
1240.2, 407.0, 36.0, 72.0, 396.0, 396.0, 300.0]
not_valid_arguments = [['3', 4, 5], ['a', 2, 3], [
7, "str", 7], ['1', '1', '1'], ['a', 'str', 7]]
class TestClass(unittest.TestCase):
# Перевіряємо чи розрахунки вірні
def test1(self):
triangle = Triangle([5, 3, 3])
self.assertEqual(triangle.perimetr(), 11)
self.assertEqual(triangle.square(), 4.15)
# Перевіряємо чи тип даних коректний
# ('3', 4, 5),
# ('a', 2, 3),
# (7, "str", 7),
# ('1', '1', '1'),
# ('a', 'str', 7)
def test2(self):
for i in not_valid_arguments:
with self.assertRaises(TypeError):
triangle = Triangle(i)
triangle.perimetr()
triangle.square()
# Перевіряємо чи результат від'ємний або рівний 0
def test3(self):
triangle = Triangle([-3, -5, -3])
self.assertLessEqual(triangle.perimetr(), 0)
# Перевіряємо чи вхіні дані від'ємні або нулеві
def test4(self):
triangle = Triangle([-3, 0, -3])
for i in triangle.input_value():
self.assertLessEqual(i, 0)
# Перевіряємо на правильність
# ((3, 4, 5), 6.0),
# ((10, 10, 10), 43.30),
# ((6, 7, 8), 20.33),
# ((7, 7, 7), 21.21),
# ((50, 50, 75), 1240.19),
# ((37, 43, 22), 406.99),
# ((26, 25, 3), 36.0),
# ((30, 29, 5), 72.0),
# ((87, 55, 34), 396.0),
# ((120, 109, 13), 396.0),
# ((123, 122, 5), 300.0)
def test5(self):
for i in range(len(valid_test_data)):
triangle = Triangle(valid_test_data[i])
self.assertEqual(triangle.square(), rezultat_test_data[i])
# Перевіряємо що довхина вхідних даних = 3
def test6(self):
triangle = Triangle([-5, -5, -3])
self.assertLessEqual(len(triangle.input_value()), 3)
triangle = Triangle([-5, -5, -3])
print(triangle.perimetr())
print(triangle.square())
print(triangle.input_value())
| false |
ea6b1b325303699febde9050a58e031f18651475 | NaregAmirianMegan/Hailstone-Problem | /hailstone_interactive.py | 558 | 4.125 | 4 | def isEven(num):
if(num%2 == 0):
return True
else:
return False
def applyOdd(num):
return 3*num + 1
def applyEven(num):
return num/2
def analyze(num, count):
if(isEven(num)):
num = applyEven(num)
else:
num = applyOdd(num)
if(num == 1):
print("Value: ", num, "Iteration: ", count)
return count
else:
print("Value: ", num, "Iteration: ", count)
analyze(num, count+1)
num = input("Please enter a number to test the hailstone conjecture: ")
analyze(int(num), 1)
| true |
391c94dc9513855243ea8658926ff404ac1510b2 | yangwenbinGit/python_programe | /python_04/do_slice.py | 2,282 | 4.1875 | 4 | # 切片
# 取一个list或tuple的部分元素是非常常见的操作。比如,一个list如下:
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
# 取前3个元素,应该怎么做?笨办法就是:
print(L[0],L[1],L[2])
# 也可以用循环的方式 方式一
i=0
for x in L:
if(i<3):
print(L[i])
i=i+1
# 方式二 range(5)生成的序列是从0开始小于5的整数 list(range(5)) 会将生成的数转换为list
r=[]
n=3
for i in list(range(n)):
r.append(L[i])
print(r)
print(list(range(n)))
# 对这种经常取指定索引范围的操作,用循环十分繁琐,因此,Python提供了切片(Slice)操作符,能大大简化这种操作。
# 对应上面的问题,取前3个元素,用一行代码就可以完成切片:
# L[0:3]表示,从索引0开始取,直到索引3为止,但不包括索引3。即索引0,1,2,正好是3个元素
print(L[0:3])
# 如果第一个索引是0,还可以省略
print(L[:3])
# 也可以从索引1开始,取出2个元素出来
print(L[1:3])
# Python支持L[-1]取倒数第一个元素,那么它同样支持倒数切片
# 记住倒数第一个元素的索引是-1
print(L[-1:]) # ['Jack']
print(L[-2:]) # ['Bob', 'Jack']
print(L[-2:-1]) # ['Bob']
# 我们先创建一个0-99的数列
M =list(range(100))
print(M)
# 取出前10个数
print(M[0:10]) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 取出后10个
print(M[-10:])
# 前11-20中的所有数:
print(M[11:21])
# 前10个数,每两个取一个:
print(M[0:10:2])
# 所有数,每5个取一个:
print(M[::5])
# 甚至什么都不写,只写[:]就可以原样复制一个list
print(M[:])
# tuple也是一种list,唯一区别是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple
N =(0,1,2,3,4,5)
print(N[:3]) # (0,1,2)
# 字符串'xxx'也可以看成是一种list,每个元素就是一个字符。因此,字符串也可以用切片操作,只是操作结果仍是字符串
S ='ABCDEFG'
print(S[0:3]) # ABC
print(S[::2]) # ACEG
# 在很多编程语言中,针对字符串提供了很多各种截取函数(例如,substring),其实目的就是对字符串切片。Python没有针对字符串的截取函数,只需要切片一个操作就可以完成,非常简单
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.