blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
721ca0484e16e055698583ac67947cabc0662dcc | gauchoux/210CT-CW | /8.py | 1,428 | 4.15625 | 4 | def main():
print("\n")
print(" |----------------------------------------|")
print(" | Think of a number between 1 and 2000 |")
print(" | Tap enter when you are ready |")
print(" |----------------------------------------| \n")
input()
guess(biglist())
def biglist():
L=[]
for i in range(1,2001):
L.append(i)
return L
def guess(arr):
if len(arr) == 1:
print("The number you're thinking of is " + arr)
a = input(" Is the number " + str(arr[int(len(arr)/2)-1]) + " ? Yes or No ? ")
if a == "Yes" or a == "yes":
print("\n I win, I guessed you were thinking of the number " + str(arr[int(len(arr)/2)-1]))
elif a == "No" or a == "no":
b = input("\n Is it higher or lower than " + str(arr[int(len(arr)/2)-1]) + " ? ")
if b == "Higher" or b == "higher":
for i in range(arr[0], arr[int(len(arr)/2)]):
arr.remove(i)
guess(arr)
elif b == "Lower" or b == "lower":
for i in range(arr[int(len(arr)/2)], (arr[int(len(arr)-1)] + 1)):
arr.remove(i)
guess(arr)
else:
print("Enter a valid answer")
guess(arr)
else:
print("Enter a valid answer \n")
guess(arr)
main()
| false |
b663f88fb904ab3cbdc403584471c752335ed6bf | darienhdez/PythonEx | /errorhandlingEx.py | 1,008 | 4.1875 | 4 | # Error Handling Ex
#IF YOU ENTER A NUMBER > 0 THEN:
# run the else code: Thank you
# run the finally code: ok im finally done!
# run the print code: can you hear me?
# go back to the beginning because the statements remains True
#IF YOU ENTER A LETTER THEN:
# run except ValueError code: please enter a number
# run the finally code: ok im finally done!
# run the continue: go back to the beginning
# IF YOU ENTER ZERO (0) THEN:
# run except ZeroDivisionError code: enter a number greater than 0
# run finally code: ok im finally done!
# run the break: exit the loop
while True:
try:
age = int(input('What is your age?'))
10/age
except ValueError:
print('please enter a number')
continue
except ZeroDivisionError:
print('enter a number greater than 0')
break
else:
print('Thank you')
finally:
print('ok im finally done!')
print ('can you hear me?')
| true |
2c48be82be2770cd0d323946e1a8af2154848ce1 | kanpicha2542/WorkShopp | /string/modify.py | 610 | 4.25 | 4 | string = " Hello, World! "
print(string.upper()) # output : "HeLLO, WORLD!"
print(string.lower()) # output : "hello, world!"
print(string.strip()) # output : "Hello, World!" กำจัดช่องว่างที่ไม่อยากให้มี
print(string.replace("H", "J")) # output : Jello, World! แก้ไขตัวอัคระเปลี่ยน H เป็น J
print(string.split(",")) # output : [' Hello', 'World!'] # ตัดประโยคด้วย ,
print(len(string)) # 15 # นัย String มีกี่อัคระ รวมเว้นวรรค
| false |
5d6144fd1841520626389ce25f7fc61d62d2fdd8 | onitonitonito/k_mooc_reboot | /module_turtle/turtle_letters_Idan.py | 1,678 | 4.40625 | 4 | """
# Draw Letters In Turtle
# https://stackoverflow.com/questions/43689387/draw-letters-in-turtle
"""
# [IMPORTANT] : CHECK! How to colntol
# - stting the window size
# - giving a scale to the letters
print(__doc__)
# from turtle import (Turtle, Screen,)
import turtle
NAME = "IDAN"
BORDER = 2
BOX_WIDTH, BOX_HEIGHT = 6, 10 # letter bounding box
WIDTH, HEIGHT = BOX_WIDTH - BORDER * 2, BOX_HEIGHT - BORDER * 2 # letter size
def letter_A(turtle):
turtle.forward(HEIGHT / 2)
for _ in range(3):
turtle.forward(HEIGHT / 2)
turtle.right(90)
turtle.forward(WIDTH)
turtle.right(90)
turtle.forward(HEIGHT)
def letter_D(turtle):
turtle.forward(HEIGHT)
turtle.right(90)
turtle.circle(-HEIGHT / 2, 180, 30)
def letter_I(turtle):
turtle.right(90)
turtle.forward(WIDTH)
turtle.backward(WIDTH / 2)
turtle.left(90)
turtle.forward(HEIGHT)
turtle.right(90)
turtle.backward(WIDTH / 2)
turtle.forward(WIDTH)
def letter_N(turtle):
turtle.forward(HEIGHT)
turtle.goto(turtle.xcor() + WIDTH, BORDER)
turtle.forward(HEIGHT)
LETTERS = {'A': letter_A, 'D': letter_D, 'I': letter_I, 'N': letter_N}
window = turtle.Screen()
window.setup(200, 100) # arbitrarly set the screen size, you can
window.title("Turtle writing my name: {}".format(NAME))
window.setworldcoordinates(0, 0, BOX_WIDTH * len(NAME), BOX_HEIGHT)
marker = turtle.Turtle()
for i, letter in enumerate(NAME):
marker.penup()
marker.goto(i * BOX_WIDTH + BORDER, BORDER)
marker.setheading(90)
if letter in LETTERS:
marker.pendown()
LETTERS[letter](marker)
marker.hideturtle()
window.mainloop()
| false |
7f975fdb559c9bf28dd75c99aef26bd7161cdff0 | rafaelpfreire/code-snippets | /exercises/bublesort.py | 774 | 4.34375 | 4 | # Difficulty: Easy
# Category: Sorting
#
# Write a function that takes in an array of integers and returns a sorted version of that array.
# Use the Bubble Sort Algorithm to sort the array.
#
# If you are unfamiliar with Bubble Sort, we recommend watching the Conceptual Overview section of
# this question's video explanation before starting to code
#
# Sample Input
# array = [8, 5, 2, 9, 5, 6, 3]
#
# Sample Output
# [2, 3, 5, 5, 6, 8, 9]
#
def bubbleSort(array):
notSorted = True
while(notSorted):
notSorted = False
for i in range(0,len(array)-1):
if array[i] > array[i+1]:
aux = array[i]
array[i] = array[i+1]
array[i+1] = aux
notSorted = True
return array
| true |
d108bf3944ba2d819419300f9e7ad6989de9af7a | vidyaakbar/260303_practice_dailycommit | /list.py | 388 | 4.21875 | 4 | # second smallest element
def find_length(lists):
length = len(lists)
lists.sort()
print("second smallest element is ", lists[1])
lists = [1, 2, 3, 4]
find_length(list)
# change nth value with (n+1)th value
list1 = [0, 1, 2, 3, 4, 5]
n = 2
new_list = []
for i in range (0, len(list1), n):
new_list.append(list1[i+1])
new_list.append(list1[i])
print(new_list)
| true |
f82dbb867f571753aa09dad2d41f25eb0bb7ae3f | CarolynMillMoo/pands-problem-sheets | /weeklyTask05pythonweekday.py | 359 | 4.3125 | 4 | #this program will check the date and
#output whether or not today is a weekday
#Author: Carolyn Moorhouse
import pandas as pd
def is_weekday(date):
return bool(len(pd.bdate_range(date, date)))
print("Check weekday or not?")
print('2021-04-04:', is_weekday('2021-04-04'))
print('2021-04-05:', is_weekday('2021-04-05'))
print('2021-04-06:', is_weekday('2021-04-06')) | true |
332cbc28d4e23e0bd4e7cd34ffe80691a80e8245 | ervaneet82/python | /practice/EDABIT/list_of_multiples.py | 292 | 4.46875 | 4 | '''
Create a function that takes two numbers as arguments (num, length)
and returns a list of multiples of num up to length.
list_of_multiples(7, 5) ➞ [7, 14, 21, 28, 35]
'''
def list_of_multiples (num, length):
return [i * num for i in range(1, length+1)]
print(list_of_multiples(7, 5)) | true |
a13de922fe1a1c0723bf7f3bf3229eae987e7454 | GetFreke/Trabajos | /Tuplas y listas/Tuplas y listas2.py | 250 | 4.15625 | 4 | print("Hace que no se repitan las letras por ejemplo puse Ha ha hola y no se repitio el A")
lista = []
cadena = input("Dame una cadena pe:")
for c in cadena:
if (c not in lista):
lista.append(c)
print(lista) | false |
80a7b738ec1ac2fe2c94f26698ff5c3740ef27db | marsied107/CS0008-f2016 | /Ch3-Ex/Ch3-Ex2.py | 742 | 4.40625 | 4 | #Asks for the length and width of the two rectangles
length1 = float(input('Enter the length of rectangle 1: '))
width1 = float(input('Enter the width of rectangle 1: '))
length2 = float(input('Enter the length of rectangle 2: '))
width2 = float(input('Enter the width of rectangle 2: '))
#Calculates the area of rectangle 1
area1 = length1 * width1
#Calculates the area of rectangle 2
area2 = length2 * width2
#Tells you what rectangle has the greatest area
if area1 > area2:
print('The area of rectangle 1 is greater than rectangle 2')
else:
if area2 > area1:
print('The area of rectangle 2 is greater than rectangle 1')
else:
if area1 == area2:
print('The area of rectangle 1 and 2 are the same') | true |
2f9572a9ce51f0155dd4067508d2af8146382997 | marsied107/CS0008-f2016 | /Ch4-Ex/Ch4-Ex5.py | 1,049 | 4.59375 | 5 | #Asks for the the number of years you want to enter
total_years = int(input('Enter the number of years: '))
#Loop that displays what year you are inputing
for years in range(total_years):
total = 0
print('Year', (years+1))
print('________________')
#Has you input the inches of rainfall for each month
print('Enter the inches of rainfall for each month')
all_months = ('January ', 'February ', 'March ', 'April ', 'May ', 'June ', 'July ', 'August ', 'September ', 'October ', 'November ',
'December ')
for month in all_months:
inches = float(input(month))
total += inches
#Gives the total inches of rainfall
total_inches = total
#Gives the total number of months
total_month = total_years * 12
#Gives the average amount of rainfall per month
average_inches = total / total_month
#Prints the calculated information
print('The total number of months is: ',(total_month))
print('The total inches of rainfall is: ',(total_inches))
print('The average amount of rainfall per month is: ',(average_inches))
| true |
44a5c522ff410f8c5b7ac0d539e2e206f1385498 | marsied107/CS0008-f2016 | /Ch3-Ex/Ch3-Ex3.py | 423 | 4.3125 | 4 | #Prompts the user to enter their age
age = int(input('Enter your age as a number: '))
if (age <= 1):
print('You are classified as an infant')
else:
if age == 1 < age < 13:
print('You are classified as a child')
else:
if age == 13 <= age < 20:
print('You are classified as a teenager')
else:
if age >= 20:
print('You are classified as an adult') | true |
a1c170eaaf912cbf6686113f15d7724bfabb7670 | ponica-jaya/LOCKDOWN-CODING | /even or odd .py | 363 | 4.1875 | 4 | Given a list of numbers, write a Python program to count Even and Odd numbers in a List.
n=int(input('Enter The Size Of List: '))
print('Enter The List Elements: ')
a=[]
oc=0
ec=0
for i in range(0,n):
a.append(int(input()))
for i in a:
if i%2==0:
ec+=1
else:
oc+=1
print('Total Even Numbers In a List: ',ec)
print('Total Odd Numbers In a List: ',oc)
| true |
cb4a9bcf623f6b81a6da218bfdc6fbd072349bf0 | 932626921/- | /rpsls_template.py | 2,556 | 4.1875 | 4 | #coding:gbk
"""
һСĿRock-paper-scissors-lizard-Spock
ߣγ
ڣ2019.11.20
"""
print("ӭʹRPSLSϷ")
print("----------------")
print("ѡ:")
print('--------------')
choice_name=input()
def ball(choice_name):
if choice_name!='ʯͷ' and choice_name!='ʷ' and choice_name!='ֽ' and choice_name!='' and choice_name!='':
print('Error:No Correct Name')
else:
print('ѡΪ:%s'%choice_name)
ball(choice_name)
import random
number=random.randint(0,4)
def number_to_name(number):
if number==0:
return('ʯͷ')
if number==1:
return('ʷ')
if number==2:
return('ֽ')
if number==3:
return('')
if number==4:
return('')
comp_choice=number_to_name(number)
print('ԵѡΪ:%s'%comp_choice)
def rpsls(choice_name,comp_choice):
if choice_name=="ʯͷ" and (comp_choice=="" or comp_choice==''):
print('Ӯ')
elif choice_name=='ʯͷ' and (comp_choice=='ֽ' or comp_choice=='ʷ'):
print('Ӯ')
elif choice_name=='ʯͷ' and comp_choice=='ʯͷ':
print('ƽ')
elif choice_name=='ʷ' and comp_choice=='ʷ':
print('ƽ')
elif choice_name=='ʷ' and (comp_choice=='' or comp_choice=='ʯͷ'):
print('Ӯ')
elif choice_name=='ʷ' and (comp_choice=='' or comp_choice==''):
print('Ӯ')
elif choice_name=='ֽ' and (comp_choice=='ʷ' or comp_choice=='ʯͷ'):
print('Ӯ')
elif choice_name=='ֽ' and (comp_choice=='' or comp_choice==''):
print('Ӯ')
elif choice_name=="ֽ" and comp_choice=="ֽ":
print('ƽ')
elif choice_name=='' and comp_choice=='ֽ' or comp_choice=='':
print('Ӯ')
elif choice_name=='' and comp_choice=='ʯͷ' or comp_choice=='ʷ':
print('Ӯ')
elif choice_name=='' and comp_choice=='':
print('ƽ')
elif choice_name=='' and comp_choice=='':
print('ƽ')
elif choice_name=='' and comp_choice=='ʷ' or comp_choice=='ֽ':
print('Ӯ')
elif choice_name=='' and comp_choice=='' or comp_choice=='ʯͷ':
print('Ӯ')
rpsls(choice_name,comp_choice)
| false |
e8d3574fe4070be43843bc0fe8e2c576e1aa47a7 | antonnifo/ADTs | /sum.py | 682 | 4.40625 | 4 | def sumArray(arr=[3, 5, -4, 8, 11, 1, -1, 6], target = 10):
'''check if there are any two elements that sums up to a given target in an array.
Args:
arr (list, optional): a list of integers or floats. Defaults to [3, 5, -4, 8, 11, 1, -1, 6].
target (int, optional): the desired target sum. Defaults to 10.
Returns:
a list of the two numbers otherwise none.
Run time:
linear time: O(n)
'''
index_map = {}
for index in range(len(arr)):
num = arr[index]
other = target - num
if other in index_map:
return [other, arr[index]]
index_map[num] = index
return None
| true |
61efc9bbae6541246c4fa301171c9432732e3c85 | kunaldesign/python-program | /program 30.py | 268 | 4.34375 | 4 | #program to convert decimal,binary,octal and hexadecimal.
dec=int(input('enter the number:: '))
print("the decimal value of %d is :"%dec)
print bin(dec),'in binary.'
print oct(dec),'in octal.'
print hex(dec),'in hexadecimal.'
raw_input ("press enter to exit..")
exit() | true |
cec502ef1f24576c45a853f7d031a1d86eab0cb9 | kunaldesign/python-program | /program 6.py | 223 | 4.21875 | 4 | # program to compute quotient and remainder
num1=int(input("enter the dividend: "))
num2=int(input("enter the divisor: "))
quotient=num1/num2
remainder=num1%num2
print('quotient= ',quotient)
print('remainder= ',remainder)
| true |
e4c49457d12b82c0889fe4a227ed1eb662607aaf | kunaldesign/python-program | /program 47.py | 751 | 4.1875 | 4 | #program to find profit or loss
#insert data
cost_price=float(input("enter cost price >> "))
selling_price=float(input("enter selling price >> "))
if (selling_price>cost_price):
#calculate profit
profit=selling_price-cost_price
print("you have profit of {}".format(profit))
#calculate profit persentage
profit_persentage=(profit/cost_price)*100
print("your profit persentage is {}%".format(profit_persentage))
else:
#calculate loss
loss=cost_price-selling_price
print("you go to loss of {}".format(loss))
#calculate loss persentage
loss_persentage=(loss/cost_price)*100
print("your loss persentage is {}%".format(loss_persentage))
#screen stopper
raw_input ("press enter to exit..")
exit() | true |
339207d9082ab701a04e0a60c0c00499ddf789cb | kunaldesign/python-program | /program 44.py | 2,094 | 4.125 | 4 | #program for text rotating in pygame(graphics)
#import a library of functions called 'pygame'
import pygame
import sys
#initialize the game engine
pygame.init()
#define some colours
BLACK=(0,0,0)
WHITE=(255,255,255)
BLUE=(0,0,255)
GREEN=(0,255,0)
RED=(255,0,0)
PI=3.141592653
#set the height and width of the screen
size=(400,500)
screen=pygame.display.set_mode(size)
pygame.display.set_caption("rotate text")
#loop until the user clicks the close button.
done=False
clock=pygame.time.Clock()
text_rotate_degrees=0
#loop as long as done==false
while not done:
for event in pygame.event.get(): #user did somethings
if event.type==pygame.QUIT: #if user clicked close
done=True #flag that we are done so we exit this loop
#all drawing code happens after the for loop and but inside the main while not done loop.
#clear the screen and set the screen and set the screen background
screen.fill(WHITE)
#draw some borders
pygame.draw.line(screen,BLACK,[100,50],[200,50])
pygame.draw.line(screen,BLACK,[100,50],[100,150])
#select the font to use, size, bold, italics
font=pygame.font.SysFont("calibri",25,True,False)
#sideways text
text=font.render("sideways text",True,BLACK)
text=pygame.transform.rotate(text,90)
screen.blit(text,[0,0])
#sideways text
text=font.render("upside down text",True,BLACK)
text=pygame.transform.rotate(text,180)
screen.blit(text,[30,0])
#flipped text
text=font.render("flipped text",True,BLACK)
text=pygame.transform.flip(text,False,True)
screen.blit(text,[30,20])
#animated rotation
text=font.render("rotating text",True,BLACK)
text=pygame.transform.rotate(text,text_rotate_degrees)
text_rotate_degrees+=1
screen.blit(text,[100,50])
#go a head and update the screen with what we've drawn.
#this must happen after all the other drawing commands.
pygame.display.flip()
#this limits the while loop to a max of 60 times per second.
#leave this out and we will use all CPU we can.
clock.tick(60)
pygame.quit() | true |
43f9715b8c34780832171eb1fba5c551ddfa7d84 | UalwaysKnow/-offer | /offer/细节实现/9.数值的整数次方.py | 402 | 4.125 | 4 | '''
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
'''
def power(base,exponent):
if base == 0:
return False
elif base == 1:
return 1
if exponent == 0:
return 1
elif exponent > 0:
for i in range(exponent-1):
base = base * base
return base
else:
for i in range(abs(exponent)-1):
base = base * base
base = 1/base
return base | false |
55ba2a2cb14416aa9d0e23d0a6ec1321fb638bcd | Chldse/Python__Projects | /Number_guess_Git.py | 1,409 | 4.25 | 4 | print(""" Let's see if you can read my mind!
I am thinking of a number between 1 and 20""")
def num_guess():
secret_num = "19"
user_guess = ""
#Setting guess count to zero so that counts can be added on as user guesses.
guess_count = 0
#The guess_limit variable stores the number of times I am allowing the user to take a guess.
guess_limit = 3
#Setting no_guesses variable to false to begin becasue when it becomes true, game ends.
no_guesses = False
###This while loop is saying: if the user has not guessed the correct answer and
###the user still has guesses avaiable it will iterate through the if statement until
###the conditions of the if-statement are met or the answer is guessed correctly.
while user_guess != secret_num and not (no_guesses):
if guess_count < guess_limit:
user_guess = input("Take a guess! ")
guess_count += 1
###If the conditons of the if-statement have not been met, the no_guesses variable
### are set to True, saying the user is out of guesses and the 2nd if-statement
### will print an ending message.
else:
no_guesses = True
if no_guesses:
print("You've lost user, I am sorry")
else:
print("Congratulations! You're a mind reader. ")
####If the user guesses correctly and the no_guesses variable is still false
### the else will print out a celebratory message.
num_guess()
| true |
1c05b8fc67191640924050d085c8496683daf9d0 | d03r/do | /python/Michigan/c10_tuple_lec_notes.py | 2,363 | 4.5 | 4 | x = ('Glenn', 'Sally', 'Joseph')
print x[2]
y = (1, 9, 2)
print y
print max(y)
# Tuples are 'immutable'
# Unlike a list, once you created a tuple, you cannot alter its contents
# similar to a string
# Tuples are more efficient
# Since Python does not have to build tuple structures to be modifiable,
# they are simpler and more efficient in terms of memory use and performance
# than lists
# So in our program when we are making 'temporary variables' we prefer tuples over lists
# Tuples and Assignment
# We can also put a tuple on the left hand side of an assignment statement
(x, y ) = (4, 'fred')
print x
print y
a, b = (99, 98) # can even remove parenthesis
print a
print b
# Tuples and Dictionaries
# The items() method in dictionaries return a list of (key, value) tuples
d = dict()
d['csev'] = 2
d['cewn'] = 4
for (k,v) in d.items():
print k,v
tups = d.items()
print tups
# Tuples are Comparable
# The comparison operators work with tuples and other sequences if the first
# item is equal, Python goes on to the next element, and so on, until it finds
# elements that differ.
print (0, 1, 2) < (5, 1, 2)
# Sorting Lists of Tuples
# We can take advantage of the ability to sort a list of tuples to get a
# sorted version of a dictionary
# First we sort the dictionary by the key using the items() method
d = {'a':10, 'b':1, 'c':22}
t = d.items()
print t # [('a', 10), ('c', 22), ('b', 1)]
t.sort()
print t # [('a', 10), ('b', 1), ('c', 22)]
# Using sorted()
# We can do this even more directly using the built-in function sorted
# that takes a sequence as a parameter and returns a sorted sequence
for k, v in sorted(d.items()):
print k, v
# Sort by values instead of key
# - If we could constructs a list of tuples of the form (value, key) we could sort by value
# - We do this with a for-loop that creates a list of tuples
c = {'a':10, 'b':1, 'c':22}
tmp = list()
for k, v in c.items():
tmp.append( (v, k) )
print tmp # [(10, 'a'), (22, 'c'), (1, 'b')]
tmp.sort(reverse=True) # [(22, 'c'), (10, 'a'), (1, 'b')]
print tmp
tmp.sort() # [(1, 'b'), (10, 'a'), (22, 'c')]
print tmp
# Adv
# Even Shorter Version
# List comprehension creates a dynamic list.
# In this case, we make a list of reversed tuples and then sort it.
c = {'a':10, 'b':1, 'c':22}
print sorted( [ (v,k) for k, v in c.items() ] ) # [(1, 'b'), (10, 'a'), (22, 'c')]
| true |
8c7e4310a6037e0646e0dce2c30490940d3f4f0b | d03r/do | /python/Enthought_Canopy_Training/Numpy_Arrays_Lect.py | 1,358 | 4.21875 | 4 | import numpy as np
# Simple Array Creation
lst = [0, 1, 2, 3]
a = np.array(lst)
print lst # [0, 1, 2, 3]
print a #[0 1 2 3]
# Checking the type
print type(a) # <type 'numpy.ndarray'>, upper limit of number of dimensions (nd) = 32
# Numeric 'Type' of Elements
print a.dtype # int64
# Bytes per elements
print a.itemsize # 8
# Array Shape
# - Shape returns a tuple listing the length of the array along each dimension
print a.shape # (4,)
print np.shape(a) # (4,)
# Array Size
# - Size repots the entire number of elements in an array
print a.size # 4
print np.size(a) # 4
# Bytes of Memory Used
# Return the number of bytes used by the data portion of the array
print a.nbytes # 32
# Number of Dimensions
print a.ndim # 1
# Array Indexing & Slicing
# Array Indexing
print a[0] # 0
a[0] = 10
print a # [10 1 2 3]
# Fill
# Set all values in an array
a.fill(0)
print a # [0 0 0 0]
# This also works, but may be slower.
a[:] = 1
print a # [1 1 1 1]
# Beware of type coercion
print a.dtype # int64
# Assigning a float into an int32 array truncates the decimal part
a[0] = 10.6
print a # [10 1 1 1]
# Fill has the same behavior
a.fill(-4.8)
print a # [-4 -4 -4 -4]
# Slicing
#
# var[lower:upper:step]
#
# Slicing arrays
# indices: 0 1 2 3 4
a = np.array([10, 11, 12, 13, 14])
print a # [10 11 12 13 14]
| true |
a6578fc689b9d3f8124b12f5f1cd72efbaaa1456 | azrap/Algorithms | /eating_cookies/eating_cookies.py | 1,357 | 4.1875 | 4 | #!/usr/bin/python
import sys
# The cache parameter is here for if you want to implement
# a solution that is more efficient than the naive
# recursive solution
# simple recursion way to solve eating cookies
def eating_cookies_1(n, cache=None):
if n < 2:
return 1
elif n == 2:
return 2
return eating_cookies_1(n-1)+eating_cookies_1(n-2) + eating_cookies_1(n-3)
# cache = {}
# incorporating cache to solve eating_cookies:
def eating_cookies(n, cache={}):
if n < 2:
return 1
if n == 2:
return 2
if n not in cache:
cache[n] = eating_cookies(
n-1)+eating_cookies(n-2) + eating_cookies(n-3)
return cache[n]
# solved eating_cookies iteratively
def eating_cookies_2(n, cache=None):
if n < 2:
return 1
elif n == 2:
return 2
n_0 = 1
n_1 = 1
n_2 = 2
count = 2
while count < n:
sum = n_0+n_1+n_2
n_0 = n_1
n_1 = n_2
n_2 = sum
count += 1
return sum
# print(eating_cookies_1(15))
if __name__ == "__main__":
if len(sys.argv) > 1:
num_cookies = int(sys.argv[1])
print("There are {ways} ways for Cookie Monster to eat {n} cookies.".format(
ways=eating_cookies(num_cookies), n=num_cookies))
else:
print('Usage: eating_cookies.py [num_cookies]')
| false |
96bcc484d8112f71a44b40df60a43f4ad4355c1e | RP-Eswar/PythonBasicFunctions | /list_overlap.py.py | 738 | 4.34375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
''''This is a python code that describes one method as a solution to the given problem statement.
Write a function list_overlap(list1,list2) that takes two lists of integers as input, and returns a list of the common elements. Don't use sets for this.
'''
def list_overlap( list1, list2):
common_list =[]
for x in list1:
for y in list2:
if int(x ) == int(y):
common_list.append(x)
return common_list
# try block to handle the exception
list_1 = input("Enter List - 1 elements").split( )
list_2 = input("Enter List - 2 elements").split( )
res_list = list_overlap(list_1, list_2)
print("Common elements")
print(res_list)
# In[ ]:
| true |
1c50c1cec9433b1b335d839622683166c9be3740 | AnoopKumarJangir/Python_Course | /Day 4/Challenge3.py | 754 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 26 15:27:14 2019
@author: Anoop K. Jangir
"""
#Challenge 3
#Importing random module to choose a random value bt the computer itself as save it in name of secret_number.
import random
secret_number=random.randint(0,10)
#Now taking a number by the user from the keboard and store it in the name of guess_number.
guess_number=int(input("Enter your number:"))
#After getting the number then compare them and show who win this guessing game between computer and user. Also printing the number high or low.
if(guess_number < secret_number):
print("The Guessing number is too low.")
elif(guess_number > secret_number):
print("The guessig number is too high.")
else:
print("Player Wins And Computer Loses.") | true |
de7b1bfb27d1d349fe2179147316e50c6b3eb825 | KateKapranova/cryptography | /caesar.py | 897 | 4.1875 | 4 | #caesar cipher implementation
dict={"A":0,"B":1,"C":2,"D":3,"E":4,"F":5,"G":6,
"H":7,"I":8,"J":9,"K":10,"L":11,"M":12,"N":13,"O":14,
"P":15,"Q":16,"R":17,"S":18,"T":19,"U":20,"V":21,"W":22,
"X":23,"Y":24,"Z":25," ":26}
n=27
key="F"
def encoding_shift(x):
encoded=(dict[x] + dict[key])%n
for k in dict.keys():
if dict[k]==encoded:
return k
def decoding_shift(x):
decoded = (dict[x]-dict[key])%n
for k in dict.keys():
if dict[k]==decoded:
return k
def caesarEncode(plain_text):
cipher=""
for i in range(len(plain_text)):
cipher+=encoding_shift(plain_text[i])
return cipher
print(caesarEncode("ALL CATS ARE BLACK AT NIGHT"))
def caesarDecode(cipher):
message=""
for i in range(len(cipher)):
message+=decoding_shift(cipher[i])
return message
print(caesarDecode("FQQEHFYXEFWJEGQFHPEFYESNLMY"))
| false |
4a906a80bb9dec595b7b7265d7fa67064367fcd9 | Alpensin/Pizza-Square-and-Price-counter | /pizza.py | 515 | 4.21875 | 4 | import math
def pizza_size_and_price(diameter, price: int, currency='$'):
'''
Enter pizza diameter and price as int (price*100)
Returns square of pizza and price of 1cm**2
Example
pizza_size_and_price(32, 600)
pizza_size_and_price(45, 900, 'rub.')
'''
pizza_square = math.pi*(diameter/2)**2
sm2_price = price/pizza_square
print(f'Pizza square: {round(pizza_square,2)} cm^2, Price for cm^2 {round(sm2_price,2)} {currency}')
return pizza_square, sm2_price
| true |
37385b54a25674135549fc93694d1a48c9c64e1c | yanlinpu/information | /arithmetic/sort/python/2_bubble_sort.py | 1,425 | 4.28125 | 4 | # -*- coding: utf-8 -*
'''
2. 冒泡排序(Bubble Sort)
原理
冒泡排序(Bubble Sort)是一种简单的排序算法。
它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。
走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。
1. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
2. 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。
3. 针对所有的元素重复以上的步骤,除了最后一个。
4. 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
'''
def bubble_sort(lists):
count = len(lists)
for i in range (count):
flag = True #标识符 步骤4
for j in range(1, count-i): # i = 0遍历所有元素 i>1 count-i到count 已排序=====如步骤2,3
if lists[j-1] > lists[j]:
lists[j-1],lists[j] = lists[j],lists[j-1] #如果前一个元素大于后一个元素 互换值
flag = False
if flag:
return lists
return lists
a = [3, 1, 5, 7, 2, 4, 9, 6, 8]
sorted = bubble_sort(a)
print(sorted) | false |
04b6140542ede66c574931afc1c7775f571d6b00 | aocsa/intro_to_python_solns | /code_challenges/letter_counter.py | 1,051 | 4.1875 | 4 | # write a function that counts the number of times a given letter appears in a document
# the output should be in a dictionary
def letter_counter(path_to_file, letters_to_count):
# create an empty dictionary
dictionary = {}
# go through each letter to count
for letter in letters_to_count:
# add each to dictionary
dictionary.update({letter : 0})
# go through each letter in the dictionary
for key in dictionary:
# open the file
with open(path_to_file) as new_file:
# examine each line
for line in new_file:
# go through each letter in that line
for letter in line:
# check if the key is the same as the letter
if letter == key:
# increase the value for that key by 1
dictionary[key] += 1
# output the results
return dictionary
if __name__=='__main__':
# run a test
test = letter_counter('data/test.txt', 'abcd')
print(test)
| true |
25157d6ff90038e03f108a0a8ebf22837005bc43 | Netra-Bahadur-khatri/Python_dajngo_By_Ranbindra_Joshi | /03_LessThanFive.py | 1,253 | 4.5 | 4 |
# Take a list, say for example this one:
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# and write a program that prints out all the elements of the list that are less than 5.
# Extras:
# Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.
# Write this in one line of Python.
# Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user.
# Program to print out all the elements that are less than five.
list_1 = [10,5,6,2,3,1,9]
def less_than_five_InList():
flag = True
for a in list_1:
if a <= 5:
print(a)
flag = False
if flag:
print("No elements in the list are less than five.")
# Program to return all the elements that are less than 5 in certain list.
def return_list_of_less_than_five(input_list):
less_than_five = []
for b in input_list:
if b <= 5:
less_than_five.append(b)
return less_than_five
if __name__ == "__main__":
less_than_five_InList()
new_list1 = [12,13,24,0,45,67,78,1,2,3,4]
x = return_list_of_less_than_five(new_list1)
print(x)
| true |
e0d6fd7957018744ddb0faf48ed39849630f5db3 | Netra-Bahadur-khatri/Python_dajngo_By_Ranbindra_Joshi | /01_100_Years.py | 853 | 4.15625 | 4 | # Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
# Extras:
# Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. (Hint: order of operations exists in Python)
# Print out that many copies of the previous message on separate lines. (Hint: the string "\n is the same as pressing the ENTER button)
# age = 12
import datetime
def user_age():
# global age
age = int(input("Enter user age: \n"))
return age
def PersonDetails():
now = datetime.datetime.now()
year = now.year
age = user_age()
to_100 = year + 100 - age
print('You will be 100 years old in ', to_100,' years')
if __name__ == "__main__":
PersonDetails()
| true |
7b9bcd00f2ee18a5211850f483d9eab7c08059f7 | rostonn/pythonW3 | /basic/27.py | 255 | 4.28125 | 4 | # write a program to concatenate all elements of a list into a string and print it
def concat_list(list):
string = ''
for item in list:
string = string + str(item)
print(string)
print(''.join(str(e) for e in list))
concat_list([1,2,3,'a','ee'])
| true |
9c08a193cf8072dffbdb1ce325acaabdf0c06706 | rostonn/pythonW3 | /list/6.py | 353 | 4.125 | 4 | # Program to sort list of tuples by the second tuple value
def sort_t(list):
ans = []
for i in range(len(list)):
for j in range(len(list)-1):
if list[j][1] > list[j+1][1]:
temp = list[j]
list[j] = list[j+1]
list[j+1] = temp
return list
sample = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
print(len(sample))
print(sort_t(sample))
| true |
2b4a1e357e271ca9b8e512a297bf957027a78705 | rostonn/pythonW3 | /strings/4.py | 277 | 4.1875 | 4 | # return a string where all occurences of first charcater replaced with $ except first character
def dollar_replace(string):
ans = string[1:]
print(ans)
ans = ans.replace(string[0],'$')
ans = string[0] + ans
return ans
test = dollar_replace("hehhooohhh");
print(test)
| true |
21b8bdccda14cacb503a5427531692c82415292a | ChampionJakkrit/204113_COMPUTER_PRINCIPLES | /Laboratory 4/HW04_2_600510533.py | 2,632 | 4.21875 | 4 | #!/usr/bin/env Python3
# จักรกฤษณ์ บุญเนตร
# 600510533
# HW 04
# Problem 2
# 204113 Sec 02A
# definition of node containing data and pointer to next node
class Node(object):
# constructor
def __init__(self, d, n=None):
self.data = d
self.next_node = n
# getter and setter method
def get_next(self):
return self.next_node
def set_next(self, n):
self.next_node = n
def get_data(self):
return self.data
def set_data(self, d):
self.data = d
#------------------end of class Node -------------------#
# Definition of class LinkedList containing root node location
class LinkedList(object):
def __init__(self, r=None):
self.root = r
def add(self, d):
new_node = Node(d, self.root)
self.root = new_node
# traverse along the list and print value of each node, seperate the
# value with " "
def print(self):
currnode = self.root
while currnode:
print(currnode.get_data(), end=" ")
currnode = currnode.get_next()
print()
# insert value d in the linked list with ascending order
def append(self, d):
newnode = Node(d, None) # สร้าง newnode
if self.root == None:
self.add(d)
else:
currnode = self.root # ตัวแรก
while currnode.get_next() != None:
currnode = currnode.get_next() # วนไปจนกว่าจะเจอตัวสุดท้าย ซึ่ง currnode จะเป็นตัวรองสุดท้าย
currnode.set_next(newnode) # ให้ currnode (ตัวสุดท้าย) ชี้ newnode(จะต่อหลัง)
def rprint(self):
currnode = self.root
list_curr = [] # สร้าง list
while currnode: # นับแต่ละตัวทั้งหมด
d = currnode.get_data()
list_curr.append(d) # ใส่ data ทีละตัวใน list
currnode = currnode.get_next() # ให้ currnode ชี้ตัวถัดไปเรื่อยๆ
re_list = reversed(list_curr) # กลับเลขใน list
for i in re_list: # วนทีละตัวใน list ที่กลับ
print(i, end = " ")
def main():
myList = LinkedList()
order = input().split(" ")
order = list(map(int, order))
for item in order:
myList.append(item)
myList.print()
myList.rprint()
if __name__ == '__main__':
main()
| true |
8fcfed6ce8b4f9241b7e5f1741458e06385efa75 | Delictum/python_algorithms_and_data_structures | /module8_graphs/task3_depth_first_search.py | 1,650 | 4.25 | 4 | """
Написать программу, которая обходит не взвешенный ориентированный граф без петель,
в котором все вершины связаны, по алгоритму поиска в глубину (Depth-First Search).
Примечания:
a. граф должен храниться в виде списка смежности;
b. генерация графа выполняется в отдельной функции, которая принимает на вход число вершин.
"""
from random import randint
def generate_adjacency_list_graph(n: "int count vertex"):
graph = []
for i in range(n):
vertex_path = []
for j in range(n):
if i != j and randint(0, 1): # если не создание петли и 50% вероятность создания
vertex_path.append(j)
elif j == n - 1: # если ни разу не везло и вершина не связалась с другими, принудительно свяжем с последней
vertex_path.append(j)
graph.append(vertex_path)
return graph
def depth_first_search(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
# print(start)
for next in set(graph[start]) - visited:
depth_first_search(graph, next, visited)
return visited
n = int(input('Введите кол-во вершин для генерации графа: '))
g = generate_adjacency_list_graph(n)
print(*g, sep='\n')
print(depth_first_search(g, 0))
| false |
e8b5285640b6a314c9bbe77dcc99e06aa8585180 | Delictum/python_algorithms_and_data_structures | /module01_intro_algorithmization_and_simple_algorithms/task6_triangle_type.py | 1,213 | 4.21875 | 4 | """
The task 6:
По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника,
составленного из этих отрезков. Если такой треугольник существует, то определить,
является ли он разносторонним, равнобедренным или равносторонним.
"""
fst_side_len = int(input("Введите певую сторону: "))
scd_side_len = int(input("Введите вторую сторону: "))
tht_side_len = int(input("Введите третью сторону: "))
if fst_side_len + scd_side_len <= tht_side_len or \
fst_side_len + tht_side_len <= scd_side_len or \
scd_side_len + tht_side_len <= fst_side_len:
print("Треугольник не существует")
elif fst_side_len == scd_side_len == tht_side_len:
print("Равносторонний")
elif fst_side_len != scd_side_len and fst_side_len != tht_side_len and scd_side_len != tht_side_len:
print("Разносторонний")
else:
print("Равнобедренный")
| false |
8ea195345db8f13501f45e263d461ec1a79c705b | Farah-H/engineering_74_python | /lists_and_tuples.py | 1,710 | 4.6875 | 5 | # # collection in python
# # lists?
# # we can add, remove , change an item in a list, they are MUTABLE
# # indexing starts with 0
# #syntax: my_list = [item1, item2, ...]
# shopping_list = ['apple', 'milk', 'bread']
# print(shopping_list)
# print(type(shopping_list))
# # Managing lists
# # look at indexing in the list items
# print(shopping_list[1])
# #print(shopping_list[start:end:step])
# # how can we add an item to our list
# shopping_list.append('eggs')
# print(shopping_list)
# # how can we remove an item from our list
# shopping_list.remove('apple')
# print(shopping_list)
# # how can we remove the item we just added later
# shopping_list.pop()
# print(shopping_list)
# # how can i replace an ittem in my list
# shopping_list[1] = 'fruits'
# mixed_shopping_list = [1, 2, 3, 'apple', 'milk', 'bread']
# print(mixed_shopping_list)
#task
# create mixed data list of 7 items
# display type of data
# add delete replace pop
# my_mixed_list = [1, 2.4, [1,3,4] , 'potato', 'porridge', 6.7, 10]
# for _ in my_mixed_list:
# print(_, type(_))
# #add
# my_mixed_list.append(600)
# print(my_mixed_list)
# #delete
# my_mixed_list.remove('potato')
# print(my_mixed_list)
# #replace
# my_mixed_list[1] = 'tomatoes'
# print(my_mixed_list)
# #pop
# my_mixed_list.pop()
# print(my_mixed_list)
# # use indexing to print the list in reverse order
# print(my_mixed_list[::-1])
# Tuples are IMMUTABLE - can't be changed
# Use case NI number, DOB, place of birth
# Sytax: we use commas to declare a tuple, but standard practice is also to encapsulate a tuple in ()
short_list = ('paracetemol', 'eggs', 'supermalt')
print(type(short_list))
#short_list[1] = 'fruits'
print(short_list[-1]) | true |
65a9eb28e256e773cb0c1d2ab142b0c51ed64bec | Mercurius13/Hacktoberfest2021-1 | /AddTwoNums.py | 220 | 4.125 | 4 | # just change Add to sum
num1 = input("Enter your first number:\n")
num2 = input("Enter your second number:\n")
# change Add to sum
sum = num1 + num2
print("Sum of {0} and {1} is {2}" .format(num1, num2, sum)) | true |
a8bd094bcdad5cf1abd8327d3a0418e01ede437b | Aaron250907/PythonCourse1 | /Factorial For Loop.py | 203 | 4.28125 | 4 | # Factorial Using For Loop
Number = int(input("Enter Any Number : "))
factorial = 1
for f in range (1, Number + 1) :
factorial = factorial * f
print("Factorial of", Number, "=", factorial)
| true |
60e625b9a434bb942986fbc886b881cc5b0c221b | Aaron250907/PythonCourse1 | /Palindrom.py | 234 | 4.53125 | 5 | String1 = input("Enter A Text String : ");
Reversed_String = String1[::-1]
if String1 == Reversed_String :
print("The String" ,String1, "is A Palindrome");
else:
print("The String", String1 ,"is not a Palindrome"); | false |
80d1b907cf697ce7d009ddc8f31d019c4a44049d | Aaron250907/PythonCourse1 | /List Operations.py | 1,747 | 4.28125 | 4 | # Differnet Operations On Lists
List1 = [
11, 22, 33, 44, 55, 66, 77, 88, 99
]# List of Integers
print('List1 = ',List1 )
print('Lenght = ',len(List1))
#len is used to find the length of the Elements
List1.insert(2,100)
print('List 1 With Insert Function', List1)
# Insert Used to Insert Charcthers in Lists at PARTICULAR INDEX POSITION
List1.append(200)
print('List1 with Append Function', List1)
# Append Used only to add charcter at the END OF TTHE LIST
List1.remove(77)
print('List1 when used remove Function to remove 77 ', List1)
# Remove is used to REMOVE A CHRACTER
A = List1.pop(6)
# Saves the Index Value fo the Integer and the Text String from the list and saves in another Variable
print('List1 with the pop function', List1)
print(A)
List1.reverse()
print(List1)
# Reverse Reverses the Order of the List
small_value = min(List1)
big_value = max(List1)
print('Minimum Value of List1 =',small_value)
print('Maximum Value of List1 = ', big_value)
# Inline Commands
print('Minimum Value of List1 =',min(List1))
print('Maximum Value of List1 =',max(List1))
List1.sort()
print(List1)
#Sort is used to SORT THE LIST IN ASCENDING ORDER
List2 = [20, 34, 58, 79, 65, 34]
List2.sort()
print(List2)
print(List2[0])
print(List2[-1])
print(List1)
print(List1[4:8])
print(List1[0:6])
print(List2[-4:-1])
#: Will Select Index From So and So
print(List2[1:])
# Prints From Index Value Till End of the List
print(List1[:5])
# Prints all index Values tii Index Value Written
print(List2[0:6:2])
# Select From index 0-5 at the Interval of 2
concat1 = [1,3,5,7,9]
concat2=[2,4,6,8,10]
concat3 =concat1 +concat2
print(concat3)
concat4 = concat1[1:3] + concat2[2:3] | true |
0541ba72c6fa82db892404516f0bd8000ed3abe2 | kaczifant/HackerRank-Problems-In-Python | /Language Proficiency/Easy/find_a_string.py | 813 | 4.40625 | 4 | # https://www.hackerrank.com/challenges/find-a-string/problem
'''
You have to print the number of times that the substring occurs in the given string.
String traversal will take place from left to right, not from right to left.
NOTE: String letters are case-sensitive.
For example:
string: 'ABCDCDC'
substring: 'CDC'
occurrence: 2
'''
# Complete the function below
def count_substring(string, sub_string):
count = 0
len_substring = len(sub_string)
for i in range(len(string)-len_substring+1):
if string[i:i+len_substring] == sub_string:
count += 1
return count
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
count = count_substring(string, sub_string)
print(count) | true |
0c55fbc063989aea74be0bc1475081ecfdb24eac | kaczifant/HackerRank-Problems-In-Python | /Data Structures/Easy/merge_two_sorted_linked_lists.py | 1,950 | 4.21875 | 4 | # https://www.hackerrank.com/challenges/merge-two-sorted-linked-lists/problem
#!/bin/python3
import math
import os
import random
import re
import sys
class SinglyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_node(self, node_data):
node = SinglyLinkedListNode(node_data)
if not self.head:
self.head = node
else:
self.tail.next = node
self.tail = node
def print_singly_linked_list(node, sep, fptr):
while node:
fptr.write(str(node.data))
node = node.next
if node:
fptr.write(sep)
# Complete the mergeLists function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def mergeLists(head1, head2):
if not (head1 or head2):
return
if not head1:
return head2
if not head2:
return head1
current_a = head1
current_b = head2
smallest = None
if head1.data <= head2.data:
head_merged = head1
smallest = current_a
current_a = smallest.next
else:
head_merged = head2
smallest = current_b
current_b = smallest.next
while current_a and current_b:
if current_a.data <= current_b.data:
smallest.next = current_a
smallest = current_a
current_a = smallest.next
else:
smallest.next = current_b
smallest = current_b
current_b = smallest.next
if not current_a:
smallest.next = current_b
if not current_b:
smallest.next = current_a
return head_merged
if __name__ == '__main__': | true |
06938f42f0ace928610770a44855a5d175844931 | GongXingXY/LearnPython100 | /Python100/1_15/day3_String_DataStructure/tuple.py | 2,167 | 4.375 | 4 | # Python 中的元组与列表类类似也是一种容器数据类型,可以用一个变量(对象)来存储多个数据,不同之处在于元组的元素不能修改,在前面的代码中
# 我们已经不止一次使用过元组了.顾名思义,我们把多个元素组合到一直
# 就形成了一个元组,所以它和列表一样可以保存多条数据.
# 定义元组
t = ('龚幸','38', True, '广东茂名')
print(t)
# 获取元组中的元素
print(t[0])
print(t[3])
# 遍历元组中的值
for member in t:
print(member)
# 重新给元组赋值
# t[0] = '王大多' # TypeError
# 变量t重新引用了新的元组原来的元组将被垃圾回收
t = ('王大多', 20, True, '云南昆明')
print(t)
# 将元组转换成列表
person = list(t)
print(person)
# 列表是可以修改它的元素的
person[0] = '李小龙'
person[1] = 25
print(person)
# 将列表转换成元组
fruits_list = ['apple', 'banana', 'orange']
fruits_tuple = tuple(fruits_list)
print(fruits_tuple)
'''
元组中的元素是无法修改的,事实上我们在项目中尤其是多线程环境(后面会讲到)中可能更喜欢使用的是那些不变对象(
一方面因为对象状态不能修改,所以可以避免由此引起的不必要的程序错误,简单的说就是一个不变的对象要比可变的对象更加容易维护
;另一方面因为没有任何一个线程能够修改不变对象的内部状态,一个不变对象自动就是线程安全的,这样就可以省掉处理同步化的开销。一个不变对象可以方便的被共享访问)。所以结论就是:如果不需要对元素进行添加、删除、修改的时候,可以考虑使用元组,当然如果一个方法要返回多个值,使用元组也是不错的选择。
元组在创建时间和占用的空间上面都优于列表。
我们可以使用sys模块的getsizeof函数来检查存储同样的元素的元组和列表各自占用了多少内存空间,这个很容易做到。
我们也可以在ipython中使用魔法指令%timeit来分析创建同样内容的元组和列表所花费的时间,下图是我的macOS系统上测试的结果。
'''
| false |
3dc599af3ea5555f28ed8f3d03323a064c98e4c5 | Adam-Of-Earth/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 354 | 4.28125 | 4 | #!/usr/bin/python3
"""module to read a number of lines"""
def read_lines(filename="", nb_lines=0):
"""prints lines from a file"""
with open(filename, encoding="UTF-8") as myFile:
if nb_lines <= 0:
print(myFile.read(), end="")
return
for i in range(nb_lines):
print(myFile.readline(), end="")
| true |
5bc9145d0e6dfcf1c6cdbb163dfbd9068f699d3b | Adam-Of-Earth/holbertonschool-higher_level_programming | /0x06-python-classes/3-square.py | 618 | 4.4375 | 4 | #!/usr/bin/python3
"""a class Square
Description of a square class
"""
class Square:
"""square shape
infomation about the square and how to use it
"""
def __init__(self, size=0):
"""Create a square size large
size(int): how large the size wil be
"""
if not isinstance(size, int):
raise TypeError("size must be an integer")
elif size < 0:
raise ValueError("size must be >= 0")
else:
self.__size = size
def area(self):
"""finds the squares area"""
return self.__size * self.__size
| true |
9482287ccd98005aa6a5cbc0c246101f80495add | TreidynA/CP1404_Practicals | /Prac_05/hex_colours.py | 594 | 4.3125 | 4 | NAME_TO_CODE = {"aquamarine1": "#7fffd4", "brown4": "#8b2323", "chartreuse3": "#66cd00", "Coral": "#ff7f50",
"darkgoldenrod": "#b8860b", "darkorchid": "#9932cc", "dodgerblue4": "#104e8b", "floralwhite": "#fffaf0",
"darlviolet": "#9400d3", "deepslategray": "#2f4f4f"}
print(NAME_TO_CODE)
colour_name = input("Enter colour name: ").lower()
while colour_name != "":
if colour_name in NAME_TO_CODE:
print(colour_name, "is", NAME_TO_CODE[colour_name])
else:
print("Invalid colour name")
colour_name = input("Enter colour name: ").lower() | false |
78a06ea049afc07e7cbb04d22e27963de6ab00a9 | vgrozev/SofUni_Python_hmwrks | /Programming Basics with Python - април 2018/03. Simple-Conditions/13. Area of Figures.py | 441 | 4.125 | 4 | import math
figure = input()
if figure == 'square':
side = float(input())
area = pow(side, 2)
elif figure == 'rectangle':
side1 = float(input())
side2 = float(input())
area = side1 * side2
elif figure == 'circle':
radius = float(input())
area = math.pi * pow(radius, 2)
elif figure == 'triangle':
base = float(input())
height = float(input())
area = base * height / 2
print("{0:.3f}".format(area))
| false |
5e9f3d7fef9d0e8dc59b7bdf536686046914d0ae | CesarPalomeque/tarea1_DiaposiTiVas | /ejercicio13.py | 822 | 4.125 | 4 | class Estructuras_Ciclicas:
#Diseñe un código para calcular la suma y producto de N números enteros, utilizando un bucle controlado por el usuario.
def __init__(self):
pass
#BUCLE CONTROLADO POR CONDICIÓN
def estructuraCic3(self):
suma=0
producto=1
print("Desea continuar [S/N]: ")
resp= input().capitalize()
while resp == "S":
num= int(input("Ingrese un número: "))
suma= suma+num
producto= producto*num
print("El total de la suma es: {}" .format(suma))
print("El total del producto es: {}" .format(producto))
print("Desea continuar [S/N]: ")
resp=input().capitalize()
clase1= Estructuras_Ciclicas()
clase1.estructuraCic3() | false |
ed269ee1e2b6c0464249d8b9aa08ba8944c1d427 | brucewayne1248/Machine-Learning-A-Z | /numpy_class/python_classes.py | 717 | 4.125 | 4 | # Python Object-Oriented Programming
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
def fullname(self):
return ('{} {}'.format(self.first, self.last))
emp_1 = Employee('Corey', 'Schafer', 50000)
#emp_1.first = 'Corey' #manually instances can be added
#emp_1.last = 'Schafer'
#emp_1.pay = 50000
#print(emp_1.email)
#print('{} {}'.format(emp1_first, emp_1.last)) # manually printing
print(emp_1.fullname())
# equal lines
print(Employee.fullname(emp_1))
# when classes are generally called
| true |
df6c49bcb814af25cc8c97e88f2de1d999fe180b | terahratheheart/heaps | /heaps/heap_sort.py | 354 | 4.15625 | 4 |
from heaps.min_heap import MinHeap
def heap_sort(nums):
""" This method uses a heap to sort an array.
Time Complexity: ?
Space Complexity: ?
"""
heap = MinHeap()
for num in nums:
heap.add(num)
index = 0
while not heap.empty():
nums[index] = heap.remove()
index += 1
return nums
| true |
de03a58bfd71925c6660aebea0ae2d5f7a99ff82 | prabhathkota/Python_Scripts | /list_2.py | 390 | 4.1875 | 4 | students = ["Mahatma Gandhi", "Mother Teresa", "Paul Coelho", "Bill Gates", "Steve Jobs"]
new_students = students[:]
for student in new_students:
print("Do you want to keep student", student, "?")
#print "Do you want to keep student", student, "?"
answer = input("yes/no ")
#answer = raw_input ("yes/no ")
if answer != "yes":
students.remove(student)
print(students)
#print students
| false |
675c4a8dda8f2359cfb3ee27ea767eb1bad049e7 | prabhathkota/Python_Scripts | /closures/global_vs_nonlocal.py | 2,170 | 4.21875 | 4 | #########################
# Global Scope Vs Enclosing Scope Vs Local Scope
# LEGB rule
# Local(L): Defined inside function/class
# Enclosed(E): Defined inside enclosing functions(Nested function concept)
# Global(G): Defined at the uppermost level
# Built-in(B): Reserved names in Python builtin modules
#########################
message = 'global'
def enclosing():
message = 'enclosing'
def local():
message = 'local'
print('enclosing message: ', message)
local()
print('enclosing message: ', message)
def enclosing_nonlocal():
message = 'enclosing'
def local():
nonlocal message # This refers to the above message in enclosing scope, not in global scope
message = 'local'
print('enclosing message: ', message)
local()
print('enclosing message: ', message)
def enclosing_global():
message = 'enclosing'
def local():
global message
message = 'local' # Here you are updating message in global scope, not in enclosing scope
print('enclosing message: ', message)
local()
print('enclosing message: ', message)
if __name__ == '__main__':
print('------------------------------------')
print('global message: ', message)
enclosing()
print('global message: ', message)
print('----------------NONLOCAL------------------')
print('global message: ', message)
enclosing_nonlocal()
print('global message: ', message)
print('----------------GLOBAL--------------------')
print('global message: ', message)
enclosing_global()
print('global message: ', message)
print('------------------------------------')
"""
Output:
------------------------------------
global message: global
enclosing message: enclosing
enclosing message: enclosing
global message: global
----------------NONLOCAL------------------
global message: global
enclosing message: enclosing
enclosing message: local
global message: global
----------------GLOBAL--------------------
global message: global
enclosing message: enclosing
enclosing message: enclosing
global message: local
------------------------------------
"""
| true |
45ec5dfa10138c5c04197865ab06ad5200f4444e | naveenjaglan/Project-2 | /01_Basics.py | 823 | 4.3125 | 4 | # some operations in numbers
print(2+2)
print(8%4)
print(4/2)
# here we got 2.0 not 2 because it give us float which means floating point representation, in which "." used after numbers.
# if you divide 5 by 2 then you want 2.5 not 2 so it convert this int into float to give you 2.5 as output then 2.0.
# if you want answer in integer than use double slash.
print(5//2)
print(8+9-10)
print(8+2-7+(0+30-12))
# cube function
print(2**12)
# Mod operator: gives the remainder.
print(10%3)
'''
String- Combination of characters, you can use double quote or single quote to write string.
'''
print("navin")
print('navin')
print('navin\' ')
print('navin\'s laptop')
print(10*"navin")
print("c:\docs\navin")
#raw string - removes all functions
print(r'c:\docs\navin')
# how to write backslash in python
print("2\\2") | true |
e96c689b42290c0e7df2c665fd53b9f5f43a0ad7 | berachele/Leetcode-problems | /sum.py | 731 | 4.3125 | 4 | # Find all the pairs of two integers in an unsorted array that sum up to a given S.
# For example, if the array is [3, 5, 2, -4, 8, 11] and the sum is 7, your program should return [[11, -4], [2, 5]]
# because 11 + -4 = 7 and 2 + 5 = 7.
def find_sum(array, sum):
#have a rsults list
results = []
#iterate through array as a nest for loop
for num1 in array:
for num2 in array:
if num1 > num2:
if (num1 + num2) == sum:
results.append([num1, num2])
#does it add to the sum?
else:
continue
#if yes, add to results
return results
myarray = [3, 5, 2, -4, 8, 11]
sum = 7
print(find_sum(myarray, sum)) | true |
b3e88cb255e7a1a0d8c77fda49949b17ff437470 | AStillwell/Chapter_5 | /Challenge.py | 593 | 4.125 | 4 | # Chapter 5, Challenge 1
# Author: Alton Stillwell
# Date: 11/12/14(mm/dd/yy)
##########################
# Design
# create a list named 'words' to store mult. words
# create a loop to put all the words in a variable 'newWords'
# in a random order, not repeating the word
# Print 'newWords'
##########################
import random
# List
WORDS = ["The","Man","Sat","On","Sky","Apple","Wart","Car","Medicine"]
newWords = ""
# Loop
while WORDS:
word = random.randrange(len(WORDS))
newWords = newWords + WORDS[word] + " "
WORDS = WORDS[:word]+ WORDS[(word+1):]
# Final Output
print (newWords)
| true |
1f9a55a1d3de4e2f323615426b3a78df0fa5c7fa | SMAK1993/Train-Routes | /node.py | 1,231 | 4.25 | 4 | """
Definition of the Node Class
"""
class Node:
"""
Custom Node Class
"""
def __init__(self, name):
"""
Constructor for Node objects.
Initialize node's name to :param name & connected_to to empty dictionary
:param name: name of node object
:attribute name: name of node object
:attribute connected_to: dictionary of neighbor nodes where key is
Node object and value is edge weight
"""
self.name = name
self.connected_to = {}
def add_neighbor(self, neighbor, weight=0):
"""
Adds neighbor node to this node's connected_to dictionary
:param neighbor: neighbor node object
:param weight: optional weight of edge to neighbor (defaults to 0)
"""
self.connected_to[neighbor] = int(weight)
def get_connections(self):
"""
Return a list of node objects that are neighbors to this node
"""
return self.connected_to.keys()
def get_weight(self, neighbor):
"""
Return the edge weight to the neighbor of this node object
:param neighbor: adjacent node object to current node
"""
return self.connected_to[neighbor]
| true |
4f3ce1440f47b0e6e67db32db888f5b721943f1e | sushyamr/Intro-to-CS | /Midterm/deep_reverse_forloop.py | 801 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 14 06:31:24 2018
@author: sushy
"""
def deep_reverse(L):
""" assumes L is a list of lists whose elements are ints
Mutates L such that it reverses its elements and also
reverses the order of the int elements in every element of L.
It does not return anything.
"""
for l in L:
#l.reverse() reverse the list within
size = len(l)
templ = l.copy()
for i in range(size):
l[i] = templ[(size - 1) - i]
#now reverse L in similar fashion
sizeL = len(L)
tempL = L.copy()
for i in range(sizeL):
L[i] = tempL[(size - 1) - i]
testL = [[1], [8, 4], [5, 6, 7], [2, 5, 7, 8]]
print(testL)
deep_reverse(testL)
print(testL) | true |
fe71df166f9dfd625ab45916111ed1c7c7743b69 | mnipshagen/monty | /2018/12/analysis.py | 962 | 4.1875 | 4 | """
Plots reaction time against distance to stimulus with data read from a file.
Reads in data from a file named `experiment.csv`, which needs to supply the
field values `circle_x` and `circle_y` which give the stimulus position, and
`reaction_time` for the reaction time in milliseconds.
It then calculates the distance from the center to the stimulus and plots the
reaction time against the calculated distance. It assumues that the distance
is in pixels.
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# get the csv data and calculate the distance.
# saving it in a new column for accessability
df = pd.read_csv("experiment.csv")
df['dist'] = np.sqrt(df['circle_x']**2 + df['circle_y']**2)
# on to the plot
fig, ax = plt.subplots() # subplots defaults to a single plot
# reactiontime over distance
ax.scatter(df['dist'], df['reaction_time'])
ax.set_xlabel("distance in pixels")
ax.set_ylabel("reaction time in ms")
plt.show() | true |
e48495ecc483d59e30a524bc7697061d48f8872a | Flipswxtch/Python-Crash-Course | /Chapter 6/try_it_6_4.py | 878 | 4.4375 | 4 | # create a dictionary
glossary = {
'variable' : 'named space in memory for data',
'tuple' : 'immutable list',
'dictionary' : 'container for key-value pairs that can hold any amount of information',
'title' : 'method that capitalizes the first letter of a word',
'sorted' : 'method that sorts data passed to it; ie, list, dictionary',
}
# add three key-value pairs to dictionary
glossary['print'] ='function that prints chosen characters, variables, or other output to screen'
glossary['slice'] = 'tool that allows a user to perform work on specifically selected items in a list'
glossary['operands'] = """symbols that are used to set values equal to one another, \
check if values are equal to each other, and other things."""
# loop through all items in dictionary, print items
for term, definition in glossary.items():
print(f"{term} : {definition}") | true |
76c2799c0a40157cb55c97f0e10e89bab5ec5e42 | Flipswxtch/Python-Crash-Course | /Chapter 7/move_items_between_lists.py | 936 | 4.21875 | 4 | # create a list and set values equal to users who've not been confirmed
unconfirmed_users = ['alice', 'brian', 'candice']
# create empty list to store users after they've been confirmed
confirmed_users = []
# create while loop that continues until no values exist in unconfirmed
# users list
while unconfirmed_users:
# create variable and set it equal to a user in the unconfirmed
# users list while simultaneously removing the value from the list
current_user = unconfirmed_users.pop()
# print a statement for each user in the unconfirmed list
print(f"Verifying user: {current_user.title()}")
# add unconfirmed user to confirmed list
confirmed_users.append(current_user)
# print a simple statement to screen
print(f"\nThe following users have been confirmed:")
# iterate through each user in the confirmed user list and print them.
for confirmed_user in confirmed_users:
print(confirmed_user.title()) | true |
12efe79302475436cf9daa896a1e1aae2c85c010 | Flipswxtch/Python-Crash-Course | /Chapter 3/try_it.py | 904 | 4.1875 | 4 | who_id_invite = ['grandma', 'Ben', 'Ryen']
print(f"I miss you {who_id_invite[0].title()}, would you like to go get dinner?")
print(f"Hello, {who_id_invite[1].title()} and {who_id_invite[-1].title()}. Do you guys want to get dinner tonight?")
print(f"{who_id_invite[-1].title()} can't make it.")
who_id_invite[-1] = 'dustin'
print(f"I asked {who_id_invite[-1].title()} if he wanted to come along instead.")
print('\n\n\n')
print("I was able to find a bigger table so more people can be invited!")
who_id_invite.insert(0, 'tim')
who_id_invite.insert(0, 'mom')
who_id_invite.append('dad')
print(f"I've decided to invite {who_id_invite[0].title()}, {who_id_invite[1].title()}, and {who_id_invite[-1].title()} to the dinner as well.\n\n")
for guest in who_id_invite:
print(f"This is an invitation to {guest.title()} for dinner tonight")
print(f"I am inviting {len(who_id_invite)} people to dinner") | false |
36192a2ecc232a52ac9d5cf2ccabe065da854561 | jaskaranskalra/Python | /Calculator.py | 1,372 | 4.21875 | 4 | # In[41]:
def calculate():
Number_1 = int(input('Enter your first number: '))
Number_2 = int(input('Enter your second number: '))
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
if operation == '+':
#Addition
print ('{} + {} = '.format(Number_1, Number_2))
print (Number_1 + Number_2)
elif operation == '-':
#Substraction
print ('{} - {} = '.format(Number_1, Number_2))
print (Number_1 - Number_2)
elif operation == '*':
#Multiplication
print ('{} * {} = '.format(Number_1, Number_2))
print (Number_1 * Number_2)
elif operation == '/':
#Division
print ('{} / {} = '.format(Number_1, Number_2))
print (Number_1 / Number_2)
else:
print ('Operator types is not a valid operator, please run the program again.')
calculate_again()
def calculate_again():
# new input from user
calc_again = input('''Do you want to calculate again?
Please type Y for Yes or N for No.''')
if calc_again.upper() == 'Y':
calculate()
elif calc_again.upper() == 'N':
print('Thanks for using the program. See you again!')
else:
calculate_again()
# In[42]:
calculate()
| true |
d2b6c917472e7c08b6397ef81b933ff43b85ac91 | rendersonjunior/UriOnlineJudge-Python | /1133_Rest_of_a_Division.py | 703 | 4.1875 | 4 | # Rest of a Division
"""
Write a program that reads two integer numbers X and Y.
Print all numbers between X and Y which dividing it by 5 the rest is equal to 2 or equal to 3.
Input
The input file contains 2 any positive integers, not necessarily in ascending order.
Output
Print all numbers according to above description, always in ascending order.
Input Sample
10
18
Output Sample
12
13
17
"""
def main():
x = int(input())
y = int(input())
# troca valores para colocar em sequencia
if x > y:
x, y = y, x
for i in range(x+1, y, 1):
if i % 5 == 2 or i % 5 == 3:
print(i)
if __name__ == "__main__":
main()
| true |
e91b0bec8adb1f02504af4710b551222255ea0e0 | rendersonjunior/UriOnlineJudge-Python | /1142_PUM.py | 573 | 4.40625 | 4 | # PUM
"""
Write a program that reads an integer N.
This N is the number of output lines printed by this program.
Input
The input file contains an integer N.
Output
Print the output according to the given example.
Input Sample
7
Output Sample
1 2 3 PUM
5 6 7 PUM
9 10 11 PUM
13 14 15 PUM
17 18 19 PUM
21 22 23 PUM
25 26 27 PUM
"""
def main():
N = int(input())
pum = 0
for i in range(N):
print(str(pum + 1) + " " + str(pum + 2) + " " + str(pum + 3) + " PUM")
pum += 4
if __name__ == "__main__":
main() | true |
1f85802f5814a4e726ae86a51bd763a72147b555 | rendersonjunior/UriOnlineJudge-Python | /1144_Logical_Sequence.py | 893 | 4.375 | 4 | # Logical Sequence
"""
Write a program that reads an integer N.
N * 2 lines must be printed by this program according to the example below.
For numbers with more than 6 digits, all digits must be printed
(no cientific notation allowed).
Input
The input file contains an integer N (1 < N < 1000).
Output
Print the output according to the given example.
Input Sample
5
Output Sample
1 1 1
1 2 2
2 4 8
2 5 9
3 9 27
3 10 28
4 16 64
4 17 65
5 25 125
5 26 126
"""
def main():
try:
n = int(input())
assert(1 < n < 1000)
for i in range(n):
value = int(i+1)
print(str(value) + " " + str(pow(value, 2)) + " " + str(pow(value, 3)))
print(str(value) + " " + str(pow(value, 2)+1) + " " + str(pow(value, 3)+1))
except AssertionError:
pass
if __name__ == "__main__":
main()
| true |
0b1180f54637f3830c7c53ad444722e8953e366a | balishweta/Hello_git | /assignment_19.py | 1,914 | 4.5625 | 5 | # Q.1 - Create a numpy array with 10 elements of the shape(10,1) using np.random and find out the mean of the elements using basic numpy functions.
# import numpy as np
# new_array = np.random.random((10, 1))
# print(new_array)
#
# print('Applying mean() function:')
# print(np.mean(new_array))
# Q.2 - Create a numpy array with 20 elements of the shape(20,1) using np.random find the variance and standard deviation of the elements.
# import numpy as np
#
#
# new_array = np.random.random((20, 1))
# print(new_array)
#
# print('Apply standard deviation() fn')
# print(np.std(new_array))
#
#
# print('Apply varianace () fn')
# print(np.var(new_array))
# Q.3 - Create a numpy array A of shape(10,20) and B of shape (20,25) using np.random. Print the matrix which is the matrix multiplication of A and B.
# The shape of the new matrix should be (10,25). Using basic numpy math functions only find the sum of all the elements of the new matrix.
# import numpy as np
#
# A = np.random.random((10, 20))
# B = np.random.random((20, 25))
# print('Printing the matrix multiplication')
# C = np.dot(A, B)
# print(C.shape)
#
# print(C)
# print('Finding the sum of all the elements')
# print(np.sum(C))
# #Q.4 - Create a numpy array A of shape(10,1).Using the basic operations of the numpy array generate an array of shape(10,1)
# such that each element is the following function applied on each element of A.
#
# f(x)=1 / (1 + exp(-x))
# Apply this function to each element of A and print the new array holding the value the function returns
# Example:
# a=[a1,a2,a3]
# n(new array to be printed )=[ f(a1), f(a2), f(a3)]
import numpy as np
import math
def f(x):
return 1 / (1 + math.exp(-x))
A = np.arange(10).reshape(10, 1)
print(A)
S = np.empty([])
for i in A:
S = np.copy(f(A[i]))
print(S)
#
#
# for i in A:
# S[i] = f(A[i])
| true |
f0298b52af4a9b4eac369ee7261974b9ad851c4f | balishweta/Hello_git | /Assignment_3.py | 1,936 | 4.46875 | 4 | # ASSIGNMENT-3 DATA TYPES
#
# Q.1- Create a list with user defined inputs.
list_days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
print(list_days)
# Second way---if inputs are required from the user
a = []
n1 = int(input("Enter number of elements:"))
for i in range(1, n1+1):
b = int(input("Enter element:"))
a.append(b)
print(a)
# Q.2- Add the following list to above created list:
# [‘google’,’apple’,’facebook’,’microsoft’,’tesla’]
list_company = ['google', 'apple', 'facebook', 'microsoft', 'tesla']
list_days.extend(list_company)
print(list_days)
# Q.3- Count the number of time an object occurs in a list.
my_list = ['google', 'apple', 'facebook', 'microsoft', 'tesla', 'google', 'tesla', 'google', 'tesla', 'facebook']
my_list.count('google')
my_list.count('apple')
my_list.count('facebook')
my_list.count('microsoft')
my_list.count('tesla')
# Q.4- create a list with numbers and sort it in ascending order.
my_number_list = [23, 12, 33, 44, 57, 34, 10]
my_number_list.sort()
my_number_list
# Q.5- Given are two one-dimensional arrays A and B which are sorted in ascending order. Write a program to merge
# them into a single sorted array C that contains every item from arrays A and B, in ascending order. [List]
A = [34, 4, 67, 89]
A.sort()
B = [5, 55, 76, 12, 3, 4, 89]
B.sort()
C = A+B
C.sort()
print(C)
# Q.6-Implement a stack and queue using lists.
# stack implementation
stack = ["google", "apple", "facebook"]
print(stack)
stack.append("tesla")
print(stack)
stack.append("microsoft")
print(stack)
print(stack.pop())
print(stack)
print(stack.pop())
print(stack)
# queue implementation
# adding the elements
queue = []
for i in range(0, 5):
queue.append(i)
print(queue)
# removing the elements
while queue:
j = queue.pop(0)
print(queue)
| true |
a944090a087d68145757f0bf9ce0ccecc5317778 | ArnasKundrotas/algos-python | /selection-sort.py | 2,818 | 4.28125 | 4 | # Selection sort
# Sort given array from lowest to highest values
# Selection sort is an in-place comparison sorting algorithm.
# It has an O(n²) time complexity, which makes it inefficient on large lists.
# example arr [5,3,6,2,10]
def find_smallest_arr_value(arr):
smallest_arr_value = arr[0] # 5
smallest_arr_index = 0
print(arr)
# [5, 3, 6, 2, 10]
# [5, 3, 6, 10]
# [5, 6, 10]
# [6, 10]
# [10]
for i in range(1, len(arr)): # example [5,3,6,2,10] -> loops i -> 4 times
#1.
#2.
#3.
#4.
if arr[i] < smallest_arr_value:
smallest_arr_value = arr[i]
smallest_arr_index = i
# [5,3,6,2,10]
# 1. arr[1]<arr[0] -> 3 < 5 -> smallest_arr_value = 3 -> smallest_arr_index = 1 -> print
# 2. arr[2]<3 -> 6 < 3
# 3. arr[3]<3 -> 2 < 3 -> smallest_arr_value = 2 -> smallest_arr_index = 3 -> print
# 4. arr[4]<2 -> 10 < 2
# [5,3,6,10]
# 1. arr[1]<arr[0] -> 3 < 5 -> smallest_arr_value = 3 -> smallest_arr_index = 1 -> print
# 2. arr[2]<3 -> 6 < 3
# 4. arr[3]<3 -> 10 < 3
# [5,6,10]
# 1. arr[1]<arr[0] -> 6 < 5
# 2. arr[2]<5 -> 10 < 5
# [6,10]
# 1. arr[1]<arr[0] -> 10 < 6
# [10]
print (smallest_arr_value, smallest_arr_index)
# 3 1 -> [5,3,6,2,10]
# 2 3 -> [5,3,6,2,10]
# 3 1 -> [5,3,6,10]
return smallest_arr_index # 3
# 3 -> 2
# 1 -> 3
# 0 -> 5
# 0 -> 6
# 0 -> 10
def selec_sort(arr):
new_arr = []
for i in range(len(arr)): # example [5,3,6,2,10] -> loops i -> 0,1,2,3,4 -> 5 loops
#0
#1
#2
#3
#4
smallest_arr_value = find_smallest_arr_value(arr)
# 3 -> 2
# 1 -> 3
# 0 -> 5
# 0 -> 6
# 0 -> 10
print(arr)
# [5, 3, 6, 2, 10]
# [5, 3, 6, 10]
# [5, 6, 10]
# [6, 10]
# [10]
new_arr.append(arr.pop(smallest_arr_value)) # arr.pop(arr index) -> 3,1,0,0,0
#[2]
#[2, 3]
#[2, 3, 5]
#[2, 3, 5, 6]
#[2, 3, 5, 6, 10]
return new_arr
print (selec_sort ([5,3,6,2,10]))
# [2, 3, 5, 6, 10]
print (selec_sort ([5,3,6,2,10,95,87,63,42,59,156,2849,3254,1256,1,1,23,65]))
# [1, 1, 2, 3, 5, 6, 10, 23, 42, 59, 63, 65, 87, 95, 156, 1256, 2849, 3254]
print (selec_sort ([5,3,6,2,10,95,87,63,42,59,156,2849,3254,1256,1,1,23,65,-1]))
# [-1, 1, 1, 2, 3, 5, 6, 10, 23, 42, 59, 63, 65, 87, 95, 156, 1256, 2849, 3254] | false |
a254c85fca8345d0a31c1546c78e18a872146067 | jairo-diazjanica/cit-129-2019-fall | /week2_loops_final.py | 1,832 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Joe Holleran
Python 2
09/11/2019
Week 2 - Exercises Loops!
"""
def main():
challenge_one()
challenge_two()
challenge_three()
challenge_four()
challenge_five()
def challenge_one():
print("Challenge One")
print("-------------------------")
for num in range(2, 101, 2):
print(num, end=", ")
print("\n")
def challenge_two():
print("Challenge Two")
print("-------------------------")
word = "KABOOM"
for letter in word:
print(letter, end=" ")
for x in letter:
print(x, end=" ")
for x in letter:
print(x, end=" ")
print("\n")
def challenge_three():
print("Challenge Three")
print("-------------------------")
gibberish = "askaliceithinkshe'llknow"
for letter in gibberish[::2]:
print(letter, end=" ")
print("\n")
def challenge_four():
print("Challenge Four")
print("-------------------------")
for num in range(1,5):
for number in range(5,8):
mult = num * number
print(num, "|", number, "|", mult)
print("\n")
def challenge_five():
print("Challenge Five")
print("-------------------------")
listoflists = [['mn', 'pa', 'ut'], ['b','p','c'], ['echo', 'charlie', 'tango']]
labels = {"state":"US State Abbr: ", "element":"Chemical Element: ", "alpha": "Phonetic Call: "}
for item in listoflists[0]:
print(labels.get("state"), item.upper())
for item in listoflists[1]:
print(labels.get("element"), item.upper())
for item in listoflists[2]:
print(labels.get("alpha"), item.upper())
print("\n")
if __name__ == "__main__":
main()
| false |
c104e6d6aa8532db3ad0448bf57cc035fb8ebc65 | shreykoradia/Python-with-Data-Science | /prac3.py | 390 | 4.28125 | 4 | # A school method based Python3 program
# to check if a number is prime
# function check whether a number
# is prime or not
n = int(input("Enter a valid Number"))
def isPrime(n):
# Corner case
if (n <= 1):
return False
# Check from 2 to n-1
for i in range(2, n):
if (n % i == 0):
return False
return True
# Driver Code
if isPrime(n):
print("true")
else:
print("false")
| true |
80b053fb1571d212243edc68ec6f7ada696f05d2 | shreykoradia/Python-with-Data-Science | /pract6-0.py | 461 | 4.46875 | 4 | #Given a string of odd length greater than 7, return a new string made of the middle three characters of a given String
def get_middle_char(string):
if len(string) % 2 == 0:
return None
elif len(string) <= 1:
return None
str_len = int(len(string)/2)
return string[str_len]
def main():
print('Enter a odd length string: ')
odd_string = input()
print('The middle character is', get_middle_char(odd_string))
main() | true |
79c65b2d2f9d4b7958837caf1bc7d1e3faa8a06b | GreatBahram/exercism | /python/triangle/triangle.py | 701 | 4.1875 | 4 | def is_equilateral(sides):
has_three_same_sides = len(set(sides)) == 1
if has_three_same_sides and is_triangle(sides):
return True
return False
def is_isosceles(sides):
has_two_equal_sides = len(set(sides)) <= 2 # at least
if has_two_equal_sides and is_triangle(sides):
return True
return False
def is_scalene(sides):
has_three_different_sides = len(set(sides)) == 3
if has_three_different_sides and is_triangle(sides):
return True
return False
def is_triangle(sides):
"""Return True if everything is fine."""
smallest, medium, larget = sorted(sides)
return smallest + medium >= larget and all(side > 0 for side in sides)
| true |
aec758c32b5473cfc832cf9565afb76e693229ec | HeejaeSeo/KoreaBioProgram | /day12/003.py | 273 | 4.21875 | 4 | #!/bin/usr/python
## 003. Operator
num1 = 3
num2 = 5
print("num + num2 = ", num1 + num2)
print("num - num2 = ", num1 - num2)
print("num * num2 = ", num1 * num2)
print("num / num2 = ", num1 / num2)
print("num % num2 = ", num1 % num2)
print("num // num2 = ", num1 // num2)
| false |
fde4b5f9306b155cac51669bb61a7405b2c09d06 | rishinkaku/python_course | /pycharm学习-进阶篇/线程与进程/4.1异常信息处理try.py | 837 | 4.21875 | 4 | # 异常处理
# 编程过程中可能出现很多的错误,导致程序崩溃,其实程序崩溃是操作系统和解释器,故意让程序崩溃的;为了防止更大错误出现
# 当崩溃的时候,操作系统或者解释器会发出一个异常信息,我们可以捕获这个异常信息,进行一次补救。
# try:
# a = input()
# print(int(a) + 1)
# except ValueError:
# print("异常信息")
# except IOError:
# print("IOError")
# except EOFError:
# print("EOFError")
try:
a = input()
print(int(a) + 1)
except Exception as error: # error指代错误,Exception错误的名称;Exception表示所有异常类的基类,可以捕获所有的错误信息。
print("异常信息", error, type(error))
# 当然也可以换成 except:
# print('错误')
| false |
7ee093a193c1ff85fd9f212807241bf23bb25349 | rishinkaku/python_course | /pycharm学习-基础篇/python—高阶函数/4.高阶函数-sorted.py | 1,321 | 4.59375 | 5 | ''' sorted函数: 排序作用
定义:
sorted函数对所有的可以迭代的对象进行排序
sort和sorted区别?
sort只用于列表排序
sorted: 对所有的可以迭代的对象进行排序,返回值是一个重新排列的列表, 而不是在原来的继基础上进行操作
格式:
sorted(iterable[, cmp[], key[, reverse]]) !!!
参数的说明:
iterable:可迭代的对象
cmp: 比较函数,具有两个参数,参数的值都是从可迭代的对象中取出,(可省略)
该函数必须遵守
大于 返回1
小于 返回- 1
等于 返回0
key: 用来比较的参数,只有一个参数 (可省略)
reverse:排序的规则,reverse = True 表示降序;false(默认)是升序'''
list = [1, 2, 3, 2, 1, 3, 5, 2, 3, 1]
list1 = sorted(list, reverse=True) # reverse = True 表示降序
print(list1)
print('\n')
list = [1, 2, -3, 2, -1, 3, 5, -2, 3, 1]
list1 = sorted(list,key=abs) # 按照绝对值的方式进行排序
print(list)
print(list1)
list1 = sorted(list, key=abs, reverse=True) # 按照绝对值的方式进行排序
print(list1)
print('\n')
# 2.自己定义一个函数
def myLen(str):
return len(str)
list2 = ["a1111","b222222","c33333333","d44"]
list3 = sorted(list2, key=myLen)
print(list3)
list3 = sorted(list2, key=myLen, reverse=True)
print(list3)
| false |
ff6af82614f42ee058458d0c1da34bb3136c9c28 | Sowmyareddy18/19A91A0564_Practice-Programs-Python- | /6.3.py | 664 | 4.1875 | 4 | '''
6.3
Sort the two lists
L1=[45,63,23,12,78]
L2=[12,90,72,-1]
Combine L1&L2 as single list and display the elements in the sorted order
#Dislay
L3=[-1,12,12,23,45,63,72,78,90]
Perform sorting on the list.....
'''
l1=[]
l2=[]
n1=int(input("enter how many values in list 1"))
for i in range(n1):
number=int(input())
l1.append(number)
n2=int(input("enter how many values in list 2"))
for i in range(n2):
number=int(input())
l2.append(number)
l3=l1+l2
l3.sort()
print(l3)
'''
OUTPUT:
enter how many values in list 1 4
12
23
45
56
enter how many values in list 24
34
56
67
45
[12, 23, 34, 45, 45, 56, 56, 67]
'''
| true |
a661af7c5d2187709b2fe16ca966768b8cc533e0 | calvincruzader/dailycodingproblems | /dailycodingproblem65.py | 1,343 | 4.40625 | 4 | '''
Print a twoD array in a clockwise spiral
'''
class Solution:
def print_matrix_clockwise_spiral(self, twoD_arr):
if len(twoD_arr) < 1 or len(twoD_arr[0]) < 1:
return
traversed = [[False for _col in range(len(twoD_arr[0]))] for _row in range(len(twoD_arr))]
moves = [[0,1], [1,0], [0,-1], [-1,0]]
moves_available = True
move_idx = 0
current_row, current_col = 0, 0
traversed[current_row][current_col] = True
print(twoD_arr[current_row][current_col])
while moves_available:
row, col = moves[move_idx][0], moves[move_idx][1]
current_row += row
current_col += col
if current_row < len(twoD_arr) and current_col < len(twoD_arr[0]) and not traversed[current_row][current_col]:
print(twoD_arr[current_row][current_col])
traversed[current_row][current_col] = True
else:
current_row -= row
current_col -= col
move_idx = (move_idx + 1) % 4
# peek next idx
peek_row, peek_col = current_row + moves[move_idx][0], current_col + moves[move_idx][1]
if peek_row >= len(twoD_arr) or peek_col >= len(twoD_arr[0]) or traversed[peek_row][peek_col]:
moves_available = False
x = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]
s = Solution()
s.print_matrix_clockwise_spiral(x) | true |
bc9043a669cb73da1c6d72d6d1767454e7b324d2 | calvincruzader/dailycodingproblems | /dailycodingproblem7.py | 1,529 | 4.125 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Facebook.
Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded.
For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'.
You can assume that the messages are decodable. For example, '001' is not allowed.
'''
class Solution:
def countNumDecodedWays(self, mapping, msg):
# is the mapping always going to be between numbers and letters?
# is the mapping a bijection?
if len(msg) < 1:
return 0
elif len(msg) == 1:
return 1
decode = {}
for key in mapping:
decode[mapping[key]] = key
'''
Pretty sure this is DP.
Going from left to right, for the message thus far, we will count the number of ways the current code can be decoded at n and the just add on the number of ways it was
decoded at n-1
1 = a 1
11 = k, aa 2
111 = aaa, ka, ak 3
1111 = aaaa, kaa, aka, aak, kka 5
11111 = aaaaa, kaaa, akaa, aaka, aaak, akk, kak, kka 8
'''
s = Solution()
my_mapping = {
'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14,
'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26
}
| true |
1eeff0b38194f3b0e81a8926407b344b77b0cf04 | khdouglass/algorithms | /graphs.py | 1,508 | 4.3125 | 4 | def are_connected(self, thing1, thing2):
"""Breadth-first search to see if two 'things' are connected."""
# create queue to store possible nodes to check
possible_nodes = Queue()
# create set to track which nodes haven been checked/seen
seen = set()
# add starting point 'thing' to queue and seen
possible_nodes.enqueue(thing1)
seen.add(thing1)
# while there are still things to check
while not possible_nodes.is_empty():
# look at first item in queue
thing = possible_nodes.dequeue()
# return True if it's what we're looking for
if thing is thing2:
return True
# otherwise, add things from thing's adjacency list to check
else:
for thing in thing.adjacent - seen:
possible_nodes.enqueue(thing)
seen.add(thing)
return False
def are_connected_recursive(self, thing1, thing2, seen=None):
"""Recursive depth-first search to see if two 'things' are connected."""
# if set is not passed through (first call), create set
if not seen:
seen = set()
# return True if thing matches what we're looking for
if thing1 is thing2:
return True
# if not, add thing to seen list
seen.add(thing1)
# add thing's adjacency list to seen and recursively call function on them
for thing in thing1.adjacent - seen:
if self.are_connected_recursive(person, person2, seen):
return True
return False
| true |
020ff4ff701d37274337c9b20fd8391546841caa | StefanDimitrovDimitrov/Python_Advanced | /Advanced level/Advanced/Conditional Statements Advanced/08_Fruit_Shop.py | 974 | 4.15625 | 4 | fruit = input()
day = input()
quantity = float(input())
price = 0
if day == "Monday" or day == "Tuesday" or day == 'Wednesday' or day == "Thursday" or day == "Friday":
if fruit =="banana":
price = 2.5
elif "apple" == fruit:
price = 1.2
elif "orange" == fruit:
price = 0.85
elif "grapefrui" == fruit:
price = 1.45
elif "kiwi" == fruit:
price = 2.7
elif "pineapple" == fruit:
price = 5.5
elif "grapes" == fruit:
price = 3.85
elif day == "Saturday" or day == 'Sunday':
if "banana" == fruit:
price = 2.7
elif "apple" == fruit:
price = 1.25
elif "orange" == fruit:
price = 0.9
elif "grapefruit" == fruit:
price = 1.6
elif "kiwi" == fruit:
price = 3
elif "pineapple" == fruit:
price = 5.6
elif "grapes" == fruit:
price = 4.2
if price == 0:
print('error')
else:
print (f"{price * quantity: .2f}")
| false |
a54263f5c98fd5abffca2e9b1b783fc4bbd1ddbb | jamiejamiebobamie/pythonPlayground | /jump.py | 706 | 4.15625 | 4 | """Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
Jump 1 step from index 0 to 1, then 3 steps to the last index."""
def jump(arr):
max_index = len(arr)-1
def __helper(index,_min):
if index == max_index:
return _min
return min(__helper(index+1,_min+1),__helper(index+arr[index],_min+1))
return __helper(0,0)
arr = [2,3,1,1,4]
print(jump(arr))
| true |
84bb5135cae15455cc01115155784b904470b373 | jamiejamiebobamie/pythonPlayground | /heap_experimenting.py | 2,367 | 4.1875 | 4 |
"""
Given an unsorted array, return the 2nd largest element.
"""
import heapq
A = [1001,22,3,45,56,666,75,8,90,100,11]
my_first_heap = heapq.heapify(A) #time complexity? O(n) or O(nlogn)
print(A) #checking to see if it worked... heapify is in place, apparently.
for i, item in enumerate(A):
if 2*i+2 < len(A):
print(A[i], A[2*i+1], A[2*i+2]) #testing heap property.
#a heap is perfect binary tree with nodes
#that are arranged according to
#the heap property: a parent node is as
#large or larger than the value of its
#children.
#a heap in python is represented as an array
#where each item at index i has children
#at indices 2*i+1 and 2*i+2.
# 3
# 8 75
# 22 11 666 1001
# 45 90 100 56
#returns the second largest element:
print(heapq.nlargest(2,A)[1]) #666
"""
'Given an unsorted array, return the 2nd largest element.'
import heapq
A = [1001,22,3,45,56,666,75,8,90,100,11]
heapq.heapify(A)
print(heapq.nlargest(2,A)[1])
"""
#python heapq module only provides functionality for a min heap, which is good
#when you're trying to find the LARGEST elements.
#if you want a max heap, you have to insert the negative of the values in the array
B = [1001,22,3,45,56,666,75,8,90,100,11]
#baby's first list comprehension...
B = [b*-1 for b in B]
print(B)
heapq.heapify(B)
print(B)
#i forgot there's also nsmallest:
print(heapq.nsmallest(2,A)[1])
#here's the second smallest item form the max heap:
print(-1*heapq.nlargest(2,B)[1])
#what is the time complexity between these two methods?
#it would seem like nlargest from B might be more performant.
# https://docs.python.org/2/library/heapq.html:
# "The latter two functions perform best for smaller values of n.
# For larger values, it is more efficient to use the sorted() function.
# Also, when n==1, it is more efficient to use the built-in min() and max() functions.
# If repeated usage of these functions is required,
# consider turning the iterable into an actual heap."(?)
| true |
0cdb73d7e0b55b359f30f65516aee371318c61a4 | lethanhnam1203/Algorithms | /dijkstra.py | 1,564 | 4.15625 | 4 | """
This is the implementation of the Dikstra Algorithm, based on two classes:
adjacency graph and priority queue.
"""
import numpy as np
from priority_queue import PriorityQueue
def init_for_dijkstra(graph, source_node_index):
"""
Initialize a graph with a source_node_index to prepare for the dijkstra algorithm
"""
distance_list = [np.inf] * graph.number_nodes
distance_list[source_node_index] = 0
predecessor_list = [np.inf] * graph.number_nodes
predecessor_list[source_node_index] = None
distance_queue = PriorityQueue(graph.index_list.copy(), distance_list.copy())
return distance_list, predecessor_list, distance_queue
def dijkstra(graph, source_node_index):
"""
This is an implementation of the Dijkstra algorithm. Input = a graph + source_node_index.
Outputs = a list of distances + a list of predecessors
"""
distance_list, predecessor_list, distance_queue = init_for_dijkstra(graph, source_node_index)
while distance_queue.check_if_empty() is False:
index_u = distance_queue.extract_lowest_distance()
for index_v in graph.query_all_out_neighbors(index_u):
if distance_list[index_u] + graph.adjacency_matrix[index_u, index_v] < distance_list[index_v]:
distance_list[index_v] = \
distance_list[index_u] + graph.adjacency_matrix[index_u, index_v]
predecessor_list[index_v] = index_u
distance_queue.update_distance(index_v, distance_list[index_v])
return distance_list, predecessor_list
| true |
92ef936cf7a9dd1a934eea120e90309b17231f80 | EugeneSchweiger/Hillel-HW | /edu/hillel/homework/Task11.py | 268 | 4.125 | 4 | import math
degrees=int(input("Enter degrees value"))
def deg_rad_cos(ad): #Angle degree
ar=ad*math.pi/180 #Angle radians
cos=math.cos(ar)
return round(cos,7)
print(deg_rad_cos(degrees))
print(deg_rad_cos(60))
print(deg_rad_cos(45))
print(deg_rad_cos(40)) | false |
84a7cb00c96396686a581a45883e3f5eafc118e9 | ankitanallana/albusdumbledore | /script.py | 286 | 4.375 | 4 | # Write a program to print the words of a string backwards
# For eg: "it's a beautiful day" should be "day beautiful a it's"
def reverseTheString(str):
# Write your program here
# Return the string
s = "the quick brown fox jumps over the lazy dog"
print(reverseTheString(s))
| true |
456af284c3c4a90cf70fa0ac8236a9f215f12294 | agnichakra/cescpython | /functions/tutorial.py | 2,665 | 4.125 | 4 | # A simple function
def add():
""" A function to add numbers """
a=15.6
b=23.6
print("The sum is", a+b)
add()
# odd even checking
def odd_even(num):
""" A function to check odd or even """
if num%2 == 0:
print("{} is even".format(num))
else:
print("{} is odd".format(num))
odd_even(56)
# afunction with multiple return
def employee():
name = "Agniswar"
id2 = "ABCD-002"
return name, id2
n, i = employee()
print("Name of the employee is :" , n)
print("\nID code of the employee is :" , i)
# Define a function in a function
def message(str):
def display():
return "How are you "
result = display() + str
return result
print(message("Agniswar"))
# mody and location
def modify(x):
x=15
print(x, id(x))
x =10
modify(x)
print(x, id(x))
#keywords argument
def goods(item , price):
print("Item : ", item)
print("\nPrice :" , price)
goods(item = 'Sugar', price= 90.36)
goods(price= 36.36, item = "Abcd")
#variable length argument
def add2(fixed , *args):
print("the fixed argument is", fixed)
sum = 0
for i in args:
sum = sum +i
print("The sum is :" , sum+fixed)
add2(5+69+56+98+3+4+7)
# default value of a function
def our_sum(a =40, b=37):
print("The sum is ", a+b)
our_sum()
our_sum(63)
our_sum(a=63)
our_sum(98, 65)
#keyword variable arguments
def display(fixed, **kwargs):
print("the fixed argument is", fixed)
for x, y in kwargs.items():
print("key is {} and value is {}".format(x,y))
display(5 , rollno = "00023")
display(5 , rollno = "00025", name = "Agniswar")
#passing group of elements to a function
print("Ente numbers separating with a space")
list = [int(x) for x in input().split()]
suml = sum(list)
print(suml)
# Recursive function
def factorial(n):
if n== 0:
result =1
else:
result = n*factorial(n-1)
return result
for i in range(0,11):
print("factorial if {} is {} ".format(i, factorial(i)), end="\n")
# use of lambda function
f = lambda x:x*x
print(f(5))
f2 = lambda x,y:x+y
print(f2(5,6))
list1 = [2,6,5,836,99,54,55,89,123,4456,789]
def is_even(x):
if x%2==0:
return True
else:
return False
list2 = list(filter(is_even, list1))
print(list2)
#decorator functions
def decor(fun):
def inner():
value = fun()
return value +9
return inner
def number():
return 65
result = decor(number)
print(result())
def decor(fun):
def inner():
value = fun()
return value +9
return inner
@decor
def number():
return 65
print(number()) | true |
a779ee4bf4d2a4576693dec1b2e513e2b13e7fbd | mdavinicius/alura_07_python_VI_collections_pt1_-_listas_e_tuplas | /1_listas_I.py | 1,443 | 4.21875 | 4 | idades = [39, 30, 27, 18]
print(f"O tipo da variável é: {type(idades)}") # vendo o tipo da variável com type()
print(f"A len da variável é: {len(idades)}") # vendo o tamanho com len()
print("-----------------------------------")
print(idades[1]) # fatiamento, printando o valor da posição 1
idades.append(15) # adicionando valor ao final da lista com append()
print(idades)
print(idades[4]) # fatiamento, printando o valor da posição 4
print("-----------------------------------")
for n in idades:
print(f'Printando for nº{n}') # loop for para printar todos os valores da lista de maneira formatada
print("-----------------------------------")
idades.remove(30) # removendo o valor 30 da lista com remove()
print(idades)
idades.extend([11, 5]) # agrega / concatena / extende a lista [11, 5] a lista ja existente
print(idades)
print("-----------------------------------")
idades_ano_que_vem = []
for idade in idades:
idades_ano_que_vem.append(idade + 1) # adicionou 1 ano em cada idade da lista 'idades' criando uma nova lista 'idades_ano_que_vem'
print(idades_ano_que_vem)
idades_ano_que_vem_2 = [(idade + 1) for idade in idades] # mesma coisa, porém com List Comprehension
print(idades_ano_que_vem_2)
print("-----------------------------------")
idades_ano_que_vem_3 = [(idade) for idade in idades if idade > 21] # adicionou em uma lista nova apenas as idades 'maiores que 21'
print(idades_ano_que_vem_3) | false |
0235317cfab4f69d6a50a316ebb0feed1e52bcbf | EyreC/PythonCiphers | /backwards.py | 483 | 4.25 | 4 | import string
def backwards(inputString):
wordList = inputString.split(" ") #list of space-separated words in inputString
backwardsList = [] #list of reversed words
#Generate list of reversed words
for word in wordList:
newWordList=[]
for index,letter in enumerate(word):
newWordList.append(word[-(index+1)])
newWord = "".join(newWordList)
backwardsList.append(newWord)
return " ".join(backwardsList).capitalize()
| true |
9fa9c0d20277d6aa0ac1e04b926c90a706624242 | npranno/Python_Projects | /abstraction.py | 856 | 4.25 | 4 |
from abc import ABC, abstractmethod #imports ABC and abstractmethod from abc module
class shoes(ABC):
#defines amount of the purchase of said shoes
def payAmount(self, amount):
print("Your shoes cost: ",amount)
#@abstractmethod tells user to pass in an argument, but the data isn't defined yet
@abstractmethod
def payment(self,amount):
pass #passes this function for something to be called later
class giftCard(shoes): #child class of shoes, defining that the payment is a gift card
def payment(self, amount): #payment is defined separately within this class
print("Your gift card balance is not enough to purchase this item costing {}.".format(amount))
obj = giftCard()
obj.payAmount("$60") #calls pay amount in parent class, and response
obj.payment("$60") #calls payment in child class, and response
| true |
bdde83a9b5dcaefb45becae5e98d932e376f48c4 | Xaxis/jesse | /array/union/union.py | 671 | 4.46875 | 4 |
def union(arg1, *arg2):
'''
Checks to see if a value is already in the first [array]
given. If the value is not in the [array] it appends that
that value at the end of the first [array].
'''
unionList = arg1
for i in arg2:
# 'i' should be each array given in arg2
for number in i:
# 'number' should be each value inside of each array given in arg2
if number not in unionList:
# if the number is not already in the unionList then is should add that number at the end of the list
unionList.append(number)
return unionList
print(union([1, 2, 3], [101, 2, 1, 10], [2, 1])) | true |
60df56577885ef9352a5f5de0abda331abcb80a8 | jamtot/30days | /day 13/abstract.py | 1,190 | 4.21875 | 4 | """Implement an abstract class Book."""
from abc import ABCMeta, abstractmethod
class Book(metaclass=ABCMeta): # pylint: disable=too-few-public-methods
"""Contains title, author, and abstract displayb function."""
def __init__(self, title, author):
"""Initialise the title and author."""
self.title = title
self.author = author
@abstractmethod
def display(): # pylint: disable=no-method-argument
"""Abstract display method with no implementation."""
pass # pylint: disable=unnecessary-pass
class MyBook(Book): # pylint: disable=too-few-public-methods
"""Implementation of abstract class Book."""
def __init__(self, title, author, price):
"""Call the base class constructor and set price."""
super().__init__(title, author)
self.price = price
def display(self):
"""Display function implementation."""
print("Title: " + self.title)
print("Author: " + self.author)
print("Price: " + str(self.price))
if __name__ == "__main__":
TITLE = input()
AUTHOR = input()
PRICE = int(input())
NEW_NOVEL = MyBook(TITLE, AUTHOR, PRICE)
NEW_NOVEL.display()
| true |
e2a8eed1f82572547b9b3e589d62b4daec44b37c | JordiLazo/Programming_exercises_in_python | /Numbers_python/numbers_2_Conversions.py | 619 | 4.53125 | 5 | #NUMBERS - CONVERSIONS
#int(value)
#float(value)
#str(value)
# 1 - Convert the following to int: 23.7, 2.0, "92.7", "92"
print(int(23.7))
print(int(2.0))
print(int("92"))
#print(int("92.7")) you can not double convert
print(int(float("92.7")))
# 2 - Convert the following to float: 2, "92.7", "92"
print(float(2))
print(float("92.7"))
print(float("92"))
# 3 - Convert the followiwng to string: 23.7, 2
print(str(23.7))
# 4 - Print the type of the following: (2+2.7), (2+2.0), (97-2.0)
# 5 - Print the type of the following: (2+int(2.7)), (str(97) - 2.0)
print(2+int(2.7))
#print(str(97) - 2.0)
print(int(str(97))-2.0) | false |
d5bdd3c3356ed55d6e4d7a5edec75ed3f0099bf5 | Botteam00/Banking-on-web-technology | /FRONTEND/src/test.py | 1,044 | 4.125 | 4 | """def Fibonacci(n):
# Check if input is 0 then it will
# print incorrect input
if n < 0:
print("Incorrect input")
# Check if n is 0
# then it will return 0
elif n == 0:
return 0
# Check if n is 1,2
# it will return 1
elif n == 1 or n == 2:
return 1
else:
return Fibonacci(n-1) + Fibonacci(n-2)
# Driver Program
num = input("enter a number: ")
print(Fibonacci(int(num)))
def pri(m,n):
for i in range (m,n+1):
if i>1:
for j in range (2,i):
if(i%j)==0:
break
else:
print(i)
print("enter m")
m=int(input())
print("enter n")
n=int(input())
(pri(m,n))"""
string="hello1234 hi 2225JF"
d={"digit":0,"upper":0,"lower":0,"words":0}
for i in string:
if(i.isdigit()):
d["digit"]+=1
for i in string:
if(i.isupper()):
d["upper"]+=1
for i in string:
if(i.islower()):
d["lower"]+=1
d["words"]=len(string.split())
print(d) | false |
415b79aee89723bb3b0391c3c4a30600c59d0807 | sandgate-dev/codesignal-practice | /arcade/buildPalidrome.py | 679 | 4.3125 | 4 | """
Given a string, find the shortest possible string which can be achieved by
adding characters to the end of initial string to make it a palindrome.
Example
For st = "abcdc", the output should be
buildPalindrome(st) = "abcdcba".
"""
def buildPalindrome(st):
length = len(st)
for i in range(length):
# removes first letter from string
sub = st[i:length]
if sub == sub[::-1]:
# if sub is palindrome move what you removed above into part
part = st[0:i]
# add part to st and return
return st + part[::-1]
return ""
print(buildPalindrome("abba"))
print(buildPalindrome("abcdc"))
| true |
597dbf3731c92aad9b73737d4845fd0ba84eb18d | sandgate-dev/codesignal-practice | /arcade/addBorder.py | 604 | 4.125 | 4 | """
Given a rectangular matrix of characters, add a border of asterisks(*) to it.
Example
For
picture = ["abc",
"ded"]
the output should be
addBorder(picture) = ["*****",
"*abc*",
"*ded*",
"*****"]
"""
def addBorder(picture):
border = []
char = '*'
l = len(picture[0]) + 2
b = str(char * l)
border.insert(0, b)
for i in picture:
string = char + i + char
border.append(string)
border.append(b)
return border
picture = ["abc",
"ded"]
print(addBorder(picture))
| true |
9cb88b2111a0148a155d1f88bb2631e7912dda27 | sandgate-dev/codesignal-practice | /interview-practice/arrays/firstDuplicate.py | 1,142 | 4.125 | 4 | """
Given an array 'a' that contains only numbers in the range from 1 to a.length,
find the first duplicate number for which the second occurrence has the
minimal index. In other words, if there are more than 1 duplicated numbers,
return the number for which the second occurrence has a smaller index than
the second occurrence of the other number does. If there are no such elements,
return -1.
Example:
For a = [2, 1, 3, 5, 3, 2], the output should be firstDuplicate(a) = 3.
There are 2 duplicates: numbers 2 and 3. The second occurrence of 3 has a
smaller index than the second occurrence of 2 does, so the answer is 3.
For a = [2, 2], the output should be firstDuplicate(a) = 2;
For a = [2, 4, 3, 5, 1], the output should be firstDuplicate(a) = -1
"""
def firstDuplicate(a):
my_set = set()
for value in a:
if value in my_set:
return value
else:
my_set.add(value)
return -1
a = [2, 1, 3, 5, 3, 2]
print(firstDuplicate(a))
a = [2, 2]
print(firstDuplicate(a))
a = [2, 4, 3, 5, 1]
print(firstDuplicate(a))
a = [8, 4, 6, 2, 6, 4, 7, 9, 5, 8]
print(firstDuplicate(a))
a = [1, 1, 2, 2, 1]
print(firstDuplicate(a))
| true |
def426620eda1031fcd58b6256c356dbb09cdf02 | sandgate-dev/codesignal-practice | /arcade/isBeautyfulString.py | 1,363 | 4.1875 | 4 | """
A string is said to be beautiful if b occurs in it no more times than a;
c occurs in it no more times than b; etc.
Given a string, check whether it is beautiful.
Example
For inputString = "bbbaacdafe", the output should be
isBeautifulString(inputString) = true;
For inputString = "aabbb", the output should be
isBeautifulString(inputString) = false;
For inputString = "bbc", the output should be
isBeautifulString(inputString) = false.
"""
import string
def isBeautifulString(inputString):
# letters = sorted(set(inputString))
#
# num = inputString.count('a')
# on = ord('a')
#
# if len(letters) == 1:
# return False if ord(letters[0]) > on else True
#
# for l in letters[1:]:
# if ord(l) - 1 == on:
# on = ord(l)
# if inputString.count(l) > num:
# return False
# else:
# num = inputString.count(l)
# else:
# return False
#
# return True
# Short and Simple
r = [inputString.count(i) for i in string.ascii_lowercase]
return r[::-1] == sorted(r)
print(isBeautifulString("bbbaacdafe"))
print(isBeautifulString("aabbb"))
print(isBeautifulString("bbc"))
print(isBeautifulString("zzz"))
print(isBeautifulString("bba"))
print(isBeautifulString("abcdefghijklmabcdefghijklmnpnopqrstuvwxyzz")) # False
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.