blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
9fdc839e30c4eccbb829abfa30178545f2f3f7b3 | sheayork/02A-Control-Structures | /E02a-Control-Structures-master/main06.py | 719 | 4.5 | 4 | #!/usr/bin/env python3
import sys
assert sys.version_info >= (3,7), "This script requires at least Python 3.7"
print('Greetings!')
color = input("What is my favorite color? ")
if (color.lower().strip() == 'red'):
print('Correct!')
else:
print('Sorry, try again.')
##BEFORE: Same as before, but some people ma... | true |
b93667bb58dfc610850d6ffa407ee418af6f44b0 | Mamedefmf/Python-Dev-Course-2021 | /magic_number/main.py | 1,233 | 4.15625 | 4 | import random
def ask_number (min, max):
number_int = 0
while number_int == 0:
number_str = input(f"What is the magic number ?\nType a number between {min} and {max} : ")
try:
number_int = int(number_str)
except:
print("INPUT ERROR: You need to type a valid numbe... | true |
2a2ae134cceba04732db0f61fb19f83221ca3f1d | pranavkaul/Coursera_Python_for_Everybody_Specialization | /Course-1-Programming for everybody-(Getting started with Python/Assignment_6.py | 999 | 4.3125 | 4 | #Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
#Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours.
#Put the logic to do the computation of pay in a function called computepay() and use the funct... | true |
df4a4165ed70cee917e537eb19b1ed040703dbc7 | Craby4GitHub/CIS129 | /Mod 2 Pseudocode 2.py | 2,879 | 4.3125 | 4 | ########################################################################################################################
# William Crabtree #
# 27Feb17 ... | true |
4b1ae200aa26d0259e03ec346abdb42c4671b26b | Craby4GitHub/CIS129 | /Final/Final.py | 2,265 | 4.1875 | 4 | ########################################################################################################################
# William Crabtree #
# 26Apr17 ... | true |
f5f85d737006dc462254a2926d4d7db88db72cb6 | WarrenJames/LPTHWExercises | /exl9.py | 1,005 | 4.28125 | 4 | # Excercise 9: Printing, Printing, Printing
# variable "days" is equal to "Mon Tue Wed Thu Fri Sat Sun"
days = "Mon Tue Wed Thu Fri Sat Sun"
# variable "months" is Jan Feb Mar Apr May Jun Aug seperated by \n
# \n means words written next will be printed on new a line
months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nAug"
# p... | true |
e6f1bf912c575ed81b4b0631514ee67943a26f2f | WarrenJames/LPTHWExercises | /exl18.py | 1,977 | 4.875 | 5 | # Excercise 18: Names, Variables, Code, Functions
# Functions do three things:
# They name pieces of code the way variables name strings and numbers.
# They take arguments the way your scripts take argv
# Using 1 and 2 they let you make your own "mini-scripts" or "tiny commands"
# First we tell python we want to... | true |
fd90e5312f0798ca3eb88c8139bdd2fe17786654 | SaloniSwagata/DSA | /Tree/balance.py | 1,147 | 4.15625 | 4 | # Calculate the height of a binary tree. Assuming root is at height 1
def heightTree(root):
if root is None:
return 0
leftH = heightTree(root.left)
rightH = heightTree(root.right)
H = max(leftH,rightH) # height of the tree will be the maximum of the heights of left subtree and right subtr... | true |
4af84efdf7b997185c340f2b69e7873d5b87df73 | SaloniSwagata/DSA | /Tree/BasicTree.py | 1,377 | 4.1875 | 4 | # Creating and printing a binary tree
# Creating a binary tree node
class BinaryTreeNode:
def __init__(self,data):
self.left = None
self.data = data
self.right = None
# Creating a tree by taking input tree wise (i.e, root - left subtree - right subtree)
# For None, the user enters -1
def ... | true |
c868093ac8ba3e14bad9835728fcc45598e0dfd5 | SaloniSwagata/DSA | /Tree/levelOrder.py | 1,309 | 4.25 | 4 | # Taking input level order wise using queue
# Creating a binary tree node
class BinaryTreeNode:
def __init__(self,data):
self.left = None
self.data = data
self.right = None
import queue
# Taking Level Order Input
def levelInput():
rootData = int(input("Enter the root node data: "))
... | true |
dbd90779db40037c1cdf29d85485c84b397405fc | Sudeep-K/hello-world | /Automating Tasks/Mad Libs.py | 1,445 | 4.5 | 4 | #! python
'''
Create a Mad Libs program that reads in text files and lets the user add
their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB
appears in the text file.
The program would find these occurrences and prompt the user to
replace them.
The results should be printed to the screen and saved to... | true |
e10c4cd35fce90bc44dbb4dd3ffaf75b13adcaa9 | harishvinukumar/Practice-repo | /Break the code.py | 1,503 | 4.28125 | 4 | import random
print('''\t\t\t\t\t\t\t\t### --- CODEBREAKER --- ###
\t\t\t\t\t1. The computer will think of 3 digit number that has no repeating digits.
\t\t\t\t\t2. You will then guess a 3 digit number
\t\t\t\t\t3. The computer will then give back clues, the possible clues are:
\t\t\t\t\tClose: You've guessed a corre... | true |
97aa8452a4bab355d139eed764ebfd5f692ab06b | shaikzia/Classes | /yt1_cor_classes.py | 691 | 4.21875 | 4 | # Program from Youtube Videos - corey schafer
"""
Tut1 - Classes and Instances
"""
#Defining the class
class Employee:
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
def fullname(self):
... | true |
4e592149e3f98f2d428bb5a37dd85431ad7be763 | Deepkumarbhakat/Python-Repo | /factorial.py | 206 | 4.25 | 4 | #Write a program to find the factorial value of any number entered through the keyboard
n=5
fact=1
for i in range(0,n,-1):
if i==1 or i==0:
fact=fact*1
else:
fact=fact*i
print(fact) | true |
27cd32606dddc864ce68c35f824a533e1467419d | Deepkumarbhakat/Python-Repo | /function3.py | 243 | 4.28125 | 4 | # Write a Python function to multiply all the numbers in a list.
# Sample List : (8, 2, 3, -1, 7)
# Expected Output : -336
def multiple(list):
mul = 1
for i in list:
mul =mul * i
print(mul)
list=[8,2,3,-1,7]
multiple(list) | true |
3a98e9a55e3217f3f4faa76b71ab08a75adf1d8e | Deepkumarbhakat/Python-Repo | /function9.py | 434 | 4.25 | 4 | # Write a Python function that takes a number as a parameter and check the number is prime or not.
# Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors
# other than 1 and itself.
def prime(num):
for i in range(2,num//2):
if num % i == 0:
print... | true |
63507dcd1e550687bbc7d6108211bd15cf2164af | Deepkumarbhakat/Python-Repo | /string15.py | 282 | 4.15625 | 4 | # Write a Python program that accepts a comma separated sequence of words as input
# and prints the unique words in sorted form (alphanumerically).
# Sample Words : red, white, black, red, green, black
# Expected Result : black, green, red, white,red
st=("input:"," , ")
print(st)
| true |
5ed7472af54b4e92e4f8b8160dbdfa42fc8a0c7b | deepabalan/byte-of-python | /functions/function_varargs.py | 720 | 4.15625 | 4 |
# When we declare a starred parameter such as *param, then all the
# positional arguments from that point till the end are collected as
# a tuple called 'param'.
# Similarly, when we declare a double-starred parameter such as **param,
# then all the keyword arguments from that point till end are collected
# as a dict... | true |
e2f198706079a03d282121a9959c8e913229d07c | hazydazyart/OSU | /CS344/Homework2/Problem4.py | 959 | 4.15625 | 4 | #Megan Conley
#conleyme@onid.oregonstate.edu
#CS344-400
#Homework 2
import os
import sys
import getopt
import math
#Function to check if a number is prime
#Arguments: int
#Return: boolean
#Notes: a much improved function to find primes using the sieve, this time using the
#square root hint from Homework 1.
def isPrim... | true |
a5b0bcd93668247dbaeaa869de1e1f136aa32f28 | emilyscarroll/MadLibs-in-Python | /MadLibs.py | 593 | 4.21875 | 4 | # Story: There once was a very (adjective) (animal) who lived in (city). He loved to eat (type of candy).
#1) print welcome
#2) ask for input for each blank
#3) print story
print("Hello, and welcome to MadLibs! Please enter the following words to complete your story.")
adj = input("Enter an adjective: ")
animal = inp... | true |
4f82dfb7a6b951b9a5fed1546d0743adb4109fbd | kkeller90/Python-Files | /newton.py | 335 | 4.375 | 4 | # newtons method
# compute square root of 2
def main():
print("This program evaluates the square root of 2 using Newton's Method")
root = 2
x = eval(input("Enter number of iterations: "))
for i in range(x):
root = root - (root**2 - 2)/(2*root)
print(root)
main()
... | true |
bb83df21cb7dc89440d61876288bfd6bafce994d | ZzzwyPIN/python_work | /chapter9/Demo9_2.py | 1,137 | 4.28125 | 4 | class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""返回整洁的描述性信息"""
long_name = str(self.year)+' '+self.make+' '+self.model
return long_name.title()
def read_odometer(s... | true |
eac160ec897eed706fd6924ef2c55bef93159034 | AlirieGray/Tweet-Generator | /qu.py | 1,052 | 4.21875 | 4 | from linkedlist import LinkedList
from linkedlist import Node
class Queue(LinkedList):
def __init__(self, iterable=None):
super().__init__(iterable)
def enqueue(self, item):
"""Add an object to the end of the Queue."""
self.append(item)
def dequeue(self):
"""Remove and ret... | true |
09a979bccf9cce42b1fa77cf88cf8fa889037879 | michaelworkspace/AdventOfCode2020 | /day01.py | 1,277 | 4.40625 | 4 | from typing import List
def find_product(inputs: List[int]) -> int:
"""Given a list of integers, if the sum of two element is 2020, return it's product."""
# This is the classic Two Sum problem
# This is not good solution because it is O(n^2)
# for x in INPUTS:
# for y in INPUTS:
# ... | true |
0ad185da2701617e9580000faad35f2c31df8c9a | YasmineCodes/Interview-Prep | /recursion.py | 2,641 | 4.3125 | 4 | # Write a function fib, that finds the nth fibonacci number
def fib(n):
assert n >= 0 and int(n) == n, "n must be a positive integer"
if n == 1:
return 0
elif n == 2:
return 1
else:
return fib(n-1) + fib(n-2)
print("The 4th fibonacci number is: ", fib(4)) # 2
print("The 10th ... | true |
aa92573b123c0f334eca8304adae5b1410f108e5 | Xia-Sam/hello-world | /rock paper scissors game against computer.py | 1,714 | 4.3125 | 4 | import random
rand_num=random.randint(1,3)
if rand_num==1:
com_side="rock"
elif rand_num==2:
com_side="paper"
else:
com_side="scissors"
i=0
while i<5:
print("You can input 'stop' at anytime to stop the game but nothing else is allowed.")
user_side=input("Please input your choice (R P S stands for r... | true |
55ae7ae4ad64c690800e9d2a9d37684eb3069bb9 | andkoc001/pands-problem-set | /06-secondstring.py | 1,379 | 4.15625 | 4 | # Title: Second Strig
# Description: Solution to problem 6 - program that takes a user input string and outputs every second word.
# Context: Programming and Scripting, GMIT, 2019
# Author: Andrzej Kocielski
# Email: G00376291@gmit.ie
# Date of creation: 10-03-2019
# Last update: 10-03-2019
###
# Prompt for the user;... | true |
3cc0fcee11a7eea3411f26afebac5fea6eebd6b1 | BlackJimmy/SYSU_QFTI | /mateig.py | 427 | 4.15625 | 4 | #this example shows how to compute eigen values of a matrix
from numpy import *
#initialize the matrix
n = 5
a = zeros( (n, n) )
for i in range(n):
a[i][i] = i
if(i>0):
a[i][i-1] = -1
a[i-1][i] = -1
#print the matrix
print "The matrix is:"
for i in range(n):
print a[i]
#compute the eigen ... | true |
d7d9550e9acb11727564ba122a9427139f47a5e3 | ode2020/bubble_sort.py | /bubble.py | 388 | 4.1875 | 4 | def bubble_sort(numbers):
for i in range (len(numbers) - 1, 0, -1):
for j in range (i):
if numbers[j] > numbers[j+1]:
temp = numbers[j]
numbers[j] = numbers[j+1]
numbers[j+1] = temp
print(numbers)
numbers = [5, 3, 8, 6, 7, 2]
bubble_s... | true |
aa83f5258b80e1c403a25d30aeb96f2a8125ec73 | ravalrupalj/BrainTeasers | /Edabit/Day 3.3.py | 459 | 4.125 | 4 | #Get Word Count
#Create a function that takes a string and returns the word count. The string will be a sentence.
#Examples
#count_words("Just an example here move along") ➞ 6
#count_words("This is a test") ➞ 4
#count_words("What an easy task, right") ➞ 5
def count_words(txt):
t = txt.split()
return len(t)
prin... | true |
9975f7dc75b81bbbe7cfdcd701f2e09335a3ce54 | ravalrupalj/BrainTeasers | /Edabit/Emptying_the_values.py | 1,532 | 4.4375 | 4 | #Emptying the Values
#Given a list of values, return a list with each value replaced with the empty value of the same type.
#More explicitly:
#Replace integers (e.g. 1, 3), whose type is int, with 0
#Replace floats (e.g. 3.14, 2.17), whose type is float, with 0.0
#Replace strings (e.g. "abcde", "x"), whose type is st... | true |
60a84a613c12d723ba5d141e657989f33930ab74 | ravalrupalj/BrainTeasers | /Edabit/Powerful_Numbers.py | 615 | 4.1875 | 4 | #Powerful Numbers
#Given a positive number x:
#p = (p1, p2, …)
# Set of *prime* factors of x
#If the square of every item in p is also a factor of x, then x is said to be a powerful number.
#Create a function that takes a number and returns True if it's powerful, False if it's not.
def is_powerful(num):
i=1
l=... | true |
4dd2faade46f718a07aeba94270ea71ff90b5996 | ravalrupalj/BrainTeasers | /Edabit/Is_the_Number_Symmetrical.py | 462 | 4.4375 | 4 | #Create a function that takes a number as an argument and returns True or False depending on whether the number is symmetrical or not. A number is symmetrical when it is the same as its reverse.
def is_symmetrical(num):
t=str(num)
return t==t[::-1]
print(is_symmetrical(7227) )
#➞ True
print(is_symmetrical(125... | true |
885a0a3ce15dbf2504dd24ce14552a4e245b3790 | ravalrupalj/BrainTeasers | /Edabit/Big_Countries.py | 1,652 | 4.53125 | 5 | #Big Countries
#A country can be said as being big if it is:
#Big in terms of population.
#Big in terms of area.
#Add to the Country class so that it contains the attribute is_big. Set it to True if either criterea are met:
#Population is greater than 250 million.
#Area is larger than 3 million square km.
#Also, crea... | true |
a22a66ffd651519956fc0f1ea0eb087a4146e8dd | ravalrupalj/BrainTeasers | /Edabit/Loves_Me_Loves_Me.py | 1,034 | 4.25 | 4 | #Loves Me, Loves Me Not...
#"Loves me, loves me not" is a traditional game in which a person plucks off all the petals of a flower one by one, saying the phrase "Loves me" and "Loves me not" when determining whether the one that they love, loves them back.
#Given a number of petals, return a string which repeats the p... | true |
13b3a8a4d538ca1404902f5cc9d0d4cb5380f231 | ravalrupalj/BrainTeasers | /Edabit/sum_of_even_numbers.py | 698 | 4.1875 | 4 | #Give Me the Even Numbers
#Create a function that takes two parameters (start, stop), and returns the sum of all even numbers in the range.
#sum_even_nums_in_range(10, 20) ➞ 90
# 10, 12, 14, 16, 18, 20
#sum_even_nums_in_range(51, 150) ➞ 5050
#sum_even_nums_in_range(63, 97) ➞ 1360
#Remember that the start and stop value... | true |
7801a9735e3d51e4399ee8297d719d86eb44bc58 | ravalrupalj/BrainTeasers | /Edabit/Recursion_Array_Sum.py | 440 | 4.15625 | 4 | #Recursion: Array Sum
#Write a function that finds the sum of a list. Make your function recursive.
#Return 0 for an empty list.
#Check the Resources tab for info on recursion.
def sum_recursively(lst):
if len(lst)==0:
return 0
return lst[0]+sum_recursively(lst[1:])
print(sum_recursively([1, 2, 3, 4])... | true |
207c144e096524b8de5e6d9ca11ce5cb4969d8e1 | ravalrupalj/BrainTeasers | /Edabit/Letters_Only.py | 496 | 4.25 | 4 | #Letters Only
#Write a function that removes any non-letters from a string, returning a well-known film title.
#See the Resources section for more information on Python string methods.
def letters_only(string):
l=[]
for i in string:
if i.isupper() or i.islower():
l.append(i)
return ''.jo... | true |
4fad5f1ab4362dbc1119d1f72a85d6c91abdfa8f | ravalrupalj/BrainTeasers | /Edabit/The_Fibonacci.py | 368 | 4.3125 | 4 | #The Fibonacci Number
#Create a function that, given a number, returns the corresponding Fibonacci number.
#The first number in the sequence starts at 1 (not 0).
def fibonacci(num):
a=0
b=1
for i in range(1,num+1):
c=a+b
a=b
b=c
return c
print(fibonacci(3) )
#➞ 3
print(fibonac... | true |
5182829f043490134cb86a3962b07a791e7ae0cb | ravalrupalj/BrainTeasers | /Edabit/How_many.py | 601 | 4.15625 | 4 | #How Many "Prime Numbers" Are There?
#Create a function that finds how many prime numbers there are, up to the given integer.
def prime_numbers(num):
count=0
i=1
while num:
i=i+1
for j in range(2,i+1):
if j>num:
return count
elif i%j==0 and i!=j:
... | true |
f07bfd91788707f608a580b702f3905be2bf201b | ravalrupalj/BrainTeasers | /Edabit/One_Button_Messagin.py | 650 | 4.28125 | 4 | # One Button Messaging Device
# Imagine a messaging device with only one button. For the letter A, you press the button one time, for E, you press it five times, for G, it's pressed seven times, etc, etc.
# Write a function that takes a string (the message) and returns the total number of times the button is pressed.
#... | true |
d9acdd4825dfd641d4eac7dd92d15b428b0e07f0 | ravalrupalj/BrainTeasers | /Edabit/Iterated_Square_Root.py | 597 | 4.5 | 4 | #Iterated Square Root
#The iterated square root of a number is the number of times the square root function must be applied to bring the number strictly under 2.
#Given an integer, return its iterated square root. Return "invalid" if it is negative.
#Idea for iterated square root by Richard Spence.
import math
def i_sq... | true |
edb6aaff5ead34484d01799aef3df830208b574c | ravalrupalj/BrainTeasers | /Edabit/Identical Characters.py | 460 | 4.125 | 4 | #Check if a String Contains only Identical Characters
#Write a function that returns True if all characters in a string are identical and False otherwise.
#Examples
#is_identical("aaaaaa") ➞ True
#is_identical("aabaaa") ➞ False
#is_identical("ccccca") ➞ False
#is_identical("kk") ➞ True
def is_identical(s):
return ... | true |
da002bf4a8ece0c60f4103e5cbc92f641d27f573 | ravalrupalj/BrainTeasers | /Edabit/Stand_in_line.py | 674 | 4.21875 | 4 | #Write a function that takes a list and a number as arguments. Add the number to the end of the list, then remove the first element of the list. The function should then return the updated list.
#For an empty list input, return: "No list has been selected"
def next_in_line(lst, num):
if len(lst)>0:
t=lst.po... | true |
b5255591c5a67f15767deee268a1972ca61497cd | ravalrupalj/BrainTeasers | /Edabit/Emphasise_the_Words.py | 617 | 4.21875 | 4 | #Emphasise the Words
#The challenge is to recreate the functionality of the title() method into a function called emphasise(). The title() method capitalises the first letter of every word.
#You won't run into any issues when dealing with numbers in strings.
#Please don't use the title() method directly :(
def emphasis... | true |
6eceebf49b976ec2b757eee0c7907f2845c65afd | ravalrupalj/BrainTeasers | /Edabit/Is_String_Order.py | 405 | 4.25 | 4 | #Is the String in Order?
#Create a function that takes a string and returns True or False, depending on whether the characters are in order or not.
#You don't have to handle empty strings.
def is_in_order(txt):
t=''.join(sorted(txt))
return t==txt
print(is_in_order("abc"))
#➞ True
print(is_in_order("edabit"))
#... | true |
56bf743185fc87230c9cb8d0199232d393757809 | ravalrupalj/BrainTeasers | /Edabit/Day 2.5.py | 793 | 4.53125 | 5 | #He tells you that if you multiply the height for the square of the radius and multiply the result for the mathematical constant π (Pi), you will obtain the total volume of the pizza. Implement a function that returns the volume of the pizza as a whole number, rounding it to the nearest integer (and rounding up for num... | true |
d9d1a7dbd41fea7d00f7299ae6708fc46e21d42d | ravalrupalj/BrainTeasers | /Edabit/Day 4.4.py | 510 | 4.46875 | 4 | #Is It a Triangle?
#Create a function that takes three numbers as arguments and returns True if it's a triangle and False if not.
#is_triangle(2, 3, 4) ➞ True
#is_triangle(3, 4, 5) ➞ True
#is_triangle(4, 3, 8) ➞ False
#Notes
#a, b and, c are the side lengths of the triangles.
#Test input will always be three positive n... | true |
a055bcd166678d801d9f2467347d9dfcd0e49254 | ravalrupalj/BrainTeasers | /Edabit/Count_and_Identify.py | 832 | 4.25 | 4 | #Count and Identify Data Types
#Given a function that accepts unlimited arguments, check and count how many data types are in those arguments. Finally return the total in a list.
#List order is:
#[int, str, bool, list, tuple, dictionary]
def count_datatypes(*args):
lst=[type(i) for i in args]
return [lst.count... | true |
fde94a7ba52fa1663a992ac28467e42cda866a9b | ravalrupalj/BrainTeasers | /Edabit/Lexicorgraphically First_last.py | 762 | 4.15625 | 4 | #Lexicographically First and Last
#Write a function that returns the lexicographically first and lexicographically last rearrangements of a string. Output the results in the following manner:
#first_and_last(string) ➞ [first, last]
#Lexicographically first: the permutation of the string that would appear first in the E... | true |
5c503edd8d4241b5e674e0f88b5c0edbe0888235 | ravalrupalj/BrainTeasers | /Edabit/Explosion_Intensity.py | 1,312 | 4.3125 | 4 | #Explosion Intensity
#Given an number, return a string of the word "Boom", which varies in the following ways:
#The string should include n number of "o"s, unless n is below 2 (in that case, return "boom").
#If n is evenly divisible by 2, add an exclamation mark to the end.
#If n is evenly divisible by 5, return the s... | true |
bc123a73adc60347bc2e8195581e6d556b27c329 | ravalrupalj/BrainTeasers | /Edabit/Check_if_an_array.py | 869 | 4.28125 | 4 | #Check if an array is sorted and rotated
#Given a list of distinct integers, create a function that checks if the list is sorted and rotated clockwise. If so, return "YES"; otherwise return "NO".
def check(lst):
posi = sorted(lst)
for i in range(0,len(lst)-1):
first=posi.pop(0)
posi.append(firs... | true |
a3b5f7ffe220bd211b6fde53c99b9bcb086dbf39 | ravalrupalj/BrainTeasers | /Edabit/Reverse_the_odd.py | 656 | 4.4375 | 4 | #Reverse the Odd Length Words
#Given a string, reverse all the words which have odd length. The even length words are not changed.
def reverse_odd(string):
new_lst=string.split()
s=''
for i in new_lst:
if len(i)%2!=0:
t=i[::-1]
s=s+t+' '
else:
s=s+i+' '
... | true |
8124f901f1650f94c89bdae1eaf3f837925effde | ravalrupalj/BrainTeasers | /Edabit/Balancing_Scales.py | 944 | 4.5 | 4 | #Balancing Scales
#Given a list with an odd number of elements, return whether the scale will tip "left" or "right" based on the sum of the numbers. The scale will tip on the direction of the largest total. If both sides are equal, return "balanced".
#The middle element will always be "I" so you can just ignore it.
#As... | true |
d183ee49cc90ee2ede5a0d6383404edd9f08a4a8 | nicolaespinu/LightHouse_Python | /spinic/Day14.py | 1,572 | 4.15625 | 4 | # Challenge
# Dot's neighbour said that he only likes wine from Stellenbosch, Bordeaux, and the Okanagan Valley,
# and that the sulfates can't be that high. The problem is, Dot can't really afford to spend tons
# of money on the wine. Dot's conditions for searching for wine are:
#
# Sulfates cannot be higher than 0.6.
... | true |
afdf0666b5d24b145a7fee65bf489fd01c4baa8c | OaklandPeters/til | /til/python/copy_semantics.py | 1,348 | 4.21875 | 4 | # Copy Semantics
# -------------------------
# Copy vs deep-copy, and what they do
# In short: copy is a pointer, and deep-copy is an entirely seperate data structure.
# BUT.... this behavior is inconsistent, because of the way that attribute
# setters work in Python.
# Thus, mutations of attributes is not shared... | true |
761768971347ca71abb29fcbbaccf6ef92d4df86 | Varobinson/python101 | /tip-calculator.py | 998 | 4.28125 | 4 | #Prompt the user for two things:
#The total bill amount
#The level of service, which can be one of the following:
# good, fair, or bad
#Calculate the tip amount and the total amount(bill amount + tip amount).
# The tip percentage based on the level of service is based on:
#good -> 20%
#fair -> 15%
# bad -> 10%
try:
... | true |
94bdd2d96de22c8911e7c22e46405558785fc25e | chhikara0007/intro-to-programming | /s2-code-your-own-quiz/my_code.py | 1,211 | 4.46875 | 4 | # Investigating adding and appending to lists
# If you run the following four lines of codes, what are list1 and list2?
list1 = [1,2,3,4]
list2 = [1,2,3,4]
list1 = list1 + [5]
list2.append(5)
# to check, you can print them out using the print statements below.
print list1
print list2
# What is the difference betw... | true |
592e186d9725f23f98eaf990116de6c572757063 | Lobo2008/LeetCode | /581_Shortest_Unsorted_ContinuousSubarray.py | 1,749 | 4.25 | 4 | """
Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.
You need to find the shortest such subarray and output its length.
Example 1:
Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation:... | true |
eff175292e48ca133ae5ca276a679821ebae0712 | soumilshah1995/Data-Structure-and-Algorithm-and-Meta-class | /DataStructure/Deque/DEQChallenge.py | 1,505 | 4.15625 | 4 | """
DEQUE Abstract Data Type
DEQUE = Double ended Queue
High level its combination of stack and queue
you can insert item from front and back
You can remove items from front and back
we can use a list for this example. we will use methods
>----- addfront
>----- add rear
>----- remove front
>----- remove rear
we... | true |
b777cc4d1682a6a3c1e5a450c282062c4a0514da | jrobind/python-playground | /games/guessing_game.py | 755 | 4.21875 | 4 | # Random number CLI game - to run, input a number to CLI, and a random number between
# zero and the one provided will be generated. The user must guess the correct number.
import random
base_num = raw_input('Please input a number: ')
def get_guess(base_num, repeat):
if (repeat == True):
return raw_input(... | true |
e88333ce7bd95d7fb73a07247079ae4f5cb12d11 | graciofilipe/differential_equations | /udacity_cs222/final_problems/geo_stat_orb.py | 2,907 | 4.375 | 4 | # PROBLEM 3
#
# A rocket orbits the earth at an altitude of 200 km, not firing its engine. When
# it crosses the negative part of the x-axis for the first time, it turns on its
# engine to increase its speed by the amount given in the variable called boost and
# then releases a satellite. This satellite will ascend t... | true |
75c14cfafe64264b72186017643b6c3b3dacb42f | Malak-Abdallah/Intro_to_python | /main.py | 866 | 4.3125 | 4 | # comments are written in this way!
# codes written here are solutions for solving problems from Hacker Rank.
# -------------------------------------------
# Jenan Queen
if __name__ == '__main__':
print("Hello there!! \nThis code to practise some basics in python. \n ")
str = "Hello world"
print(str[2:])
... | true |
01f42ded2480038227e1d492193c9a1dbb3395bf | Chih-YunW/Leap-Year | /leapYear_y.py | 410 | 4.1875 | 4 | while True:
try:
year = int(input("Enter a year: "))
except ValueError:
print("Input is invalid. Please enter an integer input(year)")
continue
break
if (year%4) != 0:
print(str(year) + " is not a leap year.")
else:
if(year%100) != 0:
print(str(year) + " is a leap year.")
else:
if(year%400) == 0:
pr... | true |
999579d8777c53f7ab91ebdcc13b5c76689f7411 | ayushmohanty24/python | /asign7.2.py | 682 | 4.1875 | 4 | """
Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values
"""
fname = input("Enter file name: ")
... | true |
adfa2df9495c4631f0d660714a2d130bfedd9072 | jni/interactive-prog-python | /guess-the-number.py | 2,010 | 4.15625 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
def initialize_game():
global secret_number, rangemax, guesses_remaining, guesses_label
rangemax = 100
guesses_remaining =... | true |
5fd5b964582057ac930249378e9b944ac1b31bc0 | raghav1674/graph-Algos-In-Python | /Recursion/05/StairCaseTraversal.py | 393 | 4.15625 | 4 |
def max_ways_to_reach_staircase_end(staircase_height, max_step, current_step=1):
if staircase_height == 0 or current_step == 0:
return 1
elif staircase_height >= current_step:
return max_ways_to_reach_staircase_end(
staircase_height-current_step, max_step, current_step-1) + stairc... | true |
a4a7c7db2d8fbfb5649f831e832190e719c499c6 | phos-tou-kosmou/python_portfolio | /euler_project/multiples_of_three_and_five.py | 1,459 | 4.34375 | 4 | def what_are_n():
storage = []
container = 0
while container != -1:
container = int(input("Enter a number in which you would like to find multiples of: "))
if container == -1: break
if type(container) is int and container not in storage:
storage.append(container)
... | true |
eec09d1b8c6506de84400410771fcdeb6fe73f73 | StephenTanksley/hackerrank-grind-list | /problem-solving/extra_long_factorials.py | 950 | 4.5625 | 5 | """
The factorial of the integer n, written n!, is defined as:
n! = n * (n-1) * (n-2) * ... * 3 * 2 * 1
Calculate and print the factorial of a given integer.
Complete the extraLongFactorials function in the editor below. It should print the result and return.
extraLongFactorials has ... | true |
aad85067c090c60b6095d335c6b9a0863dd76311 | dpolevodin/Euler-s-project | /task#4.py | 820 | 4.15625 | 4 | #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.
num_list = []
result = []
# Create a list with elements multiplied by each other
for i in range(100,1000... | true |
41b6ee22ddfb9f6ad0d6dc18d0ec4e5bf1e0bb43 | anagharumade/Back-to-Basics | /BinarySearch.py | 827 | 4.125 | 4 | def BinarySearch(arr, search):
high = len(arr)
low = 0
index = ((high - low)//2)
for i in range(len(arr)):
if search > arr[index]:
low = index
index = index + ((high - low)//2)
if i == (len(arr)-1):
print("Number is not present in the input arr... | true |
3967fad907d30a59282306b168bfd3fa032bfaa9 | mootfowl/dp_pdxcodeguild | /python assignments/lab10_unit_converter_v3.py | 1,466 | 4.34375 | 4 | '''
v3 Allow the user to also enter the units.
Then depending on the units, convert the distance into meters.
The units we'll allow are inches, feet, yards, miles, meters, and kilometers.
'''
def number_crunch():
selected_unit = input("Pick a unit of measurement: inches, feet, yards, miles, meters, or kilometers. ... | true |
d900cef1d0915808b0b213a6339636bf2dd3dcd2 | mootfowl/dp_pdxcodeguild | /python assignments/lab15_ROT_cipher_v1.py | 971 | 4.15625 | 4 | '''
LAB15: Write a program that decrypts a message encoded with ROT13 on each character starting with 'a',
and displays it to the user in the terminal.
'''
# DP note to self: if a = 1, ROT13 a = n (ie, 13 letters after a)
# First, let's create a function that encrypts a word with ROT13...
alphabet = 'abcdefghijklmnop... | true |
858422c01e9d9390216773f08065f38a124cb579 | monicaneill/PythonNumberGuessingGame | /guessinggame.py | 1,724 | 4.46875 | 4 | #Greetings
print("Hi there! Welcome to Monica's first coding project, 'The Python Number Guessing Game'!")
print("Let's see if you can guess the number in fewer steps than the computer openent. Let's begin!")
#Computer Function
def computerGuess(lowval, highval, randnum, count=0):
if highval >= lowval:
... | true |
0e5c69430dcddf93721e19e55a54d131394ca452 | montoyamoraga/nyu-itp | /reading-and-writing-electronic-text/classes/class_02/cat.py | 2,211 | 4.125 | 4 | # import sys library
import sys
# this is a foor loop
#stdin refers to the lines that are input to the program
#typical python styling is indenting with four spaces
for line in sys.stdin:
#strip() removes whitespace at the end of the line
#strip() is a method of a line object
line = line.strip()
if "yo... | true |
47c9f72baa7577f726046a80f338e40fd199bb61 | montoyamoraga/nyu-itp | /reading-and-writing-electronic-text/assignments/assignment_04/this.py | 2,031 | 4.1875 | 4 | #assignment 04
#for class reading and writing electronic text
#at nyu itp taught by allison parrish
#by aaron montoya-moraga
#february 2017
#the digital cut-up, part 2. write a program that reads in and creatively re-arranges the content of several source texts. what is the unit of your cut-up technique? (the word, th... | true |
e7f50e19dbf531b0af4ae651759d714278aac06b | ribeiroale/rita | /rita/example.py | 498 | 4.21875 | 4 | def add(x: float, y: float) -> float:
"""Returns the sum of two numbers."""
return x + y
def subtract(x: float, y: float) -> float:
"""Returns the subtraction of two numbers."""
return x - y
def multiply(x: float, y: float) -> float:
"""Returns the multiplication of two numbers."""
return x ... | true |
299cc5fc729fef69fea8e96cd5e72344a1aa3e12 | voyeg3r/dotfaster | /algorithm/python/getage.py | 1,075 | 4.375 | 4 | #!/usr/bin/env python3
# # -*- coding: UTF-8 -*-"
# ------------------------------------------------
# Creation Date: 01-03-2017
# Last Change: 2018 jun 01 20:00
# this script aim: Programming in Python pg 37
# author: sergio luiz araujo silva
# site: http://vivaotux.blogspot.com
# ... | true |
d9eddfd175dd379bd8453f908a0d8c5abeef7a29 | bbullek/ProgrammingPractice | /bfs.py | 1,536 | 4.1875 | 4 | ''' Breadth first traversal for binary tree '''
# First, create a Queue class which will hold nodes to be visited
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
return self.queue.pop(0)
def isEmpty(self):
return len(self.queue) == 0
... | true |
17f30d9b41e3bac84534424877c3fc81791ef755 | jibachhydv/bloomED | /level1.py | 498 | 4.15625 | 4 | # Get the Number whose index is to be returned
while True:
try:
num = int(input("Get Integer: "))
break
except ValueError:
print("Your Input is not integer")
# List of Number
numbers = [3,6,5,8]
# Function that return index of input number
def returnIndex(listNum, num):
for i in ... | true |
fca406d84960938a40a1d2216983f2c07efa374e | Suraj-S-Patil/Python_Programs | /Simple_Intrst.py | 246 | 4.125 | 4 | #Program to calculate Simple Interest
print("Enter the principal amount, rate and time period: ")
princ=int(input())
rate=float(input())
time=float(input())
si=(princ*rate*time)/100
print(f"The simple interest for given data is: {si}.")
| true |
d552de01cad51b019587300e6cf5b7cbc5d3122f | Cherol08/finance-calculator | /finance_calculators.py | 2,713 | 4.40625 | 4 | import math
#program will ask user if they want to calculate total investment or loan amount
option = """ Choose either 'investment' or 'bond' from the menu below to proceed:\n
Investment - to calculate the amount of interest you'll earn on interest
Bond - to calculate the amount you'll have to pay on a home loan\n "... | true |
462321abc830736f71325221f81c4f5075dd46fb | amithjkamath/codesamples | /python/lpthw/ex21.py | 847 | 4.15625 | 4 | # This exercise introduces 'return' from functions, and hence daisy-chaining them.
# Amith, 01/11
def add(a, b):
print "Adding %d + %d" % (a,b)
return a + b
def subtract(a, b):
print "Subtracting %d - %d" % (a,b)
return a - b
def multiply(a,b):
print "Multiplying %d * %d" % (a,b)
return a*b
... | true |
923177e67d9afe32c3bcc738a8726234c5d08ad2 | CTRL-pour-over/Learn-Python-The-Hard-Way | /ex6.py | 758 | 4.5 | 4 | # Strings and Text
# This script demonstrates the function of %s, %r operators.
x = "There are %d types of people." % 10
binary = "binary" # saves the string as a variable
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not) # inserting variables ()
# here's where we print out our variables ^... | true |
568c69be02b59df5d2c531bb707be680fc5efa77 | CTRL-pour-over/Learn-Python-The-Hard-Way | /ex29.py | 1,080 | 4.65625 | 5 | # What If
# The if statements, used in conjunction with the > , < operators will print
# the following text if True.
# In other words, ( if x is True: print "a short story" )
# Indentation is needed for syntax purpouses. if you do not indent you will get
# "IndentationError: expected an indented block".
# If you do no... | true |
46554c75d2000a673d11d628b5921831bec87b74 | CTRL-pour-over/Learn-Python-The-Hard-Way | /ex15.py | 944 | 4.25 | 4 | # Reading Files
# this file is designed to open and read a given file as plain text
# provide ex15.py with an argument (file) and it will read it to you
# then it will as for the filename again, you can also give it a different file.
from sys import argv
# here is how we can give an additional argument when trying to ... | true |
2ca7c4e31ad857f80567942a0934d9399a6da033 | zoeyangyy/algo | /exponent.py | 600 | 4.28125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Time : 2018/8/16 下午10:27
# @Author : Zoe
# @File : exponent.py
# @Description :
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
result = base
if exponent == 0:
return ... | true |
36d281d594ec06a38a84980ca15a5087ccb2436a | connor-giles/Blackjack | /hand.py | 847 | 4.125 | 4 | """This script holds the definition of the Hand class"""
import deck
class Hand:
def __init__(self):
self.cards = [] # A list of the current cards in the user's hand
self.hand_value = 0 # The actual value of the user's hand
self.num_aces = 0 # Keeps track of the number of aces that the ... | true |
6b16f67a76c4951b641d252d40a1931552381975 | by46/geek | /codewars/4kyu/52e864d1ffb6ac25db00017f.py | 2,083 | 4.1875 | 4 | """Infix to Postfix Converter
https://www.codewars.com/kata/infix-to-postfix-converter/train/python
https://www.codewars.com/kata/52e864d1ffb6ac25db00017f
Construct a function that, when given a string containing an expression in infix notation,
will return an identical expression in postfix notation.
The op... | true |
81cfaff6e7ed2ac0be013d2439592c4fb8868e63 | apugithub/Python_Self | /negetive_num_check.py | 355 | 4.15625 | 4 |
# Negetive number check
def check(num):
return True if (num<0) else False
print(check(-2))
### The function does check and return the negatives from a list
lst = [4,-5,4, -3, 23, -254]
def neg(lst):
return [num for num in lst if num <0]
# or the above statement can be written as= return sum([num < 0... | true |
8f27badfdef2487c0eb87e659fac64210faa1646 | gaylonalfano/Python-3-Bootcamp | /card.py | 767 | 4.125 | 4 | # Card class from deck of cards exercise. Using for unit testing section
# Tests: __init__ and __repr__ functions
from random import shuffle
class Card:
available_suits = ("Hearts", "Diamonds", "Clubs", "Spades")
available_values = ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K")
def _... | true |
6bcb51fae80c295f98d6004344c5ffec1028f602 | gaylonalfano/Python-3-Bootcamp | /infinite_generators_get_multiples.py | 649 | 4.21875 | 4 | # def get_multiples(number=1, count=10):
# for i in range(1, count+1):
# yield number*i
#
# evens = get_multiples(2, 3)
# print(next(evens))
# print(next(evens))
# print(next(evens))
# print(next(evens))
# GET_UNLIMITED_MULTIPLES EXERCISE:
def get_unlimited_multiples(number=1):
next_num = number
... | true |
c68446d2fa042a3c279654f3937c16d632bf2420 | gaylonalfano/Python-3-Bootcamp | /decorators_logging_wraps_metadata.py | 2,667 | 4.40625 | 4 | """
Typical syntax:
def my_decorator(fn):
def wrapper(*args, **kwargs):
# do stuff with fn(*args, **kwargs)
pass
return wrapper
Another tutorial example: https://www.youtube.com/watch?v=swU3c34d2NQ
from functools import wraps
import logging
logging.basicConfig(filename='example.log', level=lo... | true |
0fa247aef355f85a8a00d44357933f418038c91d | gaylonalfano/Python-3-Bootcamp | /debugging_pdb.py | 1,790 | 4.1875 | 4 | '''
Python Debugger (pdb) -- To set breakpoints in our code we can use pdb by inserting this line:
def function(params):
import pdb; pdb.set_trace() - Usually added/imported like this inside a function
*Rest of code*
Usually placed right before something starts breaking. Allows you to see a preview of what h... | true |
9c309fa1bc6df7bf3d6e6b7ed047df45eb670316 | gaylonalfano/Python-3-Bootcamp | /sorted.py | 1,583 | 4.5625 | 5 | '''
sorted - Returns a new sorted LIST from the items in iterable (tuple, list, dict, str, etc.)
You can also pass it a reverse=True argument.
Key difference between sorted and .sort() is that .sort() is a list-only method and returns the
sorted list in-place. sorted() accepts any type of iterable. Good for sorted on ... | true |
a5668f587fe9b9b26b70afd0e7bf97bc317c35b3 | gaylonalfano/Python-3-Bootcamp | /polymorphism_OOP.py | 1,806 | 4.3125 | 4 | '''
POLYMORPHISM - A key principle in OOP is the idea of polymorphism - an object can take
on many (poly) forms (morph). Here are two important practical applications:
1. Polymorphism & Inheritance - The same class method works in a similar way for different classes
Cat.speak() # meow
Dog.speak() # woof
Human.speak(... | true |
79c42425fad9a2049934a8208d0b8cf9ca9b0a08 | gaylonalfano/Python-3-Bootcamp | /custom_for_loop_iterator_iterable.py | 1,648 | 4.4375 | 4 | # Custom For Loop
'''
ITERATOR - An object that can be iterated upon. An object which returns data,
ONE element at a time when next() is called on it. Think of it as anything we can
run a for loop on, but behind the scenes there's a method called next() working.
ITERABLE - An object which will return an ITERATOR when... | true |
2e9cde6ddaf45706eb646ec7404d22a851430e3f | gaylonalfano/Python-3-Bootcamp | /dundermethods_namemangling.py | 1,096 | 4.5 | 4 | # _name - Simply a convention. Supposed to be "private" and not used outside of the class
# __name - Name Mangling. Python will mangle/change the name of that attribute. Ex. p._Person__lol to find it
# Used for INHERITANCE. Python mangles the name and puts the class name in there for inheritance purposes.
# Think of hi... | true |
15dbca45f3fbb904d3f747d4f165e7dbca46c684 | XavierKoen/cp1404_practicals | /prac_01/loops.py | 924 | 4.5 | 4 | """
Programs to display different kinds of lists (numerical and other).
"""
#Basic list of odd numbers between 1 and 20 (inclusive).
for i in range(1, 21, 2):
print(i, end=' ')
print()
#Section a: List counting in 10s from 0 to 100.
for i in range(0, 101, 10):
print(i, end=' ')
print()
#Section b: List count... | true |
e1e5bdeab07475e95a766701d6feb6e14fe83494 | XavierKoen/cp1404_practicals | /prac_02/password_checker.py | 2,067 | 4.53125 | 5 | """
CP1404/CP5632 - Practical
Password checker code
"""
MIN_LENGTH = 2
MAX_LENGTH = 6
SPECIAL_CHARS_REQUIRED = False
SPECIAL_CHARACTERS = "!@#$%^&*()_-=+`~,./'[]<>?{}|\\"
def main():
"""Program to get and check a user's password."""
print("Please enter a valid password")
print("Your password must be betw... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.