blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
e08c9f11aab1e0131d5f37feeb01f6475ae6ec23
|
Jwbeiisk/daily-coding-problem
|
/feb-2021/Feb22.py
| 1,107
| 4.3125
| 4
|
#!/usr/bin/env python3
"""
22th Feb 2021. #537: Easy
This problem was asked by Apple.
A Collatz sequence in mathematics can be defined as follows. Starting with any positive integer:
if n is even, the next number in the sequence is n / 2
if n is odd, the next number in the sequence is 3n + 1
It is conjectured that every such sequence eventually reaches the number 1. Test this conjecture.
Bonus: What input n <= 1000000 gives the longest sequence?
"""
"""
Solution: Spoiler alert: the conjecture is true.
To my understanding, the bonus question is quite hard and I can not imagine it to be anything more than a discussion
if even asked at an interview. Here is a link though:
https://lucidmanager.org/data-science/project-euler-14/
"""
def is_collatz(n):
if n == 1:
return True
if n % 2 == 0:
return is_collatz(int(n / 2))
else:
return is_collatz(3 * n + 1)
return False
def main():
print(is_collatz(49)) # Prints True
print(is_collatz(82)) # Prints True
return
if __name__ == "__main__":
main()
| true
|
e72f31942b3077b838ec289bffcf5a22526eea40
|
priyakrisv/priya-m
|
/set17.py
| 400
| 4.1875
| 4
|
print("Enter 'x' for exit.");
string1=input("enter first string to swap:");
if(string1=='x'):
exit()
string2=input("enter second string to swap:");
print("\nBoth string before swap:");
print("first string=",string1);
print("second string=",string2);
temp=string1;
string1=string2;
string2=temp;
print("\nBoth string after swap:");
print("first string=",string1);
print("second string=",string2);
| true
|
39959d08343f4ca027e3150e4a29186675a8ab2d
|
ramshaarshad/Algorithms
|
/number_swap.py
| 305
| 4.21875
| 4
|
'''
Swap the value of two int variables without using a third variable
'''
def number_swap(x,y):
print x,y
x = x+y
y = x-y
x = x-y
print x,y
number_swap(5.1,6.3)
def number_swap_bit(x,y):
print x,y
x = x^y
y = x^y
x = x^y
print x,y
print '\n'
number_swap_bit(5,6)
| true
|
8712efb746ee37f10d0e3d235b47a0f16c4f2c9f
|
sunshineDrizzle/learn-python-the-hard-way
|
/ex11.py
| 928
| 4.25
| 4
|
print("How old are you?", end=' ')
age = input() # 在python3.0之后就没有raw_input()这个函数了
print("How tall are you?", end=' ')
height = input()
print("How much do you weigh?", end=' ')
weight = input()
print("So, you're %r old, %r tall and %r heavy." % (age, height, weight))
# study drill 1
# raw_input()(存在于python3.0之前的版本)的作用是接受控制台的用户输入以实现交互。
# 它会将所有输入都看作字符串
# study drill 2
Age = input("How old are you?")
print("You are %s old." % Age)
# study drill 3
print("What's your name?", end=' ')
name = input()
print("Your name is %s." % name)
# study drill 4
# 这里出现反斜线的原因是因为以%r格式化输出的时候,会在对应的输出结果两端加上一对引号,
# 此处针对 6'2" 的两端加上一对单引号,因此为了区别出字符串内部的那个单引号,所以就使用了反斜线
| false
|
50ea487c9c3dd452fc4ed94cd86b223554b7afc2
|
rajivpaulsingh/python-codingbat
|
/List-2.py
| 2,799
| 4.5
| 4
|
# count_evens
"""
Return the number of even ints in the given array.
Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1.
count_evens([2, 1, 2, 3, 4]) → 3
count_evens([2, 2, 0]) → 3
count_evens([1, 3, 5]) → 0
"""
def count_evens(nums):
count = 0
for element in nums:
if element % 2 == 0:
count += 1
return count
# big_diff
"""
Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array.
Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values.
big_diff([10, 3, 5, 6]) → 7
big_diff([7, 2, 10, 9]) → 8
big_diff([2, 10, 7, 2]) → 8
"""
def big_diff(nums):
return max(nums) - min(nums)
# centered_average
"""
Return the "centered" average of an array of ints, which we'll say is the mean average of the values,
except ignoring the largest and smallest values in the array.
If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value.
Use int division to produce the final average. You may assume that the array is length 3 or more.
centered_average([1, 2, 3, 4, 100]) → 3
centered_average([1, 1, 5, 5, 10, 8, 7]) → 5
centered_average([-10, -4, -2, -4, -2, 0]) → -3
"""
def centered_average(nums):
sum = 0
for element in nums:
sum += element
return (sum - min(nums) - max(nums)) / (len(nums)-2)
# sum13
"""
Return the sum of the numbers in the array, returning 0 for an empty array.
Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.
sum13([1, 2, 2, 1]) → 6
sum13([1, 1]) → 2
sum13([1, 2, 2, 1, 13]) → 6
"""
def sum13(nums):
if len(nums) == 0:
return 0
for i in range(0, len(nums)):
if nums[i] == 13:
nums[i] = 0
if i+1 < len(nums):
nums[i+1] = 0
return sum(nums)
# sum67
"""
Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6
and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.
sum67([1, 2, 2]) → 5
sum67([1, 2, 2, 6, 99, 99, 7]) → 5
sum67([1, 1, 6, 7, 2]) → 4
"""
def sum67(nums):
for i in range(0, len(nums)):
if nums[i] == 6:
nums[i] = 0
for j in range(i+1, len(nums)):
temp = nums[j]
nums[j] = 0
if temp == 7:
i = j + 1
break
return sum(nums)
# has22
"""
Given an array of ints, return True if the array contains a 2 next to a 2 somewhere.
has22([1, 2, 2]) → True
has22([1, 2, 1, 2]) → False
has22([2, 1, 2]) → False
"""
def has22(nums):
for i in range(0, len(nums)-1):
#if nums[i] == 2 and nums[i+1] == 2:
if nums[i:i+2] == [2,2]:
return True
return False
| true
|
4404e39852e74e7ca1ad170550b02fd3b09f76dd
|
wilsonbow/CP1404
|
/Prac03/gopher_population_simulator.py
| 1,190
| 4.5
| 4
|
"""
This program will simulate the population of gophers over a ten year period.
"""
import random
BIRTH_RATE_MIN = 10 # 10%
BIRTH_RATE_MAX = 20 # 20%
DEATH_RATE_MIN = 5 # 5%
DEATH_RATE_MAX = 25 # 25%
YEARS = 10
print("Welcome to the Gopher Population Simulator!")
# Calculate births and deaths
def gopher_births(population):
"""Calculates yearly gopher births."""
birth_rate = random.randint(BIRTH_RATE_MIN, BIRTH_RATE_MAX) # Birth rate between min and max
return int(population * birth_rate / 100) # Calculate and return births
def gopher_deaths(population):
"""Calculate yearly gopher deaths"""
death_rate = random.randint(DEATH_RATE_MIN, DEATH_RATE_MAX) # Death rate between min and max
return int(population * death_rate / 100) # Calculate and return deaths
population = 1000
print("Initial population is 1000")
# Simulate for YEARS years
for year in range(1, YEARS + 1):
births = gopher_births(population)
deaths = gopher_deaths(population)
population = int(population + births - deaths)
print("In year {:>2}, there were {:>3} births and {:>3} deaths. \
The new population is: {:>4}.\n".format(year, births, deaths, population))
| true
|
c1c268aa78f389abc625b582e37ba9316f36a849
|
AlfredPianist/holbertonschool-higher_level_programming
|
/0x06-python-classes/100-singly_linked_list.py
| 2,885
| 4.3125
| 4
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""100-singly_linked_list
A Node class storing integers, and a Singly Linked List class implementing a
sorted insertion.
"""
class Node:
"""A Node class. Stores a number and a type Node.
Attributes:
__data (int): The size of the square.
__next_node (:obj:`Node`): A 'pointer' to the next node.
"""
def __init__(self, data, next_node=None):
"""Initialization of Node object with data and next node.
"""
self.data = data
self.next_node = next_node
@property
def data(self):
"""The data stored.
For the setter:
Args:
value (int): The data of the Node.
Raises:
TypeError: Data entered must be an integer.
"""
return self.__data
@data.setter
def data(self, value):
if not isinstance(value, int):
raise TypeError("data must be an integer")
self.__data = value
@property
def next_node(self):
"""The 'pointer' to the next node.
For the setter:
Args:
value (:obj:`Node`): A Node.
Raises:
TypeError: Next node has to be Node or None.
"""
return self.__next_node
@next_node.setter
def next_node(self, value):
if not (value is None or isinstance(value, Node)):
raise TypeError("next_node must be a Node object")
self.__next_node = value
class SinglyLinkedList:
"""A Singly Linked List Class. It sorts the inserted items and
preps the list to be printed by print()
Attributes:
__head (:obj:`Node`): The head of the list.
"""
def __init__(self):
"""Initialization of List object with a None head.
"""
self.__head = None
def __str__(self):
"""Formats the string to be printed by print()
Returns:
The formatted string.
"""
current = self.__head
string = ""
while (current is not None):
string += str(current.data)
if (current.next_node is not None):
string += "\n"
current = current.next_node
return string
def sorted_insert(self, value):
"""Inserts a node with its value in the correct order.
Args:
value (int): The value of the Node to be inserted.
"""
node = Node(value)
current = self.__head
if current is None:
self.__head = node
return
if value < current.data:
node.next_node = self.__head
self.__head = node
return
while (current.next_node is not None and
value >= current.next_node.data):
current = current.next_node
node.next_node = current.next_node
current.next_node = node
| true
|
e62c99e0a88f67778b9573559d2de096255a3e2d
|
AlfredPianist/holbertonschool-higher_level_programming
|
/0x0B-python-input_output/2-append_write.py
| 479
| 4.28125
| 4
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""2-append_write
This module has the function write_file which writes a text to a file.
"""
def append_write(filename="", text=""):
"""Writes some text to a file.
Args:
filename (str): The file name to be opened and read.
text (str): The text to be written.
Returns:
int: The number of characters written.
"""
with open(filename, 'a', encoding='utf-8') as f:
return f.write(text)
| true
|
bbb4a67092b02f132bb0decd76bf80c7e219c761
|
orlychaparro/python_cardio_platzi
|
/code/reto2_piedra_papel_tijera.py
| 2,937
| 4.15625
| 4
|
""" Reto 2 - Piedra, papel o tijera
Ejercicios realizados por Orlando Chaparro.
https://platzi.com/p/orlandochr
Escribe un programa que reciba como parámetro
“piedra”, “papel”, o “tijera”
y determine si ganó el jugador 1 o el jugador 2.
Bonus: determina que el ganador sea el jugador que gane 2 de 3 encuentros.
Ejemplo:
ppt(“piedra”, “papel”) ➞ “El ganador es el jugador 2
"""
def seleccion_opcion_jugador(p_opcion_jugador):
opciones_piedra_papel_tijera = {'1' : 'Piedra', '2' : 'Papel', '3': 'Tijera' }
opcion_seleccionada = opciones_piedra_papel_tijera[p_opcion_jugador]
return opcion_seleccionada
def piedra_vs_papel_vs_tijera(p_jugador1,p_jugador2):
msg_empate = "El resultado es empate"
msg_gana_1 = "El ganador es el jugador 1"
msg_gana_2 = "El ganador es el jugador 2"
if p_jugador1 == "Piedra":
if p_jugador2 == 'Piedra':
resultado = '0'
msg = msg_empate
elif p_jugador2 == 'Papel':
resultado = '2'
msg = msg_gana_2
else :
resultado = '1'
msg = msg_gana_1
if p_jugador1 == "Papel":
if p_jugador2 == 'Piedra':
resultado = '1'
msg = msg_gana_1
elif p_jugador2 == 'Papel':
resultado = '0'
msg = msg_empate
else :
resultado = '2'
msg = msg_gana_2
if p_jugador1 == "Tijera":
if p_jugador2 == 'Piedra':
resultado = '2'
msg = msg_gana_2
elif p_jugador2 == 'Papel':
resultado = '1'
msg = msg_gana_1
else :
resultado = '0'
msg = msg_empate
return [resultado,msg]
partidas_ganadas = 0
msg_final = ""
jugador1_ganadas = 0
jugador2_ganadas = 0
finalizar_juego = False
while not finalizar_juego:
jugador_1 = input(""" Seleccione una opcion
1 - Piedra
2 - Papel
3 - Tijera
: """)
jugador_2 = input(""" Seleccione una opcion
1 - Piedra
2 - Papel
3 - Tijera
: """)
jugador_1 = seleccion_opcion_jugador(jugador_1)
jugador_2 = seleccion_opcion_jugador(jugador_2)
resultado,msg = piedra_vs_papel_vs_tijera(jugador_1,jugador_2)
print("Jugador 1 x Jugador 2 Resultado")
print(" " + jugador_1 + " " + " - " + jugador_2 + ' - ' + "" + msg )
if resultado == '1':
jugador1_ganadas +=1
if jugador1_ganadas == 3:
finalizar_juego = True
msg_final = "Con tres juegos victoriosos el Ganador es el Jugador 1"
if resultado == '2':
jugador2_ganadas +=1
if jugador2_ganadas == 3:
finalizar_juego = True
msg_final = "Con tres juegos victoriosos el Ganador es el Jugador 2"
print(resultado)
print(jugador1_ganadas)
print(jugador2_ganadas)
print(finalizar_juego)
print(msg_final)
| false
|
c51da4549dc5effcf1187071aaa8a55fbdd2be74
|
Herrj3026/CTI110
|
/P3HW2_DistanceTraveled_HerrJordan.py
| 888
| 4.34375
| 4
|
#
# A program to do a basic calcuation of how far you travled
# 6/22/2021
# CTI-110 P3HW2 - DistanceTraveled
# Jordan Herr
#
#section for the inputs
car_speed = float(input("Please enter car speed: "))
time_travled = float(input("Please enter distance travled: "))
#math section for the calculations
dis_travled = car_speed * time_travled
if time_travled > 0:
print()#white space to make it neat
print("Speed entered:", car_speed)
print("Time entered:", time_travled)
print()#white space to make it neat
print("Distance Travled", dis_travled)
elif time_travled <= 0:
time_travled = 1
print("Error!!! Time must be greater than 0!!!")
print()#white space to make it neat
print("Speed entered:", car_speed)
print("Time:", time_travled)
print()#white space to make it neat
print("Distance Travled", dis_travled)
| true
|
bcaa46b3e1cc5dbff52abb328b7eb3a11184df87
|
xwmyth8023/python-date-structure
|
/queue/deque.py
| 1,528
| 4.25
| 4
|
"""
deque(也称为双端队列)是与队列类似的项的有序集合。
它有两个端部,首部和尾部,并且项在集合中保持不变。
deque 不同的地方是添加和删除项是非限制性的。
可以在前面或后面添加新项。同样,可以从任一端移除现有项。
在某种意义上,这种混合线性结构提供了单个数据结构中的栈和队列的所有能力。
deque 操作如下:
1. Deque() 创建一个空的新 deque。它不需要参数,并返回空的 deque。
2. addFront(item) 将一个新项添加到 deque 的首部。它需要 item 参数 并不返回任何内容。
3. addRear(item) 将一个新项添加到 deque 的尾部。它需要 item 参数并不返回任何内容。
4. removeFront() 从 deque 中删除首项。它不需要参数并返回 item。deque 被修改。
5. removeRear() 从 deque 中删除尾项。它不需要参数并返回 item。deque 被修改。
6. isEmpty() 测试 deque 是否为空。它不需要参数,并返回布尔值。
7. size() 返回 deque 中的项数。它不需要参数,并返回一个整数。
"""
class Deque:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def addFront(self, item):
self.items.append(item)
def addRear(self, item):
self.items.insert(0,item)
def removeFront(self):
return self.items.pop()
def removeRear(self):
return self.items.pop(0)
def size(self):
return len(self.items)
| false
|
3cec4c83350a40b81dc8e58910b57ce3e5c5428d
|
SBrman/Project-Eular
|
/4.py
| 792
| 4.1875
| 4
|
#! python3
"""
Largest palindrome product
Problem 4
A palindromic number reads the same both ways. The largest palindrome made from
the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def isPalindrome(num):
num = str(num)
for i in range(len(num)):
if num[i] != num[-(i+1)]:
return False
return True
largestNumber = 0
for num1 in range(999, 100, -1):
for num2 in range(999, 100, -1):
number = num1 * num2
if isPalindrome(number):
if number > largestNumber:
largestNumber = number
number_1, number_2 = num1, num2
print(largestNumber, ' = ', number_1, ' * ', number_2)
| true
|
9af7f0f7a29798891798048deea3137e95eca3f4
|
Jimmyopot/JimmyLeetcodeDev
|
/Easy/reverse_int.py
| 2,193
| 4.15625
| 4
|
'''
- Given a signed 32-bit integer x, return x with its digits reversed.
If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
'''
# soln 1
class Solution(object):
def reverse(self, x):
# number = 123
def divide(number, divider):
return int(number * 1.0 / divider)
def mod(number, m):
if number < 0:
return number % -m
else:
return number % m
'''
remember:
123 % 10 = 3
-123 % 10 = 7
-123 % -10 = 3
'''
MAX_INT = 2 ** 31 - 1
MIN_INT = -2 ** 31
result = 0
while x:
pop = mod(x, 10)
x = divide(x, 10)
if result > divide(MAX_INT, 10) or (result == divide(MAX_INT, 10) and pop > 7):
return 0
if result < divide(MIN_INT, 10) or (result == divide(MIN_INT, 10) and pop < -8):
return 0
result = result * 10 + pop
return result
# TIME COMPLEXITY = O(n)
# SPACE COMPLEXITY = 0(1)
# soln2 (STRING REVERSE METHOD)****************BEST SOLN********************
def reverse_integer(x):
y = str(abs(x)) # converts int x to a string
y = y.strip() # strip all leading 0's (e.g, 120-> 21, 1000-> 1)
y = y[::-1] # reverses the string
output = int(y) # reverses back to INTEGER
if output >= 2 ** 31 -1 or output <= -2 ** 31:
return 0
elif x < 0:
return -1 * output
else:
return output
print(reverse_integer(-12345))
# TIME COMPLEXITY = O(n)
# soln3
def reverse_signed(num):
sum = 0
sign = 1
if num < 0:
sign = -1
num = num * -1
while num > 0:
rem = num % 10
sum = sum * 10 + rem
num = num // 10
if not -2147483648 < sum < 2147483648:
return 0
return sign * sum
print(reverse_signed(456))
| true
|
b58ae8395c1283f60765b7dab5e0d80bb3b97751
|
kevinawood/pythonprograms
|
/LeagueDraw.py
| 1,539
| 4.125
| 4
|
import random
import time
teams = ['Sevilla',
'Bayern',
'Roma',
'Barcelona',
'Manchester City',
'Liverpool',
'Juventus',
'Real Madrid']
draw = []
def draw():
#for i in range(len(teams)):
for i in range(len(teams), 1, -1):
first_team = random.choice(teams)
print("The first team selected is........")
time.sleep(2)
print(first_team)
draw.append(first_team)
teams.remove(first_team)
second_team = random.choice(teams)
print("and they will play.........")
time.sleep(2)
print(second_team)
draw.append(second_team)
teams.remove(second_team)
print("So this tie is: {} vs {}.".format(first_team,second_team))
if len(teams == 0):
print("All teams have been draw.\n The ties are: ")
def main():
while True:
start = input("Welcome to the UEFA Champions League draw. Should we start the draw?: [Yes/no] \n")
if start.lower() in ['yes', 'y']:
draw()
elif start.lower() in ['no' ,'n']:
print("Ok, maybe another time then")
else:
print("Really not sure the input you gave, please try again.\n")
continue
if __name__ == "__main__":
main()
| false
|
399cb2a542e995969b17089d75fb73b1018dc706
|
dspec12/real_python
|
/part1/chp05/invest.py
| 923
| 4.375
| 4
|
#!/usr/bin/env python3
'''
Write a script invest.py that will track the growing amount of an investment over time. This script includes an invest()
function that takes three inputs: the initial investment amount, the annual compounding rate, and the total number of years
to invest. So, the first line of the function will look like this:
def invest(amount, rate, time):
The function then prints out the amount of the investment for every year of the time period.
In the main body of the script (after defining the function), use the following code to test your function:
invest(100, .05, 8)
invest(2000, .025, 5)
'''
def invest(amount, rate, time):
print("principal amount: ${}".format(amount))
print("annual rate of return:", rate)
for t in range(1, time + 1):
amount = amount * (1 + rate)
print("year {}: ${}".format(t, amount))
print()
invest(100, .05, 8)
invest(2000, .025, 5)
| true
|
665ba4de4b55bc221d03af876d0c17a9d3b6e602
|
dspec12/real_python
|
/part1/chp05/5-2.py
| 928
| 4.46875
| 4
|
#!/usr/bin/env python3
#Write a for loop that prints out the integers 2 through 10, each on a new line, by using the range() function
for n in range(2, 11):
print("n = ", n)
print("Loop Finished")
"""
Use a while loop that prints out the integers 2 through 10 (Hint: you'll need to create a new integer first; there
isn't a good reason to use a while loop instead of a for loop in this case, but it's good practice...)
"""
n = 2
while n < 11:
print("n = ", n)
n = n + 1
print("Loop Finished")
'''
Write a function doubles() that takes one number as its input and doubles that number three times using a loop,
displaying each result on a separate line; test your function by calling doubles(2) to display 4, 8, and 16
'''
def doubles(num):
'''Takes input and doubles that number three times'''
num = num * 2
return(num)
number = 2
for n in range(0, 3):
number = doubles(number)
print(number)
| true
|
1e6aba46347bc53f8abe7a864d239759a1fd6f91
|
Coryf65/Python-Basics
|
/PythonBasics.py
| 807
| 4.1875
| 4
|
#Python uses Snake Case for naming conventions
first_name = "Ada"
last_name = "Lovelace"
print("Hello," + first_name + " ")
print(first_name + " " + last_name + " is an awesome person!")
# print() automatically adds spaces
print("These", "will be joined", "together by spaces!")
# Python will save vars like JS kinda
is_int = 12
print(is_int)
# getting user input and saving as a var
current_mood = input("How are you today ? ")
# displaying the mood !
print("I am glad that you are ,", current_mood)
# PEMDAS...
print("PEMDAS: ", 0.1 + 0.1 + 0.1 - 0.3)
# we get 0.0000005
# now we can round this
print("rounding: ",round(0.1 + 0.1 + 0.1 - 0.3))
# this Method helps give info about the passed in function or Argument!
#help(str)
# finding strings in strings
print("corn" in "Buttered Popcorn")
| true
|
c8799a82d96c4e2268663abd19bb2ee3578c10e1
|
facunava92/1ro_Sistemas
|
/AED/Fichas/Ficha 02 - [Estructuras Secuenciales]/Guía de Ejercicios Prácticos - Ficha 02/3_EcuacionDeEinstein.py
| 486
| 4.15625
| 4
|
#!/usr/bin/python
#La famosa ecuación de Einstein para conversión de una masa m en energía viene dada por la fórmula:
#E = mc^2
#Donde c es la velocidad de la luz cuyo valor es c = 299792.458 km/seg. Desarrolle un programa que lea el valor una masa m en kilogramos y obtenga la cantidad de energía E producida en la conversión.
#Entrada
m = float(input('Ingrese el valor de la masa en Kg: '))
c= 299892.458
#Procesos
E = m*c**2
#Salida
print('\n\t La Energia es: ', E, 'J')
| false
|
055c85850dc8ca3356c4659ad534008cccb01a25
|
facunava92/1ro_Sistemas
|
/AED/Fichas/Ficha 01 - [Fundamentos]/Guía de Ejercicios Prácticos - Ficha 01/4_UltimosDigitos.py
| 637
| 4.15625
| 4
|
#!/usr/bin/python
#¿Cómo usaría el operador resto (%) para obtener el valor del último dígito de un número entero? ¿Y cómo obtendría los dos últimos dígitos? Desarrolle un programa que cargue un número entero por teclado, y muestre el último dígito del mismo (por un lado) y los dos últimos dígitos (por otro lado) [Ayuda: ¿cuáles son los posibles restos que se obtienen de dividir un número cualquiera por 10?]
#Entrada
num = int(input('Ingrese un numero entero: '))
#Proceso
UnDig = num % 10
DosDig = num % 100
#Salida
print('El último dígito es : ', UnDig)
print('Los últimos dos dígitos son : ', DosDig)
| false
|
6eeb8bf68eeb0713e477617dc4c37b8c9f98e83a
|
aurimrv/src
|
/aula-07/turtle-01.py
| 607
| 4.1875
| 4
|
import turtle
from math import sqrt
L = input("Tamanho do lado: ");
N = input("Quantidade de quadrados: ");
L = int(L)
N = int(N)
pen = turtle.Pen()
A = L*L
soma = A
cont = 2
# desenhando quadrado
pen.forward(L)
pen.left(90)
pen.forward(L)
pen.left(90)
pen.forward(L)
pen.left(90)
pen.forward(L)
while cont <= N:
D = sqrt(L)
A = A/2
soma = soma+A
cont = cont + 1
pen.left(90)
pen.forward(L/2)
pen.left(45)
pen.forward(D)
pen.left(90)
pen.forward(D)
pen.left(90)
pen.forward(D)
pen.left(90)
pen.forward(D)
L = D
print("Soma das areas: ", soma)
| false
|
6338ec300caac0b9eeb18103ec9d35d12bb5d61b
|
mohsin-siddiqui/python_practice
|
/lpth_exercise/MyRandomPrograms/areaOfCircle.py
| 238
| 4.21875
| 4
|
pi = 22/7
R = input("Please Enter the Radius of the Circle(in meter):\n") # R stands for Radius of the circle
A = pi * float(R) ** 2 # A stands for Area of the circle
print("The required Area of the circle is :",round(A),"square-meters")
| true
|
41c9edbb34832ccd2fc656a366bd89103b171e67
|
arl9kin/Python_data
|
/Tasks/file_function_questions.py
| 2,256
| 4.25
| 4
|
'''
Question 1
Create a function that will calculate the sum of two numbers. Call it sum_two.
'''
# def sum_two(a, b):
# c = a + b
# print (c)
# sum_two (3,4)
'''
Question 2
Write a function that performs multiplication of two arguments. By default the
function should multiply the first argument by 2. Call it multiply.
'''
# def multiply (a,b=2):
# c = a * b
# print (c)
# multiply (2)
# multiply (2,3)
'''
Question 3
Write a function to calculate a to the power of b. If b is not given
its default value should be 2. Call it power.
'''
# def power (a, b=2):
# c = a**b
# print (c)
# power(2)
# power(2,3)
'''
Question 4
Create a new file called capitals.txt , store the names of five capital cities
in the file on the same line.
'''
# file = open('capitals.txt', 'w')
# file.write('London, Moscow, Berlin, Rome, Tokyo')
# file.close()
# file = open('capitals.txt', 'r')
# print(file.readlines())
# file.close()
'''
Question 5
Write some code that requests the user to input another capital city.
Add that city to the list of cities in capitals. Then print the file to
the screen.
'''
# with open ('capitals.txt','r') as f:
# for i in f.readlines():
# print (i ,end = ' ')
# user = str.lower (input ('Do you want to add new capital (y/n): \n\t>>'))
# while user == "yes" or user == "y":
# user = str.lower (input ('enter new capital: \n\t>>'))
# with open ("capitals.txt", 'a') as f:
# f.write(f', {user.title()}')
# with open ('capitals.txt','r') as f:
# for i in f.readlines():
# print (i ,end = ' ')
# user = str.lower (input ('Do you want to add new capital (y/n): \n\t>>'))
# if user == 'n' or user == "no":
# print ("thanks for using my programm")
# else:
# print ("please use only y/n")
'''
Question 6
Write a function that will copy the contents of one file to a new file.
'''
# def clone (a='capitals.txt', b='capitals_copy.txt'):
# """Creates copy of original file (a)"""
# copy = []
# with open (a, 'r') as origin:
# for i in origin.readlines():
# copy.append(i)
# with open (b, 'w') as cop:
# for i in copy:
# cop.write (i)
# clone()
| true
|
348dc81dd001a621ab8fe2f5cf970a86981f6294
|
letugade/Code-Club-UWCSEA
|
/Python/Lesson01/Lesson01.py
| 508
| 4.21875
| 4
|
# Printing
print("Hello world")
# Variables
a = 3
# Printing variables
print("The value of a is", a)
# User input
name = input("What is your name? ")
print("Hello", name)
# Conditional statements
if name == "Bob":
print("Your name is Bob")
elif name == "John":
print("Your name is John")
else:
print("Your name is not Bob or John")
print("This will always print")
# Lists
alphaList = ["a", "b", "c", "d"]
alphaList.append("e")
# Dictionaries
alphaDict = {"a":1, "b":2, "c":3}
print(alphaList[0])
| true
|
d8fd66f43d8a296a435c9bc94d0c79a67249abc9
|
rmwenzel/project_euler
|
/p1/p1.py
| 286
| 4.15625
| 4
|
#!usr/bin/python
import numpy as np
def sum_multiples(n):
"""Sum multiples of 3 or 5 that are < n."""
def f(x):
return x if (x % 3 == 0 or x % 5 == 0) else 0
return sum(np.array(list(map(f, np.arange(1, n)))))
if __name__ == "__main__":
sum_multiples(1000)
| true
|
5bc2ead9259f699053de317c62b911bc86f75e3f
|
vivek-x-jha/Python-Concepts
|
/lessons/cs14_decorators_args.py
| 713
| 4.3125
| 4
|
"""
Python Tutorial: Decorators With Arguments
https://youtu.be/KlBPCzcQNU8
"""
def prefix_decorator(prefix):
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print(prefix, 'Executed Before', original_function.__name__)
result = original_function(*args, **kwargs)
print(prefix, 'Executed After', original_function.__name__, '\n')
return result
return wrapper_function
return decorator_function
@prefix_decorator('wtuppppp:')
def display_info(name, age):
print(f'display_info ran with arguments ({name}, {age})')
if __name__ == '__main__':
display_info('John', 25)
display_info('Travis', 30)
| true
|
564cb1318d466a5eeb2fbe7a7825380de3227322
|
prasannakumar2495/QA-Master
|
/pythonPractice/samplePractice/IFcondition.py
| 786
| 4.3125
| 4
|
'''
Created on 25-Dec-2018
@author: prasannakumar
'''
number = False
string = False
if number or string:
print('either of the above statements are true')
else:
print('neither of the above statements are true')
if number:
print('either of the above statements are true')
elif not(string) and number:
print('the data is not string but number')
elif not(number) and string:
print('the data is not number but string')
else:
print('neither of the above statements are true')
num1 = input('enter the 1st number')
num2 = input('enter the 2nd number')
num3 = input('enter the 3rd number')
def max_num():
if num1>num2 and num1>num3:
return num1
elif num2>num1 and num2>num3:
return num2
else:
return num3
print(max_num())
| true
|
5c2252aa3a09a3518282ca6ae984880da19a5b6d
|
zaurrasulov/Euler-Projects
|
/Euler9.py
| 318
| 4.21875
| 4
|
#This application prints the Pythagorean triplet in which a+b+c=1000
import math
def Pythagorean_triplet(n):
for b in range(n):
for a in range(1, b):
c = math.sqrt( a * a + b * b)
if (c % 1 == 0 and a+b+c==1000):
print(a, b, int(c))
Pythagorean_triplet(1000)
| false
|
ea1f557a5eee486e0afd435d1eb339dd40caad0e
|
sis00337/BCIT-CST-Term-1-Programming-Methods
|
/02. Three Short Functions/create_name.py
| 891
| 4.375
| 4
|
"""
Author: Min Soo Hwang
Github ID: Delivery_KiKi
"""
import random
import string
def create_name(length):
"""
Check if length of a name is less than or equal to 0.
:param length: an integer that indicates the length of a name
:return: the result of the function named create_random_name
"""
if length <= 0:
return None
else:
return create_random_name(length)
def create_random_name(length):
"""
Creating a randomized name.
:param length: an integer that indicates the length of a name
:return: Capitalized and randomized name
"""
name = (''.join(random.choices(string.ascii_lowercase, k=length)))
name_capitalized = name.capitalize()
return name_capitalized
def main():
# Program starts here
test = create_name(12)
print(test)
if __name__ == '__main__':
# invoke the main function
main()
| true
|
9e80ca85c78c6ccba160eb3ce0a7e60ab1e49392
|
DavidAlen123/Radius-of-a-circle
|
/Radius of a circle.py
| 255
| 4.25
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 11 07:15:17 2021
@author: DAVID ALEN
"""
from math import pi
r = float(input ("Input the radius of the circle : "))
print ("The area of the circle with radius " + str(r) + " is: " + str(pi * r**2))
| true
|
100cf26661e730aa38efa2852aaa63e87067bac4
|
4anajnaz/Devops-python
|
/largestnumber.py
| 460
| 4.375
| 4
|
#Python program to find largest number
try:
num1= input("Enter first number")
num2= input("Enter second number");
num3= input("Enter third number");
if (num1>num2) and (num1>num3):
largest = num1
elif (num2>num1) and (num2>num3):
largest = num2
else:
largest = num3
print("The largest number is :", largest)
except Exception as e:
print ("Exception block called:")
print (e)
| true
|
c5864d32adc2646fe4f605e8c5c4d9e2f44342be
|
Werifun/leetcode
|
/tree/199. 二叉树的右视图.py
| 1,596
| 4.1875
| 4
|
"""
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/ \
2 3 <---
\ \
5 4 <---
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-right-side-view
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
"""
思路:很简单
前序遍历:根左右,用height记录每个节点所在高度,遍历的过程中同一高度的最右侧的节点必然在最后一次出现,直接用right_list维护当前已遍历路径最右侧的节点
"""
def rightSideView(self, root: TreeNode) -> List[int]:
right_list=[]
if not root: return right_list
self.pre_order(root, 0, right_list)
return right_list
def pre_order(self, node, height,right_list):
if not node:
return
if len(right_list)>height:
right_list[height] = node.val
elif len(right_list)==height:
right_list.append(node.val)
# print(right_list)
else:
raise Error('right_list have false!')
self.pre_order(node.left, height+1, right_list)
self.pre_order(node.right, height+1, right_list)
return
| false
|
fb6243d1582229404e91b91dbcea5f98a093a67d
|
Werifun/leetcode
|
/tree/236. 二叉树的最近公共祖先.py
| 1,573
| 4.21875
| 4
|
"""
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
示例 1:
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出: 3
解释: 节点 5 和节点 1 的最近公共祖先是节点 3。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
lca = None
cur_node = root
pq = []
self.pre_dfs(root, cur_node, p, q, pq, lca)
return lca
def pre_dfs(self, root,cur_node,p,q, pq, lca):
if lca: return # 已发现lca
if not root: return # 空节点
if p == root or q == root:
if root in pq:
print('pq出现了两次')
pq.append(root)
if len(pq) == 2:
lca = cur_node
return
else:
| false
|
126fac3aba52940e7c6d68b6469b33a3687ec2fb
|
aaron-lee/mathmodule
|
/from math import constant.py
| 257
| 4.15625
| 4
|
from math import pi #importing only the pi constant from the module
def circumference(radius):
circum = 2*pi*radius #circumference formula
return circum
print("The circumference of circle with radius 20 is %f" % circumference(20))
| true
|
1eba38a72a5777e42e51f82ad189db3764ca7689
|
teamneem/pythonclass
|
/Projects/proj02.py
| 2,144
| 4.65625
| 5
|
#/****************************************************************************
# Section ?
# Computer Project #2
#****************************************************************************/
#Program to draw a pentagon
import turtle
import math
print 'This program will draw a congruent pentagon. The user may choose a red'
print 'green, blue ration to make the internal fill color of the pentagon.'
print 'The user will also input the length of the pentagon sides.'
red = float(raw_input('What is the red value (0-1): ')) #user imput for color
green = float(raw_input('What is the green value (0-1): '))
blue = float(raw_input('What is the blue value (0-1): '))
length = int(raw_input('What is the length of a pentagon side: '))
pred = float(1-red) #values for the pen color from inverse of fill color
pgreen = float(1-green)
pblue = float(1-blue)
x1 = length*-0.5
#calculates x coordinate of bottom left corner of pentagon
y1 = -length/10*math.sqrt(25+10*(math.sqrt(5)))
#calculates y coordinate of bottom left corner of pentagon
turtle.up()
turtle.goto(x1,y1) #move turtle from origin so final pentagon is centered
turtle.pencolor(pred, pgreen, pblue) #pencolor is inverse of fill color
turtle.pensize(5)
turtle.fillcolor(red, green, blue) #colors the inside of the pentagon
turtle.begin_fill()
turtle.down() #turtle only draws when pen is down
turtle.forward(length) #draw one side of pentagon
turtle.left(72) #change pen angle to draw next side of pentagon
turtle.forward(length)
turtle.left(72)
turtle.forward(length)
turtle.left(72)
turtle.forward(length)
turtle.left(72)
turtle.forward(length)
turtle.end_fill()
turtle.up() #turtle will not draw with pen up
turtle.right(18)
turtle.forward(20)
turtle.write('R:'+(str(red))+' ', move=True, align='left', font=('Arial', 8, 'normal'))
turtle.write('G:'+(str(green))+' ', move=True, align='left', font=('Arial', 8, 'normal'))
turtle.write('B:'+(str(blue))+' ', move=False, align='left', font=('Arial', 8, 'normal'))
turtle.hideturtle()
import time #keep turtle window open
time.sleep(30)
import os
os._exit(1)
| true
|
4a2dd635b536f0ce1f7be2cac11ed6b07c25ff87
|
Giovanni-Venegas/Curso-python
|
/6. Colecciones en Python/7.1 05-Ejercicio-set.py
| 724
| 4.25
| 4
|
#set es una colección sin orden y sin índices, no permite elementos repetidos
#y los elementos no se pueden modificar, pero si agregar nuevos o eliminar
planetas = {"Marte", "Júpiter", "Venus"}
print(planetas)
#largo
print(len(planetas))
#revisar si un elemento está presente
print( "Marte" in planetas)
#agregar
planetas.add("Tierra")
print( planetas )
planetas.add("Tierra")#no se pueden agregar elementos duplicados
print(planetas)
#eliminar con remove posiblemente arroja excepción
planetas.remove("Tierra")
print(planetas)
#eliminar con discard no arroja excepción
planetas.discard("Júpiters")
print( planetas )
#limpiar el set
planetas.clear()
print( planetas )
#eliminar el set
del planetas
#print( planetas )
| false
|
df364a633145e4742ed9117caf8e5fd035e0b4a1
|
abnerrf/cursoPython3
|
/3.pythonIntermediario/aula9/aula9.py
| 613
| 4.125
| 4
|
'''
SETS EM PYTHON (CONJUNTOS)
add (adiciona), update (atualiza), clear, discard
union | (une)
intersection & (todos os elementos presentes nos dois sets)
difference - (elementos apenas no set da esquerda)
symmetric_difference ^ (elementos que estão nos dois sets, mas não em ambos)
'''
s1 = set()
s1.add(1)
s1.add(2)
s1.add(3)
s1.discard(2)
s1.update([4,5,6],{6,7,8})
print(s1)
l1 = [1,2,1,2,2,3,3,4,4,4,4,6,6,6,5,7,8,9,'Abner','Abner']
l1 = set(l1)
l1 = list(l1)
print(l1)
s2 = {1,2,3,4,5,7,9}
s3 = {1,2,3,4,5,6}
s4 = s2 | s3
s5 = s2 & s3
s6 = s3 - s2
s7 = s2 ^ s3
print(s4)
print(s5)
print(s6)
print(s7)
| false
|
11c11c814c2f833503bbea3fd4bcd90951af5a65
|
iarzeno/MyFirstRepo
|
/list_ia.py
| 792
| 4.125
| 4
|
name = "Isa"
subjects = ["Math","French","English","Science"]
print("My name is " + name)
#print(subjects)
for i in subjects:
print("One of my classes is " + i)
tvshows = ["Gilmore Girls", "Friends", "How I met your mother"]
for i in tvshows:
if i == "Gilmore Girls":
print(i + " is the best show ever!")
elif i == "Friends":
print(i + " is so funny!")
elif i == "How I met your mother":
print("So mad its not on Netflix anymore!")
teams = []
while True:
print("Who are your facvorite teams? Type 'end to quit.")
answer = input()
if answer == "end":
break
else:
teams.append(answer)
for i in teams:
print("One of your favorite teams is " + i)
| false
|
5d88faa8306146450a306976ce89b540d106754e
|
kosmokato/python-4-infosec
|
/snippets/files.py
| 2,417
| 4.125
| 4
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
PoC: Operaciones con ficheros
"""
# Abrir un fichero
f = open('filename', 'r') # asignamos un puntero al fichero a la variable f, abierto para LEER (r)
data = f.read()
f.close() # CIERRA LOS FICHEROS SIEMPRE
g = open('filename2', 'w') # asignamos fichero2 a 'g', para ESCRIBIR (w)
g.write('escribe un string') # lo que escribamos debe ser string
g.close()
#----------------
f = open('filename', 'rb') # abrir para leer como bytes
g = open('filename2', 'wb') # abrir para escribir bytes
f.close()
g.close()
#----------------
"""
---------------------------------------------------------------------------------------
Parámetros para abrir el fichero
=======================================================================================
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
---------------------------------------------------------------------------------------
"""
import os # librerías para interactuar con el OS
path = './' # recomendamos paths enteros. En Windows los paths van con \\
print(os.listdir(path)) # listado de ficheros
os.path.isfile(path)
# CSV
# ===
import csv # no es necesario usarla: un csv es una 'tabla' con columnas separadas con comas.
# csv es una abstracción de texto a tabla, pero es texto
import csv
with open('writeData.csv','rt')as f: # otra manera de castear ficheros. LO LO DEMÁS VA TABULADO DEBAJO
data = csv.reader(f)
for row in data:
print(row)
#----------------
with open('cosicas.txt') as fichero: # otra manera de castear ficheros. LO LO DEMÁS VA TABULADO DEBAJO
data = csv.reader(fichero, delimiter=',')
lineas = 0
for row in data:
print(row)
#----------------
with open('writeData.csv', mode='w') as file:
writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
#way to write to csv file
writer.writerow(['Programming language', 'Designed by', 'Appeared', 'Extension'])
writer.writerow(['Python', 'Guido van Rossum', '1991', '.py'])
writer.writerow(['Java', 'James Gosling', '1995', '.java'])
writer.writerow(['C++', 'Bjarne Stroustrup', '1985', '.cpp'])
| false
|
99c3e82a14d1eb3a0fa1419a10d07812937784a0
|
caiopetreanu/PythonMachineLearningForTradingCourseCodes
|
/_py/01-01_to_01-03/14_numpy_arrays_random_values.py
| 1,172
| 4.125
| 4
|
""" Generating random numbers. """
import numpy
import numpy as np
def run():
# generate an array full of random numbers, uniformly sampled from [0.0, 1.0)
print("pass in a size tuple", np.random.random((5, 4))) # pass in a size tuple
print("function arguments (not a tuple)", np.random.rand(5, 4)) # function arguments (not a tuple)
# sample numbers from a Gaussian (normal) distribution
print('"standard normal" (mean = 0, s.d. = 1)"', np.random.normal(size=(2, 3))) # "standard normal" (mean = 0, s.d. = 1)
print('change mean to 50 and s.d. to 10', np.random.normal(50, 10, size=(2, 3))) # change mean to 50 and s.d. to 10
# random integers
print("a single integer in [0, 10)", np.random.randint(10)) # a single integer in [0, 10)
print("same as above, specifying [low, high) explicit", np.random.randint(0, 10)) # same as above, specifying [low, high) explicit
print("5 random integers as a 1D array", np.random.randint(0, 10, size=5)) # 5 random integers as a 1D array
print("2x3 array of random integers", np.random.randint(0, 10, size=(2, 3))) # 2x3 array of random integers
if __name__ == "__main__":
run()
| true
|
7c8cb97e1b50b85c8a7d5ec746a2b6c58bfee416
|
chav-aniket/cs1531
|
/labs/20T1-cs1531-lab05/encapsulate.py
| 695
| 4.5
| 4
|
'''
Lab05 Exercise 7
'''
import datetime
class Student:
'''
Creates a student object with name, birth year
and class age method
'''
def __init__(self, firstName, lastName, birth_year):
self.name = firstName + " " + lastName
self.birth_year = birth_year
def age(self):
'''
Added this function to encapsulate the age
'''
now = datetime.datetime.now()
return now.year - self.birth_year
def print_age(self):
'''
Used to print out the age
'''
print(f"{self.name} is {self.age()} years old")
if __name__ == '__main__':
NEW = Student("Rob", "Everest", 1961)
NEW.print_age()
| true
|
8fcda1b10eebda946124e3654c56e5176782e20f
|
abbasegbeyemi/outfield
|
/psolv_ch_4/psolv_ch_4_ADT.py
| 1,327
| 4.4375
| 4
|
class Stack:
"""The stack class which is an abstract data type that appends to and removes from the end of a list"""
def __init__(self):
"""Constructor for Stack"""
self._stack_list = []
def push(self, item):
self._stack_list.append(item)
def pop(self):
return self._stack_list.pop()
def isEmpty(self):
return self._stack_list == []
def peek(self):
return self._stack_list[len(self._stack_list) - 1]
def size(self):
return len(self._stack_list)
class Queue:
def __init__(self):
self._items = []
def enqueue(self, item):
self._items.append(item)
def dequeue(self):
return self._items.pop(0)
def isEmpty(self):
return self._items == []
def size(self):
return len(self._items)
def hot_potato(name_list, num_count):
q = Queue()
for name in name_list:
q.enqueue(name)
while q.size() > 1:
for i in range(num_count):
q.enqueue(q.dequeue())
print(f"Now removing {q.dequeue()}")
return q.dequeue()
if __name__ == '__main__':
nlist = ["Abbas", "Toyyibat", "Abike", "Hafsa", "Noni", "Uche", "Mayowa", "Folake", "Folusho", "Solape", "Folasade"]
winner = hot_potato(nlist, 6)
print(f"The winner is: {winner}")
| false
|
5bbbe57c31952c4e04e8ab5739e04cc3fb678474
|
danisebastian9/Ciclo1MinTIC
|
/Semana5/funcExternas04.py
| 903
| 4.125
| 4
|
'''
Definir una función inversa() que realice la inversión de una cadena.
Por ejemplo la cadena "estoy probando" debería devolver la cadena "odnaborp yotse"
Definir una función que diga si una cadena es palindrome "Sometamos o matemos" "oso" "radar" ""
'''
# def inversa(palabra):
# reversa = ''
# for i in palabra:
# reversa = i + reversa
# return reversa
def reves(cadena):
cadena = cadena
longitud = len(cadena)-1
inversa = ''
for i in range(longitud, -1, -1):
inversa += cadena[i]
return inversa
def esPalindrome(nuevaPal, palabra):
if nuevaPal == palabra:
print('Palabra o frase es palindrome')
else:
print('palabra o frase no es palindrome')
palabra = input('Ingrese la palabra a analizar: ').lower()
palabra = palabra.replace(' ', '')
nuevaPal = reves(palabra)
print(nuevaPal)
esPalindrome(nuevaPal, palabra)
| false
|
c961c1845e80e88496fefbb12ff75ab957c59e1a
|
mdadil98/Python_Assignment
|
/21.py
| 323
| 4.53125
| 5
|
# Python3 program to print all numbers
# between 1 to N in reverse order
# Recursive function to print
# from N to 1
def PrintReverseOrder(N):
for i in range(N, 0, -1):
print(i, end=" ")
# Driver code
if __name__ == '__main__':
N = 5;
PrintReverseOrder(N);
# This code is contributed by 29AjayKumar
| true
|
bd7b188ddcb0026ce6c83a6ac7323b441ccc42a5
|
brohum10/python_code
|
/daniel_liang/chapter06/6.12.py
| 1,190
| 4.40625
| 4
|
#Defining the function 'printChars'
def printChars(ch1, ch2, numberPerLine):
#y is a variable storing the count of
#elements printed on the screen
#as we have to print only a given number of characters per line
y=0
#Running a for loop
#'ord' function returns the ASCII value of the character
#Thus, Running the loop from the ASCII value of the starting character to
#the ASCII value of the last character
for x in range(ord(ch1),ord(ch2)+1):
#incrementing y by 1
y+=1
#checking if the limit of character to be printed
#per line is reached or not
if(y%numberPerLine==0):
#printing the character
#the 'chr' function converts the ASCII value back to character
print(chr(x))
else:
#else printing the character with a " " at the end
print(chr(x), end=" ")
def main():
#Calling the printChars function and passing the arguments
printChars("I", "Z",10)
#Calling the main function
main()
| true
|
7bbecf05287d5a11f158524c18c01143f42d534c
|
MantaXXX/python
|
/6- while/6-1.py
| 205
| 4.28125
| 4
|
# For a given integer N, print all the squares of positive integers where the square is less than or equal to N, in ascending order.
n = int(input())
i = 1
while i**2 <= n:
print(i**2, end=' ')
i += 1
| true
|
4a902e6c95a8b980fbcf6ca3193bbc2af259988c
|
MantaXXX/python
|
/3- if else /3.A.py
| 392
| 4.15625
| 4
|
# Given three integers. Determine how many of them are equal to each other. The program must print one of the numbers: 3 (if all are same), 2 (if two of them are equal to each other and the third one is different) or 0 (if all numbers are different).
a = int(input())
b = int(input())
c = int(input())
if a == b == c:
print(3)
elif a == b or a == c or b == c:
print(2)
else:
print(0)
| true
|
6c8b2745c7e34271a007e2ecaaf634938cd3b851
|
johnmarcampbell/concord
|
/concord/member.py
| 956
| 4.25
| 4
|
class Member(object):
"""This object represents one member of congress"""
def __init__(self, last_name='', first_name='', middle_name='',
bioguide_id='', birth_year='', death_year='', appointments=[]):
"""Set some values"""
self.last_name = last_name
self.first_name = first_name
self.middle_name = middle_name
self.bioguide_id = bioguide_id
self.birth_year = birth_year
self.death_year = death_year
self.appointments = appointments
def __str__(self):
"""String representation of a Member object"""
# Set middle name to empty string if there isn't one
if self.middle_name:
m = ' {}'.format(self.middle_name)
else:
m = ''
mask = '{}, {}{} [{}] - ({}-{})'
return mask.format(self.last_name, self.first_name, m, self.bioguide_id,
self.birth_year, self.death_year)
| true
|
edd62710a5ae5ae17009b97d29296f58ad99f849
|
sogouo/notes
|
/python/mydailydate.py
| 1,625
| 4.1875
| 4
|
# -*- coding: utf-8 -*-
"""关于命名不规范灰常👏走过路过大神瞬时指出
官方文档: https://docs.python.org/2/library/datetime.html
日常项目或者练习关于 datetime 模块的总结与Demo
"""
from datetime import timedelta, datetime, date
class MyDailyDate():
def get_day_of_each_month_in_datetime(self, *args):
""" 通过 datetime 对象获取上个月1号零时或者任何x号datetime 对象
"""
return (datetime.utcnow().replace(day=1, hour=0, second=0, minute = 0, microsecond=0) - timedelta(days=1)).replace(day=1)
def get_day_of_each_month_in_date(self, *args):
""" as same as: get_day_of_each_month_in_datetime
"""
return (date.today().replace(day=1) - timedelta(days=1)).replace(day=1)
mydaily = MyDailyDate()
datetime_day = mydaily.get_day_of_each_month_in_datetime()
date_day = mydaily.get_day_of_each_month_in_date()
print("{0} 的类型是 {1}".format(datetime_day, type(datetime_day)))
print("{0} 的类型是 {1}".format(date_day, type(date_day)))
""" 有时候, 通过 Model 类型按照日期字符串查询,且数据库中存储时间或者日期类型是datetime 类型,
客户端传入是格式化日期字符串: eg. '2018-11-21'
需要将日期函数转换为datetime类型: datetime.strftime(date_string, format)
"""
print("{0} 被格式化日期字符串 {1}".format(datetime_day, datetime.strftime(datetime_day, "%Y-%m-%d")))
"""
References
python date of the previous month
https://stackoverflow.com/questions/9724906/python-date-of-the-previous-month
"""
| false
|
62cd51f8869cda6893e815f3508fc07b61f7e91f
|
andelgado53/interviewProblems
|
/order_three_colors.py
| 971
| 4.15625
| 4
|
# Problem Statement:
# You are given n balls. Each of these balls are of one the three colors: Red, Green and Blue.
# They are arranged randomly in a line. Your task is to rearrange them such that all
# balls of the same color are together and their collective color groups are in this order:
# Red balls first, Green balls next and Blue balls last.
# This combination of colors is similar to the Dutch National Flag, hence the problem name.
# This is a popular sorting problem.
# Sample Input:
# balls = [G, B, G, G, R, B, R, G]
# Sample Output:
# [R, R, G, G, G, G, B, B]
# RGB
def order(arr):
r = 0
g = 0
b = len(arr) - 1
while g <= b:
if arr[g] == "G":
g += 1
elif arr[g] == "B":
arr[g], arr[b] = arr[b], arr[g]
b -= 1
else:
arr[r], arr[g] = arr[g], arr[r]
r += 1
g += 1
return arr
print(order(["G", "B", "G", "G", "R", "B", "R", "G"]))
| true
|
e5376089499f5bce5631b85ee1581a57451f0cb2
|
andelgado53/interviewProblems
|
/zig_zag_conversion.py
| 2,140
| 4.15625
| 4
|
import pprint
# The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
# (you may want to display this pattern in a fixed font for better legibility)
#
# P A H N
# A P L S I I G
# Y I R
# And then read line by line: "PAHNAPLSIIGYIR"
#
# Write the code that will take a string and make this conversion given a number of rows:
#
# string convert(string s, int numRows);
# Example 1:
#
# Input: s = "PAYPALISHIRING", numRows = 3
# Output: "PAHNAPLSIIGYIR"
# Example 2:
#
# Input: s = "PAYPALISHIRING", numRows = 4
# Output: "PINALSIGYAHRPI"
# Explanation:
#
# P I N
# A L S I G
# Y A H R
# P I
def pad(letter, num_rows, offset):
column = [None] * num_rows
column[offset] = letter
return column
def get_columns(word, rows, offset):
off = offset
output = []
start_index = 0
column = []
r = 0
while start_index < len(word):
while r < rows and start_index < len(word):
column.append(word[start_index])
r += 1
start_index += 1
if len(column) > 0:
output.append(column)
column = []
r = 0
while off >= 1 and start_index < len(word):
output.append(pad(word[start_index], rows, off))
off -= 1
start_index += 1
off = offset
return output
def convert(word, row_nums):
if len(word) <= 1 or row_nums == 0:
return word
rows = get_columns(word, row_nums, row_nums - 2)
col = 0
row = 0
new_word = ''
while col < len(rows[0]):
while row < len(rows):
if col < len(rows[row]) and rows[row][col] is not None:
new_word = new_word + rows[row][col]
row += 1
col += 1
row = 0
return new_word
def test():
test_word = "PAYPALISHIRING"
assert convert(test_word, 5) == "PHASIYIRPLIGAN"
assert convert(test_word, 4) == "PINALSIGYAHRPI"
assert convert(test_word, 3) == "PAHNAPLSIIGYIR"
assert convert(test_word, 2) == "PYAIHRNAPLSIIG"
assert convert(test_word, 1) == "PAYPALISHIRING"
test()
| true
|
9e84a0156febb09375208e2f1be5d4b3b30ae95e
|
andelgado53/interviewProblems
|
/set_matrix_zero.py
| 1,956
| 4.28125
| 4
|
# https://leetcode.com/problems/set-matrix-zeroes/
# Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
#
# Example 1:
#
# Input:
# [
# [1,1,1],
# [1,0,1],
# [1,1,1]
# ]
# Output:
# [
# [1,0,1],
# [0,0,0],
# [1,0,1]
# ]
# Example 2:
#
# Input:
# [
# [0,1,2,0],
# [3,4,5,2],
# [1,3,1,5]
# ]
# Output:
# [
# [0,0,0,0],
# [0,4,5,0],
# [0,3,1,0]
# ]
import pprint
def set_zeroes(matrix):
zero_cols = []
zero_rows = []
for r in range(len(matrix)):
for c in range(len(matrix[r])):
if matrix[r][c] == 0:
zero_cols.append(c)
zero_rows.append(r)
for col in zero_cols:
for r in range(len(matrix)):
matrix[r][col] = 0
for row in zero_rows:
for c in range(len(matrix[row])):
matrix[row][c] = 0
return matrix
def set_zeros_no_space(matrix):
is_first_col_zero = False
ROWS = len(matrix)
COLS = len(matrix[0])
for row in range(ROWS):
if matrix[row][0] == 0:
is_first_col_zero = True
for col in range(1, COLS):
if matrix[row][col] == 0:
matrix[0][col] = 0
matrix[row][0] = 0
for row in range(1, ROWS):
for col in range(1, COLS):
if matrix[row][0] == 0 or matrix[0][col] == 0:
matrix[row][col] = 0
if is_first_col_zero:
for row in range(1, ROWS):
matrix[row][0] = 0
if matrix[0][0] == 0:
for col in range(COLS):
matrix[0][col] = 0
pprint.pprint(matrix)
input1 = [
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
# pprint.pprint(set_zeroes(input1))
set_zeros_no_space(input1)
# assert set_zeroes(input1) == set_zeros_no_space(input1)
input2 = [
[1,1,1],
[1,0,1],
[1,1,1]]
# pprint.pprint(set_zeroes(input2))
set_zeros_no_space(input2)
# assert set_zeroes(input2) == set_zeros_no_space(input2)
| false
|
a9ca7660d5daf407247efa3219bde5714591e492
|
sanket-qp/IK
|
/4-Trees/invert_binary_tree.py
| 1,141
| 4.3125
| 4
|
"""
You are given root node of a binary tree T. You need to modify that tree in place,
transform it into the mirror image of the initial tree T.
https://medium.com/@theodoreyoong/coding-short-inverting-a-binary-tree-in-python-f178e50e4dac
______8______
/ \
1 __16
/
10
\
15
should convert to
______8______
/ \
16__ 1
\
10
/
15
"""
import random
from bst import Tree as BST
def mirror_image(node):
if not node:
return
left = mirror_image(node.left)
right = mirror_image(node.right)
temp_left = left
node.left = right
node.right = temp_left
return node
def main():
tree = BST()
N = 6
_set = set([random.randint(1, N * N) for _ in range(N)])
for x in _set:
tree.insert(x, "")
tree.pretty_print()
mirror_image(tree.root)
print ""
print "after inverting"
print ""
tree.pretty_print()
if __name__ == '__main__':
main()
| true
|
df7b73944b7b1d4676d64edafeb1c3cbc976d483
|
sanket-qp/IK
|
/3-Recursion/power.py
| 1,109
| 4.1875
| 4
|
"""
The problem statement is straight forward. Given a base 'a' and an exponent 'b'. Your task is to find a^b.
The value could be large enough. So, calculate a^b % 1000000007.
Approach:
keep dividing the exponent by two pow(2, 8) will be handled as follows
2x2x2x2 x 2x2x2x2
4x4 x 4x4
16 x 16
Time Complexity: O(b) where b is exponent
Space complexity: O(b) used by call stack
"""
count = 0
def power(a, b):
global count
count += 1
if b == 1:
return a
ans = power(a, b / 2) * pow(a, b / 2)
return ans * 1 if b % 2 == 0 else ans * a
def main():
global count
count = 1
a = 2
b = 4
assert pow(a, b) == power(a, b)
print count
a = 3
b = 8
count = 1
assert pow(a, b) == power(a, b)
print count
a = 2
b = 5
assert pow(a, b) == power(a, b)
a = 3
b = 9
assert pow(a, b) == power(a, b)
count = 1
a = 2
b = 33
assert pow(a, b) == power(a, b)
print count
if __name__ == '__main__':
main()
| true
|
73601e344b62ecc1b895c7485c0654c73927cb81
|
sanket-qp/IK
|
/3-Recursion/strings_from_wildcard.py
| 2,544
| 4.34375
| 4
|
"""
You are given string s of length n, having m wildcard characters '?', where each wildcard character represent
a single character.
Write a program which returns list of all possible distinct strings
that can be generated by replacing each wildcard characters in s with either '0' or '1'.
Any string in returned list must not contain '?' character i.e. you have to replace all '?'
with either '0' or '1'.
Sample Test Case 1:
Sample Input 1:
s = "1?10"
Sample Output 1:
result = ["1010", "1110"] or ["1110", "1010"].
Explanation 1:
"?" at index 1 (0 based indexing) can be replaced with either '0' or '1'. So, generated
two strings replacing "?" with '0' and '1'.
Sample Test Case 2:
Sample Input 2:
s = "1?0?"
Sample Output 2:
result = ["1000", "1001", "1100", "1101"] or any other list having same strings but in different order.
Explanation 2:
Input string have two '?' characters. Each one can be replaced with either '0' or '1'.
So, total 2*2 strings are possible as ('?' at index 1, '?' at index 3) can be replaced with
('0','0'), ('0','1'), ('1', '0'), ('1', '1').
Approach:
We find the first wild card character in the string and explore two branches by placing '0' and '1' on that index and recursively calling the function on those branches
once we are done from both the branches, we should put back the wildcard so that remaining branches can be explored
"""
def __strings_from_wildcard(s, idx, wildcard, result):
if idx == len(s):
result.append("".join(s))
return
if s[idx] != wildcard:
__strings_from_wildcard(s, idx + 1, wildcard, result)
else:
s[idx] = '0'
__strings_from_wildcard(s, idx + 1, wildcard, result)
s[idx] = '1'
__strings_from_wildcard(s, idx + 1, wildcard, result)
# backtrack the wildcard after exploring both possibilities so that
# other branches can be explored
s[idx] = wildcard
def strings_from_wildcard(s, wildcard):
result = []
__strings_from_wildcard(list(s), 0, wildcard, result)
return result
def main():
wildcard = '?'
s = "??"
actual = strings_from_wildcard(s, wildcard)
assert 4 == len(actual)
assert ["00", "01", "10", "11"] == actual
s = "1?0?"
actual = strings_from_wildcard(s, wildcard)
assert 4 == len(actual)
assert ["1000", "1001", "1100", "1101"] == actual
s = "1?0?1?"
actual = strings_from_wildcard(s, wildcard)
assert 8 == len(actual)
if __name__ == '__main__':
main()
| true
|
91acc9bd925f21654d1992dc9048232b8a8482c6
|
duhjesus/practice
|
/hackerrank/countingInversions.py
| 2,916
| 4.25
| 4
|
#!/bin/python3
import math
import os
import random
import re
import sys
# function: helper function
# merges left and right half arrays in sorted order
# input:nums= array to be sorted
# temp= place holder array, hard to do inplace sorting
# leftStart = start index of the left half array
# rightEnd = end index of the right half array
# ouput: none
# effect: sorts portion of nums array
def mergeHalves(nums, temp, leftStart,rightEnd):
leftEnd = leftStart+ (rightEnd-leftStart)//2 #middle
rightStart = leftEnd +1 # middle +1
size = rightEnd -leftStart +1
left = leftStart
right = rightStart
index = leftStart
cnt = 0
#comparing elements of the two halves
#smaller element of the two taken and copied into temp array
#then the array's(that the smaller element was in) ptr is incremented
#compared again until you reach the end of one of the arrays first
while(left <= leftEnd and right<=rightEnd):
if nums[left] <=nums[right]:
temp[index]=nums[left]
left =left +1
else:
temp[index] = nums[right]
right = right +1
cnt = cnt + leftEnd+1 -left
index = index +1
# recall python array slices go from left index : to right index (not inclusive on the right end)
# only one or the other of the halves will have remaining elements so only one of the two following lines
# will have an effect
# copying remaining elements of left half and right half
temp[index:index + leftEnd-left+1]=nums[left:left +leftEnd-left+1]
temp[index:index + rightEnd-right+1]=nums[right: right +rightEnd-right+1]
nums[leftStart:leftStart+size]=temp[leftStart:leftStart+size]
#print("result:",nums)
return cnt
def mergesort(nums, temp, leftStart, rightEnd):
if leftStart >= rightEnd:
return 0
middle = leftStart+ (rightEnd-leftStart)//2 #written like this b/c (leftstart+rightend )/2 <-overflows
cntl = mergesort(nums,temp,leftStart,middle)
cntr = mergesort(nums,temp,middle+1,rightEnd)
cntm = mergeHalves(nums,temp, leftStart,rightEnd)
return cntl+cntr+cntm
# Complete the countInversions function below.
def countInversions(arr):
temp = list(0 for i in range(0,len(arr)))
theCnt =mergesort(arr,temp,0,len(arr)-1)
return theCnt
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
n = int(input())
arr = list(map(int, input().rstrip().split()))
success = True
for i in range(0,len(arr)-1-1):
if arr[i]<= arr[i+1]:
continue
else:
success =False
break
if success == True:
result = 0
else:
result = countInversions(arr)
fptr.write(str(result) + '\n')
fptr.close()
| true
|
c393f87657b09fc9fb90621ef0d6ffe8eef1c47d
|
ErikBrany/python-lab2
|
/Lab 2_Exercise 2.py
| 914
| 4.125
| 4
|
from sys import task_list
print(sorted(task_list))
index = int(input("1. Insert new task, 2. Remove task, 3. Show all existing tasks, 4. Close program, Choose an action 1-4: "))
while index != 4:
if index == 1:
new_list = input("What task would you like to add: ")
task_list.append(new_list)
index = int(input("1. Insert new task, 2. Remove task, 3. Show all existing tasks, 4. Close program, Choose an action 1-4: "))
elif index == 2:
remove_list = input("What task would you like to remove: ")
task_list.remove(remove_list)
index = int(input("1. Insert new task, 2. Remove task, 3. Show all existing tasks, 4. Close program, Choose an action 1-4: "))
elif index == 3:
task_list.sort()
print(task_list)
index = int(input("1. Insert new task, 2. Remove task, 3. Show all existing tasks, 4. Close program, Choose an action 1-4: "))
| true
|
80c06bb6aeb90514d45d55fd50a8459630e99056
|
Arboreus-zg/Unit_converter
|
/main.py
| 642
| 4.53125
| 5
|
print("Hello! This is unit converter. It will convert kilometers into miles. Just follow instruction on screen")
while True:
kilometers = float(input("Enter a number in kilometers: "))
conv_fac = 0.621371
miles = kilometers * conv_fac
print("Your kilometers converted into miles are: ", miles)
#Ovo dalje od 10-tog reda nisam znao sam rijesiti odnosno kopirao sam iz ponuđenog rješenja..
choice = input("Would you like to do another conversion (y/n): ")
if choice.lower() != "y" and choice.lower() != "yes":
print("Thank you for using the converter")
break
| true
|
e78ef7ff493875a8789ac1022917b9208ba1aadc
|
siddeshgr/python-practice
|
/main.py
| 1,599
| 4.21875
| 4
|
#1
print("hello world")
name = input("enter your name: ")
print("hello siddesh")
#1 variables in python
x = 100
y = 100
z = 200
print(x,y,z)
#2 float [float]
x1 = 20.20
y1 = 30.30
print(x1,y1)
name = "hello"
print("single character",name[1])
name = "hello"
print("snigle character",name[3])
# Conditions for variable name
# 1. Variable should not starts with number
# 2. Should not contain space
# 3. Should not contain special characters
# Rules for long variable name PEP8
# 1. Single word
# a. Name -- correct
# b. name -- correct
# c. namE -- wrong
# 2. More than one word
# a. FullName -- correct -- Title Case
# b. Full_Name -- correct
# c. full_name -- correct
#3 string indexing
name ="hello world"
length =len(name)
print("length of string;",length)
print("single character;",name[3])
print("multiple chatrater",name[0:3])
print("mulitiple character;",name[0:4])
print("multiple charater;",name[2:5])
print("multiple charatrer start to end;",name[2::])
print("last element:",name[-1])
print("multiple last elements:",name[:-3])
#4 boolean
#value = true
#negative = false
# basic maths operators ( + , - , * ,/ , % , //)
# basic maths
print("x= ",x)
print("y= ",y)
#A addition
x = 40
y = 25
z = x+y
print("addition ",z)
#B substraction
sub = x-y
print("substraction",sub)
#C multiplication
mul = x*y
print("multiplication",mul)
#D dividion
div = x/y
print("dividion",div)
#E modulus
x1= 5
y1 = 2
mod = x1%y1
print("modulus",mod)
#F division
div = x//y
print("division",div)
| true
|
652ab15329f9c2dbf8ddc7f2053cbea0fe987617
|
earamosb8/holbertonschool-web_back_end
|
/0x00-python_variable_annotations/7-to_kv.py
| 305
| 4.125
| 4
|
#!/usr/bin/env python3
"""
Module - string and int/float to tuple
"""
from typing import Union, Tuple
def to_kv(k: str, v: Union[int, float]) -> Tuple[str, float]:
"""function to_kv that takes a string k
and an int OR float v as arguments
and returns a tuple."""
return (k, v * v)
| true
|
1e7d3ef971b8905b62be1a515dc9b82b24502def
|
earamosb8/holbertonschool-web_back_end
|
/0x00-python_variable_annotations/3-to_str.py
| 224
| 4.15625
| 4
|
#!/usr/bin/env python3
"""
Module - to string
"""
def to_str(n: float) -> str:
"""function to_str that takes a float n
as argument and returns the string
representation of the float."""
return str(n)
| true
|
a64e0ebc2e4d156518ffa5f96713b742694d886a
|
Leporoni/PythonBasic
|
/src/estrutura_for.py
| 568
| 4.125
| 4
|
numero = int(input("Digite um número: "))
for i in range(11):
print( "{n} x {i} = {resultado}".format(n=numero, i=i, resultado=numero*i))
else:
print("**Processo Concluído**")
linguagens = ["Python", "Java", "C#", "Node", "Go"]
print("Algumas linguagens de programação são: ")
for linguagem in linguagens:
print(" - " + linguagem)
capitais = {"SP":"São Paulo", "MG":"Belo Horizonte", "RJ":"Rio de Janeiro"}
print("Algumas capitais: ")
for sigla, capital in capitais.items():
print(" - {sigla}: {capital}".format(sigla=sigla, capital=capital))
| false
|
df29cb4575c299b3a6efb1bc4245ccb77b568998
|
MarcosRigal/Master-en-Python-Udemy
|
/15-manejo-errores/main.py
| 1,258
| 4.53125
| 5
|
"""
# Capturar excepciones y manejar errores en código
# susceptible a fallos/errores
try:#Comprueba el funcionamiento
nombre = input("¿Cual es tu nombre?")
if len(nombre) > 1:
nombre_usuario = "El nombre es: " + nombre
print(nombre_usuario)
except:#Si va mal
print("Ha ocurrido un error, introduzca un nombre válido")
else:
print("Todo ha ido bien")# Si va bien
finally:
print("Fin de la iteración")#Siempre
"""
#Multiples excepciones
try:
numero = int(input("Introduce un numero para elevarlo al cuadrado:"))
print(f"El cuadrado es: {numero * numero}")
except TypeError:
print("Debes convertir tus cadenas a enteros en el codigo")
except ValueError:
print("Introduce un numero correcto")
except Exception as e:
print(type(e))
print(f"Ha ocurrido un error: {type(e).__name__}")
# Exceociones personalizadas o lanzar excepcion
try:
nombre = input("Introduce el nombre: ")
edad = int(input("Introduce la edad: "))
if edad < 5 or edad >110:
raise ValueError("La edad introducida no es real")
elif len(nombre) <= 1:
raise ValueError("El nombre no esta completo")
else:
print("Hola")
except ValueError:
print("Introduce los datos correctamente")
except Exception as e:
print(f"Existe un error: {e}")
| false
|
b7e9e4dedabccd1f9cadb77bc04148f9a7bdb795
|
MarcosRigal/Master-en-Python-Udemy
|
/10-sets-diccionarios/diccionarios.py
| 730
| 4.4375
| 4
|
"""
Un diccionario es un tipo de dato que almacena otros conjuntos de datos en formato:
clave > valor (Es como un struct)
"""
persona = {
"nombre": "Marcos",
"apellidos": "Rivera",
"correo": "riveragavilanmarcos@gmail.com"
}
print(persona["correo"])
# Lista con diccionarios (Array de Structs)
contactos = [
{
"nombre": "Marcos",
"email": "marcosrigal@gmail.com"
},
{
"nombre": "Pepe",
"email": "pepe@gmail.com"
},
{
"nombre": "Salva",
"email": "salvador@gmail.com",
}
]
print(contactos[0]["nombre"])
print("\n Listado de contactos: ")
print("----------------------")
for contacto in contactos:
print(f"Nombre del contacto: {contacto['nombre']}")
print(f"Email del contacto: {contacto['email']}")
print("----------------------")
| false
|
037a548be82d0320267eb5830baabafd0f9604d1
|
yuta-inoue/soft2
|
/3/mon5.py
| 500
| 4.125
| 4
|
# -*- coding:utf-8 -*-
# 再帰関数の線形再帰(フィボナッチ数列の線形再帰)
fib = []
# 配列の要素を先に初期化して保持しておく(ループはO(n))
def init(n):
fib.append(0)
fib.append(1)
for i in range(2,n):
fib.append(fib[i-1] + fib[i-2])
# 先にO(n)で初期化した配列のn番目の要素を返す
def fib_linear(n):
return fib[n]
def main():
init(10)
for i in range(10):
print(fib_linear(i))
if __name__ == "__main__":
main()
| false
|
4693a753a7e8f36f6f7c8e7f051c3e1a345ca0cd
|
Moussaddak/holbertonschool-higher_level_programming
|
/0x0B-python-input_output/4-append_write.py
| 317
| 4.3125
| 4
|
#!/usr/bin/python3
""" Method """
def append_write(filename="", text=""):
""" appends a string at the end of
a text file (UTF8) and returns the
number of characters added: """
with open(filename, mode='a', encoding='utf-8') as file:
nb_char = file.write(text)
return nb_char
| true
|
990e1956b147a5641d1bb759ddcb99da0ba470fc
|
SvWer/MultimediaInteractionTechnologies
|
/05_Excercises03_12/02.py
| 637
| 4.3125
| 4
|
#Write a Python program to calculate number of days between two dates. Sample dates: (2019, 7, 2) (2019, 7, 11)
from datetime import date
from datetime import timedelta
if __name__ == '__main__':
date1 = input("What is the first date (dd.mm.jjjj)")
print("Date 1: ", date1)
day1, month1, year1 = map(int, date1.split('.'))
d1 = date(year1, month1, day1)
date2 = input("What is the second date (dd.mm.jjj)")
print("date 2: ", date2)
day2, month2, year2 = map(int, date2.split('.'))
d2 = date(year2, month2, day2)
delta = d1 - d2
if (delta.days < 0):
delta *= -1
print("Day difference between the two dates: ", delta.days)
| true
|
58b4ca15f45d8c5400b683b9a9ddbbddb159b816
|
pniewiejski/algorithms-playground
|
/data-structures/Stack/bracket_validation.py
| 955
| 4.21875
| 4
|
# Task:
# You are given a string containing '(', ')', '{', '}', '[' and ']',
# check if the input string is valid.
# An input string is valid if:
# * Open brackets are closed by the same type of brackets.
# * Open brackets are closed in the correct order.
from collections import deque
OPENING_BRACKETS = ['(', '[', '{']
ALLOWED_CLOSING = {
')': ['(', '}', ']'],
']': ['[', '}', ')'],
'}': ['{', ']', ')']
}
def validate_brackets(string):
stack = deque()
for symbol in string:
if symbol in OPENING_BRACKETS:
stack.append(symbol)
else:
bracket = stack.pop()
if bracket == ALLOWED_CLOSING[symbol]:
return False
return len(stack) == 0
if __name__ == "__main__":
print(validate_brackets("[()({})]")) # Expect True
print(validate_brackets("[(())({})]{")) # Expect False
print(validate_brackets("[(()({})]{}")) # Expect False
| true
|
4238ef5459c897e2dd8fff20c5f3045bbeceb15a
|
KinaD-D/Homework
|
/ДЗ 31.10.2020/Камень Ножницы Бумага.py
| 2,406
| 4.125
| 4
|
print('Добро пожаловать в камень ножницы бумага, сдесь вы будете играть с ботом.\nВ конце игры вам покажут статистику, если хотите что бы она была точнее играйте больше.')
Game = int(input('Введите сколько игр играть будете '))
scissors = bumaga = kamen = raza = wins = 0
import random
for i in range (Game):
input()
BotChoice = random.randint(1, 3)
YourChoice = int(input("Введите камень(1) бумага(2) или ножницы(3) "))
print('Соперник выкинул', BotChoice)
if YourChoice == 1 and BotChoice == 3:
print("Вы победили ")
wins += 1
elif YourChoice == BotChoice + 1:
print("Вы победили ")
wins += 1
elif YourChoice == BotChoice:
print("Ничья ")
x += 1
else:
print('Вы проиграли')
raza += 1
if YourChoice == 1:
kamen += 1
if YourChoice == 2:
bumaga += 1
if YourChoice == 3:
scissors += 1
if kamen >= bumaga + scissors:
print('Против вас ОЧЕНЬ эффективна бумага, ваш любимый выбор это камень')
elif bumaga >= kamen + scissors:
print('Против вас ОЧЕНЬ эффективны ножницы, ваш любимый выбор это бумага')
elif scissors >= kamen + bumaga:
print('Против вас ОЧЕНЬ эффективен камень, ваш любимый выбор это ножницы')
elif scissors > kamen and scissor > bumaga:
print('Против вас довольно таки эффективен камень, ваш любимый выбор это ножницы')
elif kamen > scissors and kamen > bumaga:
print('Против вас довольно таки эффективна бумага, ваш любимый выбор это камень')
elif bumaga > scissors and bumaga > kamen:
print('Против вас довольно таки эффективны ножницы, ваш любимый выбор это бумага')
else:
print('Вы играете сбалансированно')
print('Вы выиграли', wins, 'раз')
print('Вы выбрали камень', kamen, 'раз, бумагу', bumaga, 'раз, а ножницы', scissors, 'раз')
input('')
| false
|
e9c519040728ccf2b22ca6bda0c9c200840b68a8
|
OlgaBukharova/Python_projects
|
/черепашка 1/черепашка 10.py
| 276
| 4.375
| 4
|
import turtle
from math import pi
turtle.shape ('turtle')
def circle (r):
l=2*pi*r
for i in range (360):
turtle.forward (l/360)
turtle.left (1)
r=100
d=3
for i in range (d):
circle (r)
turtle.left (180)
circle(r)
turtle.left (180/d)
| false
|
393cfd774cdd988ec4b1ee0c5c958decf64c7939
|
OlgaBukharova/Python_projects
|
/черепашка 1/черепашка 11.py
| 279
| 4.375
| 4
|
import turtle
from math import pi
turtle. shape ('turtle')
def circle (r):
l=2*pi*r
for i in range (360):
turtle.forward (l/360)
turtle.left (1)
for r in range (10,100,10):
for i in range (2):
circle (r)
turtle.left (180)
| false
|
3c4465418f980be01250fa017db3031a6a69e33b
|
barenzimo/Basic-Python-Projects
|
/2-tipCalculator(2).py
| 410
| 4.28125
| 4
|
#A simple tip calculator to calculate your tips
print("Welcome to the tip calculator \n")
bill=float(input("What was the total bill paid? $"))
tip_percent=float(input("What percentage of bill would you like to give? 10, 12 or 15? "))
people=int(input("How many people are splitting the bill? "))
total=float(bill+(bill*tip_percent/100))
answer=round(total/people,2)
print(f"Each person should pay ${answer}")
| true
|
0c719b3acb3a4af4425fa11a271a079af4fdfba6
|
felipovski/python-practice
|
/intro-data-science-python-coursera/curso1/semana3/ordemCrescente.py
| 346
| 4.125
| 4
|
def main():
numero1 = int(input("Digite o primeiro número inteiro: "))
numero2 = int(input("Digite o segundo número inteiro: "))
numero3 = int(input("Digite o terceiro número inteiro: "))
if numero2 >= numero1 and numero2 <= numero3:
print("crescente")
else:
print("não está em ordem crescente")
main()
| false
|
2d462e37e3aae358cb78b7bb43b980fe0b0be395
|
jc8702/Apex---Curso-Python
|
/apex-ensino-master/aula-12-08-2020/ex-08.py
| 405
| 4.21875
| 4
|
# Exercício 08
# Escreva um programa em Python que receba o nome e o sobrenome do usuário, em seguida os imprima em ordem reversa. Por exemplo:
if __name__ == '__main__':
nome = input("Digite um nome: ")
sobrenome = input("Digite um sobrenome: ")
print(f'{nome} {sobrenome} {3 * 3}')
# Apex Ensino
#texto2 = texto.split(',')
#print(texto[::-1])
#print(texto2[1], texto2[0])
| false
|
30b7a0a95d92d3b3e7257b3d1a1f39ac6de5284e
|
jc8702/Apex---Curso-Python
|
/apex-ensino-master/aula-12-08-2020/ex-06.py
| 683
| 4.34375
| 4
|
# Exercício 06
# Escreva um programa Python que pedirá 3 números, informe qual deles é o menor.
if __name__ == '__main__':
numero1 = int(input("Digite o primeiro número: "))
numero2 = int(input("Digite o segundo número: "))
numero3 = int(input("Digite o terceiro número: "))
numeros = [numero1, numero2, numero3]
numeros.sort()
if numero1 < numero2 and numero1 < numero3:
print(f"O menor número é o primeiro: {numero1}")
elif numero2 < numero1 and numero2 < numero3:
print(f"O menor número é o segundo: {numero2}")
elif numero3 < numero1 and numero3 < numero2:
print(f"O menor número é o segundo: {numero3}")
| false
|
cc7a99e42302c448bfd8d59d0e2c2b38670dbeae
|
linhuiyangcdns/leetcodepython
|
/两个数组的交集 II.py
| 982
| 4.5625
| 5
|
"""
给定两个数组,写一个方法来计算它们的交集。
例如:
给定 nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].
注意:
输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
我们可以不考虑输出结果的顺序。
跟进:
如果给定的数组已经排好序呢?你将如何优化你的算法?
如果 nums1 的大小比 nums2 小很多,哪种方法更优?
如果nums2的元素存储在磁盘上,内存是有限的,你不能一次加载所有的元素到内存中,你该怎么办?
"""
class Solution:
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums3 = []
for i in nums1:
if i in nums2:
nums3.append(i)
return nums3
if __name__ == "__main__":
a = Solution()
nums = a.intersect([1,2,2,1],[2])
print(nums)
| false
|
0a08293e35d0d181b03ef54814b13f75e8748f6f
|
chrihill/COM170-Python-Programming
|
/Program1.py
| 590
| 4.21875
| 4
|
# Christian Hill
#Program Assignment 1
#COMS-170-01
#Display basic information about a favorite book
#Variabels: strName - my name, strBookName - stores book name, strBookAuthor - author name, strDate - copy right date, strPage - number of pages
strName = 'Christian Hill'
strBookName = 'The Fall of Reach'
strBookAuthor = 'Eric Nylund'
strDate = '2001'
strPage = '365 pages'
#Display Infoormation about me
print ('My name is ' + strName)
print ('My favorite book is ' + strBookName)
print ('written by ' + strBookAuthor)
print ('It was written in ' + strDate)
print ('It has ' + strPage)
| true
|
8d9cf33139cfed49eaf6430074b80e7ba9e5b0f0
|
PhungXuanAnh/python-note
|
/others.py
| 711
| 4.4375
| 4
|
def add(x):
return x + 1
def sample_map():
"""
map() func allows us to map an iterable to a function.
"""
print(list(map(add, [1, 2, 3])))
def sample_map_lambda():
"""
map() func allows us to map an iterable to a function.
using lambda for avoid define a func
"""
print(list(map(lambda x: x + 1, [1, 2, 3])))
def anonymous_object():
obj1 = lambda: None
setattr(obj1, "attr11", "value11")
setattr(obj1, "attr12", "value12")
obj2 = lambda: None
setattr(obj2, "obj1", obj1)
print(obj2.obj1.attr11)
print(obj2.obj1.attr12)
if __name__ == "__main__":
# sample_map()
# sample_map_lambda()
anonymous_object()
| false
|
bf10ff9510a7274223d8764192a1f36366636bb7
|
FernandaSlomp/Resumo_Tecnologias_Introdutorias
|
/Curso_Python_MEGAREVISAO/aprendendo/exercicios/ex037.py
| 486
| 4.15625
| 4
|
numero = int(input('Digite um número inteiro: '))
print('''Escolha uma das bases para a conversão
[1] converter para binário
[2] converter para octal
[3] converter para hexadecimal''')
opcao = int(input('Sua opção: '))
if opcao == 1:
print(f'{numero} em binário é igual a {bin(numero)}')
elif opcao == 2:
print(f'O {numero} em octal é {oct(numero)}')
elif opcao == 3:
print(f'O {numero} em hexadecimal é igual a {hex(numero)}')
else:
print('Opção invalida')
| false
|
3ea0003beea89266866ca00c7ae40d08a3634a4d
|
tchka/python2
|
/task_1.py
| 585
| 4.1875
| 4
|
# https://drive.google.com/file/d/18aEzzMoVyhGi9VjPBf_--2t-aVXVIvkW/view?usp=sharing
# Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь.
number = int(input('Введите целое трехзначное число: '))
number = abs(number)
n0 = number % 10
print(n0)
number = number // 10
n1 = number % 10
print(n1)
n2 = number // 10
print(n2)
product = n0 * n1 * n2
sum = n0 + n1 + n2
print(f'Произведение цифр: {product}')
print(f'Сумма цифр: {sum}')
| false
|
a25c3917dfc3fd580e9bcb107df8a50c0e9719ff
|
alliequintano/triangle
|
/main.py
| 1,412
| 4.1875
| 4
|
import unittest
# Function: triangle
#
# Given the lengths of three sides of a triangle, classify it
# by returning one of the following strings:
#
# "equ" - The triangle is equilateral, i.e. all sides are equal
# "iso" - The triangle is isoscelese, i.e. only two sides are equal
# "sca" - The triangle is scalene, i.e. no sides are equal
# "err" - The arguments do not describe a valid triangle
#
def triangle(a, b, c):
for item in a, b, c:
if not isinstance(item, int) and not isinstance(item, float):
return "err"
if (item <= 0):
return "err"
listOfSides = sorted([a, b, c])
if (listOfSides.pop() > sum(listOfSides)):
return "err"
if (a == b and b == c):
return "equ"
if (a == b or a == c or b == c):
return "iso"
return "sca"
class Tests(unittest.TestCase):
def testTriangle(self):
self.assertEqual('equ', triangle(1, 1, 1))
self.assertEqual('iso', triangle(1, 1, 2))
self.assertEqual('iso', triangle(1, 2, 2))
self.assertEqual('sca', triangle(1, 2, 3))
self.assertEqual('err', triangle(1, 1, "x"))
self.assertEqual('err', triangle(1, -1, 1))
self.assertEqual('iso', triangle(1/6, 1, 1))
self.assertEqual('sca', triangle(1, 1.5, 2))
self.assertEqual('err', triangle(1, 2, 4))
# handle zero length
unittest.main()
| true
|
808e12eef51c92d2ef004a9b39a638b1e5334fd4
|
Tometoyou1983/Python
|
/Automate boring stuff/collatz.py
| 2,119
| 4.1875
| 4
|
'''
import os, sys
os.system("clear")
print("Lets introduce you to collatz sequence or problem")
print("its an algorithm that starts with an integer and with multiple sequences reaches at 1")
numTries = 0
accumlatedNum = ""
newNumber = 0
def collatz(number):
if number % 2 == 0:
newNumber = number // 2
else:
newNumber = 3 * number + 1
return newNumber
try:
while True:
myInteger = int(input("Enter a integer: "))
while (newNumber != 1):
newNumber = collatz(myInteger)
numTries = numTries + 1
if accumlatedNum == "":
accumlatedNum = accumlatedNum + str(newNumber)
else:
accumlatedNum = accumlatedNum + ", " + str(newNumber)
myInteger = newNumber
print("It took " + str(numTries) + " tries to come to 1")
print("the sequence is: " + accumlatedNum)
playAgain = input("Would you like to play again? (Yes/No) ")
if playAgain == "Yes":
continue
else:
sys.exit()
except ValueError:
print("You did not enter an integer")
myInteger = input("Enter a valid integer: ")
'''
import os, sys
os.system("clear")
print("Lets introduce you to collatz sequence or problem")
print("its an algorithm that starts with an integer and with multiple sequences reaches at 1")
def collatz(number):
count = 0
print(str(number))
if number == 1:
return count
elif (number % 2 == 0):
count = (collatz(int(number /2)) + 1)
elif (number % 2 != 0):
count = (collatz(int(3 * number + 1)) + 1)
return count
try:
while True:
myInteger = int(input("Enter a integer: "))
numTries = collatz(myInteger)
print("It took " + str(numTries) + " tries to come to 1")
playAgain = input("Would you like to play again? (Yes/No) ")
if playAgain == "Yes":
continue
else:
sys.exit()
except ValueError:
print("You did not enter an integer")
myInteger = input("Enter a valid integer: ")
| true
|
08fd2a87081a0ddc7d56c5c9a6c393ba669efa75
|
Kennethowl/Practicas-Java-y-Python
|
/Python/HelloWorld_Datatypes.py
| 694
| 4.25
| 4
|
# Comentarios
print("Hola Mundo, como estan")
# Datatypes
# Maneras de imprimir string
print("Hola Mundo, como estan")
print("""Hola Mundo, como estan""")
print('Hola Mundo, como estan')
print('''Hola Mundo, como estan''')
# Comando Type
print(type(100))
# Concatenacion
print("See you around" + " " + "World")
# Numeros enteros y decimales
print(100)
print(10.10)
# Boolean
# True - False
# List
# [10, 15, 16, 10]
print([10, 15, 16, 10])
# Tuplas
# (10, 15, 16, 10)
# Diccionarios
print(type({
"Nombre: ":"Kenneth"
}))
# None
print(type(None))
# Comandos
#type(tipo de dato) - > type(100)
#python para abrir python
#python archivo.py - > Ejecuta el archivo
#exit()-> Salir
| false
|
02822058efc7642aa91e374dab6dcecf41100159
|
GT12ness/lectures
|
/examples/Ulohy_hodina4.py
| 1,997
| 4.15625
| 4
|
"""
1. napiste program v pythone
- vypisete text: aka je vonku teplota?
- zadate vstup (cislo)
- vyhodnotite ak je teplota vyssie ako 25 tak vypiste: "zober si tricko. "
ak nie vypiste: "Zobrer si aj sveter. "
- na konci vypiste: "Mozes ist vonku"
mozne riesenie:
"""
temperature = float(input('What is the temperature? '))
if temperature > 25:
print('Wear shorts.')
else:
print('Wear long pants.')
print('Get some exercise outside.')
# podobna uloha - oblubene jedlo
food = 'pizza'
if food == 'pizza':
print('Ummmm, my favorite!')
print('I feel like saying it 100 times...')
# print(100 * (food + '! '))
"""
2. Napiste program v pyhone, ktory po zadani poctu bodov vypise znamku.
Max pocet bodov za test je 100, napiste metodu ktora vyhodnoti vysledky kde
A >= 90, B >= 80, C >= 70, >= 60, E >= 50 inak Fx
- pouzite elif
"""
def letterGrade(score):
if score >= 90:
letter = 'A'
elif score >= 80:
letter = 'B'
elif score >= 70:
letter = 'C'
elif score >= 60:
letter = 'D'
elif score >= 50:
letter = 'E'
else:
letter = 'F'
return letter
""" 3. Vypiste cisla 0,1,2,3,4, pouzitim for """
# Prints out the numbers 0,1,2,3,4
for x in range(5):
print(x)
"""
4. Vypiste cisla 0,1,2,3,4, pouzitim while
hint: pouzite pocitadlo
"""
count = 0
while count < 5:
print(count)
count += 1 # This is the same as count = count + 1
"""
5. Vypiste cisla 0,1,2,3,4, pouzitim while a break
hint: pouzite pocitadlo
"""
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
"""
6. Vypiste len parne cisla, hint: pouzite continue a % (zvysok po deleni), vypiste len cisla mensie ako 15
"""
# Prints out only odd numbers - 1,3,5,7,9 - len parne - pouzitie continue
for x in range(15):
# Check if x is even
if x % 2 == 0:
continue
print(x)
""" ukazka printu premennej. """
for x in range(0, 3):
print("We're on time %d" % x)
| false
|
b4b469aeb580da7bf9a83b6b1b3c64a967cd3dc8
|
Turhsus/coding_dojo
|
/python/bike.py
| 736
| 4.21875
| 4
|
class Bike(object):
def __init__(self, price, max_speed, miles = 0):
self.price = price
self.max_speed = max_speed
self.miles = miles
def displayInfo(self):
print "Price:", self.price, "Dollars; Max Speed:", self.max_speed, "MPH; Miles:", self.miles
return self
def ride(self):
print "Riding"
self.miles += 10
return self
def reverse(self):
if (self.miles > 0):
print "Reversing"
self.miles -= 5
return self
else:
print "Cannot Reverse!"
return self
motorbike = Bike(1000, 100)
bicycle = Bike(200, 25)
tricycle = Bike (500, 20)
motorbike.ride().ride().ride().reverse().displayInfo()
bicycle.ride().ride().reverse().reverse().displayInfo()
tricycle.reverse().reverse().reverse().displayInfo()
| true
|
740de0cb3d6afbb7c3b28752d15a1e7bdb751a12
|
Breenori/Projects
|
/FH/SKS3/Units/urlParser/sqlite/sqlite.py
| 570
| 4.15625
| 4
|
import sqlite3
connection = sqlite3.connect('people.db')
cursor = connection.cursor()
cursor.execute("create table if not exists user(id integer primary key autoincrement, name text, age integer)")
cursor.execute("insert into user values (NULL, 'sebastian pritz', 22)")
#1
cursor.execute("select * from user")
row = cursor.fetchone()
print(row[0])
print(row[1])
print(row[2])
#2
for rows in cursor.execute("select * from user"):
print(rows)
#3
liste = cursor.execute("select * from user").fetchall()
print(liste)
cursor.close()
connection.commit()
connection.close()
| true
|
32d6d978ce4af56dd6ce8870450a4abe1addfd7e
|
MaxBI1c/afvinkopdracht-3-goed
|
/afvinkopdracht 3 opdracht 2 opdracht 2.py
| 762
| 4.21875
| 4
|
lengthrectangle_one = int(input('What is the length of the first rectangle?'))
widthrectangle_one = int(input('What is the width of the first rectangle?'))
lengthrectangle_two = int(input('What is the length of the second rectangle?'))
widthrectangle_two = int(input('What is the width of the second rectangle?'))
area_rectangle_one = lengthrectangle_one * widthrectangle_one
area_rectangle_two = lengthrectangle_two * widthrectangle_two
if area_rectangle_one > area_rectangle_two :
print('The first rectangle has a bigger area than the second rectangle')
elif area_rectangle_two < area_rectangle_one :
print('The second rectangle has a bigger area than the first rectangle')
else:
print('Both rectangles have the same area')
| true
|
b6f58732445c87338e5722342ab1cb8b26965886
|
mac95860/Python-Practice
|
/working-with-zip.py
| 1,100
| 4.15625
| 4
|
list1 = [1,2,3,4,5]
list2 = ['one', 'two', 'three', 'four', 'five']
#must use this syntax in Python 3
#python will always trunkate and conform to the shortest list length
zipped = list(zip(list1, list2))
print(zipped)
# returns
# [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')]
unzipped = list(zip(*zipped))
print(unzipped)
# returns
# [(1, 2, 3, 4, 5), ('one', 'two', 'three', 'four', 'five')]
# for (l1 , l2) in zip(list1, list2):
# print(l1)
# print(l2)
items= ['Apple', 'Banana', 'Orange']
counts = [3,2,5]
prices = [0.99, 0.25, 0.50]
sentences = []
for (item, count, price) in zip(items, counts, prices):
item, count, price = str(item), str(count), str(price)
sentence = "I bought " + count + ' ' + item + 's at ' + price + '.'
sentences.append(sentence)
# by not indenting the print statement, the statement has been moved outside of the for loop
print(sentences)
# returns
# [
# 'I bought 3 Apples at 0.99.',
# 'I bought 2 Bananas at 0.25.',
# 'I bought 5 Oranges at 0.5.'
# ]
for sentence in sentences:
print(sentence)
| true
|
e6edf7e821959e69ebfbd514bfd6ebed4d6a3504
|
taozhenting/python_introductory
|
/name_cases.py
| 542
| 4.3125
| 4
|
#练习
name="eric"
print('"Hello '+name.title()+',would you like to learn some Python today?"')
print(name.title())
print(name.upper())
print(name.lower())
print('Albert Einstein once said, "A person who never made a mistake never tried anything new."')
famous_person='Albert Einstein'
message=famous_person + ' once said, "A person who never made a mistake never tried anything new."'
print(message)
name='\teric\t'
print(name.lstrip())
print(name.rstrip())
print(name.strip())
name='\neric\n'
print(name.lstrip())
print(name.rstrip())
print(name.strip())
| true
|
c81d6c2c9354420b94c7133ef013d5c564ae367b
|
taozhenting/python_introductory
|
/4-3/练习.py
| 572
| 4.28125
| 4
|
#打印1-20
for value in range(1,21):
print(value)
#一百万
numbers = list(range(1,100001))
print(numbers)
print(min(numbers))
print(max(numbers))
print(sum(numbers))
#1到20的奇数
even_numbers = list(range(1,21,2))
for even_number in even_numbers:
print(even_number)
#3到30能被3整除
even_numbers = list(range(3,31,3))
for even_number in even_numbers:
print(even_number)
#1到10乘3次方
squares = []
for value in range(1,11):
squares.append(value**3)
print(squares)
#列表解析
squares = [value**3 for value in range(1,11)]
print(squares)
| false
|
78de74417139d34d6197348884cc2fb504b37223
|
taozhenting/python_introductory
|
/6-3/favorite_languages.py
| 1,303
| 4.15625
| 4
|
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
#遍历字典
for name,language in favorite_languages.items():
print(name.title() + "'s favorite language is" +
language.title() + ".")
#遍历字典中的所有键
for name in favorite_languages.keys():
print(name.title())
#判断朋友并打印
friends = ['phil','sarah']
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print("Hi " + name.title() +
",I see your favorite language is " +
favorite_languages[name].title() + "!")
#判断某人是否接受调查
if 'erin' not in favorite_languages.keys():
print("Erin,please take our poll!")
#字典的键排序
for name in sorted(favorite_languages.keys()):
print(name.title() + ",thank you for taking the poll.")
#遍历字典中的所有值
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())
#剔除重复的值(set集合)
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())
| true
|
15e07b16f0e6c1b0419de3232ecc28446a0ab3d0
|
BI-JULEO/BI-TP
|
/tp3/utils/distance.py
| 599
| 4.15625
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
http://fr.wikipedia.org/wiki/Distance_%28math%C3%A9matiques%29
'''
import math
def euclidienne(x,y):
'''
distance euclidienne pour 2scalaires
:param x:
:param y:
:type x: int/float
:type y: int/float
:return: la distance euclidienne entre x et y
:rtype: float
'''
return math.sqrt((x-y)**2)
def manhattan(x,y):
return abs(x-y)
def cartesien(a,b):
return math.sqrt((b[0]-a[0])**2 + (b[1]-a[1])**2)
print manhattan(2,6.5)
print euclidienne(2,6.5)
a = (1,2)
b = (1,5)
print cartesien(a,b)
| false
|
60a3272b25d14ce17af91e2ba41803ba7e48e2c7
|
IgorGarciaCosta/SomeExercises
|
/pyFiles/linkedListCycle.py
| 1,354
| 4.15625
| 4
|
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new
# node at the beginning
def push(self, new_data):
new_node = ListNode(new_data)
new_node.next = self.head
self.head = new_node
# Utility function to print it
# the linked LinkedList
def printList(self):
temp = self.head
while(temp):
print(temp.data, end=" ")
temp = temp.next
def hasCycle(self) -> bool:
s = set()
temp = self.head
while(temp):
if(temp in s):
return True
s.add(temp)
temp = temp.next
return False
# Driver program for testing
llist = LinkedList()
llist.push(20)
llist.push(4)
llist.push(15)
llist.push(10)
# Create a loop for testing
llist.head.next.next.next.next = llist.head
if(llist.hasCycle()):
print("Loop found")
else:
print("No Loop ")
# class Solution:
# def hasCycle(self, head: ListNode) -> bool:
# s = set()
# temp = head
# while(temp):
# if(temp in s):
# return True
# s.add(temp)
# temp = temp.next
# return False
| true
|
870dbcb30b9da785f1d82032c62171974f1fc6c0
|
cdhutchings/csv_read_write
|
/csv_example.py
| 796
| 4.125
| 4
|
import csv
# Here we load the .csv
"""
-open file
-read line by line
-separate by commas
"""
# with open("order_details.csv", newline='') as csv_file:
# csvreader = csv.reader(csv_file, delimiter = ",")
# print(csvreader)
#
# for row in csvreader:
# print(row)
#
# iter() creates an iterable object
# next() goes to the next line
# with open("order_details.csv", newline='') as csv_file:
# csvreader = csv.reader(csv_file, delimiter=",")
#
# iterable = iter(csvreader)
# headers = next(iterable)
#
# for row in iterable:
# print(row)
#
# list()
with open("order_details.csv", newline='') as csv_file:
csvreader = csv.reader(csv_file, delimiter=",")
for list in list(csvreader):
print(list)
# Transforming and writing to CSV
| true
|
b27ac5eca6442e9a0b09ef30d9836475deb593c3
|
mzkaoq/codewars_python
|
/5kyu Valid Parentheses/main.py
| 297
| 4.1875
| 4
|
def valid_parentheses(string):
left = 0
right = 0
for i in string:
if left - right < 0:
return False
if i == "(":
left += 1
if i == ")":
right += 1
if left - right == 0:
return True
else:
return False
| true
|
211faf6de66a218395512c29d17865aa5d5b38a3
|
PhiphyZhou/Coding-Interview-Practice-Python
|
/Cracking-the-Coding-Interview/ch9-recursion-DP/s9-1.py
| 763
| 4.3125
| 4
|
# 9.1 A child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3
# steps at a time. Implement a method to count how many possible ways the child can run up
# the stairs.
def count(n):
mem = [None]*n
return count_hop_ways(n, mem)
def count_hop_ways(n, mem):
if n == 0:
return 1
counter = 0
for i in range(1,4):
if n >= i:
if mem[n-i] == None:
mem[n-i] = count_hop_ways(n-i,mem)
counter += mem[n-i]
return counter
print count(0) # 1
print count(1) # 1
print count(2) # 2
print count(3) # 4
print count(4) # 7
print count(100) # 180396380815100901214157639
# The count for step n is just the sum of the previous 3 counts.
| true
|
220d4effabcc190fcd8690810724521ef9641da6
|
PhiphyZhou/Coding-Interview-Practice-Python
|
/HackerRank/CCI-Sorting-Comparator.py
| 1,213
| 4.25
| 4
|
# Sorting: Comparator
# https://www.hackerrank.com/challenges/ctci-comparator-sorting
# 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.
class Player:
def __init__(self, name, score):
self.name = name
self.score = score
def __repr__(self):
return (self.name, self.score)
def comparator(a, b):
return cmp((-a.score,a.name), (-b.score,b.name))
n = int(raw_input())
data = []
for i in range(n):
name, score = raw_input().split()
score = int(score)
player = Player(name, score)
data.append(player)
data = sorted(data, cmp=Player.comparator)
for i in data:
print i.name, i.score
| true
|
3957b50146e927e27fb014345ebcfcd15972a288
|
leikang123/python-code
|
/day9.py
| 950
| 4.21875
| 4
|
"""
#汽车租
car = input("what is it car ?")
print("Let mw see if I can find you a Subaru :"+' '+car)
print("\n")
men = int(input("how much have pople meat,please?"))
print(men)
if men > 8 :
print("Not")
else :
print("Yes")
print("\n")
number = int(input("please input number :"))
print(number)
if number % 10 == 0 :
print("Yes")
else :
print("No")
#
per = " please input pizza:"
while True :
message = input(per)
if message == 'quite' :
break
else:
print("ok, This is pizza"+' '+message)
"""
"""
age = "please input you age :"
while True:
num = int(input(age))
if num < 3:
print("免费")
elif num < 12 :
print("$10")
elif num >= 12:
print("$15")
elif num == 'quite':
print("bye")
"""
print("\n")
so = ['pas','pizza','hu']
fs = [];
while so :
us = so.pop()
print(us.title())
fs.append(us)
for s in fs :
print(s.title())
| false
|
e96deebf5c52ab7eda648a973f5871cc21f50d7d
|
leikang123/python-code
|
/Algorithm/Tree.py
| 1,417
| 4.21875
| 4
|
"""d定义二叉树"""
#树的节点
class Node():
#节点的属性,值,左节点,右节点
def __init__(self,value,left=None,right=None):
self.value = value
self.left= left
self.right = right
#二叉树
class BTree():
#根节点
_root = None
#跟节点属性
def __init__(self,root):
self._root = root
# 定义添加方法,node=节点
def inseft(self,node):
# 添加节点,pNode父亲节点,node带添加的节点
def inseft(pNode,node):
#如果父亲节点大于带添加的节点
if pNode.value > node.value:
#如果左节点为空
if pNode.left is None:
#增加的节点为左节点
pNode.left = node
# 否则递归的添加左节点
else:
inseft(pNode.left,node)
# 否则如果右节点的为空
else:
if pNode.right is None:
# 则添加到右节点
pNode.right=node
# 右节点递归的添加
else:
inseft(pNode.right,node)
# 添加根节点
inseft(self._root,node)
if __name__=='_main_':
tree =BTree(Node(5))
list = [2,1,4,6,8,9]
for value in list :
tree.insert(Node(value))
| false
|
2e57d87c04fcdd82734a5a0c4de8bb2f43bdd814
|
hgy9709/p2_20161118
|
/w5Main8.py
| 327
| 4.15625
| 4
|
height=input ("input user height (M): ")
weight=input ("input user weight (kg): ")
print "%.1f" %height, "%.1f" %weight
BMI=weight/(height*height)
print "%.1f" %BMI
if BMI<=18.5:
res= "Low weight"
elif 18.5<BMI<23:
res= "Nomal weight"
elif 23<=BMI<25:
res= "Over weight"
else:
res= "Very Over weight"
print res
| false
|
7d16a8117e50750c2c4f9606aba2ab6612cd3b09
|
chunin1103/nguyentuananh-c4e22
|
/Fundamentals/session3/homework/crud_1.py
| 2,589
| 4.125
| 4
|
items = ["T-shirt", "Sweater"]
loop_counter = 0
while True:
if loop_counter == 0:
n = str(input("Welcome to our shop, what do you want? \n Please enter C, R, U, D or exit: "))
loop_counter += 1
else:
n = str(input("What else do you want? \n Please enter C, R, U, D or exit: "))
if n.upper() == "R":
print("Our items:", end = " ")
print(*items, sep = ", ")
elif n.upper() == "C":
while True:
c_new_item = (input("Enter new item: "))
if c_new_item.isdigit():
print("New item cannot be a number")
elif c_new_item.isupper() or c_new_item.islower():
print("new item must contain both Lower and UPPER case")
else:
items.append(c_new_item)
break
print("Our items:", end = " ")
print(*items, sep = ", ")
elif n.upper() == "U":
while True:
u_position = (input("Update position? "))
if u_position.isalpha():
print("Position must be a number")
elif int(u_position) > len(items):
print("Location unavailable")
else:
break
while True:
u_item = str(input("Insert new item? "))
if u_item.isdigit():
print("New item cannot be a number")
elif u_item.isupper() or u_item.islower():
print("new item must contain both Lower and UPPER case")
else:
clothes[pos-1] = new_item
break
# while True:
# new_item = input("New item: ")
# if new_item.isdigit(): #handle exception
# print("must not be a number")
# elif new_item.isupper():
# print("must not contain only uppercase letter")
# elif new_item.islower():
# print("must not contain only lowercase letter")
# else:
# clothes[pos-1] = new_item
# break
# print("Our items: ", end = "")
# print(*items, sep = ", ")
elif n.upper() == "D":
while True:
d_position = (input("Delete position "))
if d_position.isalpha():
print("Delete position must be a number")
else:
items.pop(int(d_position) - 1)
break
print("Our items: ", end = "")
print(*items, sep = ", ")
elif n.lower() == "exit":
break
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.