blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
6b3146aefdfb33586ebba0f6e366067115c610dc | abhi-python/python-programs | /variablesinput.py | 679 | 4.1875 | 4 | '''
1. Variables- These are the Container to store any type of data.
2. DataType- Define the type of data like- int(integer e.g. 25),Float(25.6)
3. TypeCasting- Convert one dataType to other.
4. UserInput- input() function is used to take input from user. By default its type is String.
'''
var1 = "hello world"
var2 = "36"
var3 = 27.3
#print(type(var2))
#print(var1+var2)
print("Enter first number")
num1= input()
#print(type(num1))
print("Enter second number")
num2= input()
#print("The sum of these no is", int(num1)+int(num2))
#print("The subtraction is", int(num1)-int(num2))
#print("The multiplication is", int(num1)*int(num2))
print("The division is", int(num1)/int(num2)) | true |
6f3a8d426e89642e1a7e0b6a5467378db438dace | mehlj/challenges | /plus_minus/plus_minus.py | 807 | 4.34375 | 4 | #!/usr/bin/env python3
import decimal
def plus_minus(integers):
"""
Accepts a list[] of integers and returns ratio of elements that are positive, negative and zero
Ex: plus_minus([1,1,0,-1,-1]) --> 0.400000,0.400000,0.200000
@param integers: A list of integers, zero, positive, or negative
@return: N/A
"""
positives = []
negatives = []
zeroes = []
for i in integers:
if i > 0:
positives.append(i)
elif i < 0:
negatives.append(i)
else:
zeroes.append(i)
print(round(decimal.Decimal(len(positives) / len(integers)),6))
print(round(decimal.Decimal(len(negatives) / len(integers)),6))
print(round(decimal.Decimal(len(zeroes) / len(integers)),6))
if __name__ == '__main__':
plus_minus([1,1,-1,-1,0])
| true |
7442c70c3dbfe40a7197132fc75b1a5c250d30a4 | uzairkhan0102/Hacker_Rank_Prob_Sol | /Birthday Cake Candles.py | 1,629 | 4.3125 | 4 |
'''
You are in charge of the cake for a child's birthday.
You have decided the cake will have one candle for each year of their total age.
They will only be able to blow out the tallest of the candles.
Count how many candles are tallest.
Example
candles = [4,4,1,3]
The maximum height candles are 4 units high. There are 2 of them, so return 2.
Function Description
Complete the function birthdayCakeCandles in the editor below.
birthdayCakeCandles has the following parameter(s):
int candles[n]: the candle heights
Returns
int: the number of candles that are tallest
Input Format
The first line contains a single integer, n, the size of candles[].
The second line contains n space-separated integers,
where each integer i describes the height of candles[i].
Constraints
Sample Input 0
4
3 2 1 3
Sample Output 0
2
Explanation 0
Candle heights are [3,2,1,3] . The tallest candles are 3 units,
and there 2 of them.
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the birthdayCakeCandles function below.
def birthdayCakeCandles(ar):
max1 = 0
count = 0
for i in range(0,len(ar)):
if max1 < ar[i]:
max1 = ar[i]
for i in range(0,len(ar)):
if max1 == ar[i]:
count = count+1
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
ar_count = int(input())
ar = list(map(int, input().rstrip().split()))
result = birthdayCakeCandles(ar)
fptr.write(str(result) + '\n')
fptr.close()
| true |
b5eaa2ab33908cd0836ea4f6794391ca9a7aafec | Harshit-09/Rental-System | /Submitty_Problem_Sets/Set-2/factor.py | 901 | 4.25 | 4 |
import math
# Function to calculate sum
# of all divisors of given
# natural number
def divSum(n) :
# Final result of summation
# of divisors
result = 0
# find all divisors which
# divides 'num'
for i in range(2,(int)(math.sqrt(n))+1) :
# if 'i' is divisor of 'n'
if (n % i == 0) :
# if both divisors are same
# then add it only once
# else add both
if (i == (n/i)) :
result = result + i
else :
result = result + (i + n//i)
# Add 1 and n to result as above
# loop considers proper divisors
# greater than 1.
return (result + n + 1)
# Driver program to run the case
n = int(input("\nenter number::"))
print("result is::",divSum(n)) | true |
5e4197b11dd78733e9ba06ec0583625d4d3a3bf5 | Harshit-09/Rental-System | /Submitty_Problem_Sets/Set-1/Performance.py | 518 | 4.125 | 4 | num1 = input('Enter first number:')
num2 = input('Enter second number:')
addition = float(num1)+float(num2)
subtraction = float(num1)-float(num2)
multiplication = float(num1)*float(num2)
division = float(num1)/float(num2)
print('The sum of {0} and {1} is {2}'.format(num1,num2,addition))
print('The subtraction of {0} and {1} is {2}'.format(num1,num2,subtraction))
print('The multiplication of {0} and {1} is {2}'.format(num1,num2,multiplication))
print('The division of {0} and {1} is {2}'.format(num1,num2,division)) | true |
e7df5afb0be23661c75b779f2fb341acaf36efda | AbeerRao/PasswodGenerator | /main.py | 1,507 | 4.28125 | 4 | import random
import pyperclip
import string
#* The function to generate random strings
def get_random_string():
letters = string.ascii_letters
result_str = ''.join(random.choice(letters) for i in range(1))
return result_str
#* The function to generate random numbers
def get_random_number():
result_num = random.randint(0, 10)
return result_num
#* The function to generate random characters
def get_random_character():
charactersAllowed = ["'", "|", "<", ">", "(", ")", "[", "]", "{", "}", ",", ".", "/", "?", "`", "~"]
result_char = random.choice(charactersAllowed)
return result_char
#* The function to generate password
def generate_password():
print()
result_password = ""
#? How many digits
digits = int(input("How long do you want to generate a password? "))
#* Random sequence
SEL = [1, 2, 3]
for digit in range(digits):
thing = random.choice(SEL)
if thing == 1:
result_password += get_random_character()
elif thing == 2:
result_password += str(get_random_number())
elif thing == 3:
result_password += get_random_string()
#? Is the password OK
print()
print(result_password)
print()
POK = input("Is the above password OK? (y/n): ")
if POK == "y":
pyperclip.copy(result_password)
print()
print("Password copied to clipboard!")
elif POK == "n":
generate_password()
#* Calling the function
generate_password() | true |
6407f552b6239965c4e0579e14774a9aa36030dc | Hetchie/python-stuff | /make_your_own_spiral/make_your_own_spiral.py | 470 | 4.1875 | 4 | # make your own spiral
import turtle
import tkSimpleDialog
t = turtle.Pen()
turtle.bgcolor ("black")
t.speed(0)
colors = ["red", "blue", "green", "orange", "yellow", "purple", "gold", "pink"]
sides = tkSimpleDialog.askinteger ("number of sides",
"enter in how many sides you want 1-8" )
for x in range (360):
t.pencolor (colors [x%sides])
t.forward(x * 3 / sides + x)
t.left(360 / sides + 1)
q=input("press close to exit") | true |
8c4f2167a1d902f411dcff5b4e0132ae4bc29359 | JetCr4b07/aliens | /Alien.py | 2,148 | 4.15625 | 4 | import pygame
import random
class Alien(pygame.sprite.Sprite):
# class level variables
speed = 13
animation_cycle = 12
# this is the animation of the alien on the screen
images = []
def __init__(self, screen_rectangle):
"""
this is the constructor! Gets called when class is initialized
"""
pygame.sprite.Sprite.__init__(self, self.containers)
# this is our game screen
# instance variable
# https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3
self.SCREENRECT = screen_rectangle
# size the alien game object by using the first
# image in the collection
self.image = self.images[0]
self.rect = self.image.get_rect()
# determine which direction the alien will face/travel when
# it first appears on screen
self.direction_factor = random.choice((-1, 1))
self.x_velocity = self.direction_factor * self.speed
self.frame = 0
if (self.x_velocity < 0):
# if we're facing in a negative direction
# let's start from the right-hand side
self.rect.right = self.SCREENRECT.right
def update(self):
# let's move the alien left or right!!
self.rect.move_ip(self.x_velocity, 0)
# if alien is not on screen!
if not self.SCREENRECT.contains(self.rect):
# the alien has gone off screen,
# let's make it come back on screen
self.x_velocity = -self.x_velocity
# let's drop the alien by the height of one alien
# image to get closer to tank
self.rect.top = self.rect.bottom + 1
# this adds alien space ship rectangle back into rectangle \
# SCREENRECT
self.rect = self.rect.clamp(self.SCREENRECT)
self.frame = self.frame + 1
# flooring division:\
# https://stackoverflow.com/questions/1535596/what-is-the-reason-for-having-in-python
# 4.0 // 1.5 => 2.0
self.image = self.images[self.frame//self.animation_cycle % 3]
| true |
7656b5f17a81bc417d37fb3d5ecddb497ace80fa | allertjan/LearningCommunityBasicTrack | /week 2/assignment 2 .py | 1,635 | 4.375 | 4 | import math
def time_calculation(distance_to_travel, speed, extra_time1):
time_hours = (distance_to_travel // speed)
rest_hours = (distance_to_travel % speed)
time_minutes = (rest_hours // (speed / 60)) + extra_time1
rest_minutes = (rest_hours % (speed / 60))
time_seconds = math.ceil((rest_minutes / (speed / 3600)))
print("The travel time will be", time_hours, "hours", time_minutes, "minutes", time_seconds, "seconds")
car_dictionary = {
"distance": "time(in minutes)",
80: 60,
160: 120,
}
print("The transportation mode options are: Car,Bike and Walking. You can also add other type of transportation modes"
" by typing \"add\"")
transportation = str.lower(input("Which transportation mode will you be using?"))
if transportation == "add":
speed_new_transportation_mode = int(input("What is the speed of the new transportation mode? Speed:"))
distance = int(input("What is the distance to your destination?"))
extra_time = int(input("How many extra time do you expect you will need?(minutes)"))
if transportation == "car":
if distance in car_dictionary:
print("The travel time will be", str((car_dictionary[distance] + extra_time)), "minutes.")
else:
time_calculation(distance, 80, extra_time)
elif transportation == "add":
time_calculation(distance, speed_new_transportation_mode, extra_time)
elif transportation == "bike":
time_calculation(distance, 20, extra_time)
elif transportation == "walking":
time_calculation(distance, 5, extra_time)
else:
print("Please select one of the following transportation modes: Car,Bike,Walking or add")
| true |
35ddf06c220a7c0ca024dcf7c895a22e517ae9ae | sujeet05/python-code | /lesson24.py | 247 | 4.125 | 4 | i=0
elements =[]
while i < 6 :
print " inserting the element in list %d" %i
elements.append(i)
i=i+1
print " Before going for next iteration value of i %d" %i
print "print the list"
for num in elements:
print "List elements :%d" %num | true |
32b5f0fbacdac6c6e164f730c43cd4de3914476b | kberz/Python-greta | /Note sur 20.py | 379 | 4.125 | 4 | note = int(input("ENTREZ une note sur 20: "))
if note <= 10:
print("Vous n'avez pas eu votre bac :/")
elif note >= 16 and note < 20:
print("Vous avez eu mention très bien")
elif note >= 12 and note < 14:
print("Vous avez eu mention assez bien")
elif note >= 14 and note < 16:
print("Vous avez eu mention bien")
else :
print("vous essayez de tricher ?")
| false |
46b9e70d191b20ec84fbbfd97ac2cd11bf175a9d | encodingForBetterWorld/leetcode | /easy/IsomorphicStrings.py | 989 | 4.15625 | 4 | # Given two strings s and t, determine if they are isomorphic.
#
# Two strings are isomorphic if the characters in s can be replaced to get t.
#
# All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
#
# For example,
# Given "egg", "add", return true.
#
# Given "foo", "bar", return false.
#
# Given "paper", "title", return true.
def isIsomorphic(s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
d1 = {}
d2 = {}
count = 0
while count < len(s):
ch1 = s[count]
ch2 = t[count]
if d1.has_key(ch1) and d1.get(ch1) != ch2:
return False
if d2.has_key(ch2) and d2.get(ch2) != ch1:
return False
d1[ch1] = ch2
d2[ch2] = ch1
count += 1
return True
print isIsomorphic("eggeg","addad") | true |
620ca6c5ace53d3706a7889816b9f6f7358ac2cb | JUSTICE856/Lab-07-conditionals | /spanish.py | 228 | 4.125 | 4 | E = input("give me a word in English between cat, dog, or horse")
if E == "cat" || E == "Cat") || E == "CAT":
print("gato")
elif (E =="dog" || E == "Dog" || E == "DOG":
print("perro")
else:
print("no entiendo")
| false |
b83e2b73002b451ee810def1ef75f18cefd6d2d8 | parshanth2021/Python_Hacktoberfest2021 | /elseif.py | 362 | 4.1875 | 4 | # code with harry if else practice
Age= int(input("Enter your age= "))
if Age<18:
print("you are under 18, you can't drive")
elif Age==18:
print("you are 18, we will consider after examination you can drive or not")
elif Age<7:
print("not a valid age")
elif Age>100:
print("not a valid age")
else :
print("you can drive")
| true |
836374c5e9dd0ae5826514dadfcf50eb09634844 | VamsiKumarK/Practice | /_00_Assignment_Programs/_01_DataStructures/_03_List/_01_Sum_of_elements.py | 619 | 4.15625 | 4 | '''
Created on Nov 12, 2019
@author: Vamsi
'''
'''adding elements in a list'''
total = 0
marks = [30, 40, 55, 100, 46, 90]
print('marks :', marks)
for each in range(0, len(marks)): # Iterating through the range of list
total = total + marks[each]
print('sum of subjects in marks is', total)
'''print(sum(marks)) # Adding elements in list using sum() function.'''
'''
Adding elements in a list using for loop
'''
total = 0
marks = [30, 40, 55, 100, 46, 90]
print('marks :', marks)
for each in marks: # Iterating through the range of list
total += each
print('sum of subjects in marks is', total)
| true |
ea6b1c0a042dd7e0a2dbcda9790d8288214d4dea | VamsiKumarK/Practice | /_02_Operators/_02_03_max_num.py | 367 | 4.21875 | 4 | '''
Created on Nov 2, 2019
@author: User
'''
'''
Finding a maximum number
'''
num1 = int(input('enter a value '))
num2 = int(input('enter a value '))
num3 = int(input('enter a value '))
if num1 > num2 and num1 > num3:
print('num1 is maximum number')
elif num2 > num1 and num2 > num3:
print('num2 is maximum number')
else:
print('num3 is maximum number')
| true |
f5a5e621126e40b887bb5a7aa45368a47f71690c | VamsiKumarK/Practice | /_00_Assignment_Programs/_01_DataStructures/_03_List/_02_Multiply_elements.py | 726 | 4.28125 | 4 | '''
Created on Nov 12, 2019
@author: Vamsi
'''
'''
Multiplying elements of a list
'''
result = 1 # Instialising result to zero
points = [3, 4, 44, 57, 78]
print('points: ', points)
for unit in range(0, len(points)):
result = result * points[unit]
print('Multiplication of units in points is ', result)
print('_____________')
'''
finding maximunm number from the given list
'''
data = [3, 4, 44, 57, 78]
print('Given data is: ', data)
print('maximum number from the given data is: ', max(data))
print('_____________')
'''
Finding minimum number in the given list
'''
data = [3, 4, 44, 57, 78, 3]
print('Given data is: ', data)
print('minimum number from the given data is: ', min(data))
print('_____________')
| true |
87d166e605c7cd06ce2e42a7ac9e06da26402742 | VamsiKumarK/Practice | /_00_Assignment_Programs/_01_DataStructures/_03_List/_09_RemovingEvenElements.py | 761 | 4.28125 | 4 | '''
Created on Nov 13, 2019
@author: Vamsi
'''
'''
Removing even elements in a list using for loop
'''
score = [12, 77, 44, 54, 92, 76, 88]
score1 = []
print('Given numbers in the list: ', score)
for each in score:
score1.append(each)
for each in score1:
if each % 2 == 0: # finding even numbers in the loop
score1.remove(each)
print('Numbers with out even numbers: ', score1)
print('_________________________________________')
'''
Removing even elements in a list using range
'''
'''score = [12, 54, 79, 43, 55, 98, 77, 88]
print('Given numbers in the list: ', score)
for each in range(len(score)):
if score[each] % 2 == 0:
score.pop(each)
print('Numbers with out even numbers: ', score)
'''
| false |
63a07e484ec8611b8ca30deff6c14b9fb9a6c272 | VamsiKumarK/Practice | /_04_Control_statements/_04_01_while_loop.py | 361 | 4.21875 | 4 |
'''
basic while loop
'''
count = 1
while count <= 10:
print(count)
count += 1
print('The End')
'''
printing even numbers between 100 and 200
'''
x = 100
while x >= 100 and x <= 200:
print(x)
x += 2
print('hello')
print('______________________')
'''for loop'''
sum1 = 0
for val in range(1, 6):
sum1 = sum1 + val
print(sum1)
print('end')
| true |
8edaacc2a4f7301f37109a61450c8c4f95a6af50 | VamsiKumarK/Practice | /_00_Assignment_Programs/_02_Functions/_08_MaxOfThreeNumbers.py | 524 | 4.28125 | 4 | '''
Created on Nov 21, 2019
@author: Vamsi
'''
'''
Finding maximum of three numbers
'''
age1 = int(input('Enter the First number: '))
age2 = int(input('Enter the Second number: '))
age3 = int(input('Enter the Third number: '))
def large(a, b, c):
if a > b and a > c:
return a
elif b > a and b > c:
return b
else:
return c
# print('the maximum number is: ', large(age1, age2, age3))
max_num = large(age1, age2, age3)
print('The maximum number from the given three is: ', max_num)
| true |
1892bc344576480d7e61c02e468bf7aaf07bd3a3 | jupiterhub/learn-python-the-hard-way | /lpthw-part1/ex5.py | 637 | 4.15625 | 4 | name = 'Jupiter Tecson'
age = 30 # not a lie
height = 168 # cm
weight = 70.6 # kilos
eyes = "Brown" # double quotes is also fine
teeth = 'White'
hair = 'Black'
# f"String {variable_name}", f on the front says to format
print(f"Let's talk about {name}")
print(f"He's {height}cm tall.")
print(f"He's {weight}kg heavy.")
print(f"Actually that's not too heavy.")
print(f"He's got {eyes} eyes and {hair} hair.")
print(f"His teeth are usually {teeth} depending on the coffee")
# this line is tricky, try to get it exactly right
total = age + height + weight
# use round function
print(f"If i add {age}, {height}, and {weight} I get {round(total)}")
| true |
b758311d5e11f97e85a402104ef53d8f5b963ce2 | jupiterhub/learn-python-the-hard-way | /lpthw-part4/ex34.py | 289 | 4.21875 | 4 | # Accessing list elements
animals = ['bear', 'python3.6', 'peacock', 'kangaroo',
'whale', 'platypus']
# index 0 is called cardinal numbers (because you can get in random)
# index 1 is called ordinal (this is how humans use it, ie. imagine a race)
print(animals[0])
print(animals[5])
| true |
cdb5f8609c752e42faa8e895e1dfffb5bbe25012 | nithinprasad94/6.00-Intro-to-CS | /Week-2/ps1a.py | 1,485 | 4.375 | 4 | #Program: ps1a.py
#FUNCTION DEFINITIONS:
def annual_interest_computer(balance,interest_rate,monthly_rate):
total_paid = 0
for i in range(1,13):
print "Month: ",i
(monthly_payment,principle_paid,new_balance) = monthly_interest_computer(balance,interest_rate,monthly_rate)
total_paid += (monthly_payment)
print "Minimum monthly payment: $",monthly_payment
print "Principle paid: $",principle_paid
print "Remaining balance: $",new_balance
balance = balance - principle_paid
print "RESULT"
print "Total amount paid: $",total_paid
print "Remaining balance: $",balance
def monthly_interest_computer(balance,interest_rate,monthly_rate):
interest_on_balance = balance*interest_rate/12
monthly_payment = '%.2f' % round(balance*monthly_rate, 2)
principle_paid = '%.2f' % round((float(monthly_payment)-interest_on_balance), 2)
new_balance = '%.2f' % round(balance-float(principle_paid), 2)
return (float(monthly_payment),float(principle_paid),float(new_balance))
#MAIN PROGRAM:
#Get input from user
balance = raw_input("Enter the outstanding balance on your credit card: ")
interest_rate = raw_input("Enter the annual credit card interest rate as a decimal: ")
monthly_rate = raw_input("Enter the minimum monthly payment rate as a decimal: ")
annual_interest_computer(float(balance),float(interest_rate),float(monthly_rate))
| true |
cc93906d57ad40d1aec3256a08479f8e65b0b26d | daviddiezpuntocero/coursera | /6.00.1x_IntroductionToComputerScienceAndProgramming/FinalExam/Frob.py | 2,081 | 4.21875 | 4 | class Frob(object):
def __init__(self, name):
self.name = name
self.before = None
self.after = None
def setBefore(self, before):
# example: a.setBefore(b) sets b before a
self.before = before
def setAfter(self, after):
# example: a.setAfter(b) sets b after a
self.after = after
def getBefore(self):
return self.before
def getAfter(self):
return self.after
def myName(self):
return self.name
def insert(atMe, newFrob):
if (atMe.myName() > newFrob.myName()):
if (atMe.getBefore() == None):
atMe.setBefore(newFrob)
newFrob.setAfter(atMe)
elif (atMe.getBefore().myName() <= newFrob.myName()):
ob = atMe.getBefore()
atMe.setBefore(newFrob)
newFrob.setAfter(atMe)
newFrob.setBefore(ob)
ob.setAfter(newFrob)
else:
insert(atMe.getBefore(), newFrob);
elif (atMe.myName() <= newFrob.myName()):
if(atMe.getAfter() == None):
atMe.setAfter(newFrob)
newFrob.setBefore(atMe)
elif(atMe.getAfter().myName() >= newFrob.myName()):
oa = atMe.getAfter()
atMe.setAfter(newFrob)
newFrob.setBefore(atMe)
newFrob.setAfter(oa)
oa.setBefore(newFrob)
else:
insert(atMe.getAfter(), newFrob)
def findFront(start):
"""
start: a Frob that is part of a doubly linked list
returns: the Frob at the beginning of the linked list
"""
# Your Code Here
print start.myName()
print start.getBefore()
if start.getBefore() == None:
print "returning", start.myName()
return start
else:
return findFront(start.getBefore())
eric = Frob('eric')
andrew = Frob('andrew')
ruth = Frob('ruth')
fred = Frob('fred')
martha = Frob('martha')
insert(eric, andrew)
insert(eric, ruth)
insert(eric, fred)
insert(ruth, martha)
p = Frob('percival')
r = Frob('rupert')
insert(p, r)
# findFront(p)
print findFront(r).myName()
| false |
ea37906c0d92238698f3e42394439fd9b7e11123 | anvia38/Python_coding_mini_challenges | /findPrime.py | 1,029 | 4.125 | 4 |
def findPrimeNum(x):
"""finds the number of prime numbers
below the input"""
# create a list where each entry corresponds to the index-valued number
primes = [True] * x # if x = 10, primes = [True, True, ..., True]
primes[0] = False # 0 is not prime
primes[1] = False # 1 is not prime
# 100 = (5x20), 10x10, (20x5)
for i in range(2,int(x**0.5)+1):
if primes[i] == True:
for j in range(i*i, x, i):
# 2: 4, 6, 8, 10, ..., 100
# 3: 9, 12, 15, 18, 21, 24, 27...
# 4: skip
# 5: 25 (5, 10, 15, 20...?)
# 9 x N = 3 x (3 x N)
primes[j] = False
count = 0
for prime in primes:
if prime == True:
count = count+1
return count
def main():
test = 11# <-enter the number you want to find the number of primes below here
output = findPrimeNum(test)
print(output)
if __name__ == "__main__":
main()
| true |
23c4aa55abb069480b31be50d5c8e85825a720b4 | Dennise1993/Data_Structure_and_Algorithm | /DataStructure/LinkedList_and_Array/even_after_odd.py | 2,558 | 4.21875 | 4 | from linked_list import Node
"""
Problem Statement
Given a linked list with integer value, arrange the elements in such a manner
that all nodes with even numbers are placed after odd numbers.
Do not create any new nodes and avoid using any other value structure.
The relative order of even and odd elements must not change.
Example:
linked list = 1 2 3 4 5 6
output = 1 3 5 2 4 6
"""
def even_after_odd(head):
"""
:param - head - head of linked list
return - updated list with all even elements are odd elements
Author: Zhijin Li (lizhijin1993@gmail.com)
"""
odd = None
odd_tail = None
even = None
even_tail = None
while head:
if head.value % 2 == 0: # even
if even == None:
even = head
even_tail = even
else:
even_tail.next = head
even_tail = even_tail.next
else: # odd
if odd ==None:
odd = head
odd_tail = odd
else:
odd_tail.next = head
odd_tail = odd_tail.next
temp = head.next
head.next = None
head = temp
if odd == None:
return even
odd_tail.next = even
return odd
# helper functions for testing purpose
def create_linked_list(arr):
if len(arr)==0:
return None
head = Node(arr[0])
tail = head
for value in arr[1:]:
tail.next = Node(value)
tail = tail.next
return head
def print_linked_list(head):
while head:
print(head.value, end=' ')
head = head.next
print()
def test_function(test_case):
head = test_case[0]
solution = test_case[1]
node_tracker = dict({})
node_tracker['nodes'] = list()
temp = head
while temp:
node_tracker['nodes'].append(temp)
temp = temp.next
head = even_after_odd(head)
temp = head
index = 0
try:
while temp:
if temp.value != solution[index] or temp not in node_tracker['nodes']:
print("Fail")
return
temp = temp.next
index += 1
print("Pass")
except Exception as e:
print("Fail")
# Test case 1
arr = [1, 2, 3, 4, 5, 6]
solution = [1, 3, 5, 2, 4, 6]
head = create_linked_list(arr)
test_case = [head, solution]
test_function(test_case)
# Test case 2
arr = [1, 3, 5, 7]
solution = [1, 3, 5, 7]
head = create_linked_list(arr)
test_case = [head, solution]
test_function(test_case)
# Test case 3
arr = [2, 4, 6, 8]
solution = [2, 4, 6, 8]
head = create_linked_list(arr)
test_case = [head, solution]
test_function(test_case) | true |
08e93144b7299f7235159ed9fad4f1082049bd33 | idobleicher/pythonexamples | /examples/hashable_examples/hash_example_2.py | 837 | 4.34375 | 4 | # However, mutable objects such as lists and dictionaries do not have a hash method.
# That is one of the reasons why you cannot use that kind of objects as keys for dictionaries.
# What is important to note is that for immutable types, the hash value depends only on the data stored and
# not on the identity of the object itself.
# For instance, you can create two tuples with the same values, and see the differences:
var1 = (1, 2, 3)
var2 = (1, 2, 3)
print(id(var1))
print(id(var2))
#They are indeed different objects, however hash will return the same:
print(var1.__hash__())
print(var2.__hash__())
# This means that if you use them as dictionary keys, they are going to be
# indistinguishable (not able to be identified as different or distinct) from each other, for instance:
var3 = {var1: 'var1'}
print(var3[var2])
#var1
| true |
2512626a0ecd613b7fd9fe6ded9bf398a4e24780 | idobleicher/pythonexamples | /examples/misc/get_attribute_example.py | 1,346 | 4.59375 | 5 | #The getattr() method returns the value of the named attribute of an object.
# If not found, it returns the default value provided to the function.
# The syntax of getattr() method is:
#
# getattr(object, name[, default])
# The above syntax is equivalent to:
#
# object.name
# #getattr() Parameters
# The getattr() method takes multiple parameters:
#
# object - object whose named attribute's value is to be returned
# name - string that contains the attribute's name
# default (Optional) - value that is returned when the named attribute is not found
# Return value from getattr()
# The getattr() method returns:
#
# value of the named attribute of the given object
# default, if no named attribute is found
# AttributeError exception, if named attribute is not found AND default is not defined
#Example 1: How getattr() works in Python?
class Person:
age = 23
name = "Adam"
person = Person()
print('The age is:', getattr(person, "age"))
print('The age is:', person.age)
#The age is: 23
#The age is: 23
#Example 2: getattr() when named attribute is not found
class Person:
age = 23
name = "Adam"
person = Person()
# when default value is provided
print('The sex is:', getattr(person, 'sex', 'Male'))
#The sex is: Male
# when no default value is provided
#print('The sex is:', getattr(person, 'sex'))
#AttributeError
| true |
cc693c4df66e7ab9238bf9c01133b1a41dd072e4 | idobleicher/pythonexamples | /examples/data-types-basic/list_slice.py | 1,732 | 4.65625 | 5 |
# List slices provide a more advanced way of retrieving values from a list.
# Basic list slicing involves indexing a list with two colon-separated integers.
# This returns a new list containing all the values in the old list between the indices.
# Slicing can also be done on tuples.
nums = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
print(nums[2:6])
# [[12, 13, 14, 15] #0th - to 6th
print(nums[3:8])
# [13, 14, 15, 16, 17] #3th to 7th
print(nums[0:1])
#[10] - 0th
print("--------------")
# If the first number in a slice is omitted, it is taken to be the start of the list.
print(nums[:7])
# [10, 11, 12, 13, 14, 15, 16]
# If the second number is omitted, it is taken to be the end.
print(nums[7:])
# [17, 18, 19]
print("--------------")
# List slices can also have a third number, representing the step,
# to include only alternate values in the slice.
print(nums[::2])
# [10, 12, 14, 16, 18]
print(nums[2:8:3])
# [2:8:3] will include elements starting from the 2nd index up to the 8th with a step of 3.
# [12, 15]
print("!!--------------")
squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
print(squares[1::4])
#[1, 25, 81]
print("!!!--------------")
# Negative values can be used in list slicing (and normal list indexing).#
# When negative values are used for the first and second values in a slice (or a normal index),
# they count from the end of the list.
print("~~--------------")
print(nums[1:-1])
# [11, 12, 13, 14, 15, 16, 17, 18] #1th to len-1
print("~~--------------")
# If a negative value is used for the step, the slice is done backwards.
# Using [::-1] as a slice is a common and idiomatic way to reverse a list.
print(squares[7:5:-1])
#[49, 36]
print(squares[::-1])
#[81, 64, 49, 36, 25, 16, 9, 4, 1, 0]
| true |
2906e4eedf12510b2936a91e51b09b45ecbf0775 | idobleicher/pythonexamples | /examples/regular_expression/re_example_groups.py | 1,113 | 4.8125 | 5 | #A group can be created by surrounding part of a regular expression with parentheses.
#This means that a group can be given as an argument to metacharacters such as * and ?.
import re
#(spam) represents a group in the example.
pattern = r"egg(spam)*"
if re.match(pattern, "egg"):
print("Match 1")
#Match 1
if re.match(pattern, "eggspamspamspamegg"):
print("Match 2")
#Match 2
if re.match(pattern, "spam"):
print("Match 3")
#'([^aeiou][aeiou][^aeiou])+ match vOne or more repetitions of a non-vowel, a vowel and a non-vowel
# #The content of groups in a match can be accessed using the group function.
# A call of group(0) or group() returns the whole match.
# A call of group(n), where n is greater than 0, returns the nth group from the left.
# The method groups() returns all groups up from 1.
pattern = r"a(bc)(de)(f(g)h)i"
match = re.match(pattern, "abcdefghijklmnop")
if match:
print(match.group())
#abcdefghi
print(match.group(0))
#abcdefghi
print(match.group(1))
#bc
print(match.group(2))
#de
print(match.groups())
#('bc', 'de', 'fgh', 'g') | true |
8854b3dfc4781a34a423b23adf16ef98cdfb8327 | idobleicher/pythonexamples | /examples/control-structures/else_with_loops.py | 1,240 | 4.5 | 4 | # The else statement is most commonly used along with the if statement,
# but it can also follow a for or while loop, which gives it a different meaning.
# With the for or while loop, the code within it is called if the loop finishes normally
# (when a break statement does NOT cause an exit from the loop).
for i in range(10):
if i == 999:
break
else:
print("Unbroken 1")
for i in range(10):
if i == 5:
break
else:
print("Unbroken 2")
# Unbroken 1
# The first for loop executes normally, resulting in the printing of "Unbroken 1".
# The second loop exits due to a break, which is why it 's else statement is not executed.
for i in range(10):
if i > 5:
print(i)
break
else:
print("7")
# out-6
# The else statement can also be used with try/except statements.
# In this case, the code within it is only executed if no error occurs in the try statement.
# Example:
try:
print(1)
except ZeroDivisionError:
print(2)
else:
print(3)
try:
print(1/0)
except ZeroDivisionError:
print(4)
else:
print(5)
# 1
# 3
# 4
print ("-------------")
try:
print(1)
print(1 + "1" == 2)
print(2)
except TypeError:
print(3)
else:
print(4)
#1
#3 (4 not printed
| true |
912b29ac96f9413c8f34298d17c1a86410cb2a60 | idobleicher/pythonexamples | /examples/threads_examples/threads_synchronizing.py | 1,928 | 4.15625 | 4 | # Synchronizing Threads
#In addition to using Events, another way of synchronizing threads is through using a Condition object.
# Because the Condition uses a Lock, it can be tied to a shared resource.
# This allows threads to wait for the resource to be updated.
# In this example, the consumer() threads wait() for the Condition to be set before continuing.
# The producer() thread is responsible for setting the condition and notifying the other threads that they can continue.
import logging
import threading
import time
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s (%(threadName)-2s) %(message)s',
)
def consumer(cond):
"""wait for the condition and use the resource"""
logging.debug('Starting consumer thread')
t = threading.currentThread()
with cond:
cond.wait()
logging.debug('Resource is available to consumer')
def producer(cond):
"""set up the resource to be used by the consumer"""
logging.debug('Starting producer thread')
with cond:
logging.debug('Making resource available')
cond.notifyAll()
condition = threading.Condition()
c1 = threading.Thread(name='c1', target=consumer, args=(condition,))
c2 = threading.Thread(name='c2', target=consumer, args=(condition,))
p = threading.Thread(name='p', target=producer, args=(condition,))
c1.start()
time.sleep(2)
c2.start()
time.sleep(2)
p.start()
# #The threads use with to acquire the lock associated with the Condition. Using the acquire() and release() methods explicitly also works.
#
# 2013-02-21 06:37:49,549 (c1) Starting consumer thread
# 2013-02-21 06:37:51,550 (c2) Starting consumer thread
# 2013-02-21 06:37:53,551 (p ) Starting producer thread
# 2013-02-21 06:37:53,552 (p ) Making resource available
# 2013-02-21 06:37:53,552 (c2) Resource is available to consumer
# 2013-02-21 06:37:53,553 (c1) Resource is available to consumer
| true |
a2484c6deb981dc7f30230a3e7ff06b5aea75528 | idobleicher/pythonexamples | /examples/functional-programming/itertools_examples/itertools_zip_longest.py | 543 | 4.125 | 4 | # zip_longest( iterable1, iterable2, fillval.) :
# - This iterator prints the values of iterables alternatively in sequence.
# If one of the iterables is printed fully, remaining values are filled by the values assigned to fillvalue.
import itertools
# using zip_longest() to combine two iterables.
print ("The combined values of iterables is : ")
print (*(itertools.zip_longest('GesoGes','ekfrek',fillvalue='_' )))
# The combined values of iterables is :
# ('G', 'e') ('e', 'k') ('s', 'f') ('o', 'r') ('G', 'e') ('e', 'k') ('s', '_')
| true |
32b981379b347e1741c8d9efad8cd48d3c654872 | idobleicher/pythonexamples | /examples/functional-programming/map_example.py | 797 | 4.40625 | 4 | # The built-in functions map and filter are very useful higher-order functions that operate on
# lists (or similar objects called iterables).
#The function map takes a function and an iterable as arguments, and returns a new iterable with the function applied to each argument.
def add_five(x):
return x + 5
nums = [11, 22, 33, 44, 55]
result = list(map(add_five, nums))
print(result)
#[16, 27, 38, 49, 60]
#We could have achieved the same result more easily by using lambda syntax
#To convert the result into a list, we used list explicitly.
result = list(map(lambda x: x+5, nums))
print(result)
#[16, 27, 38, 49, 60]
def multiply2(x):
return x * 2
print(list(map(multiply2, [1, 2, 3, 4])))
# Output [2, 4, 6, 8]
print(list(map(lambda x : x*2, [1, 2, 3, 4])))
#Output [2, 4, 6, 8] | true |
24410fdceceb9aa9e047a220621668745089a236 | idobleicher/pythonexamples | /examples/generators/generators_example.py | 1,515 | 4.625 | 5 |
# Generators are a type of iterable, like lists or tuples.
#Unlike lists, they don't allow indexing with arbitrary indices, but they can still be iterated through with for loops.
#They can be created using functions and the yield statement.
#In short, generators allow you to declare a function that behaves like an iterator, i.e. it can be used in a for loop.
# Using generators results in improved performance, which is the result of the lazy (on demand) generation of values,
# which translates to lower memory usage.
# Furthermore, we do not need to wait until all the elements have been generated before we start to use them.
def countdown():
i = 5
while i > 0:
yield i
i -= 1
for i in countdown():
print(i)
# 5
# 4
# 3
# 2
# 1
# Due to the fact that they yield one item at a time, generators don't have the memory restrictions of lists.
# In fact, they can be infinite!
#
# def infinite_sevens():
# while True:
# yield 7
#
# for i in infinite_sevens():
# print(i)
#Finite generators can be converted into lists by passing them as arguments to the list function
def numbers(x):
for i in range(x):
if i % 2 == 0:
yield i
print(list(numbers(11)))
#[0, 2, 4, 6, 8, 10]
def make_word():
word = ""
for ch in "spam":
word +=ch
yield word
print(list(make_word()))
#['s', 'sp', 'spa', 'spam'] | true |
fb37e723da8e38a83973d3520ac47362b058437e | idobleicher/pythonexamples | /examples/generators/display_average.py | 1,590 | 4.15625 | 4 | import random
def get_data():
"""Return 3 random integers between 0 and 9"""
return random.sample(range(10), 3)
def consume():
"""Displays a running average across lists of integers sent to it"""
running_sum = 0
data_items_seen = 0
while True:
#data is following the consumer.send(data)
data = yield
print('In consumer. data {}'.format(data))
data_items_seen += len(data)
running_sum += sum(data)
print('The running average is {}'.format(running_sum / float(data_items_seen)))
def produce(consumer):
"""Produces a set of values and forwards them to the pre-defined consumer
function"""
while True:
data = get_data()
print('Produced {}'.format(data))
consumer.send(data)
yield
if __name__ == '__main__':
consumer = consume()
consumer.send(None)
producer = produce(consumer)
for iteration in range(5):
print('Iteration {} Producing...'.format(iteration))
next(producer)
# #Iteration 0 Producing...
# Produced [6, 5, 7]
# In consumer. data [6, 5, 7]
# The running average is 6.0
# Iteration 1 Producing...
# Produced [1, 6, 4]
# In consumer. data [1, 6, 4]
# The running average is 4.833333333333333
# Iteration 2 Producing...
# Produced [6, 4, 5]
# In consumer. data [6, 4, 5]
# The running average is 4.888888888888889
# Iteration 3 Producing...
# Produced [8, 6, 5]
# In consumer. data [8, 6, 5]
# The running average is 5.25
# Iteration 4 Producing...
# Produced [4, 0, 5]
# In consumer. data [4, 0, 5]
# The running average is 4.8 | true |
871463ddc40c31bafe290a71cd2bda87ada96b3e | realucas/pyproject_tlg | /proj1/highlow.py | 762 | 4.15625 | 4 | #!/usr/bin/env python3
"""Ricky Lucas || Making a custom if elif else program"""
import random
ranum1 = random.randint(0,5)
ranum2 = random.randint(0,5)
print(f"Welcome to High or Low!! the current number is: {ranum1} ")
if ranum2 > ranum1:
status = "h"
result = "High"
elif ranum2 < ranum1:
status = "l"
result = "Low"
else:
status = "t"
result = "Tie"
print("Is the next number High, Low or Tie: ")
while (True):
playerinput = input("High: h\n Low: l\n Tie: t\n Answer: ")
print("Invalid entry! Try again!")
if (playerinput == 'h' or 'l' or 't'):
break
print(f"The next number is {ranum2} - {result} ")
if playerinput == status:
message = "You win!"
else:
message = "Lewhewzeher!"
print(message)
| true |
24800aa2018578405f00b1a33c75de62e187c4d7 | gitRepo2/Project_04_WorkLog | /utility.py | 1,523 | 4.21875 | 4 | import regex
import pytz
import dateutil
import datetime
import pep8
def convert_datetime_to_utc(date_input):
"""Takes a string like 03/03/2018 information and localizes it with
pytz to 'Europe/Paris' and returns utc."""
parsed_datetime = datetime.datetime.strptime(date_input, '%m/%d/%Y')
local_date = pytz.timezone('Europe/Paris').localize(parsed_datetime)
utc_date = local_date.astimezone(pytz.utc)
return utc_date
def convert_utcdate_to_datestring(utc_date):
"""This function take a pytz utc date like:
'2000-03-02 23:00:00+00:00' and converts it to a '03/03/2000'
formated string. This is returned."""
# Parse string to datetime
datetime = dateutil.parser.parse(utc_date)
# Convert date from UTC to local
astimezone_date = datetime.astimezone(pytz.timezone('Europe/Paris'))
# Convert datetime to a date string
return astimezone_date.strftime("%m/%d/%Y")
def convert_minutes_time_format(input):
"""This function converts input argument minutes to hours and minutes to
a printable format. This information is returned a string like this:
xx Hours xx Minutes (=> xxx Minutes)"""
if isinstance(input, int):
pass
else:
raise ValueError("The argument could not be converted to an int.")
hours, minutes = input // 60, input % 60
output = str(hours) + ' Hours ' + str(minutes) + ' Minutes'
output += ' (=> ' + str(input) + ' Minutes)'
return output
checker = pep8.Checker('utility.py')
checker.check_all()
| true |
ea5783ee945864fdec93a2eb6f0068a2307dbd88 | bashby2/python_fundamentals | /python_fundamentals/odd_even.py | 333 | 4.46875 | 4 | # Create a function that counts from 1 to 2000. As it loops through each number, have your program generate the number and specify whether it's an odd or even number.
for i in range (1, 2001):
if i % 2 != 0:
print "Number is {}. The number is odd".format(i)
else:
print "Number is {}. The number is even.".format(i)
| true |
82b91d19563cf40b57da17a4342ad4d3651958e3 | k1lv1n/comp_math | /task7.py | 2,672 | 4.125 | 4 | """
Решение задачи 7.
"""
import numpy as np
import matplotlib.pyplot as plt
def f(x:float,R:np.ndarray) -> np.ndarray:
"""
Работает с вектором r = { x, x', y , y'}
"""
# return some function result
r_1 = np.sqrt((R[0]+mu)**2 + R[2]**2)
r_2 = np.sqrt((R[0]-mu_)**2 + R[2]**2)
tmp_1 = 2*R[3]+R[0]-mu_*(R[0]+mu)/r_1**3 - mu*(R[0]-mu_)/r_2**3 - k*R[1]
tmp_3 = -2*R[1]+R[2]-mu_*R[2]/r_1**3 - mu*R[2]/r_2**3 - k*R[3]
return np.array([R[1],tmp_1,R[3],tmp_3])
def dormand_prince(t_0,R_0,h,N):
"""
https://en.wikipedia.org/wiki/Dormand%E2%80%93Prince_method <- таблица Бутчера
x_0: точка, где заданы функция и производная
Y_0: {y(x_0), y'(x_0)}
"""
t_n = t_0
R_n = R_0.copy()
tes, xes, yes = [],[],[]
tes.append(t_n)
xes.append(R_n[0])
yes.append(R_n[2])
for _ in range(N):
k_1 = f(t_n, R_n)
k_2 = f(t_n+h/5, R_n+h*k_1/5)
k_3 = f(t_n+3*h/10, R_n+h*k_1*3/40+h*k_2*9/40)
k_4 = f(t_n+4/5*h, R_n+44*h*k_1/55 - 56*h*k_2/15 + 32*h*k_3/9)
k_5 = f(t_n+8/9*h, R_n+19372*h*k_1/6561 - 25360/2187*h*k_2+ 64448/6561*h*k_3 - 212/729*h*k_4)
k_6 = f(t_n+h, R_n+9017/3168*k_1*h - 355/33*k_2*h + 46732/5247*k_3*h +49/176*k_4*h - 5103/18656*h*k_5)
k_7 = f(t_n+h, R_n+35/384*k_1*h +0+ 500/1113*k_3*h + 125/192*k_4*h-2187/6784*k_5*h + 11/84*h*k_6)
# print(k_1, k_2, k_3, k_4, k_5, k_6, k_7)
R_n += h*(35/384*k_1 + 500/1113*k_3 + 125/192*k_4 -2187/6784*k_5 + 11/84*k_6)
t_n += h
tes.append(t_n)
xes.append(R_n[0])
yes.append(R_n[2])
return np.array(tes), xes, yes
mu = 1/82.45
mu_ = 1 - mu
# надо подобрать
t_0 = 0
T = 8
h=0.0005
N = int(T/h)
k=0
r_min = np.inf
res=0
# for i in range(-100000,100000):
# R_0 = np.array([1.2, 0 , -1.05, i/1000])
# tes, xes, yes = dormand_prince(t_0, R_0,h,N)
# r = np.sqrt((xes[0]-xes[len(xes)-1])**2 + (yes[0]-yes[len(yes)-1])**2)
# if r<r_min:
# r_min = r
# res = i/10000
# print(i/10000)
res = -0.1264
R_0 = np.array([1.2, 0 , -1.05, -1.05])
# R_1 = np.array([1.2, 0 , -1.05, -1.1])
# R_2 = np.array([1.2, 0 , -1.05, -1.2])
k =0
tes, xes, yes = dormand_prince(t_0, R_0,h,N)
k=0.1
tes, xes_1, yes_1 = dormand_prince(t_0, R_0,h,N)
k=1
tes, xes_2, yes_2 = dormand_prince(t_0, R_0,h,N)
# plt.scatter(xes_2[0],yes_2[0],s=200)
plt.scatter(xes,yes,s=5)
plt.scatter(xes_1,yes_1,s=5,c = 'r')
plt.scatter(xes_2,yes_2,s=5,c = 'b')
plt.show()
| false |
98cdae6b690131176884cea36435b27159112d7b | luismir20/Python-Programming | /423_HW3_Lists.py | 2,998 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # BUSA423.HW3:Lists
# The purpose of this assignment is working on the list.
# ## Q1. (2 points)
# Fill the ____ parts of the code below.
# In[5]:
# Let's create an empty list
my_list = []
# Let's add some values
my_list.append('Python')
my_list.append('is ok')
my_list.append('sometimes')
# Let's remove 'sometimes'
my_list.remove('sometimes')
# Let's change the second item
my_list[1] = 'is neat'
print(my_list)
# In[ ]:
# ## Q2. (2 points)
# Consider the following list. Write a program to find total and mean of the list.
# In[42]:
list1 = [ i for i in range(1000) if i%3 ==0]
# In[44]:
result = 0.0
mean = 0.0
for i in list1:
result = result + i
mean = result/len(list1)
print(result)
print(mean)
# ## Q3: (2 points)
# Consider the following list. Write a program that stores the reverse of `NumberList` in a new list called `NumberListRevised`.
#
# Hint. Start with the empty list `NumberListRevised` and fill it using the `pop()` function on `NumberList` multiple times.
# In[38]:
NumberList = [i for i in range(11)]
# In[39]:
# write your program here:
NumberListRevised=[]
NumberListRevised.append(NumberList.pop(-1))
NumberListRevised.append(NumberList.pop(-1))
NumberListRevised.append(NumberList.pop(-1))
NumberListRevised.append(NumberList.pop(-1))
NumberListRevised.append(NumberList.pop(-1))
NumberListRevised.append(NumberList.pop(-1))
NumberListRevised.append(NumberList.pop(-1))
NumberListRevised.append(NumberList.pop(-1))
NumberListRevised.append(NumberList.pop(-1))
NumberListRevised.append(NumberList.pop(-1))
NumberListRevised.append(NumberList.pop(-1))
print(NumberListRevised)
# In[ ]:
# ## Q4: (4 points)
# Consider the following list.
# In[40]:
ListofNums = [[0],[1,2,3],[4,5,6,7],[8,9,10]]
# In[8]:
#4.1: Using list indices print the first, then the second and then the third child list.
ListofNums[0:3]
# In[10]:
# 4.2: Using list indices, print out elements 0,3,4,9
print(ListofNums[0][0])
print(ListofNums[1][2])
print(ListofNums[2][0])
print(ListofNums[3][1])
# In[11]:
# 4.3. Replace the object 8 with 88.
ListofNums [3][0]=88
print(ListofNums)
# In[12]:
# 4.4. Append the new child list [11,12,13,14] to the end of the nested list.
ListofNums.append([11,12,13,14])
print(ListofNums)
# In[14]:
# 4.5. Using del function, remove the second child list in the nested list
del ListofNums[1]
print(ListofNums)
# In[32]:
#4.6. Using the remove() function, remoce the elements 4 and 9 rom the nested list
ListofNums = [[0],[1,2,3],[4,5,6,7],[8,9,10]]
ListofNums[2].remove(4)
ListofNums[3].remove(9)
print(ListofNums)
# In[36]:
#4.7. Usingh the in function, check whether the numnber 10 is in any of the child list
for x in ListofNums:
if 10 in x:
print('Yes')
# In[42]:
# 4.8. Using the len() function, determin how many child list are containted in the parent list
print(len(ListofNums))
# In[ ]:
| true |
945b1dad27d3753aacd69eabfda28321c040cc77 | ljy-002/Python.ljy-002 | /enumerate用法.py | 273 | 4.125 | 4 | seasons=['Spring','Summer','Fall','Winter']
list(enumerate(seasons,start=1)) #下标从1开始
#简写为:
#print(list(enumerate(['Spring','Summer','Fall','Winter'],start=1)))
#还可以:
#print(list(enumerate(['Spring', 'Summer', 'Fall', 'Winter'])))
| false |
f8273396fa16a77f7d709f3b42d507926506d32b | bwwheeler/novus-scripting | /csv_duplicate_remover.py | 1,755 | 4.125 | 4 | """
CSV Duplicate Remover
Removes all duplicate values in a given column of a provided CSV file,
and writes the results to a new CSV with a similar name
Input: a CSV file
Output: another CSV file with duplicates removed
"""
import os
import sys
import csv
def open_files(filename):
''' Open input csv and output file (so as not to waste time if it's invalid or locked) '''
try:
input_file = open(filename)
csv_file = csv.reader(input_file)
csv_data = list(csv_file)
input_file.close()
except FileNotFoundError:
print ('File', sys.argv[1], 'does not exist')
exit()
try:
output_file = open(str(sys.argv[1])[:-4] + '_filtered.csv', 'w', newline='')
except FileNotFoundError:
print('File', sys.argv[1], 'not found')
exit()
except PermissionError:
print('Unable to write to', str(sys.argv[1])[:-4] + '_filtered.csv')
exit()
return csv_data, output_file
def find_duplicates(csv_data, column):
''' Check for duplicate values in provided column, and write the row to a new CSV file if it is not a duplicate '''
string_list = []
csv_data_to_write = []
for line in csv_data:
if line[column] not in string_list:
string_list.append(line[column])
csv_data_to_write.append(line)
return csv_data_to_write
def write_csv(csv_data, output_file):
'''Write a new csv using the output file opened earlier'''
output_writer = csv.writer(output_file)
for line in csv_data:
output_writer.writerow(line)
print('File', output_file.name, 'written')
output_file.close()
def main():
csv_data, output_file = open_files(sys.argv[1])
csv_data_to_write = find_duplicates(csv_data, 1)
write_csv(csv_data_to_write, output_file)
if __name__ == "__main__":
main()
| true |
4d328311f58ad227644528f7a7727a8671010bd7 | Noonjik/Homework-3 | /getMin().py | 2,023 | 4.125 | 4 | #Stack implementation
class Stack:
def __init__(self):
self._size = 0
self._storage = []
self.iteration_index=0
def is_empty(self):
return self._size == 0
def push(self, value):
self._storage.append(value)
self._size += 1
def pop(self):
if self.is_empty():
return None
value = self._storage.pop(self._size - 1)
self._size -= 1
return value
def __str__(self):
print_value = 'storage of stack: '
print_value += self._storage.__str__()
print_value += 'stack size: '
print_value += str(self._size)
return print_value
def __iter__(self):
self._list_iterator = iter(self._storage)
return self._list_iterator
def peek(self):
if self.is_empty():
return None
else:
peek = self.pop()
self.push(peek)
return peek
class Min_O1(object):
def __init__(self):
self.main = Stack()
self.mins = Stack()
self._size = 0
self._storage = []
self.peek = self.main.peek()
def push(self,value):
self.main.push(value)
if self.main.is_empty():
self.mins.push(value)
self.main.push(value)
elif value <= int(self.mins.peek()):
self.mins.push(value)
else:
self.mins.push(self.mins.peek())
def pop(self):
if self.main.is_empty():
return None
else:
self.main.pop()
self.mins.pop()
def getMin(self):
if self.main.is_empty():
return None
else:
return self.mins.peek()
#testing
test1 = Min_O1()
test1.push(5)
test1.push(7)
test1.push(8)
test1.push(9)
test1.push(2)
print (test1.getMin())
test1.pop()
test1.pop()
print (test1.getMin())
| false |
d51a76194d43d0e28a4207573763f9f1f16d2b25 | smisra77/Leetcode-Examples | /Reverse Line.py | 764 | 4.1875 | 4 | #Program to reverse the words in file
filen = input("Enter filename: ")
fh = open(filen)
for line in fh:
line = line.rstrip()
words = line.split()
# reverse list of words
# suppose we have list of elements list = [1,2,3,4],
# list[0]=1, list[1]=2 and index -1 represents
# the last element list[-1]=4 ( equivalent to list[3]=4 )
# So, inputWords[-1::-1] here we have three arguments
# first is -1 that means start from last element
# second argument is empty that means move to end of list
# third arguments is difference of steps
words = words[-1::-1]
output = " ".join(words)
print('Reveresed line: ', output)
finaloutput = "".join(reversed(output))
print("Final output: ", finaloutput) | true |
5f3617a0b86b831be54e8f15c097c729820a5ea9 | smisra77/Leetcode-Examples | /word_count.py | 350 | 4.21875 | 4 | #Find word in file and count
word = raw_input("Enter a word: ")
infile = 'input-1.txt'
def word_count(w):
count = 0
with open(infile, 'r') as f:
for w in f.readlines():
count += 1
#print(w)
return count
c = word_count(word)
print ("Total count for word '%s' is: %d" % (word,c))
| true |
1c92ea3c0b5297534fd4a8ac242b6680e864eb22 | vpc20/python-data-structures | /QueuesArray.py | 1,331 | 4.34375 | 4 | ##################################
# Queue implementation using array
##################################
class Queue:
def __init__(self):
self.q = []
def is_empty(self):
return not self.q
def enqueue(self, data):
self.q.append(data)
def dequeue(self):
if self.is_empty():
return None
return self.q.pop(0)
def peek(self):
if self.is_empty():
return None
return self.q[0]
def size(self):
return len(self.q)
def print_list(self):
if self.is_empty():
print('Queue is empty')
else:
print('Queue ==> ', end='')
for item in self.q:
print(item, end=' ')
print('')
q1 = Queue()
q1.dequeue()
q1.print_list()
print('Front of queue is ' + str(q1.peek()))
print('Size of queue is ' + str(q1.size()))
q1.enqueue('a')
q1.enqueue('b')
q1.enqueue('c')
q1.enqueue('d')
q1.enqueue('e')
q1.print_list()
print('Front of queue is ' + str(q1.peek()))
print('Size of queue is ' + str(q1.size()))
print(q1.dequeue() + ' was removed from queue')
print(q1.dequeue() + ' was removed from queue')
print(q1.dequeue() + ' was removed from queue')
q1.print_list()
print('Front of queue is ' + str(q1.peek()))
print('Size of queue is ' + str(q1.size()))
| false |
45d0ddc9132fd88ecac187db4ca79780d27e3205 | vpc20/python-data-structures | /StacksArray.py | 1,356 | 4.1875 | 4 | ##################################
# Stack implementation using array
##################################
class Stack:
def __init__(self):
self.data = []
def is_empty(self):
return not self.data
def push(self, data):
self.data.append(data)
def pop(self):
if not self.is_empty():
return self.data.pop()
def peek(self):
if not self.is_empty():
return self.data[-1]
def size(self):
return len(self.data)
def print_list(self):
if self.is_empty():
print('Stack is empty')
else:
print('=============== Stack ===============')
for i in range(len(self.data) - 1, -1, -1):
print(self.data[i])
print('=========== end of list ==============')
s1 = Stack()
if s1.is_empty():
print('stack is empty')
print(s1.pop())
print(s1.peek())
print(s1.size())
s1.print_list()
s1.push('a')
s1.push('b')
s1.push('c')
s1.push('d')
s1.push('e')
s1.print_list()
print('Data at top of stack is ' + s1.peek())
print('The size of stack is ' + str(s1.size()))
print(s1.pop() + ' was popped from stack')
print(s1.pop() + ' was popped from stack')
print(s1.pop() + ' was popped from stack')
print(s1.pop() + ' was popped from stack')
print(s1.pop() + ' was popped from stack')
s1.print_list()
| false |
12158f326b4a452e443a5010996aa0210eafb990 | vpc20/python-data-structures | /QueuesAsStacks.py | 1,056 | 4.125 | 4 | class Queue:
def __init__(self):
self.stack1 = [] # will hold queue in reverse order
self.stack2 = []
def is_empty(self):
return len(self.stack1) == 0
# return not self.stack1
def enqueue(self, x):
while self.stack1:
self.stack2.append(self.stack1.pop())
self.stack1.append(x)
while self.stack2:
self.stack1.append(self.stack2.pop())
def dequeue(self):
if self.is_empty():
return None
return self.stack1.pop()
def peek(self):
return self.stack1[-1]
if __name__ == '__main__':
q = Queue()
q.enqueue(5)
q.enqueue(9)
q.enqueue(11)
print(q.peek())
print(q.stack1)
print(q.stack2)
print(f'dequeue {q.dequeue()}')
print(q.stack1)
print(q.stack2)
print(f'dequeue {q.dequeue()}')
print(q.stack1)
print(q.stack2)
print(f'dequeue {q.dequeue()}')
print(q.stack1)
print(q.stack2)
print(f'dequeue {q.dequeue()}')
print(q.stack1)
print(q.stack2)
| false |
f1c65e06c70eaba83e2482ac187002617f667e40 | fr334aks/100-days-of-Hacking | /Malw0re/014_Day_Higher_Functions/faap.py | 575 | 4.15625 | 4 | #!/usr/bin/env/python3
# Function as a return value.
def square(x):
return x ** 2 # a square function
def cube(x):
return x ** 3 # a cube function
def absolute(x):
if x >= 0:
return x # an absolute value functions.
else:
return -(x)
def high_order_function(type):
if type == 'absolute':
return square
elif type == 'cube':
return cube
elif type == 'absolute':
return absolute
result = high_order_function('square')
print (result(3))
result = high_order_function('cube')
print (result(3))
result = high_order_function('absolute')
print (result(-3))
| true |
dce3e19095fc1c8195ad0da449928efd24620d41 | fr334aks/100-days-of-Hacking | /Malw0re/09_Day_Conditionals/sort_hand.py | 217 | 4.28125 | 4 | #!/usr/bin/env/python3
a = 3
print ('A is positive') if a > 0 else print ('A is negative')
#First condition met, 'A is positive will be printed.
a = 25
print ('A is positive ') if a < 26 else print ('A is void')
| true |
415f5f90f6ad73a67080cf2dbea95ad69f0e48b5 | sabinerici/corpus-analysis-python | /samples/tutorial_4_practice.py | 1,630 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 1 15:28:39 2020
@author: kkyle2
"""
#functions for Tutorial 4 (frequency lists)
#step 1: Write a function that tokenizes a file
sample_string = "This is a sample sentence. Consequently, so is this! Is this also one?"
#in order to
#first, we will separate the punctuation marks from the other characters. There are many ways to do this, but we will start with the simple string method ".replace()"
#here is a starter punctuation list:
import glob
def load_corpus(dir_name, ending = '.txt', lower = True): #this function takes a directory/folder name as an argument, and returns a list of strings (each string is a document)
master_corpus = [] #empty list for storing the corpus documents
filenames = glob.glob(dir_name + "/*" + ending) #make a list of all ".txt" files in the directory
for filename in filenames: #iterate through the list of filenames
if lower == True:
master_corpus.append(open(filename).read().lower()) #open each file, lower it and add strings to list
else:
master_corpus.append(open(filename).read())#open each file, (but don't lower it) and add strings to list
return(master_corpus) #output list of strings (i.e., the corpus)
def load_corpus(dir_name): #this function takes a directory/folder name as an argument, and returns a list of strings (each string is a document)
filenames = glob.glob(dir_name + "/*.txt") #make a list of all ".txt" files in the directory
for filename in filenames: #iterate through the list of filenames
yield(filename).read().lower()#open each file and yield a lowered string
| true |
5aa2317a22f6fd25c7e44626c84ef8fbe15c68a4 | techno1731/DS_Learning_Journey | /80_Python_Institute/SevenSegmentDisplay/PF_Display.py | 1,584 | 4.21875 | 4 | """ A pure python implementation of the classical 7-segment display, widely used in older electronics """
def get_number():
numero = str(input("Please enter any integer number: "))
return numero
def transform_number(numero):
numero_segmentado = []
numero_segmentado_seven = []
dict_conversor = {"0":"###\n# #\n# #\n# #\n###",\
"1":" #\n #\n #\n #\n #",\
"2":"###\n #\n###\n# \n###",\
"3":"###\n #\n###\n #\n###",\
"4":"# #\n# #\n###\n #\n #",\
"5":"###\n# \n###\n #\n###",\
"6":"###\n# \n###\n# #\n###",\
"7":"###\n #\n #\n #\n #",\
"8":"###\n# #\n###\n# #\n###",\
"9":"###\n# #\n###\n #\n###"}
for digit in numero:
numero_segmentado.append(dict_conversor[digit])
for i in range(len(numero)):
numero_segmentado_seven.append(numero_segmentado[i].split("\n"))
#print(numero_segmentado_seven)
return numero_segmentado_seven
def print_numbers(numero_segmentado_seven):
for fila in range(5):
for i, val in enumerate(numero_segmentado_seven):
if i+1 == len(numero_segmentado_seven):
print(val[fila], end="\n")
else:
print(val[fila], end=" ")
return None
def main():
numero = get_number()
numero_segmentado_seven = transform_number(numero)
print_numbers(numero_segmentado_seven)
return None
if __name__ == "__main__":
main() | false |
9c8f0cc88f9d4043cc40509e15205a62e1888b64 | JoseArtur/phyton-exercices | /cap5/c5e5.7.py | 363 | 4.28125 | 4 | # Modiy the last program of a way that he user also type the start and the end of the multiplication table, instead of start from 1 and 10.
x=int(input("Type a number to the multiplication table: "))
start=int(input("Type start number: "))
end=int(input("Type the end number: "))
n=1
y=start
while n<=(end+1-start):
print(f"{x}X{y}={x*y}")
n=n+1
y=y+1 | true |
18b54764b08c9e1bd6764bfcf46fe440ee6fcbb8 | vaishakh183/mypython-codes | /venv/My programs/Exercises/Exercise16.py | 202 | 4.40625 | 4 | # Write a Python program to find the highest 3 values in a dictionary.
d1={1:8,2:12,3:3,4:4,5:5,6:6,7:7}
print(type(d1))
a=[]
for i,j in d1.items():
a.append(j)
a.sort()
print(a)
print(a[-1:-3])
| true |
f67c5cd8de7729b8dee6b6ca798314b3fb405a82 | vaishakh183/mypython-codes | /venv/My programs/Exercises/Exercise8.py | 218 | 4.28125 | 4 | #Find all occurrences of “USA” in given string ignoring the case.
word=input("enter word")
a=word.split()
count=0
for i in a:
if i.lower() == "usa":
count +=1
print("occurance of USA is" + str(count))
| true |
11110817678537e6d302edece394a82627926515 | vaishakh183/mypython-codes | /venv/My programs/myscripts/Bubblesort.py | 447 | 4.21875 | 4 | #comapre 1st and 2nd values ,if first value is grater than second ,swap it.
#now compare 2nd and 3rd values,do same..and continue..you will get largest value at the end. continue the loop.
def bubble(l1):
for j in range(len(l1)):
for i in range(1,len(l1)):
if l1[i-1] > l1[i]:
temp=l1[i]
l1[i] = l1[i-1]
l1[i-1]=temp
return l1
l1=[6,4,7,2,9,5,1,67]
print(bubble(l1))
| true |
22ea1f2d08a690e4cb09dfa049c37a4e6f02b26a | vaishakh183/mypython-codes | /venv/My programs/myscripts/polymorphism.py | 1,240 | 4.59375 | 5 | #As we know, a child class inherits all the methods from the parent class. However, you will encounter situations where the method inherited from the
# parent class doesn’t quite fit into the child class. In such cases, you will have to re-implement method in the child class.
# This process is known as Method Overriding.
#If you have overridden a method in the child class, then the version of the method will be called based upon the type of the object used to call it.
# If a child class object is used to call an overridden method then the child class version of the method is called. On the other hand, if parent class object
# is used to call an overridden method, then the parent class version of the method is called.
class A:
def explore(self):
print("from class A")
class B:
def explore(self):
print("from class B")
ob1=A()
ob2=B()
ob1.explore()
ob2.explore()
#If for some reason you still want to access the overridden method of the parent class in the child class, you can call it using the super() function.
class C:
def explore(self):
print("from class C")
class D(C):
def explore(self):
super().explore()
print("from class D")
ob3=C()
ob4=D()
ob4.explore()
| true |
2a7f732ea590f86f6b56c7fa4771d2b0a1bb2fdc | vaishakh183/mypython-codes | /venv/My programs/My games/fibonacci series.py | 540 | 4.375 | 4 | #Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. Hint: The Fibonnaci seqence is a sequence of numbers where
#the next number in the sequence is the sum of the previous two numbers in the sequence.
#The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)
def fibonnaci(limit):
l1=[]
i=1
print("limit is "+ limit)
if int(limit) ==1:
l1.append(1)
print(l1)
while i < int(limit):
limit =input("How many Fibonnaci numbers ? ")
fibonnaci(limit) | true |
6810cc26977c6bd62bad2362c9486e2bfa75f7ab | UPstartDeveloper/SPD-2.31-Testing-and-Architecture | /lab/refactoring/extract_method.py | 1,686 | 4.125 | 4 | """Written by Kamran Bigdely
Example for Compose Methods: Extract Method."""
import math
def get_grades(n_students):
"""Prompt the user to input the grades for n students.
Args:
n_students: int. Number of grades to input.
Returns: a list of floating point values
"""
grade_list = []
# Get the inputs from the user
for _ in range(n_students):
grade_list.append(int(input("Enter a number: ")))
return grade_list
def compute_stats(grade_list):
"""Compute and return the mean and standard deviation of the grades.
Args:
grade_list: List[float]. A list of numerical grade values.
Returns: a Tuple[float] of the mean and standard deviation.
"""
# Calculate the mean and standard deviation of the grades
mean = sum(grade_list) / len(grade_list)
sd = 0 # standard deviation
sum_of_sqrs = 0
for grade in grade_list:
sum_of_sqrs += (grade - mean) ** 2
sd = math.sqrt(sum_of_sqrs / len(grade_list))
return mean, sd
def print_stat(n_students):
"""Display the mean and standard deviation for the class.
Args:
n_students: int. The number of students in the class.
Returns: None.
"""
# get the grades
grade_list = get_grades(n_students)
# compute mean and standard deviation
mean, sd = compute_stats(grade_list)
# print out the mean and standard deviation in a nice format.
print("****** Grade Statistics ******")
print(f"The grades's mean is: {mean}")
print(f"The population standard deviation of grades is: {round(sd, 3)}")
print("****** END ******")
if __name__ == "__name__":
n_students = 5
print_stat(n_students)
| true |
862cfe83114cebb1c8b8aef6e89e8d436fd17501 | eignatchenko/cs.mipt_python_LB2 | /task_7.py | 1,341 | 4.3125 | 4 | #!/usr/bin/python3
_methods = """
доступные методы:
forward(X) Пройти вперёд X пикселей
backward(X) Пройти назад X пикселей
left(X) Повернуться налево на X градусов
right(X) Повернуться направо на X градусов
penup() Не оставлять след при движении
pendown() Оставлять след при движении
shape(X) Изменить значок черепахи (“arrow”, “turtle”, “circle”, “square”, “triangle”, “classic”)
stamp() Нарисовать копию черепахи в текущем месте
color() Установить цвет
begin_fill() Необходимо вызвать перед рисованием фигуры, которую надо закрасить
end_fill() Вызвать после окончания рисования фигуры
width() Установить толщину линии
goto(x, y) Переместить черепашку в точку (x, y)
"""
from math import pi, sin, cos
from turtle import Turtle , Screen
screen = Screen ( )
t = Turtle ( )
g = 0.05
for i in range ( 500 ):
t.forward ( g )
t.left ( 5 )
g += 0.05
t.screen.exitonclick ( )
t.screen.mainloop ( )
| false |
0808081eb19e082c73569a32ea2a9bb4e9f8aa23 | veronicafrota1/ScriptPython | /Exer02.py | 363 | 4.25 | 4 | # Exercicio 05
# Receber um numero e informar qual é o numero antecessor e sucessor
num = int(input('Digite um numero: ')) # recebe um valor
numAntecessor = num - 1 # calcula o antecessor
numSucessor = num + 1 # calcula o sucessor
print('O número informado foi {}, seu antecessor é {} e o sucessor é {}'.format(num, numAntecessor, numSucessor))
| false |
4bf2ffaa3e48172499b841b4a6696e460d69f2fe | codenextwolf/TeamEdgeTerm0Python | /debugger.py | 729 | 4.1875 | 4 | import random
options = ["rock", "paper", "scissors"]
print("Let's play Rock Paper Scissors!")
# Challenge
# Find the bugs below:
while True:
userInput = input("Do you want to play rock, paper, or scissors?\n").lower()
randomSelection = random.randint(0, 2)
computerSelection = options[randomSelection]
print(f"You played: {userInput} and the computer played: {computerSelection}")
if userInput == computerSelection:
print("It's a tie!")
elif((userInput = "rock" and computerSelection = "paper") or (userInput = "paper" and computerSelection = "scissors") or (userInput = "scissors" and computerSelection = "rock")):
console.log("You Lose!")
elif:
console.log("You Win!")
| true |
541ef3dc2f15c865eaf470f4bcf7c4f7a710a445 | bennybroseph/Homework | /Python/8. A-Star/SortFunction.py | 755 | 4.375 | 4 |
# Simple default evaluation for ascending order of the values
def DefaultEval(a_Arg1, a_Arg2):
if a_Arg1 > a_Arg2:
return True
else:
return False
# Takes an array of values and delegate/function pointer/??? and uses that to test if the values should be swapped
# The default sort evaluation is ascending by using 'DefaultEval' as the function
# Sorted using bubble sort
def Sort(a_Array, a_EvalFunc = DefaultEval):
for j in range(len(a_Array) - 1, 0, -1):
for i in range(j):
if a_EvalFunc(a_Array[i], a_Array[i+1]):
temp = a_Array[i]
a_Array[i] = a_Array[i+1]
a_Array[i+1] = temp
print
for i in range(0, len(a_Array)):
print a_Array[i]
def main():
array = [0, 1, 3, 4, 2, 8, 5, 22, 12, 11, 15]
Sort(array)
main() | true |
3919286ba97417ae55ec54a80c95265ee7225f18 | ChetanKumawat/test | /demo/70_writeCreate.py | 256 | 4.1875 | 4 | # 'a' - will be append to the end of the file, create the file if file doesn't exist:
f = open("demofile.txt","a")
f.write("\nNow the file has more content")
f.close()
# Open and read the file after appending:
f = open("demofile.txt","r")
print(f.read())
| true |
dd39dfd12f271a3e54c724db41405cdc88ccf170 | saroj1017/Python-programs | /paint-area-calculator.py | 564 | 4.21875 | 4 | #You are painting a wall. The instructions on the paint can says that
#1 can of paint can cover 5 square meters of wall. Given a random height and
#width of wall, calculate how many cans of paint you'll need to buy.
import math
def paint_calc(height,width,cover):
#eval_this=round((height*width)/cover)
print(f'{math.ceil((height*width)/cover)} cans are required')
test_h = int(input("Height of wall: "))
test_w = int(input("Width of wall: "))
coverage = 5
# below parameters are keyword arguments
paint_calc(height=test_h, width=test_w, cover=coverage)
| true |
8065404e0134d867bd7db1c800c52a7c1d1547fa | rajauluddin/Crash-course-on-python | /While Loop/loops.py | 1,315 | 4.21875 | 4 | # Anatomy of a While Loop
# A while loop will continuously execute code depending on the value of a condition. It begins with the keyword while, followed by a comparison to be evaluated, then a colon. On the next line is the code block to be executed, indented to the right. Similar to an if statement, the code in the body will only be executed if the comparison is evaluated to be true. What sets a while loop apart, however, is that this code block will keep executing as long as the evaluation statement is true. Once the statement is no longer true, the loop exits and the next line of code will be executed.
x=0
while x<5:
print("Not there yet, x=" + str(x))
x+=1
print("Finally x="+str(x))
print("------while loop example-----------------------")
print(" ")
def attempts(n):
x = 1
while x <= n:
print("Attempt " + str(x))
x += 1
print("Done")
attempts(6)
print("------while loop example-----------------------")
print(" ")
def count_down(start_number):
current = start_number
while current > 0:
print(current)
current -= 1
print("Zero!")
count_down(3)
print("------while loop example-----------------------")
print(" ")
def print_range(start, end):
# Loop through the numbers from start to end
n = start
while n <= 5:
print(n)
print_range(1, 5) | true |
983b51d097a821197f13a4f1c2cbacb1e1d4ffaf | novojitsaha/Python-Console-Applications | /area_of_trapezium.py | 586 | 4.125 | 4 | #!/usr/bin/env python3
# Novojit Saha
# 02/10/19
# Calculating area of a trapezium using class
class Trapezium:
def __init__(self, base1, base2, height):
self.x = base1
self.y = base2
self.z = height
def area(self):
return 0.5 * (self.x + self.y) * self.z
input_base_1 = float( input('Base one value:') )
input_base_2 = float( input('Base two value:') )
input_height = float( input('Height value:') )
trap1 = Trapezium(input_base_1, input_base_2, input_height )
areaOfTrap1 = trap1.area()
print("The area of the trapezium is " + str(areaOfTrap1)) | true |
040cab9b9dfc143a69fd8ab7bd6c942649398f17 | migueloyler/DailyCodingProblems | /balancedParens.py | 1,482 | 4.125 | 4 | '''
Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed).
For example, given the string "([])[]({})", you should return true.
Given the string "([)]" or "((()", you should return false.
'''
def isBalanced(s):
curOpen = []
countsDict = {'(': 0, ')':0, '{':0, '}':0, '[':0, ']':0}
openers = set(['{', '[', '('])
closers = set([')','}',']'])
inverse = {'[':']', '(':')','{':'}'}
#get counts of each element
for i in range(len(s)):
countsDict[s[i]] += 1
#if the counts don't match then we already know they're not balanced
for k,v in countsDict.items():
if k == '(':
if countsDict[k] != countsDict[')']:
return False
if k == '{':
if countsDict[k] != countsDict['}']:
return False
if k == '[':
if countsDict[k] != countsDict[']']:
return False
#use a stack, make sure that everytime we close one, we know that
# it must match the opener at the top of stack
for i in range(len(s)):
if i == 0:
curOpen.append(s[i])
continue
if s[i] in openers:
curOpen.append(s[i])
else:
lastOpen = curOpen.pop()
if s[i] != inverse[lastOpen]:
return False
return True
print(isBalanced('([])[]([])'))
print(isBalanced('([)]'))
print(isBalanced('((()')) | true |
8ec39d49dda24ffbeb68d5825f9cc9361d9a9914 | 1201200250PZQ/DPL5211Tri2110 | /Lab 02/Lab 2.6.py | 377 | 4.21875 | 4 | # Student ID : 1201200250
# Student Name : PAN ZHI QI
import math
radius = float(input("Please enter the radius : "))
volume = (4 / 3) * math.pi * radius * radius * radius
surfacearea = (4 * math.pi * radius * radius)
print("PI: {:.2f}".format(math.pi))
print("Volume of Sphere : {:.2f}".format(volume))
print("Surface Area of Sphere : {:.2f}".format(surfacearea)) | false |
dfc38dc241e56e66500aaec28b030f0ea69033f0 | Karandeep07/beginner-projects | /useless-trivia-program.py | 1,370 | 4.65625 | 5 | # The program takes three pieces of personal information from the user: name, age, and weight.
# From these mundane items, the program is able to produce some amusing but trivial facts about
# the person, such as how much the person would weigh on the moon.
# Though this may seem like a simple program ( and it is ), you’ll find that the program is more
# interesting when you run it because you’ve had input.
# You’ll care more about the results because they’re personally tailored to you.
# Useless Trivia#
#
# Gets personal information from the user and then
# prints true but useless information about him or her
name = input("Hello, what is your name? \n")
age = float(input("How old are you? \n"))
weight = float(input("How much do you weigh in kilograms?\n"))
print(
f"If Johnson Sakaja were to email you, he would address you as {name.title()} \nbut if he was mad, he would address you as {name.upper()}\n")
name += " "
print(
f"If a small child was trying to get your attention, he would say: \n \"{name.title()*5}\" ")
seconds = age * 365 * 24 * 60 * 60
print(f"\nYou’re over {seconds} seconds old.\n")
moon_weight = weight / 6
print(
f"\nDid you know that on the moon you would weigh only {moon_weight} kilograms?\n")
sun_weight = weight * 27.1
print(f"\nOn the sun, you'd weigh {sun_weight} (but, ah... not for long).\n")
| true |
7771eb18d5741be0248d0db47c27411585a34bd1 | costacoz/python_topics | /caching_lru_cache.py | 909 | 4.34375 | 4 | """
Example of built-in caching module.
@functools.lru_cache(maxsize=None, typed=False)
maxsize: how many results of this function call can be cached at most,
if None, there is no limit, when set to a power of 2, the performance
is the best
typed: If True, calls of different parameter types will be cached
separately.
"""
import timeit
from functools import lru_cache
@lru_cache(None)
def add(x, y):
print(f'adding: {x} + {y}')
return x + y
print(add(1, 2))
print(add(1, 3))
print(add(1, 3)) # notice, how this time it doesn't output "adding: 1 + 3"
@lru_cache(None)
def fib(n):
"""
Without caching this function takes ~3 seconds to execute, whereas
with caching it executes 0.0000018 seconds
"""
if n < 2:
return n
return fib(n - 2) + fib(n - 1)
print(f'fibonacci of (35): {timeit.timeit(lambda: fib(35), number=1)}')
| true |
b2c27a28e3827107bdbdcf6e96f736775cbf952d | costacoz/python_topics | /10_8_decimal_floating_point.py | 1,393 | 4.375 | 4 | """
Floating point arithmetic in computers is approximate due to architecture.
So decimal module offers a Decimal datatype for decimal floating point
arithmetic.
Compared to the built-in float implementation of binary floating point,
the class is especially helpful for
* financial applications and other uses which require exact decimal
representation,
* control over precision,
* control over rounding to meet legal or regulatory requirements,
* tracking of significant decimal places, or
* applications where the user expects the results to match
calculations done by hand.
"""
from decimal import *
# calculate 5% tax on 70 cent bill, using Decimal will give correct result
print(f'(Decimal) 0.70 * 1.05 = ', round(Decimal('0.70') * Decimal('1.05'), 2))
# via regular float operation it will give wrong answer:
print(f'(regular float) 0.70 * 1.05 = ', round(.70 * 1.05, 2))
# Another example of getting modulo calculation with floating point numbers:
print(f'1.00 % 0.10 via Decimal:', Decimal('1.00') % Decimal('.10'))
# again, float type gives wrong result:
print(f'1.00 % 0.10 via regular float = {1.00 % 0.10}')
print(sum([Decimal('0.1')] * 10) == Decimal('1.0'))
print(sum([0.1] * 10) == 1.0)
# The decimal module provides arithmetic with as much precision as needed:
getcontext().prec = 36
print(Decimal(1) / Decimal(7)) | true |
7588db914c5744619b7e6437525d2749c66fc196 | arnabmaji1981/thirdday | /classpractice/string1.py | 694 | 4.125 | 4 | print("first program")
data1=[1,2,3,4]
data2=['x','y','z']
print(data1[0])
print(data1[0:2])
print(data2[-3:-1])
print(data1[0:])
print(data2[:2])
print("second program")
list1=[10,20]
list2=[30,40]
list3=list1+list2
print(list3)
print("third program")
list1=[10,20]
print(list1*5)
print("fourth program/slicing")
list1=[1,2,4,5,7]
print(list1[0:2])
print(list1[4])
list1[1]=9
print(list1)
print("fifth example/list updating")
data1=[5,10,15,20,25]
print("Values of list are: ")
print(data1)
data1[2]="Multiple of 5"
print("Values of list are: ")
print(data1)
print("sixth example")
list1=[10,'rahul',50.8,'a',20,30]
print(list1)
del list1[0]
print(list1)
del list1[0:3]
print(list1)
| false |
907e82c7f3e823132a8f4969e1ec600bfd77d352 | jollylst/D04 | /HW04_ch08_ex05.py | 840 | 4.40625 | 4 | # Structure this script entirely on your own.
# See Chapter 8: Strings Exercise 5 for the task.
# Please do provide function calls that test/demonstrate your
# function.
def rotate_letter(letter, n):
# Rotate a letter by n places. Does not chage other characters.
# letter: single-letter string
# n: integer
# return: single-letter string
if letter.isupper():
start = ord('A')
elif letter.islower():
start = ord('a')
else:
return letter
c = ord(letter) - start
i = (c + n) % 26 + start
return chr(i)
def rotate_word(word, n):
# Rotate a word by n place.
# word: string
# n: integer
# return: rotated string
replacement = ""
for letter in word:
replacement = replacement + rotate_letter(letter, n)
return replacement
if __name__ == "__main__":
print(rotate_word('cheer', 7))
print(rotate_word('melon', -10))
| true |
fee5c59248178b3c7e58a1f289e809cb3a500370 | shaotianyuan/My_world | /Algorithms_Data Structures/树/l2_树嵌套列表的实现.py | 1,209 | 4.125 | 4 | """
二叉树实现(list)递归实现:
1,第一个元素为根节点的值
2,第二个元素是左子树(所以也是一个列表)
3,第二个元素是右子树(所以也是一个列表)
[root,left,right]
实现树:嵌套列表法的函数定义
1,BinaryTree创建仅有根节点的二叉树
2,insertLeft/insertRight将新节点插入树中作为其直接的左/右子节点
3,get/setRootVal 则取得或返回根节点
4,getLeft/RightChild返回左/右子树
"""
def BinaryTree(r):
return [r, [], []]
def insertLeft(root, newBranch):
t = root.pop(1)
# if len(t) > 1:
root.insert(1, [newBranch, t, []])
# else:
# root.insert(1, [newBranch, [], []])
return root
def insertRight(root, newBranch):
t = root.pop(2)
if len(t) > 1:
root.insert(2,[newBranch, [], t])
else:
root.insert(2,[newBranch, [], []])
return root
def getRootVal(root):
return root[0]
def setRootVal(root, newVal):
root[0] = newVal
def getLeftChild(root):
return root[1]
def getrightChild(root):
return root[2]
r = BinaryTree(3)
print(r)
insertLeft(r,4)
print(r)
insertLeft(r,5)
print(r)
a = r.pop(1)
print(a)
print(len(a)) | false |
4cf996e78739047bbebe81997445ff6f48e27b43 | shaotianyuan/My_world | /Algorithms_Data Structures/Recursion/l6_硬币找零.py | 2,169 | 4.15625 | 4 | """
分治策略
将问题分为若干个小规模问题,并将结果汇总得到原问题
应用番位:排序、查找、遍历、求值等
"""
'递归解法'
def recMC(coinvaluelist,change):
mincoins = change
if change in coinvaluelist:
return 1
else:
for i in [c for c in coinvaluelist if c <= change]:
numCoins = 1 + recMC(coinvaluelist, change - i)
if numCoins < mincoins:
mincoins = numCoins
return mincoins
# print(recMC([1,5,10,25],63))
"""
'递归优化'
递归:低效原因:重复计算太多
解决方法:消除重复计算,保存中间结果
"""
def recDC(c_list, change, k_result):
minCoin = change
if change in c_list:
k_result[change] = 1
return 1
elif k_result[change] > 0:
return k_result[change]
else:
for i in [c for c in c_list if c <= change]:
numCoin = 1 + recDC(c_list, change - i, k_result)
if numCoin < minCoin:
minCoin = numCoin
k_result[change] = minCoin
return minCoin
# print(recDC([1,5,10,25], 63, [0]*64))
"""
'动态规划'
1,找零兑换的动态规划算法从最简单的'一分钱找零'的最优解开始,逐步递加上去,直到我们需要的找零钱数
2,在找零递加的过程中,设法保持每一分的递加都是最优的,一直加到求解找零钱数,自然是最优的解
步骤:
1,减去1种币种,剩余部分查表获得最优解
2,遍历所有币值的情况,挑选最优解
3,记录在表中
4,加上1分钱,重复上述步骤
"""
def dpmc(c_list, change, min_list):
for cents in range(1, change + 1): # 从1分钱开始到change逐个计算最少硬币数量
coinCount = cents # 初始化一个最大值
for j in [c for c in c_list if c <= cents]: # 减去每个硬币,向后查最少硬币数量,
if min_list[cents - j] + 1 < coinCount:
coinCount = min_list[cents - j] + 1
min_list[cents] = coinCount # 同时记录总的最少数
return min_list[change] # 返回最优解
print(dpmc([1,5,10,21,25],63,[0]*64)) | false |
04632d9537a8e3a8afec1762167dee30e99aa35c | notthumann/nguyentrangan-fundametals-c4e22 | /session4/ud2.py | 458 | 4.125 | 4 | person = {
'name' : 'An',
'age' : 22,
'gender' : 'male',
}
print(person)
do = input("do you want to delete or update?(D/U) ")
if do == "D":
delete = input('what to delete?')
if delete not in person:
print("notfound")
else:
del person[delete]
print(person)
elif do == "U":
key = input("what key to update?")
value = input("What value?")
person[key]= value
print(person)
else:
print("What?")
| false |
b07d368653e90b7cdaa6dbbf28b6bcbc0e20fbfd | jennifer-ryan/pands-problem-set | /8_datetime.py | 1,554 | 4.28125 | 4 | # Problem: Write a program that outputs today’s date and time in the format "Monday, January 10th 2019 at 1:15pm".
# Note: This is an entirely different version of original code using strftime.
# Please see old commits for original solution, which worked but was very inefficient.
# Import datetime to get access to date and time
import datetime as dt
# Broken into 2 variables to add correct suffix for the date in the middle.
# first returns string formatted day, month, date.
first = dt.datetime.strftime(dt.datetime.now(), "%A, %B %#d") # Windows formatting uses '#' instead of '-' https://stackoverflow.com/a/2073189
# second returns string formatted year and time.
second = dt.datetime.strftime(dt.datetime.now(),"%Y at %#I:%M")
# Function suffix() created from original datetime solution to get suffixes for the date ('st', 'nd', 'rd' or 'th').
def suffix():
date = dt.datetime.today().day
suf = ""
if date == 1 or date == 21 or date == 31:
suf = "st"
elif date == 2 or date == 22:
suf = "nd"
elif date == 3 or date == 23:
suf = "rd"
else:
suf = "th"
return suf
# Cannot get %p in strftime to print am/pm as lowercase on Windows so wrote function below for this, based on what was written in first solution
def ampm():
hour = dt.datetime.today().hour
end = ""
if hour in range(0, 12):
end = "am"
else:
end = "pm"
return end
# Concatenate within print function to print whole string to console
print (first+suffix(), second+ampm()) | true |
b94ceabbcf4f8b20cc4153c7a68f8cc784ddcd5f | sgriffin10/ProblemSolving | /Classwork/Sessions 11-20/Session 15-17/OOP/OOP3/exercise5.py | 1,674 | 4.59375 | 5 | """
Exercise 5 (group work)
Write a definition for a class of anything you want. You have to use the following methods:
_init_ method that initializes some attributes. One of the attributes has to be an empty list.
_str_ method that returns a string that reasonably represent the thing.
A special method that overloads the one type of operators.
Some other methods that reasonably represent the thing's actions, inclduing one method that takes an object of any type and adds it to the attribute of type list.
Test your code by creating two objects and using all the methods.
"""
class Favorite_Foods:
"""Represents someone's favorite foods"""
def __init__(self, name='', foods=[]):
"""initialize"""
self.name = name
self.foods = foods
def __str__(self):
"""
return a object in a human-readable format
text represenation of this object
"""
return f"{self.name}'s favorite foods are {', '.join(self.foods)}"
def __eq__(self, other):
"""
return True if self and other share the same favorite foods
"""
return self.foods == other.foods
def __add__(self, other):
"""returns self and other favorite foods"""
total_foods = self.foods + other.foods
return f"{self.name} and {other.name}'s favorite foods are {', '.join(total_foods)}"
Arteen = Favorite_Foods('Arteen', ['ice cream', 'pizza'])
print(Arteen)
Spencer = Favorite_Foods('Spencer', ['ice cream', 'pizza'])
print(Spencer)
Brian = Favorite_Foods('Brian', ['rice', 'pasta'])
print(Brian)
print(Arteen == Spencer) #True
print(Brian == Spencer) #False
print(Arteen + Brian) | true |
e79088665ce32cd8d5f151e99965c51590aa3d28 | CeliaJ/Mycaptain | /mycaptain3.1.py | 428 | 4.125 | 4 | import time
tuple1=()
list3=[]
name=input("Enter the name of the tuple: ")
num=int(input("Enter the number of elements: "))
print("Enter the elements: ")
for var in range(num):
ele=input()
list3.append(ele)
tuple1=tuple(list3)
y=int(input("Enter the item number of the tuple to be accessed: "))
print("Fetching your data... ")
time.sleep(2)
print("The item with the number %d is: "%y, end=" ")
print(tuple1[y-1])
| true |
f6c2a3db3f92566a6c21101b90bd7e5b87913eea | jimmy605/fundamentals-of-python-data-structures | /ch01-BasicPythonProgramming/3.py | 1,319 | 4.46875 | 4 | """
3.
A standard science experiment is to drop a ball and see how high it bounces. Once the “bounciness” of the ball has been determined, the ratio gives a bounci- ness index. For example, if a ball dropped from a height of 10 feet bounces 6 feet high, the index is 0.6 and the total distance traveled by the ball is 16 feet after one bounce. If the ball were to continue bouncing, the distance after two bounces would be 10ft + 6ft + 6ft + 3.6ft = 25.6ft. Note that distance traveled for each successive bounce is the distance to the floor plus 0.6 of that distance as the ball comes back up. Write a program that lets the user enter the initial height of the ball and the number of times the ball is allowed to continue bouncing. Output should be the total distance traveled by the ball.
"""
def bounce(downPhase):
"""Returns the total of a single bounce"""
return downPhase + (downPhase * 0.6)
def ballTraveled(ballHeight, bounces):
"""Return the total distance traveled of a ball when bounced x times."""
# total variable to store the total distance traveled
totalDistance = 0
# Use a for loop to iterate through the bounces
for n in range(bounces):
totalDistance += bounce(ballHeight)
ballHeight *= 0.6
print(f'{totalDistance:.2f}')
ballTraveled(10, 2)
| true |
2f2ebef8f27d357d1691114be50861ac08aa0e31 | e-lin/LeetCode | /231-power-of-two/231-power-of-two.py | 467 | 4.25 | 4 | # solution reference:
# http://stackoverflow.com/questions/1804311/how-to-check-if-an-integer-is-a-power-of-3
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if 0 == n:
return False
while n%2 == 0:
n /= 2
return 1 == n
def main():
n = 27
solution = Solution()
print solution.isPowerOfTwo(n)
if __name__ == '__main__':
main() | false |
35a870b6ad7319ea261ae6530475d2e63e11d22f | YngraSimas/Aulas_Python | /03_primeiras_funcoes/aula07.py | 1,122 | 4.3125 | 4 | #faça um programa que peça 2 números inteiros e 1 número real e mostre:
#a) o produto do dobro do primeiro número com a metade do segundo número: (n*2) * (m/2)
# produto == multiplicação
#b) a soma do triplo do primeiro número com o terceiro número: n*3+p
#c) o terceiro número elevado ao cubo: p**3
#número real == /R, formado pela junção de 2 conjuntos: número racional,(Q),
# representado por fração e número irracional,(I), seu padrão não é possível
# ser representado por fração
def pdm(n, m):
a = (n*2) * (m/2)
return a
def st(n, p):
a = n * 3 + p
return a
def c(p):
a = p ** 3
return a
entrada_1 = int(input("Digite um número inteiro: "))
entrada_2 = int(input("Digite outro número inteiro: "))
entrada_3 = float(input("Digite um número real: "))
print(f"O produto do dobro do número {entrada_1} com a metade do número "
f"{entrada_2} é:", pdm(entrada_1, entrada_2))
print(f"A soma do triplo do número {entrada_1} com o número {entrada_3} "
f"é:", st(entrada_1, entrada_3))
print(f"O terceiro número elevado ao cubo é igual a:", c(entrada_3)) | false |
d0d44531aba6af23e5230d706e07c3df9e3f31ff | vivekgupta8983/python_tut | /Python_Tutorials/string.py | 593 | 4.375 | 4 | """
Example of String works in Python
Sequence of characters
Contians a-z, 0-9, @
In double or Single quotes
"""
a = "This is simple string"
b = 'Using single quotes'
print(a)
print(b)
c = "need to use 'qoutes' inside the string"
print(c)
d = "Another way to handle \"qoutes\""
print(d)
"""
Accessing character in a string
"""
first = "nyc"[0]
city = "cyn"
print(first)
ft = city[0]
print(ft)
"""
len()
lower()
upper()
str()
"""
stri = "This is Mixed Case"
print(stri.lower())
print(stri.upper())
print(len(stri))
print(stri + " hello " + "" + " world")
print("first" + " " + "city") | true |
d071b04fc5732ac222d27d3972e35ce2513089db | nolanchao/megalab | /Desktop/FullStack_Info_HW06-master/HW6_Starter_Code/megalab_eric/HW6_Starter_Code/app/models.py | 1,893 | 4.15625 | 4 | import sqlite3 as sql
def insert_data(trip_name, destination, friend):
# SQL statement to insert into database goes here
with sql.connect("app.db") as con:
cur = con.cursor()
cur.execute("insert into trips (trip_name, destination, friend) VALUES (?, ? ,?)", (trip_name, destination, friend))
con.commit()
def insert_address(street_address, city, state, country, zip_code):
# SQL statement to insert into database goes here
with sql.connect("app.db") as con:
cur = con.cursor()
cur.execute("insert into address (street_address, city, state, country, zip_code) VALUES (?,?,?,?,?)", (street_address, city, state, country, zip_code))
con.commit()
def retrieve_trips(destination, friend):
# SQL statement to query database goes here
with sql.connect("app.db") as con:
con.row_factory = sql.Row
# above sets up connection to accept data in the form of row objects
cur = con.cursor()
result = cur.execute("select * from trips").fetchall()
print (result)
return result
def retrieve_companions(destination, friend):
# SQL statement to query database goes here
with sql.connect("app.db") as con:
con.row_factory = sql.Row
# above sets up connection to accept data in the form of row objects
cur = con.cursor()
result = cur.execute("select * from trips WHERE FRIEND IS 'Eric' ").fetchall()
print (result)
return result
def insert_orders(name_of_part, manufacturer_of_part, value):
# SQL statement to insert into database goes here
with sql.connect("app.db") as con:
cur = con.cursor()
cur.execute("insert into orders (name_of_part, manufacturer_of_part, customer_ordered) VALUES (?,?,?)", (name_of_part, manufacturer_of_part, value))
con.commit()
##You might have additional functions to access the database | true |
9838514ebe849d98cc81649219426319d295c284 | Frann2807/Mi-primer-programa | /conceptos_practica/parte_dos/lista_de_tipos/ejecicio_tres_forma_uno.py | 854 | 4.125 | 4 | lista_usuario_letras = []
lista_usuario_numeros = []
eleccion_usuario = " "
while eleccion_usuario != "FIN":
eleccion_usuario = input("¿Que quieres añadir; Un numero o una Palabra?").upper()
if eleccion_usuario == "NUMERO":
numero_usuario = int(input("Dime un numero: "))
lista_usuario_numeros.append(numero_usuario)
print("Numero añadido!")
elif eleccion_usuario == "PALABRA":
palabra_usuario = input("Dime una palabra: ")
lista_usuario_letras.append(palabra_usuario)
print("Palabra añadida!")
elif eleccion_usuario == "FIN":
print("La lista ha terminado.")
else:
print("No se que has querido decirme, lo siento.")
print("Esta es tu lista de palabras: {}".format(lista_usuario_letras))
print("Esta es tu lista de numeros: {}".format(lista_usuario_numeros))
| false |
64eccfc1026b3e5e57d58bc857e2841e55735c8f | RobsonRomeuRizzieri/python-fundamentos-data-science-I | /exercicio06.py | 556 | 4.21875 | 4 | #obtendo a posição inicial da string contida em outra string
valor = 'Procurando por um valor aplicado para novo campos.'
#Nesse caso vai imprimir o valor 18 que é onde inicia a string procurada.
print valor.find('valor')
#vamos atribuir esse indice a uma variavel
indice = valor.find('valor')
#agora vamos reimprimir o texto somente apartir da palavra que encontramos
print valor[indice:]
#se procurar por uma string que não existe no texto de busca é retornado -1
#Vale lembrar que diferencia letra maiuscula de minuscula
print valor.find('Robson') | false |
bbcbe86d5f902fed12113aa2ff2cafdb7fe9019b | Gayatr12/Data_Structures | /linklist.py | 2,044 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 17 16:20:25 2020
@author: STSC
"""
#LinkedList
# creating LinkedList and printing
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
# Linked List class contains a Node object
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
def printlink(self,head):
temp = head
while (temp):
print(temp.data,"--->", end =" ")
temp = temp.next
print("None")
# reverse the linklist
def reverse(self,head):
temp = head
prev = None
while(temp):
Nxt =temp.next
temp.next =prev
prev = temp
temp = Nxt
return prev
# check if linklist is has cycle
def checkCycle(self, head):
slow = head
fast = head
while (fast.next !=None):
slow = slow.next
fast = fast.next.next
if fast == slow:
return True
return False
#
# Code execution starts here
if __name__=='__main__':
# Start with the empty list
llist = LinkedList()
llist.head = Node(1)
second = Node(2)
third = Node(3)
llist.head.next = second;
second.next = third
print("LinkedList:")
llist.printlink(llist.head)
rev_list = llist.reverse(llist.head)
print("Reverse LinkList:")
llist.printlink(rev_list)
if llist.checkCycle(llist.head):
print("Linklist contain Cycle")
else:
print("Linklist does not contain Cycle")
| true |
18777d3d68cc6a961f6d006acf8b657e60ac55fb | DevBaki/Python_Examples_Basic | /31_GenerateList.py | 482 | 4.28125 | 4 | lists = []
for i in range(1, 21):
lists.append(i)
'''print all the elements in the list'''
print("Elements in List:", [x ** 2 for x in lists])
'''print First 5 elements in the list'''
print("First 5 elements in list", [x ** 2 for x in lists[:5]])
'''print First 5 elements in the list'''
print("Last 5 elements in list", [x ** 2 for x in lists[-5:]])
'''print all elements except First 5 elements in the list'''
print("Last 5 elements in list", [x ** 2 for x in lists[5:]])
| true |
487b06b51d9194af58b0b2965501add0ec79ffa2 | KimDaeUng/DeepLearningPractice | /Project/PerceptronPractice/XOR_MLP.py | 2,931 | 4.3125 | 4 | # ----------
# 1. create a network of perceptrons with the correct weights
# 2. define a procedure EvalNetwork() which takes in a list of inputs and
# outputs the value of this network.
# ----------
import numpy as np
class Perceptron:
"""
This class models an artificial neuron with step activation function.
"""
def __init__(self, weights = np.array([1]), threshold = 0):
""" Initialize weights and threshold based on input arguments.
Keyword Arguments:
weights {np.array} -- weights (default: {np.array([1])})
threshold {int} -- threshold (default: {0})
"""
self.weights = weights
self.threshold = threshold
def activate(self, values):
"""Activation function
Arguments:
values {list} -- a list of numbers equal to length of weights
Returns:
int -- the output of a threshold perceptron with given inputs based on
perceptron weights and threshold
"""
# First calculate the strength with which the perceptron fires
strength = np.dot(values, self.weights)
# Then return 0 or 1 depending on strength compared to threshold
return int(strength >= self.threshold)
def EvalNetwork(inputValues, Network):
"""Implement network
Define a procedure to compute the output of the network, given inputs
Arguments:
inputValues {list} -- a list of input values e.g. [1, 0]
Network {list} -- Network that specifies a perceptron network
Returns:
int -- the output of the Network for the given set of inputs
"""
#Method1 :
# p is an instance of Perceptron.
# inner brackets --> input layer
# Network[1][0] --> Perceptron([1, -2, 1], 1) -- Only one element
#return Network[1][0].activate([p.activate(inputValues) for p in Network[0]])
#Method2 :
OutputValue = inputValues
for layer in Network:
OutputValue = list(map(lambda p: p.activate(OutputValue), layer))
return OutputValue[0] # single value list
def test(Network):
"""A few tests to make sure that the perceptron class performs as expected.
Arguments:
Network {list} -- Network list
"""
print("0 XOR 0 = 0?:", EvalNetwork(np.array([0, 0]), Network))
print("0 XOR 1 = 1?:", EvalNetwork(np.array([0, 1]), Network))
print("1 XOR 0 = 1?:", EvalNetwork(np.array([1, 0]), Network))
print("1 XOR 1 = 0?:", EvalNetwork(np.array([1, 1]), Network))
def main():
# Set up the perceptron network
Network = [
# input layer, declare input layer perceptrons here
[ Perceptron([1, 0], 1), Perceptron([1, 1], 2), Perceptron([0, 1], 1) ], \
# output node, declare output layer perceptron here
[ Perceptron([1, -2, 1], 1) ]
]
test(Network)
if __name__ == "__main__":
main()
| true |
bae1c6905cd9e40270b609b3881dd25b3292a4fd | RoxinneNwe/MyExercise | /chapter2.py | 494 | 4.1875 | 4 |
#2.2
name = input("Enter your name: ")
print("Hello, ",name,"!")
#2.3
hours=float(input("Enter Hours: "))
rate=float(input("Enter Rate: "))
print(float(hours*rate))
#2.4
width=17
height=12.0
val1 = width/2
print("1.", val1, type(val1))
val2 = width/2.0
print("2.",val2, type(val2))
val3 = height/3
print("3.",val3, type(val3))
val4 = 1 + 2 * 5
print("4.",val4, type(val4))
#2.5
Celsius = float(input("Enter Celsius Temperature: "))
Fahrenheit = (Celsius * 1.8)+32
print(Fahrenheit)
| true |
b51c43259124f33a381a94b42562151c5d077502 | RoxinneNwe/MyExercise | /for-loop-sampe2.py | 441 | 4.125 | 4 |
cars = ["BMW", "Ford", "Alfa Romeo"]
for x in cars:
print(x)
model = input("Choose a model from the above list: ")
if model == "BMW":
bmw = (80000 * 0.05) + 80000
print("BMW costs", bmw )
elif model == "Ford":
ford = (75000 * 0.05) + 75000
print("Ford costs", ford)
elif model == "Alfa Romeo":
alfar = (125000 * 0.05) + 125000
print("Alfa Romeo costs", alfar)
else:
print("Your choice is not on the list") | true |
b322891299593ec3570640d6e8159d6c1be3ca50 | RoxinneNwe/MyExercise | /jon_vowels.py | 862 | 4.1875 | 4 | """
def is_vowel(x): # function to determine vowels in boolean
while True:
print("Enter '0' for exit.")
ch = input("Enter any character: ")
if ch == '0':
break
else:
if(ch=='a' or ch=='A' or ch=='e' or ch=='E' or ch=='i' or ch=='I' or ch=='o' or ch=='O' or ch=='u' or ch=='U'):
print(ch, "is a vowel.\n")
else:
print(ch,"is not a vowel.\n")
x = ''
print(is_vowel(x))
"""
def is_vowel(x):
small_vowel=['a', 'e', 'i', 'o', 'u']
big_vowel=['A', 'E', 'I', 'O', 'U']
if(x in small_vowel) or (x in big_vowel):
return True
else:
return False
import sys
print("Enter a character: ", end='')
character=sys.stdin.read(1)
if is_vowel(character):
print(character, " is a Vowel")
else:
print(character, " is a consonant")
| false |
24e06269a824ee7651bce18797db8bb21a5b2f9a | ryanjeric/python_playground | /terms/part7_stringInterpolation.py | 439 | 4.375 | 4 | # STRING INTERPOLATION
name = 'Sasa'
age = 13
# String concatenation
greetings1 = 'My name is' + name + ' and I am ' + str(age) + ' years old'
print(greetings1)
# String interpolation - placeholders {} are replaced with their corresponding values
greetings2 = 'My name is {} and I am {} years old'.format(name,age)
print(greetings2)
greetings3 = 'I am {age} years old and my name is {name}'.format(name=name,age=age)
print(greetings3)
| true |
dd740d101fbafe3769bd57263520683c7eaa807e | ryanjeric/python_playground | /Intro/list6.py | 361 | 4.28125 | 4 | # Introduction to lists part 6 , how to sort the list
list_letters = ['s', 't', 'i', 'n', 'k', 'y']
print(list_letters)
list_letters.sort()
print(list_letters)
list_letters.sort(reverse=True)
print(list_letters)
list_numbers = ['1', '8', '3', '2']
print(list_numbers)
list_numbers.sort()
print(list_numbers)
list_numbers.sort(reverse=True)
print(list_numbers)
| true |
b5045f553032a34ecc56a874db44610ad6cbf678 | dwihdyn/backend-exploring | /Day1/mentor-answer/binary_search.py | 1,476 | 4.28125 | 4 | def binary_search(target, my_list):
"""
Finds a target element in a sorted list using the binary search algorithm. Returns the index of the target in the list.
"""
start = 0
end = len(my_list) - 1
# Find the midpoint of the list using floor division (//)
midpoint = (start + end) // 2
# Only end the loop when start point is larger than end point
while not start > end:
if target == my_list[midpoint]:
return midpoint
# Focus the left half of the list
elif target < my_list[midpoint]:
end = midpoint - 1
midpoint = (start + end) // 2
# Focus the right half of the list
elif target > my_list[midpoint]:
start = midpoint + 1
midpoint = (start + end) // 2
return False
print(binary_search(60, [12, 21, 33, 42, 57]))
# Round 1 - midpoint: index 2
# 60 is more than 33 (my_list[2])
# start point is now the element after the midpoint (2 + 1)
# Focus on index 3 onwards [42, 57]
# Round 2 - midpoint: index 3
# 60 is more than 42 (my_list)
# start point is now index 4 (3 + 1)
# Focus on index 4 [57]
# Round 3 - midpoint: index 4
# 60 is more than 57 (my_list[4])
# start point is now index 5
# HOWEVER, end point is 4
# We can never have a situation where the start point is larger than the end point
# Therefore, we can conclude that the target is not in the list
print(binary_search(5, [1, 2, 3, 4, 5, 6]))
| true |
1442973ed6b5ded0981e43722c9eab3e839ff44b | unif2/dsp | /python/q8_parsing.py | 770 | 4.15625 | 4 | # The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
import csv
file = open('football.csv')
reader = csv.reader(file)
data = list(reader)
g_index = data[0].index('Goals')
ga_index = data[0].index('Goals Allowed')
diff = []
diff.append(None)
for i in range(1,len(data)):
diff.append(int(data[i][g_index]) - int(data[i][ga_index]))
print(data[diff.index(min(diff[1:]))][0])
| true |
9a3914c8c5b87f1f0be62eae29c0f35a53e93d37 | mufeed533/66Days | /algorithms_and_datastructures/exercises/palindromes.py | 275 | 4.15625 | 4 | """
Check if an input string is palindrome or not
"""
from functools import reduce
def is_palindrome_1(string):
reversed_string = reduce(lambda x, y: y + x, string)
return reversed_string == string
input_string = str(input())
print(is_palindrome_1(input_string))
| true |
9146e19b6a8dafef725a3c2ffdd5002aa94d0163 | ahtee/programming-practice | /python/Trees.py | 2,149 | 4.21875 | 4 | # binary tree: data struct in which each node has at most two children
# which are referred to as the left child and right child.
# Top node is the root
# leaves are the bottom nodes of the tree with no children
# root starts at 0 or 1
# depth is the measure of the height from the root to the node
# height is leaves back to root
# Complete binary tree : every level except the last is completely filled
# all nodes in the last level are as far left as possible
# Full binary tree: every node has either 0 or 2 children
# define the node class like you did in linked list
# these are all depth-first search
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree(obj):
def __init__(self, root):
self.root = Node(root)
def print_tree(self, trav_type):
if trav_type == "preorder":
return self.preorder_print(tree.root, "")
elif trav_type == "inorder":
return self.inorder_print(tree.root, "")
def preorder_print(self, start, trav):
# Root -> Left -> Right
if start:
trav += (str(start.value) + "-")
trav = self.preorder_print(start.left, trav)
trav = self.preorder_print(start.right, trav)
return trav
def inorder_print(self, start, trav):
# Left -> root -> right
if start:
trav = self.inorder_print(start.left, trav)
trav += (str(start.value) + "-")
trav = self.inorder_print(start.right, trav)
return trav
def postorder_print(self, start, trav):
# Left -> right -> root
if start:
trav = self.postorder_print(start.left, trav)
trav = self.postorder_print(start.right, trav)
trav += (str(start.value) + "-")
return trav
# 1
# / \
# 2 3
# / \
# 4 5
binTree = BinaryTree(1)
binTree.root.left = Node(2)
binTree.root.right = Node(3)
binTree.root.left.left = Node(4)
binTree.root.left.right = Node(5)
# pre order traversal: check current node (root) is empty
# root, left subtree, right subtree
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.