blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3b343e3551776f7ea952f039008577bdfc36ae9c | ewertonews/learning_python | /inputs.py | 222 | 4.15625 | 4 | name = input("What is your name?\n")
age = input("How old are you?\n")
live_in = input("Where do you live?\n")
string = "Hello {}! Good to know you are {} years old and live in {}"
print(string.format(name, age, live_in)) | true |
9c3254d781dda926a1050b733044a62dd1325ec7 | kevinsu628/study-note | /leetcode-notes/easy/array/27_remove_element.py | 2,103 | 4.1875 | 4 | '''
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example 1:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length.
'''
'''
Approach 1: two pointers
i: slow pointer
j: fast pointer
Intuition: we assign nums[i] to be nums[j] as long as nums[j] is different than the target
The whole intuition of two pointer is to replace the array with unique values met by faster pointer
'''
def removeElement(nums, val):
i = 0;
for j in range(len(nums)):
if (nums[j] != val):
nums[i] = nums[j];
i+=1
return i
'''
Approach 2: Two Pointers - when elements to remove are rare
Intuition
Now consider cases where the array contains few elements to remove.
For example, nums = [1,2,3,5,4], val = 4nums=[1,2,3,5,4],val=4.
The previous algorithm will do unnecessary copy operation of the first four elements.
Another example is nums = [4,1,2,3,5], val = 4nums=[4,1,2,3,5],val=4.
It seems unnecessary to move elements [1,2,3,5][1,2,3,5] one step left as the problem description mentions
that the order of elements could be changed.
Algorithm
When we encounter nums[i] = valnums[i]=val,
we can swap the current element out with the last element and dispose the last one.
This essentially reduces the array's size by 1.
Note that the last element that was swapped in could be the value you want to remove itself.
xBut don't worry, in the next iteration we will still check this element.
'''
def removeElement(nums, val):
i = 0
n = len(nums)
while (i < n):
if (nums[i] == val):
nums[i] = nums[n - 1]
# reduce array size by one
n -= 1
else:
i += 1
return n;
| true |
880f3286c2b5052bd5972a9803db32fd1581c68d | devilsaint99/Daily-coding-problem | /product_of_array_exceptSelf.py | 680 | 4.3125 | 4 | """Given an array of integers, return a new array such that each element at index i of the new array
is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24].
If our input was [3, 2, 1], the expected output would be [2, 3, 6]."""
import numpy as np
def product_of_Array(nums):
product_list=[]
prod=np.prod(nums)
for item in nums:
product=prod//item
product_list.append(product)
return product_list
num_list=[1,2,3,4,5]
num_list1=[3,2,1]
print(product_of_Array(num_list))
print(product_of_Array(num_list1))
#GG | true |
d997ee82822d758eddcedd6d47059bae5b7c7cac | akassharjun/basic-rsa-algorithm | /app.py | 1,320 | 4.15625 | 4 | # To create keys for RSA, one does the following steps:
# 1. Picks (randomly) two large prime numbers and calls them p and q.
# 2. Calculates their product and calls it n.
# 3. Calculates the totient of n ; it is simply ( p −1)(q −1).
# 4. Picks a random integer that is coprime to ) φ(n and calls this e. A simple way is to
# just pick a random number ) > max( p,q .
# 5. Calculates (via the Euclidean division algorithm) the multiplicative inverse of e
# modulo ) φ(n and call this number d.
from math import gcd
import random
def isPrime(x):
return 2 in [x,2**x%x]
def coprime(a, b):
return gcd(a, b) == 1
def modinv(e, phi):
d_old = 0; r_old = phi
d_new = 1; r_new = e
while r_new > 0:
a = r_old // r_new
(d_old, d_new) = (d_new, d_old - a * d_new)
(r_old, r_new) = (r_new, r_old - a * r_new)
return d_old % phi if r_old == 1 else None
p, q = 13, 17
print("p =", p)
print("q =", q)
n = p * q
print("n =", n)
phi_n = (p-1)*(q-1)
print("φ(n) =", phi_n)
primes = [i for i in range(1,n) if isPrime(i)]
coprimes = []
for x in primes:
if (coprime(x, n)):
coprimes.append(x)
e = random.choice(coprimes)
print("e =",e)
d = modinv(e, phi_n)
print("d =",d)
print("Public Key is (", n, ",", e, ")")
print("Private Key is (", n, ",", d, ")")
| true |
5d6d8d557279b809dba055dc702c186c0a5abebd | carlson9/KocPython2020 | /in-classMaterial/day4/exception.py | 375 | 4.1875 | 4 | raise Exception
print("I raised an exception!")
raise Exception('I raised an exception!')
try:
print(a)
except NameError:
print("oops name error")
except:
print("oops")
finally:
print("Yes! I did it!")
for i in range(1,10):
if i==5:
print("I found five!")
continue
print("Here is five!")
else:
print(i)
else:
print("I went through all iterations!")
| true |
5dfd71362ded3403b553bc743fab89bab02e2d38 | BluFox2003/RockPaperScissorsGame | /RockPaperScissors.py | 1,684 | 4.28125 | 4 | #This is a Rock Paper Scissors game :)
import random
def aiChoice(): #This function generates the computers choice of Rock, Paper or Scissors
x = random.randint(0,2)
if x == 0:
choice = "rock"
if x == 1:
choice = "paper"
if x == 2:
choice = "scissors"
return choice
def gameLoop(choice): #Main Game Loop
playerChoice = input("Choose Rock, Paper or Scissors ")
playerChoice = playerChoice.lower()
if playerChoice == "rock": #If the player chooses Rock
if choice == "rock": print("AI chose Rock, DRAW")
elif choice == "paper": print("AI chose Paper, YOU LOSE")
elif choice == "scissors": print("AI chose Scissors, YOU WIN")
elif playerChoice == "paper": #If the player chooses Paper
if choice == "rock": print("AI chose Rock, YOU WIN")
elif choice == "paper": print("AI chose Paper, DRAW")
elif choice == "scissors": print("AI chose Scissors, YOU LOSE")
elif playerChoice == "scissors": #If the player chooses Scissors
if choice == "rock": print("AI chose Rock, YOU LOSE")
elif choice == "paper": print("AI chose Paper, YOU WIN")
elif choice == "scissors": print("AI chose Scissors, DRAW")
else: print("Oops you did a fuckywucky") #If the player chose none of the options
repeat = input("Would you like to play again? Y/N ") #Asks the user if they wanna play again
if repeat == "Y" or repeat == "y":
gameLoop(choice) #Repeats the game loop
elif repeat == "N" or repeat == "n":
exit() #Ends the program
print("Welcome to Rock, Paper, Scissors")
ai = aiChoice()
aiChoice()
gameLoop(ai) | true |
690c1fc35fdd3444d8e27876d9acb99e471b296b | gridl/cracking-the-coding-interview-4th-ed | /chapter-1/1-8-rotated-substring.py | 686 | 4.34375 | 4 | # Assume you have a method isSubstring which checks if one
# word is a substring of another. Given two strings, s1 and
# s2, write code to check if s2 is a rotation of s1 using only
# one call to isSubstring (i.e., "waterbottle" is a rotation of
# "erbottlewat").
#
# What is the minimum size of both strings?
# 1
# Does space complexity matter?
# Not initially
# Time complexity is the priority?
# Yes
def rotated_substr(word, rotat):
if len(word) != len(rotat):
return False
rotat_conc = rotat + rotat
return word in rotat_conc
if __name__ == "__main__":
print(rotated_substr("thisis", "isthis"))
print(rotated_substr("hihiho", "hihole")) | true |
f4890c20a78d87556d0136d38d1a1a40ac18c087 | AlbertGithubHome/Bella | /python/list_test.py | 898 | 4.15625 | 4 | #list test
print()
print('list test...')
classmates = ['Michael','Bob', 'Tracy']
print('classmates =', classmates)
print('len(classmates) =', len(classmates))
print('classmates[1] =', classmates[1])
print('classmates[-1] =', classmates[-1])
print(classmates.append('Alert'), classmates)
print(classmates.insert(2,'Bella'), classmates)
print(classmates.pop(), classmates)
#list 内容可以不一致
classmates[3] = 100
print(classmates)
subclassmates = ['zhuzhu', 'xiaoshandian']
classmates[2] = subclassmates
print(classmates)
print('len(classmates) =', len(classmates))
#tuple test
# the elements can not change
print()
print('tuple test...')
numbers = (1, 2, 3)
print(numbers)
new_num = (1)
print(new_num)
new_num2 = (1,)
print(new_num2)
print('len(new_num2) =',len(new_num2))
#if the element of tuple is list, you can change the list elemnet
#but you can not change tuple pointer | true |
4740f88aedeb28db6bfb615af36dfed7d76fda0f | vincent-kangzhou/LeetCode-Python | /380. Insert Delete GetRandom O(1).py | 1,434 | 4.1875 | 4 | import random
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.valToIndex = dict()
self.valList = list()
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val in self.valToIndex:
return False
self.valToIndex[val] = len(self.valList)
self.valList.append(val)
return True
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val not in self.valToIndex:
return False
lastVal = self.valList[-1]
valIndex = self.valToIndex[val]
if lastVal != val:
self.valToIndex[lastVal] = valIndex
self.valList[valIndex] = lastVal
self.valList.pop()
self.valToIndex.pop(val)
return True
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return random.choice( self.valList )
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.delete(val)
# param_3 = obj.getRandom() | true |
b3b008d706062e0b068dd8287cfb101a7e268dd9 | vincent-kangzhou/LeetCode-Python | /341. Flatten Nested List Iterator.py | 2,132 | 4.21875 | 4 | # """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
# class NestedInteger(object):
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
class NestedIterator(object):
def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
self.stack = [ [nestedList, 0] ]
def _moveToValid(self):
"""
move stack to a valid position, so that the last place is an integer
"""
while self.stack:
lastList, lastIdx = self.stack[-1]
if lastIdx<len(lastList) and lastList[lastIdx].isInteger():
return
elif lastIdx == len(lastList):
self.stack.pop()
if self.stack:
self.stack[-1][1] += 1
elif lastList[lastIdx].isInteger() == False:
self.stack.append( [ lastList[lastIdx].getList(), 0 ] )
def next(self):
"""
:rtype: int
"""
self._moveToValid()
lastList, lastIdx = self.stack[-1]
ret = lastList[lastIdx].getInteger()
self.stack[-1][1] += 1
return ret
def hasNext(self):
"""
:rtype: bool
"""
self._moveToValid()
return bool(self.stack)
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next()) | true |
eb36a1f18bb74176c9e5d3739f2a7b7353af4afe | bhavin-rb/Mathematics-1 | /Multiplication_table_generator.py | 655 | 4.6875 | 5 | '''
Multiplication generator table is cool. User can specify both the number and up
to which multiple. For example user should to input that he/she wants to seea table
listing of the first 15 multiples of 3.
Because we want to print the multiplication table from 1 to m, we have a foor loop
at (1) that iterates over each of these numbers, printing the product itself and the
number, a.
'''
def multi_table(a):
for i in range(1, int(m)): # for loop --- (1)
print('{0} x {1} = {2}'.format(a, i, a * i))
if __name__ == '__main__':
a = input('Enter a number: ')
m = input('Enter number of multiples: ')
multi_table(float(a))
| true |
4bde10e50b2b57139aed6f6f74b915a0771062dd | Ayesha116/cisco-assignments | /assigment 5/fac1.py | 869 | 4.6875 | 5 | # Write a Python function to calculate the factorial of a number (a non-negative
# integer). The function accepts the number as an argument.
def fact(number):
factorial = 1
for i in range(1,number+1):
factorial = factorial*i
print(factorial)
fact(4)
# # Python program to find the factorial of a number provided by the user.
# # change the value for a different result
# num = 3
# # To take input from the user
# #num = int(input("Enter a number: "))
# factorial = 1
# # check if the number is negative, positive or zero
# if num < 0:
# print("Sorry, factorial does not exist for negative numbers")
# elif num == 0:
# print("The factorial of 0 is 1")
# else:
# for i in range(1,num + 1):
# factorial = factorial*i
# print("The factorial of",num,"is",factorial) | true |
4801ff9cb5d83bd385b3f650a3ba808d7f3cf229 | Ayesha116/cisco-assignments | /assigment 5/market6.py | 670 | 4.34375 | 4 | # Question: 6
# Suppose a customer is shopping in a market and you need to print all the items
# which user bought from market.
# Write a function which accepts the multiple arguments of user shopping list and
# print all the items which user bought from market.
# (Hint: Arbitrary Argument concept can make this task ease)
def marketitem(*shoppinglist):
for elements in shoppinglist:
print("you brought:", elements)
shoppinglist = []
while True:
a = input(shoppinglist)
print(a, "you buy from market if you leave enter quit:")
if shoppinglist == "quit":
break
shoppinglist.append(a)
marketitem(shoppinglist)
| true |
d7f20fbdee7d28a99591ab6bc4d3baf14f4a1920 | aarizag/Challenges | /LeetCode/Algorithms/longest_substring.py | 747 | 4.1875 | 4 | """
Given a string, find the length of the longest substring without repeating characters.
"""
"""
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
"""
def lengthOfLongestSubstring(s: str) -> int:
letter_locs = {}
cur, best, from_ind = 0, 0, 0
for i, l in enumerate(s):
if l in letter_locs:
from_ind = from_ind if from_ind > letter_locs[l] else letter_locs[l]
cur = i - from_ind
else:
cur += 1
letter_locs[l] = i
best = cur if cur > best else best
return best
print(lengthOfLongestSubstring("abccbade"))
print(lengthOfLongestSubstring("abba"))
print(lengthOfLongestSubstring(""))
| true |
052bcd3e8b2293371303450d3281f56c98498521 | harish-515/Python-Projects | /Tkinter/script1.py | 1,203 | 4.375 | 4 | from tkinter import *
#GUI are generated using window & widgets
window = Tk()
"""
def km_to_miles():
print(e1_value.get())
miles = float(e1_value.get())*1.6
t1.insert(END,miles)
b1=Button(window,text="Execute",command=km_to_miles)
# pack & grid are used to make these button to visible
b1.grid(row=0,column=0)
e1_value=StringVar()
e1=Entry(window,textvariable=e1_value)
e1.grid(row=0,column=1)
t1 = Text(window,height=1,width=20)
t1.grid(row=0,column=2)
"""
def kg_to_others():
grams.delete("1.0",END)
pounds.delete("1.0",END)
ounces.delete("1.0",END)
grams.insert(END,float(kg.get())*1000)
pounds.insert(END,float(kg.get())*2.20426)
ounces.insert(END,float(kg.get())*35.274)
kg_label = Label(window,text="Kgs : ")
kg_value = StringVar()
kg = Entry(window,textvariable=kg_value)
grams = Text(window,height=1,width=20)
pounds = Text(window,height=1,width=20)
ounces = Text(window,height=1,width=20)
convertbtn = Button(window,text="Convert",command=kg_to_others)
kg_label.grid(row=0,column=0)
kg.grid(row=0,column=1)
convertbtn.grid(row=0,column=2)
grams.grid(row=1,column=0)
pounds.grid(row=1,column=1)
ounces.grid(row=1,column=2)
window.mainloop()
| true |
51f27da75c6d55eeddacaa9cef05a3d1d97bb0db | r-fle/ccse2019 | /level3.py | 1,500 | 4.21875 | 4 | #!/usr/bin/env python3
from pathlib import Path
import string
ANSWER = "dunno_yet"
###########
# level 3 #
###########
print("Welcome to Level 3.")
print("Caeser cipher from a mysterious text file")
print("---\n")
""" There is text living in: files/mysterious.txt
You've got to try and figure out what the secret message contained in it is.
The enemy have hidden it in between lots of junk, but one of our operatives
suspects it may contain references to a computer scientist born in 1815.
"""
# TASK:
# Load the file. Find the hidden message and decrypt it.
# Feel free to copy in any code from previous levels that you need.
# EXAMPLE CODE:
# 1. Tell python where our file is
# 2. Read in the file content
# 3. Split the file content up into lines
f = Path(__file__).parent / "files" / "mysterious.txt"
content = f.read_text()
all_lines = content.split("\n")
# Let's check out the first 5 lines. What's in this file?
for i in range(5):
print(all_lines[i])
print()
# Time to do some secret message hunting...
for line in all_lines:
# Something goes here, right?
print(".", end="")
print("\n")
print("The solution is:", ANSWER)
###################
# level 3 - bonus #
###################
# TASK
# Depending how you accomplished the above, there might have been another solution.
# Did you encrypt first, or decrypt first?
# TASK
# What would you do if you didn't know any of the plaintext content?
# Is there a way to score how likely it is that a given result is correct?
| true |
59b53e13a6f8bb9d2d606de898fc92738e5bd10b | imyoungmin/cs8-s20 | /W3/p6.py | 692 | 4.125 | 4 | '''
Write a program which takes 5 strings as inputs and appends them to a list l. Swap each element in l with its mirror - that is, for some element at index i, swap l[i] with l[4-i] if i < 3.
For instance, if l = ['Alex', 'Bob', 'Charlie', 'David', 'Ethan'], then after swapping, l should read
['Ethan', 'David', 'Charlie', 'Bob', 'Alex']
Finally, finish the program by creating a dictionary mapping each name to its length.
'''
# Solution here
l = []
while len(l) < 5:
l.append(input("Enter a name: "))
temp = l[0]
temp1 = l[1]
l[0] = l[4]
l[1] = l[3]
l[3] = temp1
l[4] = temp
print(l)
name_to_length = {}
for name in l:
name_to_length[name] = len(name)
print(name_to_length) | true |
c46fc22351db7e3fdafadde09aea6ae45b7c6789 | rajatthosar/Algorithms | /Sorting/qs.py | 1,682 | 4.125 | 4 | def swap(lIdx, rIdx):
"""
:param lIdx: Left Index
:param rIdx: Right Index
:return: nothing
"""
temp = array[lIdx]
array[lIdx] = array[rIdx]
array[rIdx] = temp
def partition(array, firstIdx, lastIdx):
"""
:param array: array being partitioned
:param firstIdx: head of the array
:param lastIdx: tail of the array
:return: index of pivot element after sorting
"""
pivot = array[lastIdx]
# Counter i is used as a marker to fill the array with all
# elements smaller than pivot. At the end of the loop
# pivot is swapped with the next position of i as all the
# elements before pivot are smaller than it
lowIdx = firstIdx - 1
# Note that range function stops the sequence generation at
# lastIdx. This means that there will be
# (lastIdx - firstIdx) - 1 elements in the sequence.
# The last item generated in the sequence will be lastIdx - 1
for arrayIdx in range(firstIdx, lastIdx):
if array[arrayIdx] <= pivot:
lowIdx += 1
swap(lowIdx, arrayIdx)
swap(lowIdx + 1, lastIdx)
return lowIdx + 1
def quickSort(array, firstIdx, lastIdx):
"""
:param array: Array to be sorted
:param firstIdx: head of the array
:param lastIdx: tail of the array
:return: sorted array
"""
if firstIdx < lastIdx:
pivot = partition(array, firstIdx, lastIdx)
quickSort(array, firstIdx, pivot - 1)
quickSort(array, pivot + 1, lastIdx)
print(array)
if __name__ == "__main__":
array = [10, 80, 30, 90, 40, 50, 70]
firstIdx = 0
lastIdx = len(array) - 1
quickSort(array, firstIdx, lastIdx)
| true |
68fc5fd6c86607595d5eb547218c7a55781f3389 | manjulive89/JanuaryDailyCode2021 | /DailyCode01092021.py | 1,381 | 4.5625 | 5 | # -------------------------------------------
# Daily Code 01/09/2021
# "Functions" Lesson from learnpython.org
# Coded by: Banehowl
# -------------------------------------------
# Functions are a convenient way to divide your code into useful blocks, allowing order in the code, make it
# more readable, reuse it, and save some time. Also fuctions are a key way to define interfaces so
# programmers can share their code.
# How to write functions in Python
def my_function(): # Functions are define using the block keyword "def"
print("Hello From My Function!")
# Functions may also receive arguments (variables passed from the caller to the function)
def my_function_with_args(username, greeting):
print("Hello, %s, From My Function! I wish you %s" % (username, greeting))
# Fuctions may return a value to the caller, using the keyword "return"
def sum_two_number(a, b):
return a + b
# To call functions in Python, simply write teh function's the name followed by (), placing any required
# arguments within the bracket. Using the previous functions we defined:
# print(a simple greeting)
my_function()
# prints - "Hello, Joe Doe, From My Function! I wish you a great year!"
my_function_with_args("John Doe", "a great year!")
# after this line x will hold the value 3
x = sum_two_number(1, 2)
print(x)
| true |
9d1b835fd8b5e6aeadb4ff23d54c2bc0b5435b2f | manjulive89/JanuaryDailyCode2021 | /DailyCode01202021.py | 1,831 | 4.3125 | 4 | # -----------------------------------------------
# Daily Code 01/20/2021
# "Serialization" Lesson from learnpython.org
# Coded by: Banehowl
# -----------------------------------------------
# Python provides built-in JSON libraries to encode and decode JSON
# Python 2.5, the simplejson module is used, whereas in Python 2.7, the json module is used.
# In order to use the json module, it must be imported:
import json
# There are two basic formats for JSON data. Either in a string or the object datastructure.
# The object datastructure, in Python, consists of lists and dictionaries nested inside each other.
# The object datastructure allows one to use python methods (for lists and dictionaries) to add, list,
# search and remove elements from the datastructure.
#
# The String format is mainly used to pass the data into another program or load into a datastructure.
# To load JSON back to a data structure, use the "loads" method. This method takes a string and turns
# it back into the json object datastructure. To encode a data structure to JSON, use the "dumps" method.
# This method takes an object and returns a String:
json_string = json.dumps([1, 2, 3, "a", "b", "c"])
print(json.loads(json_string))
# Sample Code using JSON:
# import json #it's already imported so...
# fix this function, so it adds the given name
# and salary pair to salaries_json, and return it
def add_employee(salaries_json, name, salary):
salaries = json.loads(salaries_json)
salaries[name] = salary
return json.dumps(salaries)
# test code
salaries = '{"Alfred" : 300, "Jane" : 400 }'
new_salaries = add_employee(salaries, "Me", 800)
decoded_salaries = json.loads(new_salaries)
print(decoded_salaries["Alfred"])
print(decoded_salaries["Jane"])
print(decoded_salaries["Me"]) | true |
5cac576e1c3b2e1ecd67bfd71ab20bc765b4eee3 | jtm192087/Assignment_8 | /ps1.py | 960 | 4.46875 | 4 | #!/usr/bin/python3
#program for adding parity bit and parity check
def check(string): #function to check for a valid string
p=set(string)
s={'0','1'}
if s==p or p=={'0'} or p=={'1'}:
print("It is a valid string")
else:
print("please enter again a valid binary string")
if __name__ == "_main_" :
string=input("please enter a valid binary string\n")
check(string) #calling check function
substring='1'
count=string.count(substring)
print("count is:",count)
if count%2==0: #to add parity bit at the end of the binary data if no. one,s is even
string=string+'1'
print("The parity corrected data is: ",string) #print corrected data
else:
string=string+'0'
print("The parity corrected data is: ",string)
print("\n")
string2=string.replace("010","0100") #replacing the '010' substring by '0100'
print("The transmitting data is: ",string2)
| true |
578f3caf2d4247460b9331ae8f8b2a9cc56a4a74 | EgorVyhodcev/Laboratornaya4 | /PyCharm/individual.py | 291 | 4.375 | 4 | print("This program computes the volume and the area of the side surface of the Rectangular parallelepiped")
a, b, c = input("Enter the length of 3 sides").split()
a = int(a)
b = int(b)
c = int(c)
print("The volume is ", a * b * c)
print("The area of the side surface is ", 2 * c * (a + b))
| true |
2531327f966f606597577132fa9e54f7ed0be407 | Rotondwatshipota1/workproject | /mypackage/recursion.py | 930 | 4.1875 | 4 | def sum_array(array):
for i in array:
return sum(array)
def fibonacci(n):
''''
this funtion returns the nth fibonacci number
Args: int n the nth position of the sequence
returns the number in the nth index of the fibonacci sequence
''''
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
def factorial(n):
'''' this funtion returns the factorial of a give n intheger
args: n it accepts an intger n as its argument
returns : the number or the factorial of the given number
''''
if n < 1:
return 1
else:
return n * factorial(n-1)
def reverse(word):
''''
this funtion returns a word in a reverse order
args : word it accepts a word as its argument
return: it returns a given word in a reverse order
''''
if word == "":
return word
else:
return reverse(word[1:]) + word[0]
| true |
338f94f012e3c673777b265662403e5ef05a5366 | alyssaevans/Intro-to-Programming | /Problem2-HW3.py | 757 | 4.3125 | 4 | #Author: Alyssa Evans
#File: AlyssaEvans-p2HW3.py
#Hwk #: 3 - Magic Dates
month = int(input("Enter a month (MM): "))
if (month > 12) or (month < 0):
print ("Months can only be from 01 to 12.")
day = int(input("Enter a day (DD): "))
if (month % 2 == 0) and (day > 30) or (day < 0):
print("Incorrect amount of days for that month.")
if (month % 2 != 0) and (day > 31) or (day < 0):
print("Incorrect amount of days for that month")
if (month == 2) and (day > 29):
print("February has a maximum of 29 days.")
year = int(input("Enter a year (YY): "))
if (year > 10):
print("You have to enter a two digit year.")
if (month * day == year):
print("The date you chose is magic!")
else:
print("The date you chose isn't magic.")
| true |
3b0f3bd8d100765ae7cb593a791c9f2908b1ce76 | rossvalera/inf1340_2015_asst2 | /exercise1.py | 2,159 | 4.1875 | 4 | #!/usr/bin/env python
""" Assignment 2, Exercise 1, INF1340, Fall, 2015. Pig Latin
This module converts English words to Pig Latin words
"""
__author__ = 'Sinisa Savic', 'Marcos Armstrong', 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__ = "MIT License"
def pig_latinify(word):
"""
This function will translate any English word to Pig latin
:param word: Any word using the alphabet
:return: The word will get translated to Pig Latin
If the first letter is a vowel will add "yay" to the end
If the first letter is a consonant will take all consonants up until teh worst vowel and add them to the end
with "ay" added
"""
# variables defined and used within code
original = word.lower()
pig = "yay"
# For this assignment we will consider y a vowel always
vowel = ["a", "e", "i", "o", "u"]
index = 0
found_letter = -1
# Makes sure that all inputs are actual letters and not numbers
if len(original) > 0 and original.isalpha():
# Checks each letter of a given word to until first vowel is found
for i in original:
if i in vowel:
found_letter = index
break
index += 1
# no vowel found thus will return given word with "ay" at the end
if found_letter == -1:
no_vowel = original + pig[1:]
return no_vowel
# When first letter in the given word is a vowel will return the word with "yay" at the end
elif found_letter == 0:
first_vowel = original + pig
return first_vowel
# Will take all consonants up until the vowel in a word
# Will return the word starting with the vowel and will add the removed consonants and "ay" to the end
else:
first_consonant = original[found_letter:] + original[0:found_letter] + pig[1:]
return first_consonant
# Any word that doesnt only use alphabetical characters will return "try again"
# No input will also return "try again"
else:
return "try again"
# Function Commented out
# print(pig_latinify(""))
| true |
a00293978a88a612e4b7a3ea532d334f43a279d5 | CooperMetts/comp110-21f-workspace | /sandbox/dictionaries.py | 1,329 | 4.53125 | 5 | """Demonstrations of dictonary capabilities."""
# Declaring the type of a dictionary
schools: dict[str, int]
# Intialize to an empty dictonary
schools = dict()
# set a key value pairing in the dictionary
schools["UNC"] = 19400
schools["Duke"] = 6717
schools["NCSU"] = 26150
# Print a dictonary literal representation
print(schools)
# Access a value by its key -- "lookup"
print(f"UNC has {schools['UNC']} students.")
# Remove a key-value pair from a dictonary by its key
schools.pop("Duke")
# Test for existence of a key
# This is a boolean expression saying 'Duke' (the key) in schools (the dictonary)
is_duke_present: bool = "Duke" in schools
print(f"Duke is present: {is_duke_present}.")
# Update / Reassign a key-value pair
schools["UNC"] = 20000
schools["NCSU"] = schools["NCSU"] + 200
print(schools)
# Demonstration of dictonary literals
# Empty dictionary literal
# This --> schools = {} is a dictionary literal and this --> dict() is a dictionary constructor
schools = {} # Same as dict()
# Alternatively, intiatlize key-value pairs
schools = {"UNC": 19400, "Duke": 6717, "NCSU": 26150}
print(schools)
# What happens when a you try to access a key that does not exist:
print(schools["UNCC"])
# Gives you KeyError: "UNCC"
for school in schools:
print(f"Key: {school} -> Value: {schools[school]}")
| true |
590cab46ee48d2e7380fd4025683f4321d9a1a34 | dipak-pawar131199/pythonlabAssignment | /Introduction/SetA/Simple calculator.py | 642 | 4.1875 | 4 | # Program to make simple calculator
num1=int(input("Enter first number: "))
num2=int(input("Enter second number: "))
ch=input(" Enter for opration symbol addition (+),substraction (-),substraction (*),substraction (/), % (get remainder) and for exit enter '$' ")
if ch=='+':
print("Sum is : ",num1+num2)
if ch== "-":
print("Difference is : ",num1-num2)
if ch=='*':
print("Multiplication is : ",num1*num2)
if ch=='/':
print("Division is : ",num1-num2)
if ch=='%':
print("Moduls is : ",num1%num2)
if ch=='$':
print("Buy");
| true |
86c83cf3af2c57cc3250540ec848a3d5924b6d4b | dipak-pawar131199/pythonlabAssignment | /Functions/Sumdigit.py | 691 | 4.15625 | 4 | ("""
1) Write a function that performs the sum of every element in the given number unless it
comes to be a single digit.
Example 12345 = 6
""")
def Calsum(num):
c=0;sum=0
while num>0: # loop for calcuating sum of digits of a number
lastdigit=num%10
sum+=lastdigit
num=num//10
k=sum
while k>0:# loop for count number of digit of sum
c=c+1
k=k//10
if c>1: # if digit count 'c' >1
Calsum(sum) # recursive call to Calsum() function
else:
print(sum) # display sum whose digit count is 1
num=int(input("Enter number: "))
Calsum(num)
| true |
df13a154e79b15d5a9b58e510c72513f8f8e2fa0 | dipak-pawar131199/pythonlabAssignment | /Conditional Construct And Looping/SetB/Fibonacci.py | 550 | 4.1875 | 4 | '''4) Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:
a. 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
b. By considering the terms in the Fibonacci sequence whose values do not exceed
four hundred, find the sum of the even-valued terms.
'''
num=int(input("enter how many fibonacci series number is display:"))
f0=1
f1=1
print("Terms of fibonaccie series is:")
print(f0,f1)
i=2
while i < num:
f=f0+f1
f0=f1
f1=f
print(f)
i=i+1
| true |
10e021531d1b56e1375e898e7599422de0ce5c9a | RobStepanyan/OOP | /Random Exercises/ex5.py | 776 | 4.15625 | 4 | '''
An iterator
'''
class Iterator:
def __init__(self, start, end, step=1):
self.index = start
self.start = start
self.end = end
self.step = step
def __iter__(self):
# __iter__ is called before __next__ once
print(self) # <__main__.Iterator object at 0x000001465A203DC8>
return self
def __next__(self):
if not (self.index + self.step) in range(self.start, self.end+self.step):
raise StopIteration
else:
self.index += self.step
return self.index - self.step
iteratable = Iterator(0, 10, 2)
while True:
try:
print(iteratable.__next__())
# or print(next(iterable))
except StopIteration:
break
'''
Result:
0
2
4
6
8
'''
| true |
9de5002aa797d635547bb7ca1989a435d4a97256 | altvec/lpthw | /ex32_1.py | 571 | 4.46875 | 4 | the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print "This is count {0}".format(number)
# same as above
for fruit in fruits:
print "A fruit of type: {0}".format(fruit)
# also we can go through mixed lists too
for i in change:
print "I got {0}".format(i)
# we can also build lists
elements = xrange(0, 6)
# now we can print then out too
for i in elements:
print "Element was: {0}".format(i)
| true |
b8e6af4affac0d2ae50f36296cc55f52c6b44af3 | PacktPublishing/Software-Architecture-with-Python | /Chapter04/defaultdict_example.py | 1,374 | 4.1875 | 4 | # Code Listing #7
"""
Examples of using defaultdict
"""
from collections import defaultdict
counts = {}
text="""Python is an interpreted language. Python is an object-oriented language.
Python is easy to learn. Python is an open source language. """
word="Python"
# Implementations with simple dictionary
for word in text.split():
word = word.lower().strip()
try:
counts[word] += 1
except KeyError:
counts[word] = 1
print("Counts of word",word,'=>',counts[word])
cities = ['Jakarta','Delhi','Newyork','Bonn','Kolkata','Bangalore','Seoul']
cities_len = {}
for city in cities:
clen = len(city)
# First create entry
if clen not in cities_len:
cities_len[clen] = []
cities_len[clen].append(city)
print('Cities grouped by length=>',cities_len)
# Implementation using default dict
# 1. Counts
counts = defaultdict(int)
for word in text.split():
word = word.lower().strip()
# Value is set to 0 and incremented by 1 in one go
counts[word] += 1
print("Counts of word",word,'=>',counts[word])
# 2. Cities grouped by length
cities = ['Jakarta','Delhi','Newyork','Bonn','Kolkata','Bangalore','Seoul']
cities_len = defaultdict(list)
for city in cities:
# Empty list is created as value and appended to in one go
cities_len[len(city)].append(city)
print('Cities grouped by length=>',cities_len)
| true |
97b15762af24ba6fb59fc4f11320e99ffcec6cf4 | rxxxxxxb/PracticeOnRepeat | /Python Statement/practice1.py | 540 | 4.125 | 4 |
# Use for, .split(), and if to create a Statement that will print out words that start with 's'
st = 'Print only the words that start with s in this sentence'
for word in st.split():
if word[0] == 's':
print(word)
# even number using range
li = list(range(1,15,2))
print(li)
#List comprehension to create a list of number devisible by 3
div3 = [x for x in range(1,50) if x%3 == 0 ]
print(div3)
#using list comprehension for 1st letter in every word
firstLetter = [word[0] for word in st.split()]
print(firstLetter) | true |
70c96ccdda8fec43e4dc2d85ba761bae2c4de876 | heyimbarathy/py_is_easy_assignments | /pirple_functions.py | 978 | 4.15625 | 4 | # -----------------------------------------------------------------------------------
# HOMEWORK #2: FUNCTIONS
# -----------------------------------------------------------------------------------
'''create 3 functions (with the same name as those attributes),
which should return the corresponding value for the attribute.
extra: create a function that returns a boolean'''
year_recorded = 2003
artist = 'Snow Patrol'
def show_favorite_band(artist):
return artist
#function with default
def return_recording_year(year = 1900):
return year
# function without parameters
def echo_best_song():
return 'Run'
def search_artist(s):
'''tests if a substring is part of the artist name'''
return s in artist
# test functions through print statements
print(f"{echo_best_song()} ({return_recording_year(year_recorded)}) – {show_favorite_band(artist)}")
print("There were no songs released in:", return_recording_year())
print(search_artist('Snow'))
print(search_artist('Sun'))
| true |
910185af5c3818d848aa569d6e57de868c9cb790 | heyimbarathy/py_is_easy_assignments | /pirple_lists.py | 1,311 | 4.15625 | 4 | # -----------------------------------------------------------------------------------
# HOMEWORK #4: LISTS
# -----------------------------------------------------------------------------------
'''Create a function that allows you to add things to a list.
Anything that's passed to this function should get added to myUniqueList,
unless its value already exists in myUniqueList.
(If the value doesn't exist already, it should be added and the function should return True.
If the value does exist, it should not be added, and the function should return False)
Add some code below that tests the function, showcasing the different scenarios,
and then finally print the value of myUniqueList
extra: Add another function that pushes all the rejected inputs into a separate global array
called myLeftovers.
'''
myUniqueList = []
myLeftovers = []
def compile_unique_list(item):
'''depending on uniqueness, allocate item to myUniqueList or myLeftovers'''
if item not in myUniqueList:
myUniqueList.append(item)
return True
else:
myLeftovers.append(item)
return False
# test entries
compile_unique_list('dog')
compile_unique_list(4)
compile_unique_list(True)
compile_unique_list(4)
compile_unique_list('lucky')
# print both lists
print('Unique list:', myUniqueList)
print('Left-overs:', myLeftovers)
| true |
5045f39041869fd81a8c406159a1bec39e4b7372 | abdelilah-web/games | /Game.py | 2,707 | 4.15625 | 4 |
class Game:
## Constractor for the main game
def __init__(self):
print('Welcome to our Games')
print('choose a game : ')
print('press [1] to play the Even-odd game')
print('Press [2] to play the Average game')
print('Press [3] to play the Multiplication')
self.choose()
##################################################
##Availabale choises
def choose(self):
while True:
select = input('your choise : ')
try:
select = int(select)
if select == 1:
print()
print()
self.Even_odd()
elif select == 2 :
print()
print()
self.Average()
elif select == 3 :
print()
print()
self.Multiplication()
else :
print('Please choose between 1, 2 or 3 ')
except ValueError:
print('Please Enter a valid number')
##################################################
##Even Odd code
def Even_odd(self) :
print('Welcome to the Even Odd game')
while True:
number = input('Enter your number : ')
if number == 'x':
print('End Of the game')
print('...')
break
try :
number = int(number)
if number % 2 == 0:
print('Even number')
else:
print('Odd number')
except ValueError :
print('Please enter a valid number')
##################################################
##Average Code
def Average(self) :
print('Welcome to the Average game')
how_number = int(input('how many number do you want to summ : '))
zero = 0
summ = 0
while how_number > zero :
numbers = int(input('your number : '))
zero += 1
summ += numbers
print(summ/how_number)
###################################################
##Multiplication Table game code
def Multiplication(self) :
print('Welcome to the Multiplication')
start = int(input('Enter the first number : '))
end = int(input('Enter the final number : '))
for x in range(start,end+1):
for y in range(1,13):
print(x,' X ',y ,' = ' ,x*y)
print('__________________________________')
## Create Object from the Class
play = Game()
| true |
b9b5e983017845ef38400a7d8ad8c9e35333d405 | bghoang/coding-challenge-me | /leetcode/Other (not caterogize yet)/maxProductThreeNumbers.py | 1,411 | 4.25 | 4 | '''
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Example 1:
Input: [1,2,3]
Output: 6
Example 2:
Input: [1,2,3,4]
Output: 24
'''
'''
First solution: O(nlogn) runtime/ O(logn) space caus of sortings
Sort the array,
Find the product of the last 3 numbers
Find the product of the first 2 numbers and the last number
Return max of those 2 product
Optimal solution: O(n) runtime/ O(1) space
Find the 3 biggest numbers and 2 smallest numbers
Loop through the list, update these numbers
Find the product of the 3 biggest numbers
Find the product of the 2 smallest numbers and the biggest number
Return max of the these 2 products
'''
def maximumProduct(nums):
# First solution
'''
nums.sort()
l = len(nums)
if l < 3:
return
product1 = nums[l-1] * nums[l-2] * nums[l-3]
product2 = nums[l-1] * nums[0] * nums[1]
return max(product1, product2)
'''
max1, max2, max3 = float('-inf'), float('-inf'), float('-inf')
min1, min2 = float('inf'), float('inf')
for num in nums:
if num >= max1:
max3, max2, max1 = max2, max1, num
elif num >= max2:
max3, max2 = max2, num
elif num > max3:
max3 = num
if num <= min1:
min2, min1 = min1, num
elif num < min2:
min2 = num
return max(max1*max2*max3, min1*min2*max1)
| true |
17756e03f8022ead554e7ec67add12ea22a45cb5 | lj015625/CodeSnippet | /src/main/python/stack/minMaxStack.py | 1,932 | 4.125 | 4 | """
Write a class for Min Max Stack.
Pushing and Popping value from the stack;
Peeking value at top of the stack;
Getting both minimum and maximum value in the stack at any time.
"""
from collections import deque
class MinMaxStack:
def __init__(self):
# doubly linked list deque is more efficient to implement large sized stack
self.minMaxStack = deque()
# O(1) time O(1) space
def peek(self):
return self.minMaxStack[-1]['number']
# O(1) time O(1) space
def pop(self):
return self.minMaxStack.pop()['number']
# O(1) time O(1) space
def push(self, number):
# default min and max to current number when stack is empty
currMinMax = {'min': number, 'max': number, 'number': number}
if len(self.minMaxStack) > 0:
lastMinMax = self.minMaxStack[-1]
currMin = min(number, lastMinMax['min'])
currMax = max(number, lastMinMax['max'])
currMinMax = {'min': currMin, 'max': currMax, 'number': number}
self.minMaxStack.append(currMinMax)
# O(1) time O(1) space
def getMin(self):
lastItem = self.minMaxStack[-1]
return lastItem['min']
# O(1) time O(1) space
def getMax(self):
lastItem = self.minMaxStack[-1]
return lastItem['max']
import unittest
def testMinMaxPeek(self, min, max, peek, stack):
self.assertEqual(stack.getMin(), min)
self.assertEqual(stack.getMax(), max)
self.assertEqual(stack.peek(), peek)
class TestProgram(unittest.TestCase):
def test_case_1(self):
stack = MinMaxStack()
stack.push(5)
testMinMaxPeek(self, 5, 5, 5, stack)
stack.push(7)
testMinMaxPeek(self, 5, 7, 7, stack)
stack.push(2)
testMinMaxPeek(self, 2, 7, 2, stack)
self.assertEqual(stack.pop(), 2)
self.assertEqual(stack.pop(), 7)
testMinMaxPeek(self, 5, 5, 5, stack)
| true |
f2e670471bfa9bcac1e5f983ecdb0240eeaaf1f2 | lj015625/CodeSnippet | /src/main/python/array/sumOfTwoNum.py | 1,598 | 4.125 | 4 | """Given an array and a target integer, write a function sum_pair_indices that returns the indices of two integers
in the array that add up to the target integer if not found such just return empty list.
Note: even though there could be many solutions, only one needs to be returned."""
def sum_pair_indices(array, target):
index_holder = {}
for i in range(len(array)):
current_number = array[i]
complement = target - current_number
if complement in index_holder:
return [index_holder[complement], i]
else:
index_holder[current_number] = i
return []
array = [1, 2, 3, 4]
target = 5
print(sum_pair_indices(array, target))
def twoNumberSum(array, targetSum):
# use hashset O(n) time O(n) space
saved = {}
for current_num in array:
complement = targetSum - current_num
if complement in saved:
return [current_num, complement]
else:
# use dict as a hashset not a hashmap
saved[current_num] = complement
return []
array = [3,5,-4,8,11,1,-1,6]
target = 10
print(twoNumberSum(array, target))
def twoNumberSum2(array, targetSum):
# use sorting O(nlogn) time O(1) space
array.sort()
left = 0
right = len(array) - 1
while left < right:
currentSum = array[left] + array[right]
if currentSum == targetSum:
return [array[left], array[right]]
elif currentSum < targetSum:
left += 1
elif currentSum > targetSum:
right -= 1
return []
print(twoNumberSum2(array, target))
| true |
153468d2ee32d18c1fe7cd6ee705d0f2e38c6ac2 | lj015625/CodeSnippet | /src/main/python/string/anagram.py | 626 | 4.28125 | 4 | """Given two strings, write a function to return True if the strings are anagrams of each other and False if they are not.
A word is not an anagram of itself.
"""
def is_anagram(string1, string2):
if string1 == string2 or len(string1) != len(string2):
return False
string1_list = sorted(string1)
string2_list = sorted(string2)
return string1_list == string2_list
string_1 = "listen"
string_2 = "silent"
print(is_anagram(string_1, string_2))
string_1 = "banana"
string_2 = "bandana"
print(is_anagram(string_1, string_2))
string_1 = "banana"
string_2 = "banana"
print(is_anagram(string_1, string_2))
| true |
ce33d6bb0f0db42a8a0b28543f1ea6895da0d00c | lj015625/CodeSnippet | /src/main/python/tree/binarySearch.py | 1,055 | 4.1875 | 4 | def binary_search_iterative(array, target):
if not array:
return -1
left = 0
right = len(array)-1
while left <= right:
mid = (left + right) // 2
# found the target
if array[mid] == target:
return mid
# if target is in first half then search from the start to mid
elif target < array[mid]:
right = mid - 1
# search from the mid to end
else:
left = mid + 1
return -1
arr = [0, 1, 21, 33, 45, 45, 61, 71, 72, 73]
target = 33
print(binary_search_iterative(arr, target))
def binarySearch(array, target):
return binarySearchHelper(array, target, 0, len(array) - 1)
def binarySearchHelper(array, target, left, right):
while left <= right:
mid = (left + right) // 2
if target == array[mid]:
return mid
elif target < array[mid]:
right = mid - 1
else:
left = mid + 1
return -1
# Test array
arr = [ 2, 3, 4, 10, 40]
target = 10
print(binarySearch(arr, target))
| true |
0ecfc8d40c1d7eba616676d03f04bb9bf187dc09 | xamuel98/The-internship | /aliceAndBob.py | 414 | 4.4375 | 4 | # Prompt user to enter a string
username = str(input("Enter your username, username should be alice or bob: "))
''' Convert the username to lowercase letters and compare
if the what the user entered correlates with accepted string '''
if username.lower() == "alice" or username.lower() == "bob":
print("Welcome to programming with python " + username)
else:
print("Invalid username...") | true |
ed4ebe2d41a2da81d843004f32223f0662e59053 | ParulProgrammingHub/assignment-1-kheniparth1998 | /prog10.py | 308 | 4.125 | 4 | principle=input("enter principle amount : ")
time=input("enter time in years : ")
rate=input("enter the interest rate per year in percentage : ")
def simple_interest(principle,time,rate):
s=(principle*rate*time)/100
return s
print "simple interest is : ",simple_interest(principle,rate,time)
| true |
8e73474a9ac03600fee353f5f64259dae9840592 | Sachey-25/TimeMachine | /Python_variables.py | 1,234 | 4.21875 | 4 | #Practice : Python Variables
#Tool : Pycharm Community Edition
#Platform : WINDOWS 10
#Author : Sachin A
#Script starts here
'''Greet'='This is a variable statement'
print(Greet)'''
#Commentning in python
# -- Single line comment
#''' ''' or """ """ multiline comment
print('We are learning python scripting and practice the same in pycharm And Varibales ')
'''[A-Za-z _]
[AnyEnlishWords and _]'''
variable = 1000
_another = 2000
CONSDATA=3.14
#Mulitple assignemnt
a,b,c,d=10,20,30,40
print("Value of c is : ",c)
print(a,b,c,d)
#first number
number_one=10
#second number
number_two=20
#addition of two numbers
print("Addition of two numbes :" ,number_one+number_two)
#Dynamical allocation
'''name = input("What is your name ?")
print(name)'''
number_third=input("Enter a number: ")
number_fourth=input("Enter another number: ")
print("Additon of entered number is :" , number_third+number_fourth)
#By default input prompt recives inputs as strings
#Implicit conversion --
#Explicit conversion
number_third=int(input("Enter a number: "))
number_fourth=int(input("Enter another number: "))
print("Additon of entered number is :" , number_third+number_fourth)
#Script Ends here
| true |
1e8e3b23f03923e87e1910f676cda91e93bc02c8 | skyesyesyo/AllDojo | /python/typelist.py | 929 | 4.25 | 4 | #input
one = ['magical unicorns',19,'hello',98.98,'world']
#output
"The array you entered is of mixed type"
"String: magical unicorns hello world"
"Sum: 117.98"
# input
two = [2,3,1,7,4,12]
#output
"The array you entered is of integer type"
"Sum: 29"
# input
three = ['magical','unicorns']
#output
"The array you entered is of string type"
"String: magical unicorns"
def typelist(somelist):
sum = 0
string = ""
for value in somelist:
if type(value) is int or type(value) is float:
sum = sum + value
elif type(value) is str:
string = string+value+" "
if(sum>0 and string != ""):
print "The array you entered is mixed type"
elif(sum>0 and string == ""):
print "The array you entered is of integer type"
elif(sum==0 and string !=""):
print "The array you entered is of string type"
print "String: {}".format(string)
if sum != 0:
print "Sum: {}".format(sum)
typelist(one)
typelist(two)
typelist(three) | true |
584c4e36f9801a63fd17adae4c750647d0afeec8 | linth/learn-python | /class/specificMethod-3.py | 606 | 4.3125 | 4 | '''
specific method
- __str__() and __repr__()
- __repr__() magic method returns a printable representation of the object.
- The __str__() magic method returns the string
Reference:
- https://www.geeksforgeeks.org/python-__repr__-magic-method/?ref=rp
'''
class GFG:
def __init__(self, name):
self.name = name
def __str__(self) -> str:
return f'Name is {self.name}'
def __repr__(self) -> str:
return f'GFG(name={self.name})'
if __name__ == '__main__':
obj = GFG('george')
print(obj.__str__())
print(obj.__repr__())
| true |
a7ab0d16e3266d89e3119cfe59447d30062a9140 | kelly4strength/intCakes | /intCake3.py | 2,264 | 4.40625 | 4 | # Given a list_of_ints,
# find the highest_product you can get from three of the integers.
# The input list_of_ints will always have at least three integers.
# find max, pop, add popped to a new list_of_ints
# add those ints bam!
# lst = [11,9,4,7,13, 21, 55, 17]
# returns [55, 21, 17]
# 93
# lst = [0, 9, 7]
# returns append three highest [9, 7]
# None
# if there are only 3 numbers in the list I need an if statement
# to add them before going through the loop
# if len(lst) == 3 then return three items added
# lst = [2, 2, 2]
# same issue as above
# returns None
# lst = [-1, 9, 8, -11]
# append three highest [9, 8]
# returns None
# lst = [-1, -9, -8, -11]
# returns
# append three highest [-1, -8]
# None
# lst = [-1, -9, -8, -11, -2]
# append three highest [-1, -2, -8]
# [-1, -2, -8]
# -11
def find_highest_product(lst):
"""function to find the highest product of three integers in a list, list will always have at least 3 integers"""
# list for the three highest numbers
three_highest = []
# product of three highest numbers
product = None
# if len(lst) == 3:
# product_of_three_highest = reduce(lambda x, y: x+y, lst)
# three_highest.append(product_of_three_highest)
# print "lst only three"
# return product_of_three_highest
while len(three_highest) < 3:
# else:
# for num in lst:
highest_num = max(lst)
print "max", highest_num
three_highest.append(highest_num)
print "append three highest", three_highest
lst.remove(highest_num)
# lst.append(0) - only added this to keep the original list the same length...
if len(three_highest) == 3:
# multiply the remaining items in the list
product_of_three_highest = reduce(lambda x, y: x+y, three_highest)
print three_highest
return product_of_three_highest
print find_highest_product([-1, -9, -8, -11, -2])
# lst.remove(product_of_three)
# for num in lst:
# two = max(lst)
# lst.remove(two)
# for num in lst:
# three = max(lst)
# lst.remove(three)
# # >>> lst = [3,7,2,9,11]
# # >>> for num in lst:
# add_top_three = 0
# # ... one = max(lst)
# # ... lst.remove(one)
# add_top_three += one
# # ... print one
# ... print lst
# ...
# 11
# [3, 7, 2, 9]
# 9
# [3, 7, 2]
# 7
# [3, 2]
# >>>
| true |
d0434e4c42c139b85ec28c175749bb189d2a19bf | Francisco-LT/trybe-exercices | /bloco36/dia2/reverse.py | 377 | 4.25 | 4 | # def reverse(list):
# reversed_list = []
# for item in list:
# reversed_list.insert(0, item)
# print(reversed_list)
# return reversed_list
def reverse(list):
if len(list) < 2:
return list
else:
print(f"list{list[1:]}, {list[0]}")
return reverse(list[1:]) + [list[0]]
teste = reverse([1, 2, 3, 4, 5])
print(teste) | true |
d2d8f309a900c4642f0e7c66b3d33e26cabaf4e9 | synaplasticity/py_kata | /ProductOfFibNumbers/product_fib_num.py | 597 | 4.34375 | 4 | def fibonacci(number):
if number == 0 or number == 1:
return number*number
else:
return fibonacci(number - 1) + fibonacci(number - 2)
def product_fib_num(product):
"""
Returns a list of the two consecutive fibonacci numbers
that give the provided product and a boolean indcating if
those two consecutive numbers where found.
"""
for n in range(1, product):
f1 = fibonacci(n)
f2 = fibonacci(n + 1)
if f1 * f2 == product or f1 * f2 > product:
break
return [f1, f2, f1 * f2 == product]
# return list[0]
| true |
1687b77c4b2d3c44b6871e653a974153db7d3f96 | ntuthukojr/holbertonschool-higher_level_programming-6 | /0x07-python-test_driven_development/0-add_integer.py | 578 | 4.125 | 4 | #!/usr/bin/python3
"""Add integer module."""
def add_integer(a, b=98):
"""
Add integer function.
@a: integer or float to be added.
@b: integer or float to be added (default set to 98).
Returns the result of the sum.
"""
if not isinstance(a, int) and not isinstance(a, float):
raise TypeError('a must be an integer')
if not isinstance(b, int) and not isinstance(b, float):
raise TypeError('b must be an integer')
if isinstance(a, float):
a = int(a)
if isinstance(b, float):
b = int(b)
return (a + b)
| true |
53bf0300d334909355777fa043e37beb823bd7d2 | NixonRosario/Encryption-and-Decryption | /main.py | 2,772 | 4.1875 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
# The Encryption Function
def cipher_encrypt(plain_text, key): # key is used has an swifting value
encrypted = ""
for c in plain_text:
if c.isupper(): # check if it's an uppercase character
c_index = ord(c) - ord('A') # ord('A') used because A is the first value in the alphabet
# shift the current character by key positions
c_shifted = (c_index + key) % 26 + ord('A')
c_new = chr(c_shifted)
encrypted += c_new
elif c.islower(): # check if its a lowercase character
# subtract the unicode of 'a' to get index in [0-25] range
c_index = ord(c) - ord('a')
c_shifted = (c_index + key) % 26 + ord('a')
c_new = chr(c_shifted)
encrypted += c_new
elif c.isdigit():
# if it's a number,shift its actual value
c_new = (int(c) + key) % 10
encrypted += str(c_new)
else:
# if its neither alphabetical nor a number, just leave it like that
encrypted += c
return encrypted
# The Decryption Function
def cipher_decrypt(ciphertext, key):
decrypted = ""
for c in ciphertext:
if c.isupper():
c_index = ord(c) - ord('A')
# shift the current character to left by key positions to get its original position
c_og_pos = (c_index - key) % 26 + ord('A')
c_og = chr(c_og_pos)
decrypted += c_og
elif c.islower():
c_index = ord(c) - ord('a')
c_og_pos = (c_index - key) % 26 + ord('a')
c_og = chr(c_og_pos)
decrypted += c_og
elif c.isdigit():
# if it's a number,shift its actual value
c_og = (int(c) - key) % 10
decrypted += str(c_og)
else:
# if its neither alphabetical nor a number, just leave it like that
decrypted += c
return decrypted
plain_text = input("Enter the message:- ")
ciphertext1 = cipher_encrypt(plain_text, 4) # function calling is made
print("Your text message:\n", plain_text)
print("Encrypted ciphertext:\n", ciphertext1)
n = input("If you want to decrypt any text press y else n: ")
if n == "y":
ciphertext = input("Enter the Encrypted text:- ")
decrypted_msg = cipher_decrypt(ciphertext, 4)
print("The decrypted message is:\n", decrypted_msg)
else:
print("Thank You!!")
| true |
29d0f0a5b83dbbcee5f053a2455f9c8722b6cb51 | MrYsLab/pseudo-microbit | /neopixel.py | 2,943 | 4.21875 | 4 | """
The neopixel module lets you use Neopixel (WS2812) individually
addressable RGB LED strips with the Microbit.
Note to use the neopixel module, you need to import it separately with:
import neopixel
Note
From our tests, the Microbit Neopixel module can drive up to around 256
Neopixels. Anything above that and you may experience weird bugs and issues.
NeoPixels are fun strips of multi-coloured programmable LEDs.
This module contains everything to plug them into a micro:bit
and create funky displays, art and games
Warning
Do not use the 3v connector on the Microbit to power any more than
8 Neopixels at a time.
If you wish to use more than 8 Neopixels, you must use a separate
3v-5v power supply for the Neopixel power pin.
Operations
Writing the colour doesn’t update the display (use show() for that).
np[0] = (255, 0, 128) # first element
np[-1] = (0, 255, 0) # last element
np.show() # only now will the updated value be shown
To read the colour of a specific pixel just reference it.
print(np[0])
Using Neopixels
Interact with Neopixels as if they were a list of tuples.
Each tuple represents the RGB (red, green and blue) mix of colours
for a specific pixel. The RGB values can range between 0 to 255.
For example, initialise a strip of 8 neopixels on a strip connected
to pin0 like this:
import neopixel
np = neopixel.NeoPixel(pin0, 8)
Set pixels by indexing them (like with a Python list). For instance,
to set the first pixel to full brightness red, you would use:
np[0] = (255, 0, 0)
Or the final pixel to purple:
np[-1] = (255, 0, 255)
Get the current colour value of a pixel by indexing it. For example,
to print the first pixel’s RGB value use:
print(np[0])
Finally, to push the new colour data to your Neopixel strip, use the .show() function:
np.show()
If nothing is happening, it’s probably because you’ve forgotten this final step..!
Note
If you’re not seeing anything change on your Neopixel strip,
make sure you have show() at least somewhere otherwise your updates won’t be shown.
"""
from typing import Tuple, List, Union
from microbit import MicroBitDigitalPin
class NeoPixel:
def __init__(self, pin: MicroBitDigitalPin, n: int):
"""
Initialise a new strip of n number of neopixel LEDs controlled via pin pin.
Each pixel is addressed by a position (starting from 0).
Neopixels are given RGB (red, green, blue) values between 0-255 as a tuple.
For example, (255,255,255) is white.
"""
def clear(self) -> None:
"""
Clear all the pixels.
"""
def show(self) -> None:
"""
Show the pixels. Must be called for any updates to become visible.
"""
def __len__(self) -> int:
pass
def __getitem__(self, key) -> Tuple[int, int, int]:
pass
def __setitem__(self, key: int, value: Union[Tuple[int, int, int], List[int]]):
pass
| true |
638715d691110084c104bba50daefd5675aea398 | baif666/ROSALIND_problem | /find_all_substring.py | 501 | 4.25 | 4 | def find_all(string, substr):
'''Find all the indexs of substring in string.'''
#Initialize start index
i = -1
#Creat a empty list to store result
result = []
while True:
i = string.find(substr, i+1)
if i < 0:
break
result.append(i)
return result
if __name__ == '__main__':
string = input('Please input your string : ')
substr = input("Please input your substring : ")
print('Result : ', find_all(string, substr))
| true |
b0cad0b1e60d45bc598647fa74cb1c584f23eeaa | JGMEYER/py-traffic-sim | /src/physics/pathing.py | 1,939 | 4.1875 | 4 | from abc import ABC, abstractmethod
from typing import Tuple
import numpy as np
class Trajectory(ABC):
@abstractmethod
def move(self, max_move_dist) -> (Tuple[float, float], float):
"""Move the point along the trajectory towards its target by the
specified distance.
If the point would reach the target in less than the provided move
distance, move the point only to the target destination.
max_move_dist - maximum distance point can move towards target
returns: (new_x, new_y), distance_moved
"""
pass
class LinearTrajectory(Trajectory):
"""Trajectory that moves a point linearly towards a target point."""
def __init__(self, start_x, start_y, end_x, end_y):
self._cur_x, self._cur_y = start_x, start_y
self._end_x, self._end_y = end_x, end_y
def move(self, max_move_dist) -> (Tuple[float, float], float):
"""See parent method for desc."""
dx = self._end_x - self._cur_x
dy = self._end_y - self._cur_y
# Optimization
if dx == 0 or dy == 0:
norm = max(abs(dx), abs(dy))
# Target reached
if max_move_dist >= norm:
return (self._end_x, self._end_y), max_move_dist - norm
self._cur_x += np.sign(dx) * max_move_dist
self._cur_y += np.sign(dy) * max_move_dist
return (self._cur_x, self._cur_y), max_move_dist
else:
vector = np.array([dx, dy])
norm = np.linalg.norm(vector)
# Target reached
if max_move_dist >= norm:
return (self._end_x, self._end_y), max_move_dist - norm
unit = vector / norm
self._cur_x, self._cur_y = tuple(
np.array([self._cur_x, self._cur_y])
+ max_move_dist * np.array(unit)
)
return (self._cur_x, self._cur_y), max_move_dist
| true |
d45df8bc1090aee92d3b02bb4e1d42fc93c402a0 | dheerajkjha/PythonBasics_Udemy | /programmingchallenge_addition_whileloop.py | 285 | 4.25 | 4 | number = int(input("Please enter an Integer number."))
number_sum = 0
print("Entered number by the user is: " + str(number))
while number > 0:
number_sum = number_sum + number
number = number - 1
print("Sum of the numbers from the entered number and 1 is: " + str(number_sum))
| true |
e96f81fc4967ca2dbb9993097f2653632b08a613 | dheerajkjha/PythonBasics_Udemy | /programmingchallenge_numberofcharacters_forloop.py | 258 | 4.34375 | 4 | user_string = input("Please enter a String.")
number_of_characters = 0
for letter in user_string:
number_of_characters = number_of_characters + 1
print(user_string)
print("The number of characters in the input string is: " + str(number_of_characters))
| true |
5e865b5a2ac4f087c4fe118e0423ef05908a4a09 | reedless/dailyinterviewpro_answers | /2019_08/daily_question_20190827.py | 528 | 4.5 | 4 | '''
You are given an array of integers. Return the largest product that
can be made by multiplying any 3 integers in the array.
Example:
[-4, -4, 2, 8] should return 128 as the largest product can be made by multiplying -4 * -4 * 8 = 128.
'''
def maximum_product_of_three(lst):
lst.sort()
cand1 = lst[0] * lst[1] * lst[-1]
cand2 = lst[-3] * lst[-2] * lst[-1]
if (cand1 > cand2):
return cand1
else:
return cand2
print (maximum_product_of_three([-4, -4, 2, 8]))
# 128
| true |
5e9bb62185611666f43897fd2033bae28d91ee18 | reedless/dailyinterviewpro_answers | /2019_08/daily_question_20190830.py | 806 | 4.21875 | 4 | '''
Implement a queue class using two stacks.
A queue is a data structure that supports the FIFO protocol (First in = first out).
Your class should support the enqueue and dequeue methods like a standard queue.
'''
class Queue:
def __init__(self):
self.head = []
self.stack = []
def enqueue(self, val):
self.stack.append(val)
def dequeue(self):
while (self.stack):
elem = self.stack.pop()
self.head.append(elem)
result = self.head.pop()
while (self.head):
elem = self.head.pop()
self.stack.append(elem)
return result
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
print (q.dequeue())
print (q.dequeue())
print (q.dequeue())
# 1 2 3
| true |
f1d328556b13e5d99c75d43cd750585184d9d9fa | deltahedge1/decorators | /decorators2.py | 1,008 | 4.28125 | 4 | import functools
#decorator with no arguments
def my_decorator(func):
@functools.wraps(func)
def function_that_runs_func(*args, **kwargs): #need to add args and kwargs
print("in the decorator")
func(*args, **kwargs) #this is the original function, dont forget to add args and kwargs
print("after the decorator")
return function_that_runs_func
@my_decorator
def my_function(x,y):
print(x+y)
my_function("hello ", "Ish")
#decorators that can accepts arguments themselves
def decorator_with_arguments(number):
def my_decorator(func):
@functools.wraps(func)
def function_that_runs_func(*arg, **kwargs): #args and kwargs needed to pass in arguments to original function
print("in the decorator")
if number == 56:
print("Not running the function!")
else:
func(*args, **kwargs)
print("After the decorator")
return function_that_runs_func
return my_decorator
| true |
0ac3a65fea58acea5bc8ae4b1bbf9a4fb45b9f87 | Hilamatu/cse210-student-nim | /nim/game/board.py | 1,548 | 4.25 | 4 | import random
class Board:
"""A board is defined as a designated playing surface.
The responsibility of Board is to keep track of the pieces in play.
Stereotype: Information Holder
Attributes:
"""
def __init__(self):
self._piles_list = []
self._prepare()
def to_string(self):
"""converts the board data to its string representation and returns it to the caller."""
print("-" *10)
for count, value in enumerate(self._piles_list):
print(f"{count}: " + "O " * value)
print("-" *10)
def apply(self, move):
"""applies a move to the playing surface. In this case, that means removing a number of stones from a pile.
Accepts one argument, an instance of Move."""
pile = move.get_pile()
stone = move.get_stones()
reduce = self._piles_list[pile] - stone
self._piles_list[pile] = reduce
def is_empty(self):
"""determines if all the stones have been removed from the board.
It returns True if the board has no stones on it; false if otherwise."""
empty = [0] * len(self._piles_list)
return self._piles_list == empty
def _prepare(self):
"""sets up the board with a random number of piles (2 - 5)
containing a random number of stones (1 - 9)."""
piles = random.randint(2, 5)
for n in range(piles):
stones = random.randint(1, 9)
self._piles_list.append(stones)
| true |
686e53872c553c6dedc03dac6cf19806cc10b19e | NenadPantelic/Cracking-the-coding-Interview | /LinkedList/Partition.py | 1,985 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 3 16:45:16 2020
@author: nenad
"""
"""
Partition: Write code to partition a linked list around a value x, such that all nodes less than x come
before all nodes greater than or equal to x. If x is contained within the list, the values of x only need
to be after the elements less than x (see below). The partition element x can appear anywhere in the
"right partition"; it does not need to appear between the left and right partitions.
"""
class Node:
def __init__(self, data): # data -> value stored in node
self.data = data
self.next = None
def partition(head, x):
if head is None:
return None
# ll with elements less than x
less_ll_head = None
# ll with element greater than or equal to x
greater_ll_head = None
# last added nodes for both sublists
prev_sm_node = None
prev_gr_node = None
node = head
while node:
# add to left sublist
if node.data < x:
if less_ll_head is None:
less_ll_head = node
else:
prev_sm_node.next = node
prev_sm_node = node
#prev_sm_node.next = None
else:
if greater_ll_head is None:
greater_ll_head = node
else:
prev_gr_node.next = node
prev_gr_node = node
#prev_gr_node.next = None
node = node.next
# make tails
prev_sm_node.next = None
prev_gr_node.next = None
# concatenate lists
prev_sm_node.next = greater_ll_head
return less_ll_head
def print_list(head):
node = head
while node:
print(node.data, end=" ")
node = node.next
print()
n1 = Node(3)
n2 = Node(5)
n3 = Node(8)
n4 = Node(5)
n5 = Node(10)
n6 = Node(2)
n7 = Node(1)
n1.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
n5.next = n6
n6.next = n7
x = 5
head = partition(n1, 5)
print_list(head) | true |
886195fb51ac965a88f3ad3c3d505548638cc6bd | JadsyHB/holbertonschool-python | /0x06-python-classes/102-square.py | 2,010 | 4.59375 | 5 | #!/usr/bin/python3
"""
Module 102-square
Defines Square class with private attribute, size validation and area
accessible with setters and getters
comparison with other squares
"""
class Square:
"""
class Square definition
Args:
size: size of side of square, default size is 0
Functions:
__init__self, size)
size(self)
size(self, value)
area(self)
"""
def __init__(self, size=0):
"""
Initilization of square
Attributes:
size: size of side of square, default value is 0
"""
self.size = size
@property
def size(self):
"""
Getter
Return: size
"""
return self.__size
@size.setter
def size(self, value):
"""
Setter
Args:
value: size is set to value when value is an int
"""
if type(value) is not int:
raise TypeError("size must be an integer")
elif value < 0:
raise ValueError("size must be >= 0")
else:
self.__size = value
def area(self):
"""
Calculates are of a square
Returns:
area
"""
return (self.__size)**2
def __eq__(self, other):
"""
Compares if equals
"""
return self.size == other.size
def __ne__(self, other):
"""
Compares if not equals
"""
return self.size != other.size
def __lt__(self, other):
"""
Compares if less than
"""
return self.size < other.size
def __le__(self, other):
"""
Compares if less than or equal
"""
return self.size <= other.size
def __gt__(self, other):
"""
Compares if greater than
"""
return self.size > other.size
def __ge__(self, other):
"""
Compares if greater than or equal
"""
return self.size >= other.size
| true |
55ffa8c32622c42f6d3a314018a0adaf0e1c0d18 | JadsyHB/holbertonschool-python | /0x06-python-classes/1-square.py | 373 | 4.125 | 4 | #!/usr/bin/python3
"""
Module 1-square
class Square defined with private attribute size
"""
class Square:
"""
class Square
Args:
size: size of a side in a square
"""
def __init__(self, size):
"""
Initialization of square
Attributes:
size: size of a side of a square
"""
self.__size = size
| true |
96384a26d49430e18697d080c49f3341e7b13834 | 23o847519/Python-Crash-Course-2nd-edition | /chapter_08/tryityourself814.py | 874 | 4.4375 | 4 | # 8-14. Cars: Write a function that stores information about
# a car in a dictionary. The function should always receive
# a manufacturer and a model name. It should then accept an
# arbitrary number of keyword arguments. Call the function
# with the required information and two other name-value
# pairs, such as a color or an optional feature. Your
# function should work for a call like this one:
# car = make_car('subaru', 'outback', color='blue',
# tow_package=True)
# Print the dictionary that’s returned to make sure all
# the information was stored correctly.
print("\nEx 8.14 Cars\n" + "-"*70)
def make_car(manufacturer, model, **car_info):
car_info['manufacturer'] = manufacturer
car_info['model'] = model
return car_info
car_profile = make_car(model = 'outback', manufacturer = 'subaru', color = 'blue', tow_package = True)
print(car_profile)
| true |
e0f7b4c472500360a03266df6e35031cd4534dc4 | 23o847519/Python-Crash-Course-2nd-edition | /chapter_07/tryityourself7.1.py | 334 | 4.15625 | 4 | # Ex 7.1 Rental Car
# Write a program that asks the user what kind of rental car they
# would like. Print a message about that car, such as
# “Let me see if I can find you a Subaru.”
print("\nEx 7.1")
rental_car = input("What kind of rental car would you like?\n")
print(f"\nLet me see if I can find you a {rental_car.title()}.") | true |
9cca96cb78e6ae2772c76f81ccf6a2106ee0ac99 | 23o847519/Python-Crash-Course-2nd-edition | /chapter_03/cars.py | 604 | 4.28125 | 4 | #Sorting
print("\nSorting")
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.sort()
print(cars)
#Reverse sorting
print("\nReverse sorting")
cars.sort(reverse=True)
print(cars)
#Sort tạm thời
print("\n Sorted()")
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Original list:")
print(cars)
print("\nSorted list:")
print(sorted(cars))
print("\nCome back to Original list:")
print(cars)
#Reverse list
#Đảo ngược toàn bộ list
print("\nReverse list")
print(cars)
cars.reverse()
print(cars)
#Length of List
print("\nLength of List")
cars.reverse()
print(cars)
print(len(cars))
| true |
44f55bae68ae6fa0fddd6628dea0c92e1f0d81fe | 23o847519/Python-Crash-Course-2nd-edition | /chapter_10/tryityourself106.py | 726 | 4.3125 | 4 | # 10-6. Addition: One common problem when prompting for numerical input
# occurs when people provide text instead of numbers. When you try to
# convert the input to an int, you’ll get a ValueError. Write a program
# that prompts for two numbers. Add them together and print the result.
# Catch the ValueError if either input value is not a number, and print
# a friendly error message. Test your program by entering two numbers
# and then by entering some text instead of a number.
print("\nEx 10.6 Addition\n" + "-"*70)
print("Give me a number\n")
try:
num1 = input("First_number = ")
num1 = int(num1)
except ValueError:
print("Value Error!, Enter a number next time.")
else:
print(f"Your number: {num1}") | true |
6ba1d02a2025378d11c0cfbf8a11055e0593e3ca | radishmouse/06-2017-cohort-python | /104/n_to_m.py | 629 | 4.375 | 4 | n = int(raw_input("Start from: "))
m = int(raw_input("End on: "))
# Let's use a while loop.
# Every while loop requires three parts:
# - the while keyword
# - the condition that stops the loop
# - a body of code that moves closer to the "stop condition"
# our loop counts up to a value.
# let's declare a counter variable
# and set the counter to start at n
count = n
# only run if count is less than or equal to the value of m
while count <= m:
# remember, we have to indent the body of our loop
# print the current value of count
print count
# move us closer to the "stop condition"
count = count + 1
| true |
50cbb178c40d42e83aed3f936feef223eca8a865 | radishmouse/06-2017-cohort-python | /dictionaries/dictionary1.py | 534 | 4.21875 | 4 | phonebook_dict = {
'Alice': '703-493-1834',
'Bob': '857-384-1234',
'Elizabeth': '484-584-2923'
}
#Print Elizabeth's phone number.
print phonebook_dict['Elizabeth']
#Add a entry to the dictionary: Kareem's number is 938-489-1234.
phonebook_dict['Kareem'] = '938-489-1234'
#Delete Alice's phone entry.
del phonebook_dict['Alice']
#Change Bob's phone number to '968-345-2345'.
phonebook_dict['Bob'] = '968-345-2345'
#Print all the phone entries.
for person, phone in phonebook_dict.items():
print "%s: %s" % (person, phone) | true |
6ebffaee162c491cc4f2289845a1bf7bbcd33604 | flub78/python-tutorial | /examples/conditions.py | 374 | 4.1875 | 4 | #!/usr/bin/python
# -*- coding:utf8 -*
print ("Basic conditional instructions\n")
def even(a):
if ((a % 2) == 0):
print (a, "is even")
if (a == 0):
print (a, " == 0")
return True
else:
print (a, "is odd")
return False
even(5)
even(6)
even(0)
bln = even(6)
if bln:
print ("6 is even")
print ("bye")
| true |
0e531d7c0b4da023818f02265ab9e009420eaec6 | flub78/python-tutorial | /examples/test_random.py | 1,395 | 4.1875 | 4 | #!/usr/bin/python
# -*- coding:utf8 -*
"""
How to use unittest
execution:
python test_random.py
or
python -m unittest discover
"""
import random
import unittest
class RandomTest(unittest.TestCase):
""" Test case for random """
def test_choice(self):
"""
given: a list
when: selecting a random elt
then: it belongs ot the list
"""
lst = list(range(10))
# print lst
elt = random.choice(lst)
# print "random elt = ", elt
self.assertIn(elt, lst)
self.assertFalse(elt % 4 == 0, "True quite often")
def test_shuffle(self):
"""
given: a list
when: shuffled
then: it still contains the same elements
likely in different order
"""
lst = list(range(10))
shuffled = list(lst) # deep copy
random.shuffle(shuffled)
# print "lst =", lst
# print "shuffled= ", shuffled
sorted = list(shuffled)
sorted.sort()
# print "sorted = ", sorted
same_order = True
i = 0
while i < 10:
same_order = same_order and (lst[i] == shuffled[i])
i += 1
self.assertEqual(sorted, lst)
self.assertFalse(same_order, "list are not in the same order after shuffling")
if __name__ == '__main__':
unittest.main()
| true |
38081fd73316e20f6361d835d710dd379e8c78ea | andremmfaria/exercises-coronapython | /chapter_06/chapter_6_6_4.py | 823 | 4.375 | 4 | # 6-4. Glossary 2: Now that you know how to loop through a dictionary, clean up the code from Exercise 6-3 (page 102) by replacing your series of print statements with ía loop that runs through the dictionary’s keys and values. When you’re sure that your loop works, add five more Python terms to your glossary. When you run your program again, these new words and meanings should automatically be included in the output.
valdict = {
"variable": "Elementar data type that stores values",
"loop": "Self repeating structure",
"dictionary": "Glossary structure",
"array": "List of elements",
"conditional": "Conditional test",
"word0": "Value0",
"word1": "Value1",
"word2": "Value2",
"word3": "Value3",
"word4": "Value4"
}
for key in valdict:
print(key + ", " + valdict[key]) | true |
8c5498b935164c457447729c6de1553b390664e5 | andremmfaria/exercises-coronapython | /chapter_06/chapter_6_6_8.py | 522 | 4.34375 | 4 | # 6-8. Pets: Make several dictionaries, where the name of each dictionary is the name of a pet. In each dictionary, include the kind of animal and the owner’s name. Store these dictionaries in a list called pets. Next, loop through your list and as you do print everything you know about each pet.
pet_0 = {
'kind' : 'dog',
'owner' : 'Juliana'
}
pet_1 = {
'kind' : 'cat',
'owner' : 'Ana'
}
pet_2 = {
'kind' : 'fish',
'owner' : 'Joao'
}
pets = [pet_0, pet_1, pet_2]
for p in pets:
print(p) | true |
7bc98b1c9a50acb1e7ff7fe3ce2781ace3a56eb8 | andremmfaria/exercises-coronapython | /chapter_07/chapter_7_7_1.py | 257 | 4.21875 | 4 | # 7-1. Rental Car: Write a program that asks the user what kind of rental car they would like. Print a message about that car, such as “Let me see if I can find you a Subaru.”
message = input("Let me see whether I can find you a Subaru")
print(message) | true |
5cb4a583ec8a49434d41500e142cb79879070d1a | mkccyro-7/Monday_test | /IF.py | 226 | 4.15625 | 4 | bis = int(input("enter number of biscuits "))
if bis == 3:
print("Not eaten")
elif 0 < bis < 3:
print("partly eaten")
elif bis == 0:
print("fully eaten")
else:
print("Enter 3 or any other number less than 3")
| true |
4ccb729ebdb80510424aa920666f6b4f0acb5a2a | ErenEla/PythonSearchEngine | /Unit_1/Unit1_Hw3.py | 1,060 | 4.1875 | 4 | # IMPORTANT BEFORE SUBMITTING:
# You should only have one print command in your function
# Given a variable, x, that stores the
# value of any decimal number, write Python
# code that prints out the nearest whole
# number to x.
# If x is exactly half way between two
# whole numbers, round up, so
# 3.5 rounds to 4 and 2.5 rounds to 3.
# You may assume x is not negative.
# Hint: The str function can convert any number into a string.
# eg str(89) converts the number 89 to the string '89'
# Along with the str function, this problem can be solved
# using just the information introduced in unit 1.
# x = 3.14159
# >>> 3 (not 3.0)
# x = 27.63
# >>> 28 (not 28.0)
# x = 3.5
# >>> 4 (not 4.0)
#ENTER CODE BELOW HERE
x = 3.14159
x_round = str(round(x))
x_point = x_round.find(".")
print(x_round[:x_point])
#Train Focus
s = "CidatyUcityda"
print('1',s[6]+s[-2:]+s[7:12])
print('2',s[6]+s[-2:]+s[7:11])
print('3',s[6]+s[2:4]+s[7:13])
print('4',s[-7]+s[2:4]+s[7:11])
print('5',s[6]+s[-2]+s[3]+s[:-2]+s[4:6])
print('6',s[6]+s[2]+s[3]+s[7:11]) | true |
4ed0dc77c6784f2006ca437568f80a73a8d51438 | ErenEla/PythonSearchEngine | /Unit_3/Unit3_Quiz1.py | 504 | 4.15625 | 4 | # Define a procedure, replace_spy,
# that takes as its input a list of
# three numbers, and modifies the
# value of the third element in the
# input list to be one more than its
# previous value.
spy = [1,2,2]
def replace_spy(x):
x[0] = x[0]
x[1] = x[1]
x[2] = x[2]+1
return x
# In the test below, the first line calls your
# procedure which will change spy, and the
# second checks you have changed it.
# Uncomment the top two lines below.
print(replace_spy(spy))
#>>> [0,0,8]
| true |
66c4d00e9ce49d8570cd7a703d04aef1b6b4d3f6 | iSabbuGiri/Control-Structures-Python- | /qs_17.py | 962 | 4.21875 | 4 | #Python program that serves as a basic calculator
def add(x,y):
return x+y
def subtract(x,y):
return x-y
def multiply(x,y):
return x*y
def divide(x,y):
return x/y
print("Select operation:")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
choice = input("Enter a choice(1/2/3/4):")
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter the first number:"))
num2 = float(input("Enter the second number:"))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2) )
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2) )
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2) )
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2) )
break
else:
print("Invalid Input")
| true |
3ba2ea80dcc916bf8e245a2ab518042b9ee55e3e | richardrcw/python | /guess.py | 270 | 4.1875 | 4 | import random
highest = 10
num = random.randint(1, highest)
guess = -1
while guess != num:
guess = int(input("Guess number between 1 and {}: ".format(highest)))
if guess > num:
print("Lower...")
elif guess < num:
print("Higher....")
else:
print("Got it!")
| true |
efabcf8f6f413c833a75c8cc5e57e556c2d12823 | prathamarora10/guessingNumber | /GuessingNumber.py | 561 | 4.21875 | 4 | print('Number Guessing Game')
print('Guess a Number (between 1 and 9):')
import random
number = random.randint(1,9)
print(number)
for i in range(0,5,1):
userInput = int(input('Enter your Guess :- '))
if userInput < 3:
print('Your guess was too low: Guess a number higher than 3')
elif userInput < 5:
print('Your guess was too low: Guess a number higher than 5')
elif userInput < 7:
print('Your guess was too low: Guess a number higher than 7')
if userInput == number:
print('Congratulations !\nYou Won !!')
| true |
39cebe0780b8532517dadf4fd04517b9ba79f207 | Carterhuang/sql-transpiler | /util.py | 922 | 4.375 | 4 | def standardize_keyword(token):
""" In returned result, all keywords are in upper case."""
return token.upper()
def join_tokens(lst, token):
"""
While joining each element in 'lst' with token,
we want to make sure each word is separated
with space.
"""
_token = token.strip(' ')
if _token == '':
# token only has empty space(s) in it,
# we make standardize it to be one empty space.
_token = ' '
else:
# Paddle a space on the left and right side of the token,
# so that "AND" becomes " AND ".
_token = ''.join([' ', standardize_keyword(_token), ' '])
return _token.join(map(str, lst))
def normalize_keyword(input_str):
"""
During transpiling, all reserved keywords(operators,
macro/field headers, etc) are converted to lower case.
e.g. 'AND' -> 'and', 'OR' -> 'or', etc.
"""
return input_str.lower()
| true |
8c9890c843a63d8b2fa90098b28594ba1e012d99 | justinhohner/python_basics | /datatypes.py | 1,042 | 4.34375 | 4 | #!/usr/local/bin/python3
# https://www.tutorialsteacher.com/python/python-data-types
#
"""
Numeric
Integer: Positive or negative whole numbers (without a fractional part)
Float: Any real number with a floating point representation in which a fractional component is denoted by a decimal symbol or scientific notation
Complex number: A number with a real and imaginary component represented as x+yj. x and y are floats and j is -1(square root of -1 called an imaginary number)
"""
x = 1
print(x)
y = 1.1
print(y)
j = -1
print(j)
i = x+j*y
print(i)
# Boolean
a = True
b = False
print(a)
print(b)
# String
a = "This is a string"
print(a)
# List
a = ["This", "is", "a", "list"]
print(a)
# Tuple
a = ("This", "is", "a", "list", 0)
print(a)
# Dictionary
a = {1:"Steve", 2:"Bill", 3:"Ram", 4: "Farha"}
print(a)
a = {"Steve":1, "Bill":2, "Ram":3, "Farha":4}
print(a)
"""
Create a variable to store your name and set it's value to your name
Create a list of numbers from 1 to 10
add the first 3 values of the list of numbers
""" | true |
9acddfa9dc609fbb3aad91d19c4348dda1aee239 | jsanon01/100-days-of-python | /resources/day4/area_circumference_circle.py | 427 | 4.59375 | 5 | """
Fill out the functions to calculate the area and circumference of a circle.
Print the result to the user.
"""
import math
def area(r):
return math.pi * r ** 2
def circumference(r):
return math.pi * 2 * r
radius = float(input("Circle radius: "))
circle_area = area(radius)
circle_circumference = circumference(radius)
print('Area: ' + str(circle_area))
print('Circumference: ' + str(circle_circumference))
| true |
e2ca488af3efc7e4d8f5bc72be4ac0a3f139edd9 | saumyatiwari/Algorithm-of-the-day | /api/FirstAPI.py | 790 | 4.125 | 4 | import flask
app=flask.Flask(__name__) #function name is app
# use to create the flask app and intilize it
@app.route("/", methods =['GET']) #Defining route and calling methods. GET will be in caps intalized as an arrya
# if giving the giving any configuration then function name will proceed with @ else it will use name alone for example we are using @app name to updae the config of @app name
def helloworld():
return "Helloworld"
if __name__ == '__main__':
app.run()
# by default flask uses 5000 port and host as 0.0.0.0
# Run steps
#1. Run with python FirstAPI.py
#2. Flask will auto. create a server & start the flask app in dev mode
#3. U can call ur API with address http://0.0.0.0:5000/
#4. First install the flask by command "pip3 install flask" before running the code | true |
1544a910a16011cc302ba6bcb449c0c8887c05ee | msvrk/frequency_dict | /build/lib/frequency_dict/frequency_dict_from_collection.py | 557 | 4.53125 | 5 | def frequency_dict_from_collection(collection):
"""
This is a useful function to convert a collection of items into a dictionary depicting the frequency of each of
the items. :param collection: Takes a collection of items as input :return: dict
"""
assert len(collection) > 0, "Cannot perform the operation on an empty collection"
dictionary = {}
keys = []
for item in collection:
if item not in keys:
keys.append(item)
dictionary[item] = 0
dictionary[item] += 1
return dictionary
| true |
660a467f0428f2564fdeec4da7f5dc171b7a2e65 | DivijeshVarma/CoreySchafer | /Decorators2.py | 2,922 | 4.46875 | 4 | # first class functions allow us to treat functions like any other
# object, for example we can pass functions as arguments to another
# function, we can return functions and we can assign functions to
# variable. Closures-- it will take advantage of first class functions
# and return inner function that remembers and has access to variables
# local to scope in which they were created.
def outer_func(mg):
def inner_func():
print(mg)
return inner_func
hi_func = outer_func('hi')
hello_func = outer_func('hello')
hi_func()
hello_func()
# Decorator is function that takes another function as an argument
# add some functionality and returns another function, all of this
# without altering source code of original function you passed in.
# Decorating our functions allow us to easily add functionality to
# our existing functions, by adding functionality inside wrapper
# without modifying original display function in any way and add
# code in wrapper in any way
def decorator_func(original_func):
def wrapper_func(*args, **kwargs):
print(f"wrapper function executed {original_func.__name__}")
original_func(*args, **kwargs)
return wrapper_func
@decorator_func
def display():
print('display function')
@decorator_func
def display_info(name, age):
print(f"name:{name}, age:{age}")
display()
display_info('divi', 27)
print('--------------------------------')
##################################
class decorator_class(object):
def __init__(self, original_func):
self.original_func = original_func
def __call__(self, *args, **kwargs):
print(f"call method executed {self.original_func.__name__}")
return self.original_func(*args, **kwargs)
@decorator_class
def display():
print('display function')
@decorator_class
def display_info(name, age):
print(f"name:{name}, age:{age}")
display()
display_info('divi', 27)
print('--------------------------------')
##################################
def decorator_func(func):
def wrapper_func(*args, **kwargs):
print(f"wrapper executed before {func.__name__}")
func(*args, **kwargs)
print(f"wrapper executed after {func.__name__}")
return wrapper_func
@decorator_func
def display_info(name, age):
print(f"display function with {name} and {age}")
display_info('divijesh', 27)
print('--------------------------------')
####################################
def prefix_decorator(prefix):
def decorator_func(func):
def wrapper_func(*args, **kwargs):
print(f"{prefix} wrapper executed before {func.__name__}")
func(*args, **kwargs)
print(f"{prefix} wrapper executed after {func.__name__}")
return wrapper_func
return decorator_func
@prefix_decorator('LOG:')
def display_info(name, age):
print(f"display function with {name} and {age}")
display_info('divijesh', 27)
| true |
b1ebc3eeeceebdf1eb6760c88d00be6b40d9e5cd | DivijeshVarma/CoreySchafer | /generators.py | 809 | 4.28125 | 4 | def square_nums(nums):
result = []
for i in nums:
result.append(i * i)
return result
sq_nums = square_nums([1, 2, 3, 4, 5])
print(sq_nums)
# square_nums function returns list , we could convert
# this to generator, we no longer get list
# Generators don't hold entire result in memory
# it yield 1 result at a time, waiting for us to ask
# next result
# when you convert generators to list you lose performance
# like list(sq_nums)
def square_nums(nums):
for i in nums:
yield (i * i)
sq_nums = square_nums([1, 2, 3, 4, 5])
print(sq_nums)
print(next(sq_nums))
for num in sq_nums:
print(num)
# list comprehensions
sqs = [x * x for x in [1, 2, 3, 4, 5]]
print(sqs)
# create generator
sqs = (x * x for x in [1, 2, 3, 4, 5])
print(sqs)
for num in sqs:
print(num)
| true |
e328a29edf17fdeed4d8e6c620fc258d9ad28890 | DivijeshVarma/CoreySchafer | /FirstclassFunctions.py | 1,438 | 4.34375 | 4 | # First class functions allow us to treat functions like
# any other object, i.e we can pass functions as argument
# to another function and returns functions, assign functions
# to variables.
def square(x):
return x * x
f1 = square(5)
# we assigned function to variable
f = square
print(f)
print(f(5))
print(f1)
# we can pass functions as arguments and returns function
# as result of other functions
# if function accepts other functions as arguments or
# return functions as a result i.e higher order function
# adding paranthesis will execute function.
# # we can pass functions as arguments:--
def square(x):
return x * x
def my_map(func, arg_list):
result = []
for i in arg_list:
result.append(func(i))
return result
squares = my_map(square, [1, 2, 3, 4])
print(squares)
# to return a function from another function, one of the
# aspects for first class function
# log variable is equal to log_message function, so we can
# run log variable as just like function, it remembers
# message from logger function
def logger(msg):
def log_message():
print(f"log: {msg}")
return log_message
log = logger('hi')
log()
# it remembers tag we passed earlier
def html_tag(tag):
def wrap_text(msg):
print(f"<{tag}>{msg}<{tag}>")
return wrap_text
p_h1 = html_tag('h1')
p_h1('Test headline')
p_h1('Another headline')
p_p1 = html_tag('p1')
p_p1('Test paragraph')
| true |
4f9c1ddb562de274a644e6d41e73d70195929274 | sairamprogramming/learn_python | /book4/chapter_1/display_output.py | 279 | 4.125 | 4 | # Program demonstrates print statement in python to display output.
print("Learning Python is fun and enjoy it.")
a = 2
print("The value of a is", a)
# Using keyword arguments in python.
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='+')
print(1, 2, 3, 4, sep='+', end='%')
print()
| true |
64c62c53556f38d9783de543225b11be87304daf | sairamprogramming/learn_python | /pluralsight/core_python_getting_started/modularity/words.py | 1,204 | 4.5625 | 5 | # Program to read a txt file from internet and put the words in string format
# into a list.
# Getting the url from the command line.
"""Retrive and print words from a URL.
Usage:
python3 words.py <url>
"""
import sys
def fetch_words(url):
"""Fetch a list of words from a URL.
Args:
url: The url of UTF-8 text document.
Returns:
A list of strings containing the words from
the document.
"""
# Importing urlopen method.
from urllib.request import urlopen
# Getting the text from the url given.
story = urlopen(url)
story_words = []
for line in story:
line_words = line.decode('utf8').split()
for word in line_words:
story_words.append(word)
story.close()
return story_words
def print_items(items):
"""Prints items one per line.
Args:
An iterable series of printable items.
"""
for item in items:
print(item)
def main(url):
"""Prints each word from a text document from a URL.
Args:
url: The url of UTF-8 text document.
"""
words = fetch_words(url)
print_items(words)
if __name__ == '__main__':
main(sys.argv[1])
| true |
99bd7e715f504ce64452c252ac93a026f426554d | gotdang/edabit-exercises | /python/factorial_iterative.py | 414 | 4.375 | 4 | """
Return the Factorial
Create a function that takes an integer and returns
the factorial of that integer. That is, the integer
multiplied by all positive lower integers.
Examples:
factorial(3) ➞ 6
factorial(5) ➞ 120
factorial(13) ➞ 6227020800
Notes:
Assume all inputs are greater than or equal to 0.
"""
def factorial(n):
fact = 1
while n > 1:
fact *= n
n -= 1
return fact
| true |
30d9fe50769150b3efcaa2a1628ef9c7c05984fa | gotdang/edabit-exercises | /python/index_multiplier.py | 428 | 4.125 | 4 | """
Index Multiplier
Return the sum of all items in a list, where each
item is multiplied by its index (zero-based).
For empty lists, return 0.
Examples:
index_multiplier([1, 2, 3, 4, 5]) ➞ 40
# (1*0 + 2*1 + 3*2 + 4*3 + 5*4)
index_multiplier([-3, 0, 8, -6]) ➞ -2
# (-3*0 + 0*1 + 8*2 + -6*3)
Notes
All items in the list will be integers.
"""
def index_multiplier(lst):
return sum([i * v for i, v in enumerate(lst)])
| true |
36f7db179bcc0339c7969dfa9f588dcd51c6d904 | adarshsree11/basic_algorithms | /sorting algorithms/heap_sort.py | 1,200 | 4.21875 | 4 | def heapify(the_list, length, i):
largest = i # considering as root
left = 2*i+1 # index of left child
right = 2*i+2 # index of right child
#see if left child exist and greater than root
if left<length and the_list[i]<the_list[left]:
largest = left
#see if right child exist and greater than root
if right<length and the_list[largest]<the_list[right]:
largest = right
#change root if larger number caught as left or right child
if largest!=i:
the_list[i],the_list[largest]=the_list[largest],the_list[i]
# heapify the new root
heapify(the_list, length, largest)
def heapSort(the_list):
n = len(the_list)
#heapify the full list
for i in range(n//2-1, -1, -1):
#heapify from last element with child to top
heapify(unsorted_list, n, i)
#heapsort sxtracting elements one by one
for i in range(n-1, 0, -1):
#swapping the root element which is max to its position
the_list[i],the_list[0] = the_list[0],the_list[i]
#heapify from root again length reduced to 'i' to keep sorted elements unchanged
heapify(the_list, i, 0)
if __name__ == '__main__':
unsorted_list = [17,87,6,22,54,3,13,41]
print(unsorted_list)
heapSort(unsorted_list)
print(unsorted_list) | true |
88bf240c30c8373b3779a459698223ec3cb74e24 | mliu31/codeinplace | /assn2/khansole_academy.py | 836 | 4.1875 | 4 | """
File: khansole_academy.py
-------------------------
Add your comments here.
"""
import random
def main():
num_correct = 0
while num_correct != 3:
num1 = random.randint(10,99)
num2 = random.randint(10,99)
sum = num1 + num2
answer = int(input("what is " + str(num1) + " + " + str(num2) + "\n>>"))
if sum == answer:
num_correct += 1
print("Correct. You've gotten " + str(num_correct) + " problem(s) right in a row! ")
if num_correct == 3:
print("Congratulations! you've mastered addition")
else:
print("Incorrect. the expected answer is " + str(sum))
num_correct = 0
# This provided line is required at the end of a Python file
# to call the main() function.
if __name__ == '__main__':
main()
| true |
346d3af90d21411c4265d7e232786fc4078f82fc | Tanay-Gupta/Hacktoberfest2021 | /python_notes1.py | 829 | 4.4375 | 4 | print("hello world")
#for single line comment
'''for multi line comment'''
#for printing a string of more than 1 line
print('''Twinkle, twinkle, little star
How I wonder what you are
Up above the world so high
Like a diamond in the sky
Twinkle, twinkle little star
How I wonder what you are''')
a=20
b="hello"
c=39.9
#here a is variable and its datatype is integer
print(a)
#how to print the datatype of a
print(type(a))
print(type(c))
#how to print arithmetic results
a=5
b=3
print ("the sum of a+b is",a+b)
print ("the diff of a-b is",a-b)
print ("the product of a*b is",a*b)
# comparison operators
a=(82<=98)
print(a)
# type conversion and type casting
a="45" #this is a string
# to convert into int
a=int(a)
print(type(a))
b= 34
print(type(b))
b=str(b)
print(type(b)) | true |
f284bdf3b3929131be1fe943b3bd5761119f4c2e | sydney0zq/opencourses | /byr-mooc-spider/week4-scrapy/yield.py | 1,088 | 4.53125 | 5 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
The first time the for calls the generator object created from your function, it will run the code in your function from the beginning until it hits yield, then it'll return the first value of the loop. Then, each other call will run the loop you have written in the function one more time, and return the next value, until there is no value to return.
The generator is considered empty once the function runs but does not hit yield anymore. It can be because the loop had come to an end, or because you do not satisfy an "if/else" anymore.
"""
def gen(n):
print("outside")
for i in range(8):
print ("inside")
yield i ** 2
for i in gen(5):
print (i, " ")
print ("*" * 50)
def gen2(n):
print("outside")
for i in range(n):
print ("inside")
yield i ** 2
n = 3
for i in gen2(n):
#n = 10 this statement does NO effect
print (i)
print ("*" * 50)
def square(n):
print ("inside")
ls = [i**2 for i in range(n)]
return ls
for i in square(5):
print(i)
| true |
88806f1c3ee74fe801b26a11b0f66a3c7d6c881d | Kajabukama/bootcamp-01 | /shape.py | 1,518 | 4.125 | 4 | # super class Shape which in herits an object
# the class is not implemented
class Shape(object):
def paint(self, canvas):
pass
# class canvas which in herits an object
# the class is not implemented
class Canvas(object):
def __init__(self, width, height):
self.width = width
self.height = height
self.data = [[' '] * width for i in range(height)]
# setter method which sets row and column
def setpixel(self, row, col):
self.data[row][col] = '*'
# getter method that will get the values of row and column
def getpixel(self, row, col):
return self.data[row][col]
def display(self):
print "\n".join(["".join(row) for row in self.data])
# the subclass Rectangle which inherits from the Shape Superclass
# inheritance concept
class Rectangle(Shape):
def __init__(self, x, y, w, h):
self.x = x
self.y = y
self.w = w
self.h = h
# a method to draw a horizontal line
def hline(self, x, y, w):
self.x = x
self.y = y
self.w = w
# another method that will draw a vertical line
def vline(self, x, y, h):
self.x = x
self.y = y
self.h = h
# this method calls the other three methods
# and draws the respective shapes on a camnvas
def paint(self, canvas):
hline(self.x, self.y, self.w)
hline(self.x, self.y + self.h, self.w)
vline(self.x, self.y, self.h)
vline(self.x + self.w, self.y, self.h) | true |
157b4ad717a84f91e60fb5dc108bcab8b2a21a12 | jwu424/Leetcode | /RotateArray.py | 1,275 | 4.125 | 4 | # Given an array, rotate the array to the right by k steps, where k is non-negative.
# 1. Make sure k < len(nums). We can use slice but need extra space.
# Time complexity: O(n). Space: O(n)
# 2. Each time pop the last one and inset it into the beginning of the list.
# Time complexity: O(n^2)
# 3. Reverse the list three times.
# Time complexity: O(n)
class Solution:
def rotate1(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
k %= len(nums)
nums[:] = nums[-k:] + nums[:-k]
def rotate2(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
k %= len(nums)
for _ in range(k):
nums.insert(0, nums.pop())
def rotate3(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
k %= len(nums)
self.reverse(nums, 0, len(nums)-1)
self.reverse(nums, 0, k-1)
self.reverse(nums, k, len(nums)-1)
def reverse(self, nums, left, right):
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1 | true |
da8890ff1f941e97b8174bc6e111272b6ffa0b20 | OliverMorgans/PythonPracticeFiles | /Calculator.py | 756 | 4.25 | 4 | #returns the sum of num1 and num 2
def add(num1, num2):
return num1 + num2
def divide(num1, num2):
return num1 / num2
def multiply(num1, num2):
return num1 * num2
def minus (num1, num2):
return num1 - num2
#*,-,/
def main():
operation = input("what do you want to do? (+-*/): ")
if(operation != "+" and operation != "-" and operation != "*" and operation != "/"):
#invalid operation
print("You must enter a valid operation (+-*/)")
else:
num1 = int(input("Enter num1: "))
num2 = int(input("Enter num2: "))
if(operation == "+"):
print(add(num1, num2))
elif(operation == "-"):
print(minus(num1, num2))
elif(operation == "*"):
print(multiply(num1, num2))
elif(operation == "/"):
print(divide(num1, num2))
main()
| true |
261a8ec6e763de736e722338241d2cf39a34c9b0 | Rggod/codewars | /Roman Numerals Decoder-6/decoder.py | 1,140 | 4.28125 | 4 | '''Problem:
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered "MCMXC" (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered "MMVIII" (2000 = MM, 8 = VIII). The Roman numeral for 1666, "MDCLXVI", uses each letter in descending order.
Example:
solution('XXI') # should return 21 '''
def solution(roman):
"""complete the solution by transforming the roman numeral into an integer"""
values = {'I' : 1 ,'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000}
sum = 0
count = 0
while(count < len(roman)):
cur = values.get(roman[count],' ')
if count == len(roman) -1 or (cur >= values.get(roman[count+1],' ')):
sum = sum + cur
else:
sum = sum +(values.get(roman[count+1],' ')-cur)
count = count +1
count = count +1
return sum
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.