blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
65268b86a2ed7ddfbf5f59db5e5b86577d3b9363 | jeffkwiat/minesweeper | /app.py | 2,961 | 4.125 | 4 | import random
class Minesweeper(object):
"""
Implementing a simple Minesweeper board.
"""
def __init__(self, width, height, number_of_mines):
self.width = width
self.height = height
self.number_of_mines = number_of_mines
self.board = self.generate_board()
self... | true |
53e9e59370cad6cfcf69c3219783070f35df4f81 | GauravR31/Solutions | /Classes/Flower_shop.py | 1,883 | 4.15625 | 4 | class Flower(object):
"""docstring for ClassName"""
def __init__(self, f_type, rate, quantity):
self.type = f_type
self.rate = rate
self.quantity = quantity
class Bouquet(object):
"""docstring for ClassName"""
def __init__(self, name):
self.name = name
self.flowers = []
def add_flower(self):
f_type =... | true |
ce97aff7408d5808d33756c8bb72e2910bbe77a4 | ngrq123/learn-python-3-the-hard-way | /pythonhardway/ex30.py | 732 | 4.34375 | 4 | # Initialise people to 30
people = 30
# Initialise cars to 40
cars = 40
# Initialise buses to 15
buses = 15
# If there are more cars then people
if cars > people:
print("We should take the cars.")
# Else if there are less cars then people
elif cars < people:
print("We should not take the cars.")
else:
prin... | true |
d61c6db3c3889e24794719d0d8e7c9a4c6a3732e | dkahuna/basicPython | /Projects/calcProgram.py | 241 | 4.5 | 4 | # Calculating the area of a circle
radius = input('Enter the radius of your circle (m): ')
area = 3.142 * int(radius)**2 # int() function is used to convert the user's input from string to integer
print('The area of your circle is:', area) | true |
5dbf3b63d6bb744d4a02aba9f41acd9ad64372c2 | dkahuna/basicPython | /FCC/ex_09/ex_09.py | 714 | 4.15625 | 4 | fname = input('Enter file name: ')
if len(fname) < 1 : fname = 'clown.txt'
hand = open(fname)
di = dict() #making an empty dictionary
for line in hand :
line = line.rstrip() #this line strips the white space on the right side per line of the file
words = line.split() #this line splits the text file into an arr... | true |
f164802d0ebb45593969d7736755758c3c84b03d | Siddharth46/first | /classp.py | 703 | 4.3125 | 4 | class Movie:
'''this code is property of siddharth dixit'''
def __init__(self,movie, actor, femaleactor, ratings):
self.movie=movie
self.actor=actor
self.femaleactor=femaleactor
self.ratings=ratings
def info(self):
print("Move name {}".format(self.movie))
pri... | false |
ecfe7da8cee6b57ab65108992a3c333f2e0dc283 | RustingSword/adventofcode | /2020/01/sol2.py | 315 | 4.125 | 4 | #!/usr/bin/env python3
def find_triple(nums, target=2020):
for first in nums:
for second in nums:
if (third := target - first - second) in nums:
return first * second * third
if __name__ == "__main__":
nums = set(map(int, open("input")))
print(find_triple(nums))
| true |
2abc3eda58ecfee7de0adc69143acad90c55bc4e | 981377660LMT/algorithm-study | /9_排序和搜索/经典题/自定义比较函数/数组组成最大数-拼接字典序最大.py | 920 | 4.25 | 4 | # 剑指 Offer 45. 把数组排成最小的数
from functools import cmp_to_key
from typing import List
# !给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。
# 数组组成最大数(拼接最大序)
# cmp_to_key 将compare函数转换成key
def mergeSort(s1: str, s2: str) -> int:
"""拼接两个字符串,字典序最小"""
return -1 if s1 + s2 < s2 + s1 else 1
def toMax(nums: List[int]) -> ... | false |
accebf20a8b38eb27330f7ec76e02e9f5d7debae | 981377660LMT/algorithm-study | /19_数学/计算几何/圆形/最小圆覆盖.py | 2,550 | 4.125 | 4 | # 你需要用最少的原材料给花园安装一个 圆形 的栅栏,
# 使花园中所有的树都在被 围在栅栏内部(在栅栏边界上的树也算在内)。
# https://leetcode.cn/problems/erect-the-fence-ii/
# !最小圆覆盖 Welzl 算法(随机增量法)
# n<=3000
import random
from typing import List, Tuple, Union
EPS = 1e-8
def calCircle2(
x1: int, y1: int, x2: int, y2: int, x3: int, y3: int
) -> Union[T... | false |
d7ab97a0b0acf6e66d0c184d3588f9673c525bfa | 981377660LMT/algorithm-study | /前端笔记/thirtysecondsofcode/python/python的typings/5_联合类型.py | 645 | 4.125 | 4 | from typing import Union
# 联合类型之联合类型会被展平
Union[Union[int, str], float] == Union[int, str, float]
# 在 3.10 版更改: 联合类型现在可以写成 X | Y
# StrOrInt = str | int
# Alternative syntax for unions requires Python 3.10 or newer
# 通常需要使用 isinstance ()检查来首先将联合类型缩小到非联合类型
def f(x: Union[int, str]) -> None:
x + 1 # Error:... | false |
37281e1e27482ad1847549fda1d6f38bcc5b8e5a | 981377660LMT/algorithm-study | /19_数学/模拟退火与爬山法/三分法求凸函数极值.py | 1,725 | 4.15625 | 4 | """
三分法求单峰函数的极值点.
更快的版本见: FibonacciSearch
"""
from typing import Callable
INF = int(4e18)
def minimize(fun: Callable[[int], int], left: int, right: int) -> int:
"""三分法求`严格凸函数fun`在`[left,right]`间的最小值"""
res = INF
while (right - left) >= 3:
diff = (right - left) // 3
mid1 ... | false |
ae0ee943b022a73f8864057c6c12916615c5ca9d | hasanalpzengin/HummingDrone | /Question_1/fibonacci.py | 384 | 4.1875 | 4 | import sys
#recursive
def fibonacci(num):
if num < 2:
return num
else:
return fibonacci(num-1)+fibonacci(num-2)
if __name__ == "__main__":
#first parameter
try:
num = int(sys.argv[1])
output = fibonacci(num)
print("Fibonacci {} = {}".format(num ,output)... | false |
ade6f9461899f60320e1ee0ceb3356dc1b78861b | jianyuecc/python_learn | /python函数的定义/Lambda形式/make_incrementor.py | 921 | 4.15625 | 4 | 出于实际需要,有几种通常在函数式编程语言例如 Lisp 中出现的功能加入到了
Python。通过 lambda 关键字,可以创建短小的匿名函数。这里有一个函数返回它
的两个参数的和: lambda a, b: a+b 。 Lambda 形式可以用于任何需要的函数对
象。出于语法限制,它们只能有一个单独的表达式。语义上讲,它们只是普通函数
定义中的一个语法技巧。类似于嵌套函数定义,lambda 形式可以从外部作用域引
用变量:
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> ... | false |
7f5f33b40f1a8d3acc72c889bef1accf9432abb7 | rubenvdham/Project-Euler | /euler009/__main__.py | 833 | 4.4375 | 4 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
def find_triplet_with_sum_of(number):
sum = number
number = int(number/2)... | true |
156ce2abce7f089a563208dd1947eb0276c00a20 | romeoalpharomeo/Python | /fundamentals/fundamentals/rock_paper_scissors.py | 1,670 | 4.5 | 4 | """
Build and application when both a user and computer can select either Rock, Paper or Scissors, determine the winner, and display the results
For reference:
Rock beats Scissors
Scissors beats Paper
Paper beats Rock
Part I
Compare user input agains computer choice and determine a winner
Part II
Compare user input ... | true |
0e792822cb1faeda92a0c0fec8bb86901c40aa09 | anmolrajaroraa/CorePythonBatch | /largest-among-three.py | 1,385 | 4.46875 | 4 | # num1, num2, num3 = 12, 34, 45
# if (num1 > num2) and (num1 > num3):
# print("The largest between {0}, {1}, {2} is {0}".format(num1, num2, num3))
# elif (num2 > num1) and (num2 > num3):
# print("The largest between {0}, {1}, {2} is {1}".format(num1, num2, num3))
# else:
# print("The largest between {1}, {... | true |
782019d56f35c65b24b5f26a682b0fb92ff7478b | davixcky/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 361 | 4.3125 | 4 | #!/usr/bin/python3
''' Add integer module '''
def add_integer(a, b=98):
''' Function that add to numbers '''
type_a, type_b = type(a), type(b)
if type_a != int and type_a != float:
raise TypeError('a must be an integer')
if type_b != int and type_b != float:
raise TypeError('b must be ... | false |
5a38d95fe9db58447d65605ddfef48559e6ae689 | angjerden/kattis | /pizza_crust/pizza_crust.py | 845 | 4.1875 | 4 | '''
George has bought a pizza. George loves cheese.
George thinks the pizza does not have enough cheese.
George gets angry.
George’s pizza is round,
and has a radius of R cm. The outermost C cm is crust,
and does not have cheese. What percent of George’s pizza has cheese?
Input
Each test case consists of a single li... | true |
14fc091ee12c9a6e841096e6e1e8f253863beeb3 | jeffbergcoutts/udacity-compsci | /lesson11.py | 1,373 | 4.53125 | 5 | '''
How to Manage Data
'''
# Quiz: Stooges
stooges = ['Moe', 'Larry', 'Curly']
# Quiz: Days in a Month
days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
def how_many_days(month):
return days_in_month[month - 1]
print how_many_days(2)
print how_many_days(9)
# Quiz: Countries
countries = [['China','Beijing',1... | false |
1e0e9f789c65d252092168bbf9d90f89092f0c17 | maryade/Personal-Learning-Python | /Udemy Python Practice programming Module 3.py | 918 | 4.46875 | 4 | # # Addition
# print(5+3)
#
# # Subtraction
# print(11-4)
#
# # multiplication
# print(22*5)
#
# # division
# print(6/3)
#
# # modulo
# print(9%5)
#
# # exponents
# print(2^4)
# print(6**2)
#
# # return integer instead of floating number
# print(11//5)
# print(451//5)
# assignment operation
x = 18
# print(x)
# to i... | true |
d064c635389f767606f56ae246d695d7b1af6ecf | kevindsteeleii/HackerRank_InterviewPreparationKit | /00_WarmUpChallenges/jumpingOnClouds_2019_02_20.py | 1,712 | 4.28125 | 4 | """
Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2. She must avoid the thunderheads. Determine the minimum number... | true |
0915df88be07251462464e301bec6535ac91626d | tarjantamas/Virtual-Controller-CNN | /src/common/util.py | 1,590 | 4.5625 | 5 | def getArgumentParameterMap(argv):
'''
Maps arguments to their list of parameters.
:param argv: list of arguments from the command line
:return: a map which maps argument names to their parameters.
If the program is run in the following way:
python main.py --capturedata param1 param2 param3 --othercommand p... | true |
0cb1eb4245d4d82b15e885ab5b7374b0c419e6e0 | epc0037/URI-CS | /CSC110/Python Lists/HW3/problem1.py | 878 | 4.40625 | 4 | # Evan Carnevale
# CSC 110 - Survey of Computer Science
# Professor Albluwi
# Homework 3 - Problem 1
# This program will generate a list containing
# all the odd numbers between 100 and 500 except 227 and 355.
# create an empty number list & set the values we wish to remove from the list
numList = []
a = 227
b = 355
... | true |
2869a4a804531ff82b8957a250082d0eaecfdd07 | epc0037/URI-CS | /CSC110/Python Functions/HW4/stocks.py | 2,179 | 4.25 | 4 | # Evan Carnevale
# CSC 110 - Survey of Computer Science
# Professor Albluwi
# Homework 4 - Problem 1
# This program will get create two lists for stock names and prices,
# which will be entered by the user using a loop. I will utilize 3 functions:
# the main function, the searchStock function and the printStock functio... | true |
1f97e7a5f66552f012f3c95e05152ac9f9747640 | epc0037/URI-CS | /CSC110/Python Basics/HW2/problem3.py | 404 | 4.375 | 4 | #Evan Carnevale
#CSC 110 - Survey of Computer Science
#Professor Albluwi
#Homework 2 - Problem 3
TOTAL_BUGS = 0
DAYS = 1
while DAYS <= 7:
print("Day", DAYS, ": Did you collect a lot of bugs today?")
today_bug = int(input("Enter the number of bugs collected today"))
TOTAL_BUGS += today_bug
DAYS +=1
... | true |
4d2057482e6711b76d94eaeff48d52ae787ca22e | GGMagenta/exerciciosMundo123 | /ex067.py | 413 | 4.125 | 4 | # Pegue um número e mostre a tabuada ate o usuario digitar um número negativo
while True:
numero = int(input('Digite um número inteiro e \033[1;32mpositivo\033[m: '))
if numero < 0:
break
for i in range(1, 11):
print(f'{numero} X {i} = {numero * i}')
i += 1
print('='*20)
... | false |
70b9f0cd268f24ad8317f72514c54cf8e11a5b36 | GGMagenta/exerciciosMundo123 | /ex037.py | 1,016 | 4.15625 | 4 | # Pegue um numero e pergunte para qual base deseja converter
# 1 - Binário 2 - Octal 3 - Hexadecimal
n = int(input('Digite o número que deseja converter: '))
opcao = int(input('Digite \033[31m1\033[m para converter para \033[31mbinário\033[m, \033[32m2\033[m'
'para \033[32moctal\033[m, e \033[33... | false |
db0c5a43933e5f1a257eaca2e3003a3a3cd7a40d | Nathansbud/Wyzdom | /Students/Suraj/quiz.py | 513 | 4.125 | 4 | students = ["Jim", "John", "Jack", "Jacob", "Joseph"]
grades = []
for student in students:
passed = False
while not passed:
try:
grade = float(input(f"Input a quiz grade for {student} (0-100): "))
if not 0 <= grade <= 100: raise ValueError()
grades.append(grade)
... | true |
49f9fe9f6f2e695223c8c73ed60d7dc01a41d0ff | rajdharmkar/Python2.7 | /sortwordsinalbetorder1.py | 527 | 4.53125 | 5 | my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = my_str.split()# here separator is a space between words
print words
# sort the list
words.sort()
# display the sorted words
for word in words:
print(word)
my_str = input("Enter a string with words separated ... | true |
17e86708d5b2a0476756c63ab8d0cd12a77eba92 | rajdharmkar/Python2.7 | /initmethd1.py | 1,676 | 4.625 | 5 | class Human:
# def __init__(self): pass # init method initializing instance variables
#
# def __str__(): pass # ??
#
# def __del__(self): pass # ??...these three def statements commented out using code>> comment with line comment..toggles
def __init__(self, name, age, gender): # self m... | true |
53ebcd324577f722da9407c61ea2adf9dc66bed1 | rajdharmkar/Python2.7 | /math/fibo.py | 1,296 | 4.28125 | 4 |
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print b, # comma in print statement acts like NOT newline , all numbers are printed in one line..a row of numbers
# without comma or anything everytime there is a new line; we get a colu... | true |
16c0d9db5c7237b6f7dace39bdaf2b949d0b070e | rajdharmkar/Python2.7 | /assertXpl2.py | 2,214 | 4.40625 | 4 | class B: # class declaration with keyword class, class object B created
# class object; instance object; function object; method object
x = 10 # this is a class attribute
def __init__(self, name): # this is a __init__ method, also called a constructor that initializes default values of instance
... | true |
b20e8e5fc85924d740d9c0ea38f22e43fecf3147 | rajdharmkar/Python2.7 | /continueeX.py | 486 | 4.34375 | 4 | for val in "string":
if val == "i":
continue
print(val),
print("The end")
#The continue statement is used to skip the rest of the code inside a loop for
#the current iteration only. Loop does not terminate but continues on with the
#next iteration.
#Syntax of Continue
#continue
#We co... | true |
13bcc351d18826e483b62b4a7eb9e94f85cdb0c6 | rajdharmkar/Python2.7 | /Exception handling/NameError3.py | 684 | 4.5 | 4 | s = raw_input('Enter a string:') # raw_input always returns a string whether 'foo'/foo/78/'78'
# n =int(raw_input(prompt))); this converts the input to an integer
n = input("Enter a number/'string':")# this takes only numbers and 'strings'; srings throw errors ..it also evaluates if any numeric expression is given
p... | true |
d3db4014449d6b02a3c6a99d7101ffc793e87048 | rajdharmkar/Python2.7 | /usinganyorendswith1.py | 583 | 4.4375 | 4 | #program to check if input string endswith ly, ed, ing or ers
needle = raw_input('Enter a string: ')
#if needle.endswith('ly') or needle.endswith('ed') or needle.endswith('ing') or needle.endswith('ers'):
# print('Is valid')
#else:
# print('Invalid')
if needle in ('ly', 'ed', 'ing', 'ers'):#improper code
... | true |
2be6e85839802e5365e65ee47d09f914d388f198 | rajdharmkar/Python2.7 | /methodoverloading1.py | 606 | 4.25 | 4 | class Human:
def sayHello(self, name=None):
if name is not None:
print 'Hello ' + name
else:
print 'Hello '
# Create instance
obj = Human()
# Call the method
obj.sayHello()
# Call the method with a parameter
obj.sayHello('Rambo')
#obj.sayHello('Run', 'Lola')... | true |
825180decbe595ad5ec6b84511f97661ae28a121 | NANGSENGKHAN/cp1404practicals | /prac02/exceptions_demo.py | 1,046 | 4.53125 | 5 | try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
while denominator == 0:
print("Denominator cannot be zero")
denominator = int(input("Enter the denominator: "))
fraction = numerator / denominator
print(fraction)
except ValueErro... | true |
9ac5ec423256abc74722ccf876114310e87aad6b | emanchas/Python | /Python/exam1IST140_Ed Manchas.py | 1,160 | 4.21875 | 4 | print ('This program converts fahrenheit to celsius \n')
user_temp = int(input('Please input a temperature in Fahrenheit:'))
while user_temp < 0:
print ('Error! Temperature must be greater than 0 degrees!')
user_temp = int(input('Please input a temperature in Fahrenheit:'))
print ('')
print ('Fahrenheit... | true |
ead5340377ca5cf9e4cae2c2ae1da8e9ac0a1ffb | arydwimarta/python3-dummie | /lat6.py | 372 | 4.28125 | 4 | course = 'Python for Beginners 123'
print (len(course)) #menghitung jumlah huruf
print (course.upper())
print (course.lower())
#print(course)
print (course.find('o')) #find string become index
#print (course.replace('for','untuk'))
print (course.replace('o', 'a'))
print ('Python' in course) #in operator
print (course.t... | false |
782af31d67c20f4b3b7d03b4ad283df4baa296fb | hoklavat/beginner-python | /08_Tuple.py | 344 | 4.125 | 4 | #08- Tuple
tuple1 = ()
print(type(tuple1))
tuple1 = (9)
print(type(tuple1))
tuple1 = (1, 2, 3, 4, 5)
print(type(tuple1))
print(tuple1[1])
#tuple1[1] = 0 Error: unmutable elements
(a, b, c, d, e) = tuple1
print(a)
print(len(tuple1))
print(max(tuple1))
print(min(tuple1))
print(tuple1 + (1 ,2 ,3))
print(tuple1 * 2)
print... | false |
fb80c96b9ea3a455cc9e5fe3daac41c59e64672b | EQ4/amplify | /src/amplify/utils.py | 643 | 4.46875 | 4 | import re
def natural_sort(string):
'''
This function is meant to be used as a value for the key-argument in
sorting functions like sorted().
It makes sure that strings like '2 foo' gets sorted before '11 foo', by
treating the digits as the value they represent.
'''
# Split the string int... | true |
599ff97346be71193c24c5818e5f2daf99cd6e04 | cfascina/python-learning | /exercices/built-in-functions/lambda-expression/main.py | 764 | 4.5625 | 5 | # Lambda expressions are anonymous functions that you will use only once.
# The following square() function will be converted into a lambda expression,
# step by step.
# Step 1:
# def square(number):
# result = number ** 2
# return result
# Step 2:
# def square(number):
# return number ** 2
# Step 3:
# d... | true |
ee4f50efcfb983282db6c7a1bedf8116508ebf55 | MDCGP105-1718/portfolio-Ellemelmarta | /Python/ex11.py | 780 | 4.1875 | 4 | from random import randint
x = int(randint (1,100))
#make user guess a number with input
guess = int(input("Guess a number between 1 - 100: "))
num_guesses = 1
#tell them higher or lower
while guess != x:
if guess > x and guess != x:
print ("wrong, too high")
guess = int(input("Guess again: "))
... | true |
b59bf1444ea96d25bb3aa233600e298f41df21e9 | ssavann/Python-Hangman-game | /Hangman.py | 1,754 | 4.34375 | 4 | #Build a hangman game
import random
import HangmanArt
import HangmanWords
#print ASCII art from "stages"
print(HangmanArt.logo)
end_of_game = False
#List of words
word_list = HangmanWords.word_list
#Let the computer generate random word
chosen_word = random.choice(word_list)
#to count the number of letter in th... | true |
40139855c83eb27e635ba657b3e4e21adb7091ce | samiran163/Helloworld | /Operators.py | 606 | 4.40625 | 4 | #Arithmetic operators
num1 =10
num2 =20
print("num1+num2=",num1 + num2)
print("num1-num2=",num1 - num2)
print("num1*num2=",num1 * num2)
print("num1/num2=",num1 / num2)
print('5^3 =',5**3)
print("20 % 3 =", 20%3)
print("22/7=", 22//7)
print('3.8//2', 3.8//2)
#Assignment operator
num3 = num1 +num2
print(num3)
num3+=nu... | false |
77f22ce39b1fee400eaf29861a4a5eca82ebf9a4 | LuiSteinkrug/Python-Design | /wheel.py | 1,400 | 4.21875 | 4 | import turtle
turtle.penup()
def drawCircle(tcolor, pen_color, scolor, radius, mv):
turtle.pencolor(pen_color) # not filling but makes body of turtle this colo
turtle.fillcolor(tcolor) # not filling but makes body of turtle this colo
turtle.begin_fill()
turtle.right(90) # Face South
... | true |
8f5136031e899e3662030a08fe9f11a1983bfc0b | pratikdk/ctci_dsa_solutions | /LinkedList/linked_list.py | 1,141 | 4.15625 | 4 | class Node():
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList():
def __init__(self):
self.head = self.tail = None
def printList(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
def link... | false |
325f52227fcdd352295be2352731b33cedaf2ba4 | urantialife/AI-Crash-Course | /Chapter 2/Functions/homework.py | 715 | 4.1875 | 4 | #Exercise for Functions: Homework Solution
def distance(x1, y1, x2, y2): # we create a new function "distance" that takes coordinates of both points as arguments
d = pow(pow(x1 - x2, 2) + pow(y1 - y2, 2), 0.5) # we calculate the distance between two points using the formula provided in the... | true |
6993f804ebd81a8fac2c2c2dcc7ba5a96d37e62d | saifsafsf/Semester-1-Assignments | /Lab 11/Modules2.py | 1,894 | 4.4375 | 4 | def strength(password):
'''Takes a password.
Returns its strength out of 10.'''
pass_strength = 0
# If length of password is Good.
if 16 >= len(password) >= 8:
pass_strength += 2
# If password has a special character
if ('$' in password) or... | true |
ce44b33c8e5d4c26ec7f67d09fff55e8d4623d9c | saifsafsf/Semester-1-Assignments | /Lab 08/task 1.py | 419 | 4.21875 | 4 | math_exp = input('Enter a mathematical expression: ') # Taking Input
while math_exp != 'Quit':
math_exp = eval(math_exp) # Evaluating Input
print(f'Result of the expression: {math_exp:.3}\n')
print('Enter Quit to exit the program OR') # Taking input for next iteration
math_exp = input('Ent... | true |
7196fac0553a675a33fe3cc7816876f40fa2966e | saifsafsf/Semester-1-Assignments | /Lab 08/AscendSort.py | 533 | 4.15625 | 4 | def ascend_sort(input_list):
'''ascend_sort([x])
Returns list sorted in ascending order.'''
for i in range(1, len(input_list)): # To iterate len(list)-1 times
for j in range((len(input_list))-i):
if input_list[j] > input_list[j+1]: # Comparing two consecutive values
... | true |
bdf165162078678430c7db868bb38f2894b27f63 | saifsafsf/Semester-1-Assignments | /Assignment 3/Task 1.py | 780 | 4.1875 | 4 | import Maxim
import Remove # Importing modules
import Reverse
nums = input('Enter a natural number: ') # Taking input
if int(nums) > 0:
largest_num = str() # Defining variable before using in line 9
while nums != '':
max_num = Maxim.maxim(nums) # Using Maxim module
large... | true |
ba2c1f8c3440bbcc652276ea22c025fdc6fae4d6 | ridinhome/Python_Fundamentals | /07_classes_objects_methods/07_01_car.py | 862 | 4.4375 | 4 | '''
Write a class to model a car. The class should:
1. Set the attributes model, year, and max_speed in the __init__() method.
2. Have a method that increases the max_speed of the car by 5 when called.
3. Have a method that prints the details of the car.
Create at least two different objects of this Car class and dem... | true |
3ca0df53a0db382f61549d00923829d0dc3b00be | ridinhome/Python_Fundamentals | /08_file_io/08_01_words_analysis.py | 1,565 | 4.4375 | 4 | '''
Write a script that reads in the words from the words.txt file and finds and prints:
1. The shortest word (if there is a tie, print all)
2. The longest word (if there is a tie, print all)
3. The total number of words in the file.
'''
my_dict = {}
shortest_list = []
longest_list = []
def shortestword(input_dic... | true |
b644aa4a1d7e9d74a773a5e2b4dc095fac236ee2 | ridinhome/Python_Fundamentals | /03_more_datatypes/3_tuples/03_16_pairing_tuples.py | 970 | 4.375 | 4 | '''
Write a script that takes in a list of numbers and:
- sorts the numbers
- stores the numbers in tuples of two in a list
- prints each tuple
If the user enters an odd numbered list, add the last item
to a tuple with the number 0.
Note: This lab might be challenging! Make sure to discuss it with your me... | true |
916c20052c18261dd5ef30d421b0e17b0e92d443 | ridinhome/Python_Fundamentals | /02_basic_datatypes/1_numbers/02_05_convert.py | 568 | 4.375 | 4 | '''
Demonstrate how to:
1) Convert an int to a float
2) Convert a float to an int
3) Perform floor division using a float and an int.
4) Use two user inputted values to perform multiplication.
Take note of what information is lost when some conversions take place.
'''
value_a = 90
value_b = 11.... | true |
f7e6225cdf68f34263c7b0d22d96b3dd5da27632 | royopa/python-2 | /ex5.py | 464 | 4.15625 | 4 | maior = None
menor = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
num=int(num)
except:
print('Invalid input')
else:
if menor is None:
menor= num
elif num < menor:
menor= num
if ma... | false |
d4c0dbee1de20b3fae2f2ae80f74d105463d4c07 | akhilkrishna57/misc | /python/cap.py | 1,727 | 4.21875 | 4 | # cap.py - Capitalize an English passage
# This example illustrates the simplest application of state machine.
# Scene: We want to make the first word capitalized of every sentence
# in a passage.
class State (object):
def setMappedChar(self, c):
self.c = c
def getMappedChar(self):
return self.c
def se... | true |
21ca29ba7a6e2a124a20291d11490a4eefabe4d3 | jhanse9522/toolkitten | /Python_Hard_Way_W2/ex8.py | 1,364 | 4.53125 | 5 | formatter = "{} {} {} {} " # this is the equivalent of taking a data of type str and creating positions (and blueprints?) for different arguments that will later be passed in and storing it in a variable called
#formatter
print(formatter.format(1, 2, 3, 4)) #The first argument being passed in and printed is of dat... | true |
06efc287d6c51abc7851cbccbece718179a9e4a0 | jhanse9522/toolkitten | /Python_Hard_Way_W2/ex16.py | 1,368 | 4.3125 | 4 | from sys import argv
script, filename = argv
print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (>C).")
print("If you do want that, hit RETURN.") #print statement doesn't ask for input. Only to hit the return key, which is what you would normally hit after entering user input. (or qu... | true |
0ba974b7a198bea2c267cb0a1d87c719c6bef25e | jhanse9522/toolkitten | /Python_Hard_Way_W2/ex15a.py | 1,171 | 4.65625 | 5 | filename = input("What's the name of the file you want to open?")
txt = open(filename) #the open command takes a parameter, in this case we passed in filename, and it can be set to our own variable. Here, our own variable stores an open text file. Note to self: (filename) and not {filename} because filename is alread... | true |
5801328332c67f3402892bab049ad7bcc2fa4514 | Giselii/numero-maior-e-menor | /033_NumeroMaioreMenor.py | 1,218 | 4.125 | 4 | #Faça um programa que leia três números e mostre qual é o maior e qual é o menor
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número:'))
n3 = int(input('Digite outro número: '))
#print('O maior número é {}'.format(max(n1, n2, n3)))
#print('O menor número é {}'.format(min(n1, n2, n3)))
if (n1 < n2)... | false |
8c035e7b062f86d4c90b504d16f5f4fa29e5a3f1 | AliZet-to/Homework2 | /Task_3.py | 1,196 | 4.25 | 4 | # Data input
side_AB_len = float(input("Please input AB side length \n"))
side_BC_len = float(input("Please input BC side length \n"))
side_AC_len = float(input("Please input AC side length \n"))
# Verification for a triangle existence
if (side_AB_len + side_BC_len) > side_AC_len and (side_BC_len + side_AC_len) > side... | false |
d9d9b96ebb5380d242f5532e475bb0a3f7547a01 | Nixer/lesson01 | /dictionaries.py | 358 | 4.125 | 4 | my_dict = {"city": "Москва", "temperature": "20"}
print(my_dict["city"])
my_dict["temperature"] = str(int(my_dict["temperature"]) - 5)
for k, v in my_dict.items():
print(f"{k} : {v}")
if "country" in my_dict:
print(True)
else:
print(False)
print(my_dict.get("country", "Россия"))
my_dict["date"] = "27.05.... | false |
63043be9d8b39e5caf053a06bd8129a27f0c4ffe | BSR-AMR-RIVM/blaOXA-48-plasmids-Microbial-Genomics | /scripts/printLine.py | 273 | 4.1875 | 4 | # quick code to print the lines that starts with >
import sys
FILE = sys.argv[1]
with open(FILE, 'r') as f:
count = 0
for line in f:
count =+ 1
if line.startswith(">"):
newLine = line.split(' ')
if len(newLine) < 3:
print(newLine)
print(count) | true |
b48bbe647eedb43c9e4adaa726842cfed8c38fd0 | Rythnyx/py_practice | /basics/reverseArray.py | 1,125 | 4.46875 | 4 | # The purpose of this excercise is to reverse a given list
exList = [1,2,3,4,5,6,7,8,9,10,'a','b','c','d','e','f','g']
# The idea here is to simply return the list that we had but step through it backward before doing so.
# This however will create a new list, what if we want to return it without creating a new one?
... | true |
787bb5e6c13463126b80c1144ae7a19274aab61b | ebonnecab/CS-2-Tweet-Generator | /regular-challenges/dictionary_words.py | 1,176 | 4.125 | 4 | #an algorithm that generates random sentences from words in a file
#TO DO: refactor code to use randint
import random
import sys
# number = sys.argv[:1]
number = input('Enter number of words: ') #takes user input
''' removes line breaks, and appends the words from the file to the list, takes five words from the list... | true |
b7bd042233235ec6d6b753ae4588c96645f0759d | alisatsar/itstep | /Python/Lessons/class/reloadOperators.py | 1,053 | 4.21875 | 4 | class Newclass():
def __init__(self, base):
self.base = base
def __add__(self, a): #позволяет добавлять к объекту значение
self.base = self.base + a
def __mul__(self, b): #позволяет объетку быть умноженным
self.base = self.base * b
def __sub__ (self, c): ... | false |
151172bdb8289efb3e3494a7c96db79c0d07de4c | kushrami/PythonProgramms | /LoanCalculator.py | 439 | 4.125 | 4 | CostOfLoan = float(input("Please enter your cost of loan = "))
InterestRate = float(input("Please enter your loan interst rate = "))
NumberOfYears = float(input("Please enter Number of years you want a loan = "))
InterestRate = InterestRate / 100.0
MonthlyPayment = CostOfLoan * (InterestRate * (InterestRate + 1.0) * N... | true |
d5c46b1068f3fa7d34ef2ef5151c1c0a825c88f5 | derpmagician/holbertonschool-higher_level_programming | /0x0B-python-input_output/0-read_file.py | 253 | 4.3125 | 4 | #!/usr/bin/python3
""" Reads an utf-8 formated file line by line"""
def read_file(filename=""):
"""Reads an UTF8 formated file line by line """
with open(filename, encoding='utf-8') as f:
for line in f:
print(line, end='')
| true |
8fc8ff320c25de0b3b15537fbbee03749721a9c1 | Aliena28898/Programming_exercises | /CodeWars_exercises/Roman Numerals Decoder.py | 1,816 | 4.28125 | 4 | '''
https://www.codewars.com/kata/roman-numerals-decoder
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be enc... | true |
24540c992ec687bd43c3b38674e1acef2f43dcb8 | Aliena28898/Programming_exercises | /CodeWars_exercises/Reversed Sequence.py | 298 | 4.25 | 4 | '''
Get the number n to return the reversed sequence from n to 1.
Example : n=5 >> [5,4,3,2,1]
'''
#SOLUTION:
def reverse_seq(n):
solution = [ ]
for num in range(n, 0, -1):
solution.append(num)
return solution
#TESTS:
test.assert_equals(reverse_seq(5),[5,4,3,2,1])
| true |
51bff2c710aa809cc0cf3162502a7acae518bf60 | AnaLuizaMendes/Unscramble-Computer-Science-Problems | /Task1.py | 1,011 | 4.25 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 1:
How many different telephone nu... | true |
18ad26f5f5613336ece2a9affadceb7282ab0a75 | aaishikasb/Hacktoberfest-2020 | /cryptography system/Crypto_system.py | 729 | 4.3125 | 4 | def machine():
keys = "abcdefghijklmnopqrstuvwxyz !"
values = keys[-1] + keys[0:-1]
encrypt = dict(zip(keys, values))
decrypt = dict(zip(values, keys))
option = input(
"Do you want to encrypt or decrypt, press e for encrypt and d for decrypt?")
message = input("what is the message you ... | true |
9f3fb321ae20fef315b17c48aada33418a993ec0 | sindaakyil/python | /pythonsets.py | 646 | 4.1875 | 4 | fruits = {'orange','apple','banana'}
print(fruits)
for x in fruits :
print(x)
fruits.add('cherry') #listeye ekler
fruits.update(['mango','grape','apple'])# listeye belirlenen elemanları ekler
fruits.remove('mango') #listeden mangoyu siler
fruits.discard('apple') # listeden apple siler
fruits.clear #bütün listeyi s... | false |
c0f8180687415dbc703433d7642329baedf9212f | MLHafizur/Unscramble-Computer-Science-Problems | /Task4.py | 1,528 | 4.1875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to i... | true |
99abf35d29cc6488acc5a7d230abd99688ca45ea | JKinsler/Sorting_Algorithms_Test | /merge_sort3.py | 1,508 | 4.15625 | 4 | """
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Merge sort
Sorting array practice
6/9/20
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Sort an unsorted array in O(nlogn) time complexity
Developer notes: this is my favorite way to organize the merge sort algorithm
because I think ... | true |
e0c5fc3a55327871f16b450def694a6dd97a8e5f | JKinsler/Sorting_Algorithms_Test | /merge_sort2.py | 1,353 | 4.15625 | 4 | """
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Merge sort
Sorting array practice
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Sort an unsorted array in O(nlogn) time complexity
"""
def merge_sort(arr):
"""
decompose the array into arrays of length 1
recombine the a... | true |
9601cc0074e5f52b7af909d3c35bc35b55c65a8c | Daozhou155/python-learn | /a6.py | 659 | 4.15625 | 4 | # !/usr/bin/env python
# -*-coding:utf-8-*-
# author: zjr time:2019/8/18
# 列表元素提取
list1 = [1, 2, ['a', 'b'], 123]
print(list1[2][1])
# 列表元素计数,不能计算列表中的列表
list2 = [123, 456, 789, [123, 111]]
list2 *= 5
a = list2.count(123)
print(a)
# 列表元素位置
list3 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list3.index(3, 0, 10))
# ... | false |
5a5c10e83e60d200ed4a722f8a018e43014d628d | Benedict-1/mypackage | /mypackage/sorting.py | 1,561 | 4.34375 | 4 | def bubble_sort(items):
'''Return array of items, sorted in ascending order'''
count = 0
for idx in range(len(items)-1):
if items[idx] > items[idx + 1]:
items[idx],items[idx + 1] = items[idx + 1],items[idx]
count += 1
if count == 0:
return items
else:
... | true |
8242e2eb55ad59d6c17497e56df4cc150fc78a33 | jpchato/data-structures-algorithms-portfolio | /python/array_shift.py | 766 | 4.3125 | 4 | '''
Feature Tasks
Write a function called insertShiftArray which takes in an array and the value to be added. Without utilizing any of the built-in methods available to your language, return an array with the new value added at the middle index.
Example
Input Output
[2,4,6,8], 5 [2,4,5,6,8]
[4,8,15,23,42], 16 [4,8,1... | true |
5332542eca544e73bb048cfeced7812d506d9943 | Ambush3/BMI-Calculator | /BMI calculator.py | 524 | 4.21875 | 4 | print("Lets find your BMI")
height = float(input("Enter your height in m: "))
weight = float(input("Enter your weight in kg: "))
bmi = weight/(height**2)
print("Your bmi is {0} and you are: ".format(bmi), end='')
if ( bmi < 18.5):
print("underweight.")
elif ( bmi >= 18.5 and bmi < 25 ):
print("nor... | false |
82f361fc9231541a923a2c071e14c9b8e6780f88 | cnagadya/bc_16_codelab | /Day_three/wordcount.py | 599 | 4.1875 | 4 | """ words function to determine the number of times a word occurs in a string"""
def words(input_string):
#dictionary template to display words as keys and occurances as values
words_dict = {}
#splitting string into list to enable iteration
words_list = input_string.split()
#iterate through the list to... | true |
3ba5adf3dfceea19a2d84aa3e983951341f10e92 | elvisasante323/code-katas | /python_code/regex.py | 515 | 4.4375 | 4 | # Learning about regex
import re
# Search the string to see if it starts with 'The' and ends with 'Spain'
text = 'The rain in Spain'
expression = re.search('^The.*Spain$', text)
if expression:
print('We have a match!\n')
else:
print('There is no match!\n')
# Find all lower case characters alphabetically betw... | true |
215950378bbcd2f020be5ebfb49cd5c7b5a9aa07 | cgisala/Capstone-Intro | /Lab1/Part2:_list_of_classes.py | 432 | 4.21875 | 4 | #Variable
choice = 'y' #Initializes choice to y
classes = [] #Declares an empty array
#Loops until the user enters 'n' for no
while(choice == 'y'):
semesterClass = input("Enter a class you are taking this semester: ")
classes.append(semesterClass)
choice = input("Do you want to add more y or n: ")
pri... | true |
ad9431376cb21d18ca9d6fa272bd7ea4ae01572f | BrunoAlz/design-patterns-python-master | /structural/adapter/adapter_1.py | 2,244 | 4.28125 | 4 | """
Adapter é um padrão de projeto estrutural que
tem a intenção de permitir que duas classes
que seriam incompatíveis trabalhem em conjunto
através de um "adaptador".
"""
from abc import ABC, abstractmethod
class IControl(ABC):
@abstractmethod
def top(self) -> None: pass
@abstractmethod
def right(se... | false |
972c11fb7b7ed641e65d1038bc92f5e777aaa5ca | BrunoAlz/design-patterns-python-master | /behavioral/strategy/strategy_1.py | 2,073 | 4.1875 | 4 | """
Strategy é um padrão de projeto comportamental que tem
a intenção de definir uma família de algoritmos,
encapsular cada uma delas e torná-las intercambiáveis.
Strategy permite que o algorítmo varie independentemente
dos clientes que o utilizam.
Princípio do aberto/fechado (Open/closed principle)
Entidades devem se... | false |
f494a23aa5ae7dd8e7f87e521fad4779e62c5118 | BrunoAlz/design-patterns-python-master | /behavioral/template_method/template_method_2.py | 1,909 | 4.3125 | 4 | """
Template Method (comportamental) tem a intenção de definir
um algoritmo em um método, postergando alguns passos
para as subclasses por herança. Template method permite
que subclasses redefinam certos passos de um algoritmo
sem mudar a estrutura do mesmo.
Também é possível definir hooks para que as subclasses
utili... | false |
57601ca144fda603bcd1822d4d1971873e23ddbc | SaiKrishnaBV/python-basics | /scopeOfVariable2.py | 656 | 4.34375 | 4 | '''
Understanding the concept of nonlocal variables(enclosed variables) inside nested functions
'''
z = 5
def in_func():
z = 10
print("In_func() --> local: z =",z)
def inner_func():
nonlocal z #to access enclosed variable instead of global variable
z+=1
print("Inner_func() --> z =",z)
def innermost_f... | false |
9e3b8d7aac17d3b5cef01341cc8452f9ac52cab6 | zrjaa1/Berkeley-CS9H-Projects | /Project2A_Power Unit Converter/source_to_base.py | 1,260 | 4.34375 | 4 | # Function Name: source_to_base
# Function Description: transfer the source unit into base unit.
# Function Input
# - source_unit: the unit of source, such as mile, cm.
# - source_value: the value in source unit.
# Function Output
# - base_unit: the unit of base, such as m, kg, L
# - base_value: the value in b... | true |
3191972f08fb2d8e4a6292c5bdd59aabdcb51688 | alfonso-torres/data_types-operators | /strings&casting.py | 1,937 | 4.65625 | 5 | # Strings and Casting
# Let's have a look at some industry practices
# single and double quotes examples
greetings = 'hello world'
single_quotes = 'single quotes \'WoW\''
double_quotes = "double quotes 'WoW'" # It is more easier to use
print(greetings)
print(single_quotes)
print(double_quotes)
# String slicing
gree... | true |
38322c01d2c410b06440fae9ce02faf2c8e045c4 | JamesPiggott/Python-Software-Engineering-Interview | /Sort/Insertionsort.py | 880 | 4.1875 | 4 | '''
Insertionsort.
This is the Python implementation of the Insertionsort sorting algorithm as it applies to an array of Integer values.
Running time: ?
Data movement: ?
@author James Piggott.
'''
import sys
import timeit
class Insertionsort(object):
def __init__(self):
print()
def ins... | true |
7a25d72e6a90603b908ec1e9d48f6c74c98d39b1 | ohveloper/python-alogorithm | /Inflearn/PreCourse/2depth_list.py | 309 | 4.125 | 4 |
a = [0] * 3
print(a)
# 2차원 list 만들기
b = [[0] * 3 for _ in range(3)]
print(b)
# 2차원 리스트 값에 접근
b[0][1] = 1
print(b)
b[1][2] = 2
print(b)
# 2차원 리스트를 표처럼 보이게 출력
for x in b:
print(x)
for x in b:
for y in x:
print(y, end=' ')
print() | false |
1bf9794ddf5f2cb1ef2c3c30725518fb8037e85e | ohveloper/python-alogorithm | /Inflearn/PreCourse/py_lambda.py | 308 | 4.1875 | 4 |
def plus_one(x):
return x+1
x = plus_one(1)
print(x)
# lambda 표현식으로 작성
plus_two = lambda x:x+2
print(plus_two(1))
# list와 map을 활용
a=[1,2,3]
print(list(map(plus_one,a)))
# list와 map에 lambda 활용
a=[1,2,3]
print(list(map(lambda x:x+2, a)))
print(list(map(int, ["1","2"]))) | false |
0c54a30b5564cf4fce07a4a22d90f2fee61fd27c | Caelifield/calculator-2 | /calculator.py | 1,170 | 4.21875 | 4 | """CLI application for a prefix-notation calculator."""
from arithmetic import (add, subtract, multiply, divide, square, cube,
power, mod, )
# Replace this with your code
def calculator():
while True:
input_string = input('Enter string:')
token = input_string.split(' ')
... | true |
204462c7d2e433cbb38fd5d0d1942cda5303b939 | VIPULKAM/python-scripts-windows | /count_lines.py | 759 | 4.21875 | 4 |
file_path='c:\\Python\\pledge.txt'
def count_lines(handle):
'''
This function returns the line count in the file.
'''
offset = 0
for line in handle:
if line:
offset += 1
continue
return offset
def count_occurnace(handle, word):
'''
This function returns... | true |
b6c9c3e78e9072babc666ddb7bf9a4e97bbbd0d6 | Telurt/python-fundamentos | /funcoes_primeira_classe_ordem.py | 935 | 4.4375 | 4 | """
Funções como objeto de primeira classe, são funçòes que se
comportam como qualquer tipo nativo de uma determinada linguagem
"""
def somar(a, b):
return a + b
def subtrair(a, b):
return a - b
# lista = [somar, subtrair]
# for funcao in lista:
# print(funcao(1,2))
# a = somar
# print(a(1,2))
"""
Funçõ... | false |
854838cba4d9a2f2abddfb86bccd1237e9140a4c | jofro9/algorithms | /assignment1/question3.py | 2,458 | 4.1875 | 4 | # Joe Froelicher
# CSCI 3412 - Algorithms
# Dr. Mazen al Borno
# 9/8/2020
# Assignment 1
import math
# Question 3
class UnitCircle:
def __init__(self):
self.TARGET_AREA_ = 3.14
self.RADIUS_ = 1.
self.triangles_ = 4.
self.iter = 0
### member functions for use throughout code ##... | true |
731beff49555f623448ce5cb13188586fa850201 | tabish606/python | /comp_list.py | 665 | 4.53125 | 5 | #list comprehension
#simple list example
#creat a list of squares
squares = []
for i in range(1,11):
squares.append(i**2)
print(squares)
#using list comprehension
squares1 = []
squares1 = [i**2 for i in range(1,11)]
print(squares1)
#NOTE : in list comprehension method the data is to be... | true |
077f37a82c31021b049710be0f385af0a202df8b | tabish606/python | /lamda.py | 610 | 4.15625 | 4 | #normal function
def add(a,b):
return a+b
print(add(4,3))
#lambda expression
add2 = lambda a,b : a+b #lambda function does not need name of function
print(add2(2,3))
multiply = lambda a,b : a*b
print(multiply(2,3))
# is even check
#def is_even(a):
# return a%2 == 0 #it return True if even ... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.