blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
fb9aab692c17f2645dd53720f75797f8356d1d71 | sdkcouto/exercises-coronapython | /chapter_7_7_5.py | 677 | 4.21875 | 4 | #Movie Tickets: A movie theater charges different ticket prices depending on a person’s age. If a person is under the age of 3, the ticket is free; if they are between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is $15. Write a loop in which you ask users their age, and then tell them the cost of their movie ticket.
ages = '\nHow old are you?'
ages += "\nEnter 'quit' when you are finished."
while True:
age = input(ages)
if age == 'quit':
break
elif int(age) < 3:
print('The entrance is free.')
elif int(age) > 3 and int(age) < 12:
print('The ticket is $10.')
else:
print('The ticket is $15')
| true |
035c2e6ec718ce310deb71c4b07f2e78d1d6a00b | sdkcouto/exercises-coronapython | /chapter_5_5_4.py | 734 | 4.21875 | 4 | #2: Choose a color for an alien as you did in Exercise 5-3, and write an if-else chain.
#• If the alien’s color is green, print a statement that the player just earned 5 points for shooting the alien.
alien = 'green'
if alien == 'green':
print("You just eaned 5 points")
#• If the alien’s color isn’t green, print a statement that the player just earned 10 points.
alien = 'red'
if alien == 'green':
print("You just eaned 5 points")
if alien != 'green':
print('You just earned 10 points')
#• Write one version of this program that runs the if block and another that runs the else block.
alien = 'green'
if alien == 'green':
print('You just eaned 5 points')
else:
print('You just earned 10 points') | true |
e70517ab364dd913451937fcd1c945cf68325547 | sdkcouto/exercises-coronapython | /chapter_4_4_6.py | 202 | 4.25 | 4 | # 4-6. Odd Numbers: Use the third argument of the range() function to make a list of the odd numbers from 1 to 20. Use a for loop to print each number.
number=range(1,21,2)
for n in number:
print(n) | true |
d12ee10c6d259895f52f652d3e66e66f81cec84a | d-jskim/202003_platform | /김지수/pre_python_02.py | 759 | 4.125 | 4 | """"2.if문을 이용해 첫번째와 두번째 수, 연산기호를 입력하게 하여 계산값이 나오는 계산기를 만드시오"""
input1 = float(input("숫자를 입력하시오: "))
inputOp = input("연산자를 입력하시오(+, -, *, /): ")
input2 = float(input("숫자를 한 번 더 입력하시오: "))
# calculation
def cal(operator, a, b):
if operator == "+":
return a + b
elif operator == "-":
return a - b
elif operator == "*":
return a * b
elif operator =="/":
return a / b
else:
print("계산할 수 없습니다. '+', '-', '*', '/' 중 하나만 선택하시오.")
return
print("연산 결과: ", cal(inputOp, input1, input2)) | false |
70a590a6fb7e0eb5b662b5a813b34ed0d046ba3e | DerevenetsArtyom/pure-python | /algorithms/Problem_Solving_Algorithms_Data Structures/sorting_and_search/merge_sorts/merge_sort.py | 1,532 | 4.15625 | 4 | """
Code was taken and combined from:
http://rextester.com/PEAA86258
https://brilliant.org/wiki/merge/
https://gist.github.com/jvashishtha/2720700
https://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
https://codereview.stackexchange.com/questions/154135/recursive-merge-sort-in-python
"""
# The merge sort algorithm comes in two parts:
# * sort function
# * merge function
def merge(left, right):
result = []
left_idx = right_inx = 0
# looping while exhaust one of arrays
# P.S. change direction of comparison to change the direction of sort
while left_idx < len(left) and right_inx < len(right):
if left[left_idx] < right[right_inx]:
result.append(left[left_idx])
left_idx += 1
else:
result.append(right[right_inx])
right_inx += 1
# here we have reached end of left / right
# and add to result rest of another list
if left_idx < len(left):
result.extend(left[left_idx:])
if right_inx < len(right):
result.extend(right[right_inx:])
# Also could be without checking
# result += left[left_index:]
# result += right[right_index:]
return result
def merge_sort(arr):
"""Divide array in half and merge sort recursively"""
if len(arr) <= 1:
return arr
middle = len(arr) // 2
left = merge_sort(arr[:middle])
right = merge_sort(arr[middle:])
return merge(left, right)
alist = [5, 2, 1, 9, 0, 4, 6]
print(alist)
res = merge_sort(alist)
print('')
print(res)
| true |
4c19687dfe5f96d172b0dfadde701061a826de4a | DerevenetsArtyom/pure-python | /iterators/simple_infinite.py | 609 | 4.125 | 4 | class InfiniteIterator:
def __init__(self):
self.__number = 0
def __iter__(self):
return self
def __next__(self):
self.__number += 1
return self.__number
# Just plain usage of InfiniteIterator
doubler = InfiniteIterator()
counter = 0
for number in doubler:
# print(number)
if counter > 10:
break
counter += 1
# Create iterable from InfiniteIterator
class InfiniteNumbers:
def __iter__(self):
return InfiniteIterator()
infinite_numbers = InfiniteNumbers()
for x in infinite_numbers:
print(x)
if x > 99:
break
| true |
7652ee504f1c6fa2cca1373d18006a5f91ac5832 | Realcomms/Python | /001.FirstStart/05.반복문.py | 965 | 4.15625 | 4 | # 반복문 예제
for item in range(0,10):
print(item)
for item in range(0, 10):
print("Hello")
# 리스트 예제
list_number = [0, 1, 2, 3, 4, 5]
list_string = ["Seoul", "Busan", "Daegu"]
print(list_number)
print(list_string)
# 리스트에서 인덱스로 아이템 선택하기
num_list = [0, 1, 2, 2, 4]
print(num_list)
print(num_list[3])
# for로 리스트 출력하기
for item in [0, 1, 2, 3, 4]:
print(item)
# 구구단 만들기
print(2, 1, 2)
print(2, "*", 1, "=", 2)
for num in range(1, 10):
print(2, num)
for item in range(1, 10):
print(2, "*", item, "=", 2 * item)
# for문을 바로 리스트로 만들기
num_list = [1, 2, 3, 4]
# num_list 각각에 2를 곱한 결과
print("# num_list 각각에 2를 곱한 결과")
for num in num_list:
print(num * 2)
num_lt = [1, 2, 2, 4]
# num_lt 각각에 2를 곱한 결과(다시 list 형태로 만드는 방법)
resultCom = [num * 2 for num in num_lt]
print(resultCom)
| false |
d22e309329d4be1d63df1cf55f0fa8aa34ee9f61 | awescarsoto/HackerRank | /comparator_sorting.py | 1,845 | 4.1875 | 4 | '''
Comparators are used to compare two objects. In this challenge, you'll create a comparator and use it to sort an array. The Player class is provided in the editor below; it has two fields:
A string, .
An integer, .
Given an array of Player objects, write a comparator that sorts them in order of decreasing score; if or more players have the same score, sort those players alphabetically by name. To do this, you must create a Checker class that implements the Comparator interface, then write an int compare(Player a, Player b) method implementing the Comparator.compare(T o1, T o2) method.
Input Format
Locked stub code in the Solution class handles the following input from stdin:
The first line contains an integer, , denoting the number of players.
Each of the subsequent lines contains a player's respective and .
Constraints
Two or more players can have the same name.
Player names consist of lowercase English alphabetic letters.
Output Format
You are not responsible for printing any output to stdout. Locked stub code in Solution will create a Checker object, use it to sort the Player array, and print each sorted element.
Sample Input
5
amy 100
david 100
heraldo 50
aakansha 75
aleksa 150
Sample Output
aleksa 150
amy 100
david 100
aakansha 75
heraldo 50
Explanation
As you can see, the players are first sorted by decreasing score and then sorted alphabetically by name.
'''
class Player:
def __init__(self, name, score):
self.name = name
self.score = score
def __repr__(self):
return repr(self.score, self.name)
def comparator(a, b):
if a.score > b.score:
return -1
elif a.score < b.score:
return 1
elif a.name > b.name:
return 1
elif a.name < b.name:
return -1
else:
return 0 | true |
7f858eb23fb8cdd237dba1400bb3cc138be14f14 | awreynold/Python | /src/Simple Calculator/calcOperations.py | 781 | 4.34375 | 4 | #holds all the operations that the calculator supports
#adds the 2 numbers and prints the result string to the console
def add(value1, value2):
print(value1 + " + " + value2 + " = " + str(int(value1) + int(value2)))
#subtracts value2 from value1 and prints the result string to the console
def subtract(value1, value2):
print(value1 + " - " + value2 + " = " + str(int(value1) + int(value2)))
#multiplies value1 and value2 and prints the result string to the console
def multiply(value1, value2):
print(value1 + " * " + value2 + " = " + str(int(value1) + int(value2)))
#divides value1 by value2 and prints the result string to the console
def divide(value1, value2):
print(value1 + " / " + value2 + " = " + str(int(value1) + int(value2))) | true |
ee7b6f40d6ae56fc0c310bfdb58124fbf4087986 | db97828/PythonAlgorithm | /python/20200822_stcack_예제.py | 1,127 | 4.40625 | 4 | """
작성일: 2020-08-22
==============================================================================
문제: 문제 내용
==============================================================================
소요 시간: 00분
"""
stack = []
stack.append(5)
stack.append(2)
stack.append(3)
stack.append(7)
stack.pop()
stack.append(1)
stack.append(4)
stack.pop()
print(stack) # 최하단 원소부터 출력
print(stack[::-1]) # 최상단 원소부터 출력
"""
접근법: 내가 왜 이런 방식으로 문제를 해결했는지 작성
==============================================================================
다른 해결 방식: 다른 해결 방법
==============================================================================
개선점: 개선할 수 있는 부분
==============================================================================
노트:
stack은 별도의 라이브러리 사용 필요 없다, 선입후출 구조
append() -> 가장 뒤쪽에 데이터 삽입
pop() -> 가장 뒤쪽 데이터 꺼냄
=> append()와 pop()메서드 이용하면 스택 자료구조와 동일하게 동작
""" | false |
344443ef259ecf0278fdfb8f2c24c62586a2533c | ljdutton2/Interview_questions | /leetcode/longest_common_prefix.py | 674 | 4.125 | 4 | """Write a function to find the longest common prefix string
amongst an array of strings.If there is no common prefix,
return an empty string ""."""
#the time complexity of this is O(n) because imagine we have a min
#string with a whooole bunch if letters it has to traverse through
#all of them
def common_prefix(array):
if not array:
return ""
min_ = min(array)
max_ = max(array)
array = array.sort()
if not min_:
return ""
for i in range(len(min_)):
if max_[i] != min_[i]:
return max_[:i]
return min_[:]
array = ["flower", "florist","floral", "fleet", "find"]
print(common_prefix(array))
| true |
95c8eb90a5c30642bb1ad30fadc6e78e8ddac566 | vickispark/pyBasics | /app5.py | 469 | 4.15625 | 4 | is_male = True
is_tall = False
if is_male:
print("you are a male")
else:
print("not a male")
if is_male and is_tall:
print("male or tall")
if is_tall:
print("tall")
if is_male:
print("male")
if is_male and is_tall:
print("both")
else:
print("either one")
elif is_tall and not is_male:
print("tall not male")
elif not(is_tall) and is_male:
print("male not tall")
else:
print("not both")
| false |
6b94696763fcd5a49bc149ddc4741aad9d3aa8fa | JuarezFilho/Programas | /Mini Sistema.py | 2,475 | 4.21875 | 4 | menu='MENU DE INTERAÇÃO'
print('=-'*30)
print(menu.center(55))
print('=-'*30)
print('[1] Cadastro de Produtos')
print('[2] Cadastro de Usuário')
print('[3] Cadastro de Mercados')
print('[4] Comparar preços de produtos')
print('[5] Comparar preços por cesta básica')
print('=-'*30)
RespostaUsuario=int(input('Resposta: '))
print('=-'*30)
if RespostaUsuario == 1:
print("Opção 1 escolhida. Cadastre os produtos")
produtos=[]
preços=[]
while True:
produtos.append(input("Nome do produto: "))
preços.append(float(input("Preço do produto: ")))
resposta=input("Deseja continuar? [S/N]: ").upper()
print('=-' * 30)
if resposta == 'N':
break
print('Produtos Cadastrados')
for c in range(len(produtos)):
print(f'{produtos[c].upper()} : R${preços[c]}')
elif RespostaUsuario == 2:
print('Opção 2 escolhida. Cadastre o Usuário')
usuarios=[]
while True:
usuarios.append(input('Nome do usuário: '))
resposta = input("Deseja continuar? [S/N]: ").upper()
print('=-' * 30)
if resposta == 'N':
break
print("Usuários Cadastrados")
for c in usuarios:
print(c)
elif RespostaUsuario == 3:
print("Opção 3 escolhida. Cadastre o Mercado")
mercado=[]
while True:
mercado.append(input("Nome do Mercado: "))
resposta = input("Deseja continuar? [S/N]: ").upper()
print('=-' * 30)
if resposta == 'N':
break
print("Mercados Cadastrados")
for c in mercado:
print(c)
elif RespostaUsuario == 4:
print('Opção 4 escolhida. Compare os preços')
m1=input("Nome do mercado: ")
p1=float(input(f"Preço do produto no {m1}: "))
print('=-' * 30)
m2=input("Nome do 2 mercado: ")
p2=float(input(f"Preço do produto no {m2}: "))
print('=-' * 30)
if p1 < p2:
print(f"O produto é mais barato no {m1}")
else:
print(f"O produto é mais barato no {m2}")
elif RespostaUsuario == 5:
print('Opção 5 escolhida. Compare os preços')
m1=input("Nome do mercado: ")
p1=float(input(f"Preço da cesta básica no {m1}: "))
print('=-' * 30)
m2=input("Nome do 2 mercado: ")
p2=float(input(f"Preço da cesta básica no {m2}: "))
print('=-' * 30)
if p1 < p2:
print(f"A cesta mais barata é no {m1}")
else:
print(f"A cesta mais barata é no {m2}")
else:
print("Opção Inválida") | false |
009824f67648165a6b5eface6b8b0723ffb119f3 | Maniask/Python-progs | /Notdivisibleby5.py | 215 | 4.15625 | 4 | # This is a python program for finding the numbers from 1 to 20 that are not divisible by 5.
# Created By: Mani Agarwal
# Email : agarwalmani22@gmail.com
# Date : 08-01-2019
for i in range(1,21):
if(i%5!=0):
print(i)
| true |
c9f906ec7249ff621d9d2ec13b925be00765ceac | VIKULBHA/Devopsbc | /Python/First project/Exercises/Temperature Converter.py | 2,374 | 4.21875 | 4 | print("to convert Celsius to Fahrenheit enter a")
print("to convert Fahrenheit to Celsius enter b")
user_input = input()
if user_input == "a":
if isinstance(user_input, str):
temperature = input("Enter the temperature")
result = ((float(temperature)*9/5)+32)
print(result)
elif user_input == "b":
if isinstance(user_input, str):
temperature = input('Enter the temperature')
result = ((float(temperature)-32)*5/9)
print(result)
#---------------------
print("to convert Celsius to Fahrenheit enter a")
print("to convert Fahrenheit to Celsius enter b")
user_input = input()
if user_input == "a":
if isinstance(user_input, str):
temperature = input("Enter the temperature")
result = ((float(temperature)*9/5)+32)
print(result)
elif user_input == "b":
if isinstance(user_input, str):
temperature = input('Enter the temperature')
result = ((float(temperature)-32)*5/9)
print(result)
#----------------------
print("to convert Celsius to Fahrenheit enter a")
print("to convert Fahrenheit to Celsius enter b")
print("to convert Celsius to Kelvin enter c")
user_input = input()
if user_input == "a":
temperature = float(input("Enter the base temperature: "))
result = (temperature*9/5)+32
elif user_input == "b":
temperature = float(input("Enter the base temperature: "))
result = (temperature-32)*5/9
elif user_input == "c":
temperature = float(input("Enter the base temperature: "))
result = (temperature+273)
print(result)
#Emerson Mellado:spiral_calendar_pad: 9 minutes ago
#One more solution with functions:
print("to convert Celsius to Fahrenheit enter a")
print("to convert Fahrenheit to Celsius enter b")
print("to convert Celsius to Kelvin enter c")
user_input = input()
def celsius_to_fahrenheit(temp):
return (temp*9/5)+32
def fahrenheit_to_celsius(t):
return (t-32)*5/9
def celsius_to_kelvin(x):
return x+273
if user_input == "a":
temperature = float(input("Enter the base temperature: "))
result = celsius_to_fahrenheit(temperature)
elif user_input == "b":
temperature = float(input("Enter the base temperature: "))
result = fahrenheit_to_celsius(temperature)
elif user_input == "c":
temperature = float(input("Enter the base temperature: "))
result = celsius_to_kelvin(temperature)
print(result) | true |
2d3892438747e185a524b6faf3c8dfa53afe2251 | MobiDevOS/PythonBasic | /Main.py | 2,769 | 4.21875 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""测试main函数入门"""
if __name__=='__main__':
#基础层级测试
a = 8
b = 9
if a>10:
if b>10:
print(b)
print(a)
#基础函数测试
def sum(num1,num2):
# 两数之和
if not (isinstance (num1,(int ,float)) and isinstance (num2,(int ,float))):
raise TypeError('参数类型错误')
return num1+num2
print(sum(1,2))
#函数返回多个值测试
def division ( num1, num2 ):
# 求商与余数
a = num1 % num2
b = (num1-a) / num2
return b , a
num1 , num2 = division(9,4)
tuple1 = division(9,4)
print (num1,num2)
print (tuple1)
#测试必须按照 特定名称传值 如age *,age 是一体的 * 后面所有的参数必须要按照指定名称来传值
def print_user_info( name , *,age , sex = '男' ):
#打印用户信息
print('昵称:{}'.format(name) , end = ' ')
print('年龄:{}'.format(age) , end = ' ')
print('性别:{}'.format(sex))
return;
print_user_info( '张三',age='12',sex='女')
#* hobby指的是一个可变长的元组,** hobby表示一个指定关键字的元组
def print_user_info( name , age , sex = '男' , ** hobby ):
# 打印用户信息
print('昵称:{}'.format(name) , end = ' ')
print('年龄:{}'.format(age) , end = ' ')
print('性别:{}'.format(sex) ,end = ' ' )
print('爱好:{}'.format(hobby))
return;
print_user_info(12,23,'女',hobby=('234','343','43434'))
#测试匿名函数 输出结果100001 表示执行的时候才确定数值
num2 = 100
sum1 = lambda num1 : num1 + num2 ;
num2 = 10000
sum2 = lambda num1 : num1 + num2 ;
print( sum1( 1 ) )
print( sum2( 1 ) )
#################
# 测试迭代 #
#################
# 1、for 循环迭代字符串
for char in 'liangdianshui' :
print ( char , end = ' ' )
print('\n')
# 2、for 循环迭代 list
list1 = [1,2,3,4,5]
for num1 in list1 :
if num1 == 3:
continue
print ( num1 , end = ' ' )
print('\n')
# 3、for 循环迭代 (字典)
dict1 = {'name':'张珊','age':'23','sex':'男'}
for key in dict1 : # 迭代 dict 中的 key
print ( key+":",end = ' ')
print ( dict1.get(key),end = ' ')
print('\n')
for value in dict1.values() : # 迭代 dict 中的 value
print ( value , end = ' ' )
print ('\n')
# 如果 list 里面一个元素有两个变量,也是很容易迭代的
for x , y in [ (1,'a') , (2,'b') , (3,'c') ] :
print ( x , y )
| false |
85c60005a744c29e0ce031f48394a8de0660f95c | WareeshaNazeer/BTechProject | /q3.py | 700 | 4.125 | 4 | string=input("Enter password\n")
length=len(string)
nouns=['book', 'company', 'pen', 'fruit', 'building']
special="@!#$%&*"
len_param=True
count=0
count_check=False
alphanum_param=1
noun=0
if(length>16):
len_pam=False
for i in nouns:
if(i==string):
noun=1
for i in string:
if (special.find(i)>-1):
count=count+1
if(count>=2):
count_check=True
for i in string:
asc=ord(i)
if((asc>=48 and asc<=57)or(asc>=97 and asc<=122)or(asc>=65 and asc<=90)):
alphanum_param=1*alphanum_param
else:
if(special.find(i)<0):
alphanum_param=0*alphanum_param
if(len_param==True and noun==0 and count_check==True and alphanum_param==1):
print("Valid password")
else:
print("Invalid password")
| true |
a37f23553ffd5fc08f959bd9312d2409e667cc08 | Yona-Dav/DI_Bootcamp | /Week_5/Day3/Daily_challenge/Circle.py | 1,438 | 4.15625 | 4 | import math
import turtle
class Circle:
circles = []
def __init__(self):
print('''
1. Diameter
2. Radius
''')
ans = input('Which one to you want to input. Enter a number ')
if ans=='1':
self.diameter = int(input('Enter diameter '))
self.radius = self.diameter/2
elif ans=='2':
self.radius = int(input('Enter the radius '))
self.circles.append(self.radius)
def circle_area(self):
self.aera = math.pi*self.radius**2
print(self.aera)
def __str__(self):
return f'Circle with a radius of {self.radius}'
def draw_circle(self):
t = turtle.Turtle()
print(t.circle(self.radius))
def __add__(self,other):
return self.radius + other.radius
def __gt__(self,other):
if self.radius > other.radius:
return True
elif self.radius < other.radius:
return False
def __eq__(self, other):
if self.radius == other.radius:
return True
else:
return False
def list_sorted(self):
return sorted(self.circles)
circle1 = Circle()
circle1.circle_area()
circle1.draw_circle()
circle2 = Circle()
circle2.circle_area()
circle2.draw_circle()
print(circle2+circle1)
print(circle1>circle2)
print(circle1==circle2)
print(circle2.list_sorted())
| false |
414395345bdb053ed7f2111ea60507e8e0037820 | Yona-Dav/DI_Bootcamp | /Week_4/Day4/Exercise_XP_NINJA/exercises.py | 916 | 4.3125 | 4 | # Exercise 1 : Box Of Stars
def longuest_words(*args):
longuest_word = ''
for arg in args:
if len(arg)>len(longuest_word):
longuest_word = arg
return len(longuest_word)
def box_printer(*args):
print('*'*2+'*'*longuest_words(*args)+'*'*2)
for arg in args:
space = longuest_words(*args) - len(arg)
print('*'+' '+arg+' '*space+' '+'*')
print('*'*2+'*'*longuest_words(*args)+'*'*2)
box_printer("Hello", "World", "in", "reallylongword", "a", "frame")
# Exercise 2
'''this algorithm is used to sort'''
def insertion_sort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertion_sort(alist)
print(alist) | false |
b74bfa6961c6b5705cdfa255cbd1d3e0daf65f21 | andres2233/varios-proyectos | /python-curse/lists.py | 1,129 | 4.28125 | 4 | #vamos a ver como hacaer una lista de objetos en python
#demo_list=["HOLA", GREEN, [2, 3, 4], TRUE]
#como se hace unalista de numeros
number_list = list((1, 2, 3, 4))
print(number_list)
print(type(number_list)) #ype es para saber que tipo de string es
#Con este cpmado hacemos una lista de un numero a otro o rango
entre = list(range(1, 200)) #el valor siempr llega un numero menos osea 1 a 199
print(entre)
# para saber las fuciones que se pueden hacer en una lista
colors = ["green", "black", "yelow"]
print(dir(colors))
#para saber la cantidad de cofuncionesque se pueden hacer en una lista
print(len(colors))
#para saber si algo esta o no dentro de una lista aplicamos el comando :
print("green" in colors)
#la respuesta sera true si si esta o false si no lo esta esto es llamado boolean
#si quieres cambair algo de una list si cambiarlo directamente enotneces :
colors["green"]= "blackplatano"
print(colors)
#si quieres agreagr varios srings a una lista se utiliza el siguiente comando
colors.extend(["violet", "purple"])
print(colors)
#para poner un strin en una posicion espesifica :
colors.insert(1, "papaya" ) | false |
811d925755cb66c527831c4ec3abfd3e8fa8e1d5 | clevercoderjoy/Competitive-Coding | /CF_Way_Too_Long_Words.py | 2,183 | 4.125 | 4 | # A. Way Too Long Words
# time limit per test1 second
# memory limit per test256 megabytes
# inputstandard input
# outputstandard output
# Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
# Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
# This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
# Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
# You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
# Input
# The first line contains an integer n (1 ≤ n ≤ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
# Output
# Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.
# Examples
# inputCopy
# 4
# word
# localization
# internationalization
# pneumonoultramicroscopicsilicovolcanoconiosis
# outputCopy
# word
# l10n
# i18n
# p43s
# Explanation:
# If the alphabets in the word are more than 10 then we need to print the abbreviation of the word.
# If the alphabets in the word are less than 10 then we simply need to print the letter as it is.
# To print the abbreviation of the word we need to print the first word, the length of word - 2 and the last alphabet
# For output we need to take the word as input and print the word or the abbreviation as per the condition one by one.
limit = int(input())
for word in range(limit):
word = input()
if len(word) > 10:
print(word[0], end = "")
print(len(word) - 2, end = "")
print(word[-1])
else:
print(word) | true |
1cabad3a5d2d1a93c604755d913e687dca2e2e01 | GersonCity/Python | /ATBS/chap7.py | 963 | 4.15625 | 4 | # Regular Expressions
# Funcion que valida un numero de telefono
def isPhoneNumber(text):
if len(text) != 12:
return False
for i in range(0, 3):
if not text[i].isdecimal():
return False
if text[3] != '-':
return False
for i in range(4, 7):
if not text[i].isdecimal():
return False
if text[7] != '-':
return False
for i in range(8, 12):
if not text[i].isdecimal():
return False
return True
# print('415-555-4242 is a phone number:')
# print(isPhoneNumber('415-555-4242'))
# print('Moshi moshi is a phone number:')
# print(isPhoneNumber('Moshi moshi'))
#
message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
for i in range(len(message)):
# print(i)
chunk = message[i:i + 12] # va leyendo asi : 0:0+12 -> 1:1+12 -> 2:2+12
print(chunk)
if isPhoneNumber(chunk):
print('Phone number found: ' + chunk)
print('Done')
| false |
0057cc5b8e99525bfc49dd93b6edc01e79afa6e6 | GersonCity/Python | /begginer/Condiciones.py | 875 | 4.1875 | 4 |
# Comparisons:
# Equal: ==
# Not Equal: !=
# Greater Than: >
# Less Than: <
# Greater or Equal: >=
# Less or Equal: <=
# Object Identity: is Verifica los mismos obejetos en memoria
# lenguaje = 'Java'
# if lenguaje == 'Python':
# print('Lenguaje es Python')
# elif lenguaje == 'Java':
# print('Lenguaje es Java')
# else:
# print('No match')
# and
# or
# not
# user = 'Admin'
# logged_in = True
# if user == 'Admin' and logged_in:
# print('Admin Page')
# else:
# print('Bad Creds')
# if not logged_in:
# print('Please log in')
# else:
# print('Welcome')
# False Values:
# False
# None
# Zero of any numeric type
# Any empty sequence. For example, '', (), [].
# Any empty mapping. For example, {}.
conditions = False
if conditions:
print('Evaluated to True')
else:
print('Evaluated to False')
| true |
49cea55f4ad5a067a1b8467aea66eab19d57535f | jisshub/python-development | /pythonAdvanced/stack_queues.py | 760 | 4.21875 | 4 | # stack and queue operations using list
# numbers = []
# # stack
# numbers.append(30)
# numbers.append(16)
# numbers.append(15)
# numbers.append(13)
# print(numbers)
#
# # pop in list
# # numbers.pop()
# # print(numbers)
#
# # add an element
# numbers.append(77)
#
# print(numbers)
#
# # pop
# numbers.pop()
# print(numbers)
# stack and queue operation using deque
from _collections import deque
print(deque)
# deque is an object of collection class
# initialize a deque
numbers = deque()
numbers.append(55)
numbers.append(52)
numbers.append(54)
numbers.append(56)
numbers.append(57)
print(numbers)
# pop from deque
numbers.pop()
print(numbers)
numbers.append(90)
print(numbers)
print(numbers.popleft())
print(numbers.popleft())
print(numbers.popleft())
| false |
40b9a7057fae9312035d751a56accd81b3d50732 | jisshub/python-development | /pythonAdvanced/python_Enumerate.py | 1,150 | 4.21875 | 4 | # python enumerate function
grocery = ['bread', 'milk', 'butter']
enumerateGrocery = enumerate(grocery)
print(list(enumerateGrocery))
# here enumerate function adds a counter to the
# each value in the list. counter will default starts
# from 0.
# when v print enumrated result v gets an enumerate object.
# so v converts it to list using list()
# counter is laike a key value for each iterator
# convert the enumerate object to tuple.
# sample -2
myGrades = ['A', 'B', 'C', 'D']
enumerateGrades = enumerate(myGrades)
print(tuple(enumerateGrades))
# can also add start value for the counter
laptop_brands = ['hp', 'dell', 'asus', 'samsung', 'haiti', 'xiaomi']
lapEnumerate = enumerate(laptop_brands, 2)
print(list(lapEnumerate))
# looping over an enumerated object
grocery = ['bread', 'milk', 'butter']
for item in enumerate(grocery):
print(item)
print('\n')
for count, item in enumerate(grocery):
print(count, item)
# here count represents the cpunter value
for count, item in enumerate(grocery, 100):
print(count, item)
# Example
pages = ['page1', 'page2', 'page3', 'page4']
for c, i in enumerate(pages, 1001):
print(c, i)
| true |
c45832a5d861bd9ef38c09faf2027e080f90f9aa | reniz128/loops-and-list | /loops.py | 514 | 4.40625 | 4 | """
the program consists of creating a list and
iterating over it to add values to a new list.
we attach both lists in another list and show on the screen
"""
def attach_lists(first_value, second_value):
while len(first_value) == len(second_value): # 3==3
all_lst=first_value+second_value
print(all_lst)
break
def lst():
lst=[1,2,3]
new_lst=[] # [0, 1, 2]
for i in range(len(lst)): # [0, 1, 2]
new_lst.append(i)
attach_lists(lst, new_lst)
lst()
| true |
ae2474491ad32e308826b794c182d44779b6cfca | Kartturi/CodewarsPython | /DashatizeIt.py | 728 | 4.3125 | 4 |
# Given a number, return a string with dash'-'marks before and after each
# odd integer, but do not begin or end the string with a dash mark.
# Ex:
# dashatize(274) -> '2-7-4'
# dashatize(6815) -> '68-1-5'
def dashatize(num):
newList = []
build = ''
if num is None:
return 'None'
for i,char in enumerate(str(num),start=0):
if not char.isdigit():
continue
if int(char) % 2 == 0:
build += char
if i == len(str(num)) - 1:
newList.append(build)
else:
if len(build) > 0:
newList.append(build)
build = ''
newList.append(char)
return '-'.join(newList)
print(dashatize('')) | true |
b4d8f4bb458935d917f5a81d95ddd381a4bffa9e | MihailMecetin/killingCode | /ex5.py | 542 | 4.3125 | 4 | Name = 'Someguy'
Age = 23
Height = 190 # Centimeters
Weight = 90 # kg
Eyes = 'Green'
Teeth = 'White'
Hair = 'Black'
Pronoun = 'He'
Pronoun2 = 'His'
print(f"Let'stalk about {Name}.")
print(f"{Pronoun}'s {Height} centimiters tall. Which is", round(Height * 0.3937), "in inches." )
print(f"{Pronoun}'s {Weight} kilograms heavy. Which is", round(Weight * 2.205), "in pounds.")
print("Actually that's not too much.")
print(f"{Pronoun}'s got {Eyes} eyes and {Hair} hair.")
print(f"{Pronoun2} teeth are usually {Teeth} depending on the coffee.")
| true |
40c1a997a52f31f0ed458e03a2ff1d61d4bbfaef | Vinicius120824/Projeto-Aula | /Atividade1.py | 2,188 | 4.34375 | 4 | #Introdução ao Programa
print('\tPara começar preencha o cadastro com nome e peso de seu lutador, '
'para saber em qual categoria ele se encaixa!! ')
# o \t = espaço / seria para deixar mais apresentavel para o leitor que irá ver o resultado na tela !
#Declaração das variáveis aonde o usurario terá digitar as informações
nome = input('\tDigite o nome do lutador: ')
peso = float(input('\tDigite o peso do lutador (em kg): '))
#Processamento
#Aqui seria a entrada onde será a verificação do valor so peso e aonde ele se encaixa na tabela de categoria
#e irá imprimir na tela o peso o nome e a categoria se a função for verdadeira
if peso < 65:
print('\n Nome fornecido: {}\n Peso fornecido: {}\n '
'O lutador {} pesa {}Kg e se enquadra na categoria Pena'.format(nome, peso, nome, peso))
elif peso >= 65 and peso < 72:
print('\n Nome fornecido: {}\n Peso fornecido: {}\n '
'O lutador {} pesa {}Kg e se enquadra na categoria Leve'.format(nome, peso, nome, peso))
elif peso >= 72 and peso < 79:
print('\n Nome fornecido: {}\n Peso fornecido: {}\n '
'O lutador {} pesa {}Kg e se enquadra na categoria Ligeiro'.format(nome, peso, nome, peso))
elif peso >= 79 and peso < 86:
print('\n Nome fornecido: {}\n Peso fornecido: {}\n '
'O lutador {} pesa {}Kg e se enquadra na categoria Meio-Médio'.format(nome, peso, nome, peso))
elif peso >= 86 and peso < 93:
print('\n Nome fornecido: {}\n Peso fornecido: {}\n '
'O lutador {} pesa {}Kg e se enquadra na categoria Médio'.format(nome, peso, nome, peso))
elif peso >= 93 and peso < 100:
print('\n Nome fornecido: {}\n Peso fornecido: {}\n '
'O lutador {} pesa {}Kg e se enquadra na categoria Meio-Pesado'.format(nome, peso, nome, peso))
#Se caso nem uma das funções acima for verdadeira ela entra no else que seria de 100kg pra cima
#e imprima a ultima categoria
else:
print('\n Nome fornecido: {}\n Peso fornecido: {}\n '
'O lutador {} pesa {}Kg e se enquadra na categoria Pesado' .format(nome, peso, nome, peso))
# o \n = pular linha / seria para deixar mais apresentavel para o leitor que irá ver o resultado na tela ! | false |
196a1de819e9f592ce89a0b2b742922fdaec0138 | mtaggart/LPTHW | /ex21.py | 943 | 4.15625 | 4 | def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTPLYING %d * %d" % (a, b)
return a * b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
print "Let's do some math with just functions!"
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)
# A puzzle for the extra credit, type it in anyway.
print "Here is a puzzle."
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print "That becomes: ", what, "Can you do it by hand?"
print ((30+5)+((78-4)-((90*2)*((100/2)/2))))
that = ((6.0+12.0)/(8.0*(2.0-1.0)))
age = add(6.0, 12.0)
height = subtract(2.0, 1.0)
this = (divide(age, multiply(8.0, height)))
print that, "is equal to", this | true |
1f458fb22c8c1501ef16ee69ade680b56d274748 | ujrc/RealPython | /Chapter10/Chapter10_Review-Exercises_1.py | 843 | 4.15625 | 4 |
# 1.read in poem.txt
my_file=open("poem.txt","rb")
for line in my_file.readlines():
print line
my_file.close()
#2.Read files using with keyword
with open("poem.txt","rb") as my_files:
for line in my_files.readlines():
print line
# copy contents of poem.txt into output.txt
input_files=open("poem.txt","rb")
output_files=open("output.txt","wb")
for line in input_files.readline():
output_files.write(line)
print line,
output_files.close()
input_files.close()
with open("poem.txt","rb") as input_files, open("output.txt","wb") as output_files:
for line in input_files.readline():
output_files.write(line)
#4 Append text to output.txt
with open ("output.txt","a+") as output_file:
new_line="This is text will added to whatever is in output.txt file"
output_file.write(new_line)
for line in output_file:
print line,
| true |
16565c4e41c57d75a93c871d0c9b74e913770cdf | bopopescu/luminar2 | /amstrong number.py | 243 | 4.125 | 4 | num = int(input("Enter the number"))
res=0
while(num!=0):
digit=num%10
res=res+(digit*digit*digit)
num=num//10
#
print(res)
if(res == num):
print("It is an amstrong number")
else:
print("It is not an amstrong number") | true |
579eb0fb7ac8eff088fd85e5a549022f8acc47eb | CataHax/lab3-py | /ex1.py | 277 | 4.15625 | 4 | x1 = int(input("Enter the first number:"))
x2 = int(input("Enter the second number:"))
x3 = int(input("Enter the third number:"))
# now I must do three "if-s"
if x3 > x2 > x1:
print("increasing")
elif x1 > x2 > x3:
print("decreasing")
else:
print("nothing")
| false |
f08cd85b8687195795e7131d1050ccc10768a924 | danmachinez/curso_em_videoPython | /ex037.py | 706 | 4.15625 | 4 | num = int(input('Digite um número inteiro que deseja convertes: '))
print('''Escolha uma das bases para conversão:
[ 1 ] converter para BINÁRIO
[ 2 ] converter para OCTAL
[ 3 ] converter para HEXADECIMAL''')
escolhaConversao = (input('Qual sua oção de conversão? '))
while escolhaConversao not in '123':
escolhaConversao = (input('ESCOLHA INVÁLIDA! Qual sua oção de conversão? '))
if escolhaConversao == '1':
print(f'O número {num} convertido para BÍNARIO é {bin(num)[2:]}')
elif escolhaConversao == '2':
print(f'O número {num} convertido para OCTAL é {oct(num)[2:]}')
elif escolhaConversao == '3':
print(f'O número {num} convertido para HEXADECIMAL é {hex(num)[2:]}') | false |
1e8f06dc57291005ed2b5322a445a525ab830944 | Alex-Preciado/dstructs-py | /dstructs/Stack.py | 976 | 4.1875 | 4 |
class Stack:
def __init__(self):
self.items = []
def push(self, item):
'''
Accepts and item as a paremeter and appends it to the end of the list
Returns nothing
Runtime for this method is O(1)
'''
self.items.append(item)
def pop(self):
'''
Removes and returns the last item from the list which is the top item of the Stack
Runtime for this method is O(1)
'''
if self.items:
return self.items.pop()
else:
return None
def peek(self):
"""
Method to return the last item of the stack.
Runtime for this method is O(1)
"""
if self.items:
return self.items[-1]
else:
return None
def size(self):
"""
Method to return the lenght of the list representing the stack
Runtime for this method is O(1)
"""
return len(self.items)
def is_empty(self):
"""
Method to check if the stack list is empty
Runtime for this method is O(1)
"""
return self.items == [] | true |
097d8ab60c507161a88fe781b20a1920a4b198d3 | JuniorDugue/data-structure-and-algos-in-python | /recursions/recursionMethod.py | 623 | 4.46875 | 4 |
'''
def recursionMethod(parameters):
if exit from condition satisfied:
return some value
else:
recursionMethod(modified parameters)
'''
# deeper dive into how recursion works
# '''
def firstMethod():
secondMethod()
print("I am the first method")
def secondMethod():
thirdMethod()
print("I am the second method")
def thirdMethod():
fourthMethod()
print("I am the third method")
def fourthMethod():
print("I am the fourth method")
# '''
# '''
def recursiveMethod(n):
if n<1:
print("n is less than 1")
else:
recursiveMethod(n-1)
print(n)
# ''' | true |
3f4b6302aff28fc6bc997ef6be9aa4ca29ba3c55 | anthonyndunguwanja/Anthony-Ndungu-bootcamp-17 | /Day 1/test_prime_numbers.py | 872 | 4.15625 | 4 | #Testing Prime Number Generator
'''These are tests to be passed for a program to generate prime numbers'''
import unittest
from prime_numbers import prime_number_generator
class PrimeGeneratorTest(unittest.TestCase):
def test_only_positive(self):
self.assertEqual(prime_number_generator(-1), "Prime numbers cannot be less than two.")
def test_prime_numbers(self):
self.assertEqual(prime_number_generator(10), [2, 3, 5, 7])
def test_one(self):
self.assertEqual(prime_number_generator(1), "Zero or One cannot be prime numbers.")
def test_invalid_type_string(self):
self.assertEqual(prime_number_generator("String"), "Only integers are allowed.")
def test_zero(self):
self.assertEqual(prime_number_generator(0), "Zero or One cannot be prime numbers.")
if __name__ == "__main__":
unittest.main()
| true |
2b99faa8a5862ba37f22ca1a9c1bb65cfa83f84b | thiagodnog/projects-and-training | /Curso Python Coursera/Semana 7/Lista de Exercícios 5/lista5Exercicio2-ImprimeRetanguloVazado.py | 1,107 | 4.625 | 5 | """
Curso de Introdução à Ciência da Computação com Python Parte 1
Semana 7 - Lista de Exercício 5
Exercício 2
Refaça o exercício 1 imprimindo os retângulos sem preenchimento, de forma que os caracteres que não estiverem na borda do retângulo sejam espaços.
Por exemplo:
digite a largura: 10
digite a altura: 3
##########
# #
##########
digite a largura: 2
digite a altura: 2
##
##
"""
largura = int(input("digite a lagura: "))
altura = int(input("digite a lagura: "))
contadorLargura = largura
contadorAltura = altura
while contadorAltura != 0:
while contadorLargura != 0:
if contadorAltura == 1 or contadorAltura == altura:
print("#", end="")
contadorLargura = contadorLargura - 1
else:
if contadorLargura == 1 or contadorLargura == largura:
print("#",end="")
contadorLargura = contadorLargura - 1
else:
print(" ",end="")
contadorLargura = contadorLargura - 1
contadorAltura = contadorAltura - 1
print()
contadorLargura = largura | false |
1033a6f949b33017c56a4e47d881dcf5278fda00 | thiagodnog/projects-and-training | /Curso Python Coursera/Semana 3/Desafios/desafioFormulaBhaskara.py | 670 | 4.21875 | 4 | """
Curso - Introdução à Ciência da Computação com Python Parte 1
Semana 3 - Desafio
Escreva um programa para encontrar as raízes de uma função de segundo grau.
autor: Thiago Nogueira
"""
import math
a = int(input("Digite o valor do coeficiente quadrático: "))
b = int(input("Digite o valor do coeficiente linear: "))
c = int(input("Digite o valor do termo independente: "))
delta = b**2 - 4*a*c
x1 = (- b + math.sqrt(abs(delta)))/(2*a)
x2 = (- b - math.sqrt(abs(delta)))/(2*a)
if delta > 0:
print("As raizes da equação são:", "x1 =", x1, "e x2 =", x2)
elif delta == 0:
print("A raiz da equação é x =", x1)
else:
print("Não há raiz real.") | false |
271014628b1272d7698dac528624143c4941e8b5 | thiagodnog/projects-and-training | /Curso Python Coursera/Semana 5/Desafios/desafioBinomioNewton.py | 821 | 4.21875 | 4 | """
Curso - Introdução à Ciência da Computação com Python Parte 1
Semana 5 - Desafio
Escreva um programa utilizando funções para calcular um binômio de Newton através dos coeficientes binomiais.
Exemplo:
>>Digite o valor de n: 5
120
autor: Thiago Nogueira
"""
#n = int(input("Digite o valor do número de combinações n: "))
#k = int(input("Digite o termo k: "))
def binomio (n,k):
binomial = 0
if k > n:
print ("Erro! o a relação k < = n deve ser verdadeira")
else:
binomial = fatorial(n) / (fatorial(k)*fatorial(n-k))
return binomial
def fatorial (numero):
fatorial = numero
if numero == 0:
return 1
else:
while numero > 1 :
fatorial = fatorial * (numero - 1)
numero = numero - 1
return fatorial
#binomio(n,k) | false |
d9ecc8c75e4d583ccd8d6fae9ee5b55ad3277f08 | thiagodnog/projects-and-training | /Curso Python Coursera/Semana 3/Livro Texto/livroTexto-cap06Selecao-ex11.py | 624 | 4.5 | 4 | """"
Curso de Introdução à Ciência da Computação com Python Parte 1
Livro Texto
Exercício 11
Escreva uma função é_ânguloreto que, dado o comprimento de três lados de um triângulo, determina se o triângulo é retângulo.
Estenda o programa de forma que os lados possam ser dados à função em qualquer ordem.
"""
def é_ânguloreto (lado1,lado2,lado3):
if lado1**2 == lado2**2 + lado3**2:
print(True)
elif lado2**2 == lado1**2 + lado3**2:
print(True)
elif lado3**2 == lado1**2 + lado2**2:
print(True)
else:
print(False)
é_ânguloreto(1.5,2,2.5)
| false |
53475e0ec15e139658454977db364f8aee6f8770 | thiagodnog/projects-and-training | /Curso Python Coursera/Semana 7/Lista de Exercícios 5/lista5Exercicio1-ImprimeRetanguloCheio.py | 813 | 4.5 | 4 | """
Curso de Introdução à Ciência da Computação com Python Parte 1
Semana 7 - Lista de Exercício 5
Exercício 1
Escreva um programa que recebe como entradas (utilize a função input) dois números inteiros correspondentes à largura e à altura de um retângulo, respectivamente. O programa deve imprimir uma cadeia de caracteres que represente o retângulo informado com caracteres '#' na saída.
Por exemplo:
digite a largura: 10
digite a altura: 3
##########
##########
##########
digite a largura: 2
digite a altura: 2
##
##
"""
largura = int(input("digite a lagura: "))
altura = int(input("digite a lagura: "))
contador = largura
while altura != 0:
while contador != 0:
print("#", end="")
contador = contador - 1
altura = altura - 1
print()
contador = largura
| false |
871320f56c96bfeb535688ca29256777f12f8a6b | laharily/python | /Pirate Language.py | 1,896 | 4.21875 | 4 | def translate():
'''translate() -> None
Prompts user to enter dictionary files and input and output files
Changes words in input file according to the dictionary file
Write translation in output file'''
# input for file names
dictFileName = input('Enter name of dictionary: ')
textFileName = input('Enter name of text file to translate: ')
outputFileName = input('Enter name of output file: ' )
# open files
meanings = open(dictFileName, 'r')
inFile = open(textFileName, 'r')
outFile = open(outputFileName, 'w')
# turn the first file into a dictionary
dictionary = {}
for line in meanings:
line = line.strip("\n")
line = line.split("|") # split each line using the "|" sign
dictionary[line[0]] = line[1] # add words before and after sign as key and value to dict
meanings.close() # close the file meanings
# translate the input file
translated = " " # create new string
for line in inFile: # in each line
line = line.lower()
line = line.split()
for word in line: # for each word
if word in dictionary: # if that word can be translated
translated += dictionary[word] # find the value of that word in the dictionary and add to string
translated += " " # add space after each word
else: # if word can't be translated
translated += word # just add word to string
translated += " "
translated += "\n" # after each line add a new line
outFile.write(translated) # write the string into the output file
inFile.close() # close the input file
translate() # call the function
outFile.close() # close the output file
| true |
1c5768ef505c723ec59e8be4586050e73c1b5892 | laharily/python | /Testing Sets.py | 1,136 | 4.4375 | 4 | # A set is a list of values. You can store different values or data types just
# like a tuple, but you can change the values. A tuple doesn't allow you to
# change the values. A set is always sorted.
# A set removes duplicates.
mix = {"Lahari", 11, "Reading", 6, "A", 90.5, 5.2, "Lahari"}
print (mix)
set1 = {1, 2, 3, 35, 24, 3125, 98519, 0}
set2 = {1, 3, 2435, 78, 89, 9, 98159, 32}
# A union means combining more than one set together.
set3 = set1|set2
print (set3)
# An intersection means that you get a set with common values.
set4 = set1&set2
print (set4)
# A difference means the resulting set has unique values from the first set.
set5 = set1-set2
set6 = set2-set1
print (set5)
print (set6)
# A symmetric difference means elements that are in the first and the second but
# but not in both.
set7 = set1^set2
print (set7)
# Swimming is a set of students that are taking swimming lesosns. Tennis is a
# set of students who are taking tennis lessons.
swimming = {"Lahari", "Sydney", "Aashita"}
tennis = {"Rhea", "Nithya", "Vedavi", "Lahari"}
# List of students taking swimming and tennis lessons.
print (swimming&tennis)
| true |
d3415fdb5d5c28ee798727bdb55a2ade7cc7d961 | laharily/python | /Your Weight on the Moon.py | 522 | 4.15625 | 4 | print ("Weight each year on the moon:")
x = 100
y = 100
for z in range (1,15):
print ( y * 0.165)
y = y+1
x = x * 0.165
x = x + 15
print ("Weight on the moon after 15 years: " , x)
# Get the weight of myself and assign it to x and y. x=100, y=100
# Use a loop for z in range (1,15)
# print ("Weight each year on the moon: y * 0.165)
# y = y + 1
# Calculate weight of myself on the moon - x = x * 0.165
# Calculate your weight in 15 year on the moon: Add 15 years: x = x + 15
# Print x
| true |
b6edde581aeb860fa725f537cc49f463f6f02194 | preetika125/demo | /advancedTopics.py | 279 | 4.15625 | 4 | #list comprehension in python
a=[x**2 for x in range(1,5)]
print(a)
#generator expression
b=(x**2 for x in range(5,11))
print('generator object',b)
print('next value',next(b))
#map()
a=map(lambda x:x**2,range(1,10))
print(a)
#filter()
b=map(lambda x:x<5,range(1,10))
print(b)
| false |
35d46339a3d493046a588bb4af8e12f97209ed80 | Bernat2001/Simple-Calculator-Pyhton | /python1.py | 1,010 | 4.34375 | 4 | print("Esto es una calculadora")
print("-----------------------")
numero1=(int(input("Escribe el primer numero: ")))
print("-----------------------")
print("Elige entre: ")
print("+")
print("-")
print("*")
print("/")
print("**")
metodo=(str(input("Escribe el metodo de la operación: ")))
print("-----------------------")
numero2=(int(input("Escribe el segundo numero: ")))
print("-----------------------")
if metodo==("+"):
print(f"El resultado es: {numero1+numero2}")
print("Gracias por utilizar la calculadora")
if metodo==("-"):
print(f"El resultado es: {numero1-numero2}")
print("Gracias por utilizar la calculadora")
if metodo==("*"):
print(f"El resultado es: {numero1*numero2}")
print("Gracias por utilizar la calculadora")
if metodo==("/"):
print(f"El resultado es: {numero1/numero2}")
print("Gracias por utilizar la calculadora")
if metodo==("**"):
print(f"El resultado es: {numero1**numero2}")
print("Gracias por utilizar la calculadora")
| false |
d3c636975094c12297eb004b975441b797a160c9 | liamthanrahan/lunchtime-python | /2017/session-1/problem7.py | 482 | 4.65625 | 5 | # Calculate the sum of:
# every number from 1 to n divisible by 3
# Where n is a number supplied by the user.
# Submit your answer to the marker bot using functions as shown below. Do not change the name of the functions.
def sum_div3_numbers(n):
_sum_of_numbers = 0
for i in range(int(n)):
if (i % 3 == 0):
_sum_of_numbers += i
return _sum_of_numbers
# number = input("Sum of numbers divisible by 3 from 1 to: ")
# print(sum_div3_numbers(number))
| true |
773a5a2c9b1ce6915ae8eb8e26e3da1ab91dd0bb | jaramosperez/Pythonizando | /Conceptos/lectura_por_teclado.py | 468 | 4.15625 | 4 | # INGRESAR VALOR POR CONSOLA CON EL METODO INPUT()
# TODO LO QUE SE INGRESE POR ESE MÉTODO ES CONSIDERADO UN STRING O CADENA DE CARACTERES.
valor = input('Introduce un valor: ')
print(valor)
# print(valor + 100)
# CONVERTIR LOS VALORES INGRESADOS POR TECLADO A OTRO TIPO
# Se convierte en entero.
# int(valor)
valor = float(valor)
print(valor + 100)
# SE PUEDE ENGLOBAR TODO EN UNA SENTENCIA
valor = (float(input('Ingresa un valor numérico')))
print(valor + 200)
| false |
40fa3463de0630423bdb2bfdfbf35fa3c689e3f7 | jaramosperez/Pythonizando | /Conceptos/control_flujo_while.py | 2,004 | 4.3125 | 4 | # ¿QUE ES LA ITERACION?
# Iterar es realizar una determinada acción varias veces.
# Cada vez que se repite la acción se denomina iteración.
# LA MAGIA DE LAS ITERACIONES.
# Para encontrar un elemento, la computadora debe recorrer los registros
# y compararlos hasta encontrar el que se buscar.
#SENTENCIA WHILE (MIENTRAS)
# Se basa en repetir un bloque a partir de evaluar una condición lógica, siempre que ésta sea True.
# Nosotros como programadores, debemos planificar un momento en que la condición cambie a False y Finalice.
# Si no tiene una indicación las iteraciones no terminarian y entrariamos en un loop infinito.
# EJEMPLO 01
c = 0
while c <= 5:
c += 1
print('c Vale', c)
else:
print('Se han completado las iteraciones y el valor final para c es: ', c)
#EJEMPLO 02
numero = 0
while numero <= 10:
numero += 1
if (numero == 4):
print('Se rompe la iteración en: ', numero)
break
print('Numero vale: ', numero)
else:
print('Se ha completado la iteracion hasta el final con ', numero)
# EJEMPLO 03
otro_numero = 0
while otro_numero <= 10:
otro_numero += 1
if (otro_numero == 4):
print('Continuamos con las iteraciones ', otro_numero)
continue
print('Numero vale: ', otro_numero)
else:
print('Se ha completado la iteracion hasta el final con ', otro_numero)
# EJEMPLO 04
print("Bienvenido al menú interactivo")
while(True):
print("""¿Qué quieres hacer? Escribe el número de la opción
1) Quiero que me saludes
2) Quiero que me muestres los numeros del 1 al 10
3) Quiero irme a mi casa.""")
opcion = int(input('Ingresa el número de la opción'))
if opcion == 1:
print('Hola estimado!, espero que te guste Python\n')
elif opcion == 2:
n = 0
while(n <= 10):
print(n)
n += 1
elif opcion == 3:
print('Hasta la vista Baby!')
break
else:
print('Has seleccionado mal el comando, intentan nuevamente')
| false |
b1af189fa2e8b6846a512c303530fa4524728592 | jaramosperez/Pythonizando | /Conceptos/tuplas.py | 599 | 4.25 | 4 | # LAS TUPLAS SON COLECCIONES SIMILARES A LAS LISTAS CON LA DIFERENCIA QUE ESTAS SON INMUTABLES.
# NOS SIRVEN PARA ASEGURARNOS QUE CIERTOS DATOS NO SE PUEDAN MODIFICAR.
tupla = (100, "Hola", [1, 2, 3], -50)
print(tupla)
print(tupla[1])
print(tupla[2][1])
print(len(tupla))
# Podemos buscar con index en la tupla, pero entregará un error si no lo encuentprra
print(tupla.index('Hola'))
# Podemos usar count para buscar elementos repetidos
tupla_repetida = (10, 10, 10, 20, 20, 50, 70, 40, 100)
print(tupla_repetida.count('algo'))
# NO ACEPTA EL METODO APPEND. PUES NO SE PUEDE MODIFICAR LA TUPLA. | false |
67efa6af41db8b88bdce46391f6941f6b7dab69c | efrainc/data_structures | /binheap/binheap.py | 2,660 | 4.125 | 4 | #! /usr/bin/env python
# Queue Python file for Efrain, Mark and Henry
class Binheap(object):
def __init__(self):
self.items = []
def push(self, value):
"""Add value to bottom of binheap."""
self.items.append(value)
if len(self.items) > 1:
self.sort_bottom()
def pop(self):
"""Remove top value from the binheap."""
if len(self.items) > 1:
top = self.items[0]
self.items[0] = self.items.pop()
self.sort_top()
return top
else:
return self.items.pop()
def parent(self, position):
"""Return parent of current position."""
if position == 0:
raise AttributeError("At top of tree.")
return (position-1)/2
def child_L(self, position):
"""Return left child of current position."""
cl = 2*position + 1
if cl > len(self.items)-1:
return None
else:
return cl
def child_R(self, position):
"""Return right child of current position."""
cr = 2*position + 2
if cr > len(self.items)-1:
return None
else:
return cr
def find_max_child(self, position):
"""Return largest value between R and L child of current position."""
ChildR = self.child_R(position)
ChildL = self.child_L(position)
try:
if self.items[ChildL] >= self.items[ChildR]:
return ChildL
else:
return ChildR
except (AttributeError, IndexError, TypeError):
if ChildL is not None:
return ChildL
else:
raise TypeError
def switch(self, x, y):
"""Switch position of two nodes"""
(self.items[x], self.items[y]) = (self.items[y], self.items[x])
def sort_bottom(self):
"""Bubbles up a value to the right place from bottom to top"""
temp = len(self.items)-1
while self.items[temp] > self.items[self.parent(temp)]:
self.switch(temp, self.parent(temp))
try:
temp = self.parent(temp)
self.parent(temp)
except AttributeError:
break
def sort_top(self):
"""Pull value up from children to fill an empty position."""
temp = 0
while True:
try:
temp_child = self.find_max_child(temp)
if self.items[temp] < self.items[temp_child]:
self.switch(temp, temp_child)
temp = temp_child
except TypeError:
break
| true |
dc85cdc0a7fb4c109744f085d75310308e374c04 | akhavanmohsen/Python | /Game - You guess random number selected with computer.py | 342 | 4.125 | 4 | import random
guess = random.randint(1,99)
your_num = int(input('Please enter your guess number : '))
while guess != your_num :
if guess > your_num :
print ('Your guess is small ')
else:
print ('Your guess is big')
your_num = int(input('Please enter your guess number : '))
print('WoooooW, You are win')
| true |
bf21db68309029a4c908f993fa9d3cb435a6c81c | leila100/coding-exercises | /python/trapping_rain_water.py | 760 | 4.125 | 4 | '''
Given n non-negative integers representing an elevation map where the width of each bar is 1,
compute how much water it is able to trap after raining.
example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
'''
def trap(height):
"""
:type height: List[int]
:rtype: int
"""
l, r = 0, len(height) - 1
left_max, right_max = 0, 0
total_volume = 0
while l <= r:
left_max = max(height[l], left_max)
right_max = max(height[r], right_max)
if left_max < right_max:
total_volume += (left_max - height[l])
l +=1
elif left_max >= right_max:
total_volume += (right_max - height[r])
r -=1
return total_volume
print(trap([0,1,0,2,1,0,1,3,2,1,2,1])) | true |
6c5088cda3f60a1d58ab34241758c36ec200326b | leila100/coding-exercises | /python/topKFrequent.py | 2,710 | 4.25 | 4 | '''
Given a non-empty list of words, return the k most frequent elements.
Your answer should be sorted by frequency from highest to lowest.
If two words have the same frequency, then the word with the lower alphabetical order comes first.
Example 1:
Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
with the number of occurrence being 4, 3, 2 and 1 respectively.
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Input words contain only lowercase letters.
Follow up:
Try to solve it in O(n log k) time and O(n) extra space.
'''
'''
Time Complexity: O(NlogN), where N is the length of words. We count the frequency of each word in O(N) time, then we sort the given words in O(NlogN) time.
Space Complexity: O(N), the space used to store our frequencies.
'''
def topKFrequent(words, k):
# Record frequencies in hash table
freq = {}
for word in words:
if word in freq:
freq[word] += 1
else:
freq[word] = 1
# build another hash table with the keys being the freqs and values being list of words
freqWords = {}
for word in freq:
frequency = freq[word]
if frequency in freqWords:
freqWords[frequency].append(word)
else:
freqWords[frequency] = [word]
frequencies = sorted(freqWords.keys(), reverse = True)
solution = []
for f in frequencies:
for word in sorted(freqWords[f]):
if len(solution) < k:
solution.append(word)
else:
return solution
return solution
'''
def topKFrequent(self, words, k):
count = collections.Counter(words)
candidates = list(count.keys())
candidates.sort(key = lambda w: (-count[w], w))
return candidates[:k]
'''
'''
# time complexity: O(N+klogN): our heapq.heapify operation and counting operations are O(N), and each of k heapq.heappop operations are O(log N).
class Solution(object):
def topKFrequent(self, words, k):
count = collections.Counter(words)
heap = [(-freq, word) for word, freq in count.items()]
heapq.heapify(heap)
return [heapq.heappop(heap)[1] for _ in xrange(k)]
'''
words = ["i", "love", "leetcode", "i", "love", "coding"]
print(topKFrequent(words, 2)) | true |
a194078b82341c2634b9bfcfb5862e3471c0bc7d | leila100/coding-exercises | /codeSignal/theCore/labOfTransformations/characterParity.py | 922 | 4.46875 | 4 | '''
Given a character, check if it represents an odd digit, an even digit or not a digit at all.
Example
For symbol = '5', the output should be
characterParity(symbol) = "odd";
For symbol = '8', the output should be
characterParity(symbol) = "even";
For symbol = 'q', the output should be
characterParity(symbol) = "not a digit".
Input/Output
[execution time limit] 4 seconds (py3)
[input] char symbol
A symbol to check.
Guaranteed constraints:
symbol is guaranteed to be a UTF-8 symbol.
[output] string
'''
def characterParity(symbol):
try:
num = int(symbol)
if (num % 2 == 0):
return "even"
else:
return "odd"
except ValueError:
return "not a digit"
'''
def characterParity(s):
return "not a digit" if not s.isdigit() else "odd" if int(s)%2 else "even"
'''
print(characterParity("5"))
print(characterParity("4"))
print(characterParity("o")) | true |
4b5da4d08d54822de741c8b8e9f693ff2a59c6ba | Ajaymenonm/python-programming-CPSC-442 | /Assignment-02/assignment3.py | 1,223 | 4.1875 | 4 | # # The Hidden Word: Maya writes weekly articles for a well‐known magazine, but she is missing one word each time she is about to send the article to the editor. The article is not complete without this word. Maya has a friend, Dan, and he is very good with words, but he does not like just to give them away. He texts Maya a number, and she needs to find out the hidden word.
# The words can contain only the letters:
# "a", "b", "d", "e", "i", "l", "m", "n", "o", and "t".
# Luckily, Maya has the key:
# "a" – 6, "b" – 1, "d" – 7, "e" – 4, "i" – 3, "l" – 2, "m" – 9, "n" – 8, "o" – 0, and "t" – 5
# Write a function hidden(num) which accepts number and returns the hidden‐word which is missing.
input_number = input('enter the value: ') # get the number from command line
def hidden(num):
decoded_word = ""
num_array = map(int, str(num)) # strip number to digits
for i in num_array:
KEY = { # dictionary
6: "a",
1: "b",
7: "d",
4: "e",
3: "i",
2: "l",
9: "m",
8: "n",
0: "o",
5: "t",
}
decoded_word += KEY[i] # form decoded string
print(decoded_word)
hidden(input_number) | true |
963a23244ed5c59daa7cbbcfe12bdd70f8bed197 | Ajaymenonm/python-programming-CPSC-442 | /Assignment-01/assignment1.py | 338 | 4.375 | 4 | ## Write a Python program which prompts the user for a Celsius temperature, converts the temperature to Fahrenheit, and prints out the converted temperature.
print('Please enter the temperature in celsius')
celsius = input()
fahrenheit = round(((float(celsius) * 9) / 5 + 32), 2)
print("Temperature in Fahrenheit is " + str(fahrenheit))
| true |
c51dbcee89d07fc1657b0a5859a623f6b04d2377 | yatish0492/PythonTutorial | /4_List.py | 2,980 | 4.1875 | 4 | '''
Variables in Python
-------------------
List is identified by [ ].
List is Mutable.
List is heterogeneous.
'''
# List is Heterogeneous
a = [1,2,"yatish",25.3]
print(a) # Output --> [1, 2, 'yatish', 25.3]
# Like String it is negative indexed from end
a = [1,2,"yatish",25.3]
print(a[-1]) # Output --> 25.3
# Like String we can use range in index
a = [1,2,"yatish",25.3]
print(a[1:3]) # Output --> [2, 'yatish']
print(a[:3]) # Output --> [1, 2, 'yatish']
print(a[2:]) # Output --> ['yatish', 25.3]
# List is Mutable unlike string
a = [1,2,"yatish",25.3]
a[1] = "ashok" # Replace "yatish" with "ashok". replaced 1 with 1
print(a)
a = [1,2,"yatish",25.3]
a[1:3] = ["ashok","ramya"] # Replace 2,"yatish" with "ashok","ramya". replaced 2 with 2
print(a)
a = [1,2,"yatish",25.3]
a[1:3] = ["ashok","ramya","gagan"] # Replace 2,"yatish" with "ashok","ramya","gagan". replaced 2 with 3
print(a)
a = [1,2,"yatish",25.3]
a[1:3] = ["ashok"] # Replace 2,"yatish" with "ashok". replaced 2 with 1
print(a)
# Multi dimension List
a = [[1,2,3],[4,5,6]]
print(a[1][1])
# adding a new element to List. append() will add element at the last
a = [1,2,"yatish",25.3]
a.append(4) # Output --> [1, 2, 'yatish', 25.3, 4]
print(a)
a = [1,2,"yatish",25.3]
a.append([4,5]) # Output --> [1, 2, 'yatish', 25.3, [4, 5]]. It will not add 4 and 5 seperately
print(a) # to list. it actually adds one element only which will be list of [4,5]
# adding a new element to List at specified index. insert(index,element)
a = [1,2,"yatish",25.3]
a.insert(2,"ashok") # Output --> [1, 2, 'ashok', 'yatish', 25.3]. inserted "ashok" at index 2 and
print(a) # pushed other elements by 1 index.
# adding a list of elements as individual elements to list.
a = [1,2,"yatish",25.3] # Output --> [1, 2, 'yatish', 25.3, 4, 5]. instead of adding single element [4,5]
a.extend([4,5]) # to list. it added individual elements 4 and 5
print(a)
# remove element. pop()
a = [1,2,"yatish",25.3]
a.pop() # Remove last element
print(a)
a = [1,2,"yatish",25.3]
a.pop(1) # Remove element at index 1
print(a)
# remove elements using range. del
a = [1,2,"yatish",25.3]
del a[1:3] # Output --> [1, 25.3]. remove elements in range of [1:3]
print(a)
# clear the list
a = [1,2,"yatish",25.3]
a.clear()
print(a)
# min(list). similarly max(list), sum(list)
a = [1,2,25.3]
print(min(a)) # Output --> 1.
a = [1,2,"yatish",25.3]
#min(a) # Output --> TypeError: '<' not supported between instances of 'str' and 'int'
# sort()
a = [5,4,3,2,1]
a.sort()
print(a) # output --> [1, 2, 3, 4, 5]
| false |
ca1cf3cc542aa4a8cf0887dccfd3f6676d69dec5 | yatish0492/PythonTutorial | /33_Inner_Class.py | 951 | 4.71875 | 5 | '''
Inner Class
-----------
It is similar to Java, In outer class, if we need to access inner class members then we need to create object of inner
class and access them.
But one difference is that inner class doesn't have access to outer class members like java.
'''
class Student:
def __init__(self):
self.rollNumber = 1
def accessingChildClassMember(self):
obj = self.Laptop()
print(obj.brand) # accessing inner class member using inner class object.
class Laptop:
def __init__(self):
self.brand = "HP"
def accessingParentClassMember(self):
print(rollNumber) # this gives error as we cannot access out class members like java. even using
# 'self.rollNumber' doesn't help
studentObj = Student()
laptopObj = Student.Laptop()
studentObj.accessingChildClassMember()
laptopObj.accessingParentClassMember() | true |
e0de2fb275c218a375902b81552002567e878a49 | yatish0492/PythonTutorial | /interviewPrograms/4_Fibonacci.py | 343 | 4.15625 | 4 | '''
Fibonacci Series
----------------
0 1 1 2 3 5 8 13 ....
'''
def Fibonacci(n) :
a = 0
b = 1
print(a)
print(b)
for i in range(2,n) : # iterating from 2 as we have already printed 0 and 1
print(a + b)
c = b
b = a + b
a = c
Fibonacci(10) # Output --> 0 1 1 2 3 5 8 13 21 34
| false |
b336e0a984220a861a5e7ecdcb626d75bc25c089 | yatish0492/PythonTutorial | /pandas/4_GroupBy_DataFrame.py | 2,040 | 4.375 | 4 | '''
We can do groupby on the column of a data frame so that it creates seperate groups for each unique value in that column.
'''
import pandas as pd
data = {
'Country' : ['India','Paris','India','India','Paris'],
'places' : ['Taj Mahal', 'Eifil Tower', 'Madikeri', 'Goa', 'Catacomb'],
'Temperature' : [50, 30, 40, 20, 60]
}
dataFrame = pd.DataFrame(data)
groups = dataFrame.groupby('Country') # it will return type 'pandas.core.groupby.DataFrameGroupBy'. it basically creates
# something like Map with key value pair. key will be the each value of 'Country'
# column. Value will be the dataFrame of rows with corresponding country.
# Equivalent to - SELECT * FROM dataFrame GROUP BY Country
for country, countryDF in groups :
print("key : ", country)
print("Value : ", countryDF)
# Output --> key : India
# Value : Country places
# 0 India Taj Mahal
# 2 India Madikeri
# 3 India Goa
# key : Paris
# Value : Country places
# 1 Paris Eifil Tower
# 4 Paris Catacomb
IndiaGroupDF = groups.get_group('India') # Gets data frame of rows with 'Country' column value as 'India'.
maxNumberDF = groups.max()
# Output --> Country places Temperature
# India Taj Mahal 50
# Paris Eifil Tower 60
# It gives the max value of Integer/Numeric columns within each group. As in the output 50 is the max temperature of
# 'Temperature' column within 'India' group. similarly 60 for 'Paris'
meanNumberDF = groups.mean()
describedGroupsDF = groups.describe()
groups.plot() # Gives the plot of Temperature graphs. it gives 2 charts, one for 'India' and other for 'Paris'
# Basically, it plots the lines in graph for all Integer/Numeric columns
| true |
02f8bf06035361d6dede7a6836aa656bf66d3600 | SPritchard86/cp1404 | /cp1404Practicals/prac_05/word_occurrences.py | 1,062 | 4.40625 | 4 |
def main():
"""Get a string input and print out a formatted list of the occurrence number of words."""
string = input("Enter your string: ")
split_string = string.split(" ")
split_string.sort()
string_dictionary = create_dictionary(split_string)
longest_word_length = find_longest_word(split_string)
for word in string_dictionary:
print("{:{}s} : {}".format(word, longest_word_length, string_dictionary[word]))
def create_dictionary(split_string):
"""Count occurrence of words and return dictionary."""
string_dictionary = {}
for word in split_string:
if word in string_dictionary:
string_dictionary[word] += 1
else:
string_dictionary[word] = 1
return string_dictionary
def find_longest_word(split_string):
"""from a list, find the longest string and return its length."""
longest_word_length = 0
for word in split_string:
if len(word) > longest_word_length:
longest_word_length = len(word)
return longest_word_length
main()
| true |
bb14273f75abcc1ad13f1dd54983226a5030b035 | carward25/count_letters.py | /count_letters.py | 782 | 4.15625 | 4 | #name: Cassidy Ward
#date: 11/17/2021
#description: this program takes as a parameter a string
# and returns a dictionary that tabulates how many of each letter is in that string
def count_letters(string):
letter_dic = {}
#looping through each character in string, converted to upper case to
#minimise comparisons
for c in string.upper():
#checking if c is an alphabet
if c.isalpha():
#if c is already in letter_dic, adding 1 to current count
#note that the syntax is letter_dic[c] += 1 , not letter_dic[c] =+ 1
if c in letter_dic:
letter_dic[c] += 1
#otherwise, adding to dict with count=1
else:
letter_dic[c] = 1
#return the dictionary
return letter_dic | true |
2e16010f7a7ee1c43e92950b9ddced310f358aca | ujjwal82/Udemy | /best-top-python-3-advanced-programming-basics-for-beginners/practice - map.py | 756 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 23 09:05:05 2018
@author: Ujjwal
"""
# [iterable] =====> [new iterable]
# -------------- ------------------
# | element 1 | => | new element 1 |
# | element 2 | => | new element 2 |
# | element 3 | => | new element 3 |
# | ... | => | ... |
# | element N | => | new element N |
# -------------- -----------------
iterable = [1, 2, 3, 4]
# [Goal]
# List: [5, 10, 15, 20]
List = []
for number in iterable:
List.append(number * 5)
# [5, 10, 15, 20]
# here is how we can do this using MAP function
List = list(map(lambda n: n*5, iterable))
def multiply_by_5(number):
return number * 5
List = list(map(multiply_by_5, iterable))
| false |
3ae03bb8a5e948d62b043ab2ecd66c5d792a4895 | stephanieboroshok/Lab5 | /Probem 1.py | 584 | 4.1875 | 4 | # Dice Game Truth Table
# 1 point per odd number
# 3 points if sum of both dice even
# truth table on paper in notebook
def roll_dice (die1,die2):
if ((die1%2==0) and (die2%2==0)):
return ('You get 3 points!')
elif ((die1%2==1) and (die2%2==1)):
return ('You get 5 points!')
elif ((die1%2==1) and (die2%2==0)):
return ('You get 1 point.')
elif ((die1%2==0) and (die2%2==1)):
return ('You get 1 point.')
else:
pass
die1=int(input('Roll the first die:'))
die2=int(input('Roll the second die:'))
print (roll_dice(die1,die2)) | true |
62eaa3699886d7f2440c82fdcd78d366b7034d7c | xuejieshougeji0826/leetcode_top100 | /88.py | 677 | 4.1875 | 4 | '''给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
说明:
初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:
输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
输出: [1,2,2,3,5,6]'''
class Solution:
def merge(self, nums1, m, nums2, n):
for i in range(len(nums2)):
nums1[m+i]=nums2[i]
nums1.sort()
print(nums1)
s = Solution()
nums1 = [1,2,3,0,0,0]
m = 3
nums2 = [2,5,6]
n = 3
print(s.merge(nums1,3,nums2,3))
| false |
25e12017baf26b03e69e309450065a535b3cfc15 | KIMJUNSICK/basic_Python | /sequence_types.py | 593 | 4.25 | 4 | # sequrence type - list & tuple
# list is mutable
# tuple is immutable
# list - []
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
print(type(days)) # list
# list operation - in
print("Mon" in days) # True
print("MON" in days) # False
# list operation - len
print(len(days))
# list operation - reverse
days.reverse()
print(days)
# list operation - clear
days.clear()
print(days)
# list operation - append
days.append("Sat")
print(days)
# find data in list with order infomation
print(days[0]) # Thu
# tuple - ()
days2 = ("Mon", "Tue", "Wed", "Thu", "Fri")
print(type(days2)) # tuple
| true |
7d658da5e9c58da623f20873281ea3b4857330b3 | joselitan/selenium-python-framework | /tests/trash/test_util.py | 490 | 4.125 | 4 |
def verifyListContains(expectedList, actualList):
"""
Verify actual list contains elements of expected list
parameters:
expectedList: Expected List
actualList: actual List
"""
length = len(expectedList)
for i in range(0, length):
if expectedList[i] not in actualList:
return False
else:
return True
expectedList = [6,7,8,9,10]
actualList = [1,2,3,4,5]
print(verifyListContains(expectedList, actualList))
| true |
cc87320cdbd93636ec382f797635b82da25d186b | andymithamclarke/Pundits-Review-Scraping | /phase_three_pipeline_inside_notebook/matchreportscraper/modules/lemmatize_remove_stopwords.py | 853 | 4.125 | 4 | # =========================
# This file contains a function to lemmatize a phrase and remove stopwords from the phrase
# =========================
# The function will remove the words in the phrase that are present within the customized list of stopwords
# It will then return all words to their lemma form
# This is done in order to best process the phrase for sentiment analysis
# =============
# IMPORTS
# =============
from nltk.stem import WordNetLemmatizer
from nltk import word_tokenize
# Local imports
import modules.stopwords as stopwords
# =============
# The Function
# =============
def lemmatize_remove_stopwords(phrase):
# Apply the functionality with a list comprehension and return the string
return " ".join([WordNetLemmatizer().lemmatize(word) for word in word_tokenize(phrase) if word not in stopwords.stopwords()])
| true |
07a3eb685d1f854446a363d129dd07894f5ebf4b | leonzh2k/Harbinger | /NEW 1Buttons and positoning.py | 692 | 4.1875 | 4 | from tkinter import*
root=Tk()
theLabel=Label(root,text="This is our Tkinter window")
theLabel.pack()
theLabel=Label(root,text="This is our second sentence")
theLabel.pack()
topFrame=Frame(root)
topFrame.pack() #Python will know this is top based on the below code
botFrame=Frame(root)
botFrame.pack(side=BOTTOM)
theButton1=Button(None,text="Click Me!",fg="Blue")
theButton1.pack(side=LEFT)
theButton4=Button(None,text="Click Me!",fg="Yellow")
theButton4.pack(side=RIGHT,fill=X)
theButton3=Button(None,text="Click Me!",fg="Purple")
theButton3.pack(side=RIGHT,fill=Y)
theButton2=Button(None,text="Hello!",fg="Red")
theButton2.pack(side=LEFT)
root.mainloop()
| true |
a54d8c2bb51813c5b397444cd8cd55752e541095 | littlecorner/LearnPython | /untitled/chapter06/6.4访问权限.py | 1,144 | 4.21875 | 4 | #具有私有权限的属性和方法在类内部是可以被访问的,在类外部无法访问私有属性和方法
class Dog:
def __init__(self,n):
self.name = n
self.__age = 1 #私有属性
#私有方法,用于设置年龄
def __setAge(self,a):
self.__age=a
#设置名字和年龄属性
def setInfo(self,name,age):
#如果传入的名字不是空字符串,则给对象设置新的名字
if name!="":
self.name=name
if age>0 and age<=20:
#调用私有方法设置年龄
self.__setAge(age)
else:
print("设置年龄失败,非法年龄!")
def getInfo(self):
#在函数内访问私有属性"__age"
print("我的名字是:{},我现在{}岁!".format(self.name,self.__age))
wangcai=Dog("旺财")
wangcai.getInfo()
print("我长大了!")
#给旺财设置新的年龄
wangcai.setInfo("",10)
wangcai.getInfo()
#在类外部无法访问私有属性和方法 故报错!!!!
#print("我的名字是:{},我{}岁了!".format(wangcai.name,wangcai.__age))
#wangcai.__setAge(10) | false |
5439fad36fd6b71c88f0428444e3bc97071dbf37 | sibylle69/CS50-Harvard-course-exercises | /sibylle69-cs50-problems-2020-x-mario-less (1)/sibylle69-cs50-problems-2020-x-mario-less/mario.py | 308 | 4.15625 | 4 | #!/usr/bin/python
h = input("Height:")
if int(h) > 8 or int(h) < 1:
print("Height must be smaller than 8")
h = input("Height:")
for i in range(int(h)):
for j in range(int(h)-1-i):
print(" ", end ="")
for k in range(i+1):
print("#", end ="")
print()
| false |
312fdfb129cc8fccb64330df320fbc1a9689f043 | TheTekUnion/Software | /console_applications/console_prime.py | 662 | 4.3125 | 4 | #Makes the program run continuously (RUNTIME)
while True:
try:
#user input
number = int(input("Enter a number "))
#Initially True
prime = True
#2 - sqrt of number
for factor in range(2, int(number ** 0.5 + 1)):
#Trial Division Algorithm
if number % factor == 0:
prime = False
break
#Output
if prime is True:
print("%d is a prime number" %number + ".")
else:
print("%d is not a prime number" %number + ".")
#Check for type error with general exception
except:
print("You cannot enter text.") | true |
c783445049bc8f39032c1580af55d6f866b9d0c7 | TheTekUnion/Software | /console_applications/distance_formula.py | 407 | 4.1875 | 4 | import math
while True:
try:
x2 = float(input("Enter x2: "))
x1 = float(input("Enter x1: "))
y2 = float(input("Enter y2: "))
y1 = float(input("Enter y1: "))
def distance(y1, y2, x1, x2):
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
print("Distance: " + str(distance(y1, y2, x1, x2)))
except:
print("You cannot enter text.") | false |
9b514c1cef3f31eea5bc368412e7708f1fd03b16 | vero-obando/Programacion | /Clases/ejemploWhile.py | 883 | 4.15625 | 4 | # Entradas
MENSAJE_BIENVENIDA = 'Muy buenos dias, despierte que esta en clase de 6'
PREGUNTA_MENU = ''' Ingrese
1. Para mostrar numeros del 1-5
2. Para preguntar tu nombre
3. Para mostrar el año en el que estamos
4.Salir
'''
PREGUNTA_NOMBRE = 'Ingrese su nombre por favor : '
MENSAJE_ERROR = 'Por favor ingresa una opcion valida'
# Codigo
entrada = 1
while ( entrada >= 1 and entrada <= 3):
entrada = int (input (PREGUNTA_MENU))
print (entrada)
if (entrada == 1):
print (1,2,3,4,5)
elif (entrada == 2):
nombre = input (PREGUNTA_NOMBRE)
print (f'Bienvenido {nombre} a este menu emplea otras opciones')
elif (entrada == 3) :
print ('Estamos en el año 2021')
elif (entrada == 4):
print ('Muchas gracias por usar el programa feliz dia')
else:
entrada = 1
print (MENSAJE_ERROR)
| false |
f3e1047442abae512088bc7822bf3a46fac229df | cjb5799/DSC510Fall2020 | /Shareef_DSC510/Shareef_3.1.py | 1,380 | 4.3125 | 4 | #DSC 510
#Week 3
#Programming Assignment Week 3
#Author Adonis Shareef
#09/20/2020
#welcome the user
print("Welcome!")
#ask the user for thier company name
companyName = input("Enter the name of your servicing company.")
fiberOpticCable = 0
#validate user input with try except
valid_input = False
while not valid_input:
try:
fiberOpticCable = float(input("Enter the number of feet of fiber optic cable needed."))#ask the user for the amount of cable needed in feet
if fiberOpticCable < 0:
print("Enter a positive numerical value such as 1,2,3...")
continue
break
except ValueError:
print("Enter a positive numerical value such as 1,2,3...")
continue
#conditional statements for cost per feet
if 100 < fiberOpticCable <= 250 :
charge_per_foot = 0.8
elif 250 < fiberOpticCable <= 500:
charge_per_foot = 0.7
elif fiberOpticCable > 500:
charge_per_foot = 0.5
else:
charge_per_foot = 0.87
#calculate the total cost
initialCost = round((int(fiberOpticCable)*charge_per_foot),2);
#calculate tax
tax = round((0.095*initialCost),2);
totalCost = initialCost + tax;
#receipt format
print("\tRecipt")
print("\tCompany: ",companyName)
print("\t"+"Calbe: ",fiberOpticCable,"ft")
print("\tRate per foot: $", charge_per_foot)
print("\tCost: $",initialCost)
print("\tTax: $",tax)
print("\tTotal: $",totalCost)
| true |
c23100f644794b9b4802624f6b0956c92111a140 | cjb5799/DSC510Fall2020 | /Sutow_DSC510/Assignment5.1.py | 1,791 | 4.625 | 5 | #DSC 510#
#Week 5#
#Programming Assignment Week 5#
#Author: Brett Sutow#
#9/28/2020#
#If changes made please fill-out log#
#Change:#
#Changes Made:#
#Date of Change:#
#Author:#
#Change Approved By:#
#Date Moved to Production:#
'''The following program will create a mathemtical equation where the user can input
the numbers and the operation that is needed. This eqution will return the correct total'''
#Introduction#
print('Hello!')
name = input('What is your name?')
print("Welcome {name}! Let's begin the mathematical equation!".format(name = name))
#Defines first number#
num1 = float(input('Enter the first number: '))
#Defines second number#
num2 = float(input('Enter the second number: '))
#Defines which operator the user chooses
operator = input('Choose a mathematical operator: ')
#Below performs and defines calculation#
def performCalculation(opeartor):
if operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
elif operator == "/":
print(num1 / num2)
performCalculation(operator)
#The following function will allow the user to input a list, and then get the total sum and average#
#User inputs how many numbers they would like to list#
list_of_input = []
how_many_numbers = int(input('How many numbers would you like to input: '))
#Creates loop for the numbers input#
for n in range(how_many_numbers):
numbers = int(input('Enter the list'))
list_of_input.append(numbers)
#Defines the function and begins the process of calculating sum and average#
def calculateAverage():
total=sum(list_of_input)
average=(sum(list_of_input))/(len(list_of_input))
return(total,average)
calculateAverage()
print('Total sum and average an of list:', calculateAverage())
| true |
50b55f3f8cb8ded473276c2f3458a6bac77f975d | cjb5799/DSC510Fall2020 | /CHAVALI_DSC510/Assignment_8.1.py | 1,376 | 4.15625 | 4 | # DSC510
# Week 8 Assignment - Assignment_8.1.py
# calculating Word frequency
# Author Sowmya Chavali
# 10/22/20
import string
# This function checks if an individual word is in the dictionary and adds it as a key if it is not present.
def add_word(w,dict):
if w not in dict.keys():
dict[w] = 0
dict[w] += 1
# Process_line cleans a line of text from the input and calls add_word() to add the words from
# each line to the dictionary.
def process_line(text,file_dict):
for s in text:
# stripping punctuation
no_punct=s.translate(str.maketrans('', '', string.punctuation))
# Convert to lowercase and split words into a list.
words = no_punct.lower().split()
for word in words:
add_word(word,file_dict)
#This function prints the word frequency from the dictionary
def pretty_print(wordDict):
print("Length of the dictionary: %i" %len(wordDict))
print("Word Count")
print("------------------------")
for w in sorted(wordDict, key =wordDict.get, reverse=True):
print("%12s %s" % (w.ljust(12), wordDict[w]))
def main():
gba_file = open('gettysburg.txt', 'r') # opening the text file in read mode
file_dict = {}
lines = [line.rstrip('\n') for line in gba_file] # getting rid of newline chars
process_line(lines, file_dict)
pretty_print(file_dict)
main()
| true |
1458d6e57545dcc8cdfbebed8079af264b1b4ec7 | cjb5799/DSC510Fall2020 | /FENCL_DSC510/Assignment 11.1.py | 1,427 | 4.15625 | 4 | # DSC 510
# Week 10
# Programming Assignment Week 10
# Author Riley Fencl
# 11/7/2020
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
class CashRegister:
def __init__(self, count=0, total=0):
self.registertotal = total
self.registercount = count
def getTotal(self):
return self.registertotal
def getCount(self):
return self.registercount
def additem(self, price):
self.registercount += 1
self.registertotal += price
def main():
print("Howdy! Welcome to Cash Register Program!")
user_register = CashRegister()
user_action = {}
while user_action != "quit":
user_action = input("Would you like to add an item to your shopping cart? (Type Quit to exit).\n").lower()
if user_action == "quit":
break
elif user_action != "yes":
print("Please enter either yes or quit")
continue
user_input = float(input("Please enter the price of your item (No $ is necessary).\n"))
user_register.additem(user_input)
print("Thanks for using my program!\n"
"Here are the totals for your shopping cart!")
print("-------------------------------------------")
print("Shopping Cart Quantity: ", user_register.getCount(), "item(s)")
print("Shopping Cart Total: ", locale.currency(user_register.getTotal()))
main()
| true |
7358e88ff75fb5dcb0054cd884b6becbc313f9b7 | rupaliwaghmare/If-else | /time.py | 632 | 4.1875 | 4 | time=float(input("enter the time"))
if time>=6.30 and time<=7.30:
print("morning exercise")
elif time>=7.30 and time<=9.00:
print("break")
elif time>=9.00 and time<=10.00:
print("english activity")
elif time>=10.00 and time<=13.00:
print("coding")
elif time>=13.00 and time<=14.30:
print("break")
elif time>=14.30 and time<=17.00:
print("coding")
elif time>=17.00 and time<=17.29:
print("break")
elif time>=17.30 and time<=19.00:
print("culture activity")
elif time>=19.00 and time<=20.00:
print("study time")
elif time>=20.00 and time<=21.00:
print("learning circle")
| true |
dc625dbca8327727e6f382dd867a4f43a55c0448 | Suhail727/GeneralProgramming | /Sorting (Merge Sort).py | 1,488 | 4.40625 | 4 | def mergeSort(a):
# Sort only if there is more thanone element in array
if len(a)>1:
# Find the middle index and create 2 lists, left and right.
mid = len(a)//2
l = a[:mid]
r = a[mid:]
# Call the function recursively until left and right lists have only one element each
mergeSort(l)
mergeSort(r)
# Merge Function
# i for left list, j for right list, k for main list
i = j = k = 0
# i and j should be within size of left and right list. If they aren't, it means either list has become empty.
# In that case move to next while loop
while i < len(l) and j < len(r):
# Check which is smaller value from left and right list, whichever is smaller append to main list
if l[i] < r[j]:
a[k] = l[i]
i += 1
else:
a[k] = r[j]
j += 1
k += 1
# If either left or right list becomes empty, just append the remaining list elements to the main list.
while i < len(l):
a[k] = l[i]
i += 1
k += 1
while j < len(r):
a[k] = r[j]
j += 1
k += 1
# Code to print the list
def printList(arr):
for i in range(len(arr)):
print(arr[i],end=" ")
print()
# driver code to test the above code
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print ("Given array is", end="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)
| true |
afc37162626711beb5971f529e0c1dc4b64ddc90 | bibek1892/python_assignment2 | /qn10.py | 922 | 4.4375 | 4 | #10. Write a function that takes camel-cased strings (i.e.
#ThisIsCamelCased), and converts them to snake case (i.e.
#this_is_camel_cased). Modify the function by adding an argument,
#separator, so it will also convert to the kebab case
#(i.e.this-is-camel-case) as well.
def case_converter(camelcase):
seperator='_'
string = camelcase[0].lower()
for letter in camelcase[1:]:
if letter.isupper():
string += seperator + letter.lower()
else:
string += letter
return string
res = case_converter('ItsMeBibekKhatiwada')
print("snake case:", res)
def case_converter(camelcase, seperator):
string = camelcase[0].lower()
for letter in camelcase[1:]:
if letter.isupper():
string += seperator + letter.lower()
else:
string += letter
return string
res = case_converter('ItsMeBibekKhatiwada', '-')
print("kebab case:", res) | true |
3412d25307905197d4db0aea9867a233c9f476b5 | bibek1892/python_assignment2 | /qn7.py | 756 | 4.28125 | 4 | #7. Create a list of tuples of first name, last name, and age for your
#friends and colleagues. If you don't know the age, put in None.
#Calculate the average age, skipping over any None values. Print out
#each name, followed by old or young if they are above or below the average age.
friends_list = [('Bibek', 'Khatiwada', 25), ('Basbin', 'Wagle', 26), ('Ashok', 'Dahal', 24), ('Kishor', 'Karki', 23),
]
sum_age = 0
count = 0
for items in friends_list:
if items[2] != None:
count += 1
sum_age += items[2]
avg_age = sum_age // count
for items in friends_list:
if items[2] != None:
print(items[0], end=':-')
if items[2] > avg_age:
print('Old')
else:
print('Young')
| true |
2fb24e6e9ef9ca90eced0e7ff444016a6c5b0e9c | sergey-pashaev/practice | /py/src/practice/aoc/y2015/d2p2.py | 1,410 | 4.15625 | 4 | # Day 2, Part Two
# The elves are also running low on ribbon. Ribbon is all the same
# width, so they only have to worry about the length they need to
# order, which they would again like to be exact.
# The ribbon required to wrap a present is the shortest distance
# around its sides, or the smallest perimeter of any one face. Each
# present also requires a bow made out of ribbon as well; the feet of
# ribbon required for the perfect bow is equal to the cubic feet of
# volume of the present. Don't ask how they tie the bow, though;
# they'll never tell.
# For example:
# A present with dimensions 2x3x4 requires 2+2+3+3 = 10 feet of
# ribbon to wrap the present plus 2*3*4 = 24 feet of ribbon for the
# bow, for a total of 34 feet.
# A present with dimensions 1x1x10 requires 1+1+1+1 = 4 feet of
# ribbon to wrap the present plus 1*1*10 = 10 feet of ribbon for the
# bow, for a total of 14 feet.
# How many total feet of ribbon should they order?
from typing import List
import math
def ribbon(string: str) -> int:
parts = list(filter(lambda x: len(x) > 0, string.split("x")))
if len(parts) != 3:
return 0
dimensions: List[int] = list(map(int, parts))
perimeters: List[int] = [
2 * (dimensions[0] + dimensions[1]),
2 * (dimensions[1] + dimensions[2]),
2 * (dimensions[2] + dimensions[0]),
]
return min(perimeters) + math.prod(dimensions)
| true |
7c55cf4479a4173ee65254c09c0635d3fda10f79 | vik407/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 239 | 4.28125 | 4 | #!/usr/bin/python3
def uppercase(str):
for char in str:
charoffset = 0
if ord(char) > 96 and ord(char) < 123:
charoffset = -32
print("{:s}".format(chr(ord(char) + charoffset)), end='')
print('')
| false |
a81e13b08520d96ce81927ba30d6ac4006aac74f | max-belichenko/django-cathedral | /date_to_day_of_week_rus.py | 680 | 4.1875 | 4 | def date_to_day_of_week_rus(d: 'datetime.date') -> str:
"""
Returns name of a weekday for a date of the standart datetime module.
Language: Russian.
Example:
d = date(year=2020, month=5, day=15)
return value: 'пятница'
"""
WEEKDAY = {
0: 'понедельник',
1: 'вторник',
2: 'среда',
3: 'четверг',
4: 'пятница',
5: 'суббота',
6: 'воскресенье'
}
return WEEKDAY[d.weekday()]
if __name__ == '__main__':
from datetime import date, time
d = date(year=2020, month=5, day=15)
print(date_to_day_of_week_rus(d))
| true |
cd07a19ef3dedabaa281c6c332c70e28acf1f04a | CSteele97/Leeds-stuff | /classes.py | 1,891 | 4.125 | 4 | # Define a class - person is the name of the class and is a new type of class
# Define a function that will operate within the class that gives the person money and
# happiness values
class Person:
def __init__(self, money, happiness):
self.money = money
self.happiness = happiness
# This function will change the money and happines values based on whether "work" is
# assigned to the person
def work(self):
self.money = self.money + 10
self.happiness = self.happiness - 5
# This function will change the money and happiness based on whether any money is spent
def consume(self):
self.happiness += 7
self.money -= 8
# This will print the definitions for the self.money and self.happiness function
def __repr__(self):
return (f"A person with money = {self.money} "
f"and happiness = {self.happiness}")
# Interact with another person which increases both their happiness
def interact(self, other):
self.happiness += 1
other.happiness += 1
# Create a variable (person) called Jitse that has a money value of 100
# and a happiness value of 10
jitse = Person(100, 10)
# Can check the money and happiness values of the person by typing jitse.money in the
# right corner window
# This assignes the work function to Jitse
jitse.work()
# This assignes the consume function to Jitse
jitse.consume()
# This can see how much money Jitse has now he is working
print("Jitse's money:", jitse.money)
# Adding an f in front of the string means curly brackets can be used
print(f"Jitse: money = {jitse.money}, "
f"happiness = {jitse.happiness}")
print(jitse)
# Create a new person
rob = Person(500, 5)
# Make rob interact with jitse
rob.interact(jitse)
print('After interaction:')
print(jitse)
print(rob) | true |
ad147a78b791aed03146050b033e7c5ea002ee80 | cauequeiroz/pythonprinciples.com | /challenge_02.py | 454 | 4.15625 | 4 | # Middle letter
# Write a function named mid that takes a string as its parameter. Your function should extract and
# return the middle letter. If there is no middle letter, your function should return the empty string.
# For example, mid("abc") should return "b" and mid("aaaa") should return "".
# https://pythonprinciples.com/challenges/Middle-letter/
def mid(text):
if len(text) % 2 == 0:
return ""
return text[len(text) // 2]
| true |
2cccc241644b7076b2a1aeedd259d5479497347f | HughesJoshB/CSC-121 | /M5HW2/classCar.py | 909 | 4.125 | 4 | # Joshua Hughes
# April 12th 2017
# Car class assignment
# M5HW2
increase = 5
decrease = 5
# create class Car
class Car:
def __init__(self, year, make, speed):
self.__year_model = year
self.__make = make
self.__speed = speed
# Define the agrument for year_model
def set_year(self, year):
self.__year = year
# define the agrument for make
def set_make(self, make):
self.__make = make
# Define the agrument for speed
def set_speed(self, speed):
self.__speed = 0
# Define the get agrument for year_model
def get_year_model(self):
return self.__year_model
# Define the get agrument for make
def get_make(self):
return self.__make
# Define the get agrument for speed
def get_speed(self):
return self.__speed
# Define Accelerate
def accelerate(self):
self.__speed += increase
# Define brake
def brake(self):
self.__speed -= decrease
| false |
b04b396865a75ea3682f61b40d36e373b1ba4e30 | AwuorMarvin/Prime_Number_Generator | /prime_generator.py | 747 | 4.21875 | 4 | def prime_number_generator(maximum):
ls = [] #Empty list into which th values will be stored for easier use with the tests
for num in range(2, maximum + 1): #Looping through the given range
if num > 1: #Ensuring that the numbers are all positive
for i in range(2, num): #Looping between 2 and each of the numbers from the outer loop
if (num % i) == 0: #checking to see if any of the numbers from the second loop divides the value from the outer loop
break #break out of the loop to improve run time
else:
#print(num) - This was for debugging purposes
ls.append(num) #Append the numbers sequentially
return ls #return the resulting list | true |
24630b885b89833680966732901b855f106cd5a3 | dsakurai/bad_code | /main.py | 1,099 | 4.125 | 4 | import datetime
# Unit test の例
def square(x):
"""
Calculate the square of x.
>>> square(2)
4
>>> square(-2)
4
"""
return x * x
def age_in_days(birthday, today):
"""
誕生日から日齢を計算する
- 例: age_in_days("1900-01-01", "2021-09-03")
- birthday: "YYYY-MM-DD" の 形式の誕生日の文字列
- today: "YYYY-MM-DD" の 形式の今日の文字列
"""
if birthday == "":
# raise Exception("Bad input")
print("Bad input.")
exit(1)
# return None
# 誕生日の年月日
year, month, day = birthday.split("-")
# 今日の年月日
t_year, t_month, t_day = today.split("-")
# 年の差
diff_years = 365 * float(t_year) - float(year)
# 月の差
diff_months = 31 * float(t_month) - float(month)
# 日の差
diff_days = float(t_day) - float(day)
return diff_years + diff_months + diff_days
x = 3
age = age_in_days("", "2000-03-01")
print(age)
# if __name__ == '__main__':
# import doctest
# doctest.testmod()
| false |
8ee11b2bb619216f8987e5dd8f712fa5b37c64b0 | arifcahya/introduction | /Harshrathore_21BCON019_10th.py | 515 | 4.28125 | 4 | #To check if the program is 1,2,3 digit
#Taking input from user
num = int(input("Enter number : "))
#for input less than 0
if num<0:
print("Invalid Entry. Valid range is 0 to 999.")
#For single digit number
elif num<10:
print("Single digit number is entered.")
#For two digit number
elif num<100:
print("Two digit number is entered.")
#For three digit number
elif num<1000:
print("Three digit number is entred.")
#For all other cases
else:
print("Invalid Entry. Valid range is 0 to 999.")
| true |
56ecfe904a2d7f38197b6eb7b5b02f8037e190da | arifcahya/introduction | /palindrome.py | 218 | 4.15625 | 4 | '''Write a Python program to check whether a given number is palindrome or not?'''
number = input()
if str(number)==str(number[::-1]):
print(f'{number} is palindrome number')
else:
print(f'{number} is not palindrome')
| false |
212fa7a125fd808b02a1b605464f3ae1b86941b3 | TranshumanSoft/Classify-by-name | /classifybyname.py | 661 | 4.34375 | 4 | print("Some people will have chocolate or vanilla icecream, it depends on their names.")
name = str(input("What's your name?"))
name = name.lower()
group = ""
if name.startswith("a" or "b" or "C" or "d" or "e" or "f" or "g" or "h" or "i" or "j" or "k" or "l" or "m"):
print("You are from group 'A'." )
group = group + "A"
else:
print("You are from group 'B'.")
group = group + "B"
icecream = str(input("What is your group?"))
icecream = icecream.upper()
if icecream == "A":
print("Here's your vanilla icecream!")
elif icecream == "B":
print("Here's your chocolate icecream!")
else:
print("That group doesn't exist.") | true |
be0925c28ff4912af2e11046c3a76389d40a5cd6 | sphinx-gallery/sample-project | /SampleModule/module.py | 563 | 4.1875 | 4 | def fun_power(x,y):
"""
Returns x raised to the power of y.
Parameters
----------
x : int
base
y : int
exponent
Returns
-------
out : int
the result of x to the power of y
"""
return x**y
class class_power():
"""A class that performs the power function."""
def __init__(self, x, y):
self.x = x
self.y = y
def power(self):
try:
return self.x**self.y
except:
print('Something went wrong. Make sure x and y are both numbers')
| true |
c0fcfc444310297cfae187bab6f316b0a62c5fc8 | fernandezjames24/python-training | /PythonBasics/Basic String Operators/BasicStringOperators.py | 1,271 | 4.15625 | 4 |
#change string variable s to a string appropriate on criteria below
#the string would be "string data welcome!"
s = "String data welcome!"
# Length should be 20
print("Length of s = %d" % len(s))
# First occurrence of "a" should be at index 8
print("The first occurrence of the letter a = %d" % s.index("a"))
# Based on variable s, it has 2 a's on word "data"
print("a occurs %d times" % s.count("a"))
# Slicing the string into bits
print("The first five characters are '%s'" % s[:5]) # Start to 5
print("The next five characters are '%s'" % s[5:10]) # 5 to 10
print("The thirteenth character is '%s'" % s[12]) # Just number 12
print("The characters with odd index are '%s'" %s[1::2]) #(0-based indexing)
print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end
# to uppercase
print("String in uppercase: %s" % s.upper())
#to lower case
print("String in lowercase: %s" % s.lower())
# s variable starts with a string "Str" from word "String"
if s.startswith("Str"):
print("String starts with 'Str'. Good!")
# s variable ends with a string "ome!" from word "welcome!"
if s.endswith("ome!"):
print("String ends with 'ome!'. Good!")
# when s splitted, it contains exactly 3 words
print("Split the words of the string: %s" % s.split(" "))
| true |
af797989b99c6a843e80532a635e5743077ad2db | fernandezjames24/python-training | /PythonBasics/Functions/Functions.py | 1,000 | 4.4375 | 4 |
# function list_benefits() returns a list of strings
def list_benefits():
return ["More organized code","More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"]
# function that returns a string that starts with its argument and will end
# with literal "is a benefit of functions!"
def build_sentence(info):
return info + " is a benefit of functions!"
# main function to run
def name_the_benefits_of_functions():
# assigning list_benefits() func to a variable (since list_benefits() returns
# a list, list_of_benefits variable will become a list)
list_of_benefits = list_benefits()
# iterate through list_of_benefits elements
for benefit in list_of_benefits:
# prints build_sentence(benefit) function, which returns a string.
# benefit value is an element of list_of_benefits list per successive
# iteration
print(build_sentence(benefit))
# call function
name_the_benefits_of_functions()
| true |
bfc2f3ea30b5fac8d1ffbd8f4e026bf9d6d9c3ae | candytale55/modules_python_examples_Py_3 | /random_sample.py | 2,072 | 4.1875 | 4 |
# random.sample() takes a range and a number as its arguments. It will return the specified number of random numbers from that range.
import codecademylib3_seaborn
from matplotlib import pyplot as plt
import random
numbers_a = range(1,13)
# range of numbers 1 through 12 (inclusive).
print(numbers_a)
numbers_b = random.sample(range(1000),12)
# a random sample of twelve numbers within range(1000).
print(numbers_b)
# plot these number sets against each other using plt. Call plt.plot() with your two variables as its arguments.
plt.plot(numbers_a, numbers_b)
plt.show()
# When we want to invoke the randint() function we call random.randint(). This is default behavior where Python offers a namespace for the module.
# A namespace isolates the functions, classes, and variables defined in the module from the code in the file doing the importing. Your local namespace, meanwhile, is where your code is run.
# Python defaults to naming the namespace after the module being imported, but sometimes this name could be ambiguous or lengthy. Sometimes, the module’s name could also conflict with an object you have defined within your local namespace.
# this name can be altered by aliasing using the as keyword:
# _import module_name as name_you_pick_for_the_module_
# You usually use aliases if the name of the library is long and typing it every time you want to use one of its functions takes a lot of time.
# import * where the * ,known as a “wildcard”, matches anything and everything in the library. This syntax is considered dangerous because it could _pollute_ the local namespace.
# Pollution occurs when the same name could apply to two possible things. For example, you have a function floor() for floor tiles, and using _from math import *_ you also import a function floor() that rounds down floats
# https://discuss.codecademy.com/t/what-happens-if-i-import-an-module-or-function-that-conflicts-with-an-object-defined-in-my-local-namespace/374440
# https://discuss.codecademy.com/t/what-is-the-codecademylib3-seaborn-module/461312
| true |
d436f6cf4df4d2a1c6aab21df588f354e6043ba4 | oabuoun/calculator | /calculator/calc_functions.py | 371 | 4.15625 | 4 | def add(number1, number2):
number3 = number1 + number2
return number3
def subtract(number1, number2):
number3 = number1 - number2
return number3
def multiply(number1, number2):
number3 = number1 * number2
return number3
def divide(number1, number2):
if number2 == 0:
return None
number3 = number1 / number2
return number3
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.