blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
d7252629d420dca47b5fc4910ebc93578f60bf44 | veritakim/study_python | /study_python/day9/loop_star.py | 902 | 4.15625 | 4 | '''
계단식으로 별 출력하기
증첩 루프
for i in range(횟수) # 바깥쪽 루프
for j in range(횟수) # 안쪽 루프
가로 처리 코드
세로 처리 코드
'''
for i in range(5):
for j in range(5):
print("*", end="")
print()
for i in range(5):
for j in range(5):
print(f"j:{j}", end=" ")
print(f"i:{i}\\n")
# 별 출력하기~
for i in range(5):
for j in range(5):
if j <= i:
print("*", end="")
print()
# 별 대각선으로 찍기
for i in range(5):
for j in range(5):
if i >= 1 and j < i:
print(" ", end="")
elif i == j:
print("*", end="")
print()
# 역 삼각형으로 별 출력
for i in range(5):
for j in range(5):
if i>0 and i > j :
print(" ", end="")
else:
print("*", end="")
print()
| false |
67faf3c41b90be73374613ffe610e522d67117f8 | firewb/calculator | /calculator.py | 2,091 | 4.25 | 4 | #!/usr/bin/env python3
title = "This is a scientfic calculator created by firew shafi"
titlelen = len(title)
def intro():
'''Displays intro '''
title = "This is a scientfic calculator created by firew shafi"
titlelen = len(title)
print ('*'* titlelen)
print (title)
print ('*'* titlelen)
print(' For the equation in the following format ax2 + bx + c, Enter "abc" without any space\n')
print('Remember your inputs are case and chatacter sensitive')
print (' /\_/\ ')
print (' ( o.o ) Happy Testing ')
print (' > ^ < ')
print ('*'* titlelen)
x = 'y'
z = True
while x == 'y' or x == 'Y':
intro ()
while z == True:
equation = input ('Please, input the quadratic equation in the specified format: ')
if (equation.isdigit()):
z = False
else:
z = True
print (' /\_/\ ')
print (' ( o.o ) {0:^10}'.format('Input Error, Please Enter a value as specified above'))
print (' > ^ < ')
a = int(equation[0])
b = int(equation[1])
c = int(equation[2])
value = ((b * b) - ((4 * a)) * c)
if value > 0:
sqrt = value ** (1/2)
addup = (( -1 * b ) + value)/ (-2 * a)
subtract = ((-1 * b) - value)/ (-2 * a)
print ('*'* 10)
print ('The results are ' + '{0:3.2F} and {1:3.2F}'.format(addup, subtract))
print ('*'* 10)
elif value == 0:
print ('*'* 10)
print ('The result is ' + '{0:3.2F}'.format(addup))
print ('*'* 10)
elif value < 0:
aa = -1 * b
print ('The result is a complex number ' + '{0:3.2F} + {1:2.2F}C'.format(aa, value))
else:
print ('The solution to this equation is COMPLEX number\n ')
print ('Unfortunatly my program is not yet ready to calculate complex number')
print ('Please check back soon')
x = input ('Would you like to perform another operation? Enter "y" for yes or any other key for no: ')
print ('*'* titlelen)
print (' {0:^53} '.format('Thanks for using my first program'))
print ('*'* titlelen)
| true |
283580e4683c241cb7f1d22d6302dbafda804736 | luisvmpcl/PYTHON3 | /diccionario1.py | 1,162 | 4.40625 | 4 | #22
#diccionario = {1: "Hola", 2: "Como estas", 3: "Bien"}
#print(diccionario)
"""
diccionario = {
1:"Hola",
2:"Como estas",
3:"Bien"
}
print(diccionario)
"""
"""
diccionario = {
1:"Hola",
2:"Como estas",
3:"Bien"
}
diccionario = {} # aqui estoy redefiniendo el diccionario es decir va imprimir vacio
print(diccionario)
"""
"""
diccionario = {
1:"Hola",
2:"Como estas",
3:"Bien",
1: "y tu?" # como vemos hay 2 claves con diferentes valores ; entonces agregara al diccionario lo ultimo
}
print(diccionario)
"""
"""
diccionario = {
1:"Hola",
2:"Como estas",
3:"Bien"
}
print(diccionario[2])
"""
"""
diccionario = {
1:"Hola",
2:"Como estas",
3:"Bien"
}
resultado = diccionario.get(0,"No existe un valor asociado a esta clave o no existe esta clave")
#esta es la manera correcta de obtener un valor de un diccionario
print(resultado)
"""
diccionario = {
1:"Hola",
2:"Como estas",
3:"Bien"
}
resultado = diccionario.get(0,"No existe un valor asociado a esta clave o no existe esta clave")
diccionario[4] ="Que Fino" # asi añadimos un valor
print(diccionario)
| false |
b5b93fef86f3d5a370da9057021a9f49e5a46cd3 | nair97/https-github.com-ABE65100-AUG-2020-assignment-1-python-learning-the-basics-nair97 | /Exercise_4.2_flower.py | 2,254 | 4.59375 | 5 | # -*- coding: utf-8 -*-
"""
Spyder Editor
To draw 3 set of flowers using turtle module
by Meera - 09-01-2020
"""
import math
import turtle
#math function provides all mathematical functions
#turtle module creates images
# import the tkinter graphics library tools. Note that is was called Tkinter for
# Python 2
from tkinter import *
def polyline(obj, length, sides, angle):
for i in range(sides):
obj.fd(length)
obj.lt(angle)
#Generalizing polyline to take angle and length to draw arc for petals
def arc(t, radius, angle):
arc_length = 2 * math.pi * radius * angle / 360
sides = int(arc_length / 3) + 1
step_length = arc_length / sides
step_angle = angle / sides
#rewriting arc to use polyline
#calculating the arc length and angle for petal formation
polyline(obj = t, length = step_length, sides = sides, angle = step_angle)
def petal(t, r, angle):
for i in range(2):
arc(t, r, angle)
t.lt(180.0-angle)
#creating the petal using arc
def flower(t, n, r, angle):
"""
t: turtle
n: number of petals in the flower
r: radius of the arcs
angle: angle that subtends the arc
"""
for i in range(n):
petal(t, r, angle)
t.lt(360.0/n)
#creating flower using petal
def move_turtle(t, length):
t.pu()
t.fd(length)
t.pd()
#moving pen up and down using turtle to draw the flower
bob = turtle.Turtle()
# the following condition checks whether we are
# running as a script, in which case run the test code,
# or being imported, in which case don't.
if __name__ == '__main__':
# Indent your control code here so that it does not
# run if functions are imported by another program.
# draw the first flower
move_turtle(bob, -200)
flower(bob, 7, 60.0, 60.0)
# move to next location, draw second flower
move_turtle(bob, 200)
flower(bob, 10, 50.0, 70.0)
# move to next location, draw third flower
move_turtle(bob, 200)
flower(bob, 20, 120.0, 20.0)
bob.hideturtle()
ts = turtle.getscreen() # grab the drawing screen for later use
ts.getcanvas().postscript(file="flower.eps") # extract the image and save as a postscript file
turtle.bye() # close the drawing screen and end the turtle session
| true |
d6ffd6a761096bfe324a36cb0fca5ada4ecd9025 | ksjksjwin/practice-coding-problem | /CodeSignal/sortByHeight.py | 1,001 | 4.21875 | 4 | '''
Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the people by their heights in a non-descending order without moving the trees. People can be very tall!
Example
For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be
sortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190].
[input] array.integer a
If a[i] = -1, then the ith position is occupied by a tree. Otherwise a[i] is the height of a person standing in the ith position.
[output] array.integer
Sorted array a with all the trees untouched.
Copyright to © 2020 BrainFights Inc. All rights reserved
'''
def sortByHeight(a):
index_list = []
height_list = []
for i in range(len(a)):
if a[i] == -1:
continue
else:
index_list.append(i)
height_list.append(a[i])
height_list.sort()
i = 0
for index in index_list:
a[index] = height_list[i]
i += 1
return a
| true |
978d5951c4eda9a8af8b08a3fdd99c64586211c3 | ksjksjwin/practice-coding-problem | /LeetCode/isPalindrome.py | 919 | 4.15625 | 4 | '''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
Copyright © 2020 LeetCode
'''
class Solution:
def isPalindrome(self, s: str) -> bool:
'''
1. Remove all white spaces in s.
2. find a middle index.
3. Compare starting from the beginning and end to the middle.
4. If palindrome, return True. If not, return False.
'''
#s.replace(" ", "")
#used join(), isalnum(), lower() method
s = ''.join(char for char in s if char.isalnum()).lower()
middle = len(s) // 2
for i in range(middle):
if s[i] != s[-1-i]:
return False
return True
| true |
ab5255c66430947348c194e9278a7e7056b41861 | benblaut/cse491-numberz | /fib_iter/example.py | 286 | 4.46875 | 4 | import fib
for n, i in zip(range(3), fib.fib()):
print i
# additional questions to address:
# - what the heck do 'zip' and 'range' do, and why are they there?
# "zip" iterates over two ranges, and "range" denotes a range from 0 to the number in parentheses (0-3, so a range of 4)
| true |
b7f5322889f87f3496af7cefced9db2bad56e168 | veena863/python-practice-01 | /practice02.py | 772 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[10]:
#Numbers
#1 Integers: Any plane digit is a integer
x=2;y=3;z=4
print(x,y,z)
#Advanced approach of assignment operator is
x,y,z=2,3,4
print(x,y,z)
# In[12]:
#2 Float:a number with a decimal number
x=1.2
y=2.2
print(x+y)
# In[15]:
#3 Constant:variable whose is constant throughtout the program
#Constant is variable is declared in Capital letters
MAX_CONN=100
print(MAX_CONN)
# In[26]:
#Introduction to collection data types
#1 List : List is a mutable datatype which means we can modify the datatype
#List is defined in[]
fruits=['apple','mango','banana','orange']
print(fruits)
print(fruits[1].title())
fruits[1]='pineapple'#to change the value of certain we can refer the index
print(fruits[1].upper())
| true |
4cb827b971c2e9324355e96b1a3e838d349e57bb | ronl27/Python | /scores.py | 819 | 4.28125 | 4 | # Scores and Grades
# Write a function that generates ten scores between 60 and 100. Each time a score is generated, your function should display what the grade is for a particular score. Here is the grade table:
#
# Score: 60 - 69; Grade - D
# Score: 70 - 79; Grade - C
# Score: 80 - 89; Grade - B
# Score: 90 - 100; Grade - A
def grades():
count = 1
while count <= 10:
import random
num = random.randint(60,100)
if num < 70 and num> 60:
print "Total", num , ":Your grade is a D"
if num < 80 and num > 70:
print "Total", num, ":Your grade is a C"
if num < 90 and num > 80:
print "Total", num , ":Your grade is a B"
if num < 100 and num > 90:
print "Total", num , ":Your grade is a A"
count +=1
grades()
| true |
1f33bddde1ca44bda6c8e9643f836cf3fbc130d4 | voidbert/PyTacToe | /CommentRemover.py | 2,016 | 4.59375 | 5 | #A file that removes comments in Python scripts. This is useful to reduce the
#size of the game file to save space on the calculator. Empty lines are also
#removed but comments after code aren't. Example:
#print("Hello, world") #This comment isn't removed
#Imported the needed sys module
import sys
#The function that writes the help message and informs the user about the usage
#of this script
def PrintHelpMessage():
print("Script usage:")
print("Use \"python\" on Windows and \"python3\" on Linux")
print("python3 CommentRemover.py [script name] [output file]")
#Check if the number of command-line arguments is right. Two arguments are
#expected (plus one because the python script name is in the arguments).
if len(sys.argv) != 3:
#If there are two arguments and the second one is "--help", show the
#message that shows how to use this script and exit the script
if len(sys.argv) == 2 and sys.argv[1] == "--help":
PrintHelpMessage()
exit()
else:
#The number of arguments is wrong. Show the help message and exit the
#program.
print("Invalid script usage\n")
PrintHelpMessage()
exit()
#Try to open the input file
lines = []
try:
f = open(sys.argv[1], "r")
#Read every line of the file
lines = f.readlines()
#Close the file
f.close()
except:
#Error opening the input file. Warn the user and exit the program.
print("Error opening the input file. Aborting . . .")
exit()
#Try to open the output file to write to it
try:
f = open(sys.argv[2], "w")
except:
#Failed to open the output file. Warn the use and exit the script.
print("Error opening the output file. Aborting . . .")
exit()
#Remove he comments for every line in the file
for i in range(len(lines)):
#Remove the spaces and tabs in the beginning and end of the line
t = lines[i].strip()
#If the line isn't empty and the first character after the spaces and tabs
#isn't a "#" (this line is not a comment), add this line to the file
if len(t) >= 1:
if t[0] != "#":
f.write(lines[i])
#Close the file
f.close()
| true |
2ab7dcde7fbf76a679aabb0876d9407a42ad53af | jalaldotmy/TTTK2053-Module5 | /Fundamentals/Input and Output.py | 2,254 | 4.1875 | 4 | #Task 1: Run the script and explain the implementation
## Break a name into two parts -- the last name and the first names.
fullName = input("Enter a full name: ")
n = fullName.rfind(" ") # index of the space preceding the last name
# Display the desired information.
print("Last name:", fullName[n+1:]) #n+1 will find the last space and using counting space until end and will take all word after that
print("First name(s):", fullName[:n]) #word will taken from start untul last space found
#Task 2: Run the script and Explain the purpose of escape sequences used in the script
## Demonstrate use of escape sequences.
print("01234567890123456")
print("a\tb\tc") #Defaul tab size is 8
print("a\tb\tc".expandtabs(5)) #5 tab size
print("Nudge, \tnudge, \nwink, \twink.".expandtabs(11)) #11 tab size
#The expandtabs() method returns a copy of string with all tab characters '\t' replaced with whitespace characters until the next multiple of tabsize parameter.
#The expandtabs() takes an integer tabsize argument. The default tabsize is 8.
#Task 3: Run the script and elaborate the use of sep= in displaying output
# Demonstrate justificarion of output.
print("0123456789012345678901234567")
print("Rank".ljust(5), "Player".ljust(20), "HR".rjust(3), sep="")
print('1'.center(5), "Barry Bonds".ljust(20), "762".rjust(3), sep="")
print('2'.center(5), "Hank Aaron".ljust(20), "755".rjust(3), sep="")
print('3'.center(5), "Babe Ruth".ljust(20), "714".rjust(3), sep="")
#The sep separator is used between the values. It defaults into a space character.
#Task 4: Run the script and describe the formatting applied in the script
#Demonstrate use of the format method.
print("The area of {0:s} is {1:,d} square miles.".format("Texas", 268820))
str1 = "The population of {0:s} is {1:.2%} of the U.S. population."
print(str1.format("Texas", 26448000 / 309000000))
#The area of Texas is 268,820 square miles.
#The population of Texas is 8.56% of the U.S. population.
#The built-in format() method returns a formatted representation of the given value controlled by the format specifier.
#{0:s} first string (s) in format() located
#{1:,d} second with decimal (d) in format() located
#{1:.2%} second with .2 float number and % at the end
| true |
5bbbc0834d562b02263187aef04468dfff4bfe44 | AnaMaghear/Python-Beginner | /For.py | 670 | 4.125 | 4 | for letter in "casa": # ia fiecare element de dupa in
print(letter)
friends =["Maris","Ioana","Carla"]
for friend in friends:
print(friend)
print("\n")
for i in range(2, 7): # range i>=2 i<3
print(i)
print("\n")
for i in range(len(friends)): # lungime lista
print(friends[i])
print("\n")
for i in range(5):
if i==0:
print("primul")
n= int(input("n="))
for i in range(n): # range i<n
print(i)
print("\n")
# Functie exponetiala
def exponent (a , b):
exp=1
for i in range(b):
exp=exp*a
return exp
b= input()
e=input()
print(b+ "^" + e + "=" + str(exponent(int(b),int(e))))
| false |
a91f4bfd2f64fb7edd7402f530750c361f12ccad | lmhbali16/algorithms | /ds_class/reverse_linkedlist.py | 871 | 4.1875 | 4 | '''
Given a singly linked list, we would like to traverse the
elements of the list in reverse order.
You are only allowed to use O(1) extra space,
but this time you are allowed to modify the list you are traversing.
Give an O(n) time algorithm.
'''
class Node:
value = None
next = None
def reverse_linkedlist(head):
if head.next is None:
return a
b = head.next
head.next = None
while b.next is not None:
temp = b.next
b.next = head
head = b
b = temp
b.next = head
return b
a = Node()
a.value = 9
b = Node()
b.value = 3
c = Node()
c.value = 1
d = Node()
d.value = 4
e = Node()
e.value = 8
a.next = b
b.next = c
c.next = d
d.next = e
result = a
while result is not None:
print(result.value)
result = result.next
result = reverse_linkedlist(a)
print("\nreverse\n")
while result is not None:
print(result.value)
result = result.next | true |
5f906c021b941343d19836b6febbf4bf7d43a353 | dawidsielski/Python-learning | /sites with exercises/w3resource.com/Dictionatry/ex39.py | 201 | 4.15625 | 4 | d1 = {'key1': 1, 'key2': 3, 'key3': 2}
d2 = {'key1': 1, 'key2': 2}
d1_keys = d1.keys()
d2_keys = d2.keys()
for key in d1_keys:
if key in d2_keys:
print("key " + key + " is in d1 and d2")
| false |
bc2c386c4d4ebb8faa08d36db2224fe035338871 | brettjbush/adventofcode | /2016/day02/day02_2.py | 2,952 | 4.125 | 4 | #!/usr/bin/python
"""
--- Part Two ---
You finally arrive at the bathroom (it's a several minute walk from the lobby so visitors can behold the many fancy conference rooms and water coolers on this floor) and go to punch in the code. Much to your bladder's dismay, the keypad is not at all like you imagined it. Instead, you are confronted with the result of hundreds of man-hours of bathroom-keypad-design meetings:
1
2 3 4
5 6 7 8 9
A B C
D
You still start at "5" and stop when you're at an edge, but given the same instructions as above, the outcome is very different:
You start at "5" and don't move at all (up and left are both edges), ending at 5.
Continuing from "5", you move right twice and down three times (through "6", "7", "B", "D", "D"), ending at D.
Then, from "D", you move five more times (through "D", "B", "C", "C", "B"), ending at B.
Finally, after five more moves, you end at 3.
So, given the actual keypad layout, the code would be 5DB3.
Using the same instructions in your puzzle input, what is the correct bathroom code?
"""
import sys
def clamp(x, low_bound, high_bound):
return max(low_bound, min(x, high_bound))
def main():
filename = sys.argv[1]
row_low_bound = 0
row_high_bound = 4
col_low_bound = 0
col_high_bound = 4
row = 2
col = 2
sequence = list()
file = open(filename)
contents = file.read()
print(contents)
instructions = contents.splitlines()
for instruction in instructions:
for direction in list(instruction):
if direction == 'U' :
row = clamp(row - 1, row_low_bound, row_high_bound)
col_low_bound = abs(row - 2)
col_high_bound = 4 - abs(row - 2)
elif direction == 'R':
col = clamp(col + 1, col_low_bound, col_high_bound)
row_low_bound = abs(col - 2)
row_high_bound = 4 - abs(col - 2)
elif direction == 'D':
row = clamp(row + 1, row_low_bound, row_high_bound)
col_low_bound = abs(row - 2)
col_high_bound = 4 - abs(row - 2)
else:
col = clamp(col - 1, col_low_bound, col_high_bound)
row_low_bound = abs(col - 2)
row_high_bound = 4 - abs(col - 2)
counter = 0
for num in range(0,row):
counter += 4 - abs(num - 2) - abs(num - 2) + 1
key_number = counter + 1 + col - abs(row - 2)
character = ""
if key_number < 10:
character = str(key_number)
elif key_number == 10:
character = "A"
elif key_number == 11:
character = "B"
elif key_number == 12:
character = "C"
elif key_number == 13:
character = "D"
sequence.append(character)
code = "".join(sequence)
print("The bathroom code is: " + code)
if __name__ == "__main__":
main()
| true |
3f61528984edd34b56089cb42baf1672b63b61bc | jw56578/learn-python | /lesson3_functions.py | 893 | 4.4375 | 4 | import datetime
# copy and paste the below code 3 more times and print a different name
# a function is a group of code that needs to be called multipl times
# put the code in a function called printName so you don't have to keep typing the same code over and over
# call the function in place of where the duplicate code would normally be
# make sure to create the function before you call it
print('John')
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
print('Bob')
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
# The duplicate code usually has one thing that needs to be different, in this case name
# a function handles this with arguments
# an argument is just variable that you are assigning for each function call
# add an argument to your function 'thename'
| true |
2cd6234b044d42ef4cb0b418d4918a113aa35150 | polancof1182/CTI110 | /P3LAB_PolancoDelaRosa.py | 913 | 4.15625 | 4 | # CTI-110
# P3TLAB-Debugging
# Francicso PolancoDelaRosa
# 6/21/2018
def main():
# This program takes a number grade and outputs a letter grade.
# system uses 10-point grading scale
A_score = 90
B_score = 80
C_score = 70
D_score = 60
F_score = 50
score = int(input('Enter a numeric score: 0 to 100 '))
if score > 89:
print('You made an A: ')
print('Your numeric score of',score,'is an A ')
elif score> 79:
print('You made a B: ')
print('Your numeric score of',score,'is an B ')
elif score > 69:
print('You made a C: ')
print('Your numeric score of',score,'is an C ')
elif score > 59:
print('You made a D: ')
print('Your numeric score of',score,'is an D ')
elif score > 49:
print('You made a F: ')
print('Your numeric score of',score,'is an F ')
else:
print('invalid')
# program start
main()
| true |
b3ceaba60dfe9edc7e2880f496b4af40d4de006b | luizffdemoraes/Python_1Semestre | /Exercicios/Média simples.py | 727 | 4.15625 | 4 | """
Descrição
Escreva um programa em Python3 que receba a altura de 4 pessoas, calcule e imprima a média final.
Formato de entrada
As entradas serão números reais positivos não nulos. Não deve ser impresso nenhum texto para pedir os dados de entrada.
Formato de saída
A saída devera ser formatada conforme o exemplo:
A media das alturas eh: <valor>
onde <valor> será substituído pelo resultado calculado.
OBS.: Atenção aos acentos no texto de saída.
o The Huxley não aceita caracteres acentuados mesmo nas strings
"""
a1 = float(input())
a2 = float(input())
a3 = float(input())
a4 = float(input())
media = (a1 + a2 + a3 + a4) / 4
print(f'A media das alturas eh: {media}')
| false |
d8210899c0be06b357438307e475b9ceaf5ffcaf | luizffdemoraes/Python_1Semestre | /AC/Contando múltiplos I.py | 1,343 | 4.15625 | 4 | """
Faça um programa que receba dois inteiros x e n, com x, n > 0 e x < n, e conte o número de múltplos de x menores do que n.
DICA 1: Os múltiplos de um número são obtidos multiplicando-se esse número pelos números naturais (1, 2, 3, 4, 5, ...)
DICA 2: No primeiro exemplo, os múltiplos de são: 7*1, 7*2, 7*3, 7*4, 7*5, .... --> 7, 14, 21, 28, 35, ... Sendo assim,
temos 3 múltiplos que são estritamente menores que 28, já que o quarto múltiplo é o próprio 28 (portanto = e não < ).
DICA 3: Use um laço de repetição para ir percorrendo os números inteiros e um acumulador para contar +1 para cada múltiplo encontrado,
parando quando o múltiplo da vez for igual ao número limite dado (ou seja, deve executar enquando ele for menor).
Formato de entrada
A entrada consiste em dois números inteiros x e n, nessa ordem e separados por uma quebra de linha.
Considere que:
x, n > 0
x < n
Mas não é necessário validar a entrada.
Formato de saída
A saída deve ser a expressão a seguir:
O numero <x> tem <y> multiplos menores que <n>.
Onde os termos entre < > devem ser substituídos pelos valores encontrados para cada caso.
"""
v1 = int(input())
v2 = int(input())
x = 1
while v1 * x < v2:
x = x + 1
print(f'O numero {v1} tem {x-1} multiplos menores que {v2}.')
| false |
642b969ea1602a3ec8ce277dc9c70e4ecadaf817 | TiredOfThisAll/Epam-hometsks | /task_5/task_5_ex_3.py | 978 | 4.25 | 4 | """
Create function sum_geometric_elements, determining the sum of the first elements of a decreasing geometric
progression of real numbers with a given initial element of a progression `a` and a given progression step `t`,
while the last element must be greater than a given `lim`. `an` is calculated by the formula (an+1 = an * t), 0<t<1
Function must return float and round the answer to three decimal places using round().
Check the parameter `t` and raise a ValueError if it does not satisfy the inequality 0<t<1.
`a` and `lim` must be greater than 0, otherwise raise a ValueError.
Example,
For a progression, where a1 = 100, and t = 0.5, the sum of the first elements, grater than alim = 20, equals to
100+50+25 = 175
"""
import math
def sum_geometric_elements(a, t, l):
while False:
pass
if not 0 < t < 1 or a <= 0 or l <= 0:
raise ValueError
if l == a:
return 0
return round(a*(1-t**(math.floor(math.log(l/a, t))+1))/(1-t), 3)
| true |
c1270a670156d7e931e9abd5b5b83c07d7d0cf45 | TiredOfThisAll/Epam-hometsks | /task_9/task_9_ex_2.py | 852 | 4.4375 | 4 | """
Write a function that checks whether a string is a palindrome or not.
Return 'True' if it is a palindrome, else 'False'.
Note:
Usage of reversing functions is required.
Raise ValueError in case of wrong data type
To check your implementation you can use strings from here
(https://en.wikipedia.org/wiki/Palindrome#Famous_palindromes).
"""
def is_palindrome(test_string: str) -> bool:
if not isinstance(test_string, str):
raise ValueError
index = 0
for i in reversed(test_string):
if i.isalpha() and test_string[index].isalpha():
if not i.lower() == test_string[index].lower():
return False
return True
# if test_string.lower().replace(" ", "") == test_string[::-1].lower().replace(" ", ""):
# return True
# return False
print(is_palindrome("Do geese see God")) | true |
e436a7e9095e79717698bed17619ca6c4fa45d49 | yaremych/si206-ds4 | /code.py | 1,739 | 4.3125 | 4 | # function to return the factorial of a number
import unittest
# Add comments
def factorial(num):
ans = 1
if num < 0:
return None
elif num < 2:
return ans
else:
for i in range(1, num + 1):
ans = ans * i
return ans
# function to check if the input year is a leap year or not
def check_leap_year(year):
isLeap = False
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
isLeap = True
else:
isLeap = True
return isLeap
print("factorial(0): {}".format(factorial(0)))
print("factorial(1): {}".format(factorial(1)))
print("factorial(5): {}".format(factorial(5)))
print("factorial(-3): {}".format(factorial(-3)))
print("check_leap_year(2000): {}".format(check_leap_year(2000)))
print("check_leap_year(1990): {}".format(check_leap_year(1990)))
print("check_leap_year(2012): {}".format(check_leap_year(2012)))
print("check_leap_year(2100): {}".format(check_leap_year(2100)))
print("\n\n***Starting Tests***\n\n")
class LeapYearTests(unittest.TestCase):
def test_leap_year(self):
t1 = check_leap_year(2001)
self.assertEqual(t1, False)
def test_leap_year2(self):
t1 = check_leap_year(2016)
self.assertEqual(t1, True)
def test_leap_year3(self):
t1 = check_leap_year(0)
self.assertEqual(t1, True)
class FactorialTests(unittest.TestCase):
def test_factorial1(self):
f1 = factorial(3)
self.assertEqual(f1, 6)
def test_factorial2(self):
f1 = factorial(2)
self.assertEqual(f1, 2)
def test_factorial3(self):
f1 = factorial(-100)
self.assertEqual(f1, None)
unittest.main(verbosity=2)
| false |
398087d022d701825aa8022fa074294e0b222244 | ingadis/max_int.py | /max_int.py | 1,408 | 4.375 | 4 | north_int = int(input("Number of cars travelling north: "))
south_int = int(input("Number of cars travelling south: "))
east_int = int(input("Number of cars travelling east: "))
west_int = int(input("Number of cars travelling west: "))
north_south = north_int + south_int #the sum of north and south traffic
east_west = east_int + west_int #the sum of east and west traffic
while east_west + north_south > 0: #while there is some traffic still in any lane
if north_south >= east_west: #if north_south either has more or equal traffic it starts with green light
print("Green light on N/S")
north_int -= 5
if north_int < 0:
north_int = 0
south_int -= 5
if south_int < 0:
south_int = 0
north_south = north_int + south_int #updated car count in each lane
east_west = east_int + west_int #again updated car count
else: #if the east_west has more traffic than the north_south it gets the green light
print("Green light on E/W")
east_int -= 5
if east_int < 0:
east_int = 0
west_int -= 5
if west_int < 0:
west_int = 0
north_south = north_int + south_int
east_west = east_int + west_int
else:
print("No cars waiting, the traffic jam has been solved!") | false |
d40009682eb23ccbed804a8781cf7190d2582d46 | pruppet/Portfolio | /years.py | 486 | 4.34375 | 4 | #Author: Maggie Laidlaw
#Python program to find all Sundays that are the first
#of the month between 1901 and 2000.
def loopYears():
notLeap = [3,0,3,2,3,2,3,3,2,3,2,3]
leap = [3,1,3,2,3,2,3,3,2,3,2,3]
day = 2 #Su-0,M-1,...,S-6
year = 1901
count = 0
for x in range (1901,2000):
if x%100 != 0 && x%4 == 0:
for y in leap:
day+=y
elif x%100 == 0 && x%400 == 0:
for y in leap:
day+=y
else
for y in notLeap:
day+=y
if day == 7:
count++
day = 0
print count | false |
5c375468236c672ff6aeb1782282206600108197 | dooran/Aaron-s-Rep | /main2.19.py | 2,091 | 4.34375 | 4 | #Manuel Duran 1584885
#input the number so cups of lemon juice, water and agave nectar
cups_lemon_juice = float(input('Enter amount of lemon juice (in cups):\n'))
cups_water = float(input('Enter amount of water (in cups):\n'))
cups_agave_nectar = float(input('Enter amount of agave nectar (in cups):\n'))
# input the number of servings the recipe yields
cups_serving = float(input('How many servings does this make?\n'))
# display the input values
print('\nLemonade ingredients - yields %.2f servings' %(cups_serving))
print('%.2f cup(s) lemon juice' %(cups_lemon_juice))
print('%.2f cup(s) water'%(cups_water))
print('%.2f cup(s) agave nectar'%(cups_agave_nectar))
# input the desired number of servings
cups_serving_needed = float(input('\nHow many servings would you like to make?\n'))
# calculate the amount of each ingredient needed for 1 cup
lemon_juice_for_one = cups_lemon_juice/cups_serving
water_for_one= cups_water/cups_serving
agave_nectar_for_one = cups_agave_nectar/cups_serving
# calculate the amounts of each ingredient needed for desired servings
cups_lemon_juice_needed = lemon_juice_for_one*cups_serving_needed
cups_water_needed = water_for_one*cups_serving_needed
cups_agave_nectar_needed = agave_nectar_for_one*cups_serving_needed
# display the calculated amount of ingredients
print('\nLemonade ingredients - yields %.2f servings' %(cups_serving_needed))
print('%.2f cup(s) lemon juice' %(cups_lemon_juice_needed))
print('%.2f cup(s) water'%(cups_water_needed))
print('%.2f cup(s) agave nectar'%(cups_agave_nectar_needed))
# convert the calculated amount from cups to gallons (16 cups = 1 gallon)
gallons_lemon_juice = cups_lemon_juice_needed/16
gallons_water = cups_water_needed/16
gallons_agave_nectar = cups_agave_nectar_needed/16
# display the amounts in gallons
print('\nLemonade ingredients - yields %.2f servings' %(cups_serving_needed))
print('%.2f gallon(s) lemon juice' %(gallons_lemon_juice))
print('%.2f gallon(s) water'%(gallons_water))
print('%.2f gallon(s) agave nectar'%(gallons_agave_nectar))
#end of program | true |
614c4157f947e294c7b1fd451b11517866aff7e8 | CosmoSt4r/exercism-python | /easy/prime-factors/prime_factors.py | 809 | 4.15625 | 4 | """
Solution to Prime Factors task on Exercism
https://exercism.org/tracks/python/exercises/prime-factors
"""
def is_prime(value: int) -> bool:
"""Check if value is prime"""
if value == 1:
return False
if value <= 0:
raise ValueError("Value must be greater than zero")
for i in range(2, int(value**(1/2)) + 1):
if value % i == 0:
return False
return True
def factors(value: int) -> list:
"""Get all prime factors of the given value"""
prime_factors: list = []
for i in range(2, value + 1):
if i > 2 and i % 2 == 0 or not is_prime(i):
continue
while value % i == 0:
value = int(value / i)
prime_factors.append(i)
if value == 1:
break
return prime_factors
| true |
1ff5af9c8380f4126ea35a8944e916b060a1a915 | CosmoSt4r/exercism-python | /easy/pythagorean-triplet/pythagorean_triplet.py | 499 | 4.1875 | 4 | """
Solution to Pythagorean Triplet task on Exercism
https://exercism.org/tracks/python/exercises/pythagorean-triplet
"""
def triplets_with_sum(number: int) -> list:
"""Get all pythagorean triplets which in sum give number"""
result = []
for a in range(1, number // 3):
for b in range(a + 1, (number // 3) * 2):
c = number - a - b
if a + b < c or a * a + b * b != c * c:
continue
result.append([a, b, c])
return result
| false |
82f7fdb214f3dfea2dc1741721c84ead57626c08 | fehringj/Python-Coding-Exercises | /MyQueue.py | 1,591 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 3 10:13:17 2019
@author: Jenny
"""
# Requires Stack.py
from Stack import *
new_stack = Stack()
old_stack = Stack()
class MyQueue:
"""Implementation of a queue that is comprised of two stacks"""
def size(self):
return len(new_stack) + len(old_stack)
def add(self, value):
"""Add elements to new_stack, which contains newest elements at the
top of the stack
pre: input value to add
post: return True when completed"""
new_stack.push(value)
def move_stacks(self):
"""Moves values from the new_stack to old_stack so that older values
are now on the top of the old_stack
post: new_stack is empty and old_stack has all values stored newest on
bottom to oldest on top"""
if old_stack.is_empty():
while not new_stack.is_empty():
old_stack.push(new_stack.pop())
def queue_peek(self):
"""Returns oldest item add to the stacks"""
self.move_stacks()
return old_stack.peek()
def remove(self):
"""Removes oldest value from the stacks and returns that value"""
self.move_stacks()
return old_stack.pop()
m = MyQueue()
m.add(2)
m.add(1)
m.add(3)
m.add(4)
m.add(5)
m.add(6)
new_stack.print_stack()
print(new_stack.peek())
print(m.queue_peek())
old_stack.print_stack()
print(m.size())
print(m.remove())
old_stack.print_stack() | true |
0d9a6f03bf18ad832dab8db1e8994226127167d0 | zmengle/python_learn | /day/05.py | 406 | 4.125 | 4 | # 使用dict
dict1 = {'a': 100, 'b': 10}
dict1['c'] = 1000
dict1['c'] = 10000
print(dict1)
print('f' in dict1, 'a' in dict1)
print(dict1.get('c', 0), dict1.get('g', 0))
dict1.pop('c')
print(dict1)
# dict查询快 但是耗内存
# list查询慢 不耗内存
# 使用set(list) key唯一,set和dict的唯一区别仅在于没有存储对应的value
set1 = ([1, 2, 4])
print(set1)
set1.__add__(12)
| false |
7a1a837e9ecd484294d547d4aff4676242d04c2a | AprajitaChhawi/365DaysOfCode.JANUARY | /Day 14 merge two sorted list.py | 2,187 | 4.125 | 4 | #User function Template for python3
'''
Function to merge two sorted lists in one
using constant space.
Function Arguments: head_a and head_b (head reference of both the sorted lists)
Return Type: head of the obtained list after merger.
{
# Node Class
class Node:
def __init__(self, data): # data -> value stored in node
self.data = data
self.next = None
}
'''
def sortedMerge(head_A, head_B):
temp=Node(0)
pointer=temp
while(head_A and head_B):
if head_A.data<=head_B.data:
pointer.next=head_A
head_A=head_A.next
else:
pointer.next=head_B
head_B=head_B.next
pointer=pointer.next
if head_A==None:
pointer.next=head_B
else:
pointer.next=head_A
return temp.next
# code here
#{
# Driver Code Starts
#Initial Template for Python 3
# Node Class
class Node:
def __init__(self, data): # data -> value stored in node
self.data = data
self.next = None
# Linked List Class
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
# creates a new node with given value and appends it at the end of the linked list
def append(self, new_value):
new_node = Node(new_value)
if self.head is None:
self.head = new_node
self.tail = new_node
return
self.tail.next = new_node
self.tail = new_node
# prints the elements of linked list
def printList(n):
while n is not None:
print(n.data, end=' ')
n = n.next
print()
if __name__ == '__main__':
for _ in range(int(input())):
n,m = map(int, input().strip().split())
a = LinkedList() # create a new linked list 'a'.
b = LinkedList() # create a new linked list 'b'.
nodes_a = list(map(int, input().strip().split()))
nodes_b = list(map(int, input().strip().split()))
for x in nodes_a:
a.append(x)
for x in nodes_b:
b.append(x)
printList(sortedMerge(a.head,b.head))
# } Driver Code Ends
| true |
9464a8f9fdeb1836c92d2e2d3d55bb2e55b669da | AprajitaChhawi/365DaysOfCode.JANUARY | /Day 21 reverse a string.py | 370 | 4.15625 | 4 | #User function Template for python3
def reverseWord(s):
s1=""
for i in range(0,len(s)):
s1+=s[len(s)-i-1]
return s1
#your code here
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == "__main__":
t = int(input())
while(t>0):
s = input()
print(reverseWord(s))
t = t-1
# } Driver Code Ends
| false |
6dc622886e68061531b5f8a2fbd6a9367a1af767 | Saurabh9520/python-programs | /largest palindr.py | 1,282 | 4.25 | 4 | def isPalindrome(n):
# Find the appropriate divisor
# to extract the leading digit
divisor = 1
while (int(n / divisor) >= 10):
divisor *= 10
while (n != 0):
leading = int(n / divisor)
trailing = n % 10
# If first and last digits are
# not same then return false
if (leading != trailing):
return False
# Removing the leading and trailing
# digits from the number
n = int((n % divisor) / 10)
# Reducing divisor by a factor
# of 2 as 2 digits are dropped
divisor = int(divisor / 100)
return True
# Function to find the largest
# palindromic number
def largestPalindrome(A, n):
currentMax = -1
for i in range(0, n, 1):
# If a palindrome larger than
# the currentMax is found
if (A[i] > currentMax and isPalindrome(A[i])):
currentMax = A[i]
# Return the largest palindromic
# number from the array
return currentMax
# Driver Code
if __name__ == '__main__':
A = [1, 232, 54545, 999991]
n = len(A)
# print required answer
print(largestPalindrome(A, n))
| true |
4cd4d0c0e2af76e507dbf7ea9c9a967ea9122a18 | isaacMullen/Class-Projects | /my first game..py | 562 | 4.21875 | 4 | x = 67
print ('''Welcome to my game... You will be asked to choose a number between
1 and 100, The computer has also chosen a number between 1 and 100. The object
of this game is to eventually reach the same number as the computer. using
simple information you will be provided with in the form of <,>,=.''')
num1 = int(input('choose a number'))
print('your number is',num1)
while (num1 != x):
if (num1 < x):
print('more')
if (num1 > x):
print('less')
num1 = int(input('choose a number'))
print('YOU WON')
| true |
dc625928f7ee963d49758b929564870304259e1c | AshwinShanbhag/Coursera_PythonCode | /Coursera Assignment 8.4_new.py | 692 | 4.46875 | 4 | """8.4) Open the file 'romeo.txt' and read it line by line. For each line, split the line into a list of words using the split() method.
The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append
it to the list. When the program completes, sort and print the resulting words in alphabetical order.
You can download the sample data at http://www.py4e.com/code3/romeo.txt """
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
word = line.split()
for nw in word: # checks each word in line
if nw not in lst:
lst.append(nw)
print(sorted(lst))
| true |
16cb42d79ada5f327ca8ff3bb0e840028dc4d699 | DishenMakwana/Python-DS | /Python Data structures/stack2.py | 1,003 | 4.1875 | 4 | from collections import deque
class Stack():
def __init__(self):
self.stack = deque()
def push(self, value):
self.stack.append(value)
def pop(self):
if self.empty():
return 'Stack is empty'
return self.stack.pop()
def top(self):
if self.empty():
return 'Stack is empty'
return self.stack[-1]
def empty(self):
if len(self.stack) <= 0:
return True
return False
def display(self):
return self.stack
def size(self):
return self.size
stack = Stack()
# Operation results when the stack is empty
print(stack.top())
print(stack.pop())
print(stack.empty())
# Pushing values to stack
stack.push(5)
stack.push(8)
stack.push(1)
print('Current stack:',stack.display())
print('Value popped from stack :',stack.pop())
print('Current stack:',stack.display())
print('Value on top of stack:',stack.top())
print('Current stack:',stack.display())
print(stack.empty()) | true |
1e0e064580cae963a11da5e4ab8c147cba83e53e | JaiJun/Codewar | /8 kyu/Is n divisible by x and y.py | 551 | 4.25 | 4 | """
Create a function that checks if a number n is divisible by two numbers x AND y.
All inputs are positive, non-zero digits.
I think best solution:
def is_divisible(n,x,y):
return n % x == 0 and n % y == 0
https://www.codewars.com/kata/5545f109004975ea66000086
"""
def is_divisible(n, x, y):
if n % x == 0 and n % y == 0:
print("True")
return True
else:
print("False")
return False
if __name__ == '__main__':
n = 3
x = 1
y = 3
is_divisible(n, x, y)
| true |
095443c6aa00d7a1cf26144fef51e0e6b3d368da | JaiJun/Codewar | /7 kyu/Unlucky Days.py | 1,008 | 4.21875 | 4 | """
Friday 13th or Black Friday is considered as unlucky day.
Calculate how many unlucky days are in the given year.
Find the number of Friday 13th in the given year.
Input: Year as an integer.
Output: Number of Black Fridays in the year as an integer.
Examples:
unluckyDays(2015) == 3
unluckyDays(1986) == 1
I think best solution:
from datetime import date
def unlucky_days(year):
return sum(date(year, m, 13).weekday() == 4 for m in range(1, 13))
https://www.codewars.com/kata/56eb0be52caf798c630013c0
"""
from datetime import date, timedelta
def unlucky_days(year):
d1 = date(year, 1, 1)
d2 = date(year, 12, 31)
delta = d2 - d1
count = 0
for i in range(delta.days + 1):
nowdate = d1 + timedelta(days=i)
if nowdate.day == 13 and nowdate.weekday() == 4:
print(nowdate)
count += 1
return count
if __name__ == '__main__':
input = 2015
unlucky_days(input)
| true |
5d5030661faa2593eae476df9f7cbb4d1991ccd5 | JaiJun/Codewar | /7 kyu/Mr Martingale.py | 2,349 | 4.28125 | 4 | """
You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the Martingale strategy is.
You will be given a starting cash balance and an array of binary digits to represent a win or a loss as you play: 0 for loss and 1 for win.
You should create a function martingale to return the balance after playing all rounds.
You start with a stake of 100 dollars(unit of cash). If you lose a round, you lose the stake placed on that round and double the stake for your next bet. When you win, you win 100% of the stake and revert back to staking 100 dollars on your next bet.
Example:
martingale(1000, [1, 1, 0, 0, 1]) === 1300
you win your 1st round: gain $100, balance = 1100
win 2nd round: gain $100, balance = 1200
lose 3rd round: lose $100 dollars, balance = 1100
double stake for 4th round and lost: staked $200, lose $200, balance = 900
double stake for 5th round and won: staked $400 won $400, balance = 1300
NOTE: Your balance is allowed to go below 0 (debt) :(
"""
def martingale(bank, outcomes):
Bet = 100
origalmoney = 0
for i in range(len(outcomes)):
print("Round %d-> %d Bet:%d"%(i, outcomes[i], Bet))
# print("Current Bet->", Bet)
if outcomes[i] ==0:
origalmoney = origalmoney-Bet
# print("Loss(Twice) Money", origalmoney)
Bet=Bet*2
# print("Loss(Twice) Bet",Bet)
elif outcomes[i]==1:
origalmoney = origalmoney +Bet
# print("Win Money", origalmoney)
Bet =100
# print("Win Bet", origalmoney)
else:
origalmoney=0
# print("===============================")
print("Total Money", bank+origalmoney)
TotalMoney =bank+origalmoney
# outcomes=bank+origalmoney
return TotalMoney
if __name__=='__main__':
basic_tests = [
[500, [], 500],
[1000, [1, 1, 0, 0, 1], 1300],
[0, [0, 0, 0, 0, 1, 0, 0, ], -200],
[5100, [1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], 5600],
[-500, [1, 1, 0, 1, 0, 1, 0], -200]
]
for bankroll, rounds, output in basic_tests:
# print("Backrool",bankroll)
# print("Rounds",len(rounds))
# print("Output",output)
print(martingale(bankroll, rounds),output) | true |
bb16544fcbd25a20e61072b7faffd6ac0f6ac114 | JaiJun/Codewar | /8 kyu/Is he gonna survive.py | 1,260 | 4.15625 | 4 | """
A hero is on his way to the castle to complete his mission.
However, he's been told that the castle is surrounded with a couple of powerful dragons!
each dragon takes 2 bullets to be defeated, our hero has no idea how many bullets he should carry.
Assuming he's gonna grab a specific given number of bullets and move forward to fight another specific given number of dragons, will he survive?
Return True if yes, False otherwise :)
I think best solution:
def hero(bullets, dragons):
'''
Ascertains if hero can survive
Parameters:
bullets: (int) - number of bullets hero has
dragons: (int) - number of dragons
Returns:
True (Survive) or False (Hero gets killed)
'''
if bullets >= 2*dragons:
return True
elif bullets < 2*dragons:
return False
https://www.codewars.com/kata/59ca8246d751df55cc00014c
"""
def hero(bullets, dragons):
if bullets/2 >= float(dragons):
print("True")
return True
else:
print("False")
return False
if __name__ == '__main__':
bullets = 10
dragons = 5
hero(bullets, dragons)
| true |
1fa3180c91f2cd3b0d8114ff03bab5b75b71358b | JaiJun/Codewar | /7 kyu/Reverse a Number.py | 1,002 | 4.375 | 4 | """
Given a number, write a function to output its reverse digits. (e.g. given 123 the answer is 321)
Numbers should preserve their sign; i.e. a negative number should still be negative when reversed.
Examples
123 -> 321
-456 -> -654
1000 -> 1
I think best solution:
def reverseNumber(n):
if n >= 0:
return int(str(n)[::-1])
else:
return int(str(n).strip('-')[::-1])*-1
"""
def reverse_number(n):
rev_number = 0
if n < 0:
n = n * -1
while (n > 0):
remainder = n % 10
rev_number = (rev_number * 10) + remainder
n = n // 10
return (rev_number * -1)
else:
while (n > 0):
remainder = n % 10
rev_number = (rev_number * 10) + remainder
n = n // 10
return rev_number
print("The reverse number is : {}".format(rev_number))
if __name__ == '__main__':
input = 321
reverse_number(input)
| true |
a96a4a83a1cf28935c8bff11bbe2e4b3899687fc | JaiJun/Codewar | /7 kyu/Disemvowel Trolls.py | 1,149 | 4.375 | 4 | """
Trolls are attacking your comment section!
A common way to deal with this situation is to remove all of the vowels from the trolls' comments, neutralizing the threat.
Your task is to write a function that takes a string and return a new string with all vowels removed.
For example:
the string "This website is for losers LOL!" would become "Ths wbst s fr lsrs LL!".
Note: for this kata y isn't considered a vowel.
What is English vowels-> a、e、i、o、u
"""
def disemvowel(string):
delword =["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
replaceword = ""
detectword = list(string)
combineword = []
for i in range(len(detectword)):
print(detectword[i])
for j in range(len(delword)):
if detectword[i] == delword[j]:
detectword[i] =replaceword
print("Replace!")
else:
print("Nothing Replace")
combineword.append(detectword[i])
Result = "".join(combineword)
print(Result)
return Result
if __name__=='__main__':
input = "This website is for losers LOL!"
disemvowel(input) | true |
776ef7eb8dcecc8c86da50a56cc5d218e6140d9d | JaiJun/Codewar | /7 kyu/Simple string matching.py | 2,128 | 4.3125 | 4 | """
You will be given two strings a and b consisting of lower case letters,
but a will have at most one asterix character.
The asterix (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase letters.
No other character of string a can be replaced.
If it is possible to replace the asterix in a to obtain string b, then string b matches the pattern.
If the string matches, return true else false.
For example:
solve("code*s","codewars") = true, because we can replace the asterix(*) with "war" to match the second string.
solve("codewar*s","codewars") = true, because we can replace the asterix(*) with "" to match the second string.
solve("codewars","codewars") = true, because the strings already match.
solve("a","b") = false
Solution key> fnmatch
I think best solution:
from fnmatch import fnmatch
def solve(a, b):
print(fnmatch(b, a))
return fnmatch(b, a)
https://www.codewars.com/kata/5bc052f93f43de7054000188
"""
def solve(a, b):
if "*" in a:
print("a>", a)
print("b>", b)
element = a.split('*')
left = len(element[0])
right = len(element[1])
print(b[:left], b[-right:])
if len(a.replace('*', "")) > len(b):
print("More >b", False)
return False
else:
if element[0] == b[:left] and element[1] == b[-right:]:
print("1-True")
return True
elif element[0] == "" and element[1] == b[-right:]:
print("2-True")
return True
elif element[1] == "" and element[0] == b[:left]:
print("3-True")
return True
else:
print("4-False")
return False
else:
if len(a) == len(b):
print("Not Contain * >", True)
return True
else:
print("Not Contain * >", False)
return False
if __name__ == '__main__':
a = "code*warrior"
b = "codewars"
solve(a, b)
| true |
741f0a0e4797077a17a64418ce9175a9ba85ddac | varunpandey0502/skyfi_labs_ml_workshop | /hands-on_introduction/2 - build_your_first_machine_learning_model - exercise.py | 1,853 | 4.1875 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
#Import the train.csv file
sydney_file_path =
home_data =
#Step 1 - Specify the prediction target
#Select the target variable, which corresponds to the sales price. Save this to a new variable called `y`. You'll need to print a list of the columns to find the name of the column you need.
# print the list of columns in the dataset to find the name of the prediction target
y =
#Step 2: Create X
#Now you will create a DataFrame called `X` holding the predictive features.
#Since you want only some columns from the original data, you'll first create a list with the names of the columns you want in `X`.
#
#You'll use just the following columns in the list (you can copy and paste the whole list to save some typing, though you'll still need to add quotes):
# * LotArea
# * YearBuilt
# * 1stFlrSF
# * 2ndFlrSF
# * FullBath
# * BedroomAbvGr
# * TotRmsAbvGrd
#After you've created that list of features, use it to create the DataFrame that you'll use to fit the model.
## Create the list of features below
feature_names =
# select data corresponding to features in feature_names
X =
# Review data
# print description or statistics from X
# print the top few lines
print()
#Step 3: Specify and Fit Model
#Create a `DecisionTreeRegressor` and save it as home_model. Ensure you've done the relevant import from sklearn to run this command.
home_model =
#Then fit the model you just created using the data in `X` and `y` that you saved above.
home_model.fit(X,y)
#Step 4: Make Predictions
predictions =
print(predictions)
#Think About Your Results
#Use the `head` method to compare the top few predictions to the actual home values (in `y`) for those same homes. Anything surprising?
#You'll understand why this happened if you keep going.
| true |
29d82ea0cd907107818cbf803a13fc185e16d50d | ishitadate/nsfPython | /Week 9/w9_homework.py | 498 | 4.125 | 4 | print("problem 1")
# write a simple example to show how 3 functions of your choice from the math and random libraries work.
print("problem 2")
# create something that takes command-line imput, does some mathematical calculations with the
# number inputted and some other random numbers, and returns something back
print("problem 3")
# generate a random number
# have the user guess the number until they're right
# for more information on everything built-in: https://docs.python.org/3/library/ | true |
dffccbd116d9b81b2bd5aa3de049ec7ebef46c56 | kavyareddi/level1_python | /program_4_class_inheritance.py | 1,015 | 4.125 | 4 | #program on class inheritance
#input : defining classe subclass and thier attributes
class Person:
# initializing the variables
# defining constructor
def __init__(self, personName, personAge):
self.name = personName
self.age = personAge
# defining class methods
def showName(self):
print(self.name)
def showAge(self):
print(self.age)
# definition of subclass starts here
class Student(Person):
def __init__(self, studentName, studentAge, studentId):
Person.__init__(self, studentName,studentAge)
self.studentId = studentId
def getId(self):
return self.studentId # returns the value of student id
# end of subclass definition
# Create an object of the superclass
person1 = Person("kavya", 23)
# call member methods of the objects
person1.showAge()
# Create an object of the subclass
student1 = Student("karthik", 22, 102)
print(student1.getId())
student1.showName() | true |
f8e16231cedbdf1526e2fa2c5ab4aa60f760821c | Nihaoaung/git-test | /for-loop.py | 291 | 4.125 | 4 | names=['aung aung','mg mg','su su','aye aye']
for name in names:
if name=='mg mg':
print(f'{name} is a tour guide')
break
else :
print(f'{name} is a forgein')
fruits=['apple','mango','orange','pineapple']
for fruit in fruits :
print(f'{fruit} is a fruit')
| false |
e3bb9036ba091d5a066d664368e51b13f0ab7252 | KenNyakundi01/Password-Locker | /user.py | 1,313 | 4.3125 | 4 | class User:
'''
This is the user class where the user is persisted to disk in a plain file
'''
user_list = [] # empty user list
def __init__(self, username, password):
'''
__init__ method that helps us define properties for our objects
Args:
username: New user's username
password: New user's password
'''
self.username = username
self.password = password
def save_user(self):
'''
save_user method: saves user to user list as an append
'''
User.user_list.append(self)
def delete_user(self):
'''
delete_user method: deletes the last user saved to the user_list
'''
User.user_list.remove(self)
@classmethod
def find_by_name(cls, name):
'''
find_by_name class method: Method that takes in a name and returns a user with that name
'''
for user in cls.user_list:
if user.username == name:
return user
@classmethod
def user_exist(cls, name):
'''
Method that checks if a user exists from the user list
'''
for user in cls.user_list:
if user.username == name:
return True
return False
| true |
56bea18d5d3dfe7a2bc3e339cf5bad8577daa060 | agatanyc/section_normalization | /mysolution/matching.py | 2,971 | 4.25 | 4 | #!/usr/bin/env python
from string import ascii_uppercase
# some sections may have numerical ROW names (1-10) and some may have alphanumeric row names (A-Z, AA-DD). Your code should support both
def extract_integer(text):
"""Filters non-digits from text, and parses the result as an integer."""
try:
digits = ''.join(c for c in text if c.isdigit())
except Exception:
pass
return int(digits)
def extract_integer_old(text):
"""Filters non-digits from text, and parses the result as an integer."""
digits = ''.join(c for c in text if c.isdigit())
if not digits:
raise Exception("text is not numeric")
return int(digits)
def parse_row_name(text):
if not text:
raise Exception("row number text is empty")
elif all(c.isdigit() for c in text):
return int(text)
elif len(text) < 3 and all(c in ascii_uppercase for c in text):
first = ord(text[0]) - ord(ascii_uppercase[0]) + 1
# checking only for AA, BB, CC not AB, AC
# if we have two characters we run out of letters e.i the Row is CC:
# first = ord(C) - ord(ascii_uppercase[0]) + 1
# first = 67 - 65 + 1
# CC = len(ascii_uppercase) + first
# CC = 26 + 3 => Row 29
return first if len(text) < 2 else len(ascii_uppercase) + first
else:
raise Exception("bad row number: " + text)
def extract_row_name(text):
row_names = ['AA', 'AB', 'AC', 'AD',
'BA', 'BB', 'BC', 'BD',
'CA', 'CB', 'CC', 'CD',
'DA', 'DB', 'DC', 'DD'
]
if not text:
raise Exception("row number text is empty")
elif all(c.isdigit() for c in text):
return int(text)
elif len(text) < 3 and all(c in ascii_uppercase for c in text):
first = ord(text[0]) - ord(ascii_uppercase[0]) + 1
return first if len(text) < 2 else len(ascii_uppercase) + row_names.index(text) + 1
else:
raise Exception("bad row number: " + text)
def get_upper(text):
upper = (c.upper for c in text if c.isalpha())
return upper
print 'XXXXX'
for s in get_upper('aaaa1'):
print str(s)
assert extract_integer('Empire Suite 241') == 241
assert extract_integer('Empire Suite 2a41') == 241
assert parse_row_name('1') == 1
assert parse_row_name('10') == 10
assert parse_row_name('A') == 1
assert parse_row_name('DD') == 30
assert extract_row_name('AA') == 27
assert extract_row_name('AD') == 30
"""
| section | row | n_section_id | n_row_id | valid |
|-------------------|-----|--------------|----------|-------|
| Section 432 | 1 | 215 | 0 | TRUE |
| Section 432 | 2 | 215 | 1 | TRUE |
| Section 432 | 99 | 215 | | FALSE |
| Promenade Box 432 | 1 | 215 | 0 | TRUE |
| sdlkjsdflksjdf | 1 | | | FALSE |
| 432 | 1-5 | 215 | | FALSE |
"""
| true |
168dc53740de4847cd82a81c34317b4373639a49 | cuauhtemocmartinez/python_projects | /Lab 1/CMartinezLab1.py | 1,528 | 4.3125 | 4 | #################################################################
# Program Header
# Course: CIS 117 Python Programming
# Name: Cuauhtemoc Alex Martinez
# Description: Lab 1
# Application: Hello World and infomation
# Topics: Using Python3 Interpreter and capturing program output
# Development Environment: Windows 10
# Version: Python 3.7.4
# Solution File: CMartinezLab1
# Date: 01/26/20
#################################################################
#Program Source Statements
print("Hello World!")
name=input("What is your last name? ")
csm_id=input("What is your CSM ID#? ")
print("Your last " + name + " and your CSM ID# " + csm_id + " has been saved.")
last_day=input("What is the date to drop this class with a 'W'? ")
final_exam=input("What is the date of the Final Exam? ")
source_code=input("What is the Source Code Format for this class? ")
camel_case=input("What is an example of Camel Case? ")
mnemonic_identifiers=input("What are Mnemonic Identifiers? ")
# Program Output
"""
Hello World!
What is your last name? Martinez
What is your CSM ID#? G01010673
Your last Martinez and your CSM ID# G01010673 has been saved.
What is the date to drop this class with a 'W'? April 23
What is the date of the Final Exam? May 19
What is the Source Code Format for this class? Source code lines should not exceed 79 characters.
What is an example of Camel Case? CamelCase
What are Mnemonic Identifiers? A name that will be used for a single purpose and should not be used for any other purpose.
"""
| true |
5a6b854e94c511821e21f7e04e39c28a112f1d96 | plushies/py | /rps.py | 1,477 | 4.125 | 4 | from random import randint
cont = 'memes'
pscore = 0
cscore = 0
print('ROCK PAPER SCISSORS')
print('enter \'stop\' to end the game')
while cont == 'memes':
player = input('rock, paper, or scissors? ')
while player != 'rock' and player != 'paper' and player != 'scissors' and player != 'stop':
player = input('you must enter a valid choice! ')
if player == 'stop':
cont = 'stop'
num = randint(1,3)
if num == 1:
comp = 'rock'
elif num == 2:
comp = 'paper'
else:
comp = 'scissors'
if player != 'stop':
print(player, 'vs', comp)
if player == 'rock':
if comp == 'paper':
print('computer wins!')
cscore = cscore + 1
elif comp == 'scissors':
print('you win!')
pscore = pscore + 1
if player == 'paper':
if comp == 'scissors':
print('computer wins!')
cscore = cscore + 1
elif comp == 'rock':
print('you win!')
pscore = pscore + 1
if player == 'scissors':
if comp == 'rock':
print('computer wins!')
cscore = cscore + 1
elif comp == 'paper':
print('you win!')
pscore = pscore + 1
if player == comp:
print('it\'s a draw!')
print('FINAL SCORES')
print('you:', pscore, 'computer:', cscore)
print('goodbye :)')
| true |
59593f705c26af60ea691ed9de128691f39ac493 | bmandiya308/python_trunk | /pallendron.py | 226 | 4.28125 | 4 | def reversed(s):
rev = s[::-1]
return rev
input_str = str(input("Please enter string to check pallendrom"))
rev = reversed(input_str)
if(rev == input_str):
print("pallendrom")
else:
print("Not a pallendromj")
| true |
0c4c890525138446edcd5578cd431c6d289d92b4 | bmandiya308/python_trunk | /dict_order_dic.py | 419 | 4.375 | 4 | # A Python program to demonstrate working of OrderedDict
from collections import OrderedDict
import string
print("This is a Dict:\n")
dict_1 =list(range(26))
dict_2 = list(string.ascii_lowercase)
d = {dict_1[i]:dict_2[i] for i in range(len(dict_1))}
for key, value in d.items():
print(key,value)
print("\nThis is an Ordered Dict:\n")
od = OrderedDict(d)
for key, value in od.items():
print(key, value)
| true |
3647001cacf70f7b0d550fb80e75ee2d5f114910 | RohanDeySarkar/DSA | /sorting_algo/2_insertion_sort/insertionSort.py | 370 | 4.15625 | 4 | def insertionSort(arr):
for i in range(1, len(arr)):
currentIdx = i
while currentIdx > 0 and arr[currentIdx] < arr[currentIdx - 1]:
swap(arr, currentIdx, currentIdx - 1)
currentIdx -= 1
return arr
def swap(arr, idx1, idx2):
arr[idx1], arr[idx2] = arr[idx2], arr[idx1]
arr = [8,5,2,9,5,6,3]
print(insertionSort(arr))
| true |
6151b44413b5c121ae437edcae4132ad7cf10424 | requestriya/Python_Basics | /basic27.py | 277 | 4.15625 | 4 | # wap to sum of three numbers given integers. however, if two values are equal sum will be zero
def sum_nums(n1, n2, n3):
if (n1 == n2 or n1 == n3 or n2 == n3):
sum = 0
else:
sum = n1+n2+n3
return sum
print(sum_nums(2,4,5))
print(sum_nums(2,2,2)) | false |
c9549a896f442252f998a5a784da381dccdee559 | requestriya/Python_Basics | /basic60.py | 357 | 4.59375 | 5 | # Write a Python program to check whether a string is numeric.
# 1.
val = '12345'
count = 0
for i in val:
if (ord(i)>=48 and ord(i)<=57):
count+=1
else:
print('has alpha values')
break
if count == len(val):
print('val has only numeric value')
# 2.
if val.isdigit():
print('its numeric')
else:
print('has alpha') | true |
373acac5374b31482cb2f0121d48e0ca79edeafc | requestriya/Python_Basics | /basic54.py | 229 | 4.125 | 4 | # define a string that has alphanumeric letters and print only alphabet from that string
dec = 'ABc5d90uibdy56h38$!a'
for i in dec:
if (ord(i)>=65 and ord(i)<=90) or (ord(i)>=97 and ord(i)<=122):
print(i, end=' ')
| false |
c6608f837bf7d38af00ad6af3af1ceba22f0a28f | j3py/cracking_codes | /caesar_cipher.py | 2,382 | 4.15625 | 4 | # Caesar Cipher
import pyperclip
import cipherrandom
def main():
# the string to be encrypted/decrypted
message = input('Enter message: ')
# whether the program enc or dec
mode = input('Type e for encrypt or d for decrypt: ')
# every possible symbol that can be enc:
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.,`~@#$%^&*()_-+=[]{}|;:<>/'
symLength = len(SYMBOLS)
# check for random key
if mode == 'e' or mode == 'E':
key = cipherrandom.getRandInt(symLength)
else:
keyInput = input('Input key to decrypt by: ')
key = int(keyInput)
# check key is legit
if key < 0 or key >= symLength:
print('Your key must be between 0 and ' + (symlength - 1))
return main()
# store the enc/dec message:
translated = ''
# store unenc/undec symbols
unaccepted = ''
# main caesar cipher algorithm
for symbol in message:
# if the symbol is valid then handle encryption/decryption
if symbol in SYMBOLS:
symbolIndex = SYMBOLS.find(symbol)
if (mode == 'e' or mode == 'E'):
translatedIndex = symbolIndex + key
elif (mode == 'd' or mode == 'D'):
translatedIndex = symbolIndex - key
else:
print('Mode ' + mode + ' not recognized. Must be the letter e or the letter d, case insensitive.')
# handle wraparound
if translatedIndex >= len(SYMBOLS):
translatedIndex = translatedIndex - len(SYMBOLS)
elif translatedIndex < 0:
translatedIndex = translatedIndex + len(SYMBOLS)
translated = translated + SYMBOLS[translatedIndex]
else:
# append non-encrypted/decrypted symbols for warning message
unaccepted = unaccepted + symbol
# append the raw symbol to the message
translated = translated + symbol
# output the result
if len(unaccepted) > 0:
print('* * * * Warning * * * * \nThese symbols were untouched by the Caesar Cipher: ' + unaccepted + '\n* * * * * * * * * * * *')
print('Your key is: ' + str(key))
print('The following result has been copied to your clipboard: ')
print(translated)
pyperclip.copy(translated)
if __name__ == '__main__':
main()
| true |
44459258bdde077daa7e3ed2775c2f79e19b7d3b | eaglerock1337/realpython | /part1/1.1-1.9/find.py | 273 | 4.125 | 4 | print("AAA".find("a"))
name = "Version 2.0"
ver = 2.0
print(name.find(str(ver)))
string = input("Please enter a string: ")
search = input("Please enter a search character: ")
print("The result of searching '{}' for '{}' is {}.".format(string, search, string.find(search)))
| true |
3a13c13c28e5b18fd24578568b3c50e6eb053ca2 | rituteval/collatz | /collatz.py | 494 | 4.40625 | 4 | # The number we will perform the collatz operation on.
n = int(input("Enter a positive integer:"))
# Keep looping until we reach number 1.
# Note: This is assumes the collatz conjecture is true.
while n != 1:
# Print the current value of n.
print (n)
#Check is n is even.
if n % 2 == 0:
# If n is even, divede it by two.
n = n // 2
else:
# If n is odd, multiply it by three and add 1.
n = (3 * n) + 1
# Finally, print the 1.
print (n)
| true |
3099d9b4450c63646d2a63658edb9b11a4d40613 | Sergei729/Python_begin | /Task_4.py | 718 | 4.15625 | 4 | # Программа принимает действительное положительное число x и целое отрицательное число y.
# Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y).
# При решении задания необходимо обойтись без встроенной функции возведения числа в степень.
def my_func(x, y):
return x ** y if y >= 0 else my_func(x, y + 1) * 1 / x
print(my_func(float(input('Введите число')), int(input('Введите степень'))))
| false |
7ca49776529709e5f0892f41e0c229e1a4548822 | tayyabmalik4/pandas_in_python | /14_interpolate_#2_pandas_practical.py | 1,737 | 4.5625 | 5 | # *****************Interpolate function using pandas linbray in python******************
# discuss about-----parameters of interpolate-----------method,axis,limit,inplace,limit_direction,limit_area
import pandas as pd
inter1=pd.read_csv('F:\\tayyab programming\\machine learning\\pandaswithtayyab\\05_using_write_the_csv_file_merge-sort.csv')
print(inter1)
# print(inter1.interpolate())
# /////if we want to fill the missing values using interpolate function in column or row wise than we use axis function
# /////the default axis value is colums(0) and if we want to fill row wise than we use axis=1
# -----NOTE(all rows datatype is same and numaric if it is not same than error throgh)
# print(inter1.interpolate(axis=1))
# /////if we want to fill the values as own requirments and the spacific columns or rows than we use limit function
# print(inter1.interpolate(limit=3))
# //////if we want to fill the values previous or next(forward or backword or both) base than we use limit_direction function
# print(inter1.interpolate(limit=2,limit_direction='forward'))
# print(inter1.interpolate(limit_direction='backward'))
# print(inter1.interpolate(limit_direction='both'))
# ////if we want to fill the empty values in just the program values guess than we use limit_area='inside' function
# print(inter1.interpolate(limit_area='inside'))
# ////and if we want to fill the values out side of the program means other values which we wish than we use limit_area='outside' function
# print(inter1.interpolate(limit_area='outside'))
# /////if we want to replace the empty values csv sheet to fill values sheet using interpolate function than we use inplace=True function
print(inter1.interpolate(inplace=True))
print(inter1)
| true |
a121eb4f526d1c1d0eddd7c6c40674582afcc825 | tayyabmalik4/pandas_in_python | /10_Handling_missing_values_#03_pandas_practical_09.py | 2,807 | 4.59375 | 5 | # ******************************Handling Missing values part 3 using pandas in python*****************************
# /////discuss about (dropna(values,method,axis,how,subset,thresh,inplace))
# /////dropna() function basically which colums or rows are exists the empty values and we want to drop this colums or rows than we use dropna() function
# /////it drop bydefault rows -----print(csv.dropna())------and if we want to drop the colums than we use this function-------print(csv.dropna(axis=1))
# ////if we want to drop these rows(default) or colums who are present the null values than we use ------print(csv.dropna(axis=? ,how='any' ))-----any is a default
# if we want to drop those colums or rows who are all null values than we use this function---------print(csv.dropna(axis=?, how='all'))
# /////////if we want to drop these colums who are miminum 1 or more values are non-empty than we use this function-------print(csv.dropna(thresh=?))
# /////if we want drop the spacific row or column than we use this function----------print(csv.dropna(subset=['column_name']))
# /////if we want to replace the csv sheet which are not present in empty values than we use this function-------print(csv.dropna(inplace=True))
import pandas as pd
csv=pd.read_csv('F:\\tayyab programming\\machine learning\\pandaswithtayyab\\05_using_write_the_csv_file_merge-sort.csv')
# print(csv)
# /////it drop bydefault rows -----print(csv.dropna())
# print(csv.dropna())
# //////and if we want to drop the colums than we use this function-------print(csv.dropna(axis=1))
# print(csv.dropna(axis=1))
# /////////if we want to drop these rows(default) or colums who are present the null values than we use ------print(csv.dropna(axis=? ,how='any' ))-----any is a default
# /////for colums
# print(csv.dropna(axis=1,how='any'))
# /////for rows
# print(csv.dropna(axis=0,how='any'))
# if we want to drop those colums or rows who are all null values than we use this function---------print(csv.dropna(axis=?, how='all'))
# //////for colums
# print(csv.dropna(axis=1, how='all'))
# /////for rows
# print(csv.dropna(axis=0,how='all'))
# //////if we want to drop down these boxs who are minimum one or more values are not-empty than we use this function-------print(csv.dropna(thresh=?))
# print(csv.dropna(thresh=9))
# ////////if we want to drop the spacific rows or colums which the empty values are present than we use this function--------print(csv.dropna(subset=['column_name']))
# print(csv.dropna(subset=['Date']))
# print(csv.dropna(subset=['time']))
# /////if we want to replace the empty values csv sheet to csv sheet which are not present in empty values than we use this function-------print(csv.dropna(inplace=))
# csv1=csv.dropna(inplace=False)
print(csv.dropna(inplace=True))
print(csv)
| true |
344701e7c5b2f5410f4155127c1777969dc50f2a | tayyabmalik4/pandas_in_python | /02_Series_pandas_practical_01.py | 2,658 | 4.15625 | 4 | # ////////series in pandas/////////////////
# //////Series is a one dimentional array in pandas
# //////
# ****************import the pandas library
import pandas as pd
# //////checking the version of pandas
# /////the verion is 1.3.0
# print(pd.__version__)
lst=[1,2,-3,6.2,'data values']
# print(lst)
# *******************starting the series function in pandas
# //////to converting the 1d array to table form we use Series function in pandas in python
ser=pd.Series(lst)
# print(ser)
# print(type(ser))
# ///////pandas.core.series.Series=1d array
# //////to creating the Series in short way
ser1=pd.Series([1,2,3,4,5])
# print(ser1)
# //////to creating the empty series in pandas
ser2=pd.Series([ ],dtype=object)
print(ser2)
# /////if we want to write the index manually then we use this function
# /////but the index is equals to the values if it is not equal than it comes to error
ser3=pd.Series([1,2,3,4,5],index=[1,2,3,4,5])
# print(ser3)
# //////if we want to change the data type than we use this function
ser4=pd.Series([12,14,16,18,20],index=[1,2,3,4,5],dtype=float)
# print(ser4)
# /////if we want to insert the name of the object than we use this function
ser5 = pd.Series([11,13,15,17,12],dtype=float, name="amazing pandas functionality")
# print(ser5)
# /////if we want to inserting the single value than we use this function
ser6=pd.Series(8)
# print(ser6)
# /////if we want to creat many index of same nums than we use this function
ser7=pd.Series(8,index=[2,5])
# print(ser7)
# /////////if we want to print the dictionary
# -------in this dictionary key represents the index and values represents the values
ser8=pd.Series({'a':2,'b':4,'c':45})
# print(ser8)
ser9=pd.Series([1,2,3,4,5,6,7,8,9])
ser10=pd.Series([11,12,13,14,15,16,17,18,19])
ser11=pd.Series([1,2,3,4,5,6])
# print(ser9)
# ///////if we want to acces the array in spacific element than we use this function
# print(ser9[3])
# //////if we want acces two or more elements of the array than we use slicing function
# print(ser9[2:6])
# /////if we want to acces the maximum value than we use this function
# print(ser9.max())
# /////if we want to acces the minmum value than we use min f=unction
# print(ser9.min())
# /////if we want to printout that the numbers greater or lesser than we use operaters in pandas
# print(ser9[ser9>4])
# print(ser9[ser9<5])
# ////if we want to add the 2 same arrays then we use add operator or + operator
# /////if the number of indexs are not same its also work well and it is the functionality of pandas
print(ser9+ser10)
# /////handling emplty datas
# /////NaN means the Not a Number
print(ser9+ser11)
| true |
972166aa22c08efe01fceb483298ecb61c803f2b | ocslegna/hackerrank | /hackerrank/Python/Collections/namedtuple.py | 772 | 4.34375 | 4 | #!/usr/bin/python3
"""
Basically, namedtuples are easy to create, lightweight object types.
They turn tuples into convenient containers for simple tasks.
With namedtuples, you don’t have to use integer indices for accessing members of a tuple.
Named tuples are especially useful for assigning field
names to result tuples returned by the csv or sqlite3 modules:
__
DATA is a STUDENT list that takes as arguments those returned
by the * operator when applying a resulting list of splitting the input.
"""
from collections import namedtuple
if __name__ == '__main__':
STUDENTS = int(input())
STUDENT = namedtuple('STUDENT', input())
DATA = [STUDENT(*input().split()) for i in range(STUDENTS)]
print(sum(int(stud.MARKS) for stud in DATA)/STUDENTS)
| true |
d807e356e346c5348197311aa88aac7ab543af5a | minasel/GEOS636_PAG | /listings/io_wite.py | 712 | 4.125 | 4 | fname = "io_print.txt"
#1) open this file in read mode
print("Example 1")
print("--------------------Start")
my_file = open(fname, "r")
#print the entire thing
print(my_file.read())
#close the file
my_file.close()
print("--------------------End")
#2) print a two lines of the file
print("Example 2")
print("--------------------Start")
my_file = open(fname, "r")
#read and print a line, twice
print(my_file.readline())
print(my_file.readline())
#close the file
my_file.close()
print("--------------------End")
#3) print each line in a loop
print("Example 3")
print("--------------------Start")
with open(fname, 'r') as my_file:
for l in my_file:
print(l, end='')
print("--------------------End")
| true |
30d006b121bda4a42bb623f0eab1c9baf3c42dbd | Chaitanya-Raj/PyLearn | /SimpleCalculator.py | 650 | 4.125 | 4 | import os
print("Welcome to Simple Calculator")
print("1.Addition")
print("2.Subtraction")
print("3.Multiplication")
print("4.Division")
print("5.Modulus")
print("6.Exponentiation")
choice = int(input("Choose an option : "))
print()
x = float(input("Enter the first number : "))
y = float(input("Enter the second number : "))
if choice == 1:
result = x + y
if choice == 2:
result = x - y
if choice == 3:
result = x * y
if choice == 4:
result = x / y
if choice == 5:
result = x % y
if choice == 6:
result = x ** y
print()
print("The result of the operation is "+str(result))
os.system("pause") | true |
4df2681be502fd1dd5d1efff5022b24e5699dca3 | DouglasBavoso/ExerciciosPraticaPython | /ex065MaiorMenorValores.py | 840 | 4.15625 | 4 | # =================== MAIOR E MENOR VALORES ================================
# Crie um programa que leia varios numeros inteiros pelo teclado
# No final da execucao, mostre a media entre todos os valores e qual foi a mair e menor valores lidos
# O programa deve perguntar ao usuario se ele quer ou nao continuar a digitar valores.
cont = 1
num = int(input('Digite um número? '))
user = str(input('Quer continuar? {S/N} ')).strip().lower()
soma = maior = menor = num
while user != 'n':
num = int(input('Digite um número? '))
user = str(input('Quer continuar? {S/N} ')).strip().lower()
soma += num
if num > maior:
maior = num
if num < menor:
menor = num
cont += 1
print('Você digitou {} números e a média foi {:.2f} \nO maior valor foi {} e o menor foi {}'.format(cont, soma/cont, maior, menor))
| false |
53a8765a33abbc2f03cd581ae1df8936542d96a2 | DouglasBavoso/ExerciciosPraticaPython | /ex024VereficandoAsPrimeirasLetrasDeUmTexto.py | 309 | 4.1875 | 4 | # ============================ VERIFICANDO AS PRIMEIRAS LETRAS DE UM TEXTO =============================================
# Crie um programa que leia o nome de uma cidade e diga se ela começa ou nao com o nome "SANTO"
cid = str(input('Em que cidade você nasceu? ')).strip()
print(cid[:5].upper() == 'SANTO') | false |
c0000e107d0c36eb4f5b5f00fba30a80c3213ba2 | samyak1903/Decision_Making | /A4.py | 1,021 | 4.28125 | 4 | '''Q.4- Ask user to enter age, sex ( M or F ), marital status ( Y or N ) and then using following rules print their place of service.
1. if employee is female, then she will work only in urban areas.
2. if employee is a male and age is in between 20 to 40 then he may work in anywhere
3. if employee is male and age is in between 40 t0 60 then he will work in urban areas only.
4. And any other input of age should print "ERROR".
Q.5- A shop will give discount of 10% if the cost of purchased quantity is more than 1000.Ask user for quantity Suppose, one unit will cost 100. Judge and print total cost for user.
'''
age=int(input("Enter the age of employee: "))
sex=input("Gender: M or F: ")
status=input("Marital status: Y/N: ")
if sex.upper()=='F':
print("Employee will work only in urban areas ")
if sex.upper()=='M':
if age>=20 and age<=40:
print("Emoployee can work anywhere")
elif age>=40 and age<=60:
print("Employee will work only in urban areas")
else:
print("ERROR")
| true |
e1b7def14c817489a104e200dc255bb376324bcd | zayarmyothwin/programming-basic-python | /code/math.py | 501 | 4.25 | 4 | x=input("Enter first value : ")
y=input("Enter second value : ")
op=input("Operator + - * / : ")
try:
x=int(x)
y=int(y)
output=True
if op=="+":
result=x+y
elif op=="-":
result=x-y
elif op=="*":
result=x*y;/
elif op=="/":
result=x/y
else :
output = False
print("Wrong Operator")
if output :
print("Result is : ",result)
except ValueError:
print("Please enter number only.")
print(ValueError)
| false |
beae28fba50dbfa69d98aa8ab5201c0a25ac4645 | aleksiheikkila/AdventOfCode2019 | /day01/The_Tyranny_of_the_Rocket_Equation.py | 1,584 | 4.15625 | 4 |
# to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
def calc_fuel_req(mass: int) -> int:
return (mass // 3) - 2
# Unit tests
#For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.
#For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2.
#For a mass of 1969, the fuel required is 654.
#For a mass of 100756, the fuel required is 33583.
assert calc_fuel_req(12) == 2
assert calc_fuel_req(14) == 2
assert calc_fuel_req(1969) == 654
assert calc_fuel_req(100756) == 33583
with open("input.txt") as f:
masses = [int(line.strip()) for line in f.readlines()]
# Part 1:
total_fuel_req = sum(calc_fuel_req(mass) for mass in masses)
print("(pt.1 ans) Fuel needed:", total_fuel_req)
# Part 2: Need also fuel for fuel, and so on
def calc_fuel_req_considering_fuel(mass: int) -> int:
total_fuel = 0
additional_fuel_needed = calc_fuel_req(mass)
while additional_fuel_needed > 0:
total_fuel += additional_fuel_needed
additional_fuel_needed = calc_fuel_req(additional_fuel_needed) # fuel need for the added fuel
return total_fuel
# Unit tests
assert calc_fuel_req_considering_fuel(14) == 2
assert calc_fuel_req_considering_fuel(100756) == 50346
# What is the sum of the fuel requirements for all of the modules on your spacecraft
# when also taking into account the mass of the added fuel?
total_fuel_req_pt2 = sum(calc_fuel_req_considering_fuel(mass) for mass in masses)
print("(pt.1 ans) Fuel needed:", total_fuel_req_pt2) | true |
f5675d3dfe845e6522c1e418eb3e846720ad250b | ArnabBasak/PythonRepository | /progrms nltk/stop words.py | 657 | 4.1875 | 4 | from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
example_sentence = "this is a first sentence written by me in the nltk python."
stop_words = set(stopwords.words("english"))
print('original sentence is',example_sentence)
#print(stop_words)
words = word_tokenize(example_sentence)
filtered_sentence = []
for w in words:
if w not in stop_words:
filtered_sentence.append(w)
print(filtered_sentence)
#it can be done in one line as well
filtered_sentence1 = [w for w in words if not w in stop_words]
print(filtered_sentence1)
#stop words are the punctuation words which are used in the english sentence such as "is an etc"
| true |
bdd31b8913b5e2480dada2e1f4092aa4cd251b59 | ArnabBasak/PythonRepository | /Python_Programs/PythonCode/Dice_Rolling_Simulator.py | 1,969 | 4.5625 | 5 | """
1. Dice Rolling Simulator
The Goal: Like the title suggests, this project involves writing a program that simulates rolling dice. When the program runs, it will randomly choose a number between 1 and 6. (Or whatever other integer you prefer — the number of sides on the die is up to you.) The program will print what that number is. It should then ask you if you’d like to roll again. For this project, you’ll need to set the min and max number that your dice can produce. For the average die, that means a minimum of 1 and a maximum of 6. You’ll also want a function that randomly grabs a number within that range and prints it.
Concepts to keep in mind:
Random
Integer
Print
While Loops
"""
import random
class Simulator:
def __init__(self):
"""This is the init funtion where it will only set the score variable"""
self.playerScore = 0
def getInput(self):
"""This funtion will take the input from the user and intimate it if its fine or not"""
self.userchoice = int(input('enter any number between 1 and 6'))
if self.userchoice not in range(1,6):
print("the entereted number is not in range please enter again")
self.getInput()
def gamePlay(self):
"""This is the funtion where it will compare with the userchoice and the system choice"""
self.randomNumber = random.randrange(1,6)
if self.randomNumber == self.userchoice:
self.playerScore += 1
print("congratulation you won your score is: ",self.playerScore)
else:
print("Sorry you lost press 1 to play again")
self.userchoice = int(input())
if self.userchoice == 1:
self.getInput()
self.gamePlay()
else:
print("THANK YOU")
print("your final score is",self.playerScore)
s = Simulator()
s.getInput()
s.gamePlay()
| true |
299a505a01a4b9180c53a461882f5ee26b4b4107 | ArnabBasak/PythonRepository | /python programs/posnegnumber.py | 282 | 4.34375 | 4 | number = int(input("enter any number it can be postive negative or 0"))
if number == 0:
print("the number is nither negative nor postive its 0")
elif number>0:
print("the numer is postive")
elif number<0:
print("the number is negative")
else:
print("invalid input")
| true |
71bc39777c133295ca95cf2c16b33feae0186086 | MxValix/corso_data_science_python | /5nov.py | 999 | 4.375 | 4 | # Test Case 1
# Enter your annual salary: 120000
# Enter the percent of your salary to save, as a decimal: .10
# Enter the cost of your dream home: 1000000
# Number of months: 183
#
# Test Case 2
# Enter your annual salary: 80000
# Enter the percent of your salary to save, as a decimal: .15
# Enter the cost of your dream home: 500000
# Number of months: 105
if __name__ == '__main__':
current_savings = 0.0
annual_return = 0.04
months = 0
annual_salary = int(input("Enter your annual salary: "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
portion_saved = (annual_salary / 12.0) * portion_saved
total_cost = int(input("Enter the cost of your dream home: "))
portion_down_payment = total_cost * 0.25
while current_savings < portion_down_payment:
months += 1
monthly = current_savings * (annual_return / 12)
current_savings += monthly + portion_saved
print("Number of months:", months)
| true |
b1a2365c9c26db6bc0702c5ecf7537c5fc9dfeae | ashleyabrooks/code-challenges | /polish_calculator.py | 1,144 | 4.25 | 4 | """Calculator
>>> calc("+ 1 2") # 1 + 2
3
>>> calc("* 2 + 1 2") # 2 * (1 + 2)
6
>>> calc("+ 9 * 2 3") # 9 + (2 * 3)
15
Let's make sure we have non-commutative operators working:
>>> calc("- 1 2") # 1 - 2
-1
>>> calc("- 9 * 2 3") # 9 - (2 * 3)
3
>>> calc("/ 6 - 4 2") # 6 / (4 - 2)
3
"""
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num21
def calc(s):
"""Evaluate expression."""
stack = s.split()
num2 = int(stack.pop())
while stack:
num1 = int(stack.pop())
operator = stack.pop()
if operator == '+':
num2 = num1 + num2
elif operator == '-':
num2 = num1 - num2
elif operator == '*':
num2 = num1 * num2
elif operator == '/':
num2 = num1 / num2
return num2
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED. ***\n"
| false |
3e0e0258c387fdcd702a446e0d8f8265ac72ad23 | avyuktitech/DXCRepo | /Python_Calculator.py | 975 | 4.3125 | 4 | # This was Sample Python script
# Basic Calculator:
# This function performs additiion
def add(a, b):
return a + b
# This function performs subtraction
def subtract(a, b):
return a - b
# This function performs multiplication
def multiply(a, b):
return a * b
#This function performs division
def divide(a, b):
return a / b
print("Hello, Happy To see you ~!! Select the arithmetic operation.")
print("+")
print("-")
print("*")
print("/")
#User input, Keyboard Input
choice = input("Hello good to see you , please enter operator to use:")
A = int(input("Please enter first number: "))
B = int(input("Please enter second number: "))
if choice == '+':
print(A,"+",B,"=", add(A,B))
elif choice == '-':
print(A,"-",B,"=", subtract(A,B))
elif choice == '*':
print(A,"*",B,"=", multiply(A,B))
elif choice == '/':
print(A,"/",B,"=", divide(A,B))
else:
print("Invalid input")
| true |
db14964251ed0383169d71315f0208de6cfe7509 | TechbirdsYogendra/DataStructureExercisePython | /recursion.py | 525 | 4.125 | 4 | # This funcion returns factoril of a number.
def factorial(n):
if n == 0 or n == 1:
return 1
elif n < 0:
return 0
else:
return n * factorial(n-1)
n = 5
fact = factorial(n)
print(f"Factorial of {n} is {fact}.")
# It returns nth numner in Fibonacci series.
def fibonacci(n):
if n == 1 or n == 2:
return n-1
else:
return fibonacci(n-2) + fibonacci(n-1)
n_1 = 10
fibo_number = fibonacci(n_1)
print(f"{n_1}th number in the fibonacci series is {fibo_number}.")
| true |
44d926fffff7a4f11a052faadc042496ffebeb49 | jPUENTE23/ESTRUCTURA-DE-BASES-DE-DATOS-Y-SU-PROCESAMIENTO-3ER-SEMESTRE | /Ejemplos/04_importacion_datetime.py | 1,480 | 4.25 | 4 | '''
Ejemplo para ilustrar la importación de la librería datetime en Python 3
Demuestra el uso de: hora, fecha y aritmética de fechas
'''
import datetime
import time
SEPARADOR = ("*" * 20) + "\n"
#Creación de una hora específica
hora = datetime.time(10, 20, 30)
print(f"El tipo de objeto de la hora es {type(hora)}")
print(f"La hora es {hora}")
print(f"La hora de {hora} es {hora.hour}") #Limitado 0..23
print(f"El minuto de {hora} es {hora.minute}") #limitado 0..59
print(f"El segundo de {hora} es {hora.second}") #limitado 0..59
print(f"El microsegundo de {hora} es {hora.microsecond}") #limitado 0..999
print(SEPARADOR * 2)
#Determinar la fecha del sistema
fecha_actual = datetime.date.today()
print(f"El tipo de objeto de la fecha es {type(fecha_actual)}")
print(f"La fecha actual es {fecha_actual}")
print(f"El año actual es {fecha_actual.year}")
print(f"El mes actual es {fecha_actual.month}")
print(f"El día actual es {fecha_actual.day}")
print(SEPARADOR * 2)
#Convertir un string a fecha
fecha_capturada = input("Dime una fecha: \n")
fecha_procesada = datetime.datetime.strptime(fecha_capturada, "%d/%m/%Y").date()
print(type(fecha_capturada))
print(type(fecha_procesada))
print(f"La fecha capturada se transformó a {fecha_procesada}")
#Aritmética de fechas básica
cant_dias = int(input("Dime la cantidad de días a adelantar:\n"))
nueva_fecha = fecha_procesada + datetime.timedelta(days=+cant_dias)
print(f"La nueva fecha es {nueva_fecha}")
print(SEPARADOR) | false |
f475c34f064940629f995f092b5cbd5d3a1bd569 | sohye-lee/algorithm_study | /9498.py | 359 | 4.125 | 4 | score = int(input(""))
def grade(score):
if score > 100 or score < 0:
return
if score >= 90 and score <= 100:
print("A")
elif score < 90 and score >= 80:
print("B")
elif score < 80 and score >= 70:
print("C")
elif score < 70 and score >= 60:
print("D")
else:
print("F")
grade(score)
| false |
2c3d384f7671d2db709bb0381168eca461595e2d | runningshuai/jz_offer | /48.不用加减乘除做加法.py | 690 | 4.125 | 4 | """
题目描述
写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
思路:
①不考虑进位:两个数之和是异或
②计算进位:求与,左移一位
若②不为0,就继续①②步
"""
class Solution:
def Add(self, num1, num2):
# write code here
if not num1:
return num2
elif not num2:
return num1
while num2:
num1, num2 = (num1 ^ num2) & 0xFFFFFFFF, (num1 & num2) << 1
if num1 >> 31 == 0:
return num1
else:
return num1 - 2**32
if __name__ == '__main__':
s = Solution()
print(s.Add(-1, 1))
| false |
b5999e8997bb3450f85dc92493c2cab17639a1f6 | mmeysenburg/ccla-hpc-workshop | /src/optimizing-python/function-alias/exercise02.py | 403 | 4.15625 | 4 | '''
Function alias exercise 2
Convert cartesian coordinates to polar.
'''
import math
import random
# create n cartesian coordinates in the unit square
n = 1_000_000
uni = random.uniform
cartesians = [(uni(-1, 1), uni(-1, 1)) for i in range(n)]
# write code here to create a new list called polars.
# the new list should contain the polar coordinate
# equivalents of each of the coors in cartesians. | true |
f275b55d7ee2ce5aa69e40898b8a846a7033d386 | Ahsank01/FullStack-Cyber_Bootcamp | /WEEK_1/Day_1/7_Forwards_Is_Backwards.py | 928 | 4.625 | 5 | #!/usr/bin/env python3
"""
The path to the input file will be passed into your program as a command line argument when your program is called.
Write a program that receives a single word as input and checks to see if the word is a palindrome
(i.e. words that look the same written backwards).
"""
import sys
def F_is_B():
# store a file name in this variable
file_name = sys.argv[1]
# open a file. with => this will automatically close the file
with open(file_name, 'r') as f:
# read the data line by line, convert it into a list and save it in tha data variable
data = f.read().split()
# loop over the data list and pass each value to words, one at a time
for words in data:
# check if the word is a palindrome
if words == words[::-1]:
print("True")
else:
print("False")
F_is_B() | true |
7a00269839623ccf7c805152f61711d543f4a721 | Ahsank01/FullStack-Cyber_Bootcamp | /WEEK_1/Day_1/8_Lines.py | 829 | 4.125 | 4 | #!/usr/bin/env python3
"""
Your boss handed you a simple task, just replace the "newlines" from the provided file with spaces...
(hint - it's not just that simple)
"""
# Import the 'sys' module
import sys
def lines():
# Get the name of the file from the command line arguments
file_name = sys.argv[1]
# Final output string
output = ''
# open a file
with open(file_name, 'r') as f:
# Iterate over the line
for lines in f:
# Remove the newline character from the line
lines = lines.strip()
# Append the line to the output string
output += lines
# Add a space if the line was not empty
if len(output) > 0:
output += ' '
print(output, end='')
lines() | true |
8ca87f709db67790f37e7e77d762eb00261d0e0a | PashaKim/Python-Function-for-basic-math-operation | /Basic-Math-Operations.py | 653 | 4.6875 | 5 | #Write the function "arnntetik", taking 3 arguments:
#the first 2 - the number, the third - the operation that should be performed on them.
#If the third argument is +, add them; If -, then subtract; Multiply; / - divide (the first into the second). In other cases, return the string "Unknown operation" ..
print ("Hi. This function (arithmetic(1,2,'+')) use for math operation whith 2 numbers. Use +,-,*,/")
def arithmetic (a, b, c):
if c == '+':
return a + b
elif c == '-':
return a - b
elif c == '*':
return a * b
elif c == '/':
return a / b
else:
print ('Unknown operation. Use +,-,*,/')
| true |
6ea19b0d8bdb75aa46b59db78ba90f608ec65047 | bosskeangkai/Python-Math-Solving | /max_min.py | 1,025 | 4.15625 | 4 | # input three number and then check what is the max or min number and then finally show on your screen
# while loop 5 time
# คำสั่ง if เเบบ 1 ทางเลือก
# do only if for check
# initail
max = 0
min = 0
n = 1
# process
# while loop check if n <= 5 loop
while n <= 5:
x = int(input("Enter your X number:"))
y = int(input("Enter your Y number:"))
z = int(input("Enter your Z number:"))
# if-else condition
if(x > y and x > z):
max = x
if(x < y and x < z):
min = x
if(y > x and y > z):
max = y
if(y < x and y < z):
min = y
if(z > x and z > y):
max = z
if(z < x and z < y):
min = z
# output
print(
f"The number that I had to input was {x,y,z} and the max and min number is {max,min}")
# input 4 5 6
# The number that I had to input was (4, 5, 6) and the max and min number is (6, 4)
# loop until n > 5
n = n+1
print("End")
| true |
6f036986207dfaf22e0a7e8af4e71edf12ed478c | MatthewTurk247/Programming-II | /Recursion.py | 764 | 4.375 | 4 | # Recursion: functions calling themselves
# Functions calling functions
def f():
g()
print("f")
def g():
print("g")
f()
# Functions calling themselves
def hello():
print("hello")
hello()
# hello()
# helpful uses: searching files
# We can control the recursion depth
def controlled(level, end_level):
print("Recursion depth:", level)
if level < end_level:
controlled(level + 1, end_level)
controlled(1, 20)
# Factorial
def factorial(n):
total = 1
for i in range(1, n + 1):
total *= i
return total
print(factorial(9))
def recursive_factorial(n):
if n == 1:
return n
elif n == 0:
return 1
else:
return n * recursive_factorial(n - 1)
print(recursive_factorial(5)) | true |
e18137c5524499290af0cdbdfdbf4e8a0a0563da | ValentynaGorbachenko/cd2 | /ltcd/matrixReshape.py | 2,259 | 4.34375 | 4 | '''
In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.
You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.
The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.
If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
Example 1:
Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
Example 2:
Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
Note:
The height and width of the given matrix is in range [1, 100].
The given r and c are all positive.
'''
def matrixReshape(nums, r, c):
# get a number of elements in current matrix
try:
nums_of_elements = len(nums)*len(nums[0])
except IndexError:
nums_of_elements = 0
print(nums_of_elements, r*c)
# check if reshape is possible
if nums_of_elements != r*c:
return nums
temp = []
res = [[0]*c]*r
rr=[]
print(res, r, c)
# flatten a matrix
for x in nums:
temp.extend(x)
print(temp)
count = 0
for i in range(r):
print(i)
rr.append([])
for j in range(c):
rr[i].append(temp[count])
count+=1
# for j in range(c):
# res[i][j] = temp[count]
# count+=1
print(rr)
return rr
# matrixReshape( [[1,2],[3,4]] , 4,1)
def matrixReshape2(nums, r, c):
rows = len(nums)
cols = len(nums[0])
if rows*cols == r*c:
numsI = [x for y in nums for x in y]
numsR = [numsI[i:i+c] for i in range(0, len(numsI), c)]
else:
return nums
return numsR
print(matrixReshape2( [[1,2],[3,4]] , 4,2)) | true |
7e4b0c59f46428157c01a81fbbcfcbc1d42a9e08 | jheyer23/python_gdal | /Functions.py | 524 | 4.21875 | 4 | # Writing functions in Python
#Where a block line is more Python code (even another block), and the block head is of the following format: block_keyword block_name(argument1,argument2, ...) Block keywords you already know are "if", "for", and "while".
# Functions in python are defined using the block keyword "def", followed with the function's name as the block's name. For example:
def my_function_with_arguments(username, greeting):
print("Hello, %s, From My Function!, I wish you %s"%
(username, greeting))
| true |
bfe48ca69a214ffd51785329ca332be465a99bd1 | jheyer23/python_gdal | /Dictionaries.py | 984 | 4.59375 | 5 | # Storing items in dictionary
# Different attributes - name, email, phone, etc.
# Key value pairs (Key: name, email, phone). Each key has value
# Keys need to be unique in a dictionary - cannot duplicate
# Values of keys can be any data type
customer = {
"name": "John",
"age": 30,
"is_verified": True
}
print(customer["name"])
# Doesn't yell at us if specify a key that does not exist here. Can add default value (e.g. Jan 1 1980)
print(customer.get("birthdate", "Jan 1 1980"))
# Update key
customer["name"] = "Jack Smith"
print(customer["name"])
# Exercise
# Program asks for phone number
phone = input("Phone: ")
# Need dictionary to map key to a value
digits_mapping = {
"1": "One",
"2": "Two",
"3": "Three",
"4": "Four"
}
output = ""
for ch in phone:
output += digits_mapping.get(ch, "!") + " " # For each iteration get this and add to output string. If number is not in dictionary the exclamation mark is printed
print(output) | true |
d71a573e079571fb6033bc22c03438b4c0a9b7c3 | dressaco/Python-FiapOn | /Cap02Pt02_Decisoes/Ex02_DecisaoComposta.py | 774 | 4.15625 | 4 | name = input('Digite o nome: ')
age = int(input('Digite a idade: '))
contagious_susp = input('Suspeita de doença infecto-contagiosa (S/N)?').upper()
if age >= 65 and contagious_susp == 'S':
print('O paciente ' + name + ' será direcionado para a sala AMARELA - COM prioridade')
elif age < 65 and contagious_susp == 'S':
print('O paciente ' + name + ' será direcionado para a sala AMARELA - SEM prioridade')
elif age >= 65 and contagious_susp == 'N':
print('O paciente ' + name + ' será direcionado para a sala BRANCA - COM prioridade')
elif age < 65 and contagious_susp == 'N':
print('O paciente ' + name + ' será direcionado para a sala BRANCA - SEM prioridade')
else:
print('Responda a suspeita de doença infectocontagiosa com \'S\' ou \'N\'')
print('FIM') | false |
b28ca5390ed22e9860761f7dcfccf1ff9ca868ac | Neeraj-Palliyali/chegg_python | /test.py | 410 | 4.3125 | 4 |
# getting account number
accountNo=input("Enter the 8 digit account number:")
# try catch for if the input cannot be converted to integer
try:
account=int(accountNo)
# if the length is not equal to 8
if(len(str(account))==8):
print("The account number is valid")
else:
print("Invalid account number")
# the input will be invalid
except:
print("Invalid account number") | true |
c9ab498ac08db9fe6d289bc7ebc2fa4b3a173738 | Freire71/treinamento-python | /exercicios/modulo-4/exercicio-3.py | 512 | 4.15625 | 4 | # Dada uma lista com os nomes = ["Tony Stark", "Peter Parker", "Thor"]
# Crie uma nova lista contendo a primeira letra de cada nome na lista, converta essa caractere para minusculo
# Faça essa operação utilizando compreensão de listas e um loop tradicional
# Compare os 2 métodos
nomes = ["Tony Stark", "Peter Parker", "Thor"]
# Dada a lista [1,2,3,4,5,6]
# Crie uma nova lista cotendo apenas os valores ímpares
# Faça essa operação utilizando compreensão de listas e um loop tradicional
numeros = [1, 2, 3, 4, 5, 6]
| false |
e944d86b29c424384cf1e35c2593220107a8d9d1 | reggiemccoy/python_code | /tempature/converter.py | 305 | 4.25 | 4 |
print("Welcome to my conversion project for measurements")
cm = int(input(" please enter in cm: \n")) # making sure the data entered is integer
# and then make the text appear on a new line
conVertthis =(.39*cm)
print(conVertthis)
print("inches")
foot = (conVertthis/12)
print(foot)
print("feet")
| true |
23578f985e19392effd465752c3fe289c0431fe5 | reggiemccoy/python_code | /compare/compare_sting_input.py | 271 | 4.25 | 4 | # String compare in Python with input
str_input1 = input("Enter First String? ")
str_input2 = input("Enter Second String? ")
# comparing by ==
if str_input1 == str_input2:
print("First and second strings are same!")
else:
print("You entered different strings!") | true |
a6d5b82a61dda2ff6693d5fac779d175690fc451 | duncandill/Age | /age.py | 1,306 | 4.15625 | 4 | def question():
answer = None
while answer is None:
print ("Welcome to AGE\n please enter your age.")
answer = input("How old are you?\nEnter a number from 0 to 99 ")
try:
answer = int(answer)
if answer >99 or answer < 0:
answer = None
except:
answer = None
if answer is 1:
print("You are 1 year old")
else:
print("You are " + str(answer) + " years old")
if answer > -1 and answer < 3 :
print ("This makes you a baby or a toddler")
if answer > 3 and answer < 13 :
print ("This makes you a child")
if answer > 13 and answer < 19 :
print ("This makes you a teenager")
if answer > 19 and answer < 60 :
print ("This makes you an adult")
if answer > 60 and answer < 99 :
print ("This makes you an elder")
answer2= None
while answer2 is None:
answer2 = input("try again(yes/no) ")
if answer2 in ["yes" , "y" , "Y" , "YES"]:
answer = None
question()
if answer2 in ["no" , "n" , "N" , "NO"]:
pass
print("thank you" )
else:
print("I do not understand")
answer2= None
return None
question()
| true |
39f208f932dfb344b589ee8c69e12432bcde3e8d | arcadecoder/Rosalind-algorithms | /RabbitsandRecurrence.py | 838 | 4.46875 | 4 |
def Fibonacci_loop_rabbits(months, offsprings):
"""
1. Initially assign 1 parent and one child. This is the first set of offspring.
2. Loop over the number of months (minus 1 - we already had the first month)
3. The child becomes a parent, so given a new value (still 1)
4. The child value is now the parent, plus the previous child x the new offspring that they produce
"""
parent, child = 1, 1
for itr in range(months - 1):
child, parent = parent, parent + (child * offsprings)
print(child)
return child
Fibonacci_loop_rabbits(30, 2)
# o - small rabbits - have to mature and reporduce in the next cycle only
# O - mature rabits - They can reproduce and move to the next cycle
"""
Month 1: [o]
Month 2: [O]
Month 3: [O o o]
Month 4: [O o o O O]
Month 5: [O o o O O O o o O o o]
"""
| true |
7273758e0cced965db85a7dbc850da8439b45588 | varnitmittal/quarantine-coding-revision | /DS/Queue/deque_incomplete.py | 1,360 | 4.15625 | 4 | #Deque implementation
class Deque:
def __init__(self, *args):
self.max = 5
self.deque = []
self.front = -1
self. rear = -1
self.display()
def isFull(self):
return False
def insertFront(self, x):
if self.isFull():
print("Can't insert, deque is already full.")
elif len(self.deque) == 0:
self.deque.insert(0, x)
self.rear = 0
self.front = 0
else:
self.deque.insert(0, x)
self.front
def deleteFront(self):
if self.isEmpty():
print("Deque is already empty")
else:
self.deque.pop(0)
def isEmpty(self):
return False
def insertRear(self, x):
if self.isFull():
print("Can't insert, deque is already full.")
else:
self.deque.append(x)
def deleteRear(self):
if self.isEmpty():
print("Deque is already empty")
else:
self.deque.pop()
def peekFront(self):
pass
def peekRear(self):
pass
def display(self):
print(self.deque)
D = Deque()
D.insertFront(10)
D.insertRear(20)
D.insertRear(30)
D.insertRear(40)
D.insertRear(50)
D.insertRear(60)
D.insertRear(70)
D.display()
D.deleteRear()
D.deleteFront()
D.display() | true |
f78cc4d4d4456a10f09d870bfd0385f2bc588431 | baleshwar-mahto/cse-using-python | /sqplot.py | 537 | 4.34375 | 4 | #python 3 program to plot x^2 and x^3 function on same graph
import numpy as np
import matplotlib.pyplot as plt
from pylab import rcParams
rcParams['figure.figsize']=5,3
#figure of the size 5in x 3in
x=np.linspace(-1,1,10)
y=x**2
y1=x**3
plt.plot(x,y,'r.',label=r'$y=x^2$')
plt.plot(x,y1,lw=3,color ='g',label =r'$y=x^3$')
plt.axhline(2,color='k') # draw hor axis
plt.axvline(2,color='k') # draw vertical axis
plt.xlim(-1,1)
plt.ylim(-1,1)
plt.xlabel(r'$x$',fontsize=20)
plt.ylabel(r'$y$',fontsize=20)
plt.legend(loc=4)
plt.show()
| true |
130a86a145641063007d47126c2aab88150a3c76 | SHJoon/Algorithms | /arrays/5_reverse.py | 496 | 4.40625 | 4 | # Reverse Array
# Given a numerical array, reverse the order of the
# values. The reversed array should have the same
# length, with existing elements moved to other
# indices so that the order of elements is reversed.
def reverse_array(lst):
for i in range(len(lst) // 2):
temp = lst[i]
lst[i] = lst[len(lst) - i - 1]
lst[len(lst) - i - 1] = temp
my_lst = [0,1,2,3,4]
my_lst2 = [0,1,2,3,4,5]
reverse_array(my_lst)
reverse_array(my_lst2)
print(my_lst)
print(my_lst2) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.