blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3c46a34d85f9f770eec03952fbfb76a6738252bf | Tanmay53/cohort_3 | /submissions/sm_102_amit/week_14/day_3/evaluation/email_domain.py | 235 | 4.1875 | 4 | # Find the email domain
email = input("Enter email address: ")
result = ""
for i in range(len(email)):
if email[i] == "@":
result = email[i + 1:]
print(result)
# Sample Case:
'''
Enter email address: akamit21@gmail.com
gmail.com
'''
| true |
2b9d0e8269b9665dff7264ec32a848a974b77a3e | lin-br/pythonando-do-lin | /studies/classes/aula010_variaveis_compostas_lista_tupla_dicionario/file003_dicionario.py | 830 | 4.21875 | 4 | """
Variáveis compostas
Tuplas inicia com ()
Lista inicia com []
Dicionário inicia com {}
Conjuntos inicia com {}
Dicionário são mutáveis
"""
dados = dict()
dados['nome'] = 'Lin'
dados['idade'] = 26
dados['sexo'] = 'M'
print(dados)
dados = {'nome': 'Pedro', 'idade': 25}
print(dados)
print(dados['nome'])
dados['sexo'] = 'M'
del dados['idade']
print(dados)
filmes = {
'titulo': 'Star Wars',
'ano': 1977,
'diretor': 'George Lucas'
}
print(filmes.values()) # só os valores
print(filmes.keys()) # só as chaves
print(filmes.items()) # tanto as chaves quanto os valores
# com um for de exemplo:
for key, value in filmes.items():
print(f'O {key} é {value}')
locadora = list()
locadora.append(filmes)
print(locadora)
# atualiza o dicionário atual com outro
dados.update(filmes)
print(dados)
| false |
ae820b193c160d4c3bb40229cf162b2096126c6c | jrfaber90/Prime | /generate.py | 1,113 | 4.15625 | 4 | # !/usr/bin/python
from primepackage.primemodule import *
from primepackage.primeio import *
"""A Python module generating a list of prime numbers and output them into a csv file
"""
def main():
"""Generate 100 prime numbers and output it into output.csv file
variable primes calls getNPrime(100) to generate a list of prime numbers to 100
write_primes() is called using parameters (primes(list), 'output.csv')
variable l created and calls function read_primes() using 'output.csv'
to retrieve list of prime numbers that was created
print() function called with l(list) as the argument and prints all the values of list l
"""
# call method getNPrime to retrieve prime numbers up to 100
primes = getNPrime(100)
# call the write_primes method using primes list from above and write it to a csvfile
write_primes(primes, 'output.csv')
# variable l is given the list of prime numbers from csvfile written by write_primes
l = read_primes('output.csv')
# print values of list l
print(l)
if __name__ == '__main__':
main()
| true |
98ffb29a1385dead0827c3556f01f59e245da8ec | catstacks/DFESW3 | /functions.py | 2,372 | 4.34375 | 4 | # Create a program that works out a grade based on marks with the use of functions.
# The program should take the students name, homework score (/25), assessment score (/50) and final exam score (/100) as inputs, and output their name and final ICT grade as a percentage. See below:
# name = str(input("Please enter your full name: "))
# homework_score = int(input("Input your homework score( /25): "))
# assessment_score = int(input("Input your assessment score( /50): "))
# final_exam_score = int(input("Input your final exam score( /100): "))
# Reminder: any inputs and prints should not be included inside the function definition, and should strictly be done outside.
# def final_score(score1, score2, score3):
# total = round((((score1 + score2 + score3)/175)*100),2)
# return total
# final_score_percentage = final_score(homework_score, assessment_score, final_exam_score)
# print(f"{name} has a final ICT grade percentage score of {final_score_percentage}%")
# Stretch goal: Include grade boundaries such that the program also outputs a grade for the student (A, B, etc.)
def final_score(score1, score2, score3):
total = round((((score1 + score2 + score3)/175)*100),2)
return total
name = str(input("Please enter your full name: "))
homework_score = 26
assessment_score = 51
final_exam_score = 101
while homework_score > 25:
print("Please enter a valid score between 0 and 25")
homework_score = int(input("Input your homework score( /25): "))
while assessment_score > 50:
print("Please enter a valid score between 0 and 50")
assessment_score = int(input("Input your assessment score( /50): "))
while final_exam_score > 100:
print("Please enter a valid score between 0 and 100")
final_exam_score = int(input("Input your final exam score( /100): "))
final_score_percentage = final_score(homework_score, assessment_score, final_exam_score)
if 85 < final_score_percentage <= 100:
grade = "A"
elif 70 < final_score_percentage <= 85:
grade = "B"
elif 55 < final_score_percentage <= 70:
grade = "C"
elif 40 < final_score_percentage <= 55:
grade = "D"
elif 30 < final_score_percentage <= 40:
grade = "E"
elif 20 < final_score_percentage <= 30:
grade = "F"
else:
grade = "Fail"
print(f"{name} has a final score of {final_score_percentage}% and has obtained a final grade {grade} in ICT") | true |
76c61799b95031e11f8877dad72bba772d508a5c | AshishRMenon/CV-Project-2019 | /bin/gui/messagebox.py | 309 | 4.1875 | 4 | from tkinter import *
import tkinter.messagebox
root = Tk()
tkinter.messagebox.showinfo('Window Title',"do you want to save it!")
answer = tkinter.messagebox.askquestion("Question 1","do you like it?")
if answer == 'yes':
print("so you like it!")
else:
print("so you don't like it!")
root.mainloop() | true |
b36c1caa002e1541f34c2c543566a92969aa0837 | CableX88/Projects | /Python projects/forSquares.py | 603 | 4.125 | 4 | # This program allows the user to enter start and end range
#Program List nums and its squares
start = int(input("Enter start number: "))
end = int(input("Enter end number: "))
print("Number\t Square")
print("_______________")
for num in range(start,end):
square = num**2
print(num,'\t',square)
##=============== RESTART: H:/python projects CS10/forSquares.py ===============
##Enter start number: 10
##Enter end number: 21
##Number Square
##_____________________
##10 100
##11 121
##12 144
##13 169
##14 196
##15 225
##16 256
##17 289
##18 324
##19 361
##20 400
##>>>
| true |
932405d48032f74c5eb01e6fadcbdee98dbb0663 | CableX88/Projects | /Python projects/HW 5.py | 2,988 | 4.4375 | 4 | #David Brown
#ID: 837183
#This program calculates the costs of loans
class Loan:
def __init__(self, rate = 2.5, years = 1, loan = 1000, borrower = " "):
self.__rate = rate #the interest rate for your loan
self.__years = years # the years you have to pay for
self.__loan = loan # your loan
self.__borrower = borrower # I.E you
def getRate(self): ## Annual Interest Rate
return self.__rate
def getYears(self): ## Number of Years loan is for
return self.__years
def getLoan(self): ## Ammount of the Loan
return self.__loan
def getBorrower(self): ## Name of the Borrower meaning you
return self.__borrower
def setRate(self, rate):
self.__rate = rate
def setYears(self, years):
self.__years = years
def setLoan(self, loan):
self.__loan = loan
def setBorrower(self, borrower):
self.__borrower = borrower
def getMonthlyPayment(self):
MonthlyIntrestRate = self.__rate / 1200 ## the Monthly Interest Rate for the loan
monthlyPayment = (self.__loan * MonthlyIntrestRate) / (1 - (1 / (1 + MonthlyIntrestRate) ** (self.__years * 12)))
return monthlyPayment
def getTotalPayment(self):
totalPayment = self.getMonthlyPayment() * self.__years * 12
return totalPayment
def main():
loan = Loan()
loan.setRate(float(input("Enter yearly interest rate, for example, 7.25: ")))
loan.setYears(float(input("Enter number of years as an integer: ")))
loan.setLoan(float(input("Enter a loan amount, for example, 120000.95: ")))
loan.setBorrower(input("Enter a borrower's name: "))
print("The loan is for", loan.getBorrower())
print("The monthly payment is",format(loan.getMonthlyPayment(),'.2f'))
print("The total payment is",format(loan.getTotalPayment(),'.2f'))
print()
print()
changeL=input("Do you want to change the loan ammount? Y for yes, enter to quit: ")
while changeL.upper() == "Y":
loan.setLoan(float(input("Enter new loan amount: ")))
print("The loan is for", loan.getBorrower())
print("The monthly payment is",format(loan.getMonthlyPayment(),'.2f'))
print("The total payment is",format(loan.getTotalPayment(),'.2f'))
changeL=input("Do you want to change the loan ammount? Y for yes, enter to quit: ")
main()
##================== RESTART: D:\python projects CS10\HW 5.py ==================
##Enter yearly interest rate, for example, 7.25: 2.5
##Enter number of years as an integer: 5
##Enter a loan amount, for example, 120000.95: 1000.00
##Enter a borrower's name: David Brown
##The loan is for David Brown
##The monthly payment is 17.75
##The total payment is 1064.84
##
##
##Do you want to change the loan ammount? Y for yes, enter to quit: Y
##Enter new loan amount: 5000
##The loan is for David Brown
##The monthly payment is 88.74
##The total payment is 5324.21
##Do you want to change the loan ammount? Y for yes, enter to quit:
| true |
b22c1b5e41321b73dcb4141d0b57b30898835138 | thanhkma1996/python-apication | /Basic/main.py | 698 | 4.3125 | 4 | print("This line will be printed.")
#syntax python
if 5 > 2:
print("test python list project")
#variable
x = "thanh"
y = 5
print(x)
print(y)
print(type(y))
#data type of variable
test1 = str('xin chao viet nam')
test2 = int(3)
test3 = float(3)
print(test1)
print(test2)
print(test3)
#example variable name
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
print(myvar)
print(my_var)
print(_my_var)
print(myVar)
print(MYVAR)
print(myvar2)
#Many Values to Multiple Variables
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
#Unpack a Collection
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z) | false |
93e27d884f148db46c066f752722a9cc1894241c | yichuanma95/leetcode-solns | /python3/maxDepthNTree.py | 999 | 4.125 | 4 | '''
Problem 559: Maximum Depth of N-ary Tree
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to
the farthest leaf node.
For example, given a 3-ary tree:
1
|-3
| |-5
| |-6
|-2
|-4
* my best recreation of an N-ary tree with ASCII in a Python comment
We should return its max depth, which is 3.
Note:
1. The depth of the tree is at most 1000.
2. The total number of nodes is at most 5000.
'''
"""
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> int:
return self.postOrder(root)
def postOrder(self, node: 'Node') -> int:
if node is None:
return 0
if len(node.children) == 0:
return 1
depths: List[int] = [self.postOrder(child) for child in node.children]
return max(depths) + 1
| true |
c71f366183f0242ebf46f067ead100786877602e | yichuanma95/leetcode-solns | /python3/employeeImportance.py | 1,964 | 4.1875 | 4 | '''
Problem 690: Employee Importance
You are given a data structure of employee information, which includes the employee's unique
id, their importance value and their direct subordinates' id.
For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee
3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure
like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note
that although employee 3 is also a subordinate of employee 1, the relationship is not direct.
Now given the employee information of a company, and an employee id, you need to return the
total importance value of this employee and all their subordinates.
Example 1:
Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
Output: 11
Explanation:
Employee 1 has importance value 5, and he has two direct subordinates: employee 2 and employee
3. They both have importance value 3. So the total importance value of employee 1 is 5 + 3 + 3 = 11.
Notes:
1. One employee has at most one direct leader and may have several subordinates.
2. The maximum number of employees won't exceed 2000.
'''
"""
# Definition for Employee.
class Employee:
def __init__(self, id: int, importance: int, subordinates: List[int]):
self.id = id
self.importance = importance
self.subordinates = subordinates
"""
class Solution:
def getImportance(self, employees: List['Employee'], id: int) -> int:
employee_map = {}
for employee in employees:
employee_map[employee.id] = employee
subject = employee_map[id]
return self.traverse_for_importance(employee_map, subject)
def traverse_for_importance(self, employee_map, subject):
return sum(
map(
lambda x: self.traverse_for_importance(employee_map, employee_map[x]),
subject.subordinates
)
) + subject.importance
| true |
fe2202c1febc99f88a854880575b070deee996c7 | yaminirathod/WEEK1_Assignment | /Assignment_Question3_Method1.py | 467 | 4.4375 | 4 | # 3.Write a Python program to display the current date and time.
# Developed by : Yamini Rathod C0796390
# Date : 16-05-2021
import datetime
print('The program to display the current date and time. Prepared by : Yamini Rathod C0796390')
currenttime = datetime.datetime.now()
#currentday = datetime.datetime.day()
#currentyear = datetime.date.today().year
print('Current Date & Time : {}'.format(currenttime.strftime("%Y/%m/%d %H:%M:%S")))
#print(currentday)
#print(currentyear) | true |
e3b970c21f73c854badfc06eb624c374dc019bac | jpchato/data-structures-and-algorithms-python | /challenges/ll_merge/ll_merge.py | 892 | 4.21875 | 4 | def mergeLists(self, other_list):
list1_curr = self.head
list2_curr = other_list.head
# This line of code checks to ensure that there are available positions in curr
while list1_curr != None and list2_curr != None
# Save next pointers
# Creating new variables which save next pointers
list1_next = list1_curr.next
list2_next = list2_curr.next
# Makes list2_curr as next of list1_curr
list2_curr.next = list1_next # changes the next pointer of list2_curr
list1_curr.next = list2_curr # changes the next pointer of list1_curr
# update current pointers for current iteration
# In my own words, I think these lines below are resetting the values to their original values so we can loop again in the while
list1_curr = list1_next
list2_curr = list2_next
other_list.head = list2_curr
| true |
edf23eb42d256e999a6d278aa0200dd40f240ce9 | jpchato/data-structures-and-algorithms-python | /challenges/merge_sort/merge_sort.py | 2,423 | 4.40625 | 4 | # reference https://www.geeksforgeeks.org/merge-sort/
# reference https://www.pythoncentral.io/merge-sort-implementation-guide/
def merge_sort(arr):
# If the length of the array is greater than 1, execute the code below
if len(arr) > 1:
# Finds the middle of the array using floor division(decimals removed)
mid = len(arr)//2
# Holds the values for the left half of the array
l = arr[:mid]
# Holds the values for the right half of the array
r = arr[mid:]
# recursively sorts the left half
merge_sort(l)
# recursively sorts the right half
merge_sort(r)
# iteration values are all set to zero
# same as writing 3 lines of code and setting each value to 0
i = j = k = 0
# While i and j are less than the length of their respective halves, execute the code below
while i < len(l) and j < len(r):
# if the value of the left half is less than the value of the right half, execute the code below
if l[i] < r[j]:
# The value in the array is set to the value at l[i]
arr[k] = l[i]
# iterate i once
i += 1
# If the above if statement is not true, that is the value at r[j] is not greater than the value at l[i], execute the code below
else:
# The value in the array is set to the value at r[j]
arr[k] = r[j]
# iterate j once
j += 1
# iterate k once, this helps us break out of our while loop
k += 1
# Rest of the code checks to see if any element was left
# While the length of the left is greater than i, execute code below
while i < len(l):
# Sets the value of arr[k] to the value of l[i]
arr[k] = l[i]
# iterates i by 1
i += 1
# iterates k by 1
k += 1
# While the length of the right is greater than j, execute the code below
while j < len(r):
# set the value of arr[k] to the value of r[j]
arr[k] = r[j]
# iterate j by 1
j += 1
# iterate k by 1
k += 1
# return the arr, important for testing
return arr
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print(merge_sort(arr))
| true |
8f0b8e7e12ce9ee412fb0ab3fc2a4c2d511abd5d | manutaberner/fer-homework-py | /sesion1.py | 1,707 | 4.1875 | 4 |
#Este ejemplo es importando datetime que lo valida por nosotros FACIL!
"""import datetime
inputDate = input("Introduzca la fecha de la siguiente manera 'dd/mm/yy' : ")
dia,mes,ano = inputDate.split('/')#separa el dia el mes y la fecha
esFechaValida = True
try :
datetime.datetime(int(ano),int(mes),int(dia))
except ValueError :
esFechaValida = False
if(esFechaValida) :
print ("La fecha es valida")
else :
print ("La fecha NO es valida")
"""
##############################################################################
#ESTE TE GESTIONA LOS ERRORES y puede poner el rango
def fechaValida(fecha):
from datetime import datetime, date
date_input = fecha
try:
#convierte la fecha intrducida a formate date
valid_date = datetime.strptime(date_input, '%d/%m/%Y').date()
#aqui decides el rango de fechas en el que queires comprobar
if not (date(2000, 1, 1) <= valid_date <= date(2100, 12, 31)):
errcod = 1
else:
errcod = 0
except ValueError:
errcod = 2
return errcod
##################################################################################
#Programa que valida los DNI o NIF extranjeros
def validoDNI(dni):
tabla = "TRWAGMYFPDXBNJZSQVHLCKE"
dig_ext = "XYZ"
reemp_dig_ext = {'X':'0', 'Y':'1', 'Z':'2'}
numeros = "1234567890"
dni = dni.upper()
if len(dni) == 9:
dig_control = dni[8]
dni = dni[:8]
if dni[0] in dig_ext:
dni = dni.replace(dni[0], reemp_dig_ext[dni[0]])
return len(dni) == len([n for n in dni if n in numeros]) \
and tabla[int(dni)%23] == dig_control
return False | false |
b21531b2085f41323820c20f2342f92eb44a3b1d | zoearon/calculator-2 | /calculator.py | 1,690 | 4.4375 | 4 | """A prefix-notation calculator.
Using the arithmetic.py file from Calculator Part 1, create the
calculator program yourself in this file.
"""
from arithmetic import *
def find_opp(opp):
if opp == "+":
return add
elif opp == "-":
return subtract
elif opp == "*":
return multiply
elif opp == "/":
return divide
elif opp == "square":
return square
elif opp == "cube":
return cube
elif opp == "pow":
return power
elif opp == "mod":
return mod
def calc(opperator, numbers):
"""runs a arthemtic opperation on list of numbers (of any size)"""
if find_opp(opperator) is None:
return "Not a valid operator"
else:
return reduce(find_opp(opperator), numbers)
#def calc_2(par):
# """runs arthemtic opperation when only one number"""
#
# return find_opp(par[0])(int(par[1]))
def flo_inputs(num_list):
""" chaneges a list in to a list of floats"""
flo_list = []
for i in num_list:
flo_list.append(float(i))
return flo_list
# except ValueError:
# print "Only numbers after operator accepted"
while True:
input_string = raw_input(">")
t_input = input_string.split(" ")
if t_input[0] == "q":
print "You are now exiting!"
break
else:
opp = t_input[0]
try:
num_list = flo_inputs(t_input[1:])
except ValueError:
print "only numbers after operator accepted"
continue
print calc(opp, num_list)
#if len(t_input) < 3:
# print calc_2(t_input)
#else:
# print calc_3(t_input)
# Your code goes here
| true |
79104e1e20862bda459ffcb288b9ea8a491172e6 | meghana0910/PythonAssignments | /A2-answer5,6.py | 484 | 4.21875 | 4 | """Answer5"""
a = 14
b = 10
if a>b :
print("A is larger")
elif a<b :
print("B is larger")
else:
print("Both are equal")
"""Answer6-A2"""
a = 6
b = 5
if a % 4 == 0 and a % 3 == 0 and b % 4 == 0 and b % 3 == 0 :
print ("Both are divisible by 4 and 3")
elif a % 4 == 0 or a % 3 ==0:
print("A is divisible by 4 or 3")
elif b % 4 == 0 or b % 3 ==0:
print("B is divisible by 4 or 3")
else:
print("None of them are divisible by 4 or 3")
| false |
a12c32c5c94ce9178a1265ecbf08fda3e98e8799 | rojaboina/Python | /python_basics/Trouble.py | 229 | 4.1875 | 4 | def city_country(city,country):
i=1
while i<=3:
i=i+1
city=input("please enter your city name")
country=input("please enter your country name")
print(f"{city},{country} are amazing")
city_country('city','country')
| true |
9b5c0cf38475483e2a76698f675e2192cbf751b9 | jps27CSE/Python-Programming | /Decimal to Binary.py | 286 | 4.1875 | 4 | def dec_to_binary(n):
bits = []
while n > 0:
bits.append(n%2)
n = n // 2
bits.reverse()
binary = ''
for bit in bits:
binary += str(bit)
return binary
num = int(input("Your decimal number: "))
binary = dec_to_binary(num)
print("Your binary is:", binary) | false |
10abc4dcb99706de8ba7c0f5bf2e256c7570289e | gaiagirl007/char_sheet | /my_dice.py | 1,232 | 4.34375 | 4 | """This 'rolls' dice."""
import random
def roll(num, max):
"""Generates a random number between 1 and max, num times.
Adds and returns the results
num: int > 0
max: int > 1"""
assert type(num) == int and num > 0
assert type(max) == int and max > 1
total = 0
for i in range(num):
total += random.randint(1, max)
return total
def roll_dice(num_dice, max_value):
"""Prints the results of 'roll' function
num_dice: int > 0
max_value: int > 1"""
assert type(num_dice) == int and num_dice > 0
assert type(max_value) == int and max_value > 1
print(num_dice, "d", max_value, " = ", roll(num_dice, max_value))
def roll_stats():
"""Uses the 'roll' function to roll 1d6 4 times, dropping the lowest
value. Prints the sum of the remaining 3. Completes 6 times."""
stats = []
for i in range(6):
single = []
for j in range(4):
single.append(roll(1, 6))
single.sort()
best_total = 0
for k in range(1, 4):
best_total += single[k]
stats.append(best_total)
return stats
def character():
print(str(roll_stats()))
| true |
ae51aea0b4f2f332e051fe548f4f397570c9ce52 | ehsanmpd/Python_samples | /Training/Q21/Q21.py | 922 | 4.1875 | 4 | class Point:
def __init__(self,x_init,y_init):
self.x = x_init
self.y = y_init
def move(self,direction,step):
if direction=="UP":
self.y += step
elif direction == "DOWN":
self.y -= step
elif direction == "LEFT":
self.x -= step
elif direction == "RIGHT":
self.x += step
def distance(self,nextPoint):
return sqrt(pow(self.x-nextPoint.x,2)+pow(self.y - nextPoint.y,2))
def current_position(self):
return [self.x,self.y]
from math import sqrt
p = Point(0,0)
while True:
line = input("Type direction step (to terminate type 0):")
if line != '0':
dirStep = line.split(' ')
if len(dirStep)==2:
p.move(dirStep[0],int(dirStep[1]))
print("Current position: ",p.current_position())
else:
break
print("Distance: ",round(p.distance(Point(0,0)))) | false |
c3bb1172b9ac1d6ce80c5082aba7634f267ff71f | muskansharma2000/DataScience | /Algorithms/Search/BinarySearch/binary_search.py | 729 | 4.21875 | 4 | def binary_search_recursive(a, left, right, e):
if left <= right:
middle = left + int((right - left) / 2)
if a[middle] == e:
return middle
elif a[middle] < e:
return binary_search_recursive(a, middle + 1, right, e)
else:
return binary_search_recursive(a, left, middle - 1, e)
def binary_search(a, left, right, e):
while left <= right:
middle = left + int((right - left) / 2)
if a[middle] == e:
return middle
elif a[middle] < e:
left = middle + 1
else:
right = middle - 1
# Example:
array = [1, 2, 3, 4, 5, 6, 7, 8]
position = binary_search_recursive(array, 0, 7, 2)
print(position) | false |
30a0626f0018e445b54a08dd49136be59dfebad5 | SatyamAS/venom | /SL_LAB/QA2.py | 532 | 4.25 | 4 | ##2. Write a python program to count the frequency of words in a given file.
file = open("QA2.txt")
worddic = { }
for line in file:
myline = line.split()
for word in myline:
w = worddic.get(word,0)
worddic[word] = w + 1
print (worddic ,"\n ")
##OR
##from collections import Counter
##def word_count(fname):
## with open(fname) as f:
## return Counter(f.read().split())
##
##print("Number of words in the file :",word_count("QA2.txt"))
| true |
3e2e1985cb59016d7d9abd1bf413d6104a9c1292 | SatyamAS/venom | /SL_LAB/QB4.py | 827 | 4.25 | 4 | ##4. Load the Titanic dataset into one of the data structures (NumPy or Pandas).
##Display header rows and description of the loaded dataset.
##Remove unnecessary features (E.g. drop unwanted columns) from the dataset.
##Manipulate data by replacing empty column values with a default value.
##Pandas for structured data operations and manipulations.
import pandas as pd
from pandas import Series, DataFrame
import matplotlib.pyplot as plt
titanic_df = pd.read_csv("titanic.csv")
print("======DATA HEADERS======")
print(titanic_df.head())
print("======DATA INFO=====")
titanic_df.info()
print("======DATA DESCRIPTION=====")
print(titanic_df.describe())
#replacing empty column values with default value Q
titanic_df["Embarked"] = titanic_df["Embarked"].fillna("Q")
print(titanic_df["Embarked"])
| true |
a2ef88cea9f11193584a02e691aa1e8d8d7edd7a | yanglei-xyz/eat_python_in_30_days | /day_01/11_dict.py | 512 | 4.34375 | 4 | # dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print(d['Bob'])
d['Adam'] = 67
print(d)
# 判断某个元素是否存在
print('Thomas' in d) # false
# 通过dict提供的get()方法,如果key不存在,可以返回None,或者自己指定的value:
print(d.get('Thomas')) # None
print(d.get('Thomas', -1)) # -1
# 删除一个key,用pop(key)方法
print(d.pop('Bob'))
print(d)
| false |
873613eb3d8b5a2b31ca221294674eb036711250 | zhoupengzu/PythonPractice | /Practice/practice3.py | 508 | 4.25 | 4 | # 序列解包与链式赋值
'''
str,tuple,list,set,dict都可以做序列解包和赋值,但是需要注意:
1、dict得到的是其key
2、两边的个数需要相同
'''
a = 1, 2, 3
print(type(a)) #<class 'tuple'>
print(a) #(1, 2, 3)
# a, b = 1, 2, 3 #这样是不行的
# a, b, c = 1, 2 #这样也是不行的
a, b, c = (1,2,3)
print(a,b,c)
a, b, c = [1,2,3]
print(a,b,c)
a,b,c = 'abc'
print(a, b, c)
a,b,c = {1,2,3}
print(a,b,c)
a,b,c = {'1':1,'2':'2','3':'c'}
print(a, b, c) # 1 2 3
| false |
a2e667235a5e2f5dbe17bf49e7e5e41328e97137 | han8909227/leetcode | /tree/path_sum_lc112.py | 1,088 | 4.25 | 4 |
# Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
# For example:
# Given the below binary tree and sum = 22,
# 5
# / \
# 4 8
# / / \
# 11 13 4
# / \ \
# 7 2 1
# return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
class Node(object):
"""Simple node class."""
def __init__(self, val):
"""."""
self.val = val
self.left = None
self.right = None
def path_sum(node, target):
"""LC 112."""
if not node:
return False
if not node.left and not node.right:
return node.val == target
return path_sum(node.left, target - node.val) or path_sum(node.right, target - node.val)
if __name__ == "__main__":
head = Node(20)
head.left = Node(10)
head.left.left = Node(5)
head.left.right = Node(15)
head.right = Node(30)
head.right.left = Node(25)
head.right.right = Node(35)
| true |
958d7889c39d995c6ddf5760409a234761f5f232 | han8909227/leetcode | /linked_list/intersection_two_ll_lc160.py | 2,111 | 4.1875 | 4 | # Write a program to find the node at which the intersection of two singly linked lists begins.
# For example, the following two linked lists:
# A: a1 → a2
# ↘
# c1 → c2 → c3
# ↗
# B: b1 → b2 → b3
# begin to intersect at node c1.
# Notes:
# If the two linked lists have no intersection at all, return null.
# The linked lists must retain their original structure after the function returns.
# You may assume there are no cycles anywhere in the entire linked structure.
# Your code should preferably run in O(n) time and use only O(1) memory.
class LinkedList(object):
"""Simple linked list class."""
def __init__(self, val):
"""."""
self.next = None
self.val = val
def intersection_finder(l1, l2):
"""Find intersecting node between two linked lists."""
l1_count, l2_count = 0, 0
temp_l1, temp_l2 = l1, l2
while temp_l1: # get len of l1
temp_l1 = temp_l1.next
l1_count += 1
while temp_l2: # get len of l2
temp_l2 = temp_l2.next
l2_count += 1
long_ll = l1 if l1_count > l2_count else l2 # determine the longer ll
short_ll = l2 if l2_count > l1_count else l1 # determine the shorter ll
short_count = l1_count if l1_count < l2_count else l2_count
diff = abs(l1_count - l2_count) # diff between the lens
for _ in range(diff): # cut off long ll head to make it as long as short ll
long_ll = long_ll.next
for _ in range(short_count): # loop through both ll together
if long_ll.next is short_ll.next: # if they share same node will reflect here
return long_ll.next.val
else: # keep iterating
long_ll = long_ll.next
short_ll = short_ll.next
return -1
if __name__ == '__main__':
l1 = LinkedList(1)
l1.next = LinkedList(2)
l1.next.next = LinkedList(3)
l2 = LinkedList(5)
l2.next = LinkedList(4)
l2.next.next = l1.next.next
print('the intersecting node between l1 and l2 is ' + str(intersection_finder(l1, l2)))
| true |
1937b55cf07d80ca4289babb1eb9ee7092a5ea40 | han8909227/leetcode | /tree/sibliing_pointer_ii_lc117.py | 2,563 | 4.28125 | 4 | # Follow up for problem "Populating Next Right Pointers in Each Node".
# What if the given tree could be any binary tree? Would your previous solution still work?
# Note:
# You may only use constant extra space.
# For example,
# Given the following binary tree,
# 1
# / \
# 2 3
# / \ \
# 4 5 7
# After calling your function, the tree should look like:
# 1 -> NULL
# / \
# 2 -> 3 -> NULL
# / \ \
# 4-> 5 -> 7 -> NULL
class Node(object):
"""Simple node class."""
def __init__(self, data):
"""."""
self.data = data
self.left = None
self.right = None
def connect2(node):
"""LC 117."""
while node:
curr = node
while curr:
if curr.left and curr.right: # with both children
curr.left.next = curr.right
if curr.next:
if curr.left and not curr.right: # curr single child left
if curr.next.left: # next single child left
curr.left.next = curr.next.left
elif curr.next.right: # next single child right
curr.left.next = curr.next.right
elif curr.right and not curr.left: # curr single child right
if curr.next.left:
curr.right.next = curr.next.left
elif curr.next.right:
curr.right.next = curr.next.right
curr = curr.next # loop across
if node.right and not node.left: # single child right
node = node.right
else: # single child left or both or none(all fine)
node = node.left
# a more elagent solution..
def second_connect2(root):
"""LC 117."""
head = None
pre = None
curr = root
while curr:
while curr:
if curr.left:
if pre:
pre.next = curr.left
else:
head = curr.left
pre = curr.left
if curr.right:
if pre:
pre.next = curr.right
else:
head = curr.right
pre = curr.right
curr = curr.next
curr = head
pre = None
head = None
if __name__ == "__main__":
head = Node(20)
head.left = Node(10)
head.left.left = Node(5)
head.left.right = Node(15)
head.right = Node(30)
head.right.left = Node(25)
head.right.right = Node(35)
| true |
1db7b331d60a6872c595d0441cb07cd606284180 | han8909227/leetcode | /stack_and_q/q_with_stacks_lc232.py | 1,638 | 4.5 | 4 | # Implement the following operations of a queue using stacks.
# push(x) -- Push element x to the back of queue.
# pop() -- Removes the element from in front of queue.
# peek() -- Get the front element.
# empty() -- Return whether the queue is empty.
# Notes:
# You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
# Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
# You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
class StackQueue(object):
"""Queue with two stacks."""
def __init__(self, vals=None):
"""."""
self._s1 = []
self._s2 = []
if vals:
for val in vals:
self.push(val)
def push(self, val):
"""Same as enqueue."""
if not self._s2:
self._s2.append(val)
return
for _ in self._s2: # reverse s2 to s1
self._s1.append(self._s2.pop())
self._s1.append(val) # add to end of s1(top of queue)
for _ in self._s1: # flip again to s2, end is deQ val
self._s2.append(self._s1.pop())
def pop(self):
"""Same as dequeue."""
result = self._s2.pop()
return result
def peek(self):
"""Peek next dequeue val."""
return self._s2[-1]
def empty(self):
"""Return whether queue is empty."""
return len(self._s2)
| true |
3b2575fcfca6f487c6125159cce920fc84bc8b21 | Chiki1601/Insertion-sort-visualisation | /insertion.py | 1,953 | 4.3125 | 4 | Program:
# Insertion Sort Visualization using Matplotlib in Python
# import all the modules
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib as mp
import numpy as np
import random
# set the style of the graph
plt.style.use('fivethirtyeight')
# input the size of the array (list here)
# and shuffle the elements to create
# a random list
n = int(input("enter array size\n"))
a = [i for i in range(1, n+1)]
random.shuffle(a)
# insertion sort
def insertionsort(a):
for j in range(1, len(a)):
key = a[j]
i = j-1
while(i >= 0 and a[i] > key):
a[i+1] = a[i]
i -= 1
# yield the current position
# of elements in a
yield a
a[i+1] = key
yield a
# generator object returned by the function
generator = insertionsort(a)
# to set the colors of the bars.
data_normalizer = mp.colors.Normalize()
color_map = mp.colors.LinearSegmentedColormap(
"my_map",
{
"red": [(0, 1.0, 1.0),
(1.0, .5, .5)],
"green": [(0, 0.5, 0.5),
(1.0, 0, 0)],
"blue": [(0, 0.50, 0.5),
(1.0, 0, 0)]
}
)
fig, ax = plt.subplots()
# the bar container
rects = ax.bar(range(len(a)), a, align="edge",
color=color_map(data_normalizer(range(n))))
# setting the view limit of x and y axes
ax.set_xlim(0, len(a))
ax.set_ylim(0, int(1.1*len(a)))
# the text to be shown on the upper left
# indicating the number of iterations
# transform indicates the position with
# relevance to the axes coordinates.
text = ax.text(0.01, 0.95, "", transform=ax.transAxes)
iteration = [0]
# function to be called repeatedly to animate
def animate(A, rects, iteration):
# setting the size of each bar equal
# to the value of the elements
for rect, val in zip(rects, A):
rect.set_height(val)
iteration[0] += 1
text.set_text("iterations : {}".format(iteration[0]))
anim = FuncAnimation(fig, func=animate,
fargs=(rects, iteration), frames=generator, interval=50,
repeat=False)
plt.show()
| true |
92e730a36142ca0e7aee4ae2084e75be488832e4 | mrityunjaykumar911/DSA | /Hackerrank/Data Structures/Arrays/Arrays - DS.py | 1,171 | 4.1875 | 4 | # coding=utf-8
"""
Created by mrityunjayk on 3/10/16.
Website: https://www.hackerrank.com/challenges/arrays-ds
-----------------------------------------------------------------
Problem Statement:
An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, , of size , each memory location has some unique index, (where ), that can be referenced as (you may also see it written as ). Given an array, , of integers, print each element in reverse order as a single line of space-separated integers.
Example:
Sample Input 4 1 4 3 2 Sample Output 2 3 4 1
-----------------------------------------------------------------
Category: Arrays
"""
# Hackerrank
class Solution:
def __init__(self):
self.class_name = "Arrays - DS"
def __str__(self):
return self.class_name
def findSolution(self):
# TODO adding raw input source
n = int(raw_input().strip())
arr = raw_input().strip().split()
arr.reverse()
return ' '.join(arr)
s = Solution()
print s.findSolution() | true |
de11db01eab089669ea8524708b232bc843b0663 | Rayxclockwork/python-data-structures-and-algorithms | /challenges/ll_merge/ll_merge.py | 1,217 | 4.21875 | 4 | class LinkedList:
def __init__(self):
"""starts empty linked list"""
self.head = None
def insert(self, value):
"""Instantiates new node as head"""
current = self.head
new_node = Node(value, current)
self.head = new_node
def merge_lists(self, linked_list1, linked_list2):
"""zip-merges 2 linked lists together"""
linked_list1_current = self.head
linked_list2_current = linked_list2.head
while linked_list1_current != None and linked_list2_current != None:
linked_list1_next = linked_list1_current.next
linked_list2_next = linked_list2_current.next
linked_list2_current.next = linked_list1_next
linked_list1_current.next = linked_list2_current
linked_list1_next = linked_list1_current
linked_list2_next = linked_list2_current
linked_list2_current = linked_list2.head
return self
linked_list1 = LinkedList()
linked_list1.insert(1)
linked_list1.insert(12)
linked_list1.insert(3)
linked_list1.insert(5)
linked_list1.insert(7)
linked_list1.insert(11)
linked_list1.insert(51)
linked_list2 = LinkedList()
linked_list2.insert(18)
linked_list2.insert(4)
linked_list2.insert(9)
linked_list2.insert(2)
linked_list2.insert(6)
linked_list2.insert(13)
linked_list2.insert(45) | true |
6ba58d2db274f519893a307bc9194f0ed6c0fc90 | tigranpro7/BEHomeworks | /Lesson4/hw041_normal.py | 445 | 4.125 | 4 | # Задание-1:
# Напишите функцию, возвращающую ряд Фибоначчи с n-элемента до m-элемента.
# Первыми элементами ряда считать цифры 1 1
def fibonacci(n, m):
row_nach = [1, 1]
while len(row_nach) != m:
r = row_nach[-1] + row_nach[-2]
row_nach.append(r)
row_fin = row_nach[n-1:]
return row_fin
print(fibonacci(5, 10))
| false |
48838f6777e4b2479a4d2027fe0205567e9000b9 | tigranpro7/BEHomeworks | /Lesson5-new/easy51.py | 465 | 4.1875 | 4 | # Задание-1:
# Дан список, заполненный произвольными целыми числами.
# Получить новый список, элементы которого будут
# квадратами элементов исходного списка
# [1, 2, 4, 0] --> [1, 4, 16, 0]
import random
old_list = list(random.randint(0,20) for _ in range(10))
new_list = list(el**2 for el in old_list)
print(old_list, '-->', new_list) | false |
5d3ace37037d6aeeac63924ccc3513f8d71f8c66 | bryan-truong99/SASE-Name-Checker | /main.py | 1,470 | 4.40625 | 4 | import csv
import pandas as pd
names = ["francis", "kelynn", ""]
def convert_csv(file):
df = pd.read_csv(file)
name_column = df["Name"]
return name_column
def scan_names(column):
names = ["josh", "raph", "elton", "francis", "kelly l", "kelly c", "kaitlyn", "baron", "michelle", "young", "brandon", "kelynn", "sharon", "hy", "jon", "vivi", "lisa", "reyna", "henry", "prad", "julie", "tanya", "nguyen"]
for name in reversed(names):
for name_resp in column:
if name in name_resp.lower():
names.remove(name)
break
return(names)
if __name__ == "__main__":
name_col = None
print("Hello, welcome to the SASE Name Checker! Use this tool to check if a name is missing from a form.")
birthday = input("Is this for a birthday? [Y/N] ")
if birthday.lower() == "y":
name = input("Who's birthday is it? ")
try:
name_col = convert_csv("C:\\Users\\bryan\\Downloads\\Birthday Card for "+name.capitalize()+" (Responses) - Form Responses 1.csv")
except:
print("Oops, couldn't find that file!")
else:
filepath = input("Enter the file path to the form: ")
try:
name_col = convert_csv(filepath)
except:
print("Oops, couldn't find that file!")
names_list = scan_names(name_col)
print("The following people have not filled out the form yet: ")
print(*names_list, sep = ", ")
| true |
88d556e10605d81ffa31189577b78c064a0849db | slieer/py | /Hands-On-Computational-Thinking-with-Python.-master/ch3_statecapitals4.py | 315 | 4.34375 | 4 | state_capitals = {
"Ohio" : "Columbus",
"Alabama" : "Montgomery",
"Arkansas" : "Little Rock"
}
state_capitals["Iowa"] = "Des Moines"
state = raw_input("What state's capital are you looking for today? ")
capital = state_capitals[state]
print("The capital of " + state + " is " + capital + ".")
| false |
80b1216b3fbf1e12b6268af7cb84704810531aeb | DustinYook/COURSE_COMPUTER-ENGINEERING-INTRODUCTION | /PythonWS/Chapter7/test0705_6.py | 598 | 4.1875 | 4 | # 프로그램 목적: 파이썬 함수의 특징 -> 리턴값이 여러개
# 1) 1개 인자를 받아 2개를 리턴
def prints(param):
result = 10 + param
return result, param # 파이썬에서는 리턴값이 2개일 수 있다
print(prints(1)) # 결과값: (11, 1)
r, arg = prints(2)
print(r, arg) # 결과값: 12 2
# 2) 2개 인자를 받아 2개를 리턴
def prints(param1, param2):
result1 = param1 + param2
result2 = param1 - param2
return result1, result2
print(prints(10, 20)) # 결과값: (30, -10)
r1, r2 = prints(10, 20)
print(r1, r2) # 결과값: 30 -10 | false |
a61fa310a7b45e679d56dce23639373a9ba6981e | bvpcsiofficial/BVPCSI-HACKTOBERFEST | /Python/Dijkstras_algo.py | 1,850 | 4.25 | 4 | """
We can use Dijkstra's two stack algorithm to solve an equation
such as: (5 + ((4 * 2) * (2 + 3)))
"""
import operator as op
class Stack:
def __init__(self, limit=10):
self.stack = []
self.limit = limit
def __bool__(self):
return bool(self.stack)
def __str__(self):
return str(self.stack)
def push(self, data):
if len(self.stack) >= self.limit:
raise IndexError('stack is fully filled')
self.stack.append(data)
def pop(self):
if self.stack:
return self.stack.pop()
else:
raise IndexError("pop from an empty stack")
def peek(self):
if self.stack:
return self.stack[-1]
def is_empty(self):
return not bool(self.stack)
def size(self):
return len(self.stack)
def __contains__(self, item) -> bool:
return item in self.stack
def dijkstras_two_stack_algorithm(equation: str) -> int:
operators = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub}
operand_stack = Stack()
operator_stack = Stack()
for i in equation:
if i.isdigit():
# RULE 1
operand_stack.push(int(i))
elif i in operators:
# RULE 2
operator_stack.push(i)
elif i == ")":
# RULE 4
opr = operator_stack.peek()
operator_stack.pop()
num1 = operand_stack.peek()
operand_stack.pop()
num2 = operand_stack.peek()
operand_stack.pop()
total = operators[opr](num2, num1)
operand_stack.push(total)
# RULE 5
return operand_stack.peek()
if __name__ == "__main__":
equation = "(5 + ((4 * 2) * (2 + 3)))"
# answer = 45
print(f"{equation} = {dijkstras_two_stack_algorithm(equation)}")
| false |
ec27f69bbe0176ab257cdd22750502914052a912 | CeballosAndres/python-course | /Unidad 1/ejercicio1.6.py | 1,544 | 4.21875 | 4 | # Programa que lee un código postal desde teclado, lo busca dentro
# de un archivo json y en caso de encontrarse el código imprime
# el estado y municipio al que pertenece el código. En caso de que no
# se encuentre imprime: "Código Postal NO encontrado".
#
# Tecnológico Nacional de México Campus Colima
# Ingeniería en Sistemas Computacionales
# Lenguaje de programación Python
#
# José Andrés Ceballos Vadillo
# 17460386
# Importar libreria para trabajar con json
import json
# Método para solicitar código postal y validar formato
def get_postal_code():
while True:
code = input("Ingrese el código postal a buscar: ")
if len(code) == 5:
try:
int(code)
break
except:
print("Debe ingresar solo números!")
else:
print("El código postal se debe componer de 5 dígitos")
return code
# Método para abrir json e iterar sus elementos en busqueda de código postal
def find_postal_code(code, json_file):
with open(json_file, encoding="utf8") as file:
data = json.load(file)
for elem in data['data']:
if code == elem['d_codigo']:
return elem
return False
if __name__ == "__main__":
postal_code = get_postal_code()
response = find_postal_code(postal_code, 'codigos_postales.json')
if response == False:
print("\nCódigo Postal NO encontrado")
else:
print(f"El código pertenece a... \nEstado: {response['d_estado']}\nEstado: {response['d_nmpio']} ") | false |
63a339a1ebdc06649e169f333cb7d72686df311e | gojo5t5/elements-of-ai-building-ai | /BuildingAI/8_fishing_in_the_nordics.py | 1,360 | 4.1875 | 4 | # using bayes theorem and knowledge of conditional probabilities to solve probability problems
countries = ['Denmark', 'Finland', 'Iceland', 'Norway', 'Sweden']
populations = [5615000, 5439000, 324000, 5080000, 9609000]
male_fishers = [1822, 2575, 3400, 11291, 1731]
female_fishers = [69, 77, 400, 320, 26]
total_male_fishers = sum(male_fishers)
total_female_fishers = sum(female_fishers)
def guess(winner_gender):
# decide whether we're looking at female fishers or male fishers
if winner_gender == 'female':
fishers = female_fishers
total_fishers = total_female_fishers
else:
fishers = male_fishers
total_fishers = total_male_fishers
guess = None
biggest = 0.0
# loop through all countries and fishers and keep track of the biggest probability
# brute forcing
for country, fishers in zip(countries, fishers):
prob = fishers/total_fishers * 100
if prob > biggest:
guess = country
biggest = prob
return (guess, biggest)
def main():
country, fraction = guess("male")
print("if the winner is male, my guess is he's from %s; probability %.2f%%" % (
country, fraction))
country, fraction = guess("female")
print("if the winner is female, my guess is she's from %s; probability %.2f%%" % (
country, fraction))
main()
| true |
3f2189c4a07e03f7f8bd13f9ff72ab02fe971727 | southpawgeek/perlweeklychallenge-club | /challenge-188/spazm/python/ch-1.py | 1,348 | 4.15625 | 4 | #!/usr/bin/env python
"""
You are given list of integers list of size n and divisor k.
Write a script to find out count of pairs in the given list that satisfies the following rules.
The pair (i, j) is eligible if and only if
a) 0 <= i < j < len(list)
b) list[i] + list[j] is divisible by k
"""
def count_matching_pairs_naive(input, n, k):
count = 0
for i, val_i in enumerate(input):
for val_j in input[i + 1 :]:
if (val_i + val_j) % k == 0:
count += 1
return count
def count_matching_pairs(input, n, k):
mods = [i % k for i in input]
count = 0
for i, mod_i in enumerate(mods):
for mod_k in mods[i + 1 :]:
if mod_i + mod_k == 0 or mod_i + mod_k == k:
count += 1
return count
if __name__ == "__main__":
test_data = [
[[4, 5, 1, 6], 2, 2],
[[1, 2, 3, 4], 2, 2],
[[1, 3, 4, 5], 3, 2],
[[5, 1, 2, 3], 4, 2],
[[7, 2, 4, 5], 4, 1],
]
for input, k, expected in test_data:
print(f"input: {input}, k:{k}, expected:{expected}")
val = count_matching_pairs(input, len(input), k)
assert val == expected, f"{val} == expected {expected}"
val = count_matching_pairs_naive(input, len(input), k)
assert val == expected, f"{val} == expected {expected}"
| false |
26f3150214602744c5ad7f8aec6a44ce0056ef36 | southpawgeek/perlweeklychallenge-club | /challenge-027/paulo-custodio/python/ch-1.py | 705 | 4.15625 | 4 | #!/usr/bin/python3
# Challenge 027
#
# Task #1
# Write a script to find the intersection of two straight lines. The
# co-ordinates of the two lines should be provided as command line parameter.
# For example:
#
# The two ends of Line 1 are represented as co-ordinates (a,b) and (c,d).
#
# The two ends of Line 2 are represented as co-ordinates (p,q) and (r,s).
#
# The script should print the co-ordinates of point of intersection of the
# above two lines.
import sys
x1,y1,x2,y2,x3,y3,x4,y4 = [int(x) for x in sys.argv[1:9]]
D = (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4)
x = ((x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4))/D
y = ((x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4))/D
print("{:.1f} {:.1f}".format(x, y))
| true |
31a5bcde9add1323edd56aaaab7cbe25e41e3e34 | southpawgeek/perlweeklychallenge-club | /challenge-110/paulo-custodio/python/ch-2.py | 858 | 4.3125 | 4 | #!/usr/bin/env python3
# Challenge 110
#
# TASK #2 - Transpose File
# Submitted by: Mohammad S Anwar
# You are given a text file.
#
# Write a script to transpose the contents of the given file.
#
# Input File
# name,age,sex
# Mohammad,45,m
# Joe,20,m
# Julie,35,f
# Cristina,10,f
# Output:
# name,Mohammad,Joe,Julie,Cristina
# age,45,20,35,10
# sex,m,m,f,f
import fileinput
import sys
def read_input():
lines = []
for line in fileinput.input():
lines.append(line)
return lines
def read_data(lines):
m = []
for line in lines:
line = line.strip()
cols = line.split(',')
m.append(cols)
return m
def transpose(m):
t = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]
return t
def print_data(m):
for row in m:
print(",".join(row))
print_data(transpose(read_data(read_input())))
| true |
f951353e5df55a780b2237169b0c9f9186c29eca | southpawgeek/perlweeklychallenge-club | /challenge-161/paulo-custodio/python/ch-1.py | 792 | 4.375 | 4 | #!/usr/bin/env python3
# Challenge 161
#
# Task 1: Abecedarian Words
# Submitted by: Ryan J Thompson
# An abecedarian word is a word whose letters are arranged in alphabetical
# order. For example, "knotty" is an abecedarian word, but "knots" is not.
# Output or return a list of all abecedarian words in the dictionary, sorted
# in decreasing order of length.
#
# Optionally, using only abecedarian words, leave a short comment in your code
# to make your reviewer smile.
import sys
out = set()
with open(sys.argv[1]) as f:
for line in f.readlines():
word = line.rstrip()
if len(word)>=3:
abcd_word = "".join(sorted(word)).lower()
if word==abcd_word:
out.add(word)
for word in sorted(sorted(out), key=len, reverse=True):
print(word)
| true |
030c1519a0c1d3a8f35a5f2ef66a013c57d84c89 | southpawgeek/perlweeklychallenge-club | /challenge-173/mohammad-anwar/python/ch-1.py | 674 | 4.15625 | 4 | #!/usr/bin/python3
'''
Week 173:
https://theweeklychallenge.org/blog/perl-weekly-challenge-173
Task #1: Esthetic Number
You are given a positive integer, $n.
Write a script to find out if the given number is Esthetic Number.
'''
import unittest
def is_esthetic_number(n):
s = str(n)
for i in range(1, len(s)):
if abs(int(s[i-1]) - int(s[i])) != 1:
return False
return True
#
#
# Unit test class
class TestEstheticNumber(unittest.TestCase):
def test_example_1(self):
self.assertTrue(is_esthetic_number(5456))
def test_example_2(self):
self.assertFalse(is_esthetic_number(120))
unittest.main()
| true |
42c60c0d222f3f40092de0a72c4804b2981ba967 | southpawgeek/perlweeklychallenge-club | /challenge-130/paulo-custodio/python/ch-1.py | 669 | 4.3125 | 4 | #!/usr/bin/env python3
# Challenge 130
#
# TASK #1 > Odd Number
# Submitted by: Mohammad S Anwar
# You are given an array of positive integers, such that all the
# numbers appear even number of times except one number.
#
# Write a script to find that integer.
#
# Example 1
# Input: @N = (2, 5, 4, 4, 5, 5, 2)
# Output: 5 as it appears 3 times in the array where as all other
# numbers 2 and 4 appears exactly twice.
# Example 2
# Input: @N = (1, 2, 3, 4, 3, 2, 1, 4, 4)
# Output: 4
import sys
N = sys.argv[1:]
count = {}
for n in N:
if n not in count:
count[n] = 1
else:
count[n] += 1
for n,count in count.items():
if count%2==1:
print(n)
| true |
0beed57c25142010c86bce187f6f1bd5500e0272 | southpawgeek/perlweeklychallenge-club | /challenge-193/robert-dicicco/python/ch-1.py | 843 | 4.15625 | 4 | #!/usr/bin/env python
'''
AUTHOR: Robert DiCicco
DATE: 2022-11-28
Challenge 193 Binary String ( Python )
Write a script to find all possible binary numbers of size $n.
Example 1
Input: $n = 2
Output: 00, 11, 01, 10
Example 2
Input: $n = 3
Output: 000, 001, 010, 100, 111, 110, 101, 011
------------------------------------------------------
SAMPLE OUTPUT
python .\BinaryString.py
Input: $n = 2
Output: 00 01 10 11
Input: $n = 3
Output: 000 001 010 011 100 101 110 111
Input: $n = 4
Output: 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
'''
arr = [2,3,4]
for p in arr:
print("Input: $n = ",p)
rng = range(2**p)
print("Output: ", end=" ")
for n in rng :
pw = "0" + str(p)
print("{:{width}b}".format(n,width=pw), end=" ")
print("\n")
| false |
42c5d098c63d936c874a0675cc8ac29d0a5f8b9a | southpawgeek/perlweeklychallenge-club | /challenge-048/user-person/python/ch-2.py | 1,993 | 4.25 | 4 | #!/usr/bin/env python
###########################################################################
# script name: ch-2.py #
# #
# https://perlweeklychallenge.org/blog/perl-weekly-challenge-048/ #
# #
# Palindrome Dates #
# Write a script to print all Palindrome Dates between 2000 and 2999. #
# The format of date is mmddyyyy. For example, the first one was on #
# October 2, 2001 as it is represented as 10022001. #
# #
###########################################################################
# M M D D Y Y Y Y
# [01][*][012][2][2][012][*][01]
# k j i i j k
#
# k - Months can only begin with 0 or 1.
# j - The second months digit needs all numbers e.g. January 01 to October 10 (and of course beyond).
# i - Days begin with 0,1,2,3, However all years begin with 2 so the corresponding number
# means all days end in 2. 32 is not a valid day so the 3 is not needed.
for i in range(3):
for j in range(10):
for k in range(2):
if (k == 1 and j > 2) or (k == 0 and j == 0):
continue
print(k,j,"-",i,"2-2",i,j,k,sep='')
k += 1
j += 1
i += 1
# output:
#
# 10-02-2001
# 01-02-2010
# 11-02-2011
# 02-02-2020
# 12-02-2021
# 03-02-2030
# 04-02-2040
# 05-02-2050
# 06-02-2060
# 07-02-2070
# 08-02-2080
# 09-02-2090
# 10-12-2101
# 01-12-2110
# 11-12-2111
# 02-12-2120
# 12-12-2121
# 03-12-2130
# 04-12-2140
# 05-12-2150
# 06-12-2160
# 07-12-2170
# 08-12-2180
# 09-12-2190
# 10-22-2201
# 01-22-2210
# 11-22-2211
# 02-22-2220
# 12-22-2221
# 03-22-2230
# 04-22-2240
# 05-22-2250
# 06-22-2260
# 07-22-2270
# 08-22-2280
# 09-22-2290
| false |
4b54d973574fb84eba889258103ccc5a52e3b1bf | southpawgeek/perlweeklychallenge-club | /challenge-135/paulo-custodio/python/ch-2.py | 1,019 | 4.15625 | 4 | #!/usr/bin/env python3
# Challenge 135
#
# TASK #2 > Validate SEDOL
# Submitted by: Mohammad S Anwar
# You are given 7-characters alphanumeric SEDOL.
#
# Write a script to validate the given SEDOL. Print 1 if it is a valid SEDOL
# otherwise 0.
#
# For more information about SEDOL, please checkout the wikipedia page.
#
# Example 1
# Input: $SEDOL = '2936921'
# Output: 1
# Example 2
# Input: $SEDOL = '1234567'
# Output: 0
# Example 3
# Input: $SEDOL = 'B0YBKL9'
# Output: 1
import sys
import re
def check_sedol(sedol):
def compute_check_digit(input_str):
weight = [1, 3, 1, 7, 3, 9]
input = [int(c, 36) for c in input_str]
sum = 0
for i in range(0, 6):
sum += input[i] * weight[i]
return str(10-sum%10)
if not re.match(r"^[0-9BCDFGHJKLMNPQRSTVWXYZ]{6}[0-9]$", sedol):
return 0
input = sedol[0:6]
check_digit = compute_check_digit(input)
if input+check_digit==sedol:
return 1
else:
return 0
print(check_sedol(sys.argv[1]))
| false |
e26e73fc636c01477fe6d582aa9a5982d26431f2 | southpawgeek/perlweeklychallenge-club | /challenge-125/paulo-custodio/python/ch-2.py | 2,199 | 4.5625 | 5 | #!/usr/bin/env python3
# Challenge 125
#
# TASK #2 > Binary Tree Diameter
# Submitted by: Mohammad S Anwar
# You are given binary tree as below:
#
# 1
# / \
# 2 5
# / \ / \
# 3 4 6 7
# / \
# 8 10
# /
# 9
# Write a script to find the diameter of the given binary tree.
#
# The diameter of a binary tree is the length of the longest path between any
# two nodes in a tree. It doesn't have to pass through the root.
#
# For the above given binary tree, possible diameters (6) are:
#
# 3, 2, 1, 5, 7, 8, 9
#
# or
#
# 4, 2, 1, 5, 7, 8, 9
#
# UPDATE (2021-08-10 17:00:00 BST): Jorg Sommrey corrected the example.
# The length of a path is the number of its edges, not the number of the
# vertices it connects. So the diameter should be 6, not 7.
import fileinput
import re
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def __repr__(self):
return "Node(value: {}, left: {}, right: {})" \
.format(self.value, self.left, self.right)
def read_input():
lines = []
for line in fileinput.input():
lines.append(line)
return lines
def parse_subtree(lines, row, col):
def ch(row, col):
if row < 0 or row >= len(lines) or \
col < 0 or col >= len(lines[row]):
return ' '
else:
return lines[row][col]
tree = Node(int(lines[row][col]))
if ch(row + 1, col - 1) == '/':
tree.left = parse_subtree(lines, row + 2, col - 2)
if ch(row + 1, col + 1) == '\\':
tree.right = parse_subtree(lines, row + 2, col + 2)
return tree
def parse(lines):
found = re.search("^[ ]+\d", lines[0])
col = found.span()[1] - 1
return parse_subtree(lines, 0, col)
def height(node):
if node is None:
return 0
return 1 + max(height(node.left), height(node.right))
def diameter(root):
if root is None:
return 0
lheight = height(root.left)
rheight = height(root.right)
ldiameter = diameter(root.left)
rdiameter = diameter(root.right)
return max(lheight + rheight + 1, max(ldiameter, rdiameter))-1
tree = parse(read_input())
print(diameter(tree))
| true |
181b98baf3ef0ec7b6326b319d0265303ee35f7f | southpawgeek/perlweeklychallenge-club | /challenge-080/paulo-custodio/python/ch-1.py | 604 | 4.1875 | 4 | #!/usr/bin/python3
# Challenge 080
#
# TASK #1 > Smallest Positive Number
# Submitted by: Mohammad S Anwar
# You are given unsorted list of integers @N.
#
# Write a script to find out the smallest positive number missing.
#
# Example 1:
# Input: @N = (5, 2, -2, 0)
# Output: 1
# Example 2:
# Input: @N = (1, 8, -1)
# Output: 2
# Example 3:
# Input: @N = (2, 0, -1)
# Output: 1
import sys
def missing(nums):
nums = sorted(filter(lambda x:x>0, nums))
for a,b in zip(nums, range(1, len(nums)+1)):
if a!=b:
return b
return len(nums)+1
print(missing([int(x) for x in sys.argv[1:]]))
| true |
e5474b43f691af3c6bccca35ec0976bda446f3e5 | southpawgeek/perlweeklychallenge-club | /challenge-142/paulo-custodio/python/ch-1.py | 996 | 4.25 | 4 | #!/usr/bin/python3
# Challenge 142
#
# TASK #1 > Divisor Last Digit
# Submitted by: Mohammad S Anwar
# You are given positive integers, $m and $n.
#
# Write a script to find total count of divisors of $m having last digit $n.
#
#
# Example 1:
# Input: $m = 24, $n = 2
# Output: 2
#
# The divisors of 24 are 1, 2, 3, 4, 6, 8 and 12.
# There are only 2 divisors having last digit 2 are 2 and 12.
#
# Example 2:
# Input: $m = 30, $n = 5
# Output: 2
#
# The divisors of 30 are 1, 2, 3, 5, 6, 10 and 15.
# There are only 2 divisors having last digit 5 are 5 and 15.
import sys
import math
import re
def divisors(n):
div_low = []
div_high = []
for i in range(1, int(math.sqrt(n)+1)):
if n%i==0:
div_low.append(i)
if n/i!=i:
div_high.append(int(n/i))
div_high = div_high[::-1]
return [*div_low, *div_high]
m = int(sys.argv[1])
n = int(sys.argv[2])
count = len(list(filter(lambda x: re.search(str(n)+"$", str(x)), divisors(m))))
print(count)
| false |
24571be35274ccdbf012e6f495cfb55113ff06bc | southpawgeek/perlweeklychallenge-club | /challenge-111/paulo-custodio/python/ch-1.py | 1,727 | 4.1875 | 4 | #!/usr/bin/env python3
# Challenge 111
#
# TASK #1 - Search Matrix
# Submitted by: Mohammad S Anwar
# You are given 5x5 matrix filled with integers such that each row is sorted
# from left to right and the first integer of each row is greater than the
# last integer of the previous row.
#
# Write a script to find a given integer in the matrix using an efficient
# search algorithm.
#
# Example
# Matrix: [ 1, 2, 3, 5, 7 ]
# [ 9, 11, 15, 19, 20 ]
# [ 23, 24, 25, 29, 31 ]
# [ 32, 33, 39, 40, 42 ]
# [ 45, 47, 48, 49, 50 ]
#
# Input: 35
# Output: 0 since it is missing in the matrix
#
# Input: 39
# Output: 1 as it exists in the matrix
import sys
data = [[ 1, 2, 3, 5, 7 ],
[ 9, 11, 15, 19, 20 ],
[ 23, 24, 25, 29, 31 ],
[ 32, 33, 39, 40, 42 ],
[ 45, 47, 48, 49, 50 ]]
def find_col(n, row):
l = 0
h = len(data[row])-1
if n < data[row][0] or n > data[row][-1]:
return -1
while l < h:
m = int((l+h)/2)
if n < data[row][m]:
h = m-1
elif n > data[row][m]:
l = m+1
else:
return m
if n != data[row][l]:
return -1
else:
return l
def find_row(n):
l = 0
h = len(data)-1
if n < data[0][0] or n > data[-1][-1]:
return -1
while l < h:
m = int((l+h)/2)
if n < data[m][0]:
h = m-1
elif n > data[m][-1]:
l = m+1
else:
return m
return l
def find(n):
row = find_row(n)
if row < 0:
return 0
col = find_col(n, row)
if col < 0:
return 0
else:
return 1
print(find(int(sys.argv[1])))
| true |
aa4e0c6eb4930e5e41544dfa45235084582d27a2 | southpawgeek/perlweeklychallenge-club | /challenge-018/paulo-custodio/python/ch-2.py | 2,813 | 4.59375 | 5 | #!/usr/bin/python3
# Challenge 018
#
# Task #2
# Write a script to implement Priority Queue. It is like regular queue except
# each element has a priority associated with it. In a priority queue, an
# element with high priority is served before an element with low priority.
# Please check this wiki page for more informations. It should serve the
# following operations:
#
# is_empty: check whether the queue has no elements.
# insert_with_priority: add an element to the queue with an associated priority.
# pull_highest_priority_element: remove the element from the queue that has the
# highest priority, and return it. If two elements have the same priority,
# then return element added first.
# priority queue
class PQueue():
def __init__(self):
self.q = []
def is_empty(self):
return len(self.q)==0
def insert(self, pri, elem):
if self.is_empty():
self.q.append([pri, [elem]])
elif pri < self.q[0][0]:
self.q.insert(0, [pri, [elem]])
elif pri > self.q[-1][0]:
self.q.append([pri, [elem]])
else:
for i in range(0, len(self.q)):
if self.q[i][0] == pri:
self.q[i][1].append(elem)
return
elif self.q[i][0] > pri:
self.q.insert(i, [pri, [elem]])
return
def pull(self):
if self.is_empty():
return None
else:
elem = self.q[-1][1].pop(0)
if len(self.q[-1][1]) == 0:
self.q.pop(-1)
return elem
# tests
test_num = 0
def ok(f, title):
global test_num
test_num += 1
if f:
print(f"ok {test_num} - {title}")
else:
print(f"nok {test_num} - {title}")
def eq(a, b, title):
ok(a==b, title)
if a!=b:
print("#", a, "!=", b)
def done_testing():
print(f"1..{test_num}")
# run tests
q = PQueue()
ok(q.is_empty(), "is empty")
ok(q.pull() is None, "pull from empty queue")
# insert same priority
q.insert(1, 123)
ok(not q.is_empty(), "is not empty")
q.insert(1, 456)
ok(not q.is_empty(), "is not empty")
q.insert(1, 789)
ok(not q.is_empty(), "is not empty")
# pull
eq(q.pull(), 123, "got element")
ok(not q.is_empty(), "is not empty")
eq(q.pull(), 456, "got element")
ok(not q.is_empty(), "is not empty")
eq(q.pull(), 789, "got element")
ok(q.is_empty(), "is empty")
# insert higher priority
q.insert(1, 123)
q.insert(1, 456)
q.insert(2, 23)
q.insert(3, 4)
# insert lower priority
q.insert(0, 999)
q.insert(0, 998)
eq(q.pull(), 4, "got element")
eq(q.pull(), 23, "got element")
eq(q.pull(), 123, "got element")
eq(q.pull(), 456, "got element")
eq(q.pull(), 999, "got element")
eq(q.pull(), 998, "got element")
ok(q.is_empty(), "is empty")
done_testing()
| true |
3562ca58227644917359011d9ac2bdc4600eba3c | southpawgeek/perlweeklychallenge-club | /challenge-123/paulo-custodio/python/ch-1.py | 1,000 | 4.5625 | 5 | #!/usr/bin/env python
# Challenge 123
#
# TASK #1 > Ugly Numbers
# Submitted by: Mohammad S Anwar
# You are given an integer $n >= 1.
#
# Write a script to find the $nth element of Ugly Numbers.
#
# Ugly numbers are those number whose prime factors are 2, 3 or 5. For example,
# the first 10 Ugly Numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12.
#
# Example
# Input: $n = 7
# Output: 8
#
# Input: $n = 10
# Output: 12
import sys
# return an iterator to generate the sequence
# the sequence is a merge of all multiples of 2, 3 and 5
def hamming_gen():
seq = [[1], [1], [1]]
base = [2, 3, 5]
while True:
# get the smallest of the multiples
n = min(seq[0][0], seq[1][0], seq[2][0])
for i in range(0, 3):
# shift used multiples
if seq[i][0] == n:
seq[i].pop(0)
# push next multiple
seq[i].append(n*base[i])
yield n
# main
iter = hamming_gen()
for i in range(0, int(sys.argv[1])):
print(next(iter))
| true |
04dcac16a22dc5d949c0faad45add1d819bd83c0 | southpawgeek/perlweeklychallenge-club | /challenge-030/paulo-custodio/python/ch-1.py | 354 | 4.21875 | 4 | #!/usr/bin/python3
# Challenge 030
#
# Task #1
# Write a script to list dates for Sunday Christmas between 2019 and 2100. For
# example, 25 Dec 2022 is Sunday.
import datetime
sunday_xmas = []
for year in range(2019, 2101):
dt = datetime.date(year, 12, 25)
if dt.isoweekday()==7:
sunday_xmas.append(year)
print(*sunday_xmas, sep=", ")
| false |
28058f54553dc829e4b41477761197daa2b8ea53 | southpawgeek/perlweeklychallenge-club | /challenge-013/paulo-custodio/python/ch-1.py | 897 | 4.5 | 4 | #!/usr/bin/python3
# Challenge 013
#
# Challenge #1
# Write a script to print the date of last Friday of every month of a given year.
# For example, if the given year is 2019 then it should print the following:
#
# 2019/01/25
# 2019/02/22
# 2019/03/29
# 2019/04/26
# 2019/05/31
# 2019/06/28
# 2019/07/26
# 2019/08/30
# 2019/09/27
# 2019/10/25
# 2019/11/29
# 2019/12/27
import sys
import datetime
def last_day_of_month(year, month):
dt = datetime.date(year, month, 28)
while dt.month==month:
dt += datetime.timedelta(days=1)
dt -= datetime.timedelta(days=1)
return dt
def last_friday(dt):
while dt.isoweekday()!=5:
dt -= datetime.timedelta(days=1)
return dt
def print_last_fridays(year):
for month in range(1, 13):
dt = last_friday(last_day_of_month(year, month))
print(dt.strftime("%Y/%m/%d"))
print_last_fridays(int(sys.argv[1]))
| true |
ddeb79648fe323c4e2332c76c2943b8635494494 | southpawgeek/perlweeklychallenge-club | /challenge-140/paulo-custodio/python/ch-1.py | 802 | 4.21875 | 4 | #!/usr/bin/python3
# Challenge 140
#
# TASK #1 > Add Binary
# Submitted by: Mohammad S Anwar
# You are given two decimal-coded binary numbers, $a and $b.
#
# Write a script to simulate the addition of the given binary numbers.
#
# The script should simulate something like $a + $b. (operator overloading)
#
# Example 1
# Input: $a = 11; $b = 1;
# Output: 100
# Example 2
# Input: $a = 101; $b = 1;
# Output: 110
# Example 3
# Input: $a = 100; $b = 11;
# Output: 111
import sys
class Binary():
def __init__(self, n):
self.n = n
def __str__(self):
return str(self.n)
def __add__(self, other):
a = int(str(self.n), 2)
b = int(str(other.n), 2)
return Binary(int("{:b}".format(a+b)))
a = Binary(int(sys.argv[1]))
b = Binary(int(sys.argv[2]))
c = a+b
print(c)
| true |
cbd9121e6c8c3f678ec2ce3d918c1380bf271d58 | southpawgeek/perlweeklychallenge-club | /challenge-120/paulo-custodio/python/ch-2.py | 1,057 | 4.40625 | 4 | #!/usr/bin/env python
# Challenge 120
#
# TASK #2 - Clock Angle
# Submitted by: Mohammad S Anwar
# You are given time $T in the format hh:mm.
#
# Write a script to find the smaller angle formed by the hands of an analog
# clock at a given time.
#
# HINT: A analog clock is divided up into 12 sectors. One sector represents 30
# degree (360/12 = 30).
#
# Example
# Input: $T = '03:10'
# Output: 35 degree
#
# The distance between the 2 and the 3 on the clock is 30 degree.
# For the 10 minutes i.e. 1/6 of an hour that have passed.
# The hour hand has also moved 1/6 of the distance between the 3 and the 4,
# which adds 5 degree (1/6 of 30).
# The total measure of the angle is 35 degree.
#
# Input: $T = '04:00'
# Output: 120 degree
import sys
def clock_angles(hh, mm):
mm_angle = mm * 360 // 60
hh_angle = (hh % 12) * 360 // 12 + mm_angle // 12
return hh_angle, mm_angle
hh, mm = [int(x) for x in sys.argv[1].split(':')]
hh_angle, mm_angle = clock_angles(hh, mm)
angle = abs(hh_angle - mm_angle)
if angle > 180:
angle = 360 - angle
print(angle)
| true |
5e4e40bdfdd873f1a7d3167402d0464c944f74a8 | southpawgeek/perlweeklychallenge-club | /challenge-115/paulo-custodio/python/ch-2.py | 878 | 4.34375 | 4 | #!/usr/bin/env python3
# Challenge 115
#
# TASK #2 - Largest Multiple
# Submitted by: Mohammad S Anwar
# You are given a list of positive integers (0-9), single digit.
#
# Write a script to find the largest multiple of 2 that can be formed from the
# list.
#
# Examples
# Input: @N = (1, 0, 2, 6)
# Output: 6210
#
# Input: @N = (1, 4, 2, 8)
# Output: 8412
#
# Input: @N = (4, 1, 7, 6)
# Output: 7614
import sys
def largest_mult2(nums):
# select smallest even number for last element
even = list(filter(lambda x: x%2 == 0, nums))
if len(even)==0:
return 0 # no even numbers
even.sort()
last = even[0]
# sort the other elements in descending order
nums = list(filter(lambda x: x!=last, nums))
nums.sort()
nums = nums[::-1]
return int("".join([str(x) for x in [*nums, last]]))
print(largest_mult2([int(x) for x in sys.argv[1:]]))
| true |
00e20f7815261d3df81deaef6fefb67c38037ce5 | mannerslee/leetcode | /merge_sort.py | 543 | 4.1875 | 4 | '''
解题报告。
注意的点:
'''
def merge(arr, left, mid, right):
i = left
j = mid
while i < mid or j <= right:
if (i < mid and arr[i] < arr[j]) or j > right:
pass
def merge_sort(arr, left, right):
if left < right:
mid = int((left + right) / 2)
merge_sort(arr, left, mid)
merge_sort(arr, mid + 1, right)
merge(arr, left, mid, right)
if __name__ == '__main__':
arr = [3, 1, 4, 1, 5, 9]
print(merge_sort(arr, left=0, right=len(arr) - 1))
| false |
57a13fefb2407ad365415d7736d66812291a8998 | JohnnyFang/datacamp | /machine-learning-with-the-experts-school-budgets/04-learning-from-the-expert-processing/10-implementing-the-hashing-trick-in-scikit-learn.py | 799 | 4.1875 | 4 | """
Implementing the hashing trick in scikit-learn
In this exercise you will check out the scikit-learn implementation of HashingVectorizer before adding it to your pipeline later.
As you saw in the video, HashingVectorizer acts just like CountVectorizer in that it can accept token_pattern and ngram_range parameters. The important difference is that it creates hash values from the text, so that we get all the computational advantages of hashing!
Instructions
100 XP
Import HashingVectorizer from sklearn.feature_extraction.text.
Instantiate the HashingVectorizer as hashing_vec using the TOKENS_ALPHANUMERIC pattern.
Fit and transform hashing_vec using text_data. Save the result as hashed_text.
Hit 'Submit Answer' to see some of the resulting hash values.
"""
fit_transform
| true |
51b2a825d5e02f40b396f365c5226e96dd1fa440 | JohnnyFang/datacamp | /10-Merging-DataFrames-with-Pandas/04-case-study-Summer-Olympics/06-computing-percentage-cjange-in-fraction-of-medals-won.py | 923 | 4.375 | 4 | '''
Create mean_fractions by chaining the methods .expanding().mean() to fractions.
Compute the percentage change in mean_fractions down each column by applying .pct_change() and multiplying by 100. Assign the result to fractions_change.
Reset the index of fractions_change using the .reset_index() method. This will make 'Edition' an ordinary column.
Print the first and last 5 rows of the DataFrame fractions_change. This has been done for you, so hit 'Submit Answer' to see the results!
'''
# Apply the expanding mean: mean_fractions
mean_fractions = fractions.expanding().mean()
# Compute the percentage change: fractions_change
fractions_change = mean_fractions.pct_change() * 100
# Reset the index of fractions_change: fractions_change
fractions_change = fractions_change.reset_index()
# Print first & last 5 rows of fractions_change
print(fractions_change.head())
print(fractions_change.tail())
| true |
6a3c75c8c221fdaad8a6ec854679349cd7e419b5 | anushajain19/Extracting-data-with-python | /Week 5/xml_parsing.py | 1,261 | 4.15625 | 4 |
#Extracting Data from XML
#In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/geoxml.py. The program will prompt for a URL, read the XML data from that URL using urllib and then parse and extract the comment counts from the XML data, compute the sum of the numbers in the file.
#We provide two files for this assignment. One is a sample file where we give you the sum for your testing and the other is the actual data you need to process for the assignment.
#Sample data: http://py4e-data.dr-chuck.net/comments_42.xml (Sum=2553)
#Actual data: http://py4e-data.dr-chuck.net/comments_589717.xml (Sum ends with 12)
#You do not need to save these files to your folder since your program will read the data directly from the URL. Note: Each student will have a distinct data url for the assignment - so only use your own data url for analysis.
#use pip install beautifulsoup4 requests lxml
from bs4 import BeautifulSoup
import requests
url = 'http://py4e-data.dr-chuck.net/comments_589717.xml'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'lxml')
count = soup.find_all('count')
total = sum(int(i.text) for i in count)
print(f'The sum of all count in doc are: {total}')
| true |
187905f103c8abf7dbfbdd019fecee72d3d739a2 | ShashankDhungana/gvhj | /Lab2/N4.py | 395 | 4.25 | 4 | '''4. Given three integers, print the smallest one. (Three integers should be user input)'''
a = int(input('Enter first number : '))
b = int(input('Enter second number : '))
c = int(input('Enter third number : '))
smallest = 0
if a < b and a < c :
smallest = a
if b < a and b < c :
smallest = b
if c < a and c < b :
smallest = c
print(smallest, "is the smallest of three numbers") | true |
b7a535269c7432fc8dd856d32c59175db5add137 | PorcupineVN/Algorithms-and-data-structures-in-Python | /task_9.py | 602 | 4.4375 | 4 | # Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого).
print('Введите первое число: ')
a = float(input())
print('Введите второе число: ')
b = float(input())
print('Введите третье число: ')
c = float(input())
if b < a < c or c < a < b:
print(f'Среднее число: {a}')
elif a < b < c or c < b < a:
print(f'Среднее число: {b}')
else:
print(f'Среднее число: {c}')
| false |
3afcb51d1df181cfc0add8a80d85af8f1a95169d | guiltylogik/automateTheBoringStuff | /guessingGame.py | 1,602 | 4.15625 | 4 | # A simple guessing game.
# TODO: get player name
# get random number - secret number
# get player guesses
# give hint after 3 tries
# display result after 5 tries
# decompose the program
import random as r
lower_limit = r.randint(0, 40)
upper_limit = r.randint(60, 100)
com_guess = r.randint(lower_limit, upper_limit)
print(f"DEBUG: com guess = {com_guess}")
player_name = input("Hey! What's your name: ").capitalize()
print(f"\n{player_name}! I am thinking of a number between {lower_limit} and {upper_limit}")
for guesses in range(1, 6):
guess = int(input("Make a Guess: "))
if guess > upper_limit or guess < lower_limit:
print(f"\nOh! common, {guess} is not in the range {lower_limit}-{upper_limit}.")
elif guess < com_guess:
print("\nYour Guess is too low! Guess higher")
# FIXME - Hint - FIXED
if guesses > 3:
print(f"Hint: the difference between {guess} and my number is {com_guess - guess}\n")
elif guess > com_guess:
print("\nYour Guess is too high! Guess lower.")
# FIXME - Hint - FIXED
if guesses > 3:
print(f"Hint: the difference between {guess} and my number is {guess - com_guess}\n")
else:
break
# try_time = "tries" if guesses > 1 else "try\nyou are very lucky"
try_time = ("tries", "try.\nYou are a very lucky person.") [guesses == 1]
if guess == com_guess:
print(f"\nCongrats! {player_name}, You guessed my number in {guesses} {try_time}.")
else:
print(f"\nSorry! {player_name}, the number I was thinking is {com_guess}.")
| true |
1cd2e92359d0c033ea58f34d650952f09453353d | RUPAbahadur/Python-Programs | /indexingstring.py | 996 | 4.21875 | 4 | """
String indexing examples.
"""
phrase = "Python is great!"
# first character
print(phrase[0]) #retrieve the first char of variable'a value
# fourth character
fourth = phrase[3]
print(fourth)
print(type(phrase)) # 'type' returns the type of object ->str
print(type(fourth)) # in python even a single character is considered as a str type
# length of string
phraselen = len(phrase) #returns no.of. character)starts from 1) #indexing starts from 0
print(phraselen)
# last character
print(phrase[phraselen - 1]) #to retrieve last char -1 can be used
print(phrase[-1]) #indexing from left: 0 1 2 3 ...
#indexing from right: .....-3 -2 -1
# thirteenth from last (fourth) character
print(phrase[-13])
# Out of bounds
#print(phrase[phraselen]) #index should be in range not more not less
#print(phrase[-20])
# Indices
# string = "abcde"
# character a b c d e
# pos index 0 1 2 3 4
# neg index -5 -4 -3 -2 -1
| true |
42cf76652772e5a7b7799b832793aca78f15b8ce | raopratik/Commonsense-QA | /SocialIQA/utils.py | 970 | 4.21875 | 4 | import sys
sys.path.append(".")
import pickle
def save_dictionary(dictionary, save_path):
"""
This method is used to save dictionary to a given path in pickle file
Args:
dictionary (dict): dictionary which has to be saved
save_path (str): path where the dictionary has to be saved
"""
with open(save_path, 'wb') as handle:
print("saving model to:", save_path)
pickle.dump(dictionary, handle, protocol=pickle.HIGHEST_PROTOCOL)
print("dictionary saved to:", save_path)
def load_dictionary(load_path):
"""
This method is used to load the dictionary given a path
Args:
load_path (str): loading dictionary from the given path
Returns:
dictionary (dict): the loaded dictionary
"""
with open(load_path, 'rb') as handle:
print("loading data from:", load_path)
dictionary = pickle.load(handle)
print("loading completed")
return dictionary
| true |
9fa09e148a3df0f8a0cbffdcd7ce8ddd60d47d4a | turboslayer198/mitx-6.00.1x | /Lecture Programs/palindrome.py | 282 | 4.125 | 4 | def isPalindrome(str):
if len(str) == 1:
return True
else:
return str[0] == str[-1] and isPalindrome(str[1:-1])
str = input('Enter a string - ')
if isPalindrome(str):
print('\nIt is indeed a palindrome\n')
else:
print('\nIt is not a palindrome\n')
| false |
862e362b69389d17a3285f4d4a77c7ff3f920c65 | turboslayer198/mitx-6.00.1x | /Lecture Programs/coordinate.py | 1,450 | 4.25 | 4 | class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other_coordinate_object):
x_diff_sq = (self.x - other_coordinate_object.x)**2
y_diff_sq = (self.y - other_coordinate_object.y)**2
return (x_diff_sq + y_diff_sq)**0.5
# Python calls __str__ method when used with 'print' on your class object
def __str__(self):
return f'({self.x}, {self.y})'
# Override the operators to work with objects
def __add__(self, other_coordinate_object):
return f'({self.x + other_coordinate_object.x}, {self.y + other_coordinate_object.y})'
# def __sub__(self, other): for overriding '-'
# def __eq__(self, other): for overriding '=='
# def __len__(self): for overriding 'len(self)'
def __lt__(self, other_coordinate_object): #for overriding '<'
return f'Write logic to check if point o is less than point p!'
# Origin
o = Coordinate(0, 0)
# Point
p = Coordinate(6, 9)
print(f'The distance between point o({o.x},{o.y}) and p({p.x},{p.y}) is: {round(o.distance(p), 2)} units')
print(f'Distance - {Coordinate.distance(o, p)}')
# print(p) returns <__main__.Coordinate object at 0x109c699e8> which is 'uninformative'. We define a '__str__' method in class to define what we wanna do with that print(c)
print(p)
print(f'Addition of point o({o.x},{o.y}) and p({p.x},{p.y}) is: {Coordinate.__add__(o, p)}')
print(o < p)
| true |
eaa9bca966aa7efb22c0134ffea586bfa7eb8818 | GuilhermeLaraRusso/python_work | /ch_9_classes/9_14_overriding_methods_from_parent_class.py | 2,440 | 5 | 5 | # Overriding Methods from the Parent Class
# You can override any method from the parent class that doesn’t fit what
# you’re trying to model with the child class. To do this, you define a method
# in the child class with the same name as the method you want to override
# in the parent class. Python will disregard the parent class method and only
# pay attention to the method you define in the child class.
# Say the class Car had a method called fill_gas_tank(). This method is
# meaningless for an all-electric vehicle, so you might want to override this
# method. Here’s one way to do that:
class Car():
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
Initialize attributes of the parent class.
Then initialize attributes specific to an electric car
"""
super().__init__(make, model, year)
self.battery_size = 70
def describe_battery(self):
"""Print a statement describing the battery size."""
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def fill_gas_tank(self):
"""Electric cars don't have gas tanks."""
print("This car doesn't need a gas tank!")
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
my_tesla.fill_gas_tank()
# Now if someone tries to call fill_gas_tank() with an electric car, Python
# will ignore the method fill_gas_tank() in Car and run this code instead. When
# you use inheritance, you can make your child classes retain what you need
# and override anything you don’t need from the parent class. | true |
119e03f8a51cf75ef2171958a5b7b15b70fdcc76 | GuilhermeLaraRusso/python_work | /ch_8_functions/8_14_returning_a_dictionary.py | 535 | 4.40625 | 4 | # A function can return any kind of value you need it to, including more complicated
# data structures like lists and dictionaries. For example, the following
# function takes in parts of a name and returns a dictionary representing
# a person:
def build_person(first_name, last_name, age=''):
"""Return a dictionary of information about a person."""
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person
musician = build_person('jimi', 'hendrix', age=27)
print(musician) | true |
6cf16136cd35f69714f4c93c3059f3b450f6fd22 | GuilhermeLaraRusso/python_work | /ch_10_files_and_exceptions/10_1_reading_an_entire_file.py | 2,826 | 4.8125 | 5 | # To try the following examples yourself, you can enter these lines in an
# editor and save the file as pi_digits.txt, or you can download the file from the
# book’s resources through https://www.nostarch.com/pythoncrashcourse/. Save
# the file in the same directory where you’ll store this chapter’s programs.
# Here’s a program that opens this file, reads it, and prints the contents
# of the file to the screen:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
# The first line of this program has a lot going on. Let’s start by looking
# at the open() function. To do any work with a file, even just printing its contents,
# you first need to open the file to access it. The open() function needs
# one argument: the name of the file you want to open. Python looks for this
# file in the directory where the program that’s currently being executed is
# stored. In this example, file_reader.py is currently running, so Python looks
# for pi_digits.txt in the directory where file_reader.py is stored. The open()
# function returns an object representing the file. Here, open('pi_digits.txt')
# returns an object representing pi_digits.txt. Python stores this object in
# file_object, which we’ll work with later in the program.
# The keyword with closes the file once access to it is no longer needed.
# Notice how we call open() in this program but not close(). You could open
# Files and Exceptions 191
# and close the file by calling open() and close(), but if a bug in your program
# prevents the close() statement from being executed, the file may never
# close. This may seem trivial, but improperly closed files can cause data
# to be lost or corrupted. And if you call close() too early in your program,
# you’ll find yourself trying to work with a closed file (a file you can’t access),
# which leads to more errors. It’s not always easy to know exactly when you
# should close a file, but with the structure shown here, Python will figure that
# out for you. All you have to do is open the file and work with it as desired,
# trusting that Python will close it automatically when the time is right.
# Once we have a file object representing pi_digits.txt, we use the read()
# method in the second line of our program to read the entire contents of
# the file and store it as one long string in contents. When we print the value
# of contents, we get the entire text file back:
#
# The only difference between this output and the original file is the
# extra blank line at the end of the output. The blank line appears because
# read() returns an empty string when it reaches the end of the file; this empty
# string shows up as a blank line. If you want to remove the extra blank line,
# you can use rstrip() in the print statement: | true |
80a289744df25efcbc7b6eecb170b6d4fad12daf | GuilhermeLaraRusso/python_work | /ch_6_dictionaries/6_6_modifying_values_in_dictionary.py | 1,062 | 4.53125 | 5 | # To modify a value in a dictionary, give the name of the dictionary with the
# key in square brackets and then the new value you want associated with
# that key.
#
# alien_0 = {'color': 'green'}
# print("The alien is " + alien_0['color'] + '.')
#
# alien_0['color'] = 'yellow'
# print("The alien is now " + alien_0['color'] + '.')
# For a more interesting example, let’s track the position of an alien that
# can move at different speeds. We’ll store a value representing the alien’s
# current speed and then use it to determine how far to the right the alien
# should move:
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print('"Original x-position: ' + str(alien_0['x_position']))
# Move the alien to the right
# Determine how far to move the alien based on its current speed.
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
x_increment = 3
alien_0['x_position'] = alien_0['x_position'] + x_increment
print("New' x-position: " + str(alien_0['x_position']))
| true |
6a4b61be398e25ff44daa2d4dce0d72dc94b882a | GuilhermeLaraRusso/python_work | /ch_5_if_statements/5_6_simple_if_statement.py | 709 | 4.21875 | 4 | # The simplest kind of if statement has one test and one action:
# if condicional_test:
# do something
# You can put any conditional test in the first line and just about any
# action in the indented block following the test. If the conditional test
# evaluates to True, Python executes the code following the if statement.
# If the test evaluates to False, Python ignores the code following the if
# statement.
# Let’s say we have a variable representing a person’s age, and we want to
# know if that person is old enough to vote. The following code tests whether
# the person can vote:
age = 19
if age >= 18:
print('You are old enough to vote!')
print('Have you registered to vote yet?')
| true |
7e6de2fcb534cf1c31453998bfcb9b2bbe7d5149 | GuilhermeLaraRusso/python_work | /ch_3_introducing_lists/3_1_listas.py | 1,167 | 4.65625 | 5 | # A list is a collection of items in a particular order. You can make a list that
# includes the letters of the alphabet, the digits from 0–9, or the names of
# all the people in your family. You can put anything you want into a list, and
# 38 Chapter 3
# the items in your list don’t have to be related in any particular way. Because
# a list usually contains more than one element, it’s a good idea to make the
# name of your list plural, such as letters, digits, or names.
# In Python, square brackets ([]) indicate a list, and individual elements
# in the list are separated by commas. Here’s a simple example of a list that
# contains a few kinds of bicycles:
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
# Para acessar apenas um elemento da lista, basta colocar a posição do elemento dentro do colchetes
print(bicycles[0])
print(bicycles[0].title())
# Para acessar o último elemento da lista, é utilizado [-1]
print(bicycles[-1])
# Para acessar o antepenúltimo item da lista, utiliza [-2], depois [-3] e assim sucessivamente
message = 'My first bicycle was a ' + bicycles[0].title() +'.'
print(message)
| true |
c550306104afca1fd23071a399f6136b94c0ab9f | GuilhermeLaraRusso/python_work | /ch_4_working_with_lists/4_12_exercicio_4_10.py | 844 | 4.875 | 5 | # 4-10. Slices: Using one of the programs you wrote in this chapter, add several
# lines to the end of the program that do the following:
# • Print the message, The first three items in the list are:. Then use a slice to
# print the first three items from that program’s list.
# • Print the message, Three items from the middle of the list are:. Use a slice
# to print three items from the middle of the list.
# • Print the message, The last three items in the list are:. Use a slice to print
# the last three items in the list.
my_foods = ['pizza', 'falafel', 'carrot cake', 'strogonoff', 'fries', 'chocolate']
print('The first three items on the list are: ')
print(my_foods[:3])
print('\nThree items from the middle of the list are: ')
print(my_foods[2:5])
print('\nThe last three items in the list are:')
print(my_foods[-3:]) | true |
4bd4d9ac9e3089f0e7ead3871614b33d9ea350f5 | GuilhermeLaraRusso/python_work | /ch_4_working_with_lists/4_11_copying_a_list.py | 1,048 | 4.78125 | 5 | # To copy a list, you can make a slice that includes the entire original list
# by omitting the first index and the second index ([:]). This tells Python to
# make a slice that starts at the first item and ends with the last item, producing
# a copy of the entire list.
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print('My favorite foods are: ')
print(my_foods)
print("\nMy friend's favorite foods are: ")
print(friend_foods)
# This doesn't work:
# friend_foods = my_foods
# Instead of storing a copy of my_foods in friend_foods at u, we set
# friend_foods equal to my_foods. This syntax actually tells Python to connect
# the new variable friend_foods to the list that is already contained in
# my_foods, so now both variables point to the same list. As a result, when we
# add 'cannoli' to my_foods, it will also appear in friend_foods. Likewise 'ice
# cream' will appear in both lists, even though it appears to be added only to
# friend_foods.
| true |
24b521e249dbb84ce0f4fa2abcb4344cfb7fd079 | GuilhermeLaraRusso/python_work | /ch_4_working_with_lists/4_15_writing_over_a_Tuple.py | 490 | 4.5625 | 5 | # Although you can’t modify a tuple, you can assign a new value to a variable
# that holds a tuple.
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
# When compared with lists, tuples are simple data structures. Use them
# when you want to store a set of values that should not be changed throughout
# the life of a program. | true |
c005f5b24a8ba094077e0f7a07e9c1e825bcbf86 | GuilhermeLaraRusso/python_work | /ch_6_dictionaries/6_8_dictionary_of_similar_objects.py | 591 | 4.4375 | 4 | # The previous example involved storing different kinds of information about
# one object, an alien in a game. You can also use a dictionary to store one
# kind of information about many objects.
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("Sarah's favorite language is " +
favorite_languages['sarah'].title() +
".\n")
# Utilizando o loop para percorrer todos os valores - parte 6_11
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " + language.title()) | true |
5bc9490da14edf1bf5eab478736afaccf4f8983e | GuilhermeLaraRusso/python_work | /ch_5_if_statements/5_12_exercicio_5_7.py | 914 | 4.40625 | 4 | # 5-7. Favorite Fruit: Make a list of your favorite fruits, and then write a series of
# independent if statements that check for certain fruits in your list.
# • Make a list of your three favorite fruits and call it favorite_fruits.
# • Write five if statements. Each should check whether a certain kind of fruit
# is in your list. If the fruit is in your list, the if block should print a statement,
# such as You really like bananas!
favorite_fruits = ['banana', 'apple', 'peach']
if 'banana' in favorite_fruits:
fruta = 'banana'
print('You really like ' + fruta.title() + '.')
if 'apple' in favorite_fruits:
fruta = 'apple'
print('You really like ' + fruta.title() + '.')
if 'peach' in favorite_fruits:
fruta = 'peach'
print('You really like ' + fruta.title() + '.')
if 'pineapple' in favorite_fruits:
fruta = 'pineapple'
print('You really like ' + fruta.title() + '.')
| true |
a63e882dcaa372fb86f6c6f1b295b03bdd2b0df8 | GuilhermeLaraRusso/python_work | /ch_6_dictionaries/6_9_exercicio_6_2.py | 594 | 4.125 | 4 | # 6-2. Favorite Numbers: Use a dictionary to store people’s favorite numbers.
# Think of five names, and use them as keys in your dictionary. Think of a favorite
# number for each person, and store each as a value in your dictionary. Print
# each person’s name and their favorite number. For even more fun, poll a few
# friends and get some actual data for your program.
favorite_numbers = {'Guilherme': 17,
'Thais': 8,
'Lorenzo': 6,
'Gloria': 17,
'Rogerio': 49,
}
print(favorite_numbers) | true |
4404a0a7e16dd2342778b7fd2482fcfa6c1229d9 | GuilhermeLaraRusso/python_work | /ch_8_functions/8_15_using_function_with_while_loop.py | 819 | 4.40625 | 4 | # You can use functions with all the Python structures you’ve learned about
# so far. For example, let’s use the get_formatted_name() function with a while
# loop to greet users more formally. Here’s a first attempt at greeting people
# using their first and last names:
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted"""
full_name = first_name + ' ' + last_name
return full_name.title()
# This is an infinite loop!
while True:
print("\nPlease tell me your name:")
print("(enter 'q' at any time to quit)")
f_name = input("First name: ")
if f_name == 'q':
break
l_name = input("Last name: ")
if l_name == 'q':
break
formatted_name = get_formatted_name(f_name, l_name)
print("\nHello, " + formatted_name + "!")
| true |
30a8bf8c4649b7fe4789b4b71f5c1c2bb86dea8a | GuilhermeLaraRusso/python_work | /ch_3_introducing_lists/3_9_organizando_lista.py | 835 | 4.65625 | 5 | # Sorting a List Permanently with the sort() Method
# Python’s sort() method makes it relatively easy to sort a list. Imagine we
# have a list of cars and want to change the order of the list to store them
# alphabetically. To keep the task simple, let’s assume that all the values in
# the list are lowercase.
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
# The sort() method, shown at u, changes the order of the list permanently.
# The cars are now in alphabetical order, and we can never revert to
# the original order:
# You can also sort this list in reverse alphabetical order by passing the
# argument reverse=True to the sort() method. The following example sorts
# the list of cars in reverse alphabetical order:
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)
| true |
ba13cd4d066df89ec2c1ac7a0aa9f84456751a2c | ecz5032/hw1-python | /main.py | 1,877 | 4.15625 | 4 | #author Eric Zhang ecz5032@psu.edu
gradeOneInput = input("Enter your course 1 letter grade: ")
credit1 = input("Enter your course 1 credit: ")
credit1 = float(credit1)
if gradeOneInput == "A":
gradeOne = 4
elif gradeOneInput == "A-":
gradeOne = 3.67
elif gradeOneInput == "B+":
gradeOne = 3.33
elif gradeOneInput == "B":
gradeOne = 3
elif gradeOneInput == "B-":
gradeOne = 2.67
elif gradeOneInput == "C+":
gradeOne = 2.33
elif gradeOneInput == "C":
gradeOne = 2
elif gradeOneInput == "D":
gradeOne = 1
else:
gradeOne = 0
print("Grade point for course 1 is: " +str(gradeOne))
gradeTwoInput = input("Enter your course 2 letter grade: ")
credit2 = input("Enter your course 2 credit: ")
credit2 = float(credit2)
if gradeTwoInput == "A":
gradeTwo = 4
elif gradeTwoInput == "A-":
gradeTwo = 3.67
elif gradeTwoInput == "B+":
gradeTwo = 3.33
elif gradeTwoInput == "B":
gradeTwo = 3
elif gradeTwoInput == "B-":
gradeTwo = 2.67
elif gradeTwoInput == "C+":
gradeTwo = 2.33
elif gradeTwoInput == "C":
gradeTwo = 2
elif gradeTwoInput == "D":
gradeTwo = 1
else:
gradeTwo = 0
print("Grade point for course 2 is: " +str(gradeTwo))
gradeThreeInput = input("Enter your course 3 letter grade: ")
credit3 = input("Enter your course 3 credit: ")
credit3 = float(credit3)
if gradeThreeInput == "A":
gradeThree = 4
elif gradeThreeInput == "A-":
gradeThree = 3.67
elif gradeThreeInput == "B+":
gradeThree = 3.33
elif gradeThreeInput == "B":
gradeThree = 3
elif gradeThreeInput == "B-":
gradeThree = 2.67
elif gradeThreeInput == "C+":
gradeThree = 2.33
elif gradeThreeInput == "C":
gradeThree = 2
elif gradeThreeInput == "D":
gradeThree = 1
else:
gradeThree = 0
print("Grade point for course 3 is: " +str(gradeThree))
GPA = (gradeOne * credit1 + gradeTwo * credit2+gradeThree * credit3) / (credit1+credit2+credit3)
print("Your GPA is: "+str(GPA))
| false |
cea42b481f54d9de79ebe6bcde75e31c2cec59e9 | techkuz/cs101 | /pset3/find_element.py | 556 | 4.125 | 4 | # Define a procedure, find_element,
# that takes as its inputs a list
# and a value of any type, and
# returns the index of the first
# element in the input list that
# matches the value.
# If there is no matching element,
# return -1.
def find_element(list1, value):
for i in list1:
p = str(i).find(str(value))
#print p
#print list1[i-1]
#print i
if p != -1:
return list1.index(value)
return -1
print find_element([1,2,3],3)
#>>> 2
print find_element(['alpha','beta'],'gamma')
#>>> -1 | true |
36d3a0021913601c5a66403e84c9bf62525ea4ea | KESA24/Hello_python | /calculator.py | 568 | 4.375 | 4 |
# num1 = input("Enter a number: ")
# num2 = input("Enter another number: ")
# # Returns only whole number
# # result = int(num1) + int(num2)
#
# # float uses both decimals and whole numbers
# result = float(num1) + float(num2)
# print(result)
# Better Calculator!
num5 = float(input("Enter first number: "))
op = input("Enter operator: ")
num6 = float(input("Enter second number: "))
if op == "+":
print(num5+num6)
elif op == "-":
print(num5-num6)
elif op == "/":
print(num5/num6)
elif op == "*":
print(num5*num6)
else:
print("Invalid operator") | true |
52d23edde3fa733d4045a09f97707a8f93a8bc8e | david-belbeze/PythonQueue | /queue.py | 1,663 | 4.34375 | 4 | # -*- coding: UTF_8 -*-
class Queue:
FIFO = 0
LIFO = 1
def __init__(self, l=[], t=FIFO):
"""
An object which implement the queue logic from a list.
:param l: The base list to use with this queue. The list is empty by default.
:param t: The type of the queue FIFO or LIFO. FIFO by default
:type l: list
:type t: int
"""
self.list = l
self.__type = t
def push(self, e):
"""
Push the param at the end of the queue.
:param e: The element to insert in the queue.
"""
self.list.append(e)
def pull(self):
"""
Pull the element as the type of the queue
:raise ValueError: If the queue type is not provided.
:return: The element to pull as the logic of the queue
"""
if self.__type == self.__class__.FIFO:
return self.list.pop(0)
elif self.__type == self.__class__.LIFO:
return self.list.pop(len(self.list) - 1)
else:
raise ValueError("The type must be set to FIFO or LIFO. See the documentation")
return None
def clear(self):
"""
Clear the queue to be empty.
"""
count = len(self.list)
while count > 0:
self.list.pop(0)
count -= 1
def is_empty(self):
"""
Check if the queue is empty or not.
:return: True if the queue is empty False otherwise
:rtype: bool
"""
return len(self.list) == 0
def __str__(self):
return str(self.list)
| true |
659ab18067fc79c6384da8f3d08c90fc570fe09f | vinaykumargattu/Simple_Python_Programs | /nested_for_loop_in_python.py | 508 | 4.25 | 4 | #Nested for loop in python
"""x=int(input("Enter a number"))
i,j=0,0
for i in range(0,x):
print("")
for j in range(0,i+1):
print("*", end='')"""
#for loop with else
"""number1=int(input("Enter the number"))
for i in range(0,number1):
print(i)
else:
print("Forloop completed")
"""
#for loop with break statement
number2=int(input("Enter the number"))
for i in range(0, number2):
print(i)
break;
else:
print("for loop once executed and exit due to break condition") | true |
b9120e09acf688cc6359d6e1c1fa493f3247c605 | millidavids/cs115 | /lab6inclass.py | 1,395 | 4.15625 | 4 | # Prolog
# Authors: David Yurek, Stanley McClister, Evan Whitmer
# Section 012 :: Team 3
# September 27, 2013
# ______________________________________________________________________________
#
# Purpose: The purpose of this program is to make a multiplication iteration program
# based on two integer inputs from the user.
#
# Preconditions: There are two inputs from the user; 2 integers.
#
# Post-conditions: The output of the program are the multiplication iterations of the for loop
# based on the 2 integer inputs from the user.
#_______________________________________________________________________________
# Call main.
def main():
# Defines the variables based on user input.
firstNum = int(input("Enter the first number: ")) # First integer used in iteration.
secondNum = int(input("Enter the second number: ")) # Second integer used in iteration.
iterationNum = int(input("How many iterations "
"of multiplication? ")) # Iteration number integer.
dynamicVar = 0 # Dynamic variable used in loop.
# Prints a line break and the first 2 numbers.
print()
print(firstNum, secondNum, end=" ")
for mult in range(iterationNum):
dynamicVar = secondNum
secondNum *= firstNum
firstNum = dynamicVar
print(secondNum, end= " ")
main() | true |
00cffefd4ba7dc1578b785da6fb8cb913aa1629e | GrisoFandango/Week-8 | /3 - dictionary example.py | 646 | 4.125 | 4 | contacts={"greg": 7235591,
"Mary": 3841212,
"Bob": 3841212,
"Susan": 2213278}
# print content of dictionary
print("Dictionary content are: \n", contacts)
#printing the value of a dictionary key
print("Phone number for Susan is:", contacts["Susan"])
#print out how many keys are in the dictionary
print("Lenght of dictionary is:", len(contacts))
#adding two keys in the dictionary
contacts["John"]=4440001
contacts["Fred"]=5550001
#deleting the contact calle "bob"
contacts.pop("Bob")
print("Contents of contacts after deleting entry for bob is:\n", contacts)
print("lenght of dictionary is now:", len(contacts))
| true |
ebdc250e40e4bdbe2a3f9c4ef6d609635e5746d8 | DinaShaim/Python_basics | /HomeWork_2/les_2_task_2.py | 654 | 4.125 | 4 | # Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы
# с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте.
# Для заполнения списка элементов необходимо использовать функцию input().
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8]
i = 0
while i < len(my_list)-1:
my_list[i], my_list[i+1] = my_list[i+1], my_list[i]
i += 2
print(my_list)
| false |
d67a66904417883e6d0c391a6fa6bac8c57162c0 | DinaShaim/Python_basics | /HomeWork_3/les3_task1.py | 591 | 4.21875 | 4 | # Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
# Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
def division(x1, x2):
try:
return round(x1 / x2, 5)
except ZeroDivisionError:
return f"Деление на 0"
print(division(int(input('Введите делимое:')), int(input('Введите делитель:'))))
| false |
e47858f3529f1ac82279414fcd0436d0ece6e869 | manifoldfrs/python_sandbox | /python_sandbox_starter/lists.py | 877 | 4.1875 | 4 | # A List is a collection which is ordered and changeable. Allows duplicate members.
# Create list
numbers = [ 1, 2, 3, 4, 5]
# Using a constructor, it's like JS, as if you're calling a new Array constructor.
numbers2 = list((1,2,3,4,5))
# print(numbers, numbers2)
fruits = ['Apples', 'Oranges', 'Grapes', 'Pears']
# Get a single value from a list
print(fruits[1]) # lists are zero-based just like arrays, here we're getting oranges
# Get length
print(len(fruits))
# Append to list
fruits.append('Mangos')
# Remove from list
fruits.remove('Grapes')
# Appending to list at a specific position
fruits.insert(2, 'Strawberries')
# Removing from a specific position
fruits.pop(2) # Strawberries is gone
# Reverse list
fruits.reverse()
# Sort list
fruits.sort()
# Reverse sort
fruits.sort(reverse=True)
# Change element/value
fruits[0] = 'Blueberries'
print(fruits) | true |
7b554d44b40dabeeb0833cbd69bdeb1f356301e5 | adonaifariasdev/CursoemVideo | /aula17.py | 2,365 | 4.625 | 5 | # Observe abaixo que a TUPLA é IMUTÁVEL!!!
'''num = (2, 5, 9,1)
num[2] = 3
print(num)'''
#Já na LISTA os valores do eslementos podem ser trocados, conforme abaixo:
'''num = [2, 5, 9, 1]
print(num)
num[2] = 3
print(num)'''
''''# Adicionando valores e colocando na Ordem:
num = [2, 5, 9, 1]
print(num)
num[2] = 3 # Substitui o valor do elemento por esse novo, no caso o valor 9 passará a ser 3.
#num[4] = 7 Não pode ser adicionado valores dessa forma, vai dar Traceback, pois a lista so tem 4 elementos indo de 0, 1, 2, 3
num.append(7) #Dessa forma sim será adicionado o 7
print(num)
num.sort() # Colocará na ordem
print(num)
num.sort(reverse=True) # Colocará em Ordem REVERSA
print(num)
print(f'Essa lista tem {len(num)} elementos') # o len mostra quantos elementos tem na lista
num.insert(2, 0) # na posição 2, irá colocar o 0 e aumentará a LISTA
print(num)
print(f'Essa lista tem {len(num)} elementos')
# Remoção de elementos:
num.pop() # Sem nenhum parametro irá eliminar o ultimo elemento da LISTA.
print(num)
num.pop(2) # eliminará o elemento 2 da LISTA
print(num)
num.insert(2, 2)
print(num)
num.remove(2) #Irá remover o primeiro elemento 2, procura o inicio da lista
print(num)
#num.remove(4) # o valor não está na lista, dara ero ao executar
if 4 in num: #Bastante útil
num.remove(4)
else:
print('Não achei o número 4')'''
'''valores = [] # pode ser valores = list()
valores.append(5)
valores.append(9)
valores.append(4)
#print(valores)
for v in valores: #mostrará os valores formatados -> para cada valor dentro de valores, imprima...
print(f'{v}...', end='')
print('\n')
for c, v in enumerate(valores): # Na posição da chave(c), mostra o valor(v) dentro de valores
print(f'Na posição {c} encontrei o valor {v}!')
print('Cheguei ao final da lista.')
print('\n')
for cont in range(0, 5):
valores.append((int(input('Digite um valor: '))))
#for c, v in enumerate(valores): # Na posição da chave(c), mostra o valor(v) dentro de valores
# print(f'Na posição {c} encontrei o valor {v}!')'''
a = [2, 3, 4, 7]
b = a # Observe que para fazer a cópia de a para b deve ser usado da seguinte forma b = a[:], ou seja, cira uma cópia de a para b
print(f'Lista A: {a}')
print(f'Lista B: {b}')
b[2] = 8 #Mudará nas duas listas abaixo: pois é feito uma ligação
print(f'Lista A: {a}')
print(f'Lista B: {b}')
| false |
9063134f575bc3addf0317e22d73431ff9b1c4e0 | li--paul/CareerCup-1 | /CC8_1/Fibo.py | 386 | 4.21875 | 4 | def fibo(number):
if number == 0:
return 0
elif number == 1:
return 1
elif number == 2:
return 1
else:
return(fibo(number - 1) + fibo(number - 2))
number = int(input("Please input a number for fibo calculate: "))
while number < 0:
print("Number should bigger than zero, try again.")
number = int(input("Please input a number for fibo calculate: "))
print(fibo(number)) | true |
b4129971bb0aacd1dc26dec4dacf2913caae7e02 | iampruven/learning-py-games | /tictactoe.py | 1,291 | 4.28125 | 4 | # Tic Tac Toe Game
# player1 = input("Please choose a marker: 'X' or 'O'")
# position = int(input('Please enter a number between 1-9:'))
from IPython.display import clear_output
def display_board(board):
# create the set up of the board
print(board[0]+'|'+board[1]+'|'+board[2])
print('-----')
print(board[3]+'|'+board[4]+'|'+board[5])
print('-----')
print(board[6]+'|'+board[7]+'|'+board[8])
test_board = ['#','X','O','X','O','X','O','X','O','X']
# print(display_board(test_board))
def player_input():
player1 = 'Wrong'
while player1 not in ['X', 'O']:
player1 = input('Player 1, Choose X or O as your character: ')
if player1 not in ['X', 'O']:
print('Select either X or O.')
if player1 == 'X':
player2='O'
else:
player2='X'
return (player1, player2)
print(player_input())
# can use tuple unpacking
# player1_marker, player2_marker = player_input()
def place_marker(board, marker, position):
choice = 'wrong'
while choice not in ['1', '2', '3', '4', '5', '6', '7','8','9']:
choice = input('Please select a value from 1-9, that has not been chosen yet. ')
if choice not in ['1', '2', '3', '4', '5', '6', '7','8','9']:
print('Please select a proper value.') | true |
29ceed44c99c72879e2198bcd15a3c19ef3e9dc8 | paulinatharail/python-challenge | /PyBank/main.py | 2,805 | 4.125 | 4 | import os
import csv
#path to the csv file
bank_csv = os.path.join("Resources","budget_data.csv")
#open the file
with open (bank_csv, newline="") as bankcsvfile:
#create a reader to the file
csv_reader = csv.reader(bankcsvfile, delimiter = ",")
csv_header = next(csv_reader)
#print (f"The csv header is {csv_header}")
#Variable Initialization
monthCount = 0
netTotal = 0
greatestProfitIncreaseMonth = ''
greatestProfitIncreaseAmount = 0
greatestProfitDecreaseMonth = ''
greatestProfitDecreaseAmount = 0
for row in csv_reader: #for each row in the csv file
#count #months in csv file
monthCount += 1
#Assign the profit/loss amount and month of each row to variable
RowAmount = int(row[1])
RowMonth = row[0]
#total net amount of "Profit/Losses"
netTotal = netTotal + RowAmount #2nd column => Profit/Loss column
#greatest increase in profits (date & amount)
if RowAmount > 0: #profit
if RowAmount > greatestProfitIncreaseAmount: #New higher profit
greatestProfitIncreaseAmount = RowAmount
greatestProfitIncreaseMonth = RowMonth
#greatest decrease in profits (date & amount)
else: #loss
if RowAmount < greatestProfitDecreaseAmount: #New lower profit
greatestProfitDecreaseAmount = RowAmount
greatestProfitDecreaseMonth = RowMonth
#Display results to screen
print("Financial Analysis")
print(" ----------------------------")
print(f"Total months: {monthCount}")
print(f"Total: ${netTotal}")
print(f"Greatest Increase in Profits: {greatestProfitIncreaseMonth} (${greatestProfitIncreaseAmount})")
print(f"Greatest Decrease in Profits: {greatestProfitDecreaseMonth} (${greatestProfitDecreaseAmount})")
#Write results to text file
#path to output text file
txt_output = os.path.join("Output", "PyBank_text_output.txt")
#Open file in write mode and specify variable to hold contents
with open(txt_output, 'w', newline = "") as txt_file:
#initialize txt writer
txt_file.write(f"Financial Analysis\n")
txt_file.write(f"----------------------------\n")
txt_file.write(f"Total months: {monthCount}\n")
txt_file.write(f"Total: ${netTotal}\n")
txt_file.write(f"Greatest Increase in Profits: {greatestProfitIncreaseMonth} (${greatestProfitIncreaseAmount})\n")
txt_file.write(f"Greatest Decrease in Profits: {greatestProfitDecreaseMonth} (${greatestProfitDecreaseAmount})\n")
#Open file for writing (basic write)
#file = open("PyBank_output.txt","w")
#file.write(f"Total months: {monthCount}")
#file.write(f"Total: {netTotal}")
#file.write(f"Greatest Increase in Profits: {greatestProfitIncreaseMonth} (${greatestProfitIncreaseAmount})")
#file.write(f"Greatest Decrease in Profits: {greatestProfitDecreaseMonth} (${greatestProfitDecreaseAmount})")
| true |
2b50e8a5a14bed6f10bbcd5110db1cfd91876781 | santoshvijapure/DS_with_hacktoberfest | /Data_Structures/Python/pytree.py | 1,604 | 4.40625 | 4 | # Python program to find the maximum width of
# binary tree using Level Order Traversal.
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to get the maximum width of a binary tree
def getMaxWidth(root):
maxWidth = 0
h = height(root)
# Get width of each level and compare the
# width with maximum width so far
for i in range(1,h+1):
width = getWidth(root, i)
if (width > maxWidth):
maxWidth = width
return maxWidth
# Get width of a given level
def getWidth(root,level):
if root is None:
return 0
if level == 1:
return 1
elif level > 1:
return (getWidth(root.left,level-1) +
getWidth(root.right,level-1))
# UTILITY FUNCTIONS
# Compute the "height" of a tree -- the number of
# nodes along the longest path from the root node
# down to the farthest leaf node.
def height(node):
if node is None:
return 0
else:
# compute the height of each subtree
lHeight = height(node.left)
rHeight = height(node.right)
# use the larger one
return (lHeight+1) if (lHeight > rHeight) else (rHeight+1)
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.right = Node(8)
root.right.right.left = Node(6)
root.right.right.right = Node(7)
"""
Constructed bunary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
"""
print "Maximum width is %d" %(getMaxWidth(root))
# This code is contributed by Naveen Aili
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.