blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
54d4bc412e328063c12a71f0ac512c568a17809e | lnarasim/250_problems | /pyproblems/matrix_diagonal_sum.py | 1,078 | 4.25 | 4 | '''To find the sum of both leading and secondary diagonals'''
def diagonal_sum(matrix_list):
'''This function takes in a valid list as matrix and returns the sum of both the diagonals '''
if not isinstance(matrix_list, list):
raise TypeError("Enter the matrix as a list of lists")
for i, _ in enumerate(matrix_list):
if not isinstance(matrix_list[i], list):
raise TypeError("The elements in the list, should also be a list")
if len(matrix_list) != len(matrix_list[0]):
raise IndexError("Invalid Matrix Size, Enter a square matrix")
for i, _ in enumerate(matrix_list):
if not isinstance(matrix_list[i][i], int) or isinstance(matrix_list[i][i], bool):
raise TypeError(f"Invalid type of entry{type(matrix_list[i][i])}")
leading_diag = 0 #Principal diagonal
secondary_diag = 0 #secondary diagonal
length = len(matrix_list)-1
for i in range(length+1):
leading_diag += matrix_list[i][i]
secondary_diag += matrix_list[i][length -(i+1)]
return leading_diag+secondary_diag
| true |
52df1e8c06358e418977e3ac4b00e273542aa4f5 | githubajaydhage/mypythonprojects | /square.py | 762 | 4.59375 | 5 | # draw square in Python Turtle
import turtle
t = turtle.Turtle()
s = int(input("Enter the length of the side of the Squre: "))
# drawing first side
t.forward(s) # Forward turtle by s units
t.left(90) # Turn turtle by 90 degree
# drawing second side
t.forward(s) # Forward turtle by s units
t.left(90) # Turn turtle by 90 degree
# drawing third side
t.forward(s) # Forward turtle by s units
t.left(90) # Turn turtle by 90 degree
# drawing fourth side
t.forward(s) # Forward turtle by s units
t.left(90) # Turn turtle by 90 degree
# draw Squre in Python Turtle
import turtle
t = turtle.Turtle()
s = int(input("Enter the length of the side of squre: "))
for _ in range(4):
t.forward(s) # Forward turtle by s units
t.left(90) # Turn turtle by 90 degree
| false |
f89e48a81868e178f207e1d0980d2641f8b92ae3 | jeremybowden73/CS50 | /pset6/python-conversions/mario_more.py | 388 | 4.125 | 4 | while True:
height = int(input("Height: ")) #convert the string input to an int
if height >= 0 and height <= 23: #if height is not in bounds 0 to 23, ask again
break
for row in range(height):
print(" " * (height-(row+1)), end="") #the end="" prevents the auto newline
print("#" * (row+1), end="")
print(" ", end="")
print("#" * (row+1))
| true |
d59dc74cd73d24b863636db63ecc742aa5cd4a25 | weihsuanchou/algorithm_py | /Program.py | 1,631 | 4.1875 | 4 |
import math
# I comment
''' multiline comment
Whenever the Python interpreter reads a source file, it does two things:
it sets a few special variables like __name__, and then
it executes all of the code found in the file.
'''
def greeting_from_river():
print("Rise & Shine!!")
name = "Unknown"
def demo_global_var():
global name
name = "River"
print(name)
def demo_arithmetic():
print("demo_arithmetic~\n")
print("7+2 =",7+2)
print("7-2 =",7-2)
print("7*2 =",7*2)
print("7/2 =",7/2)
print("7%2 =",7%2)
print("7**2 =",7**2) #power
print("7//2 =",7//2) #Floor
print("math.floor(7/2) = ", math.floor(7/2))
print("math.ceil(7/2) = ", math.ceil(7/2))
def demo_function_param(a="a", b="unknow"):
print("I am getting "+ a +" "+ b)
def demo_if():
myScore = 99
if myScore >= 100:
print("You are awesom")
elif myScore >=90:
print("Still very good")
else:
print("That is fine")
if(myScore >= 90 and myScore <=99):
print("You are the best")
def demo_list():
friends = ['Kuan', 'Chiu', 'Jen', 'Yan','Juchi']
print("ALL FRIENDS = ", friends)
print("Friend 1 ", friends[1])
print("Friend 1 ", friends[1:])
print("Friend 1 ", str(friends[:3]))
print("Friend 1 ", friends[-1])
famliy = ['Chou', 'Yang']
people = [friends, famliy]
print(people)
print(people[1][1])
def main():
#demo_function_param("River", "Chou") #I am getting River Chou
#demo_function_param(a="River") #I am getting River unknow
demo_list()
if __name__ =="__main__":
main() | true |
6f20179e54420d7542488561ce0fea4ae2084c43 | rileychapman/SoftDes | /inclass17.py | 1,500 | 4.125 | 4 | import pygame
import time
class AnimatedCircle(object):
""" Reperesents a circle that can draw itself to a pygame window. """
def __init__(self, center_x, center_y, v_x, v_y, radius):
""" Initialize the Circle object.
center_x: the x-coordinate of the center of the circle
center_y: the y-coordinate of the center of the circle
v_x: the x-velocity of the circle
v_y: the y-velocity of the circle
radius: the radius of the circle
"""
self.center_x = center_x
self.center_y = center_y
self.v_x = v_x
self.v_y = v_y
self.radius = radius
def draw(self,screen):
""" Draw the Circle to the screen.
screen: the pygame screen to draw to
"""
pygame.draw.circle(screen, pygame.Color(0,0,0), (self.center_x,self.center_y), self.radius, 1)
def animate(self):
""" Update the position of the circle """
self.x += self.v_x
self.y += self.v_y
if __name__ == '__main__':
pygame.init()
size = (640,480)
screen = pygame.display.set_mode(size)
circ = AnimatedCircle(100,100, 0, 0, 20)
running = True
while running:
screen.fill(pygame.Color(255,255,255))
circ.draw(screen)
for event in pygame.event.get():
if event.type == 'QUIT':
running = False
time.sleep(.01)
pygame.display.update()
pygame.quit()
| true |
2c1aa8a871b50d3f2220679784199bf968a2511c | chiragrawat12/Working-on-List-CSV-SQLite3 | /app.py | 669 | 4.25 | 4 | from utils.database_SQLite import *
USER_CHOICE="""
Enter:
-'a' to add a new book
-'l' to list all books
-'r' to mark a book as read
-'d' to delete a book
-'q' to quit
"""
def menu():
create_book_table()
user_input=input(USER_CHOICE)
while user_input!='q':
if user_input=='a':
prompt_add_book()
elif user_input=='l':
list_book()
elif user_input=='r':
prompt_read_book()
elif user_input=='d':
prompt_delete_book()
else:
print("Unknown command please enter again.")
user_input=input(USER_CHOICE)
if __name__=="__main__":
menu() | false |
256c7bfd70d0167660f6ada0a5932df9e4b7dfd3 | Chandan-CV/school-lab-programs | /Program1.py | 669 | 4.1875 | 4 | #Program 1
#Write a program to accept a number and print its multiplication table
#Name : Adeesh Devanand
#Date of Execution: July 17, 2020
#Class 11
n=int(input("Enter a number"))
print("Multiplication table for the number ", n, " is:")
print(n, "x 1 =", n*1 )
print(n, "x 2 =", n*2 )
print(n, "x 3 =", n*3 )
print(n, "x 4 =", n*4 )
print(n, "x 5 =", n*5 )
print(n, "x 6 =", n*6 )
print(n, "x 7 =", n*7 )
print(n, "x 8 =", n*8 )
print(n, "x 9 =", n*9 )
print(n, "x 10 =", n*10 )
''' Output of Program 1
Enter a number2
Multiplication table for the number 2 is:
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20 '''
| true |
7c3bfb385d867930d0f8563f7d49e7a8655d4c1e | Chandan-CV/school-lab-programs | /lab program 36.py | 949 | 4.125 | 4 | #Program 36
#Write a program to create a dictionary of product name and price. Return
#the price of the product entered by the user.
#Name: Neha Namburi
#Date of Excetution: October 14, 2020
#Class: 11
d={} # empty dict
ans='y'
while((ans=='y') or (ans=='Y')):
# values of p and pr are local to this while loop- i.e. once leaves loop, new values
p=input("enter product name")
pr=float(input("enter price"))
d[p]= pr
ans= input("enter y or Y to continue")
print(d)
p=input("enter product name")
for i in d:
if(i==p):
print("price =", d[i])
break
else:
print("product not found")
''' Output for Program 36
enter product nameapple
enter price200
enter y or Y to continuey
enter product namebanana
enter price250
enter y or Y to continuey
enter product nameorange
enter price140
enter y or Y to continuej
{'apple': 200.0, 'banana': 250.0, 'orange': 140.0}
enter priduct nameorange
price = 140.0
'''
| true |
f418da51cad2a6f1a3e828bf734940e641071a20 | Chandan-CV/school-lab-programs | /Program6.py | 360 | 4.15625 | 4 | #Program 6
#Write a program to accept 2 string and concatinate them
#Name : Adeesh Devanand
#Date of Execution: July 17, 2020
#Class 11
str1 = input("Enter String 1")
str2 = input("Enter String 2")
s = str1 +str2
print("Concatinated string is", s)
'''Output of Program 6
Enter String 1Hi my name is
Enter String 2Adeesh Devanand
Concatinated string is Hi my name isAdeesh Devanand'''
| true |
c86c9c07e181f9a47cd24c8d4f24a76eec2c6bc4 | prakhar117/Adhoc-python-codes | /problem5.py | 335 | 4.28125 | 4 |
import datetime
name=input("Enter your name:")
current_time=datetime.datetime.now()
if 0 <= current_time.hour < 12:
print("good morning",name)
elif 12 <= current_time.hour < 17:
print("goodafter noon",name)
elif 17 <= current_time.hour < 20:
print("good evening",name)
elif 20 <= current_time.hour <= 23:
print("good night",name)
| true |
c3034e5412b0fd0e9e0671dc3087f4c86e560e13 | ArseniyCool/8.Nested-loops | /RUS/C Новым годом,программист 2.0.py | 690 | 4.3125 | 4 | # Каждый программист хочет иметь под Новый год Новогоднюю ёлку, однако программист на то и
# программист,он может создать ёлку прямо у себя в программе!
# Программа создаёт новогоднюю ёлку, состающую из поочерёдных чисел
height = int(input('Введите число шариков:'))
counter = 1
length = 1
while counter <= height:
for i in range(0, length):
print(counter, end=' ')
counter += 1
if counter > height:
break
length += 1
print('')
| false |
68eda1964f4cad5269f5a6186ac0c386b589c4da | mizhi/project-euler | /python/problem-4.py | 614 | 4.1875 | 4 | #!/usr/bin/env python
# A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.
#
# Find the largest palindrome made from the product of two 3-digit numbers.
max_n = 999 * 999
def palindrome_number(n):
ns=str(n)
return ns == ns[::-1]
pnumbers = [n for n in xrange(max_n + 1) if palindrome_number(n)]
pnumber_div=[]
for pn in pnumbers:
for n in xrange(999, 100, -1):
if pn % n == 0:
n2 = pn / n
if len(str(n2)) == 3:
pnumber_div.append((n, n2, pn))
print pnumber_div[-1]
| true |
0005c55a1553278d56ae7dc93595034dde4652d3 | mizhi/project-euler | /python/problem-59.py | 2,915 | 4.28125 | 4 | #!/usr/bin/env python
# Each character on a computer is assigned a unique code and the
# preferred standard is ASCII (American Standard Code for Information
# Interchange). For example, uppercase A = 65, asterisk (*) = 42, and
# lowercase k = 107.
#
# A modern encryption method is to take a text file, convert the bytes
# to ASCII, then XOR each byte with a given value, taken from a secret
# key. The advantage with the XOR function is that using the same
# encryption key on the cipher text, restores the plain text; for
# example, 65 XOR 42 = 107, then 107 XOR 42 = 65.
#
# For unbreakable encryption, the key is the same length as the plain
# text message, and the key is made up of random bytes. The user would
# keep the encrypted message and the encryption key in different
# locations, and without both "halves", it is impossible to decrypt
# the message.
#
# Unfortunately, this method is impractical for most users, so the
# modified method is to use a password as a key. If the password is
# shorter than the message, which is likely, the key is repeated
# cyclically throughout the message. The balance for this method is
# using a sufficiently long password key for security, but short
# enough to be memorable.
#
# Your task has been made easy, as the encryption key consists of
# three lower case characters. Using cipher1.txt (right click and
# 'Save Link/Target As...'), a file containing the encrypted ASCII
# codes, and the knowledge that the plain text must contain common
# English words, decrypt the message and find the sum of the ASCII
# values in the original text.
import fileinput
import sys
def decrypt(msg, key):
newm = []
for ki in xrange(0, len(msg)):
newm.append(msg[ki] ^ key[ki % len(key)])
ki += 1
return newm
# load message
matrix_file = sys.argv[-1]
fi=fileinput.input(matrix_file)
cmessage=[]
for l in fi:
nums=[int(i) for i in l.split(",")]
cmessage.extend(nums)
fileinput.close()
# load up filter words
fi=fileinput.input('/usr/share/dict/words')
words=set([w.lower().strip() for w in fi])
fileinput.close()
# generate all possible keys
print "Generating keys..."
lower_case=[ord(c) for c in 'abcdefghijklmnopqrstuvwxyz']
keys = []
for i in lower_case:
newkey=[i]
for j in lower_case:
newkey.append(j)
for k in lower_case:
newkey.append(k)
keys.append(tuple(newkey))
newkey.pop()
newkey.pop()
print "Decrypting...", len(keys)
# brute decrypt
pmessages = {}
for k in keys:
pmessages[k] = "".join([chr(c) for c in decrypt(cmessage, k)])
for c in pmessages[k]:
if not (ord(c) >= ord(' ') and ord(c) <= ord('z')):
del pmessages[k]
break
print "Summing... ", len(pmessages.keys())
for k,m in pmessages.items():
if 'the' in m.lower():
print m, sum([ord(c) for c in m])
print "Candidates..."
| true |
b4d7d7ab05cae0be2c75839f51f10190b66cc1d1 | sravi2421/dsp | /python/q8_parsing.py | 885 | 4.28125 | 4 | # The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
import csv
import sys
file1 = open('football.csv')
reader = csv.reader(file1)
mydict = dict((rows[0],rows[1:8]) for rows in reader)
del mydict['Team']
highest_gd=0
highest_gd_team = "No one"
for key in mydict:
goal_difference = int(mydict[key][4])-int(mydict[key][5])
if goal_difference > highest_gd:
highest_gd = int(mydict[key][4])-int(mydict[key][5])
highest_gd_team = key
print highest_gd_team
file1.close()
| true |
0b46720100bed0e445aed0fc63a491f2607161be | pamd/foo | /python/list.py~ | 452 | 4.3125 | 4 | #!/usr/bin/python
# List: [ ]
names = [ "Dave", "John", "Mary" ]
names.append("dhu") # Add "dhu" at the end
names.insert(2, "helen") # insert "helen" between "John" and "Mary"
names.sort() # sort list
names.remove("Dave") # Remove all occurrences of "Dave"
# names[1: ]
# names[2:4]
# Number of elements in list:
len(names)
# len() can be also used on string, set, tuple or dictionary
names2 = {} # empty list #1
names3 = list() #empty list #2
| true |
044ed6fad1dad35dc8ff45b8c7415c13159e5f2b | conor1982/Programming-for-Data-Analysis.repo | /tuesday.py | 380 | 4.21875 | 4 | import datetime
today = datetime.datetime.today()
dayofweek = today.weekday()
print("Lets check if it is Tuesday.")
if dayofweek == 1:
print("It's Tuesday")
elif dayofweek == 0:
print("It's not Tuesday, it is Monday!")
print("Luckily it will be Tuesday tomorrow!")
else:
print("Unfortunatley, It is not Tuesday")
print("Thanks for checking if it's Tuesday")
| true |
fcc3ab129d1277a198761122033e67be9e89241c | GodwinOkpechi/python-scripts | /functions.py | 1,606 | 4.375 | 4 | def greet():
print('holla')
print('hello, how are u ')
greet()
# to allow ur user send in input
def greeting():
name=input('ur name: ')
age=input('how old are u: ')
print(name)
print('hello, how are u ')
print('u are', age,'yrs old')
greeting()
#to use functions to respond to inputted data
def greet2(name):
print('hello' ,name, 'how are u ')
greet2('sarah')
# to add other parameters
def greet3(name, age):
print('hello' ,name, 'how are u ')
print('u are', age,'yrs old')
greet3('sarah', 26)
# Note:if u want use a function u must first declare it then use before going into a different function.
# to return data from a code for usage purpose
# Note: the return keyword must be the last thing used in ur code cause it serves as a end comment or limit for ur code.
def add_nums(num1,num2):
sum= num1 + num2
return sum
def multiply_nums(num1,num2):
multi= num1 * num2
return multi
print(add_nums(20,5))
print(multiply_nums(20,5))
result= add_nums(30,21) + multiply_nums(3,4)
Result= add_nums(30,21) + add_nums(5,6)
result_2= add_nums(24,13)
print(result)
print(Result)
print(result_2)
# note on Positional arguments and Named arguments
def do_something(num1,num2,num3):
print('i love football')
print(num1 + num2 * num3)
# the below function is a positional argument cause it's elements are derived from position.
do_something(30,40,50)
# or
# the below function is a named argument cause it's elements are named or assigned to their units.
do_something(num3=50,num1=30,num2=40) | true |
2b87b10d43f7109dd1aa0ed0604b66edb770a5d8 | GodwinOkpechi/python-scripts | /classwork.py | 1,324 | 4.21875 | 4 | '''
# a python program to collect the age of a user then check if the age is greater than 18
age=int(input('how old are u:' ))
if age >= 18:
print('welcome to our site, u met the age requirement')
else:
print("pls we are redirecting u to our other site, u haven't met the age requirement")
numbers=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
for x in numbers:
print(x)
nums=range(0,20)
for y in nums:
print(x)
number=0
while number<=20:
print (number)
number=number+1
'''
#Write a program to show inheritance in classes and objects
class Chefs:
def __init__(self,name,age):
self.name=name
self.age=age
def cookrice(self):
print(f'{self.name} is cooking rice')
def bakecake(self):
print(f'{self.name} is baking cake.')
class NigerianChefs:
def __init__(self,name,age,state_of_origin):
super().__init__(name,age)
self.state_of_origin=state_of_origin
def cookjollof(self):
print(f'{self.name} is cooking jollof rice.')
name=input('enter ur name: ')
age=input('how old are u: ')
state_of_origin= input('which state are u from: ')
chef1=NigerianChefs(name,age,state_of_origin)
print(chef1.name)
chef1.cookjollof()
chef1.bakecake()
chef1.cookrice
| true |
9281d5a93d5ff9da301e52c478b4941e9bde236e | IamGianluca/checkio-solutions | /checkio/electronic_station/the_longest_palindromic.py | 1,762 | 4.3125 | 4 | def longest_palindromic(text):
"""Find longest palindromic substring in a given string.
Args:
text [string] : The string that needs to be scanned.
Returns:
The longest palindromic substring [str]. If more than one substring is
found, returns the one which is closer to the beginning.
"""
palindromes = []
l = len(text)
# edge case, check if the entire word is composed by the same letter
# (i.e. "aaaa"), in that case the entire word is the longest palindrome
first = text[0]
if l == sum([1 if letter == first else 0 for letter in text]):
return text
# find all palindromic substrings moving from left to right
for i in range(l):
pal = letter_check(idx=i, text=text)
palindromes.extend([pal])
# find longest palindrome among all those we found; if there are than one
# palindrome of max length return the closer to the left
sizes = [len(pal) for pal in palindromes]
longest_size = max(sizes)
for pal in palindromes:
if len(pal) == longest_size:
return pal
def letter_check(idx, text, offset=0):
"""Check the adjacent letters to the one at index N, if the one immediatelly
before and after are the same, keep searching until they are not.
Args:
idx [int]: The index where we want to start searching.
text [str]: The word we want to search.
Returns:
The longest palindromic substring [str] centered at index *idx*.
"""
try:
if text[idx-offset] == text[idx+offset]:
return letter_check(idx=idx, text=text, offset=offset+1)
else:
return text[idx-offset+1:idx+offset]
except IndexError:
return text[idx-offset:idx+offset-1]
| true |
58e237fee29f870176208de079e68ecb6b8ab7e6 | halazi/52python | /regex_even_chars.py | 341 | 4.25 | 4 | #!/usr/bin/python
## find all occurrences of sub-strings in the whole text
## which consist of even number of same word characters
import re
s = "Today iss thhhe last daa of SpringBreeeeeek"
match = re.findall(r"(((\w)\3)\2*)", s)
for t in match:
print t[0]
#print "group 1 -> ", match.group(1)
#print "group 2 -> ", match.group(2)
| false |
f880e89e4964f3653a367f2f22afccf336dcaedb | Erfan021/Practice_Python | /Errors.py | 1,639 | 4.15625 | 4 | # ERROR HANDLING
while True:
try:
age= int(input('Enter your age: '))
print(age)
print('thanks')
break
except:
print('Please enter the number')
while True:
try:
age= int(input('Enter your age: '))
print(age)
except:
print('Please enter the number')
else:
print('thanks')
break
def division(num1, num2):
try:
return num1/num2
except (TypeError, ZeroDivisionError) as err: # Error Wrapping
print(err)
print(division(1,'1'))
print(division(1,0))
while True:
try:
age= int(input('Enter your age: '))
print(5/age)
except ValueError:
print('Please enter the number')
except ZeroDivisionError:
print('Provide number greater than Zero')
else:
print('thanks')
break
finally: # it runs regardless of anything.
print('End')
while True:
try:
age= int(input('Enter your age: '))
print(5/age)
except ValueError:
print('Please enter the number')
continue
except ZeroDivisionError:
print('Provide number greater than Zero')
break
else:
print('thanks')
finally:
print('End')
print('Move On')
while True:
try:
age= int(input('Enter your age: '))
print(5/age)
raise ValueError('Stop Now')
except ZeroDivisionError:
print('Provide number greater than Zero')
else:
print('thanks')
break
finally:
print('End')
| true |
2d87083960bdfcedf26be0971fef813bf61bce8f | dev-roliveira/Python | /Arquivos de Código/recebendo_dados_usuário.py | 864 | 4.1875 | 4 | """
Recebendo dados do usuário...
input() -> Todo dado recebido via input é do tipo String (tudo que estiver entre aspas)
Cast -> Nomenclatura usada na conversão de um dado em outro tipo de dado
"""
# Exemplo antigo
# print("Qual seu nome?")
# nome = input()
# Exemplo novo
nome = input('Qual seu Nome? \n ')
# Exemplo antigo
# print("Seja Bem-Vindo(a) %s" % nome)
# Exemplo novo
# print('Seja Bem Vindo(a) {0}'.format(nome))
# Mais atual disponível a partir do 3.6
print(f'Seja bem vindo(a) {nome}')
# Exemplo antigo
# print("Qual sua idade?")
# idade = input()
# Exemplo novo
idade = input('Qual sua idade? \n')
# Exemplo antigo
# print("%s tem %s anos" % (nome, idade))
# Exemplo novo
# print('{0} tem {1} anos'.format(nome, idade))
# Mais atual disponível a partir do 3.6
print(f'{nome} tem {idade} anos')
print(f'E nasceu no ano de {2019 - int(idade)}')
| false |
153b15b5a6cd634d86d494e16d35b085a151e1db | dev-roliveira/Python | /Arquivos de Código/min_e_max.py | 1,408 | 4.1875 | 4 | """
Min e Max
max() -> Retorna o maior valor em um iteravel, ou o maior de dois ou mais elementos
min() -> Retorna o menor valor em um iteravel, ou o menor de dois ou mais elementos
"""
# lista = [1, 8, 4, 99, 34, 129]
# tupla = (1, 8, 4, 99, 34, 129)
# conjunto = {1, 8, 4, 99, 34, 129}
# dicionário = {'a': 1, 'b': 8, 'c': 4, 'd': 99, 'e': 34, 'f': 129}
# print(max(lista))
# print(max(tupla))
# print(max(conjunto))
# print(max(dicionário.values()))
'Verificando entre dois valores'
# val1 = int(input('Numero 1: '))
# val2 = int(input('Numero 2: '))
# print(max(val1, val2))
'Verificando entre strings'
# nomes = ['Arya', 'Jon', 'Bran', 'Sansa']
# print(max(nomes)) # Arya, pois incia-se com 'A'
# print(min(nomes)) # Sansa, pos inicia-se com 'S"
# print(max(nomes, key=lambda nome: len(nome))) # Sansa
# print(min(nomes, key=lambda nome: len(nome))) # Jon
'Verificando em Dicionario'
# musicas = [{"titulo": "Thunderstuck", "Tocou": 3},
# {"titulo": "Dead Skin Mask", "Tocou": 2},
# {"titulo": "Back in Black", "Tocou": 4},
# {"titulo": "Iron Man", "Tocou": 32}]
# print(max(musicas, key= lambda musica: musica['Tocou']))
# print(min(musicas, key= lambda musica: musica['Tocou']))
# print(max(musicas, key= lambda musica: musica['Tocou'])['titulo']) # Somente o titulo
# print(min(musicas, key= lambda musica: musica['Tocou'])['titulo']) # Somente o titulo
| false |
93e68f2f4379b51c32dc0bdc3c513a17ba2e2bf1 | dev-roliveira/Python | /Arquivos de Código/tuplas.py | 1,295 | 4.46875 | 4 | """
Tuplas
"""
# Gerar tupla por Range
# tupla = tuple(range(11))
# print(tupla)
# Desempacotamento de Tupla
# tupla = ('Geek University', 'Programação em Python')
# escola, curso = tupla
# print(escola)
# print(curso)
# Adição, Remoção de elementos nas tuplas não existem, dado o fato de serem imutáveis
# Soma, Valor Máximo, Valor Mínimo e Tamanho funcionam como em listas
# Concatenação de Tuplas
# tupla = 1, 2, 3
# print(tupla)
# tupla2 = 4, 5, 6
# print(tupla2)
# print(tupla + tupla2)
# Ou pode-se realizar o metodo:
# tupla = tupla + tupla2
# Verificar se determinado elemento está contido na tupla
# tupla = 1, 2, 3
# print(3 in tupla)
# Iterando em um tupla
# tupla = 1, 2, 3
# for n in tupla:
# print(n)
# for indice, valor in enumerate(tupla):
# print(indice, valor)
# Contando elementos dentro de uma tupla
# tupla = ('a','b', 'c', 'd', 'e', 'a', 'b')
# print(tupla.count('a'))
# Dicas na utilização de tuplas
# Devemos utilizar tuplas sempre que não precisarmos modificar os dados contidos em uma coleção
# O acesso a elementos de uma tupla é semelhante ao acesso em uma lista
# Iterar com while
# Slicing também é permitido em Tuplas
# Tuplas são mais rápidas do que listas
# A imutabilidade deixa a tupla mais segura que uma lista normal
#
| false |
7bbadb2f479ddd6d281afa14841ab900b8de2f9a | cifpfbmoll/practica-5-python-klz0 | /P5E59_sgonzalez.py | 592 | 4.15625 | 4 | #Práctica 5 - Ejercicios para realizar con bucles for
#P5E9_sgonzalez
# Escribe un programa que pida la anchura de un rectángulo y lo dibuje
# de la siguiente manera: anchura: 5 altura: 4
#*****
#* *
#* *
#*****
ancho=int(input("Introduce el ancho del rectángulo "))
alto=int(input("Introduce el alto del rectángulo "))
PX="*"
for i in range(alto):
if (i==0)or(i==alto-1):
print(PX*ancho)
print (" ")
else:
print(PX+((ancho-2)*" ")+PX)
print (" ")
| false |
6dc54e8f4ca020fb4a3d81c6e722e19737fc7b9e | nicholasgdml/exercicioscursoemvideo-python | /ex_python_mundo3/ex076.py | 874 | 4.1875 | 4 | """
Exercício Python 076: Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços,
na sequência. No final, mostre uma listagem de preços, organizando os dados em forma tabular.
"""
# Tupla de produtos
produtos = ('Lápis', 1.75,
'Borracha', 2.00,
'Caderno', 15.90,
'Estojo', 25.00,
'Transferidor', 4.20,
'Compasso', 9.99,
'Mochila', 120.00,
'Caneta', 22.30,
'Livros', 34.90)
# Titulo
print('=' * 34)
print(f'{"Tabela de preços":^34}')
print('=' * 34)
# looping for que ultiliza impar e par para encontrar o preço e nome do produto
for pos in range(0, len(produtos)):
if pos % 2 == 0:
print(f'{produtos[pos]:•<23}', end='')
else:
print(f'R${produtos[pos]:>7.2f}')
# Linha para finalizar
print('=' * 34)
| false |
2f8c641d57a59a561ec532682137e036bb00a869 | nicholasgdml/exercicioscursoemvideo-python | /ex_python_mundo3/ex093.py | 965 | 4.15625 | 4 | '''Exercício Python 093: Crie um programa que gerencie o aproveitamento de um jogador de futebol.
O programa vai ler o nome do jogador e quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida.
No final, tudo isso será guardado em um dicionário, incluindo o total de gols feitos durante o campeonato.'''
jogador = {}
gols = []
jogador['nome'] = str(input('Nome do jogador: '))
partidas = int(input(f'Quantas partidas {jogador["nome"]} jogou?: '))
for c in range(0, partidas):
gols.append(int(input(f' Quantos gols na partida {c}?: ')))
jogador['gols'] = gols[:]
jogador['total'] = sum(gols)
print('=-' * 24)
print(jogador)
print('=-' * 24)
for k, v in jogador.items():
print(f'O campo {k} tem o valor {v}.')
print('=-' * 24)
print(f'O {jogador["nome"]} jogou {partidas} partidas.')
for k, v in enumerate(jogador['gols']):
print(f' -> Na partida {k}, fez {v} gols.')
print(f'Foi um total de {jogador["total"]}') | false |
64b9fa9d4b229ac938e714ced54ae66928a5af89 | nicholasgdml/exercicioscursoemvideo-python | /ex_python_mundo3/ex099.py | 724 | 4.21875 | 4 | """Exercício Python 099: Faça um programa que tenha uma função chamada maior(),
que receba vários parâmetros com valores inteiros. Seu programa tem que analisar
todos os valores e dizer qual deles é o maior."""
from time import sleep
def maior(*maior):
print('~' * 30)
print('Analisando os valores passados...')
for k, v in enumerate(maior):
print(v, end=' ')
sleep(0.5)
if k == 0:
maior_valor = v
else:
if v > maior_valor:
maior_valor = v
print(f'Foram informados {len(maior)} valores ao todo.')
print(f'O maior valor informado foi {maior_valor}.')
maior(10, 4)
maior(5, 11, 7, 10, 3, 9)
maior(1, 3, 1, 2)
maior(11, 1)
| false |
9d354b7b577b406b82d172555d2c678ee0ffd89b | nicholasgdml/exercicioscursoemvideo-python | /ex_python_mundo3/ex097.py | 802 | 4.21875 | 4 | '''Exercício Python 097: Faça um programa que tenha uma função chamada escreva(), que receba um texto qualquer como parâmetro e mostre uma mensagem com tamanho adaptável. Ex:
escreva(‘Olá, Mundo!’)
Saída:
~~~~~~~~~
Olá, Mundo!
~~~~~~~~~
'''
def escreva(palavra):
tamanhoPalavra = len(palavra)
print('~' * (tamanhoPalavra + 4))
print(f' {palavra}')
print('~' * (tamanhoPalavra + 4))
escreva('Nicholas') | false |
2d73ba0b486367cc744ce2a57b73da98071dda23 | nicholasgdml/exercicioscursoemvideo-python | /ex_python_mundo2/ex060.py | 396 | 4.125 | 4 | '''Exercício Python 060: Faça um programa que leia um número qualquer e mostre o seu fatorial. Exemplo:
5! = 5 x 4 x 3 x 2 x 1 = 120'''
from math import factorial
while True:
n = int(input('Digite um número para fatorar: '))
f = factorial(n)
c = n
while c > 0:
print('{}'.format(c), end='')
print(' x ' if c > 1 else ' = ', end='')
c -= 1
print(f) | false |
f65168ab112875c8156b53907831c6c029f616b3 | BKunneke/Python | /UDemyClass/ListsAndDictionaries.py | 1,569 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 17 07:07:44 2016
@author: bkunneke
"""
# Lists are sequences of objects
myList = [1, 2, 3, 4, 5]
# Add new items to the list
myList.append(6)
myList.append("Butter")
# Lists are indexed
print(myList[2])
print(myList[len(myList)-1]) # Last Item in the list
print(type(myList))
# Tuples are immutable
myTuple = (1, 2, 2, 2, 3, 4, 5)
# append is not an attribute of a tuple
print(myTuple.count(2))
# Sets and Dictionaries are collections
# Sets are colletions of unique items
mySet = {1, 2, 3, 4}
# Add duplicate item to previous list
myList.append(1)
# Convert to set and the duplicate is gone
mySet = set(myList)
# Dictionaries are collections of key/value pairs
myDict = {"some_key":1, "another_key":"another brick in the wall", "3":"3"}
# Two ways to access the dictionary, both yield the same result
print(myDict.get('another_key'))
print(myDict['another_key'])
# Lists can be converted to sets and vice versa
myNewList = list(mySet)
myNewSet = set(myList)
# Range function can generate a sequence
print(range(1, 10, 2)) # Start at 1, stop at 10, count by 2
myEvenNewerList = list(range(1, 100, 3))
# Range of a list
print(myEvenNewerList[1:4]) # Prints items 2, 3, and 4 in the list
myEvenNewerList[0:3] # First 3 items
myEvenNewerList[:3] # Also the first 3 items
myEvenNewerList[10:] # All items from the 10th element on
myEvenNewerList[-3:-1] # Start at the 3rd from the last and stop at second from last
# Strings are basically lists of bytes
myString = "Bill Kunneke"
myString[1:9] # Yields "ill Kunn"
| true |
290edbf312cac8f43a3c11d5f62f930959ac0358 | kris-randen/udacity-algorithms | /venv/P0/Task4.py | 1,911 | 4.125 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
MAIN, LINEAR, NL, PLOT = '__main__', lambda x: x, '\n', True
def senders_receivers(items, size):
senders, receivers = set(), set()
for item in items[:size]:
senders.add(item[0])
receivers.add(item[1])
return senders, receivers
def callers_callees(size):
return senders_receivers(calls, size)
def texters_textees(size):
return senders_receivers(texts, size)
# noinspection PyShadowingNames
def solution(size_calls, size_texts):
callers, callees = callers_callees(size_calls)
texters, textees = texters_textees(size_texts)
return sorted(list(callers - set().union(texters, textees, callees)))
def time(size):
from time import time
start, _, end = time(), solution(size, size), time()
return end - start
# noinspection PyShadowingNames
def performance(s=100):
sizes = range(s, min(len(calls), len(texts)))
return sizes, [time(size) for size in sizes]
if __name__ == MAIN:
marketers = solution(len(calls), len(texts))
print(f"These numbers could be telemarketers: {NL + NL.join(list(marketers))}")
if PLOT:
from plot import plot
n, t = performance()
plot(n, t, loglog=True, interpolation=LINEAR) | true |
b9ce22b48224232998fd6e605ca9910953c38d90 | zhijingjing1/DSCI_522_group_31 | /src/01_download_data.py | 1,481 | 4.375 | 4 | # author: Tran Doan Khanh Vu
# date: 2020-11-21
"""Downloads a csv data from a website to a local filepath. The output file will be either a csv or a feather file format, and it is determined by the extension of the file name.
Usage: src/download_data.py --url=<url> --out_file=<out_file>
Options:
--url=<url> The URL of the file we want to download (the extension must be csv)
--out_file=<out_file> The path and the filename and the extension where we want to save the file in our disk
"""
import os
import pandas as pd
import requests
from docopt import docopt
import feather
opt = docopt(__doc__)
def main(url, out_file):
# Step 1: Check if the url is valid
request = requests.get(url)
if request.status_code != 200:
print('Web site does not exist')
return
# Step 2: Read the data into Pandas data frame
input = pd.read_csv(url)
# Step 3: Create the path if it does not exist
dirpath = os.path.dirname(out_file)
if not os.path.exists(dirpath):
os.makedirs(dirpath)
# Step 4: Write the file locally based on the extension type
extension = out_file[out_file.rindex(".")+1:]
if extension == "csv":
input.to_csv(out_file, index = False)
print("Create csv file " + out_file)
elif extension == "feather":
feather.write_dataframe(input, out_file)
print("Create feather file " + out_file)
if __name__ == "__main__":
main(opt["--url"], opt["--out_file"]) | true |
08441caafe44d2bae9d1f3511791598ad90ec02e | samskinner111/python_programs | /conditionals_and_loops.py | 1,835 | 4.15625 | 4 | #### False in Python #####
print(False is False)
print(None is False)
print(int(0) is False)
print(float(0.0) is False)
print("" is False) # empty string
print([] is False) # empty list/array
print(() is False) # empty tuple
print({} is False) # empty dict/hash
print(set() is False) # empty set
print()
###
num = 5
if (num%2) == 0:
print('I like ' + str(num))
else:
print('I\'m ambivalent about ' + str(num))
###
print()
#### Handling exceptions
def get_number_from_user():
input_is_invalid = True
while input_is_invalid:
num = input('Please enter a whole number: ')
try:
num = int(num)
print('whole!')
# Won't get here if exception is raised. '
input_is_invalid = False
except ValueError:
print(num + ' is not a whole number. Try again.')
return num
get_number_from_user()
print()
####
houses = ["Stark", "Lannister", "Targaryen"]
h = list(map(lambda house: house.upper(), houses))
print(h)
print()
#### filter
nums = [0,1,2,3,4,5,6,7,8,9]
f = list(filter(lambda x: x % 2 == 0, nums))
print(f)
print()
#### Comprehensions
grades = [100, 90, 0, 80]
print([x for x in grades])list()
print([x+5 for x in grades])
print()
#####
words = ["Winter is coming", "Hear me roar", "Fire and blood"]
g = list(zip(houses, words))
print(g)
print(type(g)) # list/array
print()
###
house2words = {house: words for house, words in zip(houses, words)}
print(house2words)
print(type(house2words)) # dict/hash
print()
###
z = dict(zip(houses, words))
print(z)
print(type(z))
print()
###
import functools
d = functools.reduce(lambda x, y: x * y, [1,1,2,3,4,5,6,7,8,9]) #
print(d)
print()
##
a1 = functools.reduce(lambda x, y: x * y, [1,2,3,4,5])
a2 = functools.reduce(lambda x, y: x * y, range(1,6))
print(a1)
print(a2) #
print()
| true |
b3e4e4643606d5b0eb50d0a26b6d9fc20dc21ed6 | tvonsosen/CAP-code | /recursionCombos.py | 707 | 4.125 | 4 | # A function that uses recursion to print all distinct combinations of a given length k, can repeat values from list
def combosList(list1, k):
new = []
# removes duplicate elements in given list so duplicate lists aren't printed
for i in list1:
if i not in new:
new.append(i)
generateCombos(new,0,k,[])
def generateCombos(list1,start,k,combo):
# Prints list using recursion and then pops/replaces last value to print other combinations
for i in range(start,len(list1)):
combo.append(list1[i])
if k == 1:
print(combo)
else:
generateCombos(list1,i,k-1,combo)
combo.pop()
combosList([1,2,3], 2)
| true |
2ee1a9fc603738537b43b5cacd3391e8f721b78f | g-ford/advent-of-code | /2022/day8/main.py | 2,875 | 4.125 | 4 | def count(t, r, step, i):
"""
Count the number of 'scenic' trees near tree `t`
`r` is the set of trees to compare - either a row or column
`step` is the direction to search and should 1 or -1
`i` is the position of the x|y that we are looking for
Interestingly, apparently elves can see over trees but can't look up
If a tree is blocked by a larger tree that it still smaller than `t` then
we can still see it. e.g `t` being a tree of height 5 and `r` a set
of 4341 would count as 4
"""
if step < 0:
over = list(reversed(r[:t[i]]))
else:
over = r[t[i]+1:len(r)]
count = 0
for s in over:
if s[2] >= t[2]:
return count + 1
count += 1
return count
def countRow(t, r, step):
return count(t, r, step, 1)
def countCol(t, r, step):
return count(t, r, step, 0)
def day8(input):
visible = set()
all_trees = set()
max_y = len(input)
max_x = len(input[0])
for x in range(max_x):
for y in range(max_y):
# on first pass we know that trees on the edge are visible
if x == 0 or y == 0 or x == max_x - 1 or y == max_y - 1 :
visible.add((x, y, input[x][y]))
all_trees.add((x, y, input[x][y]))
# We do part 2 first as we don't care about trees on the edge
# and we have that set now before we start adding other visible
# trees to it
scores = []
for tree in sorted(all_trees - visible):
row = sorted([t for t in all_trees if t[0] == tree[0]])
col = sorted([t for t in all_trees if t[1] == tree[1]])
r = countRow(tree, row, 1)
l = countRow(tree, row, -1)
u = countCol(tree, col, -1)
d = countCol(tree, col, 1)
scores.append(r * l * u * d)
print("Part2: ", f"Max scenic: {max(scores)}")
for tree in sorted(all_trees):
if tree not in visible:
row = [t for t in all_trees if t[1] == tree[1]]
col = [t for t in all_trees if t[0] == tree[0]]
# North
if all([t[2] < tree[2] for t in row if t[0] < tree[0]]):
visible.add(tree)
continue
# south
if all([t[2] < tree[2] for t in row if t[0] > tree[0]]):
visible.add(tree)
continue
# east
if all([t[2] < tree[2] for t in col if t[1] < tree[1]]):
visible.add(tree)
continue
# west
if all([t[2] < tree[2] for t in col if t[1] > tree[1]]):
visible.add(tree)
continue
print("Part1: ", f"Visible: {len(visible)}")
if __name__ == "__main__":
def clean(value):
return list(map(int, (x for x in value.strip())))
input = list(map(clean, open("day8/input.txt").readlines()))
day8(input)
| true |
60f77271c3ced1394530ad6769f59d0665c04c5e | 911-buiciuc-andrei/intermediate-python-course | /dice_roller.py | 550 | 4.15625 | 4 | import random
def main():
dice_rolls = int(input("The number of dice throws: "))
dice_size = int(input("The number of sides for a dice: "))
dice_sum = 0
while dice_rolls:
roll = random.randint(1, dice_size)
if roll == 1:
print(f'You rolled a {roll}! Critical Fail!')
elif roll == dice_size:
print(f'You rolled a {roll}! Critical Success!')
else:
print(f'You rolled a {roll}')
dice_sum += roll
dice_rolls -= 1
print(f'You rolled a total of: {dice_sum}')
if __name__== "__main__":
main()
| true |
5fba8dbdab0297997d645b4bfe86f7e73698b7b3 | omer21-meet/meet2019y1lab1 | /Day3/shelon.py | 577 | 4.125 | 4 | name = input("Whats your name?")
print("Hello " + name)
age = (input("Whats your age " + name))
live = input("Where do u live?")
print(live + " is a nice place!")
team = input("Whats your favorite soccer team?")
print("I dont like them that much...")
num = input("Choose a number between 0 to 1000 and i will try to guess it!")
num2 = 985
if num == num2:
print("is your number 985?")
else:
print("Hmm let me think...")
num3 = input("Can u write your number again?")
answer = input("Is your number " + num3 + "?")
if answer == "yes":
print("Yay!")
| true |
bdcc44484d5e45f446be3b86ebbe23580b1f9871 | rusheelkurapati30/Python | /multithreadCon.py | 1,249 | 4.28125 | 4 | #Program to print odd and even numbers.
# maximum = int(input("\nPlease enter maximum value to print even and odd numbers: "))
# for number in range(1, maximum+1):
# if number % 1 == 0:
# print(number)
# else:
# print(number)
#Program to print odd and even numbers.
# maximum = int(input("\nPlease enter any maximum value to print even and odd numbers: "))
# def odd():
# for oddNumber in range(1, maximum + 1, 2):
# print(oddNumber)
# def even():
# for evenNumber in range(2, maximum + 1, 2):
# print(evenNumber)
# odd()
# even()
#Program to print odd and even numbers using threads.
import threading
import time
maximum = int(input("\nPlease enter any maximum value: "))
def odd():
for oddNumber in range(1, maximum + 1, 2):
print(oddNumber)
time.sleep(0.2)
def even():
for evenNumber in range(2, maximum + 1, 2):
print(evenNumber)
time.sleep(0.2)
def threadStart():
try:
thread1 = threading.Thread(target = odd)
thread1.start()
time.sleep(0.1)
thread2 = threading.Thread(target = even)
thread2.start()
except:
print("Error!")
threadStart()
CREATE FUNCTION printName(
name varchar(20)
)
RETURNS SELECT name from dual | true |
5fd0cc8371301539c0443ae15b9fffda1bf97212 | jorgemartinez2010/AprendiendoPython. | /Scripts/Multiplo.py | 747 | 4.21875 | 4 | #Se captura un numero y se almacena en la variable numero
#y es convertido a tipo int
numero=int(input("Dame un numero entero: "))
#Se almacenan los valores booleanos la evaluacion de
#residuales. Si el residuo es cero, entonces el
#numero es multiplo.
esMultiplo3 = ((numero%3)==0)
esMultiplo5 = ((numero%5)==0)
esMultiplo7 = ((numero%7)==0)
#Cuando se usa el and, se resuelve por verdadero si todas
#las condiciones son verdaderas. Cuando se usa or, se resuelve
#como verdadero si al menos hay una condicion verdadera. Los
#parentesis le dicen a Pyhton que las primeras condiciones
#son juntas, y la tercera es una condicion independiente.
if ((esMultiplo3 and esMultiplo5) or esMultiplo7):
print("Es correcto")
else:
print("Incorrecto") | false |
e6781560237199b923a1ff0c6452b7a8ec8911cf | sueunal/sueun.github.io | /index.py | 1,311 | 4.15625 | 4 | import pandas as pd
import streamlit as st
df = pd.DataFrame({'A' : [4,None], 'B' : [10,20],
'C' : [100,50], 'D' : [-30,-50],
'E' : [1500,800], 'F' : [0.258,1.366]})
# Apply styler so that the A column will be displayed with integer value because there is None in it.
df_style = df.style.format(precision=2, na_rep='MISSING', thousands=",", formatter={('A'): "{:.0f}"})
st.write('Current dataframe')
st.dataframe(df_style)
# We use a form to wait for the user to finish selecting columns.
# The user would press the submit button when done.
# This is done to optimize the streamlit application performance.
# As we know streamlit will re-run the code from top to bottom
# whenever the user changes the column selections.
with st.form('form'):
sel_column = st.multiselect('Select column', df.columns,
help='Select a column to form a new dataframe. Press submit when done.')
drop_na = st.checkbox('Drop rows with missing value', value=True)
submitted = st.form_submit_button("Submit")
if submitted:
dfnew = df[sel_column]
if drop_na:
dfnew = dfnew.dropna()
st.write('New dataframe')
dfnew_style = dfnew.style.format(precision=2, na_rep='MISSING', thousands=",", formatter={('A'): "{:.0f}"})
st.dataframe(dfnew_style) | true |
6975011168771670ca39913b57e48aeeb5d50235 | MichaelLing83/pymixofknuth | /src/Buss.py | 919 | 4.34375 | 4 |
class Buss:
'''
Buss class represents a buss connection between two components, which is composed of a set of pins. Each pin is a boolean value, and True stands for high voltage, and False stands for low voltage.
'''
def __init__(self, pin_default_state=False):
'''
'''
self.pins = list()
self.pin_names = dict()
self.pin_default_state = pin_default_state
def add_pin(self, pin_index, pin_name):
'''
'''
assert pin_index>=len(self.pins), "pin_index=%d is already defined!" % pin_index
assert pin_name not in self.pin_names.keys(), "pin_name=%s is already defined!" % pin_name
self.pins.append(self.pin_default_state)
self.pin_names[pin_name] = pin_index
if __name__ == '__main__':
print("Buss class test!")
buss = Buss()
buss.add_pin(0, "valid")
print(buss.pins)
print(buss.pin_names) | true |
f2e89068de62d09c767faf93176dd7aadf88a3b8 | zhujinliang/python-snippets | /sort/bubble_sort.py | 380 | 4.3125 | 4 | # -*- coding: utf-8 -*-
def bubble_sort(array):
length = len(array)
for i in range(length):
for j in range(length - i - 1):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
return array
if __name__ == '__main__':
array = [2, 1, 5, 6, 9, 10, 3, 8, 16, 7]
result = bubble_sort(array)
print result | false |
7fc2841d85f749d22268140eba6d98b399c80e72 | zj-dreamly/my-program-learning | /python/01.入门/15.条件运算符.py | 700 | 4.1875 | 4 | # 条件运算符(三元运算符)
# 语法: 语句1 if 条件表达式 else 语句2
# 执行流程:
# 条件运算符在执行时,会先对条件表达式进行求值判断
# 如果判断结果为True,则执行语句1,并返回执行结果
# 如果判断结果为False,则执行语句2,并返回执行结果
# 练习:
# 现在有a b c三个变量,三个变量中分别保存有三个数值,
# 请通过条件运算符获取三个值中的最大值
# print('你好') if False else print('Hello')
a = 30
b = 50
# print('a的值比较大!') if a > b else print('b的值比较大!')
# 获取a和b之间的较大值
max = a if a > b else b
print(max) | false |
7b019660126a15fe3bbcbd43a8db17057642235f | dfaure57/cip39 | /uni2/logica.py | 1,675 | 4.125 | 4 | # coding: utf-8
def conjuncion(variable1, variable2):
if (variable1 and variable2):
return 'verdad'
else:
return 'falso'
def disyuncion(variable1, variable2):
if (variable1 or variable2):
return 'verdad'
else:
return 'falso'
def mostrar(variable1):
if (variable1):
return 'verdad'
else:
return 'falso'
#
# Un poco de lógica
#
# conjunción (símbolos habituales AND, &&)
# proposición 1 operador proposición 2 RESULTADO
# ============= ======== ============= =========
# verdad y verdad => verdad
# verdad y falso => falso
# falso y verdad => falso
# falso y falso => falso
#
# disyunción (símbolos habituales OR, ||)
# proposición 1 operador proposición 2 RESULTADO
# ============= ======== ============= =========
# verdad o verdad => verdad
# verdad o falso => verdad
# falso o verdad => verdad
# falso o falso => falso
#
# Negación (simbolos habituales: not, !)
#
# No verdad = falso
# No falso = verdad
#
# No (no verdad) = verdad (aka "el si de las niñas")
print ('Ejecutando '+__file__)
print ("ejemplos con lógica\n")
a = True;
b = False;
print ("a es "+mostrar(a))
print ("b es "+mostrar(b))
print ("conjunción 'a y b' es " + conjuncion(a,b))
print ("disyunción 'a o b' es " + disyuncion(a,b))
print ("la negacion de 'a' es " + mostrar(not a))
print ("\fFIN desde python!\n")
| false |
70bbdf602ed30bf8ab01532b08afa11d68d999c2 | mehzabeen000/dictionary_python | /sort_values.py | 392 | 4.46875 | 4 | # Python script to sort (ascending and descending) a dictionary by value.
dict_names={'bijender':45,'deepak':60,'param':20,'anjali':30,'roshini':50}
dict1 = sorted(dict_names.items(), key=lambda x: x[1])
print(dict1)
dict_names={'bijender':45,'deepak':60,'param':20,'anjali':30,'roshini':50}
dict1 = sorted(dict_names.items(), key=lambda x: x[1],reverse=True)
print(dict1)
| false |
7b8d084d23cbd1e4f9ab2b537c03fd3092334c2c | mehzabeen000/dictionary_python | /unique_values_list.py | 462 | 4.40625 | 4 | #From the given list we have to take the values in different list and sort the unique values.
list1=[{"first":"1"}, {"second": "2"}, {"third": "1"}, {"four": "5"}, {"five":"5"}, {"six":"9"},{"seven":"7"}]
list_values=[]
for keys in list1:
for key,values in keys.items():
list_values.append(values)
end_list=[]
for element in list_values:
if element not in end_list:
end_list.append(element)
print(end_list,"is the sorted unique list")
| true |
577d79b03ce6b59d68934af581eeac59e3801488 | luoChengwen/Hacker_rank_test | /leetcode/ImplementTrie.py | 1,745 | 4.3125 | 4 | '''
Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns true
Note:
You may assume that all inputs are consist of lowercase letters a-z.
All inputs are guaranteed to be non-empty strings.
'''
# solution 1: first intuition is to use list, then append. I tried but this is slow.
# solution 2:
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.wordlist = dict()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
temp = self.wordlist
for i in word:
if i not in temp:
temp[i] = dict()
temp = temp[i]
temp['#'] = True #this is a nice mark indicating the end of the word
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
temp = self.wordlist
for j in word:
if j in temp:
temp = temp[j]
else:
return False
print(temp)
return '#' in temp # this is to check whether it is now the end of the word,
# compare with starts with
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
temp = self.wordlist
for m in prefix:
if m in temp:
temp = temp[m]
else:
return False
return True
| true |
52c33d67d70a072753934df5dfeee51e58fbeebc | Sanyarozetka/Python_lessons | /hometask/hometask_04/String.py | 443 | 4.15625 | 4 | """
Дана строка, состоящая из слов, разделенных пробелами. Определите, сколько в ней слов.
Используйте для решения задачи функцию `count()`
"""
string = input("Введите строку: ")
n_words = string.count(' ')
print('Количество слов в строке, разделенные пробелами: ' + str(n_words + 1))
| false |
3d1be21fe100d868a1a0a836f849910f1bb90f59 | MasReed/Commons | /numerical/dec_bin_conversion.py | 1,450 | 4.59375 | 5 |
def dec_to_bin(dec_num):
"""Converts a decimal number into a binary string.
Args:
dec_num (int): Decimal number to convert.
Returns:
str: Binary number as a string.
"""
binary = []
quotient = dec_num
while quotient != 0:
#q, r = divmod(quotient, 2)
remainder = quotient % 2
quotient = quotient // 2
binary.append(str(remainder))
return ''.join(binary)
def bin_to_dec(bin_str):
"""Converts a binary string into a decimal number.
Args:
bin_str (str): Binary string to convert.
Returns:
int: Decimal number.
"""
decimal = 0
bit_exponent = 0
bin_str = list(bin_str)
bin_reverse = bin_str[::-1]
# Uses reverse of binary to exponentiate each term more cleanly.
for bit in bin_reverse:
bit = int(bit)
if bit != 1 and bit != 0:
raise ValueError('A binary number should be used.')
decimal += bit * (2**bit_exponent)
bit_exponent += 1
return decimal
if __name__ == '__main__':
print('Convert between decimals or binary, please make a choice:')
print('[1]: Decimal -> Binary')
print('[2]: Binary -> Decimal')
conversion = input()
if conversion == '1':
dec = int(input('Enter the decimal number: '))
print(dec_to_bin(dec))
elif conversion == '2':
bin = input('Enter the binary number: ')
print(bin_to_dec(bin))
| true |
de24cbb5bbc94ac17a0cbbbf2c2e335f62259dc5 | fadeawaylove/leetcode_practice | /数组/867_转置矩阵.py | 768 | 4.21875 | 4 | """
给定一个矩阵 A, 返回 A 的转置矩阵。
矩阵的转置是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。
示例 1:
输入:[[1,2,3],[4,5,6],[7,8,9]]
输出:[[1,4,7],[2,5,8],[3,6,9]]
示例 2:
输入:[[1,2,3],[4,5,6]]
输出:[[1,4],[2,5],[3,6]]
提示:
1 <= A.length <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/transpose-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from typing import List
class Solution:
def transpose(self, A: List[List[int]]) -> List[List[int]]:
return list(zip(*[A[i] for i in range(len(A))]))
Solution().transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
| false |
a16691307cb35b62a4aeb31b7768830fbb8fba10 | snehaly24/python-assignments | /assignments-2/Assignment2_6.py | 365 | 4.3125 | 4 | """
6. Write a program which accept one number and display below pattern.
Input : 5
Output :
* * * * *
* * * *
* * *
* *
*
"""
def main():
no = int(input("Enter number :"))
for row in range(no,0,-1):
for col in range(row):
print("*",end=" ")
print()
if __name__ == "__main__":
main()
| true |
dc5618213be2e90f196b7e4705776f06dac43d3c | snehaly24/python-assignments | /assignment-1/Assignment1_10.py | 267 | 4.21875 | 4 | """
Write a program which accept name from user and display length of its name.
Input : Marvellous Output : 10
"""
def main():
name = input("Enter the name :")
print("Length of string :",len(name))
if __name__ == "__main__":
main()
| true |
0adca422a6e3cf5a4e87a8d52d2db12aecdfbe76 | Dark-C-oder/Data_structures | /venv/linked_list_Insertion.py | 1,248 | 4.1875 | 4 | class node:
def __init__(self, data):
self.next = None
self.data = data
class linked_list:
def __init__(self):
self.head = None
def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next
def append(self,data):
new_node = node(data)
if self.head == None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def insert_asFirstNode(self,data):
new_node = node(data)
new_node.next = self.head
self.head = new_node
def insert_inMiddle(self,data,prev_node):
if not prev_node:
print("No previous node is available enter correct node!!!!!!")
return
new_node = node(data)
new_node.next = prev_node.next
prev_node.next = new_node
lnd = linked_list()
lnd.append('A')
lnd.append('B')
# lnd.append('C')
lnd.append('D')
lnd.append('E')
# lnd.print_list()
# print("===============")
lnd.insert_asFirstNode('v')
lnd.insert_inMiddle('C',lnd.head.next.next)
lnd.print_list()
print(l)
| true |
63e1857eb8ba1606abf71011ac21417261186697 | mehmetozanguven/Python-Files | /Homeworks/HW4/HW4_220201036.py | 2,662 | 4.15625 | 4 | import random
words = ["stack", "queue", "tree", "linked list", "software",
"hardware", "operating systems", "algorithm", "computer", "network"]
def randomly():
guess_word=random.choice(words)
list_guess_word = list(guess_word)
return list_guess_word
def initializing_word():
initializing_word = "-" * len(a)
list_initializing_word = list(initializing_word)
for i in range(len(a)):
if " " == a[i]: #this if statement was used for to remove "-" "operating system and linked list"
list_initializing_word[i] = " "
return list_initializing_word
def replace_word():
remaining = 6
while remaining >= 0:
take_word = raw_input("Plesea enter the word or one letter ==")
if len(take_word) == 1:
if take_word not in a:
remaining = remaining - 1
if remaining == 0:
print name.upper(),",You have lost.Our world would be","".join(a)
break
print "You have ",remaining,"remainings"
if take_word in a:
for i in range (len(a)):
if take_word == a[i]:
b[i] = take_word
if b == a: #this if condition was used for if all letter ,which gets user,
# form a word,then program says that "YOU WIN"
print name.upper(),",Congratulations!Our world is","".join(a)
break
print b
else:
if take_word == "".join(a):
print name.upper(), ",Congratulations! Our word is",take_word.upper()
remaining = -1 #this line was used for out of the loop
if take_word != "".join(a):
print name.upper(),",You have lost.Our word would be","".join(a)
remaining = -1 #this line was used for out of the loop
print "Welcome to our game.Please enter a name then game will be started\n" \
"Pay attention!!If you want to guess all word,you have just one guess\n" \
"If you want to guess by one by,you have 6 guesses"
print
name = raw_input("Please enter a your name \n")
print "Welcome ",name.upper()
correct = True
while correct:
a = randomly()
b = initializing_word()
print "This is the list"
print b
replace_word()
print "Do you want to play again?If you do not please enter 1 if you do enter 2"
x = input()
if x == 1:
correct = False #this line,i am using like break
else:
correct = True
#Mehmet Ozan Guven
#220201036 | true |
06392c078ff130910c97257635e59c96ed7da79a | jonicmecija/EE-381 | /Code Examples/modeExample.py | 637 | 4.125 | 4 | '''
Jonic Mecija
August 28, 2019
EE 381
Description: This is a method on how to get the mode.
'''
# how to get the mode
nums = [3,4,5,7,7,7,1,1,1]
from collections import Counter
c = Counter(nums) #creates tuples of elements in the list (not mutable)
print(c)
freq = c.most_common() #most common method
print(freq)
max_occur = freq[0][1] #second element of tples will be max assigned
if max_occur != 1:
modes = [] #empty list
for m in freq:
if m[1] == max_occur: # second position in tuple equal to max_occur
modes.append(m[0])
print("The mode(s) are: ", modes)
else:
print("There is no mode.") | true |
143a1916c0ebf1e6023fe9d3bd0d4f21dab9339d | UmaViswa/Number-Pattern | /pattern.py | 247 | 4.125 | 4 | #printing pattern getting values from the user
from __future__ import print_function #python3 to python2 compatibility
rows = int(input("Enter the number:"))
for i in range(1,rows+1):
for j in range(1,i+1):
print(i, end='')
print()
| true |
7366cc14e1fc4e0d9247616295f7491f93310482 | felipe-nakanishi/Python-Programming | /Credit Card Validation/credit_card_check.py | 1,748 | 4.34375 | 4 | #function that applies Lunh's algorithm to generate a validation number:
def validation(number):
sum_1 = 0
sum_2 = 0
#sum the numbers from the last digit skipping one digit:
for digit_1 in range(len(str(number)),0,-2): #we needed to convert the number to str so that we can find its len.
number_int = int(str(number)[digit_1-1]) #convert the number to int so that we can sum it.
sum_1 += number_int
for digit_2 in range(len(str(number))-1,0,-2): #multiply the remaining numbers by 2 and sum them.
number_mult = int(str(number)[digit_2-1])*2
sum_2 += sum(int(digit) for digit in str(number_mult))
validation_number = sum_1 + sum_2 #obtain the validation number.
return validation_number
#function that uses the validation number to identify if the card is valid and it's brand:
def check_brand(validation_number):
if validation_number % 10 == 0: #check if the validation number represents a valid credit card.
#if the number is valid then we check to identify what is the brand of the card.
if len(str(number)) == 15 and (str(number)[:1] == '34' or str(number)[:1] == '37'):
return 'AMEX'
elif len(str(number)) == 16 and (str(number)[:1] == '51' or str(number)[:1] == '52' or str(number)[:1] == '53' or str(number)[:1] == '54' or str(number)[:1] == '55'):
return 'MASTERCARD'
elif (len(str(number)) == 16 or len(str(number)) == 13) and str(number)[0] == '4':
return 'VISA'
else:
return 'INVALID'
number = input('Type a credit card number to check if it is valid, please:') #prompt for the user to type a card number
#call the functions and return the brand of the card if valid.
validation_number = validation(number)
brand = check_brand(validation_number)
print(brand)
| true |
6708606f700997bc7f40a395760db643e77c3470 | ViniciusSchutt/Python | /Introductory algorithms/Simulacao lançamento de dados.py | 505 | 4.21875 | 4 | """
faça um programa que simule um lançamento de dados. Lance os dados 10 vezes e armazene os dados em uma lista.
depois, mostre quantas vezes cada valor foi conseguido.
dica use um vetor de contadores (1 a 6) e uma função para gerar numeros aleatorios
simulando o lancamento de dados
"""
from random import randint
lista = [0] * 7
for i in range (10):
n = randint(1,6)
print("Numero: ", n)
lista[n] = lista[n]+1
for i in range(1,7):
print("Numero: ", i, "quantidade: ", lista[i])
| false |
263f339e775700fa2a383547e7d03bdbd799c4cf | ViniciusSchutt/Python | /Introductory algorithms/Triple.py | 253 | 4.28125 | 4 | # simple code to give the triple of any number informed
n = float(input("Inform a number: "))
while n != -10000: # -10000 is a random example
triple = n*3
print("The triple of the number is: ", triple)
n = float(input("Inform a number: "))
| true |
ec6982c897c981a3f10d05df0dd0e664b7b6912d | ViniciusSchutt/Python | /Varied codes/cash.py | 2,223 | 4.125 | 4 | import sys
cents = 0
coins = 0
quarters = 25
dimes = 10
nickels = 5
pennies = 1
def test(dollars): # Creating a function to test wether the user input is composed of numbers only or not
while True:
try:
val = float(dollars) # If this is true, call the function 'charge' which will do the calculations
charge(dollars)
break
except ValueError: # If false, recursively call the test function forever until the user contributes
test(dollars=input("Charge: $ "))
def charge(dollars):
# Define all variables as global to avoid problems
global cents
global coins
global quarters
global dimes
global nickels
global pennies
# As in here the input is guaranteed to be numeric, transform it to float type
dollars = float(dollars)
if dollars > 0: # Finally, with all tests done, the program can run normaly
if dollars == 0.00: # If the informed value is zero
print(f"{coins}") # Automatically the number of coins will be zero as well
# Converting the dollars value to cents
cents = round(dollars * 100)
# While cents are greater than 25, do the following:
while cents >= 25:
cents = cents - quarters
coins = coins + 1
# While cents are simultaneously greater than dimes and lesser than quarters, do the following:
while cents < 25 and cents >= 10:
cents = cents - dimes
coins += 1
# While cents are simultaneously greater than nickels and lesser than dimes, do the following:
while cents < 10 and cents >= 5:
cents = cents - nickels
coins += 1
# While cents are simultaneously greater than pennies and lesser than nickels, do the following:
while cents < 5 and cents >= 1:
cents = cents - pennies
coins += 1
# Print the number os coins in the screen
print(f"{coins}")
sys.exit(0)
if dollars < 0:
print("Invalid input.")
dollars = charge(input("Charge: $ "))
# Get raw user input, so we can test later if it's a number or not
dollars = input("Charge: $ ")
test(dollars) | true |
add8ec6e717c401eb52f9b9d360cc995c8890166 | ViniciusSchutt/Python | /Introductory algorithms/Credito x salario.py | 1,479 | 4.34375 | 4 | """
03 o banco XXX concederá um crédito especial aos seus clientes de acordo com o salário médio no último ano. Elaborar um algoritmo que leia o saldo médio do
cliente e calcule o valor do crédito de acordo com a tabela a seguir. Imprimir uma mensagem informando o saldo médio e o valor do crédito.
SALDO MEDIO PERCENTUAL
de 0 a 500.00 nenhum crédito
de 500.01 a 1000.00 30% do valor do saldo médio
De 1000.01 a 3000.00 40% do valor do saldo médio
Acima de 3000.00 50% do valor do saldo médio
"""
saldomedio=float(input("Saudações cliente, como vai? Por favor, informe seu saldo médio: "))
if saldomedio > 0 and saldomedio <=500.00:
credito=0
print("Sentimos muitíssimo informar senhor(a) mas, com esse saldo, não há crédito a ser concedido, lamentavelmente. Mas não desanime!")
elif saldomedio > 500.00 and saldomedio <= 1000.00:
credito=saldomedio*0.3
print("'Chá-Ching $*-*$' - Congratulações! O valor do seu crédito especial é de: R$", credito)
elif saldomedio > 1000.01 and saldomedio <= 3000.00:
credito=saldomedio*0.4
print("'Chá-Ching $*-*$' - Congratulações! O valor do seu crédito especial é de: R$", credito)
elif saldomedio > 3000.00:
credito=saldomedio*0.5
print("'Chá-Ching $*-*$' - Congratulações! O valor do seu crédito especial é de: R$", credito)
else:
print("Valor de crédito inválido, o senhor(a) pode ter digitando um valor negativo! Tente novamente!")
| false |
e14876fdd70066e88d366c3c96553f648d8c6956 | TheRevanchist/Design-and-Analysis-of-Algorithms-Part-1 | /Programming Assignment 2/Count Comparison 2.py | 1,802 | 4.125 | 4 | # An implementation of quicksort algorithm using the last element of the array
# as pivot. In addition, it prints the total number of comparisons
# the global variable which counts the comparisons
count = 0
def quickSort(array, head, tail):
# an implementation of quicksort algorithm
# inputs:
# array - an unsorted array of numbers
# head - the index of the first element in array, 0
# tail - the index of the last element in array, -1
if head >= tail:
return
else:
pivot = partition(array, head, tail)
quickSort(array, head, pivot)
quickSort(array, pivot+1, tail)
def partition(array, head, tail):
# the implementation of the partition method
# inputs: same as in the previous method
# output: the index of pivot
global count
swap(array, head, tail-1)
pivot = array[head]
i = head + 1
count += tail - head - 1
for j in range(head+1, tail):
if array[j] < pivot:
swap(array, i, j)
i += 1
swap(array, i-1, head)
return i-1
def swap(A, x, y ):
# a helper method which swaps two elements in an array
A[x],A[y]=A[y],A[x]
# read the file
lista = "D:/Workbench/Online Courses/Design and Analysis of Algorithms, Part 1/Programming Assignment 2/text.txt"
f = open(lista, 'r')
array = []
for line in f: array.append(int(line))
# sort it and print the number of comparisons
quickSort(array, 0, len(array))
print count | true |
feca9e772a98920d1fe28157b64cce812b1dd751 | romwil22/python-trick-and-cheat | /sort_tuples/sorting-tuples.py | 318 | 4.15625 | 4 | # List of tuples
tup = (2, 5, 7, 23, 67, 54, 28, 12)
print('list of tuples:\n', tup)
print()
# Sorting a tuples
sort_tup = sorted(tup)
print('Sorted list of tuples:\n', sort_tup)
print()
# sort in descending order
sort_tup = sorted(tup, reverse=True)
print('Sorted list of tuples in descending order:\n', sort_tup)
| true |
cb923b798887d9dc8d9790f52e17b7552da38cfd | RobRcx/algorithm-design-techniques | /dynamic-programming/coin_change_dp.py | 1,313 | 4.125 | 4 | # Copyright (c) June 02, 2017 CareerMonk Publications and others.
# E-Mail : info@careermonk.com
# Creation Date : 2017-06-02 06:15:46
# Last modification : 2017-06-02
# Modified by : Narasimha Karumanchi
# Book Title : Algorithm Design Techniques
# Warranty : This software is provided "as is" without any
# warranty; without even the implied warranty of
# merchantability or fitness for a particular purpose.
def print_coins(min_coins, denominations):
start = len(min_coins) - 1
if min_coins[start] == -1:
print "No Solution Possible."
return
print "Coins:",
while start != 0:
coin = denominations[min_coins[start]]
print "%d " % coin,
start = start - coin
def make_change(denominations, C):
cols = C + 1
table =[0 if idx == 0 else float("inf") for idx in range(cols)]
min_coins = [-1 for _ in range(C + 1)]
for j in range(len(denominations)):
for i in range(1, cols):
coin = denominations[j]
if i >= denominations[j]:
if table[i] > 1 + table[i - coin]:
table[i] = 1 + table[i - coin]
min_coins[i] = j
print_coins(min_coins, denominations)
return table[cols - 1]
print make_change([1, 5, 10, 20, 25, 50], 40)
| true |
fd4dd7bb892962b7e3211cb01517977e234c22c1 | ristory/CS3030-Python-Perl | /Assignment4/temp | 1,183 | 4.25 | 4 | #!/usr/bin/python
while True:
print("\nWelcome to the CS 3030 Temperature Conversion Program");
print("Main Menu");
print("1:Fahrenheit to Celsius");
print("2:Celsius to Fahrenheit");
print("3:Exit program\n");
x = raw_input("Please enter 1, 2 or 3: ");
if x == "1":
y = raw_input("Please enter degrees Fahrenheit: ");
try:
def fahrenheitToCelsius(f):
return str(round((((float(f)) - 32.0) * (5.0 /9.0)),1))
print(y + " degrees Fahrenheit equals " + str(fahrenheitToCelsius(y)) + " degrees Celsius");
except(ValueError):
print("Invalid entry");
elif x == "2":
y = raw_input("Please enter degrees Celsius: ");
try:
def celsiusToFahrenheit(g):
return str(round((((9.0/5.0)*(float(y))+32.0)),1))
print(y + " degrees Celsius equals " + str(celsiusToFahrenheit(y)) + " degrees Fahrenheit");
except(ValueError):
print("Invalid entry");
elif x =="3":
break;
else:
print("Invalid enrty");
# z = (y - 32.0) * (5.0/9.0);
# print ("degrees Celsius euqal degrees Fahrenheit");
# else:
# print("Invalid Entry");
| false |
53f00d30365fed72d015b6d5d04db149737f2786 | sniboboof/data-structures | /mergesort.py | 1,548 | 4.1875 | 4 | import time
import random
def mergesort(mylist):
mergehelper(mylist, 0, len(mylist))
return mylist
def mergehelper(mylist, start, end):
if end-start <= 1:
return mylist
halfway = start + (end-start)/2
mergehelper(mylist, start, halfway)
mergehelper(mylist, halfway, end)
while start < halfway and halfway < end:
if mylist[start] <= mylist[halfway]:
start += 1
else:
insertpartial(mylist, mylist[halfway], start, halfway)
start += 1
halfway += 1
return mylist
def insertpartial(mylist, value, index, end):
#similar to list.insert() but works over only part of a list
#list.insert is O(n) where n is the length of the WHOLE list
#this only inserts over part of the list, so it's O(n) over
#this part of the list, averaging out to O(log n) for the function
#i think
tempval = mylist[index]
mylist[index] = value
for i in range(index+1, end+1):
value = tempval
tempval = mylist[i]
mylist[i] = value
if __name__ == "__main__":
a = range(10000)
#worst part of the algorithm is insertpartial
#so if you never have to call that (it's in order)
#it goes faster
start = time.time()
mergesort(a)
stop = time.time()
print "fastest: " + str(stop-start)
#and it will be the worst when it insertpartials every time
#so reverse order
a.reverse()
start = time.time()
mergesort(a)
stop = time.time()
print "slowest: " + str(stop-start)
| true |
294c32c4b63c0376df295beb0037a4ebe17c168b | amalko/Python--Project--Reversing-a-number | /Reversing a number.py | 256 | 4.3125 | 4 |
num= int(input("Enter the number you want to reverse: "))
reverse= 0
print(reverse)
while (num!=0):
digit= int(num % 10)
reverse= int((reverse*10)) + digit
num= int(num/10)
print("Reversed number is : ", end="")
print(reverse)
| true |
9f65663ca3b3355274af35f192637d4b1f1d1007 | mbrayton27/LeapYear | /LeapYear.py | 475 | 4.125 | 4 | #Run this code by typing "python matthew_brayton_hw1.py" on the engineering server command line. It is just a normal python file
number = int(input("Enter an integer number: "))
if(number%4) == 0:
if(number%100) == 0:
if (number%400) == 0:
print("That year is leap year")
else:
print("That year is NOT a leap year")
else:
print("That year is a leap year")
else :
print("That year is NOT a leap year")
| true |
f08bea0f0e3a195aca5285b644bb479c3bbcff3b | olpsm/sandbox | /mit/bisection_cube_root.py | 750 | 4.25 | 4 | ####################
## EXAMPLE: bisection cube root (only positive cubes!)
####################
cube = 27
cube = 8120601
## won't work with x < 1 because initial upper bound is less than ans
##cube = 0.25
epsilon = 0.01
num_guesses = 0
low = 0
high = cube
guess = (high + low)/2.0
while abs(guess**3 - cube) >= epsilon:
print(guess, guess**3, abs(guess**3 - cube))
if guess**3 < cube:
# look only in upper half search space
low = guess
else:
# look only in lower half search space
high = guess
# next guess is halfway in search space
guess = (high + low)/2.0
num_guesses += 1
print('num_guesses =', num_guesses)
print(guess, 'is close to the cube root of', cube)
print('the cube of guess is', guess**3)
| true |
35cc663d9caa82a3cabc6d97a1b3837dfb43c231 | mannuelf/python | /src/00_fundamentals/decorators.py | 998 | 4.65625 | 5 | # A decorator is a function that gets called before another function
import functools
def my_decorators(func):
@functools.wraps(func)
def function_that_runs_fun():
print("Im the decorator")
func()
print("After the decorator")
return function_that_runs_fun
@my_decorators
def my_function():
print("I'm the function!")
my_function()
##
def decorator_with_arguments(number):
def my_decorator(func):
@functools.wraps(func)
def function_that_runs_func(*args, **kwargs):
if number == 55:
print("In the decorator ======")
else:
func(*args, *kwargs)
print("=======After the decorator!")
return function_that_runs_func
return my_decorator
# Decorators can accept arguments, many arguments, so always pass in *arg and *kwargs
@decorator_with_arguments(55)
def my_function_too(x, y):
print("hello from function_too")
print(x + y)
my_function_too(77, 89) | true |
76c2cc142437eca0eb2db2c54947a2f2484647ec | rosworld07/pythonprograms | /python programs/progrm31_menu driven program for arithmetic operation .py | 767 | 4.40625 | 4 | #menu driven program for arithmetic operation using +,-,/,*
print("press + for add")
print("press - for sub")
print("press * for mul")
print("press / for div")
ch=input("enter your choice")
if ch=="+":
num1=int(input("enter num1"))
num2=int(input("enter num2"))
res=num1+num2
print("addition ="+str(res))
elif ch=="-" :
num1=int(input("enter num1"))
num2=int(input("enter num2"))
res=num1-num2
print("sub ="+str(res))
elif ch=="*":
num1=int(input("enter num1"))
num2=int(input("enter num2"))
res=num1*num2
print("mul ="+str(res))
elif ch=="/" :
num1=int(input("enter num1"))
num2=int(input("enter num2"))
res=num1/num2
print("div ="+str(res))
else :
print("not valid choice")
| false |
93828e9a4f279154939188ae7c61105905b79bd2 | rosworld07/pythonprograms | /python programs/progrm26_age of 3 person find greatest one.py | 323 | 4.15625 | 4 | #enter the age of 3 person find greatest one
p1=int(input("enter the age of person 1"))
p2=int(input("enter the age of person 2"))
p3=int(input("enter the age of person 3"))
if p1>p2 and p1>p3:
print("p1 is greater")
elif p2>p1 and p2>p3 :
print("p2 is greater ")
else :
print("p3 is greater")
| false |
543b7374b33777cf5dec9d2df542a77481deafc9 | steven-cruz/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 442 | 4.375 | 4 | #!/usr/bin/python3
'''
0-add_integer function
function that adds two integers
'''
def add_integer(a, b=98):
''' funtion that sum two integer ckeck if a/b are int or float '''
if type(a) is int or type(a) is float:
if type(b) is int or type(b) is float:
return int(a) + int(b)
else:
raise TypeError("b must be an integer")
else:
raise TypeError("a must be an integer")
| true |
d2e44ea65841864ef75cd5e39048cf47e5c5b3fb | govindgurjar/python-lab | /replace_ds_to_ss.py | 270 | 4.15625 | 4 | # Q. Replace double spaces with single spaces in previous program
string = input("Enter String: ")
while ' ' in string:
string = string.replace(' ', ' ')
print("changed string = " + string)
# Output: Enter String: Rohit Jain
# changed string = Rohit Jain
| true |
abf26e82e5eeaa97d6461e9bbd5118b93f1a33c3 | malfridur18/python | /dice.py | 696 | 4.34375 | 4 | d1 = int(input("Input first dice: ")) # Do not change this line
d2 = int(input("Input second dice: ")) # Do not change this line
if d1>=1 and d1<=6 and d2>=1 and d2<=6:
if d1+d2==7 or d1+d2==11:
print('Winner')
elif d1+d2==1 or d1+d2==3 or d1+d2==12:
print('Loser')
else:
print(d1+d2)
else:
print('Invalid input')
# Fill in the missing code below
#Accept d1 and d2, the number on two dices as input.
#First, check to see that they are in the proper range for dice (1-6).
#If not, print the message "Invalid input". Otherwise, determine the sum.
#If the sum is 7 or 11, print "Winner".
#If the sum is 2, 3 or 12, print "Loser". Otherwise print the sum.
| true |
d356bb588bb7a6c0bbaec413588481ad79b5913d | lucasgoncalvess/SEII-LucasGoncalveseSilva | /Semana 2/prog03.py | 786 | 4.59375 | 5 | #Python Tutorial for Beginners 3: Integers and Floats - Working with Numeric Data
# Arithmetic Operators:
# Addition: 3 + 2
# Subtraction: 3 - 2
# Multiplication: 3 * 2
# Division: 3 / 2
# Floor Division: 3 // 2 sem resto
# Exponent: 3 ** 2
# Modulus: 3 % 2
# Comparisons:
# Equal: 3 == 2
# Not Equal: 3 != 2
# Greater Than: 3 > 2
# Less Than: 3 < 2
# Greater or Equal: 3 >= 2
# Less or Equal: 3 <= 2
num = 3.14
print(num)
print(type(num)) #mostra classe do numero
print(round(num)) #arredonda o numero
#verificar condições
num1 = 3
num2 = 2
print(num1 != num2)
#converter str em numero
num_1 = '100'
num_2 = '200'
num_1 = int(num_1)
num_2 = int(num_2)
print(num_1 + num_2) | false |
edacb91b734fb206e226f420ae52ae7b648cc3d5 | Matildenesheim/First-Tasks-for-NLP | /Testmedkenneth.py | 791 | 4.1875 | 4 |
# make a string
string = 'this is a string'
a_list_of_strings = string.split(" ")
a_list_of_strings[0]
a_list_of_strings[2]
#create function
def print_hello():
print('hello world')
print_hello()
#rename function + combine function
new_name = print_hello
new_name()
#new function, adding hello after each string
def add_hello_to_string(string):
return string + "hello"
add_hello_to_string("test")
# Task 1 - Creat string which uses addition
"westworld" + " " + "rocks"
# Task 2 - Multiplication
("westworld" + " " + "rocks"+ " ") * 10
# Task 3 - use at least one object method
'hej'.capitalize()
# Task 4 - def a function taking two numbers, printing both the sum and the calculation
def calculator(x,y):
answer = x + y
print(f"{x}+{y}+{answer}")
calculator(2,5) | true |
89b181c8a28062f976fd6fef2c06a436512e067d | hejiali-hub/test | /app.py | 997 | 4.21875 | 4 | # has_good_credit = True
# has_crimnal_record = True
#
# if has_good_credit and not has_crimnal_record:
# print("Eligible for loan")
#
#
# temperature = 30
#
# if temperature != 30:
# print ("It's a hot day")
# else:
# print ("It's not a hot day")
#
# name = 'yu'
#
# if len(name) < 3:
# print("name must be at least 3 characters")
# elif len(name) > 50:
# print("name can be maximum of 50 characters")
# else:
# print('name looks good')
# weight = int(input('Weight: '))
# unit= input ('(L)bs or (K)g: ')
# if unit.upper() == "L":
# converted = weight * 0.45
# print(f'You are {converted} kilos')
# else:
# converted = weight / 0.45
# print(f'You are {converted} pounds')
# i = 1
# while i <=5:
# print('*' * i)
# i = i + 1
# print("Done")
name = input('Write your name: ')
if len(name) < 3:
print("name must be at least 3 characters")
elif len(name) > 50:
print("name can be maximum of 50 characters")
else:
print('name looks good') | true |
b44e560b0aa835629f50bf1586f7c2eba4c43d11 | RachelCooperPSU/AWC_GWC_Week5 | /bear_attack_demo/multi_guess_function.py | 2,212 | 4.25 | 4 | #======================================================================
#iteration_intro.py
#This program gives a motivating example for using loops and functions
#======================================================================
#IMPORT DEPENDENCIES
#====================
#Import sys for ARGV functionality
import sys
from random import randint
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import time
def output_correct(correct_meme):
print("You guessed correctly!")
print("Congratulations! You get a bear meme! ")
time.sleep(1)
output_image = mpimg.imread(correct_meme)
return output_image
def output_incorrect(incorrect_meme):
print("That was not correct!")
print("Unfortunately I must send the bear-o-dactyl. ")
time.sleep(1)
output_image = mpimg.imread(incorrect_meme)
return output_image
def main(args):
# Step 1: Generate a random integer number from 1 to 5
random_num = randint(1,5)
input_num_guesses = int(input("How many guesses would you like? "))
correct_guess = False
num_guess = 0
while((not correct_guess) and (num_guess < input_num_guesses)):
# Step 2: Have the user guess the number
user_guess = int(input("Guess my number: "))
num_guess = num_guess + 1
# Step 3: Check if the numbers match
if(user_guess == random_num):
correct_guess = True
print("The number was: " + str(random_num) + "\n")
# Step 3: Check if the user guessed correctly and give feedback
if(correct_guess == True):
meme = "bear_meme_" + str(random_num) + ".png"
output_image = output_correct(meme)
else:
meme = "bear_o_dactyl.png"
output_image = output_incorrect(meme)
imgplot = plt.imshow(output_image)
plt.show()
#=======================================================================
#Execute main with the specified parameters
if __name__ == "__main__":
main(sys.argv[1:])
| true |
c29dd4e5c3483a5c7ea0bd9ead7c3910de88b642 | barbaralois/cs-module-project-iterative-sorting | /src/searching/searching.py | 1,169 | 4.25 | 4 | def linear_search(arr, target):
# progress through the array item by item
for i in range(len(arr)):
# check if that item is the target
if arr[i] == target:
# if it is, return i. Otherwise it keeps going through the loop
return i
return -1 # if you get to the end and it isn't there: not found
# Write an iterative implementation of Binary Search
def binary_search(arr, target):
# set variables for the smallest and largest unchecked values
min = 0
max = len(arr)-1
while min <= max:
# find the difference of the min and max positions
mid = (min + max) // 2
# guess the item right in the middle
guess = arr[mid]
if guess == target:
# if that's the target, return it
return mid
elif target > guess:
# if that's smaller than the target, set the min to one higher than the checked num
min = mid + 1
else:
# if that's larger than the target, set the max to one lower than the checked num
max = mid - 1
return -1 # if you get to the end and it isn't there: not found
| true |
c0450c461f75eea2423c997f40034fcc19bcce1e | 15ec016/python-programming | /22.py | 798 | 4.28125 | 4 | # Python 3 implementation to find
# the number closest to n
# Function to find the number closest
# to n and divisible by m
def closestNumber(n, m) :
# Find the quotient
q = n // m
# 1st possible closest number
n1 = m * q
# 2nd possible closest number
if((n * m) > 0) :
n2 = (m * (q + 1))
else :
n2 = (m * (q - 1))
# if true, then n1 is the required closest number
if (abs(n - n1) < abs(n - n2)) :
return n1
# else n2 is the required closest number
return n2
# Driver program to test above
n = 13; m = 4
print(closestNum(n, m))
n = -15; m = 6
print(closestNum(n, m))
n = 0; m = 8
print(closestNum(n, m))
n = 18; m = -7
print(closestNum(n, m))
# This code is contributed by Nikita tiwari.
| false |
0f7d0575ea62ede6e65fb8a1479c7ef02384c456 | laippmiles/Leetcode | /!155_最小栈_180615.py | 1,943 | 4.34375 | 4 | '''
设计一个支持 push,pop,top 操作,
并能在常数时间内检索到最小元素的栈。
1.push(x) -- 将元素 x 推入栈中。
2.pop() -- 删除栈顶的元素。
3.top() -- 获取栈顶元素。
4.getMin() -- 检索栈中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
'''
#参考:
#https://www.cnblogs.com/baiyb/p/8443337.html
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.minnumlist = []
#用最小栈的方法找最小值
self.minnum = None
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.stack.append(x)
if len(self.stack) == 1:
self.minnumlist.append(x)
self.minnum = x
#最小栈是一个降序数组
if x <= self.minnumlist[-1]:
self.minnumlist.append(x)
self.minnum = x
def pop(self):
"""
:rtype: void
"""
if self.stack[-1] == self.minnumlist[-1]:
self.minnumlist.pop()
if len(self.minnumlist) == 0:
self.minnum = None
else:
self.minnum = self.minnumlist[-1]
#删除栈顶的元素时要考虑栈顶元素可能和最小栈相关
self.stack.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.minnum
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin() | false |
ce99bd04b86550d2e9485883542de1320ac3a623 | bernardo-zuchowski/coursera-py-usp | /list5ex (2).py | 404 | 4.125 | 4 | l = int(input("Digite a largura: "))
a = int(input("Digite a altura: "))
aux_l = l
aux_a = a
while aux_a > 0:
while aux_l > 0:
if aux_a == a or aux_a == 1:
print("#", end="")
else:
if aux_l == l or aux_l == 1:
print("#", end="")
else:
print(" ", end="")
aux_l -= 1
print('')
aux_l = l
aux_a -= 1 | false |
8582d494794e2fbb419eeb2ce65b4700dda4b03c | antonycbueno/Github-Python | /Udemy - Python Para Todos/positivo_negativo.py | 203 | 4.21875 | 4 | numero = float(input('Informe um número com decimais: '))
if numero < 0:
print('O número é negativo!')
elif numero > 0:
print('O número é positivo!')
else:
print('Você informou zero.') | false |
9390cbd09678cce6aafde0cc0f7e55bdf3752f5c | TheCyberian/Data-Structures | /1. Stack/balance-parenthesis.py | 1,358 | 4.40625 | 4 | """
Use a stack to check whether or not a string has
balanced usage of parenthesis.
Examples:
(), ()(), (({{[]}})) <- balanced
((), {{{}}], [][]]] <- unbalanced
Use cases:
balanced -> [{()}]
unbalanced -> (()
unbalanced -> ))
"""
from stack import Stack
def is_match(p1, p2):
if p1 == "(" and p2 == ")":
return True
elif p1 == "{" and p2 == "}":
return True
elif p1 == "[" and p2 == "]":
return True
else:
return False
def is_parenthesis_balanced(parenthesis_string):
s = Stack()
is_balanced = True
index = 0
while index < len(parenthesis_string) and is_balanced:
parenthesis = parenthesis_string[index]
if parenthesis in "{([":
s.push(parenthesis)
else:
if s.is_empty():
is_balanced = False
else:
top = s.pop()
if not is_match(top, parenthesis):
is_balanced = False
index += 1
if s.is_empty() and is_balanced:
return True
else:
return False
#Used Test Cases
print(is_parenthesis_balanced("(({{[]}}))"))
print(is_parenthesis_balanced("({[]}})"))
print(is_parenthesis_balanced("(({{[}}))"))
print(is_parenthesis_balanced("(({{}}))"))
print(is_parenthesis_balanced("(({{[]}})"))
print(is_parenthesis_balanced("))"))
| true |
951d912a9a51c0d571b622d51e477fb64d3aa764 | mrtousif/Algorithms_using_python | /queueLL.py | 1,298 | 4.125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class Queue:
def __init__(self):
self.first = None
self.last = self.first
self.length = 0
def enqueue(self, value):
""" Add a node at the end """
newNode = Node(value)
if self.first is None:
self.first = newNode
else:
self.last.next = newNode
self.last = newNode
self.length += 1
def dequeue(self):
"""Delete first node at the end"""
if self.first is None:
return None
deleteNode = self.first
self.first = deleteNode.next
self.length -= 1
return deleteNode
def peek(self):
return self.first.value
def printList(self):
presentNode = self.first
array = []
while presentNode:
array.append(presentNode.value)
presentNode = presentNode.next
return array
if __name__ == '__main__':
myQueue = Queue()
myQueue.enqueue(69)
myQueue.enqueue(37)
# print(myQueue.dequeue())
# print(myQueue.dequeue())
# print(myQueue.dequeue())
# print(myQueue.dequeue())
# myQueue.enqueue(45)
# myQueue.enqueue(44)
| true |
065a5a8dfcdda672029881182ca94b4e63c6621d | Likh-Alex/PostgreSQL-Python | /registration_app.py | 2,402 | 4.25 | 4 | student_list = []
def create_student():
#Ask user for the student name and marks
student_name = input("Enter your name: ")
# create a dict in the format {'name':student_name, 'marks': []}
student = {'name':student_name,
'marks': []}
# return the dictionary
return student
def add_marks(student, mark):
#add a mark to the student dictionary
student["marks"].append(mark)
def calc_avg_mark(student):
#check len of students marks
number = len(student['marks'])
if number == 0:
return 0
#calculate the average
total = sum(student['marks'])
return total/number
def student_details(student):
#print out the string that tells the user the info abouth the student
print(f"The name of the student is {student['name']}, scores are {student['marks']}"
f" and the average mark is {calc_avg_mark(student)}")
def print_all_students(students):
# print out the string that tells the user the info abouth the student for every student in the list
for i, student in enumerate(students):
print(f"ID : {i}")
print(student_details(student))
def menu():
#add a student to a student list
#add a mark to a student
#Print a list of students
#Exit the application
selection = input("Enter 'p' to print the list of all students,"
" 's' to add a new student,"
" 'm' to add marks for the student,"
" 'q' to exit"
"\nEnter your selection: ...")
while selection != 'q':
if selection == 'p':
print_all_students(student_list)
print("No students in the list")
elif selection == 's':
student_list.append(create_student())
elif selection == 'm':
student_id = int(input("Enter the student ID to a mark to: "))
student = student_list[student_id]
new_mark = int(input("Enter a new mark to be added: "))
add_marks(student, new_mark)
selection = input("Enter 'p' to print the list of all students,"
" 's' to add a new student,"
" 'm' to add marks for the student,"
" 'q' to exit"
"\nEnter your selection: ...")
menu() | true |
0b35680aa3b5cdeb4fdff6fd7905817c4d2bf980 | lbain/cs101 | /Lesson_4_Problem_Set_(Optional)/01-Word_Count/solutions.py | 726 | 4.28125 | 4 | # Please write SOLUTIONS here
# From the README:
# We do NOT accept pull requests that have deleted another contributer's hint or solution without a very clear reason
# ALL solutions must be clearly documented
# ALL solutions must actually work
# ONLY use concepts covered in the class so far
def count_words(str):
if str=="" or str==" ": # Account for the case where there are no words in the string
return 0
else:
count=1 #If the string isn't empty, or just a space, then there will be at least one word, so start count at 1
for i in str:
# Go through the string, and every time you find a space, add to count.
if i ==" ":
count+=1
return count
| true |
bcdf411a8de2ef4befac81fb1287573221ab9718 | Vimbai1985/my-first-blog | /python_intro.py | 704 | 4.40625 | 4 | if 3>2:
print('It works!')
if 5<2:
print('5 is indeed greater than 2')
else:
print('5 is not greater than 2')
name = 'bev'
if name =='vimbai':
print('Hey vimbai!')
elif name =='viviene':
print('Hey viviene!')
else:
print('Hey anonymous!')
volume = 157
if volume< 20:
print("Its kinda quiet.")
elif 20<= volume < 40:
print("Its nice for background music")
elif 40<= volume < 60:
print("Perfect, I can hear all the details")
elif 60<= volume < 80:
print("Nice for parties")
elif 80<= volume <100:
print("A bit loud")
else:
print("My ears are hurting! :(")
if volume < 20 or volume > 80:
volume = 50
print("That's better!")
| true |
afb1b54ac6a508ef034f2ee06de26af1276e7201 | boston3394/Python-the-hard-way | /ex38.py | 1,708 | 4.125 | 4 | ten_things = "Apples Oranges Crows Telephone Light Sugar"
print "Wait, there's not 10 things in that list, let's fix that."
stuff = ten_things.split(' ')
more_stuff = ["day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10: ##len is number of items in a list
next_one = more_stuff.pop()
#list.pop([i])Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
print "Adding: ", next_one
stuff.append(next_one) #takes it from the bottom of the list
print "There's %d items now." % len(stuff)
print "There we go: ", stuff
print "Let's do some things with stuff."
print stuff[1]
print stuff[-1] #whoa! fancy
print stuff.pop()
print ' '.join(stuff) #what? cool. joins items with '' between them. aha!
print '#'.join(stuff[3:5]) #very cool joins item 3 and four on the list. does NOT have item 5.
#Objects are an encapsulation of variables and functions into a single entity. Objects get their variables and functions from classes. Classes are essentially a template to create your objects.What is a class? Think of a class as a blueprint. It isn't something in itself, it simply describes how to make something. You can create lots of objects from that blueprint - known technically as an instance.
#A: dir(something) gives you all the attributes of the object. The class is like the blueprint for the house.
| true |
67b8b9de05cca3a26a7ca560630a81af8150a8ef | KaterinaMutafova/SoftUni | /Programming Basics with Python/Advanced_conditional_statements/Cond_advanced_lab_ex3_animal_type.py | 347 | 4.15625 | 4 | animal = input()
type_of_animal = "Any_animal"
if animal == "dog":
type_of_animal = "mammal"
elif animal == "crocodile":
type_of_animal = "reptile"
elif animal == "tortoise":
type_of_animal = "reptile"
elif animal == "snake":
type_of_animal = "reptile"
else:
type_of_animal = "unknown"
print(type_of_animal)
| false |
8351b9fd62544303d7960adbd8aa3fb9b484c224 | Gisellechen0115/functions | /function_modules.py | 2,041 | 4.4375 | 4 | #argument論點 range(2,10,3) 裡面有三個arguments
#parentheses表示()括號
#DRY principle makes code easier to maintain
#WET principle makes code bad and repetitive
#defthat you can create ur own functions
def my_func():
print('spam')
print('egg')
print('morning')
my_func()
#
def hello():
print("hi")
hello()
#argument is defined inside the()
def AA(WORD):
print(WORD+"!")
AA("SPAM")
AA("EGG")
#define function with more than one arguments, separate with commas
def AA(x,y):
print(x + y)
print(x - y)
AA(5,8)
#parameten參數
#define a function that prints "Yes", if its parameter is an even number, and "No" otherwise.
def even(x):
if x % 2 == 0:
print("Yes")
else:
print("No")
even(80)
#returning from funtion, such as int or str, return a value that can be used later
def max(x, y):
if x >= y:
return x
else:
return y
print(max(4, 7))
z = max(8, 5)
print(z)
#int 沒有長度,只有str可以
def shortest_str(x, y):
if len(x) <= len(y):
return(x)
else:
return(y)
print(shortest_str("1","2"))
"""once you return a value from a function, it immediately stops being excuted.
Any code after the return statement will never happen."""
def add_number(x, y):
total = x + y
return total
print("this won't be print")
print(add_number(4,5))
#defined function can be assined and reassigned to variables
def multiply(x, y):
return x* y
a=4
b=7
opperation=multiply
print(opperation(a,b))
'''
opperation=multiply(4, 7)
print(opperation)
'''
#function can also be used as arguments of other functions
def add(x, y):
return x + y
def do_twice(func, x, y):
return func(func(x, y),func(x, y)) #return
a=5
b=10
print(do_twice(add,a,b))
#一樣得到相同的結果 plus可以用其他代稱
def add(x, y):
return x + y
def do_twice(plus, x, y):
return plus(plus(x, y),plus(x,y))
a=5
b=10
print(do_twice(add, a, b))
#
def square(x):
return x* x
def test(func,x):
test(square,42)
| true |
c35b440fea35abbcd180598c3e4cf3254c44ae40 | oscar503sv/basicos_python | /strings/formatos.py | 719 | 4.375 | 4 | texto = "curso de Python 3, Python básico"
resultado = texto.capitalize()
print(resultado)
resultado = texto.swapcase()
print(resultado)
resultado = texto.upper()
print(resultado)
resultado = texto.lower()
print(resultado)
print(resultado.isupper())
print(resultado.islower())
resultado = texto.title()
print(resultado)
#Remplaza parte del texto por otro con el numero
#Se le indica el número de veces que lo debe reemplazar
#Por si el texto está más de una vez en el string.
resultado = texto.replace("Python","Ruby",1)
print(resultado)
#El metodo strip le quita los espacios al inicio y final al string
texto_dos = " curso de Python 3, Python básico "
resultado = texto.strip()
print(resultado)
| false |
91899af168261e7a7cfe8394fc4d6984b86b7c16 | Jaspreetkumar1999/python-series | /001integer and floats.py | 795 | 4.40625 | 4 | # num =3.5
# print(type(num)) to see type of num
# print(3**2) to exponent powers try also some other basics +-/ // %
num = -1
# # num = num+1
# num +=1 to increment
# print(abs(num)) it will print absolute value means it will remove negative sign
# print(round(4.34)) to round of near by integer value
# for = 3
# print(for) varible name should be beyound the inbuilt func
# print(round(4.34,1)) passing position upto we want round off
# # print(3==2)
# # print(3!=2)
# # print(3>2) these all will return output in the form of boolean values
# # print(3<2)
# # print(3>=2)
# print(3<=2)
num_1 = '100'
num_2='200'
# print(num_1+num_2) it will show only concatenation of strings
num_1 = int('100')
num_2= int('200')
# print(num_1+num_2) it will show arithmatic output
| true |
a33de89dcccc25a6cc1ac98eb55f4069a0386faf | nscspc/NetworkSecurity_Bootcamp_Project | /hashing with iteration.py | 824 | 4.1875 | 4 | import hashlib
string=input("enter string that you want to encrypt : ")
print("choose the algorithm in which you want to encrypt the string : \n(1). md5\n(2). sha1\n(3). sha512")
algo=int(input("enter you choice here : "))
s=string.encode()# string should be encoded before hashing
hashed=s
if(algo==1):
for i in range(10):
s=hashlib.md5(s).hexdigest()
s=s.encode()
print("10 times hashed form of",string,"in md5 is :",s)
elif(algo==2):
for i in range(10):
s=hashlib.sha1(s).hexdigest()
s=s.encode()
print("10 times hashed form of",string,"in sha1 is :",s)
elif(algo==3):
for i in range(10):
s=hashlib.sha512(s).hexdigest()
s=s.encode()
print("10 times hashed form of",string,"in sha512 is :",s)
else:
print("wrong input")
| true |
d2839f7124c77a98b793be6e0f0cf8266eacf51d | tinkalpatel09/Python-Classrooms | /Assignment2/isVowel.py | 1,092 | 4.125 | 4 | #! usr/bin/env/python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 15 12:50 2019
@author: Michelle M Khalife
"""
def isVowel(c):
return c.lower() in ('aeiouy') # Change c into lower case and check if in set of vowels
# Driver Code
validInput = False
while (validInput == False):
arg = str(input("Enter a letter to check its type: "))
validInput = len(arg)==1 and (65<=ord(arg)<=90 or 97<=ord(arg)<=122)
if (isVowel(arg) == True):
print(arg + " is a vowel\n")
else:
print(arg + " is a consonant\n")
# There are other valid ways to check whether or not the character is a vowel, some better than others
# isVowel_Basic = (c=="a" or c=="e" or c=="i" or c=="o" or c=="u" or c=='y'\ # Rudimentary
# c=="A" or c=="E" or c=="I" or c=="O" or c=="U" or c=='Y') # Call lower() to avoid redundant check
# isVowel_WithList = c.lower() in ['a', 'e', 'i', 'o', 'u', 'y'] # List is better
# isVowel_WithSet = c.lower() in (['a', 'e', 'i', 'o', 'u', 'y']) # Set created from list
| true |
38e5b58709297d9da27b8126d2fccbe64d6928c8 | meesont/RGSW | /Python/Intermediate Python Stuff/Intermediate python stuff 3.py | 977 | 4.21875 | 4 | #Generators vs comprehension
'''
Generators use much less memory than comprehension however is slower
Generators create the values on the fly (range() is a generator expression)
List comprehension processes the entire list at once and stores it in memory, therefore
functioning quicker however using more memory
'''
import functools, time
#Timing decorator (online code)
def timing(func):
@functools.wraps(func)
def newfunc(*args, **kwargs):
startTime = time.time()
func(*args, **kwargs)
elapsedTime = time.time() - startTime
print('[{}] finished in {} ms'.format(
func.__name__, int(elapsedTime * 1000)))
return newfunc
#This is a generator expression
@timing #timing decorator
def generator():
xyz = (i for i in range(500000))
print(list(xyz)[:5])
@timing
def comprehension():
abc = [i for i in range(500000)]
print(abc[:5])
if __name__ == '__main__':
generator()
comprehension() | true |
ce8b39daff8179e952032f1909b169f1fd1ad8b8 | girishjakkam/python-repo | /prie.py | 389 | 4.125 | 4 | def is_prime(x):
a=1
b=0
while a>=1 and a<=9:
if x%a==0 and x>0:
a=a+1
b=b+1
print a
if b<=2:
print b
print "prime number"
return True
else:
print "not a prime number"
return False
x=raw_input("enter a number:")
is_prime(x)
| true |
7975e2aa6dcb156fb5a7d2bb0f0e78376b52893c | shinobu1023/1082_PCCU_CSIE_ObjectOrientedProgramming | /期末考/Q5.py | 2,668 | 4.5625 | 5 | '''==========================================
第五題-Python Student Inheritance
=========================================='''
''' 本題重點:Python物件繼承 '''
# Date 類別
class Date():
# 建構子
def __init__(self, newYear, newMonth, newDay):
self.__year = newYear
self.__month = newMonth
self.__day = newDay
# 設定年
def setYear(self, newYear):
self.__year = newYear
# 設定月
def setMonth(self, newMonth):
self.__month = newMonth
# 設定日
def setDay(self, newDay):
self.__day = newDay
# 取得年
def getYear(self):
return self.__year
# 取得月
def getMonth(self):
return self.__month
# 取得日
def getDay(self):
return self.__day
# 輸出
def toString(self):
print(str(self.getYear()) + "-" + str(self.getMonth()) + "-" + str(self.getDay()), end=' ')
# Person 類別
class Person():
# 建構子
def __init__(self, newName, newBirthday):
self.__name = newName
self.__birthday = newBirthday
# 設定名字
def setName(self, newName):
self.__name = newName
# 設定生日
def setBirthday(self, newBirthday):
self.__birthday = newBirthday
# 取得名字
def getName(self):
return self.__name
# 取得生日
def getBirthday(self):
return self.__birthday
# 輸出
def toString(self):
print(self.getName(), end=' ')
self.getBirthday().toString()
# Student 類別 (繼承 Person)
class Student(Person):
# 建構子
def __init__(self, newName, newMathScore, newChineseScore, newBirthday):
self.__mathScore = newMathScore
self.__chineseScore = newChineseScore
super().__init__(newName, newBirthday)
# 設定數學成績
def setMathScore(self, newMathScore):
self.__mathScore = newMathScore
# 設定國文成績
def setChineseScore(self, newChineseScore):
self.__chineseScore = newChineseScore
# 取得數學成績
def getMathScore(self):
return self.__mathScore
# 取得國文成績
def getChineseScore(self):
return self.__chineseScore
# 計算平均成績
def average(self):
return (self.__mathScore + self.__chineseScore) / 2
# 輸出
def toString(self):
super().toString()
print(self.average())
# 主程式
if __name__ == "__main__":
# 根據題目宣告兩個 Student 物件
s1 = Student("Candy", 70, 100, Date(1999, 6, 1))
s2 = Student("Spotlight", 89, 60, Date(1997, 10, 8))
# 分別輸出
s1.toString()
s2.toString() | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.