blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
991d140f7e4100ae35f740c3b97f1ed62de4e7f9
|
Krishnaarunangsu/LoggingDemonstration
|
/python_slice_1.py
| 1,427
| 4.5
| 4
|
# The slice() constructor creates a slice object representing the set of indices specified by range(start, stop, step).
# The slice object is used to slice a given sequence (string, bytes, tuple, list or range) or any object which supports sequence protocol (implements __getitem__() and __len__() method).
# Slice object represents the indices specified by range(start, stop, step).
# The syntax of slice() are:
# slice(stop)
# slice(start, stop, step)
# slice() Parameters
# slice() mainly takes three parameters which have the same meaning in both constructs:
# start - starting integer where the slicing of the object starts
# stop - integer until which the slicing takes place. The slicing stops at index stop - 1.
# step - integer value which determines the increment between each index for slicing
# If a single parameter is passed, start and step are set to None.
print(slice(3))
print(slice(1, 5, 2))
# Get substring from a given string using slice object
py_string: str = 'Python'
# Contains indices(0, 1, 1, 2)
# i.e. that is P, y, t
index_1=slice(3)
print(py_string[index_1])
# contains indices (1, 3)
# i.e. y and h
index_2 = slice(1, 5, 2)
print(py_string[index_2])
index_3 = slice(2)
print(py_string[index_3])
# contains indices (-1, -2, -3)
# i.e. n, o and h
index_4 = slice(-1, -4, -1)
print(index_4)
print(py_string[index_4])
# https://www.programiz.com/python-programming/methods/built-in/slice
| true
|
92fcb82ffdcd43241e2d84afeb5ca1dcb6d65d23
|
wangluobing/wa101
|
/day02/linklist.py
| 2,690
| 4.15625
| 4
|
"""
linklist.py
功能: 实现单链表的构建和功能操作
重点代码
"""
# 创建节点类
class Node:
"""
思路: 将自定义的类视为节点的生成类,实例对象中
包含数据部分和指向下一个节点的next
"""
def __init__(self, val, next=None):
self.val = val # 有用数据
self.next = next # 循环下一个节点关系
# 做链表操作
class LinkList:
"""
思路: 单链表类,生成对象可以进行增删改查操作
具体操作通过调用具体方法完成
"""
def __init__(self):
"""
初始化链表,标记一个链表的开端,以便于获取后续
的节点
"""
self.head = Node(None)
# 通过list_为链表添加一组节点
def init_list(self, list_):
p = self.head # p 作为移动变量
for item in list_:
p.next = Node(item)
p = p.next
# 遍历链表
def show(self):
p = self.head.next # 第一个有效节点
while p is not None:
print(p.val)
p = p.next # p向后移动
# 判断链表为空
def is_empty(self):
if self.head.next is None:
return True
else:
return False
# 清空链表
def clear(self):
self.head.next = None
# 尾部插入
def append(self, val):
p = self.head
while p.next is not None:
p = p.next
p.next = Node(val)
# 头部插入
def head_insert(self, val):
node = Node(val)
node.next = self.head.next
self.head.next = node
# 指定插入位置
def insert(self, index, val):
p = self.head
for i in range(index):
# 超出位置最大范围结束循环
if p.next is None:
break
p = p.next
node = Node(val)
node.next = p.next
p.next = node
# 删除节点
def delete(self, x):
p = self.head
# 结束循环必然两个条件其一为假
while p.next and p.next.val != x:
p = p.next
if p.next is None:
raise ValueError("x not in linklist")
else:
p.next = p.next.next
# 获取某个节点值,传入节点位置获取节点值
def get_index(self,index):
if index < 0:
raise IndexError("index out of range")
p = self.head.next
for i in range(index):
if p.next is None:
raise IndexError("index out of range")
p = p.next
return p.val
| false
|
f718803b224aff52828ca1c194f63fdb8706e64f
|
yashshah4/python-2
|
/ex6.py
| 725
| 4.375
| 4
|
#creating a string x with formatting method %d
x = "There are %d types of people." % 10
#creating further strings
binary = "binary"
do_not = "don't"
#creating a second string with string formatting method
y = "Those who know %s and those who %s" %(binary, do_not)
#printing the first two strings
print x
print y
#using two printing methods below to highlight the difference between %r & %s
print "I said %r." %x
print "I also said : `%s`." % y
#further highlighting the usage of %r
hilarious = False
joke_evaluation = "Isnt't that joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side"
#concatenating two strings using '+'
print w + e
| true
|
8f3477536c169937d8052f3d97e730546aa33420
|
brgermano/estudo_python
|
/listas/dicionario3.py
| 975
| 4.25
| 4
|
#criando um dicionario com dados
dicionario = {"Yoda":"Mestre Jedi", "Mace Windu": "Mestre Jedi", "Anakin Skywalker":"Cavaleiro Jedi", "R2-D2":"Dróide", "Dex":"Balconista"}
#exibindo o dicionário completo
for chave, valor in dicionario.items():
print("O personagem {} é da categoria {}".format(chave, valor))
#removendo o item cuja chave é R2-D2
dicionario.pop("R2-D2")
print("===============================")
#exibindo o dicionário completo após a remoção
for chave, valor in dicionario.items():
print("O personagem {} é da categoria {}".format(chave, valor))
#removendo ultimo item
print("=================================")
dicionario.popitem()
for chave, valor in dicionario.items():
print("O personagem {} é da categoria {}".format(chave, valor))
print("====================== aqui")
#apagando tudo do dicionario
dicionario.clear()
for chave, valor in dicionario.items():
print("O personagem {} é da categoria {}".format(chave, valor))
| false
|
566e03d3a6aafdc31f2427f1d04633cdeca96682
|
brgermano/estudo_python
|
/listas/tupla.py
| 363
| 4.1875
| 4
|
categorias = ("youngling", "padawan", "knight", "master")
print(categorias)
print(categorias[0]) # youngling
print(categorias[1]) # padawan
#usando um indice negativo para exibir o ultimo item da tupla
print(categorias[-1]) # master
# Exibindo cada item da tupla usando um loop
print("======= LOOP ========")
for categoria in categorias:
print(categoria)
| false
|
07cf522b16d5d13d48a8a8422ea10b84a60c81b4
|
Gladarfin/Practice-Python
|
/turtle-tasks-master/turtle_11.py
| 319
| 4.1875
| 4
|
import turtle
turtle.shape('turtle')
turtle.speed(100)
def draw_circle(direction, step):
angle=2*direction
for i in range(180):
turtle.forward(step)
turtle.left(angle)
step=2.0
turtle.left(90)
for i in range(0, 10, 1):
draw_circle(1, step)
draw_circle(-1, step)
step+=0.3
| true
|
e0b4849d6bea59c51b50017d00ba93b5defb7963
|
johnmarkdaniels/python_practice
|
/odd_even.py
| 272
| 4.125
| 4
|
num = int(input('Please input a number: '))
if num % 2 == 0:
print(f'Your number ({str(num)}) is an even number.')
if num % 4 == 0:
print('Incidentally, your number is evenly divisible by 4.')
else:
print(f'Your number ({str(num)}) is an odd number.')
| true
|
aebf2c565ac04e903da16fe7c96d812824c21d60
|
HenriqueEichstadt/MeusCursos
|
/Python/PythonFundamentos/Cap03/DSA-Python-Cap03-05-Metodos.py
| 482
| 4.15625
| 4
|
# # Métodos
# Criando uma lista
lst = [100, -2, 12, 65, 0]
# Usando um método do objeto lista
lst.append(10)
# Imprimindo a lista
lst
# Usando um método do objeto lista
lst.count(10)
# A função help() explica como utilizar cada método de um objeto
help(lst.count)
# A função dir() mostra todos os métodos e atributos de um objeto
dir(lst)
a = 'Isso é uma string'
# O método de um objeto pode ser chamado dentro de uma função, como print()
print (a.split())
| false
|
508e4a3139bca354467178cbc2687416924599ea
|
Harpreetkaurpanesar25/python.py
|
/anagram.py
| 267
| 4.1875
| 4
|
#an anagram of a string is another string that contains same char, only the order of characters are different
def anagram(s1,s2):
if sorted(s1)==sorted(s2):
print("yes")
else:
print("no")
s1=str(input(""))
s2=str(input(""))
anagram(s1,s2)
| true
|
56c6c4417ca6f8dd1bc1880957484ed343b2a81d
|
teayes/Python
|
/Experiments/Exp6.py
| 731
| 4.15625
| 4
|
class stringValidation:
def __init__(self):
self.open= ["[", "{", "("]
self.close= ["]", "}", ")"]
def validate(self,string):
stack = []
for char in string:
if char in self.open:
stack.append(char)
elif char in self.close:
pos = self.close.index(char)
if len(stack) and (self.open[pos] == stack[-1]):
stack.pop()
else:
return False
if not len(stack):
return True
sv=stringValidation()
string=input("Enter a string:")
check=sv.validate(string)
if check:
print("The brackets are in order")
else:
print("The brackets are not in order")
| true
|
77c6300b4d7a20a073b857c545c8d702eee86595
|
AlexKasapis/Daily-Coding-Problems
|
/2019-02-23.py
| 1,252
| 4.125
| 4
|
# PROBLEM DESCRIPTION
# Given a sorted list of integers, square the elements and give the output in sorted order.
# For example, given [-9, -2, 0, 2, 3], return [0, 4, 4, 9, 81].
#
# SOLUTION
# Lets assume two pointers, pointing to the start and end of the list. The pointer which points to the number with the
# highest absolute value moves towards the other. The number, after it has been squared, is inserted to the start of
# the output list. This loop stops when the two pointers pass each other. This solution has a time complexity of O(n).
if __name__ == '__main__':
numbers = [-9, -2, 0, 2, 3] # Example list
output = []
# Initiate the left and right pointers
left_pointer = 0
right_pointer = len(numbers) - 1
# Loop until the two pointers pass each other, meaning that right pointer will be on the left side of the left
# pointer and thus having a lower value than the right pointer.
while left_pointer <= right_pointer:
if abs(numbers[left_pointer]) > abs(numbers[right_pointer]):
output.insert(0, pow(numbers[left_pointer], 2))
left_pointer += 1
else:
output.insert(0, (pow(numbers[right_pointer], 2)))
right_pointer -= 1
print(output)
| true
|
12404706673d1dfc33acabc52ba250789909496f
|
afrahaamer/PPLab
|
/VI Data Structures, Arrays, Vectors and Data Frames/3 Vectors/2 Basic Arithmetic operation/arithOperations.py
| 1,094
| 4.3125
| 4
|
# importing numpy
import numpy as np
# creating a 1-D list (Horizontal)
list1 = [5, 6, 9]
# creating a 1-D list (Horizontal)
list2 = [1, 2, 3]
# creating first vector
vector1 = np.array(list1)
# printing vector1
print("First Vector : " + str(vector1))
# creating secodn vector
vector2 = np.array(list2)
# printing vector2
print("Second Vector : " + str(vector2))
# adding both the vector
# a + b = (a1 + b1, a2 + b2, a3 + b3)
addition = vector1 + vector2
# printing addition vector
print("Vector Addition : " + str(addition))
# subtracting both the vector
# a - b = (a1 - b1, a2 - b2, a3 - b3)
subtraction = vector1 - vector2
# printing addition vector
print("Vector Substraction : " + str(subtraction))
# multiplying both the vector
# a * b = (a1 * b1, a2 * b2, a3 * b3)
multiplication = vector1 * vector2
# printing multiplication vector
print("Vector Multiplication : " + str(multiplication))
# dividing both the vector
# a / b = (a1 / b1, a2 / b2, a3 / b3)
division = vector1 / vector2
# printing multiplication vector
print("Vector Division : " + str(multiplication))
| false
|
527835943216d348696b0ad6ed7f8ba521e5a56d
|
afrahaamer/PPLab
|
/III Regular Expressions/1 RegEx Functions/findall/Metacharachters/ends with.py
| 241
| 4.21875
| 4
|
# $ - Pattern ends with
# ^ - Pattern starts with
import re
t = "Hello, How are you World"
# Checks if string ends with World?
x = re.findall("World$",t)
print(x)
# Checks if string starts with Hello
x = re.findall("^Hello",t)
print(x)
| true
|
312c35e0ee73ce3aa7b0836cf8f594d030ac1054
|
MostDeadDeveloper/Python_Tutorial_Exercises
|
/exercise3.py
| 357
| 4.21875
| 4
|
# Challenge - Functions Exercise
# Create a function named tripleprint that takes a string as a parameter
# and prints that string 3 times in a row.
# So if I passed in the string "hello",
# it would print "hellohellohello"
def tripleprint(val):
print(val*3)
return val*3
#tripleprint("hello")
# ^ - remove this to see the function call.
| true
|
0340d501babc4af06989c1455a8026e0b76c7cc8
|
bchhun/Codes-Kata
|
/prime_factors.py
| 1,509
| 4.21875
| 4
|
#coding: utf-8
"""
Compute the prime factors of a given natural number.
Bernard says: What is a prime factor ? http://en.wikipedia.org/wiki/Prime_factor
Test Cases ([...] denotes a list)
primes(1) -> []
primes(2) -> [2]
primes(3) -> [3]
primes(4) -> [2,2]
primes(5) -> [5]
primes(6) -> [2,3]
primes(7) -> [7]
primes(8) -> [2,2,2]
primes(9) -> [3,3]
"""
import unittest, math
def is_prime(num):
"""
http://en.wikipedia.org/wiki/Prime_number
"""
i = 2
while i <= math.sqrt(num):
if num % i == 0:
return False
i += 1
return True
def primes(num):
primes_list = []
base = 2
possibilities = xrange(base, num+1)
possibility = base
while (not primes_list) and (possibility in possibilities):
if is_prime(possibility) and num % possibility == 0:
primes_list = primes_list + [possibility] + primes(num/possibility)
possibility += 1
return primes_list
class primesTest(unittest.TestCase):
def test_unique(self):
self.assertEqual(primes(1), [])
self.assertEqual(primes(2), [2])
self.assertEqual(primes(3), [3])
self.assertEqual(primes(5), [5])
self.assertEqual(primes(7), [7])
def test_multiple(self):
self.assertEqual(primes(4), [2,2])
self.assertEqual(primes(6), [2,3])
self.assertEqual(primes(8), [2,2,2])
self.assertEqual(primes(9), [3,3])
def main():
unittest.main()
if __name__ == '__main__':
main()
| true
|
c3272a68e7f7705810f956609b24d6a6477d2faa
|
kimmvsrnglim/DigitalCrafts
|
/week2/print_triangle.py
| 222
| 4.1875
| 4
|
def triangle(height):
for x in range(0, height, 2):
space = " " * ((height - x)/2)
print space + "*" * (x + 1)
user_input = int(raw_input("What's the height of your triangle?"))
triangle (user_input)
| true
|
ee0d216b772925a8a2713e8ed7be384cd2e4f5fd
|
xandhiller/learningPython
|
/stringTidbits.py
| 454
| 4.40625
| 4
|
print('Enter a string: ')
n = input()
print("\nLength of string is: " + str(len(n)))
print()
# Starting i at 1 because i determines the non-inclusive upper limit of string
# truncation.
for i in range(1, len(n)+1):
print("string[0:"+str(i)+"]: \t" + n[0:i])
print()
# Conclusions:
# The operator 'string[0:8]' will take the zeroth element up to element 7.
# The operator 'string[1:8]' will take element one (second letter) up to
# element 7.
| true
|
eb7b6302495e29878e2db6ffd4240b8c941a61d0
|
nasreen94/luminar-python
|
/flow contols/decisin making/ifelif.py
| 1,098
| 4.125
| 4
|
# no1=int(input("enter d first no"))
# no2=int(input("enter d secnd no"))
# no3=int(input("enter d third no"))
# if no1>no2:
# if no1>no3:
# print("largest no is",no1)
# else:
# print("largest no is",no3)
# else:
# if no2>no3:
#
# print("largest no is ",no2)
# else:
# print("largest no is ",no3)no3
# no1=int(input("enter d first no"))
# no2=int(input("enter d secnd no"))
# no3=int(input("enter d third no"))
#
# if (no1>no2)&(no1>no3):
# print("max no",no1)
# elif (no2>no1)&(no2>no3):
# print("max no",no2)
# elif (no3>no1)&(no3>no2):
# print("max no", no3)
# else:
# print("all r equal")
m1=int(input("enter mark of stdent"))
m2=int(input("enter mark of stdent"))
m3=int(input("enter mark of stdent"))
print("marks f sudent is:",m1,m2,m3)
total=m1+m2+m3
print("total mark out of 150 is",total)
if total>145:
print("grade is A")
elif (total <145)&(total>=140):
print("grade is B")
elif (total<140)&(total>=135):
print("grade is C")
elif( total<135)&(total>=130):
print("grade is D")
else:
print("failed")
| false
|
b1c3fa918bcbc2fa1ac9f877291389d52eaf0278
|
JuanDAC/holbertonschool-higher_level_programming
|
/0x06-python-classes/101-square.py
| 1,910
| 4.5625
| 5
|
#!/usr/bin/python3
"""File with class Square"""
class Square:
"""Class use to represent a Square"""
def __init__(self, size=0, position=(0, 0)):
"""__init__ constructor method"""
self.size = size
self.position = position
@property
def size(self):
return self.__size
@size.setter
def size(self, value):
if type(value) is not int:
raise TypeError("size must be an integer")
if value < 0:
raise ValueError("size must be >= 0")
self.__size = value
@property
def position(self):
return self.__position
@position.setter
def position(self, value):
if type(value) is not tuple or len(value) != 2:
raise TypeError("position must be a tuple of 2 positive integers")
for i in range(len(value)):
if type(value[i]) is not int or value[i] < 0:
raise TypeError(
"position must be a tuple of 2 positive integers")
self.__position = value
def area(self):
"""area that returns the current square area"""
return self.size ** 2
def my_print(self):
"""my_print that prints in stdout the square with the character #"""
if not self.size:
print()
print(self)
def __str__(self):
"""__string__ that prints in stdout the square with the character #"""
string = ""
size = self.size
if size:
string += (self.position[1] * "\n")
for i in range(size):
newline = "\n" if (size - 1 != i) else ""
string += (self.position[0] * " " + size * "#") + newline
return string
if __name__ == "__main__":
my_square = Square(5, (0, 0))
print(my_square)
print("--")
my_square = Square(5, (4, 1))
print(my_square)
print("--")
my_square.my_print()
| true
|
2aac08cdac3ed1a5dc6c875d5ebb9f91e900bb81
|
daveshanahan/python_challenges
|
/database_admin_program.py
| 1,848
| 4.15625
| 4
|
log_on_info = {
"davids1":"MahonAbtr!n1",
"lydiam2":"Password1234",
"carlynnH":"scheduling54321",
"maryMcN":"Forecaster123",
"colinM":"paymentsG145",
"admin00":"administrator5",
}
print("Welcome to the database admin program")
username = input("\nPlease enter your username: ").strip()
# logic for control flow
if username in log_on_info:
password = input("Please enter your password: ").strip()
if password in log_on_info[username]:
print("\nHello " + username + "! You are logged in")
# if admin logs in
if username == "admin00":
print("Here is the current database:\n")
for keys, values in log_on_info.items():
print("Username: " + keys + "\t\tPassword: " + values)
else:
# if other user logged in
change_choice = input("Would you like to change your password: ").lower()
if change_choice.startswith("y"):
new_password = input("What would you like to change your password to: ")
# check password length and add to dict if correct length
if len(new_password) >= 8:
log_on_info[username] = new_password
print("\n" + username + ", your new password is " + new_password)
# else reject password and display original
elif len(new_password) < 8:
print(new_password + " is not the minimum password length of 8 characters.")
print("\n" + username + ", your password is " + password)
elif change_choice.startswith("n"):
print("Ok. Thank you for using the database admin program.")
else:
print("Password incorrect!")
else:
print("Username not found. Goodbye!")
| true
|
78fd793c2ca6e3021894ee562e7d7cc5ad32b990
|
daveshanahan/python_challenges
|
/Quadratic_Equation_Solver_App.py
| 1,261
| 4.375
| 4
|
import cmath
# print introduction
print("Welcome to the Quadratic Equation Solver App")
print("\nA Quadratic equation is of the form ax^2 + bx + c = 0.")
print("Your solutions can be real or complex numbers.")
print("A complex number has two parts: a + bj")
print("Where a is the real portion and bj is the imaginary portion.")
# gather user input and create list to iterate over
num_equations = int(input("\nHow many equations would you like to solve today: "))
list_equations = list(range(0,num_equations))
#loop through interable to solve for roots of each equation
for i in list_equations:
print("\nSolving equation #" + str(i + 1))
print("----------------------------------")
a = float(input("\nPlease enter your value of a (coefficient of x^2: "))
b = float(input("Please enter your value of b (coefficient of x): "))
c = float(input("Please enter your value of c (coefficient): "))
d = (b**2)-(4*a*c)
print("\nThe solutions to " + str(a) + "x^2 + " + str(b) + "x + " + str(c) + " = 0 are:")
x1 = (-b+cmath.sqrt(d))/2*a
print("\nx1 = " + str(x1))
x2 = (-b-cmath.sqrt(d))/2*a
print("x2 = " + str(x2))
print("\nThank you for using the Quadratic Equation Solver App. Goodbye.")
| true
|
c6ab0fa71832cc589f844da6120d509fedd04a15
|
daveshanahan/python_challenges
|
/guess_my_number_game.py
| 893
| 4.21875
| 4
|
import random
print("Welcome to the Guess My Number App")
# gather user input
name = input("\nHello! What is your name: ").title().strip()
# generate random number
print("Well " + name + ", I am thinking of a number between 1 and 20.")
random_num = random.randint(1,20)
# initialise guess counter and get user to take guesses
guess_count = 0
for i in range(5):
guess = int(input("\nTake a guess: "))
if guess < random_num:
guess_count += 1
print("Too low!")
elif guess > random_num:
guess_count += 1
print("Too high!")
else:
guess_count += 1
break
# print game recap statement
if guess == random_num:
print("\nGood job, " + name + "! You guessed my number in " + str(guess_count) + " guesses.")
else:
print("\nGame over! The number I was thinking of is " + str(random_num) + ".")
| true
|
0deda362dc460620ab43364b17599182f1f12e87
|
daveshanahan/python_challenges
|
/grade_point_average_calculator.py
| 2,658
| 4.4375
| 4
|
print("Welcome to the average calculator app")
# gather user input
name = input("\nWhat is your name? ").title().strip()
num_grades = int(input("How many grades would you like to enter? "))
print("\n")
# initialise list and append number of grades depending on user input
grades = []
for i in range(num_grades):
grades.append(int(input("Please enter a grade: ")))
# sort grades and print list of grades in descending order
grades.sort(reverse=True)
print("\nGrades Highest to Lowest: ")
for i in grades:
print("\t" + str(i))
# calculate average grade
avg_grade = round(float(sum(grades)/len(grades)), 2)
# print summary table
print("\n" + name + "'s Grade Summary:\n\tTotal number of grades: " + str(len(grades)) + "\n\tHighest grade: " + str(max(grades)) + "\n\tLowest grade: " + str(min(grades)) + "\n\tAverage grade: " + str(avg_grade))
# get user input to calculate grade needed to get new average
desired_avg = float(input("\nWhat is your desired average? "))
req_grade = (desired_avg*(len(grades)+1))-float(sum(grades))
# print req_grade message for user
print("\nGood luck " + name + "!\nYou will need to get a " + str(req_grade) + " on your next assignment to earn a " + str(desired_avg) + " average.")
print("\nLet's see what your average could have been if you did better/worse on an assignment.")
# make copy of list to use for rest of program
grades_two = grades.copy()
# gather user input to change grade
ch_grade = int(input("What grade would you like to change: "))
new_grade = int(input("What grade would you like to change " + str(ch_grade) + " to: "))
# remove old grade, add new grade
grades_two.remove(ch_grade)
grades_two.append(new_grade)
# sort grades and print list of grades in descending order
grades_two.sort(reverse=True)
print("\nGrades Highest to Lowest: ")
for i in grades_two:
print("\t" + str(i))
# calculate new average grade
new_avg_grade = round(float(sum(grades_two)/len(grades_two)), 2)
# print summary again with new grades
print("\n" + name + "'s New Grade Summary:\n\tTotal number of grades: " + str(len(grades_two)) + "\n\tHighest grade: " + str(max(grades_two)) + "\n\tLowest grade: " + str(min(grades_two)) + "\n\tAverage grade: " + str(new_avg_grade))
# print comparison of average scores and last statements
print("Your new average would be a " + str(new_avg_grade) + " compared to your real average of " + str(avg_grade) + ".\nThat is a change of " + str(round(new_avg_grade-avg_grade, 2)) + " points!")
print("\nToo bad your original grades are still the same!\n" + str(grades) + "\nYou should go ask for extra credit!")
| true
|
a85f63d5cfc5b211612bb92d388bbfb9526de482
|
davidac2007/python_tutorials
|
/numbers.py
| 2,448
| 4.5
| 4
|
# Python numbers
# There are three numeric types in Pythom:
# int
x = 1
# float
y =2.8
# complex
z = 1j
print(type(x))
print(type(y))
print(type(z))
# Int
# Int or integer, is a whole number, positive or negative, without decimals,
# of unlimited length.
x = 1
y = 366376429
z = -3255522
print(type(x))
print(type(y))
print(type(z))
# Float
# Float, or "floating point number",positive or negative,
# containing one or more decimals.
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
# Float can also be scientific numbers with an "e" to indicate the power of 10.
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
# Complex
# Complex numbers are written with a "j" as the imaginary part:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
# Type conversion
# You can convert from one type to another with the int(), float(), amd complex() methods:
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
# You cannot convert complex numbers into another number type.
# Random number
# Python does not have a random() function to make a random number,
# but Python has a built-in module called random that can be used
# to make random numbers:
# Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1,10))
# Python Casting
# Casting in python is therefore done using constructor functions:
'''
int() - constructs an integer number from an integer literal, a float literal
(by removing all decimals), or a string literal (providing the string represents
a whole number)
float() - constructs a float number from an integer literal, a float literal or a
string literal (providing the string represents a float or an integer)
str() - constructs a string from a wide variety of data types, including
strings, integer literals and float literals
'''
# Integers
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
# Floats
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
# Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
| true
|
9dda68c3e93388399b7d1026d82efa2d41ea26a5
|
GuhanSGCIT/Trees-and-Graphs-problem
|
/The lost one.py
| 2,750
| 4.375
| 4
|
"""
Shankar the Artist had two lists that were permutations of one another. He was very proud. Unfortunately, while transporting them
from one exhibition to another, some numbers were lost out of the first list. Can you find the missing numbers?
As an example, the array with some numbers missing, arr=[7,2,5,3,5,3]. The original array of numbers brr=[7,2,5,4,6,3,5,3].
The numbers missing are [4,6].
Notes:
If a number occurs multiple times in the lists, you must ensure that the frequency of that number in both lists is the same.
If that is not the case, then it is also a missing number.
You have to print all the missing numbers in ascending order.
Print each missing number once, even if it is missing multiple times.
The difference between the maximum and minimum number in the second list is less than or equal to 100.
arr: the array with missing numbers
brr: the original array of numbers
timing:2sec
level:6
Input:
There will be four lines of input:
N is the size of the first list, arr.
The next line contains N space-separated integers arr[i].
M is the size of the second list, brr.
The next line contains M space-separated integers brr[i].
Output:
Output the missing numbers in ascending order separated by space.
Constraints
1≤n,m≤2 X 10^5
n≤m
1≤brr[i]≤10^4
Xmax - Xmin ≤100
Sample Input:
10
203 204 205 206 207 208 203 204 205 206
13
203 204 204 205 206 207 205 208 203 206 205 206 204
Sample Output:
204 205 206
EXPLANATION:
204 is present in both arrays. Its frequency in arr is 2, while its frequency in brr is 3.
Similarly, 205 and 206 occur twice in arr, but three times in brr. The rest of the numbers have the same frequencies in both lists.
input:
12
1 5 6 7 9 11 2 3 6 7 10 11
4
11 20 9 11
output:
20
input:
8
12 23 45 56 13 23 46 47
5
1 3 5 2 4
output:
1 2 3 4 5
input:
6
111 333 555 222 402 302
7
103 204 506 704 204 511 699
output:
704 103 204 506 699 511
input:
3
1 5 2
4
10 20 30 10
output:
10 20 30
hint:
The main task is to find the frequency of numbers in each array. This can be done using count array.
If the frequency of a number is different, then print that number.
we can have two count arrays for each array. Then we need to run a loop for the count array.
While traversing the array if frequencies mismatch, print that number.
"""
from sys import stdin,stdout
n=int(stdin.readline())
d={}
arr=[int(num) for num in stdin.readline().split()]
m=int(stdin.readline())
brr=[int(num) for num in stdin.readline().split()]
if n-m==0:
print(0)
else:
for i in set(brr):
if brr.count(i)!=arr.count(i):
print(i,end=' ')
| true
|
60652845c16c2840261f73b47b9225abd39ca9b0
|
GuhanSGCIT/Trees-and-Graphs-problem
|
/Spell Bob.py
| 2,515
| 4.3125
| 4
|
"""
Varun likes to play with cards a lot. Today, he's playing a game with three cards. Each card has a letter written on the top face and
another (possibly identical) letter written on the bottom face. Varun can arbitrarily reorder the cards and/or flip any of the cards
in any way he wishes (in particular, he can leave the cards as they were). He wants to do it in such a way that the letters on the
top faces of the cards, read left to right, would spell out the name of his favorite friend Bob.
Determine whether it is possible for Varun to spell "bob" with these cards.
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single string with length 3 denoting the characters written on the top faces of the first,second and third card.
The second line contains a single string with length 3 denoting the characters written on the bottom faces of the first,second and third card.
Output
For each test case, print a single line containing the string "yes" (without quotes) if Chef can spell "bob" or "no" (without quotes) if he cannot.
Constraints
1≤T≤20,000
each string contains only lowercase English letters
Example Input
3
bob
rob
dbc
ocb
boc
obc
Example Output
yes
yes
no
Explanation
Example case 1: The top faces of the cards already spell out "bob".
Example case 2: Chef can rearrange the cards in the following way to spell "bob": the second card non-flipped, the first card flipped and the third card flipped.
Example case 3: There is no way for Chef to spell out "bob".
input:
5
kok
obo
kol
bbo
mom
bob
lok
non
bbo
boo
output:
no
yes
yes
no
yes
input:
1
boo
oob
output:
yes
input:
2
ooo
bbb
bob
bob
output:
yes
yes
input:
5
bbb
oob
ooo
bob
obo
obc
abs
abb
boa
ala
output:
yes
yes
no
no
no
hint:
First, fix the letter ooo for the middle card. Now, try the remaining cards and check if both of them contain a “b” on either side of them.
"""
T = int(input())
for _ in range(T):
s = input()
t = input()
ok = False
for i in range(3):
if s[i] == 'o' or t[i] == 'o':
cnt = 0
for j in range(3):
if j != i:
if s[j] == 'b' or t[j] == 'b':
cnt += 1
if cnt == 2:
ok = True
print("yes" if ok else "no");
| true
|
4472990ca9ef518a8e02dfcd668a19b7fcefd1ab
|
GuhanSGCIT/Trees-and-Graphs-problem
|
/snake pattern.py
| 1,244
| 4.28125
| 4
|
"""
Given an M x N matrix .In the given matrix, you have to print the elements of the matrix in the snake pattern.
i des
First line contains two space separated integers M,N,which denotes the dimensions of matrix.
Next for each M lines contains N space separated integers,denotes the values.
Odes
print the snake
Exp
From sample
the first row is printed as same and the second row is appended reversed with the first.
1 2 3 7 6 5
Hin
We traverse all rows. For every row, we check if it is even or odd. If even, we print from left to
right else print from right to left.
In
3 3
1 2 3
4 5 6
7 8 9
Ot
1 2 3 6 5 4 7 8 9
In
2 3
1 2 3
5 6 7
ot
1 2 3 7 6 5
In
1 1
1
ot
1
In
3 2
1 1
1 1
1 1
ot
1 1 1 1 1 1
In
5 3
1 2 3
4 5 6
7 8 9
1 2 3
4 5 6
ot
1 2 3 6 5 4 7 8 9 3 2 1 4 5 6
T
600
"""
M,N=map(int,input().split())
def printf(mat):
global M, N
for i in range(M):
if i % 2 == 0:
for j in range(N):
print(str(mat[i][j]),
end = " ")
else:
for j in range(N - 1, -1, -1):
print(str(mat[i][j]),
end = " ")
mat=[]
for i in range(M):
l=list(map(int,input().split()))
mat.append(l)
printf(mat)
| true
|
6012371aef940cf255e34f4d6960533564924be4
|
GuhanSGCIT/Trees-and-Graphs-problem
|
/Guna and grid.py
| 1,212
| 4.125
| 4
|
"""
Recently, Guna got a grid with n rows and m columns. Rows are indexed from 1 to n and columns are indexed from 1 to m.
The cell (i,j) is the cell of intersection of row i and column j. Each cell has a number written on it. The number written
on cell (i,j) is equal to (i+j). Now, Guna wants to select some cells from the grid, such that for every pair of selected cells ,
the numbers on the cells are co-prime. Determine the maximum number of cells that Guna can select.
Timing:1sec
level:4
Input Description:
Single line containing integers n and m denoting number of rows and number of columns respectively.
Output description:
Single line containing the answer.
Constraints
1≤n,m≤106
Input:
3 4
Output:
4
input:
45 65
Output:
29
input:
8 9
Output:
7
input:
5 6
Output:
5
input:
0 1
Output:
0
solution:
"""
def Sieve(n):
prime = [1 for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * 2, n+1, p):
prime[i] = 0
p += 1
return prime
try:
n,m=list(map(int,input().split()))
x=Sieve(n+m)
print(sum(x)-2)
except:
pass
| true
|
d0ae84a9f2cb762c24b70b92ea1cab0e3acbe92d
|
GuhanSGCIT/Trees-and-Graphs-problem
|
/Egg Dropping Puzzle-Samsung.py
| 2,110
| 4.40625
| 4
|
"""
Suppose you have N eggs and you want to determine from which floor in a K-floor building you can drop an egg such that it doesn't break. You have to determine the minimum number of attempts you need in order find the critical floor in the worst case while using the best strategy.There are few rules given below.
An egg that survives a fall can be used again.
A broken egg must be discarded.
The effect of a fall is the same for all eggs.
If the egg doesn't break at a certain floor, it will not break at any floor below.
If the eggs breaks at a certain floor, it will break at any floor above.
timing:1.5sec
level:6
Input:
The first line of input is T denoting the number of testcases.Then each of the T lines contains two positive integer N and K where 'N' is the number of eggs and 'K' is number of floor in building.
Output:
For each test case, print a single line containing one integer the minimum number of attempt you need in order find the critical floor.
Constraints:
1<=T<=30
1<=N<=10
1<=K<=50
Example:
Input:
2
2 10
3 5
Output:
4
3
input:
3
1 5
2 16
2 8
output
5
6
4
input:
2
1 6
3 15
output
6
5
input:
1
2 8
output
4
input:
4
1 5
2 7
2 9
1 9
output
5
4
4
9
hint:
calculate the minimum number of droppings needed in the worst case. The floor which gives the minimum value in the worst case is going to be part of the solution.
In the following solutions, we return the minimum number of trials in the worst case; these solutions can be easily modified to print floor numbers of every trial also.
"""
import sys
def eggDrop(n, k):
if (k == 1 or k == 0):
return k
if (n == 1):
return k
min = sys.maxsize
for x in range(1, k + 1):
res = max(eggDrop(n - 1, x - 1),
eggDrop(n, k - x))
if (res < min):
min = res
return min + 1
if __name__ == "__main__":
for i in range(int(input())):
n,k=map(int,input().split())
print(eggDrop(n, k))
| true
|
cbc7d523b97ec18e747d0955b769c475c6935aff
|
alfonso-torres/eng84_OOP_exercises
|
/Fizzbuzz.py
| 1,403
| 4.4375
| 4
|
# Exercise 1 - Fizzbuzz
# Write a program that outputs sequentially the integers from 1 to 100, but on some conditions prints a string instead:
# when the integer is a multiple of 3 print “Fizz” instead of the number,
# when it is a multiple of 5 print “Buzz” instead of the number,
# when it is a multiple of both 3 and 5 print “FizzBuzz” instead of the number.
# Notes: must be in a class and method format
# Let's create the Fizzbuzz class
class Fizzbuzz:
def __init__(self):
self.three = 3 # Integer to check if is a multiple of 3
self.five = 5 # Integer to check if is a multiple of 5
# Function that will check if the number is multiple of 3 or 5 and print the correct answer
def fizzbuzz_prints(self):
i = 1
while i <= 100: # loop while from 1 to 100
if i % self.three == 0 and i % self.five == 0: # check if is multiple of both
print("FizzBuzz")
elif i % self.three == 0: # check if is multiple of 3
print("Fizz")
elif i % self.five == 0: # check if is multiple of 5
print("Buzz")
else:
print(i) # number that is not dividable by 3 or 5
i += 1
# Let's create an object of the Fizzbuzz Class
object_fizzbuzz = Fizzbuzz()
# Call the function that will print the corrects answers
object_fizzbuzz.fizzbuzz_prints()
| true
|
6ed4d522eed64bb845676e0b9bcbd24e21ffa1ff
|
taroserigano/coderbyte
|
/Arrays/Consecutive.py
| 737
| 4.1875
| 4
|
'''
Consecutive
Have the function Consecutive(arr) take the array of integers stored in arr and return the minimum number of integers needed to make the contents of arr consecutive from the lowest number to the highest number. For example: If arr contains [4, 8, 6] then the output should be 2 because two numbers need to be added to the array (5 and 7) to make it a consecutive array of numbers from 4 to 8. Negative numbers may be entered as parameters and no array will have less than 2 elements.
Examples
Input: [5,10,15]
Output: 8
Input: [-2,10,4]
Output: 10
'''
def Consecutive(arr):
return max(arr) - min(arr) - len(arr) +1
# keep this function call here
print Consecutive(raw_input([5,10,15))
| true
|
4d03565e948a1b5f093d0ff0cb589ead794f8d21
|
taroserigano/coderbyte
|
/Trees & Graphs/SymmetricTree.py
| 1,203
| 4.5
| 4
|
'''
Symmetric Tree
HIDE QUESTION
Have the function SymmetricTree(strArr) take the array of strings stored in strArr, which will represent a binary tree, and determine if the tree is symmetric (a mirror image of itself). The array will be implemented similar to how a binary heap is implemented, except the tree may not be complete and NULL nodes on any level of the tree will be represented with a #. For example: if strArr is ["1", "2", "2", "3", "#", "#", "3"] then this tree looks like the following:
For the input above, your program should return the string true because the binary tree is symmetric.
Use the Parameter Testing feature in the box below to test your code with different arguments.
"["1", "2", "2", "3", "#", "#", "3"]"
'''
def SymmetricTree(a):
# code goes here
arr, branch, store = list(a), 1, []
while len(arr) > 0: #squeeze out
x = []
for i in range(branch):
x.append(arr[0])
del arr[0]
store.append(x)
branch *= 2
for i in store:
if i != list(reversed(i)) :
return 'false'
return 'true'
# keep this function call here
print SymmetricTree(raw_input())
| true
|
75bb3cbcba0b24a5487276691650603e261e416d
|
mgomez9638/CIS-106-Mario-Gomez
|
/Assignment 8/Activity 1.py
| 668
| 4.40625
| 4
|
# Activity 1
# This program gives the user access to create a multiplication table.
# You simply begin with entering a value, entering a starting point, and the size of the table.
def getExpressions():
print("Enter the number of expressions")
expressions = int(input())
return expressions
def getValue():
print("Enter a value: ")
value = int(input())
return value
# Main
value = getValue()
expressions = getExpressions()
multiplierValue = 1
while multiplierValue <= expressions:
total = value * multiplierValue
print(str(value) + " * " + str(multiplierValue) + " = " + str(total))
multiplierValue = multiplierValue + 1
| true
|
bf3a761daa923e3fc486c37ed4a522d4cbb57d45
|
mgomez9638/CIS-106-Mario-Gomez
|
/Assignment 5/Activity 6.py
| 2,061
| 4.34375
| 4
|
# Activity 6
# This program is intended to determine how much paint is required to paint a room.
# It, also, expresses how much the gallons of paint cost.
def get_length():
length = float(input("Enter the length of the room(in feet): "))
return length
def get_width():
width = float(input("Enter the width of the room(in feet): "))
return width
def get_height():
height = float(input("Enter the height of the room(in feet): "))
return height
def get_price_per_gallon():
price_per_gallon = float(input("Enter the price per gallon of paint: $"))
return price_per_gallon
def get_square_feet_per_gallon():
square_feet_per_gallon = float(input("Enter the square feet that a gallon of paint will cover: "))
return square_feet_per_gallon
def calculate_total_area(length, width, height):
total_area = round(2 * length * height + 2 * width * height, 2)
return total_area
def calculate_gallons(total_area, square_feet_per_gallon):
gallons = int(round(total_area / square_feet_per_gallon + 0.5))
return gallons
def calculate_total_price_of_paint(gallons, price_per_gallon):
total_price_of_paint = round(gallons * price_per_gallon, 2)
return total_price_of_paint
def display_result(total_area, gallons, total_price_of_paint):
print("The total area of the room is " + str(total_area) +
" square feet. The number of gallons needed are " + str(gallons) +
". The total cost of the paint is $" + str(total_price_of_paint) +
".")
def main():
length = get_length()
width = get_width()
height = get_height()
price_per_gallon = get_price_per_gallon()
square_feet_per_gallon = get_square_feet_per_gallon()
total_area = calculate_total_area(length, width, height)
gallons = calculate_gallons(total_area, square_feet_per_gallon)
total_price_of_paint = calculate_total_price_of_paint(gallons, price_per_gallon)
display_result(total_area, gallons, total_price_of_paint)
main()
| true
|
3031e95c3286a9b596e179e6e08b8903b99625ba
|
mgomez9638/CIS-106-Mario-Gomez
|
/Assignment 4/Activity 3.py
| 439
| 4.15625
| 4
|
# Assignment Three
# This program gives the user access to calculate the distance in U.S. standard lengths.
# It converts miles into yards, feet, and inches.
print("Enter distance in miles: ")
miles = float(input())
yards = 1760 * miles
feet = 5280 * miles
inches = 63360 * miles
print("The distance in yards is " + str(yards) +
". The distance in feet is " + str(feet) +
". The distance in inches is " + str(inches) + ".")
| true
|
1c132cd8d307833a17f4860c3d0267c89e0f83c6
|
Sridevi333/Python-Deep-Learning-Programming
|
/ICP2/wordsperline.py
| 355
| 4.125
| 4
|
fileName = input("Enter file name: ")
f = open(fileName, "r")
# Open file for input
lines=0
mostWordsInLine = 0
for lineOfText in f.readlines():
wordCount = 0
lines += 1
f1=lineOfText.split()
wordCount=wordCount+len(f1)
if len(f1) > mostWordsInLine:
mostWordsInLine = len(f1)
print ((str(lineOfText)),str(wordCount))
| true
|
ec79fbf6c6334667e4604b67cf4718304c5be637
|
mrzhang638993/python-basis
|
/object_excercise.py
| 1,525
| 4.1875
| 4
|
# python 对象的课后习题的训练
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Line:
def __init__(self, z, r):
self.z = z
self.r = r
def getLen(self):
return math.sqrt(math.pow((self.z.x - self.r.x), 2) + math.pow((self.z.y - self.r.y), 2))
point1 = Point(3, 4)
point2 = Point(5, 6)
line = Line(point1, point2)
print(line.getLen())
# 使用self使用的都是实例对象的属性的,使用类对象对应的都是类对象
class C:
num = 0
def __init__(self):
self.x = 4
self.y = 5
C.count = 6
c = C()
# 打印类的属性
print(C.__dict__)
# 打印实例对象的属性
print(c.__dict__)
# 定义类实例进行类的追踪创建了多少类对象的
# 体会出来类对象和实例对象的区别操作
class T:
count = 0
def __init__(self):
T.count += 1
def getCount(self):
return T.count
def __del__(self):
T.count -= 1
t1 = T()
t2 = T()
t3 = T()
print(T.count)
del t1
del t2
print(T.count)
# 定义栈对象,实现栈常见的操作逻辑,对应的是有顺序的数据结构的
class Stack(list):
def isEmpty(self):
return self.count()
def push(self, x):
self.append(x)
def pop(self):
self.pop(0)
def top(self):
return self.__getitem__(0)
def bootom(self):
return self.__getitem__(self.count() - 1)
# 学习资源学习。
stack = Stack()
print(stack.isEmpty())
| false
|
d1f6b7f2192bbd7c650dca043c403264af0fdce4
|
mrzhang638993/python-basis
|
/module_exercise.py
| 1,485
| 4.40625
| 4
|
# python中的模块对应的是一个python文件
"""
1.我们现在有一个 hello.py 的文件,里边有一个 hi() 函数:.&ymiM?t
def hi():
print("Hi everyone, I love FishC.com!")
复制代码
请问我如何在另外一个源文件 test.py 里边使用 hello.py 的 hi() 函数呢?
答案:对应的引用方式是如下的:
import hello_1 as hello
hello.hi()
2.模块对应的引入方式主要包括如下的3中引入方式的:
导入方式之一:import 模块导入操作
导入方式之二:from 模块名称 import 函数名称 可以只引入部分的名称
导入方式之三: import 模块名称 as 新名字 推荐使用这个方式来实现操作的
3. 曾经我们讲过有办法阻止 from…import * 导入你的“私隐”属性,你还记得是怎么做的吗?
from 模块名称 import 函数名称 可以避免导入函数的私有属性的。
4. from a import sayHi
from b import sayHi
sayHi()
对应的存在覆盖的问题,执行的是下面的一个函数的操作的
5.出现下面的问题对应的解决的办法是:
# a.py
from b import y
def x():
print('x')
# b.py
from a import x
def y():
print('y')
存在对应的循环依赖的办法实现的。
"""
import const
const.NAME = "FishC"
print(const.NAME)
try:
# 尝试修改常量
const.NAME = "FishC.com"
except TypeError as Err:
print(Err)
try:
# 变量名需要大写
const.name = "FishC"
except TypeError as Err:
print(Err)
| false
|
98f2a515844083826503ee03d9420d36aa90ca19
|
mrzhang638993/python-basis
|
/game.py
| 447
| 4.28125
| 4
|
"""使用python 设计第一个游戏"""
temp=input("不妨猜猜小甲鱼现在心里想的是那个数字: ") #接收用户的输入,赋值给temp
guess=int(temp);
if guess==8: #注意缩进的位置的,python非常注重缩进操作的
print("你是小甲鱼心里的蛔虫嘛?!")
print("哼,猜中了也没有奖励!")
else:
print("猜错了,小甲鱼现在心里想的是8!")
print("游戏结束,不玩了")
| false
|
7af3b6b3a8cf63f64ad0527790de8e75d4ae9c1c
|
thaiscardia/ex-python
|
/project-euler/problem1-multiples3and5.py.py
| 310
| 4.125
| 4
|
"""definir o limite para 1000
%5 == 0 -> uma função or %3 == 0
se o num for divisivel, lista;
soma a lista
"""
def calculo():
lista = []
for num in range(1, 1000):
if num %5 == 0 or num %3 == 0:
lista.append(num)
soma = sum(lista)
print(soma)
calculo()
| false
|
3fe3c7b31f3dd81cc5d45896ae728f7a05f524ed
|
thaiscardia/ex-python
|
/Guanabara/Mundo1/ex26-ocorrenciaString.py
| 417
| 4.1875
| 4
|
"""Faça um programa que leia uma frase pelo teclado e mostre:
- quantas vezes aparece a letra "A";
- em que posição ela aparece a primeira vez;
- em que posição ela aparece a última vez;"""
f = input("Digite a frase aqui: ")
f = f.upper()
print("Esta frase possui {} letra(s) A".format(f.count("A")))
print("O primeiro A da string está localizado em {} e o último em {}.".format(f.index("A"), f.rindex("A")))
| false
|
1a0e41d3b08f4c98db46d0f7e01e7ae247b21298
|
Chuukwudi/Think-python
|
/chapter8_exercise8_5.py
| 2,544
| 4.28125
| 4
|
'''
str.islower()
Return True if all cased characters in the string are lowercase and there is at least one cased character,
False otherwise.
'''
def any_lowercase1(s):
for c in s:
if c.islower():
return True
else:
return False
'''Here, the funtion takes the first character, if it is Upper case,
it returns false, if it is lower case, it returns true. it does not iterate over other characters in the string s'''
# -----------------------------------------------------------------------------------------------------------------------
def any_lowercase2(s):
for c in s:
if 'c'.islower():
return 'True'
else:
return 'False'
'''this function checks only the string 'c' is lower, which always returns True'''
# -----------------------------------------------------------------------------------------------------------------------
def any_lowercase3(s):
for c in s:
flag = c.islower()
return flag
'''This would have been a nice code except that it only returns after iterating completly.
Hence, the output is based on the last letter of the string you're checking, it ignores the state of other characters
but only return its last check '''
# -----------------------------------------------------------------------------------------------------------------------
def any_lowercase4(s):
flag = False
for c in s:
flag = flag or c.islower()
return flag
'''This is the perfect code. During the iteration, once a lowercase is met, the flag changes to True.
if another lower case is met, c.islower changes to false but the flag still maintains True because if the
"or" gate'''
# -----------------------------------------------------------------------------------------------------------------------
def any_lowercase5(s):
for c in s:
if not c.islower():
return False
return True
'''This code returns True by default but, it will only work when the string being tested has not more that one
upper case letter. Once it encounters an upper case letter, it returns a value and the if statement doesnt run
anymore.
'''
# -----------------------------------------------------------------------------------------------------------------------
print(any_lowercase1('WaSEe'))
print(any_lowercase2('CSEc'))
print(any_lowercase3('ccSEc'))
print(any_lowercase4('CSddE'))
print(any_lowercase5('EeE'))
| true
|
7783f793664c77640e328a30721a8c28b06e7a07
|
anandaviamianni/Pengkondisian-Modul-2-
|
/Studi Kasus.py
| 717
| 4.1875
| 4
|
# Kiki dan Titis adalah seorang programmer di PT Daspro, kemudian mereka diminta oleh atasannya
# untuk membuat sebuah program untuk menentukkan kategori umur, dengan ketentuan umur seperti di bawah.
print("==== KATEGORI UMUR ====")
umur = int(input("Masukkan umur anda = "))
print("\nAnda Berada pada : ")
print("===============================")
if umur > 0 and umur <= 5:
print("Masa Balita")
elif umur > 5 and umur <= 12:
print("Masa Kanak-kanak")
elif umur > 12 and umur <= 25:
print("Masa Remaja")
elif umur > 25 and umur <= 45:
print("Masa Remaja")
elif umur > 45 and umur <= 65:
print("Masa Lansia")
else:
print("Masa Manula")
print("==============================")
| false
|
a12543e90095726b5bd8a96463da4311462fb58e
|
LeeGing/Python_Exercises
|
/8_ball.py
| 835
| 4.3125
| 4
|
#Magic 8 Ball
def shake():
import random
print ("======================================================")
print ("==================== MAGIC 8 BALL ====================")
print ("======================================================")
user_input = input("ASK THE 8 BALL YOUR QUESTION: ")
ans = random.randint(1,5)
if ans == 1:
print ("======================================================")
print ("8 BALL: PERHAPS, YES.")
shake()
elif ans == 2:
print ("======================================================")
print ("8 BALL: UNFORTUNATELY, NO")
shake()
elif ans == 3:
print ("======================================================")
print ("8 BALL: I CAN'T SAY.")
shake()
else:
print ("======================================================")
print ("8 BALL: ASK ME AGAIN LATER")
shake()
shake()
| false
|
7b659166ca9845366521da6132889c30e7de2849
|
makaiolam/final-day-1
|
/main.py
| 1,796
| 4.21875
| 4
|
import turtle
# turtle = turtle.Turtle()
# shape = input("choose shape triangle square or circle")
# if shape == ("triangle"):
# def triangle(length,color):
# turtle.speed(1)
# turtle.color(color)
# turtle.forward(length)
# turtle.left(120)
# turtle.forward(length)
# turtle.left(120)
# turtle.forward(length)
# c = input("choose a color black or red")
# l = input("choose a length for the triangle, 100 or 50")
# triangle(l,c)
# elif shape == ("square"):
# def square(length, color):
# turtle.speed(1)
# turtle.color(color)
# turtle.forward(length)
# turtle.left(90)
# turtle.forward(length)
# turtle.left(90)
# turtle.forward(length)
# turtle.left(90)
# turtle.forward(length)
# c = input("choose a color black or red")
# l = input("choose a length for the triangle, 100 or 50")
# square(l,c)
# if shape == ("circle"):
# def circle(length,color):
# turtle.circle(length)
# c = input("choose a color red or black:")
# l = input("choose a length 100 or 50:")
# circle(l,c)
# window = turtle.Screen()
# window.setup(500,500)
# turtle = turtle.Turtle()
window = turtle.Screen()
window.setup(500,500)
turtle = turtle.Turtle()
def drawcircle():
turtle.circle(100)
turtle.speed(15)
def pattern1():
x = 0
while x < 36:
drawcircle()
turtle.right(50)
x += 1
pattern1()
def drawcircle2():
turtle.circle(50)
turtle.speed(10)
def circle():
x = 0
while x < 26:
drawcircle()
turtle.left(100)
x =+ 1
circle()
# window = turtle.Screen()
# window.setup(500,500)
# turtle = turtle.Turtle()
# def drawcircle():
# turtle.circle(100)
# turtle.speed(15)
# def pattern1():
# x = 0
# while x < 36:
# drawcircle()
# turtle.right(50)
# x += 1
# pattern1()
| false
|
a1af47bd51c847b5ec8815835a24f13e89aa3053
|
ckaydevs/learning_python
|
/class/draw art/squre.py
| 924
| 4.3125
| 4
|
import turtle
def draw_square(some_turtle):
for i in range(1,5):
some_turtle.forward(100)
some_turtle.right(90)
def draw_art():
window=turtle.Screen()
window.bgcolor("red")
#Create the turtle brad- Draws a square
brad=turtle.Turtle()
brad.shape("turtle")
brad.color("yellow")
brad.speed(10)
for i in range (1,37):
draw_square(brad)
brad.right(10)
#Create the turtle pit- Draws a circle
#pit = turtle.Turtle()
#pit.shape("arrow")
#pit.color("blue")
#pit.circle(100) '''
window.exitonclick()
draw_art()
'''
I wrote this at first to make circle from square
angle=0
while(angle<360):
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
brad.right(5)
angle+=5 '''
| true
|
7a4f8c8d68bd58f1cd327f3e41bc09329a5c3e6a
|
joelgarzatx/portfolio
|
/python/Python3_Homework03/src/decoder.py
| 752
| 4.125
| 4
|
"""
Decoder provided function alphabator(list) accepts an integer list,
which returns the list of integers, substituting letters of the alphabet
for integer values from 1 through 26
"""
def alphabator(object_list):
""" Accepts a list of objects and returns the objects from
the list, replacing integer values from 1 to 26 with
the corresponding letter of the English alphabet
"""
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for object in object_list:
if object in range(1,27): # object is integer from 1 - 26
ret_val = alphabet[object-1] # grab corresponding letter from alphabet list
else: # other integer value or object
ret_val = object
yield ret_val
| true
|
bb47cb2a447892832f217c28d2570902d1c9709e
|
AdamBorg/PracCP1404
|
/Prac03/asciiTable.py
| 774
| 4.21875
| 4
|
def main():
lower = 33
upper = 127
num_entered = get_number(lower,upper)
print("{:>3} {:>6} \n".format(num_entered, chr(num_entered)))
print_ascii_table(lower, upper)
def get_number(lower,upper):
num_entered = 0
exit_character = 'e'
while num_entered < 33 or num_entered > 127 or exit_character == 'e':
try:
num_entered = int(input("please enter a number between {} and {} \n".format(lower, upper)))
exit_character = 'i'
except ValueError:
print("Please enter a valid number")
return num_entered
def print_ascii_table(lower, upper):
for i in range(lower, upper):
print("{:>3} {:>6}".format(i, chr(i)))
main()
#made change to see what happens when pushed to gitHub
| true
|
ae2357e9ae0dc6da9f2aef9c4bd6897259cf9018
|
sstoudenmier/CSCI-280
|
/Assignment5/PathNode.py
| 1,798
| 4.15625
| 4
|
'''
Class representing a map location being searched. A map location is defined by its (row,
column) coordinates and the previous PathNode.
'''
class PathNode:
def __init__(self, row=0, col=0, previous=None):
self.row = row
self.col = col
self.previous = previous
'''
Gets the row number for the PathNode.
@return: the value of the row for the PathNode
'''
def getRow(self):
return self.row
'''
Gets the column number for the PathNode.
@return: the value of the column for the PathNode
'''
def getCol(self):
return self.col
'''
Gets the previous node for the PathNode.
@return: the pathnode that was previous looked at
'''
def getPrevious(self):
return self.previous
'''
Sets the previous node for the PathNode.
@param: previous - value to set for the previous node
'''
def setPrevious(self, previous):
self.previous = previous
'''
Override the equals method so that it can compare two PathNode objects.
@param: other - another PathNode class to compare self to
@return: true if self and other are equal in row and column; false otherwise
'''
def __eq__(self, other):
if self.getRow() == other.getRow() and self.getCol() == other.getCol():
return True
return False
'''
Overide the hash method.
@return: a hash value for the PathNode objects
'''
def __hash__(self):
return 31 * self.getRow() + self.getCol()
'''
Override the toString method for PathNode so that it can print out the coordinates.
@return: a string representation of the PathNode
'''
def __str__(self):
return "(" + str(self.getRow()) + ", " + str(self.getCol()) + ")"
| true
|
b8e0e7bb09098d3470458211331885555a417662
|
russian-droid/100DoC_D03
|
/main.py
| 2,717
| 4.25
| 4
|
#following Udemy course: 100 days of code by Angela Yu
number = int(input ('Please enter an intger?\n'))
x=number%2
if x==0:
print ('that is an even nunber')
else:
print ('that is an odd number')
print(x)
#-----------------------------------
print ('\n\n-------WELCOME TO THE BMI CALCULATOR-------')
weight = float(input ('enter the weight in kg?\n'))
height = float(input ('enter the height in m\n'))
wholeBMI = weight / (height * height)
BMI = round(wholeBMI)
print(BMI)
if BMI <= 18.5:
print('You are UNDERweight')
elif BMI <= 25:
print('You are NORMAL weight')
elif BMI <= 30:
print('You are slightly OVERweight')
elif BMI <= 35:
print('You are OBESE')
else:
print('You are clinically OBESE')
#----------------------------
#https://ascii.co.uk/art
print('''
_ _
__ ___.--'_`. .'_`--.___ __
( _`.'. - 'o` ) ( 'o` - .`.'_ )
_\.'_' _.-' `-._ `_`./_
( \`. ) //\` '/\\ ( .'/ )
\_`-'`---'\\__, ,__//`---'`-'_/
\` `-\ /-' '/
` '
''')
print('\n\n---------------We can tell you if entered year is a leap or normal---------------')
year = int(input ('Please enter the year?\n'))
if year % 4 == 0:
#print ('LEAP')
if year % 100 == 0:
#print ('NORMAL')
if year % 400 == 0:
print ('LEAP')
else:
print ('NORMAL')
else:
print ('LEAP')
else:
print ('NORMAL')
#----------------------------
size = input ('Please pick a size for your pizza: S, M, L\n')
if size == 'S':
total = 15
elif size == 'M':
total = 20
else:
total = 25
pepperoni = input ('Do you want pepperony: Y or N\n')
if pepperoni == 'Y':
if size == 'S':
total += 2
else:
total += 3
else:
pass
extra_cheese = input ('Do you want extra cheese: Y or N\n')
if extra_cheese == 'Y':
total += 1
print(total)
#----------------------------
#kids name macthing game
name1=input("First name: ")
name2=input("Second name: ")
name=name1.lower()+name2.lower()
result1 = 0
for x in name:
if x in "true":
result1 += 1
else:
pass
result2 = 0
for x in name:
if x in "love":
result2 += 1
else:
pass
#print(f'Your score is: {result1}{result2}')
#change int into str
result1=str(result1)
result2=str(result2)
result =result1+result2
#change back to int
result = int(result)
if result < 10 or result > 90:
print (f'Your score is {result}, you go together like coke and mentos')
elif result > 40 and result < 50:
print (f'Your score is {result}, you are alright together')
else:
print (f'Your score is {result}')
| false
|
3a41918c0f0137427561146e947191acd06963a5
|
akash639743/Python_Assignment
|
/Dictionary.py
| 912
| 4.5
| 4
|
# Dictionary
#1. Create a Dictionary with at least 5 key value pairs of the Student
students={1:"akash",2:"rohit",3:"simran",4:"mohit",5:"sonam"}
print(students)
# 1.1. Adding the values in dictionary
students[6]="soni"
print(students)
# 1.2. Updating the values in dictionary
students.update({7: "mukesh"})
print(students)
# 1.3. Accessing the value in dictionary
x = students[3]
print(x)
# 1.4. Create a nested loop dictionary
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily)
# 1.5. Access the values of nested loop dictionary
x=myfamily["child2"]
print(x)
# 1.6. Print the keys present in a particular dictionary
print(students.keys())
print(myfamily.keys())
# 1.7. Delete a value from a dictionary
del myfamily
print(myfamily)
| true
|
b983ae86176ffd7877a2e0b6351249487a5215cd
|
akash639743/Python_Assignment
|
/Access_Modifiers.py
| 2,223
| 4.125
| 4
|
# Access Modeifiers
# 1. Create a class with PRIVATE fields
class Geek:
# private members
__name = None
__roll = None
__branch = None
# constructor
def __init__(self, name, roll, branch):
self.__name = name
self.__roll = roll
self.__branch = branch
# private member function
def __displayDetails(self):
# accessing private data members
print("Name: ", self.__name)
print("Roll: ", self.__roll)
print("Branch: ", self.__branch)
# public member function
def accessPrivateFunction(self):
# accesing private member function
self.__displayDetails()
# creating object
obj = Geek("R2J", 1706256, "Information Technology")
# calling public member function of the class
obj.accessPrivateFunction()
# 2. Create a class with PROTECTED fields and methods.
# super class
class Student:
# protected data members
_name = None
_roll = None
_branch = None
# constructor
def __init__(self, name, roll, branch):
self._name = name
self._roll = roll
self._branch = branch
# protected member function
def _displayRollAndBranch(self):
# accessing protected data members
print("Roll: ", self._roll)
print("Branch: ", self._branch)
# derived class
class Geek(Student):
# constructor
def __init__(self, name, roll, branch):
Student.__init__(self, name, roll, branch)
# public member function
def displayDetails(self):
# accessing protected data members of super class
print("Name: ", self._name)
# accessing protected member functions of super class
self._displayRollAndBranch()
# creating objects of the derived class
obj = Geek("R2J", 1706256, "Information Technology")
# calling public member functions of the class
obj.displayDetails()
# 3. Create a class with PUBLIC fields and methods.
class Geek:
# constructor
def __init__(self, name, age):
# public data mambers
self.geekName = name
self.geekAge = age
# public member function
def displayAge(self):
# accessing public data member
print("Age: ", self.geekAge)
# creating object of the class
obj = Geek("R2J", 20)
# accessing public data member
print("Name: ", obj.geekName)
# calling public member function of the class
obj.displayAge()
| true
|
eaf51afa470cdb8bb97633aa5d624075d47ba331
|
dieg0varela/holbertonschool-higher_level_programming
|
/0x06-python-classes/5-square.py
| 1,044
| 4.3125
| 4
|
#!/usr/bin/python3
"""Define class Square"""
class Square:
"""Class Square"""
def __init__(self, new_size=0):
"""Init Method load size"""
if (isinstance(new_size, int) is False):
raise TypeError("size must be an integer")
if (new_size < 0):
raise ValueError("size must be >= 0")
self.__size = new_size
def area(self):
"""Area calculation"""
return (self.__size * self.__size)
def my_print(self):
"""Print square of your size"""
if (self.__size == 0):
print()
else:
for x in range(self.__size):
for y in range(self.__size):
print("#", end='')
print()
@property
def size(self):
return self.__size
@size.setter
def size(self, val):
if (isinstance(val, int) is False):
raise TypeError("size must be an integer")
if (val < 0):
raise ValueError("size must be >= 0")
self.__size = val
| true
|
3c8374bfdcac02646aa651cb2eca1f4b79f0dbb9
|
thorenscientific/py
|
/TypeTrip/TypeTrip.py
| 422
| 4.15625
| 4
|
# A simple script demonstrating duck typing...
print "How trippy are Python Types??"
print "Let's start with x=1...."
x = 1
print "x's value:"
print x
print "x's type:"
print type(x)
print "Now do this: x = x * 1.01"
x = x * 1.01
print "x's value:"
print x
print "x's type:"
print type(x)
print "Now do this: x = x + 1*j"
x = x + 1j
print "x's value:"
print x
print "x's type:"
print type(x)
| true
|
51c28572bb0431407138dab7f4a21f68db4de271
|
luizfpq/PythonDjango
|
/Exercicios IFSP/ex3.py
| 824
| 4.15625
| 4
|
# -*- coding:utf-8 -*-
'''
@author: LuizQuirino
@contact: luizfpq@gmail.com
Exercício 3
Escreva um programa que leia do usuário o nome e RA de 3 alunos e armazene essa
informação em um dicionário, relacionando o RA ao nome do aluno
Peça ao usuário para informar um RA e exiba o nome do aluno associado
'''
from soupsieve.util import string
user1 = raw_input('Entre com o RGA do aluno 1: ')
userName1 = raw_input('Entre com nome do aluno 1: ')
user2 = raw_input('Entre com o RGA do aluno 2: ')
userName2 = raw_input('Entre com nome do aluno 2: ')
user3 = raw_input('Entre com o RGA do aluno 3: ')
userName3 = raw_input('Entre com nome do aluno 3: ')
students = {user1:userName1, user2:userName2, user3:userName3}
find = raw_input('Informe um RGA para buscar:')
print('O aluno pesquisado é: {}'.format(students[find]))
| false
|
c1ad2b3ac87e01b9a230b71b9aca5af6bb34d9ed
|
flora5/py_simple
|
/map_reduce_filter.py
| 1,062
| 4.21875
| 4
|
"""
filter(function or None, sequence) -> list, tuple, or string
Return those items of sequence for which function(item) is true. If
function is None, return the items that are true. If sequence is a tuple
or string, return the same type, else return a list.
"""
str = ['a','b','c','d']
def func(s):
if s!='a':
return s
else:
return None
print filter(func,str) #['b', 'c', 'd']
a = [1, 2, 3]
b = [4, 5, 6, 7]
c = [8, 9, 1, 2, 3]
L = map(lambda x: len(x), [a, b, c])
# L == [3, 4, 5]
"""
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
"""
# L == [3, 4, 5]
N = reduce(lambda x, y: x+y, L) # 3+4 +5
# N == 12
| true
|
c12bf91981fc6c3da928419f0db163662eea1798
|
Riverfount/pacote-desafios-pythonicos
|
/14_mimic.py
| 1,888
| 4.25
| 4
|
"""
Leia o arquivo especificado via linha de comando.
Faça um split() no espaço em branco para obter todas as palavras
no arquivo, em vez de ler o arquivo linha a linha, é mais facil obter
uma string gigante e fazer o split uma vez.
Crie um dicionario "imitador" que mapeia cada palavra que aparece no arquivo
com a lista de todas as palavras que seguem imediatamente essa palavra no
arquivo. A lista de palavras pode estar em qualquer ordem, e deve incluir
duplicatas. Por exemplo, a chave 'and' pode ter a listagem
["then","best","then","after", ...] listando todas as palavras que
vieram depois de 'and' no texto de entrada. Diremos que a string vazia
é o que vem antes a primeira palavra no arquivo.
Com o dicionario imitador é bastante simples emitir aleatoriamente texto
que imita o original. Imprima uma palavra, depois veja quais palavras podem
vir a seguir e pegue uma aleatoriamente como a proxima palavra do texto.
Use a string vazia como a primeira palavra do texto para preparar as coisas.
Se caso ficar preso em uma palavra que não está no dicionario, apenas volte
para a string vazia para manter as coisas em movimento.
PS: o módulo padrão do python 'random' conta com o
random.choice(list), método que escolhe um elemento aleatório de uma lista
não vazia.
"""
import random
import sys
def mimic_dict(filename):
"""Retorna o dicionario imitador mapeando cada palavra para a lista de
palavras subsequentes."""
# +++ SUA SOLUÇÃO +++
return
def print_mimic(mimic_dict, word):
"""Dado o dicionario imitador e a palavra inicial, imprime texto de 200 palavras."""
# +++ SUA SOLUÇÃO +++
return
# Chama mimic_dict() e print_mimic()
def main():
if len(sys.argv) != 2:
print('Utilização: ./14_mimic.py file-to-read')
sys.exit(1)
dict = mimic_dict(sys.argv[1])
print_mimic(dict, '')
if __name__ == '__main__':
main()
| false
|
f5df8af88f3449e2124e9cc0899300bc2eff9fb7
|
mzanzilla/Python-For-Programmers
|
/Files/ex3.py
| 1,239
| 4.5
| 4
|
#Updating records in a text file
#We want to update the name for record number 300 - change name from White to Williams
#Updating textfiles can affect formattting because texts may have varrying length.
#To address this a temporary file will be created
import os
tempFile = open("tempFile.txt", "w")
accounts = open("accounts.txt", "r")
#The 'with' statement manages two resource objects
with accounts, tempFile:
#Loop through each line or record in the text file
for record in accounts:
#I split and unpack each line into variables
account, name, balance = record.split()
#If the account number is not equal to the record number 300, I want to put that record (or line)
#in a temporary text file else I want to join the existing record with the name "Williams" to create
#a new record
if account != "300":
tempFile.write(record)
else:
newRecord = ' '.join([account, "Williams", balance])
tempFile.write(newRecord + "\n")
#delete the accounts text file
#remove should be used with caution as it does not warn you about deleting a file
os.remove("accounts.txt")
#rename tempFile to accounts.txt
os.rename("tempFile.txt", "accounts.txt")
| true
|
17ee83f78ffc75ddc60789152a67d32531fff727
|
mzanzilla/Python-For-Programmers
|
/Exceptions/ex1.py
| 656
| 4.375
| 4
|
#demonstrating how to handle a division by zero exception
while True:
#attempt to convert and divide values
try:
number1 = int(input("Enter numerator: "))
number2 = int(input("Enter denuminator: "))
result = number1 / number2
except ValueError: #Tried to convert non-numeric value to integer
print("You must enter two integers\n")
except ZeroDivisionError: #denominator was zero
print("Attempted to divide by zero\n")
else:
print(f"{number1:.3f}/{number2:.3f} = {result:.3f}")
break #If no exceptions occur print the numerater/denominator and the result and terminate the program
| true
|
4461ea009cb18cfc2b7167372e5d31c1a8e35c2f
|
tmemud/Python-Projects
|
/ex72.py
| 1,110
| 4.40625
| 4
|
# Use the file name mbox-short.txt as the file name
#7.2 Write a program that prompts for a file name, then opens that file and reads through the file,
#looking for lines of the form: X-DSPAM-Confidence: 0.8475
#Count these lines and extract the floating point values from each of the lines and
#compute the average of those values and produce an output as shown below.
#Do not use the sum() function or a variable named sum in your solution.
#You can download the sample data at http://www.py4e.com/code3/mbox-short.txt
#when you are testing below enter mbox-short.txt as the file name.
#Average spam confidence: 0.750718518519
fname = input("Enter file name: ")
fh = open(fname)
count = 0
add = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
sval = line.find(":")
numbers = line[sval+2 : ]
fval = float (numbers)
add += fval
count += 1
average = add/count
print("Average spam confidence:", average)
#count = count + 1
#print(count)
#print(line)
#print (count)
#print("Done")
| true
|
a7351fb387a69885aad636368da7e110c0ec1696
|
crossihuy/MyRepo
|
/idk_with_loops.py
| 353
| 4.15625
| 4
|
my_list = []
while True:
question = input("Do you want to add a name: \ny|n: ").lower()
if question == "y" or question == "":
my_list.append(input("Give me a friend's name: "))
continue
elif question == "n":
break
else:
print("You did not select y or n")
for i in my_list:
print(i + " is my friend")
| false
|
21e4f6682d558e19baf340cf753df5d1f9516f45
|
harushimo/python_programs
|
/month_validator.py
| 304
| 4.125
| 4
|
#!/usr/bin/python
months = ['January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December']
def valid_month:
for i in months:
if(i.lower() == months.lower()):
return i
print valid_month("January")
print valid_month("january")
| false
|
230305855dd6284c061fc408a7805931cb0cb7c8
|
juanall/Informatica
|
/TP2.py/2.14.py
| 703
| 4.125
| 4
|
#Ejercicio 14
#Creá una función que calcule la temperatura media de un día a partir de la
# temperatura máxima y mínima. Escribí un programa principal, que utilizando
# la función anterior, vaya pidiendo la temperatura máxima y mínima de cada
# día y vaya mostrando la media. El programa tiene que pedir el número de días
# que se van a introducir.
def calcularTemperaturaMedia(temp1,temp2):
return (temp1 + temp2)/2
cantidad=int(input("¿Cuántas temperaturas vas a calcular?:"))
for indice in range(cantidad):
tmin = float(input("Introduce temperatura mínima:"))
tmax = float(input("Introduce temperatura máxima:"))
print("Temperatura media:",calcularTemperaturaMedia(tmin,tmax))
| false
|
b527e70db8dd5f3cf9afa0047c9a4140cbb94e82
|
bkoehler2016/python_projects
|
/forloop.py
| 458
| 4.28125
| 4
|
"""
a way to print objects in a list
"""
a = ["Jared", 13, "Rebecca", 14, "Brigham", 12, "Jenn", 3, "Ben", 4]
# printing the list using * operator separated
# by space
print("printing the list using * operator separated by space")
print(*a)
# printing the list using * and sep operator
print("printing lists separated by commas")
print(*a, sep = ", ")
# print in new line
print("printing lists in new line")
print(*a, sep = "\n")
| true
|
9257561acddd02bd56de08bd1122f91c14000de5
|
yuanchangwang/cheshi
|
/L04(下)迭代器、map、reduce、sorted、filter、列表、字典、集合推导式、生成器函数/课件/8.生成器.py
| 1,018
| 4.25
| 4
|
# ### 生成器 元组推导式是生成器(generator)
'''
定义:生成器可以实现自定义,迭代器是系统内置的,不能够更改
生成器的本质就是迭代器,只不过可以自定义.
生成器有两种定义的方式:
(1) 生成器表达式 (里面是推导式,外面用圆括号)
(2) 生成器函数
'''
# (1) 元组推导式的形式来写生成器
gen = (i * 2 for i in range(5))
print(gen)
from collections import Iterator
print(isinstance(gen,Iterator))
# (2)使用for循环进行调用
for i in gen:
print(i)
# (3)还可以使用next进行调用
gen = (i * 2 for i in range(5))
res = next(gen)
print(res)
res = next(gen)
print(res)
res = next(gen)
print(res)
res = next(gen)
print(res)
res = next(gen)
print(res)
# res = next(gen) # error 越界错误 next调用生成器 是单向不可逆的过程.
# print(res)
# (4) 利用for 和next 配合使用 调用生成器
gen = (i * 2 for i in range(5))
for i in range(3):
res = next(gen)
print(res)
| false
|
3725f3519dcaaa993db6aabb5eb7f225798e2b09
|
yuanchangwang/cheshi
|
/L04(下)迭代器、map、reduce、sorted、filter、列表、字典、集合推导式、生成器函数/课件/4.sorted.py
| 1,112
| 4.25
| 4
|
# ### sorted
'''
sorted(iterable,reverse=False,key=函数)
功能:排序
参数:
iterable:可迭代性数据(常用:容器类型数据,range对象,迭代器)
reverse : 是否倒序
默认正序reverse= False(从小到大) 如果reverse=True 代表倒序 (从大到小)
key = 自定义函数 或者 内置函数
返回值:
排序的序列
'''
listvar = [1,2,-88,-4,5]
# 按照从小到大默认排序
res = sorted(listvar)
print(res)
# 从大到小排序
res = sorted(listvar,reverse=True)
print(res)
# 按照绝对值排序 (内置函数abs)
'''
abs 绝对值函数
'''
res = abs(-1.5)
print(res)
listvar = [1,2,-88,-4,5]
res = sorted(listvar,key=abs)
print(res)
'''
abs(1) => 1
abs(2) => 2
abs(-4) => 4
abs(5) => 5
abs(-88) => 88
'''
# 按照余数排序 (自定义函数)
listvar = [19,23,44,57]
def func(n):
return n % 10
res = sorted(listvar,key=func)
print(res)
'''
23 => 3
44 => 4
57 => 7
19 => 9
'''
listvar = [4,1,2,9]
listvar.sort()
print(listvar)
'''
# sort 基于原有列表进行修改
# sorted 是产生一个新列表
除此之外,所有用法全都相同
'''
| false
|
946013b211c5d2f35e399817d567c3bd267006a0
|
johnnyshi1225/leetcode
|
/problems/21_Merge_Two_Sorted_Lists.py
| 2,069
| 4.125
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#########################################################################
# Author: Johnny Shi
# Created Time: 2018-09-14 13:17:08
# File Name: 21_Merge_Two_Sorted_Lists.py
# Description:
#########################################################################
from simple_linked_list import ListNode, linked_list, print_linked_list
class Solution:
def mergeTwoLists1(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = None
tail = None
if not l1 and not l2:
return None
if l1 and not l2:
head = l1
return head
elif l2 and not l1:
head = l2
return head
while l1 and l2:
if l1.val <= l2.val:
if not head:
head = l1
tail = l1
else:
tail.next = l1
tail = l1
l1 = l1.next
else:
if not head:
head = l2
tail = l2
else:
tail.next = l2
tail = l2
l2 = l2.next
if l1:
tail.next = l1
elif l2:
tail.next = l2
return head
# 简洁版本
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = tail = ListNode(0)
while l1 and l2:
if l1.val <= l2.val:
tail.next = l1
l1 = l1.next
else:
tail.next = l2
l2 = l2.next
tail = tail.next
if l1:
tail.next = l1
elif l2:
tail.next = l2
return head.next
head1 = linked_list([1, 2])
head2 = linked_list([1, 2, 3, 4])
ret = Solution().mergeTwoLists(head1, head2)
print_linked_list(ret)
# vim: set expandtab ts=4 sts=4 sw=4 :
| false
|
091ad70053e25fc51ac502a53946d36d96219715
|
OctaveC/holbertonschool-higher_level_programming
|
/0x07-python-test_driven_development/5-text_indentation.py
| 566
| 4.375
| 4
|
#!/usr/bin/python3
"""
This is a module that prints a text with 2 new lines
after each of these characters: ., ? and :
"""
def text_indentation(text):
""" This function indents text based on special characters """
if type(text) is not str:
raise TypeError("text must be a string")
leap = True
for char in text:
if not (char is ' ' and leap is True):
print(char, end="")
leap = False
if char in [':', '.', '?']:
print()
print()
leap = True
| true
|
183e49a5349c95ef8196ad65754fec65fedf3a35
|
Invecklad-py/New_start
|
/What_is_your_name_input.py
| 295
| 4.125
| 4
|
first_name = input("What's your first name?")
last_name = input("What's your last name?")
answer = input("So your name is " + first_name + " " + last_name + "?")
if answer == "yes":
print("Great!")
if answer == "no":
print("I'm sorry we got that wrong, please try again")
| true
|
104df48126c81aaade444844a5c67c501a98126a
|
Lumiras/Treehouse-Python-Scripts
|
/Beginning_python/general_exercises/shopping_list_4.py
| 2,236
| 4.125
| 4
|
shopping_list = []
def clear_list():
confirm = input("Are you sure you want to completely clear the list?\nThere is no way to undo this!\nType YES to confirm ")
if confirm == 'YES':
del shopping_list[:]
def move_item(idx, mov):
index = idx - 1
item = shopping_list.pop(index - 1)
shopping_list.insert(mov, item)
def remove_item(idx):
index = idx - 1
item = shopping_list.pop(index)
print("Removed {} ".format(item))
def show_help():
print("\nSeparate each item with a comma")
print("Type DONE to quit\nType SHOW to see the current list\nType HELP to get this message\nType REMOVE to delete an item")
def show_list():
if len(shopping_list) > 0:
count = 1
for item in shopping_list:
print("{} -> {}".format(count, item))
count += 1
else:
print("\nYour shopping list is currently empty")
def prompt():
print("\nGive me a list of things you want to shop for: ")
show_help()
while True:
prompt()
new_stuff = input(">>")
if new_stuff == "DONE":
print("\nHere's your list:")
show_list()
break
elif new_stuff == "HELP":
show_help()
continue
elif new_stuff == "SHOW":
show_list()
continue
elif new_stuff == "REMOVE":
show_list()
idx = input("Which item do you want to remove? ")
remove_item(int(idx))
continue
elif new_stuff == "MOVE":
show_list()
idx = input("Which item do you want to move? ")
mov = input("Where do you want to move the item? ")
move_item(int(idx), int(mov))
elif new_stuff == "CLEAR":
clear_list()
else:
new_list = new_stuff.split(",")
index = input("Add this at a certain spot? Press ENTER to insert at the end of the list "
"\nor give me a number to place it at a certain spot. You currently have {} items in your list: ".format(len(shopping_list)))
if index:
spot = int(index)-1
for item in new_list:
shopping_list.insert(spot, item.strip())
spot += 1
else:
for item in new_list:
shopping_list.append(item.strip())
| true
|
04f1caf80aaf3699dfe4e525c7f69909c5a33476
|
clarencekwong/CSCA20-B20
|
/e4.py
| 1,672
| 4.15625
| 4
|
import doctest
def average_list(M):
'''(list of list of int) -> list of float
Return a list of floats where each float is the average of the
corresponding list in the given list of lists.
>>> M = [[0,2,1],[4,4],[10,20,40,50]]
>>> average_list(M)
[1.0, 4.0, 30.0]
>>> M = []
>>> average_list(M)
[]
'''
new = []
for i in range(len(M)):
avg = sum(M[i])/len(M[i])
new.append(avg)
return new
def increasing(L):
'''(list of int) -> bool
Return True if the given list of ints is in increasing order and
False otherwise.
>>> increasing([4,3,2,1])
False
>>> increasing([2,4,6,8])
True
>>> increasing([0,0,1,2])
False
>>> increasing([3])
True
>>> increasing([1,2,4,3])
False
'''
index = 0
while index < (len(L)-1):
if L[index] >= L[index+1]:
return False
index += 1
return True
def merge(L1, L2):
'''(list of int, list of int) -> (list of int)
Return a list of ints sorted in increasing order that is the merge
of the given sorted lists of integers.
>>> merge([0,2,4],[1,3,5])
[0, 1, 2, 3, 4, 5]
>>> merge([2,4],[1,2,4])
[1, 2, 2, 4, 4]
>>> merge([0,1,2],[3,4])
[0, 1, 2, 3, 4]
>>> merge([],[1,3,4])
[1, 3, 4]
'''
new_lst = []
while L1 and L2:
if L1[0] < L2[0]:
new_lst.append(L1.pop(0))
elif L1[0] > L2[0]:
new_lst.append(L2.pop(0))
else:
new_lst.append(L1.pop(0))
new_lst.append(L2.pop(0))
return new_lst + L1 + L2
if __name__ == '__main__':
doctest.testmod(verbose=True)
| true
|
27ff7f866f125b4930facd5f7f28d04e151b0f79
|
pinardy/Digital-World
|
/Week 3/wk3_hw4.py
| 622
| 4.21875
| 4
|
def isPrime(x):
if x==2:
return True
elif x<2 or x % 2 == 0:
return False
elif x==2:
return True
else:
return all(x % i for i in xrange(2, x))
#all function: Return True if all elements of the iterable are true
#(or if the iterable is empty).
#range returns a Python list object and xrange returns an xrange object.
print 'isPrime(2)'
ans=isPrime(2)
print ans
print 'isPrime(3)'
ans=isPrime(3)
print ans
print 'isPrime(7)'
ans=isPrime(7)
print ans
print 'isPrime(9)'
ans=isPrime(9)
print ans
print 'isPrime(21)'
ans=isPrime(21)
print ans
| true
|
6435a57030eda2023e17f57b4c127cce9c45163c
|
TheManTheLegend1/python_Projects
|
/updateHand.py
| 2,062
| 4.1875
| 4
|
import random
import string
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
def getFrequencyDict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
#
# Problem #1: Scoring a word
#
def displayHand(hand):
"""
Displays the letters currently in the hand.
For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in hand.keys():
for j in range(hand[letter]):
print letter, # print all on the same line
print # print an empty line
def dealHand(n):
"""
Returns a random hand containing n lowercase letters.
At least n/3 the letters in the hand should be VOWELS.
Hands are represented as dictionaries. The keys are
letters and the values are the number of times the
particular letter is repeated in that hand.
n: int >= 0
returns: dictionary (string -> int)
"""
hand={}
numVowels = n / 3
for i in range(numVowels):
x = VOWELS[random.randrange(0,len(VOWELS))]
hand[x] = hand.get(x, 0) + 1
for i in range(numVowels, n):
x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
hand[x] = hand.get(x, 0) + 1
return hand
userHand = {'e': 2, 'h': 1, 'n': 1, 'u': 1, 't': 3, 'w': 1, 'y': 1}
def updateHand(hand, word):
h = hand.copy()
for letter in word:
if h[letter] >= 0:
h[letter] -= 1
return h
print updateHand(userHand, 'teeth')
| true
|
890f47b04fe5db62dcdc5a6bc571c343c7ea75a9
|
TheManTheLegend1/python_Projects
|
/Silly.py
| 255
| 4.1875
| 4
|
#Silly Strings
#Deonstrates string concatenation and repetition
print("You can concatenate two " + "stringswith the '+' operator.")
print("\nThis string" + "may not " + "seemterr" + "ibly impressive. " \
+ "But what " + "you dont know" + " is that\n ")
| false
|
534022b24a83574867a9ff27f6b88e9a5fde56a3
|
SUNIL-KUDUPUDI-1644/sunil1
|
/ck3.py
| 248
| 4.21875
| 4
|
char=input("enter a char=\n")
if (char>='a' and char <='z') or (char>'A' and char<'Z'):
if char=='a' or char=='e' or char=='i' or char=='o' or char=='u':
print("vowel")
else:
print("const")
else:
print("invalid syntax")
| false
|
d1dbff287e9541cab7ec2f46958e0990ccc73eb6
|
Arya16ap/moneyuyyyyyof.py
|
/countingWords.py
| 403
| 4.125
| 4
|
introString = input("enter your introduction: ")
characterCount = 0
wordCount = 1
for i in introString:
characterCount=characterCount+1
if(i==' '):
wordCount = wordCount+1
characterCount = characterCount-1
if(wordCount<5):
print("invalid intro")
print("no. of words in the string: ")
print(wordCount)
print("no. of letters in the string: ")
print(characterCount)
| true
|
99355b9314b27ebb7d7ec5a4c523cdeaaf3e97fd
|
NAMELEZS/Python_Programs
|
/length_function.py
| 248
| 4.15625
| 4
|
### 03/28/2021
### Norman Lowery II
### How to find the length of a list
# We can use the len() fucntion to find out how long a list is
birthday_days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
print(len(birthday_days))
| true
|
4f247571b9e29902cdfab301b0b2039e6c0e3d3b
|
lebronjames2008/python-invent
|
/w3schools/Scopes.py
| 799
| 4.375
| 4
|
# A variable is only available from inside the region it is created. This is called scope.
def myfunc():
x = 300
print(x)
myfunc()
# A variable created inside a function is available inside that function
x = 300
def myfunc():
print(x)
myfunc()
print(x)
# Printing 2 300's
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)
# The function will print the local x, and then the code will print the global x:
def myfunc():
global x
x = 300
myfunc()
print(x)
# Another way to print with global
# Also, use the global keyword if you want to make a change to a global variable inside a function.
x = 300
def myfunc():
global x
x = 200
myfunc()
print(x)
# To change the value of a global variable inside a function, refer to the variable by using the global keyword:
| true
|
469cf9247ced31818e7060426dfb7f1f67d91ad6
|
lebronjames2008/python-invent
|
/w3schools/Inheritance.py
| 1,945
| 4.34375
| 4
|
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
# Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
#Use the pass keyword when you do not want to add any other properties or methods to the class.
class Student(Person):
pass
# In student class, you are borrowing parent classes things and just doing it in a easier way, so basically its inheriting from the parent class.
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
x = Student("Mike", "Olsen")
x.printname()
# Python also has a super() function that will make the child class inherit all the methods and properties from its parent
# By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
x = Student("Mike", "Olsen")
x.printname()
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
x = Student("Mike", "Olsen", 2019)
x.welcome()
| true
|
a5a700f7fa77777ea9a3c65669d67f0fd4313dd0
|
lebronjames2008/python-invent
|
/chapter9/testlist1.py
| 706
| 4.34375
| 4
|
names_list = ['sibi', 'rahul', 'santha', 'scott', 'james']
# print all the elements in the list
print(names_list)
# print the 4th index of the list
print(names_list[4])
print(names_list[-5])
thislist = ["apple", "banana", "cherry"]
print(thislist)
thislist[1] = "blackcurrant"
print(thislist)
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
# find the size of the list
print(len(names_list))
# append is adding a new element to the end of the list
names_list.append('rishi')
print(names_list)
names_list.insert(3, 'jeremy')
print(names_list)
# The pop() method removes the specified index, (or the last item if index is not specified):
names_list.pop()
print(names_list)
| true
|
7da6111a2ac0a3d281c0e615e69683aebcf6cae2
|
AlbertoLG1992/AprendiendoPython
|
/Ejemplos/3-TiposDeDatosNumericos/TipoDatosBooleanos.py
| 622
| 4.25
| 4
|
# Los operadores booleanos son:
# or : ||
# and : &&
# not : para negar
x = True
y = False
if(x and not y):
print("ok")
else:
print("no")
# Para comparar listas tenemos all y any
# all(iterador) : Recibe un iterador, por ejemplo una lista,
# y devuelve True si todos los elementos son verdaderos o el iterador está vacío.
if(all([1, True, [1, 2]])):
print("all ok")
else:
print("all no")
# any(iterador) : Recibe un iterador, por ejemplo una lista,
# y devuelve True si alguno de sus elemento es verdadero, sino devuelve False.
if(any([1, False, [1, 2]])):
print("any ok")
else:
print("any no")
| false
|
27e08ae25f106d0179bff869f02855717cd417dd
|
AlbertoLG1992/AprendiendoPython
|
/Ejemplos/5-TipoDatosSecuencia/Listas.py
| 1,152
| 4.4375
| 4
|
# Las listas ( list ) me permiten guardar un conjunto de datos que se pueden repetir y
# que pueden ser de distintos tipos. Es un tipo mutable.
'''
SLICE
Para optener un rango dentro de una lista:
lista[start:end] # Elementos desde la posición start hasta end-1
lista[start:] # Elementos desde la posición start hasta el final
lista[:end] # Elementos desde el principio hata la posición end-1
lista[:] # Todos Los elementos
lista[start:end:step] # Igual que el anterior pero dando step saltos.
Se pueden utilizar también índices negativos, por ejemplo: lista[::-1]
'''
# Con la función enumerate enumera la lista y devuelve un objeto como tupla
seasons = ['Primavera', 'Verano', 'Otoño', 'Invierno']
print(list(enumerate(seasons)))
# Si se quiere empezar en un número concreto es de la siguiente forma
print(list(enumerate(seasons, start=1)))
# Para copiar una lista sin copiar el id al que referencia es mediante slice
seasons2 = seasons[:]
# Listas bidimensionales
tabla = [[1,2,3],[4,5,6],[7,8,9]]
print(tabla[1][1])
# Recorrer una lista bidimensional
for fila in tabla:
for elem in fila:
print(elem, end=" ")
print()
| false
|
71039d8b5847e341112b2194918eebe219589a40
|
vlad-zankevich/LearningPython
|
/album.py
| 1,222
| 4.1875
| 4
|
def run():
# Theme with function
def make_album(singer_name, album_name, track_number=''):
"""This function will make the dictionary with your album"""
# Album dictionary, empty in default
album = {}
# You can enter quantity of tracks in album if you want
if track_number:
album['track number'] = track_number
# Here you enter singer name
album['singer name'] = singer_name
# Here you enter album name
album['album name'] = album_name
# The dictionary with entering data returns
return album
users_dict = {}
while True:
user_name = input("Please, enter your name: ")
user_album = make_album(input("Enter singer or group name: "),
input("Enter album name: "),
input("If you want, enter track numbers"
"\nIf not, just press 'Enter': "))
users_dict[user_name] = user_album
message = input("Print 'q' if you don't want to continue: ")
# Exit from cycle
if message == 'q':
break
print(users_dict)
if __name__ == "__main__":
run()
| true
|
a900892c18dfd7679221269c3a7d8cfe3a1586a7
|
mblahay/blahay_standard_library
|
/regexp_tools.py
| 1,129
| 4.25
| 4
|
import re
import itertools
import blahay_standard_library as bsl
def regexp_like(args, argp):
'''
A simple wrapper around the re.search function. The result
of that function will be converted to a binary True/False.
This function will return a simple True or False, no match object.
Parameters:
-----------
args - This is the string argument which is to be searched.
argp - This is the pattern that is used when searching args
'''
return bool(re.search(argp, args)) # Simply execute the search method using the string and pattern,
# then interpret the existance of a returned match object into
# a True of False using the bool constructor.
def regexp_substr():
pass
def regexp_replace():
pass
def regexp_parse(args, pat):
'''
Separate the string args by pat and denote which elements are
a pattern match and which ones are not.
'''
x=zip(re.split(pat,args),itertools.repeat(False))
y=zip(re.findall(pat,args),itertools.repeat(True))
return bsl.interleave(x,y)
| true
|
322747201ef9fe9aa660c5a8831e396266789520
|
Santhosh-27/Practice-Programs
|
/N_day_profit_sell_k_times.py
| 1,317
| 4.34375
| 4
|
'''
Stock Buy Sell to Maximize Profit
The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days.
For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying on day 0, selling on day 3.
Again buy on day 4 and sell on day 6. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.
'''
# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
def stockBuySell(price, n):
# Prices must be given for at least two days
if (n == 1):
return
i=0
profit = 0
while(i<n-1):
while(i<n-1 and price[i+1]<=price[i]):
i += 1
buy = i
i += 1
while(i<n and price[i]>=price[i-1]):
i += 1
sell = i-1
profit = price[buy]+price[sell]
print("Buy on day:"+str(buy)+" and sell on day:"+str(sell))
print("Total Profit:"+str(profit))
# Driver code
# Stock prices on consecutive days
#price = [100, 180, 260, 310, 40, 535, 695]
price = [1,5,2,3,7,6,4,5]
n = len(price)
# Fucntion call
stockBuySell(price, n)
| true
|
095cf2d2b9c6d71f606901fc6c3aef5ab75b0ac7
|
bc-townsend/aco_example
|
/aco_example/path.py
| 2,145
| 4.40625
| 4
|
import pygame
from math import sqrt
class Path:
"""Represents a path object. These are connections between nodes.
"""
def __init__(self, color, node1, node2):
"""Initialization method for a path object.
Args:
color: The color of this path.
node1: One of the nodes to be connected as neighbors.
node2: The other node to be connected as neighbors.
"""
self.color = color
self.node1 = node1
self.node2 = node2
self.start_pos = node1.rect.center
self.end_pos = node2.rect.center
self.width = 30
# Pheromone value determines how likely an ant is to travel along this path.
self.pheromone = 1
self.phero_evap = 0.1
self.font = pygame.font.SysFont('Arial', 28)
def get_dist(self, node_size):
"""Returns the length/distance of this path.
Args:
node_size: Used to calculate the distance so that the numbers are not incredibly large due to pixel measurements.
"""
x_diff = self.node2.rect.centerx - self.node1.rect.centerx
y_diff = self.node2.rect.centery - self.node1.rect.centery
return sqrt(x_diff ** 2 + y_diff ** 2) / node_size
def draw(self, surface):
"""Draws this path on the specified surface.
Args:
surface: The pygame surface to draw this path on.
"""
pygame.draw.line(surface, self.color, self.start_pos, self.end_pos, self.width)
center_point = ((self.end_pos[0] + self.start_pos[0]) / 2, (self.end_pos[1] + self.start_pos[1]) / 2)
text = self.font.render(f'{round(self.get_dist(80), 1)}', True, (255, 255, 255))
surface.blit(text, center_point)
def phero_evaporation(self):
"""Controls how much pheromone this path loses.
"""
self.pheromone -= (self.pheromone * self.phero_evap)
def __eq__(self, obj):
return isinstance(obj, Path) and self.node1 is obj.node1 and self.node2 is obj.node2
def __str__(self):
return f'Path {self.node1.node_id}->{self.node2.node_id}. Phero: {self.pheromone}'
| true
|
9163e5b356aa777c64151d0cb77dd76e464ba1a7
|
robertpvk/phyton-base
|
/lesson1/task1.py
| 1,958
| 4.15625
| 4
|
"""
ЗАДАНИЕ 1
Человеко-ориентированное представление интервала времени
Спросить у пользователя размер интервала (в секундах). Вывести на экран строку в зависимости от размера интервала:
1) до минуты: <s> сек;
2) до часа: <m> мин <s> сек;
3) до суток: <h> час <m> мин <s> сек;
4) сутки или больше: <d> дн <h> час <m> мин <s> сек
Например, если пользователь введет 4567 секунд, вывести:
1 час 16 мин 7 сек
"""
print('Привет! Давай посчитаем твое время, которое у тебя есть:)')
seconds = int(input('Просто введи свой интвервал в секундах\n'))
year = seconds // 31536000
month = (seconds // 2592000) % 12
day = (seconds // 86400) % 31
hour = (seconds // 3600) % 24
minute = (seconds // 60) % 60
second = seconds % 60
if seconds < 60:
print('Итак, у тебя ', second, 'сек')
elif 60 >= seconds < 3600:
print('Итак, у тебя ', minute, 'мин', second, 'сек')
elif 3600 >= seconds < 86400:
print('Итак, у тебя ', hour, 'ч', minute, 'мин', second, 'сек')
elif 86400 >= seconds < 2592000:
print('Итак, у тебя ', day, 'д', hour, 'ч', minute, 'мин', second, 'сек')
elif 2592000 >= seconds < 31536000:
print('Итак, у тебя ', month, 'мес', day, 'д', hour, 'ч', minute, 'мин', second, 'сек')
elif seconds >= 31536000:
print('Итак, у тебя ', year, 'г', month, 'мес', day, 'д', hour, 'ч', minute, 'мин', second, 'сек')
"""
Можно ли было просто написать так?
print('Итак, у тебя ', year, 'г', month, 'мес', day, 'д', hour, 'ч', minute, 'м', second, 'с')
"""
| false
|
8fd16d1053d689bd3068035610b8250213ee3c45
|
robertpvk/phyton-base
|
/lesson3/task1.py
| 974
| 4.28125
| 4
|
"""
1. Написать функцию num_translate(), переводящую числительные от 0 до 10 c английского на русский язык. Например:
>>> >>> num_translate("one")
"один"
>>> num_translate("eight")
"восемь"
Если перевод сделать невозможно, вернуть None. Подумайте, как и где лучше хранить информацию, необходимую для перевода:
какой тип данных выбрать, в теле функции или снаружи.
"""
numbers = {
'One': 'Один',
'Two': 'Два',
'Three': 'Три',
'Four': 'Четыре',
'Five': 'Пять',
'Six': 'Шесть',
'Seven': 'Семь',
'Eight': 'Восемь',
'Nine': 'Девять',
'Ten': 'Десять'
}
def num_translate(word):
return numbers.get(word)
print(num_translate("Five"))
print(num_translate("Eleven"))
| false
|
33901933c76acda3b74577e52e989c1e4d4e34a8
|
NiteshKumar14/MCA_SEM_1
|
/Assignments/OOPs pythonn/synonym_using_existing_dict.py
| 1,495
| 4.46875
| 4
|
# create an empty my_dictionary
my_my_dict={
"sad":"sure",
"depressed":"Sad",
"Dejected":"Sad",
"Heavy":"Sad",
"Amused":"Happy",
"Delighted":"Happy",
"Pleased":"Happy",
"Annoyed":"Angry",
"Agitated":"Angry",
"Mad":"Angry",
"Determined":"Energized",
"Creative":"Energized",
}
def display(dict):
iterator=1
for keys,values in dict.items():
print(iterator,"\t\t",keys,"\t\t",values)
iterator+=1
def key_found(key):
for k in my_dict.keys():
if k==key:
return True
return False
# def display(my_dict):
# for k in my_dict.keys():
# print(k,"type ",type(k))
# print("hello MR.X \n just enter number of words then follow the format. \n you are good to go \n we will take care of your synonym dairy ")
my_dict={}
#input number of words with their coreesponding meaning
no_of_words=int(input("Number of words: "))
#creating a my_dictionary with key as meaning and values as list of words
print("enter in format words : meaning")
#loop until all words are entered
while(no_of_words):
word=input()
meaning=input(":")
#display(my_dict)
#if my_dict is empty:
if key_found(meaning):
#print("key found")
my_dict[meaning].append(word)
#display(my_dict)
else:
my_dict[meaning]=list()
my_dict[meaning].append(word)
display(my_dict)
no_of_words-=1
iterator=1
print("Page\t\tMeaning\t\tSynonymns)")
| true
|
b08167b84bd467cc501f5b59165ca3ef8c100f38
|
NiteshKumar14/MCA_SEM_1
|
/Assignments/OOPs pythonn/happy_sum_of_squares.py
| 2,261
| 4.125
| 4
|
def sum_of_squares(sqdnumber): #defining a function that take a string and return its elements sum
sqdNumber_result=0 #initializing sum array for storing sum
iteratator=len(sqdnumber)-1 #iterating till the length of string in descending order
if not iteratator: #if the length of string is 1(here iterator will be zero)
return int(sqdnumber[0])**2
while iteratator: #looping digits
sqdNumber_result+=int(sqdnumber[iteratator])**2
iteratator-=1
if(iteratator==0): #for the last index(0) as loop will exit now
sqdNumber_result+=int(sqdnumber[iteratator])**2
return sqdNumber_result
def happy_number(number): #happy function determines whether a number is happy or not
iterator=10 #performing 10 iteration to prevent infinite loop.
if sum_of_squares(number)==1: #edge case if the number sum of squares is 1
return True
while iterator:
number=sum_of_squares(str(number)) #storing the sum of squares of the number
if sum_of_squares(str(number))==1: #condition for happy number
return True
iterator-=1
return False
# test_case=int(input("test_cases:\t")) #taking input as string
number=input()
print("sum of squares :",sum_of_squares(number)) #invoking sum of squares function
if happy_number(number) :
print("Its a Happy Number")
else:
print("Not a Happy Number ")
# number=input("enter a number:\t")
# if happy_number(str(iterator)):
# print(sum_of_squares(str(iterator)),"\t",end='')
# print(iterator)
# # print("Its a Happy Number\t")
# # else:
# # print("Not a Happy Number\t")
# test_case-=1
| true
|
4eaf701470c01077f14e5491eecd6282bb0e61c8
|
freebrains/Python_basics
|
/Lesson_5.1.py
| 563
| 4.4375
| 4
|
"""
Создать программно файл в текстовом формате, записать в него построчно данные,
вводимые пользователем. Об окончании ввода данных свидетельствует пустая строка.
Create with a program file in text format and write the data entered by the user line
by line. An empty string indicates the end of data entry.
"""
first_task = open("lesson_5.txt", 'a')
first_task.write(input("Enter a word - ") + "\n")
first_task.close()
| false
|
5f5df0b3966bb1a5c613d0c4f6e4f524cee0c742
|
freebrains/Python_basics
|
/Lesson_3.3.py
| 580
| 4.3125
| 4
|
"""
Реализовать функцию my_func(), которая принимает три позиционных
аргумента, и возвращает сумму наибольших двух аргументов.
Implement the my_func () function, which takes three positional
arguments, and returns the sum of the largest two arguments.
"""
def my_func(var_1=int(input("Enter first number - ")), var_2=int(input("Enter second number - ")),
var_3=int(input("Enter third number - "))):
return sorted([var_1, var_2, var_3])[1:]
print(sum(my_func()))
| true
|
a3b0f1df4ea0fefeba0f39fd5669d5a364d508da
|
freebrains/Python_basics
|
/Lesson_8.4.py
| 2,319
| 4.34375
| 4
|
"""
Начните работу над проектом «Склад оргтехники». Создайте класс, описывающий склад. А также класс «Оргтехника»,
который будет базовым для классов-наследников. Эти классы — конкретные типы оргтехники (принтер, сканер, ксерокс).
В базовом классе определить параметры, общие для приведенных типов. В классах-наследниках реализовать параметры,
уникальные для каждого типа оргтехники.
Start working on the "office equipment Warehouse" project. Create a class that describes the warehouse. As well as
the "office equipment" class, which will be the base class for successor classes. These classes are specific
types of office equipment (printer, scanner, copier). In the base class, define parameters that are common to the
given types. In the successor classes, implement parameters that are unique for each type of office equipment.
"""
data = []
class Orgtech:
def __init__(self, weight, place, name, qty):
self.weight = weight
self.place = place
self.name = name
self.quantity = qty
self.store_data()
def store_data(self):
data.append(self.__dict__)
class Printer(Orgtech):
def __init__(self, weight, place, name, qty, print_time, form):
super().__init__(weight, place, name, qty)
self.time = print_time
self.form = form
class Scanner(Orgtech):
def __init__(self, weight, place, name, qty, scan_resolution, scan_color):
super().__init__(weight, place, name, qty)
self.resolution = scan_resolution
self.color = scan_color
class Xerox(Orgtech):
def __init__(self, weight, place, name, qty, speed, screen):
super().__init__(weight, place, name, qty)
self.speed = speed
self.screen = screen
printer_1 = Printer(5, 'office', 'Canon 1060', 10, 2, 'A4')
printer_2 = Printer(10, 'library', 'Xerox 2000', 1, 1, 'A3')
scanner_1 = Scanner(6, 'office', 'Scanit 500', 15, 1080, 'color')
xerox_1 = Xerox(25, "account", "MFP Xerox", 4, 12, 'color')
print(data)
| false
|
9dec69e9d104c4011702af47bd2cc816109852ff
|
freebrains/Python_basics
|
/Lesson1.4.py
| 664
| 4.21875
| 4
|
'''
Пользователь вводит целое положительное число.
Найдите самую большую цифру в числе. Для решения
используйте цикл while и арифметические операции.
The user enters integer. Find the largest digit
in the number. Use while cycle and arithmetic
operations.
'''
number = int(input("Enter the number - "))
a = number % 10
high = a
while True:
number = number // 10
if number % 10 != 0:
a = number % 10
if a >= high:
high = a
else:
high = high
continue
else:
break
print(high)
| false
|
1d40d049794faa916c6f4a845d138e1b02ae8ef7
|
jamilcse13/python-and-flask-udemy
|
/16. whileLoop.py
| 598
| 4.1875
| 4
|
count = 0
while count<10:
count += 1
print("count=", count)
print("good bye!")
## while loop else statement
count = 0
while count<10:
print(count, "is less than 10")
count += 1
else:
print(count, "is not less than 10")
print("good bye!")
# single statement suits
flag = 1 #it eill be an infinite loop
# while (flag): print('Given flag is really true! ')
print('bye bye!')
## infinite loop: break by pressing ctrl+c
var = 1
while var ==1: #it generates an infinite loop
num = int(input("Enter a number: "))
print("You entered: ", num)
print("Good bye!")
| true
|
70d8a528a99c1599b955146f76a6c9db09b9f3e8
|
TarunVenkataRamesh-0515/19A91A0515_IICSEA_IVSEM_PYTHONLAB_1_TO_3
|
/distance.py
| 368
| 4.125
| 4
|
"""
Implement a python script to compute
distance between two points taking inp from the user (Pythagorean Theorem)
"""
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("distance between",(x1,y1),"and",(x2,y2),"is : ",result)
| false
|
54b8b9b9be1d12692909024eeb63535055a70268
|
piotrpasich/python_exercises
|
/zestaw8.py
| 2,152
| 4.1875
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Piotr Pasich, Łukasz Wycisło
WSB, Informatyka, Niestacjonarne, Programowanie w jezyku Python
Zestaw 8
"""
"""
Zadanie 1.
Napisz program zawierający instrukcję rysowania trójkąta równobocznego .
"""
import turtle
def zadanie1():
t = turtle.Turtle()
for i in range(3):
t.left((360/3))
t.forward(100)
"""
Zadanie 2.
Napisz program pozwalający na narysowanie poniżej przedstawionego fraktala:
"""
import math
def square(t, side=100, iteration = 30):
print(side, iteration)
for i in range(4):
t.forward(side)
t.left(90)
if (iteration != 0):
newSide = math.floor(side * 0.9)
square(t, newSide, iteration-1)
def zadanie2():
t = turtle.Turtle()
t.speed('fastest')
square(t)
"""
Zadanie 3*.
Napisz program pozwalający na narysowanie fraktala przedstawionego na następnej stronie.
"""
points = [[-175,-125],[0,175],[175,-125]] #size of triangle
def getMidPoint(p1,p2):
return ( (p1[0]+p2[0]) / 2, (p1[1] + p2[1]) / 2) #find midpoint
def triangle(t, points, iteration):
t.up()
t.goto(points[0][0],points[0][1])
t.down()
t.goto(points[1][0],points[1][1])
t.goto(points[2][0],points[2][1])
t.goto(points[0][0],points[0][1])
if iteration>0:
triangle(t, [points[0],
getMidPoint(points[0], points[1]),
getMidPoint(points[0], points[2])],
iteration-1)
triangle(t, [points[1],
getMidPoint(points[0], points[1]),
getMidPoint(points[1], points[2])],
iteration-1)
triangle(t, [points[2],
getMidPoint(points[2], points[1]),
getMidPoint(points[0], points[2])],
iteration-1)
def zadanie3():
t = turtle.Turtle()
t.ht()
t.speed(9)
iterations = 5
triangle(t, points, iterations)
x = int(input("Podaj numer zadania: "))
#x = 3
if (x==1):
zadanie1()
elif (x==2):
zadanie2()
elif (x==3):
zadanie3()
| false
|
de7ba808f6b8b5e1296dfa2ab02918ba520b8b0f
|
vandecloud/python
|
/10-set-diccionarios/diccionarios.py
| 836
| 4.3125
| 4
|
"""
DICCIONARIOS
Un diccionario es un tipo de dato que almacena un conunto de datos.
en formato clave > valor
es parcecido a un array asociativo o un objeto json.
"""
"""
persona = {
"nombre": "Pablo",
"apellido": "Vande",
"Web": "a definir"
}
print(type(persona))
print(persona["apellido"]) # Acceder al indice que indicamos
"""
contactos = [
{"nombre": "pablo",
"email": "pablo@pablo.com"
},
{
"nombre": "roberto",
"email": "roberto@roberto.com"
},
{
"nombre": "camilo",
"email": "camilo@camilo.com"
}
]
#print(contactos)
#print(contactos[1]["email"])
print ("n\Listado de contacos: ")
for contacto in contactos:
print(f"Nombre del contacto: {contacto ['nombre']}")
print(f"email del contacto: {contacto ['email']}")
print(f"**************************************")
| false
|
6a40da9daeb7b5c96488dd8552caafac2f0e0044
|
tedgey/while_loop_exercises
|
/p_a_s_II.py
| 346
| 4.15625
| 4
|
# print a square II - user chooses square size
square_size_input = input("How long should the square's sides be? ")
square_size_length = int(square_size_input)
symbol_count = square_size_length * ("*")
counter = 0
while counter < square_size_length:
counter = counter + 1
if counter <= square_size_length:
print(symbol_count)
| true
|
22f7df39cb5e448034c348c6b3587138de937361
|
MTDahmer/Portfolio
|
/hw2.py
| 2,972
| 4.28125
| 4
|
# File: hw2.py
# Author: Mitchell Dahmer
# Date: 9/18/17
# Section: 503
# E-mail: mtdahmer@tamu.edu
# Description: a program that takes two operands from a user and then modifies them based on the operation given by the user in the form of a string
import math
def main():
firstInteger = int(input("Please enter the first operand: ")) #these three lines take the desired inputs from the user in the form of two numbers and an operation respectively
secondInteger = int(input("Please enter the second operand: "))
userOper = str(input("Please enter the operation: "))
operation= userOper.lower() #turns the strin input by the user into all lowercase letters for easier identification
print("Operand 1 is %.0f" % firstInteger) #three lines that print off the variables input by the user
print("Operand 2 is %.0f" % secondInteger)
print("The operation is %s" % userOper)
if (operation=='add'): #adds the integers together if the input operation is add and then prints the total
total = firstInteger+secondInteger
print("Your result is %.3f" % total)
elif (operation=='subtract'): #subtracts the integers from each otherif the input operation is subtract and then prints the total
total = firstInteger-secondInteger
print("Your result is %.3f" % total)
elif (operation=='multiply'): #multiplies the integers together if the input operation is multiply and then prints the total
total = firstInteger*secondInteger
print("Your result is %.3f" % total)
elif (operation=='divide'): #divides the integers by each other if the input operation is divide and then prints the total
if(secondInteger==0): #gives the user and error if the second operand is a 0
print("Division by zero is not allowed")
else:
total = firstInteger/secondInteger
print("Your result is %.3f" % total)
else:
print("Invalid operation") #gives an error if the operation given is not one of the four
total = abs(total) #three lines that take the absolute value of the total and turn the total into a string whose integers can be counted to find length
strTotal = str(total)
numb = len(strTotal)
if ((firstInteger>0) and (secondInteger>0)) or ((firstInteger<0) and (secondInteger<0)) or ((numb>2)): #prints a line between the total and the special conditions only if any exist
print('------------------------------')
if (firstInteger>0) and (secondInteger>0): #prints notifcation if both operand are positive
print("Both operand are positive")
elif(firstInteger<0) and (secondInteger<0): #prints notifcation if both operand are negative
print("Both operand are negative")
if (numb>2): #prints notification if the number has over three digits
print("The result is has three or more digits")
main()
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.