blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
637c98c17ed65d72a4538fb19958ed10198a017b | onkcharkupalli1051/pyprograms | /ds_nptel/test 2/5.py | 676 | 4.28125 | 4 | """
A positive integer n is a sum of three squares if n = i2 + j2 + k2 for integers i,j,k such that i ≥ 1, j ≥ 1 and k ≥ 1. For instance, 29 is a sum of three squares because 10 = 22 + 32 + 42, and so is 6 (12 + 12 + 22). On the other hand, 16 and 20 are not sums of three squares.
Write a Python function sumof3squares(n) that takes a positive integer argument and returns True if the integer is a sum of three squares, and False otherwise.
"""
def sumof3squares(n):
for i in range(n):
for j in range(n):
for k in range(n):
if(n == i**2 + j**2 + k**2):
return True
return False
print(sumof3squares(16)) | true |
812dde47bf82dde83275c5a6e5c445ef6a0171ab | onkcharkupalli1051/pyprograms | /ds_nptel/NPTEL_DATA_STRUCTURES_TEST_1/ques4.py | 580 | 4.34375 | 4 | """
Question 4
A list is a non-decreasing if each element is at least as big as the preceding one. For instance [], [7], [8,8,11] and [3,19,44,44,63,89] are non-decreasing, while [3,18,4] and [23,14,3,14,3,23] are not. Here is a recursive function to check if a list is non-decreasing. You have to fill in the missing argument for the recursive call.
def nondecreasing(l):
if l==[] or len(l) == 1:
return(True)
else:
return(...)
Open up the code submission box below and fill in the missing argument for the recursive call.
"""
l[0] <= l[1] and nondecreasing(l[1:]) | true |
62edb5acaf0f4806e84966e822083a39cdf66805 | YhHoo/Python-Tutorials | /enumerate.py | 477 | 4.125 | 4 | '''
THIS IS enumerate examples****
it allows us to loop over something and have an automatic counter
'''
c = ['banana', 'apple', 'pear', 'orange']
for index, item in enumerate(c, 2): # '2' tell the enumerate to start counting from 2
print(index, item)
'''
[CONSOLE]
2 banana
3 apple
4 pear
5 orange
'''
c = ['banana', 'apple', 'pear', 'orange']
for index, item in enumerate(c):
print(index, '+', item)
'''
[CONSOLE]
0 + banana
1 + apple
2 + pear
3 + orange
''' | true |
1dd0e6d8e73c6dbd174227baf893ad6695f56dab | thisguyisbarry/Uni-Programming | /Year 2/Python/labtest2.py | 2,048 | 4.5 | 4 | import math
class Vector3D(object):
"""Vector with 3 coordinates"""
def __init__(self, x, y, z):
"""Takes in coordinates for a 3d vector"""
self.x = x
self.y = y
self.z = z
self.magnitude = 0
def __add__(self, v2):
"""Adds two 3D vectors
(x+a, y+b, z+c)
where x,y,z are from the first vector
and a,b,c are from the second vector"""
return self.x + v2.x, self.y + v2.y, self.z + v2.z
def __sub__(self, v2):
"""Subtracts two 3D vectors
(x-a, y-b, z-c)
where x,y,z are from the first vector
and a,b,c are from the second vector"""
return self.x - v2.x, self.y - v2.y, self.z - v2.z
def __mul__(self, n):
"""Multiplies the a 3d vector
either by an integer in the form
(x*n, y*n, z*n) or in the form
(x*a + y*b + z*c) where
x,y,z are from the first vector
and a,b,c are from the second vector
to get the dot product"""
# Check which type of multiplication needs to be done
if type(n) == int:
return self.x * n, self.y * n, self.z * n
else:
return self.x * n.x + self.y * n.y + self.z * n.z
def magnitude(self):
"""Finds the magnitude of a 3d vector
The magnitude is gotten by:
sqrt(x^2+y^2+z^2)"""
self.magnitude = math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
def __str__(self):
return "( {}, {}, {} )".format(self.x, self.y, self.z)
v1 = Vector3D(1, 2, 3)
v2 = Vector3D(5, 5, 5)
print("Printing v1")
print("v1 = ", v1)
print("Printing v2")
print("v2 = ", v2)
v3 = v1 + v2
print("Printing addition")
print("v1 + v2 = ", v3)
v4 = v1 - v2
print("Printing subtraction")
print("v1 - v2 = ", v4)
v5 = v1 * v2
print("Printing dot product")
print("v1 * v2 = ", v5)
print("Printing integer multiplication")
v6 = v1 * 2
print("v1 * 2 = ", v6)
# Not sure why this isn't working
# print("v1 magnitude is ", v1.magnitude())
| true |
30e68edadbaba888f4e0c6b4f04e074a43051738 | The-Blue-Wizard/Miscellany | /easter.py | 627 | 4.40625 | 4 | #!/bin/python
# Python program to calculate Easter date for a given year.
# This program was translated from an *ancient* BASIC program
# taken from a certain black papercover book course on BASIC
# programming whose title totally escapes me, as that was
# during my high school time. Obviously placed in public
# domain, and don't ask me how it works! :-)
print
i = int(raw_input('Year: '))
v = i % 19
w = i % 4
t = i % 7
c = 19*v+24
s = c % 30
c = 2*w+4*t+6*s+5
z = c % 7
d = 22+s+z
if d <= 31:
print 'The date of Easter is March %d, %d' % (d,i)
else:
d -= 31
print 'The date of Easter is April %d, %d' % (d,i)
| true |
132c7a205f2f0d2926e539c172223fb505a0f2c1 | L-ByDo/OneDayOneAlgo | /Algorithms/Searching_Algorithms/Binary Search/SquareOfNumber.py | 1,338 | 4.25 | 4 | #Find the square of a given number in a sorted array. If present, Return Yes with the index of element's index
#Else return No
#Program using Recursive Binary Search
#Returns True for Yes and False for No
def BinarySearch(arr, left, right, NumSquare):
#check for preventing infinite recursive loop
if right >= left :
mid = left + (right-left) // 2
# If element is present at the middle itself
if arr[mid] == NumSquare:
return True
# If element is smaller than mid, then it
# can only be present in left subarray
elif arr[mid] > NumSquare:
return BinarySearch(arr, left, mid-1, NumSquare)
# Else the element can only be present
# in right subarray
else:
return BinarySearch(arr, mid+1, right, NumSquare)
#Element not present in array
else:
return False
#input a sorted array. A sorted array is either of ascending order or descending order
arr = [int(x) for x in input().split()]
left = 0 #left index
Num = int(input()) #Number whose square is to be searched for
NumSquare = Num*Num
#Function CAll
result = BinarySearch(arr, 0, len(arr)-1, NumSquare)
#check for True
if result:
print("Yes! " + "The index of square of {} is {}".format(Num, arr.index(Num*Num)))
#For false
else:
print("No") | true |
94e17585ee5d0fc214dea1cbc886bd8fa33af30e | EmreCenk/Breaking_Polygons | /Mathematical_Functions/coordinates.py | 2,277 | 4.5 | 4 |
from math import cos,sin,radians,degrees,sqrt,atan2
def cartesian(r,theta,tuple_new_origin=(0,0)):
"""Converts height given polar coordinate r,theta into height coordinate on the cartesian plane (x,y). We use polar
coordinates to make the rotation mechanics easier. This function also converts theta into radians."""
#theta=0.0174533*theta #1 degrees = 0.0174533 radians
theta=radians(theta)
# we need to modify our calculation for the new origin as well
x=r*cos(theta)+tuple_new_origin[0] #finding x
y=r*sin(theta)+tuple_new_origin[1] #finding y
return (x,y)
def polar(x,y,tuple_new_origin=(0,0)):
"""Is the inverse function of 'cartesian'. Converts height given cartesian coordinate; x,y into height polar coordinate in
the form (r, theta). """
w=(x-tuple_new_origin[0]) #width of mini triangle
h=(y-tuple_new_origin[0]) #height of mini triangle
r=sqrt((w**2)+(h**2)) # from the pythagorean theorem
theta=atan2(h,w)
return r,degrees(theta)
#I was going to use the following function, but it increases the computational complexity of the game too much
# def elipse_to_polygon(centerx, centery, height, width, accuracy=5):
# print("input",centerx, centery, height, width)
# """This function converts an elıpse to """
# coordinates=[]
# coordinates2=[]
# y_dif= 2 * height / accuracy
# for i in range(accuracy): #loop through y values on the elipse and calculate the corresponding x coordinate.
#
# y=y_dif*i+centery
# #using the equation of an elipse, we can solve for x:
#
# soloution_part_1=sqrt(
# (1- (((y-centery)/width)**2))*(height**2)
# )
# #The square root can be positive or negatve. That's why we will add both coordinates.
# coordinates.append([y, centerx + soloution_part_1])
# coordinates2.append([y, centerx - soloution_part_1])
#
# final=[]
# for i in coordinates:
# final.append(i)
# for i in range(1,len(coordinates2)):
# final.append(coordinates2[-i])
# return final
if __name__ == '__main__':
angle=123
r=12
new=cartesian(r,angle)
print(new)
neww=polar(new[0],new[1])
print(neww)
| true |
893fff12d545faa410309b4b2b087305e6ad99cc | AxiomDaniel/boneyard | /algorithms-and-data-structures/sorting_algorithms/insertion_sort.py | 1,596 | 4.59375 | 5 | #!/usr/bin/env python3
def insertion_sort(a_list):
""" Sorts a list of integers/floats using insertion sort
Complexity: O(N^2)
Args:
a_list (list[int/float]): List to be sorted
Returns:
None
"""
for k in range(1, len(a_list)):
for i in range(k - 1, -1, -1):
# print("k: " + str(k) + " i: " + str(i))
if a_list[i] > a_list[i + 1]:
a_list[i + 1], a_list[i] = a_list[i], a_list[i + 1]
else:
# print("break")
break
# print(a_list)
def main():
sample_list = [5, 2, 1, 3, 6, 4]
print("Unsorted List: " + str(sample_list))
insertion_sort(sample_list)
print("Sorted List: " + str(sample_list))
if __name__ == '__main__':
main()
'''
Reasoning for complexity:
Insertion sort imaginarily partitions the array into two parts: one unsorted and one sorted.
The sorted partition starts off with one element only, that is, the first element in the array.
With each successive iteration, insertion grows the sorted partition by one element.
In the process of growing the sorted partition by one element, it has to find an appropriate position for that element.
This requires the algorithm to compare that element with elements already within the sorted partition.
With N elements, insertion sort will have to run N-1 iterations to grow the sorted partition. At k-th iteration, it might have to do a maximum of k-1 comparisons. k is bounded by N, which is the number of elements in the list
Therefore, insertion sort can be bounded by O(N^2)
'''
| true |
deb7f660c0f607492dbbcd59c71936876c893b35 | Erik-D-Mueller/Python-Neural-Network-Playground | /Version1point0/initial.py | 1,363 | 4.3125 | 4 | # 02-12-2020
# following along to a video showing how to implement simple neural network
# this is a perceptron, meaning it has only one layer
import numpy as np
# sigmoid function is used to normalize, negatives values return a value below 1/2 and approaching zero, positive values return above 1/2 and approaching 1
def sigmoid(x):
return 1 / (1 + np.exp(-x))
#
def sigmoid_derivative(x):
return x * (1 - x)
# training input data
training_input_data = np.array([
[0,1,0],
[1,1,1],
[1,0,1],
[0,1,0]])
training_output_data = np.array([[0, 1, 1, 0]]).T
#creates a 1x3 matrix with values between -1 and 1
synaptic_weights = 2 * np.random.random((3, 1)) - 1
print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
print('Initial Random starting synaptic weights: ')
print(synaptic_weights)
input_layer = training_input_data
for iteration in range(200):
outputs = sigmoid(np.dot(training_input_data,synaptic_weights))
error = training_output_data - outputs
adjustments = error + sigmoid_derivative(outputs)
synaptic_weights += np.dot(input_layer.T, adjustments)
print('Synaptic weights after training')
print(synaptic_weights)
print('Final Synaptic Weights')
print(synaptic_weights)
print('Outputs after training')
print(outputs)
| true |
1326800eed0a49d19b8e959f7d58e2e65195963a | ImtiazMalek/PythonTasks | /input.py | 215 | 4.375 | 4 | name=input("Enter your name: ")#user will inter name and comment
age=input("Enter your age: ")#and we are saving it under various variables
print("Hello "+name+", you are "+age+" years old")#it'll print the result | true |
45e52f554eee3a9c1153ab1fe29bedac254891a3 | sitati-elsis/teaching-python-demo | /inheritance.py | 760 | 4.1875 | 4 | class Parent():
def __init__(self,last_name,eye_color):
print ("Parent constructor called")
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print "%s %s" %(self.last_name,self.eye_color)
billy_cyrus = Parent("Cyrus","blue")
billy_cyrus.show_info()
class Child(Parent):
def __init__(self,last_name,eye_color,number_of_toys):
print "Child constructor called"
""" To initiliaze the values we are inheriting from class parent
we should reuse class parent's __init__method """
Parent.__init__(self,last_name,eye_color)
# Initialize number of toys
self.number_of_toys = number_of_toys
miley_cyrus = Child("Cyrus","blue",5)
miley_cyrus.show_info()
# print miley_cyrus.last_name
# print miley_cyrus.number_of_toys | true |
2245c07a64384e77a44b9540fcd551f245492289 | ShimaSama/Python | /email.py | 344 | 4.3125 | 4 | #program to know if the email format is correct or not
email=input("Introduce an email address: ")
count=email.count('@')
count2=email.count('.')
end=email.rfind('@') #final
start=email.find("@")
if(count!=1 or count2<1 or end==(len(email)-1) or start==0):
print("Wrong email address")
else:
print("correct email address") | true |
5fc28ab298c14b482825b23bb6320ca32e50b514 | sudiptasharif/python | /python_crash_course/chapter9/fraction.py | 1,763 | 4.4375 | 4 | class Fraction(object):
"""
A number represented as a fraction
"""
def __init__(self, num, denom):
"""
:param num: integer numerator
:param denom: integer denominator
"""
assert type(num) == int and type(denom) == int, "ints not used"
self.num = num
self.denom = denom
def __str__(self):
"""
:return: Returns a string representation of self
"""
return str(self.num) + "/" + str(self.denom)
def __add__(self, other):
"""
Adds two fractions
:param other: other fraction
:return: a new fraction representing the addition
"""
top = self.num * other.denom + self.denom * other.num
bottom = self.denom * other.denom
return Fraction(top, bottom)
def __sub__(self, other):
"""
Subtracts two fractions
:param other: other fraction
:return: a new fraction representing the subtraction
"""
top = self.num * other.denom - self.denom * other.num
bottom = self.denom * other.denom
return Fraction(top, bottom)
def __float__(self):
"""
returns the float value of the fraction
:return: float value of fraction
"""
return self.num / self.denom
def __mul__(self, other):
"""
multiplication of two fractions
:param other: a Fraction object
:return: a fraction that represents the multiplication
"""
top = self.num * other.num
bottom = self.denom * other.denom
return Fraction(top, bottom)
a = Fraction(1, 4)
print(a)
b = Fraction(3, 4)
print(b)
c = a + b
print(c)
d = a - b
print(d)
print(float(c))
print(float(d))
| true |
253e80b1f9ae499d49eb0d79c34b821e0c8dfb6d | waditya/HackerRank_Linked_List | /09_Merge_Sorted_LinkList.py | 2,952 | 4.28125 | 4 | """
Merge two linked lists
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method.
"""
def MergeLists(headA, headB):
#Flag
flag = 1
#Counter
counter = 0
#NodeCounters
counterA = True
counterB = True
##Pointer to the Heads
nodeA = headA
nodeB = headB
if((headA != None) and (headB == None)):
return(None)
elif((headA == None) and (headB != None)):
return(headB)
elif((headA != None) and (headB == None)):
return(headA)
else:
ctr = 1
principal_node = Node(None,None);
node = principal_node
currNodeA = nodeA
currNodeB = nodeB
while(counterA or counterB):
if((currNodeA.data < currNodeB.data) and (counterA)):
if(ctr == 1):
temp = Node(currNodeA.data, None)
principal_node.next = temp
node = node.next
ctr = ctr + 1
if(currNodeA.next != None):
currNodeA = currNodeA.next
else:
counterA = False
else:
temp = Node(currNodeA.data, None)
node.next = temp
node = node.next
if(currNodeA.next != None):
currNodeA = currNodeA.next
else:
counterA = False
else:
if(ctr == 1):
temp = Node(currNodeB.data, None)
principal_node.next = temp
node = node.next
ctr = ctr + 1
if(currNodeB.next != None):
currNodeB= currNodeB.next
else:
counterB = False
currNodeB.data = currNodeA.data + 1
else:
temp = Node(currNodeB.data, None)
node.next = temp
node = node.next
if(currNodeB.next != None):
currNodeB= currNodeB.next
else:
counterB = False
currNodeB.data = currNodeA.data + 1
return(principal_node.next)
| true |
6647f2a03e8d08ca8807c5dad2c2a0694d264713 | SethGoss/notes1 | /notes1.py | 363 | 4.28125 | 4 | # this is a comment, use them vary often
print(4 + 6) # addition
print(-4 -5) #subtraction
print(6 * 3) #multiplication
print(8 / 3) #division
print(3 ** 3) #exponents - 3 to the 3rd power
print(10 % 3) #modulo gives the remainder
print(15%5)
print(9%4)
# to make variable, think of a name
name = input("What is your name?: ")
print("hello "+ name) | true |
c8af7a794f8074f9c803cd7ebb61ae00b509f475 | Frigus27/Structure-Iced | /iced/game_object.py | 2,130 | 4.1875 | 4 | """
game_object.py
--------------
The implement of the objects in the game.
The game object is the minimum unit to define a interactive
object in a game, e.g. a block, a road, a character, etc.
In Structure Iced, you can easily define an object by
simply inherit the class game_object. A game object
requires the arguments in the following text:
1. An image (which will be showed when game begins)
2. A creation function (To note what the function should do
when it is being created)
3. A loop function (To note what the function should do
every game loop)
4. A destroying function (The one when it is being
destroyed)
For more, see the documentation.
"""
import pygame
class Object():
"""The game object"""
class _InstanceVariables():
def __init__(self):
self.pos_x = 0
self.pos_y = 0
def __init__(self):
self.image = 0
self.image_surface = pygame.surface.Surface((0, 0))
self.InstanceVariables = self._InstanceVariables()
def set_image_by_filename(self, new_image_filename: str):
"""To set the image by filename and path"""
self.image = pygame.image.load(new_image_filename)
self.image_surface = self.image.convert()
def set_image_by_surface(self, new_image_surface: pygame.surface.Surface):
"""To set the image by the surface you've created"""
self.image = 0
self.image_surface = new_image_surface
def on_create(self):
"""the function executes when created"""
def loop(self):
"""the function executes every game loop"""
def on_destroy(self):
"""the function executes when destroyed"""
def update_instance_pos(self, new_pos_x: int, new_pos_y: int):
"""update the position of the instance of the object"""
self.InstanceVariables.pos_x = new_pos_x
self.InstanceVariables.pos_y = new_pos_y
def get_instance_pos(self):
"""get the position of the instance of the object"""
return self.InstanceVariables.pos_x, self.InstanceVariables.pos_y
| true |
c28d9ede48b5c683d129d8f18c93f823fe72be38 | artsyanka/October2016Test1 | /centralLimitTheorem-Outcomes-Lesson16.py | 1,088 | 4.125 | 4 | #Write a function flip that simulates flipping n fair coins.
#It should return a list representing the result of each flip as a 1 or 0
#To generate randomness, you can use the function random.random() to get
#a number between 0 or 1. Checking if it's less than 0.5 can help your
#transform it to be 0 or 1
import random
from math import sqrt
from plotting import *
def mean(data):
#print(float(sum(data))/len(data))
return float(sum(data))/len(data)
def variance(data):
mu=mean(data)
return sum([(x-mu)**2 for x in data])/len(data)
def stddev(data):
return sqrt(variance(data))
def flip(N):
#Insert your code here
flipsList=[]
for i in range(N):
if random.random() < 0.5:
flipsList.append(0)
else:
flipsList.append(1)
return flipsList
def sample(N):
#Insert your code here
meansList=[]
for i in range(N):
meansList.append(mean(flip(N)))
return meansList
N=1000
outcomes=sample(N)
histplot(outcomes,nbins=30)
print(mean(outcomes))
print(stddev(outcomes))
| true |
b579e7e4c50ed64154b48830b5d7e6b22c21dd64 | Rogerd97/mintic_class_examples | /P27/13-05-2021/ATM.py | 934 | 4.125 | 4 | # https://www.codechef.com/problems/HS08TEST
# Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction
# if X is a multiple of 5, and Pooja's account balance has enough cash to perform the withdrawal transaction
# (including bank charges). For each successful withdrawal the bank charges 0.50 $US.
# Calculate Pooja's account balance after an attempted transaction.
# Input:
# 30 120.00
# Output:
# 89.50
# Input:
# 42 120.00
# Output:
# 120.00
# Input:
# 300 120.00
# Output:
# 120.00
withdraw = float(input("Insert the withdraw: "))
balance = float(input("Insert the account's balance: "))
if withdraw % 5 != 0:
print("You should use numbers divided by 5")
elif balance > withdraw + 0.5:
new_balance = balance - (withdraw + 0.5)
print(f"Your new account balance is {new_balance}")
else:
print(f"You do not have enough money, your account balance is {balance}")
| true |
5ff84a677d4a9595a5d05185a7b0aecacea9e3dd | Rogerd97/mintic_class_examples | /P62/12-05-2021/if_else_2.py | 1,325 | 4.34375 | 4 | # Write a program that asks for the user for the month number
# your script should convert the number to the month's name and prints it
# Solution 1
# month_number = input("Insert a month number: ")
# month_number = int(month_number)
# months = {"1": "enero", "2": "febrero", "3": "marzo"}
# if month_number < 1 or month_number > 12:
# print("you inserted a not valid number")
# else:
# month = months[str(month_number)]
# print(month)
# # Solution 2
# month_number = input("Insert a month number: ")
# month_number = int(month_number)
# months = ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre",
# "octubre", "noviembre", "diciembre"]
# # 0
# # 1
# if month_number < 1 or month_number > 12:
# print("you inserted a not valid number")
# else:
# month_number = month_number - 1
# print(months[month_number])
# # Solution 3
month_number = input("Insert a month number: ")
month_number = int(month_number)
months = ["", "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre",
"octubre", "noviembre", "diciembre"]
# 1
# False and False
# False
# -1
# True and False
# False
if month_number < 1 or month_number > 12:
print("you inserted a not valid number")
else:
print(months[month_number])
| true |
3b41d3051d166653385c7072bab3f1fc7bb3e462 | Rogerd97/mintic_class_examples | /P62/26-05-2021/exercise_1.py | 540 | 4.46875 | 4 | # Write a Python script to display the various Date Time formats
# a) Current date and time
# b) Current year
# c) Month of year
# d) Week number of the year
# e) Weekday of the week
# f) Day of year
# g) Day of the month
# h) Day of week
import datetime
def print_dates():
date = datetime.datetime.now()
print(date)
print(date.year)
print(date.month)
print(date.strftime("%b"))
print(date.strftime("%U"))
print(date.strftime("%j"))
print(date.strftime("%d"))
print(date.strftime("%A"))
print_dates()
| true |
9d386d7dece46d9e947ae02c509e0ff10fa08be5 | levi-fivecoat/Learn | /datatypes/strings.py | 473 | 4.28125 | 4 | my_str = "This is a string."
my_str_2 = "I am a strings. I can contain numbers 12345"
my_str_3 = "1390840938095"
username = "levi : "
# YOU CAN ADD STRINGS
my_str = username + my_str
my_str_2 = username + my_str_2
# YOU CAN SEE WHAT KIND OF DATA TYPE BY USING TYPE()
print(type(my_str))
# UPPERCASES STRING
my_str = my_str.upper()
# CAPITALIZES FIRST LETTER
print(my_str.capitalize())
# YOU CAN PRINT BY USING PRINT()
print(my_str)
print(my_str_2)
print(my_str_3)
| true |
aa878f2bfc544a6ffdb642d6279faba0addc552c | Juxhen/Data14Python | /Introduction/hello_variables.py | 1,333 | 4.25 | 4 | # a = 5
# b = 2
# c = "Hello!"
# d = 0.25
# e = True
# f = [1,2,3]
# g = (1,2,3)
# h = {1,2,3}
#
# print(a)
# print(b)
# print(c)
#
# # How to find the type of variables
# print(type(a))
# print(type(b))
# print(type(c))
# print(type(d))
# print(type(e))
# print(type(f))
# print(type(g))
# print(type(h))
# CTRL + / To comment out a block of code
# print("What is your name?")
# name = input()
# print(name)
# Use input to collect name, age and DOB from user & display them
#
# print("What is your name?")
# name = input()
# nameType = type(name)
# print("What is your age?")
# age = input()
# ageType = type(age)
# print("What is your d.o.b, format DD/MM/YY")
# dob = input()
# dobType = type(dob)
# print(name, age, dob)
# print(dobType)
#
#-----------------------------------------------------------------------
#
# name = input("What is your name?")
# age = int(input("What is your age")) #casting change one data type to another
# age = int(input("Siblings"))
# decimal = float(print("Favourite decimal"))
# animal = input("what is your fav animal")
#
# print(f"Hi {name} you're {age} and you have {siblings} your fav dec is {decimal} and your fav animal is {animal}")
#-------boolean ---------------
hw = "Hello World!"
hw.isalpha()
print(hw.islower())
print(hw.isupper())
print(hw.startswith("H"))
print(hw.endswith("!")) | true |
c4b2d02cb02ff875450fc56f1b839cab49b85af6 | SDBranka/A_Basic_PyGame_Program | /hello_game.py | 718 | 4.15625 | 4 | #Import and initialize Pygame library
import pygame
pygame.init()
#set up your display window
screen = pygame.display.set_mode((500,500))
#set up a game loop
running = True
while running:
# did user click the window close button?
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# fill the screen with white
white_for_screenfill = (255,255,255)
screen.fill(white_for_screenfill)
# draw a solid blue circle
blue_for_circle = (0,0,255)
location_of_circle_center = (250,250)
pygame.draw.circle(screen, blue_for_circle, location_of_circle_center, 75)
#flip the display
pygame.display.flip()
#exit pygame
pygame.quit() | true |
fc89779a2cf480512ac48b7a21c5d344a30e56d6 | Seanie96/ProjectEuler | /python/src/Problem_4.py | 1,154 | 4.34375 | 4 | """ solution to problem 4 """
NUM = 998001.0
def main():
""" main function """
starting_num = NUM
while starting_num > 0.0:
num = int(starting_num)
if palindrome(num):
print "palindrome: " + str(num)
if two_factors(num):
print "largest number: " + str(num)
return 0
starting_num = starting_num - 1.0
return 0
def palindrome(num):
""" checkes whether the passed number is a palindrome """
num_str = str(num)
index = 0
length = len(num_str)
while index <= (length / 2):
if num_str[index] != num_str[length - 1 - index]:
return False
index = index + 1
return True
def two_factors(num_1):
""" Function that discoveres whether the passed number can be
broken down into 2 three digit number factors. """
num_1 = float(num_1)
index = 100.0
while index < num_1 and index < 1000.0:
num_2 = num_1 / index
if num_2 % 1.0 == 0 and num_2 >= 100.0 and num_2 < 1000.0:
return True
index = index + 1.0
return False
if __name__ == "__main__":
main()
| true |
95eb8f40f40eed4eebfa1e13dcb0117b80cb6832 | mamare-matc/Intro_to_pyhton2021 | /week3_strings.py | 1,347 | 4.5 | 4 | #!/usr/bin/python3
#week 3 srting formating assignment
varRed = "Red"
varGreen = "Green"
varBlue = "Blue"
varName = "Timmy"
varLoot = 10.4516295
# 1 print a formatted version of varName
print(f"'Hello {varName}")
# 2 print multiple strings connecting with hyphon
print(f"'{varRed}-{varGreen}-{varBlue}'")
# 3 print strings concatnating with variable
print(f"'Is this {varGreen} or {varBlue}?'")
# 4 print string concatnating with varName
print(f"'My name is {varName}'")
# 5 print varRed by adding ++
print(f"'[++{varRed}++]'")
# 6 print varGreen adding == at the end
print(f"'[{varGreen.lower()}==]'")
# 7 print **** and varBlue
print(f"'[****{varBlue.lower()}]'")
# 8 print varBlue multiple time
print(f"'{varBlue}'"*10)
# 9 print varLoot with single qoute
print(f"'{varLoot}'")
# 10 print varLoot using indexing to get the first three numbers
print(round(varLoot, 1))
# 11 print string concat with indexing varLoot
print(f"I have $" + str(round(varLoot, 2)))
# 12 print a formatted string that contais variables
print(f"'[$$${varRed}$$$$][$${varGreen}$$$][$$${varBlue}$$$]'")
# 13 print reversed string for varRed and varBlue
print(f"'[ {varRed[::-1]} ][ {varGreen} ][ {varBlue[::-1]} ]'")
# 14 print string concattnating with variables
print(f"'First Color:[{varRed}]Second Color:[{varGreen}]Third Color:[{varBlue}]'")
| true |
cd21e893b48d106b791d822b6fded66542924661 | a12590/LeetCode_My | /100-149/link_preoder(stack)_flatten.py | 1,798 | 4.1875 | 4 | #!/usr/bin/python
# _*_ coding: utf-8 _*_
"""
非递归先序遍历,注意rtype void要求
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
# pointer
pointer = TreeNode(None)
if root is None:
return
stack = []
stack.append(root)
while stack:
top = stack.pop()
# 这里先遍历right是因为stack,使得出栈left先
if top.right:
stack.append(top.right)
if top.left:
stack.append(top.left)
pointer.right = top
pointer.left = None
pointer = top
# 全局dummy
# self.pointer = None
# def traverse(root):
# if not root:return
# # 后序遍历
# traverse(root.right)
# traverse(root.left)
# root.left = self.pointer
# root.left = None
# self.pointer = root
# traverse(root)
"""
public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public TreeNode parentNode = null;
public void flatten(TreeNode root) {
if (root == null){
return;
}
if (parentNode != null){
parentNode.left = null;
parentNode.right = root;
}
# 后移不是next,而是后赋值前
parentNode = root;
flatten(root.left);
flatten(root.right);
}
}
"""
| true |
9f12786f688abb908c333b2249be6fb18bdcd1d6 | keyurbsq/Consultadd | /Additional Task/ex6.py | 258 | 4.4375 | 4 | #Write a program in Python to iterate through the string “hello my name is abcde” and print the
#string which is having an even length.
k = 'hello my name is abcde'
p = k.split(" ")
print(p)
for i in p:
if len(i) % 2 == 0:
print(i)
| true |
d63d46c893052f76ea6f0906dd7166af5793a27b | keyurbsq/Consultadd | /Additional Task/ex4.py | 245 | 4.3125 | 4 | #Write a program in Python to iterate through the list of numbers in the range of 1,100 and print
#the number which is divisible by 3 and is a multiple of 2.
a = range(1, 101)
for i in a:
if i%3 == 0 and i%2==0:
print(i)
| true |
da83ffdd1873d70f4f5321c09c0a3ff1fb1ffc85 | r0meroh/CSE_CLUB_cpp_to_python_workshop | /people_main.py | 1,580 | 4.25 | 4 | from person import *
from worker import *
import functions as fun
def main():
# create list of both types of objects
people = []
workers = []
# prompt user
answer = input("adding a Person, worker? Or type exit to stop\n")
answer = answer.upper()
while answer != 'EXIT':
# if anwer is person, create a person object and append it to list
if answer == 'PERSON':
name = input('Enter name of person:\n')
age = input('Enter age of person:\n')
name = person(name, age)
people.append(name)
print('the following person was added:' )
fun.display_person(name)
elif answer == 'WORKER':
name = input('Enter name of worker\n:')
age = input('Enter age of worker: \n')
occupation = input('Enter occupation of worker: ')
name = worker(name,age,occupation)
workers.append(name)
print('the following worker was added: ')
fun.display_worker(name)
else:
print('invalid choice, please try again...\n')
answer = input("adding a Person, worker? Or type exit to stop\n")
answer = answer.upper()
# outside of loop
return people, workers
def print_lists(list):
for item in list:
print(item)
if __name__ == '__main__':
list_of_people, list_of_workers = main()
print('The following people were added:')
print_lists(list_of_people)
print('The following workers were added: ')
print_lists(list_of_workers)
| true |
e0058dfbb608836b24d131f6c92cabc1c551ad68 | rjraiyani/Repository2 | /larger_number.py | 272 | 4.125 | 4 | number1 = int(input('Please enter a number ' ))
number2 = int(input('Please enter another number ' ))
if number1 > number2:
print('The first number is larger.')
elif number1 < number2:
print('The second number is larger.')
else:
print('The two numbers are equal.' )
| true |
edd5cf21f14675cf6a4af3d6f20a082bd48ab1ae | davidlkang/foundations_code | /shopping_list.py | 1,423 | 4.125 | 4 | def show_help():
print("""
Type 'HELP' for this help.
Type 'CLEAR' to clear your list.
Type 'DEL X' where 'X' is the number of the element you want to remove.
Type 'SHOW' to display your list.
Type 'DONE' to stop adding items.
""")
def add_to_list(user_input):
shopping_list.append(user_input.lower())
print("Great! Your item was added. There are", len(shopping_list), "items in your list.")
def clear_list():
shopping_list.clear()
print("Success. Your list was cleared.")
def show_list():
print("You have the following items in your shopping list: ")
for element in shopping_list:
print(element)
def delete_item_from_list(index):
index = int(index) - 1
print("You succesfully removed {}.".format(shopping_list.pop(index)))
shopping_list = []
show_help()
while True:
user_input = input("> ")
if user_input == "HELP":
show_help()
elif user_input == "CLEAR":
clear_list()
elif "DEL " in user_input:
delete_item_from_list(user_input[4])
elif user_input == "SHOW":
show_list()
elif user_input == "DONE":
show_list()
break
elif user_input.lower() in shopping_list:
print("You already have {} in your shopping list. Do you still want to add it? ".format(user_input))
if input("(Y/N) ").lower() == "y":
add_to_list(user_input)
else:
add_to_list(user_input)
| true |
7ca179a45c2136eb638a635b700909482a5376fb | davidlkang/foundations_code | /login_app.py | 1,277 | 4.25 | 4 | users = {
"user1" : "password1",
"user2" : "password2",
"user3" : "password3"}
def accept_login(users, username, password):
if username in users:
if password == users[username]:
return True
return False
def login():
while True:
if input("Do you want to sign in?\n(Y/n) ").lower() == "y":
username = input("What is your username? ")
password = input("And your password? ")
if accept_login(users, username, password):
print("login successful!")
break
else:
print("login failed...")
else:
if input("Do you want to sign up?\n(Y/n) ").lower() == "y":
username_input = input("Please enter your username.\n> ")
while username_input in users:
username_input = input("Please use another username!\n> ")
password_input = input("Great! That username works. Now enter your password!\n> ")
users.update({username_input: password_input})
print("Your username: {} was added.".format(username_input))
else:
print("Goodbye!")
break
if __name__ == "__main__":
login()
| true |
f02e6f8d9a81b072ab3582f1469a62cc25b0905b | takaakit/design-pattern-examples-in-python | /structural_patterns/flyweight/main.py | 901 | 4.34375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from structural_patterns.flyweight.large_size_string import LargeSizeString
'''
Display a string consisting of large characters (0-9 digits only).
Large character objects are not created until they are needed.
And the created objects are reused.
Example Output
-----
Please enter digits (ex. 1212123): 123
####
###
###
###
###
###
#######
########
###
###
########
#
#
##########
########
###
###
########
###
# ###
########
'''
if __name__ == '__main__':
input_value = input('Please enter digits (ex. 1212123): ')
bs = LargeSizeString(string=input_value)
bs.display()
| true |
bad357e547032486bc7e5b04b7b92351148a2b19 | 21milushcalvin/grades | /Grades.py | 1,649 | 4.25 | 4 | #--By Calvin Milush, Tyler Milush
#--12 December, 2018
#--This program determines a test's letter grade, given a percentage score.
#--Calvin Milush
#-Initializes variables:
score = 0
scoreList = []
counter = 0
total = 0
#--Calvin Milush
#-Looped input for test scores:
while (score != -1):
score = input("Input test score (-1 to exit loop): ")
if (score != -1):
scoreList.append(score)
counter += 1
total += score
else:
break
#--Tyler Milush
#-Assigns a letter grade to each inputted score:
letterList = []
for i in range(counter):
if scoreList[i] >= 90:
letterList.append("A")
elif scoreList[i] >= 80 and scoreList[i] <= 89:
letterList.append("B")
elif scoreList[i] >= 70 and scoreList[i] <= 79:
letterList.append("C")
elif scoreList[i] >= 60 and scoreList[i] <= 69:
letterList.append("D")
elif scoreList[i] < 60:
letterList.append("F")
print
print "List of scores: ", scoreList
print "Grade of each score: ", letterList
print
#--Calvin Milush
#-Calculates and prints average (if greater than 0):
if (counter > 0):
avg = total / float(counter)
print "%0s %0.2f" % ("Average test score: ", avg)
else:
print "Error: Requires at least one test score."
#--Tyler Milush
#-Assigns a letter grade to the average:
avgLetter = ""
if(avg >= 90):
avgLetter = "A"
elif(avg >= 80 and avg <=89):
avgLetter = "B"
elif(avg >= 70 and avg <=79):
avgLetter = "C"
elif(avg >= 60 and avg <=69):
avgLetter = "D"
elif(avg < 60):
avgLetter = "F"
print "Letter grade of average: ", avgLetter
| true |
3f2832d039f29ef99679e8c51d42f5fb08b1dcff | pullannagari/python-training | /ProgramFlow/contrived.py | 425 | 4.21875 | 4 | # con·trived
# /kənˈtrīvd/
# Learn to pronounce
# adjective
# deliberately created rather than arising naturally or spontaneously.
# FOR ELSE, else is activated if all the iterations are complete/there is no break
numbers = [1, 45, 132, 161, 610]
for number in numbers:
if number % 8 == 0:
#reject the list
print("The numbers are unacceptable")
break
else:
print("The numbers are fine") | true |
7f9b228de7c12560ac80445c6b1a4d7543ddc263 | pullannagari/python-training | /Functions_Intro/banner.py | 1,312 | 4.15625 | 4 | # using default parameters,
# the argument becomes
# optional at the caller
def banner_text(text: str = " ", screen_width: int = 60) -> None:
"""
centers the text and prints with padded ** at the start and the end
:param text: string to be centered and printed
:param screen_width: width of the screen on which text should be printed
:raises ValueError: if the supplies string is longer than screen width
"""
if len(text) > screen_width - 4:
raise ValueError("screen {0} is larger than specified width {1}"
.format(text, screen_width))
if text == "*":
print("*" * screen_width)
else:
output_string = "**{0}**".format(text.center(screen_width - 4))
print(output_string)
width = 60
banner_text("*")
banner_text("lorem ipsum lorem ipsum")
banner_text("the quick brown fox jumped over lazy dog")
banner_text(screen_width=60) # key word arguments are used when both
# arguments are optional
banner_text("lorem ipsum lorem ipsum", width)
banner_text("the quick brown fox jumped over the lazy dog", width)
banner_text("*", width)
# result = banner_text("Nothing is returned", width) # returns None by default
# print(result)
# numbers = [ 1, 3, 5, 2, 6]
# print(numbers.sort()) # prints None since sort() returns None
| true |
232c40b3f47c42c8a33fcc5d7e4bde2719969080 | Hemalatah/Python-Basic-Coding | /Practice2.py | 2,684 | 4.125 | 4 | #CRAZY NUMBERS
def crazy_sum(numbers):
i = 0;
sum = 0;
while i < len(numbers):
product = numbers[i] * i;
sum += product;
i += 1;
return sum;
numbers = [2,3,5];
print crazy_sum(numbers);
#FIND THE NUMBER OF PERFECT SQUARES BELOW THIS NUMBER
def square_nums(max):
num = 1;
count = 0;
while num < max:
product = num * num;
if product < max:
count += 1;
num += 1;
return count;
print square_nums(25);
#PRINTS OUT THE ELEMENT IN THE ARRAY WHICH IS EITHER DIVISIBLE BY 3 OR 5
def crazy_nums(max):
i = 1;
list = [];
new_list = [];
while i < max:
list.append(i);
i += 1;
for i in list:
if i % 3 == 0 and i % 5 == 0:
continue;
elif i % 3 == 0 or i % 5 == 0:
new_list.append(i);
else:
continue;
return new_list;
print crazy_nums(3);
#PRINTS OUT THE SUM OF ANY THREE NUMBERS IN THE ARRAY WHICH IS EQUAL TO SEVEN
def lucky_sevens(numbers):
i = 0;
Bool = False;
if len(numbers) <= 1:
print("Length of numbers should be atleast 2");
while i + 2 < len(numbers):
sum = numbers[i] + numbers[i+1] + numbers[i+2];
if sum == 7:
Bool = True;
i += 1;
return Bool;
numbers = [1,2,3,4,5];
print(lucky_sevens(numbers));
numbers = [2,1,5,1,0];
print(lucky_sevens(numbers));
numbers = [0,-2,1,8];
print(lucky_sevens(numbers));
numbers = [7,7,7,7];
print(lucky_sevens(numbers));
numbers = [3,4,3,4];
print(lucky_sevens(numbers));
#FIND THE NUMBER OF ODD ELEMENTS IN THE ARRAY
def oddball_sum(numbers):
i = 0;
sum = 0;
while i < len(numbers):
if (numbers[i]%2) != 0:
sum = sum + numbers[i];
i += 1;
return sum;
numbers = [1,2,3,4,5];
print(oddball_sum(numbers));
numbers = [0,6,4,4];
print(oddball_sum(numbers));
numbers = [1,2,1];
print(oddball_sum(numbers));
#REMOVES VOWEL FROM THE STRING
def disemvowel(string):
vowel = 'aeiou';
i = 0;
while i < len(string):
if string[i] in vowel:
string = string.replace(string[i],"");
else:
i += 1;
return string;
string = "foobar";
print(disemvowel(string));
print(disemvowel("ruby"));
print(disemvowel("aeiou"));
#DASHERIZE THE NUMBER
def odd(intput):
if (intput%2):
return True;
else:
return False;
def dasherize_number(number):
s = str(number);
new_list = [];
i = 0;
while i < len(s):
if odd(int(s[i])):
if i == 0:
new_list.append(s[i]);
new_list.append('-');
elif i == len(s)-1:
new_list.append('-');
new_list.append(s[i]);
elif odd(int(s[i-1])):
new_list.append(s[i]);
new_list.append('-');
else:
new_list.append('-');
new_list.append(s[i]);
new_list.append('-');
else:
new_list.append(s[i]);
i += 1;
new_list = "".join(new_list);
return new_list;
print dasherize_number(3243);
| true |
1ba2daae4ad916e06b92b9277ca113d64bbd3a84 | miss-faerie/Python_the_hard_way | /ex3.py | 507 | 4.25 | 4 | hens = int(25+30/6)
roosters = int(100-25*3%4)
eggs = int(3+2+1-5+4%2-1/4+6)
print()
print("I will now count my chickens:")
print("Hens",hens)
print("Roosters",roosters)
print("Now I will count the eggs:",eggs)
print()
print("Is it true that 3+2 < 5-7 ?",(3+2)<(5-7))
print("What is 3+2 ?",3+2)
print("What is 5-7 ?",5-7)
print("Oh that's why it's False.")
print()
print("How about some more.")
print("Is it greater?",5 > -2)
print("Is it greater or equal?",5 >= -2)
print("Is it less or equal?",5 <= -2) | true |
16e176e7b1f43c5c78feea53472ad5cdf2949955 | tsabz/ITS_320 | /Option #2: Repetition Control Structure - Five Floating Point Numbers.py | 1,321 | 4.25 | 4 | values_dict = {
'Module 1': 0,
'Module 2': 0,
'Module 3': 0,
'Module 4': 0,
'Module 5': 0,
}
# first we want to have the student enter grades into set
def Enter_grades():
print('Please enter your grade for Module 1:')
values_dict['Module 1'] = int(float(input()))
print('Please enter your grade for Module 2:')
values_dict['Module 2'] = int(float(input()))
print('Please enter your grade for Module 3:')
values_dict['Module 3'] = int(float(input()))
print('Please enter your grade for Module 4:')
values_dict['Module 4'] = int(float(input()))
print('Please enter your grade for Module 5:')
values_dict['Module 5'] = int(float(input()))
def Average():
avg = 0
for value in values_dict.values():
avg += value
avg = avg / len(values_dict)
print('Your average score is:')
print(float(avg))
def min_max():
# min numbers
minimum = min(values_dict.values())
print('Your lowest score was ' +
min(values_dict) + ':')
print(float(minimum))
# max numbers
maximum = max(values_dict.values())
print('Your highest score was ' + max(values_dict) + ':')
print(float(maximum))
def main():
Enter_grades()
print(values_dict)
Average()
min_max()
if __name__ == "__main__":
main()
| true |
f13d14609b6c98949dc2e70a7de24f4a5e443ca0 | taeheechoi/coding-practice | /FF_mergeTwoSortedLists.py | 1,061 | 4.1875 | 4 | # https://leetcode.com/problems/merge-two-sorted-lists/
# Input: list1 = [1,2,4], list2 = [1,3,4]
# Output: [1,1,2,3,4,4]
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
#create dummy node so we can compare the first node in each list
dummy = ListNode()
#initialise current node pointer
curr = dummy
#while the lists are valid
while list1 and list2:
#if the value is list1 is less than the value in list2
if list1.val < list2.val:
#the next node in the list will be the list1 node
curr.next = list1
list1 = list1.next
else:
#if not then the next node in the list will be the list2 node
curr.next = list2
list2 = list2.next
#increment node
curr = curr.next
#if list1 node is valid but not list2 node add the rest of the nodes from list1
if list1:
curr.next = list1
#if list2 node is valid but not list1 node add the rest of the nodes from list2
elif list2:
curr.next = list2
#return the head of the merged list
return dummy.next | true |
2190f7f62adf79cd2ee82007132c9571e4f0e68b | Codeducate/codeducate.github.io | /students/python-projects-2016/guttikonda_dhanasekar.py | 950 | 4.1875 | 4 | #This program will tell people how much calories they can consume until they have reached their limit.
print("How old are you")
age = int(input())
print("How many calories have you consumed today?")
cc = int(input())
print("Are you a male or female?")
gender = input()
print("Thanks! We are currently calculating your data")
if age <= 3 and gender=="female":
print("You have consumed", 1000-cc)
elif age <= 3 and gender=="male":
print("You have consumed”, 1000-cc)
elif (4 <= age <= 8 and gender==("female"): print("You have consumed", 1200-cc)
elif (4<=age <= 8 and gender=="male"):
print("You have consumed”, 1400-cc)
elif (9 <= age <= 13 and gender=="female"):
print("You have consumed", 1600-cc)
elif (9<=age <= 13 and gender=="male"):
print("You have consumed”, 1800-cc)
elif (14 <= age <= 18 and gender=="female"):
print("You have consumed", 1800-cc)
elif (14<=age <= 18 and gender=="male"):
print("You have consumed”, 2200-cc) | true |
98e78ab456a9b654f37b48fd459c6b24f2560b93 | afmendes/alticelabs | /Programs and Applications/Raspberry Pi 4/Project/classes/Queue.py | 595 | 4.1875 | 4 | # simple queue class with FIFO logic
class Queue(object):
"""FIFO Logic"""
def __init__(self, max_size: int = 1000):
self.__item = []
# adds a new item on the start of the queue
def enqueue(self, add):
self.__item.insert(0, add)
return True
# removes the last items of the queue
def dequeue(self):
if not self.is_empty():
return self.__item.pop()
# checks if the queue is empty and return True if it is, else returns False
def is_empty(self):
if not self.__item:
return True
return False
| true |
eba5b2a0bceea1cc3848e70e0e68fc0f0607a677 | tanishksachdeva/leetcode_prog | /9. Palindrome Number.py | 1,083 | 4.3125 | 4 | # Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
# Follow up: Could you solve it without converting the integer to a string?
# Example 1:
# Input: x = 121
# Output: true
# Example 2:
# Input: x = -121
# Output: false
# Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
# Example 3:
# Input: x = 10
# Output: false
# Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
# Example 4:
# Input: x = -101
# Output: false
# Constraints:
# -231 <= x <= 231 - 1
class Solution:
def get_rev(self,n):
rev =0
while(n > 0):
r = n %10
rev = (rev *10) + r
n = n //10
return rev
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
rev = self.get_rev(x)
print(rev)
if rev==x:
return True
else:
return False
| true |
084a8d9a138e77eba923726e61c139b58170073d | femakin/Age-Finder | /agefinder.py | 1,116 | 4.25 | 4 | #Importing the necessary modules
from datetime import date, datetime
import calendar
#from datetime import datetime
#Getting user input
try:
last_birthday = input('Enter your last birthdate (i.e. 2017,07,01)')
year, month, day = map(int, last_birthday.split(','))
Age_lastbthday = int(input("Age, as at last birthday? "))
#Converting to Date object
date_ = date(year, month, day).weekday()
Year_born = year - Age_lastbthday #Year born from User Input
born_str = str(Year_born) #Birth year to string
conc = (str(Year_born) + str(month) + str(day)) #Concatenation (Year_born, month and day) from date object
born_date = datetime.strptime(conc, '%Y%m%d') #To get the necessary date format
week = datetime.strptime(conc, '%Y%m%d').weekday() #To get the actual birth day of the week
print(f"Thank you for coming around. You were born on { born_date} which happens to be on {(calendar.day_name[week]) }")
#print( (calendar.day_name[week]) )
except:
ValueError
print("Wrong Input! Please make sure your input is in this format: 2017,07,01 ")
quit()
| true |
57249ecd6489b40f0ca4d3ea7dd57661b436c106 | tjastill03/PythonExamples | /Iteration.py | 343 | 4.15625 | 4 | # Taylor Astill
# What is happening is a lsit has been craeted and the list is being printed.
# Then it is sayingfor each of the listed numbers
# list of numbers
numberlist = [1,2,3,4,5,6,7,8,9,10]
print(numberlist)
# iterate over the list
for entry in numberlist:
# Selection over the iteration
if (entry % 2) == 0:
print(entry) | true |
fee46693ff557202fba24ba5a16126341624fdd6 | lepaclab/Python_Fundamentals | /Medical_Insurance.py | 2,599 | 4.6875 | 5 | # Python Syntax: Medical Insurance Project
# Suppose you are a medical professional curious
#about how certain factors contribute to medical
#insurance costs. Using a formula that estimates
#a person’s yearly insurance costs, you will investigate
#how different factors such as age, sex, BMI, etc. affect the prediction.
# Our first step is to create the variables for each factor we will consider when estimating medical insurance costs.
# These are the variables we will need to create:
# age: age of the individual in years
# sex: 0 for female, 1 for male*
# bmi: individual’s body mass index
# num_of_children: number of children the individual has
# smoker: 0 for a non-smoker, 1 for a smoker
# At the top of script.py, create the following variables for a 28-year-old, nonsmoking woman who has three children and a BMI of 26.2
# create the initial variables below
age = 28
sex = 0
bmi = 26.2
num_of_children = 3
smoker = 0
# Add insurance estimate formula below
insurance_cost = 250 * age - 128 * sex + 370 * bmi + 425 * num_of_children + 24000 * smoker - 12500
print("This person's insurance cost is", insurance_cost, "dollars.")
# Age Factor
age += 4
# BMI Factor
new_insurance_cost = 250 * age - 128 * sex + 370 * bmi + 425 * num_of_children + 24000 * smoker - 12500
change_in_insurance_cost = new_insurance_cost - insurance_cost
print("The change in cost of insurance after increasing the age by 4 years is " + str(change_in_insurance_cost) + " dollars.")
age = 28
bmi += 3.1
new_insurance_cost = 250 * age - 128 * sex + 370 * bmi + 425 * num_of_children + 24000 * smoker - 12500
change_in_insurance_cost = new_insurance_cost - insurance_cost
print("The change in estimated insurance cost after increasing BMI by 3.1 is " + str(change_in_insurance_cost) + " dollars.")
# Male vs. Female Factor
bmi = 26.2
sex = 1
new_insurance_cost = 250 * age - 128 * sex + 370 * bmi + 425 * num_of_children + 24000 * smoker - 12500
change_in_insurance_cost = new_insurance_cost - insurance_cost
print("The change in estimated cost for being male instead of female is " + str(change_in_insurance_cost) + " dollars")
# Notice that this time you got a negative value for change_in_insurance_cost. Let’s think about what this means. We changed the sex variable from 0 (female) to 1 (male) and it decreased the estimated insurance costs.
# This means that men tend to have lower medical costs on average than women. Reflect on the other findings you have dug up from this investigation so far.
# Extra Practice
| true |
49f8b9cfb5f19a643a0bacfe6a775c7d33d1e95d | denvinnpaolo/AlgoExpert-Road-to-Cerification-Questions | /Recursion/NthFibonacci.py | 713 | 4.34375 | 4 | # Nth Fibonacci
# Difficulty: Easy
# Instruction:
#
# The Fibonacci sequence is defined as follows: the first number of the sequence
# is 0 , the second number is 1 , and the nth number is the sum of the (n - 1)th
# and (n - 2)th numbers. Write a function that takes in an integer "n"
# and returns the nth Fibonacci number.
# Solution 1: Recurision
def getNthFib(n):
# Write your code here.
if n == 1:
return 0
if n == 2:
return 1
return getNthFib(n-1) + getNthFib(n-2)
# Solution 2: Memoize
def getNthFib(n):
# Write your code here.
d = {
1 : 0,
2 : 1
}
if n in d:
return d[n]
else:
for i in range(3, n+1):
d[i] = d[i - 1] + d[i - 2]
return d[n]
| true |
adffbd365423fb9421921d4ca7c0f5765fe0ac60 | denvinnpaolo/AlgoExpert-Road-to-Cerification-Questions | /Arrays/ThreeNumSum.py | 1,745 | 4.34375 | 4 | # ThreeNumSum
# Difficulty: Easy
# Instruction:
# Write a function that takes in a non-empty array of distinct integers and an
# integer representing a target sum. The function should find all triplets in
# the array that sum up to the target sum and return a two-dimensional array of
# all these triplets. The numbers in each triplet should be ordered in ascending
# order, and the triplets themselves should be ordered in ascending order with
# respect to the numbers they hold.
# If no three numbers sum up to the target sum, the function should return an
# empty array.
# Solution 1:
def threeNumberSum(array, targetSum):
# Write your code here.
array.sort()
ans = []
for i in range(len(array)):
left = i + 1
right = len(array) - 1
while left < right:
curSum = array[i] + array[left] + array[right]
if curSum == targetSum:
ans.append([array[i], array[left], array[right]])
left += 1
right -= 1
elif curSum < targetSum:
left += 1
elif curSum > targetSum:
right -= 1
return ans
# Solution 2:
ans = []
d ={}
for i in range(len(array)):
for j in range(len(array)):
if i == j:
continue
num = targetSum - (array[i] + array[j])
if num in d:
d[num].append([array[i], array[j]])
else:
d[num] = [[array[i], array[j]]]
for i in range(len(array)):
if array[i] in d:
for j in range(len(d[array[i]])):
if array[i] in d[array[i]][j]:
continue
possible_ans = d[array[i]][j][0] + d[array[i]][j][1] + array[i]
if possible_ans == targetSum:
d[array[i]][j].append(array[i])
d[array[i]][j].sort()
if d[array[i]][j] not in ans:
ans.append(d[array[i]][j])
ans.sort()
return ans
| true |
e7499f4caab0fb651b8d9a3fc5a7c374d184d28f | akhileshsantoshwar/Python-Program | /Programs/P07_PrimeNumber.py | 660 | 4.40625 | 4 | #Author: AKHILESH
#This program checks whether the entered number is prime or not
def checkPrime(number):
'''This function checks for prime number'''
isPrime = False
if number == 2:
print(number, 'is a Prime Number')
if number > 1:
for i in range(2, number):
if number % i == 0:
print(number, 'is not a Prime Number')
isPrime = False
break
else:
isPrime = True
if isPrime:
print(number, 'is a Prime Number')
if __name__ == '__main__':
userInput = int(input('Enter a number to check: '))
checkPrime(userInput)
| true |
4fe9d7b1d738012d552b79fb4dc92a3c65fa7e53 | akhileshsantoshwar/Python-Program | /Programs/P08_Fibonacci.py | 804 | 4.21875 | 4 | #Author: AKHILESH
#This program calculates the fibonacci series till the n-th term
def fibonacci(number):
'''This function calculates the fibonacci series till the n-th term'''
if number <= 1:
return number
else:
return (fibonacci(number - 1) + fibonacci(number - 2))
def fibonacci_without_recursion(number):
if number == 0: return 0
fibonacci0, fibonacci1 = 0, 1
for i in range(2, number + 1):
fibonacci1, fibonacci0 = fibonacci0 + fibonacci1, fibonacci1
return fibonacci1
if __name__ == '__main__':
userInput = int(input('Enter the number upto which you wish to calculate fibonnaci series: '))
for i in range(userInput + 1):
print(fibonacci(i),end=' ')
print("\nUsing LOOP:")
print(fibonacci_without_recursion(userInput))
| true |
3060667c2327aa358575d9e096d9bdc353ebedaa | akhileshsantoshwar/Python-Program | /Programs/P11_BinaryToDecimal.py | 604 | 4.5625 | 5 | #Author: AKHILESH
#This program converts the given binary number to its decimal equivalent
def binaryToDecimal(binary):
'''This function calculates the decimal equivalent to given binary number'''
binary1 = binary
decimal, i, n = 0, 0, 0
while(binary != 0):
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary//10
i += 1
print('Decimal equivalent of {} is {}'.format(binary1, decimal))
if __name__ == '__main__':
userInput = int(input('Enter the binary number to check its decimal equivalent: '))
binaryToDecimal(userInput)
| true |
c3e19b89c753c95505dc168514dd760f486dd4b9 | akhileshsantoshwar/Python-Program | /OOP/P03_InstanceAttributes.py | 619 | 4.21875 | 4 | #Author: AKHILESH
#In this example we will be seeing how instance Attributes are used
#Instance attributes are accessed by: object.attribute
#Attributes are looked First in the instance and THEN in the class
import random
class Vehicle():
#Class Methods/ Attributes
def type(self):
#NOTE: This is not a class attribute as the variable is binded to self. Hence it becomes
#instance attribute
self.randomValue = random.randint(1,10) #Setting the instance attribute
car = Vehicle()
car.type() #Calling the class Method
print(car.randomValue) #Calling the instance attribute
| true |
74d0b16405a97e6b5d2140634f2295d466b50e64 | akhileshsantoshwar/Python-Program | /Programs/P54_PythonCSV.py | 1,206 | 4.3125 | 4 | # Author: AKHILESH
# In this example we will see how to use CSV files with Python
# csv.QUOTE_ALL = Instructs writer objects to quote all fields.
# csv.QUOTE_MINIMAL = Instructs writer objects to only quote those fields which contain special characters such
# as delimiter, quotechar or any of the characters in lineterminator.
# csv.QUOTE_NONNUMERIC = Instructs writer objects to quote all non-numeric fields.
# Instructs the reader to convert all non-quoted fields to type float.
# csv.QUOTE_NONE = Instructs writer objects to never quote fields.
import csv
def csvRead(filePath):
with open(filePath) as fd:
reader = csv.reader(fd, delimiter = ',')
for row in reader:
print(row[0] + ' ' + row[1])
def csvWrite(filePath, data):
with open(filePath, 'a') as fd:
writer = csv.writer(fd, delimiter=',', quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(data)
if __name__ == '__main__':
# data = ['Firstname', 'Lastname']
# csvWrite('example.csv', data)
userInput = input('What is your Fullname? ')
userInput = userInput.split(' ')
csvWrite('example.csv', userInput)
csvRead('example.csv')
| true |
0488727a912f98123c6e0fdd47ccde36df895fbd | akhileshsantoshwar/Python-Program | /Programs/P63_Graph.py | 2,160 | 4.59375 | 5 | # Author: AKHILESH
# In this example, we will see how to implement graphs in Python
class Vertex(object):
''' This class helps to create a Vertex for our graph '''
def __init__(self, key):
self.key = key
self.edges = {}
def addNeighbour(self, neighbour, weight = 0):
self.edges[neighbour] = weight
def __str__(self):
return str(self.key) + 'connected to: ' + str([x.key for x in self.edges])
def getEdges(self):
return self.edges.keys()
def getKey(self):
return self.key
def getWeight(self, neighbour):
try:
return self.edges[neighbour]
except:
return None
class Graph(object):
''' This class helps to create Graph with the help of created vertexes '''
def __init__(self):
self.vertexList = {}
self.count = 0
def addVertex(self, key):
self.count += 1
newVertex = Vertex(key)
self.vertexList[key] = newVertex
return newVertex
def getVertex(self, vertex):
if vertex in self.vertexList:
return self.vertexList[vertex]
else:
return None
def addEdge(self, fromEdge, toEdge, cost = 0):
if fromEdge not in self.vertexList:
newVertex = self.addVertex(fromEdge)
if toEdge not in self.vertexList:
newVertex = self.addVertex(toEdge)
self.vertexList[fromEdge].addNeighbour(self.vertexList[toEdge], cost)
def getVertices(self):
return self.vertexList.keys()
def __iter__(self):
return iter(self.vertexList.values())
if __name__ == '__main__':
graph = Graph()
graph.addVertex('A')
graph.addVertex('B')
graph.addVertex('C')
graph.addVertex('D')
graph.addEdge('A', 'B', 5)
graph.addEdge('A', 'C', 6)
graph.addEdge('A', 'D', 2)
graph.addEdge('C', 'D', 3)
for vertex in graph:
for vertexes in vertex.getEdges():
print('({}, {}) => {}'.format(vertex.getKey(), vertexes.getKey(), vertex.getWeight(vertexes)))
# OUTPUT:
# (C, D) => 3
# (A, C) => 6
# (A, D) => 2
# (A, B) => 5
| true |
8271310a83d59aa0d0d0c392a16a19ef538c749d | akhileshsantoshwar/Python-Program | /Numpy/P06_NumpyStringFunctions.py | 1,723 | 4.28125 | 4 | # Author: AKHILESH
import numpy as np
abc = ['abc']
xyz = ['xyz']
# string concatenation
print(np.char.add(abc, xyz)) # ['abcxyz']
print(np.char.add(abc, 'pqr')) # ['abcpqr']
# string multiplication
print(np.char.multiply(abc, 3)) # ['abcabcabc']
# numpy.char.center: This function returns an array of the required width so that the input string is
# centered and padded on the left and right with fillchar.
print(np.char.center(abc, 20, fillchar = '*')) # ['********abc*********']
# numpy.char.capitalize(): This function returns the copy of the string with the first letter capitalized.
print(np.char.capitalize('hello world')) # Hello world
# numpy.char.title(): This function returns a title cased version of the input string with the first letter
# of each word capitalized.
print(np.char.title('hello how are you?')) # Hello How Are You?
# numpy.char.lower(): This function returns an array with elements converted to lowercase. It calls
# str.lower for each element.
print(np.char.lower(['HELLO','WORLD'])) # ['hello' 'world']
# numpy.char.upper(): This function calls str.upper function on each element in an array to return
# the uppercase array elements.
print(np.char.upper('hello')) # HELLO
# numpy.char.split(): This function returns a list of words in the input string. By default, a whitespace
# is used as a separator
print(np.char.split('Abhi Patil')) # ['Abhi', 'Patil']
print(np.char.split('2017-02-11', sep='-')) # ['2017', '02', '11']
# numpy.char.join(): This method returns a string in which the individual characters are joined by
# separator character specified.
print(np.char.join(':','dmy')) # d:m:y
| true |
384c45c69dc7f7896f84c42fdfa9e7b9a4a1d394 | tobyatgithub/data_structure_and_algorithms | /challenges/tree_intersection/tree_intersection.py | 1,392 | 4.3125 | 4 | """
In this file, we write a function called tree_intersection that
takes two binary tree parameters. Without utilizing any of the
built-in library methods available to your language, return a
set of values found in both trees.
"""
def tree_intersection(tree1, tree2):
"""
This function takes in two binary trees as input,
read the first tree and store everything into a
dictionary.
Traverse the second tree and compare. (notice that
we don't store data of second tree.)
"""
store = {}
def preOrder1(tree, root, storage={}):
"""
Traverse tree 1
"""
if root:
value = root.val
storage.setdefault(value, 0)
storage[value] += 1
preOrder1(tree, root.left, storage=storage)
preOrder1(tree, root.right, storage=storage)
preOrder1(tree1, tree1.root, store)
duplicate = []
def preOrder2(tree, root, storage):
"""
Traverse tree 2 and compare
"""
if root:
value = root.val
if value in storage.keys():
duplicate.append(value)
else:
storage.setdefault(value, 0)
storage[value] += 1
preOrder2(tree, root.left, storage)
preOrder2(tree, root.right, storage)
preOrder2(tree2, tree2.root, store)
return set(duplicate)
| true |
212ea767940360110c036e885c544609782f9a82 | tobyatgithub/data_structure_and_algorithms | /data_structures/binary_tree/binary_tree.py | 1,454 | 4.375 | 4 | """
In this file, we make a simple implementation of binary
tree.
"""
import collections
class TreeNode:
def __init___(self, value=0):
self.value = value
self.right = None
self.left = None
def __str__(self):
out = f'This is a tree node with value = { self.val } and left = { self.left } and right = { self.right }'
return out
def __repr__(self):
out = f'This is a tree node with value = { self.val } and left = { self.left }'
f'and right = { self.right }'
return out
class binary_tree:
def __init__(self, iterable=[]):
self.root = None
self.index = 0
if iterable:
if isinstance(iterable, collections.Iterable):
for i in iterable:
self.insert(i)
else:
raise TypeError('Binary_tree class takes None or Iterable \
input, got {}'.format(type(iterable)))
def __str__(self):
out = f'This is a binay tree with root = { self.root.val }'
return out
def __repr__(self):
out = f'This is a binay tree with root = { self.root.val }'
return out
def insert(self, value=0):
pass
# I just notice that...most implementation online
# about binary tree is actually BST...
# which is easier to implement insert
# otherwise...shall we keep an index to keep track of
# insertion?
| true |
8e05603d65047bb6f747be134a6b9b6554f5d9cc | ganguli-lab/nems | /nems/nonlinearities.py | 757 | 4.21875 | 4 | """
Nonlinearities and their derivatives
Each function returns the value and derivative of a nonlinearity. Given :math:`y = f(x)`, the function returns
:math:`y` and :math:`dy/dx`
"""
import numpy as np
def exp(x):
"""Exponential function"""
# compute the exponential
y = np.exp(x)
# compute the first and second derivatives
dydx = y
dy2dx2 = y
return y, dydx, dy2dx2
def softrect(x):
""" Soft rectifying function
.. math::
y = \log(1+e^x)
"""
# compute the soft rectifying nonlinearity
x_exp = np.exp(x)
y = np.log1p(x_exp)
# compute the derivative
dydx = x_exp / (1 + x_exp)
# compute the second derivative
dy2dx2 = x_exp / (1 + x_exp)**2
return y, dydx, dy2dx2
| true |
4851bf916952b52b1b52eb1d010878e33bba3855 | tusvhar01/practice-set | /Practice set 42.py | 489 | 4.25 | 4 | my_tuple = tuple((1, 2, "string"))
print(my_tuple)
my_list = [2, 4, 6]
print(my_list) # outputs: [2, 4, 6]
print(type(my_list)) # outputs: <class 'list'>
tup = tuple(my_list)
print(tup) # outputs: (2, 4, 6)
print(type(tup)) # outputs: <class 'tuple'>
#You can also create a tuple using a Python built-in function called tuple().
# This is particularly useful when you want to convert a certain iterable (e.g., a list, range, string, etc.) to a tuple: | true |
37c28ad515026a3db91878d907f7d31e14f7e9a7 | tusvhar01/practice-set | /Practice set 73.py | 472 | 4.125 | 4 | a=input("Enter first text: ")
b=input("Enter second text: ")
a=a.upper()
b=b.upper()
a=a.replace(' ','')
b=b.replace(' ','')
if sorted(a)==sorted(b):
print("It is Anagram") # anagram
else:
print("Not Anagram")
#An anagram is a new word formed by rearranging the letters of a word, using all the original
# letters exactly once. For example, the phrases
# "rail safety" and "fairy tales" are anagrams, while "I am" and "You are" are not.
| true |
bd50429e48eae21d7a37647c65ae61866c1e97cb | dviar2718/code | /python3/types.py | 1,259 | 4.1875 | 4 | """
Python3 Object Types
Everything in Python is an Object.
Python Programs can be decomposed into modules, statements, expressions, and
objects.
1. Programs are composed of modules.
2. Modules contain statements.
3. Statements contain expressions.
4. Expressions create and process objects
Object Type Example
----------- ---------------------------------------------------
Numbers 1234, 3.14159, 3 + 4j, Ob111, Decimal(), Fraction()
Strings 'spam', "Bob's", b'a\x01c', u'sp\xc4m'
Lists [1, [2, 'three'], 4.5], list(range(10))
Dictionaries {'food':'spam', 'taste':'yum'}, dict(hours=10)
Tuples (1,'spam', 4, 'U'), tuple('spam'), namedtuple
Files open('eggs.txt'), open(r'C:\ham.bin', 'wb')
Sets set('abc'), {'a', 'b', 'c'}
Other core types Booleans, types, None
Program unit types Functions, modules, classes
Implementation related types Compiled code, stack tracebacks
Once you create an object, you bind its operation set for all time.
This means that Python is dynamically typed.
It is also strongly typed (you can only do to an object what it allows)
Immutable Objects
------------------------
Numbers, Strings, Tuples
Mutable Objects
------------------------
Lists, Dictionaries, Sets
"""
| true |
1a7b97bce6b4c638d505e1089594f54914485ec0 | shaner13/OOP | /Week 2/decimal_to_binary.py | 598 | 4.15625 | 4 | #intiialising variables
decimal_num = 0
correct = 0
i = 0
binary = ''
while(correct==0):
decimal_num = int(input("Enter a number to be converted to binary.\n"))
if(decimal_num>=0):
correct = correct + 1
#end if
else:
print("Enter a positive integer please.")
#end else
#end while
while(decimal_num>0):
if(decimal_num % 2 == 0):
binary = binary + '0'
#end if
else:
binary = binary + '1'
#end else
decimal_num = decimal_num // 2
#end while
print("Your number in binary is:\n")
print(binary[::-1])
#end for
| true |
294115d83f56263f56ff23790c35646fa69f8342 | techreign/PythonScripts | /batch_rename.py | 905 | 4.15625 | 4 | # This will batch rename a group of files in a given directory to the name you want to rename it to (numbers will be added)
import os
import argparse
def rename(work_dir, name):
os.chdir(work_dir)
num = 1
for file_name in os.listdir(work_dir):
file_parts = (os.path.splitext(file_name))
os.rename(file_name, name + str(num) + file_parts[1])
num += 1
def get_parser():
parser = argparse.ArgumentParser(description="Batch renaming of files in a folder")
parser.add_argument('work_dir', metavar='WORK_DIR', type=str, nargs=1, help='the directory where you wish to rename the files')
parser.add_argument('name', metavar='NAME', type=str, nargs=1, help='the new name of the files')
return parser
def main():
parser = get_parser()
args = vars(parser.parse_args())
work_dir = args['work_dir'][0]
name = args['name'][0]
rename(work_dir, name)
if __name__ == "__main__":
main()
| true |
f08a7e8583fe03de82c43fc4a032837f5ac43b06 | bartoszmaleta/python-microsoft-devs-yt-course | /25th video Collections.py | 1,278 | 4.125 | 4 | from array import array # used later
names = ['Bartosz', 'Magda']
print(names)
scores = []
scores.append(98) # Add new item to the end
scores.append(85)
print(scores)
print(scores[1]) # collections are zero-indexed
points = array('d') # d stands for digits
points.append(44)
points.append(12)
print(points)
print(points[1])
# Arrays:
# - designed for simple types such as numbers
# - must all be the same type
# Lists:
# - store anything
# - store any type
last_names = ['Maleta', 'Huget']
print(len(last_names)) # get the number of items in last_names
last_names.insert(0, 'Krawiec') # Insert before index
print(last_names)
last_names.sort()
print(last_names)
# _________________________
# Retrieving ranges
second_names = ['Messi', 'Ronaldo', 'Rooney']
footballers = second_names[0:2] # will get the first two items!
# first number is starting index, second number is number of
# items to retrieve
print(second_names)
print(footballers)
# ___________________________
# Dictionaries
person = {'first': 'Jakub'}
person['last'] = 'Maleta'
print(person)
print(person['first'])
# Dictionaries:
# - key/value pairs
# - storage order not guaranteed
# Lists
# - zero-based index
# - storage order guaranteed | true |
9eb9c7ecf681c8ccc2e9d89a0c8324f94560a1f3 | bartoszmaleta/python-microsoft-devs-yt-course | /31st - 32nd video Parameterized functions.py | 878 | 4.28125 | 4 | # same as before:
def get_initial2(name):
initial = name[0:1].upper()
return initial
first_name3 = input("Enter your firist name: ")
last_name3 = input("Enter your last name: ")
print('Your initials are: ' + get_initial2(first_name3) + get_initial2(last_name3))
# ___________________
def get_iniial(name, force_uppercase=True):
# force_uppercase and False added, to have a
# option to choose whether you want upperacse or not
if force_uppercase:
initial = name[0:1].upper()
else:
initial = name[0:1]
return initial
first_name = input('Enter your fist name: ')
first_name_initial = get_iniial(first_name, False)
# or
# first_name_initial = get_iniial(force_uppercase=False, \
# name-first_name)
# dont have to be in order, if there is "="!!!!!
print('Your inital is: ' + first_name_initial) | true |
6544630135a7287c24d1ee167285dc00202cb9aa | MMVonnSeek/Hacktoberfest-2021 | /Python-Programs/avg-parse.py | 1,168 | 4.15625 | 4 | # Total, Average and Count Computation from numbers in a text file with a mix of words and numbers
fname = input("Enter file name: ")
# Ensure your file is in the same folder as this script
# Test file used here is mbox.txt
fhandle = open(fname)
# Seeking number after this word x
x = "X-DSPAM-Confidence:"
y = len(x)
# This shows that the total number of characters is 19
print(y)
# This would show that character 19 is ':' where you can slice to get the numbers after that
print(x[18:])
# Create count to count number of numbers
count = 0
# Create total to sum all the numbers
total = 0
for line in fhandle:
if line.startswith(x):
# Slice the number from the sentence
line_number = line[19:]
line_number = float(line_number)
# print(line_number)
# This shows that we have successfully extracted the floating numbers
# Loop, iterates through all numbers to count number of numbers
count += 1
# Loop, iterates through all numbers to count sum of numbers
total += line_number
print("Count of numbers", count)
print("Sum of numbers", total)
print("Average of numbers", total / count)
| true |
6934e148c95348cd43a07ddb86fadc5723a0e003 | MMVonnSeek/Hacktoberfest-2021 | /Python-Programs/number_decorator.py | 543 | 4.34375 | 4 | # to decorate country code according to user defined countrycode
# the best practical way to learn python decorator
country_code = {"nepal": 977, "india": 91, "us": 1}
def formatted_mob(original_func):
def wrapper(country, num):
country = country.lower()
if country in country_code:
return f"+{country_code[country]}-{original_func(country,num)}"
else:
return num
return wrapper
@formatted_mob
def num(country, num):
return num
number = num("nepal", 9844718578)
print(number)
| true |
dc882ac280f0b5c40cbc1d69ee9db9529e1ad001 | Raviteja02/CorePython | /venv/Parameters.py | 2,308 | 4.28125 | 4 |
#NonDefault Parameters: we will pass values to the non default parameters at the time of calling the function.
def add(a,b):
c = a+b
print(c)
add(100,200)
add(200,300)
print(add) #function address storing in a variable with the name of the function.
sum=add #we can assign the function variable to any user defined variable.
sum(10,20) #and we can access the function with that variable name.
#Default Parameters: we will pass values to the default parameters while creating the function.
def sub(d=20,e=30):
f=e-d
print(f)
sub()
sub(30)
sub(10,40) #if we pass values to default parameters it will override the existing values and give results.
def mult(g,h=10): #one NonDefault and Default Parameter.
i=g*h
print(i)
mult(20)
#def div(j=10,k): #error Default parameter folows Nondefault parameter.
# l=j/k #it wont work.,we can't define a Nondefault parameter after defining Default parameter.
#Orbitary Parameters: the parameters which are preceeded by the (*) are konwn as orbitary Parameters.
def ravi(*a): #Single Star Orbitary Parameter it returns tuple as a result.
print(a)
print(type(a))
ravi()
ravi(10,20,30)
def teja(j,*k):
print(j)
print(type(j))
print(k)
print(type(k))
teja(10,20,30,40)
#def sai(*l,m): Nondefault parameter follwed by sigle star 0rbitary parameter will wont work
# print(l)
# print(type(l))
# print(m)
# print(type(m))
#sai(5,60,70,80)
def satya(*l,m): #Nondefault parameter follwed by sigle star 0rbitary parameter will wont work
print(l)
print(type(l))
print(m)
print(type(m))
satya(5,60,70,80,m=90)
def sai(*l,m=20):
print(l)
print(type(l))
print(m)
print(type(m))
sai(8,40,70,60)
def myfunc(**a): #Multi Star Orbitary Parameter and it will return dictionary as a result
print(a)
print(type(a))
myfunc(x=10,y=20,z=30)
#Arguments
#NonKeyWord Arguments also known as positional arguments.
def nonkeyword(name,msg):
print("Hello",name,msg)
nonkeyword("raviteja","good Morning")
nonkeyword("good Morning","Raviteja")
#Keyword Arguments also known as NOnPositional Arguments.
def keyword(name,msg):
print("Hello",name,msg)
keyword(name="raviteja",msg="good Morning")
keyword(msg="good Morning",name="raviteja")
| true |
3b1bbf74275f81501c8aa183e1ea7d941f075f56 | Tadiuz/PythonBasics | /Functions.py | 2,366 | 4.125 | 4 | # Add 1 to a and store it in B
def add1(a):
"""
This function takes as parameter a number and add one
"""
B = a+1
print(a," if you add one will be: ",B)
add1(5)
print(help(add1))
print("*"*100)
# Lets declare a function that multiplies two numbers
def mult(a,b):
C = a*b
return C
print("This wont be printed")
Result = mult(12,2)
print(Result)
print("*"*100)
# Lets sen string as a paramenter to our multiplication function
Result = mult(5, " Hello World ")
print(Result)
print("*"*100)
# Function definition
def square(a):
"""
Square the input and add 1
"""
b = 1
c = a*a+b
print(a, " If you square +1 ", c)
z = square(2)
print("*"*100)
# Firs block
A1 = 4
B1 = 5
C1 = A1*B1+2*A1*B1-1
if (C1 < 0):
C1 = 0
else:
C1 = 5
print(C1)
print("*"*100)
# Firs block
A1 = 0
B1 = 0
C1 = A1*B1+2*A1*B1-1
if (C1 < 0):
C1 = 0
else:
C1 = 5
print(C1)
print("*"*100)
# Make a function for the calculation above
def equation(A1,B1):
C1 = A1 * B1 + 2 * A1 * B1 - 1
if (C1 < 0):
C1 = 0
else:
C1 = 5
return C1
C2 = equation(4,5)
C3 = equation(0,0)
print(C2)
print(C3)
print("*"*100)
# Example for setting a parameter with default value
def isGoodRaiting(rating = 4):
if(rating < 7):
print("This album sucks it's raiting is: ", rating)
else:
print("This album is good it's raiting is: ", rating)
isGoodRaiting(1)
isGoodRaiting(10)
isGoodRaiting()
print("*"*100)
# Lets create a function with packed arguments
def printAll(*args):
print("Num of arguments: ", len(args))
for argument in args:
print(argument)
printAll("Red", "Yellow", "Blue", "Orange")
print("*"*100)
printAll("Red", "Yellow")
print("*"*100)
# Kwargs parameter
def printDictionary(**kwargs):
for key in kwargs:
print(key + ": " + kwargs[key])
printDictionary(Country = 'Canada', Providence = 'Ontario', City = 'Toronto')
print("*"*100)
# Funtion
def addItems(list):
list.append("Three")
list.append("Four")
My_list = ["One", "Two"]
print(My_list)
addItems(My_list)
print(My_list)
print("*"*100)
#Example of a global variable
Artist = "Michael Jackson"
def printer1(artist):
global internal_var
internal_var = "Elvis"
print(artist," is an artist")
printer1(Artist)
printer1(internal_var)
| true |
b2c4bb3420c54e65d601c16f3bc3e130372ae0de | nfarnan/cs001X_examples | /functions/TH/04_main.py | 655 | 4.15625 | 4 | def main():
# get weight from the user
weight = float(input("How heavy is the package to ship (lbs)? "))
if weight <= 0:
print("Invalid weight (you jerk)")
total = None
elif weight <= 2:
# flat rate of $5
total = 5
# between 2 and 6 lbs:
elif weight <= 6:
# $5 + $1.50 per lb over 2
total = 5 + 1.5 * (weight - 2)
# between 6 and 10 lbs:
elif weight <= 10:
# $11 + $1.25 per lb over 6
total = 11 + 1.25 * (weight - 6)
# over 10 lbs:
else:
# $16 + $1 per lb over 10
total = 16 + (weight - 10)
if total != None:
# output total cost to user:
print("It will cost $", format(total, ".2f"), " to ship", sep="")
main()
| true |
b5dd5d77115b2c9206c4ce6c22985e362f13c15e | nfarnan/cs001X_examples | /exceptions/MW/03_input_valid.py | 529 | 4.21875 | 4 | def get_non_negative():
valid = False
while not valid:
try:
num = int(input("Enter a non-negative int: "))
except:
print("Invalid! Not an integer.")
else:
if num < 0:
print("Invalid! Was negative.")
else:
valid = True
return num
def get_non_negative2():
while True:
try:
num = int(input("Enter a non-negative int: "))
except:
print("Invalid! Not an integer.")
else:
if num < 0:
print("Invalid! Was negative.")
else:
return num
an_int = get_non_negative()
print(an_int)
| true |
b862f9fd6aad966de8bd05c2bfcb9f9f12ba61f5 | mhashilkar/Python- | /2.9.7_Variable-length_arguments.py | 590 | 4.5 | 4 | # When you need to give more number of arguments to the function
# " * "used this symbol tho the argument that means it will take multiple value
# it will be a tuple and to print that args you have to used the for loop
def printinfo(args1, *vartuple):
print("Output is: ")
print(args1)
for var in vartuple:
print(var)
printinfo(10,20)
printinfo(10,20,30,40)
def test_var_args(f_args, *argvs):
print("First normal args:", f_args)
for var in argvs:
print("another arg through *argvs: ",var)
test_var_args('yahoo','Google','Python','PHP','Angular.js')
| true |
b0c57e4bbcfa9a9e6283ebceeca1a0a5594a28c5 | ramyashah27/chapter-8-and-chapter-9 | /chapter 9 files are op/03write.py | 382 | 4.15625 | 4 | # f = open('another.txt', 'w')
# f.write("this file is created through writing in 'w'")
# f.close()
# this is to make/open file and will add (write) all data in it, it will overright
f = open('another.txt', 'a')
f.write(' and this is appending')
f.close()
#this is to add data in the end
# how many times we run the program each time the data in write will add in the end | true |
b2c09cf42fa22404a0945b1746176a1b847bd260 | dobtco/beacon | /beacon/importer/importer.py | 974 | 4.125 | 4 | # -*- coding: utf-8 -*-
import csv
def convert_empty_to_none(val):
'''Converts empty or "None" strings to None Types
Arguments:
val: The field to be converted
Returns:
The passed value if the value is not an empty string or
'None', ``None`` otherwise.
'''
return val if val not in ['', 'None'] else None
def extract(file_target, first_row_headers=[]):
'''Pulls csv data out of a file target.
Arguments:
file_target: a file object
Keyword Arguments:
first_row_headers: An optional list of headers that can
be used as the keys in the returned DictReader
Returns:
A :py:class:`~csv.DictReader` object.
'''
data = []
with open(file_target, 'rU') as f:
fieldnames = first_row_headers if len(first_row_headers) > 0 else None
reader = csv.DictReader(f, fieldnames=fieldnames)
for row in reader:
data.append(row)
return data | true |
31d79ed21483f3cbbc646fbe94cf0282a1753f91 | OceanicSix/Python_program | /parallel_data_processing/data_parition/binary_search.py | 914 | 4.125 | 4 | # Binary search function
def binary_search(data, target):
matched_record = None
position = -1 # not found position
lower = 0
middle = 0
upper = len(data) - 1
### START CODE HERE ###
while (lower <= upper):
# calculate middle: the half of lower and upper
middle = int((lower + upper) / 2)
if data[middle]==target:
matched_record=target
position=middle
return position,matched_record
elif data[middle]<target:
lower = middle + 1
else:
upper=middle-1
### END CODE HERE ###
return position, matched_record
if __name__ == '__main__':
D = [55, 30, 68, 39, 1,
4, 49, 90, 34, 76,
82, 56, 31, 25, 78,
56, 38, 32, 88, 9,
44, 98, 11, 70, 66,
89, 99, 22, 23, 26]
sortD=D[:]
sortD.sort()
print(binary_search(sortD,31)) | true |
33e560583b1170525123c867bb254127c920737f | OceanicSix/Python_program | /Study/Search_and_Sort/Insertion_sort.py | 840 | 4.34375 | 4 | # sorts the list in an ascending order using insertion sort
def insertion_sort(the_list):
# obtain the length of the list
n = len(the_list)
# begin with the first item of the list
# treat it as the only item in the sorted sublist
for i in range(1, n):
# indicate the current item to be positioned
current_item = the_list[i]
# find the correct position where the current item
# should be placed in the sorted sublist
pos = i
while pos > 0 and the_list[pos - 1] > current_item:
# shift items in the sorted sublist that are
# larger than the current item to the right
the_list[pos] = the_list[pos - 1]
pos -= 1
# place the current item at its correct position
the_list[pos] = current_item
return the_list | true |
f23588e2e08a6dd36a79b09485ebc0f7a59ed6b7 | chiragkalal/python_tutorials | /Python Basics/1.python_str_basics.py | 930 | 4.40625 | 4 | ''' Learn basic string functionalities '''
message = "it's my world." #In python we can use single quotes in double quotes and vice cersa.
print(message)
message = 'it\'s my world.' #Escape character('\') can handle quote within quote.
print(message)
message = """ It's my world. And I know how to save this world
from bad people. This world has peace and happiness. """ #For multiline string
print(message)
print(message[0]) #returns first letter of str(slicing[start_include:end_exclude:difference])
print(dir(message)) #returns all methods that can apply on str
print(message.lower())
print(message.upper())
print(message.count('l'))
print(message.find('w'))
print(message.find('universe'))
new_msg = message.replace('world', 'universe')
print(new_msg)
# print(help(str)) #retuns all string methds descriptions and
# print(help(str.lower)) #you can also specify specific method name like str.lower() | true |
be83f2c448015ca8108ba665a057ce30ef3e7ed0 | Lucchese-Anthony/MonteCarloSimulation | /SimPiNoMatplotlib.py | 885 | 4.21875 | 4 | import math
import random
inside = 1
outside = 1
count = 0
def inCircle(x, y):
#function that sees if the coordinates are contained within the circle, either returning false or true
return math.sqrt( (x**2) + (y**2) ) <= 1
while True:
count = count + 1
#random.uniform generates a 'random' number between the given values, for example, 'random.uniform(-1, 1)' generates .21946219
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)
#if its in the circle, add one to the amount of points inside the circle
if (inCircle(x, y)):
inside = inside + 1
#and one if the coordinate is not in the circle
else:
outside = outside + 1
#this prints the ratio of coordinates inside the circle with the points outside the circle
#each 100 is printed to reduce the amount of clutter
if count % 100:
print(inside / outside)
| true |
209c616fe9c622b4269bddd5a7ec8d06d9a27e86 | paula867/Girls-Who-Code-Files | /survey.py | 2,480 | 4.15625 | 4 | import json
import statistics
questions = ["What is your name?",
"What is your favorite color?",
"What town and state do you live in?",
"What is your age?",
"What year were you born?"]
answers = {}
keys = ["Name", "Favorite color", "Hometown","Age", "Birthyear"]
all_answers = []
choice = input("Would you like to take a survey? Type yes or no. ")
while choice == "yes": #forever loop
answers = {} # this dictionary used to be outside. The answers would be replaced everytime someone took a survey with the answers of the last survey.
# When answers was put inside the while loop, that didn't happen anymore.
for q in range(len(questions)): #when you use for i in range i = to an interger. When you use for i in list i = to a concept or variable.
response = input(questions[q] +" ") # raw_input is the same as input for now
answers[keys[q]] = response #sets the keys(list) to a value every time you go through the loop
all_answers.append(answers)
choice = input("Would you like to take a survey? Type yes or no. ")
json_file = open("json.json", "w")
index = 0
json_file.write('[\n')
for d in all_answers:
if (index < len(all_answers) - 1): #length is always one more than the index
json.dump(d,json_file) #opening json file then storing all the items (dictionaries/ d) in all_answers
json_file.write(',\n') #writes into json file #'\n' adds a new line or what is known as 'enter' for humans
else: #will be the last index because the index is less than the length not less than or equal to.
json.dump(d, json_file)
json_file.write('\n')
index += 1
json_file.write(']') # .write adds things to a json file.
json_file.close() #closes json file
ages_surveys = []
for a in all_answers:
the_ages = a["Age"] #add the age you find in all_answers to the_ages
the_ages = int(the_ages)
ages_surveys.append(the_ages)
cities = []
for c in all_answers:
city = c["Hometown"]
cities.append(city)
colors = []
for o in all_answers:
color = o["Favorite color"]
colors.append(color)
print(all_answers)
print("The average age of the participants is", statistics.mean(ages_surveys))
print("The city most people live in is ", statistics.mode(cities))
print("The most liked color among the participants is", statistics.mode(colors))
| true |
c2123be019eca85251fbd003ad3894bb51373433 | jacobroberson/ITM313 | /hw2.py | 1,516 | 4.5 | 4 | '''
This program provides an interface for users to select a medium and enter a distance
that a sound wave wil travel. Then the program will calculate and display the time it
takes for the waveto travel the given distance.
Programmer: Jacob Roberson
Course: ITM313
'''
#Intialize variables
selection = 0
medium = ""
air = 1100
water = 4900
steel = 16400
distace = 0
time = 0
#Receive user input
print("Welcome to THE SPEED OF SOUND CALCULATOR")
selection = int(input("\nSelect the medium the wave will be traveling through by "
"entering the corresponding number\nMENU:\n1.) Air\n2.) Water\n"
"3.) Steel\nSELECTION: "))
distance = eval(input("Please enter the distance the sound wave will travel in feet: "))
#Calculation
if(selection == 1 and distance > 0):
medium = "air"
time = distance/air
elif(selection == 2 and distance > 0):
medium = "water"
time = distance/water
elif(selection == 3 and distance > 0):
medium = "steel"
time = distance/steel
elif(distance <= 0):
print("\nERROR:\nPlease rerun the program and enter a distance greater than 0 feet."
"\n\nINVALID OUTPUT:")
else:
print("\nERROR:\nYou have entered an invalid selection. Please rerun the program "
"and enter a valid selection.\n\nINVALID OUTPUT:")
#Output
print("\nThe time it will take a sound wave to travel", distance, "feet through",
medium, "is %.4f" % (time), "seconds")
| true |
ee3615b1612d3340005a8b07a6e93bc130153591 | JanJochemProgramming/basic_track_answers | /week3/session/dicts.py | 338 | 4.25 | 4 | capitals = {"The Netherlands": "Amsterdam", "France": "Paris"}
capitals["Japan"] = "Tokyo"
for country in reversed(sorted(capitals)):
print(country, capitals[country])
fruit_basket = {"Apple": 3}
fruit_to_add = input("Which fruit to add? ")
fruit_basket[fruit_to_add] = fruit_basket.get(fruit_to_add, 0) + 1
print(fruit_basket)
| true |
8ec7c46f57e44354f3479ea02e8e0cf34aaec352 | oreqizer/pv248 | /04/book_export.py | 1,691 | 4.1875 | 4 | # In the second exercise, we will take the database created in the
# previous exercise (‹books.dat›) and generate the original JSON.
# You may want to use a join or two.
# First write a function which will produce a ‹list› of ‹dict›'s
# that represent the books, starting from an open sqlite connection.
import sqlite3
import json
from book_import import opendb
query_books = """
--begin-sql
SELECT b.name
FROM book AS b
--end-sql
"""
query_authors = """
--begin-sql
SELECT a.name
FROM book AS b
INNER JOIN book_author_list AS l ON l.book_id = b.id
INNER JOIN author AS a ON l.author_id = a.id
WHERE b.name = ?
--end-sql
"""
def read_books(conn):
cur = conn.cursor()
res = []
cur.execute(query_books)
books = cur.fetchall()
for b in books:
cur.execute(query_authors, b)
authors = cur.fetchall()
res.append({
"name": b[0],
"authors": [name for (name,) in authors],
})
conn.commit()
return res
# Now write a driver that takes two filenames. It should open the
# database (do you need the foreign keys pragma this time? why yes
# or why not? what are the cons of leaving it out?), read the books,
# convert the list to JSON and store it in the output file.
def export_books(file_in, file_out):
conn = opendb(file_in)
res = json.dumps(read_books(conn), indent=" ")
open(file_out, "w").write(res)
def test_main():
export_books('books.dat', 'books_2.json')
with open('books.json', 'r') as f1:
js1 = json.load(f1)
with open('books_2.json', 'r') as f2:
js2 = json.load(f2)
assert js1 == js2
if __name__ == "__main__":
test_main()
| true |
a0151ddb3bc4c2d393abbd431826393e46063b89 | zachacaria/DiscreteMath-II | /q2.py | 1,356 | 4.15625 | 4 | import itertools
import random
def random_permutation(iterable, r):
"Random selection from itertools.permutations(iterable, r)"
pool = tuple(iterable)
r = len(pool) if r is None else r
return tuple(random.sample(pool, r))
# Function to do insertion sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
# This code is contributed by Mohit Kumra
#permut = itertools.permutations(random_permutation(range(1,101), 5))
#permut = itertools.permutations.random_permutation(range(100),3)
#permut = itertools.permutations([1,2,3,4,5,6],3)
#count_permut = []
#for i in permut:
#count_permut.append(i)
#print all permutations
#print count_permut.index(i)+1, i
#print the total number of permutations
#print'number of permutations', len(count_permut)
permut = itertools.permutations(random_permutation(range(1,101), 100))
# Driver code to test above
#count_permut = []
count_permut = []
insertionSort(count_permut)
print ("Sorted array is:")
for i in range(len(count_permut)):
print ("%d" %count_permut[i])
#for i in range(len(arr)):
#print ("%d" %arr[i])
| true |
115b477fb7b86d34e9df784d43bfe29b2dcbf06a | tanyastropheus/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 364 | 4.28125 | 4 | #!/usr/bin/python3
def number_of_lines(filename=""):
"""count the number of lines in a text file
Args:
filename (str): file to be counted
Returns:
line_num (int): number of lines in the file.
"""
line_num = 0
with open(filename, encoding="UTF8") as f:
for line in f:
line_num += 1
return line_num
| true |
fafd561f1c3020231747a3480278bcf91c457a82 | AYamaui/Practice | /exercises/cyclic_rotation.py | 1,998 | 4.3125 | 4 | """
An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved to the first place).
The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.
Write a function:
def solution(A, K)
that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.
For example, given
A = [3, 8, 9, 7, 6]
K = 3
the function should return [9, 7, 6, 3, 8]. Three rotations were made:
[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
For another example, given
A = [0, 0, 0]
K = 1
the function should return [0, 0, 0]
Given
A = [1, 2, 3, 4]
K = 4
the function should return [1, 2, 3, 4]
Assume that:
N and K are integers within the range [0..100];
each element of array A is an integer within the range [−1,000..1,000].
In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.
"""
def solution(A, K):
N = len(A)
final_array = [0]*N
for i in range(N):
new_index = i + K - N*((i + K )// N)
final_array[new_index] = A[i]
return final_array
if __name__ == '__main__':
A = [3, 8, 9, 7, 6]
K = 3
print(solution(A, K))
A = [0, 0, 0]
K = 1
print(solution(A, K))
A = [1, 2, 3, 4]
K = 4
print(solution(A, K))
A = [2]
K = 10
print(solution(A, K))
A = [8, 11, 4, 20, 1]
K = 12
print(solution(A, K))
A = [8, 11, 4, 20, 1]
K = 11
print(solution(A, K))
A = [8, 11, 4, 20]
K = 12
print(solution(A, K))
A = [8, 11, 4, 20]
K = 11
print(solution(A, K))
A = [2, 3]
K = 5
print(solution(A, K))
| true |
5f404ca2db9ce87abe64ba7fd1dd111b1ceeb022 | matt969696/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/100-matrix_mul.py | 1,965 | 4.25 | 4 | #!/usr/bin/python3
"""
2-matrix_mul module - Contains simple function matrix_mul
"""
def matrix_mul(m_a, m_b):
"""
Multiplies 2 matrices
Return the new matrix
The 2 matrix must be non null list of list
The 2 matrix must be multiable
All elements of the 2 matrix must be integers or floats
"""
if type(m_a) is not list:
raise TypeError("m_a must be a list")
if type(m_b) is not list:
raise TypeError("m_b must be a list")
for line in m_a:
if type(line) is not list:
raise TypeError("m_a must be a list of lists")
for line in m_b:
if type(line) is not list:
raise TypeError("m_b must be a list of lists")
if len(m_a) == 0 or len(m_a[0]) == 0:
raise ValueError("m_a can't be empty")
if len(m_b) == 0 or len(m_b[0]) == 0:
raise ValueError("m_b can't be empty")
for line in m_a:
for a in line:
if type(a) is not int and type(a) is not float:
raise TypeError("m_a should contain only integers or floats")
for line in m_b:
for a in line:
if type(a) is not int and type(a) is not float:
raise TypeError("m_b should contain only integers or floats")
for line in m_a:
if len(line) != len(m_a[0]):
raise TypeError("each row of m_a must be of the same size")
for line in m_b:
if len(line) != len(m_b[0]):
raise TypeError("each row of m_b must be of the same size")
linea = len(m_a)
cola = len(m_a[0])
lineb = len(m_b)
colb = len(m_b[0])
if cola != lineb:
raise ValueError("m_a and m_b can't be multiplied")
outmat = []
for i in range(linea):
totline = []
for j in range(colb):
tot = 0
for k in range(cola):
tot += m_a[i][k] * m_b[k][j]
totline.append(tot)
outmat.append(totline)
return(outmat)
| true |
6aef4c2a49e81fe1fe83dacb7e246acee51ab11c | Floozutter/silly | /python/montyhallsim.py | 2,038 | 4.15625 | 4 | """
A loose simulation of the Monty Hall problem in Python.
"""
from random import randrange, sample
from typing import Tuple
Prize = bool
GOAT = False
CAR = True
def make_doors(doorcount: int, car_index: int) -> Tuple[Prize]:
"""Returns a representation of the doors in the Monty Hall Problem."""
return tuple(CAR if i == car_index else GOAT for i in range(doorcount))
def play(doorcount: int, switch: bool) -> Prize:
"""Runs a trial of the Monty Hall problem and returns the Prize."""
# Make the doors with a randomly generated index for the winning door.
doors = make_doors(doorcount, randrange(doorcount))
# Randomly generate the player's first choice.
firstchoice = randrange(doorcount)
# Generate every revealable door.
# A door is revealable if it contains a goat and is not the first choice.
revealable = tuple(
i for i, prize in enumerate(doors) if (
i != firstchoice and prize == GOAT
)
)
# Reveal doors so that one door remains apart from the first choice.
revealed = sample(revealable, doorcount - 2)
# Get the index of the final remaining door.
otherchoice = next(iter(
set(range(doorcount)) - set(revealed) - {firstchoice}
))
# Choose between the player's first choice and the other choice.
finalchoice = otherchoice if switch else firstchoice
# Return the Prize corresponding to the final choice.
return doors[finalchoice]
def test(doorcount: int, switch: bool, trials: int) -> bool:
"""Returns a win rate for the Monty Hall problem with repeated trials."""
wins = sum(int(play(doorcount, switch) == CAR) for _ in range(trials))
return wins/trials
if __name__ == "__main__":
trials = 10000
# Test always switching with 3 doors.
print(f"{3:>3} Doors | Always Switch: ", end="")
print(f"{test(3, True, trials):%}")
# Test always switching with 100 doors.
print(f"{100:>3} Doors | Always Switch: ", end="")
print(f"{test(100, True, trials):%}")
| true |
c7e11b86d21975a2afda2485194161106cadf3b3 | ariquintal/StructuredProgramming2A | /unit1/activity_04.py | 338 | 4.1875 | 4 | print("Start Program")
##### DECLARE VARIABLES ######
num1 = 0
num2 = 0
result_add = 0
result_m = 0
num1 = int(input("Enter number1\n"))
num2 = int(input("Enter number2\n"))
result_add = num1 + num2
result_m = num1 * num2
print("This is the add", result_add)
print("This is the multiplication", result_m)
print ("Program Ending...") | true |
b9c3c868e064818e27304573dec01cc97a4c3ab1 | candacewilliams/Intro-to-Computer-Science | /moon_earths_moon.py | 299 | 4.15625 | 4 | first_name = input('What is your first name?')
last_name = input('What is your last name?')
weight = float(input('What is your weight?'))
moon_weight = str(weight* .17)
print('My name is ' + last_name + '. ' + first_name + last_name + '. And I weigh ' + moon_weight + ' pounds on the moon.')
| true |
ed89b53b3082f608adb2f612cf856d87d1f51c78 | SandySingh/Code-for-fun | /name_without_vowels.py | 359 | 4.5 | 4 | print "Enter a name"
name = raw_input()
#Defining all vowels in a list
vowels = ['a', 'e', 'i', 'o', 'u']
name_without_vowels = ''
#Removing the vowels or rather forming a name with only consonants
for i in name:
if i in vowels:
continue
name_without_vowels += i
print "The name without vowels is:"
print name_without_vowels
| true |
8fbcb251349fe18342d92c4d91433b7ab6ca9d53 | gsaikarthik/python-assignment7 | /assignment7_sum_and_average_of_n_numbers.py | 330 | 4.21875 | 4 | print("Input some integers to calculate their sum and average. Input 0 to exit.")
count = 0
sum = 0.0
number = 1
while number != 0:
number = int(input(""))
sum = sum + number
count += 1
if count == 0:
print("Input some numbers")
else:
print("Average and Sum of the above numbers are: ", sum / (count-1), sum) | true |
4731e40b41f073544f2edf67fb02b6d93396cd7b | hbomb222/ICTPRG-Python | /week3q4 new.py | 819 | 4.40625 | 4 | username = input("enter username ") # ask user for username
user_dict = {"bob":"password1234", "fred":"happypass122", "lock":"passwithlock144"} # create dictionary of username password pairs
if (username == "bob" or username == "fred" or username == "lock"): # check if the entered username matches any of the known values
password = (input("enter password ")) # ask user for password
check_password = user_dict[username] # retrive the saved password from the dictionary for the entered username
if (password == check_password): # check if the entered password is the same as the saved password
print ("access granted") # print if username and password match
else: # if the passwords do not match, jump to this code
print ("access denied") # print if username matches but password does not match | true |
5e3d41c1d7e1d49566416dced623ae593b58c079 | nickwerner-hub/WhirlwindTourOfPython | /Scripting/03_RangeFunctionExample.py | 270 | 4.34375 | 4 | #RangeFunctionExample.py
# This example demonstrates the range function for generating
# a sequence of values that can be used in a for loop.
pi = 3.1415
for r in range(0,100,20):
area = (r ** 2) * pi
print "The area of a circle with radius ", r, "is ", area | true |
313925e1c6edb9d16bc921aff0c8897ee1d2bdf5 | nickwerner-hub/WhirlwindTourOfPython | /Scripting/07_WriteDataExample.py | 1,620 | 4.34375 | 4 | #WriteDataExample.py
# This script demonstrates how a file object is used to both write to a new text file and
# append to an existing text file.In it we will read the contents of the EnoNearDurham.txt
# file and write selected data records to the output file.
# First, create some variables. "dataFileName" will point to the EnoNearDurham.txt file,
# and "outputFileName" will that will contain the name of the file we will create.
dataFileName = "S://Scripting2//EnoNearDurham.txt"
outputFileName = "S://Scripting2//SelectedNWISRecords.txt"
# Next, open the data file and read its contents into a list object. This is similar
# to the previous tutorial, but here we read the entire contents into a single list
dataFileObj = open(dataFileName, 'r') ## Opens the data file as read only
lineList = dataFileObj.readlines() ## Creates a list of lines from the data file
dataFileObj.close() ## We have our list, so we can close the file
print len(lineList), " lines read in" ## This is a quick statement to show how many lines were read
# Here, we create a file object in 'w' or write mode. This step creates a new file at
# the location specified. IF A FILE EXISTS ALREADY THIS WILL OVERWRITE IT!
newFileObj = open(outputFileName,'w')
# Next, we loop through the lines in the dataList. If it's a comment, we'll skip it.
# Otherwise, we'll split the items in the line into a list.
for dataLine in lineList:
# If the line is a comment, skip further processing and go to the next line
if dataLine[:4] <> "USGS":
continue
newFileObj.write(dataLine)
newFileObj.close() | true |
1fc51bc3ec116ee0663399bffae6825020d33801 | abdbaddude/codeval | /python/jolly_jumper.py3 | 2,166 | 4.1875 | 4 | #!/usr/bin/env python3
"""
JOLLY JUMPERS
CHALLENGE DESCRIPTION:
Credits: Programming Challenges by Steven S. Skiena and Miguel A. Revilla
A sequence of n > 0 integers is called a jolly jumper if the absolute values of the
differences between successive elements take on all possible values 1 through n - 1.
eg.
1 4 2 3
is a jolly jumper, because the absolute differences are 3, 2, and 1, respectively.
The definition implies that any sequence of a single integer is a jolly jumper.
Write a program to determine whether each of a number of sequences is a jolly jumper.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename.
Each line in this file is one test case.
Each test case will contain an integer n < 3000
followed by n integers representing the sequence. The integers are space delimited.
OUTPUT SAMPLE:
For each line of input generate a line of output saying 'Jolly' or 'Not jolly'.
"""
"""
@params List of n sequence such that 0 < n < 3000
e.g x = [1,4,2,3]
"""
def is_jolly_jumpers(seq):
n = seq.pop(0) #first number in list is number of integers
if ( n == 1 and len(seq) == 1) : return True #The definition implies that any sequence of a single integer is a jolly jumper
else:
if ((n == len(seq)) and (1 < n and n<3000) ): #condition must be fulfilled
_,*tail = seq #pythonic way of removing/ignoring values
len_tail = len(tail)
c=[ abs(seq[i] - tail[i]) for i in range(len_tail)]
#Decided against using sorted and used sum instead as sorted will bring in algorithm overhead of Big O = N
#hence used sum for test
sum_test = (sum(c)==sum(list(range(len_tail+1))))
possible_values_test = True if (min(c) == 1 and (n-max(c)) == 1) else False #Ensure possible values 1 .. n-1
return possible_values_test and sum_test
else:
return False
import sys
test_cases = open(sys.argv[1], 'r')
tests=test_cases.readlines()
for test in tests:
if test.strip(): #only nonempty lines are only considered
s_list = test.strip().split(" ") #convert each line to a string list.
i_list = [int(i) for i in s_list ] #convert string list to int
print ('Jolly' if is_jolly_jumpers(i_list) else 'Not jolly' )
| true |
87c2fcfcaa140e8971926f8da3098c5abe781271 | Nadeem-Doc/210CT-Labsheet | /Labsheet 5 - Task 2.py | 1,542 | 4.21875 | 4 | class Node():
def __init__(self, value):
self.value=value
self.next=None # node pointing to next
self.prev=None # node pointing to prev
class List():
def __init__(self):
self.head=None
self.tail=None
def insert(self,n,x):
#Not actually perfect: how do we prepend to an existing list?
if n!=None:
x.next = n.next
n.next = x
x.prev = n
if x.next != None:
x.next.prev = x
if self.head == None:
self.head = self.tail = x #assigns the value of x to the head and tail
x.prev = x.next = None
elif self.tail == n:
self.tail = x #reassigns the tail to the current node
def display(self):
values=[]
n=self.head
while n!=None:
values.append(str(n.value))
n=n.next
print ("List: ", ",".join(values))
def lisrem(self,n):
if n.prev != None:
n.prev.next = n.next
else:
l.head = n.next
if n.next != None:
n.next.prev = n.prev
else:
l.tail = n.prev
if __name__ == '__main__':
l=List()
n = Node(6)
n1 = Node(2)
n2 = Node(3)
n3 = Node(4)
l.insert(None, n)
l.insert(l.head,n1)
l.insert(l.head,n2)
l.insert(l.head,n3)
l.lisrem(n)
l.display()
| true |
f0664f2b9a826598dc873e8c27d53b6623f67b5b | Vanagand/Data-Structures | /queue/queue.py | 1,520 | 4.21875 | 4 | #>>> Check <PASS>
"""
A queue is a data structure whose primary purpose is to store and
return elements in First In First Out order.
1. Implement the Queue class using an array as the underlying storage structure.
Make sure the Queue tests pass.
2. Re-implement the Queue class, this time using the linked list implementation
as the underlying storage structure.
Make sure the Queue tests pass.
3. What is the difference between using an array vs. a linked list when
implementing a Queue?
Stretch: What if you could only use instances of your Stack class to implement the Queue?
What would that look like? How many Stacks would you need? Try it!
"""
from sys import path
path.append("../")
from singly_linked_list.singly_linked_list import singleLinkedList
class Queue: #<<<
def __init__(self):
self._stack = 0
self._storage = singleLinkedList()
def __len__(self):
return self._stack
def enqueue(self, value):
self._storage.add_to_tail(value)
self._stack += 1
def dequeue(self):
if self.__len__() > 0:
self._stack -= 1
return self._storage.remove_head()
if self.__len__() <= 0:
return
if __name__ == "__main__":
pass
# import pkgutil
# search_path = ['.'] # set to None to see all modules importable from sys.path
# all_modules = [x[1] for x in pkgutil.iter_modules(path=search_path)]
# print(all_modules) | true |
de5f1ae3bae6d0744cd18ded1ec0631d48fbb559 | TanvirKaur17/Greedy-4 | /shortestwayToFormString.py | 912 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 29 08:30:10 2019
@author: tanvirkaur
implemented on spyder
Time Complexity = O(m*n)
Space Complexity = O(1)
we maintain two pointers one for source and one for target
Then we compare the first element of source with the target
If we iterate through the entire source we again reset the pointer
untill we visit the entire target
We maintain the curr pointer to check whether we have found the ith element
of target in source or not.
"""
def shortestWay(source, target):
if source == target:
return 1
result = 0
s = len(source)
t = len(target)
i = 0
while (i<t):
j =0
curr = i
while(j<s):
if (i <t and source[j] == target[i]):
i += 1
j +=1
if curr == i:
return -1
result += 1
return result
| true |
0f8df2bb7f0ca56f34737d85faa3aeb5d4c8a300 | emmanuelagubata/Wheel-of-Fortune | /student_starter/main.py | 1,188 | 4.15625 | 4 | # Rules
print('Guess one letter at a time. If you want to buy a vowel, you must have at least $500, otherwise, you cannot buy a vowel. If you think you know the word or phrase, type \'guess\' to guess the word or phrase. You will earn each letter at a set amount and vowels will not cost anything.')
from random import randint
# needed for your test cases so your random outputs would match ours
random.seed(3)
# List of letters to remove after each guess
# List of all vowels
# Categories and words
# Pick a random category
# Get a random word or phrase from the category
# Fill up list with blanks for characters in word
# Function to print Word
def printWord(word):
# Keep guessing until word is guessed correctly
while True:
while True:
# Pick a random amount from amounts
# If the user wants to guess phrase or word
# If the user guesses letter they've already guessed
# If guess is a vowel, subtract $500 from total per vowel
# If the user cannot buy vowel
# If everything else is False, remove letter from alphabet and replace char in Word with letter in word
# If word or phrase is fully guessed, end game
| true |
355df5e645f38513d4581c5f3f08ed41568c59e2 | zaincbs/PYTECH | /reverseOfString.py | 375 | 4.375 | 4 | #!/usr/bin/env python
"""
Define a function reverse, that computes the reversal of a string. For example, reverse("I am testing") should return the string "gnitset ma I".
"""
def reverse(s):
k= ""
for i in range (len(s)-1, -1, -1):
k = k + s[i]
return k
def main():
v = reverse("This is testing")
print v
if __name__ == "__main__":
main()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.