blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
a806dad256f648f42532c9cf866a3c0e9caf48e7 | Sasha1152/Training | /def_value_by_default.py | 1,360 | 4.25 | 4 | def foo(x, l=[]):
l.append(x)
print(x, l)
foo(1) # 1 [1]
foo(2) # 2 [1, 2]
foo(3) # 3 [1, 2, 3]
print('------'*3)
def foo(x, l):
l.append(x)
print(x, l)
l = []
foo(1, l) # 1 [1]
foo(2, l) # 2 [1, 2]
foo(3, l) # 3 [1, 2, 3]
print('------'*3)
def f(a = 0):
a += 1 # Операція присвоєння по ... | false |
4fe99da9a59cc213e6a1f1e2d4cc83064118852e | Sasha1152/Training | /classes/circle_Raymond.py | 2,119 | 4.125 | 4 | # https://www.youtube.com/watch?v=tfaFMfulY1M&feature=youtu.be
import math
class Circle:
"""An advanced circle analitic toolkit"""
__slots__ = ['diameter'] # flyweight design pattern suppresses the instance dictionary
version = '0.1' # class variable
def __init__(self, radius):
self.radius ... | true |
a5a57b64d94b05d9d17fb70835b7957caa2eff62 | cihangirkoral/python-rewiew | /homework_02.py | 1,834 | 4.71875 | 5 | # ################ HOMEWORK 02 ######################
# 4-1. Pizzas: Think of at least three kinds of your favorite pizza Store these
# pizza names in a list, and then use a for loop to print the name of each pizza
# • Modify your for loop to print a sentence using the name of the pizza
# instead of... | true |
efe029dfb58aa46842ed74b76c21914d988a802e | SyedAltamash/AltamashProgramming | /Fibonacci_Sequence.py | 393 | 4.15625 | 4 | #from math import e
#result = input('How many decimal places do you want to print for e: ')
#print('{:.{}f}'.format(e, result))
def fibonacci_sequence(number):
list = []
a =1
b = 1
for i in range(number):
list.append(a)
a,b = b,a+b
print(list)
result = int(input('Hey e... | true |
539949c601098bf6ee18857023a80eb440d06426 | 6reg/data_visualization | /visualize.py | 1,899 | 4.1875 | 4 | """
Image Visualization Project.
This program creates visualizations of data sets that
change over time. For example, 'child-mortality.txt'
is loaded in and the output is a vsualization of the
change in child mortality around the world from 1960
until 2017. Red means high and green means low.
"""
from simpleimag... | true |
b98da74f144dc5cb6a3f6e691f9a0f2e41a8cb03 | frisomeijer/ProjectEuler100 | /Problem_020/Solution_020.py | 660 | 4.15625 | 4 | '''
Problem 20:
n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
'''
import time
start_time = time.time()
def factorial_digit_sum(n):
fac... | true |
a82368543cd9c132cf1b7be409942c718b2e6d54 | luissalgueiro/curso_iot | /codigos_py/dog.py | 1,267 | 4.15625 | 4 | ## AUTHOR= Luis Salgueiro
## DATE= 21/10/2019
## DESCRIPTION = CODE FOR ACTIVITY 2 OF PLA3
class Dog:
species="caniche"
def __init__(self, name, age):
self.name = name
self.age = age
bambi = Dog("Bambi", 5)
mikey = Dog("Rufus", 6)
boby = Dog("Boby",15)
rino = Dog("Rino", 5)
oli = Dog("Oli",... | false |
cf39769061e619e9a3edf87688327e97f96ccf26 | prasanna1695/python-code | /1-2.py | 474 | 4.34375 | 4 | #Write code to reverse a C-Style String.
#(C-String means that abcd is represented as five characters
# including the null character.)
def reverseCStyleString(s):
reversed_string = ""
for char in s:
reversed_string = char + reversed_string
return reversed_string
print "Test1: hello"
print reverseCStyleString("he... | true |
487b0fedc3b0d970786718cf9034254afbf0d8b4 | prasanna1695/python-code | /4-1.py | 2,695 | 4.40625 | 4 | #Implement a function to check if a tree is balanced. For the purposes of this question,
#a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one
class Tree(object):
def __init__(self):
self.left = None
self.right = None
self.data = None
#not necess... | true |
f98cea48e5ef2da1ddd158c9cab3e2102f4a2fa0 | johnsonl7597/CTI-110 | /P2HW2_ListSets_JohnsonLilee.py | 1,190 | 4.34375 | 4 | #This program will demonstrate the students understanding of lists and sets.
#CTI-110, P2HW2 - List and Sets
#Lilee Johnson
#05 Oct 2021
#-----------------------------------------------------------------------------
#pesudocode
#prompt user for 6 indivual numbers
#store the numbers in a list called List6
#displ... | true |
124651b1e5621e7b54ff62ce933226a778393798 | hnhillol/PythonExercise | /HwAssignment7.py | 1,903 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 7 02:34:40 2019
@author: hnhillol
Homework Assignment #7: Dictionaries and Sets
Details:
Return to your first homework assignments, when you described your favorite song. Refactor that code so
all the variables are held as dictionary keys and value. Then refactor your p... | true |
f2962e714e32fc1ce26a388eb416ccd20f72fa36 | diegoarielsimonelli/variables_python | /ejercicios_profunidzacion/profundizacion_1.py | 1,598 | 4.375 | 4 | # Tipos de variables [Python]
# Ejercicios de profundización
# Autor: Inove Coding School
# Version: 2.0
# NOTA:
# Estos ejercicios son de mayor dificultad que los de clase y práctica.
# Están pensados para aquellos con conocimientos previo o que dispongan
# de mucho más tiempo para abordar estos temas por su cuenta... | false |
7f3cf610dffccafa759a59ce287ffc73ee2a9639 | SyriiAdvent/Intro-Python-I | /src/13_file_io.py | 967 | 4.28125 | 4 | """
Python makes performing file I/O simple. Take a look
at how to read and write to files here:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
"""
# Open up the "foo.txt" file (which already exists) for reading
# Print all the contents of the file, then close the file
# Note: pay close... | true |
48d2d40bb733d33b57da20111b607832579a9aee | cs-fullstack-2019-fall/python-loops-cw-rjrobins16 | /classwork.py | 1,507 | 4.5625 | 5 |
# ### Exercise 1:
# Print -20 to and including 50. Use any loop you want.
#
for x in range(-20,51,1):
print(x)
# ### Exercise 2:
# Create a loop that prints even numbers from 0 to and including 20.
# Hint: You can find multiples of 2 with (whatever_number % 2 == 0)
for x in range(0,21,2):
if x % 2 == 0:
... | true |
3325662f01c1766dc3c42943e6a1e12c56c354ef | jarvis-1805/Simple-Python-Projects | /theGuessingGame.py | 900 | 4.15625 | 4 | import random
print("\t\t\tThe Guessing Game!")
print("WARNING!!! Once you enter the game you have to guess the right number!!!\n")
c = input("Still want to enter the game!!! ('y' or 'n'): ")
print()
while c == 'y':
true_value = random.randint(1, 100)
while True:
chosed_value = int(inpu... | true |
f1f869c390877cfc42bcd25dbec63137b46e3533 | kaizer1v/ds-algo | /datastructures/matrix.py | 1,797 | 4.125 | 4 | class Matrix:
'''
[[1, 2],
[2, 1]]
is a matrix
'''
def __init__(self, arr):
self.matrix = arr
self.height = self.calc_height()
self.width = self.calc_width()
def calc_height(self):
return len(self.matrix)
def calc_width(self):
if self._is_valid... | true |
5dd783701c899fae07a094a2e2fce4094e370942 | kaizer1v/ds-algo | /datastructures/priority_queue.py | 1,388 | 4.40625 | 4 | '''
Priority Queue
Prioritiy queue operates just like a queue, but when `pop`-ing
out the first element that was added, it instead takes out the
highest (max) element from the queue. Thus, the items in the
priority queue should be comparable. When you add a new item
into the queue, it will automatically remove the min... | true |
acd3f5a7488cfaf4a3ee5df935eb200f85f3e98d | Hafidzmhmmd/PurwadhikaDataScience | /EXAM_MODUL_1_MUHAMMAD_HAFIDZ_JAKARTA.py | 1,913 | 4.15625 | 4 | # ---------------------------------------------<1>---------------------------------------------
kata = 'hello there how are you doing'
def hastag(string):
if string == '':
output = 'False'
else:
word = string.split(' ')
output = '#'
for x in range(len(word)):
... | false |
803aa2044f18114b72acaa66d0412cdcb61a3d48 | Arsenault-CMSC201-Fall2019/Spring_2020_code_samples | /February_17_coding.py | 985 | 4.28125 | 4 | # Examples of code using while loops
# from Monday, Feb. 17
age = 0;
while (age < 18):
age = input("enter your age in years: ")
print ("If you’re 18 or older you should vote")
print ("that's the end of our story")
# compute 10! Using a while loop
product = 1
factor = 1
while factor <= 10:
product *= factor #or ... | true |
e7f171ee421609f0c28813cb89cb8869ca9510fe | Arsenault-CMSC201-Fall2019/Spring_2020_code_samples | /February_5_code.py | 408 | 4.1875 | 4 | ######################
#
# This is one way to write a block
# of comments
#
########################
"""
This is another way to write a block
of comments
"""
'''
This will work too
'''
verb = input("please enter a verb")
new_verb = verb + "ing"
print(new_verb)
principal = 10000
rate = 0.03/12
n_payments = 72
cost ... | true |
864d5005fbc7a132a7ee970d006bbf40503496e6 | Arsenault-CMSC201-Fall2019/Spring_2020_code_samples | /February_19_coding.py | 1,230 | 4.125 | 4 | #coding for Wednesday, February 19
# Printing new lines, or not
print("this produces two lines", "\n", "of output")
print("this produces one line", end="")
print("of output")
# printing out an integer
print("{:d} is the answer to the question".format(42))
#printing the same value as a float
print("{:f} is the answe... | true |
3892ee83ecc247e92abac626cad19c4d8285f715 | arizala13/interview_cake | /hash_map_example.py | 333 | 4.125 | 4 | def return_true_or(s):
count_chars = {}
for char in s:
if char in count_chars:
count_chars[char] += 1
else:
count_chars[char] = 1
print(count_chars)
return_true_or("racecar")
# practice of adding a value to a dictionary
# and keeping track of how many times its... | false |
b987f123317a7f8e3feaf6dac464732e13fec601 | Spideyboi21/jash_python_pdxcode | /python learning/test.py | 350 | 4.125 | 4 |
if -4 < -6:
print("True")
else:
print('False')
if "part" in "party!!!1":
print("True")
else:
print("False")
age = input('how old are you?')
if int(age)< 28 and int(age) >=0:
print("this is valid")
else:
print("not valid")
name = input('What is my name? ')
if name == "Jash":
print("that... | true |
022bddfcc020eb7273a2180a8d391d3fd383ecea | jldupont/jldupont.com | /trunk/Tests/PYTHON/TestClassMethods.py | 521 | 4.15625 | 4 | class X:
def m(cls, p):
print "X: cls=%s , p=%s" % (cls,p)
# required for X.m() to work
m = classmethod(m)
class Y(X):
def m(cls,p):
print "Y: cls=%s , p=%s" % (cls,p)
X.m(p)
# required for X.m() to work
m = classmethod(m)
if (__name__ == "__m... | false |
82b473b6d4b8ce07c42b92870b91fee3fb5c8da5 | soonebabu/firstPY | /first.py | 318 | 4.21875 | 4 |
def checkPrime(num):
if num==1 or num==2 or prime(num):
return False
else:
return True
def prime(num):
for i in range(3,num-1):
if (num%i)==0:
return True
value = input('enter the value')
print(value)
if checkPrime(value):
print('prime')
else:
print('not')
| true |
aa5377b9f0a11e32cde4fa8c7ac47ca3bbb9f659 | BigBoiTom/Hangman-Game | /Hangman_Game.py | 2,686 | 4.15625 | 4 | import random, time
def play_again():
answer = input('Would you like to play again? yes/no: ').lower()
if answer == 'y' or answer == 'yes':
play_game()
elif answer == 'n' or answer == 'no':
print("Thanks for Playing!")
time.sleep(2)
exit()
else:
pass
def get_... | true |
1e9b87bca4f32738e79e1dec5654589374328125 | juancoan/python | /Basic/WtihASDemo.py | 989 | 4.125 | 4 | """
WITH / AS keywords
"""
# print("Normal WRITE start")
# File2 = open("File_IO.txt", "w")
# File2.write("Trying to write to the file2.")
# File2.close() #If I do not write the close() statement, nothing will happen. ALWAYS write it
#
# print("Normal READ start")
# File3 = open("File_IO.txt", "r")
# for line in File... | true |
3a136144b49f4e564b98cd44b97e77cf73866e93 | juancoan/python | /Basic/File2Read.py | 795 | 4.1875 | 4 |
my_file2 = open("File2Read.txt", 'r') #use the 'r' mode to read
print(str(my_file2.read())) #prints the read method, all the content of the file
my_file2.close()
print('#*'*20)
print("LINE BY LINE EXAMPLE......... Will print the first line only, unless I call that print method twice")
my_file_BY_LINE = open("File2Re... | true |
80a1b64a82ff503d1d41333e893f449881ee87c6 | CircleZ3791117/CodingPractice | /source_code/717_1BitAnd2BitCharacters.py | 1,646 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'circlezhou'
'''
Description:
We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).
Now given a string represented by several bits. Return whether the last charac... | true |
ff935fe0a87fbe0539bce9c276773eacbd9d06ed | yourspleenfell/python_fundamentals | /dictionary/dict.py | 831 | 4.1875 | 4 | # Create a dictionary containing information about yourself. Keys should include name, age, country of birth and favorite language.
# Write a function that will print something about the dictionary.
def aboutMe():
me = {
"first_name":"Dylan",
"last_name":"Arbuthnot",
"age":"26",
"bi... | false |
ad79baa9bd795e7e28ba7df8db472be9725d86de | amitauti/HelloWorldPython | /ex02.py | 1,019 | 4.25 | 4 | # http://www.practicepython.org/exercise/2014/02/05/02-odd-or-even.html
# Ask the user for a number. Depending on whether the number is even or
# odd, print out an appropriate message to the user.
import sys
def main():
askuser ()
def askuser():
#part one
str = input("Enter a number: ")
num = int(flo... | true |
2f7f8cb23eb74c9046769b6200a49147384375cd | nasirmajid29/Anthology-of-Algorithms | /Algorithms/sorting/mergeSort/mergeSort.py | 972 | 4.28125 | 4 | def mergeSort(array):
if len(array) > 1:
middle = len(array) // 2 # Finding the middle of the array
left = array[:middle] # Split array into 2
right = array[middle:]
mergeSort(left) # sorting the first half
mergeSort(right) # sorting the second half
# Copy... | true |
2929f49be61557f3233c7c68291711c9426c4638 | huchen086/web-caesar | /caesar.py | 1,154 | 4.1875 | 4 | def alphabet_position(letter):
"""receives a letter (that is, a string with only one alphabetic character)"""
"""and returns the 0-based numerical position of that letter"""
"""within the alphabet."""
letter = letter.upper()
position = ord(letter) - 65
return position
def rotate_character(char... | true |
9afee39db5f15d957c60df0a1c50213b73d888aa | ciccolini/Python | /Function.py | 2,459 | 4.46875 | 4 | #to create a function
#by using def keyword
def my_function():
print("Hello from a function")
#to call a function
my_function()
#to add as many parameters as possible
def my_function(fsurname):
print(fsurname + " " + "Name")
my_function("Anthony")
my_function("Romain")
my_function("MP")
#improvement
def my_f... | true |
e09d88413f22afee9604ef82652ba6a367214362 | idan0610/intro2cs-ex3 | /decomposition.py | 897 | 4.25 | 4 | ######################################################################
# FILE: decomposition.py
# WRITER: Idan Refaeli, idan0610, 305681132
# EXERCISE: intro2cs ex3 2014-2015
# DESCRIPTION:
# Find the number of goblets Gimli drank of each day
#######################################################################
num_... | true |
625086292e7df6169fd0029150706ea71f67c7bc | Nermeen3/Python-Practice | /Merge Sort Recursion.py | 1,444 | 4.40625 | 4 | ### Merge sort: works by dividing the array into halves and each half into another half
### until we're left with n arrays each holds one element from the original array
### then we go back up by comparing arrays and sorrting them as we go up
### time complexity is O(nlogn)
### Auxillary space is O(n)
from random impo... | true |
761d028f12ce52d7b4893506879955c25c7037b0 | ThushanthaSanju/Algorithm-Python | /BubbleSort.py | 374 | 4.46875 | 4 | array1 = []
for v in range(8):
array1.append(int(input("Enter the number : ")))
print(array1)
def bubbleSort(array):
n=len(array)
for i in range (0,n):
for j in range(n-1,i,-1):
if array[j]<array[j-1]:
array[j],array[j-1] = array[j-1],array[j]
bubbleSort(array1)
print... | false |
cc35fdcb39ec8d8d70e9bbc4d325fadfecba12cb | thaynagome/teste_python_junior | /teste_1015.py | 656 | 4.15625 | 4 | #!/usr/bin/env python
# -- coding: utf-8 --
#Importa a biblioteca para a raiz quadrada
import math
#Solicitará em uma linha a inserção dos valores em uma linha
x1,y1 = input("Digite os valores de x1 e y1: ").split(" ")
# Converte os valor para flutuantes
x1 = float(x1)
y1 = float(y1)
#Solicitará em uma linha a i... | false |
f46ab39b3d768e73922c1d09ec115c9e92c566b8 | arriolac/Project-Euler | /problem19.py | 1,318 | 4.25 | 4 | def is_leap_year(year):
return year % 4 == 0 and ((year % 400 == 0) or (year % 100 != 0))
def num_days_for_year(year):
num_days_in_feb = (29 if is_leap_year(year) else 28)
return (4 * 30) + (31 * 7) + num_days_in_feb
def num_days_for_month(month, year):
if month == 2:
return (29 if is_leap_y... | false |
39351a74c9a0e7e20d2fd64e10982fdd2cd0611b | ospupegam/for-test | /Processing_DNA_in_file .py | 570 | 4.28125 | 4 | '''
Processing DNA in a file
The file input.txt contains a number of DNA sequences, one per line. Each sequence starts with the same 14 base pair fragment – a sequencing adapter that should have been removed.
Write a program that will
trim this adapter and write the cleaned sequences to a new file
print the length of... | true |
566e05e99024a9a86095738523f5ad0522c41da1 | DanglaGT/code_snippets | /pandas/operations_on_columns.py | 303 | 4.15625 | 4 |
import pandas as pd
# using a dictionary to create a pandas dataframe
# the keys are the column names and the values are the data
df = pd.DataFrame({
'x': [1, 3, 5],
'y': [2, 4, 6]})
print(df)
# adding column x and column y in newly created
# column z
df['z'] = df['x'] + df['y']
print(df)
| true |
c6dd52dc9c6f3ff0711c27cfe6acc4f4eaedffdd | jmccutchan/python_snippets | /generator.py | 1,386 | 4.1875 | 4 | #This example uses generator functions and yields a generator instead of returning a list
#use 'yield' instead of 'return' - yield a generator instead of returning a list, this consumes less memory
def index_words(text):
if text:
yield 0
for index, letter in enumerate(text):
if letter == ' ':
... | true |
01a3983ad06be499932f3b89cf27a63d49239c6a | FabianoBill/Estudos-em-Python | /Curso-em-video/115-exerciciospython/d103_ficha_jogador.py | 444 | 4.34375 | 4 | # Exercício Python 103: Faça um programa que tenha uma função chamada ficha(), que receba dois parâmetros opcionais: o nome de um jogador e quantos gols ele marcou. O programa deverá ser capaz de mostrar a ficha do jogador, mesmo que algum dado não tenha sido informado corretamente.
def ficha(j="<desconhecido>", g=0):... | false |
5d25b7f11594efecde8c32383658f942ce0b8f37 | FabianoBill/Estudos-em-Python | /Exercicios/Contagem-caracteres-dicionario.py | 1,370 | 4.125 | 4 | def contar_caracteres(s):
"""Função que conta os caracteres de uma string
Ex:
>>> contar_caracteres('banana')
{'b': 1, 'a': 3, 'n': 2}
:param s: string a ser contada
"""
resultado = {}
for caracter in s:
# contagem = resultado.get(caracter, 0)
# contagem += 1
#... | false |
bd190ff7638072ae4befb62e0c73c880d61bb371 | FabianoBill/Estudos-em-Python | /Curso-em-video/115-exerciciospython/d073_times.py | 576 | 4.21875 | 4 | # Exercício Python 73: Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre: a) Os 5 primeiros times.b) Os últimos 4 colocados.c) Times em ordem alfabética.d) Em que posição está o time da Chapecoense.
times = ("a", "e", "i", "o", "u... | false |
42fd336b56a83f68c5d05f22818c28d39b67f195 | FabianoBill/Estudos-em-Python | /Curso-em-video/115-exerciciospython/d095_futebol2.py | 1,561 | 4.125 | 4 | # Exercício Python 093: Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ler o nome do jogador e quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida. No final, tudo isso será guardado em um dicionário, incluindo o total de gols feitos durante o c... | false |
b5a4675e7b252d58079c48e760ebfe623a8cbecd | FabianoBill/Estudos-em-Python | /Curso-em-video/115-exerciciospython/d099_maior.py | 477 | 4.25 | 4 | # Exercício Python 099: Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores inteiros. Seu programa tem que analisar todos os valores e dizer qual deles é o maior.
def maior(* prmt):
c = max = 0
for valor in prmt:
if c == 0:
max = valor
els... | false |
58bd82ac0a4eb5331736225afcb3e1ec9865f0a7 | Stheycee/Exerc-cio | /stheyce_q2_tuplas.py | 1,325 | 4.625 | 5 | '''
é comum no jogo de dominó ter uma rodada antes de iniciar o jogo na qual todos os integrantes escolhem
apenas uma pedra e quem retirar o maior valor inicia o jogo,
outra situação é quando o jogo fecha e inicia a contagem de pontos, aquele que tiver a menor pontuação vence.
simule um jogo de dominó com quatro jogado... | false |
5b4d8c87bdac439f9129969434726c5f1d988172 | jeffalstott/powerlaw | /testing/walkobj.py | 2,106 | 4.21875 | 4 | """walkobj - object walker module
Functions for walking the tree of an object
Usage:
Recursively print values of slots in a class instance obj:
walk(obj, print)
Recursively print values of all slots in a list of classes:
walk([obj1, obj2, ...], print)
Convert an object into a typed tree
typ... | true |
dea24af2de89866d3a77fce75b268f6be6306b8d | AntGrimm/180bytwo_home_assignment | /app.py | 1,881 | 4.21875 | 4 | # Functions are commented out at the bottom, remove comment to run each function
import itertools
# Removing a character in a loop and checking word against dictionary
def check_super_word(check_str, dictionary):
for i in range(0, len(check_str)): # Removing each character in loop
new_str = ''.join([che... | true |
41d2b009044c0725c83d588cc15700d4775a48a6 | KKEIO1000/Sorting-Algorithms | /Bubble Sort (Optimized Ω(n)).py | 707 | 4.3125 | 4 | import random
def bubble_sort(lst):
"""Function to sort a list via optimized bubble sort, O(n^2), Ω(n) if the list is already sorted"""
#Sets a flag so if no swap happened, the loop exits
sort = True
#Main body of the iterative loop
while sort:
sort = False
for i in range(len(lst)-1):
... | true |
a55e7da40409b9160df98169b4bf7ac36eb7735b | sajay/learnbycoding | /learnpy/capital_city_loop.py | 1,449 | 4.5625 | 5 | #Review your state capitals along with dictionaries and while loops!
#First, finish filling out the following dictionary with the remaining states and their
#associated capitals in a file called capitals.py. Or you can grab the finished file directly from the exercises folder in the course repository #on Github.
#capit... | true |
3fe028c17fbe2be2504d6caee35ada09f9c008d2 | sajay/learnbycoding | /dailycodeproblems/car-cdr.py | 944 | 4.34375 | 4 | #This problem was asked by Jane Street.
#cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair.
#For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.
# Given this implementation of cons:
# def cons(a, b):
# def pair(f):
# return f(a, b)
# ... | true |
5196bf1716062f91599b7fd2456156aaa5ef3e8f | Davidsaemund/TileTraveller_Assign_8 | /TileTraveller.py | 2,521 | 4.15625 | 4 | # Assignment 8
# Tile Traveler
# Program that moves NORTH, SOUTH, WEST and EAST in a 3v3 tile plan.
#Function that gets your current loc and tells you what options you have
def tile_traveller(x,y):
if (x == 1 and y == 1) or (x == 2 and y == 1):
print("You can travel: (N)orth.")
elif (x == 1 and y ==... | false |
1030840b3ca5e98c70aa8d878c41a3bffed72114 | niqaabi01/Intro_python | /Week2/Perimter2.py | 577 | 4.1875 | 4 | width1 = float(input("enter width one : "))
height1 =float(input("enter height one : "))
width2 = float(input("enter width two : "))
height2 = float(input("enter height two :"))
cost_mp =float(input(" enter price per meter :"))
height = 2 * float(height1)
width = float(width1) + (width2)
def multiply(width):
re... | true |
2551c03e063d0cd16da6e3e0ee2881f5279faaae | ewang14/hello-world | /pizza.py | 2,399 | 4.1875 | 4 | # pizzaQuiz2
# tell the user what's going on
print ("What Type of Pizza Are You?")
print (" ")
print ("Take our quiz to find out what type of pizza you are!")
print (" ")
# player information on the player
player = {
"name": "unknown",
"superpower": "unknown",
"faveColor" : "unknown",
"drink" : "unknown"
}
#... | true |
4058a599a844f012a9a8367d8cce7c3fbad2cdea | StephanieTabosa/estudo-python | /aula07desafio008.py | 520 | 4.21875 | 4 | # Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros
metros = float(input('Digite um valor em metros: '))
centimetros = metros*100
milimetros = metros*1000
dm = metros*10
dam = metros/10
hm = metros/100
km = metros/1000
print('\n O valor {} está em metros.\n Sua con... | false |
fa1e91ecda206b22c8e5f78feda5caf988b0fe5e | StephanieTabosa/estudo-python | /aula10desafio033.py | 429 | 4.125 | 4 | # Faça um programa que leia três números e mostre qual é o maior e qual é o menor.
import math
numero = float(input('Digite o primeiro número: '))
numero2 = float(input('Digite o segundo número: '))
numero3 = float(input('Digite o terceiro número: '))
lista = [numero, numero2, numero3]
print('O MENOR número é... | false |
735db79beeb3cb7c513e97a79f5aa846b15d46d2 | rspurlock/SP_Online_PY210 | /students/rspurlock/lesson4/dict_lab.py | 2,290 | 4.5625 | 5 | #!/usr/bin/env python3
def printDictionary(dictionary):
"""
Function to display a dictionary in a nice readable fashion
Positional Parameters
:param dictionary: Dictionary to print key/value pairs for
"""
# Loop thru all the dictionary items (key/value pairs) printing them
for key, value... | true |
0ff5d9ba153ea7e0cf4b5e246199f6ee4a825a76 | danilocecci/CEV-Python3 | /ex063.py | 226 | 4.125 | 4 | sequence = int(input('Digite a quantidade de números fibonacci que deseja: '))
numbers = [0, 1]
counter = 2
while counter < sequence:
numbers.append(numbers[counter-1]+numbers[counter-2])
counter += 1
print(numbers) | false |
63af36128dff39515a0ae170f713e96b44d26e9a | danilocecci/CEV-Python3 | /ex005.py | 258 | 4.21875 | 4 | print('Vamos verificar o antecessor e o sucessor de um número!')
numero = int(input('Para isso, preciso que digite um número: '))
print('O antecessor de "{}" é {}!'.format(numero, (numero-1)))
print('O sucessor de "{}" é {}!'.format(numero, (numero+1)))
| false |
50c346bdbdbd12de77a6f3c92e0928e027440cf9 | emurph1/ENGR-102-Labs | /CFUs/CFU3.py | 1,304 | 4.125 | 4 | # By submitting this assignment, I agree to the following:
# “Aggies do not lie, cheat, or steal, or tolerate those who do”
# “I have not given or received any unauthorized aid on this assignment”
# Emily Murphy
# ENGR 102-552
# CFU 3
# 10/03/2018
homework = int(input('Enter homework grade: ')) # user input... | true |
65699bd59c477e72c32d3b57072b08750c07724b | RyanRosvall/program-arcade-games | /Lab 01 - Calculator/lab_01_part_a.py | 238 | 4.1875 | 4 | #!/usr/bin/env python3
#Fahrenheit to Celsius conversion
#Ryan Rosvall
#11/1/17
temperature = int(input("Enter temperature in Fahrenheit: "))
conversion = ((temperature - int(32)) * 5/9)
print('The temperature in Celsius: ' + str(conversion))
| false |
bc2cebe6671e920cb68096f6222ff5a24846a32e | greenfox-zerda-lasers/hvaradi | /week-04/day-4/trial.py | 380 | 4.25 | 4 | # def factorial(number):
# product=1
# for i in range(number):
# product=product * (i+1)
# return product
#
# print(factorial(3))
def factorial(number):
if number <= 1:
return 1
else:
return number * factorial(number-1)
print(factorial(3))
# product = 1
# for i in range (... | true |
76459e26f6290338ca907294bc7d5daf660e2491 | greenfox-zerda-lasers/hvaradi | /week-05/day-1/helga_work.py | 834 | 4.1875 | 4 | #Write a function, that takes two strings and returns a boolean value based on
#if the two strings are Anagramms or not.
from collections import Counter
word1="hu la"
word2="hoop"
def anagramm(word1, word2):
letters1=[]
letters2=[]
for i in range(len(word1)):
letters1.append(word1.lower()[i])
... | true |
19e59384dc5e93fe24c6be1d883c441b6de1a7e7 | greenfox-zerda-lasers/hvaradi | /week-03/day-3/circle_area_circumference.py | 618 | 4.3125 | 4 | # Create a `Circle` class that takes it's radius as cinstructor parameter
# It should have a `get_circumference` method that returns it's circumference
# It should have a `get_area` method that returns it's area
class Circle():
radius = 0
def __init__(self, radius, pi):
self.radius = radius
self.pi = 3.14... | true |
b881fe869bdf97f6da563415c2b3a7bd7da23434 | Amar-Ag/PythonAssignment | /Functions3.py | 1,623 | 4.8125 | 5 | """
11) Python program to create a lambda function that adds 15 to a given
number passed in as an argument, also create a lambda function that multiplies
argument x with argument y and print the result.
"""
fifteen = lambda num: num + 15
multiplyTwo = lambda num1, num2: num1 * num2
print(fifteen(15))
print(multiplyTwo... | true |
c1c57774c47113e39d38d942341708aff20135af | TomMarquez/Evolutionary-Programming | /Final_Project/Main.py | 1,391 | 4.125 | 4 | from Population import Population
from Window import Window
import tkinter as tk
from tkinter import *
import random
import time
import random
import matplotlib.pyplot as plt
def main():
pop_size = 100
iteration = 10000
max_fit = 0
top_fit = 0
average_fit = 0
pop = Population(pop_size, 10, 10)... | true |
490b325247e485c5f28db97b58f4b255be2c04b2 | RomanKV-1/lesson1 | /hard1.py | 370 | 4.125 | 4 | #Пользователь вводит число определите, является ли данное число простым. Делится только на себя и на единицу
n = int(input('Введите число'))
d = 2
while n % d != 0:
d += 1
if d == n:
print('Число простое')
else:
print('Число составное')
| false |
f15086d8e41223760acc5830fe0051e5b6edaa75 | chay360/learning-python | /ex3.py | 519 | 4.3125 | 4 | #.............Numbers and Math..........#
print("I will count my chickens:")
print("Hens", 25 + 30/6)
print("Roosters",100 -25 * 3 % 4)
print("Now i will count eggs:")
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
print("Is it true that 2 + 3 < 5 - 7?")
print(2 + 3 < 5 - 7)
print("What is 3 + 2?", 3 + 2)
print("What i... | true |
dbf2ad366c7b4cdb31587c9f352a24b1f9e41252 | MLGNateDog/untitledPycharmProject | /Comparison Operators.py | 222 | 4.34375 | 4 | # Here are the different types of Comparison Operators
# > Greater than
# >= Greater than or equal to
# < Less than
# <= Less than or equal to
# == equal to
# != not equal to
# Example of use
x = 3 != 2
print(x) | true |
b9f5a15e8e0af0c669f2b4f1623b0927fa2a1375 | KnowledgeMavens/Science-Tech | /Pandas9-30-17/DataFrames2.py | 629 | 4.1875 | 4 | '''https://pythonprogramming.net/basics-data-analysis-python-pandas-tutorial/
'''
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
style.use('fivethirtyeight')
web_stats = {'Day':[1,2,3,4,5,6],
'Visitors':[43,34,65,56,29,76],
'Bounce Rate':[... | false |
1f2a525543983b83a41d64c22b57ff3c2286541b | Momolunar/mypackage | /recsort/recursion.py | 1,537 | 4.5 | 4 | def sum_array(array):
'''
Return sum of all items in array
Args:
array (array): list or array-like object containing numerical values.
Returns:
int: sum of items.
Examples:
>>> sum_array([1,2,3,4,5])
15
'''
if len(array)==1: #if one item in list, return... | false |
cb1d0c79331de9a64c5973e7db253ac42f783265 | omogbolahan94/Budget-App | /main.py | 2,024 | 4.3125 | 4 |
class Budget:
"""
Create a Budget class that can instantiate objects based on different
budget categories(class instances) like food, clothing, and entertainment.
These objects should allow for:
1. Depositing funds to each of the categories
2. Withdrawing funds from each category
3. Comp... | true |
2440ddb0f0e2bc3873f11d0fe7bee65d50b55365 | zhianwang/Python | /Regression/A02Module_G33419803.py | 2,852 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 24 16:53:56 2016
@author: Zhian Wang
GWID: G33419803
This program is define 3 function to to compute the regression coefficients
for the data in an input csv file and plot the regression.
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from... | true |
0ff2439b7a7ced2ab34e6f91b0eb9fbe8f2122ce | Aqua5lad/CDs-Sample-Python-Code | /ListForRange.py | 1,315 | 4.53125 | 5 | # Colm Doherty 2018-02-21
# These are chunks of code I've written to test the List, For & Range functions
# they are tested & proven to work!
# here are some Lists, showing indexing & len(gth) (ie. number of items)
Beatles = ['John', 'Paul', 'George', 'Ringo']
print ("the third Beatle was", Beatles[-2])
print ("the ... | true |
852c089e789383369c2b5f7a58efeacd1142aab6 | mwenz27/python_onsite_2019 | /week_01/05_lists/Exercise_01.py | 568 | 4.15625 | 4 | '''
Take in 10 numbers from the user. Place the numbers in a list.
Using the loop of your choice, calculate the sum of all of the
numbers in the list as well as the average.
Print the results.
'''
num = []# create a list of numbers
count = 0
try:
print('Input numbers 10 times \n')
for i in range(10):
... | true |
437962b8b376a8148dd7848d5aeebc836f08a188 | mwenz27/python_onsite_2019 | /week_03/02_exception_handling/04_validate.py | 562 | 4.59375 | 5 | '''
Create a script that asks a user to input an integer, checks for the
validity of the input type, and displays a message depending on whether
the input was an integer or not.
The script should keep prompting the user until they enter an integer.
'''
flag = True
while flag:
try:
user_input = input('En... | true |
d2ba4e9f40f018006ef974c6a2a1624120ff5aff | mwenz27/python_onsite_2019 | /week_01/04_strings/01_str_methods.py | 938 | 4.40625 | 4 | '''
There are many string methods available to perform all sorts of tasks.
Experiment with some of them to make sure you
understand how they work. strip and replace are particularly useful.
Python documentation uses a syntax that might be confusing.
For example, in find(sub[, start[, end]]), the brackets indicate
opt... | true |
5b9ca8cd066392ae59f20e6e311ccefb363bebc0 | mwenz27/python_onsite_2019 | /week_01/04_strings/05_mixcase.py | 840 | 4.40625 | 4 | '''
Write a script that takes a user inputted string
and prints it out in the following three formats.
- All letters capitalized.
- All letters lower case.
- All vowels lower case and all consonants upper case.
'''
sentence = "If real is what you can feel, smell, taste and see, then real is simply electri... | true |
1eeaf888fcb40efb3cce79e2143649c269314c97 | JaredFlomen/LearningPython | /conditionals.py | 732 | 4.25 | 4 | a = -1
if a > 0:
print('A is a positive number')
elif a < 0:
print('A is a negative number')
else:
print('A is zero')
b = -1
print('B is positive') if b > 0 else print('B is negative')
a = 3
if a > 0 and a % 2 == 0:
print('A is an even and positive integer')
elif a > 0 and a % 2 != 0:
print('A is a positive... | false |
2e6f49c33c863d56f3270f10ffb4d2467b8074cd | standrewscollege2018/2021-year-11-classwork-RyanBanks1827 | /List playground.py | 569 | 4.28125 | 4 | # For lists we use square brackets
# Items must be split by comma
# Items = ["Item1", "Item2"]
# print(Items[0])
# To add something to the end of a list, use append()
# Items.append("Dr Evil")
# To add something directly into a list, use the Items.insert() or list.insert()
# Items.insert(1, "Dr good")
# Lists are ... | true |
838fdf5d8d24feaa89d08ef78f434be1247e5756 | spohlson/Linked-Lists | /circular_linked.py | 1,557 | 4.21875 | 4 | """ Implement a circular linked list """
class Node(object):
def __init__(self, data = None, next = None):
self.data = data
self.next = next
def __str__(self):
# Node data in string form
return str(self.data)
class CircleLinkedList(object):
def __init__(self):
self.head = None
self.tail = None
se... | true |
56fcf653effc79c4b8371d94f5102088b7253dcb | ParkerCS/ch-tkinter-sdemirjian | /tkinter_8ball.py | 2,493 | 4.59375 | 5 | # MAGIC 8-BALL (25pts)
# Create a tkinter app which acts as a "Magic 8-ball" fortune teller
# The user asks a yes/no question that they want an answer to.
# Then the user clicks a button, and your program displays
# the "magic" random answer to their question.
# Your program will have the following properties:
# - Use ... | true |
e39e0dcff94b1416043dd5124c81bf8186e95809 | otisscott/1114-Stuff | /Lab 6/sqrprinter.py | 269 | 4.125 | 4 | inp = int(input("Enter a positive integer: "))
for rows in range(inp):
row = ""
for columns in range(inp):
if columns < rows:
row += "#"
elif rows < columns:
row += "$"
else:
row += "%"
print(row)
| true |
ad608cd56dd0019920087c779e26f69e97d9882a | otisscott/1114-Stuff | /Lab 2/simplecalculator.py | 490 | 4.25 | 4 | firstInt = int(input("Please enter the first integer:"))
secondInt = int((input("Please enter the second integer:")))
simpSum = str(firstInt + secondInt)
simpDif = str(firstInt - secondInt)
simpProd = str(firstInt * secondInt)
simpQuot = str(firstInt // secondInt)
simpRem = str(firstInt % secondInt)
print("This sum i... | true |
6f0cb2d42343987c32067f038502547114b46511 | aleckramarczyk/project-euler | /smallestmultiple.py | 839 | 4.125 | 4 | #2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
def main():
found = False
num = 2520
#any number that is divisible by 1 through 20 will be a multi... | true |
53bfe4d2a4a989302f4dae54d7fa4bb106da5d9d | anastasiiavoronina/python_itea2020 | /py_itea2020_classes/lesson01/lesson01_task02.py | 376 | 4.21875 | 4 | dict_countries = {
'Ukraine': 'Kiev',
'Poland' : 'Warsaw',
'Great Britain' : 'London',
'France' : 'Paris',
'Belarus': 'Minsk'
}
list_countries = ['Spain', 'Poland', 'Ukraine', 'France', 'Italy', ' Norway', 'Greece']
for country in list_countries:
if country in dict_countries:
print(dic... | false |
ee9d9d9256c74a84275211c616b8e4f1bf3b22b9 | jeremy-wischusen/codingbat | /python/logicone/caught_speeding_test.py | 819 | 4.1875 | 4 | """
You are driving a little too fast, and a police officer stops you.
Write code to compute the result, encoded as an int value:
0=no ticket, 1=small ticket, 2=big ticket.
If speed is 60 or less, the result is 0.
If speed is between 61 and 80 inclusive, the result is 1.
If speed is 81 or more, the result is 2.
... | true |
af1ef8b6837deec2de38278564e515bb854d92d8 | sandeep-skb/Data-Structures | /Python/Trees/diameter.py | 1,465 | 4.25 | 4 | class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
def height(node):
if node == None:
return 0
return (max(height(node.left), height(node.right))+1)
def diameter(node):
'''
The diameter of a tree (sometimes called the width) is the number of nodes on th... | true |
04b293e819b642b0755f35e10fd270879f0b5a32 | sandeep-skb/Data-Structures | /Python/Linked-list/Singly-Linked-List/exchange_by_2.py | 879 | 4.1875 | 4 |
def traverse(node):
if node != None:
print(node.data)
traverse(node.next)
def exchange(node):
prev = Node(0)
prev.next = node
head = prev
while((node != None) and (node.next != None)):
prev.next = node.next
temp = node.next.next
node.next.next = node
... | true |
4a04175c4580b1f1045f0697e6f2aaf43cabd164 | JSisques/Python-Toolbox | /Seccion 03 - Estructuras de datos/01-Listas.py | 2,418 | 4.59375 | 5 | '''
Una lista es una variable que contiene varios datos o variables de cualquier tipo
Se puede crear una lista vacia utilizando []
Los elementos de las tienen posiciones, siendo la primera posicion la 0 y la ultima la longitud de la lista menos 1
'''
miLista = ["Javi", "Perro", 6, True, 7.5]
listaVacia = []
'''
Para ... | false |
a309f848cc6480e61dab0cc08c5cda2cac0b890e | JSisques/Python-Toolbox | /Seccion 04 - Funciones/01-Funciones.py | 2,801 | 4.1875 | 4 | '''
Una funcion en programación es un tipo de sentencia que puede o no tener valores de entrada (parametros) y que puede devolver o no un valor de retorno
La sintaxis de los metodos o funciones es la siguiente: nombreMetodo(parametros separados por comas)
Ejemplos:
1. comprobarLetra(letra)
2. comprobarResultado... | false |
dac456345780fe6ced123598995a6e2285a89ef2 | zabcdefghijklmnopqrstuvwxy/AI-Study | /1.numpy/topic59/topic59.py | 1,558 | 4.4375 | 4 | #argsort(a, axis=-1, kind='quicksort', order=None)
# Returns the indices that would sort an array.
#
# Perform an indirect sort along the given axis using the algorithm specified
# by the `kind` keyword. It returns an array of indices of the same shape as
# `a` that index data along the given axis in so... | true |
0add5d9bcab734baa48b5bfc76db3e12b8be0617 | pratikv06/Python-Practice | /Object Oriented/2_class.py | 850 | 4.1875 | 4 | class Dog():
def __init__(self, name, age):
''' Its like constructor - called when object is created (once)'''
# self - represent object of that instance
self.name = name
self.age = age
def get_name(self):
''' Display dog name'''
print("Name: " + self.... | true |
ed8ce5ee6f148e1f31e3cbec554f3942455486c1 | beginner-lrk/test_python | /listandtuple.py | 1,782 | 4.4375 | 4 | #! /usr/bin/python
# -*- coding: UTF-8 -*-
# 变量classmates就是一个list,x=[ ]
print(1)
classmates = ['tom', 'Bob', '流川']
print(classmates)
print(len(classmates))
# 用索引来访问list中每一个位置的元素,记得索引是从0开始的,最后一个元素的索引是len(classmates) - 1。
print(classmates[0], classmates[1], classmates[len(classmates) - 1])
# 取最后一个元素,倒数第二个,倒数第三个
print(cla... | false |
9a707d82601e9d9624b52f04884606cfe8d81e53 | noevazz/learning_python | /035_list_comprehension.py | 681 | 4.46875 | 4 | #A list comprehension is actually a list, but created on-the-fly during program execution,
# and is not described statically.
# sintax = [ value for value in expression1 if expression2]
# it will generate a list with the values if the optional expression is True
my_list = [number for number in range(1, 11)] # this wil... | true |
e09e60bf03324e754a246d9ef71870103a86ee3a | noevazz/learning_python | /082__init__method.py | 811 | 4.3125 | 4 | # classes have an implicit method (that you can customize) to initialize your class with some values or etc.
# the __init__ method is called constructor
# __init__ cannot return a value!!!!!!!! as it is designed to return a newly created object and nothing else;
class MyNiceClass():
# whenever you see "self" it is us... | true |
1ac5d30ca8eb886ca9e3c293d490ca97d314024d | noevazz/learning_python | /072_ord_chr.py | 708 | 4.59375 | 5 | print("------ ord ------")
# if you want to know a specific character's ASCII/UNICODE code point value,
# you can use a function named ord() (as in ordinal).
print(ord("A")) # 65
print(ord("a")) # 97
print(ord(" ")) # 32 (a-A)
print(ord("ę"))
# The function needs a >strong>one-character string as its argument
# breachi... | true |
1e78bed77a7b9c6d2c986581073098305e0fb66b | noevazz/learning_python | /010_basic_operations.py | 676 | 4.59375 | 5 | # +, -, *, /, //, %, **
print("BINARY operators require 2 parts, e.g. 3+2:")
print("addition", 23+20)
print("addition", 23+20.) # if at least one number is float the result will be a float
print("subtraction", 1.-23)
print("multiplication", 2*9)
print("division", 5/2)
print("floor division", 5//2) # floor division (IT ... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.