blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
d4d54e8aba42185e4cb6a5e556e1c3cbc6ced421 | talianassi921/python-practice | /Methods/bouncer.py | 276 | 4.125 | 4 | print("How old are you?")
age = int(input())
if age:
if age >=18 and age <21:
print("You can enter but need a wristband")
elif age>=21:
print("You can enter and drink")
else:
print("You can not enter")
else:
print("please enter an age") | true |
85761e99170d558e0ac85952c5b7f8b77cff08a9 | talianassi921/python-practice | /Methods/args.py | 531 | 4.15625 | 4 | # *args - special operator youc an pass to functions, gathers remaining arguments as a tuple
# args is a tuple of all the arguments
def sum_all_nums(*args):
total = 0
for num in args:
total +=num
return total
print(sum_all_nums(4,6))
print(sum_all_nums(5,1,4))
def ensure_correct_info(*args):
... | true |
2af0488f4996ac04670fb29af7f1a3a23d02782f | alejandroTo/python | /unidad1/metIntegrados.py | 613 | 4.21875 | 4 | #convertir un numero a binario
#los primeros dos caracteres indican que tipo de dato es
a = 10
print(bin(a))
#convertir un numero a hexadecimal
#los primeros dos caracteres indican que tipo de dato es
print(hex(a))
#convertir de binario a base 10 o normal
#en el primeros dos caracteres va el tipo a convertir
#en la seg... | false |
199378efaad8817d2cd61913481cb49d52f40a08 | ChoppingBroccoli/Python_Exercises | /Calc_Square_Root.py | 397 | 4.125 | 4 | user_response=float(input("Enter a number: "))
guess=user_response/2
accuracy=0.01
iteration=0
while abs(user_response-(guess**2)) > accuracy:
print("Guessed square root is:",guess)
guess=(guess+(user_response/guess))/2
iteration=iteration+1
print("Original number is: ", user_response)
print("Squar... | true |
21fa39452077c1183cfcc275ed79c6bda46798c3 | ChoppingBroccoli/Python_Exercises | /another for loop.py | 860 | 4.25 | 4 | # Receive input from the user
user_input = input("Enter a number:")
#Convert the user input from a str to a int
n = int(user_input)
#Initialize count to 0. count will store sum of all the numbers
count = 0
#Initialize iterations to 0. iterations will keep track of how many iterations it takes to complete th... | true |
40fdfef0505312f53ed56b03ec5c98698f8f80e9 | leeban99/python-practice | /function_list.py | 481 | 4.21875 | 4 | # Write your code here :-)
#Functions in list
def func():
print('Inside func')
def disp():
print('Inside disp')
def msg():
print('Inside msg')
lst = [func, disp, msg]
for f in lst:
f()
############################################
lst1 = [1,2,3,4,5,6]
lst2 = [9,8,7,6,5,4]
maplst = map(lambda n1,n2 : ... | false |
2fb43c8d11bf0b7629cee530490ad8b58f0d043e | jisshub/python-django-training | /code-snippets/phone_no_valid.py | 262 | 4.125 | 4 | # Phone number Validation
import re
def phone_num(phone):
regex = re.fullmatch('^[6-9]\d\d{5}', phone)
if regex is None:
return 'Invalid Phone'
else:
return 'Valid Number'
number = input('Enter Phone: ')
print(phone_num(number))
| true |
3fc1b978e652550c15fe35ddfb3c1546cbac35e9 | jisshub/python-django-training | /oops-python/operator_overloading.py | 1,611 | 4.3125 | 4 | # OPERATOR OVERLOADING
class Books:
def __init__(self, pages):
self.pages = pages
b1 = Books(300)
b2 = Books(400)
print(b1 + b2)
# here v cant add both the objects since it is an object type
# here can use special method or magic method called add()
# ie. __add__()
class Books:
def __init__(s... | true |
36ebbd30c49b486649326d084075f441739f39eb | jisshub/python-django-training | /regex/match_using_pipe.py | 1,310 | 5 | 5 | # Matching Multiple Groups with the Pipe
#
# The | character is called a pipe. You can use it anywhere you want to match one
# of many expressions. For example, the regular expression r'Batman|Tina Fey'
# will match either 'Batman' or 'Tina Fey' .
import re
pattern = re.compile(r'jiss|jose')
match = pattern.search('j... | true |
b07326cd738f97339c160e810093bace567efbf0 | goldgator/BinaryBattlesClient | /Question1.py | 331 | 4.21875 | 4 |
"""Greeting Name! [Easy]"""
"""Code a Function that takes a name(string) and adds a greeting"""
"""Ex: Input("Danny") --> Output = "Hey Danny!" """
"""Solution"""
def hello_name(name):
return "Hello {}!".format(name)
# Test
print(hello_name("Danny"))
print(hello_name("Gali"))
print(hello_nam... | false |
feaf84136bb18ef9712ea7f2bc687c7f4faaebfe | CBarreiro96/holbertonschool-higher_level_programming | /0x06-python-classes/5-square.py | 930 | 4.40625 | 4 | #!/usr/bin/python3
"""
Class square with follow restriction
Default size to 0. Raise error on invalid size inputs.
Methods Getter and Setter properties for size.
Methods of Area to find the size
Methods of print to pint #
"""
class Square:
"""A class that defines a square by size, which defaults 0.
Square can... | true |
b4fcdf4f4d64314d40ec3bff2bb3103c8003afe6 | Tvashta/cp | /BFS and DFS/LargestInLevel.py | 979 | 4.15625 | 4 | # You have a binary tree t. Your task is to find the largest value in each row of this tree.
# In a tree, a row is a set of nodes that have equal depth. For example, a row with depth 0 is a tree root,
# a row with depth 1 is composed of the root's children, etc.
# Return an array in which the first element is the larg... | true |
8120e1e0c841585435bcafa63e9a71a28904900a | nupurj24/comp110-21f-workspace | /exercises/ex01/relational_operators.py | 448 | 4.125 | 4 | """A program that shows how relational operators work."""
__author__ = "730391424"
a: str = input("Choose a whole number for the left-hand side of the equations. ")
b: str = input("Choose a whole number for the right-hand side of the equations. ")
c = int(a)
d = int(b)
print(a + " < " + b + " is " + str(c < d))
print(a... | true |
f4ee9c06880c6bbf9166658025cb80c3bf4c749b | imshaiknasir/PythonProjectx | /Basics/Constructor01.py | 359 | 4.28125 | 4 | #constructor in python...
class Truck:
brand = "BMW"
def __init__(self): #to create constructor is __init__(); this function will be executed while object creation
print("Constructor is executed first.")
def getName(self):
print("Simple method execution.")
obj = Truck() #constructor e... | true |
6511be165f3d7c476c8a6dfce32fd82a534c33f4 | SandeshKarumuri/Telusko-Python | /telusko/OOP/Operator Overloading.py | 824 | 4.125 | 4 | # a = 5
# b = 'th Dimension'
# print(a + b)
# print(int.__add__(a,b)) used for addition of two integers
class Student:
def __init__(self, m1, m2):
self.m1 = m1
self.m2 = m2
def __add__(self, other): # Student.__add__(self,other)
m1 = self.m1 + other.m1
m2 = self.m2... | false |
e622423eae6d1f6a2c82aab4fba13d446b45c05c | SteveChristian70/Coderbyte | /vowelCounter.py | 478 | 4.1875 | 4 | '''
Have the function VowelCount(str) take the str string parameter
being passed and return the number of vowels the string contains
(ie. "All cows eat grass" would return 5). Do not count y as a vowel for this challenge.
Use the Parameter Testing feature in the box below to test
your code with different arguments... | true |
629b337e0a0d4fedc8bfb38f3625640b0ad2f291 | ArunVasanthmdu/Python-Tricks | /numbertotext.py | 1,030 | 4.375 | 4 |
# Function to convert number to text
def convertValue(digit):
if digit == '0':
print("Zero ", end = " ")
elif digit == '1':
print("One ", end = " ")
elif digit == '2':
print("Two ", end = " ")
elif digit=='3':
print("Three",end=" ")
elif digit == '4':
... | false |
91ce4b1cf253455e9f528d8d34d258f1e09ac41c | redi-backend-python/celsius-fahrenheit-converter | /celsius-fahrenheit-converter.py | 719 | 4.25 | 4 | def print_celsius_values_with_signature(celsius):
if False: # Please add the condition
print("The celsius value you entered is positive")
elif False: # Please add the condition
print("The celsius value you entered is zero")
else:
print("The celsius value you entered is negative")
... | true |
f2f0d723ac0515704dfd0a64e8dc53840110112a | pagliuca523/Python--Intro-to-Comp-Science | /month_abbreviation.py | 316 | 4.1875 | 4 | #Program to show a short name for months
def main():
months = "JanFebMarAprMayJunJulAugSepOctNovDec"
usr_month = int(input("Please enter the month number (1-12): "))
usr_month = ((usr_month -1) * 3)
month_abbrev = months [usr_month:usr_month+3]
print("Month: {}".format(month_abbrev))
main() | false |
039e5d861330d79c47a6df234f14d41a7077650b | pagliuca523/Python--Intro-to-Comp-Science | /month_complete_name.py | 355 | 4.25 | 4 | #Program to show a long name for months
def main():
months = ("January","February","March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
usr_month = int(input("Please enter the month number (1-12): "))
usr_month = usr_month -1
#print(type(months)) -- Tuple
... | true |
906a54c881a62712a2fe243695a76d6c5c68f4e1 | pagliuca523/Python--Intro-to-Comp-Science | /vol_suf_sphere.py | 321 | 4.125 | 4 | import math
def main():
print("Calculus Sphere Volume & Surface")
radius = float(input("Please enter radius value: "))
#pi = 3.1415
volume_sph = ((4/3) * (math.pi * (radius**3)))
area_sph = 4*(math.pi*(radius**2))
print ("Volume = {}" "\nArea = {}".format(volume_sph,area_sph))
main(... | false |
93b662ec86fd09571214a98bf17ab609f9cc1256 | NotSvipdagr/Python-course | /mystuff/ex20.py | 2,618 | 4.5625 | 5 | # The below line imports the argv module from sys
from sys import argv
# The below line gives the argument variables to unpack using argv on the command line
script, input_file = argv
# The below line defines function "print_all" with one FuncVar "f"
def print_all(f):
# The below line prints/uses whatever value ... | true |
14b22a3a90b2065ab876dabc6a0d00280c050db8 | Harmandhindsa19/Python-online | /class6/assignment6.py | 1,672 | 4.15625 | 4 | #print the taken input to screen
l=[]
for x in range(10):
l.append(int(input("enter the element:")))
print(l)
#infinite loop
x=10
while True:
print("hello world")
x+=1
#list
list=[]
for i in range(6):
list.append(int(input("enter the element:")))
squarelist=[]
for i in range(6):
square... | true |
a1f4767db03a0eafa55d610176496a25b6d7aab2 | gadlakha/Two-Pointers-2 | /Problem2.py | 1,309 | 4.15625 | 4 | #Two Pointers 2
#Problem1 : https://leetcode.com/problems/merge-sorted-array/
#All test cases passed on Leetcode
#Time Complexity-O(N)
#Space Complexity-O(1)
class Solution:
def merge(self, nums1, m, nums2, n) :
"""
Do not return anything, modify nums1 in-place instead.
"""
... | true |
82968b5f157b80902e356e4a22d7ebe945772507 | zz45/Python-for-Data-Structures-Algorithms-and-Interviews | /Sentence Reversal.py | 1,048 | 4.28125 | 4 | # -*- coding: utf-8 -*-
'''
Given a string of words, reverse all the words. For example:
Given:
'This is the best'
Return:
'best the is This'
As part of this exercise you should remove all leading and trailing whitespace. So that inputs such as:
' space here' and 'space here '
both bec... | true |
c71d32560377d57ca57802fa196cc58610081680 | wangrui0/python-base | /com/day07/demo04_global_attention.py | 620 | 4.3125 | 4 | # 注意 全局变量定义的顺序:全局变量在函数调用之前定义就可以啦;故为了好看:我们一般在开头调用
a = 100
# b = 200
# c = 300
def test():
print("a=%d" % a)
print("b=%d" % b)
print("c=%d" % c)
b = 200
test()
c = 300 # 有问题
'''
a=100
Traceback (most recent call last):
b=200
File "C:/File/2-workspace/python/python-base/com/day07/demo04_global_atten... | false |
e99ba66f99a5ca461eb42a8b3ae25d4edcd825f2 | wangrui0/python-base | /com/day10/Demo13ClassPropertyObjectProperty.py | 711 | 4.34375 | 4 | """
实现记录创建对象个数的功能
"""
class Tool(object):
def __init__(self, new_name):
self.name = new_name
# 底下这个方法太笨啦
num = 0
tool1 = Tool("铁锹")
num += 1
print(num)
tool2 = Tool("工兵铲")
num += 1
print(num)
tool3 = Tool("水桶")
num += 1
print(num)
"""
1
2
3
"""
class Tool2(object):
"""
实例属性为某个类所有,对象共有
"... | false |
457755022b554a1df8f956ee5cc93949c2a8a9b8 | Xelanos/Intro | /ex2/quadratic_equation.py | 1,994 | 4.15625 | 4 | import math
def quadratic_equation(a, b, c):
"""A function that returns the solution/s of
an quadratic equation by using it's coefficients
"""
discriminant = math.pow(b, 2) - 4 * a * c # Discriminant variable
if a == 0:
first_solution = (-c) / b
second_solution = None
# no s... | true |
2bb86c4c828cc8fcd05f02c2f7bab3e209897721 | lucasjacintho/pyCamp | /Projetos/Session-05/18_calculadora_simples.py | 1,110 | 4.1875 | 4 | """
Problem: Faça um programa que mostre ao usuario um menu com 4 opções de operações matematicas
(as basicas, por exemplo). O usuario escolhe uma das opções e o seu programa então
pede dois valores numericos e realiza a operação, mostrando o resultado e saindo
Author: João Lucas
Pycamp
"""
print('==... | false |
eb5d0bc7c7d56a93e2c6b618292e32cd4cdf24fb | sdotpeng/Python_Jan_Plan | /Jan_26/Image.py | 1,880 | 4.40625 | 4 | # Images
# For the next weeks, we'll focus on an important area of computer science called image processing
'''
What is an image?
'''
'''
You are probably accustomed to working with .jpg, .gif, .png, and
other types of image on your computer
'''
'''
How do computers store the data that make up an image? It's represe... | true |
b6019fafc668be24a49ec0580281f4cf43284e05 | sdotpeng/Python_Jan_Plan | /Jan_19/shallow_copy.py | 657 | 4.46875 | 4 | my_list = [1,2,3,4,5]
# Shallow Copy
# my_list2 = my_list
# print("my_list:", my_list)
# print("my_list2:", my_list2)
# my_list2[2] = 99
# print("Assigning 99...")
# print("my_list:", my_list)
# print("my_list2:", my_list2)
# # Deep copy
# my_list2 = my_list.copy()
# print("my_list:", my_list)
# print("my_list2:"... | false |
1514457b8e3f3d13e3202c1201bb3e7fcd47ff73 | sdotpeng/Python_Jan_Plan | /Jan_14/loops.py | 1,046 | 4.25 | 4 | # Why do we need loops?
# Because it saves time for a repeated task
# for <loop index> in range(<number of loop iterations>):
# <loop body>
# range(number) returns an iterator
# for i in range(10):
# print(i)
# for element in [1,3,5]:
# print(element)
import turtle
window = turtle.Screen()
t = turtle.Turt... | false |
0efcdc8af2d92a5e90dd8cd093bfd1e073904ea2 | sdotpeng/Python_Jan_Plan | /LI_CS151Project1/Project01/extension2.py | 298 | 4.15625 | 4 | '''Draw an n-gon'''
import turtle
window = turtle.Screen()
t = turtle.Turtle()
def n_gon(side_length, num_side):
angle = 360 / num_side
for i in range(num_side):
t.forward(side_length)
t.right(angle)
n_gon(60, 18)
n_gon(30,5)
n_gon(40,12)
n_gon(20,6)
window.exitonclick() | false |
99c10717fb45b38ed64a5b91c294c5996eccd2e4 | kobaltkween/python2 | /Lesson 03 - Test Driven Development/testadder.py | 997 | 4.40625 | 4 | """
Demonstrates the fundamentals of unittest.
adder() is a function that lets you 'add' integers, strings, and lists.
"""
from adder import adder # keep the tested code separate from the tests
import unittest
class TestAdder(unittest.TestCase):
def testNumbers(self):
self.assertEqual(adder(3,4), 7,... | true |
37f3b9a8889fb1715439edb85a72eac1b72fd147 | steveflys/data-structures-and-algorithms | /sorting_algos/selection.py | 536 | 4.125 | 4 | """Do a selection sort of a list of elements."""
def selection_sort(my_list):
"""Define the selection sort algorithm."""
if len(my_list) < 2:
return my_list
for index in range(0, len(my_list)-1, +1):
index_of_min = index
for location in range(index, len(my_list)):
if my... | true |
2e56375e2bb4412f5634fe64f7051fc76ef54d99 | steveflys/data-structures-and-algorithms | /sorting_algos/radix_sort.py | 953 | 4.21875 | 4 | """Write a function that accepts an array of positive integers, and returns an array sorted by a radix sort algorithm."""
def radix_sort(my_list):
"""Define a radix sort."""
if len(my_list) < 2:
return my_list
RADIX = 10
maxLength = False
tmp = -1
placement = 1
while not ... | true |
bfcb1b39c27515ff0baeba72e18d72d092fc2aeb | viserati/obey | /ch1text.py | 1,769 | 4.375 | 4 | # Sample text to be analyzed.
text = """The first thing that stands between you and writing your first, real,
piece of code, is learning the skill of breaking problems down into
acheivable little actions that a computer can do for you. Of course,
you and the computer will also need to be speaking a common language,
bu... | true |
96abaf71b418165023b18d20d62656b8d86b3237 | Elvistor/ejerciciosPy | /listas_tuplas/Ejercicio_6.py | 935 | 4.34375 | 4 | """Escribir un programa que almacene las asignaturas de un curso
(por ejemplo Matemáticas, Física, Química, Historia y Lengua)
en una lista, pregunte al usuario la nota que ha sacado en cada asignatura y
elimine de la lista las asignaturas aprobadas.
Al final el programa debe mostrar por pantalla las asignaturas qu... | false |
8a8363ac9d3829f15629afa31c409c916ea31c9e | Elvistor/ejerciciosPy | /condicionales/Ejercicio_1.py | 237 | 4.125 | 4 | #Escribir un programa que pregunte al usuario su edad y muestre por pantalla si es mayor de edad o no.
edad = int(input("Ingrese su edad: "))
if edad >= 18:
print("Usted es mayor de edad.")
else:
print("Usted es menor de edad.") | false |
3520e85161da8905a37384c79a917d6150be0ba2 | Elvistor/ejerciciosPy | /string/Ejercicio_7.py | 465 | 4.125 | 4 | """Escribir un programa que pregunte el correo electrónico del usuario en la consola y muestre por
pantalla otro correo electrónico con el mismo nombre (la parte delante de la arroba @) pero con
dominio ceu.es"""
mail = input("Ingrese su mail: ")
if "@" in mail:
for letra in range(len(mail)):
if mail[let... | false |
57580c8a588560f4dab0389789e4efdfd1dfd21b | Elvistor/ejerciciosPy | /listas_tuplas/Ejercicio_8.py | 261 | 4.25 | 4 | """Escribir un programa que pida al usuario una palabra y muestre por pantalla si es un palíndromo."""
palabra = input("Ingrese una palagra: ")
if palabra.lower() == palabra[::-1].lower():
print("Es un palíndromo")
else:
print("No es un palíndromo") | false |
443c2c70bda52833f40ab1b99c827304ec649803 | Elvistor/ejerciciosPy | /listas_tuplas/Ejercicio_1.py | 329 | 4.3125 | 4 | """Escribir un programa que almacene las asignaturas de un curso
(por ejemplo Matemáticas, Física, Química, Historia y Lengua) en una lista y la muestre por pantalla"""
materias = []
while input("Desea agregar una materia?: ") == "s":
materias.append(input("Ingrese el nombre de la materia: "))
else:
print(mat... | false |
aeb6a963512560aef34639f66ce7928a100359f1 | Elvistor/ejerciciosPy | /listas_tuplas/Ejercicio_11.py | 287 | 4.15625 | 4 | """Escribir un programa que almacene los vectores (1,2,3) y (-1,0,2)
en dos listas y muestre por pantalla su producto escalar."""
x = (1,2,3)
y = (-1,0,2)
prod_escalar = 0
for a in range(len(x)):
prod_escalar += x[a] * y[a]
print(f"El producto escalar de x e y es: {prod_escalar}") | false |
02a0eb26186f1e94a1d9c58f2ba3fa2cfa72ddfa | mayrazan/exercicios-python-unoesc | /comparação/8.py | 465 | 4.1875 | 4 | produto1 = float(input("Qual o valor do produto 1 em R$? "))
produto2 = float(input("Qual o valor do produto 2 em R$? "))
produto3 = float(input("Qual o valor do produto 3 em R$? "))
if produto1 < produto2 and produto1 < produto3:
print("Você deve comprar o produto 1")
elif produto2 < produto1 and produto2 < prod... | false |
9e3101c4372ea5a241840ee7415bae874614e0be | shekhar316/Cyber-Security_Assignments_CSE_3rdSem | /Assignment_02/Solution_06.py | 337 | 4.15625 | 4 | #string is palindrome or not
def isPalindrome(string):
i = 0
j = len(string) - 1
flag = 0
while j >= i:
if not string[i] == string[j]:
flag = 1
i += 1
j -= 1
if (flag == 1):
print("String is not palindrome.")
else:
print("String is Palindrome.")
st = input("Enter the string : ")
i... | true |
d405d71afd926403cc81f83f5279086202b9d7b9 | jonlorusso/projecteuler | /problem00007.py | 800 | 4.1875 | 4 | #!/usr/bin/env
# 10001st prime
# Problem 7
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?
import math
from itertools import islice
def isprime(n):
if n == 1:
return False
for i in xrange(2, int(math.sqrt(n)... | true |
b1b741e7757f261aaf6376e14d3b14d82743db38 | jonlorusso/projecteuler | /problem00019.py | 2,083 | 4.21875 | 4 | #!/usr/bin/env python
# Counting Sundays
# Problem 19
# You are given the following information, but you may prefer to do some research for yourself.
# 1 Jan 1900 was a Monday.
# Thirty days has September,
# April, June and November.
# All the rest have thirty-one,
# Saving February alone,
# Which has twenty-eight, ... | false |
803e02d25fc177746dbca3ceba2b9ce9c9451788 | joao04joao/teste_das_aulas | /Aula01.py | 555 | 4.125 | 4 | # print('Olá, estou aprendendo Python!')
# FAÇA UM PROGRAMA QUE LEIA UM NOME E IMPRIMA: O SEU NOME É FULANO DE TAL
nome = input('Informe o nome:')
print('O seu nome é:', nome)
# FAÇA UM PROGRAMA QUE LEIA UM NÚMERO E IMPRIMA A FRASE: O NÚMERO INFORMADO É TAL
num = input('Informe o número: ')
print('O número inform... | false |
24f8941fca82fcc36e85574a14708e38dce6033e | lolNickFox/pythonWorkshop | /demo.py | 2,934 | 4.21875 | 4 |
# coding: utf-8
# Live Demo
# ---------
#
# Let's implement a function that returns the $n$th element of a certain series.
#
# The first two elements of the series are given:
#
# $$F_0 = 1, F_1 = 1$$
#
# The function returns $F_n$ such that:
#
# $$F_n = F_{n - 2} + F_{n - 1}$$
# In[13]:
def fibonacci(n):
... | true |
ab78a3d3e88d09367b3783bdf66de31dbcfed698 | psm18/16ECA_parksunmyeong | /lab 01 intro/08_streamplot_demo_features.py | 1,086 | 4.21875 | 4 | # -*- coding: utf8 -*-
"""
Demo of the 'streamplor' function.
A streamplot, or streamline plot, is used to display 2D vector fields, This
example shows a few features of the stream plot function:
*Varying the color along a streamline.
*Varying the desity of streamlines.
*Varying the line width along a st... | true |
d2ce0f86bc7aee4e348337ff2414e04696b1947e | tolik0/Lab_3 | /point.py | 417 | 4.125 | 4 | class Point:
"""
Class that represent point
"""
def __init__(self, x=0, y=0):
"""
(Point, float, float) -> NoneType
Create new point
"""
self.x = x
self.y = y
def distance(self, p):
"""
(Point, Point) -> float
Return distance ... | false |
032ec8b52b6a31902a63d98f1caba75830101d42 | riturajkush/Geeks-for-geeks-DSA-in-python | /hashing/Sorting Elements of an Array by Frequency.py | 1,388 | 4.125 | 4 | #User function Template for python3
'''
Your task is to sort the elements according
to the frequency of their occurence
in the given array.
Function Arguments: array a with size n.
Return Type:none, print the sorted array
'''
def values(dic):
return dic.values
def sortByFreq(arr,n):
dic ... | true |
70475137935f83421aaea43af6b5607ac606837c | www-wy-com/StudyPy01 | /180202_input_output.py | 1,233 | 4.21875 | 4 | # -*- coding: utf-8 -*-
import pickle
# 用户输入内容
def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
something = input('enter text: ')
if is_palindrome(something):
print('yes, this is palindrome')
else:
print('no, this is not a palindrome')
# 再议input
birth=input('... | true |
a96ffed047aae4ae9c795c20b13af35f168a9030 | bhargavraju/practice-py2 | /hashing/copy_list.py | 1,248 | 4.125 | 4 | """
A linked list is given such that each node contains an additional random pointer which could point to any node
in the list or NULL. Return a deep copy of the list.
Example
Given list
1 -> 2 -> 3
with random pointers going from
1 -> 3
2 -> 1
3 -> 1
You should return a deep copy of the list. The returned an... | true |
6c605d2e08388d3b94983568b1fd925184e23e55 | bhargavraju/practice-py2 | /arrays/insert_interval.py | 1,252 | 4.15625 | 4 | """
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9] insert and merge [2,5] would result in [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[... | true |
6285c75c7972f537d3a73ad89d2d938ee086be44 | zhgmyron/python_ask | /hellworld.py | 441 | 4.15625 | 4 | names=['mama','mike','jim']
def list_all(names):
print("--------")
for i in names:
print (i)
list_all(names)
absent=names.pop(1)
print(absent+"can't present the party")
names.append('mao')
list_all(names)
names.insert(0,'ba')
names.insert(2,'di')
names.append("chou")
list_all(names)
a=names.pop()
print... | true |
660fcf161264ed8b3315707172eabd77b1fd125e | JorJeG/python | /9/icecreamstand.py | 902 | 4.125 | 4 | class Restaurant(object):
"""Simple restaurant class"""
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print(self.restaurant_name)
print(... | false |
7effc9859d4c01502a739f97055913f0312a61ca | kk0174lll/codewars | /Infix to Postfix Converter/main.py | 1,413 | 4.15625 | 4 | '''
Construct a function that, when given a string containing an expression in infix notation,
will return an identical expression in postfix notation.
The operators used will be +, -, *, /, and ^ with standard precedence rules and
left-associativity of all operators but ^.
The operands will be single-digit integers b... | true |
4d738768501ceef38bda1496afefc3849cddc557 | OlegZhdanoff/algorithm | /lesson_2/task_3.py | 561 | 4.1875 | 4 | # 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если
# введено число 3486, надо вывести 6843.
def reverse(num):
if num // 10:
tmp = num
exp = 0
while tmp > 9:
tmp //= 10
exp += 1
return (num % 10) *... | false |
bad8984b8b21df30f8cd186a4efad8ee4e5b8b14 | Ntalemarvin/python | /list.py | 398 | 4.3125 | 4 | #LISTS
names = ['john','isaac','Marvin','frost','Mary','Benj']
print(names[4])
print(names[2:3])
print(names[:])
names[3]='frosts'
print(names)
#write a program to find the largest number in a list
numbers = [2,3,5,6,17,69,7,9,10,69,200,453,23,45]
'''lets assume the largest number is numbers[0]'''
max = numbers[0]... | true |
c112260af77340ed69565e507527486656cb43da | kidusasfaw/addiscoder_2016 | /labs/server_files_without_solutions/lab9/trionacci2/trionacci2_solution.py | 337 | 4.125 | 4 | import sys
# the input to this function is an integer n. The output is the nth trionacci number.
def trionacci(n):
# student should implement this function
###########################################
# INPUT OUTPUT CODE. DO NOT EDIT CODE BELOW.
n = int(sys.stdin.readline())
ans = trionacci(n)
sys.stdout.write(st... | true |
769173e701119ce1a7d0f12f310eed2c4adfc291 | Ttibsi/AutomateTheBoringStuff | /Ch.07 - Pattern Matching with Regular Expressions/FindPhoneNumberDividedIntoGroups.py | 649 | 4.15625 | 4 | # More Pattern Matching with Regular Expressions
import re
phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
phoneNumRegexWithBrackets = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)')
mo = phoneNumRegexWithBrackets.search('my number is (415) 555-4242')
#This gets the parenthesis sections of the regex, with it... | true |
e7f360ad026af0dab1c535b40445a55154c2da00 | katiaOlem/poo-1719110962 | /semana_codigos/manejo.py | 2,860 | 4.21875 | 4 | import math #Ayuda con las funciones matemáticas
lista_numeros=[]#Contador de los números
class NumerosError ():#Clase
def __init__(self): #Metodo Constructor
pass
def numeros_evaluar(self): #Metodo
try:#Declaracion de Try para identificar errores
numeros=int(input(" Ingrese el ... | false |
23970409685018fba3be8c38d9c2fa46a4dd3073 | shriya246/Python-internship-Best-Enlist | /Day8.py | 2,062 | 4.28125 | 4 | dict1={"a":1,"b":2}
dict2={"c":3,"d":4}
dict3=(dict2.update(dict1))
print(dict2)
#sorting and convert list into set
list1 = [4,3,2,1]
list2 =list1[::-1]
set1 = set(list2)
print(set1)
#3) program to list number of items in a dictionary key
names = {3:"a",2:"b",1:"c"}
list3 = dict.keys(names)
print("list of d... | true |
57acdcb38d4b52d2878b2ee8ee795af745fcd506 | alexguldemond/MA173A_Sample_Code | /python/data_structures/tuples.py | 457 | 4.375 | 4 | #!/usr/bin/python3
# Tuples are like lists, but they are immutable, i.e. cannot be changed
tup = (1, 2, "Hello")
# We can index them like lists
print(tup[1])
# But we cannot change them
# tup[0] = 3
# The above will error out
# Tuples can also be easily unpacked. This can be useful for getting several values out a... | true |
786f227d47997cb4c425bbfb5a86dd5ea4d079bc | alexguldemond/MA173A_Sample_Code | /python/printing/formatted_printing.py | 369 | 4.46875 | 4 | #!/usr/bin/python3
# Sometimes you want to print data without worrying about building strings.
# Formatted printing makes this convenient
datum1 = 1.1
datum2 = 1.2
datum3 = 1.3
# Note the prefix f, and the use of curly braces inside the string
print(f"Here is some data: {datum1}, {datum2}, {datum3}")
# Should print ... | true |
cdf12952bb23eb100f0087eeecb10d871abe0e5d | LuisMoranDev/Python-Projects | /Python Projects/Change.py | 1,192 | 4.125 | 4 | def changeBack():
cents = {"Quarters: ":.25, "Dimes: ":.10, "Nickels: ":0.05, "Pennies ": 0.01}
while True:
try:
cost = float(input("Enter the cost of the item: "))
except ValueError:
print("Cost must be an integer")
else:
if cost < 0:
print("The cost of the item must be greater than 0")
else:
... | true |
b5e8bbc2d21bbedb292067b7963fbcabe67138be | coryeleven/learn_python | /range.py | 832 | 4.375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2021/7/24 4:40 下午
# @File : range.py
# @Description :
# range() 指定步长,函数从2开始,每次加3,直至达到或不超过终值
#rang生成一个列表
even_numbers = list(range(2,20,3))
print(even_numbers)
# ** 乘方运算
squares = []
for values in range(1,11):
square = values**2
squares.append(square) #append 追加之列表元素的末尾
... | false |
94c8188c7661f1a499d8f80378e1ae3d0722b8f4 | coryeleven/learn_python | /input_while.py | 2,875 | 4.1875 | 4 | """
1.input str、int,求模运算符
2.while 循环
3.break continue结束或跳出循环
"""
#存储成一个变量提示信息 int
'''
prompt = "If you tell us who are you , we can personalize the message you see."
prompt += "\nWhat is your first name?\n"
name = input(prompt)
print(name)
height = input("How tall are you, in inches? ")
height = int(height... | true |
8a45ef85f2d529e5abfee8b8c2b64b94bd87d202 | micmor-m/Hangman | /main.py | 1,028 | 4.125 | 4 | import random
from hangman_words import word_list
from hangman_art import stages, logo
end_of_game = False
# word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
lives = 6
print(logo)
# print(f'The solution is {chosen_word}.')
display = []
for ch in chosen_word:
display.append("_")
... | true |
018a792e66958a5d8683eb50b0062806417586d2 | arcSlayer85/random_python_bits | /inchesToCms.py | 876 | 4.71875 | 5 | #! /usr/bin/python
"""
program that offers the user the choice of converting cm to inches or
inches to centimetres. Use functions for each of the conversion programs.
"""
# Function for cm's to inches...
def calculateCms ( int ):
_cm = _height * 2.54;
print (_cm);
# function for inches to cm'... | true |
0c971beb8153ccefa16c9ce4cafd459718021198 | DerianQM/algo_and_structures_python | /Lesson1/2.py | 645 | 4.34375 | 4 | # 2. Выполнить логические побитовые операции "И", "ИЛИ" и др.
# над числами 5 и 6. Выполнить
# над числом 5 побитовый сдвиг вправо и влево на два знака.
a = 5
b = 6
print(f"{a} имеет вид в битах {bin(a)}\n {b} имеет вид в битах {bin(b)}")
print(f"{a} И {b} = {a&b} в битах {bin(a&b)}")
print(f"{a} ИЛИ {b} = {a|b} в бит... | false |
8690cf0bf9a05db858172dd1e96b87e139e5eb6b | longchushui/How-to-think-like-a-computer-scientist | /exercise_0312.py | 646 | 4.40625 | 4 | #Write a program to draw a face of a clock that looks something like this:
import turtle # get the turtle module
# set up screen
wn = turtle.Screen()
wn.bgcolor("lightgreen")
# set up turtle
tess = turtle.Turtle()
tess.color("blue") # make tess blue
tess.shape("turtle") # now tess looks like a turt... | true |
f27a17b433ae7e6d8149eb9738d0859f4c016ceb | longchushui/How-to-think-like-a-computer-scientist | /exercise_0501.py | 733 | 4.46875 | 4 | # Assume the days of the week are numbered 0,1,2,3,4,5,6 from Sunday to Saturday.
# Write a function which is given the day number, and it returns the day name (a string).
def day_name(day_number):
""" The function day_name() returns the day_name {Sunday-Saturday} given
the day_number {0-6}.
"""
... | true |
c884357afb95680b5ffb0d2b4875305db8eefa9e | longchushui/How-to-think-like-a-computer-scientist | /exercise_0404.py | 603 | 4.28125 | 4 | import turtle
def draw_poly(t, n, sz):
""" The function draw_poly() makes a turtle t draw a regular polygon with n corners
of size sz.
"""
for i in range(n):
t.forward(sz)
t.left(360/n)
# set up screen
wn = turtle.Screen()
wn.bgcolor("lightgreen") # make the background gr... | true |
7b5bec25ca82e213e87aea54d4db5ca6106b05c9 | ctlnwtkns/itc_110 | /abs_hw/ch7/regexStriptest.py | 1,707 | 4.5 | 4 | '''
Write a function that takes a string and does the same thing as the strip()
string method (remove whitespace characters, i.e. space, tab, newline).
If no arguments are passed other than the string to
strip, then whitespace characters will be removed from the beginning and
end of the string.
Otherwise, the chara... | true |
72c0a270951ee86997d0cc30cccef052e29f4d31 | affiong/switch_affiong | /hangman1.py | 1,713 | 4.125 | 4 | import random
wordlist = "one two three four five six seven".upper().split()
random.shuffle(wordlist)
secret_word = wordlist.pop()
correct = []
incorrect = []
#print("DEBUG: %s" % secret_word)
def display_word():
#display random word
for i in secret_word:
if i in correct:
print(i, end=" "... | true |
dcaa2fe4a88600d9d2aba51c8b56031c39a9b089 | slickFix/Python_algos | /DS_ALGO/gcd.py | 470 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 8 19:34:01 2019
@author: siddharth
"""
# Implementing Greatest Common Divisor
def gcd(m,n):
if (m<n):
(m,n) = (n,m)
if (m%n==0):
return n
else:
return gcd(n,m%n) # gcd(m,n) = gcd(n,m%n)
if __name... | false |
cf3229f2a98ca503348020f2e821d5f1dcabe1d3 | pdefusco/Python | /app_development/lpth/ex24.py | 797 | 4.34375 | 4 | #putting concepts together:
print("This is a variation of the original exercise")
text = """Ma quanto e bello andare in giro per i colli bolognesi
\t se hai una vespa special che \n ti toglie i problemi
anche con l\'apopstrofo
"""
print("----")
print(text)
print("----")
result = 1**2+3**6
print("now doing some sim... | false |
88addc9e635a001adef7b8a0738130032830ef7d | pdefusco/Python | /app_development/lpth/ex11.py | 454 | 4.21875 | 4 | #working with inputs and printing the text
print("How old are you?", end= ' ')
age = input()
print("How tall are you?", end = ' ')
height = input()
print(f"The age is {age} and the height is {height}")
#now inputting numbers:
print("Let's do some math. Multuply value x times value y")
print('Assign value for x: ', ... | true |
34b2c0dfa65c7f51f4b6ed3ee54b64fd407882a9 | ShwetaAkiwate/GitDemo | /pythonTesting/write.py | 462 | 4.28125 | 4 | # read the file and store all the lines in list
#reverse the list
#write the list back to the file
with open('test.txt', 'r') as reader: # with is used for open the file, shortcut of "file = open('test.txt') file.close())"
content = reader.readlines() #[abc,bretwer,cere, derre,egrete]
reversed(content) #[e... | true |
c8ba9f5518d1e54101e500afd2341a5a5ac5827d | ShwetaAkiwate/GitDemo | /pythonTesting/demo2nd.py | 885 | 4.40625 | 4 |
values = [1, 2, "Krunal", 4, 5]
# list is data type that allows multiple values and can be different data type
print(values[0])
print(values[3])
print(values[-1]) # if you want to print last value in the list. this is shortcut
print(values[1:3])
values.insert(3, "shweta")
print(values)
values.append("End")
p... | true |
9b7adad9b27492dbe0ac4f5f232b9ed02e4c78d9 | BrodyCur/oop-inheritance | /class_time.py | 679 | 4.125 | 4 | class Person:
def __init__(self, name):
self.name = name
def greeting(self):
print(f"Hi my name is {self.name}.")
class Student(Person):
def learn(self):
print("I get it!")
class Instructor(Person):
def teach(self):
print("An object is an instance of a class.")
teacher = Instructor('Na... | true |
496c0f74a51698cb39a0cce23c6a462ac775f41b | MaxTyson/GH | /GH/HT_6/HT_6-2.py | 1,417 | 4.4375 | 4 | '''
Створити клас Person, в якому буде присутнім метод __init__ який буде
приймати * аргументів, які зберігатиме в відповідні змінні. Методи,
які повинні бути в класі Person - show_age, print_name, show_all_information.
Створіть 2 екземпляри класу Person та в кожному з екземплярів
створіть атребут profession.
'''
... | false |
7b1ed9f05b439119fbba39393cea3e7d5bc3bc27 | rtuita23/bicycle | /bicycle.py | 1,659 | 4.40625 | 4 | """
BICYCLE CLASS
TODO - A bicycle has a model name
TODO - A bicycle has a weight
TODO - A bicycle has a cost
TODO - Return as dictionary ()
"""
class Bicycle:
def __init__(self, modelName, weight, cost):
self.modelName = modelName
self.weight = weight
self.cost = cost
... | true |
72446ac72787e677c180957a9fd3d871f3dfd0ea | ThiruArasuGit/PYTHON | /Programs/dummy.py | 933 | 4.15625 | 4 | nlist = [1, 2, 0, 3, 0, 4]
print(nlist)
''' sum of min and max numbers'''
sumOf_min_max = max(nlist) + min(nlist)
print(f'Sum of min and max: {sumOf_min_max}')
''' Method:1 find sum of even numbers'''
even_lst = []
for i in range(len(nlist)):
if nlist[i] > 0 and nlist[i] % 2 == 0:
even_lst.append(nlist[... | false |
2a3186ce3f5f0c3c5bcae47810b04285541eac56 | gaolingshan/LeetcodePython | /500KeyboardRow.py | 1,239 | 4.15625 | 4 | '''
500. Keyboard Row
Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.
Example 1:
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
Note:
You may use one character in the keyboard more than once.
You may ... | true |
23a076b0d68ae363d2226119184ea976d5a6b1d7 | gaolingshan/LeetcodePython | /414ThirdMaximumNumber.py | 1,199 | 4.15625 | 4 | '''
414. Third Maximum Number
Difficulty: Easy
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.
Example 2:
Input: [1, 2... | true |
bb63af901b9acacc65d119ab5444da3bb25d20c6 | hyc121110/LeetCodeProblems | /String/isValidParentheses.py | 629 | 4.15625 | 4 | '''
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
'''
... | true |
ae871173fa6e77f1423dda6dcecfc0407e7d8239 | hyc121110/LeetCodeProblems | /Others/maxProduct.py | 864 | 4.28125 | 4 | '''
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
'''
def maxProduct(nums):
# initialize max product
r = nums[0]
# imax/imin stores the max/min product of subarray that ends with the current number A[i]
imax = imin = r... | true |
d215f6192e52fcfb423810ed9d3cef7bf453ddbb | hyc121110/LeetCodeProblems | /String/letterCombinations.py | 980 | 4.21875 | 4 | '''
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
'''
def letterCombinations(digits):
map_ = {
'2' : '... | true |
e2df8c6429a4423480779f58e94c207b78bf500e | hyc121110/LeetCodeProblems | /Array/subsets2.py | 721 | 4.21875 | 4 | '''
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
'''
def subsetsWithDup(nums):
# similar to subset.py but with sorting and checking
# if subset in result list or not
res = list()... | true |
2e4cd6eccf5231c205e6b8846224721b9516dd74 | chanhosuh/algorithms | /sorting/quicksort/utils.py | 1,383 | 4.125 | 4 | from random import randrange
def position_pivot(a, lo, hi, pivot=None):
"""
various possibilities, but here we select a reasonably
robust pivot selection methodology: median of three
After possibly several swaps, a[hi] is the "median"
value of a[lo], a[hi-1], a[hi].
Note:
- it's assumed ... | true |
1fc0c94d2dd509c2d8becbba0ed16b67fe3d02ef | misohan/Jmk | /dict_test.py | 789 | 4.34375 | 4 | # Create a dict directory which stores telephone numbers (as string values),
# and populate it with these key-value pairs:
directory = {
'Jane Doe': '+27 555 5367',
'John Smith': '+27 555 6254',
'Bob Stone': '+27 555 5689'
}
# Change Jane’s number to +27 555 1024
directory['Jane Doe'] = '+27 555 1024'
#... | true |
0471166b0d6f9d6252987d7ed81d8cc61e767c0f | ashrafm97/pycharm_oop_project | /dogs_class.py | 1,597 | 4.46875 | 4 | # abstract and create the class dog
# class Dog():
# pass
#initializing a Dog object
# dog_instance1 = Dog()
#print the Dog object
# print(dog_instance1)
# print(type(dog_instance1))
# you want to define classes on one side and run them on the other... you need to chop this code and place it in the run file... | true |
d6f148e6819e4e16c5a6fe547db13b7f54996a3a | pqGC/Core_python_programming | /python/6-15.py | 2,211 | 4.25 | 4 | #! /usr/bin/env python
# encoding:utf-8
import time
from datetime import date
def calcdate(string1,string2):
temp_list1 = string1.split('/')
temp_list2 = string2.split('/')
days_count = ""
first_date = date(int(temp_list1[2]),int(temp_list1[1]),int(temp_list1[0]))
second_date = date(int(temp_list2[2]),int(temp_li... | false |
cd9cbd6cbe29ed79ee8775368599218fe0e0a151 | duqcyxwd/python-practice- | /MaxProductOfThree.py | 1,884 | 4.28125 | 4 | #!/usr/bin/env python
# For example, array A such that:
# A[0] = -3
# A[1] = 1
# A[2] = 2
# A[3] = -2
# A[4] = 5
# A[5] = 6
# contains the following example triplets:
# (1, 2, 4), product is 1 * 2 * 5 = 10
# (2, 4, 5), product is 2 * 5 * 6 = 60
# Your goal is to find the maximal product of any triplet.
... | true |
2a10483d5ba863777c8bc3411ba5fa91e476df16 | ashish6194/pythonbasics | /chapter_04/01_comp_op.py | 351 | 4.3125 | 4 | name = input("What's your name? ")
if name == "Jessica":
print("Hello, nice to see you {}".format(name))
elif name == "Danielle":
print("Hello, you are a great person!")
elif name != "Mariah":
print("You're not Mariah!")
elif name == "Kingston":
print("Hi, {}, let's have lunch soon!".format(name))
else:... | true |
b9c455b5b293307355cea6d4a5239a4b86a2f9d5 | JeffreyAsuncion/CSPT15_Graphs_I_GP | /src/demos/demo1.py | 780 | 4.125 | 4 | """
You are given an undirected graph with its maximum degree (the degree of a node
is the number of edges connected to the node).
You need to write a function that can take an undirected graph as its argument
and color the graph legally (a legal graph coloring is when no adjacent nodes
have the same color).
The number... | true |
14bb42f59d4bdbc07ac76c43936e4cb347d63e10 | muigaipeter/Python_class | /workingfolder/classes/demo1.py | 1,505 | 4.21875 | 4 | #is a blue print in oop
#an object/instance
#syntax
#class name_of_the_class():
#the blue print attributes
class Person():
name = 'Developer'
d1 = Person()
d2 = Person()
print(d1.name)
print(d2.name)
#all classes has a function called _init_()
# which is always executed when the class is being ... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.