blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
73219c63946768b4458c9c4c9f30639a83829d19 | AndyLaneOlson/LearnPython | /Ch3TurtleShapes.py | 863 | 4.28125 | 4 | import turtle
#Set up my turtle and screen
wn = turtle.Screen()
myTurtle = turtle.Turtle()
myTurtle.shape("turtle")
myTurtle.speed(1)
myTurtle.pensize(8)
myTurtle.color("blue")
myTurtle.penup()
myTurtle.backward(400)
myTurtle.pendown()
#Make the turtle do a triangle
for i in range(3):
myTurtle.forward(100)
myT... | false |
c0994074084e337bba081ca44c37d2d4d8553f8f | xtom0369/python-learning | /task/Learn Python The Hard Way/task33/ex33_py3.py | 368 | 4.15625 | 4 | space_number = int(input("Input a space number : "))
max_number = int(input("Input a max number : "))
i = 0
numbers = []
while i < max_number:
print(f"At the top i is {i}")
numbers.append(i)
i = i + space_number
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}")
print("The ... | true |
27d0745e6199185dc5b1fb8d9739b2d0226fd606 | letaniaferreira/guessinggame | /game.py | 1,554 | 4.1875 | 4 | """A number-guessing game."""
# greet player
# get player name
# choose random number between 1 and 100
# repeat forever:
# get guess
# if guess is incorrect:
# give hint
# increase number of guesses
# else:
# congratulate player
import random
name = raw_input("Welcome, what is yo... | true |
567566abb3fad5fb82f4944fb222941988bf8fc8 | vokoramus/GB_python1_homework | /Homework__1/HW1-4.py | 458 | 4.25 | 4 | '''4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе.
Для решения используйте цикл while и арифметические операции.'''
n = int(input("Введите n: "))
max_char = n % 10
while n > 0:
last_chr = n % 10
if last_chr > max_char:
max_char = last_chr
n //= 10
print("max =... | false |
1532020913bb3d12e049d871a9d544fb0d5f4abc | KD4/TIL | /Algorithm/merge_two_sorted_lists.py | 1,227 | 4.1875 | 4 | # Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
# splice 꼬아 잇다
# 주어준 링크드리스트 두 개를 하나의 리스트로 만들어라. 두 리스트의 노드들을 꼬아서 만들어야한다.
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
... | true |
b6364e51af1472c1eec2b3bef4e9aa5d68f4e2e4 | CHuber00/Simulation | /Sprint-1-Python_and_Descriptive_Statistics/Deliverables/MoreCalculations.py | 2,014 | 4.25 | 4 | """
Christian Huber
CMS 380, Fall 2020 / Sprint 1 / MoreCalculations
This script reads a text file's values and calculates and prints
the mean, median, variance, and standard deviation.
"""
from math import sqrt
import matplotlib
matplotlib.use("Agg")
from matplotlib import pyplot as plt
def mean(x):
... | true |
0779044e55eb618e79e6cc91c7d8d59e614713dc | yamiau/Courses | /[Udemy] Web Scraping with Python - BeautifulSoup, Requests, Selenium/00 Data Structures Refresher/List Comprehension 2.py | 777 | 4.21875 | 4 | '''Nested lists'''
carts = [['toothpaste', 'soap', 'toilet paper'], ['meat', 'fruit', 'cereal'], ['pencil', 'notebook', 'eraser']]
#or
person1 = ['toothpaste', 'soap', 'toilet paper']
person2 = ['meat', 'fruit', 'cereal']
person3 = ['pencil', 'notebook', 'eraser']
carts = [person1, person2, person3]
print(carts)
fo... | true |
16ab5543da15a3db9c80b7526c55e3745eadf2af | lithiumspiral/python | /calculator.py | 1,196 | 4.25 | 4 | import math
print('This calculator requires you to enter a function and a number')
print('The functions are as follows:')
print('S - sine')
print('C - cosine')
print('T - tangent')
print('R - square root')
print('N - natural log')
print('X 0- eXit the program')
f, v = input("Please enter a function and a value ").spl... | true |
d508ae43c03ea8337d2d5dcfeb3ccfc75555df4d | Emma-2016/introduction-to-computer-science-and-programming | /lecture15.py | 1,958 | 4.34375 | 4 | # Class - template to create instance of object.
# Instance has some internal attributes.
class cartesianPoint:
pass
cp1 = cartesianPoint()
cp2 = cartesianPoint()
cp1.x = 1.0
cp2.x = 1.0
cp1.y = 2.0
cp2.y = 3.0
def samePoint(p1, p2):
return (p1.x == p2.x) and (p1.y == p2.y)
def printPoint(p):
print '(' + ... | true |
3f835498966366c4a404fc4eb00725bbca57fee9 | fredssbr/MITx-6.00.1x | /strings-exercise2.py | 304 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 10 19:59:32 2016
@author: frederico
"""
#Exercise 2 - Strings
str1 = 'hello'
str2 = ','
str3 = 'world'
print('str1: ' + str1)
print('str1[0]: ' + str1[0])
print('str1[1]: ' + str1[1])
print('str1[-1]: ' + str1[-1])
print('len(str1): ' + str(len(str1)))
| false |
00ce7ddd2e3fe18691908492ddd2de4ebde05559 | ckceddie/OOP | /OOP_Bike.py | 878 | 4.25 | 4 | # OOP Bike
# define the Bike class
class bike(object):
def __init__ (self , price , max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
def displayInfo(self):
print "bike's price is " + str(self.price)
print "maximum speed : " + str(self.max_speed... | true |
6b20406d423409b7a977d67e670b61022f4f0976 | ehpessoa/Python | /Automate-The-Boring-Stuff-With-Python/Chapter 03 - Functions/the_collatz_sequence.py | 329 | 4.4375 | 4 | #! python3
# the_collatz_sequence.py - Take user input num and prints collatz sequence
def collatz(num):
print(num)
while num != 1:
if int(num) % 2:
num = 3 * num + 1
else:
num = num // 2
print(num)
user_num = input('Enter a number ')
collatz(us... | false |
6604cf3f68749b72d0eeb22a76e03075d2b87a02 | jkbstepien/ASD-2021 | /graphs/cycle_graph_adj_list.py | 1,087 | 4.125 | 4 | def cycle_util(graph, v, visited, parent):
"""
Utility function for cycle.
:param graph: representation of a graph as adjacency list.
:param v: current vertex.
:param visited: list of visited vertexes.
:param parent: list of vertexes' parents.
:return: boolean value for cycle function.
"... | true |
830aaaa0664c6d8f993de0097927ff4c385c6d4e | okipriyadi/NewSamplePython | /SamplePython/samplePython/Modul/memcache/_01_Using_memcache.py | 1,261 | 4.21875 | 4 | """
kesimpuan sementara saya, memcache digunakan untuk menyimpan sebuah value di memori cache
sehingga program lain bisa mengambil value tersebut dengan cara mencari key yang telah ditetapkan
coba lihat value di file ini bisa didapatkan oleh file _02_test.py
It's fairly simple. You write values using keys and expiry... | false |
d93db45bbff954b5957cf7d8b62363877c7b0e84 | okipriyadi/NewSamplePython | /SamplePython/build_in_modul/_04_getattr.py | 678 | 4.5625 | 5 | """
Objects in Python can have attributes. For example you have an object person,
that has several attributes: name, gender, etc. You access these attributes
(be it methods or data objects) usually writing: person.name, person.gender,
person.the_method(), etc.
But what if you don't know the attribute's name at the ... | false |
f08bd170328ec6dc4ca3c8da2f3d8e2af7af5891 | okipriyadi/NewSamplePython | /SamplePython/build_in_modul/_01_zip.py | 358 | 4.125 | 4 | """
built-in zip berfungsi untuk iterasi yang menghasilkan satu-ke satu. return nya berupa tuple.
contoh zip([1, 2, 3, 4], ['a', 'b', 'c', 'f']) menghasikan
"""
a = zip([1, 2, 3, 4], ['a', 'b', 'c', 'f'])
for i in a :
print i
print "a = " , a
b = zip([1, 2], ['a', 'b', 'c', 'f'])
print "b =",b
c = zip([1, 2, ... | false |
cf4bf216fd03c9acaff05038fe3f204902ddd216 | anmolparida/selenium_python | /CorePython/FlowControl/Pattern_Stars.py | 758 | 4.125 | 4 | """
Write a Python program to construct the following pattern, using a nested for loop.
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
"""
def pattern_star_right_arrow_method1(n):
print('pattern_star_right_arrow_method1')
for i in range(n + 1):
print("* " * i)
for j in ran... | false |
5512e04c4832ad7b74e6a0ae7d3151643747dd8c | anmolparida/selenium_python | /CorePython/DataTypes/Dictionary/DictionaryMethods.py | 1,181 | 4.28125 | 4 | d = {'A': 1, 'B' : 2}
print(d)
print(d.items())
print(d.keys())
print(d.values())
print(d.get('A'))
print(d['A'])
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
print(my_dict)
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
print(my_dict)
# us... | true |
6a655da9e2fefbfaa7a77ce652b6af6755ae1e95 | surenthiran123/sp.py | /number.py | 330 | 4.21875 | 4 | n1=input();
n2=input();
n3=input();
Largest = n1
if Largest < n2:
if n2 > n3:
print(n2,"is Largest")
else:
print(n3,"is Largest")
elif Largest < n3:
if n3 > n2:
print(n3,"is Largest")
else:
print(n2,"is Largest")
else:
print(n1,"is ... | false |
946d183421857c5896636eac5dcaa797091cb87a | aboyington/cs50x2021 | /week6/pset6/mario/more/mario.py | 480 | 4.15625 | 4 | from cs50 import get_int
def get_height(min=1, max=8):
"""Prompt user for height value."""
while True:
height = get_int("Height: ")
if height >= min and height <= max:
return height
def print_pyramid(n):
"""Print n height of half-pyramid to console."""
for i in range(1, n... | true |
2b233d93ef2101f8833bbff948682add348fde63 | djanibekov/algorithms_py | /inversion_counting.py | 2,025 | 4.21875 | 4 | inversion_count = 0
def inversion_counter_conquer(first, second):
"""[This function counts #inversions while merging two lists/arrays ]
Args:
first ([list]): [left unsorted half]
second ([list]): [right unsorted half]
Returns:
[tuple]: [(first: merged list of left and right halves... | true |
63ca4f68c05708f2482045d06775fa5d7d22ea55 | loudan-arc/schafertuts | /conds.py | 1,574 | 4.1875 | 4 | #unlike with other programming languages that require parentheses ()
#python does not need it for if-else statements, but it works with it
fake = False
empty = None
stmt = 0
f = 69
k = 420
hz = [60, 75, 90, 120, 144, 240, 360]
if k > f:
print(f"no parentheses if condition: {k} > {f}")
if (k > f):
... | true |
4afceabb3673acbe934061dd9888d06e0457a152 | dark5eid83/algos | /Easy/palindrome_check.py | 330 | 4.25 | 4 | # Write a function that takes in a non-empty string that returns a boolean representing
# whether or not the string is a palindrome.
# Sample input: "abcdcba"
# Sample output: True
def isPalindrome(string, i=0):
j = len(string) - 1 - i
return True if i >= j else string[i] == string[j] and isPalindrome(stri... | true |
7ce3fe03de726250fbad7573e0f6a12afa5fcc4a | AshishKadam2666/Daisy | /swap.py | 219 | 4.125 | 4 | # Taking user inputs:
x = 20
y = 10
# creating a temporary variable to swap the values
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
| true |
ef3a0ab8ca46680697e312f31094b9ce455a37bb | Choe-Yun/Algorithm | /LeetCode/문자열 다루기/02.Reverse_String.py | 746 | 4.15625 | 4 | ### 문제
# Write a function that reverses a string. The input string is given as an array of characters s.
# 문자열을 뒤집는 함수를 작성해라. 인풋값은 배열이다
### Example 1
# Input: s = ["h","e","l","l","o"]
# Output: ["o","l","l","e","h"]
###### code
from typing import List
# 투 포인터를 이용한 스왑 방식
class Solution:
def reverseString(... | false |
bb155d4d67a7611506849ea6160074b6fec2d01f | kalpitthakkar/daily-coding | /problems/Jane_Street/P5_consCarCdr.py | 1,420 | 4.125 | 4 | def cons(a, b):
def pair(f):
return f(a, b)
return pair
class Problem5(object):
def __init__(self,
name):
self.name = name
# The whole idea of this problem is functional programming.
# Use the function cons(a, b) to understand the functional
# interface requir... | true |
11b8b5e7175b685c7f3718409d22ce34322dbb11 | mariagarciau/EntregaPractica3 | /ejercicioadivinar.py | 1,884 | 4.125 | 4 | """
En este desafío, probamos su conocimiento sobre el uso de declaraciones
condicionales if-else para automatizar los procesos de toma de decisiones.
Juguemos un juego para darte una idea de cómo diferentes algoritmos para el mismo
problema pueden tener eficiencias muy diferentes.
Deberás desarrollar un algoritmo que ... | false |
84f2c41dd849d194eb1bbdbb5abc97ae9f05bfcd | trishajjohnson/python-ds-practice | /fs_1_is_odd_string/is_odd_string.py | 974 | 4.21875 | 4 | def is_odd_string(word):
"""Is the sum of the character-positions odd?
Word is a simple word of uppercase/lowercase letters without punctuation.
For each character, find it's "character position" ("a"=1, "b"=2, etc).
Return True/False, depending on whether sum of those numbers is odd.
For example... | true |
1991e34b3272b9374e485fb49abe10f2adfb7b3b | smirnoffmg/codeforces | /519B.py | 303 | 4.15625 | 4 | # -*- coding: utf-8 -*-
n = int(raw_input())
first_row = map(int, raw_input().split(' '))
second_row = map(int, raw_input().split(' '))
third_row = map(int, raw_input().split(' '))
print [item for item in first_row if item not in second_row]
print [item for item in second_row if item not in third_row] | true |
42e25fed3a11b28f2bd4eb5070ce2ff7034eeda1 | sanapplegates/Python_qxf2_exercises | /bmi.py | 288 | 4.28125 | 4 |
#calculate the bmi of user
#user height in kg
print("Enter the user's weight(kg):")
weight = int(input())
#user height in metres
print("Enter the user's height(metre) :")
height = int(input())
#Body Mass Index of user
bmi = weight/(height*height)
print("bmi of user:",bmi)
| true |
7f200a512c5821b826df1a6eec5259ef91484125 | nahuelv/frro-soporte-2019-11 | /practico_01_cvg/ejercicio_08.py | 547 | 4.21875 | 4 | """
Definir una función superposicion() que tome dos listas y devuelva True si tienen al
menos 1 miembro en común o devuelva False de lo contrario. Escribir la función
usando el bucle for anidado.
"""
lista_1 = ["a", "b", "c"]
lista_2 = ["b", "d", "e"]
def superposicion (lista1, lista2):
for i in range (0, len(... | false |
b88a715b7625b1b27f47e9cb6098e00e8e616f7e | lexruee/project-euler | /problem_9.py | 326 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
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 main():
#TODO
pass
if __name__ == '__main__':... | true |
91e717e2422ba6a54dcfef0de4292846b9fd1832 | Laavanya-Agarwal/Python-C2 | /Making functions/countWords.py | 271 | 4.3125 | 4 | def countWords():
fileName = input('Enter the File Name')
file = open(fileName, 'r')
noOfWords = 0
for line in file:
words = line.split()
noOfWords = noOfWords + len(words)
print('The number of words is ' + str(noOfWords))
countWords() | true |
3c54aa7bc9815de81888d9b40085067fa1cf218a | keryl/2017-03-24 | /even_number.py | 467 | 4.25 | 4 | def even_num(l):
# first, we will ensure l is of type "list"
if type(l) != list:
return "argument passed is not a list of numbers"
# secondly, check l is a list of numbers only
for n in l:
if not (type(n) == int or type(n) == float):
return "some elements in your list are... | true |
8bd5806dd9b01c9eb90592e7239e8662ae9f1af5 | danny237/Python-Assignment3 | /insertion_sort.py | 541 | 4.1875 | 4 | """Insertion Sort"""
def insertion_sort(list1):
"""function for insertion sort"""
for i in range(1, len(list1)):
key = list1[i]
j = i-1
while j >=0 and key < list1[j] :
list1[j+1] = list1[j]
j -= 1
list1[j+1] = key
return lis... | true |
adfba4e45bc9ec9707eeda09767bfde152600426 | reachtoakhtar/data-structure | /tree/problems/binary_tree/diameter.py | 776 | 4.125 | 4 | __author__ = "akhtar"
def height(root, ans):
if root is None:
return 0
left_height = height(root.left, ans)
right_height = height(root.right, ans)
# update the answer, because diameter of a tree is nothing but maximum
# value of (left_height + right_height + 1) for each node
... | true |
93c12f6ced3ca1b9d99a490e6e3e7d6551dbd58f | hector81/Aprendiendo_Python | /Bucles/Hexagono.py | 625 | 4.125 | 4 | numero = 0
cuadrado = ''
# bucle para poner numero correto
while numero < 1 :
# ponemos el numero
numero = int(input('Escribe el número '))
print()
if numero < 1:
print('El número debe ser positivo')
else:
numeroArriba = numero
while numeroArriba < ((numero*2) + 3)... | false |
b9d59b5bd22207e7d7188fdfffa92f5acbccd82f | hector81/Aprendiendo_Python | /CursoPython/Unidad7/Ejercicios/ejercicio_II_u7.py | 1,171 | 4.53125 | 5 | '''
Lambda y map()
map() es una función incorporada de orden superior que toma una función e iterable como entradas, y
devuelve un iterador que aplica la función a cada elemento de la iterable. El código de abajo
usa map() para encontrar la media de cada lista en números para crear los promedios de la lista.
... | false |
08be952345411637b829e6af9f3ff91c745225cd | hector81/Aprendiendo_Python | /CursoPython/Unidad5/Ejemplos/ejemplo3_if_else_anidados.py | 1,063 | 4.125 | 4 | '''
Durante el trimestre, un estudiante debe realizar tres exámenes. Cada examen tiene una calificación
y la nota total que recibe el estudiante es la suma de las dos mejores calificaciones.
Escribe un programa que lea las tres notas y determine cuál es la calificación total que recibirá el
estudiante.
Sola... | false |
0c8d83c250fa1300cde1e30bade521711b00199c | hector81/Aprendiendo_Python | /Integer/Introducir_Pares.py | 396 | 4.125 | 4 | def introducirNumero():
while True:
try:
x = int(input("Por favor ingrese un número par: "))
return x
break
except ValueError:
print("Oops! No era válido. Intente nuevamente...")
numero = 0
while numero%2 == 0:
numero = introdu... | false |
a5084140a8d49079bcbac4d8d6cc2cb27721ebab | hector81/Aprendiendo_Python | /Excepciones/Ejercicio2_texto_ruta_OSError.py | 1,117 | 4.125 | 4 | '''
EJERCICIOS EXCEPCIONES
2. Programa que itere sobre una lista de cadenas de texto que contienen nombres
de fichero hasta encontrar el primero que existe (OSError) [Pista: crear nuestra
propia función, existe_fichero(ruta), que devuelve True o False]
'''
# buscar fichero = Ejercicio2_texto_ruta_OSError.py
... | false |
9570e6bbbe210122e6a2611d19622fabafac0777 | hector81/Aprendiendo_Python | /CursoPython/Unidad6/Soluciones/ejercicio_I_u6 (2).py | 637 | 4.3125 | 4 | """Diseña un programa que genere un entero al azar y te permita introducir números para saber si aciertas dicho número.
El programa debe incluir un mensaje de ayuda y un conteo de intentos.
"""
import random
num = int(input("Introduce un número del uno a l diez: "))
aleatorio = random.randint(1,10)
while num != al... | false |
8c72ee9e300534e48b4f7ff9adad76e665e758b5 | hector81/Aprendiendo_Python | /CursoPython/Unidad7/Ejemplos/funcion_nonlocal.py | 558 | 4.15625 | 4 | '''
Si el programa contiene solamente funciones que no contienen a su vez funciones, todas las variables
libres son variables globales. Pero si el programa contiene una función que a su vez contiene una
función, las variables libres de esas "subfunciones" pueden ser globales (si pertenecen al programa
principa... | false |
3cd870efac96ad2866c909ef969caf5acc2830d1 | hector81/Aprendiendo_Python | /CursoPython/Unidad9/Ejemplos/clase_metodo_operador_matematico.py | 557 | 4.375 | 4 | class Punto():
"""Clase que va representar un punto en un plano
Por lo que tendrá una coordenada cartesiana(x,y)
"""
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, otro):
""" Devuelve la suma de ambos puntos. """
return Punto(self.... | false |
7a165c4d007d1ba99dc4024e658e26bcc7dbee5d | hector81/Aprendiendo_Python | /Listas/Ordenacion_listas.py | 729 | 4.40625 | 4 | '''
ORDENACIÓN DE LISTAS
'''
x = [8, 2, 3, 7, 5, 3, 7, 3, 1]
print(x)
print(f"1. El mayor número de la lista ")
print(f"{max(x)}")
print(f"2. El menor número de la lista ")
print(f"{min(x)}")
print(f"3. Los tres mayores números de la lista ")
lista = sorted(x, reverse=True)
print(lista[0:3])
print(f... | false |
a43ddbb034d53912e38c51fc663c49e12520f22f | hector81/Aprendiendo_Python | /CursoPython/Unidad4/Ejemplos/listas_funciones.py | 996 | 4.40625 | 4 | ''' funciones_listas '''
x = [20, 30, 40, 50, 30]
y = [20, "abc", 56, 90, "ty"]
print(len(x)) # devuelve numero elemento lista x
print(len(y)) # devuelve numero elemento lista x
#max y min solo funcionan con listas numéricas
print(max(x)) # maximo de la lista x
# ERROR # print(max(y)) # maximo de la list... | false |
7915e90dd431cedcd1820486783a299df813b0b9 | SoumyaMalgonde/AlgoBook | /python/sorting/selection_sort.py | 654 | 4.21875 | 4 | #coding: utf-8
def minimum(array, index):
length = len(array)
minimum_index = index
for j in range(index, length):
if array[minimum_index] > array[j]:
minimum_index = j
return minimum_index
def selection_sort(array):
length = len(array)
for i in range(length - 1):
... | true |
3b68f1f217fd64cc0428e93fbfe17745c664cb2e | SoumyaMalgonde/AlgoBook | /python/maths/jaccard.py | 374 | 4.1875 | 4 |
a = set()
b = set()
m = int(input("Enter number elements in set 1: "))
n = int(input("Enter number elements in set 2: "))
print("Enter elements of set 1: ")
for i in range(m):
a.add(input())
print("Enter elements of set 2: ")
for i in range(n):
b.add(input())
similarity = len(a.intersection(b))/len(a.union... | true |
df7feb3e68df6d0434ed16f02ce3fcf0fd1dbf99 | SoumyaMalgonde/AlgoBook | /python/maths/Volume of 3D shapes.py | 2,970 | 4.1875 | 4 | import math
print("*****Volume of the Cube*****\n")
side=float(input("Enter the edge of the cube "))
volume = side**3
print("Volume of the cube of side = ",side," is " ,volume,)
print("\n*****Volume of Cuboid*****\n")
length=float(input("Enter the length of the cuboid "))
breadth=float(input("Enter the breadth of the... | true |
bb114c561547aa3adbcf855e3e3985e08c748a01 | SoumyaMalgonde/AlgoBook | /python/sorting/Recursive_quick_sort.py | 834 | 4.1875 | 4 | def quick_sort(arr, l, r): # arr[l:r]
if r - l <= 1: # base case
return ()
# partition w.r.t pivot - arr[l]
# dividing array into three parts one pivot
# one yellow part which contains elements less than pivot
# and last green part which contains elements greater than pivot
yellow = l +... | true |
edb2d3e1a9f09ce94933b8b223af17dda52143a3 | SunshinePalahang/Assignment-5 | /prog2.py | 327 | 4.15625 | 4 | def min_of_3():
a = int(input("First number: "))
b = int(input("Second number: "))
c = int(input("Third number: "))
if a < b and a < c:
min = a
elif b < a and b < c:
min = b
else:
min = c
return min
minimum = min_of_3()
print(f"The lowest of the 3 numbers is {min... | true |
34a2bfbe98dfb42c1f3d2a8f444da8e49ca04639 | PaxMax1/School-Work | /fbi.py | 1,610 | 4.25 | 4 | # a322_electricity_trends.py
# This program uses the pandas module to load a 3-dimensional data sheet into a pandas DataFrame object
# Then it will use the matplotlib module to plot comparative line graphs
import matplotlib.pyplot as plt
import pandas as pd
# choose countries of interest
my_countries = ['United Stat... | true |
c275468117aa43e59ac27afd391e463d0983a979 | gevishahari/mesmerised-world | /integersopr.py | 230 | 4.125 | 4 | x=int(input("enter the value of x"))
y=int(input("enter the value of y"))
if(x>y):
print("x is the largest number")
if(y>x):
print("y is the largest number")
if (x==y):
print("x is equal to y")
print("they are equal") | true |
d76dfe561f9111effed1b82da602bf6df98f2405 | AdmireKhulumo/Caroline | /stack.py | 2,278 | 4.15625 | 4 | # a manual implementation of a stack using a list
# specifically used for strings
from typing import List
class Stack:
# initialise list to hold items
def __init__(self):
# initialise stack variable
self.stack: List[str] = []
# define a property for the stack -- works as a getter
@pro... | true |
8b7da9557874db581b38432a28b41f9058e9dadf | cpelaezp/IA | /1. Python/ejemplos/3.projects/1.contactos/contactoBook.py | 831 | 4.15625 | 4 | class Contacto:
def __init__(self, name, phone, email):
self._name = name
self._phone = name
self._email = email
class ContactoBook:
def __init__(self):
self._contactos = []
def add(self):
name = str(input("Ingrese el nombre: "))
phone = str(input("Ingrese e... | false |
71021e7cf21f47c13df7be87afe4e169eb945ab5 | jessicazhuofanzh/Jessica-Zhuofan--Zhang | /assignment1.py | 1,535 | 4.21875 | 4 | #assignment 1
myComputer = {
"brand": "Apple",
"color": "Grey",
"size": 15.4,
"language": "English"
}
print(myComputer)
myBag = {
"color": "Black",
"brand": "MM6",
"bagWidth": 22,
"bagHeight": 42
}
print(myBag)
myApartment = {
"location": "New York City",
"type": "s... | true |
15774b26dae087e6ec683e676046c29d2009b904 | devimonica/Python-exercises---Mosh-Hamedani-YT- | /4.py | 490 | 4.5 | 4 | # Write a function called showNumbers that takes a parameter called limit. It should
# print all the numbers between 0 and limit with a label to identify the even and odd numbers. For example,
# if the limit is 3, it should print:
# 0 EVEN
# 1 ODD
# 2 EVEN
# 3 ODD
# Solution:
def showNumbers(limit)... | true |
d5d3b540482b581ad95e5a4d4ab4e8dbcc1280fd | gninoshev/SQLite_Databases_With_Python | /delete_records.py | 411 | 4.1875 | 4 | import sqlite3
# Connect to database
conn = sqlite3.connect("customer.db")
# Create a cursor
c = conn.cursor()
# Order By Database - Order BY
c.execute("SELECT rowid,* FROM customers ORDER BY rowid ")
# Order Descending
c.execute("SELECT rowid,* FROM customers ORDER BY rowid DESC")
items = c.fetc... | true |
5a0637856f9dddcb3d6667340def81e831361c7d | kaloyansabchev/Programming-Basics-with-Python | /PB Exam - 20 and 21 February 2021/03. Computer Room.py | 755 | 4.25 | 4 | month = input()
hours = int(input())
people_in_group = int(input())
time_of_the_day = input()
per_hour = 0
if month == "march" or month == "april" or month == "may":
if time_of_the_day == "day":
per_hour = 10.50
elif time_of_the_day == "night":
per_hour = 8.40
elif month == "june" or month == ... | true |
a818501d5eccec65ef65fe2d1cf461258ade1e99 | kaloyansabchev/Programming-Basics-with-Python | /03 Conditional Statements Advanced Lab/11. Fruit Shop.py | 1,773 | 4.125 | 4 | product = input()
day = input()
quantity = float(input())
if day == "Saturday" or day == "Sunday":
if product == 'banana':
banana_cost = 2.70 * quantity
print(f'{banana_cost:.2f}')
elif product == 'apple':
apple_cost = 1.25 * quantity
print(f'{apple_cost:.2f}')
elif product ... | false |
3b46d280e7581cb9cf36098bf3375b126a9305b7 | i-fernandez/Project-Euler | /Problem_004/problem_4.py | 862 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 27 19:32:24 2020
@author: israel
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def is_palindrome(number):
st = str(number)
size = len(st)
for i in range(0,int(size/2)):
if (st[i] != st[size-i-1]... | false |
bb2ff59d2062a5b6ab007782f05653c2fd7fb1c1 | Ramya74/ERP-projects | /Employee.py | 1,296 | 4.25 | 4 | employees = [] #empty List
while True:
print("1. Add employee")
print("2. Delete employee")
print("3. Search employee")
print("4. Display all employee")
print("5. Change a employee name in the list")
print("6. exit")
ch = int(input("Enter your choice: "))
if ch is None:
print("no data present in Employees")... | true |
36987ff25b32b7f90e4fdcddbb0e8067acdbd4ec | saubhagyav/100_Days_Code_Challenge | /DAYS/Day61/Collatz_Sequence.py | 315 | 4.34375 | 4 | def Collatz_Sequence(num):
Result = [num]
while num != 1:
if num % 2 == 0:
num = num/2
else:
num = 3*num+1
Result.append(num)
return Result
if __name__ == "__main__":
num = int(input("Enter a Number: "))
print(Collatz_Sequence(num)) | false |
5491efb3841bc753f8de6fff6b0f5233c132a805 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day22/Remove_Duplicates_in_Dictionary.py | 364 | 4.21875 | 4 | def Remove_Duplicates(Test_string):
Test_list = []
for elements in Test_string.split(" "):
if ((Test_string.count(elements) > 1 or Test_string.count(elements) == 1) and elements not in Test_list):
Test_list.append(elements)
return Test_list
Test_string = input("Enter a String: ... | true |
f2f47ab9d8e116d43c619e88b3db0807b4d658f9 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day10/String_Palindrome.py | 203 | 4.1875 | 4 | def Palindrome(Test_String):
if Test_String == Test_String[::-1]:
return True
else:
return False
Test_String = input("Enter a String: ")
print(Palindrome(Test_String))
| true |
816b1917aa477d70f2ce4c30323d811ae7896bde | saubhagyav/100_Days_Code_Challenge | /DAYS/Day18/Remove_Keys_from_Dictionary.py | 387 | 4.1875 | 4 | def Remove_Keys(Test_dict, Remove_Value):
return {key: value for key, value in Test_dict.items() if key != Remove_Value}
N_value = int(input("Enter n: "))
Test_dict = {}
for i in range(N_value):
key = input("Key: ")
Value = int(input("Value: "))
Test_dict[key] = Value
Remove_Value = input("W... | false |
ab24f06d7a40626bf37222236b0ad610637171bb | yuttana76/python_study | /py_dictionary.py | 563 | 4.125 | 4 | phonebook = {
'John':999,
'Jack':888,
'Jill':777
}
print(phonebook)
#Interating
for name,tel in phonebook.items():
print('%s has phone number is %s' %(name,tel))
#Delete item
print('Delete item')
del phonebook['Jill']
print(phonebook)
#Update and Add item
print('Update and Add item')
phonebook.update... | false |
73d106223ed6a7d1b8435d731bf0ac076927484e | britannica/euler-club | /Week33/euler33_smccullars.py | 2,818 | 4.125 | 4 | class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __eq__(self, other):
return self.numerator == other.numerator and self.denominator == other.denominator
def __str__(self):
return '{}/{}'.format(self.nu... | false |
d386360920ee5b5e08654d3e2c781148839fbdc9 | scudan/TestPython | /com/refrencePython/function/FunctionT1.py | 468 | 4.375 | 4 | #可变参数函数
def concat(*args , sep ='/'):
return sep.join(args);
result = concat("earth","mars","venus");
print(result);
result1 = concat("earth","mars","venus",sep =".");
print(result1);
# 参数分拆
# *args 分拆 元祖
# **args 分拆 字典
list1 = list(range(3,6))
print(list1);
args = [3,6]
list2 = list(range(*args))
print(list2);
... | false |
bb1a8090d3fc97546339037bbc0e9b06ff43b438 | 3point14guy/Interactive-Python | /strings/count_e.py | 1,153 | 4.34375 | 4 | # Assign to a variable in your program a triple-quoted string that contains your favorite paragraph of text - perhaps a poem, a speech, instructions to bake a cake, some inspirational verses, etc.
#
# Write a function that counts the number of alphabetic characters (a through z, or A through Z) in your text and then k... | true |
11992691b92d6d74aa41fe6797f70f810ea3bfb9 | 3point14guy/Interactive-Python | /tkinter/hello_world_tkinter.py | 1,249 | 4.15625 | 4 | import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter import simpledialog
window = tk.Tk()
# my_label = ttk.Label(window, text="Hello World!")
# my_label.grid(row=1, column=1)
# messagebox.showinfo("Information", "Information Message")
# messagebox.showerror("Error", "My error mess... | true |
da34092f0d87be4f33072a3e2df047652fb29cf3 | sudj/24-Exam3-201920 | /src/problem2.py | 2,658 | 4.125 | 4 | """
Exam 3, problem 2.
Authors: Vibha Alangar, Aaron Wilkin, David Mutchler, Dave Fisher,
Matt Boutell, Amanda Stouder, their colleagues and
Daniel Su. January 2019.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
def main():
""" Calls the TEST functions in this module. """
run_tes... | true |
b2e763e72dd93b471294f997d2c18ab041ad665c | Evanc123/interview_prep | /gainlo/3sum.py | 1,274 | 4.375 | 4 | '''
Determine if any 3 integers in an array sum to 0.
For example, for array [4, 3, -1, 2, -2, 10], the function
should return true since 3 + (-1) + (-2) = 0. To make things simple,
each number can be used at most once.
'''
'''
1. Naive Solution is to test every 3 numbers to test if it is zero
2. is it possible to c... | true |
5ebd4c91bd2fd1b34fbfdcff3198aef77ceb8612 | CrazyCoder4Carrot/lintcode | /python/Insert Node in a Binary Search Tree.py | 1,676 | 4.25 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
"""
Revursive version
"""
class Solution:
"""
@param root: The root of the binary search tree.
@param node: insert this node into the binary search tree.
@return... | true |
0046fd9fa359ebfaa81b7fb40ecf2c5f6d278273 | sfagnon/stephane_fagnon_test | /QuestionA/QaMethods.py | 1,120 | 4.21875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#Verify if the two positions provided form a line
def isLineValid(line_X1,line_X2):
answer = True
if(line_X1 == line_X2):
answer = False
print("Points coordinates must be different from each other to form a line")
return answer
#Verify i... | true |
1916ef020df5cb454e7887d2d4bb051d308887e3 | sammysun0711/data_structures_fundamental | /week1/tree_height/tree_height.py | 2,341 | 4.15625 | 4 | # python3
import sys
import threading
# final solution
""" Compute height of a given tree
Height of a (rooted) tree is the maximum depth of a node,
or the maximum distance from a leaf to the root.
"""
class TreeHeight:
def __init__(self, nodes):
self.num = len(nodes)
self.parent = nodes
... | true |
7cafa9fc6b348af6d2f11ad8771c5cca59b1bea7 | irina-baeva/algorithms-with-python | /data-structure/stack.py | 1,702 | 4.15625 | 4 | '''Imlementing stack based on linked list'''
class Element(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def append(self, new_element):
current = self.head
... | true |
01ece2001beaf028b52be310a8f1df24858f4e59 | amitesh1201/Python_30Days | /OldPrgms/Day3_prc05.py | 579 | 4.375 | 4 | # Basic String Processing : four important options: lower, upper, capitalize, and title.
# In order to use these methods, we just need to use the dot notation again, just like with format.
print("Hello, World!".lower()) # "hello, world!"
print("Hello, World!".upper()) # "HELLO, WORLD!"
print("... | true |
f6c183fb7de25707619a330224cdfa841a8b44be | maryliateixeira/pyModulo01 | /desafio005.py | 229 | 4.15625 | 4 | # Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e antecessor
n= int(input('Digite um número:'))
print('Analisando o número {}, o seu antecessor é {} e o sucessor {}' .format(n, (n-1), (n+1)))
| false |
b9151241f8234f5c1f038c733a5d0ff46da376d3 | louishuynh/patterns | /observer/observer3.py | 2,260 | 4.15625 | 4 | """
Source: https://www.youtube.com/watch?v=87MNuBgeg34
We can have observable that can notify one group of subscribers for one kind of situation.
Notify a different group of subscribers for different kind of situation.
We can have the same subscribers in both groups.
We call these situations events (different kinds o... | true |
e2ef440e9f140b93cb1adc8bf478baf2beae8fa3 | timmichanga13/python | /fundamentals/oop/demo/oop_notes.py | 1,389 | 4.25 | 4 | # Encapsulation is the idea that an instance of the class is responsible for its own data
# I have a bank account, teller verifies account info, makes withdrawal from acct
# I can't just reach over and take money from the drawer
# Inheritance allows us to pass attributes and methods from parents to children
# Vehicles... | true |
95eaa4c8b527c0ac22bbd95dcfc30dad1fc836ad | notwhale/devops-school-3 | /Python/Homework/hw09/problem6.py | 973 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Решить несколько задач из projecteuler.net
Решения должны быть максимально лаконичными, и использовать list comprehensions.
problem6 - list comprehension : one line
problem9 - list comprehension : one line
problem40 - list comprehension
problem48 - list comprehensio... | true |
97d12c33b2d142eaf238ae867bf6324c08a02bf9 | lanvce/learn-Python-the-hard-way | /ex32.py | 1,033 | 4.46875 | 4 | the_count=[1,2,3,4,5]
fruits=['apples','oranges','pears','apricots']
change=[1,'pennies',2,'dimes',3,'quarters']
#this fruit kind of fora-loop goes through a list
for number in the_count:
print(f"this is count {number}")
#same as above
for fruit in fruits:
print(f"A fruit of type :{fruit}")
#also we can g... | true |
ce5457678e0742d76a9e7935a257cd1af6e05617 | RobertElias/PythonProjects | /GroceryList/main.py | 1,980 | 4.375 | 4 | #Grocery List App
import datetime
#create date time object and store current date/time
time = datetime.datetime.now()
month = str(time.month)
day = str(time.day)
hour = str(time.hour)
minute = str(time.minute)
foods = ["Meat", "Cheese"]
print("Welcome to the Grocery List App.")
print("Current Date and Time: " + month ... | true |
dae536759b45c9c3db4f98695e57aa4aeb51c88d | RobertElias/PythonProjects | /Multiplication_Exponentiation_App/main.py | 1,673 | 4.15625 | 4 | print("Welcome to the multiplication/exponentiation table app.")
print("What number would you like to work with?")
# Gather user input
name = input("\nHello, what is your name: ").title().strip()
num = float(input("What number would you like to work with: "))
message = name + ", Math is really cool!!!"
# Multiplica... | false |
0cf8bac0a47bb1156eaaff40503bc1cdcadb50a1 | RobertElias/PythonProjects | /Arrays/main_1.py | 309 | 4.375 | 4 | #Write a Python program to create an array of 5 integers and display the array items.
from array import *
array_num = array('i', [1,3,5,7,9])
for i in array_num:
print("Loop through the array.",i)
print("Access first three items individually")
print(array_num[0])
print(array_num[1])
print(array_num[2])
| true |
83fb395b9fc573098d6fe9f258391a4eef07f0e9 | RobertElias/PythonProjects | /Favorite_Teacher/main.py | 2,539 | 4.46875 | 4 | print("Welcome to the Favorite Teachers Program")
fav_teachers = []
#Get user input
fav_teachers.append(input("Who is your first favorite teacher: ").title())
fav_teachers.append(input("Who is your second favorite teacher: ").title())
fav_teachers.append(input("Who is your third favorite teacher: ").title())
fav_teac... | false |
2dae568f69ab9c93d43fb38f7f5a776844bb5e3e | Isco170/Python_tutorial | /Lists/listComprehension.py | 723 | 4.84375 | 5 | # List Comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
# Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name
# Without list comprehension
# fruits = ["apple", "banana", "cherry", "kiwi", ... | true |
a315863eeb4b603354fc7f681e053554a35582fc | IonutPopovici1992/Python | /LearnPython/if_statements.py | 276 | 4.25 | 4 | is_male = True
is_tall = True
if is_male and is_tall:
print("You are a tall male.")
elif is_male and not(is_tall):
print("You are a short male.")
elif not(is_male) and is_tall:
print("You are not a male, but you are tall.")
else:
print("You are not a male.")
| true |
3f4261421609d3248060d7b9d12de47ad8bac76d | becomeuseless/WeUseless | /204_Count_Primes.py | 2,069 | 4.125 | 4 | '''
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
'''
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
#attemp 1... | true |
77665880cde79a8f833fb1a3f8dfe9c88368d970 | codexnubes/Coding_Dojo | /api_ajax/OOP/bike/bikechain.py | 1,120 | 4.25 | 4 | class Bike(object):
def __init__(self,price,max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
def displayinfo(self):
print "Here are your bike stats:\n\
Price: ${}\n\
Max Speed: {}\n\
Miles Rode: {}".format(self... | true |
256f3e7cfe573c0bed1c8e5e62c6df1226d9cc79 | AlenaGB/hw | /5.py | 465 | 4.125 | 4 | gain = float(input("What is the revenue this month? $"))
costs = float(input("What is the monthly expenses? $"))
if gain == costs:
print ("Not bad. No losses this month")
elif gain < costs:
print("It's time to think seriosly about cutting costs")
else:
print("Great! This month you have a profit")
staff... | true |
c619f9cd9cef317f81eab2637a5b454ef9c745e5 | TwiggyTwixter/Udemy-Project | /test.py | 309 | 4.15625 | 4 | print("This program calculates the average of two numbers")
firstNumber = float (input({"What will the first number be:"}))
secondNumber = float (input({"What will the second number be:"}))
print("The numbers are",firstNumber, "and",secondNumber)
print("The average is: ", (firstNumber + secondNumber )/ 2) | true |
37899a51d576727fdbde970880245b40e7e5b7b4 | dusanvojnovic/tic-tac-toe | /tic_tac_toe.py | 2,430 | 4.125 | 4 | import os
board = [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "]
def print_board(board):
print(board[7] + ' |' + board[8] + ' |' + board[9])
print("--------")
print(board[4] + ' |' + board[5] + ' |' + board[6])
print("--------")
print(board[1] + ' |' + board[2] + ' |' + board[3])
def game()... | true |
f4247987858702440a4739dc84674cec373d9384 | league-python-student/level0-module1-dencee | /_02_variables_practice/circle_area_calculator.py | 1,345 | 4.53125 | 5 | import turtle
from tkinter import messagebox, simpledialog, Tk
import math
import turtle
# Goal: Write a Python program that asks the user for the radius
# of a circle and displays the area of that circle.
# The formula for the area of a circle is πr^2.
# See example image in package to chec... | true |
6d63273b82815d33226d51ddf224e22434bbaded | WalterVives/Project_Euler | /4_largest_palindrome_product.py | 975 | 4.15625 | 4 | """
From: projecteuler.net
Problem ID: 4
Author: Walter Vives
GitHub: https://github.com/WalterVives
Problem:
A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers... | true |
74914ed8c197d826a7c557c8a1fcd3c8e3c805aa | aryanirani6/ICS4U-Classwork | /example.py | 866 | 4.5625 | 5 | """
create a text file with word on a number of lines
1. open the text file and print out 'f.read()'. What does it look like?
2. use a for loop to print out each line individually. 'for line in f:'
3. print our words only with "m", or some other specific letter.
"""
# with open("Some_file.txt", 'r') as f:
# print(f.re... | true |
6798074572ee5e82a5da113a6ace75b4670ae00c | aryanirani6/ICS4U-Classwork | /classes/classes2.py | 2,179 | 4.375 | 4 | """
name: str
cost: int
nutrition: int
"""
class Food:
""" Food class
Attributes:
name (str): name of food
cost (int): cost of food
nutrition (int): how nutritious it is
"""
def __init__(self, name: str, cost: int, nutrition: int):
""" Create a Food object.
Arg... | true |
7416e1c946d17374332e7e4ebabb09eb159aaa97 | GribaHub/Python | /exercise15.py | 967 | 4.5 | 4 | # https://www.practicepython.org/
# PRACTICE PYTHON
# Beginner Python exercises
# Write a program (using functions!) that asks the user for a long string containing multiple words.
# Print back to the user the same string, except with the words in backwards order.
# clear shell
def cls():
print(50 * "\n"... | true |
dca9c5f3548711b16c7736adc0588fff766c95a1 | kirubakaran28/Python-codes | /valid palindrome.py | 359 | 4.15625 | 4 | import re
def isPalindrome(s):
s = s.lower()
#removes anything that is not a alphabet or number
s = re.sub('[^a-z0-9]','',s)
#checks for palindrome
if s == s[::-1]:
return True
else:
return False
s = str(input("Enter ... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.