blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
9b2f359901f6a835563e878a9f103dec0b110a86 | nguiaSoren/Snake-game | /scoreboard.py | 1,123 | 4.3125 | 4 | from turtle import Turtle
FONT = ("Arial", 24, "normal")
#
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
# Set initials score to 0
self.score = 0
# Set colot to white
self.color("white")
# Hide the turtle, we wonly want to see the text
self... | true |
ddfe13cbff04a326ed196b20beb8f1414364b086 | luzperdomo92/test_python | /hello.py | 209 | 4.25 | 4 | name = input("enter your name: ")
if len(name) < 3:
print("name must be al least 3 characters")
elif len(name) > 20:
print("name can be a maximun 50 characteres")
else:
print("name looks good!")
| true |
450b68eb2689957ce61da69333d6a0588820339d | GTVanitha/PracticePython | /bday_dict.py | 1,003 | 4.34375 | 4 |
birthdays = {
'Vanitha' : '05/05/90',
'Som' : '02/04/84',
'Vino' : '08/08/91'
}
def b_days():
print "Welcome to birthday dictionary! We know the birthdays of:"
names = birthdays.keys()
print ',\n'.join(names)
whose = raw_input("Who's birthday do you wa... | true |
4c71d1fa592e3c54844946aa62e8eb4f7c69f95f | Aravindan-C/LearningPython | /LearnSet.py | 535 | 4.3125 | 4 | __author__ = 'aravindan'
"""A set is used to contain an unordered collection of objects,To create a set use the set() function and supply a sequence of items such as follows"""
s= set([3,5,9,10,10,11]) # create a set of unique numbers
t=set("Hello") # create a set of unique characters
u=set("abcde")
"""set... | true |
06623bd65d8ba4d62713be768697929943c83e61 | Aravindan-C/LearningPython | /LearnIterationAndLooping.py | 640 | 4.15625 | 4 | __author__ = 'aravindan'
for n in [1,2,3,4,5,6,7,8,9,0]:
print "2 to the %d power is %d" % (n,2**n)
for n in range(1,10) :
print "2 to the %d power is %d" % (n,2**n)
a= range(5)
b=range(1,8)
c=range(0,14,3)
d=range(8,1,-1)
print a,b,c,d
a= "Hello World"
# print out the individual characters in a
for c in a :
... | false |
908ff1d7ed7b294b3bef209c6ca6ffbf43851ba8 | loc-dev/CursoEmVideo-Python-Exercicios | /Exercicio_008/desafio_008.py | 598 | 4.15625 | 4 | # Desafio 008 - Referente aula Fase07
# Escreva um programa que leia um valor em metros
# e o exiba em outras unidades de medidas de comprimento.
# Versão 01
valor_m = float(input('Digite um valor em metros: '))
print(' ')
print('A medida de {}m corresponde a: '.format(valor_m))
print('{}km (Quilômetro)'.format(valo... | false |
37e9ec85ea551c5a0f77ba61a24f955da77d0426 | loc-dev/CursoEmVideo-Python-Exercicios | /Exercicio_022/desafio_022.py | 662 | 4.375 | 4 | # Desafio 022 - Referente aula Fase09
# Crie um programa que leia o nome completo de uma pessoa
# e mostre:
# - O nome com todas as letras maiúsculas e minúsculas.
# - Quantas letras no total (sem considerar espaços).
# - Quantas letras tem o primeiro nome.
nome = input("Digite o seu nome completo: ")
print('')
print... | false |
c21762ec2545a3836c039837ec782c8828044fca | jkusita/Python3-Practice-Projects | /count_vowels.py | 1,833 | 4.25 | 4 | # Count Vowels – Enter a string and the program counts the number of vowels in the text. For added complexity have it report a sum of each vowel found.
vowel_list = ["a", "e", "i", "o", "u"]
vowel_count = 0 # Change this so it adds all the values of the keys in the new dictionary.
vowel_count_found = {"a": 0, "e": 0, ... | true |
2487fdd78e971f078f6844a2fa5bb0cd031b0d71 | Dunkaburk/gruprog_1 | /grundlaggande_programvareutveckling/week2/src/samples/MathMethods.py | 751 | 4.25 | 4 | # package samples
# math is the python API for numerical calculations
from math import *
def math_program():
f_val = 2.1
print(f"Square root {sqrt(f_val)}")
print(f"Square {pow(f_val, 2)}")
print(f"Floor {floor(f_val)}")
print(f"Ceil {ceil(f_val)}")
print(f"Round {round(f_val)}")
# etc. ... | true |
1b54c0d17ea896a12aa2a20779416e0bac85d066 | Dunkaburk/gruprog_1 | /grundlaggande_programvareutveckling/week3_tantan/src/exercises/Ex4MedianKthSmallest.py | 901 | 4.15625 | 4 | # package exercises
#
# Even more list methods, possibly even trickier
#
def median_kth_smallest_program():
list1 = [9, 3, 0, 1, 3, -2]
# print(not is_sorted(list1)) # Is sorted in increasing order? No not yet!
# sort(list1) # Sort in increasing order, original order lost!
print(list1 == [-2, 0... | true |
16acd854ef3b668e05578fd5efff2b5c2a6f88f4 | Dunkaburk/gruprog_1 | /grundlaggande_programvareutveckling/Week1Exercises/Week1Exercises/week1/src/exercises/Ex2EasterSunday.py | 1,705 | 4.3125 | 4 | # package exercises
# Program to calculate easter Sunday for some year (1900-2099)
# https://en.wikipedia.org/wiki/Computus (we use a variation of
# Gauss algorithm, scroll down article, don't need to understand in detail)
#
# To check your result: http://www.wheniseastersunday.com/
#
# See:
# - LogicalAnd... | true |
fd550e115ac526fe5ac6bc9543278a7d852325b6 | anthonysim/Python | /Intro_to_Programming_Python/pres.py | 444 | 4.5 | 4 | """
US Presidents
Takes the names, sorts the order by first name, then by last name.
From there, the last name is placed in front of the first name, then printed
"""
def main():
names = [("Lyndon, Johnson"), ("John, Kennedy"), ("Andrew, Johnson")]
names.sort(key=lambda name: name.split()[0])
names.sor... | true |
c1dceb57ede0b3eb1f1fe5fe658fe283116d68f3 | pythonic-shk/Euler-Problems | /euler1.py | 229 | 4.34375 | 4 | n = input("Enter n: ")
multiples = []
for i in range(int(n)):
if i%3 == 0 or i%5 == 0:
multiples.append(i)
print("Multiples of 3 or 5 or both are ",multiples)
print("Sum of Multiples of ",n," Numbers is ",sum(multiples)) | true |
7468f255b87e3b4aa495e372b44aba87ff2928d1 | tengrommel/go_live | /machine_learning_go/01_gathering_and_organizating_data/gopher_style/python_ex/myprogram.py | 449 | 4.3125 | 4 | import pandas as pd
'''
It is true that, very quickly, we can write some Python code to parse this CSV
and output the maximum value from the integer column without even
knowing what types are in the data:
'''
# Define column names
cols = [
'integercolumn',
'stringcolumn'
]
# Read in the CSV with pandas.
data... | true |
e863fd0cfe96478d6550b426d675de6cfc84c08a | kami71539/Python-programs-4 | /Program 19 Printing even and odd number in the given range.py | 515 | 4.28125 | 4 | #To print even numbers from low to high number.
low=int(input("Enter the lower limit: "))
high=int(input("ENter the higher limit: "))
for i in range(low,high):
if(i%2==0):
print(i,end=" ")
print("")
for i in range(low,high):
if(i%2!=0):
print(i,end=" ")
#Printing odd numbers ... | true |
61bef90211ffd18868427d3059e8ab8dee3fefde | kami71539/Python-programs-4 | /Program 25 Printing text after specific lines.py | 303 | 4.15625 | 4 | #Printing text after specific lines.
text=str(input("Enter Text: "))
text_number=int(input("Enter number of text you'd like to print; "))
line_number=1
for i in range(0,text_number):
print(text)
for j in range(0,line_number):
print("1")
line_number=line_number+1
print(text) | true |
38658702ed937a7ba65fd1d478a371e4c6d5e789 | kami71539/Python-programs-4 | /Program 42 Finding LCM and HCF using recursion.py | 259 | 4.25 | 4 | #To find the HCF and LCM of a number using recursion.
def HCF(x,y):
if x%y==0:
return y
else:
return HCF(y,x%y)
x=int(input(""))
y=int(input(""))
hcf=HCF(x,y)
lcm=(x*y)/hcf
print("The HCF is",hcf,". The LCM is",lcm) | true |
6f2ac1ae18a208e032f7f1db77f64710f3b9bd00 | kami71539/Python-programs-4 | /Program 15 Exponents.py | 221 | 4.375 | 4 | print(2**3)
def exponents(base,power):
i=1
for index in range(power):
i=i*base
return i
a=int(input(""))
b=int(input(""))
print(a, "raised to the power of" ,b,"would give us", exponents(a,b))
| true |
e80d7d475ddcf65eddd08d77aa4c2c03f965dfb9 | kami71539/Python-programs-4 | /Program 35 To count the uppercase and lowercase characters in the given string. unresolved.py | 458 | 4.125 | 4 | #To count the uppercase and lowercase characters in the given string.
string=input("")
j='a'
lower=0
upper=0
space=0
for i in string:
for j in range(65,92):
if chr(j) in i:
upper=upper+1
elif j==" ":
space=space+1
for j in range(97,123):
if chr(j) in ... | true |
870b35565e3ae8e46a0e2a12179675a20825f5c4 | targupt/projects | /project -1 calculator.py | 325 | 4.3125 | 4 | num1 = int(input("1st number "))
num2 = int(input("2nd number "))
sign = input("which sign(+,-,/,x or *)")
if sign == "+":
print(num1+num2)
elif sign == "-":
print(num1-num2)
elif sign == "/":
print(num1/num2)
elif sign == "x" or sign == "X":
print(num1*num2)
else:
print("wrong input please try aga... | false |
01c172d4c6c6b4d9714c2aca9b9d4b425a3933d3 | lexjox777/Python-conditional | /main.py | 838 | 4.21875 | 4 | # x=5
# y=6
# if x<y:
# print('Yes')
#==========
# if 'Hello' in 'Hello World!':
# print('Yes')
#==================
# x=7
# y=6
# if x > y:
# print('yes it is greater')
# elif x < y:
# print('no it is less')
# else:
# print('Neither')
#==================
# '''
# Nested if statement
# '''
# num... | false |
84650242ab531d3a0755452b8c6eb4476e0a710c | dncnwtts/project-euler | /1.py | 582 | 4.21875 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these
# multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
def multiples(n,k):
multiples = []
i = 1
while i < n:
if k*i < n:
multiples.append(k*i)
i += 1
else:
return m... | true |
e047b285aa5bf1b187187c52a22fae191836ed0f | chubaezeks/Learn-Python-the-Hard-Way | /ex19.py | 1,804 | 4.3125 | 4 | #Here we defined the function by two (not sure what to call them)
def cheese_and_crackers (cheese_count, boxes_of_crackers):
print "You have %d cheese!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
#We take tha... | true |
965cd05ce217b1b5d27cefb89b62935dc250a692 | hmkthor/play | /play_006.py | 590 | 4.40625 | 4 | """
Change a Range of Item Values
To change the value of items within a specific range, define a list with the new values,
and refer to the range of index numbers where you want to insert the new values:
"""
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermel... | true |
359ce1c69a952d51fd9024adade90be51e6ebb00 | LiuPengPython/algorithms | /algorithms/strings/is_rotated.py | 324 | 4.3125 | 4 | """
Given two strings s1 and s2, determine if s2 is a rotated version of s1.
For example,
is_rotated("hello", "llohe") returns True
is_rotated("hello", "helol") returns False
accepts two strings
returns bool
"""
def is_rotated(s1, s2):
if len(s1) == len(s2):
return s2 in s1 + s1
else:
return F... | true |
b1a9fee52ca6eae1ee380a0d95491d735c7360bd | jeantardelli/wargameRepo | /wargame/designpatterns/strategies_traditional.py | 1,633 | 4.15625 | 4 | """strategies_traditional
Example to show one way of implementing different design pattern strategies
in Python.
The example shown here resembles a 'traditional' implementation in Python
(traditional = the one you may implement in languages like
C++). For a more Pythonic approach, see the file strategies_pythonic.py... | true |
93b2af4c8f1a23483747d04ea3902c644b581543 | jeantardelli/wargameRepo | /wargame/performance-study/pool_example.py | 1,201 | 4.375 | 4 | """pool_example
Shows a trivial example on how to use various methods of the class Pool.
"""
import multiprocessing
def get_result(num):
"""Trivial function used in multiprocessing example"""
process_name = multiprocessing.current_process().name
print("Current process: {0} - Input number: {1}".format(proc... | true |
d37a677d52bcb30328947235f0198a9447ddeb34 | jeantardelli/wargameRepo | /wargame/GUI/simple_application_2.py | 1,025 | 4.125 | 4 | """simple_application_2
A 'Hello World' GUI application OOP using Tkinter module.
"""
import sys
if sys.version_info < (3, 0):
from Tkinter import Tk, Label, Button, LEFT, RIGHT
else:
from tkinter import Tk, Label, Button, LEFT, RIGHT
class MyGame:
def __init__(self, mainwin):
"""Simple Tkinter G... | true |
c72fb1953ee65169041fa399508fbd5204986270 | yeti98/LearnPy | /src/basic/TypeOfVar.py | 978 | 4.125 | 4 |
#IMMUTABLE: int,
## Immutable vs immutable var
#Case3:
# default parameter for append_list() is empty list lst []. but it is a mutable variable. Let's see what happen with the following codes:
def append_list(item, lst=[]):
lst.append(item)
return lst
print(append_list("item 1")) # ['item 1']
print(append... | true |
0243e8d54259a3cecd9e84443bae674a66f090f7 | amandamurray2021/Programming-Semester-One | /labs/week06-functions/menu2.py | 801 | 4.34375 | 4 | # Q3
# This program uses the function from student.py.
# It keeps displaying the menu until the user picks Q.
# If the user chooses a, then call a function called doAdd ().
# If the user chooses v, then call a function called doView ().
def displayMenu ():
print ("What would you like to do?")
print ("\t (a) Ad... | true |
581152e31c7db41497c55661eee0ad92026487cf | berkcangumusisik/CourseBuddiesPython101 | /Pratik Problemler/09 - Math Seviye 2/02 - basicCalculator.py | 477 | 4.3125 | 4 | """İki sayı ve bir operatör (+, -, *, /) alan ve hesaplamanın sonucunu döndüren bir fonksiyon yazın."""
def calculate(num1, operator, num2):
if operator == "+":
return num1 + num2
elif operator == "-":
return num1 - num2
elif operator == "*":
return num1 * num2
elif op... | false |
1f4677231483102e14e550023ca914280acf3a5c | berkcangumusisik/CourseBuddiesPython101 | /Pratik Problemler/06 - Lists Seviye 1/05 - insertLast.py | 387 | 4.125 | 4 | """ Alıştırma 4.1.5: Son Ekle
Listenin son elemanı olarak insert_last eklenen adında bir fonksiyon yazın x.
Not: Sen, işlev her zaman bir liste adı verilecek varsayabiliriz ancak, olabilir
değil bu liste boş olmadığını varsayalım."""
def insert_last(my_list, x):
if len(my_list) >= 0:
my_list.append(x)
... | false |
d39156f96eeac77c4a9e1606b3566ae0afbb4f84 | berkcangumusisik/CourseBuddiesPython101 | /1. Hafta/05 - Lab Saati Uygulamaları/ornek1.py | 1,012 | 4.40625 | 4 | """Python Hafta 1 - 1:
CourseBuddies üniversitesi öğrencilerinin mezun olup olamayacağını göstermek için
bir sistem oluşturmaya çalışıyor.
Öncelikle durumunu öğrenmek isteyen öğrencinin, ismini yaşını ve not ortalamasını
(0 - 100 arası) girmesi gerekiyor (input() fonksiyonu ile kullanıcıdan alıcak).
eğer kullanıcının y... | false |
0c8874c6ed0902384e7ba0790e5e1b28741868ba | berkcangumusisik/CourseBuddiesPython101 | /Pratik Problemler/13 - Lists Seviye 3/07 - sumTheLenghts.py | 413 | 4.21875 | 4 | """
Uzunlukları Topla
Bir sum_the_lengths listedeki tüm dizelerin uzunluğunu toplayan adlı bir işlev yazın .
Not: Sen, işlev her zaman bir liste adı verilecek varsayabiliriz ancak, olabilir
değil bu liste boş olmadığını varsayalım.
"""
def sum_length(my_list):
length = 0
for string in my_list:
length... | false |
dd32bd386f65c98a15f23d9a62b563eb8e48b96e | joscelino/Calculadora_estequiometrica | /Formula_Clapeyron/clapeyron_dinamica.py | 1,121 | 4.125 | 4 |
variable = int(input("""Choose a variable:
[1] Pressure
[2] Volume
[3] Number of moles
[4] Temperature
"""))
R = 0.082
if variable == 1:
# Inputs
V = float(input('Volume (L): '))
T = float(input('Temperature (K): '))
n = float(input('Number of moles: '))
# Formula
P = (n * R * T) / V
#... | false |
2df05235e11b4f969f147ffa6dcde19ceb0c0dec | VB-Cloudboy/PythonCodes | /10-Tuples/02_Access-Tuple.py | 403 | 4.125 | 4 | mytuple = (100,200,300,400,500,600,700,800,900)
#1. Print specific postion of the tuples starting from Right
print(mytuple[2])
print(mytuple[4])
print(mytuple[5])
#2. Print specific postion of the tuples starting from Left
print(mytuple[-3])
print(mytuple[-5])
print(mytuple[-4])
#3. Slicing (Start: Stop: Stepsize)
... | true |
b286bc4bd3179f174b808381c6f408bd80e2bcfe | ml758392/python_tedu | /python2/Day3_modlue_oop/pycharm/9.重写__repr__与__str__.py | 807 | 4.15625 | 4 | # -*-coding:utf-8-*-
"""
重写:可将函数重写定义一遍
__str__()
__repr__()
"""
class Person(object):
"""
:param
:parameter
"""
def __init__(self, name, age):
self.name = name
self.age = age
def myself(self):
print("I'm %s , %s years old " % (self.name, self.age))
# __str__()在... | false |
7e40c4b9259486ee55d80691c66f8a8cc0efb36c | ml758392/python_tedu | /nsd2018-master/nsd1804/python/day01/hello.py | 706 | 4.1875 | 4 | # 如果希望将数据输出在屏幕上,常用的方法是print
print('Hello World!')
print('Hello' + 'World!')
print('Hello', 'World!') # 默认各项之间用空格分隔
print('Hello', 'World!', 'abc', sep='***') # 指定分隔符是***
print('Hello World!', end='####')
# print默认在打印结束后加上一个回车,可以使用end=重置结束符
n = input('number: ') # 屏幕提示number: 用户输入的内容赋值给n
print(n) # input得到的数据全都是字符... | false |
8c326cefac9c979874f8a03334934c685a88c953 | forthing/leetcode-share | /python/152 Maximum Product Subarray.py | 813 | 4.21875 | 4 | '''
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
'''
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: Lis... | true |
88ddaec1c09a46fac173c4b520c6253b59aad09b | kmair/Graduate-Research | /PYOMO_exercises_w_soln/exercises/Python/fcn_soln.py | 1,248 | 4.40625 | 4 | ## Write a function that takes in a list of numbers and *prints* the value of the largest number. Be sure to test your function.
def print_max_value(nums):
print("The max value is: ")
print(max(nums))
## Write a function that takes a list of numbers and *returns* the largest number
def max_value(nums):
return ... | true |
82d3e7c695fbab62b222781240a1865cfe877151 | Kaushalendra-the-real-1/Python-assignment | /Q2.py | 779 | 4.125 | 4 | # class Person:
# def __init__(self):
# print("Hello Reader ... ")
# class Male(Person):
# def get_gender(self):
# print("I am from Male Class")
# class Female(Person):
# def get_gender(self):
# print("I am from Female Class")
# Obj = Female()
# Obj.get_gender()
# -----------------... | true |
e33a070506458cacbf4d52304982c491f2c9980d | xynicole/Python-Course-Work | /lab/435/ZeroDivideValue.py | 595 | 4.25 | 4 | def main():
print("This program will divide two numbers of your choosing for as long as you like\n")
divisorStr = input("Input a divisor: ")
while divisorStr:
dividendStr = input("Input a dividend: ")
try:
divisor = int(divisorStr)
dividend = int(dividendStr)
print (dividend ... | true |
881fc46faa626aaac3317dd9f65d3e8975b3f32e | xynicole/Python-Course-Work | /W12/kiloToMiles.py | 1,148 | 4.25 | 4 | '''
Stores value in kilometers
Retrieves value in kilometers or miles
Displays value in kilometers and miles
'''
class KiloToMiles:
# Constructor
def __init__(self, kilo = 0.0):
self.__kilo = float(kilo)
self.__KILO_TO_MILES = 0.6214 # Conversion constant
# ----------------------------------... | false |
240868c7fb1cf39a3db78c9c5912d7dc93c79e45 | SamuelMontanez/Shopping_List | /shopping_list.py | 2,127 | 4.1875 | 4 | import os
shopping_list = []
def clear_screen():
os.system("cls" if os.name == "nt" else "clear")
def show_help():
clear_screen()
print("What should we pick up at the store?")
print("""
Enter 'DONE' to stop adding items.
Enter 'HELP' for this help.
Enter 'SHOW' to see your current list.
Ente... | true |
ec8887453eaa5f263665f651338a470b4b8c5f7c | lura00/guess_the_number | /main.py | 915 | 4.15625 | 4 | from random import randint
from game1 import number_game
def show_menu():
print("\n===========================================")
print("| Welcome |")
print("| Do you want to play a game? |")
print("| 1. Enter the number game |")
print("| ... | true |
13006b2b8a77c97f0f190a3228aa53452bbefc6d | scardona7/nuevasTecnologias | /taller1/ejercicio11.py | 665 | 4.1875 | 4 | """ 11) Algoritmo que nos diga si una persona puede acceder a cursar un ciclo formativo de grado superior o no. Para acceder a un grado superior, si se tiene un titulo de bachiller, en caso de no tenerlo, se puede acceder si hemos superado una prueba de acceso. """
titulo_bach = input("¿Tiene un titulo Bachiller?: (si... | false |
18a73e6c8cd9289ce5ba0fd1006dc2ce400e375f | LehlohonoloMopeli/level_0_coding_challenge | /task_3.py | 350 | 4.1875 | 4 | def hello(name):
"""
Description: Accepts the name of an individual and prints "Hello ..." where
the ellipsis represents the name of the individual.
type(output) : str
"""
if type(name) == str:
result = print("Hello " + name + "!")
return result
else:
... | true |
9d07cb1bbb8e780c193dbb19c6c0ef4b83cb7914 | unfo/exercism-python | /bob/bob.py | 723 | 4.25 | 4 | def hey(sentence):
"""
Bob is a lackadaisical teenager. In conversation, his responses are very limited.
Bob answers 'Sure.' if you ask him a question.
He answers 'Whoa, chill out!' if you yell at him.
He says 'Fine. Be that way!' if you address him without actually saying
anything.
He answers 'Whatever.' to any... | true |
be97e8da8f3733fbb6c0a2e8abb0b950a11181c4 | fitzcn/oojhs-code | /loops/printingThroughLoops.py | 313 | 4.125 | 4 | """
Below the first 12 numbers in the Fibonacci Sequence are declared in an array list (fibSeq).
Part 1, Use a loop to print each of the 12 numbers.
Part 2, use a loop to print each of the 12 numbers on the same line.
"""
fibSeq = ["1","1","2","3","5","8","13","21","34","55","89","144"]
#part 1
#part 2
| true |
d190cf17e29502fd451ff812f68414fef94eeec9 | aysin/Python-Projects | /ex32.py | 538 | 4.65625 | 5 | #creating list while doing loops
the_count = [1, 2, 3, 4, 5]
fruits = ['apple', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
#this first kind of for loop goes through a list
for n in the_count:
print "This is count %d." % n
#same as above
for n in fruits:
print "A fruit type ... | true |
cde03d01900ffa7f01f5f80e4bfc869454ac8116 | AshTiwari/Python-Guide | /OOPS/OOPS_Abstract_Class_and_Method.py | 720 | 4.5625 | 5 | #abstract classes
# ABC- Abstract Base Class and abstractmethod
from abc import ABC, abstractmethod
print('abstract method is the method user must implement in the child class.')
print('abstract method cannot be instantiated outside child class.')
print('\n\n')
class parent(ABC):
def __init__(self):
pass... | true |
94555b4909e244e1e8e9e23bb97ad48b81308118 | jinliangXX/LeetCode | /380. Insert Delete GetRandom O(1)/solution.py | 1,462 | 4.1875 | 4 | import random
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.result = list()
self.index = dict()
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain ... | true |
076a40fc02b0791eedaae92747394f46170a9678 | prathyusak/pythonBasics | /errors.py | 2,720 | 4.21875 | 4 | #Syntax Errors and Exceptions
#while True print('Hello world') => syntax error
#ZeroDivisionError =>10 * (1/0)
#NameError => 4 + spam*3
#TypeError => '2' + 2
#################
# Handling Exceptions
import sys
def this_fails():
x = 1/0
while True:
try:
x = int(input("Please enter a number: "))
t... | true |
57e443004e07c95bc99217d700e6b4f40f5c8a5f | yamaz420/PythonIntro-LOLcodeAndShit | /pythonLOL/vtp.py | 2,378 | 4.125 | 4 | from utils import Utils
class VocabularyTrainingProgram:
words = [
Word("hus", "house")
Word("bil", "car")
]
def show_menu(self):
choice = None
while choice !=5:
print(
'''
1. Add a new word
2. Shuffle the words i... | true |
4f55c17a043ee6a78b76220c8c25240a21b8195c | yamaz420/PythonIntro-LOLcodeAndShit | /pythonLOL/IfAndLoops.py | 1,881 | 4.15625 | 4 | #-----------!!!INDENTATION!!!-----------
# age = int(input("What is your age?"))
# if age >= 20:
# print("You are grown up, you can go to Systemet!")
# else:
# print("you are to young for systemet...")
# if age >= 20:
# if age >= 30:
# print("Allright, you can go to systemet for me, i hate sho... | true |
a891ee5380c54a475737976341d776b9ef44e15c | ShubhamGarg01/Faulty-Calculator | /faultycalci.py | 619 | 4.1875 | 4 | print("enter 1st number")
num1= int(input())
print("enter 2nd number")
num2= int(input())
print("so what u weant" ,"+,*,/,-,%")
num3= input()
if num1 == 45 and num2==3 and num3== "*":
print("555")
elif num1 ==56 and num2==9 and num3=="+":
print("77")
elif num1== 56 and num2==6 and num3=="/":
pr... | false |
421a3a05798ec7bfdfd104994e220ffb9f2613f7 | Tornike-Skhulukhia/IBSU_Masters_Files | /code_files/__PYTHON__/lecture_2/two.py | 1,401 | 4.1875 | 4 |
def are_on_same_side(check_p_1, check_p_2, point_1, point_2):
'''
returns True, if check points are on the same side of a line
formed by connecting point_1 and point_2
arguments:
1. check_p_1 - tuple with x and y coordinates of check point 1
2. check_p_2 - tuple with x and y coor... | true |
4cd244592bd39514d627fd2eea224af3edd60a48 | matheuszei/Python_DesafiosCursoemvideo | /0014_desafio.py | 231 | 4.34375 | 4 | #Escreva um programa que converta uma temperatura digitada em °C e converta para °F.
c = float(input('Informe a temperatura em C: '))
f = (c * 1.80) + 32
print('A temperatura de {}°C corresponde a {:.1}°F!'.format(c, f))
| false |
0fdc190bda0f1af4caf7354f380ce94134c70c78 | cizamihigo/guess_game_Python | /GuessTheGame.py | 2,703 | 4.21875 | 4 | print("Welcome To Guess: The Game")
print("You can guess which word is that one: ")
def check_guess(guess, answer):
global score
Still = True
attempt = 0
var = 2
global NuQuest
while Still and attempt < 3 :
if guess.lower() == answer.lower() :
print("\nCorrect Answer " + ans... | true |
0ebfa784abeddd768186f99209602dd7ef870e56 | feleHaile/my-isc-work | /python_work_RW/6-input-output.py | 1,745 | 4.3125 | 4 | print
print "Input/Output Exercise"
print
# part 1 - opening weather.csv file
with open ('weather.csv', 'r') as rain: # opens the file as 'read-only'
data = rain.read() # calls out the file under variable rain and reads it
print data # prints the data
# part 2 - reading the file line by line
with open ('weather.... | true |
a40fd3e7668b013a356cfa8559e993e770cc7231 | feleHaile/my-isc-work | /python_work_RW/13-numpy-calculations.py | 2,314 | 4.3125 | 4 | print
print "Calculations and Operations on Numpy Arrays Exercise"
print
import numpy as np # importing the numpy library, with shortcut of np
# part 1 - array calculations
a = np.array([range(4), range(10,14)]) # creating an array 2x4 with ranges
b = np.array([2, -1, 1, 0]) # creating an array from a list
# multip... | true |
12f3789e81a69e4daa75f9497dd94f382f5f0153 | zamunda68/python | /main.py | 507 | 4.21875 | 4 | # Python variable function example
# Basic example of the print() function with new line between the words
print("Hello \n Marin")
print("Bye!")
# Example of .islower method which returns true if letters in the variable value are lower
txt = "hello world" # the variable and its value
txt.islower() # using the .islow... | true |
1ef4a7869a5048f6d66fbdb56203fa2f0198fb22 | zamunda68/python | /dictionaries.py | 1,116 | 4.75 | 5 | """ Dictionary is a special structure, which allows us to store information in what is called
key value pairs (KVP). You can create one KVP and when you want to access specific information
inside of the dictionary, you can just refer to it by its key """
# Similar to actual dictionary, the word is the key and the mea... | true |
a95b3e4a2102e76c1a6b4932d6053a66b9593d5d | b-zhang93/CS50-Intro-to-Computer-Science-Harvard-Problem-Sets | /pset6 - Intro to Python/caesar/caesar.py | 1,022 | 4.21875 | 4 | from cs50 import get_string
from cs50 import get_int
from sys import argv
# check for CLA to be in order and return error message if so
if len(argv) != 2:
print("Usage: ./caesar key k")
exit(1)
# checks for integer and positive
elif not argv[1].isdigit():
print("Usage: ./caesar key k")
exit(1)
# defi... | true |
c891f23d90e49fa066d06e90fd5ad2d45c9afd7d | gmarler/courseware-tnl | /labs/py3/decorators/memoize.py | 1,122 | 4.1875 | 4 | '''
Your job in this lab is to implement a decorator called "memoize".
This decorator is already applied to the functions f, g, and h below.
You just need to write it.
HINT: The wrapper function only needs to accept non-keyword arguments
(i.e., *args). You don't need to accept keyword arguments in this lab.
(That is m... | true |
3f7a247198d94307902d20edec5016511a4343e6 | kpetrone1/kpetrone1 | /s7hw_mysqrt_final.py | 1,348 | 4.4375 | 4 | #23 Sept 2016 (Homework following Session 7)
#While a few adjustments have been made, the majority of the following code has been sourced from a blog titled "Random Thoughts" by Estevan Pequeno at https://epequeno.wordpress.com/2011/01/04/solutions-7-3/.
#function to test Newton's method vs. math.sqrt() to find squar... | true |
92297bb3778093c35679b32b2a1ffd22a3339403 | harsh52/Assignments-competitive_coding | /Algo_practice/LeetCode/Decode_Ways.py | 1,874 | 4.1875 | 4 | '''
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" c... | true |
28f0e5637cd7ca7d5b47451e27e6e1d0ac7db093 | zlatnizmaj/GUI-app | /OOP/OOP-03-Variables.py | 642 | 4.40625 | 4 | # In python programming, we have three types of variables,
# They are: 1. Class variable 2. Instance variable 3. Global variable
# Class variable
class Test():
class_var = "Class Variable"
class_var2 = "Class Variable2"
# print(class_var) --> error, not defined
x = Test()
print(x.class_var)
print(x.class_var2... | true |
1e45cfd30735bc93f3341bb6bfdec05603fa77fc | pravsp/problem_solving | /Python/BinaryTree/solution/invert.py | 1,025 | 4.125 | 4 | '''Invert a binary tree.'''
import __init__
from binarytree import BinaryTree
from treenode import TreeNode
from util.btutil import BinaryTreeUtil
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Invert:
... | true |
b6ff3bb38beaea248d13389d5246d449e8e8bf8a | Arushi96/Python | /Radical- Python Assignment Solutions/Loops and Conditions/Question 3.py | 367 | 4.15625 | 4 | #Assignment Questions
#Q: Write a program which calculates the summation of first N numbers except those which are divisible by 3 or 7.
n = int(input ("Enter the number till which you want to find summation: "))
s=0
i=0
while i<=n:
if (i%3==0)or(i%7==0):
#print(i)
i+=1
continue
else:
... | true |
35025370621c265eff6d02c68d4284525634f5e1 | mtjhartley/codingdojo | /dojoassignments/python/fundamentals/find_characters.py | 568 | 4.21875 | 4 | """
Write a program that takes a list of strings and a string containing a single character, and prints a new list of all the strings containing that character.
Here's an example:
# input
word_list = ['hello','world','my','name','is','Anna']
char = 'o'
# output
new_list = ['hello','world']
"""
def find_characters(lst... | true |
ac0c500a62196c5bf29fe013f86a82946fdb65b2 | mtjhartley/codingdojo | /dojoassignments/python/fundamentals/list_example.py | 854 | 4.28125 | 4 | fruits = ['apple', 'banana', 'orange']
vegetables = ['corn', 'bok choy', 'lettuce']
fruits_and_vegetables = fruits + vegetables
print fruits_and_vegetables
salad = 3 * vegetables
print salad
print vegetables[0] #corn
print vegetables[1] #bok choy
print vegetables[2] #lettuce
vegetables.append('spinach')
print veget... | true |
3389a2cb84c667ada3e41ec096592cfdbf6c2e07 | mtjhartley/codingdojo | /dojoassignments/python/fundamentals/compare_array.py | 2,432 | 4.3125 | 4 | """
Write a program that compares two lists and prints a message depending on if the inputs are identical or not.
Your program should be able to accept and compare two lists: list_one and list_two.
If both lists are identical print "The lists are the same".
If they are not identical print "The lists are not the same... | true |
19aa6ef97da6fdbb4a2a11fd2e66060d8a04f72e | nmarriotti/PythonTutorials | /readfile.py | 659 | 4.125 | 4 | ################################################################################
# TITLE: Reading files in Python
# DESCRIPTION: Open a text file and read the contents of it.
################################################################################
def main():
# Call the openFile method and pass it F... | true |
6a6034e699003b4a4ab0f11f7b2a9e89f235dc92 | Eugene-Korneev/GB_01_Python_Basics | /lesson_03/task_01.py | 822 | 4.25 | 4 | # Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
# Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
def divide(number_1, number_2):
if number_2 == 0:
return None
return number_1 / number_2
# num_1 = input("Введите перво... | false |
7b72749a9f1bbf33723e47ddd491529226a414d5 | Eugene-Korneev/GB_01_Python_Basics | /lesson_03/task_06.py | 1,205 | 4.4375 | 4 | # Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же,
# но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
# Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом.
# Каждое слово состоит из латинских букв в... | false |
22d1c4d381fbbf7cbf52568137b1b079f41e1e3c | RicardoBaniski/Python | /Opet/4_Periodo/Scripts_CEV/Mundo_01/Aula009.py | 1,449 | 4.78125 | 5 | print('''Nessa aula, vamos aprender operações com String no Python. As principais operações que vamos aprender são o Fatiamento de String, Análise com len(), count(), find(), transformações com replace(), upper(), lower(), capitalize(), title(), strip(), junção com join().
''')
frase = 'Curso em Video Python'
print(f... | false |
85d84d9c937233fb243c2a67a482c84d778bb60b | nicolas-huber/reddit-dailyprogrammer | /unusualBases.py | 1,734 | 4.3125 | 4 | # Decimal to "Base Fib" - "Base Fib" to Decimal Converter
# challenge url: "https://www.reddit.com/r/dailyprogrammer/comments/5196fi/20160905_challenge_282_easy_unusual_bases/"
# Base Fib: use (1) or don't use (0) a Fibonacci Number to create any positive integer
# example:
# 13 8 5 3 2 1 1
# 1 0 0 ... | true |
b0b353eb1b6e426d235a046850ba74aea627d7a2 | LJ-Godfrey/Learn-to-code | /Encryption-101/encryption_project/encrypt.py | 1,178 | 4.25 | 4 | # This file contains various encryption methods, for use in an encryption / decryption program
def caesar(string):
res = str()
for letter in string:
if letter.lower() >= 'a' and letter.lower() <= 'm':
res += chr(ord(letter) + 13)
elif letter.lower() >= 'n' and letter.lower() <= 'z':... | true |
fd1f0836c9c89a66ff6a555f48577538e398f026 | Moby5/myleetcode | /python/671_Second_Minimum_Node_In_a_Binary_Tree.py | 2,525 | 4.125 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
@File: 671_Second_Minimum_Node_In_a_Binary_Tree.py
@Desc:
@Author: Abby Mo
@Date Created: 2018-3-10
"""
"""
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node... | true |
b76d2e373ea53f6ef7498888b0a80365bc48ec38 | Moby5/myleetcode | /python/532_K-diff_Pairs_in_an_Array.py | 2,592 | 4.125 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
LeetCode 532. K-diff Pairs in an Array
Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute differen... | true |
1956ea7ce6d5955b343157031ad1089928bf0dfa | Moby5/myleetcode | /python/202_Happy_Number.py | 2,098 | 4.125 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
202. Happy Number
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits,
and repeat the process until the number equ... | false |
bd4619b0c4c69fddaa93c8e896a89873c74e245a | Moby5/myleetcode | /python/414_Third_Maximum_Number.py | 2,199 | 4.15625 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
http://bookshadow.com/weblog/2016/10/09/leetcode-third-maximum-number/
414. Third Maximum Number
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 ... | true |
435ea91454abcafece1d68c23106f565bc004030 | Moby5/myleetcode | /python/263_Ugly_Number.py | 1,258 | 4.1875 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
http://bookshadow.com/weblog/2015/08/19/leetcode-ugly-number/
263. Ugly Number
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly sinc... | false |
a3f0ed60542ab8174c23174d1a48c8e2273b9e50 | Moby5/myleetcode | /python/640_Solve_the_Equation.py | 2,492 | 4.3125 | 4 | #!/usr/bin/env python
# coding=utf-8
# 566_reshape_the_matrix.py
"""
http://bookshadow.com/weblog/2017/07/09/leetcode-solve-the-equation/
LeetCode 640. Solve the Equation
Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x a... | true |
549ae44ba1517ca134e2677a63cc3fe5cfb5f205 | joaoribas35/distance_calculator | /app/services/calculate_distance.py | 943 | 4.34375 | 4 | import haversine as hs
def calculate_distance(coordinates):
""" Will calculate the distance from Saint Basil's Cathedral and the address provided by client usind Haversine python lib. Saint Basil's Cathedral is used as an approximation to define whether the provided address is located inside the MKAD Moscow Ring ... | true |
536bf2470f47c6353bc674b6c1efd668f8c03473 | nonbinaryprogrammer/python-poet | /sentence_generator.py | 787 | 4.15625 | 4 | import random
from datetime import datetime
from dictionary import Words
#initializes the dictionary so that we can use the words
words = Words();
#makes the random number generator more random
random.seed(datetime.now)
#gets 3 random numbers between 0 and the length of each list of words
random1 = random.randint(0, ... | true |
5ac31df1a7457d4431e7c8fbdc1892bf02d393d0 | qtdwzAdam/leet_code | /py/back/work_405.py | 1,282 | 4.53125 | 5 | # -*- coding: utf-8 -*-
#########################################################################
# Author : Adam
# Email : zju_duwangze@163.com
# File Name : work_405.py
# Created on : 2019-08-30 15:26:20
# Last Modified : 2019-08-30 15:29:47
# Description :
# Given an integer, write an algori... | true |
4b3ce42dde5e951efe9620bfce24c01f380715e7 | gauravtatke/codetinkering | /leetcode/LC110_balanced_bintree.py | 2,087 | 4.3125 | 4 | # Given a binary tree, determine if it is height-balanced.
# For this problem, a height-balanced binary tree is defined as:
# a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
# Example 1:
# Given the following tree [3,9,20,null,null,15,7]:
# 3
# / \
# 9 20
... | true |
32a89094e2c55e2a5b13cf4a52a1cf6ef7206894 | gauravtatke/codetinkering | /leetcode/LC98_validate_BST.py | 798 | 4.21875 | 4 | # Given a binary tree, determine if it is a valid binary search tree (BST).
#
# Assume a BST is defined as follows:
#
# The left subtree of a node contains only nodes with keys less than the node's key.
# The right subtree of a node contains only nodes with keys greater than the node's key.
# Both the left ... | true |
996e3858f7eb3c4a8de569db426c2f9cdd5fd71a | gauravtatke/codetinkering | /dsnalgo/firstnonrepeatcharinstring.py | 1,292 | 4.15625 | 4 | #!/usr/bin/env python3
# Given a string, find the first non-repeating character in it. For
# example, if the input string is “GeeksforGeeks”, then output should be
# ‘f’ and if input string is “GeeksQuiz”, then output should be ‘G’.
def findNonRepeatChar(stri):
chlist = [0 for ch in range(256)]
for ch in str... | true |
c106671082f8f393f73ebad1a355929e142cfdc6 | gauravtatke/codetinkering | /leetcode/LC345_reverse_vowelsof_string.py | 739 | 4.28125 | 4 | # Write a function that takes a string as input and reverse only the vowels of a string.
#
# Example 1:
# Given s = "hello", return "holle".
#
# Example 2:
# Given s = "leetcode", return "leotcede".
#
# Note:
# The vowels does not include the letter "y".
def reverseVowels(s):
lstr = list(s)
i = 0
j = len(... | true |
0d37f87ebde2412443f7fefbf53705ac0f03b019 | gauravtatke/codetinkering | /dsnalgo/lengthoflongestpalindrome.py | 2,308 | 4.1875 | 4 | #!/usr/bin/env python3
# Given a linked list, the task is to complete the function maxPalindrome which
# returns an integer denoting the length of the longest palindrome list that
# exist in the given linked list.
#
# Examples:
#
# Input : List = 2->3->7->3->2->12->24
# Output : 5
# The longest palindrome list is 2-... | true |
8d9bb6926f1bd85ef8da53778229913d6ac4bc86 | gauravtatke/codetinkering | /dsnalgo/sort_pile_of_cards.py | 1,047 | 4.125 | 4 | #!/usr/bin/env python3
# We have N cards with each card numbered from 1 to N. All cards are randomly shuffled. We are allowed only operation moveCard(n) which moves the card with value n to the top of the pile. You are required to find out the minimum number of moveCard() operations required to sort the cards in incre... | true |
a783b4053b012143e18b6a8bd4335a8b84b5d031 | gauravtatke/codetinkering | /leetcode/LC433_min_gene_mut.py | 2,495 | 4.15625 | 4 | # A gene string can be represented by an 8-character long string, with choices from "A", "C", "G", "T".
# Suppose we need to investigate about a mutation (mutation from "start" to "end"), where ONE mutation is defined as ONE single character changed in the gene string.
# For example, "AACCGGTT" -> "AACCGGTA" is 1 mutat... | true |
ffe24156489d5063ee564b1b5c558585363a7944 | directornicm/python | /Project_4.py | 572 | 4.28125 | 4 | # To calculate leap year:
# A leap year is a year which is divisible by 4 but ...
# if it is divisible by 100, it must be divisible by 400.
# indentation matters - take care of it
year = int(input("Give the year to be checked for leap year"))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 ==... | true |
b0beed001a2b92c2770e863690799397ce682581 | kkowalsks/CS362-Homework-7 | /leapyear.py | 603 | 4.1875 | 4 | def leapCheck(int):
if int % 4 != 0:
int = str(int)
print(int + " is not a leap year")
return False
else:
if int % 100 != 0:
int = str(int)
print(int + " is a leap year")
return True
else:
if int % 400 != 0:
... | false |
67eb2e0043b1c1d63395df0de8f4e39a98930a7e | luthraG/ds-algo-war | /general-practice/17_09_2019/p16.py | 996 | 4.1875 | 4 | '''
Given a non-empty string check if it can be constructed by taking a substring of it and
appending multiple copies of the substring together.
You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
Example 1:
Input: "abab"
Output: ... | true |
bd48564a03e15ec4c6f2d287ec3b651947418118 | luthraG/ds-algo-war | /general-practice/20_08_2019/p1.py | 861 | 4.125 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 10 Million.
from timeit import default_timer as timer
if __name__ == '__main__':
start = timer()
number = 1000
# Since... | true |
3ec6fd0dcd97904b08c95fe17cac67b03a75a61f | luthraG/ds-algo-war | /general-practice/11_09_2019/p11.py | 648 | 4.15625 | 4 | '''
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
'''
from timeit import default_timer as timer
power = int(input('Enter the power that needs to be raised to base 2 :: '))
start = timer()
sum_of_digits = 0
number = 2 << (power - 1)
numb... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.