blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
2ae130d5f467c00cd8c54b05409bbf4839b8579a | shaunn/projecteuler | /Problem1/py/p1.py | 1,730 | 4.21875 | 4 | # divisors of 3 and 5
#
# Problem 1
# If we list all the natural numbers below 10 that are divisors of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these divisors is 23.
#
# Find the sum of all the divisors of 3 or 5 below 1000.
# Strategies
#
# 1. `remainder = dividend - divisor * quotient` and `remainder=0`
# 2. Using the built-in modulo function
# 3. Using the built-in remainder function
# Packages! tbd...
# Constants and variables!
# Set the upper limit
upper_limit = 1000
# Set the list of divisors to test against
divisors = [3, 5]
# Define the 'summer' containing the running of sums
summer = 0
# Functions!
def test_if_multiple(test_number, test_divisor):
if test_number < test_divisor:
return False
if test_zero_using_modulo_function(test_number, test_divisor):
return True
else:
return False
def test_zero_using_modulo_function(test_number, test_divisor):
# 2. Using the built-in modulo function
test = test_number % test_divisor
if test == 0:
return True
else:
return False
def main():
global summer
# Note that the range function is the total number of elements starting at 0.
# Conveniently this satisfies the "below 1000" requirement out of the box!
for number in range(upper_limit):
# Rules state 'Find the sum of all the divisors of 3 or 5'
# Once a match is found for the multiple, don't perform further processing
multiple = False
for divisor in divisors:
if not multiple:
if test_if_multiple(number, divisor):
multiple = True
summer = summer + number
print(str(summer))
if __name__ == "__main__":
main()
| true |
ab403bbb4698cc504ca55c83af4067710a785ae6 | ziyadalvi/PythonBook | /6The Dynamic Typing Interlude/3GarbageCollection.py | 1,251 | 4.28125 | 4 | #when we reassign a variable, what happens to the value it was
#previously referencing? For example, after the following statements, what happens to
#the object 3?
"""The answer is that in Python, whenever a name is assigned to a new object, the space
held by the prior object is reclaimed if it is not referenced by any other name or object.
This automatic reclamation of objects’ space is known as garbage collection"""
x = 42
x = 'shrubbery' # Reclaim 42 now (unless referenced elsewhere)
x = 3.1415 # Reclaim 'shrubbery' now
x = [1, 2, 3] # Reclaim 3.1415 now
#notice that x is set to a different type of object each time. Again, though this is
#not really the case, the effect looks like that the type of x is changing over time.
#Each time x is
#assigned to a new object, Python reclaims the prior object’s space. For instance, when
#it is assigned the string 'shrubbery', the object 42 is immediately reclaimed (assuming
#it is not referenced anywhere else)
#Internally, Python accomplishes this feat by keeping a counter in every object that keeps
#track of the number of references currently pointing to that object. As soon as (and
#exactly when) this counter drops to zero, the object’s memory space is automatically
#reclaimed
| true |
655c7e3810af8e5c502f65f2a95892598a45e1b9 | anila-a/CEN-206-Data-Structures | /lab04/mainPolygon.py | 1,306 | 4.5625 | 5 | '''
Program: mainPolygon.py
Author: Anila Hoxha
Last date modified: 03/21/2020
Design a class named Polygon to represent a regular polygon. In regular
polygon, all the sides have the same length. The class contains:
Constructor: Instance Variable: n – number of sides with default value 3,
side – length of the side with default value 1.
Methods:
• Getters and Setters methods for all instance variables
• getPerimeter() that returns the perimeter of the polygon.
• getArea() that returns the area of the polygon.
Use the following test program mainPolygon.py that creates two Polygon objects - one
with no-arg constructor and the other with Polygon(8, 5).
'''
from polygon import * # Import Polygon class from polygon.py file
# Create objects
poly1 = Polygon()
poly2 = Polygon(8, 5)
print("Polygon 1: ")
print(" # of sides: ", poly1.getN())
print(" length of a side: ", poly1.getSide())
print(" Area: %.2f" %poly1.getArea())
print(" Perimeter: ", poly1.getPerimeter())
print("Polygon 2: ")
print(" # of sides: ", poly2.getN())
print(" length of a side: ", poly2.getSide())
print(" Area: %.2f" %poly2.getArea())
print(" Perimeter: ", poly2.getPerimeter())
| true |
84f6fd7694a4f63abc9c445f7a2d0a6c13ab57a8 | anila-a/CEN-206-Data-Structures | /hw01/hw1_2.py | 868 | 4.125 | 4 | '''
Program: hw1_2.py
Author: Anila Hoxha
Last date modified: 04/2/2020
Consider the Fibonacci function, F(n), which I defined such that
𝐹(1) = 1, 𝐹(2) = 2, 𝑎𝑛𝑑 𝐹(𝑛) = 𝐹(𝑛 − 2) + 𝐹(𝑛 − 1) 𝑓𝑜𝑟 𝑛 > 2.
Describe an efficient algorithm for determining first n Fibonacci numbers. What is the running time of
your algorithm, “Big-Oh”?
'''
def fibonacci(n):
a = 0 # O(1)
b = 1 # O(1)
if n == 1: # O(1)
print(a)
elif n == 2: # O(1)
print(a)
print(b)
else: # O(1)
print(a)
print(b)
for i in range(3, n+1): # O(n)
c = a + b # O(n)
print(c) # O(n)
# Exchange values for incrementation
a = b # O(n)
b = c # O(n)
n = int(input("Enter the value of n: ")) # O(1)
fibonacci(n) | true |
500e415d59727e99428a28bb85835e81a35eb836 | anila-a/CEN-206-Data-Structures | /midterm/Q1/main_Q1.py | 439 | 4.25 | 4 | '''
Program: main_Q1.py
Author: Anila Hoxha
Last date modified: 05/14/2020
Implement a program that can input an expression in postfix notation (see
Exercise C-6.22) and output its value.
'''
from postfix import *
''' Test the program with sample input: 52+83-*4/ '''
exp = str(input("Enter the expression: ")) # Read the user input
print("Postfix evaluation:", postfix(exp)) # Print the postfix evaluation of the expression
| true |
ac14eab101249ad1f9e19f01f9add32ad7e01e7a | anila-a/CEN-206-Data-Structures | /lab04/mainFlight.py | 1,761 | 4.5 | 4 | '''
Program: mainFlight.py
Author: Anila Hoxha
Last date modified: 03/21/2020
Design then implement a class to represent a Flight. A Flight has a flight
number, a source, a destination and a number of available seats. The class should have:
• A constructor to initialize the 4 instance variables. You must shorten the name of
the source and the destination by calling the method
shortAndCapital(name).
• Accessor/getters methods for each one of the 4 instance variables.
• Mutator/setters methods for each one of the 4 instance variables except the
flight number instance variable.
• A method reserve(numberOfSeats) to reserve seats on the flight.
(NOTE: You must check that there is enough number of seats to reserve)
• A function cancel(numberOfSeats) to cancel one or more reservations.
• A toString method to easily return the flight information as follows:
A method equal to compare 2 flights.
(NOTE: 2 Flights considered being equal if they have the same flight number,
flg1.equal(flg2))
• A method shortAndCapital(name) to shorten the name of the source and
destination to 3 characters only if it is longer than 3 characters.
'''
from flight import * # Import Flight class from flight.py file
# Create objects
flg1 = Flight(flightNr = 5432, source = "Tirana", destination = "Vienna", seatsNr = 100)
flg2 = Flight(flightNr = 2345, source = "Vienna", destination = "Munich", seatsNr = 100)
# Reserve
nrR = int(input("Enter the number of seats you want to reserve: "))
flg1.reverse(nrR)
# Cancel
nrC = int(input("Enter the number of seats you want to cancel: "))
flg1.cancel(nrC)
# Print flight information
print("Your flight information: ")
flg1.toString()
# Compare two flights
Flight.compare(flg1, flg2)
| true |
3d4cbfbfc5da19abbc3fd2b8c9e99d4192f48e4c | anila-a/CEN-206-Data-Structures | /midterm/Q2/B/singlyQueue.py | 2,276 | 4.1875 | 4 | '''
Program: singlyQueue.py
Author: Anila Hoxha
Last date modified: 05/16/2020
Write a singlyQueue class, using a singly linked list as storage. Test your class in testing.py
by adding, removing several elements. Submit, singlyQueue.py and testing.py.
'''
class SinglyQueue:
# FIFO queue implementation using a singly linked list for storage
class _Node:
__slots__ = '_element', '_next'
def __init__(self, element, next): # Constructor
self._element = element # Value of the node
self._next = next # Reference to the next node
def __init__(self): # Constructor
# Create an empty queue
self._head = None # No initial value
self._tail = None # No initial value
self._size = 0
def __len__(self): # Find the length of the queue
return self._size # Return the number of elements in the queue
def is_empty(self): # Check if the queue is empty or not
return self._size == 0 # Return True if the queue is empty
def first(self):
# Return (but do not remove) the element at the front of the queue
if self.is_empty(): # If the queue is empty
return ('Queue is empty') # If so, return this statement
return self._head._element # If not, return the first element in the queue
def dequeue(self):
# Remove and return the first element of the queue
if self.is_empty(): # If the queue is empty
return ('Queue is empty') # If so, return this statement
ans = self._head._element
self._head = self._head._next
self._size -= 1 # Decrement size by 1
if self.is_empty(): # Special case as queue is empty
self._tail = None # Removed head had been the tail
return ans
def enqueue(self, e):
# Add an element to the back of queue
newest = self._Node(e, None) # Node will be new tail node
if self.is_empty(): # If the queue is empty
self._head = newest # Special case: previously empty
else:
self._tail._next = newest # Tail node references to the newest node
self._tail = newest # Update reference to tail node
self._size += 1 # Increment size with one
| true |
fd59412ce8e23b59d93543166848d4c9ff9f25b6 | urmidedhia/Unicode | /Task1Bonus.py | 1,543 | 4.28125 | 4 | number = int(input("Enter number of words : "))
words = []
print("Enter the words : ")
for i in range(number): # Taking input in a list words
element = input()
words.append(element)
dist = []
for word in words: # Adding distinct words to a list dist
if word not in dist:
dist.append(word)
distinct = len(dist) # Number of distinct words is length of list dist
print("Number of distinct words is", distinct)
occur = []
for word in dist: # Adding number of occurrences of each distinct word in a list occur
count = 0
for item in words:
if word == item:
count += 1
occur.append(count)
print(count) # Printing number of occurrences of each distinct word
for j in range(distinct): # Arranging both the lists in descending order of occurrences
for i in range(j + 1, distinct): # Since length of dist is same as length of occur
if occur[j] < occur[i]:
temp = dist[j] # Swapping in dist list
dist[j] = dist[i]
dist[i] = temp
temp = occur[j] # Swapping in occur list
occur[j] = occur[i]
occur[i] = temp
print("The input in descending order of occurrences is : ", dist)
print("The most repeated word is : ", dist[0])
print("The least repeated word is : ", dist[-1])
| true |
d161e2a732a5c0c15610d8145b428419b87bcd9a | Yaasirmb/Alarm-Clock | /alarm.py | 602 | 4.125 | 4 | from datetime import datetime
import time
from playsound import playsound
#Program that will act as an alarm clock.
print("Please enter your time in the following format: '07:30:PM \n")
def alarm (user = input("When would you like your alarm to ring? ")):
when_to_ring = datetime.strptime(user, '%I:%M:%p').time()
while True:
time.sleep(2)
current_time = datetime.now().time().strftime("%I:%M:%p")
if when_to_ring.strftime("%I:%M:%p") == current_time:
playsound('wake_up.mp3')
print('Current time ' + current_time)
alarm() | true |
e0aa2e46821854211eac3041ec4fee381da8d516 | BeAgarwal/Palindrome | /Python/Different Types/palindrome_type1.py | 642 | 4.15625 | 4 | ''' Code by Shubham Agarwal
Link: https://github.com/BeAgarwal/Palindrome '''
'''Program to check the sum of a digit is a palindrome or not.'''
def check_palindrome(n):
r = 0
t = n
while n > 0:
rem = n % 10
r = (r * 10) + rem
n = n // 10
if r == t:
return True
else:
return False
def sumfunc(n):
s = 0
while n > 0:
rem = n % 10
s = s + rem
n //= 10
print("Sum of a digit is:", s)
return check_palindrome(s)
num = int(input("Enter the number: "))
ans = sumfunc(num)
if ans:
print("Palindrome.")
else:
print("Not a Palindrome.")
| false |
5c4d4fd464c0fa9bbb58f4f34125cff05b1a3d57 | PauloHARocha/accentureChallenge | /classification_naiveBayes.py | 2,036 | 4.125 | 4 | import pandas as pd
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split
from sklearn import metrics
# Naive Bayes
# The objective of this module is to classify the data from the pre-processed dataset,
# based on the alignment of each hero (good or bad), using the Naive Bayes algorithm.
# Question 3:
# 1- The Naive Bayes algorithm is a classifier based on the Bayes' theorem,
# which is based on conditional probability. It is a probabilistic algorithm that
# returns the probability of each entry belonging to a class. Two assumptions are
# made by this algorithm, the first is that the features are independent, and the second
# is that all features have an equal effect on the classification. Because of this assumptions
# the algorithm is called 'Naive'.
#
# 2- Due to the large number of categorical variables and most of them having several categories,
# it was decided to reduce the number of categories and to transform each category into a column
# representing whether or not the hero has such a characteristic. Due to the same characteristics
# of the data set it was chosen to use the Multinomial Naive Bayes algorithm, which has a better
# performance with this type of data.
#
# 3- Accuracy is being used as a metric to evaluate the model result,
# Read pre-processsed dataset
df = pd.read_csv('datasets/info_power_processed.csv')
X = df.drop(columns=['name', 'Alignment'])
# Classifying in good or bad
y = df['Alignment']
# Split dataset into training set and test set # 70% training and 30% test
X_train, X_test, y_train, y_test = train_test_split(X, y.values.ravel(),
test_size=0.3,random_state=109)
# Initialize algorithm
clf = MultinomialNB()
# Training model
clf.fit(X_train, y_train)
# Predicting test cases
y_pred = clf.predict(X_test)
# Model Accuracy
print("Accuracy:",metrics.accuracy_score(y_test, y_pred)) | true |
b8557d880d175569782682709d7055f2e219b994 | kabitakumari20/if_else_py | /calculator.py | 408 | 4.3125 | 4 | num=int(input("enter the num:-"))
num1=int(input("enter the num1:-"))
symbol=input("enter the symbol:-")
if symbol=="+":
print(num+num1)
elif symbol=="-":
print(num-num1)
elif symbol=="*":
print(num*num1)
elif symbol=="%":
print(num%num1)
elif symbol=="//":
print(num//num1)
elif symbol=="/":
print(num/num1)
elif symbol=="**":
print(num**num1)
else:
print("nothing is their") | false |
770dc7e863343aabae12f23a99b7da024c5827d1 | ZakOpry/digital-crafts | /week1/day3/introToPython4.py | 271 | 4.15625 | 4 | # Conditionals
print("Welcome to this program")
firstName = input("What is your first name?")
length_of_first_name = len(firstName)
print(firstName)
if length_of_first_name <= 0:
print("Please enter at least one character")
else:
print(f"Hello {firstName}")
| true |
07b213e5a72caa2ce55966adfcdeb5ddf8b05362 | HughesSvynnr/prg1_homework | /hw4.py | 1,891 | 4.125 | 4 | '''
problem 1
Ask a user for a number. Depending on the number, respond with how many factors exist within that number
for example:
Enter a number
>15
15 has 4 factors, which are 1 3 5 15
'''
'''
problem 2
Write a program that will ask a user for a word. For that word, replace each letter with
the appropriate letter of the phonetic alphabet.
For instance
Enter a word
>balloon
Bravo Alpha Lima Lima Oscar Oscar November
'''
#problem 1
print("give me a whole number")
number = input("> ")
factors = []
for x in range(1, int(number)+1):
if(int(number)%x==0):
factors.append(x)
print(number, " has ",len(factors)," factors. ",factors)
#problem 2
print("Type a word")
word = input("> ")
word_split = word.split(" ")
for x in word:
if(x=="a"):
print("Alpha")
elif(x=="b"):
print("Bravo")
elif(x=="c"):
print("Charlie")
elif(x=="d"):
print("Delta")
elif(x=="e"):
print("Echo")
elif(x=="f"):
print("Foxtrot")
elif(x=="g"):
print("Golf")
elif(x=="h"):
print("Hotel")
elif(x=="i"):
print("Indigo")
elif(x=="j"):
print("Juliet")
elif(x=="k"):
print("Kilo")
elif(x=="l"):
print("Lima")
elif(x=="m"):
print("Mike")
elif(x=="n"):
print("November")
elif(x=="o"):
print("Oscar")
elif(x=="p"):
print("Papa")
elif(x=="q"):
print("Quatar")
elif(x=="r"):
print("Romeo")
elif(x=="s"):
print("Siera")
elif(x=="t"):
print("Tango")
elif(x=="u"):
print("Uniform")
elif(x=="v"):
print("Victor")
elif(x=="w"):
print("Whiskey")
elif(x=="x"):
print("X-ray")
elif(x=="y"):
print("Yankee")
elif(x=="z"):
print("Zulu")
else:
print("Not word try english again")
| true |
7f3c7e24569cd0d3e070018bc26bf9946c83bf24 | Pragya1407/sdet | /python/Activity11.py | 327 | 4.1875 | 4 | dict_fruit = {
"apple" : 50,
"banana" : 10,
"watermelon" : 40,
"orange" : 25,
"kiwi" : 30
}
check_fruit = input("What fruit you want?? ").lower()
if (check_fruit in dict_fruit) :
print("yes.. " + check_fruit + " is available")
else :
print("no.. " + check_fruit + " is not available") | false |
71f42f050b38abbc8e9bb1824c52c5195a4783fa | ImBadnick/CryptographyAlgorithms | /Algorithms/SuccessiveQuadratures/sq.py | 1,437 | 4.125 | 4 | def printList(l,listname):
print(listname + " values:", end=' ')
for j in range(len(l)):
print(l[j], end=' ')
print("")
def decomposeZ(x):
powers = []
i = 1
while i <= x:
if i & x:
powers.append(i)
i <<= 1
return powers
def calculateY_2_J(y,max,S):
listY_2_J = []
i = 0
while 2**i <= max:
listY_2_J.append((y**(2**i)) % S)
i = i+1
return listY_2_J
def calculateX(powers,y, S):
list = []
x = 1
for value in powers:
x = (x * (y**int(value))) % s
return x%S
def repeatSigntoString(list,sign):
repeatString = str(list[0])
for i in range(len(list)-1):
repeatString = repeatString + " " + sign + " " + str(list[i+1])
return repeatString
if __name__ == '__main__':
print("The algorithm bases on calculate x = (y^z) mod s with SuccessiveQuadratures method")
try:
y = int(input("Insert y: "))
z = int(input("Insert z: "))
s = int(input("Insert s: "))
except ValueError:
print("Input is not an integer!")
exit(0)
powers = decomposeZ(z)
printList(powers,"DecomposeZ List")
y_2_j = calculateY_2_J(y,int(powers[-1]),s)
counter = 0;
for value in y_2_j:
print("{}^{} mod {} = {}".format(y,2**counter,s,value))
counter+=1
x = calculateX(powers,y, s)
print(("x value = {}^{} mod {} = " + str(x)).format(y,z,s)) | false |
d1d822f3c1b76c2c4953efa1b43f5fe7f8d8c0c1 | ImBadnick/CryptographyAlgorithms | /Algorithms/EllipticCurves/kobritz.py | 1,063 | 4.15625 | 4 | class point:
def __init__(self, x, y):
self.x = x
self.y = y
def quadraticResidues(module):
quadraticresidues = []
for i in range(module):
quadraticresidues.append(point(i,(i**2) % module))
return quadraticresidues
if __name__ == '__main__':
print("Transform m into a point of the elliptic curve E_p(a,b) - Kobritz algorithm")
m= int(input("Insert m: "))
h= int(input("Insert h: "))
a = int(input("Insert a: "))
b = int(input("Insert b: "))
module = int(input("Insert module: "))
if not ((m+1)*h < module):
print("False condition (m+1)*h < p ")
exit(0)
quadraticresidues = quadraticResidues(module)
pm = -1
for x in range(h):
_x_ = m*h + x
y_2 = ((_x_ ** 3) + a * _x_ + b) % module
print("i = {} -> x = {} , y^2 = {}".format(x,_x_,y_2))
for p in quadraticresidues:
if(y_2 == p.y):
pm = point(_x_,(y_2)**(1/2))
if(pm == -1):
print("m coding not found")
else: print("Pm = " + pm.__dict__) | false |
be0d9eb645a4aeadd0f5dc9e5c78336aba9d7527 | IvanKelber/plattsburgh-local-search | /Circles/circle.py | 2,119 | 4.15625 | 4 | # Created by Ivan Kelber, March 2017
import sys
import random
import math
def circles(points):
'''
- points is a list of n tuples (x,y) representing locations of n circles.
The point (x,y) at points[i] represents a circle whose center is at
(x,y) and whose radius is i.
This function returns the side of the smallest possible square that can
surround each of these circles such that no two circles are overlapping.
If two circles are found to be overlapping this function will return
sys.maxint.
'''
minX = sys.maxint
maxX = 0
minY = sys.maxint
maxY = 0
distance = [[1000 for i in range(len(points))] for j in range(len(points))]
for radius in range(len(points)):
point = points[radius]
#Update X
minX = min(minX,point[0]-radius)
maxX = max(maxX,point[0]+radius)
#Update Y
minY = min(minY,point[1]-radius)
maxY = max(maxY,point[1]+radius)
for radius2 in range(len(points)):
point2 = points[radius2]
if point is not point2:
distance[radius][radius2] = dist(point,point2,radius,radius2)
if(distance[radius][radius2] < 0):
# printDistance(distance)
return sys.maxint
# printDistance(distance)
return max(maxY-minY,maxX-minX)
def printDistance(distanceMatrix):
'''
Used to print out the distance matrix computed in the circles function;
primarily for debugging.
'''
for i in range(len(distanceMatrix)):
row = ""
for j in range(len(distanceMatrix)):
row += str(distanceMatrix[i][j]) + "\t"
print row
def dist(a,b,ra,rb):
'''
- a,b are centers of circles
- ra,rb are the respective radii of those two circles.
This function calculates the distance between the edges of two circles.
Note that this returns a negative value if two circles are overlapping.
'''
return math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2) - (ra + rb)
def main():
pass
if __name__ == '__main__':
main()
| true |
743606a3c25a96d1e7addb7ac6294bc04319f527 | NaughtyJim/learning-python | /2019-09-16/trees.py | 898 | 4.34375 | 4 | def main():
width = input('How wide should the tree be? ')
height = input('How tall should the tree be? ')
print("Here's your tree:")
print()
width = int(width)
height = int(height)
# this is the call if we omit the height
# print_tree(width, width // 2 + width % 2)
print_tree(width, height)
def print_tree(width, height):
# initialize i depending on whether the width is odd or even
i = 2 - width % 2
trunk_count = i
h = 0
# how often should we increment the number of leaves?
increment_step = int(2 * height / width)
while h < height:
print(' ' * ((width - i) // 2), '*' * i)
h += 1
if h % increment_step == 0 and i < width:
i += 2
print_trunk(width, trunk_count)
def print_trunk(width, count):
print(' ' * ((width - 1) // 2), '|' * count)
if __name__ == '__main__':
main()
| true |
a32ecf010adc0c1fde48a03a73def9282c101def | Pallavi2000/heraizen_internship | /internship/M_1/digit.py | 388 | 4.21875 | 4 | """program to accept a number from the user and determine the sum of digits of that number.
Repeat the operation until the sum gets to be a single digit number."""
n=int(input("Enter the value of n: "))
temp=n
digit=n
while digit>=10:
digit=0
while not n==0 :
r=n%10
digit+=r
n=n//10
n=digit
print(f"Given Number : {temp} Sum of Digits : {digit}")
| true |
82b7d80de1f353d744906bbe3203149cad2299e2 | Pallavi2000/heraizen_internship | /internship/armstrong.py | 291 | 4.375 | 4 | """Program to check whether a given number is armstrong number or not"""
n=int(input("Enter the value of n: "))
temp=n
sum=0
while not temp==0:
r=temp%10
sum+=r**3
temp=temp//10
if n==sum:
print(f"{n} is a armstrong number")
else:
print(f"{n} is not a armstrong number") | true |
40ac93b72c9244b3b4fe2dd07601dd2afd9a1324 | Pallavi2000/heraizen_internship | /internship/mod2/labqns/qns1.py | 313 | 4.1875 | 4 | """Program to calculate Simple interest"""
principle = float(input("Enter the principle value: "))
rate_of_interest = float(input("Enter the rate of interest: "))
time = float(input("Enter the time: "))
simple_interest = (principle * rate_of_interest * time) / 100
print(f"Simple interest = {simple_interest}")
| false |
d6d13883deaedf3f3db0d95dda7a77fda53d5712 | CRaNkXD/PyMoneyOrga | /PyMoneyOrga/PyMoneyOrga/domain/account.py | 2,184 | 4.3125 | 4 | from dataclasses import dataclass
import datetime
@dataclass
class Transaction(object):
"""
Data class for transactions made from and to an account. Used in Account class.
"""
amount: int
new_balance: int
description: str
time_stamp: datetime.datetime
account_id: int = None # foreign key to Account
class Account(object):
"""
Class for defining an account.
"""
def __init__(self, acc_name, balance, currency, transactions=None):
if transactions is None:
transactions = []
self._acc_name = acc_name
self._balance = balance
self._currency = currency
self._transactions = transactions # list of Transaction objects
def __str__(self):
return f"Account Name: {self._acc_name}; Money in Account: {self._balance}"
def __repr__(self):
return f"Account Name: {self._acc_name}; Money in Account: {self._balance}"
def add_income(self, amount, description):
"""
Adds an income to the account which is than saved in the transactions list.
"""
self._balance += amount
self.transactions.append(
Transaction(
amount=amount,
new_balance=self._balance,
description=description,
time_stamp=datetime.datetime.now(),
)
)
def add_expense(self, amount, description):
"""
Adds an expense to the account which is than saved in the transactions list.
"""
self._balance -= amount
self.transactions.append(
Transaction(
amount=-amount,
new_balance=self._balance,
description=description,
time_stamp=datetime.datetime.now(),
)
)
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, balance):
self._balance = balance
@property
def acc_name(self):
return self._acc_name
@property
def currency(self):
return self._currency
@property
def transactions(self):
return self._transactions
| true |
47c8166a0ae2e8c9ef5d2b38fefe83d2983e18d4 | as0113-dev/Python-Data-Structure | /mergeSort.py | 1,078 | 4.1875 | 4 | def mergeSort(array):
#base case
if len(array) <= 1:
return array
#midpoint of "array"
mid = len(array)//2
#split array in half
leftSplit = array[:mid]
rightSplit = array[mid:]
#recursively call the splitting of array
leftSplit = mergeSort(leftSplit)
rightSplit = mergeSort(rightSplit)
#final step call the merge "helper" function that builds the array and sort them
return merge(leftSplit, rightSplit)
def merge(leftArr, rightArr):
#the array that we return in the end after filling it up
result = []
l_Index, r_Index = 0, 0
while l_Index < len(leftArr) and r_Index < len(rightArr):
if leftArr[l_Index] < rightArr[r_Index]:
result.append(leftArr[l_Index])
l_Index += 1
else:
result.append(rightArr[r_Index])
r_Index += 1
if l_Index == len(leftArr):
result += rightArr[r_Index:]
else:
result += leftArr[l_Index:]
return result
list1 = [22,15,10,18,100]
fixed_list1 = mergeSort(list1)
print(fixed_list1) | true |
32e8cbc32de0f0520b196d38feb18cd4000cd71c | trafo41/Hackerrank-python-domain-solutions | /class1_.py | 1,508 | 4.3125 | 4 | """ class Student:
message = "hello there"
def __init__(self,n,a,m=0):
self.name = n
self.age = a
self.marks = m
def display(self):
print("-----------------------------")
print("Your name : ", self.name)
print("Your age : ", self.age)
print("Your marks : ", self.marks)
print("-----------------------------")
# print("Message : ", self.message)
s1 = Student("veer", 22)
s1.display() """
""" class Student:
message = "hello there"
def __init__(self,n,a,*m):
self.name = n
self.age = a
self.marks = m
def display(self):
print("-----------------------------")
print("Your name : ", self.name)
print("Your age : ", self.age)
print("Your marks : ", self.marks)
print("-----------------------------")
# print("Message : ", self.message)
s1 = Student("veer", 22, 95,56,98)
s1.display() """
class Student:
message = "hello there"
def __init__(self,n,a,**m):
self.name = n
self.age = a
self.marks = m
def display(self):
print("-----------------------------")
print("Your name : ", self.name)
print("Your age : ", self.age)
print("Your marks : ", self.marks)
print("-----------------------------")
# print("Message : ", self.message)
s1 = Student("veer", 22, science = 95, math = 56, phy = 98)
s1.display() | false |
2b93732d35dbee22032b49dc9968e6f07ad8ee89 | stavernatalia95/Lesson-5.2-Assignment | /Exercise #1.py | 781 | 4.34375 | 4 | # Assume you have the list xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
# Write a loop that prints each of the numbers on a new line
for i in xs:
print(i)
# Write a loop that prints each number and its square on a new line.
for i in xs:
print(i,i**2)
# Write a loop that adds all the numbers from the list into a variable called total.
# You should set the total variable to have the value 0 before you start adding them up,
# and print the value in total after the loop has completed.
total=0
for i in xs:
total+=i
print("Total:", total)
# Print the product of all the numbers in the list. (product means all multiplied together)
product=1
for i in xs:
product*=i
print("Product:", product) | true |
c2beb9e3beeb12a3e91f5189ea70fde4e4a07c87 | SHETU-GUHA/1st | /1st chapter.py | 1,128 | 4.375 | 4 | print('Hellow World!')
print ('What is your name?')
myName = input()
print ('it is good to meet you ' + myName)
print('The length of our name is :')
print (len(myName))
print ('what is your age?')
myAge = input ()
print ('You will be ' + str (int(myAge)+1) + 'in a year.')
#1. operator (*, -, / , +) values ('hello', -88.8, 5)
# variable (spam), string ('spam')
# int,floating point ,string
# after running the code bacon value is 21
# 'spam' + 'spamspam' = spamspamspam
'spam' * 3 =
spam
spam
spam
#Why is eggs a valid variable name while 100 is invalid?
Because variable names cannot begin with a number.
# What three functions can be used to get the integer, floating-point number, or string version of a value?
str()
int()
float()
#Why does this expression cause an error? How can you fix it?
'I have eaten ' + 99 + ' burritos.'
This expression causes an error because here'I have eaten' and 'burritos' are strings, while 99 is treated as integer. In order to fix the error and print 'I have eaten 99 burritos.', 99 needs '' around it to treat it as a string.
| true |
6c24097e7f79f64552a51b7ee99e712f6f94e438 | HristoMohamed/PythonStuff | /python-retrospective-hw/task1/solution.py | 1,535 | 4.28125 | 4 | #!/usr/bin/env python
def what_is_my_sign(day, month):
if (month == 3 and day >= 21) or (month == 4 and day <= 20):
print('Овен')
return 'Овен'
if (month == 4 and day >= 21) or (month == 5 and day <= 20):
print('Телец')
return 'Телец'
if (month == 5 and day >= 21) or (month == 6 and day <= 20):
print('Близнаци')
return 'Близнаци'
if (month == 6 and day >= 21) or (month == 7 and day <= 21):
print('Рак')
return 'Рак'
if (month == 7 and day >= 22) or (month == 8 and day <= 22):
print('Лъв')
return 'Лъв'
if (month == 8 and day >= 23) or (month == 9 and day <= 22):
print('Дева')
return 'Дева'
if (month == 9 and day >= 23) or (month == 10 and day <= 22):
print('Везни')
return 'Везни'
if (month == 10 and day >= 23) or (month == 11 and day <= 21):
print('Скорпион')
return 'Скорпион'
if (month == 11 and day >= 22) or (month == 12 and day <= 21):
print('Стрелец')
return 'Стрелец'
if (month == 12 and day >= 22) or (month == 1 and day <= 19):
print('Козирог')
return 'Козирог'
if (month == 1 and day >= 20) or (month == 2 and day <= 18):
print('Водолей')
return 'Водолей'
if (month == 2 and day >= 19) or (month == 3 and day <= 20):
print('Риби')
return 'Риби'
| false |
99765350a6e38f6d6d9b46b2fdf0ae956f4d204f | Anna-Dvoskina/basic_exercises | /string_challenges.py | 1,199 | 4.15625 | 4 |
# Вывести последнюю букву в слове
from typing import Counter
word = 'Архангельск'
# ???
print(word[-1])
# Вывести количество букв "а" в слове
word = 'Архангельск'
# ???
print(f'{Counter(word.lower())}')
# Вывести количество гласных букв в слове
word = 'Arkhangelsk'
count = 0
for letter in word:
if letter.lower() in 'aeiou':
count += 1
print(f'кол-во букв в слове {word}: {count}')
# ???
# Вывести количество слов в предложении
sentence = 'Мы приехали в гости'
# ???
print(len(sentence.split()))
# Вывести первую букву каждого слова на отдельной строке
sentence = 'Мы приехали в гости'
# ???
for word in sentence.split():
print(f'{word[0].lower()}')
print('______')
# Вывести усреднённую длину слова в предложении
sentence = 'Мы приехали в гости'
# ???
words = sentence.split()
print(word)
average = sum(len(word) for word in words) / len(sentence.split())
print(average)
| false |
f204312c8a2bd68d75b89db21b8334c3d7d9191d | Anurag-12/learning-python | /Coroutines_Example/main.py | 2,464 | 4.3125 | 4 | '''
Both generator and coroutine operate over the data; the main differences are:
Generators produce data
Coroutines consume data
Coroutines are mostly used in cases of time-consuming programs, such as tasks related to machine learning or deep learning algorithms or in cases
where the program has to read a file containing a large number of data. In such situations, we do not want the program to read the file or data,
again and again, so we use coroutines to make the program more efficient and faster. Coroutines run endlessly in a program because they use a while
loop with a true or 1 condition so it may run until infinite time. Even after yielding the value to the caller, it still awaits further instruction
or calls. We have to stop the execution of coroutine by calling coroutine.close() function.
Syntax:
def myfunc():
while True:
value = (yield)
Execution is the same as of a generator. When you call a coroutine, nothing happens. They only run in response to the next() and send() methods.
Coroutine requires the use of the next statement first so it may start its execution. Without a next() it will not start executing. We can search
a coroutine by sending it the keywords as input using object name along with send(). The keywords to be searched are send inside the parenthesis.
send() — used to send data to coroutine
close() — to close the coroutine
'''
def searcher():
import time
# Some 4 seconds time consuming task
book = "This is a book on anurag and code with anurag and good"
time.sleep(4)
while True:
text = (yield) # whatever name is being passed to search
if text in book:
print("Your text is in the book")
else:
print("Text is not in the book")
search = searcher()
print("search started")
next(search)
print("Next method run")
search.send("anurag")
search.close()
#search.send("anurag") # this will throw error since the coroutine is closed
###############################################################
def names():
import time
names = "anurag harry haris carry amit ajey bhuvan shubham rahul aftab hrithik vivek ujjawal mohit rohit"
time.sleep(2)
while True:
text = (yield)
if text in names:
print("Your name is in the list.")
else:
print("Your name is not in the list.")
name = names()
next(name)
name.send(input("Type your Name: "))
| true |
d181bf517a3d745068e1e2de3af4d91abaf18b6b | Anurag-12/learning-python | /seek-tell-file/main.py | 861 | 4.4375 | 4 | #This code will change the current file position to 5, and print the rest of the line.
# Note: not all file objects are seekable.
f = open("myfile.txt", "r")
f.seek(5)
print( f.readline() )
f.close()
f = open("myfile.txt")
f.seek(11)
print(f.tell())
print(f.readline())
# print(f.tell())
print(f.readline())
# print(f.tell())
f.close()
###################################################
# With open(“file1txt”) as f, open(“file2.txt”) as g
'''advantages of With block:
Multiple files can be opened.
The files that are opened together can have different modes
Automatically closes file
Saves processing power by opening and closing file only when running code inside the block
'''
with open("harry.txt") as f:
a = f.readlines()
print(a)
# f = open("harry.txt", "rt")
# f.close()
| true |
5111dee03f6cdcc8dc76ffe3409b809fefaf4ffd | vijaypalmanit/daily_coding_problem | /daily_coding_problem_2.py | 649 | 4.125 | 4 | # This problem was asked by Uber.
# 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].
# Follow-up: what if you can't use division?
def product(n):
arr=[]
for i in range(len(n)):
product=1
for j in range(len(n)):
if i != j:
product=product*n[j]
arr.append(product)
return arr
n=[6, 15, 10, 7]
print(product(n))
| true |
36829d8f6439f71ab6bca0fcf2b99617a611101a | Smile-Bonchichi/Library_Lab_PIPITEH | /4 семестр/Питон/Задание практика 5.py | 1,238 | 4.1875 | 4 | ===1===
class Mercedes(object):
def __init__(self, colors, type, model):
self.colors = colors
self.type = type
self.mode = model
def drive(self):
"""
Drive
"""
return "Я за рулем машины"
def brake(self):
"""
Brake
"""
return "Я пропустил пешеходов"
if __name__ == "__main__":
car = Mercedes("black","sedan","s-class")
print(car.colors)
print(car.type)
print(car.mode)
pick = Mercedes("grey","pickup","x-class")
print(pick.colors)
===2===
class Cars():
def __init__(self,brand,type,country):
self.brand=brand
self.type=type
self.country=country
if __name__=="__main__":
car = Cars("Lexus", "jeep", "japan")
print("У меня машина марки",car.brand)
class Student():
def __init__(self,group,cours,nat):
self.group=group
self.cours=cours
self.nat=nat
if __name__=="__main__":
person=Student("Пи-5-19","2ой курс","Кыргыз")
print("Привет меня зовут Назар я",person.cours,"и я из группы",person.group) | false |
54ad1438359c861d10e728bea6baadc29fb4f997 | RafaelLua13/URI | /1002.py | 435 | 4.1875 | 4 |
## Código ##
r = float(input())
a = (r * r) * 3.14159
print("A=%0.4f" %a)
## Código comentado ##
# r = float(input()) # Definição da variável 'r' como um valor float (Não necessáriamente inteiro).
# a = (r * r) * 3.14159 # Cálculo da área do circulo multiplicando r^2 (r**2) pelo valor de Pi (3.14159).
# print("A=%0.4f" %a) # Mostrando a variavel 'a' com apenas 4 casas decimais (%0.4f).
| false |
1f848e8400a6ecfc1342116e24906206c8745fd2 | GDMane/Santubhau | /collectionsArrays/listOperations.py | 921 | 4.15625 | 4 |
print("Shree Swami Samarth")
print("Collections (array)")
gmList = ['ganesh', 'ganesh', 'gmList']#duplicate allowed
print(gmList[0])#single object print using index
print("--------------")
'''
gmList.reverse()
print(gmList)#reverce elements in original refrance
print("--------------")
'''
gmList[0]="myChange"
print(gmList)#update on any particular index
print("--------------")
gmList.append("myAppend")
print(gmList)#Append object at the end /Last index
print("--------------")
gmList.pop(1)
print(gmList)#delete any perticular index object
print("--------------")
gmList.insert(1,"myInsertTest")
print(gmList)
print("--------------")
gmList.remove("gmList")
print(gmList)#remove perticular object
print("--------------")
gmList1 = ["copyTest"]
print(gmList1)
gmList1 = gmList.copy()
print(gmList1)
print(gmList)#copy list to another list
print("--------------")
gmList.extend("1")
print(gmList)
print("--------------")
| false |
c4051d5b29c21c23b545cee418d14da0e11b29a0 | shaunakchitare/PythonLearnings | /function_programs.py | 2,152 | 4.40625 | 4 | #-------------------------------------------------------------------------------
#Exercise 1 - Creat a function that accepts 3 ardument and return their sum
print('\nExercise 1')
def add_numbers(x,y,z):
total = x + y + z
return total
total = add_numbers(5,1,9)
print(total)
#-------------------------------------------------------------------------------
#Exercise 2 - Create a
print('\nExercise 2')
def add_numbers_2(list_nums):
total = 0
for num in list_nums:
total = total + num
return total
total = add_numbers_2([4,3,7,5,8])
print(total)
#-------------------------------------------------------------------------------
print('\nExercise 3')
def add_numbers_3(list_nums_1,list_nums_2):
list_nums = list_nums_1 + list_nums_2
return add_numbers_2(list_nums)
total = add_numbers_3([4,3,7,5,8],[5,7,6,1,4])
print(total)
#-------------------------------------------------------------------------------
print('\nExercise 4')
def add_numbers_4(list_nums_1,list_nums_2,list_nums_3):
list_nums = list_nums_1 + list_nums_2 + list_nums_3
return add_numbers_2(list_nums)
total = add_numbers_4([4,3,7,5,8],[5,7,6,1,4],[9,5,7,0,2])
print(total)
#-------------------------------------------------------------------------------
print('\nExercise 5')
def add_numbers_5(my_dict):
v1 = my_dict['a']
v2 = my_dict['b']
v3 = my_dict['c']
L1 = [v1,v2,v3]
r = sum(L1)
return r
total = add_numbers_5({'a':1,'b':2,'c':3})
print(total)
#-------------------------------------------------------------------------------
print('\nExercise 6')
def add_numbers_6(my_dict):
values = my_dict.values()
r = sum(values)
return r
total = add_numbers_6({'a':1,'b':2,'c':3, 'd':4})
print(total)
#-------------------------------------------------------------------------------
print('\nExercise 7')
def add_numbers_7(kanha):
shaunak = kanha['s']
jas = kanha['j']
kedar = kanha['k']
shrijit = kanha['sh']
anvi = kanha['a']
Sjksha = [shaunak,jas,kedar,shrijit,anvi]
v = sum(Sjksha)
return v
total = add_numbers_7({'s':9,'j':10,'k':8,'sh':7,'a':6})
print(total)
| true |
1cd0a2fc2283355d1398aafb3fea2e57a50b5312 | kovokilla/python | /namedTuple.py | 684 | 4.375 | 4 | # Import the 'namedtuple' function from the 'collections' module
from collections import namedtuple
# Set the tuple
#tuple je v podstate object
individual = namedtuple("Nazov_identifikacia", "name age height")
user = individual(name="Homer", age=37, height=178)
user2 = individual(name="Peter", age=33, height=175)
# Print the tuple
print(user)
print(user2)
people = (user, user2)
# Print each item in the tuple
#looping through tuple of tuples
#v pythone loopujes inak, ked das for item in (collection of items), tak “item” bude uz ten tuple,
# takze ak chces jeho .name tak das item.name a nie collection[item].
for i in people:
print(i.name)
print(i.age)
print(i.height) | true |
75f90baadc03152562d4ef37d19a8b050130664c | carlan/dailyprogrammer | /easy/2/python/app.py | 1,003 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""app.py: challenge #2"""
__author__ = "Carlan Calazans"
__copyright__ = "Copyright 2016, Carlan Calazans"
__credits__ = ["Carlan Calazans"]
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "Carlan Calazans"
__email__ = "carlancalazans at gmail dot com"
__status__ = "Development"
class Calculator(object):
def addition(self, n1, n2):
print("Addition n1={} and n2={}".format(n1,n2))
print("result={}".format(eval("n1+n2")))
return n1+n2
def subtraction(self, n1, n2):
print("Subtraction n1={} and n2={}".format(n1,n2))
print("result={}".format(eval("n1-n2")))
return n1-n2
def multiplication(self, n1, n2):
print("Multiplication n1={} and n2={}".format(n1,n2))
print("result={}".format(eval("n1*n2")))
return n1*n2
def division(self, n1, n2):
print("Division n1={} and n2={}".format(n1,n2))
print("result={}".format(eval("n1/n2")))
return n1/n2
calc = Calculator()
calc.addition(2,2)
calc.subtraction(10,5)
calc.multiplication(3,3)
calc.division(9,3)
| false |
8433b4e7cd6dd75a94344d8a5eb9d75f37a41ca3 | udoy382/PyCode15h | /chapter_005.py | 1,657 | 4.25 | 4 | # Chapter -5 Dictionary & Sets
# mydict = {
# "Fast": "In a quick manner",
# "Udoy": "Coder",
# "Marks":[1,2,3,4],
# "anatherdict": {'Udoy':'Player'}
# }
# print(mydict['Fast'])
# print(mydict['Udoy'])
# mydict['Marks'] = [22, 99, 436]
# print(mydict['Marks'])
# print(mydict['anatherdict']['Udoy'])
# -----------------------------------
# Dictionary methods
# -----------------------------------
mydict = {
"fast": "In a quick manner",
"udoy": "Coder",
"marks":[1,2,3,4],
"anatherdict": {'Udoy':'Player'}
}
# print(mydict.keys())
# print(list(mydict.keys()))
# print(mydict.values())
# print(type(mydict.items()))
# updatedict = {
# "udoy": "Rice",
# "Harry": "Banana",
# "Maryam": "Apple"
# }
# print(mydict)
# mydict.update(updatedict) # Update the dictionary by adding key-value pairs from updatedict
# print(mydict)
# print(mydict.get('udoy2')) # returns none as udoy2 is not peresent in the dictionary
# print(mydict['udoy2']) # throws an error as udoy2 is not present in the dictionary
# ---------------------------
# sets in python
# ---------------------------
a = {1, 2, 3, 5, 1}
# print(a)
# print(type(a))
# print(a)
# this syntax will creat an empty dictionary and not an empty set
x = {}
# print(type(x))
# an empty set can be creating using the below syntax
y = set()
# print(type(y))
# adding values to an empty set
y.add(4)
y.add(5)
y.add(7)
y.add(4)
# y.add({4:5}) # cannot add list or dict to sets
# print(y)
# set method
# print(len(y))
# y.remove(4)
# print(y)
# print(y.pop())
# y.clear()
# print(y)
# print(y.union())
# print(y.intersection()) | false |
0161d8a35ce81625815121d56e93b56162a62b95 | sabirul-islam/Python-Practice | /ANISUL ISLAM/list.py | 1,125 | 4.34375 | 4 | subjects = ['javascript', 'python', 'php', 'java', 'flutter', 'kotlin']
print(subjects)
print(subjects[1])
print(subjects[2:]) # print from 2 number index
print(subjects[-1])
print('python' in subjects) # check is this subject in here?(case sensitive)
print('golang' not in subjects) # it returns true
print(subjects + ['xamarin', 45]) # add new list
print(subjects * 3) # showing this list 3 times
print(len(subjects)) # showing length and count from 1
subjects.append('c++') # insrt a item
print(subjects)
subjects.insert(2, 'c') # insert a new item in a specific location
print(subjects)
subjects.remove('kotlin') # remove a item
print(subjects)
subjects.sort() # sort the list alphabeticaly
print(subjects)
subjects.reverse()
print(subjects)
subjects.pop() # remove the last item
print(subjects)
subjects.clear() # clear all the item
print(subjects)
subjectsCopy = subjects.copy() # copy old list in a new list
print(subjectsCopy)
subjectsIndex = subjects.index('java') # showing index of an item
print(subjectsIndex)
subjectsCount = subjects.count('kotlin') # an item how many times have in the list
print(subjectsCount) | true |
a2ebbe7a95c56145f67b5e46208e3bbced0c44d2 | Bokomoko/classes-and-operations-in-data-model-python | /main.py | 744 | 4.375 | 4 | class Polynomial:
# method to initialize the object with some values
def __init__(self, *coefs):
self.coefs = coefs
# function to represent the object (print)
# similar to __str__ but for debuging purposes
# it will be used if no __str__ method
def __repr__(self):
return 'Polynomial(*{!r})'.format(self.coefs)
# method to add two objects of this class
def __add__(self,other):
return Polynomial(*(x+y for x,y in zip(self.coefs,other.coefs)))
# method to evaluate the Polynomial
# can be used to implement a funcion based on the class
def __call__(self, number):
v = 0
for expo in self.coefs:
v+= number**expo
return v
p1 = Polynomial( 1, 2, 3)
p2 = Polynomial(3, 4, 3)
print(p1+p2) | true |
3ca81cce7fcf16010bd88b5fc94d932dd5834db0 | rodrigodata/learning | /pyhton/arithmetic_operations/arithmetic_operations.py | 434 | 4.1875 | 4 | # add
print(10 + 3) # 13
# subtract
print(10 - 4) # 6
#float
print(2.22 * 3) # 6.66
# multiplication
print(2 * 8) # 16
# division
print(10 / 3) # 3.3333333333333335
print(10 // 3) # 3 => Returns an integer from division
# modules
print(10 % 3) # 1 Returns the remaining
# exponation
print(10 ** 3) # 1000
####
#increment
### bad
x = 10
x = x + 3
print(x) # 13
### good
y = 10
y += 3
print(y) # 13
z = 20
z -= 10
print(z) # 10 | true |
f69b922883c61272175ca5b0a538106b2941a81a | esencgr/Programming_Contest_Solutions | /HackerRank/PYTHON/swap_case.py | 342 | 4.15625 | 4 | def swap_case(s):
temp = list()
st = ""
for i in s:
if i.islower():
temp.append(i.upper())
elif i.isupper():
temp.append(i.lower())
else:
temp.append(i)
return st.join(temp)
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result) | false |
23af8376aab114dd358d6d40903882886c800d88 | ryankchang/DataClass | /Python Codes/Week3-1/Exercise 5.py | 1,093 | 4.1875 | 4 | import random
possible = ['rock','paper','scissors']
continue_code = 'y'
while continue_code == 'y':
user = input('Pick one - [rock | paper | scissors]: ')
computer = random.choice(possible)
if user not in possible:
print('Please select a valid choice. {user} is not valid.')
print(f'You picked {user}. Computer picked {computer}.')
if user == 'rock':
if computer == 'paper':
print('Computer wins :(')
elif computer == 'rock':
print("Try again")
elif computer == 'scissors':
print("You win!")
elif user == 'scissors':
if computer == 'paper':
print('You win!')
elif computer == 'rock':
print("Computer wins :(")
elif computer == 'scissors':
print("You win!")
elif user == 'paper':
if computer == 'paper':
print('Try again')
elif computer == 'rock':
print("You win!")
elif computer == 'scissors':
print("Computer wins :(")
continue_code = input("Continue? [y/n]: ")
| false |
3c9c29480c72a6e8082cd18297d94773ab531e4f | gedo147/Python | /ConvertClassToDictionary/BinaryTree.py | 719 | 4.1875 | 4 |
class BinaryTree:
def __init__(self,value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
tree = BinaryTree(10,left=BinaryTree(7,left=3, right=8), right=BinaryTree(15,left=11,right=17))
print(tree.__dict__)
print("So as we can see only the outer binaryTree class got converted into dictionary, it doesn't go into heirarchy")
print("So can we do something here")
res = tree.__dict__
for key, value in res.items():
if hasattr(value, '__dict__'): # This basically checks if object is something on which __dict__ can be called, for ex for value = 10, __dict__ can't be called.
res[key] = value.__dict__
print(res)
| true |
05efea7cc368a98561a771dbc17927731fcf81f9 | gedo147/Python | /Comprehension/dict_comprehensions.py | 1,078 | 4.4375 | 4 | d = { 'hello': 1, 'hi': 2, 'namaste': 3}
print("Current Dictionary")
print(d)
print("when we iterate over a dictionary, every item becomes a tuple")
for item in d.items():
print(item)
a,b,c = ("abc", 12, 14) # and this is how a tuple can be extracted
print(a)
print(b)
print(c)
#so
for a, b in d.items():
print("a = " + a)
print("b = " + str(b))
print("So a becomes key and b becomes value")
print("So for a , b in items we want b : a in dictionary")
print(" d_inverse = { b: a for a, b in d.items()}")
# as you can see a automatically becomes key and b automatically becomes value
# I want that In one line value become key and key becomes value in another dictionary
d_inverse = {b:a for a, b in d.items()}
print(d_inverse)
#Similary if we want to find length of all values
k = [ len(a) for a,b in d.items()] # it will be of same order as items are in dictionary
print(k)
# we can store above in dictionary as well
k = { len(a) for a,b in d.items()} # here no matter what it will always be sorted
print(k) | false |
70ded69c41a75a06894364a029d28f77f54cad9c | ariannasg/python3-training | /standard_library/json_ops.py | 1,356 | 4.1875 | 4 | #!usr/bin/env python3
# working with JSON data
import json
import urllib.request
# use urllib to retrieve some sample JSON data
req = urllib.request.urlopen("http://httpbin.org/json")
data = req.read().decode('utf-8')
print(data)
# use the JSON module to parse the returned data
obj = json.loads(data)
# when the data is parsed, we can access it like any other object
print(obj["slideshow"]["author"])
for slide in obj["slideshow"]["slides"]:
print(slide["title"])
# python objects can also be written out as JSON
objdata = {
"name": "Joe Marini",
"author": True,
"titles": [
"Learning Python", "Advanced Python",
"Python Standard Library Essential Training"
]
}
# writing the above object as json to a file
with open("jsonoutput.json", "w") as fp:
json.dump(objdata, fp, indent=4)
# CONSOLE OUTPUT:
# {
# "slideshow": {
# "author": "Yours Truly",
# "date": "date of publication",
# "slides": [
# {
# "title": "Wake up to WonderWidgets!",
# "type": "all"
# },
# {
# "items": [
# "Why <em>WonderWidgets</em> are great",
# "Who <em>buys</em> WonderWidgets"
# ],
# "title": "Overview",
# "type": "all"
# }
# ],
# "title": "Sample Slide Show"
# }
# }
#
# Yours Truly
# Wake up to WonderWidgets!
# Overview
| true |
9835578b347135a0a3be9da82c7f1538b64843d1 | ariannasg/python3-training | /advanced/lambdas.py | 1,336 | 4.8125 | 5 | #!usr/bin/env python3
# lambdas are simple and small anonymous functions that are used in situations
# where defining a whole separate function would unnecessarily increase the
# complexity of the code and reduce readability.
# Lambdas can be used as in-place functions when using built-ins conversion
# functions like filter, map, etc
def celsius_to_fahrenheit(temp):
return (temp * 9 / 5) + 32
def fahrenheit_to_celsius(temp):
return (temp - 32) * 5 / 9
def main():
celsius_temps = (0, 12, 34, 100)
fahrenheit_temps = (32, 65, 100, 212)
# Use regular functions to convert temps
print(list(map(fahrenheit_to_celsius, fahrenheit_temps)))
print(list(map(celsius_to_fahrenheit, celsius_temps)))
# Use lambdas to accomplish the same thing
# reducing the complexity of the code
print(list(map(lambda temp: (temp - 32) * 5 / 9, fahrenheit_temps)))
print(list(map(lambda temp: (temp * 9 / 5) + 32, celsius_temps)))
# using lambda as the filter function
odd_f_temps = list(filter(lambda temp: (temp % 2) != 0, fahrenheit_temps))
print(odd_f_temps)
if __name__ == "__main__":
main()
# CONSOLE OUTPUT:
# [0.0, 18.333333333333332, 37.77777777777778, 100.0]
# [32.0, 53.6, 93.2, 212.0]
# [0.0, 18.333333333333332, 37.77777777777778, 100.0]
# [32.0, 53.6, 93.2, 212.0]
# [65]
| true |
45287696df3e49cbf7899d074edcdc0ae31e35a4 | ariannasg/python3-training | /standard_library/random_sequence.py | 1,788 | 4.8125 | 5 | #!usr/bin/env python3
import random
import string
# A common use case for random number generation is to use the generated
# random number along with a sequence of other values.
# So for example, you might want to select a random element from a list or
# a set of other elements.
# Use the choice function to randomly select from a sequence
moves = ["rock", "paper", "scissors"]
print(random.choice(moves))
# Use the choices function (introduced in python 3.6) to create a list of
# random elements
roulette_wheel = ["black", "red", "green"]
weights = [18, 18, 2]
# we define we want a list of 10 elements, otherwise is 1 by default
# there are only 2 green spaces on a roulette wheel, the green color shouldn't
# have the same chance to appear as black and red. we use weights for this.
# the weights arg tells the function how to distribute the results.
print(random.choices(roulette_wheel, weights, k=10))
# The sample function randomly selects elements from a population
# without replacement (the chosen items are not replaced)
# and without duplicates.
# here we print 6 random uppercase letters without duplicates
chosen = random.sample(string.ascii_uppercase, 6)
print(chosen)
# The shuffle function shuffles a sequence in place
players = ["Bill", "Jane", "Joe", "Sally", "Mike", "Lindsay"]
random.shuffle(players)
print(players)
# to shuffle an immutable sequence/collection, use the sample function first
result = random.sample(string.ascii_uppercase, k=len(string.ascii_uppercase))
random.shuffle(result)
print(''.join(result))
# CONSOLE OUTPUT (it will vary!):
# paper
# ['black', 'red', 'black', 'black', 'black', 'black', 'red', 'black', 'red', 'red']
# ['P', 'D', 'W', 'K', 'U', 'V']
# ['Lindsay', 'Mike', 'Bill', 'Sally', 'Joe', 'Jane']
# IRKXAVZNPHUCBLSEOJGQYWTFDM
| true |
4e1dec27165ae11de26af08675f180aaaba8f2d9 | ariannasg/python3-training | /standard_library/urls_parsing.py | 1,349 | 4.15625 | 4 | #!usr/bin/env python3
# Using the URL parsing functions to deconstruct and parse URLs
import urllib.parse
sample_url = "https://example.com:8080/test.html?val1=1&val2=Hello+World"
# parse a URL with urlparse()
result = urllib.parse.urlparse(sample_url)
print(result)
print('scheme:', result.scheme)
print('hostname:', result.hostname)
print('path:', result.path)
print('port:', result.port)
print('url:', result.geturl())
# in order to use special chars (space,ñ) un a url we need to convert them
# quote() replaces special characters for use in URLs
sample_string = "Hello El Niño"
print(urllib.parse.quote(sample_string))
print(urllib.parse.quote_plus(sample_string))
# how to convert dict of values into parameter strings for using in a URL as
# part of the query string
# Use urlencode() to convert maps to parameter strings
query_data = {
'Name': "John Doe",
"City": "Anytown USA",
"Age": 37
}
result = urllib.parse.urlencode(query_data)
print(result)
# CONSOLE OUTPUT:
# ParseResult(scheme='https', netloc='example.com:8080', path='/test.html', params='', query='val1=1&val2=Hello+World', fragment='')
# scheme: https
# hostname: example.com
# path: /test.html
# port: 8080
# url: https://example.com:8080/test.html?val1=1&val2=Hello+World
# Hello%20El%20Ni%C3%B1o
# Hello+El+Ni%C3%B1o
# Name=John+Doe&City=Anytown+USA&Age=37
| true |
bec0dc0a1418dc6eaddb447325395115ed8dddb4 | ariannasg/python3-training | /standard_library/string_search.py | 897 | 4.46875 | 4 | #!usr/bin/env python3
# Use standard library functions to search strings for content
sample_str = "The quick brown fox jumps over the lazy dog"
# startsWith and endsWith functions
print(sample_str.startswith("The"))
print(sample_str.startswith("the"))
print(sample_str.endswith("dog"))
# the find function starts searching from the left/start side of the str)
# and rfind function starts searching from the right hand-side of the str
# they both return the index at which the substring was found
print(sample_str.find("the"))
print(sample_str.rfind("the"))
# for knowing if a substr is contained in the str
print("the" in sample_str)
# using replace
new_str = sample_str.replace("lazy", "tired")
print(new_str)
# counting instances of substrings
print(sample_str.count("over"))
# CONSOLE OUTPUT:
# True
# False
# True
# 31
# 31
# True
# The quick brown fox jumps over the tired dog
# 1
| true |
e5acc44ad8a023261a1818cce025e33ea782e299 | vijonly/100_Days_of_Code | /Day2/tip_calculator.py | 357 | 4.1875 | 4 | # Tip Calculator project
print("Welcome to the tip calculator.")
bill = float(input("What was the total bill? $"))
partition = int(input("How many people to split the bill? "))
tip_percentage = int(input("What percentage tip would you like to give? 10, 12, or 15? "))
print(f"Each person should pay: ${(bill / partition) * (tip_percentage + 100) / 100}")
| true |
b3c75e95a54ef8a1ddaf19b83b4595a94df35cd7 | vijonly/100_Days_of_Code | /Day15/coffee_machine.py | 2,702 | 4.25 | 4 | # Coffee Machine Program
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100
}
profit = 0
def generate_report():
'''Prints the report showing current resource values'''
for resource, value in resources.items():
print(f"{resource}: {value}")
print(f"Money: {profit}")
def check_resource(coffee):
'''
Check if there are enough resources to make user's desired coffee.
'''
for ingredient, quantity in MENU[coffee]['ingredients'].items():
if resources[ingredient] < quantity:
print(f"Sorry there is not enough {ingredient}")
return False
return True
def process_coin():
print("Please insert coins.")
quarters = int(input("How many quarters?: "))
dimes = int(input("How many dimes?: "))
nickles = int(input("How many nickles?: "))
pennies = int(input("How many pennies?: "))
money = round((quarters * 0.25) + (dimes * 0.10) + (dimes * 0.05) + (pennies * 0.01), 2)
return money
def complete_transaction(money, coffee_cost):
'''Return Boolean value by validating the payment'''
if money >= coffee_cost:
change = round(money - coffee_cost, 2)
print(f"Here is ${change} in change.")
global profit
profit += coffee_cost
return True
else:
print("Sorry that's not enough money. Money refunded!")
return False
def make_coffee(coffee_name, ingredients):
'''Deduct the required ingredients from the resources.'''
for ingredient in ingredients:
resources[ingredient] -= ingredients[ingredient]
print(f"Here is your {coffee_name} ☕. Enjoy!")
def start():
serving = True
while serving:
choice = input("\nWhat would you like? (espresso/latte/cappuccino): ").lower()
if choice == 'off':
print("Maintainence Mode!")
serving = False
elif choice == 'report':
generate_report()
elif choice in MENU.keys():
coffee = MENU[choice]
if check_resource(choice):
money = process_coin()
if complete_transaction(money, coffee['cost']):
make_coffee(choice, coffee['ingredients'])
start() | true |
5db1788519d32d194b83d998344193c9cc8044d9 | vijonly/100_Days_of_Code | /Day8/area_calc.py | 654 | 4.3125 | 4 | # Area Calc
"""
You are painting a wall.
The instructions on the paint can says that 1 can of paint can cover 5 square meters of wall.
Given a random height and width of wall,
calculate how many cans of paint you'll need to buy.
Formula to caclculate number of cans:
(wall_height x wall_width) / coverage per can
"""
import math
def paint_calc(height, width, coverage):
number_of_cans = math.ceil((height * width) / coverage)
print(f"You'll need {number_of_cans} cans of paint.")
wall_height = int(input("Enter Height of wall: "))
wall_width = int(input("Enter Width of wall: "))
coverage = 5
paint_calc(wall_height, wall_width, coverage) | true |
591489c8f26efdd66c23665fce80a3d5ea3096dd | malmhaug/Py_AbsBegin | /Ch4E2_egasseM/main.py | 353 | 4.34375 | 4 | # Project Name: Ch4E2_egasseM
# Name: Jim-Kristian Malmhaug
# Date: 11 Des 2015
# Description: This program take an input message from the user and prints it backwards
message = str(input("Hey! Please enter a message: "))
print("\nThe message is backwards:\n")
for letter_nr in range(len(message), 0, -1):
print(message[letter_nr-1])
input("\nPress Enter...") | true |
ab6a519ff67fba192d60c3fc45b4833034676a9a | malmhaug/Py_AbsBegin | /Ch3E4_GuessMyNumber_V1.02/main.py | 2,503 | 4.21875 | 4 | # Project Name: Ch3E4_GuessMyNumber_V1.02
# Name: Jim-Kristian Malmhaug
# Date: 25 Oct 2015
# Description: This program is a modified version of the
# Guess My Number program from the book, with computer versus player
# Guess My Number - Computer guesser
#
# The user picks a random number between 1 and 100
# The computer tries to guess it.
# Tries = 10
# ---------------------------------------------------------------------------------
# PSEUDO CODE
# ---------------------------------------------------------------------------------
# 1. Welcome user and tell him/her what to do
# 2. Store user input in the_number
# 3. Set guess to 0
# 4. Set tries to 1
# 5. set low_guess to 1
# 6. Set high_guess to 100
# 7. Import random library
# 8. While the computer has not guessed the number and tries are below 10
# 8.1 Computer guess a number between low_guess value and high_guess value
# 8.2 Print the guess
# 8.3 If the guess is higher than the the_number
# 8.3.1 Print lower text and inform of tries left
# 8.3.2 Set high_guess to last guessed number minus one
# 8.4 Else
# 8.4.1 Print higher text and inform of tries left
# 8.4.2 Set low_guess to las guessed number plus one
# 8.5 Increment tries
# 9. If tries is above or equal to 10
# 9.1 Print failure text
# 10. If tries is below 10
# 10.1 Print winner text and winner number
# 10.2 Print tries
# 11. Print exit text, and ask for user enter input
# ---------------------------------------------------------------------------------
print("\tWelcome to 'Guess My Number'!")
print("\nThinking of a number between 1 and 100.")
print("The computer will try to guess your number in 10 tries.")
# set the initial values
the_number = int(input("Enter the number here: "))
guess = 0
tries = 1
low_guess = 1
high_guess = 100
import random
# guessing loop
while (guess != the_number) and (tries < 10):
guess = random.randint(low_guess, high_guess)
print(guess)
if guess > the_number:
print("Lower... Computer has " + str(10 - tries) + " left!")
high_guess = guess - 1
else:
print("Higher... Computer has " + str(10 - tries) + " left!")
low_guess = guess + 1
tries += 1
if tries >= 10:
print("\nThe computer failed insanely!")
else:
print("\nThe computer guessed it! The number was", the_number)
print("And it only took", tries, "tries!\n")
input("\n\nPress the enter key to exit.") | true |
cefb4ec8bf58af1859c49337d9cd7ca70df5ef77 | pohrebniak/Python-base-Online-March | /pogrebnyak_yuriy/03/Task_3_2_Custom map.py | 1,779 | 4.34375 | 4 | '''
Implement custom_map function, which will behave like the original Python map() function.
Add docstring.
'''
def custom_map(func, *args):
"""
Custom_map function, which will behave like the original Python map() function.
:param arg1: func, function name to which custom_map passes each element of given iterable
:param arg2: *args, A sequence, collection or an iterator object
:type arg1: type - string
:type arg2: type - list
:return: Returns a list of the results after applying the given function
to each item of a given iterable
:rtype: return type - list
Small comment: the differance between map() and custom_map(), output example:
>>> map(print, [1, 2, 3])
<map object at 0x034D7B20>
>>> list(map(print, [1, 2, 3]))
1
2
3
[None, None, None]
>>> custom_map(print, [1, 2, 3])
1
2
3
[None, None, None]
Custom_map() don`t return object (link to memory value) but return list of the results.
And I don`t know how to make it exactly the same function as map().
Possibly It`s needed to use python mathods.
"""
def inner_func(in_args):
"""
Function for solve: custom_map(lambda x,y: x*y, [1,2],[3,4])
"""
print('in_args: ', in_args)
print(len(in_args))
x = func(tuple(in_args))
return x
if len(args) == 1:
return [func(i) for arg in args for i in arg]
else:
return inner_func(args)
l = [['sat', 'bat', 'cat', 'mat'], ['sat', 'bat', 'cat', 'mat']]
test = list(map(list, l))
print('Original map() result:', test)
test = list(custom_map(list, l))
print('Custom function custom_map() result:', test)
| true |
4674b82a4afad64d74fe1973eb1c83566b3c6aab | pohrebniak/Python-base-Online-March | /kirill_kravchenko/02/task_2.3.py | 1,580 | 4.25 | 4 | # Given an array, find the int that appears an odd number of times. There will always be only one integer that appears an odd number of times.
#
# Examples:
#
# list: [1, 2, 3, 1, 3, 2, 1]
# output: 1
str = [1, 2, 3, 1, 3, 2, 1]
# ======
# 1 variant
# ======
equiv = 0
for i in str:
for j in str:
if i == j:
equiv += 1
if equiv > 0 and equiv % 2:
print(f'This is number "{i}" occurs "{equiv}" times in array')
break
equiv = 0
if equiv % 2 == 0:
print(f'There is no number that occurs odd times in array')
# ======
# 2 variant, not optimal, not normal, but all numbers
# ======
str_odd = []
length = 0
for i in str:
str_odd.append([i for j in str if i == j])
for j in str_odd:
length = len(j)
if length > 0 and length % 2:
print(f'This is number "{j[0]}" occurs "{length}" times in array')
break
if length % 2 == 0:
print(f'There is no number that occurs odd times in array')
# ======
# 3 variant
# ======
new_array = []
new_index_array = []
if_print = True
for i in str:
flag = True
for j in range(len(new_array)):
if new_array[j] == i:
new_index_array[j] += 1
flag = False
if flag:
new_array.append(i)
new_index_array.append(1)
for j in range(len(new_index_array)):
if new_index_array[j] % 2:
if_print = False
print(f'This is number "{new_array[j]}" occurs "{new_index_array[j]}" times in array')
break
if if_print:
print(f'There is no number that occurs odd times in array')
| true |
d03e936eb276d78f90572ad39a31e14ff76a32e5 | MuskanKhandelwal/Coding-problem-prep | /Operator overloading.py | 456 | 4.125 | 4 | class Student:
def __init__(self,x,y):
self.x=x
self.y=y
def __add__(self, other):
ans1=self.x+other.x
ans2=self.y+other.y
return ans1,ans2
S1=Student(10,20)
S2=Student(5,6)
S3=S1+S2 #This will give error as we are trying to add 2 objects, so we will override add method to add objects(operator overloading)
print(S3)
#After operator overloading giving addition answer
#S3=Student.__add__(S1,S2) | true |
4c92cfc6d9f3709ab208e4fec1d2bc1970cccea2 | agladman/python-exercises | /small-exercises/readtime.py | 1,087 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Calculates reading time based on average pace of 130 words per minute.
"""
import sys, time
def mpace(p):
if type(p) == int and p > 0:
return p
else:
match p:
case "slow":
return 100
case "average":
return 130
case "fast":
return 160
case _:
raise ValueError
def main():
words = None
pace = 130
# capture words and pace from sys args if passed
if len(sys.argv) == 2:
words = int(sys.argv[1])
elif len(sys.argv) > 2:
words = int(sys.argv[1])
p = sys.argv[2]
if p.isnumeric():
p = int(p)
pace = mpace(p)
# get words from user if still needed, pace stays as default
if words is None:
words = int(input("Enter wordcount: "))
# perform the calculation
sec = words/pace * 60
ty_res = time.gmtime(sec)
res = time.strftime("%Hh:%Mm:%Ss", ty_res)
print(f"Reading time: {res}")
if __name__ == '__main__':
main()
| true |
25dce67e505a17f3c7b71eb4a397539c956fa72d | agladman/python-exercises | /small-exercises/alphabetbob.py | 406 | 4.34375 | 4 | #!/usr/bin/env Python3
"""
Write a program that asks the user for their name, and then prints out
their name with the first letter replaced by each letter of the alphabet
in turn, e.g. for 'Bob' it prints 'Aob', 'Bob', 'Cob', 'Dob' etc.
"""
alpha = 'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z'.split()
name = input('Please enter your name: ')
for letter in alpha:
print(letter + name[1:])
| true |
3a82c8e9821e237a17e5ffe44aa806518de59433 | agladman/python-exercises | /small-exercises/benny.py | 650 | 4.21875 | 4 | #!/usr/bin/env python3
while True:
name = input('What is your name? ')
if name.replace(' ', '').isalpha():
print(f'Hello, {name}.')
break
else:
print('That\'s not a name!')
print('Here are the letters in your name: ', end='')
letters = []
for c in name:
if c not in letters:
letters.append(c)
letters.sort()
print(', '.join(l for l in letters))
bennychoice = input('Are you a benny tied to a tree? ')
if bennychoice.lower() == 'yes':
print('Haha, you\'re a benny tied to a tree!')
elif bennychoice.lower() == 'no':
print('BENNY ON THE LOOSE! BENNY ON THE LOOSE!')
else:
print('Pfeh.')
| false |
827baf8718a70c90c62f702f817824a47d6ac068 | dtom90/Algorithms | /Arrays/nearly-sorted-algorithm.py | 1,490 | 4.125 | 4 | """
Nearly Sorted Algorithm
https://practice.geeksforgeeks.org/problems/nearly-sorted-algorithm/0
Given an array of n elements, where each element is at most k away from its target position.
The task is to print array in sorted form.
Input:
First line consists of T test cases.
First line of every test case consists of two integers N and K,
denoting number of elements in array and at most k positions away from its target position respectively.
Second line of every test case consists of elements of array.
Output:
Single line output to print the sorted array.
Constraints:
1<=T<=100
1<=N<=100
1<=K<=N
Example:
Input:
2
3 3
2 1 3
6 3
2 6 3 12 56 8
Output:
1 2 3
2 3 6 8 12 56
"""
def parse_input(func):
t = int(input()) # "How many use cases? "
# print('{} test cases'.format(t))
for i in range(t):
# print('use case {}'.format(i + 1))
n, k = list(map(lambda x: int(x), input().split())) # "Size of array? "
# print('n = {}'.format(n))
# print('k = {}'.format(k))
seq = list(map(lambda x: int(x), input().split())) # "Sequence? "
# print(seq)
print(func(n, k, seq))
def fast_sort(n, k, seq):
swapped = True
while swapped:
swapped = False
for i in range(n-1):
if seq[i+1] < seq[i]:
tmp = seq[i]
seq[i] = seq[i+1]
seq[i+1] = tmp
swapped = True
return ' '.join(str(n) for n in seq)
parse_input(fast_sort)
| true |
0a67103e7ad9ba72106c840ed1dfcd7e07c2869c | dtom90/Algorithms | /Encoding/url-shortener.py | 2,067 | 4.5 | 4 | """
https://practice.geeksforgeeks.org/problems/design-a-tiny-url-or-url-shortener/0
Design a system that takes big URLs like “http://www.geeksforgeeks.org/count-sum-of-digits-in-numbers-from-1-to-n/”
and converts them into a short 6 character URL.
It is given that URLs are stored in database and every URL has an associated integer id.
So your program should take an integer id and generate a 6 character long URL.
A URL character can be one of the following
A lower case alphabet [‘a’ to ‘z’], total 26 characters
An upper case alphabet [‘A’ to ‘Z’], total 26 characters
A digit [‘0′ to ‘9’], total 10 characters
There are total 26 + 26 + 10 = 62 possible characters.
So the task is to convert an integer (database id) to a base 62 number where digits of 62 base are
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Input:
The first line of input contains an integer T denoting the number of test cases.
The second line consists of a long integer.
Output:
For each testcase, in a new line, print the shortened string in the first line
and convert the shortened string back to ID (to make sure that your conversion works fine)
and print that in the second line.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 232-1
Example:
Input:
1
12345
Output:
dnh
12345
"""
def parse_input(func):
t = int(input()) # "How many use cases? "
# print('{} test cases'.format(t))
for i in range(t):
id = int(input())
func(id)
def generate_tiny_url(id):
encoding = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
short_arr = []
while id > 62:
i = id % 62
# print(i)
short_arr.append(encoding[i])
id = int(id / 62)
# print(id)
short_arr.append(encoding[id])
# short_arr.reverse()
str = ''.join(short_arr[::-1])
print(str)
num = 0
mult = 1
for char in short_arr:
n = encoding.index(char)
# print(n, mult)
num += n * mult
mult *= 62
print(num)
parse_input(generate_tiny_url)
| true |
834de094ea09b3e3a66ea6b7222a8ad905f9d790 | nurawat/learning_python | /list_range_introduction.py | 641 | 4.15625 | 4 | ##
# Basic Learner type
#
##
# ip_address = input("Please Enter IP address : ")
# print(ip_address.count("."))
ip_address = ["127.0.0.1", "192.168.0.1", "192.168.1.1"]
for single_IP in ip_address:
print("IP given is {}".format(single_IP))
### List
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7]
numbers = even + odd
l_numbers = numbers
numbers.sort(reverse = True)
print(numbers is even)
if sorted(l_numbers) == numbers:
print("YES")
else:
print("NO")
print(list("Hi, This is arun"))
dummy = "this is a test"
print(dummy.split())
###### range
print("#######################")
print(list(range(0,10,1)))
print(list(range(0,10,2)))
| true |
34b4df534b19bc416dffdb4f35a63681d9c6fa16 | anant-creator/Other_sources | /Area_perimeter_of_Triangle.py | 404 | 4.125 | 4 | ''' Area and perimeter of a right angle triangle '''
base = int(input("Enter the base of triangle:- "))
height = int(input("Enter the height of triangle:- "))
print("If you want to know the area then use '0' as hypotenuse")
hypotenuse = int(input("Enter the hypotenuse:- "))
area = base * height / 2
perimeter = base + height + hypotenuse
if hypotenuse == 0:
print(area)
else:
print(perimeter)
| true |
66a5d533a37ba0df7d85bba6df765a903e5679d3 | KakE-TURTL3/PythonPractice | /Login System/loginSystem.py | 1,509 | 4.15625 | 4 | import time
#Introduces user to program they are using
print("Welcome to *insert name here*")
#Asks the user to either register or log in
opt = int(input ("To continue you must login or register. Please pick an option.\n1)Log In\n2)Register\n"))
#Defines login function
def login():
accountName = input("Please enter your account name: ")
password = input("Please enter your password: ")
f = open("accounts.txt", "r")
real = f.read()
accountDetails = accountName + ", " + password + "\n"
if accountDetails == real:
print("You have successfully logged in to the account: " + accountName + "\n")
time.sleep(2)
else:
print("Login failed. You entered the wrong username or password. Please try again.\n")
login()
f.close()
#Define register function
def register():
registerAccountName = input("Please input a suitable username: ")
registerPassword = input("Please enter a suitable password: ")
confirmPassword = input("Please confirm your password: ")
if registerPassword == confirmPassword:
f = open("accounts.txt", "w")
f.write(registerAccountName + ", " + registerPassword + "\n")
f.close()
print("Now you must log in")
login()
else:
print("The first password you entered didnt match the confirm password. Please try again.\n")
register()
if opt == 1:
login()
elif opt == 2:
register()
else:
quit
| true |
704eeb3197f4bfd65121dcb7bed54dc5113014b5 | simrit1/scrabble-word-score-calculator | /scrabble_word_score.py | 1,837 | 4.25 | 4 | '''
Habitica Challenge October 2019
Challenge Description
In the game Scrabble each letter has a value. One completed word gives you a score.
Write a program that takes a word as an imput and outputs the calculated scrabble score.
Values and Letters:
1 - A, E, I, O, U, L, N, R, S, T
2 - D, G
3 - B, C, M, P
4 - F, H, V, W, Y
5 - K
8 - J, X
10 - Q, Z
Example:
The word "cabbage" gives you a score of 14 (c-3, a-1, b-3, b-3, a-1, g-2, e-1)
Extensions:
You can play a double or triple letter
You can play a double or triple word
'''
import os
let_val = {
'A':1, 'E':1, 'I':1, 'O':1, 'U':1, 'L':1, 'N':1, 'R':1, 'S':1, 'T':1,
'D':2, 'G':2,
'B':3, 'C':3, 'M':3, 'P':3,
'F':4, 'H':4, 'V':4, 'W':4, 'Y':4,
'K':5,
'J':8, 'X':8,
'Q':10, 'Z':10
}
def select_action():
print('Please Select Action:')
op = -1
while not(op == '1' or op == '0'):
print(' 1 - Check word')
print(' 0 - Exit')
op = input('Option: ')
return op
def check_valid_word(word):
with open('sowpods.txt') as f:
if word in f.read():
return True
return False
def enter_word():
word = input('Please enter word: ').upper().strip()
while not check_valid_word(word):
word = input('Invalid Scrabble word. Please Try again: ').upper().strip()
score = 0
for let in word:
score += let_val[let]
print('Valid Scrabble word! The score for {} is: {}\n'.format(word, score))
def main():
dir_path = os.path.dirname(os.path.realpath(__file__))
os.chdir(dir_path)
print('Welcome to scrabble word value calculator!')
opt = select_action()
while opt != '0':
enter_word()
opt = select_action()
print('Thanks for playing!')
main() | true |
f1bee033404e488367764c89353caa5798015b37 | PaulCardoos/pythonBasics | /ListComprehensions/Examples/concatLists.py | 214 | 4.21875 | 4 | #concatenting lists in python is like combing them
x = [1, 2, 3]
y = [4, 5]
z = x + y
print(z)
#z = [1, 2, 3, 4, 5]
#if you multiple 3 * x it is similar to x + x + x
print(3 * x)
#[1, 2, 3, 1, 2, 3, 1, 2, 3] | false |
08f9a8c7e174acc88b18811e4b2b6ee2b6bc0c4f | Liquid-sun/MIT-6.00.1x | /week-4/fruits.py | 1,665 | 4.21875 | 4 |
"""
Code Grader: Python Loves Fruits
(10 points possible)
Python is an MIT student who loves fruits. He carries different types of fruits (represented by capital letters)
daily from his house to the MIT campus to eat on the way. But the way he eats fruits is unique.
After each fruit he eats (except the last one which he eats just on reaching the campus), he takes a 30 second
break in which he buys 1 fruit of each type other than the one he just had.
Cobra, his close friend, one day decided to keep a check on Python. He followed him on his way to MIT campus
and noted down the type of fruit he ate in the form of a string pattern (Eg.: 'AABBBBCA').
Can you help Cobra determine the maximum quantity out of the different types of fruits
that is present with Python when he has reached the campus?
Write a function nfruits that takes two arguments:
A non-empty dictionary containing type of fruit and its quantity initially with Python when he leaves home (length < 10)
A string pattern of the fruits eaten by Python on his journey as observed by Cobra.
This function should return the maximum quantity out of the different types of fruits that is available with
Python when he has reached the campus.
For example, if the initial quantities are {'A': 1, 'B': 2, 'C': 3} and the string pattern is 'AC' then
'A' is consumed, updated values are {'A': 0, 'B': 2, 'C': 3}
Python buys 'B' and 'C', updated values are {'A': 0, 'B': 3, 'C': 4}
'C' is consumed, updated values are {'A': 0, 'B': 3, 'C': 3}
Now Python has reached the campus. So the function will return 3 that is maximum of the quantities of the three fruits.
"""
| true |
d43a9d3ba885470d292cb3d377913f7257862571 | Liquid-sun/MIT-6.00.1x | /week-1-2/payments3.py | 731 | 4.125 | 4 | #!/usr/bin/env python
balance = 320000
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate / 12.0
min_pay = balance / 12
max_pay = (balance * (1 + monthlyInterestRate)**12) / 12.0
ans = (min_pay + max_pay) / 2
while(balance <= 0):
print('pay: ', ans)
for month in range(1, 13):
balance -= ans
interest = (annualInterestRate / 12.0) * balance
balance += interest
print("Remaining balance at the end of the year: {}".format(round(balance, 2)))
print("Min payment: {}".format(ans))
if balance > 0:
min_pay = ans
else:
max_pay = ans
print("--------------------------------------------")
#print("Lowest Payment: {}".format(round(ans, 2)))
| true |
2dfc365283d74732559002389ca6b526ec4d0891 | Liquid-sun/MIT-6.00.1x | /quiz/flatten.py | 616 | 4.46875 | 4 | #!/usr/bin/env python
"""
Problem 6
(15 points possible)
Write a function to flatten a list. The list contains other lists, strings, or ints.
For example, [[1,'a',['cat'],2],[[[3]],'dog'],4,5] is flattened into [1,'a','cat',2,3,'dog',4,5]
"""
def flatten(aList):
'''
aList: a list
Returns a copy of aList, which is a flattened version of aList
'''
flt = lambda *n: (e for a in n for e in (flt(*a) if isinstance(a, list) else (a,)))
return list(flt(aList))
if __name__=="__main__":
test_list = [[1,'a',['cat'],2],[[[3]],'dog'],4,5]
flat = flatten(test_list)
print flat
| true |
96f5e490d0d0e216bc13b8ac4b6fced2a3888e86 | Liquid-sun/MIT-6.00.1x | /week-6/queue.py | 1,694 | 4.46875 | 4 | #!/usr/bin/env python
"""
For this exercise, you will be coding your very first class, a Queue class.
Queues are a fundamental computer science data structure. A queue is basically
like a line at Disneyland - you can add elements to a queue, and they maintain
a specific order.
When you want to get something off the end of a queue, you get the item that
has been in there the longest (this is known as 'first-in-first-out', or FIFO).
You can read up on queues at Wikipedia if you'd like to learn more.
In your Queue class, you will need three methods:
__init__:
initialize your Queue (think: how will you store the queue's elements?
You'll need to initialize an appropriate object attribute in this method)
insert:
inserts one element in your Queue
remove:
removes (or 'pops') one element from your Queue and returns it.
If the queue is empty, raises a ValueError.
"""
class Queue(object):
def __init__(self):
self.qu = []
def __len__(self):
return len(self.qu)
def __repr__(self):
q = ','.join([str(i) for i in self.qu])
return "Queue({})".format(q)
def __str__(self):
q = ','.join([str(i) for i in self.qu])
return "[{}]".format(q)
def insert(self, item):
self.qu.append(item)
def remove(self):
if not self.qu:
raise ValueError("Queue is empty")
else:
fst = self.qu[0]
self.qu = self.qu[1:]
return fst
if __name__=="__main__":
q = Queue()
for i in range(10):
q.insert(i)
print repr(q)
for i in range(20):
elem = q.remove()
print("Removing: {}".format(elem))
print repr(q)
| true |
d34b5d4f791efb03822cd6841ba5f7636cf635f1 | prajaktasangore/coding-challenge-2015 | /PythogorousTriplets.py | 787 | 4.3125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Prajakta Sangore
# Date: 30th September 2015
# Problem: A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a2 + b2 = c2
# For example, 32 + 42 = 9 + 16 = 25 = 52.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
import time
import decimal
start_time = time.time()
def pythagorous():
for a in xrange (1,1000):
for b in xrange(2,1000):
c = 1000 - (a+b)
if((a**2) + (b**2) == (c**2)):
if(a + b + c == 1000):
print "a = %d b =%d c = %d" %(a,b,c)
print "The sum is = %d" %(a+b+c)
print "The product is = %d" %(a*b*c)
return 1
pythagorous()
print "total time taken = %s seconds" %round((time.time() - start_time),2)
| true |
c8a6d7caef5c558d448908ba2f764f4adbfab1d8 | chunkify/Course_Materials | /CMPT 830_Bioinformatics_and_Computational_Biology/Assignment_1/Solution/Exercise 2.py | 2,098 | 4.21875 | 4 | #!/usr/bin/env python3
# This script will open the file "Glycoprotein.fasta" and read each line of the
# file within a for-loop. That means that each iteration through the for-loop
# will be performed with a new (the next) line of the input file. The
# number of characters in each line is printed.
# Open the file
#file = open("Glycoprotein.fasta")
flag = 0
total_sequence = 0
amino_acid = "";
amino_acid_count = 0
print("Enter the name of a FASTA file: ")
file_name = input()
file_name_list = file_name.split(".")
length_list = len(file_name_list)
if length_list == 2 and file_name_list[1] != "fasta":
print("enter a valid FASTA file name with extension fasta ")
elif length_list == 1:
fasta_file_name = file_name + ".fasta" # make the file name with extension "fasta"
file = open(fasta_file_name, "r")
flag = 1
else:
file = open(file_name,"r")
flag = 1
f= open("out.txt","w+")
# The next operation will repeatedly read the next line of the file and place
# it in the string "line". The loop will then be performed for each
# value of "line". Note that the terminating newline character
# (of the line that was read) will be included in the value of "line"
if flag:
for line in file:
#Print out the length of the line
if line[0] == ">":
header = line
if amino_acid_count != 0:
print("the first ten characters are: ",amino_acid[0:10]," and the total amino acid count is: ",amino_acid_count)
amino_acid_count = 0
amino_acid = ""
print("the header is: ", line.rstrip())
total_sequence += 1
#f.write(line)
else:
line = line.rstrip()
amino_acid += line
amino_acid_count += len(line)
#line = line.rstrip()
#print( "the line contains ", len(line), " characters")
#print("the string: ", line)
# Close the opened file. This step is actually optional if it occurs
# at the end of the script.
#file.close()
if header[0] == ">":
print("the first ten characters are: ", amino_acid[0:10], " and the total amino acid count is: ", amino_acid_count)
print("total sequence is: ", total_sequence)
| true |
b87ab17b096cb7c1eed8dd619788156da0ce6047 | ashrafuzzaman1973/python-basic | /logical.py | 424 | 4.1875 | 4 |
'''
num1 = 30
num2 = 50
num3 = 40
if num1 > num2 and num1 > num3 :
print(num1)
elif num2 > num1 and num2 > num3 :
print(num2)
else:
print(num3)
'''
#vowel - a,e,i,o,u
'''
ch = 'b'
if ch == 'a' or ch == 'e' or ch == 'i' and ch == 'o' or ch == 'u' :
print("Vowel")
else:
print("Consonant")
'''
marks = 69
if 80 <= marks <= 100:
print("A+")
elif 70 <= marks <= 79:
print("A")
else:
print("C") | false |
d3db0e57da66e3105e022c17ee7567a2358b9541 | chriscross00/cci | /data_structures/linked_lists.py | 2,176 | 4.15625 | 4 | # https://www.codefellows.org/blog/implementing-a-singly-linked-list-in-python/
# READ THIS https://www.greenteapress.com/thinkpython/thinkCSpy/html/chap17
# .html
# creating the class Node
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def get_data(self):
return self.data
def set_data(self, val):
self.data = val
def get_next(self):
return self.next
def set_next(self, val):
self.next = val
# Class linked list
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def get_size(self):
return self.size
def is_empty(self):
return self.head is None
def add(self, item):
temp = Node(item)
temp.set_next(self.head)
self.head = temp
self.size += 1
def search(self, item):
current = self.head
found = False
while current is not None and not found:
if current.get_data() == item:
found = True
else:
current = current.get_next()
return found
def remove(self, item):
# Setting up our pointers
current = self.head
previous = None
found = False
# The search function
while not found:
if current.get_data() == item:
found = True
self.size -= 1
else:
previous = current
current = current.get_next()
# Once item is found break to this if-else statement which 'leap
# frogs' the item node, connecting the previous node to the node
# after current.
if previous is None:
self.head = current.get_next()
else:
previous.set_next(current.get_next())
def print_list(self):
current = self.head
while current is not None:
print(current.get_data())
current = current.get_next()
mylist = LinkedList()
mylist.add(31)
mylist.add(77)
mylist.add(17)
mylist.add(93)
mylist.add(26)
mylist.add(54)
mylist.print_list()
| true |
4f4b1f8d07e12ede2fc210ab563bd6ece33feeab | BlackTimber-Labs/DemoPullRequest | /Python/ashi77.py | 1,785 | 4.28125 | 4 | from random import randint
EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5
#Function to check user's guess against actual answer.
def check_answer(guess, answer, turns):
"""checks answer against guess. Returns the number of turns remaining."""
if guess > answer:
print("Too high.")
return turns - 1
elif guess < answer:
print("Too low.")
return turns - 1
else:
print(f"You got it! The answer was {answer}.")
#Make function to set difficulty.
def set_difficulty():
level = input("Choose a difficulty. Type 'easy' or 'hard': ")
if level == "easy":
return EASY_LEVEL_TURNS
else:
return HARD_LEVEL_TURNS
def game():
print("""
/ _ \_ _ ___ ___ ___ /__ \ |__ ___ /\ \ \_ _ _ __ ___ | |__ ___ _ __
/ /_\/ | | |/ _ \/ __/ __| / /\/ '_ \ / _ \ / \/ / | | | '_ ` _ \| '_ \ / _ \ '__|
/ /_\\| |_| | __/\__ \__ \ / / | | | | __/ / /\ /| |_| | | | | | | |_) | __/ |
\____/ \__,_|\___||___/___/ \/ |_| |_|\___| \_\ \/ \__,_|_| |_| |_|_.__/ \___|_|
""")
#Choosing a random number between 1 and 100.
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
answer = randint(1, 100)
print(f"Pssst, the correct answer is {answer}")
turns = set_difficulty()
#Repeat the guessing functionality if they get it wrong.
guess = 0
while guess != answer:
print(f"You have {turns} attempts remaining to guess the number.")
#Let the user guess a number.
guess = int(input("Make a guess: "))
#Track the number of turns and reduce by 1 if they get it wrong.
turns = check_answer(guess, answer, turns)
if turns == 0:
print("You've run out of guesses, you lose.")
return
elif guess != answer:
print("Guess again.")
game()
| false |
13300283d829e0a97591566f852896cbf30e2a00 | BlackTimber-Labs/DemoPullRequest | /Python/tripur1.py | 303 | 4.15625 | 4 | # to find sum
# of elements in given array
def _sum(arr):
sum=0
for i in arr:
sum = sum + i
return(sum)
# driver function
arr=[]
# input values to list
arr = [12, 3, 4, 15]
# calculating length of array
n = len(arr)
ans = _sum(arr)
# display sum
print ('Sum of the array is ', ans)
| true |
ae33b423103085042b0b0084035f20108689778e | fizzahwaseem/Assignments | /31_gcd.py | 394 | 4.21875 | 4 | #Python program to compute the greatest common divisor (GCD) of two positive integers.
print('To find GCD enter ')
num1 = int(input('number 1 : '))
num2 = int(input('number 2 : '))
if num1 > num2:
greater = num1
else:
greater = num2
for i in range(1, greater+1):
if((num1 % i == 0) and (num2 % i == 0)):
gcd = i
print('The gcd of' , num1 , 'and' , num2 , 'is' , gcd) | true |
37bd3a47aacd1402a5e1a2dd9bc3d828b0222027 | fizzahwaseem/Assignments | /26_digit_to_etc.py | 257 | 4.53125 | 5 | #Python program to convert an integer to Binary, Octal and Hexadecimal numbers
decimal = int(input("Enter an integer: "))
print(decimal, "to binary: ", bin(decimal))
print(decimal, "to octal: ", oct(decimal))
print(decimal, "to hexadecimal: ", hex(decimal)) | false |
bd671af590ae1ec9251afc96487aa2e1f95db6cb | fizzahwaseem/Assignments | /20_time_to_seconds.py | 224 | 4.28125 | 4 | #Python program to convert all units of time into seconds.
hour = int(input("Enter time in hours: "))
minute = int(input("Enter time in minutes: "))
t = (hour * 60 * 60) + (minute * 60)
print("Total time in seconds is: ", t) | true |
26a3b257f2a1797e32773e653195450f68e83729 | AnneOkk/Alien_Game | /bullet.py | 1,561 | 4.125 | 4 | import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""A class to manage bullets fired from the ship"""
def __init__(self, ai_game):
"""Create a bullet object at the ship's current position."""
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
self.color = self.settings.bullet_color
# Create a bullet rect at (0,0) and then set the correct position.
self.rect = pygame.Rect(0,0, self.settings.bullet_width,
self.settings.bullet_height) # requires the x- and y-coordinates of the top-left
# corner rect, and the width and height of the rect
self.rect.midtop = ai_game.ship.rect.midtop # set the bullet's midtop attribute to match the ship's midtop
# attribute --> makes it look like the bullet emerges from the top of the ship (like it is fired)
# Store the bullet's position as a decimal value.
self.y = float(self.rect.y) #store decimal values for the bullet's y coordinate, so we can make fine
# adjustment to the bullet's speed
def update(self):
"""Move the bullet up the screen"""
#Uodate the decimal position of the bullet.
self.y -= self.settings.bullet_speed #when bullet is fired, it moves up the screen --> decreasing y value
#Update the rect position.
self.rect.y = self.y
def draw_bullet(self):
"""Draw the bullet to the screen"""
pygame.draw.ellipse(self.screen, self.color, self.rect) | true |
343cd7567341f94b32b70ac9b1089734aa79aaaf | trev3rd/gogo | /guess1.py | 1,622 | 4.46875 | 4 | import random
guessesTaken = 0 #this represents how many times the user has tried guessing the right number starting from zero
number = random.randint(1, 10)
print(number) #this shows the random number the computer picked good for seeing if code works properly
print(' I am thinking of a number between 1 and 10.')
while guessesTaken < 3: #this says while the user has tried less than 3 times the follwoing shall happen
print('Take a guess.')
guess = input() # this basically allows the user to input a response from the above print statement
guess = int(guess)# this makes sure that its a integer that should be guessed
guessesTaken = guessesTaken + 1 # the "count" basically that you had in your code for the increments
#this is where the if statements come in
if guess == number +1 or guess == number -1: #as i said in class to give output hot if its 1 higher or lower
print('Your guess is hot')
if guess == number +2 or guess == number -2:#if its 2 higher or lower from random number
print('Your guess is warm.')
elif guess > number +2 or guess < number -2:#if greater than 2(3 or more/3 or less) it will say cold
print('your guess is cold')
if guess == number: # if the user gets the right number the following happends
print('Good job! You guessed my number in ', guessesTaken)#outputs how many times it took user to guess
break
if guess != number: # this is outside of loop to avoid a paradox and confusion with the top 3 ifs in the while statement
print('Nope. The number I was thinking of was ', number)
| true |
e40c1a1235616b50f4eee5211d52146eb15d2234 | rugved-mahamune/interview-practice | /fibo.py | 273 | 4.1875 | 4 | '''def fibonacci(n):
if(n == 1 or n == 2):
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
num = 8
print(fibonacci(num))'''
list1 = [0,1]
n = 8
curr = 2
while(curr < n):
list1.append(list1[curr-1] + list1[curr-2])
curr+=1
print(list1) | false |
0b5ce13bcb253816f93f40949150a0fc47b2dddd | faliona6/PythonWork | /letter.py | 404 | 4.125 | 4 |
word = input("What is the magical word?")
def Dictionary(word):
dictionary = {}
a = 0
for letter in word:
if letter in dictionary:
dictionary[letter] = dictionary[letter] + 1
else:
dictionary[letter] = 1
return dictionary
dictionary = Dictionary(word)
for let, count in dictionary.items():
print("Letter: " + let + "\tCount: " + str(count))
| true |
7b14801d22dc3b8aedb276b27d5e636634fc25c7 | Darshan1917/Data_analysis | /titanic.py | 1,330 | 4.28125 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
titanic = pd.read_csv('train.csv', delimiter = ',')
'''
## checking the datatypes
#print (titanic.info())
## or
#print (titanic.dtypes)
## Describe gives mean total number , median etc
#print (titanic.describe())
'''
# print (type(titanic))
''' to see head and tail of a dataset'''
print(titanic.head()) # gives first 5 record
print(titanic.tail()) # gives last 5 records of the dataset
''' shape of my dataset '''
print(titanic.shape)
value = titanic.isnull()
print (value)
print (titanic.isnull().sum())
''' General way to create a dataframe pd.Dataframe()
'''
df = pd.DataFrame()
df['Name'] = ['Steve Smith','Virat Kholi', 'Sachin ramesh Tendulkar']
df['age'] = [30,29,37]
df['salary'] = [35000,45000,55000]
df['country'] = ['Aus','Ind','Ind']
print (df)
#adding rows to dataframe
#create a row and add
new_row = pd.Series([' Angelo Mathews', 28, 32000,'Sri'], index =['Name','age','salary','country'])
#print(new_row)
#print(type(new_row))
#we use df.append
df = df.append(new_row, ignore_index=True)
print (df)
#navigate in dataframe loc and iloc
print(df.iloc[0])
print(titanic.iloc[0][4])
''' select the entire row '''
print(df.iloc[ : 2]) # only select only 2 rows
print(df[['age','salary']]) #only columns
print(df.loc[:,"age":"country"])
print(df.iloc[:,1:3])
| false |
1b536c7de215a6511df46e606f059fef64529533 | j33mk/PythonSandboxProdVersion | /pythonsandbox/sandbox/newpython/dopamine.py | 872 | 4.1875 | 4 | #i was thinking how can i link my dopamine with programming, get back to programming and learn datascience, machine learning, and make myself expert in everything that i come across
# what is stopping me? What are the things that are stopping me
# this is the question that i am searching the answer
print('dopamine research')
import numpy as np
#lets build a little game to get back to what i am missing for quite long time
guess_numbers = [1,2,3,4,5,6,7,8,9,10]
guessed_number = np.random.choice(guess_numbers)
if guessed_number%2 == 0:
print("It seems the number is even")
else:
print("Well the number seems to be odd try to guess it")
user_input = int(input("Enter a number: "))
score = 0
if user_input == guessed_number:
score = score+1
print("You guess corrected :)")
print("Your score is : "+str(score))
else:
print("sorry try again :(")
| true |
eff5e1ac079573feb1d0cf78aacd4f2088e8c845 | turalss/Python | /day_2_a.py | 1,299 | 4.40625 | 4 | # Write a string that returns just the letter ‘r’ from ‘Hello World’
# For example, ‘Hello World’[0] returns ‘H’.You should write one line of code. Don’t assign a variable name to the string.
hello_world = 'Hello World'
print(hello_world[8])
# 2. String slicing to grab the word ‘ink’ from the word ‘thinker’
# S=’hello’,what is the output of h[1]
s = 'hello'
print(s[1]) # output is 'e'
thinker = 'thinker'
print(thinker[2:5])
# 3. S=’Sammy’ what is the output of s[2:]”
sammy = 'Sammy'
print(sammy[2:]) # outpur is 'mmy'.
# 4. With a single set function can you turn the word ‘Mississippi’ to distinct character word.
def split_string(string):
return [char for char in string]
mississippi = 'Mississippi!'
print(split_string(mississippi))
# 5. The word or whole phrase which has the same sequence of letters in both directions is called a palindrome.
def palidrome(data):
result = []
data = data[1:]
for string in data:
if ''.join(e for e in string if e.isalnum()).lower() == ''.join(e for e in string if e.isalnum())[::-1].lower():
result.append('Y')
else:
result.append('N')
return(result)
data = [3, 'Amore, Roma', 'No "x" in Nixon', 'Was it a cat I saw?']
print(palidrome(data))
| true |
8c4f0158e801cb77e85555ac6283c78f44c99ce9 | AISWARYAK99/Python | /tuples.py | 952 | 4.65625 | 5 | #tuples
#they are not mutable
my_tuple=()
my_tuple1=tuple()
print(my_tuple)
print(my_tuple1)
my_tuple=my_tuple+(1,2,3)
print(my_tuple)
my_tuple2=(1,2,3)
my_tupple4=tuple(('Python','Java','Php',1))
print(my_tuple2)
print(my_tupple4)
my_tuple5='example', #add comma if we want tuple with single elements
print(type(my_tuple5))
#Accessing elements
my_tuple6=(1,2,3,['Hindi','telugu'])
print(my_tuple6[0])
print(my_tuple6[:])
print(my_tuple6[3][1])#2 element of 3rd index
print(my_tuple6[::-1])#accessing elements in reverse order
print(my_tuple6[0:5:2])#0 to 4 will be printed with jumping of 2 elements instead of 1
my_tuple6[3][1]='English' #we can change values of a tuple since it is immutable but we since the 3rd index of tuple is a list we can change the list component of that tuple.
print(my_tuple6)
#tuple methods
my_tuple7=(1,2,3,'English')
print(my_tuple7.count('English'))
print(my_tuple7.index('English'))
| true |
b3fd5e9b71657eeb1333aa465f429d511ba27a2f | AISWARYAK99/Python | /start1.py | 1,685 | 4.28125 | 4 | #python beginning
'''
There are 6 data types in python.
1.Numeric(not mutable)
2.List(mutable)
3.Tuples
4.Dictionary
5.Set
6.String
'''
print('hello users welcome to the basics')
a=int(input('Enter num a:'))#input is read as a string so converting it to int.
b=int(input('Enter num s:'))#type conversion of string to int
print('The addition of a and is:',(a+b))
#data types
a=10
b=30
a=9
print(a)
#numeric dataype
a=10 #integer
b=-10
c=3.14 #Float
d=0.142
e=10+3j #Complex-numbers
f=6j
print(a+b,c-d,e-f,end='\n')
print(a-c,b-f,a*b,end='\n')
#type-conversions
s='10010' #String
c=(int)(s,2) # passing 2 since its a binary num we need to convert s to an integer of base 2 which is binary
print('After converting to integer base 2: %d ' %c,end='\n')
e=float(s)
print('After converting to float: %f ' %e,end='\n')
s='4' #initialising integer
c=ord(s) # char converted to integer
print('After converting character to integer : %d ' %c,end='\n')
c=hex(56)
print('After converting 56 to hexadecimal string : ' +c,end='\n')
c=oct(56)
print('After converting 56 to octal string : '+c,end='\n')
s='Aiswarya' #initialising string
c=tuple(s)
print('After converting string to tuple ',c,end='\n')
c=set(s)
print('After converting string to set ',c,end='\n')
c=list(s)
print('After converting string to list ',c,end='\n')
a=1
b=2
tup=(('a',1),('f',2),('g',3)) #initialising tuple
c=complex(1,2)
print('After converting integer to complex numbers ',c,end='\n')
c=str(a)
print('After converting integer to string ',c,end='\n')
c=dict(tup)
print('After converting tuple to dictionary ',c,end='\n')
| true |
eadc78f6241176af767fed72ac5fbf14b5440c4f | Ivasuissa/python1 | /isEven.py | 246 | 4.1875 | 4 |
def is_even(n):
if (n % 1) == 0:
if (n % 2) == 0:
print("True")
return True
else:
print("False")
return False
else:
print(f"{n} is not an integer")
is_even(-4) | true |
eb0146449cf4c1038ba3107983fbed12bb9db675 | mdmcconville/Solutions | /validPalindrome.py | 683 | 4.15625 | 4 | import string
"""
This determines whether a given string is a palindrome regardless of case,
punctuation, or whitespace.
"""
class Solution:
"""
Precondition: s is a string
Postcondition: returns a boolean
"""
def isPalindrome(self, s):
# Case: string is empty
if not s:
return True
else:
# Remove whitespace and punctuation and make all lower-case
s = ''.join(i for i in s if i not in(string.punctuation +
string.whitespace)).lower()
# Return whether the reversed string equals the original
return s == s[::-1]
| true |
9c86124bc1733189f8edab9712a4d79e3e074345 | mlesigues/Python | /everyday challenge/day_19.py | 1,916 | 4.125 | 4 | #Task: Vertical Order Traversal of a Binary Tree from Leetcode
#src:https://www.geeksforgeeks.org/print-binary-tree-vertical-order-set-2/
#src:https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/253965/Python-8-lines-array-and-hashmap-solutions
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import defaultdict
class Solution:
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
#the horizontal distance of root is set to 0 => root: (x,y) = (0,0)
#will be used for the vertical nodes, min and max vertical indices
self.dic = collections.defaultdict(list)
""""
self.minimumLevel, self.maximumLevel = float("inf"), -float("inf")
#dfs function: takes in root, horizontal coordinate, vertical coordinate
def dfs(root, hor, ver):
self.maximumLevel = min(hor, self.minimumLevel)
self.minimumLevel = max(hor, self.maximumLevel)
dic[hor].append((ver, root.val))
if root.left:
dfs(root.left, hor-1, ver+1)
if root.right:
dfs(root.right, hor+1, ver+1)
dfs(root, 0,0)
result = []
for i in range(self.minimumLevel, self.maximumLevel + 1):
result += [[i for i,j in sorted(dic[i])]]
return result
"""
def dfs(node, hor, ver):
if node:
self.dic[hor].append((ver, node.val))
dfs(node.left, hor - 1, ver + 1)
dfs(node.right, hor + 1, ver + 1)
dfs(root, 0, 0)
return [list(map(lambda hor: hor[1], sorted(arr))) for x, arr in sorted(self.dic.items())]
| true |
551824b92a522ebbaa8d8efb5b2a790953662133 | mlesigues/Python | /everyday challenge/day_13.py | 1,713 | 4.125 | 4 | #TASK: Given a full name, your task is to capitalize the name appropriately.
#input: s is the full name
# Complete the solve function below.
def solve(s):
#s[0] = s.capitalize()
#cap = s.capitalize()
# for i in len(range(s)):
# if s[i] == " ":
# s[i+1] = s.capitalize()
# for i in range(0, len(s)):
# if [s+1] == " ":
# cap = s.capitalize()
# strSplit = s.split(" ")
# for i in range(0, len(s)):
# i[0] = s.capitalize()
# if s[i] == strSplit:
# if s[i+1] != strSplit:
# s[i+1] = s.capitalize()
# return s
#newString = s
#new_string = newString.capitalize()
newString = s
new_string = ' '.join(map(str.capitalize, newString.split(' ')))
return new_string
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = solve(s)
fptr.write(result + '\n')
fptr.close()
#TASK: matrix addition.
#input: user will input the two arrays => can be converted to matrices
from array import *
#src: https://www.geeksforgeeks.org/take-matrix-input-from-user-in-python/
userInput_Row = int(input("Enter the number of rows: "))
userInput_Col = int(input("Enter the number of columns: "))
print("Enter entries in a single line (press enter after each element): ")
#result = list(map(int, input("Enter array elements: ").split()))
result = []
#putting values into a matrix
for i in range(userInput_Row):
emp = []
for j in range(userInput_Col):
emp.append(int(input()))
result.append(emp)
#print matrix
for i in range(userInput_Row):
for j in range(userInput_Col):
print(result[i][j], end=" ")
print()
| true |
bc4bbe31282a164f7490f19f8809323a04e551c7 | mangel2500/Programacion | /Práctica 7 Python/Exer-2.py | 603 | 4.1875 | 4 | '''MIGUEL ANGEL MENA ALCALDE - PRACTICA 7 EJERCICIO 2
Escribe un programa que lea el nombre y los dos apellidos de
una persona (en tres cadenas de caracteres diferentes), los pase
como parmetros a una funcin, y sta debe unirlos y devolver
una nica cadena. La cadena final la imprimir el programa por pantalla'''
def total():
nombre=raw_input("Escribe tu nombre: ")
apellido1=raw_input("Escribe tu primer apellido: ")
apellido2=raw_input("Escribe tu segundo apellido: ")
total = nombre+' '+ apellido1+' '+apellido2
print 'Tu nombre es: ',total
total()
| false |
ece505a202ad37c9ca990f3b84f121cc076f5a02 | amrishparmar/countdown-solver | /countdown.py | 2,941 | 4.25 | 4 | import argparse
import sys
def load_words(filename):
"""Load all words (9 letters or less) from dictionary into memory
:param filename: A string, the filename to load
:return: A set, all relevant words in the file
"""
valid_words = set()
with open(filename, 'r') as word_file:
for word in word_file:
if len(word) < 11: # only want 9 letter words (accounts for \n extra char)
valid_words.add(word.rstrip('\n'))
return valid_words
def generate_solutions(words, letters, sort=True):
"""Generate a list of all possible solutions from the given letters
:param words: A set of all valid words
:param letters: A string, the letters from which is derive the solution
:return: A list of strings, the solutions
"""
solutions = []
def check_all_letters_valid(word):
"""Check whether a word can be made from the given letters"""
temp_letters = letters
for letter in word:
if letter in temp_letters:
index_of_letter = temp_letters.index(letter)
temp_letters = temp_letters[:index_of_letter] + temp_letters[index_of_letter + 1:]
else:
return False
return True
for word in words:
if check_all_letters_valid(word):
solutions.append(word)
if sort:
solutions.sort(key=lambda w: len(w))
return solutions
def pretty_print_solutions(solutions, reverse=False):
"""Print out the solutions organised by word length
:param solutions: A list of strings containing the possible solutions
:param reverse: A bool, whether to print longest to shortest (True) or shortest to longest (False)
"""
word_lists = [[word for word in solutions if len(word) == i] for i in range(1, 10)]
for i, sublist in enumerate(word_lists):
print('=== {} letter words ==='.format(i + 1))
for word in sorted(sublist, reverse=reverse):
print(word)
def main():
"""Main function"""
parser = argparse.ArgumentParser(description='Generate possible solutions to a Countdown puzzle.')
parser.add_argument('dictionary', type=str, help='A dictionary filename')
parser.add_argument('--letters', type=str, help='The puzzle letters')
args = parser.parse_args()
words = load_words(args.dictionary)
if args.letters:
solutions = generate_solutions(words, args.letters)
pretty_print_solutions(solutions)
else:
while True:
try:
letters = input('Enter letters (or Ctrl-D to quit): ')
except EOFError:
print('Quitting...')
sys.exit()
solutions = generate_solutions(words, letters)
print('Solutions are:')
pretty_print_solutions(solutions)
print()
if __name__ == '__main__':
main()
| true |
c77766a42c2ad2c69e0dbb57ae284d8aa04f5a64 | robinyms78/My-Portfolio | /Exercises/Python/Learning Python_5th Edition/Chapter 4_Introducing Python Object Types/Examples/Dictionaries/Nesting Revisited/Example1/Example1/Example1.py | 375 | 4.46875 | 4 | rec = {"name": {"first": "Bob", "last": "Smith"}, "jobs": ["dev","mgr"], "age": 40.5}
# "name" is a nested dictionary
print(rec["name"])
# Index the nested dictionary
print(rec["name"]["last"])
# "jobs" is a nested list
print(rec["jobs"])
# Index the nested list
print(rec["jobs"][-1])
# Expand Bob's job description in place
rec["jobs"].append("janitor")
print(rec)
| true |
461fdf8ec3a0c44f068c802e51eff664a205dc27 | dineshkumarkummara/my-basic-programs-in-java-and-python | /folders/python/instagram/45while_else.py | 295 | 4.53125 | 5 | #In Python, you can add the "else" block after a "while" loop.
# It will be executed after the loop is over.
x=3
while x<=5: #change the condition to check different outputs
print(x)
x+=1
#if the condition is false then else statement will be executed
else:
print("done")
| true |
131fea2d621c3a61c365d6794793cd4ba30ba951 | dineshkumarkummara/my-basic-programs-in-java-and-python | /folders/python/others/fun2.py | 605 | 4.4375 | 4 | def fun(*args):
for i in args:
print(i)
args=1,2,3,4,5,6
fun(*args)
#or
print("----------")
fun(7,8,9)
#You can't provide a default for args, for example func(*args=[1,2,3]) will raise a syntax error (won't evencompile).
# You can't provide these by name when calling the function, for example func(*args=[1,2,3]) will raise aTypeError.
# But if you already have your arguments in an array (or any other Iterable), you can invoke your function like this:func(*my_stuff).
# These arguments (*args) can be accessed by index, for example args[0] will return the first argument
print(args[3])
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.