blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
0137946f7a9ea9bbdae58fc8d79266575689cf32
|
dhrvdwvd/practice
|
/python_programs/50b_genrators.py
| 1,590
| 4.78125
| 5
|
"""
Iterables are those objects for which __iter__() and __getitem__()
methods are defined. These methods are used to generate an iterator.
Iterators are those objects for __next__() method is defined.
Iterations are process through which the above are accessed.
If I wish to traverse in a python object (string, list, tuple) moving
from one element to other, then that object should be an iterable.
If an object is iterable, then it generates an iterator through
__iter__(). The iterator obtained uses __next__() method to provide
items in the iterable.
Generators are iterators. These iterators can only be traversed once at
a time
"""
# To obtain a generator, yield keyword is used. yield gives a generator
# object:
def gen(n):
for i in range(n):
yield 10*i
def fib_nth_term(n):
if(n==1 or n==2):
return 1
else:
return fib_nth_term(n-1)+fib_nth_term(n-2)
def fib_gen(n):
for i in range(1,n):
yield fib_nth_term(i)
print(gen(2))
for i in range(8):
print(i)
# The above for loop generates values 'on the fly'. It does not store
# all the values from 0 to 77 in RAM, but it generates them one by one.
# So, range is a generator.
for i in gen(4):
print(i)
g = gen(5)
print("Printing using __next__()")
print("g(0): {}".format(g.__next__()))
print("g(1): {}".format(g.__next__()))
print("g(2): {}".format(g.__next__()))
print("g(3): {}".format(g.__next__()))
print("g(4): {}".format(g.__next__()))
print("\nGenerating fibonnaci series through a generator:")
for i in fib_gen(8):
print(i)
| true
|
6769020adb8b369e75113cf4f75cc06060dc5214
|
ma-henderson/python_projects
|
/05_rock_paper_scissors.py
| 2,297
| 4.34375
| 4
|
import random
message_welcome = "Welcome to the Rock Paper Scissors Game!"
message_name = "Please input your name!"
message_choice = "Select one of the following:\n- R or Rock\n- P or Paper\n- S or Scissors"
message_win = "You WON!"
message_loss = "You LOST :("
message_end = "If you'd like to quit, enter 'q' or 'quit'"
message_quit = "quitting..."
choice_alternatives = ['r', 'rock', 'p', 'paper', 's', 'scissors']
# Functions:
def choice_checker(choice, alternatives):
"""Checks if the user's input is OK, does not stop until OK"""
while True:
for num in range(0, len(alternatives)):
if choice == alternatives[num]:
return choice
print("Incorrect input, please select one of the following:" + str(alternatives))
choice = input("Your choice (lowercase only): ")
#new_choice = choice_checker(choice_player, choice_alternatives)
# Player starts game, is welcomed
print(message_welcome)
print(message_name)
# Player inputs name
name = input("Your name: ")
while True:
# Player is asked what choice he would like to make
print(message_choice)
# Input is Checked and stored
choice_player = input("Your choice: ")
if choice_player == 'q' or choice_player == 'quit':
print(message_quit)
break
choice_player_ok = choice_checker(choice_player, choice_alternatives)
# Player choice is converted to number
if choice_player_ok == 'r' or choice_player_ok == 'rock':
choice_player_num = 0
elif choice_player_ok == 'p' or choice_player_ok == 'paper':
choice_player_num = 1
elif choice_player_ok == 's' or choice_player_ok == 'scissors':
choice_player_num = 2
# Computer randomizes its choice
choice_comp = random.randrange(3)
# Comparison is made
if choice_comp == 2 and choice_player_num == 1:
decision = 0
elif choice_comp == 1 and choice_player_num == 0:
decision = 0
elif choice_comp == 0 and choice_player_num == 2:
decision = 0
else:
decision = 1
# winner declared and printed
if decision == 1:
print(message_win)
else:
print(message_loss)
# score is recorded and printed
# player decides if he continues playing (q or quit)
print("\n" + message_end)
#BONUS: if player's name is "Tom" or "Tomas", Player always loses
# Note, if extra time use REGEXP to detect variations of tom
| true
|
e63f137ab97124caba74419a6de8f7d8c6f7aa5e
|
tarunbhatiaind/Pyhtonbasicprogs
|
/exercise_2.py
| 759
| 4.125
| 4
|
"""""
print("A","\nB")
"""
print("Enter the operation you want to do :")
print("type 1 for addition")
print("type 2 for subtraction")
print("type 3 for multiplication")
print("Type 4 for division")
op=int(input())
if op == 1 or op == 2 or op == 3 or op == 4:
print("Enter the 2 numbers for the operations :")
a=int(input())
b=int(input())
if op==3:
if a==45 and b==3 or a==3 and b==45:
print("Ans is :555")
else:
print("ans is :",a*b)
if op==2:
print("ans is ",a-b)
if op==1:
if a==56 and b==9 or a==9 and b==56:
print("ans is : 77")
else:
print("ans is",a+b)
if op==4:
if a==56 and b==6:
print("Answer is: 4.0")
else:
print("answer is:",a/b)
else:
print("invalid input")
| false
|
f58299529ddb80c5ab80ee9a7254570f74372306
|
Oscarpingping/Python_code
|
/01-Python基础阶段代码/01-基本语法/Python循环-while-练习.py
| 1,182
| 4.15625
| 4
|
# 打印10遍"社会我顺哥, 人狠话不多"
# print("社会我顺哥, 人狠话不多")
# print("社会我顺哥, 人狠话不多")
# print("社会我顺哥, 人狠话不多")
# print("社会我顺哥, 人狠话不多")
# print("社会我顺哥, 人狠话不多")
# print("社会我顺哥, 人狠话不多")
# print("社会我顺哥, 人狠话不多")
# print("社会我顺哥, 人狠话不多")
# print("社会我顺哥, 人狠话不多")
# print("社会我顺哥, 人狠话不多")
# print("社会我顺哥, 人狠话不多\n" * 10)
# while
# 一定要注意, 以后, 写循环的时候, 要考虑好, 循环的结束
# 修改条件
# 打断循环, break
# num = 0
# condition = True
# while condition:
# print("社会我顺哥, 人狠话不多")
# num += 1 # num = num + 1
# print(num)
# # 只要修改了这个条件, 那么下次就不会再被执行
# if num == 10:
# condition = False
num = 0
# condition = True
while num < 10:
print("社会我顺哥, 人狠话不多")
num += 3 # num = num + 1
print(num)
# 只要修改了这个条件, 那么下次就不会再被执行
# if num == 10:
# condition = False
| false
|
1184cff6fc360e4a0bfd5754ed1312be4cf624f1
|
ivanjankovic16/pajton-vjezbe
|
/Exercise 9.py
| 885
| 4.125
| 4
|
import random
def Guessing_Game_One():
try:
userInput = int(input('Guess the number between 1 and 9: '))
random_number = random.randint(1, 9)
if userInput == random_number:
print('Congratulations! You guessed correct!')
elif userInput < random_number:
print(f'You guessed to low! The correct answer is {random_number}')
elif userInput > random_number:
print(f'You guessed to high! The correct answer is {random_number}')
elif userInput > 9:
print('Error! You should enter a number between 1 and 9!')
except:
print('Error! You must enter a number between 1 and 9.')
Guessing_Game_One()
Guessing_Game_One()
while True:
answer = input('Dou you want to play again? (yes/exit): ')
if answer == 'yes':
Guessing_Game_One()
elif answer != 'exit':
print('Enter: yes or exit')
elif answer == 'exit':
#print(f'You took {guesses} guesses!')
break
| true
|
4b3d8f8ce9432d488a4ee4ebdc2bec1256939dbe
|
ivanjankovic16/pajton-vjezbe
|
/Exercise 16 - Password generator solutions.py
| 675
| 4.21875
| 4
|
# Exercise 16 - Password generator solutions
# Write a password generator in Python. Be creative with how you generate
# passwords - strong passwords have a mix of lowercase letters, uppercase
# letters, numbers, and symbols. The passwords should be random, generating
# a new password every time the user asks for a new password. Include your
# run-time code in a main method.
#Njihovo rješenje
import string
import random
def pw_gen(size = input, chars=string.ascii_letters + string.digits + string.punctuation):
return ''.join(random.choice(chars) for _ in range(size))
print(pw_gen(int(input('How many characters in your password?'))))
input('Press<enter>')
| true
|
4713b2790c09b0f5f98e8f544c0a961ef87c2ea5
|
ivanjankovic16/pajton-vjezbe
|
/Exercise 13 - Fibonacci.py
| 1,204
| 4.625
| 5
|
# Write a program that asks the user how many Fibonnaci numbers
# to generate and then generates them. Take this opportunity to
# think about how you can use functions. Make sure to ask the user
# to enter the number of numbers in the sequence to generate.(Hint:
# The Fibonnaci seqence is a sequence of numbers where the next number
# in the sequence is the sum of the previous two numbers in the
# sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)
def gen_fib():
nnums = int(input("How many numbers in a Fibonacci sequence do you want? "))
n1, n2 = 0, 1
count = 0
if nnums <= 0:
print("Please enter a positive integer")
#elif nterms == 1:
# print("Fibonacci sequence upto",nnums,":")
# print(n1)
else:
print("Fibonacci sequence:")
while count < nnums:
print(n1)
n3 = n1 + n2
# update values
n1 = n2
n2 = n3
count += 1 # is the same as count = count + 1. That keeps the index moving forward
gen_fib()
while True:
answer = input('Do you want to generate another sequence? (yes/no): ')
if answer == 'yes':
gen_fib()
elif answer == 'no':
break
else:
print('Enter yes or no')
#input('Press<enter>')
| true
|
e1d4247baca7c6291bd0fa90b51d920c86adb81b
|
csdaniel17/python-classwork
|
/string_split.py
| 1,387
| 4.125
| 4
|
## String split
# Implement the string split function: split(string, delimiter).
# Examples:
# split('abc,defg,hijk', ',') => ['abc', 'defg', 'hijk']
# split('JavaScript', 'a') => ['J', 'v', 'Script']
# split('JaaScript', 'a') => ['J', '', 'Script']
# split('JaaaScript', 'aa') => ['J', 'aScript']
def str_split(str, delim):
result = []
start_idx = 0
end_idx = str.index(delim)
while end_idx != -1:
# find to the end_idx (until delim)
part = str[:end_idx]
# append to array
result.append(part)
# set start index to next point after delim
start_idx = end_idx + len(delim)
# now string is cut from start_idx to leave remainder so you can find next delim
str = str[start_idx:]
# if there is no delim in the rest of string
if delim not in str:
# put remaining str in array
result.append(str)
# terminate loop
break
# end_idx is now delim in leftover string
end_idx = str.index(delim)
print result
## test before adding input functionality
# str_split('abc,defg,hijk', ',')
# str_split('JavaScript', 'a')
# str_split('JaaScript', 'a')
# str_split('JaaaScript', 'aa')
print "Give string and a delimiter to split the string on."
str = raw_input("Enter a string: ")
delim = raw_input("Enter a delim: ")
str_split(str, delim)
| true
|
cf6b1e2e097358113767dc766af9ebd853d52933
|
Audodido/IS211_Assignment1
|
/assignment1_part2.py
| 716
| 4.28125
| 4
|
class Book:
"""
A class to represent a book
Attributes:
author (string): Name of the author
title (string): Title of the book
"""
def __init__(self, author, title):
"""
Constructs all the necessary attributes for the Book object.
"""
self.author = author
self.title = title
def display(self):
"""
Returns:
(string) message containing the book's author and title
"""
print(self.title + ", written by " + self.author)
book1 = Book("John Steinbeck", "Of Mice and Men")
book2 = Book("Harper Lee", "To Kill a Mockingbird")
if __name__ == "__main__":
book1.display()
book2.display()
| true
|
c64f463ed6738262fffbe1f859f86012e566168e
|
kolarganesha/Assignment2
|
/assignment_2/list_comprehensions/list_comprehension_assignment.py
| 1,348
| 4.15625
| 4
|
''' 2. Implement List comprehensions to produce the following lists.
Write List comprehensions to produce the following Lists
['A', 'C', 'A', 'D', 'G', 'I', ’L’, ‘ D’]
['x', 'xx', 'xxx', 'xxxx', 'y', 'yy', 'yyy', 'yyyy', 'z', 'zz', 'zzz', 'zzzz']
['x', 'y', 'z', 'xx', 'yy', 'zz', 'xx', 'yy', 'zz', 'xxxx', 'yyyy', 'zzzz']
[[2], [3], [4], [3], [4], [5], [4], [5], [6]]
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]
[(1, 1), (2, 1), (3, 1), (1, 2), (2, 2), (3, 2), (1, 3), (2, 3), (3, 3)]'''
#['A', 'C', 'A', 'D', 'G', 'I', ’L’, ‘ D’]
word = "ACADGILD"
r1 = [i for i in word]
print(r1)
#['x', 'xx', 'xxx', 'xxxx', 'y', 'yy', 'yyy', 'yyyy', 'z', 'zz', 'zzz', 'zzzz']
l1 = ['x', 'y', 'z']
r2 = [i*j for i in l1 for j in range(1,5)]
print(r2)
#['x', 'y', 'z', 'xx', 'yy', 'zz', 'xx', 'yy', 'zz', 'xxxx', 'yyyy', 'zzzz']
l2 = ['x', 'y', 'z']
r3 = [i*j for i in range(1,5) for j in l2]
print(r3)
#[[2], [3], [4], [3], [4], [5], [4], [5], [6]]
l3 = [2, 3, 4]
r4 = [[i+j] for i in l3 for j in range(0,3) ]
print(r4)
#[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]
l3 = [2, 3, 4, 5]
r4 = [[i+j for i in l3] for j in range(0,4) ]
print(r4)
#[(1, 1), (2, 1), (3, 1), (1, 2), (2, 2), (3, 2), (1, 3), (2, 3), (3, 3)]
r5 = [(j,i) for i in range(1,4) for j in range(1,4)]
print(r5)
| false
|
9f020702dc8684050f12bca0a0610309033c7bc3
|
saradcd77/python_examples
|
/abstract_base_class.py
| 1,120
| 4.40625
| 4
|
# This example shows a simple use case of Abstract base class, Inheritance and Polymorphism
# The base class that inherits abstract base class in python needs to override it's method signature
# In this case read method is overriden in methods of classes that inherits Electric_Device
# Importing in-built abstract base class
from abc import ABC, abstractmethod
# Custom Exception
class InvalidOperationError(Exception):
pass
# Inherits ABC class
class Electric_Device(ABC):
def __init__(self):
self.open = False
def turn_on_device(self):
if self.open:
raise InvalidOperationError("Electric_Device is already ON!")
self.open = True
def turn_off_device(self):
if not self.open:
raise InvalidOperationError("Electric_Device is OFF")
self.open = False
@abstractmethod
def charge(self):
pass
class Heater(Electric_Device):
def charge(self):
print("Charging Electric Heater!")
class Kettle(Electric_Device):
def charge(self):
print("Charging Electric Kettle! ")
device1 = Kettle()
device1.charge()
device2 = Heater()
device2.charge()
device2.turn_on_device()
print(device2.open)
| true
|
22e801ed46b26007bbd7880dce3197fbc3e04a7c
|
simonzahn/Python_Notes
|
/Useful_Code_Snippets/DirectorySize.py
| 522
| 4.375
| 4
|
#! python3
import os
def dirSize(pth = '.'):
'''
Prints the size in bytes of a directory.
This function takes the current directory by default, or the path specified
and prints the size (in bypes) of the directory.
'''
totSize = 0
for filename in os.listdir(pth):
totSize += os.path.getsize(os.path.join(pth, filename))
return totSize
print('Your current directory is ' + os.getcwd())
print('What is the file path you want to look at?')
foo = str(input())
print(dirSize(foo))
| true
|
1672167ecd1302e8bfff3da2f790d69ff6889be4
|
KatGoodwin/LearnPython
|
/python_beginners/sessions/strings-basic/examples/.svn/text-base/string_concatenation.py.svn-base
| 734
| 4.125
| 4
|
# concatenating strings
newstring = "I am a " "concatenated string"
print newstring
concat = "I am another " + "concatenated string"
print concat
print "Our string is : " + newstring
# The above works, but if doing a lot of processing would be inefficient.
# Then a better way would be to use the string join() method, which joins
# string elements from a list.
lst = [ 'a', 'bunch', 'of', 'words', 'which', 'together', 'make', 'a',
'sentence', 'and', 'which', 'have', 'been', 'collected', 'in',
'a', 'list', 'by', 'some', 'previous', 'process.',
]
print ' '.join( lst )
# another way to construct strings is to use a format
s1 = "I am a"
s2 = "concatenated string"
print '%s formatted %s' % ( s1, s2, )
| true
|
54415d27cdec4ce01ede31c8a87f330bb703ce59
|
tomgarcia/Blabber
|
/markov.py
| 2,284
| 4.21875
| 4
|
#extra libraries used
import queue
import tools
import random
"""
markov_chain class is a class that creates a(n) markov chain statistical
model on an inputted list of objects.
The class is then able to generate randomly a new list of objects based
on the analysis model of the inputted list.
"""
class markov_chain:
"""
Class constructor, at the very minium, the class needs an inputted list of
objects the level parameter is extra to specify the level of the markov
chain
"""
def __init__(self, obj_list: list, level:int = 1):
self.level = level #level class variable
self.obj_list = obj_list #list of objects
self.transitions = {}
self.generate_prob_table()
"""
generate_prob_table goes through the list of objects and generates a probability
table of current object to the previous object that can be used to look up again.
NOTE: you might not need to keeptrack of a probability, just the count of one
object appearing after another
"""
def generate_prob_table(self):
for i in range(len(self.obj_list) - self.level):
state = self.obj_list[i:i+self.level]
next = self.obj_list[i+self.level]
if tuple(state) not in self.transitions:
self.transitions[tuple(state)] = {}
if next not in self.transitions[tuple(state)]:
self.transitions[tuple(state)][next] = 0
self.transitions[tuple(state)][next] += 1
"""
generate_random_list uses the probability table and returns a list of
objects that adheres to the probability table generated in the previous
method
NOTE: the first object has to be selected randomly(the seed)
NOTE: the count parameter is just to specify the length of the generated
list
"""
def generate_obj_list(self, count:int = 10):
start = random.randrange(len(self.obj_list)-self.level)
output = self.obj_list[start:start+self.level]
state = self.obj_list[start:start+self.level]
for i in range(count-self.level):
choice = tools.weighted_choice(self.transitions[tuple(state)])
output.append(choice)
state.append(choice)
state.pop(0)
return output
| true
|
e52255d28a1e9c0d55ce5a296e384e1d7746b87d
|
mediter/Learn-Python-the-Hard-Way-notes-and-practices
|
/ex7.py
| 1,138
| 4.46875
| 4
|
# -*- coding: utf-8 -*-
# Exercise 7: More Printing
print "Mary had a little lamb."
print "Its fleece was white as %s." % 'snow'
print "And everywhere that Mary went."
print "." * 12 # what would that do?
end1 = 'C'
end2 = 'h'
end3 = 'e'
end4 = 'e'
end5 = 's'
end6 = 'e'
end7 = 'B'
end8 = 'u'
end9 = 'r'
end10 = 'g'
end11 = 'e'
end12 = 'r'
# watch that comma at the end.
# try removing it to see what happens
print end1 + end2 + end3 + end4 + end5 + end6,
print end7 + end8 + end9 + end10 + end11 + end12
# Shorthand for printing a string multiple times
# string * number [the number can only be an integer]
print "*" + "." * 12 + "*"
print "*", "." * 12, "*"
# Use the comma inline in print would also add a
# space between the elements.
# Now without the comma in the middle
print end1 + end2 + end3 + end4 + end5 + end6
print end7 + end8 + end9 + end10 + end11 + end12
print "Summary"
print "1. When using a comma at EOL after a print statement,",
print "the result of the next print statement will follow in",
print "the same line with a space added in between them."
print "2. Otherwise, it would print on separate lines."
| true
|
660472dd3ec4d4ab685c784ea85dc540e6eb45c9
|
mediter/Learn-Python-the-Hard-Way-notes-and-practices
|
/ex9.py
| 923
| 4.28125
| 4
|
# -*- coding: utf-8 -*-
# Exercise 9: Printing, Printing, Printing
# Here's some new strange stuff, remember to type it exactly
days = "Mon Tue Wed Thu Fri Sat Sun"
# \n would make the stuff after it begin on a new line
months = "\nJan\nFeb\nMar\nApr\nMay\nJun"
# if a comma is added to the above statement, it would cause
# TypeError: can only concatenate tuple (not "str") to tuple
months = months + "\nJul\nAug\nSep\nOct\nNov\nDec"
print "Here are the days: ", days
print "Here are the months: ", months
flowers = "rose\nnarcissus",
flowers = flowers + ("tuplip", "gardenia")
print flowers
# Output -> ('rose\nnarcissus', 'tuplip', 'gardenia')
# Why "\n" does not behave as an escaped char?
# Use triple double-quotes to enclose paragraphs to be printed
print """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""
| true
|
625c2dfaeb03200f85a61300ee643d06bf9e4a0a
|
silky09/BeetrootAcademy
|
/Python_week4/day1.py
| 844
| 4.34375
| 4
|
"""print a message"""
print("Welcome to MyFriends 1.0!")
print()
"""
Homework. Advanced level
write a program, which has two print statements to print
the following text (capital letters “O” and “H” made out of “#” symbols):
#####
# #
# #
# #
#####
# #
# #
#####
# #
# #
"""
print()
for row in range(7):
for col in range(5):
if row in {0, 1, 2, 4, 5, 6} and col in {0, 4}:
print('#', end=' ')
elif row == 3:
print('#', end=' ')
else:
print(' ', end=' ')
print()
print()
for row in range(7):
for col in range(5):
if row in {0, 6} and col in {1, 2, 3}:
print('#', end=' ')
elif row in {1, 2, 3, 4, 5} and col in {0, 4}:
print('#', end=' ')
else:
print(' ', end=' ')
print()
| false
|
10dc31cc92bc284cb08fde0fda5cdb312da06025
|
Sayed-Tasif/my-programming-practice
|
/math function.py
| 256
| 4.34375
| 4
|
Num = 10
Num1 = 5
Num2 = 3
print(Num / Num1) # used to divide
print(Num % Num2) # used to see remainder
print(Num2 ** 2) # indicates something to the power {like ( "number" ** "the power number")}
print(Num2 * Num1) # used to multiply the number
| true
|
c781089190d266c5c3649f4ff96736fc1dfe8b1d
|
YanSongSong/learngit
|
/Desktop/python-workplace/homework.py
| 217
| 4.1875
| 4
|
one=int(input('Enter the first number:'))
two=int(input('Enter the second number:'))
three=int(input('Enter the third number:'))
if(one!=two and one!=three and two!=three):
a=max(one,two,three)
print(a)
| true
|
95cafd3e875061426d39fd673bbf6327c5eb7c14
|
krwinzer/web-caesar
|
/caesar.py
| 489
| 4.25
| 4
|
from helpers import alphabet_position, rotate_character
def encrypt(text, rot):
code = ''
for char in text:
if char.isalpha():
char = rotate_character(char, rot)
code = code + char
else:
code = code + char
return (code)
def main():
text = input("Please enter your text to be coded:")
rot = int(input("Please enter your desired rotation:"))
print(encrypt(text, rot))
if __name__ == "__main__":
main()
| true
|
a337618daafddfb9224eda521e2e03644f204a0e
|
Seun1609/APWEN-Python
|
/Lesson2/quadratic.py
| 1,141
| 4.21875
| 4
|
# Get inputs a, b and c
# The coefficients, in general, can be floating-point numbers
# Hence cast to floats using the float() function
a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
# Compute discriminant
D = b*b - 4*a*c
if D >= 0: # There are real roots
# x1 and x2 could be equal
# In that case, we would have real repeated roots
# This happens when the discriminant, D = 0
# Otherwise, there are real and distinct roots
x1 = (-b + D**0.5) / (2*a) # first solution
x2 = (-b - D**0.5) / (2*a) # second solution
# Print solutions
print("x1 = " + str(x1))
print("x2 = " + str(x2))
else: # Complex conjugate roots
# Get the real and imaginary parts
# In finding the imaginary part, we find the square root of -D
# This is because D itself is a negative number already
re = -b / (2*a) # real part
im = ((-D)**0.5) / (2*a) # imaginary part
# Print solutions
# x1 = re + j(im)
# x2 = re - j(im)
print("x1 = " + str(re) + " + j" + str(im))
print("x2 = " + str(re) + " - j" + str(im))
| true
|
30115c3de0f19d9878f2b00c1abf998b7b36a9fb
|
stansibande/Python-Week-Assignments
|
/Functions.py
| 2,048
| 4.25
| 4
|
#name and age printing function
def nameAge(x,y):
print ("My name is {} and i am {} Years old.".format(x,y))
#take two numbers and multiply them
def multiply(x,y):
result=x*y
print("{} X {} = {}.".format(x,y,result))
#take two numbers and check if a number x is a multiple of a number Y
def multiples(x,y):
if x%y==0:
print("The number {} is a multiple of the number {}".format(x,y))
print
else:
print("The number {} is not a multiple of the number {}.".format(x,y))
print()
#out of three numbers determine biggest and smallest
def checker(num1,num2,num3):
if num1>num2:
largest=num1
else:
largest=num2
if num2>num3:
largest=num2
else:
largest=num3
if num3>largest:
largest=num3
else:
largest=largest
if largest>num1:
largest=largest
else:
largest=num1
print("The largest number between {},{} and {} is {}.".format(num1,num2,num3,largest))
print()
#Example 1
print ("Enter Your Name and Age To Be Printed:")
name=input("Enter Your Full Name:")
try:
age =int (input("Enter Your Age :"))
except:
print ("Age can only be a number")
else:
nameAge(name,age)
print()
#Example 2
print ("Enter 2 numbers to be Submitted to a fuction for Multiplication:")
num1=int(input("Enter your First number: "))
num2=int (input("Enter your second Number: "))
multiply(num1,num2)
print()
#Example 3
print ("Enter 2 numbers to be Submitted to a fuction To Determine if the First number is a Multiple of the Second Number:")
mult1=int(input("Enter your First number: "))
mult2=int (input("Enter your second Number: "))
multiples(mult1,mult2)
#Example 4
print ("Enter 3 numbers to be Submitted to a fuction To Determine Which one is the largest:")
n1=int(input("Enter your First number: "))
n2=int (input("Enter your second Number: "))
n3=int (input("Enter your third Number: "))
checker(n1,n2,n3)
| true
|
1f07e8a2872c37d2a6a74c0ef5a6e9c997d3d6ea
|
UCSD-CSE-SPIS-2021/spis21-lab03-Vikram-Marlyn
|
/lab03Warmup_Vikram.py
| 928
| 4.40625
| 4
|
# Vikram - A program to draw the first letter of your name
import turtle
def draw_picture(the_turtle):
''' Draw a simple picture using a turtle '''
the_turtle.speed(1)
the_turtle.forward(100)
the_turtle.left(90)
the_turtle.forward(100)
the_turtle.left(90)
the_turtle.forward(100)
the_turtle.left(90)
the_turtle.forward(100)
the_turtle.left(90)
my_turtle = turtle.Turtle() # Create a new Turtle object
draw_picture(my_turtle) # make the new Turtle draw the shape
turtle1 = turtle.Turtle()
turtle2 = turtle.Turtle()
turtle1.speed(1)
turtle2.speed(2)
turtle1.setpos(-50, -50)
turtle2.setpos(200, 100)
turtle1.forward(100)
turtle2.left(90)
turtle2.forward(100)
#turtle.forward(distance)
#turtle.fd(distance)
#Parameters: distance – a number (integer or float)
#Move the turtle forward by the specified distance, in the direction the turtle is headed.
| true
|
9a7ed39510c516c2e7da84be43a8f8c2a488a337
|
v-stickykeys/bitbit
|
/python/mining_simplified.py
| 2,043
| 4.1875
| 4
|
import hashlib
# The hash puzzle includes 3 pieces of data:
# A nonce, the hash of the previous block, and a set of transactions
def concatenate(nonce, prev_hash, transactions):
# We have to stringify it in order to get a concatenated value
nonce_str = str(nonce)
transactions_str = ''.join(transactions)
return ''.join([nonce_str, prev_hash, transactions_str])
# Now we want to hash this concatenated value.
def hash_sha256(concatenated):
# Bitcoin uses the SHA256 hash algorithm for mining
return hashlib.sha256(str(concatenated).encode('utf-8')).hexdigest()
# If we get a hash value inside of our defined target space we have found a
# solution to the puzzle. In this case, we will print the hash solution (which
# will be this block's hash) and return true.
def solve_hash_puzzle(nonce, prev_hash, transactions):
concatenated = concatenate(nonce, prev_hash, transactions)
proposed_solution = hash_sha256(concatenated)
# For the sake of example, we will define our target space as any hash
# output with 2 leading zeros. In Bitcoin it is actually 32 leading zeros.
if (proposed_solution[0:2] == '00'):
print(f'Solution found: {proposed_solution}')
return True
return False
# Now let's mine!
def mine_simple(max_nonce, prev_hash, transactions):
print('\nMining...')
# Note: max_nonce is just used for demonstration purposes to avoid an endless
# loop
nonce = 0 # Initalized to zero -- Is this true in Bitcoin?
while (solve_hash_puzzle(nonce, prev_hash, transactions) == False
and nonce < max_nonce):
nonce += 1
print(f'Nonce that produced solution: {nonce}')
# Uncomment the code below to see the program run
"""
_max_nonce = 100000
prev_hash = hashlib.sha256('Satoshi Nakamoto'.encode('utf-8')).hexdigest()
transactions = ["tx1", "tx2", "tx3"]
mine_simple(_max_nonce, prev_hash, transactions)
"""
# Notice the nonce value tells us how many attempts were required to find a
# solution. This is also an approximation for difficulty.
| true
|
63c362549cdfdeeea249d6d31df11e8fca7748e3
|
herr0092/python-lab3
|
/exercise8.py
| 400
| 4.34375
| 4
|
# Write a program that will compute the area of a circle.
# Prompt the user to enter the radius and
# print a nice message back to the user with the answer.
import math
print('===================')
print(' Area of a Circle ')
print('===================')
r = int(input('Enter radius: '))
area = math.pi * ( r * r)
print('The area of a circle with a radius of ', r , 'is: ' , round(area,2) )
| true
|
02096c3d2fcff25f2a680e34586a56d8d7ca1f89
|
evb-gh/exercism
|
/python/guidos-gorgeous-lasagna/lasagna.py
| 1,299
| 4.1875
| 4
|
"""Functions used in preparing Guido's gorgeous lasagna.
Learn about Guido, the creator of the Python language: https://en.wikipedia.org/wiki/Guido_van_Rossum
"""
EXPECTED_BAKE_TIME = 40
PREPARATION_TIME = 2
def bake_time_remaining(minutes):
"""Calculate the bake time remaining.
:param elapsed_bake_time: int - baking time already elapsed.
:return: int - remaining bake time derived from 'EXPECTED_BAKE_TIME'.
Function that takes the actual minutes the lasagna has been in the oven as
an argument and returns how many minutes the lasagna still needs to bake
based on the `EXPECTED_BAKE_TIME`.
"""
return EXPECTED_BAKE_TIME - minutes
def preparation_time_in_minutes(layers):
"""
Return prep time.
This function takes an int param representing the number of layers
multiplies it by the PREPARATION_TIME constant and returns an int
representing the prep time in minutes
"""
return PREPARATION_TIME * layers
def elapsed_time_in_minutes(prep, bake):
"""
Return elapsed cooking time.
This function takes two int params representing the number of layers &
the time already spent baking and returns the total elapsed minutes
spent cooking the lasagna.
"""
return preparation_time_in_minutes(prep) + bake
| true
|
80df60b4c750e3e98e1c00c0d083e3582cbd4093
|
zee7han/algorithms
|
/sorting/insertion_sort.py
| 504
| 4.28125
| 4
|
def insertion_sort(arr):
for i in range(1,len(arr)):
position = i
current_value = arr[i]
print("position and current_value before", position, current_value)
while position > 0 and arr[position-1] > current_value:
arr[position] = arr[position-1]
position = position-1
print("position and current_value after change -----------", position)
arr[position] = current_value
arr = [1,4,2,3,7,86,9]
insertion_sort(arr)
print(arr)
| true
|
4585011053584c47520de828717d53f8944292fc
|
ivaszka/etwas
|
/square.py
| 1,049
| 4.28125
| 4
|
"""Реализуйте рекурсивную функцию нарезания прямоугольника с заданными
пользователем сторонами a и b на квадраты с наибольшей возможной на
каждом этапе стороной. Выведите длины ребер получаемых квадратов и кол-
во полученных квадратов."""
from random import randint
def square(a, b, array):
if a == b:
array.append(a)
return array
elif a < b:
array.append(a)
b -= a
else:
array.append(b)
a -= b
return square(a, b, array)
c = randint(1, 15)
d = randint(1, 10)
print(str(c) + ' ' + str(d))
array = square(c, d, [])
print(array)
print(len(array))
print('______________________________________ \n\n')
a = 0
for i in array:
list = []
print()
for j in range(i):
list.append(a)
for k in range(i):
print(list)
a += 1
| false
|
027a6c2e0251e68ff32feef6b1b1710692c7e8f2
|
Sem31/Data_Science
|
/2_Numpy-practice/19_sorting_functions.py
| 1,376
| 4.125
| 4
|
#Sorting Functions
import numpy as np
#np.sort() --> return sorted values of the input array
#np.sort(array,axis,order)
print('Array :')
a = np.array([[3,7],[9,1]])
print(a)
print('\nafter applying sort function : ')
print(np.sort(a))
print('\nSorting along axis 0:')
print(np.sort(a,0))
#order parameter in sort function
dt = np.dtype([('name','S10'),('age',int)])
x = np.array([('Ram',23),('Robert',25),('Rahim',27)], dtype = dt)
print('\nArray :')
print(x)
print('dtype : ',dt)
print('Order by name : ')
print(np.sort(x, order = 'name'))
#np.nonzero() --> returns the indices of the non-zero elements
b = np.array([[30,40,0],[0,20,10],[50,0,60]])
print('\narray b is :\n',b)
print('\nafter applying nonzero() function :')
print(np.nonzero(b))
#np.Where() --> returns the indices of elements when the condition is satisfied
x = np.arange(12).reshape(3,4)
print('\nArray is :')
print(x)
print('Indices of elements >3 :')
y = np.where(x>3) #its just work like a sql query
print(y)
print('Use these indices to get elements statisfying the condition :')
print(x[y])
#np.extract() --> returns the elements satisfying any condition
x = np.arange(9).reshape(3,3)
print('\nArray : ')
print(x)
#define conditions
condition = np.mod(x,2) == 0
print('\nelement-wise value of condition :\n',condition)
print('\nextract elements using condition :\n',np.extract(condition, x))
| true
|
43c6442a8b1b90a1f69392b31c1aef2a26334f6d
|
Sem31/Data_Science
|
/3_pandas-practice/1_Create_series.py
| 950
| 4.3125
| 4
|
#Create a series using pandas
#import the pandas library
import pandas as pd #pd is a alias name
#what the syntax of the series see..
print("Series syntax :\n",pd.Series())
print('create a Series using pandas : ')
#pd.Series(array,index)
a = pd.Series([1,2,3,4]) #by default index is 0,1,2... so on
print(a)
print('\ncreate a Series using own index : ')
b = pd.Series([1,2,3,4],index = ['a','b','e','d'])
print(b)
print('\nCreate a Series using the Dictionary object : ')
dict1 = {'a':1,'b':2,'c':3,'d':4}
print("\nDictionary : ",dict1)
data = pd.Series(dict1)
print('Series :')
print(data)
print('\nAny one nan value then all data convert into float see ..:')
dict1 = {'a':1,'b':2,'c':3,'d':4}
print(dict1)
print('Series :')
print(pd.Series(dict1,index = ['e','f','a','b','c','d']))
#access the series data using slicing
print('\nSeries')
a = pd.Series([1,2,3,4]) #by default index is 0,1,2... so on
print(a)
print('first[0] values : ',a[0])
| false
|
e6c02fe3a07681cc415d9aa0e0257705aca65492
|
Rishivendra/Turtle_Race_Game
|
/3.Turtle_race.py
| 1,281
| 4.25
| 4
|
from turtle import Turtle, Screen
import random
is_race_on = False
screen = Screen()
screen.setup(width=500, height=400) # sets the width and height of the main window
user_bet = screen.textinput(title="Make your bet",
prompt="Which turtle will win the race? Enter color:") # Pop up a dialog window for input of a string
colours = ["red", "orange", "yellow", "green", "blue", "purple"]
y_positions = [-70, -40, -10, 20, 50, 80]
all_turtle = []
for turtle_index in range(0, 6):
new_turtle = Turtle(shape="turtle")
new_turtle.penup()
new_turtle.goto(x=-230, y=y_positions[turtle_index])
new_turtle.color(colours[turtle_index])
all_turtle.append(new_turtle)
if user_bet:
is_race_on = True
while is_race_on:
for turtle in all_turtle:
if turtle.xcor() > 230:
is_race_on = False # stop race
winning_color = turtle.pencolor()
if winning_color == user_bet:
print(f"You have Won! The {winning_color} is the turtle winner!")
else:
print(f"You have Lost! The {winning_color} is the turtle winner!")
rand_distance = random.randint(0, 10)
turtle.fd(rand_distance)
screen.exitonclick()
| true
|
6206eb9dc2cb71a50b5f75a1e9c8ffd11ba8e15c
|
Polaricicle/practical03
|
/q3_find_gcd.py
| 1,231
| 4.40625
| 4
|
#Filename: q3_find_gcd.py
#Author: Tan Di Sheng
#Created: 20130218
#Modified: 20130218
#Description: This program writes a function that returns the greatest common
#divisor between two positive integers
print("""This program displays a the greatest common divisor between
two positive integers.""")
#Creates a loop so that the user can keep using the application
#without having to keep restarting the application
while True:
def gcd(m, n):
min = m
if (min > n):
min = n
m = int(m)
n = int(n)
min = int(min)
while not (min == 1):
if (m % min == 0) and (n % min == 0):
break
min = min - 1
print("\nThe greatest common divisor of {0} and {1} is {2}".format(m, n, min))
while True:
m = input("\nEnter the first integer: ")
n = input("Enter the second integer: ")
try:
int(m) and int(n)
except:
print("\nPlease input integer values.")
else:
break
gcd(m, n)
#gives the user an option to quit the application
contorquit = input("\nContinue? Type no to quit: ")
if contorquit == "no":
quit()
else:
continue
| true
|
945e12dd76007dba2e48aed8932fc1f01ff4f4d2
|
Azhar9983/MyCode
|
/is_palindrome.py
| 239
| 4.21875
| 4
|
def isPalindrome(str):
if(str == "".join(reversed(str))):
print("String is Palindrome")
else:
print("String isn't Palindrome")
new = str(input("Enter SomeThing : "))
isPalindrome(new)
| false
|
54b6009927a8c2be078af2e7fdefa94f2df25dae
|
AndreHBSilva/FIAP-Computational-Thinking
|
/Checkpoint 2/exercicio1.py
| 318
| 4.125
| 4
|
n = int(input("Digite a quantidade de números na sequência: "))
qtdSequencia = 0
i = 1
m = 0
while i <= n:
numeroAnterior = m
m = int(input("Digite o " + str(i) + "° número: "))
if numeroAnterior != m:
qtdSequencia = qtdSequencia+1
i = i+1
print("Quantidade de sequências: " + str(qtdSequencia))
| false
|
f4be8a4da4e64e93c42cc9d08966934f8bf49137
|
satish3366/PES-Assignnment-Set-1
|
/20_looping_structure.py
| 458
| 4.21875
| 4
|
print "The numbers from 1 to 100 skipping odd numbers using while loop is below:"
i=1
while i<=100:
if i%2!=0:
i+=1
continue
print i
i+=1
print "\n\n"
print "Breaking the for loop i ==50"
i=1
while i<=100:
if i==50:
break
print i
i=i+1
print "using continue for the values 10,20,30,40,50"
i=1
while i<=100:
if i==10 or i==20 or i==30 or i==40 or i==50:
i=i+1
continue
print i
i=i+1
print "\n"
| false
|
5a734d271228ba71cd34021f260885193bba923d
|
abbyto/QUALIFIER
|
/main.py
| 495
| 4.125
| 4
|
import difflib
words= ['i','have','want','a','test','like','am','cheese','coding','sleeping','sandwich','burger']
def word_check(s):
for word in s.casefold().split():
if word not in words:
suggestion= difflib.get_close_matches(word, words)
print(f'Did you mean {",".join(str(x)for x in suggestion)} instead of {word}?')
s = input('Input a string: ')
word_check(s)
# mod from python.org, https://docs.python.org/3/library/difflib.html
print("lol")
| true
|
eb8f14bfc5c734800d85b84ba78ad4812876c59c
|
qufengbin/python3lib
|
/text/re/re_findall_finditer.py
| 556
| 4.15625
| 4
|
# 1.3.3 多重匹配
# findall() 函数会返回输入中与模式匹配而且不重叠的所有子串。
import re
text = 'abbaaabbbbaaaaa'
pattern = 'ab'
for match in re.findall(pattern,text):
print('Found {!r}'.format(match))
# 输出
# Found 'ab'
# Found 'ab'
# finditer() 返回一个迭代器,它会生成 Match 实例,而不是返回字符串、
for match in re.finditer(pattern,text):
s = match.start()
e = match.end()
print('Found {!r} at {:d}:{:d}'.format(text[s:e],s,e))
# 输出
# Found 'ab' at 0:2
# Found 'ab' at 5:7
| false
|
7ed458e350f78585fc568c5ad7fc9913077b7890
|
BethMwangi/DataStructuresAndAlgorithms
|
/Arrays/operations.py
| 1,693
| 4.34375
| 4
|
# Accessing an element in an array
array = [9,4,5,7,0]
print (array[3])
# output = 7
# print (array[9])---> This will print "list index out of range" since the index at 9 is not available.
# Insertion operation in an array
# One can add one or more element in an array at the end, beginning or any given index
# Insertion takes two arguments, the index to insert the element and the element , i,e insert(i, element)
array = [9,4,5,7,0]
array.insert(0,3) # the zero(0) is the first index and 3 is the element
print (array) # output --> [3, 9, 4, 5, 7, 0]
array.insert(4,8)
print (array) # output --> [3, 9, 4, 5, 8, 7, 0]
# Deletion operation in an array
# Remove an exixting element in an array with the python inbult function remove()
array = [9,4,5,7,0]
array.remove(7)
print(array) # removes the number 7 specified in the function and re-organizes the array
# Search operation in an array
# the search operation searches an element based on the index given or its value
# It uses in-built python function index()
array = [9,4,5,7,0]
print (array.index(4)) # output ---> this returns 1 since index of 4 is 1
# print (array.index(3)) # output ---> this returns an ValueError since 3 is not in the array list
# Update operation in an array
# this operation updates an exixting element in the array by re-assigning a new value to an element by index.
array = [9,4,5,7,0]
array[0] = 3
print (array) # output --->[3, 4, 5, 7, 0] upadates value at index 0 to 3 and removes 9
array = [9,4,5,7,0]
# array[5] = 3 This will return an error since the index at 5 is out of range...index goes upto 4
# print (array) - IndexError: list assignment index out of range
| true
|
fae288fd0621c537a2e53d5f5b0a6c97b7f5c21a
|
rkrishan/Data_structure_program
|
/Array_rotation.py
| 383
| 4.125
| 4
|
def reverseArray(arr,start,end):
while(start<end):
temp = arr[start]
arr[start] = arr[end]
arr[end] = temp
start += 1
end = end-1
def leftRotate(arr,d):
n = len(arr)
reverseArray(arr,0,d-1)
reverseArray(arr,d,n-1)
reverseArray(arr,0,n-1)
def printArray(arr):
for i in range(0,len(arr)):
print arr[i],
arr = [1,2,3,4,5,6,7]
leftRotate(arr,2)
printArray(arr)
| false
|
b2ecec901924b48a30b420c2b87c3f9087872bd5
|
alabiansolution/python-wd1902
|
/day4/chapter7/mypackage/code1.py
| 755
| 4.4375
| 4
|
states = {
"Imo" : "Owerri",
"Lagos" : "Ikeja",
"Oyo" : "Ibadan",
"Rivers" : "Port Harcourt",
"Taraba" : "Yalingo",
"Bornu": "Maidugri"
}
def my_avg(total_avg):
'''
This function takes a list of numbers as
an argument and returns the average
of that list
'''
sum = 0
for x in total_avg:
sum += x
return sum/len(total_avg)
def multiplication(multiply_by, start=1, stop=12):
'''
This function takes three argument
the first one is the multiplication number
and it is required. The second is the start value
and is optional while the third on is stop value
and it is also optional
'''
while start <= stop:
print(multiply_by, " X ", start, " = ", multiply_by * start)
start += 1
| true
|
d9b7c5980339a47d34694780934f8828440ff379
|
666176-HEX/codewars_python
|
/Find_The_Parity_Outlier.py
| 524
| 4.5
| 4
|
"""
You are given an array (which will have a length of at least 3, but could be very large)
containing integers. The array is either entirely comprised of odd integers or entirely
comprised of even integers except for a single integer N. Write a method that takes the
array as an argument and returns this "outlier" N."""
def find_outlier(integers):
odd = sum(map(lambda x: x%2 != 0,integers[:3])) >= 2
return list(filter(lambda x: x%2 != odd, integers))[0]
print(find_outlier([160, 3, 1719, 19, 11, 13, -21]))
| true
|
053d6552e18849fe13c14f0e4d229624f1f19076
|
mohitsoni7/oops_concepts
|
/oops5_dunder_methods.py
| 2,300
| 4.40625
| 4
|
"""
Dunder methods / Magic methods / Special methods
================================================
These are special methods which are responsible for the certain types of behaviour of
objects of every class.
Also, these methods are responsible for the concept of "Operator overloading".
Operator overloading
--------------------
It means we can make operators to work for User defined classes.
For ex. "+" operator works differently for Integers and Strings.
Similarly, we can make it work in our way for our User defined Class.
__repr__ method
---------------
It gives the "Unambiguous" representation of an instance of a class.
Usually, helps and is used in debugging, logging etc.
Used by developers!
__str__ method
---------------
It gives the "End user readable" representation of an instance of a class.
Note: If __str__ method is not there then a call to __str__ method, fallback to __repr__ method.
i.e. str(emp_1) and repr(emp_1) will give the same output.
"""
class Employee:
raise_amt = 1.04
def __init__(self, firstname, lastname, pay):
self.firstname = firstname
self.lastname = lastname
self.pay = pay
self.email = firstname.lower() + '.' + lastname.lower() + '@yopmail.com'
def fullname(self):
return '{} {}'.format(self.firstname, self.lastname)
def apply_raise(self):
self.pay = (self.pay * self.raise_amt)
def __repr__(self):
return "Employee({}, {}, {})".format(self.firstname, self.lastname, self.pay)
# def __str__(self):
# return 'Employee: {}'.format(self.fullname())
# Operator overloading
# Here, we are overloading the "+" operator
# We are making it work such that if 2 instances of class Employee are added,
# there salaries are added.
def __add__(self, other):
return int(self.pay + other.pay)
def __len__(self):
return len(self.fullname())
emp_1 = Employee('Mohit', 'Soni', 70000)
print(emp_1)
print(emp_1.__repr__())
print(Employee.__repr__(emp_1))
# print(emp_1.__str__())
print(repr(emp_1))
print(str(emp_1))
emp_2 = Employee('Udit', 'Soni', 80000)
print(emp_1 + emp_2)
print(Employee.__add__(emp_1, emp_2))
print(len(emp_1))
| true
|
fdd85c2f7ee6dc32ab562ae51f844720b13b328a
|
MixFon/ExercisesForPython
|
/group_b_task24.py
| 539
| 4.15625
| 4
|
# 24. Заданы М строк слов, которые вводятся с клавиатуры.
# Подсчитать количество гласных букв в каждой из заданных строк.
m = int(input("Введите колличество строк:\n"))
for a in range(m):
string = input("Введите строку:\n")
count = 0
for c in string:
if c in "УЕЭОАЫЯИЮуеэоаыяию":
count += 1
print("Количество гласных: " + str(count))
| false
|
98d81c42b0566db41b203261e2c82d56290799b6
|
MixFon/ExercisesForPython
|
/group_b_task31.py
| 621
| 4.125
| 4
|
# 31. Заданы М строк символов, которые вводятся с клавиатуры.
# Каждая строка представляет собой последовательность символов,
# включающих в себя вопросительные знаки. Заменить в каждой строке
# все имеющиеся вопросительные знаки звёздочками.
m = int(input("Введите колличество строк :\n"))
for a in range(m):
string = input("Введите строку:\n")
print(string.replace("?", "*"))
| false
|
a47be7352926ddacb098ca2fd795af56e691c137
|
mickyaero/Practice
|
/read.py
| 951
| 4.71875
| 5
|
"""
#It imports the thing argv from the library already in the computer "sys"
from sys import argv
#Script here means that i will have to type the filename with the python command and passes this argument to the "filename"
script, filename = argv
#OPen the file and stores it in text variable
text = open(filename)
#prints the file
print "This is the file %r" %filename
#text.read(), reads the data in the file and it is then directly printed
print text.read()
#just another print statement
"""
print " Type filename again:"
#the "> " is just what you would like to show to the user to add an input, its just a bullet !!!!!!input is taken from the user in the running of the code and that is used further in the code, so basically the code halts here and takes the input, nice!!!
file_again = raw_input("> ")
#same stores the data in "text_again"
text_again = open(file_again)
#prints it
print text_again.read()
#closes the file
text_again.close()
| true
|
535282c6449efc953b8fc171d0ca08e95fb79ac2
|
DonalMcGahon/Problems---Python
|
/Smallest&Largest.Q6/Smallest&Largest.py
| 515
| 4.4375
| 4
|
# Create an empty list
lst = []
# Ask user how many numbers they would like in the list
num = int(input('How many numbers: '))
# For the amount of numbers the user wants in the list, ask them to enter a number for each digit in the list
for n in range(num):
numbers = int(input('Enter number '))
# .append adds the numbers to the list
lst.append(numbers)
# Print out the Lagest and Smallest numbers
print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :", min(lst))
| true
|
10781a10fa8cbac266fb58bcd1b87a033d2e842b
|
DonalMcGahon/Problems---Python
|
/Palindrome.Q7/Palindrome.py
| 349
| 4.59375
| 5
|
# Ask user to input a string
user_string = str(input('Enter a string to see if it is palindrome or not: '))
# This is used to reverse the string
string_rev = reversed(user_string)
# Check to see if the string is equal to itself in reverse
if list(user_string) == list(string_rev):
print("It is palindrome")
else:
print("It is not palindrome")
| true
|
df5d470412dbee029d29972f1dc66b8fe4af7912
|
bernardukiii/Basic-Python-Scripts
|
/YourPay.py
| 611
| 4.28125
| 4
|
# Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
# Use 35 hours and a rate of 2.75 per hour to test the program (the pay should be 96.25).
# You should use input to read a string and float() to convert the string to a number.
# Do not worry about error checking or bad user data.
print("Hi there, let´s calculate how much you earn per day!")
hours = int(input("How many hours do you work per day?: "))
wage = float(input("I know this is sensitive, but I need to know how much you get paid per hour: "))
print("Your pay: " + str(hours*wage))
| true
|
f1a30c8538d2717acca6a0c4a81b5dc06c2c6516
|
GitJay37/Python-Guide
|
/basic_exercises/tuples.py
| 598
| 4.46875
| 4
|
#tuple = (1,2,3,4,5,6,7,8,9,0)
#element = tuple[:9:2] # Recorre la tupla de 2 en 2 desde el prímer índice
#print(element)
# tuple[2] = 20 #los valores de una tupla no pueden modificarse
#tupla = (1,2,3,4,5)
#one, two, three, four, five = tupla
#print(one, two, three, four, five)
array = [1, 2, 3, 4, 5]
tuplas = (2, 4, 6, 8, 10)
tuplas_1 = (3, 5, 7, 9, 11)
ten, *twenty, fifty, sixty = tuplas
print(ten)
print(twenty)
print(fifty)
print(sixty)
result = zip(array, tuplas, tuplas_1 )
result = tuple(result)
test = type(result)
print(test)
print(result)
#http://docs.python.org.ar/tutorial/
| false
|
0666f9c6ddb41f8e38a846b8a53530b8aaedfe64
|
SpenceGuo/py3-learning
|
/dataType/data_type.py
| 1,403
| 4.46875
| 4
|
"""
标准数据类型
Python3 中有六个标准的数据类型:
Number(数字)
String(字符串)
List(列表)
Tuple(元组)
Set(集合)
Dictionary(字典)
Python3 的六个标准数据类型中:
不可变数据(3 个):Number(数字)、String(字符串)、Tuple(元组);
可变数据(3 个):List(列表)、Dictionary(字典)、Set(集合)
"""
counter = 100 # 整型变量
miles = 1000.0 # 浮点型变量
name = "runoob" # 字符串
"""
多个变量赋值
Python允许你同时为多个变量赋值。例如:
"""
a = b = c = 1
# 也可以为多个对象指定多个变量。例如:
d, e, f = 1, 2, "runoob"
# 复数类型:complex
g = 4 + 3j
print(type(g))
# 判断是否属于某一类型
print(isinstance(g, complex))
"""
isinstance 和 type 的区别在于:
type()不会认为子类是一种父类类型。
isinstance()会认为子类是一种父类类型。
>>> class A:
... pass
...
>>> class B(A):
... pass
...
>>> isinstance(A(), A)
True
>>> type(A()) == A
True
>>> isinstance(B(), A)
True
>>> type(B()) == A
False
"""
"""
>>> 5 + 4 # 加法
9
>>> 4.3 - 2 # 减法
2.3
>>> 3 * 7 # 乘法
21
>>> 2 / 4 # 除法,得到一个浮点数
0.5
>>> 2 // 4 # 除法,得到一个整数
0
>>> 17 % 3 # 取余
2
>>> 2 ** 5 # 乘方
32
"""
# 浮点数
number = 1.23E-5
print(number*10000)
| false
|
d80e637ccb47dfbb56eaedea3cc1549380165edc
|
asliozn/PatikaVB-PythonFinal
|
/PythonFinalProject.py
| 1,215
| 4.34375
| 4
|
"""
PROBLEM 1
Bir listeyi düzleştiren (flatten) fonksiyon yazın. Elemanları birden çok katmanlı listtlerden ([[3],2] gibi) oluşabileceği gibi, non-scalar verilerden de oluşabilir. Örnek olarak:
input: [[1,'a',['cat'],2],[[[3]],'dog'],4,5]
output: [1,'a','cat',2,3,'dog',4,5]
"""
ex_list = [[1, 'a', ['cat'], 2], [[[3]], 'dog'], 4, 5]
flatten_list = []
def flatter(l):
for i in l:
if type(i) == list:
flatter(i)
else:
flatten_list.append(i)
flatter(ex_list)
print('Flattened List: ', flatten_list)
"""
PROBLEM 2
Verilen listenin içindeki elemanları tersine döndüren bir fonksiyon yazın. Eğer listenin içindeki elemanlar da liste içeriyorsa onların elemanlarını da tersine döndürün. Örnek olarak:
input: [[1, 2], [3, 4], [5, 6, 7]]
output: [[[7, 6, 5], [4, 3], [2, 1]]
"""
my_list = [[1, 2], [3, 4], [5, 6, 7]]
def reverse(ml):
reversed_list = []
for i in ml:
if isinstance(i, list):
reversed_list.append(reverse(i))
else:
reversed_list.append(i)
reversed_list.reverse()
return reversed_list
print("Reversed List: ", reverse(my_list))
| false
|
1f85c84c848524dd0056d74fa6cb6ca3e4bbe3f2
|
pratikmahajan2/My-Python-Projects
|
/Guess The Number Game/06 GuessTheNumber.py
| 536
| 4.15625
| 4
|
import random
my_number = random.randint(0,100)
print("Please guess my number - between 0 and 100: ")
while True:
your_number = int(input(""))
if your_number > 100 or your_number < 0:
print("Ohhoo! You need to enter number between 0 and 100. Try again")
elif (your_number > my_number):
print("Your guess is greater than my number. Try again")
elif (your_number < my_number):
print("Your number is less than my number. Try again" )
else:
print("Your won. My number is: ", my_number)
break
| true
|
9c790eb1bf7fd97ea3d02439d5335f6e09c293ec
|
Kenkiura/pyintro
|
/data structures in python.py
| 914
| 4.34375
| 4
|
#Lists
list1=[1,2,3,4,5,6]
print(list1[3])
print (list1[0])
print (list1[-2])
days=["mon","tue","wed","thur","fri","sat","sun"]
print (days[5:7])
print (days[5:])
print (days[5:6])
print (days[0:3])
print (days[:3])
print (type(list1))
list1.append(7)
print (list1)
print (list1.index(7))
list1.pop()
print (list1)
list1[5]="nikoradar!!"
print(list1)
list1[3]=[]
print (list1)
list1[3]=""
print (list1)
#Tuples
month=("jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec")
print(month[2])
#month[2]=["jul"]
print (month)
#month.append(dec)
print(month)
print(len(month))
test = (1,2,3,[4,5,6])
print(test)
print(test[3])
test[3][1]=7
print(test[3])
#tuple structure can't be changed because it's immutable but if there's a mutable object in the tuple like a list, the list can be changed
#Nesting
list2=[1,2,[3,4,[5,6,[7,8]]]]
print(len(list2))
print(list2[2][2][2][1])
| false
|
924fde1d0ded0a114f314cfe2560672f7736a629
|
Theodora17/TileTraveller
|
/tile_traveller.py
| 1,911
| 4.46875
| 4
|
# Functions for each movement - North, South, East and West
# Function that updates the position
# Function that checks if the movement wanted is possible
def north(first,second) :
if second < 3 :
second += 1
return first, second
def south(first,second) :
if second > 1 :
second -= 1
return first, second
def west(first,second) :
if first > 1 :
first -= 1
return first, second
def east(first,second) :
if first < 3 :
first += 1
return first, second
def read_choice():
choice = input("Direction: ").lower()
return choice
def get_valid_direction(first, second):
if first == 1 and second == 1:
print("You can travel: (N)orth")
elif first == 2 and second == 1:
print("You can travel: (N)orth")
elif first == 1 and second == 2:
print("You can travel: (N)orth or (E)ast or (S)outh")
elif first == 1 and second == 3:
print("You can travel: (E)ast or (S)outh")
elif first == 2 and second == 3:
print("You can travel: (W)est or (E)ast")
elif first == 2 and second == 2:
print("You can travel: (W)est or (S)outh")
elif first == 3 and second == 3:
print("You can travel: (W)est or (S)outh")
elif first == 3 and second == 2:
print("You can travel: (N)orth or (S)outh")
elif first == 3 and second == 1:
print("Victory!")
else:
print("Not a valid direction!")
return first, second
def main():
first = 1
second = 1
victory = False
while victory == False:
valid_direction = get_valid_direction(first, second)
choice = read_choice()
if choice == "n":
north(first, second)
elif choice == "s":
south(first, second)
elif choice == "w":
west(first, second)
elif choice == "e":
east(first, second)
main()
| true
|
58872f4d3554c2849ffeb4c978451bfbf415cfb3
|
mparker24/EvensAndOdds-Program
|
/main.py
| 622
| 4.25
| 4
|
#This asks the user how many numbers they are going to input
question = int(input("How many numbers do you need to check? "))
odd_count = 0
even_count = 0
#This asks for a number and outputs whether its even or odd
for i in range(question):
num = int(input("Enter number: "))
if (num % 2) == 0:
print(f"{num} is an even number")
even_count = even_count + 1
else:
print(f"{num} is an odd number")
odd_count = odd_count + 1
#This outputs how many even numbers and how many odd numbers you've inputted
print(f"You entered {even_count} even number(s)")
print(f"You entered {odd_count} odd number(s)")
| true
|
50934c184a7b7248bfae0bdcfba6c6a002d38f59
|
erikseyti/Udemy-Learn-Python-By-Doing
|
/Section 2 - Python Fundamentals/list_comprehension.py
| 766
| 4.46875
| 4
|
# create a new list with multiples by 2.
numbers = [0,1,2,3,4]
doubled_numbers = []
# a more simple way with a for loop
# for number in numbers:
# doubled_numbers.append(number *2)
# print(doubled_numbers)
# with list comprehension:
doubled_numbers = [number *2 for number in numbers]
print(doubled_numbers)
# using range of numbers:
doubled_numbers = [number *2 for number in range(5)]
print(doubled_numbers)
# You can use any number on the parameter that will be in the for loop of the list comprehension
# obviously the word number is not used, in this context
doubled_numbers = [5 for number in range(5)]
# In cases like this you can see programmers using a _ on the name of the variable
# doubled_numbers = [5 for _ in range(5)]
print(doubled_numbers)
| true
|
f3b0cd25318048ca749c91aecd7ee53e36327221
|
sloaneluckiewicz/CSCE204
|
/CSCE204/exercises/mar9/functions3.py
| 1,190
| 4.28125
| 4
|
def factorial():
num = int(input("Enter number: "))
answer = 1
# error invalid input return = takes you out of the function
if num < 1:
print("Invalid number")
return
for i in range(1, num+1):
answer *= i
print(f"{num}! = {answer}")
def power():
base = int(input("Enter number for base: "))
exponent = int(input("Enter number for exponent: "))
answer = 1
if base < 1 or exponent <1:
print("invalid input")
return
# loop through and caluculate answer, then display it
for i in range(exponent):
answer *= base
print(f"{base}^{exponent} = {answer}")
def sum():
number = int(input("Enter number to sum: "))
ans = 0
for i in range(1, number+1):
ans += i
print(f"The sum of {number} = {ans}")
# program
print("Welcome to Math!")
while True:
command = input("Compute (F)actotial, (S)um, (P)ower, or (Q)uit: ").strip() .lower()
if command == "q":
break
elif command == "f":
factorial()
elif command == "s":
sum()
elif command == "p":
power()
else:
print("Invalid input")
print("Goodbye!")
| true
|
67b96044ffc12ef97b3cefb858bbe5fa8aa3a8fd
|
sloaneluckiewicz/CSCE204
|
/CSCE204/exercises/feb2/for-loop1.py
| 888
| 4.21875
| 4
|
""" count from 1 to 10
for i in range (1,11): # add another number to desired end
print(i)
"""
""" loop counting by 2s
for i in range (2,21,2): # last parameter will indicate what you will go by called the STEP
print(i)
"""
""" loop from 10 to 1
for i in range (10,0,-1):
print(i)
"""
"""
# sum the numbers 1 through 10
sum = 0
for i in range (1,11):
sum += i
print(f"Sum of numbers 1 through 10: {sum} ")
"""
"""
# sum the numbers 1 through user end
sum = 0
userNum = int(input("Enter number : "))
for i in range(1,userNum + 1):
sum += i
print(f"Sum of numbers 1 through {userNum}: {sum} ")
"""
# sum the numbers user start through user end
sum = 0
userStart = int(input("Enter start number: "))
userEnd = int(input("Enter end number: "))
for i in range(userStart,userEnd + 1):
sum += i
print(f"Sum of numbers {userStart} through {userEnd}: {sum} ")
| false
|
e8ba520b71bcb4af787d39ad3bca0521c806c433
|
sloaneluckiewicz/CSCE204
|
/CSCE204/exercises/feb23/mult_tables.py
| 449
| 4.125
| 4
|
# multiplication table
"""
1 2 3 4 5
1 4 6 8 10
"""
tableSize = int(input("Enter size of table: "))
for row in range(1, tableSize+1): # loop through rows
for col in range(1, tableSize+1): # for every row loop their cols
ans = row * col
# if there is just one digit in the number
if len(str(ans)) == 1:
print(f" {ans}", end= " ")
else:
print(ans, end = " ")
print()
| true
|
a045dbbf26ee8600be9bbd207a535cab0d4b25b7
|
sloaneluckiewicz/CSCE204
|
/CSCE204/exercises/mar4/birthdays2.py
| 926
| 4.1875
| 4
|
# list birthdays and find closest birthday coming up
from datetime import date
birthdays = {
"Sloane": date(2021, 2, 16),
"Camille": date(2021, 9, 3),
"Jane": date(2021, 7, 10),
"Kaden": date(2021, 10, 28),
"Treyten": date(2021, 10,9),
"Mamacita": date(2021, 5, 6),
"Remi": date(2021, 5, 25),
"Mason": date(2021, 8, 8)
}
closestBirthday = date(2021,12,31)
closestFriend = ""
for person in birthdays:
birthday = birthdays[person]
daysTillClosest = (closestBirthday - date.today()).days
daysTillBirthday = (birthday - date.today()).days
# birthday already passed
if daysTillBirthday < 0:
continue
#go to next item in list --> back to beginning of for loop
if daysTillBirthday < daysTillClosest:
closestBirthday = birthday
closestFriend = person
print(f"Closest birthday is: {closestFriend} " + closestBirthday.strftime("%m/%d/%y"))
| false
|
09c598aa5bfd2a7489b5e30d6723ae6a39cdc04a
|
ceeblet/OST_PythonCertificationTrack
|
/Python1/python1/space_finder.py
| 287
| 4.15625
| 4
|
#!/usr/local/bin/python3
"""Program to locate the first space in the input string."""
s = input("Please enter a string: ")
pos = 0
for c in s:
if c == " ":
print("First space occurred at position", pos)
break
pos += 1
else:
print("No spaces in that string.")
| true
|
5bbd0ab39d4112ccac8775b398c37f8f13f42345
|
ceeblet/OST_PythonCertificationTrack
|
/Python1/python1/return_value.py
| 1,259
| 4.375
| 4
|
#!/usr/local/bin/python3
def structure_list(text):
"""Returns a list of punctuation and the location of the word 'Python' in a text"""
punctuation_marks = "!?.,:;"
punctuation = []
for mark in punctuation_marks:
if mark in text:
punctuation.append(mark)
return punctuation, text.find('Python')
text_block = """\
Python is used everywhere nowadays.
Major users include Google, Yahoo!, CERN and NASA (a team of 40 scientists and engineers
is using Python to test the systems supporting the Mars Space Lander project).
ITA, the company that produces the route search engine used by Orbitz, CheapTickets,
travel agents and many international and national airlines, uses Python extensively.
The YouTube video presentation system uses Python almost exclusively, despite their
application requiring high network bandwidth and responsiveness.
This snippet of text taken from chapter 1"""
for line in text_block.splitlines():
print(line)
p, l = structure_list(line)
if p:
print("Contains:", p)
else:
print("No punctuation in this line of text")
if ',' in p:
print("This line contains a comma")
if l >= 0:
print("Python is first used at {0}".format(l))
print('-'*80)
| true
|
ed5388f3c390d596cd6a2927960cf28e0065d8d2
|
ceeblet/OST_PythonCertificationTrack
|
/Python1/python1Homework/caserFirst.py
| 1,284
| 4.34375
| 4
|
#!/usr/local/bin/python3
""" caser.py """
import sys
def capitalize(mystr):
""" capitalize(str) - takes a string
and returns the string with first letters
capitalized.
"""
print(mystr.capitalize())
def title(mystr):
""" title(str) - takes a string and
returns the string in title form.
"""
print(mystr.title())
def upper(mystr):
""" upper(str) - takes a string and
makes it all caps.
"""
print(mystr.upper())
def lower(mystr):
""" lower(str) - takes a string and
makes it all lowercase.
"""
print(mystr.lower())
def exit(mystr):
""" exit() - ends the program."""
sys.exit()
if __name__ == "__main__":
switch = {
'capitalize': capitalize,
'title': title,
'upper': upper,
'lower': lower,
'exit': exit
}
options = switch.keys()
while True:
prompt1 = 'Enter a function name ({0}) '.format(', '.join(options))
prompt2 = 'Enter a string: '
inp1 = input(prompt1)
inp2 = input(prompt2)
option = switch.get(inp1, None)
inpstr = inp2
if option:
option(inpstr)
print("-" * 30)
else:
print("Please enter a valid option!")
| true
|
5598cd6a08c5925a4820f48bd8813d0509d26fcb
|
idealley/learning.python
|
/udacity-examples/leap_pythonic.py
| 258
| 4.21875
| 4
|
def is_leap_baby(year):
if ((year % 4 is 0) and (year % 100 is not 0)) or (year % 400 is 0):
return "{0}, {1} is a leap year".format(True, year)
return "{0} is not a leap year".format(year)
print(is_leap_baby(2014))
print(is_leap_baby(2012))
| false
|
4c490de53e3bed60e94a60e4229cffb4181d7ed8
|
dotnest/pynotes
|
/Exercises/swapping_elements.py
| 284
| 4.21875
| 4
|
# Swapping list elements
def swap_elements(in_list):
""" Return the list after swapping the biggest integer in the list
with the one at the last position.
>>> swap_elements([3, 4, 2, 2, 43, 7])
>>> [3, 4, 2, 2, 7, 43]
"""
# your code here
| true
|
15352584fbdce193854661aacf3b73826e716db8
|
paweldunajski/python_basics
|
/12_If_Statements.py
| 462
| 4.25
| 4
|
is_male = True
if is_male:
print("You are a male")
is_male = False
is_tall = False
if is_male or is_tall:
print("You are male or tall or both")
else:
print("You are not a male nor tall ")
if is_male and is_tall:
print("You are male and tall")
elif is_male and not is_tall:
print("You are male but not tall")
elif not is_male and is_tall:
print("You are not a male but are not tall")
else:
print("you are not a male and not tall")
| false
|
d859287b31a1883963543dea6c9f335ade0c0755
|
Jokekiller/Theory-Programmes
|
/Program converting ASCII to text and other way.py
| 956
| 4.125
| 4
|
#Harry Robinson
#30-09-2014
#Program converting ASCII to text and other way
print("Do you want to convert an ASCII code ? (y/n)")
response = input()
if response == "y":
ASCIINumber = int(input("Give an ASCII number"))
ASCIINumberConverted = chr(ASCIINumber)
print("The ASCII number is {0} in text characters.".format(ASCIINumberConverted))
if response == "n":
print("Do you want to convert a text character? (y/n)")
response2 = input()
if response2 == "y":
<<<<<<< HEAD
textNumber = input("Give text character: ")
textNumberConverted = ord(textNumber)
print("The ASCII code is {0}".format(textNumberConverted))
=======
textNumber = int(input("Give text character"))
textNumberConverted = ord(textNumber)
print("Text character is {1}".format(textNumberConverted))
>>>>>>> branch 'master' of https://github.com/Jokekiller/Theory-Programmes.git
| true
|
0f4085b0b240aab78424953c0a66eeb09e6b019e
|
krouvy/Useless-Python-Programms.-
|
/18 - Checking the list for parity/pop_break.py
| 707
| 4.21875
| 4
|
"""
This program checks the list
items for odd parity. If all
elements are even, then the list
will be empty. Because the "pop ()"
method cuts out the last item from the list.
"""
List = list(map(int, input("Enter your digit values ").split())) # Entering list items separated by a space
while len(List) > 0: # Execute as long as the length of the list is greater than zero
last = List.pop() # Cuts last element of List, and record in variable "last"
if last % 2 != 0: # if variable "last" is not even
print("Number", last, "is not even") # print this value
break # Exit the loop
else:
print("All numbers are even") # else print message
print(List) # and empty list
| true
|
4e93aec8e1cf56a3fc4610ac438fb50d77a856b8
|
yding57/CSCI-UA-002
|
/Lecture 3.py
| 2,238
| 4.15625
| 4
|
#Data types
# "=" is an assignment operator
# x=7+"1.0" this is ERROR
answer = input("Enter a value: ")
print(answer,type(answer))
n1 = input("Number 1: ")
n2 = input('Number 2: ')
#convert this into an integer
n1_int = int(n1)
n2_int = int(n2)
print(n1_int + n2_int)
#different from:
print(n1 + n2)
#简便convert的方法:nesting
x = int(input('Enter a number: ')) #注:there are two parentheses
#Programming Challenge
#ask the user for their name
name = input("Name: ")
#ask the user for 3 test scores
score1 = float(input ("Enter score 1: "))
#the user input mismatch the converting data type can crash the program
score2 = float(input ("Enter score 2: "))
score3 = float(input ("Enter score 3: "))
#compute sum of scores
total = score1 + score2 + score3
#compute average
average = total/3
#generate output
print("Your score in class is",average)
#Programming challenge -coin
#ask the user for the number of coins they have
#pennies
#nickels
#dimes
#quarters
pennies = int(input("Pennies: "))
nickels = int(input("Nickels: "))
dimes = int(input("Dimes: "))
quarters = int(input("Quarters: "))
#somehow convert these coins into currency
money = pennies*0.01 + nickels *0.05 + dimes*0.1 + quarters *0.25
#generate output
print('You have',money,'in your pocket!')
Weired Issue:
Pennies: 3
Nickels: 2
Dimes: 2
Quarters: 1
You have 0.5800000000000001 in your pocket
This is due to the "floating point inaccuracy"
#Errors:
#Syntax errors: didn't use your laguage right
#Runtime errors: laguage is fine, but the program crashed (usually, problem with user input)
#Logic errors: sytax-correct, runs perfectly but the result is not expected
#Metro Card program
card = float(input("How much is left on your card: "))
#compute the left rides
rides_left =int(card//2.75) # // or int()
print(rides_left)
#Time Calculations
seconds = int(input('Enter second: '))
#compute minutes
minutes = seconds // 60
reminder_seconds = seconds % 60
hours = minutes//60
reminder_minutes = minutes % 60
print("That is",hours,"hours",reminder_minutes,"minutes",reminder_seconds,"seconds")
#Format functions
format(52752.3242,".2f")#generates string
money = 100.70
money_format= format(100.70,".2f") #perserve your insignificant 0s
| true
|
607b6d533f1ac9a6ca74f04edcb43f50ad164b4d
|
AMRobert/Word_Counter
|
/WordCounter_2ndMethod.py
| 268
| 4.1875
| 4
|
#WORD COUNTER USING PYTHON
#Read the text file
file = open(r"file path")
Words = []
for i in file:
Words.extend(i.split(" "))
print(Words)
#Count the Number of Words
Word_Count=0
for x in range(len(Words)):
Word_Count = Word_Count + 1
print(Word_Count)
| true
|
8f896b4284f1f648ebf70b8d147ab87265a707f6
|
chudierp/theflowergarden
|
/flowergarden/idea.py
| 780
| 4.1875
| 4
|
import turtle as t
# draw a simple rectangle car with two wheels.
def draw_flower(x,y):
t.penup()
t.setheading(90)
t.goto(x,y)
t.pendown()
t.pencolor("green")
t.pensize(20)
t.left(90)
t.backward(150)
t.forward(150)
t.pencolor("orange")
t.pensize(15)
num_petals = 8
num_degrees = int(360/8)
for i in range(num_petals):
t.forward(50)
t.backward(50)
t.left(num_degrees)
t.pencolor("brown")
t.dot(20)
t.penup()
t.setheading(90)
t.goto(x+200,y)
t.pendown()
t.pencolor("blue")
t.pensize(15)
num_petals = 8
num_degrees = int(360/8)
for i in range(num_petals):
t.forward(50)
t.backward(50)
t.left(num_degrees)
t.pencolor("yellow")
t.dot(20)
#call draw_flower
draw_flower(0,0)
| false
|
b4ad1c25c8d0ecee08a1a48787fb7c116bcba965
|
igotboredand/python-examples
|
/loops/basic_for_loop.py
| 514
| 4.59375
| 5
|
#!/usr/bin/python3
#
# Python program to demonstrate for loops.
#
# The for loop goes through a list, like foreach in
# some other languages. A useful construct.
for x in ['Steve', 'Alice', 'Joe', 'Sue' ]:
print(x, 'is awesome.')
# Powers of 2 (for no obvious reason)
power = 1
for y in range(0,25):
print("2 to the", y, "is", power)
power = 2 * power
# Scanning a list.
fred = ['And', 'now', 'for', 'something', 'completely', 'different.'];
for i in range(0,len(fred)):
print(i, fred[i])
| true
|
00587653e7706bed6683f00538a9e22f00590cdc
|
FengdiLi/ComputationalLinguistic
|
/update automation/menu_update.py
| 2,857
| 4.15625
| 4
|
#!/usr/bin/env python
import argparse
import re
def main(old_menu, new_menu, category_key, update_key):
"""This main function will read and create two dictionaries
representing the category keys and update keys, then check and
update the price according to its multiplier if the item is
associated with a category stated in category keys"""
new_menu_lines = []
# add code to read the old menu and look for items with price updates
#########################################################################
# define a function to check and update the price in a line
def update(line, keys, cats):
for key in keys:
# search item
if re.search(f'(^|\W){key}($|\W)', line):
# retrieve price
m = re.match('.*\$(\d+(?:\.\d+)?).*', line)
if m:
# update and format price
price = f'{float(m.group(1))*cats[keys[key]]:.2f}'
result = re.sub('\$\d+(\.\d+)?', f'${price}', line)
return result
return line
# initiate category keys
d = {}
with open(category_key, 'r') as cat:
for line in cat:
line = line.strip().split('\t')
d[line[0]] = line[1]
# initiate category updates
d2 = {}
with open(update_key, 'r') as cat:
for line in cat:
line = line.strip().split('\t')
d2[line[0]] = float(line[1])
# update menu line by line
with open(old_menu, 'r') as orig_menu:
for line in orig_menu:
new_line = update(line, d, d2)
new_menu_lines.append(new_line)
# write a new file with your updates
# 'newline' set each ending as LF match the format of example
with open(new_menu, 'w', newline = '\n') as new_menu_out:
for line in new_menu_lines:
new_menu_out.write(line)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Update a menu')
parser.add_argument('--path', type=str, default="practice_menu.txt",
help='path to the menu to update')
parser.add_argument('--output_path', type=str, default="practice_menu_new.txt",
help='path to write the updated menu')
parser.add_argument('--category_key', type=str, default="item_categories.txt",
help='path to the key to item categories')
parser.add_argument('--update_key', type=str, default="category_update.txt",
help='path to the key to item categories')
args = parser.parse_args()
old_menu = args.path
new_menu = args.output_path
category_key = args.category_key
update_key = args.update_key
main(old_menu, new_menu, category_key, update_key)
| true
|
6172e61f25108eec6aee06c155264e74441ee10c
|
bacizone/python
|
/ch5-bubble-report.py
| 2,046
| 4.3125
| 4
|
#Pseudocode for Ch5 2040 excercise
#First we have a list with solutions and their scores. We are writing a loop where it iterates until all solution -score pair are output to the screen.
#Second: using the len function we display the total number of bubble tests, that is the number of elements in the list.
#Then we need a kind of ordering algorithm, that compares the score values and select the highest. Possible solution: 1. sort the list by increasing values and select its last item (the highest) 2. always compare two values, select the highest and compare it to the next value, until there is no higher value left.
# Display the list indices assigned to the highest values - how?
scores = [60, 50, 60, 58, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52, 44, 51, 69, 64, 66, 55, 52, 61, 46, 31, 57, 52, 44, 18, 41, 53, 55, 61, 51, 44]
costs = [.25, .27, .25, .25, .25, .33, .31, .25, .29, .27, .22, .31, .25, .25, .33, .21, .25, .25, .25, .28, .25, .24, .22, .20, .25, .30, .25, .24, .25, .25, .25, .27, .25, .26, .29]
# i = 0
length = len(scores)
high_score = 0
# this was a less efficient method
# while i < length:
# bubble_string = 'Bubble solution #'+ str(i)
# print(bubble_string, 'score:', scores[i])
# i = i + 1
for i in range(length):
bubble_string = 'Bubble solution #'+ str(i)
print(bubble_string, 'score:', scores[i])
if scores[i] > high_score:
high_score = scores[i]
print('Bubble test:', length)
print('Highest bubble score:', high_score)
# best_solutions = []
# if scores[i] == high_score:
# for j in range(high_score):
# best_solutions.append(high_score)
best_solutions = []
for i in range(length):
if high_score == scores[i]:
best_solutions.append(i)
print('Solutions with highest score:', best_solutions)
cost = 100.0
most_effective = 0
for i in range(length):
if scores[i] == high_score and costs[i] < cost:
most_effective = i
cost = costs[i]
print('Solution', most_effective, 'is the most effective with a cost of', costs[most_effective])
| true
|
b3f3acc08c5777696db004a6ccabcb09c1dd3c36
|
kirankumarcs02/daily-coding
|
/problems/exe_1.py
| 581
| 4.125
| 4
|
'''
This problem was recently asked by Google.
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
'''
def checkSumPair(input, k):
givenNumbers = set()
for number in input:
if (k - number) in givenNumbers:
return True
else:
givenNumbers.add(number)
return False
if __name__ == "__main__":
input = [10, 15, 3, 7]
k = 17
print(checkSumPair(input, k))
| true
|
bc4126d785715c1aebf52f99fbafea90fc21f6fe
|
kirankumarcs02/daily-coding
|
/problems/exe_40.py
| 704
| 4.1875
| 4
|
# This problem was asked by Google.
#
# Given an array of integers where every integer occurs three
# times except for one integer, which only occurs once,
# find and return the non-duplicated integer.
#
# For example, given [6, 1, 3, 3, 3, 6, 6],
# return 1. Given [13, 19, 13, 13], return 19.
def get_non_duplicate(arr):
non_duplicate = 0
number_count = dict()
for i in arr:
if i in number_count:
number_count[i] +=1
else:
number_count[i] = 1
for key in number_count.keys():
if number_count[key] == 1:
non_duplicate = key
return non_duplicate
if __name__ == "__main__":
print(get_non_duplicate([13, 19, 13, 13]))
| true
|
63c881db45cfac236675707f637c29c74f86d257
|
bhanuxhrma/learn-python-the-hard-way
|
/ex16.py
| 882
| 4.1875
| 4
|
from sys import argv
script, filename = argv
#some important file operations
#open - open the file
#close - close the file like file -> save ...
#readline - read just one line of the text
#truncate - Empties the file watch out if you care about file
#write('stuff') - write "stuff" to the file
print("we are going to erase %r"%filename)
print("If you do not want that hit ctrl-C(^C)")
print("If you want to continue hit return")
input("?")
print("opening the file.....")
target = open(filename, 'w')
print("truncating the file. Goodbye!")
target.truncate()
print("Now I'm going to ask you for three lines")
line1 = input('line1: ')
line2 = input('linw2: ')
line3 = input('line3: ')
print("now I'm going to write these to file")
target.write(line1)
target.write('\n')
target.write(line2)
target.write('\n')
target.write(line3)
print("And finally we close it.")
target.close()
| true
|
d0fc479f5b2b320c371912a327272c14266d47d3
|
lmsullivan18/Election_Analysis
|
/analysis/Class.py
| 549
| 4.15625
| 4
|
import random
print("Let's Play Rock Paper Scissors!")
# Specify the three options
options = ["r", "p", "s"]
# Computer Selection
computer_choice = random.choice(options)
# User Selection
user_choice = input("Make your Choice: (r)ock, (p)aper, (s)cissors? ")
if user_choice = computer_choice:
print("Tie!")
elif user_choice == "r" and computer_choice == "s":
print("User wins!")
elif user_choice == "r" and computer_choice == "p":
print("Computer winS!")
elif user_choice == "p" and computer_choice == "r":
print("")
| false
|
87b94b13d0d6c77a0949ae957847909804dfbc2f
|
deepakmarathe/whirlwindtourofpython
|
/operators/bitwise_operators.py
| 408
| 4.3125
| 4
|
# a & b bitwise and
# a | b bitwise or
# a ^ b bitwise xor
# a << b bitwise leftshift
# a >> b bitwise rightshift
# ~a bitwise not
# bitwise operators make sense on binary numbers, obtained by 'bin' method
print "10 in binary : ", bin(10)
print "4 in binary : ",bin(4)
# find out the number which combines the bits in 4 and 10.
print "(4 | 10) : ", 4 | 10
print "(4 | 10) in binary : ", bin(4 | 10)
| false
|
fd25c5909d3329a11e7eed49c14d08dfbf81ec95
|
deepakmarathe/whirlwindtourofpython
|
/string_regex/regex_syntax.py
| 1,772
| 4.21875
| 4
|
# Basics of regular expression syntax
import re
# Simple strings are matched directly
regex = re.compile('ion')
print regex.findall('great expectations')
# characters with special meanings
# . ^ $ * + ? { } [ ] \ | ( )
# Escaping special characters
regex = re.compile('\$')
print regex.findall(r"the cost is $100")
print "standard python strings : ", "a\tb\tc"
print "raw python strings : ", r"a\tb\tc"
# Special characters can match character groups
regex = re.compile('\w\s\w')
print regex.findall('the fox is 9 years old')
# \d match any digit
# \D match any non-digit
# \s match any whitespace
# \S match any non-whitespace
# \w match any alphanumeric character
# \W match any non-alphanumeric character
# Square brackets match custom character groups
regex = re.compile('[aeiou]')
print regex.split('consequential')
regex = re.compile('[A-Z][0-9]')
print regex.findall('1043, G2, H6')
# Wildcard match repeated characters
regex = re.compile(r"\w{3}")
print regex.findall('The quick brown fox')
regex = re.compile('\w+')
print regex.findall("The quick brown fox")
# Table of repitition markers
# ? Match 0 or 1 repetitions of proceeding
# * Match 0 or more repetitions of preceeding
# + match 1 or more repetitions of the preceeding
# {n} Match n repetitions of the preceeding
# {m, n} Match between m and n repetitions of proceeding
email2 = re.compile(r'[\w+.]+@\w+\.[a-z]{3}')
print email2.findall('barack.obama@whitehouse.gov')
# Paranthesis indicate groups to extract
email3 = re.compile('([\w+.]+)@(\w+)\.([a-z]{3})')
text ="To email Guido, try guido@python.org or the older address guido@google.com"
print email3.findall(text)
# We can even name the groups
email4 = re.compile('(?P<name>[\w+.]+)@(?P<domain>\w+)\.(?P<suffix>[a-z]{3})')
print email4.findall('guido@python.org')
| true
|
956d7b394457b2fd9526f13206e366a59788cbfd
|
mbrownlee/Python-Bk1Chp6
|
/zoo.py
| 886
| 4.15625
| 4
|
flowers = ("daisy", "rose")
print(flowers.index("rose")) # Output is 1
zoo = ("panda", "polar bear", "giraffe", "llama", "monkey", "kangaroo", "cheetah", "tiger", "sloth", "turtle")
print(zoo.index("tiger"))
print(zoo[7])
if "kangaroo" in zoo:
print("Animal is present")
(first_animal, second_animal, third_animal, fourth_animal, fifth_animal, sixth_animal, seventh_animal, eigth_animal, ninth_animal, tenth_animal ) = zoo
print(first_animal)
print(second_animal)
print(third_animal)
print(fourth_animal)
print(fifth_animal)
print(sixth_animal)
print(seventh_animal)
print(eigth_animal)
print(ninth_animal)
print(tenth_animal)
# bigger_zoo = zoo + ("jaguar", "gorilla", "peguin")
# print(bigger_zoo)
zoo = list(tuple(zoo))
print("list:", zoo)
more = ["jaguar", "gorilla", "penguin"]
zoo.extend(more)
print("extended list:", zoo)
zoo = tuple(list(zoo))
print("tuple again:", zoo)
| false
|
380cccfd40ee68bf5ffa1a99d145cffcd1fa6d4b
|
TETSUOOOO/usercheck
|
/passwordDetect.py
| 1,058
| 4.4375
| 4
|
#! python3
# passwordDetect.py - Ensures that password is 8 characters in length, at least one lowercase and one uppercase letter,
# and at least one digit
# saves accepted passwords into a json file
import json, re
filename = 'passwords.json'
def passwordDetector(text):
"""Uses a regex to parse the user input containing the password"""
passRegEx = re.compile(r'[a-z{1,6}A-Z{1,6}0-9+]{8}')
passObject = passRegEx.search(text)
try:
passObject.group()
except AttributeError:
print('Your password is not secure!')
text = input('Please re-enter password>')
passwordDetector(text)
else:
print('Your password is secure! Please confirm password>')
confirmed = input()
if confirmed == text:
with open(filename, 'a') as pass_obj:
json.dump(text, pass_obj)
print('Password is saved!')
else:
print('Does not match! Please try again.')
text = input('Please re-enter password>')
passwordDetector(text)
| true
|
c23b9c26d90994d5aac03bdeb8cf2c038762336c
|
davekunjan99/PyPractice
|
/Py6.py
| 218
| 4.28125
| 4
|
string = str(input("Enter a string: "))
revString = string[::-1]
if(string == revString):
print("Your string " + string + " is palindrome.")
else:
print("Your string " + string + " is not palindrome.")
| true
|
659de313db36bb521842ba837228b6fd87d66b52
|
davekunjan99/PyPractice
|
/Py11.py
| 455
| 4.375
| 4
|
num = int(input("Please enter a number: "))
def checkPrime(num):
isPrime = ""
if num == 1 or num == 2:
isPrime = "This number is prime."
else:
for i in range(2, num):
if num % i == 0:
isPrime = "This number is not prime."
break
else:
isPrime = "This number is prime."
return isPrime
##while(num != 0):
checkPrime = checkPrime(num)
print(checkPrime)
| true
|
f5686d3db18f0f77a679085954f752e648f8e5f4
|
mjixd/helloworld-sva-2018
|
/week2/mjstory.py
| 1,551
| 4.5
| 4
|
# let the user know what's going on
print ("Welcome to MJ World!")
print ("Answer the questions below to play.")
print ("-----------------------------------")
# variables containing all of your story info
adjective1 = raw_input("Enter an adjective: ")
food1 = raw_input("What is your favorite food?: ")
location1 = raw_input("Name a place: ")
object1 = raw_input("An object from New Yok City: ")
famousPerson1 = raw_input("A famous person you don't really like: ")
famousPerson2 = raw_input("A famous person you sort of like, but not you're favorite: ")
yourName = raw_input("What's your name?: ")
adjective2 = raw_input("Enter favorite adjective: ")
# this is the story. it is made up of strings and variables.
# the \ at the end of each line let's the computer know our string is a long one
# (a whole paragraph!) and we want to continue more code on the next line.
# play close attention to the syntax!
story = "A traveler" + adjective1 + " good " + food1 + " sushi " + location1 + ", japanese sushi restaurant " \
"providing a " + object1 + " for meals which she has made by " + famousPerson1 + ". " \
"This is an " + adjective2 + " sushi with sushi with fish egges in it made in "
+ yourName + " incredibly the most delicious recipe. " \
"" + yourName + " then have a sweet potato ice cream with roasted rice tea. " \
"the food is beautifully arranged as much as they are delicious " + food1 + " too sweet things are sent by " + famousPerson2 + " " \
"to eat some food back to " + yourName + "."
# finally we print the story
print (story)
| true
|
e90ff02843379fd3ff97a9ff61ab7fc351039e03
|
binthafra/Python
|
/2-Python Basics 2/6-iterable.py
| 422
| 4.1875
| 4
|
#iterable -list ,dict,tuple,set,string
# iterable ->ono by one check each item in the collection
user = {
'name': "afra",
'age': 20,
'can_swim': False
}
# print only keys
for item in user:
print(item)
for item in user.keys():
print(item)
# print key and value
for item in user.items():
print(item)
for item in user.values():
print(item)
for key, value in user.items():
print(key, value)
| true
|
6cc518e1a3e69721374315bcced5aed005cb4d75
|
jwodder/euler
|
/digits/euler0055.py
| 1,808
| 4.125
| 4
|
#!/usr/bin/python
"""Lychrel numbers
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
Not all numbers produce palindromes so quickly. For example,
349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337
That is, 349 took three iterations to arrive at a palindrome.
Although no one has proved it yet, it is thought that some numbers, like
196, never produce a palindrome. A number that never forms a palindrome
through the reverse and add process is called a Lychrel number. Due to the
theoretical nature of these numbers, and for the purpose of this problem, we
shall assume that a number is Lychrel until proven otherwise. In addition
you are given that for every number below ten-thousand, it will either (i)
become a palindrome in less than fifty iterations, or, (ii) no one, with all
the computing power that exists, has managed so far to map it to a
palindrome. In fact, 10677 is the first number to be shown to require over
fifty iterations before producing a palindrome: 4668731596684224866951378664
(53 iterations, 28-digits).
Surprisingly, there are palindromic numbers that are themselves Lychrel
numbers; the first example is 4994.
How many Lychrel numbers are there below ten-thousand?
NOTE: Wording was modified slightly on 24 April 2007 to emphasise the
theoretical nature of Lychrel numbers."""
__tags__ = ['digits', 'palindromic number', 'iterated functions']
def solve():
qty = 0
for i in xrange(1, 10000):
istr = str(i)
for _ in xrange(49):
i += int(istr[::-1])
istr = str(i)
if istr == istr[::-1]:
break
else:
qty += 1
return qty
if __name__ == '__main__':
print solve()
| true
|
3ade90c1e0cac84869460cd0aa453552002528d5
|
jwodder/euler
|
/euler0173.py
| 1,745
| 4.15625
| 4
|
#!/usr/bin/python
"""Using up to one million tiles how many different "hollow" square laminae can
be formed?
We shall define a square lamina to be a square outline with a square "hole"
so that the shape possesses vertical and horizontal symmetry. For example,
using exactly thirty-two square tiles we can form two different square
laminae:
###### #########
###### # #
## ## # #
## ## # #
###### # #
###### # #
# #
# #
#########
With one-hundred tiles, and not necessarily using all of the tiles at one
time, it is possible to form forty-one different square laminae.
Using up to one million tiles how many different square laminae can be
formed?"""
# The number of laminae with an inner hole of side length $s$ that can be
# formed from at most 1e6 tiles is $(S-s)/2$ where $S$ is the largest integer
# of the same parity as $s$ such that $S^2 - s^2 \leq 1e6$, i.e., `S =
# floor(sqrt(1e6 + s*s))`, possibly minus 1 (difference eliminated by rounding
# down when dividing by 2).
import math
__tags__ = ['integer sequences', 'arithmetic sequence', 'partial sums',
'integer partition']
maxTiles = 1000000
def intSqrt(x):
# faster than the one in eulerlib, and just as accurate
return int(math.floor(math.sqrt(x)))
def solve():
return sum((intSqrt(maxTiles + s*s) - s)//2 for s in xrange(1, maxTiles//4))
if __name__ == '__main__':
print solve()
| true
|
d81f15a0dd213f3f16396fbe09213fa0b90a3273
|
paulknepper/john
|
/guess_your_number.py
| 2,836
| 4.4375
| 4
|
#!/usr/local/bin/python3
# guess_your_number.py
"""
Guess Your Number rules:
I, the computer, will attempt to guess your number. This is the exact
opposite of the proposition made in guess_my_number.py. You must pick
a number between one and ten. I will make a guess. If I am incorrect,
tell me if I am too high or too low. If I guess, I win.
Note that you need to run this with python 3.x for it to work.
"""
from random import randint, choice
def main():
print("""Think of a number between 1 and some arbitrary upper bound and I
will guess it. For example, if you are thinking of a number between 1 and
1000, 1000 is your upper bound.
Don't let my artificial intelligence intimidate you.\n""")
lBound = 1
uBound = get_upper_bound()
play = input("Alright. I'm ready. Are you ready to play? (y/n): ")
while play.lower()[0] != 'n':
if lBound == uBound:
print("Ah, this must be your number: {num}".format(num=uBound))
guess = get_guess(lBound, uBound)
print("Is this your number?: {num}".format(num=guess))
answer = input("Enter 'y' for yes or 'n' for no: ")
if answer.lower()[0] == 'y':
print(choice(WIN_MESSAGE))
play = play_again(action='play')
if play.lower()[0] == 'y':
input("Think of another number, then press <enter>.")
lBound, uBound = 1, get_upper_bound()
else:
print(choice(LOSE_MESSAGE))
play = play_again()
if play.lower()[0] == 'n': break
direction = input("Was I too high (enter 'h') or too low (enter 'l')?: ")
if direction.lower()[0] == 'h':
uBound = guess - 1
else: # guess was too low
lBound = guess + 1
print(choice(ENDING_MESSAGE))
def get_upper_bound():
return int(input("So tell me--you're thinking of a number between 1 and...what?: "))
def play_again(action='guess'):
questions = ["I'm feelin' good! I think I've got your number. Give it another shot? (y/n) ",
"Shall I guess again? (y/n) "]
return input(questions[0] if action == 'play' else questions[1])
def get_guess(lower, upper):
return (upper + lower) // 2
WIN_MESSAGE = ["BAM!!! I win!", "Simple minds are easy to read.",
"Looks like I've got you figured out."]
LOSE_MESSAGE = ["You must be wearing a tinfoil hat...",
"I think you cheated.",
"Darn it. Are you sure you weren't thinking of a letter?"]
ENDING_MESSAGE = ["Aww, c'mon!!! I was just getting warmed up! Fine, then, get lost.",
"I'd be scared, too, if I were you. Goodbye.",
"Don't like being that easy to read, huh? Goodbye."]
if __name__ == '__main__': main()
| true
|
083a743d4d0d0077f417f53312cc9968484d3a14
|
KinozHao/PythonBasic
|
/e_oot/polymorphic.py
| 666
| 4.1875
| 4
|
# 所谓 多态 定义时候类型和运行时的类型不同 此时就是多态
class FAFONE(object):
def show(self):
print("FAFONE.show")
class FAFTWO(FAFONE):
def show(self):
print("FAFTWO.show")
class FAFTHREE(FAFONE):
def show(self):
print("FAFTHREE.show")
def Func(obj): # obj can us object
print(obj.show())
FAFONEs = FAFTWO()
Func(FAFONEs)
FAFONEss,FAFONEsss= FAFTHREE()
Func(FAFONEss)
# 鸭子模式 为了让func函数可以执行FAFONEs对象的show方法 又可以执行FAFONEss对象的show方法,所以定义了一个FAFONEs和FAFONEss的父类
# 而真正传入的参数: FAFONEs和FAFONEss的对象
| false
|
4258ab9b79c0d20997c84a2d6d4414bc29d953e1
|
Nathan-Zenga/210CT-Coursework-tasks
|
/cw q9 - binary search 2 - adapted.py
| 1,448
| 4.15625
| 4
|
number1 = int(input("1st number: "))
number2 = int(input("2nd number: "))
List = [4, 19, 23, 36, 40, 43, 61, 64, 78, 95]
def binarySearch(num1, num2, array):
'''performs binary search to identify if there is
a number in the List within a given interval'''
mid = len(array)//2
try:
if num1 <= num2: ##calls itself with the array halved to the right side of the pivot
if array[mid-1] >= num1 and array[mid-1] <= num2:
return True
elif array[mid-1] > num2: ##if the value is larger than pivot (to the right of the array)
return binarySearch(num1, num2, array[:mid-1]) ##calls itself with the array halved to the right side of the pivot
elif array[mid-1] < num1: ##if the value is smaller than pivot (to the left of the array)
return binarySearch(num1, num2, array[mid:]) ##calls itself with the array halved to the left side of the pivot
return False
else:
return "ERROR! Lower value > upper value"
except IndexError or RecursionError: ##signifying the two common errors during runtime
return False
print("Is there an integer between %d and %d in the list? Answer: %s" % (number1, number2, binarySearch(number1, number2, List)))
| true
|
06e6078bb3b5585e95aa3f0f11bb011e6f2723c8
|
shalu169/lets-be-smart-with-python
|
/Flatten_Dictionary.py
| 540
| 4.15625
| 4
|
"""
This problem was asked by Stripe.
Write a function to flatten a nested dictionary. Namespace the keys with a period.
For example, given the following dictionary:
{ "key": 3, "foo": { "a": 5, "bar": { "baz": 8 }}}
it should become:
{ "key": 3, "foo.a": 5, "foo.bar.baz": 8 }
You can assume keys do not contain dots in them, i.e. no clobbering will occur. """
a = eval(input())
d = {}
'''for i,j in a:
if type(j)!=dict:
d[i] = j
a.pop(i)
else:
'''
b = list(a.keys())
c = list(a.values())
d =[]
for i in c:
| true
|
f8e2832fa04459261dd5d89ec41dbc329f41cee9
|
shalu169/lets-be-smart-with-python
|
/object_to_iter.py
| 2,675
| 4.40625
| 4
|
#The __iter__() function returns an iterator for the given object (array, set, tuple etc. or custom objects).
#It creates an object that can be accessed one element at a time using __next__() function,
#which generally comes in handy when dealing with loops.
#iter(object)
#iter(callable, sentinel)
# Python code demonstrating
# basic use of iter()
#way 1:
listA = ['a', 'e', 'i', 'o', 'u']
iter_listA = iter(listA)
print(type(iter_listA)) #<class 'list_iterator'>
try:
print(next(iter_listA))
print(next(iter_listA))
print(next(iter_listA))
print(next(iter_listA))
print(next(iter_listA))
print(next(iter_listA)) # StopIteration error
except:
pass
# way 2:
# Python code demonstrating
# basic use of iter()
lst = [11, 22, 33, 44, 55]
iter_lst = iter(lst)
while True:
try:
print(iter_lst.__next__())
except:
break
# Way 3
# Python code demonstrating
# basic use of iter()
listB = ['Cat', 'Bat', 'Sat', 'Mat']
iter_listB = listB.__iter__()
print(type(iter_listB))
try:
print(iter_listB.__next__())
print(iter_listB.__next__())
print(iter_listB.__next__())
print(iter_listB.__next__())
print(iter_listB.__next__()) # StopIteration error
except:
print(" \nThrowing 'StopIterationError'",
"I cannot count more.")
# Way 4
# Python code showing use of iter() using OOPs
class Counter:
def __init__(self, start, end):
self.num = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.num > self.end:
raise StopIteration
else:
self.num += 1
return self.num - 1
# Driver code
if __name__ == '__main__':
a, b = 2, 5
c1 = Counter(a, b)
c2 = Counter(a, b)
# Way 1-to print the range without iter()
print("Print the range without iter()")
for i in c1:
print("Eating more Pizzas, couting ", i, end="\n")
print("\nPrint the range using iter()\n")
# Way 2- using iter()
obj = iter(c2)
try:
while True: # Print till error raised
print("Eating more Pizzas, couting ", next(obj))
except:
# when StopIteration raised, Print custom message
print("\nDead on overfood, GAME OVER")
# Python 3 code to demonstrate
# property of iter()
# way how iteration can not reassign back to
# initializing list
lis1 = [1, 2, 3, 4, 5]
# converting list using iter()
lis1 = iter(lis1)
# prints this
print("Values at 1st iteration : ")
for i in range(0, 5):
print(next(lis1))
# doesn't print this
print("Values at 2nd iteration : ")
for i in range(0, 5):
print(next(lis1))
| true
|
c1dc30bbfa67313204294ed063b1e3b9f9da93cd
|
giuspeppe9908/Miei-Esercizi-in-Python
|
/matrix in python/main.py
| 905
| 4.25
| 4
|
import numpy as np
# Matrix in Python using numpy class
#defing fillMAtrix function
def fillMatrix(arr, m,n):
for i in range(m):
c=[]
for j in range(n):
j = int(input("Enter the number : "))
c.append(j)
#out of the inner for loop
arr.append(c)
def printMatrix(arr):
for r in arr:
print(r)
#transpose matrix function
def Transpose(arr):
arr2 = [[arr[j][i] for j in range(len(arr))] for i in range(len(arr[0]))]
return arr2
if __name__ == '__main__':
#matrix m x n
m = int(input('Insert number of rows : '))
n = int(input('Insert number of coloumns : '))
arr = []
arr2 = []
fillMatrix(arr,m,n)
print('Printing matrix filled')
printMatrix(arr)
#transpose matrix
arr2 = Transpose(arr)
print('Printing transpose matrix...')
printMatrix(arr2)
print('End of the program')
| false
|
9b0057ebae089905fcecb0c02fccc70c25e13faa
|
Amir0AFN/pyclass
|
/s3h1.py
| 565
| 4.125
| 4
|
#Amir_Abbas_Fattahi-Thursday-14-18-class
#BMI
h = float(input("Your height(m)? \n"))
m = float(input("Your mass(Kg)? \n"))
bmi = int(m/(h**2))
print("Your BMI: " + str(bmi))
if bmi < 16:
print("You are severe thin.")
elif bmi < 17:
print("You are moderate thin.")
elif bmi < 18.5:
print("You are mild thin.")
elif bmi < 25:
print("You are normal.")
elif bmi < 30:
print("You are overweight.")
elif bmi < 35:
print("You are obese class 1")
elif bmi < 40:
print("You are obese class 2")
elif bmia > 40:
print("You are obese class 3")
| false
|
01240ebbeac9cd0dd912097c8249ca7c6654b73f
|
janedallaway/ThinkStats
|
/Chapter2/pumpkin.py
| 1,975
| 4.25
| 4
|
import thinkstats
import math
'''ThinkStats chapter 2 exercise 1
http://greenteapress.com/thinkstats/html/thinkstats003.html
This is a bit of an overkill solution for the exercise, but as I'm using it as an opportunity to learn python it seemed to make sense'''
class Pumpkin():
def __init__ (self, type, size, number):
self.type = type
self.size = size
self.number = number
def getType(self):
return self.type
def getSize(self):
return self.size
def getNumber(self):
return self.number
class Pumpkins():
def __init__ (self):
self.pumpkins = [] # store complete pumpkin objects
self.weightsOnly = [] # store the weights only, one entry per pumpkin
pass
def addPumpkin (self, myPumpkin):
self.pumpkins.append (myPumpkin)
for i in range (myPumpkin.getNumber()):
self.weightsOnly.append (myPumpkin.getSize())
def writePumpkins(self):
for pumpkin in self.pumpkins:
print "There are",pumpkin.getNumber()," ",pumpkin.getType()," pumpkins which weigh",pumpkin.getSize(),"pound each"
def writeWeights(self):
for weight in self.weightsOnly:
print weight
def meanPumpkin(self):
return thinkstats.Mean(self.weightsOnly)
def variancePumpkin(self):
return thinkstats.Var(self.weightsOnly)
def stdDeviationPumpkin(self):
return math.sqrt(self.variancePumpkin())
myPumpkins = Pumpkins()
myPumpkins.addPumpkin(Pumpkin("Decorative",1,3))
myPumpkins.addPumpkin(Pumpkin("Pie",3,2))
myPumpkins.addPumpkin(Pumpkin("Atlantic Giant",591,1))
print "The mean weight is", myPumpkins.meanPumpkin() # should be 100
print "The variance weight is", myPumpkins.variancePumpkin()
print "The standard deviation is", myPumpkins.stdDeviationPumpkin()
| true
|
254057aa4f45292225fea68a65458c4fb8098bba
|
gusmendez99/ai-hoppers
|
/game/state.py
| 700
| 4.15625
| 4
|
from copy import deepcopy
class GameState:
"""
Class to represent the state of the game.
- board = stores board information in a certain state
- current_player = stores current_player information in a specified state
- opponent = stores opponent information in specified state
"""
def __init__(self, board, player_1, player_2):
""" Constructor """
self.board = deepcopy(board)
self.current_player = deepcopy(player_1)
self.opponent = deepcopy(player_2)
def next_turn(self):
""" Switches player simulating a turn """
temp = self.current_player
self.current_player = self.opponent
self.opponent = temp
| true
|
e618ed89b65c62c5a30486dc6c79a134860efa54
|
DinakarBijili/Python-Preparation
|
/Problem Solving/Reverse/Reverse_number.py
| 263
| 4.1875
| 4
|
"""Reverse Number"""
def reverse_num(num):
reverse = 0
while num > 0:
last_digit = num%10
reverse = reverse*10 + last_digit
num = num//10
return reverse
num = int(input("Enter Number "))
result = reverse_num(num)
print(result)
| false
|
1dfda62b11b9721499dff52d38617d547647198a
|
DinakarBijili/Python-Preparation
|
/Data Structures and Algorithms/Algorithms/Sorting_Algorithms/2.Bubble.sort.py
| 1,042
| 4.375
| 4
|
# Bubble sort is a Simple Sorting algorithm that repeatedly steps through the array, compare adjecent and swaps them if they are in the wrong order.
# pass through the array is repeated until the array is sorted
#Best O(n^2); Average O(n^2); Worst O(n^2)
"""
Approach
Starting with the first element(index = 0), compare the current element with the next element of the array.
If the current element is greater than the next element of the array, swap them.
If the current element is less than the next element, move to the next element.
"""
def bubble_sort(List):
for i in range(len(List)): # Traverse through all array elements
for j in range(len(List)-1, i, - 1): # Last i elements are already in correct position(reverse order)
if List[j] < List[j - 1]:
List[j],List[j - 1] = List[j - 1], List[j] #swap
return List
if __name__ == "__main__":
# List = list(map(int,input().split())) <-- for user input
List = [3, 4, 2, 6, 5, 7, 1, 9]
print("Sorting List", bubble_sort(List))
| true
|
e88b39744da6626bb46d84c211c9475a0c45ec93
|
DinakarBijili/Python-Preparation
|
/Problem Solving/Loops/Remove_Duplication_from_string.py
| 330
| 4.125
| 4
|
"""Remove Duplication from a String """
def remove_duplication(your_str):
result = ""
for char in your_str:
if char not in result:
result += char
return result
user_input = input("Enter Characters : ")
no_duplication = remove_duplication(user_input)
print("With out Duplication = ",no_duplication)
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.