blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b8ecc471b73c1c9ff01b74835b490b29a803b8db | giovanna96/Python-Exercises | /Divisors.py | 279 | 4.125 | 4 | #Practice Python
#Create a program that asks the user for a number and then prints out a list of all the divisors of that number.
divisor = []
value = int(input("enter a number: \n"))
for i in range(value):
if value%(i+1)==0:
divisor.append(i+1)
print(divisor)
| true |
b4b8658f9f4ad759f4111193d3763690ad9265b3 | wahome24/Udemy-Python-Bible-Course-Projects | /Project 10.py | 1,420 | 4.4375 | 4 | #This is a bank simulator project using classes and objects
class Bank:
#setting a default balance
def __init__(self,name,pin,balance=500):
self.name = name
self.pin = pin
self.balance = 500
#method to deposit money
def deposit(self,amount):
self.balance += amount
print(f'Your new balance ... | true |
cebc11a76eba589bec28dd26b3a4bab75e1e5ee8 | shashankmalik/Python_Learning | /Week_4/Modifying the Contents of a List.py | 787 | 4.34375 | 4 | # The skip_elements function returns a list containing every other element from an input list, starting with the first element. Complete this function to do that, using the for loop to iterate through the input list.
def skip_elements(elements):
# Initialize variables
new_list = []
i = 0
# Iterate through the lis... | true |
4d540640c41d61c2472b73dceac524eb6494797e | chao-shi/lclc | /489_robot_cleaner_h/main.py | 2,788 | 4.125 | 4 | # """
# This is the robot's control interface.
# You should not implement it, or speculate about its implementation
# """
#class Robot(object):
# def move(self):
# """
# Returns true if the cell in front is open and robot moves into the cell.
# Returns false if the cell in front is blocked and r... | true |
93897a144a08baf27692f9dd52da610be41c0ad3 | p-perras/absp_projects | /table_printer/tablePrinter.py | 788 | 4.1875 | 4 | # !python3
# tablePrinter.py
# ABSP - Chapter 6
def print_table(table):
"""
Summary:
Prints a table of items right justified.
Args:
table (list): A 2d list of items to print.
"""
# Get the max length string of each row.
rowMaxLen = []
for row in range(len(table)):
... | true |
fc607af81e8f640a2dce4593f55301346b268054 | rubenhortas/python_examples | /native_datatypes/none.py | 759 | 4.53125 | 5 | #!/usr/bin/env python3
# None is a null number
# Comparing None to anything other than None will always return False
# None is the only null number
# It has its own datatype (NoneType)
# You can assign None to any variable, but you can not create other NoneType objects
CTE_NONE1 = None
CTE_NONE2 = None
if __name__ =... | true |
b4642af405871a89e0e22fc7a93763896ad1c240 | EngageTrooper/Basic_Calculator_Python | /Calculator_Fle.py | 820 | 4.15625 | 4 | def add(num1,num2):
return num1 + num2
def subtract(num1,num2):
return num1 - num2
def multiply(num1,num2):
return num1 * num2
def divide(num1,num2):
return num1 / num2
print("Please Select Operation -\n" \
"1.Add \n" \
"2.Subtract \n" \
"3.Multiply \n" \
"4.Divide \n" )
select = in... | false |
f86482889f39d990b99cd3ccb066a332e34eaf32 | pillofoos/Ejemplos | /TomaDecisiones.py | 636 | 4.1875 | 4 | #Archivo: TomaDecisiones.py
#Descripcion: Ejemplo en el que se muestra la utilizacion de la sentencia if, if..else, if..elif..else
# la funcion input y la utilizacion del depurador (antes y despues de conversion)
antiguedad = (int)(input("Ingrese la antiguedad en años:"))
if antiguedad > 5:
print("Le c... | false |
8f7e68843db46063d1ea23e20f305fda2408d991 | zhenghaoyang/PythonCode | /ex15.py | 1,317 | 4.15625 | 4 | # --coding: utf-8 --
#从sys模块导入argv
from sys import argv
#用户输入参数解包
script,filename = argv
#打开文件,赋值给txt
txt = open(filename)
#打印出文件名
print "Here's your file %r:"%filename
#打印出txt变量读取文件的文本
#txt.close()
print txt.read()
txt.close()
print "Type the filename again:"
#读取用户输入的参数
file_again = raw_input(">")
#读取用户输入的文件名,读取其中的文本,... | false |
cd22aa8ee2bc1ba44c8af3f5bd7d880c7edac4eb | krishnavetthi/Python | /hello.py | 817 | 4.5 | 4 | message = "Hello World"
print(message)
# In a certain encrypted message which has information about the location(area, city),
# the characters are jumbled such that first character of the first word is followed by the first character of the second word,
# then it is followed by second character of the first word and... | true |
f4fad1000ed28895c819b3bc71a98e7a9f3e87b6 | ofreshy/interviews | /hackerrank/medium/merge_the_tools.py | 2,042 | 4.46875 | 4 | """
Consider the following:
A string,
, of length where
.
An integer,
, where is a factor of
.
We can split
into substrings where each subtring, , consists of a contiguous block of characters in . Then, use each to create string
such that:
The characters in
are a subsequence of the characters in
.
An... | true |
06f8cf70cd26e9c71b989fcb63f7525fb4fc3fff | ofreshy/interviews | /interviewcake/apple_stock.py | 2,451 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Suppose we could access yesterday's stock prices as a list, where:
The values are the price in dollars of Apple stock.
A higher index indicates a later time.
So if the stock cost $500 at 10:30am and $550 at 11:00am, then:
stock_prices_yesterday[60] = 500
Write an efficient funct... | true |
7ddd97ed6cc317d4fdf9fc1731d8425d2eb3b6a4 | gunjan-madan/Namith | /Module4/1.3.py | 915 | 4.40625 | 4 | #Real Life Problems
'''Task 1: Delivery Charges'''
print("***** Task 1: *****")
print()
# Create a program that takes the following input from the user:
# - The total number of sand sack and cement sack
# - Weight of each sack [Hint: use for loop to get the weight]
# - Use a variable to which the weight of the sack... | true |
c8b8060d5aeb1374f0ef0bb89f436884e1b32748 | gunjan-madan/Namith | /Module2/3.1.py | 1,328 | 4.71875 | 5 | # In the previous lesson, you used if-elif-else statements to create a menu based program.
# Now let us take a look at using nested if-elif statements in creating menu based programs.
'''Task 1: Nested If-else'''
print()
print("*** Task 1: ***")
print()
#Make a variable like winning_number and assign any number to it b... | true |
552c0f6239df522b27684179f216efe7b10a7037 | gunjan-madan/Namith | /Module2/1.3.py | 1,705 | 4.21875 | 4 | # You used the if elif statement to handle multiple conditions.
# What if you have 10 conditions to evaluate? Will you write 10 if..elif statements?
# Is it possible to check for more than one condition in a single if statement or elif statement?
# Let's check it out
"""-----------Task 1: All in One ------------... | true |
f36fd365929003b92229a08a013b4cf1af4cc5bd | NasserAbuchaibe/holbertonschool-web_back_end | /0x00-python_variable_annotations/1-concat.py | 383 | 4.21875 | 4 | #!/usr/bin/env python3
"""Write a type-annotated function concat that takes a string str1 and a
string str2 as arguments and returns a concatenated string
"""
def concat(str1: str, str2: str) -> str:
"""[Concat two str]
Args:
str1 (str): [string 1]
str2 (str): [string 2]
Returns:
... | true |
31bc1789c9cddfef609d48fc36f7c1ecb0542864 | Lionelding/EfficientPython | /ConcurrencyAndParallelism/36a_MultiProcessing.py | 2,434 | 4.46875 | 4 | # Item 36: Multi-processing
"""
* For CPU intensive jobs, multiprocessing is faster
Because the more CPUs, the faster
* For IO intensive jobs, multithreading is faster
Because the cpu needs to wait for the I/O despite how many CPUs available
GIL is the bottleneck.
* Multi-core multi-threading is worse than single... | true |
368b25a3c24acd2bd61811676f685cb5083bbd46 | Lionelding/EfficientPython | /3_ClassAndInheritance/27_Private_Attributes.py | 1,778 | 4.28125 | 4 | # Item 27: Prefer Public Attributes Over Private Attributes
'''
1. classmethod has access to the private attributes because the classmethod is declared within the object
2. subclass has no direct access to its parent's private fields
3. subclass can access parents' private fields by tweeking its attribute names
4. Docu... | true |
3eabf8de3faf6c8bda2531a8a2292bd763113f2e | josiellestechleinn/AulasPython | /recebendo_dados_usuario.py | 1,241 | 4.40625 | 4 | """
Recebendo dados do usuário
input() -> todo dado recebido via input é do tio string
Em python, string é tudo que estiver entre:
- Aspas simples;
- Aspas duplas;
- Aspas simples triplas;
- Aspas duplas triplas;
Exemplos:
- apsas simples -> 'Josielle'
- aspas duplas -> "Josielle"
- aspas simples triplas -> '''Josiel... | false |
d1d051a33cc4da4eeec7a394394b976926ea51d8 | jenny-liang/uw_python | /week05/screen_scrape_downloader.py | 2,061 | 4.3125 | 4 | """
Assignment: choose one or both or all three. I suspect 2 is a lot harder, but
then you would have learned a lot about the GitHub API and JSON.
1. File downloader using screen scraping: write a script that scrapes
our Python Winter 2012 course page for the URLs of all the Python
source files, then downloads them a... | true |
ead0d989fc780cb3a237b09967d676a8fd2fe378 | inimitabletim/iii | /Numpy/4_change_array_shape.py | 290 | 4.1875 | 4 | # --- 變換陣列的形狀排列與維度 page.44
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
a_2d = a.reshape(3, 4)
print(a_2d)
print('\n')
a_3d = a.reshape(3, 2, 2)
print(a_3d)
print('\n')
a_2d_col = a.reshape(3, 4, order='F')
print(a_2d_col) | false |
86528dd845be83a71b90850b26a7880f85a0f758 | mk346/Python-class-Projects | /Guess_Game.py | 492 | 4.25 | 4 | secret_word ="trouser"
guess= ""
count=0
guess_limit = 3
out_of_guesses= False
print("HINT: I have two legs but i cant walk")
while guess!= secret_word and not(out_of_guesses):
if count<guess_limit:
guess = input("Enter Your Guess: ")
count+=1
else:
out_of_guesses= True
i... | true |
a8a4f8ecc948c07a6c8f96173bb2b6e32ee550aa | deepgautam77/Basic_Python_Tutorial_Class | /Week 1/Day 2/for_loop.py | 253 | 4.15625 | 4 | #for i in range(10):
# print("This is fun..")
#range() function
#print odd number from 0-100
for i in range(1,100,2):
print(i, end=' ')
#WAP to print even numbers from 2000-2500
#WAP to print odd numbers starting from 5200 and ending at 4800
| true |
d49cedb5535e851045d759e51e9a37f833f6c460 | deepgautam77/Basic_Python_Tutorial_Class | /Day 5/homework_1.py | 659 | 4.34375 | 4 |
#Create a phone directory with name, phone and email. (at least 5)
#WAP to find out all the users whose phone number ends with an 8.
#all the users who doesn't have email address. --done
d=[{'name':'Todd', 'phone':'555-1414', 'email':'todd@mail.net'},
{'name':'Helga', 'phone':'555-1618', 'email':'helga@mail.net'},
{'... | true |
694759e96c8e1988ff347b36ff6c50b55b113639 | deepgautam77/Basic_Python_Tutorial_Class | /Week 1/Day 2/simple_task.py | 294 | 4.3125 | 4 | # -273 degree celsius < invalid..
temp = float(input("Enter the temperature: "))
while temp<-273:
temp = eval(input(("Impossible temperature. Please enter above -273 degree celsius: ")))
print("The temperature of ",temp," Celsius in Farenheit is: ", 9/5*temp+32)
#break
#continue
#pass
| true |
802ac41bb0e8d2035d204bcff6f762736e66eb00 | s0513/python_basic | /answer/210616_買最多禮物_15min.py | 1,611 | 4.40625 | 4 | '''
題目:
小明和小華生完第一個孩子後非常高興,他們的兒子喜歡玩具,
所以小明想買一些玩具。他面前擺著許多不同的玩具,
上面標有它們的價格,他想用手上的錢最大程度地購買玩具。
給定玩具的價格清單和能夠花費金額,
確定他可以購買的最大禮物數量。
#註: 注意每個玩具只能購買一次。
Example:
玩具價格清單 = [ 1, 2, 3, 4 ]
手上的錢k = 7
所以預算為7個貨幣單位,他可以購買組合為[1、2、3]或[3、4],因此最多3個玩具。
限制:
1. 玩具清單n最長為10個項目
2. 玩具價格i最高100
3. 手上有的錢k最高150
'''
import random
#i = random.randin... | false |
63e63ec4a0340d36b1734eb6abe7abd0661abf43 | keylorch/python-101 | /5-tuples.py | 440 | 4.40625 | 4 | # Tuples
# Basic information and operations on Tuples in python
# Tuples are INmutable
myTuple = (1,2,3,4)
print("myTuple: ", myTuple)
print("min(myTuple): ", min(myTuple))
print("max(myTuple): ", max(myTuple))
print("sum(myTuple): ", sum(myTuple))
print("len(myTuple): ", len(myTuple))
print("1 in myTuple: ", 1 in m... | false |
6448d6558262935be6a409bfa47878d58db9fbf2 | san-smith/patterns_template | /factory_method/script.py | 1,110 | 4.125 | 4 | #coding: utf-8
"""
Типы строя
"""
class Culture:
"""
Культура
"""
def __repr__(self):
return self.__str__()
class Democracy(Culture):
def __str__(self):
return 'Democracy'
class Dictatorship(Culture):
def __str__(self):
return 'Dictatorship'
"""
Само правительство
"""
... | false |
00af72c64e08a9f15b7f869ed9745e3130e676e7 | markap/PythonPlayground | /language_features/decorator.py | 535 | 4.375 | 4 | """
a decorator example to multiply to numbers before executing the decorated function
"""
def multiply(n, m):
def _mydecorator(function):
def __mydecorator(*args, **kw):
# do some stuff before the real
# function gets called
res = function(args[0] * n, args[1] *... | true |
8c763d12a5708eaf31d2da130d47304f4414bd6b | sean-blessing/20210424-python-1-day | /ch07/classes/main.py | 640 | 4.1875 | 4 | from circle import Circle
class Rectangle:
"""Rectangle class holds length and width attributes"""
# above doctring is optional
area_formula = "area = length * width"
def __init__(self, length, width):
pass
self.length = length
self.width = width
def area(self):
""... | true |
b8387b9ee340e02727a089494ef37a9d80ed5de5 | sean-blessing/20210424-python-1-day | /ch01/rectangle-calculator/main.py | 352 | 4.15625 | 4 | print("Welcome to the area and perimeter calculator!")
choice = "y"
while choice == "y":
length = int(input("enter length:\t"))
width = int(input("enter width:\t"))
perimeter = 2*length + 2*width
area = length * width
print(f"Area:\t\t{area}")
print(f"Perimeter\t{perimeter}")
choice = in... | true |
6726b05dfc6576f5e64d65f86d2db85b6e580cb4 | guam68/class_iguana | /Code/Josh/python/lab17_palindrome_anagram.py | 813 | 4.125 | 4 | def check_palindrome():
word = input('Check and see if your word is a palindrome, give me a word\n>>').lower()
word_list = []
for i in word:
word_list.append(i)
reversed_word_list = word_list[::-1]
if reversed_word_list == word_list:
return True
else:
return False
# prin... | false |
a2939f9834efd995dce131b47835070982058687 | guam68/class_iguana | /Code/Richard/python/lab-road-trip_3.py | 1,609 | 4.21875 | 4 | """
author: Richard Sherman
2018-12-21
lab-road-trip.py, an exercise in sets and dictionaries,
finds the cities from an origin that are accessible by taking n 'hops'
"""
# this is the dictionary of sets of cities that can be reached from a given origin
# a pair are added to the original lab to facilitate testing
city_t... | false |
de513e18abf270601e74fc0e738dc4f6ef7c5c1a | guam68/class_iguana | /Code/Richard/python/lab25-atm.py | 1,914 | 4.34375 | 4 | """
author: Richard Sherman
2018-12-16
lab25-atm.py, an ATM simulator, an exercise in classes and functions
"""
import datetime
class ATM():
def __init__(self, balance = 100, rate = 0.01):
self.balance = balance
self.rate = rate
self.transactions = []
def check_withdrawal(self, amount)... | true |
164ff47a83bd250d278c32f37ecb28a1cb13e1b9 | guam68/class_iguana | /Code/nathan/pythawn/lab_03_grading.py | 1,016 | 4.15625 | 4 | #ask user for input needing a number between 50 and 100
grade = input('what was your grade? \n>')
#turn user input (string) into an integer
grade = int(grade)
#
# if grade >= 96:
# print('A+')
# elif grade == 95:
# print('A')
# elif grade >= 90:
# print('A-')
#
#lots of ifs and elifs to determine what to... | false |
bdf4fabb89d8d1d17131a525549a45e8ec38a334 | guam68/class_iguana | /Code/nathan/pythawn/lab_13_rot13.py | 1,050 | 4.3125 | 4 | #making rot13 function attached to dictionary
def rot13(user_string):
rot_dict = {'a': 'n',
'b': 'o',
'c': 'p',
'd': 'q',
'e': 'r',
'f': 's',
'g': 't',
'h': 'u',
'i': 'v',
... | false |
7a9349976447f50f8a54c6999aa1419e5e382f2e | guam68/class_iguana | /Code/Scott/Python/lab_11_simple_calculator_version2.py | 898 | 4.28125 | 4 | #lab_11_simple_calculator_version2.py
#lab_11_simple_calculator_lvl_1
#operator_dict = {'+': +,}
operator = input("What type of calculation would you like to do? Please enter '+', '-', '**', or '/' :")
operand_a = input('Please enter the first number:')
operand_b = input('Please enter the second number:')
operand_a... | true |
2eba7e9bccb0005fdf14007ee56046302fe2da97 | guam68/class_iguana | /Code/Scott/Python/lab6_password_generatory.py | 2,431 | 4.375 | 4 | #lab6_password_generatory.py
#1. acquire all possible characters
import random
import string
# n = input('How many characters would you like your password to have?:\n')
# n = int(n)
# character_list = list(string.ascii_lowercase) + list(string.digits) + list(string.punctuation)
# password = ''
# for c in range(0, n):
... | false |
d04a6a59d53ba2a8f1e969c17a945f5afaf589b9 | aeroswitch/GeekBrains | /1_Python_basics/6_OOP_Basics/Task2.py | 2,401 | 4.375 | 4 | """
2. Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина). Значения данных
атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными. Определить метод расчета
массы асфальта, необходимого для покрытия всего дорожного полотна. Использовать форм... | false |
791832ac4be5e5aea1049360ad832411becc7175 | aeroswitch/GeekBrains | /1_Python_basics/3_Functions/Task1.py | 1,217 | 4.4375 | 4 | """
1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. Числа запрашивать у
пользователя, предусмотреть обработку ситуации деления на ноль.
"""
def division(var_1, var_2):
"""Принимает два числа и возвращает результат их деления"""
try:
return var_1 / var_2
... | false |
b7816fc8efb71a1535030bc5c2a0dc583c29116c | yvette-luong/first-repo | /data-types.py | 668 | 4.1875 | 4 | """
Boolean = True or False
String = "Yvette"
Undefined = A value that is not defined
Integer = 132432
Camel Case = lower case first word and then capitalize each following word:
example: helloWorld
"""
"1231314"
Yvette = 123
Yvette
def helloYvette(): # this is a function, which is indicated by brackets
pr... | true |
4f3b7f5a2114e451ea26d078798405827063f9ba | jnthmota/ParadigmasProg | /Exercicio6/Ex2.py | 430 | 4.28125 | 4 | # 2 Defna a função div que recebe como argumentos dois números naturais m
# e n e devolve o resultado da divisão inteira de m por n. Neste exercício você não
# pode recorrer às operações aritmétcas de multplicação, divisão e resto da divisão
# inteira.
# Ex: div(7,2) = 3
def div( dividendo, divisor ):
return 0 if ... | false |
3c6d0774f7dd6da59fa5b32f3e37e389fe93f248 | davakir/geekbrains-python | /lesson-4/fifth.py | 648 | 4.28125 | 4 | """
Реализовать формирование списка, используя функцию range() и возможности генератора.
В список должны войти четные числа от 100 до 1000 (включая границы).
Необходимо получить результат вычисления произведения всех элементов списка
"""
from functools import reduce
def multiplication(multiplier_1, multiplier_2):
... | false |
5d726403aa52295dd2d32f3e6c2345dda7ef1bbc | davakir/geekbrains-python | /lesson-6/Employee.py | 1,277 | 4.25 | 4 | """
Employee больше подходит для сущности "сотрудник"
"""
class Employee:
_income = {}
def __init__(self, name, surname, position):
self.name = name
self.surname = surname
self.position = position
def set_income(self, salary, bonus):
self._income = {'salary': salary, 'bonus... | false |
7c263f8cb4c3eedce2b1cd3d678e90b57613bab6 | gdevina1/MIS3640-Repository | /Session 5/Session5InClass.py | 1,699 | 4.1875 | 4 | print("Session 5 - Functions II")
import turtle
bear = turtle.Turtle()
print(bear)
#for i in range(4): #the range has to be an integer
# bear.fd(100)
# bear.lt(90)
#for i in range(4):
# print(i)
#
#turtle.mainloop()
def square(t, length):
for i in range(4):
t.fd(length)
t.lt(90)
#sq... | false |
2e7839e32546b9cf8a790c16b71c24986d8f12cb | stevenhughes08/CIT120 | /work/python/unit7/SuperMarket.py | 1,337 | 4.28125 | 4 | # SuperMarket.py - This program creates a report that lists weekly hours worked
# by employees of a supermarket. The report lists total hours for
# each day of one week.
# Input: Interactive
# Output: Report.
# Declare variables.
HEAD1 = "WEEKLY HOURS WORKED"
DAY_FOOTER = "Day Total "
SENTINEL = "done" # Named cons... | true |
f25313f5260876e54141d6ee9a82cc2117d77521 | FelixTang-only/learn_py | /day9.py | 1,807 | 4.125 | 4 | # 函数的参数详细解读
# 位置参数
# def power(x):
# return x * x
# power(4)
# power(x, n)
# def power(x, n):
# s = 1
# while n > 0:
# n = n - 1
# s = s * x
# return s
# print(power(5, 2))
# 默认参数
# power(5)
# def power(x, n = 2):
# s = 1
# while n > 0:
# n = n - 1
# s = s * x
# ... | false |
a3d6d0d7062c1452341c59741ea67aada4dc9ed8 | danangsw/python-learning-path | /sources/8_loops/4_else_loop.py | 640 | 4.3125 | 4 | # Python supports `else` with a loops.
# When the loop condition of `for` or `while` statement fails then code part in `else` is executed.
# If `break` statement is executed then `else` block will be skipped.
# Even any `continue` statement within a loops, the `else` block will be executed.
count = 0
while count < 5:... | true |
2e4761e091c6838cfdedbd8bdd48c727a606afd5 | hjhorsting/Bootrain2 | /PythonBasics.py | 549 | 4.4375 | 4 | # 1. Write a code that outputs your name and surname in one line.
print("Harald Horsting")
# or:
print("Harald", "Horsting")
# 2. Write a 1-line code that outputs your name and surname in two separate lines by using
# a single print() call.
print("Harald \n Horsting")
# 3. Use print() function that returns the fol... | true |
0129054fc9cac41a867350212d2d11c4ac157f9f | Wanderson96/ATIVIDADE-COMPLETA | /LETRAS A B C D E.py | 1,229 | 4.15625 | 4 | dia = int(input("escreva o dia: "))
mes = int(input("escreva o mês: "))
ano = int(input("escreva o ano: "))
print("DATA: ",dia,'/',mes,'/',ano)
A = int(input("escreva a variavel A: "))
B = int(input("escreva a variavel B: "))
C = int(input("escreva a variável C: "))
print("MEDIA DAS VARIÁVEIS: ",(A+B+C)/3)
X = in... | false |
2c099c78fb2eff10a340d1ba214e333cfb17d720 | MarKuchar/intro_to_algorithms | /1_Variables/operators.py | 1,205 | 4.15625 | 4 | # Operators
# =, -, *, /, // (floor division)
# % (modulo): 'mod' remainder
# ** (power)
print(10 % 3) # 1
print(10 ** 2) # 100
print(100 // 3) # 33
print(100 - 5)
# = : assignment
number = 7
number = number + 3 # increment number by 3
number += 3 # increment number by 3
# -= : decrement operator
print("number =... | true |
5b25724eae900e42228b5687f4f2691b7bb10031 | MarKuchar/intro_to_algorithms | /8_Functions/functions.py | 1,050 | 4.28125 | 4 | # Functions are a very convenient way to divide your code into useful blocks, make it more readable and help 'reuse' it.
# In python, functions are defined using the keyword 'def', followed by function's name.
# "input --> output", "A reusable block of code"
def print_menu():
print("----- Menu -----")
print("... | true |
1d7501c04e7e41331f36b5085202c7c1da7aa91b | MarKuchar/intro_to_algorithms | /4_Tuples/tuples_basics.py | 970 | 4.34375 | 4 | # Tuples are almost identical to lists
# The only big difference between lists and tuples is that tuples cannot be modified (Immutable)
# You can NOT add(append), changed(replace), or delete "IMMUTABLE LIST"
# elements from the tuple
vowels = ("a", "e", "i", "o", "u") # consonants (b, c, d, ...)
print(vowels[0])
prin... | true |
e783da31a78d9b2f0f786c0a7f5b9a7bd707833e | MarKuchar/intro_to_algorithms | /1_Variables/variable_type.py | 883 | 4.3125 | 4 | # Data types
# There are many different data types in Python
# int: integer
# float: floating point (10.23, 3.14, etc)
# bool: boolean (True, False)
# str: a sequence of characters in quotes "aa", 'aa'
language = "en_us"
print(type(language)) # check the type of the variable
users = 10
"""
print(users + language) #... | true |
46f360e2ece2d5195fe417c92cc1b91cd1f467ae | Chauhan98ashish/Hacktoberfest_2020 | /newton_sqrt.py | 219 | 4.34375 | 4 | print("*****Square Root By Newton's Method*****")
x=int(input("Enter the number::>>"))
r=x
a=10**(-10)
while abs(x-r*r)>a:
r=(r+x/r)/2
print(r)
r=round(r,3)
print("Square root of {} is {}".format(x,r))
| true |
c7aa27a1bd3cb900533845dd60eada06f6773b7f | sairaj225/Python | /Regular Expressions/5Find_a_word_in_string.py | 307 | 4.28125 | 4 | import re
# if re.search("hello", "we have said hello to him, and he replied with hellora hello"):
# print("There is hello in the string")
# findall() returns list of all matches
words = re.findall("hello", "we have said hello to him, and he replied with hellora hello")
for i in words:
print(i)
| true |
6c7e393680152b14a04838a6406298cce3e9e3fb | sairaj225/Python | /Generators/1demo.py | 774 | 4.5625 | 5 | '''
Generators are used to create iterators,
but with a different approach.
Generators are simple functions which return an iterable set of items,
one at a time, in a special way.
'''
# If a function contains at least one yield statement
# It becames a Generator function.
# Generator function contains one or more yi... | true |
afc839d183e205f373d0d0431261cb9d26a2035c | sairaj225/Python | /Regular Expressions/12verify_phone_number.py | 251 | 4.125 | 4 | import re
# \w = [a-zA-Z0-9_]
# \W = [^a-zA-Z0-9_]
phone_number = "412-555-1212"
if re.search("\w{3}-\w{3}-\w{4}", phone_number):
print("It is a phone number")
if re.search("\d{3}-\d{3}-\d{4}", phone_number):
print("It is a phone number") | false |
65d380c3a9a7e96e88682e0d935fa3eb61f5eebd | sairaj225/Python | /Dictionaries/accessing.py | 299 | 4.25 | 4 | d = {
"name" : 'sairaju',
"roll no" : 225
}
print(d)
# Accessing the dictionary
print(d['roll no'])
print(d.get('name'))
# Changing the value of the dictionary key
d['name'] = "raje"
print(d)
# Adding new item into dictionary
d["class"] = "MCA"
print(d)
# Dictionary length
print(len(d)) | false |
f7917d704ac0e45d8b0ffc804eeac7dc65eac66b | Dnavarro805/Python-Programming | /Data Structures - Arrays/StringReverse.py | 358 | 4.1875 | 4 | # Problem: Create a funciton that reverses a string.
# Input: "Hi My Name is Daniel"
# Output: "lienaD si emaN yM iH"
def reverse(str):
reversed = []
for x in range (len(str)-1, -1, -1):
reversed.append(str[x])
return ''.join(reversed)
def reverse2(str):
return str[::-1]
print(reverse... | true |
dee9b44b301c333cd39a4f05808b6e3aa1621075 | LeeSinCOOC/My_File_Library | /Python_排序算法/selection.py | 729 | 4.125 | 4 | def selection_sort(arr):
'''
1.首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置
2.然后,再从剩余未排序元素中继续寻找最小(大)元素
3.然后放到已排序序列的末尾。
4.以此类推,直到所有元素均排序完毕。
'''
for i in range(len(arr)-1):
minIndex=i
for j in range(i+1,len(arr)):
if arr[minIndex]>arr[j]:
minIndex=j
if i=... | false |
2402ee630147b2b855b0d5b0413bf1bbbdad179c | memomora/Tarea2 | /E3_S4.py | 2,221 | 4.3125 | 4 | '''
Escriba una función en Python que permita determinar si un número es perfecto o no. Un
número perfecto es un número entero positivo cuyo valor es igual a la suma de todos sus divisors
enteros positivos. (https://es.wikipedia.org/wiki/Número_perfecto)
'''
print("========================================")
print("= ... | false |
53f1c9eee659d35d7ed4b563d21a6e4502d811e5 | nolanroosa/intermediatePython | /hw21.py | 1,835 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 12 16:59:35 2020
@author: nolanroosa
"""
# Question 1
import pandas as pd
pop = pd.read_csv("/Users/nolanroosa/Desktop/Python/pop.csv")
def menu():
print ('''
Population Menu:
1. Display the entire... | true |
e50af84ac8ce77f08597c3ef94481e5aef55fd48 | yogeshBsht/CS50x_Plurality | /Plurality.py | 1,469 | 4.34375 | 4 | # Plurality
max_candidates = 5
candidates = ['Lincoln', 'Kennedy', 'Bush', 'Obama', 'Trump', 'Biden']
# Taking number of candidates as input
flag = 1
while flag:
num_candidates = int(float(input("Enter number of candidates: ")))
if num_candidates < 2:
print("Value Error! At least 2 candidate... | true |
9a8686df420357ee5df29a2d351bc47d9502c9af | chrylzzz/first_py | /day14/3.自定义异常.py | 550 | 4.15625 | 4 | """
抛出自定义异常的语法为 raise 异常类对象
"""
##长度小于3抛出异常
class SIError(Exception):
def __init__(self, len, min_len):
self.len = len
self.min_len = min_len
def __str__(self):
return f'你输入的长度是{self.len},不能少于{self.min_len}'
def main():
try:
con = input('输入密码: ')
if len(con) < ... | false |
d8fd09cbd25c6fe085aacf33768aedcc713b7e04 | jurbanski/week2 | /solution_10.py | 2,721 | 4.34375 | 4 | #!/usr/local/bin/python3
# 2015-01-14
# Joseph Urbanski
# MPCS 50101
# Week 2 homework
# Chapter 8, Question 10 solution.
# Import the sys module to allow us to read the input filename from command line arguments
import sys
# This function will prompt the user for a filename, then check to see if the file exists. I... | true |
e8e74b30ac6da31bb4907216ea45f4a3136c23cb | eembees/molstat_water | /rotation.py | 2,600 | 4.15625 | 4 | ## rotation.py Version 1.0
## Written by Magnus Berg Sletfjerding (eembees)
###########################################################
"""Rotation Functions, inspired by
http://paulbourke.net/geometry/rotate/
Verified as working 01/07/17 by eembees"""
"""Importing modules"""
import numpy as np
from math import pi, si... | true |
7c57ed755f03c05a03c281e2b9a03529f8b441a2 | Re-Creators/ScriptAllTheThings | /Temperature Scale Converter/temperature_scale_converter.py | 1,211 | 4.5 | 4 | """
Temperature Scale Converter
- Inputs the value from the user and converts it to Fahrenheit,Kelvin & Celsius
Author : Niyoj Oli
Date : 01/10/21
"""
temp = input("Input the temperature you would like to convert? (e.g., 45F, 102C, 373K ) : ")
degree = float(temp[:-1]) # the first value of the input is taken as th... | true |
efc8169de6a436f2ba9910ae37a8526d92bd7456 | JuliasBright/Python | /Simple Calculator.py | 1,685 | 4.3125 | 4 | import sys
while True:
print("Welcome To My Simple Calculator")
print("Enter this Abbreviations To Continue")
print("Enter + for Adding")
print("Enter - for Substractiing")
print("Enter * for Multiplication")
print("Enter / for Dividing")
print("Enter ** for Exponation")
print("... | true |
5a5bfac15fdf423e125b8aa56655bdb3dbccff7a | Gagan-453/Python-Practicals | /Searching names from a list.py | 1,103 | 4.1875 | 4 | # Searching elements in a list
lst=['Gagan Adithya', 'Advith', 'Harsha', 'Praveen']
for i in range(len(lst)):
lst[i] = lst[i].lower() #Converting all the names in the list into lower case letters
print(lst)
x = input("enter element to search:")
x = x.lower() #Converting all the letters into lower case... | true |
3756486b3c91b557bff353dff8708ef25cca9a32 | Gagan-453/Python-Practicals | /GUI/Canvas/Creating oval.py | 1,375 | 4.875 | 5 | # Creating Oval using Canvas
from tkinter import *
#Create a root window
root = Tk()
# var c is Canvas class object
# root is the name of the parent window, bg is background colour, height is the height of the window and width is the breadth of window, cursor represents the shape of the cursor in the canvas
c = Canva... | true |
52a149c679fb0740c4dc8685c485ee583ce9a66b | Gagan-453/Python-Practicals | /Abstract Class example.py | 1,041 | 4.34375 | 4 | # Example of Abstract Class
from abc import*
class Car(ABC):
def __init__(self, regno):
self.regno = regno
def opentank(self):
print('Fill the fuel into the tank')
print('For the car with regno ', self.regno)
@abstractmethod
def steering(self):
pass
... | false |
44c151aff1f59e0ca9418405b9a4d7ba2ce98f30 | Gagan-453/Python-Practicals | /GUI/Canvas/Creating images.py | 939 | 4.125 | 4 | #We can display an image with the help of create_image function
from tkinter import *
#Create a root window
root = Tk()
#Create Canvas as a child to root window
c = Canvas(root, bg='white', height=700, width=1200)
#Copy images into files
file1 = PhotoImage(file="Peacock.png")
file2 = PhotoImage(file='Screenshot (40).... | true |
554f38054fbb5da57d3a88668beb4acae711007d | Gagan-453/Python-Practicals | /GUI/Frame/Frame and Widget.py | 1,701 | 4.375 | 4 | # FRAME Container
#a frame is similar to canvas that represents a rectangular area where some text or widgets can be displayed
from tkinter import *
#Create root window
root = Tk()
#Give a title for root window
root.title('Gagan\'s frame')
#Create a frame as child to root window
f = Frame(root, height=400, width=50... | true |
21e92d5add01747577aac38d6d9e46180f0492eb | Gagan-453/Python-Practicals | /GUI/Frame/Listbox Widget.py | 2,547 | 4.40625 | 4 | # LISTBOX WIDGET
# It is useful to display a list of items, so that he can select one or more items
from tkinter import *
class ListBox:
def __init__(self, root):
self.f = Frame(root, width=700, height=400)
#Let the frame will not shrink
self.f.propagate(0)
# Attach the f... | true |
d96e1b7876aebe651540e50fa717d03bd162c853 | Gagan-453/Python-Practicals | /GUI/Frame/Button Widget/Arranging widgets in a frame/Place layout manager.py | 1,899 | 4.5625 | 5 | # PLACE LAYOUT MANAGER
# Place layout manager uses place() method to arrange widgets
#The place() method takes x and y coordinates of the widget along with width and height of the window where the widget has to be displayed
from tkinter import *
class MyButton:
#Constructor
def __init__(self, root):
#... | true |
c0309348cb3d4dba07c8d321cbc157e5dbdd6d0f | Gagan-453/Python-Practicals | /GUI/Frame/Menu Widget.py | 1,979 | 4.1875 | 4 | # MENU WIDGET
# Menu represents a group of items or options for the user to select from.
from tkinter import *
class MyMenu:
def __init__(self, root):
# Create a menubar
self.menubar = Menu(root)
# attach the menubar to the root window
root.config(menu=self.menubar)
... | true |
56b0a0a2582b0e26197affa6d27865dbfe5abb26 | Gagan-453/Python-Practicals | /Date and Time.py | 2,356 | 4.5625 | 5 | #The epoch is the point where the time starts
import time
epoch = time.time() #Call time function of time module
print(epoch) #Prints how many seconds are gone since the epoch .i.e.Since the beginning of the current year
#Converting the epoch into date and time
# locatime() function converts the epoch time into time_s... | true |
ec4fc0042d9e6100b485588b60be49413925bcb7 | Gagan-453/Python-Practicals | /Exceptions.py | 2,030 | 4.59375 | 5 | # Errors which can be handled are called 'Exceptions'
# Errors cannot be handled but exceptions can be handled
#to handle exceptions they should be written in a try block
#an except block should be written where it displays the exception details to the user
#The statements in thefinally block are executed irrespective... | true |
b3a045b0649342236300272420e3d5ecdb13f65d | sabbir421/python | /if elif else.py | 313 | 4.1875 | 4 | day=int(input("number of day: "))
if day==1:
print("Saturday")
elif day ==2:
print("Sunday")
elif day ==3:
print("Monday ")
elif day ==4:
print("Tuesday ")
elif day ==5:
print("Wednesday ")
elif day ==6:
print("Tuesday")
elif day ==7:
print("Friday ")
else:
print("7 days in week") | false |
58d37c8c9a0be25faee85b7d15e6a1958cbf466f | harshbhardwaj5/Coding-Questions- | /Allsubarrayrec.py | 501 | 4.15625 | 4 | # Python3 code to print all possible subarrays
def printSubArrays(arr, start, end):
# Stop if we have reached the end of the array
if end == len(arr):
return
# Increment the end point and start from 0
elif start > end:
return printSubArrays(arr, 0, end + 1)
# Print the subarray and inc... | true |
93fe621719192fd6fc2a29f328bdb0181be8ba54 | ncamperocoder1017/CIS-2348 | /Homework1/ZyLabs_2_19.py | 1,885 | 4.125 | 4 | # Nicolas Campero
# 1856853
# Gather information from user of ingredients and servings amount
print('Enter amount of lemon juice (in cups):')
l_juice_cups = float(input())
print('Enter amount of water (in cups):')
water_cups = float(input())
print('Enter amount of agave nectar (in cups):')
agave_cups = float(input())
... | true |
73f2fa07999ca1fcc2bc2f8bf0abd832276bd149 | juliagolder/unit-2 | /unitConverter.py | 938 | 4.46875 | 4 |
#julia golder
#2/14/18
#unitConverter.py - how to convert units
print('1: kilometers to Miles')
print('2: Kilograms to Pounds')
print('3: Liters to Gallons')
print('4: Celsius to Fahrenheit')
number = int(input('Choose a number: '))
if number == 1:
celcius = int(input('Enter Degrees in Celcius: '))
fahrenh... | false |
e38197efcd64d6ad928d207bf789273cb0a6fb08 | cr8ivecodesmith/basic-programming-with-python | /lpthw/ex11.py | 756 | 4.25 | 4 | # Exercise 11: Asking questions
print('How old are you?', end=' ')
age = input()
print('How tall are you?', end=' ')
height = input()
print('How much do you weigh?', end=' ')
weight = input()
print("So you're %r old, %r tall and %r heavy." % (age, height, weight))
# Note
# Notice that we put an end=' ' after the str... | true |
637c98c17ed65d72a4538fb19958ed10198a017b | onkcharkupalli1051/pyprograms | /ds_nptel/test 2/5.py | 676 | 4.28125 | 4 | """
A positive integer n is a sum of three squares if n = i2 + j2 + k2 for integers i,j,k such that i ≥ 1, j ≥ 1 and k ≥ 1. For instance, 29 is a sum of three squares because 10 = 22 + 32 + 42, and so is 6 (12 + 12 + 22). On the other hand, 16 and 20 are not sums of three squares.
Write a Python function sumof3squares... | true |
812dde47bf82dde83275c5a6e5c445ef6a0171ab | onkcharkupalli1051/pyprograms | /ds_nptel/NPTEL_DATA_STRUCTURES_TEST_1/ques4.py | 580 | 4.34375 | 4 | """
Question 4
A list is a non-decreasing if each element is at least as big as the preceding one. For instance [], [7], [8,8,11] and [3,19,44,44,63,89] are non-decreasing, while [3,18,4] and [23,14,3,14,3,23] are not. Here is a recursive function to check if a list is non-decreasing. You have to fill in the missing ar... | true |
62edb5acaf0f4806e84966e822083a39cdf66805 | YhHoo/Python-Tutorials | /enumerate.py | 477 | 4.125 | 4 | '''
THIS IS enumerate examples****
it allows us to loop over something and have an automatic counter
'''
c = ['banana', 'apple', 'pear', 'orange']
for index, item in enumerate(c, 2): # '2' tell the enumerate to start counting from 2
print(index, item)
'''
[CONSOLE]
2 banana
3 apple
4 pear
5 orange
'''
c = ['... | true |
1dd0e6d8e73c6dbd174227baf893ad6695f56dab | thisguyisbarry/Uni-Programming | /Year 2/Python/labtest2.py | 2,048 | 4.5 | 4 | import math
class Vector3D(object):
"""Vector with 3 coordinates"""
def __init__(self, x, y, z):
"""Takes in coordinates for a 3d vector"""
self.x = x
self.y = y
self.z = z
self.magnitude = 0
def __add__(self, v2):
"""Adds two 3D vectors
(x+a, ... | true |
30e68edadbaba888f4e0c6b4f04e074a43051738 | The-Blue-Wizard/Miscellany | /easter.py | 627 | 4.40625 | 4 | #!/bin/python
# Python program to calculate Easter date for a given year.
# This program was translated from an *ancient* BASIC program
# taken from a certain black papercover book course on BASIC
# programming whose title totally escapes me, as that was
# during my high school time. Obviously placed in public
# domai... | true |
132c7a205f2f0d2926e539c172223fb505a0f2c1 | L-ByDo/OneDayOneAlgo | /Algorithms/Searching_Algorithms/Binary Search/SquareOfNumber.py | 1,338 | 4.25 | 4 | #Find the square of a given number in a sorted array. If present, Return Yes with the index of element's index
#Else return No
#Program using Recursive Binary Search
#Returns True for Yes and False for No
def BinarySearch(arr, left, right, NumSquare):
#check for preventing infinite recursive loop
if right >=... | true |
94e17585ee5d0fc214dea1cbc886bd8fa33af30e | EmreCenk/Breaking_Polygons | /Mathematical_Functions/coordinates.py | 2,277 | 4.5 | 4 |
from math import cos,sin,radians,degrees,sqrt,atan2
def cartesian(r,theta,tuple_new_origin=(0,0)):
"""Converts height given polar coordinate r,theta into height coordinate on the cartesian plane (x,y). We use polar
coordinates to make the rotation mechanics easier. This function also converts theta into ra... | true |
893fff12d545faa410309b4b2b087305e6ad99cc | AxiomDaniel/boneyard | /algorithms-and-data-structures/sorting_algorithms/insertion_sort.py | 1,596 | 4.59375 | 5 | #!/usr/bin/env python3
def insertion_sort(a_list):
""" Sorts a list of integers/floats using insertion sort
Complexity: O(N^2)
Args:
a_list (list[int/float]): List to be sorted
Returns:
None
"""
for k in range(1, len(a_list)):
for i in range(k - 1, -1, -1):
... | true |
deb7f660c0f607492dbbcd59c71936876c893b35 | Erik-D-Mueller/Python-Neural-Network-Playground | /Version1point0/initial.py | 1,363 | 4.3125 | 4 | # 02-12-2020
# following along to a video showing how to implement simple neural network
# this is a perceptron, meaning it has only one layer
import numpy as np
# sigmoid function is used to normalize, negatives values return a value below 1/2 and approaching zero, positive values return above 1/2 and approaching 1... | true |
1326800eed0a49d19b8e959f7d58e2e65195963a | ImtiazMalek/PythonTasks | /input.py | 215 | 4.375 | 4 | name=input("Enter your name: ")#user will inter name and comment
age=input("Enter your age: ")#and we are saving it under various variables
print("Hello "+name+", you are "+age+" years old")#it'll print the result | true |
45e52f554eee3a9c1153ab1fe29bedac254891a3 | sitati-elsis/teaching-python-demo | /inheritance.py | 760 | 4.1875 | 4 | class Parent():
def __init__(self,last_name,eye_color):
print ("Parent constructor called")
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print "%s %s" %(self.last_name,self.eye_color)
billy_cyrus = Parent("Cyrus","blue")
billy_cyrus.show_info()
class Child(Parent):
def __ini... | true |
1715e784d1614edae62ce5918e286ec187997c34 | doctorOb/euler | /P9-pythagoreanTriplet.py | 720 | 4.1875 | 4 | """There exists exactly one Pythagorean triplet for which a + b + c = 1000
Find the product abc."""
import math
def isPythagoreanTriplet(a,b,c):
"""determine if a < b < c and a^2 + b^2 = c^2
formally, a Pythagorean triplet"""
if a < b and b < c:
return (a**2 + b**2) == c**2
else:
return False
def solve(n)... | false |
2245c07a64384e77a44b9540fcd551f245492289 | ShimaSama/Python | /email.py | 344 | 4.3125 | 4 | #program to know if the email format is correct or not
email=input("Introduce an email address: ")
count=email.count('@')
count2=email.count('.')
end=email.rfind('@') #final
start=email.find("@")
if(count!=1 or count2<1 or end==(len(email)-1) or start==0):
print("Wrong email address")
else:
print(... | true |
5fc28ab298c14b482825b23bb6320ca32e50b514 | sudiptasharif/python | /python_crash_course/chapter9/fraction.py | 1,763 | 4.4375 | 4 | class Fraction(object):
"""
A number represented as a fraction
"""
def __init__(self, num, denom):
"""
:param num: integer numerator
:param denom: integer denominator
"""
assert type(num) == int and type(denom) == int, "ints not used"
self.num = num
... | true |
253e80b1f9ae499d49eb0d79c34b821e0c8dfb6d | waditya/HackerRank_Linked_List | /09_Merge_Sorted_LinkList.py | 2,952 | 4.28125 | 4 | """
Merge two linked lists
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method.
"""
def MergeLists(headA, headB):
... | true |
6647f2a03e8d08ca8807c5dad2c2a0694d264713 | SethGoss/notes1 | /notes1.py | 363 | 4.28125 | 4 | # this is a comment, use them vary often
print(4 + 6) # addition
print(-4 -5) #subtraction
print(6 * 3) #multiplication
print(8 / 3) #division
print(3 ** 3) #exponents - 3 to the 3rd power
print(10 % 3) #modulo gives the remainder
print(15%5)
print(9%4)
# to make variable, think of a name
name = input("Wh... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.