blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3d98365e0ba0ebbf714acc17e52c5d9b9a219e44 | iamnidheesh/MyCodes | /Python-Files/inputvalidiation.py | 396 | 4.1875 | 4 | #the Collatz sequence
def collatz(m):
if m%2==0 :
m=m//2
return m
elif m%2==1 :
m=3*m+1
return m
c=0
while c!=1 :
try :
n=int(input("Enter number :"))
c=c+1
while True :
print(n)
n=collatz(n)
if n==1 :
break
except :
print("please enter an integer")
| false |
2cddfcca5ba5885135c7cf4271166db2a18b12a3 | weishanlee/6.00.1x | /PS01/1_3.py | 2,047 | 4.28125 | 4 | # create random letter lists to test PS1
import random
import string
def test(tests,a,b):
'''
tests: int, the number of tests to perform
a: int, the length of the shortest string allowed
b: int, the length of the maximum string allowed
'''
n = 0
while n < tests:
s = generate_string(a,b)
word = longest_string(s)
print s
print 'Longest substring in alphabetical order is: ' + str(word)
n += 1
return
def generate_string(a,b):
'''
total: int, the maximum number of letters in the string
new_string: string, will hold the new string for testing
n: int:
'''
new_string = ''
n = 0
total = random.randrange(a,b)
#print 'the total number of letters are: ' + str(total)
if total == 26:
new_string = 'abcdefghijklmnopqrstuvwxyz'
elif total == 5:
new_string = 'zyxwvutsrqponmlkjihgfedcba'
else:
while n < total:
letter = random.choice(string.letters)
new_string += letter
n += 1
#print new_string.lower()
return new_string.lower()
def longest_string(s):
'''
current longest: string
testing: char
the_longest: string
'''
n = 0
current_longest = ''
testing = s[n]
the_longest = s[n]
while n < len(s) - 1:
if s[n] <= s[n+1]:
testing += s[n+1]
#print testing
elif s[n] > s[n+1]:
#print 'current: ' + str(current_longest)
#print 'longest: ' + str(the_longest)
if len(current_longest) > len(the_longest):
the_longest = current_longest
current_longest = testing
testing = s[n+1]
if len(testing) > len(the_longest):
the_longest = testing
n += 1
#print 'Longest substring in alphabetical order is: ' + str(the_longest)
return the_longest
test(5,5,26)
| true |
0b204934269b03e929537727a134c4e5685a964f | weishanlee/6.00.1x | /PS03/3_3.py | 1,389 | 4.21875 | 4 | secretWord = 'apple'
lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
It starts by converying the secretword to a list and by creating an empty
list with underscores for the word that they are trying to find.
Then it loops through for each element in the lettersGuessed list looking to see
if it is in each of the positions of the secret list.
each time it finds a letter that is in both it updates the guess with the letter
in the correct position
it then returns the clue with spaces between each letter to make it more readabile.
'''
# FILL IN YOUR CODE HERE...
secret = list(secretWord)
guess = []
for letter in secret:
guess.append('_')
for element in lettersGuessed:
n = 0
while n < len(secret):
if element == secret[n]:
guess[n] = element
n += 1
clue = ''
for each in guess:
clue += each
clue += ' '
return clue
print getGuessedWord(secretWord, lettersGuessed) | true |
a51e50f0fdcad1787d9cb0a7ab7f7cab50a4eda6 | weishanlee/6.00.1x | /Lecture 12/Lecture_12_05.py | 1,052 | 4.3125 | 4 | print "Prime generator"
def genPrimes():
primes = []
last = 1
while True:
last += 1
for p in primes:
if last % p == 0:
break
else:
primes.append(last)
yield last
primeList = genPrimes()
for i in range(1,11):
print primeList.next()
# -------------------- #
print ""
print "Fibonacci Generator"
def genFib():
fibn_1 = 1
fibn_2 = 0
while True:
next_f = fibn_1 + fibn_2
yield next_f
fibn_2 = fibn_1
fibn_1 = next_f
# Do not run this code as it is an infinite loop
# printing out every possible fibonacci number.
# however it may be useful in some situations
#for n in genFib():
# print n
fibList = genFib()
for i in range(1,11):
print fibList.next()
# -------------------- #
print ""
print "powers of two generator"
def powerTwo():
answer = 1
while True:
answer *= 2
yield answer
power = powerTwo()
for i in range(1,11):
print power.next()
| false |
3b5db557711710d79a80e3c008ab4b04fe29e1aa | josephantony8/GraduateTrainingProgram2018 | /Python/Day5/Listcommand.py | 1,828 | 4.5 | 4 | Consider a list (list = []). You can perform the following commands:
insert i e: Insert integer e at position i.
print: Print the list.
remove e: Delete the first occurrence of integer e.
append e: Insert integer e at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
Initialize your list and read in the value of followed by lines of commands where each command will be of the 7 types listed above.
Iterate through each command in order and perform the corresponding operation on your list.
comlist=[]
comcount=int(raw_input("Enter the number of commands"))
for i in range(comcount):
cmd=raw_input("enter the command and values")
ins=cmd.split(' ')
if(ins[0]=='insert'):
try:
if(ins[1].isdigit()==True and ins[2].isdigit()==True and len(ins)==3):
comlist.insert(int(ins[1]),int(ins[2]))
else:
print("Enter proper integer values")
except Exception as error:
print(error)
elif(ins[0]=='print'):
print(comlist)
elif(ins[0]=='remove' and len(ins)==2):
try:
comlist.remove(int(ins[1]))
except Exception as error:
print(error)
elif(ins[0]=='append' ):
if(ins[1].isdigit()==True and len(ins)==2):
comlist.append(int(ins[1]))
else:
print("Enter proper integer values")
elif(ins[0]=='sort'):
if(len(ins)==1):
comlist.sort()
else:
comlist.sort()
print("Sort doesn't need any arguments")
elif(ins[0]=='pop'):
try:
if(len(ins)==1 and ins[1].isdigit()==True):
comlist.pop()
elif(len(ins)==2 and ins[1].isdigit()==True):
comlist.pop(int(ins[1]))
elif(len(ins)>2):
comlist.pop(int(ins[1]),int(ins[2]))
except Exception as error:
print(error)
elif(ins[0]=='reverse'):
if(len(ins)==1):
comlist.reverse()
else:
comlist.sort()
print("reverse doesn't need any arguments")
| true |
954fbd695169cf5ca915f4afa14673647e4a77b4 | olzama/Ling471 | /demos/May13.py | 1,688 | 4.15625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression
# Linear regression demo
X = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
# Want: y = 2x + 0 (m = 2, b = 0)
Y = [2*x for x in X] # list comprehension
Y_2 = [x*x for x in X]
Y_3 = [x*x*x for x in X]
# for x in X:
# Y.append(2*x)
# plt.plot(X,Y,color="red")
# plt.plot(X,Y_2,color="blue")
# plt.plot(X,Y_3,color="green")
# plt.show()
# The data: Distance needed for cars at different speeds to stop
data_url = 'https://raw.githubusercontent.com/cmdlinetips/data/master/cars.tsv'
cars = pd.read_csv(data_url, sep="\t")
print(cars.head())
print(cars.shape)
# cars['dist']
X = cars.dist.values
Y = cars.speed.values
plt.scatter(X, Y)
plt.xlabel('Distance to stop (ft)')
plt.ylabel('Speed (mph)')
# plt.show()
lr = LinearRegression()
X_matrix = [[x] for x in X]
lm = lr.fit(X_matrix, Y)
predictions = lm.predict(X_matrix)
plt.plot(X, predictions)
# plt.show()
# By the way, that's how you could do it without any package:
# Create a matrix where first column is all 1s and second column is our X data
# To use the linear algebra package, need to use the numpy,
# because the linear algebra backage expects a proper matrix.
# Could use pandas objects as well.
#X_matrix = np.vstack((np.ones(len(X)), X)).T
# Find our A matrix (the vector of parameters) by solving a matrix equation:
#best_parameters_for_regression = np.linalg.inv(X_matrix.T.dot(X_matrix)).dot(X_matrix.T).dot(Y)
# Prediction line: Multiply X by A, now that we know A:
#predictions = X_matrix.dot(best_parameters_for_regression)
#plt.plot(X, predictions)
# plt.show()
| true |
8fa9a8bf7fe98cf7785f5a40d0dc19b0173cfa9d | nbackas/dsp | /python/q8_parsing.py | 678 | 4.125 | 4 | # The football.csv file contains the results from the English Premier League.
# The columns labeled Goals and Goals Allowed contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in for and against goals.
# The below skeleton is optional. You can use it or you can write the script with an approach of your choice.
import pandas
epl = pandas.read_csv("football.csv")
diff = epl["Goals"]-epl["Goals Allowed"]
min_ind = diff.idxmin()
print epl["Team"][19]
| true |
8c1ce3b11bdaee1a2cea312cdd71334fd944ca25 | Manpreet-Bhatti/WordCounter | /word_counter.py | 1,477 | 4.28125 | 4 | import sys # Importing the ability to use the command line to input text files
import string # Imported to use the punctuation feature
def count_the_words(file_new): # Counts the total amount of words
bunch_of_words = file_new.split(" ")
amount_of_words = len(bunch_of_words)
return amount_of_words
def most_common(file_new): # Counts and prints the most common words in (word, count) format
for p in string.punctuation: # Cleans the punctuation
file_new = file_new.replace(p, " ")
new_words = file_new.lower().split()
lone = set() # Set of unique words
for w in new_words:
lone.add(w)
pairs = [] # List of (count, unique) tuples
for l in lone:
count = 0
for w in new_words:
if w == l:
count += 1
pairs.append((count, l))
pairs.sort() # Sort the list
pairs.reverse() # Reverse it, making highest count first
for i in range(min(10, len(pairs))): # Print the ten most frequent words
count, word = pairs[i]
print("%s: %d" %(word, count))
if __name__ == "__main__": # Run code below if a text file is inputted
if len(sys.argv) < 2:
print("Usage: python word_count.py <file name>.txt")
exit(1)
filename = sys.argv[1]
f = open(filename, "r")
file_data = f.read()
f.close()
most_common(file_data)
num_of_words = count_the_words(file_data)
print("The total number of words are: %d" %(num_of_words))
| true |
25cfb5db84e817269183a1686d9f4ff72edaaae4 | gcd0318/pe | /l5/pe102.py | 1,454 | 4.125 | 4 | """
Three distinct points are plotted at random on a Cartesian plane, for which -1000 ≤ x, y ≤ 1000, such that a triangle is formed.
Consider the following two triangles:
A(-340,495), B(-153,-910), C(835,-947)
X(-175,41), Y(-421,-714), Z(574,-645)
It can be verified that triangle ABC contains the origin, whereas triangle XYZ does not.
Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text file containing the co-ordinates of one thousand "random" triangles, find the number of triangles for which the interior contains the origin.
NOTE: The first two examples in the file represent the triangles in the example given above.
"""
def oriIsSameSide(x1, y1, x2, y2, x3, y3):
return (y1*(x2-x1)-x1*(y2-y1))*((x3-x1)*(y2-y1)-(x2-x1)*(y3-y1)) > 0
def oriIsIn(x1, y1, x2, y2, x3, y3):
res = True
i = 0
while(res and(i < 3)):
res = res and oriIsSameSide(x1, y1, x2, y2, x3, y3)
tx = x1
ty = y1
x1 = x2
y1 = y2
x2 = x3
y2 = y3
x3 = tx
y3 = ty
i = i + 1
return res
f = open('triangles.txt', 'r')
ls = f.readlines()
f.close()
i = 0
for l in ls:
sx1, sy1, sx2, sy2, sx3, sy3 = l.strip().split(',')
x1 = int(sx1)
y1 = int(sy1)
x2 = int(sx2)
y2 = int(sy2)
x3 = int(sx3)
y3 = int(sy3)
if oriIsIn(x1, y1, x2, y2, x3, y3):
i = i + 1
print(i)
| true |
9010ea2d997ec82fcd62f887802e1dc6f599f70f | edward408/bicycleproject | /bikeclasses.py | 1,717 | 4.25 | 4 | #Modeling the bicycle industry
#Classes layout
#Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs.
#Methods are essential in encapsulation concept of the OOP paradigm
class Bicycle(object):
def __init__(self,model,weight,production_cost):
self.model = model
self.weight = weight
self.production_cost = production_cost
self.retail_cost = self.production_cost * 1.20
class Bike_Shop(object):
"""Defines the bike shop with its respective inventory"""
def __init__(self,store_name):
self.store_name = store_name
self.store_inventory = []
self.affordable_bikes = []
def display_bikes(self):
print "The store is called %s and it has %s" % (self.store_name,self.bikes)
def bikes_under(self, budget):
for bike in self.store_inventory:
if bike.retail_cost <= budget:
self.affordable_bikes.append(bike)
def getAffordableBikes(self):
return self.affordable_bikes
class Customers(Bike_Shop):
def __init__(self,name,budget):
self.name = name
self.budget = budget
self.shopping_cart ={}
def purchase(self,store_inventory,affordable):
for bike in store_inventory:
if bike in affordable:
self.shopping_cart[bike.model]=bike.retail_cost
self.budget -=bike.retail_cost
store_inventory.remove(bike)
def display_customers(self):
print "Customer is %s and with a budget of %s dollars" % (self.name, self.budget)
| true |
93fe3bdc09d05d492d4752b3d3300120e9c6b902 | pratik-iiitkalyani/Data_Structure_and_Algo-Python- | /interview_problem/reverse_sentance.py | 576 | 4.375 | 4 | # Write a program to print the words of a string in reverse order.
# Sample Test Cases:
# INPUT: Hi I am example for this program
# OUTPUT: Program this for example am I Hi
def revrseSentanse(str):
# spilt all the word present in the sentance
sentance = str.split(" ")
# the first letter of last word of sentance will be capital
sentance[-1] = sentance[-1].title()
# reverse the sentance
input = sentance[::-1]
# join the words
output = ' '.join(input)
return output
str = "Hi I am example for this program"
print(revrseSentanse(str))
| true |
6d6c68769059fc9e98f45d934c014ca7d1d5c47d | bretuobay/fileutils | /exercises5.py | 684 | 4.1875 | 4 | '''
Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between.
For example, translate("this is fun") should return the string "tothohisos isos fofunon".
'''
def translate(str_input):
vowel_list = ['A', 'E', 'I', 'O', 'U']
temp = str_output = ''
# TODO: remove when there are spaces
for char in str_input:
if char.upper() not in vowel_list or char.isspace() == True :
temp = char + 'o' + char
else:
temp = char
str_output += temp
return str_output
print (translate("this is fun"))
| true |
d857a6d39e3b537539c9e5f74e45a11c78d1545f | bretuobay/fileutils | /exercises7.py | 440 | 4.59375 | 5 | '''
Define a function reverse() that computes the reversal of a string. For example, reverse("I am testing") should return the string
"gnitset ma I".
'''
# this works by slicing from the end
#This is extended slice syntax. It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses a string.
def reverse(input_str):
return input_str[::-1]
print(reverse("I am testing"))
| true |
dae27379e51e88f52d0cc08859b3c9486356acea | AndyTian-Devops/PythonSample | /PhoneBook.py | 950 | 4.28125 | 4 | #简单数据库
#使用人名作为键的字典,每个人用另一个字典表示,其中phone和addr分别表示他们的电话号码和地址
people = {
'Alice':{
'phone' : '2341',
'addr' : 'Foo drive 23'
},
'Beth':{
'phone' : '9102',
'addr' : 'Bar street 42'
},
'Cecil':{
'phone' : '3158',
'addr' : 'Baz avenue 90'
}
}
#针对电话号码和地址使用的描述性标签,会在打印输出的时候用到
labels = {
'phone': 'phone number',
'addr': 'address'
}
name = input('Name: ')
#查找电话号码还是地址?
request = input('phone number(p) or address(a)?')
#使用正确的键
if request == 'p':key='phone'
if request == 'a':key='addr'
#如果名字是字典中的有效键才打印信息:
if name in people : print("%s's %s is %s."% \
(name,labels[key],people[name][key]))
| false |
35b40ee37d55f57f862dd0d76bdf73ce42bf1c92 | rozeachus/Python.py | /NumberGuess.py | 1,035 | 4.40625 | 4 | """
This program will allow a user to guess a number that the dice will roll.
If they guess higher than the dice, they'll get a message to tell them they've won.
If its lower than the dice roll, they'll lose.
"""
from random import randint
from time import sleep
def get_user_guess():
guess = int(input("Guess a number.... "))
return guess
def roll_dice(number_of_sides):
first_roll = randint(1, number_of_sides)
second_roll = randint(1, number_of_sides)
max_val = number_of_sides * 2
print ("The maximum possible value is: %d" % max_val)
guess = get_user_guess()
if guess > max_val:
print ("This value is higher than the value allowed")
else:
print ("Rolling...")
sleep(2)
print ("The first roll is: %d" % first_roll)
sleep(1)
print ("The second roll is: %d" % second_roll)
sleep(1)
total_roll = first_roll + second_roll
print ("The result is....")
sleep(1)
if guess > total_roll:
print ("You've won!")
else:
print ("Sorry, you lost")
roll_dice(6)
| true |
e48d3a6156013fcea2a50ad2eddf5f13815baedf | luis95gr/mdh-python01-solutions | /Cod_d1/prueba5.py | 208 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 22 17:11:29 2019
@author: luis9
"""
import math as mt
my_num = int(input('Enter a number to find its factorial: '))
print("Factorial: " , mt.factorial(my_num))
| false |
0ba170e17e18c0b2a2bc93ed8fc6b18399a4687d | thiagocosta-dev/Atividades-Python-CursoEmVideo | /ex008.py | 306 | 4.1875 | 4 | '''
DESAFIO 008
Crie um programa que converta uma valor em metros recebido pelo teclado, em centímetros e milímetros.
'''
metros = float(input('Digite um valor em metros: '))
cent = metros * 100
mili = metros * 1000
print(f'{metros} convertidos para centímetros da {cent} e em milímetros é {mili}')
| false |
96ae307c72437a0d89d2afec2e8fafa73ea49551 | thiagocosta-dev/Atividades-Python-CursoEmVideo | /ex033.py | 476 | 4.125 | 4 | '''
DESAFIO 033
Faça um programa que leia três números e mostre qual é o maior e qual é menor
'''
n1 = int(input('1° Número: '))
n2 = int(input('2° Número: '))
n3 = int(input('3° Número: '))
if n1 > n2 and n1 > n3:
maior = n1
elif n2 > n1 and n2 > n3:
maior = n2
else:
maior = n3
if n1 < n2 and n1 < n3:
menor = n1
elif n2 < n1 and n2 < n3:
menor = n2
else:
menor = n3
print(f'O maior é: {maior}')
print(f'O menor é: {menor}')
| false |
78ac002848dfceb1477234110f3eaeecaf2850db | kelynch/python_workshop | /exercises/if_else.py | 363 | 4.40625 | 4 | #!/bin/python
#####
## Sample Python Exercise for WIC Programming Workshop
## November 2017
## Katherine Lynch
## If-Else
print("Pick a number between 1 and 10.")
number = int(raw_input())
if number > 10:
print("Your number is greater than 10.")
elif number <= 10 and number > 0:
print("Your number is between 1 and 10.")
else:
print("Your number is less than 1.")
| false |
a5a954481f937f566af621b3071afb1e90783ab3 | guti7/hacker-rank | /30DaysOfCode/Day08/phone_book.py | 1,020 | 4.3125 | 4 | # Day 8: Dictionaries and Maps
# Learn about key-value pair mappings using Map or a Dicitionary structure
# Given n names and phone numbers, assemble a phone book that maps
# friend's names to their respective phone numbers
# Query for names and print "name=phoneNumber" for each line, if not found
# print "Not found"
# Note: Continues to read lines until EOF.
import sys
n = int(raw_input().strip())
phone_book = {}
for i in range(n): # range max in not inclusive
info_array = list(raw_input().strip().split())
# Build dictionary structure
phone_book[info_array[0]] = info_array[1]
print info_array
print phone_book
# for line in sys.stdin:
# name = line.strip()
# if name in phone_book:
# print '%s=%s' % (name, phone_book[name])
# else:
# print "Not found"
while True:
try:
name = raw_input()
if name in phone_book:
print "%s=%s" % (name, phone_book[name])
else:
print 'Not Found'
except:
break
| true |
aeea679670645912d34b278ae177905d59c87bed | par1321633/problems | /leetcode_october_challenge/minimum-domino-rotations-for-equal-row.py | 2,457 | 4.375 | 4 | """
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the ith domino, so that A[i] and B[i] swap values.
Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same.
If it cannot be done, return -1.
Example 1:
Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2]
Output: 2
Explanation:
The first figure represents the dominoes as given by A and B: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
Example 2:
Input: A = [3,5,1,2,3], B = [3,6,3,3,4]
Output: -1
Explanation:
In this case, it is not possible to rotate the dominoes to make one row of values equal.
"""
from typing import List
class Solution:
def minDominoRotations(self, A: List[int], B: List[int]) -> int:
# print (A)
# print (B)
a_hash = {}
b_hash = {}
max_val_a = 0
max_val_b = 0
for i in range(len(A)):
# print (A[i], B[i])
if A[i] not in a_hash:
a = self.check_swap_numbers(A, B, A[i])
if a != -1:
a_hash[A[i]] = a
if B[i] not in b_hash:
b = self.check_swap_numbers(B, A, B[i])
if b != -1:
b_hash[B[i]] = b
# print (a_hash, b_hash)
if len(a_hash) == 0 and len(b_hash) == 0:
return -1
a_min = min([val for i, val in a_hash.items()])
b_min = min([val for i, val in b_hash.items()])
return min(a_min, b_min)
def check_swap_numbers(self, A, B, val):
# print (A, B, val)
swap_num = 0
for i in range(len(A)):
# print (A[i], B[i], val)
if A[i] != val and B[i] != val:
return -1
elif A[i] != val and B[i] == val:
swap_num = swap_num + 1
return swap_num
if __name__ == '__main__':
A = [2,1,2,4,2,2]
B = [5,2,6,2,3,2]
print ("Case 1 : A {}, B {}".format(A, B))
sol = Solution().minDominoRotations(A, B)
print ("Solution : {}".format(sol))
A = [3,5,1,2,3]
B = [3,6,3,3,4]
print("Case 2 : A {}, B {}".format(A, B))
sol = Solution().minDominoRotations(A, B)
print("Solution : {}".format(sol))
| true |
3c9ade5a1d56b9d4ec0e674c7b84b906c1c800fa | PiotrPosiadala/PythonLearning | /S005_L025-lambda.py | 1,050 | 4.25 | 4 | #Lambda - może przyjąć dowolną ilość argumentów
def double(x):
return x*2
x = 10
x = double(x)
print(x)
x = 10
f = lambda x: x*2 #po dwukropku tylko jedno wyrazenie
print(f(x))
#---#
def power(x,y):
return x**y
x = 5
y = 3
print(power(x,y))
f = lambda x,y: x**y
print(f(x,y))
#---#
list_numbers = [1,2,3,4,11,15,20,21]
def is_odd(x):
return x % 2 != 0
print(is_odd(7), is_odd(4))
#---#
#funkcja filter wykona dana funkcje dla kazdego elementu na lisice
# dzieki lambda dostajemy cos jak wyrazenie funkcyjne, funkcja jest anonimowa, nie ma zadnej nazwy
filtered_list = list(filter (is_odd, list_numbers))
print(filtered_list)
filtered_list = list(filter(lambda x: x % 2 != 0, list_numbers))
print(filtered_list)
#---#
# skupienie kilku liniek kodu w jednej
print(list(filter(lambda x: x % 2 != 0, list_numbers)))
# generowanie sobie funkcji
def generate_multiply_function(n):
return lambda x: n * x
mul_2 = generate_multiply_function(2)
mul_3 = generate_multiply_function(3)
print(mul_2(13), mul_3(8))
| false |
1cd2a64be451bc3b5375777c203dca390eb4b1cc | Deepak-Deepu/Thinkpython | /chapter-5/exercise5.4.py | 350 | 4.125 | 4 | a = int(raw_input('What is the length of the first side?\n'))
b = int(raw_input('What is the length of the first side?\n'))
c = int(raw_input('What is the length of the first side?\n'))
def is_triangle(a, b,c):
if a > (b+c):
print('No')
elif b>(a+c):
print('No')
elif c > (a+b):
print('No')
else:
print('Yes')
print is_triangle(a, b,c)
| true |
f718b2a829a17b71c720cacf6560e1240ef8d53f | GiovannaPazello/Projetos-em-Python | /AP1/Geração de n aleatórios.py | 1,554 | 4.125 | 4 | '''Faça um programa que gere números aleatórios entre 5 e 95 até gerar um número divisível por 7.
Quando isso ocorrer informar:
- a quantidade de números divisíveis por 4 e maiores que 30 que foram gerados
- a quantidade de números pares OU menores que 30 que foram gerados.
- o percentual de números pares e o percentual de números impares
- o percentual de números ímpares dentre os números gerados que eram menores que 60
- o maior número par gerado
- o menor número impar gerado'''
import random
cont = 0
lista = []
cont1 = 0
cont2 = 0
cont3 = 0
cont4 = 0
cont5 = 0
for i in range(100):
x = random.randint(5,20)
lista.append(x)
if x%7 == 0:
if len(lista)%4 == 0 and len(lista) > 30:
cont1 +=1
if len(lista)%2 == 0 and len(lista) <30:
cont2 +=1
if len(lista)%2 == 0:
cont3 +=1
if len(lista)%2 != 0:
cont4 += 1
if len(lista) < 60:
cont5 +=1
print('a quantidade de números divisíveis por 4 e maiores que 30 que foram gerados é {}'.format(cont1))
print('a quantidade de números pares OU menores que 30 que foram gerados são {}'.format(cont2))
print('o percentual de números pares é {}% e o percentual de números impares é {}%'.format(cont3,cont4))
print('o percentual de números ímpares dentre os números gerados que eram menores que 60 é {}'.format(cont5))
print('o maior número par gerado é {}'.format(max(lista, key=int)))
print('o menor número impar gerado {}'.format(min(lista,key=int)))
| false |
1ab94728578d070cf386755b9b15eab746d72bbe | Ameiche/Homework_22 | /Homework_22.py | 2,039 | 4.125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class linkedList:
def __init__(self):
self.head = None
def append(self, data):
newNode = Node(data)
if self.head == None:
self.head = newNode
return
else:
lastNode = self.head
while lastNode.next != None:
lastNode = lastNode.next
lastNode.next = newNode
def prepend(self, data):
newNode = Node(data)
if self.head == None:
self.head = newNode
return
else:
newNode.next = self.head
self.head = newNode
def insertAfterNode(self, prevNode, data):
newNode = Node(data)
newNode.next = prevNode.next
prevNode.next = newNode
def printList(self):
curNode = self.head
while curNode.next != None:
print(curNode.data)
curNode = curNode.next
if curNode.next == None:
print(curNode.data)
def deleteNode(self, key):
curNode = self.head
if curNode != None and curNode.data == key:
self.head = curNode.next
curNode = None
return
else:
prev = None
while curNode != None and curNode.data != key:
prev = curNode
curNode = curNode.next
if curNode == None:
print("The data is not found in the list")
return
else:
prev.next = curNode.next
curNode = None
# Testing the Linked List
linkedLst = linkedList()
linkedLst.append(5)
linkedLst.append(10)
linkedLst.printList()
linkedLst.prepend(15)
linkedLst.printList()
linkedLst.insertAfterNode(linkedLst.head.next, 6)
linkedLst.insertAfterNode(linkedLst.head.next.next, 8)
linkedLst.printList()
linkedLst.deleteNode(6)
linkedLst.deleteNode(20)
linkedLst.printList()
| false |
88350f210e517a64996c1b7a382a93447fda8792 | emilywitt/HW06 | /HW06_ex09_06.py | 951 | 4.3125 | 4 | #!/usr/bin/env python
# HW06_ex09_05.py
# (1)
# Write a function called is_abecedarian that returns True if the letters in a
# word appear in alphabetical order (double letters are ok).
# - write is_abecedarian
# (2)
# How many abecedarian words are there?
# - write function(s) to assist you
# - number of abecedarian words:
##############################################################################
# Imports
# Body
def is_abecedarian(word):
if len(word) <= 1:
return True
if word[0] > word[1]:
return False
return is_abecedarian(word[1:])
##############################################################################
def main():
with open("words.txt", "r") as fin:
count_abc = 0
total_words = 0
for line in fin:
total_words += 1
word = line.strip()
if is_abecedarian(word):
count_abc+= 1
print count_abc
# print is_abecedarian('best')
if __name__ == '__main__':
main()
| true |
9d9206ef57e6dfb7444b1eb1391f5d705fb3c929 | singhsukhendra/Data-Structures-and-algorithms-in-Python | /Chapter#02/ex_R_2_9.py | 2,612 | 4.34375 | 4 | class Vector:
""" Represent a vector in a multidimensional space."""
def __init__(self, d):
""" Create d-dimensional vector of zeros. """
self._coords = [0] * d
def __len__(self): # This special method allows finding length of class instance using len(inst) style .
""" Return the dimension of the vector. """
return len(self._coords)
def __getitem__(self, j): ## This special method let you get the value using square bracket notation. like inst[j]
""" Return jth coordinate of vector."""
return self._coords[j]
def __setitem__(self, j, val): ## This special method let you set the value using square bracket notation. like inst[j] = 10
""" Set jth coordinate of vector to given value."""
self._coords[j] = val
def __add__(self, other): ## lets you use + operator
""" Return sum of two vectors."""
if len(self) != len(other): # relies on len method
raise ValueError("dimensions must agree")
result = Vector(len(self)) # start with vector of zeros
for j in range(len(self)):
result[j] = self[j] + other[j]
return result
def __eq__(self, other): ## lets you use == operator
"""Return True if vector has same coordinates as other."""
return self._coords == other._coords
def __sub__(self, other): ## lets you use == operator
if len(self) != len(other): # relies on len method
raise ValueError("dimensions must agree")
"""Return True if vector has same coordinates as other."""
result = Vector(len(self))
for i in range(len(self)):
result[i] = self._coords[i] - other._coords[i]
return result
def __neg__(self): ## This special method let you use -inst
"""Produce string representation of vector."""
result = Vector(len(self))
for i in range(len(self)):
result[i] = - self._coords[i]
return result
def __ne__(self, other): ## lets you use != operator
""" Return True if vector differs from other."""
return not self == other # rely on existing eq definition
def __str__(self): ## This special method let you use print() function to print a representation of the class instance.
"""Produce string representation of vector."""
return '<' + str(self._coords)[1:-1] + '>' # adapt list representation
if __name__ == '__main__':
vec1 = Vector(3)
vec1[0] = 10
vec2 = Vector(3)
vec2[1] = 10
print(vec2)
print(-vec2)
| true |
40c50edae79808a40a98d5538f1fba55bdb58938 | fredzhangziji/myPython100Days | /Day9_Class_Object_Advanced/decorators.py | 2,312 | 4.25 | 4 | '''
python内置的 @property装饰器 (Decorators)
之前我们讨论过Python中属性和方法访问权限的问题,虽然我们不建议将属性设置为私有的,
但是如果直接将属性暴露给外界也是有问题的,比如我们没有办法检查赋给属性的值是否有效。
我们之前的建议是将属性命名以单下划线开头,通过这种方式来暗示属性是受保护的,不建议
外界直接访问,那么如果想访问属性可以通过属性的getter(访问器)和setter(修改器)
方法进行对应的操作。如果要做到这点,就可以考虑使用@property包装器来包装getter和
setter方法,使得对属性的访问既安全又方便,代码如下所示。
'''
class Person(object):
def __init__(self, name, age):
self._name = name
self._age = age
# 访问器 - getter方法
@property # python内置的装饰器@property
def name(self):
return self._name
# 访问器 - getter方法
@property
def age(self):
return self._age
# 修改器 - setter方法
@age.setter
def age(self, age):
# 在setter里可以用下面的方法来限定input
if not isinstance(age, int): # check if the input is an integer
raise ValueError('Age must be an integer!')
if age < 0 or age > 1000: # check if the input is in range 0-1000
raise ValueError('That\'s not a human\'s age!')
self._age = age
# @name.setter
# def name(self, name):
# self._name = name
def play(self):
if self._age <= 16:
print('%s正在玩飞行棋.' % self._name)
else:
print('%s正在玩斗地主.' % self._name)
def main():
person = Person('王大锤', 12)
person.play()
person.age = 22 # 这边能set成功是因为上面有@age.setter
person.play()
# person.name = '白元芳' # AttributeError: can't set attribute
# 因为@name.setter在上面被comment掉了
print(person.name)
print(person.age)
person.length = '18cm'
person.money = '$999999'
# person.age = -1 # ValueError will be raised
# person.age = 1001 # ValueError will be raised
if __name__ == '__main__':
main()
| false |
381fe255c58115bb31ccba6a94d3f69216367d9f | fredzhangziji/myPython100Days | /Day3_BranchStructure/practice1_cmToinch.py | 740 | 4.5 | 4 | '''
Convert between cm and inch
12/17/2019
written by Fred Zhang
'''
while True:
print("\n\n-------Welcome to cm/inch Converter Version 1.0-------")
print("Enter 'cm' for converting inch to cm;")
print("Enter 'inch for converting cm to inch;")
print("Enter 'e' for exiting the program.")
print("Select option: ")
selection = input()
if selection == 'cm':
inch = float(input('Enter inch: '))
cm = inch * 2.54
print("%.2f inches = %.2f cm" % (inch, cm))
elif selection == 'inch':
cm = float(input("Enter cm: "))
inch = cm / 2.54
print('%.2f cm = %.2f inch' % (cm, inch))
elif selection == 'e':
break
else:
print("Invalid input.") | true |
4db295d5fb56f4a6779bffc189e483f6fe58dfb0 | fredzhangziji/myPython100Days | /Day3_BranchStructure/practice2_pointToGrade.py | 678 | 4.15625 | 4 | '''
Convert 100-point scale to grade scale
12/17/2019
written by Fred Zhang
'''
print('\n\nYo this is a grade converter you sucker!\n')
point = int(input('put in your stupid-ass points here: '))
print()
if point <= 100 and point >= 90:
print('You got a fucking A. Greate fucking job!')
elif point < 90 and point >= 80:
print("B. Hmm. Can't you fucking do a lil better than dat?")
elif point < 80 and point >= 70:
print("You got a C. Did you take Dr. Canas' class?")
elif point <70 and point >= 60:
print("D. Noob.")
elif point < 60:
print("Go home kid. You fucking failed.")
else:
print("How'd fuck you get over 100 points? Reported.")
print() | true |
28df5a8ca0c2ed5bf2bdbc571844a352d9266fd8 | fredzhangziji/myPython100Days | /Day2_Variable_Operator/practice1_FahrenheitToCelsius.py | 1,227 | 4.53125 | 5 | '''
A simple program to convert between Fahrenheit and Celsius degrees.
12/17/2019
written by Fred Zhang
'''
while True:
print('**************************************************')
print('**************************************************')
print('Welcome to Fahrenheit and Celsius degree converter')
print('Enter the option:')
print('c for Fahrenheit to Celsius degree;')
print('f for Celsius to Fahrenheit degree;')
print('e for exiting the program.')
print('**************************************************')
print('**************************************************')
userInput = input()
if userInput == 'c':
DegreeF = float(input('Enter the Fahrenheit degree: '))
DegreeC = (DegreeF - 32) / 1.8
print('The Celsius degree is: ', DegreeC)
if userInput == 'f':
DegreeC = float(input('Enter the Celsius degree: '))
DegreeF = 1.8 * DegreeC + 32
print('The Fahrenheit degree is: ', DegreeF)
if userInput == 'e':
break
if userInput != 'c' and userInput != 'f' and userInput != 'e':
print('userInput at this point is: ', userInput)
print("Invalid input. Please enter a valid input.") | true |
6ff06eb58bc0deca7987c036855822e85e368745 | shivamsood/Python | /factorial.py | 267 | 4.46875 | 4 | #Code to calculate Factorial of the user entered integer
factorial_input = input("Please enter the number to calculate Factorial\n\n")
output = 1
while factorial_input >= 1:
output *= factorial_input
factorial_input -=1
print "The Factorial is {}".format(output) | true |
be172b3b278c917d476ef101884bf526e6997862 | youth-for-you/Natural-Language-Processing-with-Python | /CH-1/Exercises/10.py | 680 | 4.125 | 4 | #Define a variable my_sent to be a list of words,using the syntax my_sent = ["My", "sent"]
# (but with your own words, or a favorite saying).
#Use ' '.join(my_sent) to convert this into a string.
#Use split() to split the string back into the list form you had to start with.
if __name__ == '__main__':
my_sent = ['I', 'Love', 'Python', '!']
# join():连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串
str_my_sent = ' '.join(my_sent)
print(str_my_sent)
#输出I Love Python !
list_my_sent = str_my_sent.split()
print(list_my_sent)
#输出['I', 'Love', 'Python', '!']
| true |
11ff73edd6eb7d4142a374916bfcf13662ee83ff | poojatathod/Python_Practice | /max_of_list.py | 556 | 4.375 | 4 | #que 13: The function max() from exercise 1) and the function max_of_three() from exercise 2) will only work for two and three numbers, respectively. But suppose we have a much larger number of numbers, or suppose we cannot tell in advance how many they are? Write a function max_in_list() that takes a list of numbers and returns the largest one.
def max_of_list(list1):
return max(list1)
inpt=input("enter a list of element: ")
list1=inpt.split()
list1=[int(a) for a in list1]
output=max_of_list(list1)
print("maximum no from a list is: ",output)
| true |
e3d61428e98c35ba2812b991330964bc362a0f6c | poojatathod/Python_Practice | /translate.py | 1,023 | 4.15625 | 4 | #que 5: Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".
def translate(string):
c=0
list1=[]
for x in string:
for y in string1:
if(x==y):
c+=1
if(c==0):
list1.append(x)
list1.append("o")
list1.append(x)
else:
list1.append(x)
c=0
return ''.join(list1)
def translate1(string):
list1=[]
for x in string:
if x not in string1:
list1.append(x)
list1.append("o")
list1.append(x)
else:
list1.append(x)
return ''.join(list1)
string=(input("enter a string: "))
string1="aeiouAEIOU "
output=translate1(string)
print(output)
#alternative function for translate is translate1 both gives same output
| true |
ecc17cab948c55d4262611b10b8cf6152c5297d3 | poojatathod/Python_Practice | /longest_world.py | 401 | 4.34375 | 4 | #que 15: Write a function find_longest_word() that takes a list of words and returns the length of the longest one.
def longest_word(string):
list1=[]
for x in string:
list1.append=len(x)
outpt=max(list1)
outpt1=list1.index(outpt)
outpt2=string[outpt1]
return outpt2
string=input("enter a string: ")
string=string.split()
output=longest_word(string)
print(output)
| true |
8e8d9b4f6cca0fba2c9b14d044ae44aa017529d5 | GucciGerm/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 589 | 4.28125 | 4 | #!/usr/bin/python3
class MyList(list):
"""
MyList - Created this class to inherit components from list
Args:
list - This is the list that we will be inheriting from
Return:
None, will print the sorted inherited list
"""
def print_sorted(self):
"""
print_sorted - This will print the list, but sorted (ascending sort)
Args:
self - defining that we will just refer to itself
Return:
None
"""
print(sorted(self))
""" The function will print the list in sorted (ascending sort) """
| true |
04e3213d38a169dee4919acce36d7537edcfd27f | GucciGerm/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/3-say_my_name.py | 590 | 4.46875 | 4 | #!/usr/bin/python3
"""
say my name module
"""
def say_my_name(first_name, last_name=""):
"""
say_my_name -
This function will print "My name is <first><last>"
Args:
first_name - is the users first name
last_name - is the users last name
Return:
None
"""
def say_my_name(first_name="", last_name=""):
if type(first_name) != str:
raise TypeError("first_name must be a string")
if type(last_name) != str:
raise TypeError("last_name must be a string")
else:
print("My name is {} {}".format(first_name, last_name))
| true |
8b06343d1d12cd050ae44928ebcc321809abb08f | GucciGerm/holbertonschool-higher_level_programming | /0x0B-python-input_output/11-student.py | 772 | 4.21875 | 4 | #!/usr/bin/python3
class Student:
"""
Creating a class named Student
"""
def __init__(self, first_name, last_name, age):
"""
__init__ - Initializing attibutes
Args:
first_name - This is the first name passed
last_name - This is the last name passed
age - This is the age passed
Return:
Here we want to return the dictionary representation of student
instances
"""
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self):
"""
to_json - This will retrieve the dictionary representation
of Student instance
Return:
The dictionary
"""
return (self.__dict__)
| true |
7e1862d84df0221503be876775e5f752e6a994a4 | aitorlomu/SistemasGestores | /Python/Python/Ejercicios/09.py | 236 | 4.15625 | 4 | num=int(input('Introduzca el número de números que introducirá '))
max=0
for i in range(0,num):
introducido=int(input('Introduce un número '))
if introducido>max:
max=introducido
print('El máximo valor es ',max)
| false |
3c403aebce458271cc65041f15a420abb8f010b3 | Cipher-007/Python-Program | /Convert_miles_to_Km.py | 237 | 4.375 | 4 | #Converting Miles to Kilometers
miles = float(input("Enter Miles to be converted into Kilometers: "))
#Conversion factor
conversion_factor = 1.609
#Conversion
kilometers = miles * conversion_factor
print(f"{miles}mi is {kilometers}Km") | true |
352231acb77b2f54c15df747ec2d98514bbb3427 | toby20-meet/meet2018y1lab5 | /fruit_sorter.py | 224 | 4.15625 | 4 | new_fruit = input("What fruit would you like to choose?")
if "Apple"== new_fruit:
print('Bin1')
elif "Orange" == new_fruit:
print('Bin2')
elif 'Pear' == new_fruit:
print('bin3')
else:
print("wtf dis froot?")
| false |
13c88ffd58b096511ee71e2752e0dc588c71cfed | lchoe20/lchoe20.github.io | /challenge1.py | 806 | 4.21875 | 4 | #challenge 1 prompt: create a guess the number uding a while loop
from random import * #import * is a wild card that says import all information
aRandomNumber = randint(1,20) #inclsuive
#generates a randominteger
guess = input("Guess a number between 1 and 20 inclusive: ")
#assume user's guess is equal to 5
if not guess.isnumeric(): #checks to see if users guess is a real number
print("That's not a positive whole number, try again!")
else:
guess = int(guess) #converts a string to an integer
if guess < 1 or guess > 20:
print("That's not a positive whole number, try again!")
elif(guess > aRandomNumber):
print("Pick a smaller number")
elif(guess < aRandomNumber):
print("Pick a smaller number")
else:
print("You win!")
print("game over")
| true |
278597b789075960afb774815cf487ca6fc22cff | appledora/SecurityLab_2_3 | /Task_2/CeaserCipher.py | 1,575 | 4.1875 | 4 | import string
import time
alpha = string.ascii_letters
def ceaser_decrypt_without_key(target):
print("DECRYPTING....")
key = 0
while key <= 26:
temp = ""
for char in target:
if char.isalpha():
temp += alpha[(alpha.index(char)-int(key)) % 26]
else:
temp += char
print(temp + " ........... key: ", key)
key = key + 1
def ceaser_decrypt(target, shift):
print("DECRYPTING....")
temp = ""
temp = ""
for char in target:
if char.isalpha():
temp += alpha[(alpha.index(char)-int(shift)) % 26]
else:
temp += char
print(temp)
def main():
objType = input(
"type 1 if you want to decrypt a string with a key and 2 if you want to decrypt in Brute-force... \n")
if (int(objType) == 1):
target = input(
"Type the string you want to DECRYPT with a known KEY : \n")
shift = input("Enter the shift key : \n")
start_time = time.time()
ceaser_decrypt(target, shift)
print("--- %s seconds ---" % (time.time() - start_time))
elif (int(objType) == 2):
target = input("Type the string you want to brute-force DECRYPT : \n")
start_time = time.time()
ceaser_decrypt_without_key(target)
print("--- %s seconds ---" % (time.time() - start_time))
else:
print("Only select 1 or 2")
main()
print("Congratulations!")
if __name__ == "__main__":
main()
| true |
9802d5ff29b357a696ef27482b55450c1ea6f20e | DomaninaDaria/my_python_hw | /11-14.py | 1,707 | 4.21875 | 4 | import math
print("Exercise number 11")
def degrees_in_radians(degrees):
return (degrees * math.pi) / 180
degrees1 = 45
degrees2 = 40
degrees3 = 60
print("Cos of degrees(%d)= %.4f" % (degrees1, math.cos(degrees_in_radians(degrees1))))
print("Cos of degrees(%d)= %.4f" % (degrees2, math.cos(degrees_in_radians(degrees2))))
print("Cos of degrees(%d)= %.4f" % (degrees3, math.cos(degrees_in_radians(degrees3))))
print("------------------------------------------------------------------------")
print("Exercise number 12")
def sum_of_figures(number):
return number % 10 + number % 100 // 10 + number // 100
number1 = int(input("Input three-digit number: "))
if number1 // 1000 == 0:
print("Sum of figures is: ", sum_of_figures(number1))
else:
print("You entered more than three-digit number!")
def square_perimeter(cathetus_1, cathetus_2):
return cathetus_1 * cathetus_2 * 1/2, cathetus_1 + cathetus_2 + math.sqrt(cathetus_1**2 + cathetus_2**2)
print("------------------------------------------------------------------------")
print("Exercise number 13")
side_1 = int(input("Input value of cathetus 1 : "))
side_2 = int(input("Input value of cathetus 2: "))
if side_1 <= 0 or side_2 <= 0:
print("Error, sides of rectangle can not be <0 or =0")
else:
print("Square of rectangle is %.2f and Perimeter of rectangle is %.2f" % (square_perimeter(side_1, side_2)))
def even_or_not(number):
return number % 2 == 0
print("------------------------------------------------------------------------")
print("Exercise number 14")
n = int(input("Input the number"))
if even_or_not(n):
print("Number %d is even" % n)
else:
print("Number %d is not even" % n)
| false |
9603b36b1bba94a0929fb0c2d436e6257184fef8 | elizabethdaly/collatz | /collatz.py | 519 | 4.3125 | 4 | # 16 sept 2019 collatz.py
# n is the number we will perform Collatz on.
# n = 20
# Request user input.
n = int(input("Please enter an integer n: "))
# Keep looping until n = 1.
# Note: Assumes Collatz conjecture is true.
while n != 1:
# Print the current value of n.
print(n)
# Check if n is even.
if n % 2 == 0:
# If n is even, divide n by 2.
n = n / 2
else:
# If n is odd, multiply n by 3 and add 1.
n = (3 * n) + 1
# Finally, print the current value of n.
print(n)
| true |
2d0da772303ac46285ea43b6283a17c4823e52f3 | Noah-Huppert/ksp-sandbox | /src/lib/velocity.py | 1,716 | 4.53125 | 5 | """ calc_energy calculates the kinetic energy for a given body traveling in 1D
Arguments:
- m (float): Mass of body
- v (float): Velocity of body
Returns:
- float: Kinetic energy of body
"""
def calc_energy(m, v):
# Ensure kinetic energy is negative if velocity is negative
# (Separate logic necessary because velocity looses its sign in the eq due
# to being raised to the power of 2)
dir = 1
if v < 0:
dir = -1
# Kinetic energy eq: (1/2) * m * v^2
return dir * (m * (v ** 2)) / 2
""" calc_acceleration calculates the acceleration needed to accelerate from an
initial to final velocity in a specified length of time.
Arguments:
- vi (float): Initial velocity
- vf (float): Final velocity
- dt (float): Time
Returns:
- float: Acceleration
"""
def calc_acceleration(vi, vf, dt):
# Derived from formula: vf = vi + (a * t)
return (vf - vi) / dt
""" calc_delta_distance calculates the 1D distance travelled at a specific
velocity in a certain time.
Arguments:
- vi (float): Initial velocity
- vf (float): Final velocity
- dt (float): Time duration
Returns:
- float: Distance covered
"""
def calc_delta_distance(vi, vf, dt):
# Formula: d = (vi * t) + ((1/2) * a * t^2)
a = calc_acceleration(vi, vf, dt)
return (vi * dt) + (0.5 * a * (dt ** 2))
""" calc_force calculates the force needed to add the specified kinetic energy
to a body in a certain distance.
Arguments:
- delta_energy (float): Energy to add to the body
- delta_distance (float): Distance to add energy to body in
Returns:
- float: Force
"""
def calc_force(delta_energy, delta_distance):
return delta_energy / delta_distance
| true |
2801333709f62497a68f7925030ddbe55a0397b6 | MrZebarth/PythonCheatSheet2019 | /Conditionals.py | 977 | 4.40625 | 4 | # Conditionals
# We want to be able to make decisions based on our variables
# We use the "if" statment with a condition to check for a result
num1 = int(input("Enter a first number: "))
num2 = int(input("Enter a second number: "))
if num1 > num2:
print(num1, "is greater than", num2)
elif num1 < num2:
print(num1, "is less than", num2)
else:
print(num1, "is the same as", num2)
# You can have as many "elif" statements as you want. Each one must have a different condition
# The "else" statement always goes last. This is run if none of the other conditions are met.
# We can also use this with words and letters
password = input("Enter the password: ")
realPassword = "Pa$$w0rd"
if password == realPassword:
print("You got it!")
else:
print("Wrong password")
# Possible comparisons
# == equal
# != not equal
# > greater than
# < less than
# >= greater than equal
# <= less than equal
# and combine two conditions
# or one or the other condition
| true |
e957cb1c881194614a3d58e36d953c14a59da8b7 | sidamarnath/CSE-231-Labs | /lab12.py | 2,876 | 4.25 | 4 | #########################################
# lab12.py
# ALgorithm
# Create a vector class
# Have program do calculations
#########################################
class Vector():
def __init__(self, x = 0, y = 0):
self.__x = x
self.__y = y
#self.__valid = self.__validate()
def __str__(self):
''' returns a string as formal representation of vector'''
out_str = "(" + str(round(self.__x ,2)) + "," + str(round(self.__y,2)) + ")"
return out_str
def __repr__(self):
''' returns representation of vector'''
out_str = "({:02d},{:02d})".format(self.__x, self.__y)
return out_str
def __add__(self, v):
''' returns addition of vectors in Vector format'''
return Vector(self.__x + v.__x, self.__y + v.__y)
def __sub__(self, v):
''' returns subtraction of vectors in Vector format'''
return Vector(self.__x - v.__x, self.__y - v.__y)
def __mul__(self,v):
''' returns multiplication of vectors in Vector format'''
return Vector(self.__x * v.__x, self.__y * v.__y)
def magnitude(self):
''' returns magnitude of given vector'''
from math import sqrt
return sqrt(self.__x**2 + self.__y**2)
def __eq__(self, v):
''' returns true/false if vectors are equal '''
return self.__x == v.__x and self.__y == v.__y
def __rmul__(self, v):
''' returns multiplication but not in Vector format'''
return self.__x * v.__x + self.__y * v.__y
def unit(self):
''' function returns ValueError if magnitude = 0'''
result = self.magnitude()
if result == 0:
raise ValueError("Cannot convert zero vector to a unit vector")
def main():
''' function used for testing previous functions'''
# testing __inti__ and __str__
v1 = Vector(1,2)
v2 = Vector(3,4)
print(v1)
print(v2)
# testing __add__
v_ret = v1.__add__(v2)
print(v_ret)
v3 = Vector(5,-2)
v_ret = v1.__add__(v3)
print(v_ret)
v4 = Vector(-3,-3)
v_ret = v1.__add__(v4)
print(v_ret)
# testing __sub__
v_ret = v1.__sub__(v2)
print(v_ret)
v_ret = v1.__sub__(v4)
print(v_ret)
# testing __mul__
v_ret = v1.__mul__(v4)
print(v_ret)
v_ret = v1.__mul__(v2)
print(v_ret)
# testing __rmul__
v_ret = v1.__rmul__(v4)
print(v_ret)
# testing __eq__
v5 = Vector(3,4)
v_ret = v2.__eq__(v5)
print(v_ret)
v6 = Vector(0,0)
v_ret = v1.unit()
print(v_ret)
# testing unit function
v_ret = v6.unit()
print(v_ret)
main() | true |
adbe15cb36083194aa46ab708ce15c24a07628d6 | sidamarnath/CSE-231-Labs | /lab08b.py | 1,648 | 4.15625 | 4 | ###############################
# lab08b.py
# Algorithm
# Prints out student scores alphabetically
# If name appears more than once in file, add scores together
###############################
# read file function to open and read file
# takes in dictionary and filename as argument
def read_file(dictionary, filename):
# opens file and reads the lines
fp = open(filename, "r")
reader = fp.readlines()
# ignores the first line of the file
for line in reader[1:]:
#splits line into list
line_list = line.split()
name = line_list[0]
score = int(line_list[1])
# checks for name in dictionary
if name not in dictionary:
dictionary[name] = score
else:
# find the dublicate name in dictionary and combine scores
dictionary[name] += score
# display function displays results from read_file function
def display(dictionary):
# set to an empty list
display_list = list()
# adds name and scores into display list
for name, score in dictionary.items():
display_list.append((name, score))
# sorts list alphabetically
# formats results
display_list.sort()
print("{:10s} {:<10s}".format("Name", "Total"))
for item in display_list:
print( "{:10s} {:<10d}".format(item[0], item[1]))
def main():
dictionary = {}
read_file(dictionary, "data1.txt")
read_file(dictionary, "data2.txt")
display(dictionary)
main()
| true |
3bb6d95502446c35cdbfed74b9067dc54d6d165f | 0rps/lab_from_Alex | /school_42/d02/ex04_ft_print_comb.py | 579 | 4.1875 | 4 | # Create a function on display all different combination of three different digits in ascending order,
# listed by ascending order - yes, repetition is voluntary.
def print_comb():
number = ''
flag = False
for i in range(10):
for k in range(i+1, 10):
for l in range(k+1, 10):
number = str(i) + str(k) + str(l)
if flag:
print(', ' + number, end = "")
else:
print(number, end = '')
flag = True
if __name__ == "__main__":
print_comb() | true |
20cc7f1c4ff34b334763271c8ea7ccd73071786f | vlvanchin/learn | /learn_python/others/ver3/isOddOrEven.py | 259 | 4.46875 | 4 | #!/usr/bin/env python3
def even_or_odd(number):
'''determines if number is odd or even'''
if number % 2 == 0:
return 'Even';
else:
return 'Odd';
userinput = input("enter a number to check odd or even:");
print (even_or_odd(int(userinput)));
| true |
d46d6e0a8e63ca3ae1f83ecb50707a4f3fa48538 | grrtvnlw/grrtvnlw-python-103-medium | /tip_calculator2.py | 991 | 4.25 | 4 | # write a tip calculator based off user input and quality of service and divide bill in equal parts
# get user input for total bill amount, quality of service, how many ways to split, and tip amount
total_bill = float(input("Total bill amount? "))
service_level = input("Level of service - good, fair, or bad? ")
split = float(input("Split how many ways? "))
tip = 0
# calculate tip based off user input
if service_level == "good":
tip = total_bill * .20
elif service_level == "fair":
tip = total_bill * .15
elif service_level == "bad":
tip = total_bill * .10
# format tip, bill, and split bill to dollar amount and calculate total bill and split including tip
total_bill += tip
split_bill = total_bill / split
format_tip = '%.2f' % tip
format_total_bill = '%.2f' % total_bill
format_split_bill = '%.2f' % split_bill
# display formatted output
print(f"Tip amount: ${format_tip}")
print(f"Total amount: ${format_total_bill}")
print(f"Amount per person: ${format_split_bill}")
| true |
c4aaaaa193fb7ee3b670371978dcea295c908fbe | mtj6/class_project | /users.py | 1,199 | 4.125 | 4 | """A class related to users."""
class User():
"""Describe some users."""
def __init__(self, first_name, last_name, age, sex, race, username):
"""initialize user attributes"""
self.first_name = first_name
self.last_name = last_name
self.age = age
self.sex = sex
self.race = race
self.username = username
self.login_attempts = 0
def describe_user(self):
"""describe the user"""
print('\nName: ' + self.first_name.title() + ' ' + self.last_name.title())
print('Age: ' + str(self.age))
print('Sex: ' + self.sex)
print('Race: ' + self.race)
print('Username: ' + self.username)
print("Number of login attempts: " + str(self.login_attempts))
def increment_login_attempts(self):
"""increase number of login attempts"""
self.login_attempts += 1
def greet_user(self):
"""greet the user"""
print('Hello ' + self.first_name.title() + ' ' + self.last_name.title() + '!')
def reset_login_attempts(self):
"""reset the number of login attempts"""
self.login_attempts = 0
| true |
f1ab20d4eebdbddda94de673206edee24ee84712 | pugmomsf/oh-no-broken-code | /birthday.py | 1,228 | 4.3125 | 4 | from datetime import datetime
number_endings = {
1: 'st',
2: 'nd',
3: 'rd',
}
today = datetime.now()
todays_day = today.day
# get the right ending, e.g. 1 => 1st, 2 => 2nd
# but beware! 11 => 11th, 21 => 21st, 31 => 31st
# test your code by forcing todays_day to be something different
todays_day = 9
ending = 'th'
number = 0
#for date,ending in number_endings.items():
# print "%d has ending %s" % (date, ending)
print todays_day
if todays_day < 10 or todays_day > 20:
number = todays_day % 10
if number in number_endings:
ending = number_endings[number]
# print "Today is the {}".format(todays_day)+"%s" % ending
# % number_ending
# if todays_day >= 10 or todays_day <= 20:
print "Today is the {}".format(todays_day)+"%s" % ending
birthday = int(raw_input("What day of the month is your birthday?"))
# make this print the birthday, and the right ending
ending = 'th'
if birthday < 10 or birthday > 20:
number = birthday % 10
if number in number_endings:
ending = number_endings[number]
# print "Birthday is the {}".format(birthday)+"%s" % ending
# % number_ending
# if todays_day >= 10 or todays_day <= 20:
print "Birthday is the {}".format(birthday)+"%s" % ending
| false |
3c5d3674ea3d693969e7506308cd58946233a490 | gamer0/python_challenge | /challenge3.py | 487 | 4.1875 | 4 | #! /usr/python3
import sys
import string
import re
def find_pattern(file):
with open(file,'r') as f:
f_gen = (line for line in f.readlines())
my_pattern = re.compile(r'[a-z][A-Z][A-Z][A-Z]([a-z])[A-Z][A-Z][A-Z][a-z]')
match_list = [ my_pattern.search(line) for line in f_gen]
match_list = [ match.group(1) for match in match_list if match ]
return "".join(match_list)
if __name__ == '__main__':
list_of_matches = find_pattern(sys.argv[1])
print(list_of_matches)
| false |
dd7e6f9f16d72acd47a15a4fc73f1405641be2e7 | reginashay/cs102 | /homework01/caesar.py | 1,369 | 4.40625 | 4 | def encrypt_caesar(plaintext):
"""
Encrypts plaintext using a Caesar cipher.
>>> encrypt_caesar("PYTHON")
'SBWKRQ'
>>> encrypt_caesar("python")
'sbwkrq'
>>> encrypt_caesar("0123456")
'0123456'
>>> encrypt_caesar("@#^&*${}><~?")
'@#^&*${}><~?'
>>> encrypt_caesar("")
''
"""
ciphertext = ""
de = 26
i = 3
for c in plaintext:
if (68 <= ord(c)+i <= 90) or (100 <= ord(c)+i <= 122):
ciphertext += chr(ord(c)+i)
elif (ord(c) <= 64) or (91 <= ord(c) <= 96) or (123 <= ord(c)):
ciphertext += chr(ord(c))
else:
ciphertext += chr(ord(c)+i-de)
return ciphertext
def decrypt_caesar(ciphertext):
"""
Decrypts a ciphertext using a Caesar cipher.
>>> decrypt_caesar("SBWKRQ")
'PYTHON'
>>> decrypt_caesar("sbwkrq")
'python'
>>> decrypt_caesar("0123456")
'0123456'
>>> decrypt_caesar("@#^&*${}><~?")
'@#^&*${}><~?'
>>> decrypt_caesar("")
''
"""
plaintext = ""
de = 26
i = 3
for c in ciphertext:
if (65 <= ord(c)-i <= 87) or (97 <= ord(c)-i <= 119):
plaintext += chr(ord(c)-i)
elif (ord(c) <= 64) or (91 <= ord(c) <= 96) or (123 <= ord(c)):
plaintext += chr(ord(c))
else:
plaintext += chr(ord(c)-i+de)
return plaintext
| false |
2a1b822407b558eda90301a1bfec1f5c159c21cc | alexandermedv/Prof_python7 | /main.py | 1,502 | 4.25 | 4 |
class Stack():
"""Класс, реализующий стек"""
def __init__(self):
"""Инициализация класса"""
self.stek = ''
def isEmpty(self):
"""Проверка, пустой ли стек"""
if self.stek == '':
return True
else:
return False
def push(self, element):
"""Добавление элемента в стек"""
self.stek += element
def pop(self):
"""Удаление последнего элемента из стека"""
self.stek = self.stek[:-1]
def peek(self):
"""Последний элемент стека"""
if self.stek:
return self.stek[-1]
else:
return None
def size(self):
"""Количество элементов в стеке"""
return len(self.stek)
if __name__ == '__main__':
pairs = {'{': '}', '(': ')', '[': ']'}
string = input('Введите строку\n')
stack1 = Stack()
stack2 = Stack()
for symbol in string:
stack1.push(symbol)
while stack1.size() > 0:
if stack1.peek() in pairs and pairs[stack1.peek()] == stack2.peek():
stack1.pop()
stack2.pop()
else:
stack2.push(stack1.peek())
stack1.pop()
if stack2.size() == 0:
print('Сбалансированно')
else:
print('Несбалансированно')
| false |
32197a9d260623de1d6b2b98e3c1930f8a35115e | amarmulyak/Python-Core-for-TA | /hw06/uhavir/hw06_task1.py | 902 | 4.5625 | 5 | # Provide full program code of fibo(n) function which returns array with elements of Fibonacci sequence
# n - length of Fibonacci sequence.
# NOTE: The Fibonacci sequence it's a sequence where some element it's a sum of two previous elements
# --> 1, 1, 2, 3, 5, 8, 13, 21, 34,...
# EXAMPLE OF Inputs/Ouputs when using this function:
# ```
# >>> print fibo(6)
# [1, 1, 2, 3, 5, 8]
# ```
def fibonacci(n_terms):
# check if the number of terms is valid
n1 = 0
n2 = 1
# count = 0
if n_terms <= 0:
print("Please enter a positive integer")
elif n_terms == 1:
print("Fibonacci sequence upto", n_terms, ":")
print(n1)
else:
l = []
while len(l) < n_terms:
nth = n1 + n2
# update values
n1 = n2
n2 = nth
# count += 1
l.append(n1)
return l
print(fibonacci(6))
| true |
f7fa1e213ddd43ea879957bc309c5026addb905e | amarmulyak/Python-Core-for-TA | /hw06/amarm/task1.py | 634 | 4.375 | 4 | """
Provide full program code of fibo(n) function which returns array with
elements of Fibonacci sequence
n - length of Fibonacci sequence.
NOTE: The Fibonacci sequence it's a sequence where some element it's a
sum of two previous elements --> 1, 1, 2, 3, 5, 8, 13, 21, 34,...
EXAMPLE OF Inputs/Ouputs when using this function:
print fibo(6)
[1, 1, 2, 3, 5, 8]
"""
def fibo(n):
"""This function returns n-first numbers from the Fibonacci list"""
a = 0
b = 1
fibonacci_list = [a, b]
for i in range(n):
a, b = b, a + b
fibonacci_list.append(b)
return fibonacci_list[0:n]
print(fibo(10))
| true |
17e555d24c9b10c7748c183a1ac62960f9328ba5 | amarmulyak/Python-Core-for-TA | /hw03/pnago/task_2.py | 777 | 4.1875 | 4 | year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
day = int(input("Enter a day: "))
short_months = [4, 6, 9, 11]
# Check if it is a leap year
is_leap = False
if year % 4 != 0:
is_leap
elif year % 100 != 0:
is_leap = True
elif year % 400 != 0:
is_leap
else:
is_leap = True
# Date validation
if year < 0 or month < 1 or month > 12 or day > 31:
print("The date you have entered is invalid!")
elif month in short_months and day > 30:
print("The date you have entered is invalid!")
elif month == 2:
if day > 29:
print("The date you have entered is invalid!")
elif day == 29 and not is_leap:
print("The date you have entered is invalid!")
else:
print("year:", year, "month:", month, "day:", day)
| true |
b08dfa9c61ea32b40594f424dfb140002764f5a5 | amarmulyak/Python-Core-for-TA | /hw06/arus/fibo_func.py | 583 | 4.4375 | 4 | """Provide full program code of fibo(n) function which returns array with elements of Fibonacci sequence
n - length of Fibonacci sequence.
NOTE: The Fibonacci sequence it's a sequence where some element it's a sum of two previous elements --> 1, 1, 2, 3, 5, 8, 13, 21, 34,...
"""
def fibo_func(n):
i = 1
i1 = 1
list_value = 1
fibo_list = [list_value]
while n > len(fibo_list):
fibo_list.append(list_value)
i = i1
i1 = list_value
list_value = i + i1
print(fibo_list)
n = int(input("Enter any value "))
print(fibo_func(n))
| true |
5f0a74b243d2a0d0ed6d504936a19ede39175284 | amarmulyak/Python-Core-for-TA | /hw05/yvasya/hw05_5.py | 995 | 4.125 | 4 | # Дана матриця. Знайти в ній рядок з максимальною сумою елементів, а також стовпець.
from random import random
matrix = []
for i in range(5):
row = []
for j in range(5):
row.append(int(random()*10))
matrix.append(row)
for row in matrix:
print(row)
# sum of the row
biggest_row = []
for row in matrix:
row_sum = 0
for i in range(len(row)):
row_sum += row[i]
biggest_row.append(row_sum)
print("The sum of the rows is as following: ", biggest_row)
print("")
biggest_row = max(biggest_row)
print("The maximum sum of the rows is: ", biggest_row)
print("")
# sum of the column
biggest_col = []
for column in range(len(matrix[0])):
col_sum = 0
for row in matrix:
col_sum += row[column]
biggest_col.append(col_sum)
print("The sum of the columns is as following: ", biggest_col)
print("")
biggest_col = max(biggest_col)
print("The maximum sum of the column is: ", biggest_col)
| false |
11479ff5ed3027796c3c54b35c4edbc9609ffeac | amarmulyak/Python-Core-for-TA | /hw03/amarm/task1.py | 310 | 4.28125 | 4 | from calendar import monthrange
var_year = int(input("Type the year to found out if it's leap year: "))
february = monthrange(var_year, 2) # Here 2 means second month in the year
february_days = february[1]
if february_days == 29:
print("It's a leap year!")
else:
print("This is not a leap year!")
| true |
8c9320a9c918a667a1e308dc73b7cda9d1b7aa0b | amarmulyak/Python-Core-for-TA | /hw06/yvasya/hw06_01.py | 673 | 4.28125 | 4 | """
Provide full program code of fibo(n) function which returns array with elements of Fibonacci sequence
n - length of Fibonacci sequence.
NOTE: The Fibonacci sequence it's a sequence where some element it's a sum of two
previous elements --> 1, 1, 2, 3, 5, 8, 13, 21, 34,...
EXAMPLE OF Inputs/Ouputs when using this function:
print fibo(6)
[1, 1, 2, 3, 5, 8]
"""
fib_sequence = []
def fibo(n):
elem1 = 1
elem2 = elem1 + 0
fib_sequence.append(elem1)
fib_sequence.append(elem2)
for i in range(n-2):
elem_next = elem1 + elem2
elem1, elem2 = elem2, elem_next
fib_sequence.append(elem_next)
return fib_sequence
print(fibo(6))
| true |
c4cc1df080077fd565d9afbbb3a6c1129a00501c | aiqbal-hhs/python-programming-91896-JoshuaPaterson15 | /print_statement.py | 384 | 4.21875 | 4 | print("Hello and Welcome to this Digital 200 print statement.")
print("Here is string one." + "Here is string two.")
print("Here is string one times 5." * 5)
name = input("What is your name? ")
print("Welcome to Digital 200 {}.".format(name))
print("Line one \nLine two \nLine three")
print("""This is line one
this is line two
this is line three""")
| true |
336dc2fe84d34d3865e0209e77ea4d00e6cc9d31 | K4bl0-Skat3R/exercicios-02-2014 | /exercicio 05.py | 302 | 4.125 | 4 |
# algoritimo verificar se o numero e par ou impar
# aluno Genilson
# professor Habib
# exercicio 05
n1= input("digite um numero: ")
if n1 == 0:
print "Neutro" #usei essa opcao para testar o elif(zero e par porem nulo )
elif n1 %2 == 0:
print "este numero e par"
else:
print "este numero e impar"
| false |
1658511ddf06d9124b17445af3164864cdd45c39 | nilearn/nilearn | /examples/05_glm_second_level/plot_second_level_design_matrix.py | 1,994 | 4.34375 | 4 | """
Example of second level design matrix
=====================================
This example shows how a second-level design matrix is specified: assuming that
the data refer to a group of individuals, with one image per subject, the
design matrix typically holds the characteristics of each individual.
This is used in a second-level analysis to assess the impact of these
characteristics on brain signals.
This example requires matplotlib.
"""
try:
import matplotlib.pyplot as plt
except ImportError:
raise RuntimeError("This script needs the matplotlib library")
#########################################################################
# Create a simple experimental paradigm
# -------------------------------------
# We want to get the group result of a contrast for 20 subjects.
n_subjects = 20
subjects_label = [f"sub-{int(i):02}" for i in range(1, n_subjects + 1)]
##############################################################################
# Next, we specify extra information about the subjects to create confounders.
# Without confounders the design matrix would correspond to a one sample test.
import pandas as pd
extra_info_subjects = pd.DataFrame(
{
"subject_label": subjects_label,
"age": range(15, 15 + n_subjects),
"sex": [0, 1] * (n_subjects // 2),
}
)
#########################################################################
# Create a second level design matrix
# -----------------------------------
# With that information we can create the second level design matrix.
from nilearn.glm.second_level import make_second_level_design_matrix
design_matrix = make_second_level_design_matrix(
subjects_label, extra_info_subjects
)
#########################################################################
# Let's plot it.
from nilearn.plotting import plot_design_matrix
ax = plot_design_matrix(design_matrix)
ax.set_title("Second level design matrix", fontsize=12)
ax.set_ylabel("maps")
plt.tight_layout()
plt.show()
| true |
a19ab2d3920ca3f956ca83719af3124ff6b9b073 | lberge17/learning_python | /strings.py | 368 | 4.5 | 4 | my_string = "Hello world! I'm learning Python."
print("Hello")
print(my_string)
# using square brackets to access a range of characters
print(my_string[26:30]) # prints "Pyth"
# using commas to print two items
print("My message is:", my_string[13:33]) # prints "My message is: I'm learning Python."
# using string interpolation
print(f'My message is: {my_string}') | true |
ec39e9b0fffa050ae20a40a3a73bb23cbc5f606b | manisha-jaiswal/Division-of-apples | /problem19.py | 1,258 | 4.25 | 4 | """
-------------------------------------Problem Statement:--------------------------
Harry potter has got n number of apples. Harry has some students among whom, he wants to distribute the apples. These n number of apples are provided to harry by his friends and he can request for few more or few less apples.
You need to print whether a number in range mn to mx is a divisor of n or not.
Input:
Take input n, mn and mx from the user
Output:
Print whether the numbers between mn and mx are divisor of n or not. If mn = mx, show that this is not a range and mn is equal to mx. Show the result for that number
Example:
If n is 20 and mn=2 and mx = 5
2 is a divisor of 20
3 is not a divisor of 20
…
5 is a divisor of 20
"""
try:
apples = int(input("Enter the number of apples\n"))
mn = int(input("Enter the minimum number to check\n"))
mx = int(input("Enter the maximum number to check\n"))
except ValueError:
print('Enter integers only ')
exit()
if mn>=mx:
print('This can not be the range as the min should be less than max')
for i in range(mn, mx+1):
if apples%i == 0:
print(f"{i} is a divisor of {apples}")
else:
print(f"{i} is not a divisor of {apples}")
| true |
296fb4507878591bdde602c63284b9785971509d | hungd25/projects | /CS6390/HW2_P3.py | 2,213 | 4.59375 | 5 | """
"""
def get_input():
"""
# Get height and weight from the user and validate. If inputs are (negative numbers or strings),
the program should throw an error message.
: return: height, weight
"""
try:
# get user input and convert to type float
height_input = float(input("Enter the person's height: "))
weight_input = float(input("Enter the person's weight: "))
# check for negative numbers
if height_input > 0.0 and weight_input > 0.0:
return height_input, weight_input # return height and weight
else:
print("Negative values are not allowed.")
exit() # exit program
# if string values, then throw error message
except ValueError: # throw exception for float function during version of a non digit
print("Please enter only numbers.") # inform user of string input
exit() # exit program
def calculate_bmi(height_in, weight_in):
"""
This function calculates the body mass index
: param h: height
: param w: weight
: return: bmi: body mass index
"""
try:
bmi = (weight_in * 703) / (height_in ** 2) # calculate bmi
return bmi # return bmi
except Exception as error: # throws error when problem with calculation
print("There was error calculating BMI, message: %s" % error) # print error message
exit() # exit program
def calculate_weight_category(bmi):
"""
This function to compute one of the three weight categories
: param bmi:
: return: weight_category
"""
if 18.5 < bmi < 25: # if bmi is between 18.5 and 25
weight_category = 'optimal' # set category to optimal
elif bmi < 18.5: # if bmi is less than 18.5
weight_category = 'underweight' # set category to underweight
else: # bmi > 25
weight_category = 'overweight' # set category to overweight
return weight_category # return weight_cat
# get input
height, weight = get_input()
# get BMI
BMI = calculate_bmi(height, weight)
# get weight category and print it
print('Based on your BMI of %s . You are %s' % (round(BMI, 2), calculate_weight_category(BMI)))
# End of script
| true |
d4a8e2b76d5cce35ebceb4df5064a07886a2d14f | halysl/python_module_study_code | /src/study_checkio/Fizz buzz.py | 768 | 4.5 | 4 | '''
https://py.checkio.org/mission/fizz-buzz/
"Fizz buzz" is a word game we will use to teach the robots about division. Let's learn computers.
You should write a function that will receive a positive integer and return:
"Fizz Buzz" if the number is divisible by 3 and by 5;
"Fizz" if the number is divisible by 3;
"Buzz" if the number is divisible by 5;
The number as a string for other cases.
Input: A number as an integer.
Output: The answer as a string.
'''
def checkio(number):
if number%3 == 0 and number%5 == 0:
return("Fizz Buzz")
elif number%3 == 0 and number%5 != 0:
return ("Fizz")
elif number%3 != 0 and number%5 == 0:
return ("Buzz")
else:
return (str(number))
print(checkio(7)) | true |
12ab232125ed90cbb8c19aa08924a027f36a3146 | halysl/python_module_study_code | /src/study_checkio/Second Index.py | 1,015 | 4.28125 | 4 | '''
https://py.checkio.org/mission/second-index/
You are given two strings and you have to find an index of the second occurrence of the second string in the first one.
Let's go through the first example where you need to find the second occurrence of "s" in a word "sims". It’s easy to find its first occurrence with a function index or find which will point out that "s" is the first symbol in a word "sims" and therefore the index of the first occurrence is 0. But we have to find the second "s" which is 4th in a row and that means that the index of the second occurrence (and the answer to a question) is 3.
Input: Two strings.
Output: Int or None
'''
import re
def second_index(text: str, symbol: str):
try:
a = re.search(symbol,text).span()
a = list(a)
a = text[:a[0]]+text[a[1]:]
a = re.search(symbol, a).span()
a = list(a)
print(a)
return a[1]
except:
return None
second_index("find the river", "e") | true |
47d0464a02a778306eb170b12bd379fdfee93af4 | gramanicu/labASC | /lab02/task2.py | 1,164 | 4.25 | 4 | """
Basic thread handling exercise:
Use the Thread class to create and run more than 10 threads which print their name and a random
number they receive as argument. The number of threads must be received from the command line.
e.g. Hello, I'm Thread-96 and I received the number 42
"""
from random import randint, seed
from threading import Semaphore, Thread
import threading
# Thread Class
class SimpleThread(Thread):
# Constructor
def __init__(self, nr):
Thread.__init__(self)
self.nr = nr
# Main Thread Code
def run(self):
print ("Hello, I'm Thread-", threading.get_ident(), " and I received the number ", self.nr, sep='')
def main():
# The list of threads
thread_list = []
# Initialise the rng
seed()
num_of_threads = int(input("How many threads? "))
# Create and start the threads
for i in range(num_of_threads):
t = SimpleThread(randint(1, 100))
thread_list.append(t)
thread_list[i].start()
# Wait for the threads to finish
for i in range(len(thread_list)):
thread_list[i].join()
if __name__ == "__main__":
main() | true |
9a3238fa2a37850c15df278017457807432cde9c | flyingaura/PythonLearning | /PY.exercise/exer0905001.py | 1,873 | 4.1875 | 4 | """
定义一个有理数的类,并实现有理数据的加减乘除运算 Rational(N1,N2)
"""
from LearnModule import MY_math
class Rational(object):
def __init__(self,N1,N2 = 1):
if(not isinstance(N1,int) or not isinstance(N2,int)):
raise ValueError('有理数的分子和分母都必须为整数!')
if(N2 == 0):
raise ZeroDivisionError('分母不能为零!')
RN_GCD = MY_math.CalGCD(N1,N2)
self.numer = N1 // RN_GCD
self.denom = N2 // RN_GCD
def __add__(self,RN): #定义加法
if (isinstance(RN, int)):
RN = Rational(RN)
# RN_gcd = MY_math.CalGCD(self.numer,self.denom)
RN_lcm = MY_math.CalLCM(self.denom, RN.denom)
return Rational((self.numer * RN_lcm // self.denom + RN.numer * RN_lcm // RN.denom),RN_lcm)
def __sub__(self,RN): #定义减法
if (isinstance(RN, int)):
RN = Rational(RN)
RN_lcm = MY_math.CalLCM(self.denom, RN.denom)
return Rational((self.numer * int(RN_lcm / self.denom) - RN.numer * int(RN_lcm / RN.denom)), RN_lcm)
def __mul__(self,RN): #定义乘法
if(isinstance(RN,int)):
RN = Rational(RN)
return Rational(self.numer * RN.numer, self.denom * RN.denom)
def __truediv__(self, RN): #定义除法
if(isinstance(RN,int)):
RN = Rational(RN)
return Rational(self.numer * RN.denom, self.denom * RN.numer)
def __str__(self): #定义输出,分数化简输出
if(self.denom == 1):
return '%d' % (self.numer)
return '%d / %d' %(self.numer,self.denom)
# def __repr__(self):
# return self.__str__()
RN1 = Rational(19,27)
RN2 = 5.5
print(RN1,RN2)
print(RN1 + RN2)
print(RN1 - RN2)
print(RN1 * RN2)
print(RN1 / RN2)
# print(2//-4.10)
# print(isinstance(RN1,Rational)) | false |
c12079a7505f4a68a30fa8369852f79b52a6d51a | ssahai/python | /if.py | 331 | 4.15625 | 4 | #!/usr/bin/python
# To check whether the guessed number is correct (as per our fixed number)
num = 15
guess = int (raw_input ("Enter you guess : "))
if guess == num:
print 'You guessed it right!'
elif guess > num:
print 'Your guesses a larger number'
else:
print 'You guessed a smaller number'
print 'Program exits'
| true |
3ad3977085f0aa26d5674c2cb73bbdf592a9ec8e | Aniketa1986/pythonExercises | /fortuneSim.py | 962 | 4.4375 | 4 | # chapter 3, exercise 1
# Fortune Cookie
# Write a program that simulates a fortune cookie. The program should display one of five unique fortunes, at random, each time it’s run.
import random
#generate random number between 1 and 5
randomNum = random.randint(1,5)
#Unique fortune messages
fortune1 = "Some days you are pigeon, some days you are statue. Today, bring umbrella."
fortune2 = "Wise husband is one who thinks twice before saying nothing."
fortune3 = "Dijon vu -- the same mustard as before."
fortune4 = "The fortune you seek is in another cookie."
fortune5 = "A day without sunshine is like night."
print("Welcome to the fortune cookie simulator.\nHere you will get motivated like never. \n")
if randomNum == 1:
print(fortune1)
elif randomNum == 2:
print(fortune2)
elif randomNum == 3:
print(fortune3)
elif randomNum == 4:
print(fortune4)
else: print(fortune5)
print("Now get back to your work!")
| true |
0be016a9ac85a98615dc90cc9e7c3a51015f989b | omarsaad0/Python-Learning | /Python_Elzero/039_PracticalEmailSlice.py | 423 | 4.40625 | 4 | # Practical Email Slice
# email = "omarsaad2411@gmail.com"
the_name = input("What\' Your Name ? ").strip().capitalize()
the_email = input("What\' Your Email ? ").strip().capitalize()
the_username = the_email[:the_email.index("@")].strip().capitalize()
the_domain = the_email[the_email.index("@")+1:].strip()
print(f"Hello {the_name} Your Email is {the_email}")
print(f"Your Username Is {the_username} \nYour Website Is {the_domain} ")
| false |
d99af8d7a19d0e1545818127008ba451c76e0669 | zainab404/zsfirstrepo | /packing_with_dictionaries.py | 390 | 4.375 | 4 | #packing is when you can pass multiple arguments.
#here, we used **kwargs to signify the use of multiple arguments.
#the for loop will iterate over the arguments given and print each one
def print_student(**kwargs):
for key,value in kwargs.items():
print("{} {}".format(key,value))
print_student(name = "Zainab", job = "Programmer", major = "ISOM", boyfriend = "Guillermo")
| true |
6aa6d30c03cb59c7a67036aeb778971356e70959 | wherby/hackerrank | /Temp/Scala/add.py | 406 | 4.1875 | 4 | def addInt(input):
if "a" in input and "b" in input:
a = input["a"]
b = input["b"]
try:
int(a)
try:
int(b)
return a+b
except:
print b + " is not int"
except:
print a + " is not int"
else:
print "a or b not in input parameters"
print addInt({"a":1,"b":2}) | true |
2d47bef22ea73a37b69df451cd60b9df4834603a | Andrewzh112/Data-Structures-and-Algorithms-Practice | /Two Pointers II.py | 1,257 | 4.15625 | 4 | # Valid Palindrome
class Solution:
"""
@param s: A string
@return: Whether the string is a valid palindrome
"""
def isPalindrome(self, s):
start, end = 0, len(s) - 1
while start < end:
while start < end and not s[start].isalnum():
start += 1
while start < end and not s[end].isalnum():
end -= 1
if start < end and s[start].lower() != s[end].lower():
return False
start += 1
end -= 1
return True
# Valid PalindromeII
class Solution2:
"""
@param s: a string
@return bool: whether you can make s a palindrome by deleting at most one character
"""
def validPalindrome(self, s):
# Write your code here
start, end = 0, len(s) - 1
while start < end:
if s[start] != s[end]:
return self.isSubPalindrome(start+1, end, s) or self.isSubPalindrome(start, end-1, s)
start += 1
end -= 1
return True
def isSubPalindrome(self, start, end, s):
while start < end:
if s[start] != s[end]:
return False
start += 1
end -= 1
return True
| true |
958cb78be722ee0cf1de35a0587da701bc078646 | WayneGoodwin95/Algorithms | /selection_sort.py | 710 | 4.125 | 4 | """
SELECTION SORT
loop through list keeping track of smallest unchecked index (min_index)
if another index is smaller swap the value to min_index
once looped through, change the minimum index to the next array element
repeat
"""
def selectionSort(my_arr):
min_index = 0
for min_index in range(len(my_arr)):
min_value = my_arr[min_index]
for j in range(min_index, len(my_arr)):
if my_arr[j] < my_arr[min_index]:
min_value = my_arr[j]
my_arr[j] = my_arr[min_index]
my_arr[min_index] = min_value
return my_arr
my_arr = [22, 11, 99, 88, 9, 7, 42]
print('output [7, 9, 11, 22, 42, 88, 99]')
print(selectionSort(my_arr))
| true |
7fa50383b8b022efbad2ea5bfef8fa843a199411 | lvsheng/practice | /program-arcade-games/lab1/part-a.py | 307 | 4.15625 | 4 | #!/usr/bin/env python
# enter a temperature in Fahrenheit, prints the temperature in Celsius
def fah_to_cels(temp):
return (temp - 32)/1.8
if __name__ == "__main__":
fah_temp = float(input("Enter temperature in Fahrenheit:"))
print("The temperature in Celsius: ", str(fah_to_cels(fah_temp)))
| false |
97bc3c6267200c16610d7e6725c022b0f47730a2 | andre-lobo/Complete-Python-Bootcamp | /011-if_elif_else.py | 446 | 4.1875 | 4 | #if, elif and else examples
if True:
print("It was True")
print()
x = False
if x:
print("x was True")
else:
print("x was False")
print()
loc = "Bank"
if loc == "Auto Shop":
print("Welcome to the Auto Shop")
elif loc == "Bank":
print("Welcome to the Bank")
elif loc == "Mall":
print("Welcome to the Mall")
else:
print("Where are you?")
print()
person = "Sam"
if person == "Sam":
print("Hi Sam!")
else:
print("What's your name?") | true |
4069e07be02c7875a78c5353569166a681f9f091 | andre-lobo/Complete-Python-Bootcamp | /005-lists.py | 961 | 4.34375 | 4 | #lists examples
my_list = [1, 2, 3]
my_another_list = ["text", 23, 1.3, "A"]
print(len(my_list))
print(len(my_another_list))
my_another_list = ["One", "Two", "Three", 4, 5]
print(my_another_list[0])
print(my_another_list[1:])
print(my_another_list[:3])
print("\n Add new item in list")
#add new item in list
my_list = my_list + [4]
my_another_list = my_another_list + ["Five"]
print(my_list)
print(my_another_list)
print(my_list * 2)
print("\n Append")
#append
l = [1, 2, 3]
l.append("append me")
print(l)
print(l.pop())
print(l)
x = l.pop(0)
print(x)
print(l)
print("\n Sort")
#sort
new_list = ["a", "e", "x", "b", "c"]
new_list.reverse()
print(new_list)
new_list.sort()
print(new_list)
new_list.sort(reverse = True)
print(new_list)
print("\n Matrix")
#matrix
l_1 = [1, 2, 3]
l_2 = [4, 5, 6]
l_3 = [7, 8, 9]
matrix = [l_1, l_2, l_3]
print(matrix)
print(matrix[0])
print(matrix[0][2])
first_col = [row[0] for row in matrix]
print(first_col) | false |
7a8de130d4c4ee9fccf98ce22e0fb60dd647b0da | Sabrina-Sumona/Python-learning | /oop_1.py | 1,344 | 4.125 | 4 | class StoryBook:
# CLASS VARIABLE
no_of_books = 0
discount = 0.5
def __init__(self, name, price, author_name, author_born, no_of_pages):
# setting the instance variables here
self.name = name
self.price = price
self.author_name = author_name
self.author_born = author_born
self.publishing_year = 2020
self.no_of_pages = no_of_pages
StoryBook.no_of_books += 1
# regular method 1
def get_book_info(self):
print(f'The book name: {self.name}, price: {self.price}, pages: {self.no_of_pages}')
# regular method 2
def get_author_info(self):
print(f'The author name: {self.author_name}, born: {self.author_born}')
# applying discount to an instance
def apply_discount(self):
self.price = int(self.price - self.price * StoryBook.discount)
# creating an instance/object of the StoryBook class
book_1 = StoryBook('Hamlet', 350, 'Shakespeare', 1564, 500)
book_2 = StoryBook('the_kite_runner', 200, 'khaled hosseini', 1965, 200)
# book_1.get_book_info()
# StoryBook.get_book_info(book_1)
#
# book_1.get_author_info()
# print(book_1.publishing_year)
# print(book_2.price)
# print(book_1.no_of_books)
# print(book_2.no_of_books)
# print(StoryBook.no_of_books)
print(book_2.price)
book_2.apply_discount()
print(book_2.price)
| true |
ce0093d47a713ba94d838410e642adcfe1c6073f | StenNick/LearnPython | /if_else.py | 1,788 | 4.25 | 4 | #---------- if, else
cars = ["bmw", "audi", "subaru", "solswagen", "lada", "mercedes", "skoda"]
for item in cars:
if item == "audi":
print(item.upper(), ' make upper')
else:
print(item.title())
#---- проверка вхождения значений в список с помощью оператора - in
colors = ['red', 'blue', 'white', 'black', 'purple']
def checkColor():
if 'red' in colors:
print("Yes, it's true!")
else:
print("No")
checkColor()
#--- убедимся что значения в списке отсутствуют
numbers = [10, 546, 100, 230, 540]
def checkNumbers():
if 888 not in numbers:
print("888 hot have in list")
else:
print("888 have in list...")
checkNumbers()
#--- if elif
age = 12
if age < 4:
print("Your age more them is 4")
elif age < 18:
print("Your age less them is 18")
else:
print("good bye")
topping = ["mushrooms", "tobasco", "green papers", "cheese", "red peppers", "sauce","chicken"]
pizza = ["meat", "greenery", "tobasco", "chicken"]
for ingredients in pizza:
if ingredients in topping:
print("adding " + ingredients + ".")
else:
print("Sorry")
names = ["Franco", "Georgy", "Mikle", "Admin"]
for items in names:
if items == "Admin":
print("Hello Admin! Would you like to see a status report?")
elif items != "Admin":
print("Weclome " + items + " how are you?")
else:
print("Sorry, invalid password")
Weclome Franco how are you?
Weclome Georgy how are you?
Weclome Mikle how are you?
Hello Admin! Would you like to see a status report?
current_users = ["Franco", "Georgy", "Mikle", "John", "Bob"]
new_users = ["Nick", "Julia", "Mikle", "Mayble", "Jesica", "John"]
| false |
273b56a48a8bcb4eccfd6020852347a27407649c | Napster56/Sandbox | /function_scpoe_demo.py | 666 | 4.21875 | 4 | def main():
"""Demo function for scope of an immutable object."""
x = 3 # int is immutable
print("in main, id is {}".format(id(x)))
function(x)
print("in func, id is {}".format(id(x)))
def function(y: int):
print("in func, id is {}".format(id(y)))
y += 1 # assignment creates a new object
print("in func, id is {}".format(id(y)))
main()
# reference equality
# returns: in main, id is 1396426896 }
# in func, id is 1396426896 } sharing the same object
# after assignment y += 1:
# in main, id is 1396426896
# in func, id is 1396426896
# in func, id is 1396426928 # assignment creates a new object
| true |
87f0528ad87ca333109df2a21864358aff4f4a8e | Napster56/Sandbox | /reverse_text_recursively.py | 284 | 4.28125 | 4 | """
Function to reverse a string recursively.
"""
def reverse(text):
if len(text) < 2: # base case
return text
else:
# recursive step = reverse(rest of text) + first char of text
return reverse(text[1:]) + text[0]
print(reverse("photon")) | true |
1abc35b03c60414bb9261d3ffa35ebfb9c9faefa | Napster56/Sandbox | /Classes demo/person.py | 1,260 | 4.15625 | 4 | """
Program to create a person class
"""
from datetime import datetime
class Person():
def __init__(self, first_name="", last_name="", dob="01/01/1900", gender="female"):
self.first_name = first_name
self.last_name = last_name
self.dob = dob
self.gender = gender
def calculate_age(self):
date = datetime.strptime(self.dob, '%d/%m/%Y')
age = ((datetime.today() - date).days / 365)
return age
def __str__(self):
age = self.calculate_age()
return "{self.first_name}, who is a {self.gender}, was born on {self.dob} and is {:.0f} old".format(age,
self=self)
person1 = Person("Dave", "Fields", "10/12/1934", "male")
person2 = Person("Sue", "Jones", "26/01/1966")
person3 = Person("Fred", "Watson", "17/09/1946", "male")
person4 = Person("Leslie", "Farrow", "06/02/1984")
print(person1)
class Lecturer(Person):
def __init__(self, title="Lecturer", college="Business, Law and Governance", tenure_in_years=1):
super(). __init__(title, college, str(tenure_in_years))
def __str__(self):
return ""
lecturer1 = Lecturer("Senior Lecturer", 12)
| false |
165bd77cb033c6535f0ebf67d16986a24f83dd7f | Napster56/Sandbox | /CreditCard_class.py | 2,471 | 4.15625 | 4 | """
Create a class for a consumer credit card
"""
class CreditCard:
def __init__(self, customer, bank, account, limit):
"""Make a new credit card instance
The initial balance is zero.
"""
self.customer = customer
self.bank = bank
self.account = account
self.limit = limit
self.balance = 0
def get_customer(self):
"""Return the name of the customer"""
return self.customer
def get_bank(self):
"""Return the bank's name"""
return self.bank
def get_account(self):
"""Return the card id number"""
return self.account
def get_limit(self):
"""Return credit limit"""
return self.limit
def get_balance(self):
"""Return the current balance"""
return self.balance
def debit_card(self, price):
"""Charge price to the card, if sufficient credit limit
Return True if charge was processed; False if charge denied
"""
if price + self.balance > self.limit:
return False
else:
self.balance += price
return True
def make_payment(self, amount):
"""Process customer payment to reduce balance"""
self.balance -= amount
def __str__(self):
return "Customer = {}, Bank = {}, Account = {}, Balance = {}, Limit = {}".format(self.customer, self.bank,
self.account, self.account, self.limit)
Joe = CreditCard("Jeff", "ANZ", "555 555", 2500)
print(Joe)
if __name__ == '__main__':
wallet = []
wallet.append(CreditCard("John Doe", "CBA", "5391 0375 9387 5309", 1000))
wallet.append(CreditCard("John Doe", "NAB", "3485 0399 3395 1954", 3500))
wallet.append(CreditCard("John Doe", "Westpac", "2248 1362 0477 3900", 5500))
for i in range(1, 55):
wallet[0].debit_card(i)
wallet[1].debit_card(2 * i)
wallet[2].debit_card(3 * i)
for i in range(3):
print(("Customer =", wallet[i].get_customer()))
print(("Bank =", wallet[i].get_bank()))
print(("Account =", wallet[i].get_account()))
print(("Balance =", wallet[i].get_balance()))
print(("Limit =", wallet[i].get_limit()))
while wallet[i].get_balance() > 500:
wallet[i].make_payment(500)
print(("New balance =", wallet[i].get_balance()))
print()
| true |
689b0af2411c98e7bd92590ceb0b24d8ac68b254 | Napster56/Sandbox | /user_name.py | 547 | 4.3125 | 4 | """
Ask user for their name
Tell them how many vowels are in their name
Tell them how many capitals are in their name
"""
count_vowels = 0
name = "Bobby McAardvark"
# name = input("Name: ")
for letter in name:
if letter.lower() in 'aeiou':
count_vowels += 1
print("Out of {} letters, {} has {} vowels".format(len(name), name, count_vowels))
# str function retuns a list of letters
print(str([letter for letter in name if letter.isupper()]))
# join is a string method & returns
print("".join([letter for letter in name if letter.isupper()])) | true |
5f522189d56fe7cd74fcdd8153ada80032a89cee | Napster56/Sandbox | /Classes demo/circle_class.py | 498 | 4.46875 | 4 | """
Program to create a Circle class which inherits from the Shape class.
The subclass Circle extends the superclass Shape; Circle 'is-a' Shape.
"""
from shape import Shape
class Circle(Shape):
def __init__(self, x=0, y=0, radius=1):
super().__init__(x, y) # used to access the instance of the Shape class
self.radius = radius # redefines the __init__ with a new instance variable
def area(self):
from math import pi
return self.radius ** 2 * pi
| true |
f4ca8f55ec31d63d82b33b20a76085bcb6a258ea | Napster56/Sandbox | /file_methods.py | 813 | 4.15625 | 4 | """
# readline method
temp = open("temp.txt", "r") # open file for reading
first_line = temp.readline() # reads exactly one line
print(first_line)
for line in temp: # read remaining lines
print(line)
temp.readline() # read file, return empty string
print(temp)
temp.close()
# read method
temp = open("temp.txt", "r") # open file for reading
print(temp.read(1)) # reads exactly one char
print(temp.read(2)) # reads next 2 chars
print(temp.read()) # read remaining file
temp.close()
"""
# readlines method
temp = open("temp.txt", "r") # open file for reading
file_contents = temp.readlines() # read all file lines into a list
print(file_contents)
string = "to be or not to be"
temp.write(string)
print(temp)
temp.close()
| true |
5e1390f2bdc9044de2dd6049ef3a5e0632cbf2c6 | Djheffeson/Python3-Curso-em-Video | /Exercícios/ex060.py | 330 | 4.1875 | 4 | from math import factorial
num = int(input('Digite um número para calcular seu fatorial: '))
fact = factorial(num)
print('Calculando {}! = '.format(num), end='')
while num != 0:
if num == 1:
print('{}'.format(num), end=' = ')
else:
print('{}'.format(num), end=' x ')
num -= 1
print('{}'.format(fact))
| false |
d9d5bca64263b592ac66cc580cf3d8aff5315a62 | teeradon43/Data_Structure | /Lab/LinkedList/lab43.py | 2,422 | 4.125 | 4 | """
Chapter : 6 - item : 3 - MergeOrderList
จงเขียนฟังก์ชั่นสำหรับการ Merge LinkList 2 ตัวเข้าด้วยกันโดยห้ามสร้าง Class LinkList จะมีแต่ Class Node
ซึ่งเก็บค่า value ของตัวเองและ Node ถัดไป โดยมีฟังก์ชั่นดังนี้
createList() สำหรับการสร้าง LinkList ที่รับ List เข้ามาโดยจะ return Head ของ Linklist
printList() สำหรับการ print LinkList โดยจะรับค่าเป็น head ของ Linklist และจะทำการ print ทุกตัวที่อยู่ใน
Linklist ต่อจาก head จนครบทุกตัว
mergeOrderList() สำหรับการ merge linklist 2 ตัวเข้าด้วยกันโดยให้นำมาต่อกันโดยเรียงตามค่า value โดยที่ให้รับ
parameter 2 ตัว และจะ return Head ของ Linklist ที่ทำการ merge แล้ว
****ห้ามใช้ sort() หากพบข้อนี้จะไม่ได้คะแนน****
****ห้ามสร้าง Class LinkList****
"""
"""
Test Cases
Testcase : #1 1
Enter 2 Lists : 1,3,5,7,10,20,22 4,6,7,8,15
LL1 : 1 3 5 7 10 20 22
LL2 : 4 6 7 8 15
Merge Result : 1 3 4 5 6 7 7 8 10 15 20 22
Testcase : #2 2
Enter 2 Lists : 1,4,5,5,6,7 2,3,6,9,10
LL1 : 1 4 5 5 6 7
LL2 : 2 3 6 9 10
Merge Result : 1 2 3 4 5 5 6 6 7 9 10
Testcase : #3 3
Enter 2 Lists : 2,2,2,10 1,1,1,1,5,5,5,6,7,8
LL1 : 2 2 2 10
LL2 : 1 1 1 1 5 5 5 6 7 8
Merge Result : 1 1 1 1 2 2 2 5 5 5 6 7 8 10
"""
class node:
def __init__(self,data,next = None ):
self.data = data
self.next = next
def __str__(self):
pass
def createList(l=[]):
l = list(l)
return l
def printList(H):
return 0
def mergeOrderesList(p,q):
return 0
#################### FIX comand ####################
# input only a number save in L1,L2
L1, L2 = input('Enter 2 Lists : ').split(' ')
LL1 = createList(L1)
LL2 = createList(L2)
print('LL1 : ',end='')
printList(LL1)
print('LL2 : ',end='')
printList(LL2)
m = mergeOrderesList(LL1,LL2)
print('Merge Result : ',end='')
printList(m) | false |
4a50ac2346aee77dfd6080be2541d3c810b04cea | alexisdavalos/DailyBytes | /BinaryTreeVisibleValues/binaryTreeVisibleValues.py | 921 | 4.21875 | 4 | # Given a binary tree return all the values you’d be able to see if you were standing on the left side of it with values ordered from top to bottom.
# This is the class of the input binary tree. Do not Edit!
class Tree:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
def visibleValues(root):
# Your Code Here
return
# Ex: Given the following tree…
#
# --> 4
# / \
# --> 2 7
# return [4, 2]
tree = Tree(4)
tree.left = Tree(2)
tree.right == Tree(7)
# Ex: Given the following tree…
#
# --> 7
# / \
# --> 4 9
# / \ / \
# --> 1 4 8 9
# \
# --> 9
# return [7, 4, 1, 9]
tree = Tree(7)
tree.left = Tree(4)
tree.right = Tree(9)
tree.left.left = Tree(1)
tree.left.right = Tree(4)
tree.right.left = Tree(8)
tree.right.right = Tree(9)
tree.right.right.right = Tree(9)
| true |
6681a57d55dbe2ea18d6f6d5c65776935455dde9 | alexisdavalos/DailyBytes | /MakePalindrome/makePalindrome.py | 524 | 4.1875 | 4 | # Write a function that takes in a string with any set of characters
# Determine if that string can become a palindrome
# Returns a Boolean after processing the input string
def makePalindrome(string):
# Your Code Here
return
# Test Cases Setup
print(makePalindrome("aabb")) # => true (abba)
print(makePalindrome("asdf")) # asdf => false
print(makePalindrome("asdfasdf")) # asdfasdf => true (asdffdsa)
print(makePalindrome("aaabb")) # aaabb => true (baaab)
print(makePalindrome("racecar")) # racecar => true
| true |
dc4b771cc52cb1a5d19e2a5e07858472fcb9254d | razorblack/python_programming | /PythonPractice/PrimeOrComposite.py | 307 | 4.28125 | 4 | userInput = int(input("Enter a number to check for prime \n"))
count = 0 # To count no. of factors of user input number
for i in range(2, userInput):
if userInput % i == 0:
count += 1
if count > 0:
print(f"{userInput} is composite number")
else:
print(f"{userInput} is a prime number")
| true |
e5e647601be99ae9e20aa7c3f0f37f4867a18802 | razorblack/python_programming | /PythonLab/Program6.1.py | 673 | 4.125 | 4 | # Method to perform Linear Search
def linear_search(list_of_number, no_to_search):
size = len(list_of_number)
for i in range(0, size):
if list_of_number[i] == no_to_search:
print(f"Search Successful: Element found at index {i}")
return
print("Search Unsuccessful: Element Not Found")
return
size_of_list = int(input("Enter the size of the list \n"))
entered_list = []
for i in range(0, size_of_list):
entered_list.append(int(input("Enter a element in list \n")))
print("Entered list is:")
print(entered_list)
search_number = int(input("Enter a number to search in list \n"))
linear_search(entered_list, search_number)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.