blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
4bf00048cb0797c83a7b79a1525b4bf504d9be68 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/da7d2364-a2f6-4ca1-924c-9801f5195742__findSquareRoot.py | 1,049 | 4.3125 | 4 | #!/usr/local/bin/python
import sys
usage = """ Find square root of a give number
Usage: findSquareRoot.py <number>
Example: findSquareRoot.py 16"""
def main(argv):
"""
Executes the main() flow
@param argv: Command-line arguments
@type argv: array of strings
"""
if (len(argv) != 1):
print usage
sys.exit(2)
num = float(argv[0])
print 'Input number: ', num
squareRoot = getSquareRoot(num)
print 'Square root: ', squareRoot
def getSquareRoot(num):
"""
Finds square root of a given number
@param num: Number
@type num: integer
"""
isNegative = False
if (num < 0):
isNegative = True
num = abs(num)
# start with guess num / 2
guess = num / 2
# try to find square root within range
while (abs(guess * guess - num) > 0.001):
print guess
guess = (guess + num / guess) / 2
if (isNegative):
return str(guess) + " i"
return guess
if __name__ == "__main__":
main(sys.argv[1:]) | true |
0ca64c1c83f6b6ba01a3a8f5082d5aa3b88afcdd | kocoedwards/CTBlock4P4 | /firstParsonsProblems.py | 837 | 4.5 | 4 | """
March 2, 2021
Use this document to record your answers to the Parson's Problems
shared in class.
Remember: the idea behind a Parson's Problem is that you are
shown completely correct code that is presented OUT OF ORDER.
When arranged correctly, the code does what the Parson's Problem
says it should do.
"""
#Write your answer to Parson's Problem #1 below:
#basic for loop
for x in range (0,10):
print ("hello world")
#Write your answer to Parson's Problem #2 below:
#basic list
myList = ["apples", "pineapples"]
myList.append ("apples")
myList.append ("pineapples")
print (myList)
#Write your answer to Parson's Problem #3 below:
#basic conditional
x = input ("10")
x = int (x)
if x > 0:
print ("That're more than nothing!")
else:
print ("That's a small number")
| true |
20af73f2c6effe194835b9f137cabf854269f249 | breezey12/collaborative-code | /tryingArgv.py | 977 | 4.34375 | 4 | from sys import argv
def count(start, end, incrementBy=1):
# enumerates between start and end, only lists even numbers if even = true
while start <= end:
print start
start += incrementBy
def even(start):
start += start % 2
incrementBy = 2
return start, incrementBy
def countBy(countByVal):
incrementBy = countByVal
return incrementBy
if __name__ == "__main__":
""" validates the number of arguments, enumerates positional arguments,
finds and stores optional arguments, then feeds them all to count()
"""
paramct = len(argv)-1
optional_args = []
ordered_args = []
if paramct < 2:
print "At least two arguments are required."
else:
for arg in argv:
if arg[0] == "-":
optional_args.append(arg[1:])
else:
ordered_args.append(arg)
start = int(arg)
end = int(argv[2])
count(start, end)
| true |
287e21c219a5666f20d2a14b23d70cbc4154cec2 | ebogucka/automate-the-boring-stuff | /chapter_7/strong_password_detection.py | 948 | 4.28125 | 4 | #!/usr/bin/env python3
# Strong Password Detection
import re
def check(password):
lengthRegex = re.compile(r".{8,}") # at least eight characters long
if lengthRegex.search(password) is None:
print("Password too short!")
return
lowerRegex = re.compile(r"[a-z]+") # contains lowercase characters
upperRegex = re.compile(r"[A-Z]+") # contains uppercase characters
if lowerRegex.search(password) is None or upperRegex.search(password) is None:
print("Password should contain both lower and upper case characters!")
return
digitRegex = re.compile(r"[0-9]+") # has at least one digit
if digitRegex.search(password) is None:
print("Password should contain at least one digit!")
return
print("That is a strong password!")
passwords = ["abc", "abcdefgh", "dA", "dfJHFcvcjhsdfmn", "dfJHFcvcjhsdfmn69"]
for password in passwords:
print("\n" + password)
check(password)
| true |
1f6f43f9f60431b78ccec1d4499c2f52f4ee2646 | soluke22/python-exercise | /primenumbers.py | 496 | 4.15625 | 4 | #Ask the user for a number and determine whether the number is prime or not.
def get_numb(numb_text):
return int(input(numb_text))
prime_numb = get_numb("Pick any number:")
n = list(range(2,int(prime_numb)+1))
for a in n:
if prime_numb == 2:
print("That number is prime.")
break
elif prime_numb == 1:
print("That number is not prime.")
break
elif prime_numb%a == 0:
print("That number is not prime.")
break
else:
print("That is a prime number!")
break
| true |
00f478709a36a8623a38ec865bd78d189b369fec | hichingwa7/programming_problems | /circlearea.py | 519 | 4.125 | 4 | # date: 09/21/2019
# developer: Humphrey Shikoli
# programming language: Python
# description: program that accepts radius of a circle from user and computes area
########################################################################
#
def areacircle(x):
pi = 3.14
r = float(x)
area = pi * r * r
return area
print("Enter the radius of the cirle: ")
print(".............................. ")
radius = input()
print(".............................. ", "\n")
print("Area of the circle is: ", areacircle(radius)) | true |
10c7603e3a8f8d390134f23b5891604f6d0dc74b | krushnapgosavi/Division | /div.py | 923 | 4.1875 | 4 | import pyttsx3
print("\n This is the program which will help you to find the divisible numbers of your number!!")
ch=1
engine= pyttsx3.init()
engine.setProperty("rate", 115)
engine.say(" This is the program which will help you to find the divisible numbers of your number")
while ch==1:
engine.runAndWait()
engine.say("Which number's divisible number you want")
engine.runAndWait()
x=int(input("Which number's divisible no. you want? : "))
engine.say("This is your Divisible Number's of"+str(x))
g=0
for a in range(1,x+1):
g=g+1
b=int(x%g)
if b==0:
print(g)
engine.setProperty("rate",200)
engine.say(g)
engine.setProperty("rate",115)
engine.say("Thanks for using this program , Do you want to use again")
engine.runAndWait()
ch=int(input("Thanks for using this program.Do you want to use again?(Yes(1),No(0)) : "))
| true |
1c53c34020a44ea95474c71168179987913b4bcd | lvncnt/Leetcode-OJ | /Dynamic-Programming/python/Unique-Paths.py | 1,069 | 4.1875 | 4 | """
Problem:
A robot is located at the top-left corner of a m x n grid.
The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Note: m and n will be at most 100.
"""
# 1. No obstacles
def uniquePaths(m, n):
# Bottom-up DP
matrix = [[0]*(n + 1) for i in range(m + 1)]
matrix[m - 1][n] = 1
for i in range(m-1,-1,-1):
for j in range(n-1,-1,-1):
matrix[i][j] = matrix[i+1][j]+matrix[i][j+1]
return matrix[0][0]
# 2. Some obstacles are added to the grids.
# An obstacle and empty space is marked as 1 and 0 respectively in the grid.
def uniquePathsWithObstacles(obstacleGrid):
# Bottom-up DP
m = len(obstacleGrid)
n = len(obstacleGrid[0])
matrix = [[n+1] for i in range(m+1)]
matrix[m-1][n] = 1
for i in range(m-1,-1,-1):
for j in range(n-1,-1,-1):
matrix[i][j]=0 if obstacleGrid[i][j] == 1 else matrix[i+1][j]+matrix[i][j+1]
return matrix[0][0]
| true |
782bd10d6cad1e6f4893e311078968e191bc236b | dktlee/university_projects | /intro_to_comp_sci_in_python/bar_chart.py | 2,705 | 4.53125 | 5 | ##
## Dylan Lee
## Introduction to Computer Science (2015)
##
# bar_label_length(data, max_label_length, index) produces the length
# of the largest bar label that will be created from data, which is
# max_bar_length, by checking to see if the label in data at index is bigger
# than the max_bar_length so far
# requires: the format of data will always have an even number of elements
# where a bar label string is followed by a natural number for the
# bar length
# first call of index is 0
def bar_label_length(data, max_label_length, index):
if index >= len(data):
return max_label_length
elif len(data[index]) > max_label_length:
return bar_label_length(data, len(data[index]), index+2)
else:
return bar_label_length(data, max_label_length, index+2)
# chart_acc(data, label_index, length_index, max_bar_label) prints
# out a bar chart horizontally with bar labels named from the string in data
# at label_index with a bar length of the integer at length_index in data
# formated so that the bar label is right alinged according to the
# max_bar_label
# requires: the format of data will always have an even number of elements
# where a bar label string is followed by a natural number for the
# bar length
# first call of label_index is 0
# first call of length_index is 1
def chart_acc(data, label_index, length_index, max_bar_label):
if not(label_index >= len(data)):
label = "|" + " "*(max_bar_label - len(data[label_index])-1) \
+ data[label_index] + " |"
print(label + "#"*data[length_index])
chart_acc(data, label_index + 2, length_index+2, max_bar_label)
# chart(data) consumes a list called data and prints out a bar chart
# horizontally using text and symbols to draw the display
# effects: prints the data labels from data along with #'s representing
# the bars bars
# requires: the format of data will always have an even number of elements
# where a bar label string is followed by a natural number for the
# bar length
# Examples
# calling chart(["VW", 20, "Ford", 18, "Subaru", 3,
# "Mercedes", 7, "Fiat", 2]) prints:
#| VW |####################
#| Ford |##################
#| Subaru |###
#| Mercedes |#######
#| Fiat |##
# calling chart(["Rose", 1, "Lebron", 6, "Lowry", 7, "Kobe", 24, "Durant", 35]) prints:
#| Rose |#
#| Lebron |######
#| Lowry |#######
#| Kobe |########################
#| Durant |###################################
def chart(data):
max_bar_label = bar_label_length(data, len(data[0]), 0) + 2
chart_acc(data, 0, 1, max_bar_label) | true |
e7953f05fcd5ee001e04a473e1ed6b315c9a304e | akhitab-acharya/Mchine-learning | /Python.py | 1,981 | 4.34375 | 4 | ERROR: type should be string, got "https://cs231n.github.io/python-numpy-tutorial/\nPython & Numpy Tutorial by Stanford - It's really great and covers things from the ground up.\n\n#Quicksort\n\ndef quicksort(arr):\n if len(arr) <= 1:\n return arr\n pivot = arr[len(arr) // 2]\n left = [x for x in arr if x < pivot]\n middle = [x for x in arr if x == pivot]\n right = [x for x in arr if x > pivot]\n return quicksort(left) + middle + quicksort(right)\n\nprint(quicksort([3,6,8,10,1,2,1]))\n\n\n# Prints \"[1, 1, 2, 3, 6, 8, 10]\"\n\n-----------------------------------------\n\n#LIST COMPREHENSION:\n\nnums = [1, 2, 3, 4]\nnum_squares = [x**2 for x in nums]\nprint(num_squares)\n\n\n# list comprehension with conditions:\n\nnum_even_square = [x**2 for x in nums if x % 2 == 0]\nprint(num_even_square)\n\n------------------------------------------------------------\n\n# DICTIONARY COMPREHENSION:\n\nnums = [0, 1, 2, 3, 4]\neven_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}\nprint(even_num_to_square) # Prints \"{0: 0, 2: 4, 4: 16}\"\n\n--------------------------------------------------------------------------------------\ns = \"hello\"\nprint(s.capitalize()) # Capitalize a string; prints \"Hello\"\nprint(s.upper()) # Convert a string to uppercase; prints \"HELLO\"\nprint(s.rjust(7)) # Right-justify a string, padding with spaces; prints \" hello\"\nprint(s.center(7)) # Center a string, padding with spaces; prints \" hello \"\nprint(s.replace('l', '(ell)')) # Replace all instances of one substring with another;\n # prints \"he(ell)(ell)o\"\nprint(' world '.strip()) # Strip leading and trailing whitespace; prints \"world\"\n------------------------------------------------------------------------------------------\n\n# EX. OF ENUMERATE:\n\nanimals = {'cat', 'dog', 'cow'}\nfor idx, animal in enumerate(animals):\n print('#%d %s' % (idx + 1, animal))\n\n# Prints \"#1: cat\", \"#2: dog\", \"#3: monkey\", each on its own line\n\n-------------------------------------------------------------------\n\n\n" | true |
320fec5ea73f27447974d41dbcf7b80251e4bc88 | Viheershah12/python- | /Practice_Projects/odd-even.py | 656 | 4.21875 | 4 | num = int(input("Enter a number of your choice: "))
check = 2
dev = num % 2
if dev > 0:
print("The number ",num," is a odd number")
else:
print("The number ",num," is a even number")
# more complex function to see if the number is divisible by 4
num = int(input("give me a number to check: "))
check = int(input("give me a number to divide by: "))
if num % 4 == 0:
print(num, "is a multiple of 4")
elif num % 2 == 0:
print(num, "is an even number")
else:
print(num, "is an odd number")
if num % check == 0:
print(num, "divides evenly by", check)
else:
print(num, "does not divide evenly by", check)
input("Enter to exit") | true |
9cbbed20321eab76d4f326fc164df529b8b64b88 | Viheershah12/python- | /FutureLearn/conditional/IFSTATEMENTS.py | 295 | 4.34375 | 4 | x = 5
if x == 5:
print("this number is ",x)
else:
print("this number is not",x)
if x > 5 :
print("this number is greater than ",x)
else:
print("this number is less than or equal to ",x)
if x != 5:
print("this number is not equal to ",x)
else:
print("this number is ",x) | true |
a88fa735ad3cccfca126e03b4005848c88fd569d | Viheershah12/python- | /Lessons/calculatorfunc.py | 371 | 4.25 | 4 | #define a function to return the square of a given number
#define anathor function to add up the numbers
#use the functions created to solve the equation
# x = a + b^2
def add(x,y):
return x + y
def square(x):
return x * x
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
x = add(num1 , square(num2))
print(x)
input("Enter to exit")
| true |
54af20a4223a7fce77f976c6063056318656c59a | vamotest/yandex_algorithms | /12_01_typical_interview_tasks/L. Extra letter.py | 427 | 4.125 | 4 | from itertools import zip_longest
def define_anagrams(first, second):
li = list(zip_longest(first, second))
for letter in li:
if letter[0] != letter[1]:
return letter[1]
if __name__ == '__main__':
first_word = ''.join(sorted(list(str(input()))))
second_word = ''.join(sorted(list(str(input()))))
result = define_anagrams(first_word, second_word)
print(result)
| true |
414441654abcc71a08ba8a04f1d38f17f5c26184 | mtavecchio/Other_Primer | /Python/lab4/circle.py | 1,075 | 4.40625 | 4 | #!/usr/local/bin/python3
#FILE: circle.py
#DESC: A circle class that subclasses Shape, with is_collision(), distance(), and __str__() methods
from shape import Shape
from math import sqrt
class Circle(Shape):
"""Circle Class: inherits from Shape and has method area"""
pi = 3.14159
def __init__(self, r = 1, x = 0, y = 0):
Shape.__init__(self, x, y)
self.radius = r
def area(self):
"""Circle area method: returns the area of the circle."""
return self.radius * self.radius * self.pi
def __str__(self):
return "Circle of radius {:.0f} at coordinate ({:.0f}, {:.0f})"\
.format(self.radius, self.x, self.y)
@classmethod
def distance(Circle, c1, c2):
'''calculate distance between two circle'''
circ_distance = sqrt(c1.x**2 + c2.x**2)
return circ_distance
@classmethod
def is_collision(Circle, c1, c2):
'''Return True or None'''
if c2.radius > (c2.distance(c1, c2) - c1.radius):
return True
else:
return None
| true |
1a468b1e78271d168daf89fadb04ea212bd91b50 | foobar167/junkyard | /simple_scripts/longest_increasing_subsequence.py | 2,000 | 4.25 | 4 | l = [3,4,5,9,8,1,2,7,7,7,7,7,7,7,6,0,1]
empty = []
one = [1]
two = [2,1]
three = [1,0,2,3]
tricky = [1,2,3,0,-2,-1]
ring = [3,4,5,0,1,2]
internal = [9,1,2,3,4,5,0]
# consider your list as a ring, continuous and infinite
def longest_increasing_subsequence(l):
length = len(l)
if length == 0: return 0 # list is empty
i, tmp, longest = [0, 1, 1]
# 1 < tmp means that ring is finished, but the sequence continue to increase
while i < length or 1 < tmp:
# compare elements on the ring
if l[i%length] < l[(i+1)%length]:
tmp += 1
else:
if longest < tmp: longest = tmp
tmp = 1
i += 1
return longest
print("0 == " + str(longest_increasing_subsequence(empty)))
print("1 == " + str(longest_increasing_subsequence(one)))
print("2 == " + str(longest_increasing_subsequence(two)))
print("3 == " + str(longest_increasing_subsequence(three)))
print("5 == " + str(longest_increasing_subsequence(tricky)))
print("5 == " + str(longest_increasing_subsequence(internal)))
print("6 == " + str(longest_increasing_subsequence(ring)))
print("6 == " + str(longest_increasing_subsequence(l)))
def longest_increasing_subsequence2(l):
if len(l) == 0: return 0 # list is empty
lst = l + l
length = len(lst)
#print(lst)
i, tmp, longest = [0, 1, 1]
for i in range(length-1):
if lst[i] < lst[i+1]:
tmp += 1
else:
if longest < tmp: longest = tmp
tmp = 1
return longest
print("0 == " + str(longest_increasing_subsequence2(empty)))
print("1 == " + str(longest_increasing_subsequence2(one)))
print("2 == " + str(longest_increasing_subsequence2(two)))
print("3 == " + str(longest_increasing_subsequence2(three)))
print("5 == " + str(longest_increasing_subsequence2(tricky)))
print("5 == " + str(longest_increasing_subsequence2(internal)))
print("6 == " + str(longest_increasing_subsequence2(ring)))
print("6 == " + str(longest_increasing_subsequence2(l)))
| true |
7554a545e73e15f55208072f9e28dc3d10bb53ee | MaxwellGBrown/tom_swift | /tom_swift.py | 1,895 | 4.1875 | 4 | """Trigrams application to mutate text into new, surreal, forms.
http://codekata.com/kata/kata14-tom-swift-under-the-milkwood/
"""
from collections import defaultdict
import random
def read_trigrams(text):
"""Return a trigrams dictionary from text."""
trigrams = defaultdict(list)
split_text = text.split(" ")
while len(split_text) >= 3:
first, second, third, *rest = split_text
trigrams[(first, second)].append(third)
split_text = split_text[1:]
return trigrams
def _same_order(trigram):
"""Yield items in the same order they were read from.
This should create a result equal to the original text.
"""
keys = [k for k in trigram.keys()] # keys are ordered since 3.6
seed = [*keys[0]]
yield from (item for item in seed)
while any(v for v in trigram.values()):
value = trigram[(seed[-2], seed[-1])].pop(0)
yield value
seed = [seed[-1], value]
def _random(trigram):
"""Compose a trigram in the random order."""
keys = [k for k in trigram.keys()] # keys are ordered since 3.6
seed = [*random.choice(keys)]
yield from (item for item in seed)
while any(v for v in trigram.values()):
key = (seed[-2], seed[-1])
upper_bound = len(trigram[key])
if upper_bound < 1:
break
elif upper_bound == 1:
index = 0
else:
index = random.randint(0, upper_bound - 1)
value = trigram[key].pop(index)
yield value
seed = [seed[-1], value]
def compose_text(trigram, algorithm=_random):
"""Compose text given a trigram."""
items = [i for i in algorithm(trigram)]
return " ".join(items)
def main(text="I wish I may I wish I might"):
"""Execute the trigram."""
trigrams = read_trigrams(text)
print(compose_text(trigrams))
if __name__ == "__main__":
main()
| true |
a672c36493d46e20be291214640e0fbe11f2162f | Devfasttt/Tkinker | /Positioning With Tkinter's Grid System.py | 469 | 4.375 | 4 | #import tkinter
from tkinter import *
#main window
root=Tk()
#create a label widget
myLabel1=Label(root, text="hello i am a good, really good person")#.grid(row=0, column=0)
myLabel2=Label(root, text="Who are you?")#.grid(row=3, column=7)
myLabel3=Label(root, text=" ")#.grid(row=8, column=5)
#shoving it on the screen
myLabel1.grid(row=0, column=0)
myLabel2.grid(row=1, column=7)
myLabel3.grid(row=3, column=5)
#Call the main loop
root.mainloop()
| true |
527fc33c42c57314783a3c73ba753bc37cde9a36 | vishaltanwar96/DSA | /problems/mathematics/integer_to_roman.py | 1,698 | 4.375 | 4 | def int_to_roman(num: int) -> str:
"""
number is represented as its place value i.e. 5469 = 5000 + 400 + 60 + 9
Conversion is supported till 9999.
A helper hashmap is needed to map values to a string representation of that number in roman.
For converting a number to roman number we follow a simple stategy.
We extract each digit from the number and mulitply with its 10^multiplier.
if the number is directly present in map we return it otherwise we check if the extracted digit lies between
9 and 5 if so we simply subtract 5 from it and if anything is remaining (1, 2, 3) we simply prepend
multiplier * number_string_roman else we append multiplier * number_string_roman.
"""
number_roman_string_map = {
1: 'I',
4: 'IV',
5: 'V',
9: 'IX',
10: 'X',
40: 'XL',
50: 'L',
90: 'XC',
100: 'C',
400: 'CD',
500: 'D',
900: 'CM',
1000: 'M'
}
multiplier = 0
roman_number = ''
while num > 0:
face_value = num % 10
place_value = face_value * (10 ** multiplier)
if place_value in number_roman_string_map:
roman_number = number_roman_string_map[place_value] + roman_number
elif 5 < face_value < 9:
leftover = face_value - 5
roman_number = number_roman_string_map[10 ** multiplier] * leftover + roman_number
roman_number = number_roman_string_map[5 * (10 ** multiplier)] + roman_number
else:
roman_number = number_roman_string_map[10 ** multiplier] * face_value + roman_number
num //= 10
multiplier += 1
return roman_number
| true |
872fa237b31821e8cc70700017314d2273a9ea9f | jaejun1679-cmis/jaejun1679-cmis-cs2 | /startotend.py | 946 | 4.15625 | 4 | import time
def find(start, end, attempt):
if start > end:
countdownfrom(start, end, attempt)
elif end > start:
countupfrom(start, end, attempt)
def countdownfrom(start, end, attempt):
if start == end:
print "We made it to " + str(end) + "!"
else:
time.sleep(1)
if attempt == 0:
print start
print start - 1
attempt = attempt + 1
countdownfrom((start - 1), end, attempt)
def countupfrom(start, end, attempt):
if start == end:
print "We made it to " + str(start) + "!"
else:
time.sleep(1)
if attempt == 0:
print start
print start + 1
attempt = attempt + 1
countupfrom((start + 1), end, attempt)
def main():
start = float(raw_input("Insert the starting number: "))
end = float(raw_input("Insert the ending number: "))
attempt = 0
find(start, end, attempt)
main()
| true |
f93622696104e20e2079975a9cd6b98ce5a75a2d | gk90731/100-questions-practice | /16.py | 234 | 4.25 | 4 | #Please complete the script so that it prints out the value of key b .
#d = {"a": 1, "b": 2}
#Expected output: 2
d = {"a": 1, "b": 2}
print(d["b"])
# lists have indexes, while dictionaries have keys which you create by yourself.
| true |
07d6bdf68d139c030ecb46a0a789146621671217 | matttu120/Python | /HackerRank/WhatsYourName.py | 724 | 4.1875 | 4 | '''
Problem Statement
Let's learn the basics of Python! You are given the first name and the last name of a person. Your task is to read them and print the following:
Hello firstname lastname! You just delved into python.
It's that simple!
In Python you can read a line as a string using
s = raw_input()
#here s reads the whole line.
Input Format The first line contains the first name, and the second line contains the last name.
Constraints
The length of the first and last name ≤ 10.
Output Format Print the output as mentioned above.
'''# Enter your code here. Read input from STDIN. Print output to STDOUT
s1 = raw_input()
s2 = raw_input()
print "Hello " + s1 + " " + s2 + "! You just delved into python."
| true |
eb9f909b5f7c13edf72d05b8554dd8608f21acd7 | Eliacim/Checkio.org | /Python/Home/Sun-angle.py | 1,503 | 4.46875 | 4 | '''
https://py.checkio.org/en/mission/sun-angle/
Every true traveler must know how to do 3 things: fix the fire, find the water
and extract useful information from the nature around him. Programming won't
help you with the fire and water, but when it comes to the information
extraction - it might be just the thing you need.
Your task is to find the angle of the sun above the horizon knowing the time of
the day. Input data: the sun rises in the East at 6:00 AM, which corresponds to
the angle of 0 degrees. At 12:00 PM the sun reaches its zenith, which means
that the angle equals 90 degrees. 6:00 PM is the time of the sunset so the
angle is 180 degrees. If the input will be the time of the night (before 6:00
AM or after 6:00 PM), your function should return - "I don't see the sun!".
example
Input: The time of the day.
Output: The angle of the sun, rounded to 2 decimal places.
Precondition: 00:00 <= time <= 23:59
'''
def sun_angle(time):
h, m = time.split(':')
angle = ((int(h) - 6) * 60 + int(m)) * (180 / 720)
return "I don't see the sun!" if angle < 0 or angle > 180 else angle
if __name__ == '__main__':
print("Example:")
print(sun_angle("07:00"))
print(sun_angle("01:23"))
print(sun_angle("18:01"))
# These "asserts" using only for self-checking and not necessary for
# auto-testing
assert sun_angle("07:00") == 15
assert sun_angle("01:23") == "I don't see the sun!"
print("Coding complete? Click 'Check' to earn cool rewards!")
| true |
3baebfc0fe2aa3a56263a967dcb288b2fd88b6da | Eliacim/Checkio.org | /Python/Electronic-Station/All-upper-ii.py | 769 | 4.5 | 4 | '''
https://py.checkio.org/en/mission/all-upper-ii/
Check if a given string has all symbols in upper case. If the string is empty
or doesn't have any letter in it - function should return False.
Input: A string.
Output: a boolean.
Precondition: a-z, A-Z, 1-9 and spaces
'''
def is_all_upper(text: str) -> bool:
return True if text.strip() and text == text.upper()\
and not text.isdigit() else False
if __name__ == '__main__':
print("Example:")
print(is_all_upper('ALL UPPER'))
# These "asserts" are used for self-checking and not for an auto-testing
assert is_all_upper('ALL UPPER') is True
assert is_all_upper('all lower') is False
assert is_all_upper('mixed UPPER and lower') is False
assert is_all_upper('') is False
| true |
59c8a0575f9a59348cfcb6a0fb8029f9c3b32366 | Eliacim/Checkio.org | /Python/Mine/Fizz-buzz.py | 1,125 | 4.46875 | 4 | '''
https://py.checkio.org/en/mission/fizz-buzz/
Fizz Buzz
Elementary
"Fizz buzz" is a word game we will use to teach the robots about division.
Let's learn computers.
You should write a function that will receive a positive integer and return:
"Fizz Buzz" if the number is divisible by 3 and by 5;
"Fizz" if the number is divisible by 3;
"Buzz" if the number is divisible by 5;
The number as a string for other cases.
Input: A number as an integer.
Output: The answer as a string.
Example:
checkio(15) == "Fizz Buzz"
checkio(6) == "Fizz"
checkio(5) == "Buzz"
checkio(7) == "7"
Precondition: 0 < number ≤ 1000
'''
def checkio(number: int) -> str:
return 'Fizz Buzz' if number % 15 == 0 else 'Buzz' if number % 5 == 0\
else 'Fizz' if number % 3 == 0 else str(number)
if __name__ == '__main__':
print('Example:')
print(checkio(15))
print(checkio(7))
assert checkio(15) == "Fizz Buzz", "15 is divisible by 3 and 5"
assert checkio(6) == "Fizz", "6 is divisible by 3"
assert checkio(5) == "Buzz", "5 is divisible by 5"
assert checkio(7) == "7", "7 is not divisible by 3 or 5"
| true |
b8b26c1d753a8c1511d2243bb31a373790e6ce0a | ITorres20/week2-hello-world | /helloworld.py | 626 | 4.46875 | 4 | #Ivetteliz Torres
# this program is suppose to display the hello world greeting in three different languages
language1= 'Hola Mundo!'
language2= 'Ola Mundo!'
language3= 'Bonjour le monde!'
print 'Hello World!' # greeting
print 'Please select one of the following languages.' # ask the user for language selection
#language selections
print '1.Spanish'
print '2.Portuguese'
print '3.French'
lang =input()
# from here on is where im having difficulty I dont know what im doing wrong,Please advise
if lang='1'
ans=language1
print(language1)
if lang='2'
ans=language2
print(language2)
if lang='3'
ans=language3
print(language3)
| true |
5b0002f4992b9cd73d114d3cc2fe02735a473e36 | anchaubey/pythonscripts | /file_read_write_operations/file1.py | 2,790 | 4.71875 | 5 | There are three ways to read data from a text file.
read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.
File_object.read([n])
readline() : Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line.
File_object.readline([n])
readlines() : Reads all the lines and return them as each line a string element in a list.
File_object.readlines()
with open("C:\\Users\\ankit\\Desktop\\test.txt","w+") as f:
f.write("We are learning python\nWe are learning python\nWe are learning python")
f.seek(0)
print(f.read())
print("Is readable:",f.readable())
print("Is writeable:",f.writable())
f.truncate(5)
f.flush()
f.seek(0)
print(f.read())
f.close()
==========================================================
if f.mode == 'r':
==========================
Note: ‘\n’ is treated as a special character of two bytes
# Program to show various ways to read and
# write data in a file.
file1 = open("C:\\Users\\ankit\\Desktop\\falcon.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes
file1 = open("myfile.txt","r+")
print("Output of Read function is ")
print(file1.read())
print()
# seek(n) takes the file handle to the nth
# bite from the beginning.
file1.seek(0)
print "Output of Readline function is "
print(file1.readline())
print
file1.seek(0)
# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
===============================================
Apending to a file
# Python program to illustrate
# Append vs write mode
file1 = open("C:\\Users\\ankit\\Desktop\\falcon.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
file1.close()
# Append-adds at last
file1 = open("C:\\Users\\ankit\\Desktop\\falcon.txt","a")#append mode
file1.write("Today \n")
file1.close()
file1 = open("C:\\Users\\ankit\\Desktop\\falcon.txt","r")
print("Output of Readlines after appending")
print(file1.readlines())
print()
file1.close()
# Write-Overwrites
file1 = open("C:\\Users\\ankit\\Desktop\\falcon.txt","w")#write mode
file1.write("Tomorrow \n")
file1.close()
file1 = open("C:\\Users\\ankit\\Desktop\\falcon.txt","r")
print("Output of Readlines after writing")
print(file1.readlines())
print()
file1.close()
| true |
7fb04b986773cf7a002ceb8078dc11f6b3f9b6b5 | learnMyHobby/list_HW | /sets.py | 586 | 4.5625 | 5 | # A = [‘a’,’b’,’c’,’d’] B = [‘1’,’a’,’2’,’b’]
# Find a intersection b and a union b
import math
# declaring the function
def Union(A,B):
result = list(set(A) | set(B)) # | it is or operator it adds the list since we cannot
return result # add the sets
# finding the intersection of list a and b
def Intersection(A,B):
result_1 = list(set(A) & set(B))
return result_1
A = ['a','b','c','d']
B = ['1','a','2','b']
print("Union is : ",Union(A,B))
print("Intersection between A and B is: ", Intersection(A,B))
| true |
b2358665ea9f13f35c00143fdb19b89cb52959cb | jhhalls/machine_learning_templates | /Clustering/k-means.py | 1,926 | 4.34375 | 4 | """
@author : jhhalls
K - MEANS
1. Import the libraries
2. Import the data
3. Find Optimal number of clusters
4. Build K-means Clustering model with optimal number of clusters
5. Predict the Result
6. Visualize the clusters
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#import mall dataset with pandas
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:,[3,4]].values
#find the optimal number of cluster with the elbow method
from sklearn.cluster import KMeans
wcss = []
for i in range(1,11):
kmeans = KMeans(n_clusters = i,
init = 'k-means++',
max_iter= 300,
n_init = 10,
random_state = 0)
kmeans.fit(X)
wcss.append(kmeans.inertia_)
#plot
plt.plot(range(1,11),wcss)
plt.title('The elbow method for K-means')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()
#apply k-mean with the optimal #of clusters
kmeans = KMeans(n_clusters = 5,
init = 'k-means++',
max_iter= 300,
n_init = 10,
random_state = 0)
#get a list of data points with the correspondent cluster
y_kmeans = kmeans.fit_predict(X)
#plot the cluster results
plt.scatter(X[y_kmeans==0,0], X[y_kmeans==0,1], s=100, c='red', label ='Careful')
plt.scatter(X[y_kmeans==1,0], X[y_kmeans==1,1], s=100, c='blue', label ='Standard')
plt.scatter(X[y_kmeans==2,0], X[y_kmeans==2,1], s=100, c='green', label ='Target')
plt.scatter(X[y_kmeans==3,0], X[y_kmeans==3,1], s=100, c='magenta', label ='Careless')
plt.scatter(X[y_kmeans==4,0], X[y_kmeans==4,1], s=100, c='cyan', label ='Sensible')
plt.scatter(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], s= 300, c='yellow',
label = 'centroid')
plt.title('Cluster of clients')
plt.xlabel('Annual salary K$')
plt.ylabel('Spending score')
plt.legend()
plt.show()
| true |
f13f34892527aea07186b8785b0d083bb9fed5ef | SJChou88/dsp | /python/q8_parsing.py | 915 | 4.3125 | 4 | # The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
import csv
with open('/Users/stephenchou/ds/metis/metisgh/prework/dsp/python/football.csv') as f:
reader = csv.DictReader(f)
smallestgd = None
for row in reader:
absgd = abs(int(row['Goals'])-int(row['Goals Allowed']))
if smallestgd == None:
smallestgd = absgd
smallestname = row['Team']
elif smallestgd > absgd:
smallestgd = absgd
smallestname = row['Team']
print(smallestname) | true |
9a12200c5d3af09cc03550fb4f3449cd5be6dfdd | susunini/leetcode | /110_Balanced_Binary_Tree.py | 2,508 | 4.15625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
""" Wrong. Different fromt this problem, another definition of height balanced tree.
-> max depth of leaf node - min depth of leaf node <= 1
For example
1
2
3
"""
pass
class Solution(object):
""" Wrong. """
def getDepth(self, root):
if not root:
return 0
left_dep = self.getDepth(root.left)
if left_dep == -1:
return -1
right_dep = self.getDepth(root.right)
if right_dep == -1:
return -1
return max(left_dep, right_dep) if abs(left_dep - right_dep) <= 1 else -1
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
left_dep = self.getDepth(root.left)
right_dep = self.getDepth(root.right)
return left_dep != -1 and right_dep != -1 and abs(left_dep - right_dep) <= 1
class Solution(object):
""" Tree. Divide and Conquer. 75ms.
Definition of height balanced tree"""
def getDepth(self, root):
if not root:
return 0
left_dep = self.getDepth(root.left)
if left_dep == -1:
return -1
right_dep = self.getDepth(root.right)
if right_dep == -1:
return -1
return max(left_dep, right_dep) + 1 if abs(left_dep - right_dep) <= 1 else -1
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
left_dep = self.getDepth(root.left)
right_dep = self.getDepth(root.right)
return left_dep != -1 and right_dep != -1 and abs(left_dep - right_dep) <= 1
UNBAL = -1
class Solution(object):
""" 88ms. """
def getDepth(self, root):
if not root:
return 0
left_dep = self.getDepth(root.left)
if left_dep == UNBAL:
return UNBAL
right_dep = self.getDepth(root.right)
if right_dep == UNBAL:
return UNBAL
return max(left_dep, right_dep) + 1 if abs(left_dep - right_dep) <= 1 else UNBAL
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.getDepth(root) != UNBAL
| true |
fc81d349674608957642b6ef0663e1a1c6433370 | susunini/leetcode | /143_Reorder_List.py | 1,109 | 4.125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
""" Linked List.
Classic problem. It is composed of three steps which are commonly
used for different linked list problems.
step 1: find middle node and split into two halves
step 2: reverse the second half
step 3: merge two lists
"""
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
if not head:
return head
slow = head; fast = head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
h1 = head; h2 = slow.next
slow.next = None
prev = None; cur = h2
while cur:
cur.next, prev, cur = prev, cur, cur.next
h2 = prev
p1 = h1
p2 = h2
while p2:
p1.next, p2.next, p1, p2 = p2, p1.next, p1.next, p2.next
| true |
b98bd948a6cf84a855a21a9912242964ff285ea3 | RonKang1994/Practicals_CP1404 | /Practical 4/Lecture 4.py | 779 | 4.21875 | 4 | VOWELS_CHECK = 'aeiou'
def check_vowel():
name = str(input("Name: "))
letter = 0
vowel = 0
for char in name:
letter += 1
for v_check in VOWELS_CHECK:
if char.lower() == v_check.lower():
vowel += 1
print("Out of {} letters {} has {} vowels".format(letter, name, vowel))
def long_list(text):
text_list = text.split()
final_list = list()
for i in range(0, len(text_list)):
if len(text_list[i]) > 3:
final_list.append(text_list[i])
print(final_list)
def main():
# Give a name and check how many vowels there are in it
# check_vowel()
# Convert a string into a list and give ones which have 3> characters
text = "This is a sentence"
long_list(text)
main() | true |
cea319acb2704979a43663448216e9cc322e3feb | LizhangX/DojoAssignments | /PythonFun/pyFun/Multiples_Sum_Average.py | 690 | 4.4375 | 4 | # Multiples
# Part I - Write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use a list to do this exercise.
for i in range(0,1000):
if i % 2 != 0:
print i
# Part II - Create another program that prints all the multiples of 5 from 5 to 1,000,000.
for i in range(5,1000000):
if i % 5 == 0:
print i
# Sum List
# Create a program that prints the sum of all the values in the list: a = [1, 2, 5, 10, 255, 3]
a = [1, 2, 5, 10, 255, 3]
sum = 0
for i in range(0,len(a)):
sum += a[i]
print sum
# Average List
# Create a program that prints the average of the values in the list: a = [1, 2, 5, 10, 255, 3]
avg = sum/len(a)
print avg | true |
180f640a3db8b9ba5ec1dba6d8c0605968ac0fa1 | xdisna2/4FunctCalc | /test.py | 876 | 4.4375 | 4 | # Testing type conversions
# Entering an int
x = float(input("Number 1:"))
# Convert to float
# So matter its a string it will include the .0 to make it a float
print(x)
# Change from float to int
x = 11.0
print(type(x))
x = round(11.0)
print(type(x))
# Test out is_integer function
# Note to self you must declare it as a float to try it out
x = float(input("Enter a number:"))
# Convert to int
if x.is_integer():
x = round(x)
print(x)
# Lets try adding two numbers of different types
x = 11
y = 11.5
z = x + y
# Of course this will output a float
print(z)
# What if it was 2 floats but they add to become an integer?
x = 11.0
y = 11.0
z = x + y
# It will output a float but truly its an even whole number
print(z)
# Now if the total adds up to become an integer then it will make it an integer (whole number)
if z.is_integer():
z = round(z)
print(z) | true |
757e96688c44e4f4994e151c5b664878d2a2c8d7 | RAMYA-CP/PESU-IO-SUMMER | /coding_assignment_module1/one.py | 348 | 4.3125 | 4 | #Write a Python program which accepts a sequence of comma-separated numbers from the user and generate a list and a tuple with those numbers.
l=input().split(',')
list_n=[]
for i in l:
list_n.append(int(i))
tuple_n=tuple(list_n)
print("THIS IS A LIST OF ELEMENTS:")
print(list_n)
print("THIS IS A TUPLE OF ELEMENTS:")
print(tuple_n)
| true |
c063891b5f3f8ad713ca6a22416235e38553b7e4 | biomathcode/Rosalind_solutions | /Bioinformatics Stronghold/IEN.py | 1,081 | 4.15625 | 4 | ## Calculating Expected offspring
"""
Given: Six nonnegative integers, each of which does not exceed 20,000. The integers correspond to the number of couples in a population possessing each genotype pairing for a given factor. In order, the six given integers represent the number of couples having the following genotypes:
AA-AA
AA-Aa
AA-aa
Aa-Aa
Aa-aa
aa-aa
Return: The expected number of offspring displaying the dominant phenotype in the next generation, under the assumption that every couple has exactly two offspring.
"""
def file_parser(file_name):
with open("docs/" + file_name) as f:
f = f.readline()
##number of offspring list
offList = f.split(' ')
offList = [int(x) for x in offList]
print(offList)
return offList
def expected_offspring(a):
sum = (a[0] * 1 + a[1] * 1 + a[2] * 1 + a[3] *0.75 + a[4] *0.5 + a[5] * 0) * 2
return sum
if __name__ == "__main__":
file_name = input('Please type the filename here')
offspring_list = file_parser(file_name)
print(expected_offspring(offspring_list))
| true |
f180736db7b68d0c12b796a04106660f5ed1a28b | PurityControl/uchi-komi-python | /problems/euler/0008-largest-product-in-series/ichi/largest_product_in_series.py | 893 | 4.40625 | 4 | def largest_product(length, str_of_digits):
""" returns the largest product of contiguous digits of length length
in a string of digits
args:
length: the length of contiguous digits to be calculated
str_of_digits: the string of digits to calculate the products from
"""
return max(product(nums) for nums in succesive_seqs(length, str_of_digits))
def product(lodigits):
return reduce(lambda x,y: x*y, lodigits)
def succesive_seqs(length, str_of_digits):
"""Generator takes a string of digits and returns succesive
lists of contiguous digits of length length
Args:
length: number of contiguous digits to take from list
str_of_digits: the string of digits to split up
"""
digit_list = [int(x) for x in list(str_of_digits)]
for index in range(len(str_of_digits) - length):
yield digit_list[index:index+length]
| true |
702d0eea27aa14c1d522ac6c06673dc0cecd0778 | PurityControl/uchi-komi-python | /problems/euler/0009-special-pythagorean-triplet/ichi/pythagorean_triplet.py | 596 | 4.25 | 4 | def pythagorean_triplet(sum):
""" returns the first pythagorean triplet whose lengths total sums
args:
sum: the amount the lengths of the triangle must total
"""
return first(a * b * c for (a, b, c) in triplets_summing(sum))
def triplet_p(a, b, c):
return (a * a) + (b * b) == (c * c)
def first(seq):
return next(seq)
def triplets_summing(total):
for a in range(total+1):
for b in range(total+1):
for c in range(total+1):
if (a + b + c == total) and (a < b < c) and triplet_p(a, b, c):
yield (a, b, c)
| true |
0f76d1582d68ace6e5b7d92e07ec84805220ae92 | ktops/SI-206-HW04-ktops | /magic_eight.py | 843 | 4.125 | 4 | def user_question():
user_input = input("What is your quesiton? ")
return user_input
user_input = ""
while user_input is not "quit":
user_input = user_question()
if user_input[-1] is not "?":
print("I'm sorry, I can only answer questions.")
else:
break
import random
possible_answers = ["It is certain", "It is decidedly so", "Without a doubt", "Yes definitely",
"You may rely on it", "As I see it, yes", "Most likely", "Outlook good","Yes", "Signs point to yes", "Ask again later", "Better not to tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful"]
answer_to_question = random.choice(possible_answers)
print(answer_to_question)
| true |
e3487062e8ae883c7c7e77df308fef5291821f2f | kedarjk44/basic_python | /lambda_map_filter_reduce.py | 485 | 4.21875 | 4 | # lambda can be used instead of writing a function
add_two_inputs = lambda x, y: x + y
print(add_two_inputs(8, 5))
print(add_two_inputs("this", " that"))
# map can be used to apply a function to each element of a list
list1 = [1, 2, 3, 4]
print(*list(map(lambda x: x**2, list1)))
# or can be done as
print(*[x**2 for x in list1])
# filter can be used to apply a condition to list
print(*list(filter(lambda x: x > 2, list1)))
# or can be done as
print(*[x for x in list1 if x > 2])
| true |
f1e43c1f7195269a40c8b2e4e9c721f062c5f617 | canadian-coding/posts | /2019/August/21st - Basic Logging in python/logging_demo.py | 1,777 | 4.21875 | 4 | import logging # Module that allows you to create logs; Logs are very helpful for down the road debugging
import datetime # Used in formatting strings to identify date and time
def print_num():
"""Takes user input, and if it's an int or float prints it."""
logging.debug("Starting print_int") # Only gets logged if loggers level is DEBUG (10) or below
try:
logging.info("Prompting for input") # Only gets logged if loggers level is INFO (20) or below
user_input = input("Enter a number:")
user_input = eval(user_input) # Convert input to an int or float
except: # If the user enters something other than an int or float
logging.warning(f"User didn't enter a number, they entered {user_input}") # Only gets logged if loggers level is WARNING (30) or below
logging.info(f"User entered int or float: {user_input}")
print(f"User entered int or float: {user_input}")
if __name__ == "__main__":
# For backwards compatability the logging module forces % formatting for predefined values
# SEE: For a full list of variables visit: https://docs.python.org/3/library/logging.html#logrecord-attributes
LOG_FORMAT = "{0} | %(levelname)s | %(module)s | : %(message)s".format(datetime.datetime.now().time())
# Instantiate a logger in the simplest way possible
logging.basicConfig(format=LOG_FORMAT, # Pass the log format defined above to the logger
filename='example.log', # Specifying a filename automatically puts all logs in the filename path
filemode='w', # Allows you to specify filemode; SEE: https://docs.python.org/3.7/library/functions.html#open
level=logging.DEBUG) # Defines what type of logs should show up; SEE: https://docs.python.org/3/howto/logging.html#logging-levels
print_num() | true |
0f7e7f6a8fd56a5a5e7c50ae78a0662050735c7e | canadian-coding/posts | /2019/July/8th - Optional boolean arguments in argparse/optional_boolean_arguments.py | 949 | 4.3125 | 4 | """A demo of optional boolean arguments using argparse."""
import argparse # Module used to set up argument parser
# Setting up Main Argument Parser
main_parser = argparse.ArgumentParser(description="A demo of optional boolean arguments")
# Adding optional boolean argument
main_parser.add_argument("-r", '--run',
help="If argument is present run 'print('hello')'",
action='store_true', # If -r is present, the argument is True
default=False, # If -r is not present the argument is False
required=False, # Makes argument optional
dest="run") # Makes variable accessible as 'run', see lines 19-26
def function_to_run():
"""Function intended to run if the -r or --run command is used"""
print("-r or --run was called")
# Argument parsing
args = main_parser.parse_args()
if args.run: # If -r or --run is specified, run function_to_run()
function_to_run()
else: # If -r or --run was not present
print("-r or --run was not called")
| true |
1d3124d8e22793e7cb0a9abc4d1e4a9005e2bad4 | lastcanti/learnPython | /review2.py | 555 | 4.15625 | 4 | # python variables and collections
print("I am a print statement")
# use input to get data from console
#someData = input("Enter some data: ")
#print(someData)
# lists are used to store data
a = []
a.append(1)
a.append("a")
a.pop()
b = [2]
print a
print a + b
c = (1,"a",True)
print(type(c))
print(len(c))
# tuples assigned to variables
guitar3,guitar4,guitar5 = ("fender","gibson","ibanez")
print(guitar3,guitar4,guitar5)
# dictionary creation
dict1 = {"one": 1, "two": 2, "three": 3}
print(dict1["one"])
print(dict1.keys())
print(dict1.values())
| true |
85527d167d7805f2f402da1c2f59e03178e3043a | Todai88/me | /kmom01/plane/plane1.py | 445 | 4.5 | 4 | """
Height converter
"""
height = format(1100 * 3.28084, '.2f')
speed = format(1000 * 0.62137, '.2f')
temperature = format(-50 * (9/5) + 32, '.2f')
print("""\r\n########### OUTPUT ###########\r\n\r\nThe elevation is {feet} above the sea level, \r\n
you are going {miles} miles/h, \r\n
finally the temperature outside is {temp} degrees fahrenheit \r\n
########### OUTPUT ###########""".format(feet=height, miles=speed, temp=temperature))
| true |
d6a5422996f26970b11e5a756af66c7e0d33ca0e | Todai88/me | /kmom01/hello/hello.py | 681 | 4.4375 | 4 | """
Height converter
"""
height = float(input("What is the plane's elevation in metres? \r\n"))
height = format(height * 3.28084, '.2f')
speed = float(input("What is the plane's speed in km/h? \r\n"))
speed = format(speed * 0.62137, '.2f')
temperature = float(input("Finally, what is the temperature (in celsius) outside? \r\n"))
temperature = format(temperature * (9/5) + 32, '.2f')
print("""\r\n########### OUTPUT ########### \r\n \r\n The elevation is {feet} above the sea level, \r\n
you are going {miles} miles/h, \r\n
finally the temperature outside is {temp} degrees fahrenheit \r\n
########### OUTPUT ###########""".format(feet=height, miles=speed, temp=temperature))
| true |
b0b67c197c66734915eef38b4d00787eda45e06c | cabbageGG/play_with_algorithm | /LeetCode/125_isPalindrome.py | 1,034 | 4.25 | 4 | #-*- coding: utf-8 -*-
'''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
'''
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
l = len(s)
i = 0
j = l - 1
while i<j:
while i<j and not s[i].isalnum():
i += 1
while i<j and not s[j].isalnum():
j -= 1
if s[i].upper() == s[j].upper():
i += 1
j -= 1
else:
return False
return True
if __name__ == '__main__':
s = Solution()
ss = "a.b,."
ss[0].isalnum()
tt = s.isPalindrome(ss)
print (tt)
| true |
9949c12df71be1f193ee8de7427701ec75d6b4b7 | DoneWithWork/Number-Guessing-Game | /Number Guessing Game.py | 1,547 | 4.53125 | 5 | # Import random module
import random
# Number of guesses is 3
guesses = 3
# Getting a random number between and including 1 and 10
number = random.randint(1,10)
# Some basic print statements
print("Welcome to guess the number")
print("You have to guess a number from 1-10")
print("You have 3 guesses")
# While the guesses is greater than 0, repeat the code below.
while guesses >0:
choice = int(input("Enter your guess (1-10): ")) # Getting the player input
if choice == number: # If the player's choice is equal to the number
print("You WIN!! The number was ",number) # Printing a win message and the number
quit() # exit the programme
elif choice < number: # If the player's input is smaller than the number, run the code below.
guesses -=1 # Guesses minus 1, Player has one less guess.
print("Your choice is smaller than the number. You have",guesses,"more guesses") # Giving a hint that the player's choice is smaller than the number
elif choice > number: # If the player's choice is greater than the number, run the code below.
guesses -=1 # Guesses minus 1, Player has one less guess.
print("Your choice is bigger than the number. You have",guesses,"more guesses") # Giving a hint that the player's choice is bigger than the number
# When the number of guesses is 0, the code below only will be carried out as the player would have run out of guesses.
print("You lost!! The number is",number)# Printing a lose message and the number
| true |
73692164f112b92a5786c10df1691a17aca9b38f | BolajiOlajide/python_learning | /beyond_basics/map_filter_reduce.py | 616 | 4.15625 | 4 | from functools import reduce
import operator
mul = lambda x: x * 2
items = [1, 2, 4, 5, 6, 8, 9, 10]
print(map(mul, items)) # [4, 8, 12, 16, 20]
# if you are using python3 then the result of map and filter will
# be lazy loaded so you have to manually convert to a list
first_names = ["John", "Jane", "James", "Jacob", "Jennifer"]
last_names = ["Doe", "Wash", "McClean", "James"]
print()
is_odd = lambda x: not (x % 2)
print(filter(is_odd, items)) # [2, 4, 6, 8, 10]
mul_2 = lambda x, y: x * y
new_items = [1, 2, 3, 4, 5]
print(reduce(mul_2, new_items)) # 120
print(reduce(operator.add, new_items)) # 15
| true |
43c0bc0302ce5d541f29de7c3cac24a926b21209 | jm-avila/REST-APIs-Python | /Refresher/09_the_in_keyword/code.py | 299 | 4.125 | 4 | movies_watched = {"The Matrix", "Green Book", "Her"}
user_movie = input("Enter something you've watched recently: ")
print("in movies_watched", user_movie in movies_watched)
vowels = "aeiou"
user_letter = input("Enter a letter and see if it's a vowel: ")
print("in vowels", user_letter in vowels) | true |
92988d12250b0d14e4a4a6d5e688f33f973b8b2d | DavidCorzo/EstructuraDeDatos | /#SearchingAndSorting/Sorting.py | 1,159 | 4.125 | 4 | def selection_sort(unsorted: list) -> list:
for i in range(0, len(unsorted) - 1):
min = i
for j in range(i + 1, len(unsorted)):
if unsorted[j] < unsorted[min]:
min = j
if min != i:
unsorted[i], unsorted[min] = unsorted[min], unsorted[i]
return unsorted
def bubble_sort(unsorted: list) -> list:
for i in range(0, len(unsorted)):
for j in range(0, len(unsorted) - 1 - i):
if unsorted[j] > unsorted[j + 1]:
unsorted[j], unsorted[j + 1] = unsorted[j + 1], unsorted[j]
return unsorted
def quick_sort(unordered_list: list) -> list:
lenght = len(unordered_list)
if lenght <= 1:
return unordered_list
else: # the last element is poped
pivot = unordered_list.pop()
upper, lower = list(), list()
for item in unordered_list:
if item > pivot:
upper.append(item)
else:
lower.append(item)
return quick_sort(lower) + [pivot] + quick_sort(upper)
# def main():
# L = [3,5,4,1,7,9,10]
# l = quick_sort(L)
# print(l)
# if __name__ == "__main__":
# main()
| true |
6e1c537e147eeccb2c51a55c25900c4f0c7fa19f | PriyanshuChatterjee/30-Days-of-Python | /day_6/06_tuples.py | 1,847 | 4.25 | 4 | emptyTuple = ()
brothers = ('Arijit','Debrath')
sisters = ('Apurba',)
siblings = brothers+sisters
noofSiblings = len(siblings)
parents = ('Ma','Papa')
family_members = siblings+parents
(firstSibling, secondSibling, thirdSibling, firstparent, secondParent) = family_members
fruits = ('apples','mangoes','bananas')
vegetables = ('potatoes','cauliflower')
animal_products = ('egg','milk')
food_stuff_tp = fruits+vegetables+animal_products
# Create fruits, vegetables and animal products tuples. Join the three tuples and assign it to a variable called food_stuff_tp.
# Unpack siblings and parents from family_members
# print(family_members)
# Modify the siblings tuple and add the name of your father and mother and assign it to family_members
# How many siblings do you have?
# Join brothers and sisters tuples and assign it to siblings
# Create a tuple containing names of your sisters and your brothers (imaginary siblings are fine)
# Create an empty tuple
# Change the about food_stuff_tp tuple to a food_stuff_lt list
food_stuff_lt = list(food_stuff_tp)
# print(food_stuff_lt)
# Slice out the middle item or items from the food_stuff_tp tuple or food_stuff_lt list.
midNumber = int((len(food_stuff_lt))/2)
# Slice out the first three items and the last three items from food_staff_lt list
sList = food_stuff_lt[:3]+food_stuff_lt[4:]
# Delete the food_staff_tp tuple completely
del(food_stuff_tp)
nordic_countries = ('Denmark', 'Finland','Iceland', 'Norway', 'Sweden')
# Check if 'Estonia' is a nordic country
N = 'Estonia'
res = False
for ele in nordic_countries :
if N == ele :
res = True
break
# Check if 'Iceland' is a nordic country
N = 'Iceland'
res = False
for ele in nordic_countries :
if N == ele :
res = True
break
print("Does tuple contain required value ? : " + str(res)) | true |
3034f8af8cb037de81db93f3c283ffbb8cb48116 | karthikkbaalaji/CorePython | /loops.py | 399 | 4.28125 | 4 | # Have the user enter a string, then loop through the
# string to generate a new string in which every character
# is duplicated, e.g., "hello" => "hheelllloo"
#import print function from python3
from __future__ import print_function
#get the input from the user
print("Enter a string:", end='')
inputString = raw_input()
#print as required
for letter in inputString:
print(letter*2, end='') | true |
f18d0ba8eeb0dad5a1b4bad385ade4d88fa8f5fa | karthikkbaalaji/CorePython | /lists.py | 2,279 | 4.5625 | 5 | #write a Python program to maintain two lists and loop
#until the user wants to quit
#your program should offer the user the following options:
# add an item to list 1 or 2
# remove an item from list 1 or 2 by value or index
# reverse list 1 or list 2
# display both lists
#EXTRA: add an option to check if lists are equal, even if
#contents are not in the same order (i.e, if list 1 is [3, 2,
#'apple', 4] and list 2 is [2, 3, 4, 'apple'], you
#should indicate they are the same)
from __future__ import print_function
lists = [[],[]]
while True:
print('''Choose your option:
a. Add item to a list
b. Remove an item from a list by index
c. Remove an item from a list by value
r. Reverse the list
f. Check if both lists are equal
d. Display both lists
e. Exit''')
option = raw_input()
#option to add item to the list
if option == 'a':
print("Enter which list to add item(1-2): ")
num = int(raw_input())
print("Enter the item: ")
item = raw_input()
lists[num-1].append(item)
print("Item added ")
#Removing item from list using item index
if option == 'b':
print("Enter which list to remove item(1-2): ")
num = int(raw_input())
print("Enter the item index: ")
item = int(raw_input())
lists[num-1].pop(item)
#Removing item from list using item value
if option == 'c':
print("Enter which list to remove item(1-2): ")
num = int(raw_input())
print("Enter the item value: ")
item = raw_input()
lists[num-1].remove(item)
#Reversing a list
if option == 'r':
print("Enter which list to reverse(1-2): ")
num = int(raw_input())
lists[num-1] = lists[num-1][::-1]
#lists[num-1].reverse()
#Comparing lists
if option == 'f':
for i in range(0,2):
print("List", i+1 , lists[i])
if(sorted(lists[0]) == sorted(lists[1])):
print("Lists are equal")
else:
print("Lists are not equal")
#Display lists
if option == 'd':
for i in range(0,2):
print("List", i+1 , lists[i])
#Exit
if option == 'e':
break
else:
print("Incorrect Option!") | true |
987d0755225cb89e923d22b48d212ca75cfcf9c0 | mcfaddeb4311/cti110 | /M5T1_KilometerConverter_BobbyMcFadden.py | 515 | 4.4375 | 4 | # Convert kilometer to miles.
# 6-28-2017
# CTI-110 M5T1_KilometerConverter
# Bobby McFadden
CONVERSION_FACTOR = 0.6214
def main ():
# Get the distance in kilometers.
kilometers = float (input('Enter a distance in kilometers: '))
#Display the distance converted to miles.
show_miles (kilometers)
def show_miles (km):
# Calculate miles.
miles = km * CONVERSION_FACTOR
#Display the miles.
print (km, 'kilometers equals', miles, 'miles.')
#Call the main function.
main()
| true |
cad19fd15b16c7a8494fd52bece96ff572d86487 | csbridge/csbridge2020 | /docs/starter/lectures/Lecture6/school_day.py | 544 | 4.28125 | 4 | """
This program tells whether go to school or not for a particular day.
"""
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
def main():
print("Should I go to school?")
day = int(input("Enter a day: "))
if MONDAY <= day <= FRIDAY: # day is between Monday and Friday
print("School day")
elif day == SATURDAY or day == SUNDAY: # day is either Saturday or Sunday
print("Weekend!")
else:
print(str(day) + " is not a day!")
if __name__ == '__main__':
main() | true |
3b0e7cd368a3f121c67b9a20c75f67e532de6ae3 | Cova14/PythonCourse | /dicts_exercise_1.py | 518 | 4.3125 | 4 | # We need to receive the basic info of a user
# (first_name, last_name, age, email)
# and save them as keys into a dict call user.
# After receive the data, show the info in the console
user = {}
user['first_name'] = input('Hey bro, cual es tu nombre?: ')
user['last_name'] = input('Como dices que se apellidan tus gfes?: ')
user['age'] = input('Ya alcanzas el timbre?: ')
user['email'] = input('Pásame tu correo para enviarte unas fotos UwU: ')
for key, value in user.items():
print(f'{key.upper()}: {value}') | true |
5a97ae18e7319001e3eb66d4a7e55bc0f642fc48 | xuefengCrown/Files_01_xuef | /all_xuef/程序员练级+Never/想研究的/python-further/metaclass1.py | 2,426 | 4.96875 | 5 |
#http://blog.jobbole.com/21351/
#http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python
"""
Secondly, metaclasses are complicated. You may not want to use them for very simple
class alterations. You can change classes by using two different techniques:
·monkey patching
·class decorators
99% of the time you need class alteration, you are better off using these.
But 98% of the time, you don't need class alteration at all.
"""
##basic
"""
In most languages, classes are just pieces of code that describe how to produce an object.
Classes are objects too.
Yes, objects.
As soon as you use the keyword class, Python executes it and creates an OBJECT.
The instruction
>>> class ObjectCreator(object):
... pass
...
creates in memory an object with the name "ObjectCreator".
This object (the class) is itself capable of creating objects (the instances),
and this is why it's a class.
But still, it's an object, and therefore:
·you can assign it to a variable
·you can copy it
·you can add attributes to it
·you can pass it as a function parameter
"""
class A():
def f(self):
pass
print(dir(A))
##Creating classes dynamically
"""
Since classes are objects, you can create them on the fly, like any object.
Since classes are objects, they must be generated by something.
When you use the class keyword, Python creates this object automatically.
But as with most things in Python, it gives you a way to do it manually.
"""
##What are metaclasses (finally)
"""
Metaclasses are the 'stuff' that creates classes.
MyClass = MetaClass()
my_object = MyClass()
type is the built-in metaclass Python uses, but of course, you can create your own metaclass.
"""
##The __metaclass__ attribute
"""
In Python 2, you can add a __metaclass__ attribute when you write a class
(see next section for the Python 3 syntax):
class Foo(object):
__metaclass__ = something...
[...]
If you do so, Python will use the metaclass to create the class Foo.
You write class Foo(object) first, but the class object Foo is not created in memory yet.
Python will look for __metaclass__ in the class definition. If it finds it, it will use
it to create the object class Foo. If it doesn't, it will use type to create the class.
"""
##Metaclasses in Python 3
"""
The syntax to set the metaclass has been changed in Python 3:
class Foo(object, metaclass=something):
"""
| true |
72ccad5f29e9918974a57e7ccc14b85935d52afb | xuefengCrown/Files_01_xuef | /all_xuef/程序员练级+Never/xuef code/xuef_code_python/composing_programs/4. Data Processing/4.2.6 Python Streams.py | 2,460 | 4.3125 | 4 | """
Streams offer another way to represent sequential data implicitly.
A stream is a lazily computed linked list.
Like an Link, the rest of a Stream is itself a Stream.
Unlike an Link, the rest of a stream is only computed when it is looked up,
rather than being stored in advance. That is, the rest of a stream is computed lazily.
"""
##To achieve this lazy evaluation, a stream stores a function that computes the rest of the stream.
##Whenever this function is called, its returned value is cached as part of the stream in an
##attribute called _rest, named with an underscore to indicate that it should not be accessed
##directly.
class Stream:
"""A lazily computed linked list."""
class empty:
def __repr__(self):
return 'Stream.empty'
empty = empty()
def __init__(self, first, compute_rest=lambda: empty):
assert callable(compute_rest), 'compute_rest must be callable.'
self.first = first
self._compute_rest = compute_rest
@property
def rest(self):
"""Return the rest of the stream, computing it if necessary."""
if self._compute_rest is not None:
self._rest = self._compute_rest()
self._compute_rest = None
return self._rest
def __repr__(self):
return 'Stream({0}, <...>)'.format(repr(self.first))
#r = Link(1, Link(2+3, Link(9)))
##Here, 1 is the first element of the stream, and the lambda expression that
##follows returns a function for computing the rest of the stream.
s = Stream(1, lambda: Stream(2+3, lambda: print(9)))
# the rest of s includes a function to compute the rest;
##increasing integers
##Lazy evaluation gives us the ability to represent infinite sequential datasets using streams.
##For example, we can represent increasing integers, starting at any first value.
##def integer_stream(first):
## def compute_rest():
## return integer_stream(first+1)
## return Stream(first, compute_rest)
def integer_stream(first):
# integer_stream is actually recursive because this stream's compute_rest
# calls integer_stream again
return Stream(first, lambda: integer_stream(first+1))
positives = integer_stream(1)
print(positives)
rg = integer_stream(5)
while 1:
print(rg.first)
rg = rg.rest
def map_stream(fn, s):
if s is Stream.empty:
return s
def compute_rest():
return map_stream(fn, s.rest)
return Stream(fn(s.first), compute_rest)
| true |
ea486935f6eb853ec567831155935518d9407807 | itrevex/ProgrammingLogicAndela | /coffee.py | 2,024 | 4.46875 | 4 | '''
Andela Making Coffee App
'''
#Make my coffee
INGREDIENTS = ['coffee', 'hot water']
print('Started making coffee...')
print('Getting cup')
print('Adding {}'.format(' and '.join(INGREDIENTS)))
print('Stir the mix')
print('Finished making coffeee...')
MY_COFFEE = 'Tasty Coffee'
print("--Here's your {}, Enjoy!!-- Mr. {} \n".format(MY_COFFEE, 'Evans'))
def prime_numbers(upper_limit_n):
"""
Function to return prime numbers from 0 to n
"""
#upper_limit should always be a non prime_number
if upper_limit_n % 2 == 0:
upper_limit_n += 1
for i in range(0, upper_limit_n, 2):
print(i)
##Trying a different approach of getting prime numbers
print(", ".join(""+str(i) for i in range(0, upper_limit_n, 2)))
'''
Big O notation analysis:
Number of lines executed == 2
memory points = n
second print, lines 1
memory points 1
'''
def fibonacci_squence(total_number_of_values, first_value=0, second_value=1):
"""
Generates fibonacci squence
total_number_of_values represents the total number of values in squence
first value is the start value of squence
second value is the value after the start value
"""
if total_number_of_values < 3:
raise fibonacci_squence_exception()
squence_values = [first_value, second_value]
for counter in range(total_number_of_values-2):
value_one = squence_values[counter]
value_two = squence_values[counter+1]
squence_values.append(sum_of_values(value_one, value_two))
print(", ".join(str(number) for number in squence_values))
def sum_of_values(value_one, value_two):
"""
returns sum of two values
"""
return value_one + value_two
def fibonacci_squence_exception():
"""
prints error message if total_number_of_values passed to
fibonacci squence function is less 3
"""
print("Unsupported length of squence, total_number_of_values \n should b >= 3")
prime_numbers(30)
fibonacci_squence(20, 15, 15)
| true |
d75b2ad3ccccbbc64101c9d69749f14ac09e7ef1 | N-eeraj/code_website | /Code/py/queue_ds.py | 929 | 4.21875 | 4 | def isEmpty():
return True if end == 0 else False
def isFull():
return True if end == size else False
queue = []
size = int(input("Enter Queue Size: "))
while True:
print("Queue:", queue)
end = len(queue)
option = input("\nSelect Queue Operation\n1. Is Empty?\n2. Is Full?\n3. Enqueue\n4. Dequeue\n5. Exit\nEnter Option Number: ")
print()
if option == '1':
print("Empty" if isEmpty() else "Not Empty")
elif option == '2':
print("Full" if isFull() else "Not Full")
elif option == '3':
if isFull():
print("Can't Enqueue: Queue Full")
else:
queue.append(int(input("Enter Element: ")))
elif option == '4':
if isEmpty():
print("Can't Dequeue: Queue Empty")
else:
del queue[0]
elif option == '5':
break
else:
print("Enter a number between 1 & 5")
print("Queue:", queue) | true |
ee36f2aa49982e1926fc9859ea52987fd598bc7a | jscelza/PythonKnightsSG | /week01/funWithSys.py | 868 | 4.1875 | 4 | """Playing with sys by using examples from Chapter 1.
http://www.diveintopython3.net/your-first-python-program.html
Available Functions
printSyspath()
Print value of sys.path
addDirToSyspath(string)
Adds string to sys.path
"""
import sys
def display_syspath():
"""Print sys.path value."""
print("sys.path has the following value:")
print(sys.path)
print()
def add_dir_to_Syspath(pythonKnightPath='./'):
"""Add a directory to sys.path."""
print("Adding", pythonKnightPath, " to path")
print()
sys.path.insert(0, pythonKnightPath)
if __name__ == '__main__':
print('Default Value')
display_syspath()
add_dir_to_Syspath("~/repos/PythonKnightsSG")
print('Value after inserting of directory')
display_syspath()
add_dir_to_Syspath()
print('Value after inserting of directory')
display_syspath()
| true |
13f76295927ed7cef99d759a3d4a39afaf7c47da | Pjmcnally/algo | /strings/reverse_string/reverse_string_patrick.py | 874 | 4.46875 | 4 | # Authored by Patrick McNally
# Created on 09/15/15
# Requests a string and prints it reversed
def reverse_string(chars):
"""Takes in a string and returns it reversed.
Parameters
----------
Input:
chars: string
Any string or list
Output:
chars: string
A reversed version of the input
"""
if chars:
return chars[::-1]
else:
return None
def main():
"""Prompt user for a string and prints it reversed
Parameters
----------
Input:
Output:
"""
string_ = input("What string would you like reversed? ")
rev_string = reverse_string(string_)
print(rev_string)
assert reverse_string(None) == None
assert reverse_string(['']) == ['']
assert reverse_string(['f', 'o', 'o', ' ', 'b', 'a', 'r']) == ['r', 'a', 'b', ' ', 'o', 'o', 'f']
if __name__ == '__main__':
main() | true |
1dd422098c2b504fef437676c9895036a45ada70 | Pjmcnally/algo | /sort_visualized/bubble_sort.py | 2,950 | 4.28125 | 4 | """Visualization of the bubble sort algorithm.
For reference:
https://matplotlib.org/2.1.2/gallery/animation/basic_example_writer_sgskip.html
https://github.com/snorthway/algo-viz/blob/master/bubble_sort.py
"""
from random import shuffle
import matplotlib.pyplot as plt
import matplotlib.animation as ani
# Create a list of random integers between 0 and 100
sorted_data = list(range(1, 16))
data = sorted_data.copy()
shuffle(data)
# Create the figure
fig, ax = plt.subplots()
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
def bubble_sort_gen():
"""Yield current state of bubble sort."""
sorted_index = len(data)
swapped = True
while swapped:
swapped = False
for i in range(sorted_index - 1):
yield (data, i, i + 1, sorted_index)
if data[i] > data[i + 1]:
swapped = True
data[i], data[i + 1] = data[i + 1], data[i]
yield (data, i + 1, i, sorted_index)
sorted_index -= 1
for i in range(10): # Add frames of fully sorted to end
yield (data, 0, 0, 0)
def cocktail_shaker_gen():
"""Yield current state of bubble sort."""
sorted_index_high = len(data)
sorted_index_low = -1
swapped = True
while swapped:
swapped = False
for i in range(sorted_index_low + 1, sorted_index_high - 1):
yield (data, i, i + 1, sorted_index_low, sorted_index_high)
if data[i] > data[i + 1]:
swapped = True
data[i], data[i + 1] = data[i + 1], data[i]
yield (data, i + 1, i, sorted_index_low, sorted_index_high)
sorted_index_high -= 1
if not swapped:
break
swapped = False
for i in range(sorted_index_high - 1, sorted_index_low + 1, -1):
yield (data, i, i - 1, sorted_index_low, sorted_index_high)
if data[i] < data[i - 1]:
swapped = True
data[i], data[i - 1] = data[i - 1], data[i]
yield (data, i - 1, i, sorted_index_low, sorted_index_high)
sorted_index_low += 1
for i in range(10): # Add frames of fully sorted to end
yield (data, 0, 0, 0, 0)
def update(frame):
"""Frame is the (data, i, iter_count) tuple."""
datums, orange, red, sorted_index_low, sorted_index_high = frame
ax.clear()
bars = ax.bar(range(len(data)), datums)
for k in range(len(data)):
if k <= sorted_index_low or k >= sorted_index_high:
bars[k].set_color("green")
elif k == orange or k == red:
bars[k].set_color("orange")
else:
bars[k].set_color("blue")
ax.set_title('Bubble Sort')
animation = ani.FuncAnimation(
fig,
update,
frames=cocktail_shaker_gen,
interval=200,
blit=False,
repeat=False,
save_count=10000,
)
# animation.save(r"C:\Users\Patrick\Desktop\Demo.mp4")
plt.show()
| true |
7b83ce10efb3bf9da2f9650cc1718327bf462193 | Pjmcnally/algo | /math/primes/primes_old.py | 2,206 | 4.34375 | 4 | # Authored by Patrick McNally
# Created on 09/15/15
# Requests a number from the user and generates a list of all primes
# upto and including that number.
import datetime
def list_primes(n):
"""Return a list of all primes up to "n"(inclusive).
Parameters
----------
Input:
n: int or float
A number
Output:
prime_list: list
A list including all numbers up to "n"(inclusive)
"""
prime_list = []
for num in range(2, int(n) + 1):
for div in range(2, int(num**.5 + 1)):
if num % div == 0:
break
else:
prime_list.append(num)
return prime_list
def list_primes_better(n):
"""Return a list of all primes up to "n"(inclusive).
Parameters
----------
Input:
n: int or float
A number
Output:
prime_list: list
A list including all numbers up to "n"(inclusive)
"""
prime_list = [2]
for num in range(2, int(n) + 1):
for x in prime_list:
if num % x == 0:
break
elif x > num**.5:
prime_list.append(num)
break
return prime_list
def main():
"""Requests a number from the user and returns a list of all primes
up to and including that number.
Parameters
----------
Input:
Output:
"""
total_num = 5000000
start = datetime.datetime.now()
final = list_primes(total_num)
end = datetime.datetime.now()
first_try = end - start
print("\nPrime finder process took {} seconds.\n".format(datetime.timedelta.total_seconds(first_try)))
start = datetime.datetime.now()
final2 = list_primes_better(total_num)
end = datetime.datetime.now()
sec_try = end - start
print("\nBetter Prime finder process took {} seconds.\n".format(datetime.timedelta.total_seconds(sec_try)))
if final == final2:
print("both lists match")
else:
print("The lists are not the same")
# assert list_primes(1) == []
# assert list_primes(2) == [2]
# assert list_primes(12) == [2, 3, 5, 7, 11]
# assert list_primes(12.9) == [2, 3, 5, 7, 11]
if __name__ == '__main__':
main() | true |
e887c0efe28523e4de25a523684cea8e1e1b2d92 | Neha-kumari31/Sprint-Challenge--Data-Structures-Python | /names/bst.py | 1,456 | 4.125 | 4 | '''
Binary search trees are a data structure that enforce an ordering over
the data they store. That ordering in turn makes it a lot more efficient
at searching for a particular piece of data in the tree. '''
class BSTNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Insert the given value into the tree
def insert(self, value):
#compare the current value of the node(self.value)
if value < self.value:
#insert the value in left
if self.left is None:
# insert node value if no node in the left side
self.left = BSTNode(value)
else:
# repeat the process for the next node
self.left.insert(value)
if value >= self.value:
if self.right is None:
self.right =BSTNode(value)
else:
self.right.insert(value)
# Return True if the tree contains the value
# False if it does not
def contains(self, target):
if target ==self.value:
return True
if target < self.value:
if self.left is None:
return False
else:
return self.left.contains(target)
if target >=self.value:
if self.right is None:
return False
else:
return self.right.contains(target) | true |
3483d89da70d27855bc0854d531361b2f17b10fa | TanbirulM/Rock-Paper-Scissors | /rps.py | 1,551 | 4.125 | 4 | import random
def play_game():
print('Welcome to Rock Paper Scissors!')
player_score = 0
bot_score = 0
while True:
print('Make your choice:')
choice = str(input()).lower()
print("My choice is", choice)
choices = ['rock', 'paper', 'scissor', 'end']
bot_choices = ['rock', 'paper', 'scissor']
bot_choice = random.choice(bot_choices)
print("Computer choice is", bot_choice)
if choice in choices:
if choice == bot_choice:
print('it is a tie')
elif choice == 'rock':
if bot_choice == 'paper':
print('sorry, you lose')
bot_score += 1
elif bot_choice == 'scissor':
print('You win!')
player_score += 1
elif choice == 'paper':
if bot_choice == 'scissor':
print('sorry, you lose')
bot_score += 1
elif bot_choice == 'rock':
print('You win!')
player_score += 1
elif choice == 'scissor':
if bot_choice == 'rock':
print('sorry, you lose')
bot_score += 1
elif bot_choice == 'paper':
print('You win!')
player_score += 1
elif choice == 'end':
if player_score > bot_score:
print('game has ended, player has won :D')
elif player_score < bot_score:
print('game has ended, computer has won :(')
else:
print('game has ended in a draw')
break
print('Player Score: ', player_score, ', Bot Score: ', bot_score)
else:
print('invalid choice, try again')
print('--------------------------------')
def main():
play_game()
# Standard call for main() function
if __name__ == '__main__':
main()
| true |
1cbbe648adf947a8c230a15578b1117c3a523064 | jitensinha98/Python-Practice-Programs | /ex32_2.py | 433 | 4.15625 | 4 | y=int(raw_input("Enter the starting element:"))
z=int(raw_input("Enter the ending element:"))
element=[]
for i in range(y,z+1):
element.append(i)
print "All elements are stored in the list."
print "Do you want to veiw the list :"
raw_input()
print "All elements in the list are :"
for numbers in element:
print "Numbers=%d"%numbers
p=int(raw_input("Enter the interval:"))
for i in element:
print "Numbers=%d"%i
| true |
f911f45e6505a6a3916aa7a900bcaa2379a00075 | garycunningham89/pands-problem-set | /solution1sumupto.py | 657 | 4.4375 | 4 | #Gary Cunningham. 03/03/19
#My program intends to show the sum of all the numbers for, and including, the inputted integer from number 1.
#Adaptation from python tutorials @www.docs.python.org and class tutorials.
n = input("Please enter a positive integer: ")
# Inputting the first line of the program as per the requested format.
n = int(n)
# Use of int() to ensure use of postive integers.
sum = 0
# Defining base number for program.
for num in range(1, n+1, 1):
sum = sum+num
# Creeating the range with increases to n added together within the range.
print("Sum of all numbers between 1 and", n, "is:", sum)
# Ensuring the output is explained in the program. | true |
251f9d376aefb865fffdbba56b6d4c9bbe0b305c | shawnTever/documentAnalysis | /week1/PythonBasicsTutorial.py | 2,480 | 4.28125 | 4 | my_list2 = [i * i for i in range(10)] # Creates a list of the first 10 square integers.
my_set2 = {i for i in range(10)}
my_dict2 = {i: i * 3 + 1 for i in range(10)}
print(my_list2)
print(my_set2)
print(my_dict2)
# Comprehensions can also range over the elements in a data structure.
my_list3 = [my_list2[i] * i for i in my_set2]
print(my_list3)
dictionary = {}
for a in my_list2:
if a in my_set2:
dictionary[a] = True
else:
dictionary[a] = False
print(dictionary)
import numpy as np # This statement imports the package numpy and gives it the name np
my_array1 = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) # This is a 2x3 matrix.
my_array2 = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]) # This is a 3x2 matrix.
# elements addition
np.sum(my_array1)
# Matrix multiplication
np.matmul(my_array1, my_array2)
# Matrix transpose
print(np.transpose(my_array2))
# Operations such as '+' and '*' can be directly applied to matrices
my_array1 + np.transpose(my_array2)
# The element in the first row and second column.
print(my_array1[0, 1])
# second row.
print(my_array1[1, :])
# Everything from the second row onwards.
print(my_array1[1:])
# second column.
print(my_array1[:, 1])
# Everything from the second column onwards.
print(my_array1[:, 1:])
# Everything upto (but not including) the last row
print(my_array1[:-1])
# Everything upto (but not including) the last column
print(my_array1[:, :-1])
# computing the sum of all of the elements in my_array1 except for the last column.
print(np.sum(my_array1[:, :-1]))
print('--------------------------------------------------')
import pandas as pd
my_df = pd.DataFrame({'c1': [1.0, 2.0, 3.0],
'c2': ['a', 'b', 'c'],
'c3': [True, False, True]})
print(my_df)
print(my_df.shape)
# From the second row on, up to the second column
print(my_df.iloc[1:, :2])
# index a DataFrame by using column names
print(my_df['c2'])
# In Python reading and writing to files can be done using the 'open' keyword, which creates a file handle for the
# given path. It is good practice to always use 'open' inside a 'with' clause. This will ensure that the file handle
# is closed properly once the with clause finishes.
with open('my_file.txt', 'w') as f: # Note that the 'w' means we want to write strings to this path.
# *IMPORTANT* If the file already exists, it will be overwritten.
f.write('Hello\nWorld!')
# After the with clause, the file will be closed.
| true |
8982047e06eceb6dd3a530bc09584d55cf734e25 | aa-fahim/practice-python | /OddOrEven.py | 846 | 4.21875 | 4 | ## The programs asks the user to input an integer. The program will then
## determine if the number is odd or even and also if it is a multiple of 4.
## The second part of program will ask for two numbers and then check
## if they are divisble or not.
number = int(input('Please enter a number:\n'))
a = number % 2
b = number % 4
if (a == 0):
print('The number {} is even'.format(number))
elif (a == 1):
print('The number {} is odd'.format(number))
if (b == 0):
print('The number {} is a multiple of 4'.format(number))
num = int(input('Enter another number:\n'))
check = int(input('Enter a number to divide by:\n'))
c = num % check
if (c == 0):
print('The number {} is divisible by {}'.format(num, check))
elif (c != 0):
print('The number {} is not divisble by {}'.format(num, check))
| true |
b8abc55567a07dcd99e00d752a3790ab409f6858 | aa-fahim/practice-python | /ListEnds.py | 213 | 4.1875 | 4 | ## List Ends
# Takes first and last element of input list a and places into new list and
# prints it.
def list_ends(a):
a = [5, 10, 15 ,20 ,25]
new_list = [a[0], a[len(a)-1]]
print(new_list) | true |
c3ecd3b01a046af4f3e6c203878b0864d85a0317 | bio-chris/Python | /Courses/PythonBootcamp/Project_3_Pi.py | 517 | 4.21875 | 4 | # Project 3: Find PI to the Nth Digit
# Enter a number and have the program generate PI up to that many decimal places. Keep a limit to how far the program
# will go.
"""
Using the Bailey-Borwein-Plouffe formula
"""
from decimal import *
def pi(i):
pi_value = 0
getcontext().prec = i
for n in range(i+1):
pi_value += Decimal((1/16**n)*((4/(8*n+1))-(2/(8*n+4))-(1/(8*n+5))-(1/(8*n+6))))
return pi_value
#print(pi(1000))
"""
Need to determine accuracy of above function !!!
"""
| true |
4e98356bdc6f0df8b2715536dacf8f55a792f5a9 | Nayan-Chimariya/Guess-the-number | /app.py | 2,562 | 4.15625 | 4 | #game game
from random import randint
import time
import os
guess_count = 5
hint_count = 3
def end_screen():
print("\nSee ya later loser! \n")
time.sleep(1)
exit()
def counters(guess_count, hint_count):
print(f"\nNumber of guess left = {guess_count}")
print(f"Number of hints left = {hint_count}")
def hint(correct,user_guess):
global hint_count
if hint_count != 0:
if_hint = input("\nDo you want to use hint ? (Y/N): ").lower()
if if_hint == 'y':
hint_count -= 1
if user_guess < correct:
print(f"\nHINT: your guess {user_guess} is lower than the answer")
if user_guess > correct:
print(f"\nHINT: your guess {user_guess} is higher than the answer")
else:
is_hint_left = False
def main():
game_running = True
is_hint_left = True
is_guess_left = True
global guess_count
global hint_count
print("\n---------------------------")
print("welcome to Guess the number")
print("---------------------------")
counters(guess_count, hint_count)
is_enter = input("\nPress [Enter] to play: ")
if is_enter == "":
random_number = randint(0,100)
while game_running == True:
correct = random_number
try:
user_guess = int(input("\nEnter your guess: "))
if user_guess == correct:
print("🏆 Correct!")
game_running = False
print("\n----------------------------------")
play_again = input("Do you want to play again ? (Y/N): ").lower()
if play_again == 'y':
os.system('cls')
guess_count = 5
hint_count = 3
main()
else:
end_screen()
else:
print("-------------------\n")
print("❌ Incorrect")
print(f"Your guess = {user_guess}")
guess_count -= 1
if guess_count == 0:
is_guess_left = False
game_running = False
print(f"The correct answer was {correct}")
print("\n----------------------------------")
play_again = input("Do you want to play again ? (Y/N): ").lower()
if play_again == 'y':
os.system('cls')
guess_count = 5
hint_count = 3
main()
else:
end_screen()
if is_guess_left == True:
counters(guess_count, hint_count)
if is_hint_left == True:
hint(correct,user_guess)
except ValueError:
pass
else:
end_screen()
main() | true |
4cd731424693d2ae3287132de455cd2a75c1e59f | taismassaro/stunning-engine | /anagram-finder/anagram_finder.py | 559 | 4.125 | 4 | with open('anagram_finder/2of4brif.txt') as in_file:
words = in_file.read().strip().split('\n')
words = [word.lower() for word in words]
lookup_word = 'charming'
anagrams = [lookup_word]
for word in words:
if word != lookup_word:
# to find out if a word is an anagram of another, we can convert them into a list and sort the items in the list
if sorted(word) == sorted(lookup_word):
anagrams.append(word)
if len(anagrams) <= 1:
print(f"'{lookup_word}' has no anagrams")
else:
print(f"Anagrams: {anagrams}")
| true |
9605f705daf53c27cd8292df1a5b0c6cba86604f | TimurTimergalin/natural_selection | /simulation/app.py | 2,141 | 4.15625 | 4 | import pygame
class App:
"""
Methods:
set_variables
create_sprite_groups
main_loop
run
set_variables:
Args: None
Returns: None
Set constant variables to use it in the simulation
create_sprite_groups:
Args: None
Returns: None
Create pygame.sprite.Group instances to use it in the simulation
main_loop:
Args:
screen
Returns: None
The main loop of the simulation, that displays onto the screen
run:
Args:
x
y
Returns: None
Create screen X*Y and safely run the main loop
"""
def __init__(self):
self.set_variables()
self.create_sprite_groups()
def set_variables(self):
"""
set_variables:
Args: None
Returns: None
Set constant variables to use it in the simulation
"""
self.fps = 60
def create_sprite_groups(self):
"""
create_sprite_groups:
Args: None
Returns: None
Create pygame.sprite.Group instances to use it in the simulation
"""
self.all_sprites = pygame.sprite.Group()
self.creatures = pygame.sprite.Group()
def main_loop(self, screen):
"""
main_loop:
Args:
screen
Returns: None
The main loop of the simulation, that displays onto the screen
"""
run = True
clock = pygame.time.Clock()
while run: # Game loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
screen.fill((0, 0, 0))
pygame.display.flip()
clock.tick(self.fps)
def run(self, x, y):
"""
run:
Args:
x
y
Returns: None
Create screen X*Y and safely run the main loop
"""
pygame.init()
screen: pygame.Surface = pygame.display.set_mode((x, y))
try:
self.main_loop(screen)
finally:
pygame.quit()
| true |
927b69be4111dd0b12631e59cd8d42c3bb0e9074 | gygergely/Python | /Misc/FizzBuzz/fizzbuzz.py | 1,237 | 4.1875 | 4 | def welcome():
"""
Simple welcome message to the user.
:return: None
"""
print('Welcome to the \'fizzbuzz\' game')
def user_number_input():
"""
Request a number from the user.
:return: int
"""
while True:
try:
nr = int(input('Please enter a number between 1 and 100: '))
if nr < 1 or nr > 100:
print('Range must be between 1 and 100')
continue
else:
return nr
except (TypeError, ValueError):
print('Ups something went wrong')
continue
def get_fizzbuzz(number):
"""
In case the number is divisible with 3, it prints "fizz" instead of the number. If the number is divisible with 5,
it prints "buzz". If it's divisible with both 3 and 5, it prints "fizzbuzz".
:param number: end of number loop
:return: None
"""
for nr in range(1, number + 1):
if nr % 5 == 0 and nr % 3 == 0:
print('fizzbuzz')
elif nr % 5 == 0:
print('buzz')
elif nr % 3 == 0:
print('fizz')
else:
print(nr)
# PROGRAM STARTS HERE
# -------------------
welcome()
get_fizzbuzz(user_number_input())
| true |
4163960e911dc1a91fed505e1a348d5ffb6e9d25 | AndreaCossio/PoliTo-Projects | /AmI-Labs/lab_1/e02.py | 277 | 4.375 | 4 | # Lab 01 - Exercise 02
# Retrieving the string
string = input("Insert a string: ")
# Checking length and printing
if len(string) > 2:
print("'" + string + "' yields '" + string[0] + string[1] + string[len(string) - 2] + string[len(string) - 1] + "'")
else:
print("")
| true |
e73464eaff804a0128456f9c37ad348b08856049 | AndreaCossio/PoliTo-Projects | /AmI-Labs/lab_2/e01.py | 1,214 | 4.25 | 4 | # Lab 02 - Exercise 01
# List of tasks
tasks = []
num = -1
# Main loop
while num != 4:
# Printing menu
print("""Insert the number corresponding to the action you want to perform:
1. Insert a new task
2. Remove a task (by typing its content exactly)
3. Show all existing tasks, sorted in alphabetic order
4. Close the program""")
# Catching exceptions and performing different actions
try:
num = int(input("> "))
if num == 1:
new_task = input("\nPlease insert the task to insert: ")
tasks.append(new_task)
elif num == 2:
del_task = input("\nPlease insert the task to remove: ")
try:
tasks.remove(del_task)
except ValueError:
print("It seems that the task you inserted does not already exist.")
elif num == 3:
print("\nInserted tasks:")
for task in sorted(tasks):
print(task)
elif num == 4:
print("\nExiting...")
else:
print("That didn't seem a valid number!")
print()
except ValueError:
print("That didn't seem a number!")
| true |
06cee3b6c3d1dc86c477216ae1ac9369b75dbdf0 | chasegarsee/Algorithms | /recipe_batches/recipe_batches.py | 1,679 | 4.1875 | 4 | #!/usr/bin/python
import math
def recipe_batches(recipe, ingredients):
# getting the Keys from the KEY::VALUE pairs
current_recipe = set(recipe.keys())
print(current_recipe) # printing the keys
if current_recipe.intersection(ingredients.keys()) != current_recipe:
# if they keys in current recipe and the keys in ingredients dont match...
# .intersection() finds matching values within two lists of things. nifty find
return 0
ingredients_needed = {key: ingredients[key]
for key in ingredients if key in recipe}
# ingredients_needed sets up a new set of ingredients if both
# keys are found in ingredients and recipe
batches = 999999999 # as many batches as we might need
for value in ingredients_needed:
# for every value in ingredients_needed
if ingredients[value] // recipe[value] < batches:
# if when we perform floor division (lowest whole number)
# to the values of ingredients and recipes and the result is
# less than the values in batches
batches = ingredients[value] // recipe[value]
# create a new number of batches that equals the total number of batches possible.
return batches
if __name__ == '__main__':
# Change the entries of these dictionaries to test
# your implementation with different inputs
recipe = {'milk': 1, 'butter': 5, 'flour': 5}
ingredients = {'milk': 132, 'butter': 48, 'flour': 51}
print("{batches} batches can be made from the available ingredients: {ingredients}.".format(
batches=recipe_batches(recipe, ingredients), ingredients=ingredients))
| true |
23f2a8f4b69924299a87f3821777b1ba6ddcf691 | dev-bloke/examples | /python/simple/collections.py | 1,829 | 4.3125 | 4 | # Simple list and indexing
first_list = [1, 2, 3]
print(first_list[0])
# Working from the end of the list and appending.
second_list = [1, "b", 3, "Hello"]
print(second_list[3])
print(second_list[-2])
second_list[1] = "B"
second_list.append("world")
second_list.append(first_list)
print(second_list)
# Extending, inserting, deleting and removing
third_list = ["a", "b", "c"]
third_list.extend(first_list)
print(third_list)
third_list.insert(3, 4)
print(third_list)
third_list.insert(-1, 5)
print(third_list)
del third_list[3]
print(third_list)
third_list.remove("c")
print(third_list)
# Sorting, copying and reversing
fourth_list = ["Z", "A", "Q"]
fifth_list = fourth_list[:]
fifth_list.sort()
print(fourth_list)
print(fifth_list)
def compare_length(string1):
return len(string1)
sixth_list = ["Parsons", "Alan", "The", "Project"]
sixth_list.sort(key=compare_length)
print(sixth_list)
seventh_list = sixth_list[:]
seventh_list.reverse()
print(seventh_list)
# Membership
if "Alan" in sixth_list:
print("Alan is in the list.")
print(sixth_list.index("Alan"))
if "Bob" not in sixth_list:
print("Bob is not in the list.")
# Dictionaries (maps)
map = {"key1": "value1", "key2": "value2"}
value1 = map.get("key1")
print(value1)
map["key3"] = "value3"
del map["key2"]
eighth_list = map.keys()
print(eighth_list)
print("key3" in map)
print("key2" in map)
value2 = map.get("value2", "missing")
print(value2)
# Sets
ninth_list = [1, 2, 3, 1, 2, 4]
first_set = set(ninth_list)
print(first_set)
print(3 in first_set)
# Tuples
tenth_list = [1, 3, 5]
eleventh_list = ["one", "three", "five"]
tuple = zip(tenth_list, eleventh_list)
print(tuple)
# Comprehension
twelfth_list = [item * item for item in tenth_list]
print(twelfth_list)
second_map = {item: item * item for item in tenth_list}
print(second_map)
| true |
06dbec69c44712a70985ed9ce526d2c86082c871 | lovababu/python_basics | /datastructures/dictionary.py | 1,105 | 4.5 | 4 | about = {"Name": "Avol", "Age": 32, "Address": "Bangalore"} # called dictionary key value pairs.
print(type(about))
# access keys.
# returns all keys as dict_keys (Note: dict_keys is not a list, index access may result type error).
keys = about.keys()
print(type(keys))
print(keys) # keys[0] result type error dict_keys does not support indexing.
# access values.
# returns all values as dict_values (Note: dict_values is not a list, index access may result type error.)
values = about.values()
print(values) # values[0] result type error dict_values does not support indexing.
# access through keys.
print("Name is : ", about.get("Name")) # if no key matches, it returns None object which is null in python.
# iterate over dict.
for key in about.keys():
print(about.get(key))
# change value in dict.
about["Name"] = "Srilekha"
print(about)
# delete by key.
del about["Address"]
print(about)
items = about.items() # returns list of tuples type of dict_items.
print(items) # converting mutable dict into immutable tuple.
a = dict(one=1, two=2, three=3) # dict is a class.
print(a)
| true |
ff2ba366ce3df5ad0049f46db9e44a5e50942675 | ratanvishal/hello-python | /main12.py | 384 | 4.1875 | 4 | #a=8
#b=5
#c=sum((a,b))
#print(c)
#def function(a,b):
#print("hello function r u there",a+b)
def function(a,b):
"""This is the function which calculates the average of two numbers. and this function does't work for three numbers"""
average= (a+b)/2
# print(average)
return (average)
#v=function(5,9)
#print(v)
print(function.__doc__)
| true |
73a6a5a6f21b8e7f0a8a234836b9864c021c12b6 | green-fox-academy/Unicorn-raya | /week-01/day-2/count_from_to.py | 586 | 4.375 | 4 | # Create a program that asks for two numbers
# If the second number is not bigger than the first one it should print:
# "The second number should be bigger"
#
# If it is bigger it should count from the first number to the second by one
#
# example:
#
# first number: 3, second number: 6, should print:
#
# 3
# 4
# 5
first_number = int(input("This is first number: "))
second_number = int(input("This is second number: "))
if second_number < first_number:
print("The second number should be bigger")
else:
for i in range(first_number,second_number):
print(str(i)+'\n') | true |
1b0fcc447b81b5ee00c14a93b8d87802997c3593 | green-fox-academy/Unicorn-raya | /week-01/day-3/Functions/Sort_that_list.py | 992 | 4.21875 | 4 | # Create a function that takes a list of numbers as parameter
# Returns a list where the elements are sorted in ascending numerical order
# Make a second boolean parameter, if it's `True` sort that list descending
def bubble(arr):
arr_length = len(arr)
if arr_length == 0:
return -1
for i in range(arr_length):
for j in range(i,arr_length):
if arr[i] > arr[j]:
arr[i],arr[j] = (arr[j],arr[i])
return arr
def advanced_bubble(arr, is_descending):
arr_length = len(arr)
if arr_length == 0:
return -1
if is_descending == False:
bubble(arr)
else:
for i in range(arr_length):
for j in range(i,arr_length):
if arr[i] < arr[j]:
arr[i],arr[j] = (arr[j],arr[i])
return arr
# Example:
print(bubble([43, 12, 24, 9, 5]))
# should print [5, 9, 12, 24, 34]
print(advanced_bubble([43, 12, 24, 9, 5], True))
# should print [34, 24, 9, 5]
| true |
aeeb60f44fafdf45d1c48180c6f1957adb84f2c8 | green-fox-academy/Unicorn-raya | /week-01/day-2/draw_pyramid.py | 460 | 4.25 | 4 | # Write a program that reads a number from the standard input, then draws a
# pyramid like this:
#
#
# *
# ***
# *****
# *******
#
# The pyramid should have as many lines as the number was
length = int(input())
level = 0
tmp = ""
while level < length + 1:
for i in range(length-level):
tmp += " "
for i in range(2 * level - 1):
tmp += "*"
for i in range(level-1):
tmp += " "
level += 1
print(tmp)
tmp = "" | true |
9e464ff53c74b314555a19755b90c971a2d4efbf | green-fox-academy/Unicorn-raya | /week-01/day-3/Functions/Factorial.py | 224 | 4.34375 | 4 | # - Create a function called `factorio`
# that returns it's input's factorial
def factorio( number ):
if number == 1:
return number
else:
return number * factorio (number - 1)
print(factorio(5))
| true |
9d9afc31d603928f64561a29faafe584b8296be4 | aduxhi/learnpython | /mid_test/lac_string_2.py | 863 | 4.21875 | 4 | #!/usr/bin/python
'''
Write a recursive procedure, called laceStringsRecur(s1, s2), which also laces together two strings. Your procedure should not use any explicit loop mechanism, such as a for or while loop. We have provided a template of the code; your job is to insert a single line of code in each of the indicated places.
For this problem, you must add exactly one line of code in each of the three places where we specify to write a line of code. If you add more lines, your code will not count as correct
'''
def laceStringsRecur(s1, s2):
def helpLaceStrings(s1, s2, out):
print(out)
if s1 == '':
return (out+s2)
if s2 == '':
return out+s1
else:
return helpLaceStrings(s1[1:], s2[1:], out+s1[0]+s2[0])
return helpLaceStrings(s1, s2, '')
s1 = 'abcd'
s2 = 'efghi'
x = laceStringsRecur(s1, s2)
print (x)
| true |
ef6c2b63ae1b3ef0175632bf06fc8123eed45d37 | aduxhi/learnpython | /return_print.py | 715 | 4.15625 | 4 | # -*- coding: UTF-8 -*-
'''
the print() function writes, i.e., "prints",a string in the console. The return statement causes your function to exit and hand back a value to its caller.(使函数终止并且返回一个值给它的调用者) The point of functions in general is to take in inputs and return something. The return statement is used when a function is ready to return to its caller.
Fox example, here's a function utilizing both print() and return.
'''
def foo():
print("hello form inside of foo")
return 1
print("going to call foo: ")
x = foo() # 调用foo(),将返回值赋予 x
print("called foo")
print("foo returned " + str(x))
print(foo()) # 调用 foo()
print(foo) #
print(type(foo)) | true |
492afa72418991d88094b69f59f6f548abf5fe0a | aduxhi/learnpython | /ProblemSet3/getGuessedWord.py | 656 | 4.1875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# 返回已经猜到的单词
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
# FILL IN YOUR CODE HERE...
gussed = []
for i in secretWord:
if i in lettersGuessed:
gussed.append(i)
else:
gussed.append('_ ')
return ''.join(gussed)
secretWord = 'apple'
lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
print getGuessedWord(secretWord, lettersGuessed)
| true |
d591b7440e04f08c2c65f2aa93e386db4ef5595b | danieltran-97/Python-practice | /polygon.py | 655 | 4.21875 | 4 | import turtle
class Polygon:
def __init__(self, sides,name, size=100):
self.sides = sides
self.name = name
self.size = size
self.interior_angles = (self.sides -2) * 180
self.angle = self.interior_angles/self.sides
def draw(self):
for i in range(self.sides):
turtle.forward(100)
turtle.right(180-self.angle)
square = Polygon(4, "Square")
pentagon = Polygon(5, "Pentagon")
print(square.sides)
print(square.name)
# print(square.interior_angles)
# print(square.angle)
print(pentagon.sides)
print(pentagon.name)
# pentagon.draw()
hexagon = Polygon(6, "Hexagon")
hexagon.draw() | true |
3b6dbcc99b5fddb652c3bf6fc0ff43c3162879b2 | Karanvir93875/PythonStuff | /RealTimeClock.py | 907 | 4.15625 | 4 | #This is a program which provides a close to accurate representation of real time
import os #clear screen functioning
import time
#variables display time length
seconds = float(0) #want to display decimals of each second
minutes = int(0) #want min to be dislayed as whole numbers
hours = int(0) #want hours to be displayed as whole numbers
run = input("Press x to run the program. ")
while run.lower() == "x":
if seconds > 59:
seconds = 0
minutes = minutes+1 #when counter hits 60 seconds, counter resets to 0 and adds a minutes
if minutes > 59:
minutes = 0
hours = hours+1 #when counter hits 60 minutes, counter resets to 0 and adds 1 hour
os.system('cls') #clears the command prompt, will just show current time
seconds = (seconds + .1)
print(hours, ":" , minutes, ":", seconds)
time.sleep(.1)
#will suspend execution for approximately .1 seconds
| true |
2dfe462d34c82b016bb249e719f86b1ca81d9603 | ferryleaf/GitPythonPrgms | /numbers/plus_minus.py | 2,118 | 4.15625 | 4 | #!/bin/python3
'''
Given an array of integers,
calculate the fractions of its elements that are positive, negative, and are zeros.
Print the decimal value of each fraction on a new line.
Note: This challenge introduces precision problems.
The test cases are scaled to six decimal places,
though answers with absolute error of up to 10^-4 are acceptable
For example,
given the array there are elements,
two positive, two negative and one zero.
Their ratios should be printed as
0.400000
0.400000
0.200000
Function Description
Complete the plusMinus function in the editor below.
It should print out the ratio of positive, negative and zero items in the array,
each on a separate line rounded to six decimals.
plusMinus has the following parameter(s):
arr: an array of integers
Input Format
The first line contains an integer, , denoting the size of the array.
The second line contains space-separated integers describing an array of numbers .
Constraints
0< n <=100
-100 <= arr[i] <=100
Output Format
You must print the following lines:
A decimal representing of the fraction of positive numbers in the array compared to its size.
A decimal representing of the fraction of negative numbers in the array compared to its size.
A decimal representing of the fraction of zeros in the array compared to its size
Sample Input
6
-4 3 -9 0 4 1
Sample Output
0.500000
0.333333
0.166667
Explanation
There are 3 positive numbers, 2 negative numbers, and zero in the array.
'''
import math
import os
import random
import re
import sys
# Complete the plusMinus function below.
def plusMinus(arr):
leng = len(arr)
pos=0
neg=0
zero=0
for ele in arr:
if(int(ele)>= -100 and int(ele)<=100):
if(int(ele)>0):
pos=pos+1
elif (int(ele)<0):
neg=neg+1
else:
zero+=1
print('%.6f'%(pos/leng))
print('%.6f'%(neg/leng))
print('%.6f'%(zero/leng))
if __name__ == '__main__':
n = int(input())
if (n>0 and n<=100):
arr = list(map(int, input().rstrip().split()))
plusMinus(arr)
| true |
11cc4e82a74f71bf0c395392b69bb827e5719544 | ferryleaf/GitPythonPrgms | /arrays/rotate_array.py | 1,792 | 4.15625 | 4 | '''
Given an unsorted array arr[] of size N, rotate it by D elements
in the COUNTER CLOCKWISE DIRECTION.
Example 1:
Input:
N = 5, D = 2
arr[] = {1,2,3,4,5}
Output: 3 4 5 1 2
Explanation: 1 2 3 4 5 when rotated
by 2 elements, it becomes 3 4 5 1 2.
Example 2:
Input:
N = 10, D = 3
arr[] = {2,4,6,8,10,12,14,16,18,20}
Output: 8 10 12 14 16 18 20 2 4 6
Explanation: 2 4 6 8 10 12 14 16 18 20
when rotated by 3 elements, it becomes 8 10 12 14 16 18 20 2 4 6.
Solution:
reverse(a, a+d) Reverse array from beginning till D
reverse(a+d, a+n) Reverse array from D till N
reverse(a, a+n) Reverse the whole array
UC 1:
77 69
40 13 27 87 95 40 96 71 35 79 68 2 98 3 18 93 53 57 2 81 87 42 66 90 45 20 41 30 32 18 98 72 82 76 10 28 68 57 98 54 87 66 7 84 20 25 29 72 33 30 4 20 71 69 9 16 41 50 97 24 19 46 47 52 22 56 80 89 65 29 42 51 94 1 35 65 25
Output:
29 42 51 94 1 35 65 25 40 13 27 87 95 40 96 71 35 79 68 2 98 3 18 93 53 57 2 81 87 42 66 90 45 20 41 30 32 18 98 72 82 76 10 28 68 57 98 54 87 66 7 84 20 25 29 72 33 30 4 20 71 69 9 16 41 50 97 24 19 46 47 52 22 56 80 89 65
UC 2:
5 2
1 2 3 4 5
Output: 3 4 5 1 2
UC3
10 3
2 4 6 8 10 12 14 16 18 20
Output: 8 10 12 14 16 18 20 2 4 6
'''
# More time consuming
def rotate_array(A, D, N):
a = A[D-1::-1]
b = A[N-1:D-1:-1]
a = a + b
return a[::-1]
# Faster
def rotateArr(A, D, N):
temp = A[:D]
for i in range(N):
if i < N - D:
A[i] = A[i + D]
else:
A[i] = temp[ i - (N - D)]
if __name__ == '__main__':
# arr = list(map(input().rstrip().split()), int)
arr = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
print(arr)
print(rotate_array(arr, 3, 10))
print(arr)
print()
arr = [1, 2, 3, 4, 5]
print(arr)
print(rotate_array(arr, 2, 5))
print(arr)
| true |
fd461e5e74a42b5e42b6d28e7d656811263f8c69 | ferryleaf/GitPythonPrgms | /numbers/factor_of_numbers.py | 450 | 4.125 | 4 | '''
Find the Factors of a Number:
Example:
The factors of 320 are:
1
2
4
5
8
10
16
20
32
40
64
80
160
320
'''
import math
class Solution:
def find_factors(self,num:int) -> None:
factors=list()
for i in range(1,int(math.sqrt(num))+1):
if(num%i==0):
factors.append(i)
factors.append(int(num/i))
print(factors)
if __name__=='__main__':
Solution().find_factors(int(input()))
| true |
de46cea01e81b8c4fe93c82a4e692ae76fc5a493 | ferryleaf/GitPythonPrgms | /strings/strstr.py | 1,504 | 4.125 | 4 | '''
Your task is to implement the function strstr. The function takes two strings
as arguments (s,x) and locates the occurrence of the string x in the string s.
The function returns and integer denoting the first occurrence of the string x
in s (0 based indexing).
Example 1:
Input:
s = GeeksForGeeks, x = Fr
Output: -1
Explanation: Fr is not present in the
string GeeksForGeeks as substring.
Example 2:
Input:
s = GeeksForGeeks, x = For
Output: 5
Explanation: For is present as substring
in GeeksForGeeks from index 5 (0 based
indexing).
Your Task:
You don't have to take any input. Just complete the strstr() function which
takes two strings str, target as an input parameter. The function returns -1
if no match if found else it returns an integer denoting the first occurrence
of the x in the string s.
Expected Time Complexity: O(|s|*|x|)
Expected Auxiliary Space: O(1)
Note : Try to solve the question in constant space complexity.
Constraints:
1 <= |s|,|x| <= 1000
'''
def strstr(s, p):
s_len = len(s)
p_len = len(p)
for i in range(s_len-p_len+1):
cnt = 0
for j in range(p_len):
if s[i+j] != p[j]:
break
else:
cnt += 1
idx = i
if cnt == p_len:
return idx
return -1
if __name__ == '__main__':
print(strstr('ceaaddfddbcdefbbffdacbaaaaedaafafdfcaeebdaefdfeaf', 'abf'))
print(strstr('GeeksForGeeks', 'For'))
print(strstr('abcabcabcd', 'abcd'))
| true |
5d4a34e282b9f7a119110f197a9d5af1c791adc6 | Gaurav-Dutta/python_learning | /Basics/Functions/function1.py | 921 | 4.21875 | 4 | #a function is defined by using the ketyword "def". The block of code following the funciton definition is called function block
#function may or may not return a value if the function returns a value it uses the return keyword to return a value
#the first functionn below does not return any value, the second function returns the full name of a person given first name, middle
#initial, and last name
def print_personal_info(name, city):
print(f"Hello {name}")
print(f"I live in {city}")
print_personal_info("Gaurav", "Houston")
print_personal_info(name = "Indra", city = "Houston")
print(type(print_personal_info))
def get_full_name(firstName, middleInitial, lastName):
#return firstName + " " + middleInitial + " " + lastName
return f"{firstName} {middleInitial} {lastName}"
#the return value from a function should be assigned to a variable
x = get_full_name("Gaurav", "Kumar", "Dutta")
print(x) | true |
56a689b12738635f8e5afbefe694677f81e2e51b | Gaurav-Dutta/python_learning | /Basics/datatypes/list3.py | 544 | 4.65625 | 5 | #many times we have to access each item in a list and do something with it, a process called list iteration
#the simplest way of doing list iteration is using for each method on the list
myList = ["dog", "cat", "penguin", "giraffe"]
for animal in myList:
print(animal.capitalize())
print("hello")
#adding other animals to the list
myList.append("monkey")
myList.append("bat")
print(myList)
#removing cat
myList.remove("cat")
print(myList)
#inserting animals
myList.insert(1, "horse")
myList.insert(3, "elephant")
print(myList) | true |
84c3d33f89d054cda35e0533dbd82ad4ad30bbb5 | shaikhjawad94/MITx-6.00.1x | /PS2/P3.py | 1,124 | 4.125 | 4 | low = balance / 12
high = (balance * (1 + (annualInterestRate/12.0))**12.0) / 12.0
minPay = (low + high) / 2
rerun = True
#low is the lowest minimum possible payment, i.e., when interest is 0%
#high is highets possible payment, i.e., when one payment made at the end of the year
def FixedPayBis(balance, annualInterestRate, minPay):
"""
Parameters
----------
balance : The outstanding balance on the credit card
annualInterestRate : Annual interest rate as a decimal
minPay : Smallest Monthly payment to the cent
Returns
-------
balance : New outstanding balance on the credit card
"""
month = 1
while month <= 12:
balance -= minPay
balance += balance*(annualInterestRate/12.0)
month += 1
return balance
while rerun == True:
a = FixedPayBis(balance, annualInterestRate, minPay)
if round(a) < 0:
high = minPay
minPay = (low + high) / 2
elif round(a) > 0:
low = minPay
minPay = (low + high) / 2
elif round(a) == 0:
rerun = False
print("Lowest Payment: " + str(round(minPay,2)))
| true |
23efc9bf59c75c93eb3dc71c5c170943b5b24df2 | tarunsingh8090/twowaits_python_programs | /Day 3/Problem 5.py | 503 | 4.15625 | 4 | size1 =int(input("Enter the no. of elements that you want to enter in List1:"))
List1=[]
print("Enter elements in List1 one by one:")
for i in range(size1):
List1.append(input())
size2= int(input("Enter the no. of elements that you want to enter in List2:"))
List2=[]
print("enter elements in List2 one by one:")
for i in range(size2):
List2.append(input())
intersectionList=list(set(List1).intersection(set(List2)))
print("The intersection of List1 and List2 is:",intersectionList)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.