blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
f19d6e9e46c6a3265b4625ef98f952e14861a862
|
artopping/nyu-python
|
/course1/assignment_5/exercises_test.py
| 404
| 4.125
| 4
|
x = (raw_input("would you like to convert fahrenheit(f) or celsius(c)? "))
if x == "f":
y = (raw_input("what is the fahrenheit?"))
f = (int(y) - 32) * 5.0 / 9
print ("and in celsius, that is: "),
print (f)
elif x == "c":
y = (raw_input("what is the celsius?"))
f = (int(y) *9) / 5.0 + 32
print ("and in fahrenheit, that is: "),
print (f)
else:
print ("Error)
| false
|
d3c1a39d1a4f9e21ea569ae1bc0720314ae856e2
|
artopping/nyu-python
|
/course1/assignment_5/test.py
| 284
| 4.28125
| 4
|
#!/usr/bin/env python
import sys
def convert_f2c(S):
"""(str): float
Converts a Fahrenheit temperature represented as a string
to a Celsius temperature.
"""
fahrenheit = float(S)
celsius = (fahrenheit - 32) * 5 / 9
return celsius
print (celsius)
| false
|
8ba5229b9bf24c36eec6fc113b1b020064b8ed87
|
artopping/nyu-python
|
/course2/session2/classses_session2.py
| 710
| 4.4375
| 4
|
#!/usr/bin/env python3
#Classes: storage of data and set of functions that define the class
# class has a function and data (local to itself)
# when you want to use it< instance= MyClass()>
class MyClass:
pass
#obect my_circle as instance of Class circle
# think of class as bucket...lot of room, for data storage and defs
#
class Circle:
pi = 3.14159
def __init__(self, radius=1): #self is container that everything is placed in
self.radius=radius
def area(self):
#return self.radius**2 *3.14159
return self.radius**2 * Circle.pi #using the global class
if __name__=='__main__':
my_circle = Circle(2)
print (my_circle.area())
my_circle.radius=10
print (2*3.14159*my_circle.radius)
| true
|
89db7f6519f2542bec43ceecaa3be231b1e429af
|
vivekgupta8983/python3
|
/range.py
| 269
| 4.21875
| 4
|
#!/usr/bin/python3
#range functions returns a sequence for number start from o and ends ta specific number
#range(start, stop, step)
# for i in range(100):
# print(i)
# for i in range(2, 10, 2):
# print(i)
my_range = range(1, 10)
print(my_range.index(3))
| true
|
064cb46b734706c23c60ce872fb16fccecee22a4
|
nikileeyx/learning_python
|
/2. Dictionary and List/2002_codeReusing.py
| 842
| 4.34375
| 4
|
#The Code Reusing 1.0 by @codingLYNX
'''
Note: In this question, 0 is considered to be neither a positive number nor negative number.
You are to implement the following three functions with the following specifications:
is_odd(x) returns True if the input parameter x is odd, False otherwise.
is_negative(x) returns True if the input parameter x is negative, False otherwise.
is_even_and_positive(x) returns True if the input parameter x is even AND positive, False otherwise.
'''
def is_odd(x):
if x%2 == 0:
return False
else:
return True
def is_negative(x):
if x < 0:
return True
else:
return False
def is_even_and_positive(x):
if x == 0:
return False
elif is_odd(x) or is_negative(x):
return False
else:
return True
| true
|
dffa406f4b6f6f5d0ee226b49991d5b9f625a711
|
zeydustaoglu/8.hafta_odevler-Fonksiyonlar
|
/11. OzgunListe.py
| 507
| 4.21875
| 4
|
# Verilen bir listenin içindeki özgün elemanları ayırıp yeni bir liste olarak veren bir fonksiyon yazınız.
# Örnek Liste : [1,2,3,3,3,3,4,5,5] Özgün Liste : [1, 2, 3, 4, 5]
try:
newListe = []
def ozgunListe(list):
for i in list:
if i not in newListe:
newListe.append(i)
newListe.sort()
print(newListe)
ozgunListe([1, 1, 2, 2, 5, 4, 8, 7, 5, 1, 7, 4, 6, 9, 8, 9, 3, 5])
except:
print('Hatali islem. Program sonlandirildi.. ')
| false
|
690f4504114a972a0c3aa1b2021b820880eff724
|
kmurphy13/algorithms-hw
|
/dac_search.py
| 736
| 4.1875
| 4
|
# Kira Murphy
# CS362 HW2
def dac_search(lst: list, key) -> bool:
"""
Function that searches for an item in an unsorted array by splitting the array into halves
and recursively searching for the item in each half
:param lst: The unsorted array
:param key: The item being searched for
:return: True if the item is in the list, false otherwise
"""
if len(lst) == 1:
if lst[0] == key:
return True
else:
return False
return dac_search(lst[:len(lst)//2], key) or dac_search(lst[len(lst)//2:len(lst)], key)
if __name__ == "__main__":
lst = [138, 0, 3, 36, 29, 13, 9, 12, 110, 1, 0, 12, 5, 0, 1, 0, 1, 1, 4, 11, 52, 12, 2, 1, 2, 4, 99]
print(dac_search(lst,99))
| true
|
5ceff881fad153efd3b9ce95dfd6b77c7b9f55fa
|
cheung1/python
|
/help.py
| 441
| 4.15625
| 4
|
#1.write the triangle print code
# notice: when you just define, it cannot execute
#2.define a function
def printTriangle():
'this is the help document '
print ' * '
print ' * * '
print '* * *'
#3.invoke the function
#notice:only can via the invoke to use the function
# invoke the function: write the function name,then add a pair of bracket
printTriangle()
#notice:define only once,but can invoke infite times
printTriangle()
| true
|
520ac63216a371940b7c98b2a152bd67b73c1bff
|
abhisjai/python-snippets
|
/Exercise Files/Ch2/functions_start.py
| 1,780
| 4.78125
| 5
|
#
# Example file for working with functions
#
# define a basic function
def func1():
print("I am a function")
# func1()
# Braces means to execute a function
# value on console was any print command inside the function
# If there was any return value, it was not assigned to any variable
# print(func1())
# Execute a function and print its value
# While executing it also prints any Print statements to console
# It also prints return value = None as there was no return value from inside the function
# print(func1)
# Function does not executes at all
# It only prints function defination which means functions are objects that can be passed around
# function that takes arguments
def func2 (argv1, argv2):
print(argv1, " ", argv2)
# func2(10, 20)
# print(func2(10, 20))
# function that returns a value
def cube(x):
return x*x*x
# cube(3) # This does not print any value. Return value is not assigned to any variable.
# print(cube(3))
# function with default value for an argument
def power(num, x=1):
result = 1
for i in range(x):
#Multiple number by itself for
result = result * num
return result
# print(power(2))
# # In case of missing parameters, function used default assigned value of x
# print(power(2, 3))
# # Even if x was assigned a value, you can override it when calling a function
# print(power(x=5, num=2))
# # order of arguments does not matter if you absolutely define them
#function with variable number of arguments
def multi_add(*argv):
result = 0
for x in argv:
result = result + x
return result
print(multi_add(5, 10, 25, 5))
print(multi_add(1, 2, 3, 4, 5))
# You can combine variable argument list with formal parameters
# Keep in mind, varibale argument list is last parameter
| true
|
4239a7ae04f3adc3b0546b9e18d03d7dbd90946c
|
abhisjai/python-snippets
|
/Misc Code/python-tuples.py
| 1,180
| 4.28125
| 4
|
# Task
# # Given an integer n and n space-separated integers as input, create a tuple t, of those n integers. Then compute and print the result of
# Note: hash() is one of the functions in the __builtins__ module, so it need not be imported.
# Input Format
# The first line contains an integer, n, denoting the number of elements in the tuple.
# The second line contains space-separated integers describing the elements in tuple .
# Source: https://www.hackerrank.com/challenges/python-tuples/problem
n = int(input())
# Map: map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)
# Syntax: map(fun, iter)
# Parameters :
# fun : It is a function to which map passes each element of given iterable.
# iter : It is a iterable which is to be mapped.
# a single value that denotes how many numbers should be passed to a list
n = int(input())
# print(f"Input from console {n}")
# Convert all inputs from console and type cast them into int.
integer_list = tuple(map(int, input().split()))
# print(integer_list[0])
print(hash(integer_list))
# This is a random string
| true
|
9b5aae311a253e7f46830efdb6e8bc2c00d67f9e
|
abhisjai/python-snippets
|
/Python Essential/Exercise Files/Chap03/sequence.py
| 603
| 4.15625
| 4
|
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# x = [ 1, 2, 3, 4, 5 ]
# for i in x:
# print('i is {}'.format(i))
x = {"one": 1, "two": 2, "three": 3, "four": 4}
# for i in x:
# print("key {}".format(i))
# for key, value in x.items():
# print("key {0:<5} value {1:<5}".format(key, value))
#Dictionaries are mutable - you can change value after initial assignment
# x['three'] = 42
# for key, value in x.items():
# print("key {0:<5} value {1:<5}".format(key, value))
x['five'] = 5
for key, value in x.items():
print("key {0:<5} value {1:<5}".format(key, value))
| false
|
708d5102fb648b48abd4dd3886f5bb923cf2b856
|
varunmalik123/Python-Data-Analysis
|
/write_columns.py
| 930
| 4.53125
| 5
|
def write_columns(data,fname):
"""
The purpose of this function is to take a list of numbers and perform two calculations on it.
The function will generate a csv file with three columns containing the original data and the
result from the first to calculations respectively
:param data(list with elements being either floats or ints): Input data
:param fname(str): File name of output csv
"""
assert isinstance(data, list)
assert isinstance(fname, str)
assert (len(data) > 0)
for elements in data:
assert isinstance(elements, (int, float))
import csv
fname = fname + ".csv"
with open(fname, "w") as out:
big_big = []
for no in data:
temp_list = []
temp_list.append('{0:.2f}'.format(no))
temp_list.append(" " + '{0:.2f}'.format((no**2)))
temp_list.append(" " + '{0:.2f}'.format(((no + no**2)/3)))
big_big.append(temp_list)
writer = csv.writer(out)
writer.writerows(big_big)
| true
|
5f6fb8aae1249d25774cf94ddea5c0fb8b9d41a2
|
Demon520-coder/PythonStudy
|
/study_08/Dog.py
| 597
| 4.40625
| 4
|
#创建类:
#注意点:1.约定类的首字母大写;2.类的构造函数为:__init__;3.类中的每一个方法都必须传递self形参,因为python在创建实例时会自动传递self;
#3.python类没有构造函数重载;
class Dog():
def __init__(self,name,age):
self.name=name
self.age=age
def sit(self):
print("This dog has beeb sit")
def show(self):
msg="Dog's name is "+self.name+"\n"
msg+="Dog's age is "+str(self.age)+"years"
print(msg)
def roll_over(self):
print("Look!This dog can roll over!!!")
| false
|
252bbca8310794f46c6eb24afacc135492508421
|
Demon520-coder/PythonStudy
|
/study_01/homework.py
| 1,427
| 4.34375
| 4
|
#01.输出一段字符串:
print('This is my first python program')
#02.定义一个变量,并输出大写,小写,首字母大写形式
name='Mr jonh james'
print(name.upper())
print(name.lower())
print(name.title())
#03.去除字符串首位空格、末尾空格、首位空格
address=' Beijin '
print('|'+address+'|')
print('|'+address.lstrip()+'|')
print('|'+address.rstrip()+'|')
print('|'+address.strip()+'|')
#04.定义列表集合,输出集合中的第一个、最后一个,修改其中某一个,删除其中一个元素
names=['zzl','bob','jonh','alice']
print(names[0])
print(names[-1])
names.append('tom') #追加元素
names.append('bruce')
del names[-1] #删除最后一个元素
names[0]='zzl_01' #修改第一个元素
#排序:永久排序--->通过集合对象调用排序方法;临时排序:Sorted
beforeSort=names.copy()
print(names)
beforeSort.sort()
print(beforeSort)
print(sorted(names))
print('names len='+str(len(names)))
#05.定义一个数字集合
numbers=list(range(1,30,2))
print(numbers)
#倒序输出
numbers.reverse()
#循环输出列表集合中的元素
for n in numbers:
print(n)
#输出最大、最小、求和、平均值
print('max='+str(max(numbers)))
print('min='+str(min(numbers)))
print('sum='+str(sum(numbers)))
print('avg='+str(sum(numbers)/len(numbers)))
#计算每个数的平方和
sequarNumbers=[]
for x in numbers:
sequarNumbers.append(x**2)
print(sequarNumbers)
| false
|
d8df82383460b7c1730b7d2af1623a797fb35e5e
|
ra3738/Latext
|
/hasConsSpace.py
| 1,261
| 4.15625
| 4
|
#Checks if current index is a space, returns boolean
def isThisASpace(str, index):
if (str[index] == " "):
return True
else:
return False
#Checks if current index and next index are spaces, returns boolean
#If at second last index, returns false
def hasConsSpaces(str, index):
if (index + 1 < len(str)):
if (isThisASpace(str, index) and isThisASpace(str, index+1)):
return True
else:
return False
else:
return False
#Counts no. of consecutive spaces, returns int
def howManySpaces(str, index):
length = len(str)
index = index
n = 0
while (index < length):
if (isThisASpace(str,index)):
n = n + 1
index = index + 1
else:
return n
return n
#replaces spaces number of indices after and including index with strToReplaceWith
#Returns string
def replaceSpaces(strToReplace, index, strToReplaceWith, spaces):
strList = list(strToReplace)
while (not(spaces== 0)):
strList[index] = strToReplaceWith
index = index + 1
spaces = spaces - 1
return "".join(strList)
testString = " m m "
i = 0
while (i < len(testString)):
if (hasConsSpaces(testString, i)):
j = howManySpaces(testString, i)
print(j)
testString = replaceSpaces(testString, i, "", j)
i = i + j - 1
else:
i = i + 1
print(testString)
#comment
| true
|
3060d4c3f53a1a2a35e9c41f79cf6c5c8b08402f
|
JadedCoder712/Character-Distribution
|
/testing123.py
| 2,877
| 4.21875
| 4
|
"""
distribution.py
Author: Kyle Postans
Credit: Kyle Postans, Mr. Dennison
Assignment:
Write and submit a Python program (distribution.py) that computes and displays
the distribution of characters in a given sample of text.
Output of your program should look like this:
Please enter a string of text (the bigger the better): The rain in Spain stays mainly in the plain.
The distribution of characters in "The rain in Spain stays mainly in the plain." is:
iiiiii
nnnnnn
aaaaa
sss
ttt
ee
hh
ll
pp
yy
m
r
Notice about this example:
* The text: 'The rain ... plain' is provided by the user as input to your program.
* Uppercase characters are converted to lowercase
* Spaces and punctuation marks are ignored completely.
* Characters that are more common appear first in the list.
* Where the same number of characters occur, the lines are ordered alphabetically.
For example, in the printout above, the letters e, h, l, p and y both occur twice
in the text and they are listed in the output in alphabetical order.
* Letters that do not occur in the text are not listed in the output at all.
"""
"""What I want to do is make a list of uppercase and lowercase lists.
Then make a thing that takes the list of upper/lowercase letters and creates a variable for each letter with the number of times it shows up.
Then create a list of those variables (which have numbers of letters in the sentence attached to them). Sort them by amount.
"""
sentence = input("Please enter a string of text (the bigger the better): ")
print('The distribution of characters in "{0}" is: '.format(sentence))
import string
from operator import itemgetter, attrgetter, methodcaller
bignumber=len(sentence) #unnecessary
numbers=range(1, int(bignumber)) #unnecessary
sentencelist=list(sentence) #turns the sentence into a list of letters
megalist= string.ascii_lowercase #makes a list of lowercase letters
finallist=[] #creates final list in order to put tuples into
sentence1=[x.lower() for x in sentencelist] #makes all letters lowercase
#The Actual Program:
#creating the list of tuples by putting each letter with the times they appear in the sentence:
for letter in megalist:
number=sentence1.count(letter)
if number is not int(0):
variables=(number, letter)
finallist.append(variables)
#sorting the tuple list into reverse alphabetical order, then leaving those properties in place while puttiing it order of appearance AND alphabetical order:
finallist1=sorted(finallist, key=itemgetter(0,1))
#finallist2=sorted(finallist1, key=itemgetter(0))
#finallistreversed=list(reversed(finallist1))
#print(finallistreversed)
finallistreversed = list(finallist1)
#creating the actual list of letters by multiplying the letters in the tuples by the amount of times they appear:
for x,c in finallistreversed:
if x is not int(0):
print(x*c)
| true
|
0cc275639d9847d73865c59c944c271b99605bb7
|
RohitPr/PythonProjects
|
/07. Banker Roulette/7.Banker_Roulette.py
| 502
| 4.34375
| 4
|
"""
You are going to write a program which will select a random name from a list of names.
The person selected will have to pay for everybody's food bill.
Important: You are not allowed to use the choice() function.
"""
import random
names_string = 'Angela, Ben, Jenny, Michael, Chloe'
names = names_string.split(", ")
names_list = list(names)
names_length = len(names_list)
result = random.randint(0, names_length - 1)
person_who_will_pay = names_list[result]
print(person_who_will_pay)
| true
|
b504f63cabe4ac1ad9f493410378566fda23f66b
|
CihanKeles/ACM114_Sec2
|
/Week6/nested_for_exp.py
| 614
| 4.1875
| 4
|
num_students = int(input('How many students do you have? '))
num_test_scores = int(input('How many test scores per student? '))
for student in range(num_students):
total = 0.0
print('Student number', student + 1)
print('-----------------')
for test_num in range(num_test_scores):
print('Test number', test_num + 1, end='')
score = float(input(': '))
# Add the score to the accumulator.
total += score
average = total / num_test_scores
print('The average for student number', student + 1, \
'is:', format(average, '.1f'))
print()
| true
|
799fcd9e6c1b9ad2b4f8bd37dcb14989a808bb59
|
CihanKeles/ACM114_Sec2
|
/Week14/ACM114_Quiz_Week13_solution.py
| 864
| 4.125
| 4
|
import random
# The main function.
def main():
# Initialize an empty dictionary.
number_dict = dict()
# Repeat 100 times.
for i in range(100):
# Generate a random number between 1 and 9.
random_number = random.randint(1, 9)
# Establish or increment the number in the dictionary.
if random_number not in number_dict:
number_dict[random_number] = 1
else:
number_dict[random_number] += 1
# Display the results.
print('Number\tFrequency')
print('------ ---------')
# The "sorted" function produces a sorted version of
# the list of key-value pairs from the "items" method.
for number, frequency in sorted(number_dict.items()):
print(number, frequency, sep='\t')
# Call the main function.
main()
| true
|
b0b91399237afcfe69a0b2c78428f139f658950f
|
tanngo1605/ProblemSet1
|
/problem5/solution.py
| 583
| 4.1875
| 4
|
#This is a really cool example of using closures to store data.
# We must look at the signature type of cons to retrieve its first and last elements. cons takes in a and b, and returns a new anonymous function, which itself takes in f, and calls f with a and b. So the input to car and cdr is that anonymous function, which is pair. To get a and b back, we must feed it yet another function, one that takes
# in two parameters and returns the first (if car) or last (if cdr) one.
def car (pair)
return pair(lambda a, b:a)
def cdr(pair)
return pair(lambda a,b: b)
| true
|
0f9544217d43d0c5ffeb6be1d93d2e33ef345bd0
|
tutunamayanlar2021/Python
|
/tuple.py
| 324
| 4.21875
| 4
|
tuple =(1,"iki",3)
list=[1,2,"kader"]
print(type(tuple))
print(type(list))
print(len(tuple))
list=["ali","veli"] #güncelleme
# tuple=["sena","polo"]
list[0]="ahmet" #degitirebiliyoruz
#tuple[0]=2 #degiştirilemez
print(tuple.count(1))
names=("nobody","who") +tuple #toplma işlemi yapılabiliyor
print(list)
print(names)
| false
|
24c3d30472fa0fb9cfe9d8f018b4e39dfb3592da
|
tutunamayanlar2021/Python
|
/list_methods_Exsample.py
| 1,086
| 4.46875
| 4
|
names=["Ali","yağmur","hakan","Deniz"]
years= [1998,2000,1998,1987]
# "cenk"ismini listenin sonuna ekleyin
names.append("Cenk")
#"sena"ismini listenin basına ekleyin
names.insert(0,"Sena")
#'deniz'ismini listeden siliniz
#names.remove("deniz")
# index=names.index("Deniz")
# print(index)
# names.pop(index)
# print(names)
#"deniz" isminin indexsi nedir
# result="Deniz" in names
# print(result)
#"ali "listenin bir elemnı mıdır
respons="kader"in names
respons=names.index("Ali")
print(respons)
#liste elemanlarını ters cevirin
names.reverse()
#liste elemanlarını alfetik olrak sıralayınız
names.sort()
#years listesini rakamsal büyüklüğe göre sıralayınız
years.sort()
print(years)
print(names)
#str ="Chevrolet,Dacia" karekter dizisini listeye ceviriniz
str ="Chevrolet,Dacia".split(" ")
print(str)
#kulllanıcıdan alacagınız üç marka degerini bir listede toplayınız
markalar=[]
marka=input("marka giriniz:")
markalar.append(marka)
marka=input("marka giriniz:")
markalar.append(marka)
marka=input("marka giriniz:")
markalar.append(marka)
print(markalar)
| false
|
5a830eb25ff9411d7390a9e115b36a7c20481e24
|
tutunamayanlar2021/Python
|
/referance.py
| 365
| 4.15625
| 4
|
#value types=>string,number
# deger tuttugu için atamadan sonra yapılan degişiklik
# sadece yapılanı degiştirir.adresler aynı degil.
x=10
y=25
x=y
y=30
#print(x,y)
#referance =>list,class
#Since the addresses are the same, they both change after assignment
a=["apple","banana"]
b=["apple","banana"]
a=b
b[0]="grades"
print(a,b)
| false
|
bf772445c70ed744a38609bb35aa045d5d5e29ec
|
sujanay/python-interview-questions
|
/tree.py
| 2,011
| 4.125
| 4
|
from __future__ import print_function
# Binary Tree Node
class TreeNode:
def __init__(self, v, l=None, r=None):
self.value = v
self.left = l
self.right = r
# insert data to the tree
def tree_insert(root, x):
attr = 'left' if x < root.value else 'right'
side = getattr(root, attr)
if not side: setattr(root, attr, TreeNode(x))
else: tree_insert(side, x)
# preorder traversal through the tree
def print_tree_preorder(root):
if root is None:
return
print(root.value, end=' - ')
print_tree_preorder(root.left)
print_tree_preorder(root.right)
# inorder traversal through the tree
def print_tree_inorder(root):
if root is None:
return
print_tree_inorder(root.left)
print(root.value, end=' - ')
print_tree_inorder(root.right)
# postorder traversal through the tree
def print_tree_postorder(root):
if root is None:
return
print_tree_postorder(root.left)
print_tree_postorder(root.right)
print(root.value, end = ' - ')
if __name__ == '__main__': # Tree Structure
root = TreeNode(7) # 7
tree_insert(root, 4) # / \
tree_insert(root, 5) # 4 8
tree_insert(root, 8) # / \ \
tree_insert(root, 9) # 2 5 9
tree_insert(root, 2) # \
tree_insert(root, 3) # 3
print("Inorder traversal") # Inorder(left, root, right)
print_tree_inorder(root) # outputs: 2 - 3 - 4 - 5 - 7 - 8 - 9 -
print("\n\nPreorder traversal") # Preorder(root, left, right)
print_tree_preorder(root) # outputs: 7 - 4 - 2 - 3 - 5 - 8 - 9 -
print("\n\nPostorder traversal") # Postorder(left, right, root)
print_tree_postorder(root) # outputs: 3 - 2 - 5 - 4 - 9 - 8 - 7 -
| true
|
2e615d7d4fc73f1a5540ec12938b87b2f769b5b9
|
sujanay/python-interview-questions
|
/python/Algorithms/IsAnagram.py
| 515
| 4.4375
| 4
|
"""check if the two string are anagrams of each other"""
"""
Method-1:
This method utilizes the fact that the anagram strings, when
sorted, will be equal when testing using string equality operator
"""
def Is_Anagram(str1, str2):
if len(str1) != len(str2):
return False
str1_sorted, str2_sorted = sorted(str1), sorted(str2)
return str1_sorted == str2_sorted
print(Is_Anagram('hello', 'billion'))
print(Is_Anagram('mary', 'yarm'))
print(Is_Anagram('table', 'balet'))
| true
|
8ba114592dbf2cb24b7d441d2bf84cac1b5a3228
|
chendaye/py100
|
/基础/练习/栗子-07.py
| 509
| 4.25
| 4
|
"""
计算点的距离
"""
from math import sqrt
class distance:
def __init__(self, x, y):
self.x = x
self.y = y
def move_to(self, x, y):
self.x = x
self.y = y
def move_by(self, x, y):
self.x += x
self.y += y
def dis(self, x, y):
return sqrt((self.x - x) ** 2 + (self.y - y) ** 2)
def main():
cla = distance(2, 3)
print(cla.dis(4, 8))
cla.move_to(9, 5)
print(cla.dis(4,9))
if __name__ == '__main__':
main()
| false
|
b3554ace99a9f2df79f386fafd19464937d7d4e6
|
tapczan666/sql
|
/homework_03.py
| 504
| 4.21875
| 4
|
# homework assignment No2 - continued
import sqlite3
with sqlite3.connect("cars.db") as connection:
c = connection.cursor()
# find all car models in the inventory
c.execute("SELECT * FROM inventory")
inventory = c.fetchall()
for car in inventory:
print(car[0], car[1])
print(car[2])
# find all order dated for a given model
c.execute("SELECT order_date FROM orders WHERE make = ? AND model = ? ORDER BY order_date", (car[0], car[1]))
dates = c.fetchall()
for d in dates:
print(d)
| true
|
3468722bd044822a7f85464074bc0a6cdae623bb
|
prydej/WordCount
|
/Tracker.py
| 712
| 4.1875
| 4
|
"""
Author: Julian Pryde
Name: Essay Tracker
Purpose: To count the number of words over two letters in a string
Dat: 22MAR16
Input: A String
Output: An integer containing the number of words over 2 letters in input
"""
import sys
# Read String from file
essay_handle = open(sys.argv[1])
essay = essay_handle.read()
essay_handle.close()
# Remove all punctuation
essay = essay.translate(None, "\'[](){}:,`-_.!@#$%^&*?\";\\/+=|")
# Tokenize string on spaces
split_essay = essay.split()
# Iterate through through each word, add to count if over >= 3 letters
count = 0
for butterfly in split_essay:
if butterfly.len > 2:
count += 1
# Print number of words to cmd line
print("Words over 2 letters: ", count)
| true
|
44473c6405aaa3b116b39c9887e9dd7c53413b1f
|
Luciano-Grilli/ejercicios-python-del-curso-seguido
|
/excepciones.py
| 915
| 4.125
| 4
|
import math
try: #acortar decimales
num1 = int(input("Ingrese un numero: "))
num2 = int(input("Ingrese otro numero: "))
print("resultado de la division es:","{0:.2f}".format(num1/num2))
except ZeroDivisionError:#al lado se puede poner el tipo de error o no y que responda a ese error
print("no se puedo realizar la division con esos numeros")
except ValueError:
print("Valores ingresados incorrectos")
#se pueden hacer varias excepciones y se puede poner el tipo de error
#para que responda a este
finally:#el finali se ejecuta siempre si o si
print("Programa finalizado")
edad = -1
if edad < 0:
raise TypeError("Error de tontos,no existe edad negativa")
#con tyerror podes ingresar el mensaje del error
#tambien se puede ingresar el tipo de error
#ya que estamos asi se realizan la raiz,importando la clase math
math.sqrt(5)
| false
|
6199c577d8e6bef67694d770bded9339a9293ac4
|
AzwadRafique/Azwad
|
/Whacky sentences.py
| 602
| 4.3125
| 4
|
import random
adj = input("Insert an adjective ")
noun = input("Insert a noun ")
verb = input("Insert a verb ending with 'ing' ")
if verb.count('ing') == 0:
verb = False
while verb == False:
verb = input("Please insert a verb ending with 'ing' ")
sentences = [f"Our house has {adj} furniture and there is a {verb} {noun}",
f"The school canteen has {adj} pizzas and a {verb} {noun}",
f"The {adj} {noun} is {verb} ",
f"He described the {noun} to be {adj} looking while he was {verb}"]
sentence = random.choice(sentences)
print(sentence)
| true
|
d2b105a85201dc8c909dc6c53854c9dfbe04252e
|
AzwadRafique/Azwad
|
/Emailsv.py
| 1,536
| 4.21875
| 4
|
while 1 == 1:
number_emails = {
'manha@gmail.com': '12345',
'jack@gmail.com': '124567'
}
login_or_sign_in = input('login or sign in: ')
if login_or_sign_in.upper() == 'LOGIN':
email = input('what is your email: ')
if email in number_emails:
password = input('password: ')
if password == number_emails.get(email):
print("welcome")
break
else:
print('wrong password')
else:
print('wrong email')
elif login_or_sign_in.upper() == 'SIGN IN':
new_account = input('name of account: ')
if new_account in number_emails:
print('Sorry this title has already been taken')
if len(new_account) <= 9:
print('Sorry the account name must contain a minimum of 10 characters')
if new_account.count('@gmail.com') == 0:
print("The account name must contain '@gmail.com'")
new_password = input('password: ')
if len(new_password) <= 5:
print('Sorry the password must have a minimum of 5 characters')
confirmation = input('please confirm the password')
if new_password == confirmation:
number_emails[new_account] = new_password
print("you have successfully created a new account")
break
else:
print("you have not confirmed your password please try again later")
else:
print('can you please repeat')
| true
|
4d20a237a1b8b806e5eea64c7c635dff54b4e8c2
|
dimamik/AGH_Algorithms_and_data_structures
|
/PRACTISE/FOR EXAM/Wyklady/W2_QUEUE_STACK.py
| 2,898
| 4.15625
| 4
|
class Node():
def __init__(self,val=None,next=None):
self.val=val
self.next=next
class stack_lists():
def __init__(self,size=0):
first=Node()
self.first=first
self.size=size
def pop(self):
if self.size==0:return
self.size-=1
tmp=self.first.next.next
to_ret=self.first.next
self.first.next=tmp
return to_ret
def push(self,Node_to_push):
tmp=self.first.next
Node_to_push.next=tmp
self.first.next=Node_to_push
self.size+=1
def print_stack(self):
if self.size==0:print("The stack is empty")
tmp=self.first.next
while tmp!=None:
print(tmp.val)
tmp=tmp.next
class QueueLists():
def __init__(self,first=None):
self.first=first
def push(self,Node_to_push):
if Node_to_push==None:
return None
if self.first==None:
Node_to_push.next=None
self.first=Node_to_push
else:
self.first.next=Node_to_push
def PrintQueueOnLists(self):
"""
Printing from the end
"""
tmp=self.first
while tmp!=None:
print(tmp.val)
tmp=tmp.next
def pop(self):
if self.first==None or self.first.next==None:
return None
else:
to_ret=self.first
tmp=self.first.next
self.first=tmp
return to_ret.val
""" Q=QueueLists()
Q.push(Node(15))
Q.push(Node(25))
print(Q.pop())
Q.PrintQueueOnLists() """
"""
S=stack_lists()
K=Node(5)
S.push(K)
S.print_stack()
S.pop()
S.print_stack()
"""
class stack():
def __init__(self,size=10):
tab=[None]*size
self.tab=tab
self.top=0 #Current to fill
self.size=size
def pop(self):
self.top-=1
return self.tab[self.top]
def push(self,element_to_push):
self.tab[self.top]=element_to_push
self.top+=1
def is_empty(self):
return self.size==0
def print_stack(self):
print(self.tab[:self.top])
class Queue():
def __init__(self,size_of_tab=10):
self.size_of_tab=size_of_tab
tab=[None]*size_of_tab
self.tab=tab
self.first=0
self.size=0
def is_empty(self):
return size==0
def pop(self):
self.size-=1
self.first+=1
return self.tab[self.first-1]
def push(self,el_to_push):
self.size+=1
tmp=self.first+self.size-1
self.tab[tmp]=el_to_push
def print_queue(self):
tab_tmp=[0]*self.size
k=0
for i in range(self.first,self.first+self.size):
tab_tmp[k]=self.tab[i]
k+=1
print(tab_tmp)
""" K=stack_lists()
K.push(Node(6))
K.push(Node(6))
K.push(Node(6))
K.push(Node(49))
K.pop()
K.pop()
K.pop()
K.pop()
K.print_stack() """
| true
|
4e9b9da28608efcd69df0f7706a82d16461dd7d2
|
JulieBoberg/Learn-Python-3-the-Hard-Way
|
/ex8.py
| 931
| 4.3125
| 4
|
# declare variable formatter and set it equal to a string with four sets of brackets.
formatter = "{} {} {} {}"
# prints the string in the variable formatter with the arguments in format in place of the brackets
print(formatter.format(1, 2, 3, 4))
# prints the string in the variable formatter with the arguments in format in place of the brackets
print(formatter.format("one", "two", "three", "four"))
# prints the string in the variable formatter with the arguments in format in place of the brackets
print(formatter.format(True, False, False, True))
# prints the string in the variable formatter and each bracket contains the entire string of formatter
print(formatter.format(formatter, formatter, formatter, formatter))
# prints formatter with each bracket replaced by a string provided in format()
print(formatter.format(
"Try your",
"Own text here",
"Maybe a poem",
"Or a song about fear"
))
| true
|
5d32181fdadd2ab1ca9b672617a612e03216259e
|
JulieBoberg/Learn-Python-3-the-Hard-Way
|
/ex20.py
| 1,617
| 4.1875
| 4
|
from sys import argv
script, input_file = argv
# define function print_all that accepts parameter f(a file)
def print_all(f):
# read the file(f) and print it
print(f.read())
# define function rewind which accepts parameter f
def rewind(f):
# find the (0) start of the file(f)
f.seek(0)
# define the function print_a_line that accepts line_count and a file(f)
def print_a_line(line_count, f):
# Goes to line specified in line_count and reads that line of the file, prints
print(line_count, f.readline())
# variable current_file opens the input_file
current_file = open(input_file)
# prints a string that ends with a line break
print("First let's print the whole file:\n")
# calls function print_all with current_file as parameter. This opens, reads and prints the input_file
print_all(current_file)
# prints a string
print("Now let's rewind, kind of like a tape.")
# calls function rewind that opens the input_file and goes to start of file.
rewind(current_file)
# prints a string
print("Let's print three lines:")
# variable current_line is set to 1
current_line = 1
# calls print_a_line which takes the current_line and prints it from current_file
print_a_line(current_line, current_file)
# variable current_line is increased by 1
current_line = current_line + 1 # current_line += 1
# calls print_a_line again but current_line is increased by 1
print_a_line(current_line, current_file)
# calls print_a_line again but current_line is increased by 1
current_line = current_line + 1 # current_line += 1
print_a_line(current_line, current_file)
| true
|
795ba841a724b31cc3f2963b9bd15b9a4f5346fd
|
natalialovkis/MyFirstPythonProject_Math
|
/math_project1.py
| 2,321
| 4.3125
| 4
|
# -*- coding: utf-8 -*-
# Math learning program
import random
import math
import turtle
print("Hello Dear User!")
name = input("Please, enter your name: ")
print()
print("Hello %s! Let`s learn the Math!" % name)
print()
num_of_ex = 0
while True:
try:
num_of_ex = int(input("How many exercises are you going to solve? "
"Enter a number from 1 to 10: "))
if 1 <= num_of_ex <= 10:
break
print("try again")
except ValueError:
print("That's not an int!")
user_try = 0
while user_try < num_of_ex:
first = random.randint(1, 11) # generate number between 1 and 100
second = random.randint(1, 11)
action = random.randint(1, 4) # 1=+; 2=-; 3=*;
if action == 1:
answer = first + second
try:
user_in = int(input("What is result "
"of %d + %d :" % (first, second)))
if user_in == answer:
print("Good!")
else:
print("Not right")
except ValueError:
print("That's not an int!")
elif action == 2:
answer = first - second
try:
user_in = int(input("What is result "
"of %d - %d :" % (first, second)))
if user_in == answer:
print("Good!")
else:
print("Not right")
except ValueError:
print("That's not an int!")
else:
answer = first * second
try:
user_in = int(input("What is result "
"of %d * %d :" % (first, second)))
if user_in == answer:
print("Good!")
else:
print("Not right")
except ValueError:
print("That's not an int!")
user_try += 1
print()
print("Good job! Bye!")
print()
input("Press enter to see a surprise.")
radius = 100
petals = num_of_ex
def draw_arc(b, r):
c = 2*math.pi*r
ca = c/(360/60)
n = int(ca/3)+1
l = ca/n
for i in range(n):
b.fd(l)
b.lt(360/(n*6))
def draw_petal(b, r):
draw_arc(b, r)
b.lt(180-60)
draw_arc(b, r)
b.rt(360/petals-30)
bob = turtle.Turtle()
for i in range(petals):
draw_petal(bob, radius)
bob.lt(360/4)
| true
|
30f7e7671a9c003688c80f6433f5a95b266a5a4a
|
2mohammad/Python_Prac
|
/11_flip_case/flip_case.py
| 791
| 4.28125
| 4
|
def flip_case(phrase, to_swap):
"""Flip [to_swap] case each time it appears in phrase.
>>> flip_case('Aaaahhh', 'a')
'aAAAhhh'
>>> flip_case('Aaaahhh', 'A')
'aAAAhhh'
>>> flip_case('Aaaahhh', 'h')
'AaaaHHH'
"""
"""
split string to list via list comprehension
run or build relative match via case matches
convert cases via if statements for case matches
join via str
"""
word_range = range(0, len(phrase))
phrase_range = ''
if to_swap.isupper():
for x in word_range:
if phrase[x].upper() == to_swap and phrase[x].islower() == True:
phrase_range += phrase[x].upper()
else:
phrase_range += phrase[x]
print(phrase_range)
| false
|
bb36efd1df3edf317fb9a8ba21309202e4582e33
|
TrilochanSati/exp
|
/daysInDob.py
| 832
| 4.3125
| 4
|
#Program to return days from birth of date.
from datetime import date
def daysInMonth(month:int,year:int)->int:
months=[31,28,31,30,31,30,31,31,30,31,30,31]
if(year%4==0 and month==2):
return 29
else:
month-=1
return months[month]
def daysInDob(dobDay,dobMonth,dobYear)->int:
today=date.today()
totalDays=0
curDay=today.day
curMonth=today.month
curYear=today.year
day=dobDay
month=dobMonth
year=dobYear
while(day!=curDay or month!=curMonth or year!=curYear):
dim=daysInMonth(month,year)
if(day==dim):
day=0
month+=1
totalDays+=1
day+=1
if(month>12):
month=1
year+=1
print(day,month,year)
return totalDays
print("days",daysInDob(27,9,2018))
| true
|
45971d9756dbb11d7b5c583de74c9c5fcd71fab5
|
lemonade512/CodeSnippets
|
/Python/make_args_strings.py
| 866
| 4.4375
| 4
|
#!/usr/bin/python
'''
make_args_strings.py
This snippet is an example of a decorator. The decorator in
this case takes a functions arguments and turns them into
strings.
Author: Phillip Lemons
Date Modified: 2/16/2014
'''
def _make_arguments_strings(fn):
def wrapped(*args, **kwargs):
new_args = [str(arg) for arg in args]
kwargs = {key:str(value) for key,value in kwargs.iteritems()}
for arg in new_args:
assert(type(arg) == type(""))
for value in kwargs.itervalues():
assert(type(value)==type(""))
return fn(*new_args, **kwargs)
return wrapped
@_make_arguments_strings
def my_function(num1, num2, *args, **kwargs):
print "Num1:: " + num1 + ", Num2:: " + num2
for i, arg in enumerate(args):
print i, args[i]
for key,value in kwargs.iteritems():
print key + "::", value
return
my_function(1,4,6,8,10,number=4)
| false
|
c829a7f379119a3e735a4a9b20de160faa4c3776
|
alzheimeer/holbertonschool-higher_level_programming
|
/0x07-python-test_driven_development/3-say_my_name.py
| 543
| 4.40625
| 4
|
#!/usr/bin/python3
def say_my_name(first_name, last_name=""):
"""
Args:
first_name (str): the first name
last_name (str, optional): the last name
Raises:
TypeError: if the first_name or last_name are not strings
"""
if first_name is None or type(first_name) is not str:
raise TypeError('first_name must be a string')
if last_name is None or type(last_name) is not str:
raise TypeError('last_name must be a string')
print("My name is {:s} {:s}".format(first_name, last_name))
| true
|
d65d22f6a7e69c886203c873e3870359b74f2eed
|
chenjiahui1991/LeetCode
|
/P0225.py
| 1,053
| 4.1875
| 4
|
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.line = []
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: void
"""
self.line.append(0)
for i in range(len(self.line) - 1, 0 , -1):
self.line[i] = self.line[i - 1]
self.line[0] = x
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
return self.line.pop(0)
def top(self):
"""
Get the top element.
:rtype: int
"""
return self.line[0]
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
return len(self.line) == 0
# Your MyStack object will be instantiated and called as such:
obj = MyStack()
obj.push(1)
obj.push(2)
print(obj.top())
print(obj.pop())
print(obj.empty())
# param_3 = obj.top()
# param_4 = obj.empty()
| true
|
c8de22cbd9a1535e0ad87b799dc1f604c246c33f
|
djalma21/maratona
|
/Treino Atividade 4.py
| 1,309
| 4.1875
| 4
|
#Faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são:
#"Telefonou para a vítima?"
#"Esteve no local do crime?"
#"Mora perto da vítima?"
#"Devia para a vítima?"
#"Já trabalhou com a vítima?"
#O programa deve no final emitir uma classificação sobre a participação da pessoa no crime.
#Se a pessoa responder positivamente a 2 questões ela deve ser classificada como "Suspeita",
#entre 3 e 4 como "Cúmplice"
#e 5 como "Assassino".
#Caso contrário, ele será classificado como "Inocente".
pergunta1 = input('Telefonou para a vítima?')
pergunta2 = input('Esteve no local do crime?')
pergunta3 = input('Mora perto da vítima?')
pergunta4 = input('Devia para a vítima?')
pergunta5 = input('Já trabalhou para a vítima?')
crime = "sim"
resultado = 0
if pergunta1 == crime:
resultado = resultado + 1
crime = "sim"
if pergunta2 == crime:
resultado = resultado + 1
crime = "sim"
if pergunta3 == crime:
resultado = resultado + 1
crime = "sim"
if pergunta4 == crime:
resultado = resultado + 1
crime = "sim"
if pergunta5 == crime:
resultado = resultado + 1
crime = "sim"
if resultado == 0 and 1:
print('Inocente')
if resultado == 2:
print('Suspeita')
if resultado == 3 and 4:
print('Cúmplice')
if resultado == 5:
print('Assassino')
| false
|
e51c78c3e21eb1c6a1624bd113fa1d94ab353293
|
Abishekthp/Simple_Assignments
|
/Assigmnet_1/11Factor_and_largest_factor_of_a_Number.py
| 247
| 4.25
| 4
|
#FIND THE FACTORS OF A NUMBER AND PRINT THE LARGEST FACTOR
n=int(input('Enter the number:'))
l=0
print('Factors are:')
for i in range(1,n):
if(n%i==0):
print(i)
if(i>l):
l=i
print('largest factor:',l)
| true
|
9db36b88191861353321686f4209406196385ae1
|
HolyCoffee00/python_books
|
/python_books/py_crash/chaper_7/greeter.py
| 267
| 4.21875
| 4
|
name = input("Please tell me your name: ")
print("Hello, " + name.title() + "!")
prompt = "If you tell us who you are i will personalize the message: "
prompt += "\nWhat is your firtst name: "
name = input(prompt)
print("Hello, " + name.title() + "!")
| true
|
f58ad48501d9a0a3bf2d2fcb239a1e2ca6ad9870
|
neilkazimierzsheridan/sqlite3
|
/sq2.py
| 1,070
| 4.1875
| 4
|
#sqlite part 2
import sqlite3
conn = sqlite3.connect('customer2.db')
c = conn.cursor() #create the cursor instance
#c.execute(" SELECT rowid, * FROM customers") #rowid to get autogenerated primary key, this is element 0 now
## USING THE WHERE CLAUSE SEARCHING
#c.execute(" SELECT rowid, * FROM customers WHERE last_name = 'Baker'")
#using the WHERE clause to search for something specific in field e.g. last_name
# if e.g. age could do WHERE age >= 21 etc
# WHERE last_name LIKE 'B%' for all the ones beginning B
#c.execute(" SELECT rowid, * FROM customers WHERE last_name LIKE 'M%'")
c.execute(" SELECT rowid, * FROM customers WHERE email LIKE '%google.com'")
items = c.fetchall()
print("\n", "Displaying records from database:")
for item in items:
print("\n" + "ID: " + str(item[0]) + "\n" + "Name :"+ item[1] + " " + item[2] + "\n" + "Email: " + item[3])
# display them with the primary key
conn.commit()
# Datatypes are NULL, INTEGER, REAL, TEXT, BLOB // BLOB stored as is e.g. image, audio etc.
conn.close()
| true
|
cb7f069f17d3813d4e63840db06f9bb0d08cf929
|
OSGeoLabBp/tutorials
|
/hungarian/python/code/circle.py
| 846
| 4.15625
| 4
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import math
from point import Point
class Circle(Point):
""" class for 2D circles """
def __init__(self, x=0, y=0, p=2, r=1):
super(Circle, self).__init__(x, y, p)
self.r = r
def __str__(self):
return ("{0:." + str(self.p) + "f}, {1:." + str(self.p) + "f}, {2:." +
str(self.p) + "f}").format(self.x, self.y, self.r)
def area(self):
""" area of circle """
return self.r ** 2 * math.pi
def perimeter(self):
""" perimeter of circle """
return 2 * self.r * math.pi
if __name__ == "__main__":
# test
c1 = Circle()
print(c1)
print("area: {}".format(c1.area()))
print("perimeter: {}".format(c1.perimeter()))
c1 += Point(10,20)
print(c1)
c1 = c1 + Point(10,20)
print(c1)
| false
|
644335a0226c0b9a54aeb7b689e8452e0705466a
|
ddib-ccde/pyforneteng2020
|
/week1/exercise2.py
| 1,106
| 4.1875
| 4
|
# Print an empty line
print(f"")
# Ask user for an IP address and store as string
ipaddr = input("Please enter an IP address: ")
# Split the IP address into four parts and store in a list
ipaddr_split = ipaddr.split(".")
# Print an empty line
print(f"")
# Print the header with centered text (^) and width 15
print(f"{'Octet1':^15}{'Octet2':^15}{'Octet3':^15}{'Octet4':^15}")
print("-" * 60)
# Print each octet of the IP address using list slicing
print(f"{ipaddr_split[0]:^15}{ipaddr_split[1]:^15}{ipaddr_split[2]:^15}{ipaddr_split[3]:^15}")
# Print IP in binary using builtin bin() function
# The ipaddr_split variable is a string, need to convert to integer with builtin function int()
print(
f"{bin(int(ipaddr_split[0])):^15}"
f"{bin(int(ipaddr_split[1])):^15}"
f"{bin(int(ipaddr_split[2])):^15}"
f"{bin(int(ipaddr_split[3])):^15}"
)
# Print the IP in hex format using builtin function hex()
print(
f"{hex(int(ipaddr_split[0])):^15}"
f"{hex(int(ipaddr_split[1])):^15}"
f"{hex(int(ipaddr_split[2])):^15}"
f"{hex(int(ipaddr_split[3])):^15}"
)
print("-" * 60)
| true
|
d40e6a0baa4379e0afe1dd8eacf7e2b44ee37ca5
|
zeuslawl/pau_martin
|
/Programacio/python/Superior/Estructures_Seqüencials/Estructures_Seqüencials_Ex14.py
| 759
| 4.21875
| 4
|
#!/usr/bin/python3
# -*-coding: utf8-*-
# Pau Martín Arnau
# isx46420653
# 11/10/18
# Primera versió
# Demanar un nombre de base i convertir els nombres de 3 xifres
# d'aquella base a un nombre decimal.
# Entrar un numero enter > 0 que sigui la base, també entrar 3 nombres enters > 0 i
# que el nombre no sigui major a la base.
# El resultat será el nombre introdüit pero en base decimal.
base = int(input("Quina base vols fer servir? "))
a_base = int(input("Primer dígit? "))
b_base = int(input("Segon dígit? "))
c_base = int(input("Tercer dígit? "))
a_decimal = a_base * base**2
b_decimal = b_base * base**1
c_decimal = c_base * base**0
resultat = a_decimal+b_decimal+c_decimal
print ("El teu nombre de base", base, "a decimal és el:", resultat)
| false
|
1d9174ea48f7685df67ab36c817ab72f1c1f0f7e
|
GAURAV-GAMBHIR/pythoncode
|
/3.A2.py
| 238
| 4.21875
| 4
|
a=(12,14,14,11,87,43,78)
print("smallest element is",min(a))
print("largest element is",max(a))
finding product of all element in tuple
result=1
for x in a:
result=result*x
print("product of all element in tuple is: ",result)
| true
|
c6df819a465084cbaf0ad8de72c2e554a3898a37
|
Bishwajit05/DS-Algos-Python
|
/Recursion/CoinChangeProblemRecursion.py
| 1,649
| 4.25
| 4
|
# Implement coin change problem
# Author: Pradeep K. Pant, ppant@cpan.org
# Given a target amount n and a list (array) of distinct coin values, what's the fewest coins needed to make the
# change amount.
# 1+1+1+1+1+1+1+1+1+1
# 5 + 1+1+1+1+1
# 5+5
# 10
# With 1 coin being the minimum amount.
# Solution strategy:
# This is a classic problem to show the value of dynamic programming. We'll show a basic recursive example and show
# why it's actually not the best way to solve this problem.
# Implement fibonacci_iterative()
def coin_change_recursion(target,coins):
'''
INPUT: Target change amount and list of coin values
OUTPUT: Minimum coins needed to make change
Note, this solution is not optimized.
'''
# Default to target value
min_coins = target
# Check to see if we have a single coin match (BASE CASE)
if target in coins:
return 1
else:
# for every coin value that is <= than target (Using list comprehension
for i in [c for c in coins if c <= target]:
# Recursive Call (add a count coin and subtract from the target)
num_coins = 1 + coin_change_recursion(target - i, coins)
# Reset Minimum if we have a new minimum (new num_coins less than min_coins)
if num_coins < min_coins:
min_coins = num_coins
return min_coins
# Test
print (coin_change_recursion(8,[1,5]))
# 4
# Note
# The problem with this approach is that it is very inefficient! It can take many,
# many recursive calls to finish this problem and its also inaccurate for non
# standard coin values (coin values that are not 1,5,10, etc.)
| true
|
cd49cf9074247537a3d29e2ba4d9ad0dea5634c2
|
Bishwajit05/DS-Algos-Python
|
/LinkedLists/DoublyLinkedListImple.py
| 733
| 4.34375
| 4
|
# Doubly Linked List class implementation
# Author: Pradeep K. Pant, ppant@cpan.org
# Implement basic skeleton for a doubly Linked List
# Initialize linked list class
class DoublyLinkedListNode(object):
def __init__(self,value):
self.value = value
self.prev_node = None
self.next_node = None
# Test
# Added node
a = DoublyLinkedListNode(1)
b = DoublyLinkedListNode(2)
c = DoublyLinkedListNode(3)
# Set the pointers
# setting b after a (a before b)
b.prev_node = a
a.next_node = b
# Setting c after a
b.next_node = c
c.prev_node = b
print (a.value)
print (b.value)
print (c.value)
# Print using class
print (a.next_node.value)
print (b.next_node.value)
print (b.prev_node.value)
print (c.prev_node.value)
| true
|
a75396b7a5bbd99390cb90c02857f63c0fc99df4
|
Bishwajit05/DS-Algos-Python
|
/Sorting/InsertionSortImple.py
| 938
| 4.21875
| 4
|
# Insertion Sort Implementation
# Author: Pradeep K. Pant, https://pradeeppant.com
# Insertion sort always maintains a sorted sub list in the lower portion of the list
# Each new item is then "inserted" back into the previous sublist such that the
# sorted sub list is one item larger
# Complexity O(n2) square
# Reference material: http://interactivepython.org/runestone/static/pythonds/SortSearch/TheSelectionSort.html
def insertion_sort(arr):
# For every index in array
for i in range(1,len(arr)):
# Set current values and position
currentvalue = arr[i]
position = i
# Sorted Sublist
while position>0 and arr[position-1]>currentvalue:
arr[position]=arr[position-1]
position = position-1
arr[position]=currentvalue
# Test
arr = [2,7,1,8,5,9,11,35,25]
insertion_sort(arr)
print (arr)
#[1, 2, 5, 7, 8, 11, 25, 35]
| true
|
4ce6d7ff07ffd9a199d96f8c522a4c043c1e9043
|
erien/algorithms
|
/mergeSort/python/main.py
| 2,430
| 4.34375
| 4
|
"""Example implementation of the merge sort algorithm"""
TO_SORT = "../../toSort.txt"
SORTED = "../../sorted.txt"
def read_table_from_file(path: str) -> list:
"""Reads table from a file and creates appropriate table...
I mean list!
Args:
path: Path to the file
Returns:
Read table
"""
with open(path, "r") as file:
# Omit first two lines (they're comments)
file.readline()
file.readline()
# Omit the line with amount, we don't need that
file.readline()
# Now read the rest of the numbers
tab = []
for line in file.readlines():
tab.append(int(line))
return tab
def _merge(tab: list, start: int, end: int):
"""Merges tables
Args:
tab: Table to merge
start: start of the chunk to merge
end: end of the chunk (not included) to merge
"""
half = (end + start) // 2
left = start
right = half
buffer = []
while (left < half) and (right < end):
if tab[left] < tab[right]:
buffer.append(tab[left])
left += 1
else:
buffer.append(tab[right])
right += 1
while left < half:
buffer.append(tab[left])
left += 1
while right < end:
buffer.append(tab[right])
right += 1
i = 0
while start < end:
tab[start] = buffer[i]
start += 1
i += 1
def _merge_sort(tab: list, start: int, end: int):
"""Performs merge sort, what did you expect?
The range is [start; end)
Args:
tab: Table to sort
start: start of the chunk to sort
end: end of the chunk (not included) to sort
"""
if end - start < 2:
return
half = (end + start) // 2
_merge_sort(tab, start, half)
_merge_sort(tab, half, end)
_merge(tab, start, end)
def merge_sort(tab: list):
"""Sortes the table using merge sort algorithm
Args:
tab: tab to be sorted
"""
_merge_sort(tab, 0, len(tab))
def main():
"""Guees where the whole fun starts? [: Reads table to be sorted and sorted
performs the merge sort algorithm and checks if table was sorted
"""
to_sort = read_table_from_file(TO_SORT)
sorted_table = read_table_from_file(SORTED)
merge_sort(to_sort)
assert to_sort == sorted_table
print("Table was sorted correctly!")
return 0
main()
| true
|
d3d57dbcde978689fb4122a9266b9ea44a4674c7
|
mapatelian/holbertonschool-higher_level_programming
|
/0x0B-python-input_output/3-write_file.py
| 323
| 4.25
| 4
|
#!/usr/bin/python3
def write_file(filename="", text=""):
"""Writes a string to a text file
Args:
filename (str): name of the file
text (str): string to be input
"""
with open(filename, 'w', encoding='utf-8') as filie:
characters = filie.write(text)
return characters
| true
|
ec92ebb83400693ea92230c152ec34b490eb1703
|
mapatelian/holbertonschool-higher_level_programming
|
/0x07-python-test_driven_development/0-add_integer.py
| 475
| 4.28125
| 4
|
#!/usr/bin/python3
def add_integer(a, b=98):
"""Function that adds two integers.
Args:
a (int): first integer
b (int): second integer
Return:
sum of the arguments
"""
if isinstance(a, int) is False and isinstance(a, float) is False:
raise TypeError("a must be an integer")
if isinstance(b, float) is False and isinstance(b, int) is False:
raise TypeError("b must be an integer")
return int(a) + int(b)
| true
|
acf85c1dae18cff881547f333fd36114a70e6601
|
mapatelian/holbertonschool-higher_level_programming
|
/0x0B-python-input_output/0-read_file.py
| 284
| 4.125
| 4
|
#!/usr/bin/python3
def read_file(filename=""):
"""Reads a text file in UTF-8, prints to stdout
Args:
filename (str): name of the file
"""
with open(filename, 'r', encoding='utf-8') as filie:
for linie in filie:
print(linie, end='')
| true
|
202bade662bbd859d43c58c1ed371c2c1a0eaf85
|
mengnan1994/Surrender-to-Reality
|
/py/0073_set_matrix_zeroes.py
| 1,615
| 4.1875
| 4
|
"""
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Example 1:
Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
Example 2:
Input:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
Output:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
Follow up:
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
"""
class Solution(object):
def set_zeros(self, matrix: [[int]]) -> None:
if not matrix or not matrix[0]:
return
self.matrix = matrix
self.m, self.n = len(matrix), len(matrix[0])
self._mark()
self._set_zero()
def _mark(self):
for i in range(self.m):
for j in range(self.n):
if self.matrix[i][j] == 0:
for k in range(self.m):
if self.matrix[k][j] != 0:
self.matrix[k][j] = '#'
for k in range(self.n):
if self.matrix[i][k] != 0:
self.matrix[i][k] = '#'
def _set_zero(self):
for i in range(self.m):
for j in range(self.n):
if self.matrix[i][j] == '#':
self.matrix[i][j] = 0
def test(self):
matrix = [
[0, 1, 2, 0],
[3, 4, 5, 2],
[1, 3, 1, 5]
]
self.set_zeros(matrix)
print(matrix)
Solution().test()
| true
|
dbb8650adc7e732575c33a032004fce683831afa
|
mengnan1994/Surrender-to-Reality
|
/py/0646_maximum_length_of_pair_chain.py
| 1,531
| 4.28125
| 4
|
"""
You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.
Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion.
Given a set of pairs, find the length longest chain which can be formed. You needn't use up all the given pairs. You can select pairs in any order.
Example 1:
Input: [[1,2], [2,3], [3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4]
Note:
The number of given pairs will be in the range [1, 1000].
"""
class Solution:
"""
0252_meeting_room 0253_meeting_room 的简化版本
"""
def find_longest_chain(self, pairs):
def key(element):
return element[1]
pairs = sorted(pairs, key=key)
print(pairs)
memo_num_pairs = [None for _ in pairs]
memo_max_end = [None for _ in pairs]
memo_num_pairs[0], memo_max_end[0] = 1, pairs[0][1]
for i in range(1, len(pairs), +1):
if pairs[i][0] > memo_max_end[i - 1]:
memo_num_pairs[i] = memo_num_pairs[i - 1] + 1
memo_max_end[i] = pairs[i][1]
else:
memo_num_pairs[i], memo_max_end[i] = memo_num_pairs[i - 1], memo_max_end[i - 1]
print(memo_num_pairs)
return memo_num_pairs[-1]
def test(self):
pairs = [[-10,-8],[8,9],[-5,0],[6,10],[-6,-4],[1,7],[9,10],[-4,7]]
ans = self.find_longest_chain(pairs)
print(ans)
soln = Solution()
soln.test()
| true
|
6109e08e127c59aa0699d6b7d06e8f65fb1893d7
|
mengnan1994/Surrender-to-Reality
|
/py/0151_reverse_words_in_string.py
| 880
| 4.375
| 4
|
"""
Given an input string, reverse the string word by word.
Example:
Input: "the sky is blue",
Output: "blue is sky the".
Note:
A word is defined as a sequence of non-space characters.
Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
You need to reduce multiple spaces between two words to a single space in the reversed string.
Follow up: For C programmers, try to solve it in-place in O(1) space.
"""
class Solution(object):
def reverse_words(self, string):
word_list = string.split(' ')
word_list = [word[::-1] for word in word_list]
res = ""
for word in word_list:
if word:
res += word + " "
return res[:-1][::-1]
def test(self):
print(self.reverse_words("the sky is blue shit "))
Solution().test()
| true
|
40042792515af1f36829f92aaa330ac6cb17555e
|
mengnan1994/Surrender-to-Reality
|
/py/0186_reverse_words_in_a_string_ii.py
| 1,254
| 4.25
| 4
|
"""
Given an input string , reverse the string word by word.
Example:
Input: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
Note:
A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces.
The words are always separated by a single space.
Follow up: Could you do it in-place without allocating extra space?
"""
class Solution:
def reverse_words(self, str):
idx = 0
while idx < len(str):
start = idx
while idx < len(str) and str[idx] != " ":
idx += 1
end = idx
word = str[start : end]
self._swapper(str, start, end)
idx += 1
str_len = len(str)
self._reverser(str, 0, len(str))
# str = str[::-1]
def _reverser(self, str, start, end):
for idx in range((end - start) // 2):
str[start + idx], str[end - 1 - idx] = str[end - 1 - idx], str[start + idx]
def test(self):
str = ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
self.reverse_words(str)
print(str)
soln = Solution()
soln.test()
| true
|
2f49b448e55de701569925e9f71c956bd6e1dcdf
|
mengnan1994/Surrender-to-Reality
|
/py/0098_valid_binary_search_tree.py
| 1,395
| 4.1875
| 4
|
"""
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
1. The left subtree of a node contains only nodes with keys less than the node's key.
2. The right subtree of a node contains only nodes with keys greater than the node's key.
3. Both the left and right subtrees must also be binary search trees.
Example 1:
Input:
2
/ \
1 3
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
is 5 but its right child's value is 4.
1120 -> 1134 (ac)
99.73%
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def is_valid_bst(self, root: TreeNode):
if not root:
return True
return self._dfs(root, -float("inf"), float("inf"))
def _dfs(self, node : TreeNode, lower_bound, upper_bound):
if not (node.val < upper_bound and node.val > lower_bound):
return False
valid = True
if node.left:
valid = valid and self._dfs(node.left, lower_bound, node.val)
if not valid:
return False
if node.right:
valid = valid and self._dfs(node.right, node.val, upper_bound)
return valid
| true
|
250013f9d8f1cb624ca63725487ec54ad7985317
|
WillHTam/reference
|
/bubble_sort.py
| 1,239
| 4.1875
| 4
|
# Bubble Sort
# compare consecutive pairs of elements
# swap elements in pairs such that smaller is first
# at end of list, do so again. stop when no more swaps have been made
def bubble_sort(L):
"""
inner for loop does the comparisons
outer while loop is doing multiple passes until no more swaps
"""
swap = False # flag for indicating when finished
while not swap:
swap = True
print(L)
for i in range(1, len(L)):
if L[i - 1] > L[i]: # if element is out of order, swap and set flag back to False
swap = False
temp = L[i]
L[i] = L[i - 1]
L[i - 1] = temp
# worst case? O(len(L)) for going through the whole list in the inner loop
# and through the whole list O(len(L)) for the while loop
# results in O(n*2) complexity where n is len(L)
# to do len(L) - 1 comparisons and len(L) - 1 passes
def bubble_two(L):
last_index = len(L) - 1
while last_index > 0:
print(L)
for i in range(last_index):
if L[i] > L[i + 1]:
L[i], L[i + 1] = L[i + 1], L[i]
last_index -= 1
return L
l = [1, 5, 3, 8, 4, 9, 6, 2]
m = l[:]
bubble_sort(l)
print('~')
bubble_two(m)
| true
|
912f71e7813de37a3e70d91f41c6b8c57353d45b
|
Nihiru/Python
|
/Leetcode/maximum_subarray.py
| 522
| 4.28125
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 4 17:34:37 2020
@author: nick
"""
def maximum_subarray(array):
# setting the maximum sub array similar to
max_sum = array[0]
current_sum = max_sum
for ele in array[1:]:
current_sum = max(ele + current_sum, ele) # adding elements to the existing array and determining the greatest
max_sum = max(current_sum, max_sum) # identifying the maximum between maximum_sum and pre-calculated current_sum
return max_sum
| true
|
00c305f72eb4ca256dd67b8596097b834fb7c910
|
sandesh-chhetry/basic-python-
|
/Python Assignment 4/session3_functional.py
| 2,584
| 4.25
| 4
|
""" ---------------------------------------------------------------------------------------------------------------------------------------------------- """
""" 1. Write a program to display all prime numbers from 1 to """
##function to find prime number in a range
def findPrimeNumber(initial,final):
for i in range(initial,final):
## take value from 2 to i
for j in range(2,i):
## check condition whether the number is divisible by other number except same number and 1
if (i%j) == 0:
break
else:
## if not divisible then print i
print(i)
## print(j)
print("find prime numbers?")
initialVal = input("Insert initial value: ")
finalVal = input("Insert final value: ")
##pass user input value to find the prime numbers
findPrimeNumber(int(initialVal),int(finalVal))
""" ---------------------------------------------------------------------------------------------------------------------------------------------------- """
""" 2. Ask the user for a string and print out whether this string is a palindrome or not.
(A palindrome is a string that reads the same forwards and backwards.) """
##function to check whether the given string is palindrome or not
def isPalindrome(string):
##get reverse of the input string
check = string[::-1]
##print(check)
if(string == check):
print(string+ " is palindrome.")
else:
print(string+ " is not palindrome.")
string = input("type a string to check palindrome or not: ")
##pass string paramater to the given function
isPalindrome("2552")
isPalindrome(string)
""" ---------------------------------------------------------------------------------------------------------------------------------------------------- """
"""6. Create a dictionary that has a key value pair of letters and the number of occurrences of
that letter in a string.
Given a string “pineapple”. The result should be as:
{“p”:3, “i”:1, “n”:1, “e”:2, “a”:1, “l”:1}
Don’t worry about the order of occurrence of letters. """
##function to count the letters and the number in their
def countLetters(string):
print("the letter with their numbers are: ")
dictonary = {}
for letter in string:
dictonary[letter] = dictonary.get(letter, 0) + 1
print(dictonary)
string = input("insert an string: ")
##pass input value throw parameter
countLetters(string)
| true
|
c29246c37d513184514a1319aec0688b4e3db1f2
|
sandesh-chhetry/basic-python-
|
/Python Assignment 1/listGetExample.py
| 421
| 4.15625
| 4
|
##Exercise 4. Consider a list of any arbitrary elements. Your code should print the length of the list
##and first and fourth element of the list.
##list which contain some element
elements = ["1st position", "2nd position", "3rd position", "4th position", "5th position", "6th position"]
print("Length of the given element is: " + str(len(elements)))
print("fourth element of the list is : " + str(elements[4]))
| true
|
d2a8e97cec6a7e28affd4e0209eae2bb618bcfd5
|
316060064/Taller-de-herramientas-computacionales
|
/Clases/Programas/Tarea8/Problema2.py
| 1,510
| 4.25
| 4
|
'''filas = int(input ("Introduzca el numero de filas de sus matrices: "))
columnas = int(input ("Introduzca el numero de columnas de sus matrices: "))
matriz1 = []
matriz2 = []
matriz3 = []
for i in range (filas):
matriz1.append( [0] * columnas)
matriz2.append( [0] * columnas)
matriz3.append( [0] * columnas)
print 'Ingrese su Matriz 1'
for i in range(filas):
for j in range(columnas):
matriz1[i][j] = float(raw_input('Elemento (%d,%d): ' % (i, j)))
print 'Ingrese su Matriz 2'
for i in range(filas):
for j in range(columnas):
matriz2[i][j] = float(raw_input('Elemento (%d,%d): ' % (i, j)))
for i in range(filas):
for j in range(columnas):
matriz3[i][j] += matriz1[i][j] + matriz2[i][j]
print ('Su matriz resultante es')
print matriz3
'''
filas = int(input ("Introduzca el numero de filas de sus matrices: "))
columnas = int(input ("Introduzca el numero de columnas de sus matrices: "))
matriz1 = []
matriz2 = []
for i in range (filas):
matriz1.append( [0] * columnas)
matriz2.append( [0] * columnas)
print 'Ingrese su Matriz 1'
for i in range(filas):
for j in range(columnas):
matriz1[i][j] = float(raw_input('Elemento (%d,%d): ' % (i, j)))
print matriz1
for i in range(len(matriz1)):
print ("Suma de la fila ",i + 1, "=", sum(matriz1[i]))
for i in range(len(matriz1)):
suma = 0
for j in range(len(matriz1[0])):
suma = suma + matriz1[j][i]
print ("Suma de la columna ",i + 1, "=", suma)
'''
print ('Su matriz resultante es')
print matriz2
'''
| false
|
302e14a0a325f6763f28b5f2c5d567859717fecf
|
joescalona/Programacion-Astronomica
|
/Tarea 1/ejercicio3.py
| 2,125
| 4.40625
| 4
|
#NUMEROS DE MENOR A MAYOR
#PROGRAMA MAS LARGO YA QUE CONSIDERE DIVERSAS OPCIONES INGRESADAS POR EL USUARIO
#DISCULPAR POR LA ABUNDANCIA DE CODIGO
print('------ NUMEROS DE MENOR A MAYOR (DISTINTOS) ------'+'\n')
#SOLICITAR NUMERO Y VERIFICAR QUE SEA ENTERO
a=input('Ingresa un numero = ')
#SI UN FLOTANTE, TAL COMO 2.0 ES INGRESADO, CONSIDERARLO COMO ENTERO
if float(a)==int(a):
a=int(a)
elif type(a)!=int:
print('\n'+'El numero debe ser entero!')
#COMO a YA TIENE UN TIPO, QUE ES DISTINTO AL ENTERO, SE LE ASIGNA EL VALOR NULO A a
#LO APRENDI AQUI https://stackoverflow.com/questions/19473185/what-is-a-none-value
a=None
#INSISTIR HASTA QUE SEA ENTERO
while type(a)!=int:
a=input('Intentalo nuevamente :) , ingresa el numero = ')
if float(a)==int(a):
a=int(a)
b=input('Ingresa otro numero = ')
#SI EL VALOR DE b YA FUE INGRESADO
if b==a:
#INSISTIR PARA QUE SEA DISTINTO
while b==a:
b=None
b=input('Ya ingresaste ese valor anteriormente, prueba otro = ')
if float(b)==int(b):
b=int(b)
elif type(b)!=int:
print('El numero debe ser entero!')
b=None
while type(b)!=int:
b=input('Intentalo nuevamente :) , ingresa el numero = ')
if float(b)==int(b):
b=int(b)
c=input('Ingresa el ultimo numero = ')
if c==a or c==b:
while c==a or c==b:
c=None
c=input('Ya ingresaste ese valor anteriormente, prueba otro = ')
if float(c)==int(c):
c=int(c)
elif type(c)!=int:
print('El numero debe ser entero!')
c=None
while type(c)!=int:
c=input('Intentalo nuevamente :) , ingresa el numero = ')
if float(c)==int(c):
c=int(c)
else:
c=int(c)
#POSIBLES COMBINACIONES DE LOS NUMEROS INGRESADOS (DISTINTOS) (3!)
x='Los numeros en orden ascendiente son = '
while a<b and a<c:
if b<c:
print(x + str(a) +','+str(b)+','+str(c))
break
if c<b:
print(x + str(a) +','+str(c)+','+str(b))
break
while b<a and b<c:
if a<c:
print(x + str(b) +','+str(a)+','+str(c))
break
if c<a:
print(x + str(b) +','+str(c)+','+str(a))
break
while c<a and c<b:
if a<b:
print(x + str(c) +','+str(a)+','+str(b))
break
if b<a:
print(x + str(c) +','+str(b)+','+str(a))
break
| false
|
181b5324ba8239fc341d0304edc0007e2e73fde9
|
wiselyc/python-hw
|
/swap.py
| 352
| 4.34375
| 4
|
def swap_last_item(input_list):
"""takes in a list and returns a new list that swapped the first and the last element"""
input_list[0], input_list[-1] = input_list[-1], input_list[0]
# gets the first and last element and makes the first element = the last and the last element = the first
return input_list
# returns the new list
| true
|
62482eb26b465185c7301587a6667e2b8fa18603
|
phttrang/MITx-6.00.1x
|
/Problem_Sets_3/Problem_2.py
| 1,834
| 4.25
| 4
|
# Problem 2 - Printing Out the User's Guess
# (10/10 points)
# Next, implement the function getGuessedWord that takes in two parameters - a string, secretWord, and a list of letters,
# lettersGuessed. This function returns a string that is comprised of letters and underscores, based on what letters in
# lettersGuessed are in secretWord. This shouldn't be too different from isWordGuessed!
# Example Usage:
# >>> secretWord = 'apple'
# >>> lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
# >>> print(getGuessedWord(secretWord, lettersGuessed))
# '_ pp_ e'
# When inserting underscores into your string, it's a good idea to add at least a space after each one, so it's clear to the user
# how many unguessed letters are left in the string (compare the readability of ____ with _ _ _ _ ). This is called usability -
# it's very important, when programming, to consider the usability of your program. If users find your program difficult to
# understand or operate, they won't use it!
# For this problem, you are free to use spacing in any way you wish - our grader will only check that the letters and underscores
# are in the proper order; it will not look at spacing. We do encourage you to think about usability when designing.
# For this function, you may assume that all the letters in secretWord and lettersGuessed are lowercase.
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.
'''
result = []
for char in secretWord:
if char in lettersGuessed:
result.append(char)
else:
result.append("_ ")
return " ".join(result)
| true
|
2945e387eb1a73bd8610e69bf79b7d0ff0b9462b
|
qrzhang/Udacity_Data_Structure_Algorithms
|
/3.Search_Sorting/recursion.py
| 1,221
| 4.1875
| 4
|
"""Implement a function recursively to get the desired
Fibonacci sequence value.
Your code should have the same input/output as the
iterative code in the instructions."""
def get_fib_seq(position):
first = 0
second = 1
third = first + second
seq = [first, second, third]
if position < 1:
return -1
elif position < 4:
return seq[:position - 1]
else:
for i in range(3, position):
first = second
second = third
third = first + second
seq.append(third)
i += 1
return seq
def my_get_fib(position):
first = 0
second = 1
third = first + second
if position < 0:
return -1
elif position == 0:
return first
elif position == 1:
return second
elif position == 2:
return third
else:
for i in range(2, position):
first = second
second = third
third = first + second
return third
def get_fib(position):
if position == 0 or position == 1:
return position
return get_fib(position - 1) + get_fib(position - 2)
# Test cases
print(get_fib(9))
print(get_fib(11))
print(get_fib(0))
| true
|
aa00145cfff0c3d87d1ebc57537143777a49c728
|
opeoje91/Election_Analysis
|
/CLASS/PyPoll_Console.py
| 1,634
| 4.4375
| 4
|
#The data we need to retrieve
# Assign a variable for the file to load and the path.
#file_to_load = 'Resources/election_results.csv'
# Open the election results and read the file
#with open(file_to_load) as election_data:
# To do: perform analysis.
#print(election_data)
import csv
import os
# Assign a variable for the file to load and the path.
#file_to_load = os.path.join("Resources", "election_results.csv")
# Open the election results and read the file.
#with open(file_to_load) as election_data:
# Print the file object.
#print(election_data)
#create election analysis to write
# Create a filename variable to a direct or indirect path to the file.
file_to_save = os.path.join("analysis", "election_analysis.txt")
# Using the open() function with the "w" mode we will write data to the file.
#open(file_to_save, "w")
# Using the with statement open the file as a text file.
#outfile = open(file_to_save, "w")
# Write some data to the file.
#outfile.write("Hello World")
# Close the file
#outfile.close()
# Using the with statement open the file as a text file.
with open(file_to_save, "w") as txt_file:
# Write some data to the file.
#txt_file.write("Hello World")
# Write three counties to the file.
# txt_file.write("Arapahoe, Denver, Jefferson")
#write each on new line use \n
# Write three counties to the file.
txt_file.write("Arapahoe\nDenver\nJefferson")
#The total number of votes cast
#A complete list of candidates who received votes
#The percentage of votes each candidate won
#The total number of votes each candidate won
#The winner of the election based on popular vote
| true
|
dee97b21b9e2b31df218ebf2f75f51155de51650
|
opeoje91/Election_Analysis
|
/CLASS/lists.py
| 1,247
| 4.625
| 5
|
counties = ["Arapahoe","Denver","Jefferson"]
#print(counties)
#print(counties[0])
#print(counties[2])
##-to know the second to last item in list, -1 to know the last item
#print(counties[-2])
#print(len(counties))
##slicing to get the first 2 items in counties
#print(counties[0 : 2])
##slice to get the first item in counties
#print(counties[0 : 1])
##slice to get the first and second and third items from the counties
#print(counties[ : 3])
##slice to get items after the first item
#print(counties[1:])
#counties.append("El Paso")
#print(counties)
#counties.insert(2, "El Paso")
#print(counties)
#counties.remove("El Paso")
#print(counties)
#counties.insert(3, "El Paso")
#print(counties)
#print(counties.pop(-1))
#print(counties)
#
#counties.insert(3, "El Paso")
#print(counties)
#print(counties.pop(3))
#print(counties)
#print(counties)
##Add El Paso to the second position in the list.
counties.insert(1, "El Paso")
#print(counties)
##Remove Arapahoe from the list.
counties.remove("Arapahoe")
print(counties)
##Make Denver the third item in the list, but keep Jefferson the second item in the list.
counties[1] = "Jefferson"
counties[2] = "Denver"
print(counties)
##Add Arapahoe to the list.
counties.append("Arapahoe")
print(counties)
| false
|
418c14a4ae1e95d39e400b389bf6d16c6575559f
|
ar012/python
|
/learning/sets.py
| 948
| 4.1875
| 4
|
num_set = {1, 2, 3, 4, 5}
word_set = {"mango", "banana", "orange"}
subjects = set(["math", "bangla", "english"])
print(1 in num_set)
print("mango" not in word_set)
print(subjects)
print(set())
# duplicate elements
nums = {1, 2, 3, 5, 1, 2, 6, 3, 10}
print(nums)
# To add a element to a set
nums.add(9)
print(nums)
# To remove a element from a set
nums.remove(6)
print(nums)
li = [1, 2, 3, 4, 5, 6, 7, 0, 7, 5]
list = list(set(li))
print(list)
# Set Operations
print("\nSet Operations\n")
a = {1, 2, 3, 4, 8}
b = {5, 3, 7, 8, 10}
# Union of sets
set_union = a | b
print("Union of a and b =", set_union)
# Intersection of sets
set_intersection = a & b
print("Intersection of a and b =", set_intersection)
# difference of sets
set_diff = a - b
print("Diff from a to b =", set_diff)
set_diff2 = b - a
print("Difference from b to a =", set_diff2)
# symmetric difference
# set_sym_diff = a ^ b
# print(Sym_Diff from a to b =", set_sym_diff)
| true
|
cd5b516a24221e828f5e4b3662057ca52ceba125
|
arkatsuki/assist
|
/file/file_rename.py
| 1,767
| 4.40625
| 4
|
import os
"""
改文件的后缀名
rename_to_txt:把文件后缀名改成.txt
rename_to_original:与rename_to_txt配套,还原成原来的后缀名
"""
def rename_to_txt(dir_path):
"""
success
把文件后缀名改成.txt
:param dir_path:
:return:
"""
for parent, dirnames, filenames in os.walk(dir_path):
for filename in filenames:
if not filename.endswith('.txt'):
# print('filename:',filename)
if filename.find('.') > -1:
filename_new = filename[:filename.find('.')] + '$' + filename[filename.find('.')+1:] + '.txt'
os.rename(os.path.join(parent, filename), os.path.join(parent, filename_new))
pass
pass
pass
pass
pass
def rename_to_original(dir_path):
"""
success
与rename_to_txt配套,还原成原来的后缀名
:param dir_path:
:return:
"""
for parent, dirnames, filenames in os.walk(dir_path):
for filename in filenames:
if filename.find('$') > -1:
# print('filename:',filename)
filename_new = filename[:filename.find('.')]
filename_new = filename_new.replace('$', '.')
os.rename(os.path.join(parent, filename), os.path.join(parent, filename_new))
pass
pass
pass
pass
if __name__ == "__main__":
# os.rename(r'E:\git\transfer\transfer\offsite\sf-off\do_o.py', r'E:\git\transfer\transfer\offsite\sf-off\do_o.txt')
# dir_path = r'E:\git\transfer\transfer\offsite'
dir_path = r'D:\work-all\workplace\repository\transfer\offsite'
# rename_to_txt(dir_path)
rename_to_original(dir_path)
pass
| false
|
074d2d889a50fda955b37d02d55e64db6f0cd6dc
|
mvk47/turtle-racing
|
/main.py
| 1,252
| 4.21875
| 4
|
from turtle import Turtle, Screen
import random
screen = Screen()
screen.setup(width=500, height=400)
bet= screen.textinput(title="Make your bet",
prompt= "Which turtle will win the race:\n1.Red\n2.Green\n3.Blue\n4.Yellow\n5.Orange")
print(bet)
red = Turtle()
blue = Turtle()
yellow = Turtle()
green = Turtle()
orange = Turtle()
red.color("red")
blue.color("blue")
yellow.color("yellow")
green.color("green")
orange.color("orange")
for i in (red,blue,yellow,green,orange):
i.shape("turtle")
i.penup()
race_on=False
red.goto(x=-230,y=-100)
blue.goto(x=-230,y=-70)
yellow.goto(x=-230,y=-40)
green.goto(x=-230,y=-10)
orange.goto(x=-230,y=20)
if bet:
race_on=True
while race_on:
for i in (red,blue,yellow,green,orange):
if i.xcor()>230:
race_on=False
winning_color = i
print("And the winning color is.....",winning_color.pencolor())
if winning_color==bet:
print("You have won my friend. Let there be a legend...")
else:
print("Another looser!!!")
rand_distance = random.randint(0,10)
i.forward(rand_distance)
screen.exitonclick()
| false
|
84d1c158dd321f99c38ce95c3825a457b21ca9e5
|
Charles-IV/python-scripts
|
/recursion/factorial.py
| 536
| 4.375
| 4
|
no = int(input("Enter number to work out factorial of: "))
def recursive_factorial(n, fact=1):
# fact = 1 # number to add to
fact *= n # does factorial calculation
n -= 1 # prepare for next recursion
#print("fact: {}, n = {}".format(fact, n)) - test for debugging
if n > 1: # keep repeating until it gets too low
fact = recursive_factorial(n, fact) # pass variable back to output correct value
return fact # return to output or lower level of recursion to output
print(recursive_factorial(no))
| true
|
9751e43f0580aae99460d521118ac79463027a2c
|
vapawar/vpz_pycodes
|
/vpz/vpz_rotate_array.py
| 316
| 4.125
| 4
|
def rotateL(arr, n):
for x in range(n):
start=arr[0]
for i in range(1,len(arr)):
arr[i-1]=arr[i]
arr[-1]=start
def rotateR(arr,n):
for x in range(n):
end=arr[-1]
for i in range(len(arr)-1,-1,-1):
arr[i]=arr[i-1]
arr[0]=end
x=list(range(1,8))
print(x)
rotateL(x,2)
print(x)
rotateR(x,2)
print(x)
| false
|
aab2c535b094205462ac80405250ce17ee993e4e
|
MorgFost96/School-Projects
|
/PythonProgramming/3-28/lists.py
| 1,879
| 4.5625
| 5
|
#List Examples
#----------------
#Lists of Numbers
#----------------
even_num = [ 2, 4, 6, 8, 10 ]
#----------------
#Lists of Strings
#----------------
name[ "Molly", "Steven", "Will" ]
#-------------------------
#Mixed Strings and Numbers
#-------------------------
info = [ "Alicia", 27, 155 ]
#------------
#Print a List
#------------
num = [5, 10, 15, 20 ]
print( num )
#>>>[ 5, 10, 15, 20 ]
#---------------
#List() Function
#---------------
num_list( range( 5 ) )
print( num_list )
#>>>[ 0, 1, 2, 3, 4 ]
#-----------------
#Lists are Mutable
#-----------------
mut = [ 1, 2, 3, 4, 5 ]
#>>>[ 1, 2, 3, 4, 5 ]
mut[ 0 ] = [ 99 ]
#>>>[ 99, 2, 3, 4, 5 ]
#---------------------------------
#Fill a List of Values using Index
# - Create List First
# - Fill the List
#---------------------------------
fill = [ 0 ] * 5
print( fill )
#>>>[ 0, 0, 0, 0, 0 ]
index = 0
while index < len( fill ):
fill[ index ] = 99
index += 1
print( fill )
#>>>[ 99, 99, 99, 99, 99 ]
#-------------------
#Concatenating Lists
#-------------------
list1 = [ 1, 2, 3, 4 ]
list2 = [ 5, 6, 7, 8 ]
list3 = [ "Jim", "Jon" ]
list4 = list1 + list2
print( list4 )
#>>>[ 1, 2, 3, 4, 5, 6, 7, 8 ]
list5 = list1 + list3
print( list5 )
#>>>[ 1, 2, 3, 4, "Jim", "Jon" ]
#------------
#List Slicing
#------------
days = [ "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" ]
mid_days = days[ 2:5 ]
print( mid_days )
#>>>[ "Tues", "Wed", "Thurs" ]
print( days[:3] )
#>>>[ "Sun", "Mon", "Tues" ]
print( days[2:] )
#>>>[ "Tues", "Wed", "Thurs", "Fri", "Sat" ]
print( : ] )
#>>>[ "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" ]
#-----------
#In Operator
#-----------
def main():
prod_name = [ "V4", "F8", "Q1", "R6" ]
search = input( "Enter a product name: " )
if search in prod_name:
print( search, "was found in list" )
else:
print( search, "not found" )
| false
|
d142a70a335d662c1dcc443603f17e2cc3e4996a
|
MorgFost96/School-Projects
|
/PythonProgramming/5-16/objects.py
| 2,685
| 4.34375
| 4
|
#Morgan Foster
#1021803
# Intro to Object Oriented Programming ( OOP )
# - OOP enables you to develop large scale software and GUI effectively
# - A class defines the properties and behaviors for objects
# - Objects are created from classes
# Imports
import math
# ---
# OOP
# ---
# - Use of objects to create programs
# - Object is a software entity that contains both data and code
# - The procedure ( codes ) that an object performs are called methods
# - Encapsulation
# - Combining of data and code into a single object
# - An object typically hides its data ( data binding ) but allows outside code to access its methods
# - Code reusability
# --------------------------------------
# Differences between Procedural and OOP
# --------------------------------------
# Procedural
# - Separation of data and codes
# - If change way of storing data from variables to list, must modify all functions to accept list
#
# OOP
# - Data and codes all encapsulated in class
# - Just change the data and methods in class and all objects will take care of themselves
class IncorrectCircle:
# Initializer or constructior
# - Automatically called when object is instantiated
def __init__( self, radius = 1 ):
self.radius = radius
# Self Parameter that refers to the object that invokes the method
def getPerimeter( self ):
return 2 * self.radius * math.pi
# Can use name other than self
# - Self is conventional
def getArea( you ):
return you.radius ** 2 * math.pi
def setRadius( self, radius ):
self.radius = radius
class Circle:
# Place .__ prevents direct access to the data member
def __init__( self, radius = 1 ):
self.__radius = radius
# Getters or Accessors
def getRadius( self ):
return self.__radius
def getPerimeter( self ):
return 2 * self.__radius * math.pi
def getArea( you ):
return you.__radius ** 2 * math.pi
# Setter or Mutator
def setRadius( self, radius ):
self.__radius = radius
def test():
incorrect_circle = IncorrectCircle()
# circle.radius is called a dot access
print( "The area of the circle of radius", incorrect_circle.radius, "is", incorrect_circle.getArea() )
circle = Circle( 25 )
print( "The area of the circle of radius", circle.getRadius(), "is", circle.getArea() )
#
# Direct access to data member
incorrect_circle.radius = 100
# circle.radius = 100 won't work
# Change the radius from 25 to 100
circle.setRadius( 100 )
print( incorrect_circle.radius )
print( circle.getRadius() )
test()
# To Instantiate is to create an instance of an object
| true
|
a330c68a5d2b531399e1f400f24b56d0c2d6ee4e
|
MorgFost96/School-Projects
|
/PythonProgramming/5-9/recursive.py
| 1,317
| 4.59375
| 5
|
# Recursion
# - A function that calls itself
# ---------
# Iterative
# ---------
# Main -> a -> b -> c -> d
# ---------
# Recursive
# ---------
# Main -> a -> a -> a -> a
# ----
# Note
# ----
# Whenever possible, use iterave over recusive
# Why? Faster and uses less memory
# -------
# Example
# -------
def main():
message()
def message():
print( "This is a recursive function" )
# ---------
# Factorial
# ---------
# 4! = 4 * 3 * 2 * 1
# 3! = 3 * 2 * 1
# 2! = 2 * 1
# 1! = 1
# 0! = 1
def fact( n ):
if n == 0:
return 1
else:
return n * fact( n - 1 )
def run_fact():
n = int( input( "Enter Non Negative Number: " ) )
f = fact( n )
print( "The factorial of n is", f )
run_fact()
# -----------
# Exponential
# -----------
def two():
if n == 0:
return 1
else:
return 2 * two( n - 1 )
def run_two():
n = int( input( "Enter Non Negative Number: " ) )
t = two( n )
pritn( "Two to the power of", n, "is", t )
run_two()
# ---------
# Fibonacci
# ---------
def fib( n ):
if( n == 1 or n == 2 ):
return 1
else:
return fib( n - 1 ) + fib( n - 2 )
def run_fib():
n = int( input( "Fibonacci Position: " ) )
f = fib( n )
print( "The value is", f )
run_fib()
| false
|
16b5ee3084e7b0d7c4bb3db990a45732526dd972
|
MorgFost96/School-Projects
|
/PythonProgramming/3-28/sales.py
| 711
| 4.15625
| 4
|
#This program lists the sales for 5 days
def createList():
#Teacher put ndays = 5 and sales = [ 0 ] * ndays
sales = [ 0 ] * 5
print( "Enter sales for each day" )
i = 0
while( i < len( sales ) ):
print( "Day #", i + 1, ": ", sep = "", end = "" )
sales[ i ] = float( input( ) )
i += 1
return sales
def display( list ):
print( "Here are the values entered:" )
for n in list:
print( n )
def main():
sales = createList()
display( sales )
main()
##>>>
##Enter sales for each day
##Day #1: 1000
##Day #2: 2000
##Day #3: 3000
##Day #4: 4000
##Day #5: 5000
##Here are the values entered:
##1000.0
##2000.0
##3000.0
##4000.0
##5000.0
##>>>
| false
|
51dfa9121db952f837f90310b3970a02a7ae239b
|
MorgFost96/School-Projects
|
/PythonProgramming/3-30/insert.py
| 409
| 4.5
| 4
|
#This program demonstrates the insert method
def main():
names = [ "James", "Kathryn", "Bill" ]
print( "The list before the insert: " )
print( names )
names.insert( 0, "Joe" )
print( "The list fter the insert: " )
print( names )
main()
##>>>
##The list before the insert:
##['James', 'Kathryn', 'Bill']
##The list fter the insert:
##['Joe', 'James', 'Kathryn', 'Bill']
##>>>
| false
|
97ddb326c2af50e3f61ed34fbe097d61eed12ebd
|
h4l0anne/PongGame
|
/Pong.py
| 2,421
| 4.28125
| 4
|
# Simple Pong Game in Python
import turtle
wn = turtle.Screen()
wn.title("Pong Game")
wn.bgcolor("green")
wn.setup(width=800, height=600)
wn.tracer(0)
# Paddle A
paddle_left = turtle.Turtle()
paddle_left.speed(0) # 0 for maximum possible speed
paddle_left.shape("square")
paddle_left.color("blue")
paddle_left.shapesize(stretch_wid=5, stretch_len=1)
paddle_left.penup() #Sets the current pen state to PENUP. Turtle will move around the screen, but will not draw when its pen state is PENUP
paddle_left.goto(-350, 0)
# Paddle B
paddle_right = turtle.Turtle()
paddle_right.speed(0) # 0 for maximum possible speed
paddle_right.shape("square")
paddle_right.color("blue")
paddle_right.shapesize(stretch_wid=5, stretch_len=1)
paddle_right.penup()
paddle_right.goto(350, 0)
# Ball
ball = turtle.Turtle()
ball.speed(50)
ball.shape("circle")
ball.color("red")
ball.penup()
ball.goto(0, 0)
ball.dx = 0.2 # every time the ball moves, it moves by 2 pixels
ball.dy = 0.2
# Function to move the paddle
def paddle_left_up():
y = paddle_left.ycor()
y += 20
paddle_left.sety(y)
def paddle_left_down():
y = paddle_left.ycor()
y -= 20
paddle_left.sety(y)
def paddle_right_up():
y = paddle_right.ycor()
y += 20
paddle_right.sety(y)
def paddle_right_down():
y = paddle_right.ycor()
y -= 20
paddle_right.sety(y)
# Keyboard binding to listen for keyboard input
wn.listen()
wn.onkeypress(paddle_left_up, "w")
wn.onkeypress(paddle_left_down, "s")
wn.onkeypress(paddle_right_up, "Up")
wn.onkeypress(paddle_right_down, "Down")
# Main Game Loop
while True:
wn.update()
# Move the ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# Border checking
if ball.ycor() > 290:
ball.sety(290)
ball.dy *= -1
if ball.ycor() < -290:
ball.sety(-290)
ball.dy *= -1
if ball.xcor() > 390:
ball.goto(0, 0)
ball.dx *= -1
if ball.xcor() < -390:
ball.goto(0, 0)
ball.dx *= -1
# Paddle and ball collisions
if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle_right.ycor() + 40 and ball.ycor() > paddle_right.ycor() - 40):
ball.setx(340)
ball.dx *= -1
if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < paddle_left.ycor() + 40 and ball.ycor() > paddle_left.ycor() - 40):
ball.setx(-340)
ball.dx *= -1
| true
|
2aea01ba888855ee4d4d7e024bad881d26d5e9fa
|
smartpramod/97
|
/PRo 97.py
| 449
| 4.21875
| 4
|
import random
print("NUMBER GUESSING GAME")
number=random.randint(1,9)
chances=0
print("GUESS A NUMBER BETWEEN 1 AND 9")
while(chances<5):
Guess=int(input("Enter your number"))
if Guess==number:
print("Congrulation, YOU WON")
break
elif Guess<number:
print("Your guess was too low ")
else:
print("Your guess was too high")
chances=chances+1
if not chances<5:
print("you loss")
| true
|
bc3e55ea22cd1e7e3aa39a9b020d128df16dfa92
|
aalhsn/python
|
/conditions_task.py
| 1,279
| 4.3125
| 4
|
"""
Output message, so the user know what is the code about
and some instructions
Condition_Task
author: Abdullah Alhasan
"""
print("""
Welcome to Abdullah's Calculator!
Please choose vaild numbers and an operator to be calculated...
Calculation example:
first number [operation] second number = results
""")
calc_results = 0
num1= input("Input first number: ")
try:
num1 = int(num1)
except ValueError:
print("Invaild values!")
else:
num2= input("Now, second number: ")
try:
num2 = int(num2)
except ValueError:
print("Invaild values!")
else:
op = input("""Please type in the operator symbol what is between the [..]:
[ + ]: Addition
[ - ]: Substraction
[ x ]: Multiplying
[ / ]: Division
Type here: """)
if op == "+":
results = num1 + num2
print("""
{} {} {} = ...
answer is {} """.format(num1,op,num2,results))
elif op == '-':
results = num1 - num2
print("""
{} {} {} = ...
answer is {} """.format(num1,op,num2,results))
elif op.lower() == "x":
results = num1 * num2
print("""
{} {} {} = ...
answer is {} """.format(num1,op,num2,results))
elif op == "/":
results = num1 / num2
print("""
{} {} {} = ...
answer is {} """.format(num1,op,num2,results))
else:
print("Operator is invaild!")
| true
|
e321759c85fa184f7fdb08811827a36faadc8317
|
mukesh-jogi/python_repo
|
/Sem-5/Collections/Set/set1.py
| 1,960
| 4.375
| 4
|
# Declaring Set
set1 = {"Apple","Banana","Cherry","Mango","Pinapple"}
print(set1)
# Iterate through Set
set1 = {"Apple","Banana","Cherry","Mango","Pinapple"}
for item in set1:
print(item)
# Add item to set
set1 = {"Apple","Banana","Cherry","Mango","Pinapple"}
set1.add("NewFruit")
for item in set1:
print(item)
# Add multiple items in a set
set1 = {"Apple","Banana","Cherry","Mango","Pinapple"}
set1.update(['Item1','Item2','Item3'])
for item in set1:
print(item)
# Length of set
set1 = {"Apple","Banana","Cherry","Mango","Pinapple"}
print(len(set1))
# Remove item using remove method
# If the item to remove does not exist, remove() will raise an error.
set1 = {"Apple","Banana","Cherry","Mango","Pinapple"}
set1.remove("Banana")
print(set1)
# Remove item item using discard method
# If the item to remove does not exist, discard() will NOT raise an error.
set1 = {"Apple","Banana","Cherry","Mango","Pinapple"}
set1.discard("Bananas")
print(set1)
# Remove item using pop method
set1 = {"Apple","Banana","Cherry","Mango","Pinapple"}
set1.pop()
print(set1)
# Clear all items from set using clear()
set1 = {"Apple","Banana","Cherry","Mango","Pinapple"}
set1.clear()
print(set1)
# Delete set
set1 = {"Apple","Banana","Cherry","Mango","Pinapple"}
del set1
print(set1)
# Merge sets using union method
# Both union() and update() will exclude any duplicate items
set1 = {"Apple","Banana","Cherry","Mango"}
set2 = {"Mango","Pinapple"}
set3 = set1.union(set2)
print(set1)
print(set2)
print(set3)
# Merge sets using update method
# Both union() and update() will exclude any duplicate items
set1 = {"Apple","Banana","Cherry","Mango"}
set2 = {"Mango","Pinapple"}
set1.update(set2)
print(set1)
print(set2)
# Declaring set using set constructor
set1 = set(('Banana','Mango'))
print(set1)
print(type(set1))
# Copy one set into another set
set1 = set(('Banana','Mango'))
set2 = set1.copy()
set2.add("apple")
set1.add("aaa")
print(set1)
print(set2)
| true
|
a6885c761cbf2d54c530a8a114c7782dabb2631b
|
Karolina-Wardyla/Practice-Python
|
/list_less_than_ten/task3.py
| 400
| 4.15625
| 4
|
# Take a random list, ask the user for a number and return a list that contains only elements from the original list that are smaller than the number given by the user.
random_list = [1, 2, 4, 7, 8, 9, 15, 24, 31]
filtered_numbers = []
chosen_number = int(input("Please enter a number: "))
for x in random_list:
if x < chosen_number:
filtered_numbers.append(x)
print(filtered_numbers)
| true
|
3b6824ea991b59ccd05b3d42f872c5e8d1313d4a
|
Karolina-Wardyla/Practice-Python
|
/divisors/divisors.py
| 522
| 4.34375
| 4
|
# Create a program that asks the user for a number and then prints out a list of all the divisors of that number.
# Divisor is a number that divides evenly into another number.
# (For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)
chosen_number = int(input("Please enter a number: "))
possible_divisors = range(1, chosen_number // 2 + 1)
divisors = []
for number in possible_divisors:
if chosen_number % number == 0:
divisors.append(number)
divisors.append(chosen_number)
print(divisors)
| true
|
5bf4a3b018d1ec02e5dc007da9e8ad0d7758c02b
|
HugoPorto/PythonCodes
|
/CursoPythonUnderLinux/Aula0028ForIn/ForInComLisa.py
| 578
| 4.125
| 4
|
#!/usr/bin/env python
# -*- coding:utf8 -*-
cont = 1
lista = []
while cont <= 6:
lista.append(input("Digite qualquer coisa: "))
cont = cont + 1
print lista
for item in lista:
if (type(item) == int):
print 'Item inteiro: %d' % item
elif (type(item) == str):
print 'Item string %s ' % item
elif (type(item) == float):
print 'Item float %s ' % item
elif (type(item) == list):
print 'Item lista %s ' % item
elif (type(item) == tuple):
print 'Item tupla %s ' % item
elif (type(item) == dict):
print 'Item lista %s ' % item
| false
|
0a43c57a016eb641a07c8f0e2ed16080da2866b2
|
Aaron-Nazareth/Code-of-the-Future-NumPy-beginner-series
|
/6 - Basic operations on arrays.py
| 707
| 4.5
| 4
|
# Tutorial 6
# Importing relevant modules
import numpy as np
# We can create an array between numbers like we can do with lists and the 'range' command.
# When using arrays, we use the 'arange' command.
a = np.arange(0, 5) # Creates an array from 0 up to 5 - [0 1 2 3 4]
print(a)
# Basic math operations on arrays
b = np.array([4, 6, 19, 23, 45])
print(b)
# Addition
print(a + b)
# Subtraction
print(b - a)
# Square all the elements in a
print(a**2)
# NumPy actually has it's own functions built in
print(np.square(a))
# Testing whether values in an array are less than a given value
c = np.array([1, 2, 3, 4])
print(c < 2) # This prints an array of booleans showing whether values are less than 2.
| true
|
b1b17773696b406c5682d1ad6549aad66789e111
|
Elizabethcase/unitconvert
|
/unitconvert/temperature.py
| 1,020
| 4.25
| 4
|
def fahrenheit_to_celsius(temp):
'''
Input:
temp: (float)
- temp in fahrenheit
Returns:
temp: (float)
- temp in celsius
'''
celsius = (32.0 - temp)*(5.0/9)
return celsius
def celsius_to_fahrenheit(temp):
'''
Input:
temp: (float)
- temp in fahrenheit
Returns:
temp: (float)
- temp in celsius
'''
fahrenheit = 32.0 + temp*9.0/5
return fahrenheit
def temp_convert(temp, units="c"):
'''
Input:
temp: (float)
- temp in units specified by units choice
units: (string)
- units of temperature; "c" for celsius or "f" for fahrenheit
Returns:
temp: (float)
- temp in units of desired conversion
'''
if units=="c":
return celsius_to_fahrenheit(temp)
if units=="f":
return fahrenheit_to_celsius(temp)
| false
|
9519d25c32ac136ff355e521e4bf36dc80eee71b
|
meghasundriyal/MCS311_Text_Analytics
|
/stemming.py
| 609
| 4.3125
| 4
|
#stemming is the morphological variants of same root word
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer
ps = PorterStemmer()
#words to be stemmed (list)
stem_words = ["eat", "eats", "eating", "eaten", "eater", "received","receiving"]
#find stem word for each of the word in the list
for word in stem_words:
print(word, " : ",ps.stem(word))
#stemming a sentence
'''
1. tokennize each word
2. find stem word or each word
'''
file_content = open("input.txt").read()
tokens = word_tokenize(file_content)
for word in tokens:
print(word ," : ", ps.stem(word))
| true
|
9937cae75d06147093025d2482225550aace9f9a
|
Reena-Kumari20/code_war
|
/Reversed_Words.py
| 213
| 4.1875
| 4
|
# Complete the solution so that it reverses all of the words within the string passed
def reverse_words(s):
a=(' '.join(s.split(" ")[-1::-1]))
return a
string=["hell0 world!"]
print(reverse_words(string))
| true
|
8b99f60f51da55d805fcfdd13bf0e34bc71b8386
|
Reena-Kumari20/code_war
|
/sum_of_string.py
| 586
| 4.1875
| 4
|
'''Create a function that takes 2 positive integers in form of a string as an input, and outputs
the sum (also as a string):
Example: (Input1, Input2 -->Output)
"4", "5" --> "9"
"34", "5" --> "39"
Notes:
If either input is an empty string, consider it as zero.'''
def sum_str(a, b):
if a=="" and b=="":
return str(0)
elif a!="" and b=="":
return a
elif a=="" and b!="":
return b
else:
sum=int(a)+int(b)
x=str(sum)
y=type(x)
return x,y
a=input("string_first:- ")
b=input("string_second:- ")
print(sum_str(a,b))
| true
|
301a64567164a85abdef442a8672c985776a87e0
|
jreichardtaurora/hmwk_2_test
|
/HW2_Prob_1_JaredReichardt.py
| 1,398
| 4.3125
| 4
|
'''
Created on Sep 13, 2019
@author: jared r
CSC1700 section AM
The purpose of this problem was to write a calculator that calculates
the user's total shipping cost. It handles negative inputs properly, and prompts the user
for their package weight, and what type of shipping they used.
'''
def main():
print("Starting Fast Freight Shipping Company Shipping Calculator")
weight = float(input("What was your total package weight (in pounds)? "))
while weight <= 0:
weight = float(input("Error, please make sure your weight is a positive number: "))
ship = input("Did you use Expedited (E) or Regular (R) shipping? ")
if ship == 'E':
shipping = "Expedited"
elif ship == 'R':
shipping = "Regular"
if ship == 'E':
if weight <= 2:
rate = 1.5
elif weight <= 6:
rate = 3.0
elif weight < 10:
rate = 4.0
else:
rate = 4.75
elif ship == 'R':
if weight <= 2:
rate = 1.0
elif weight <= 6:
rate = 2.0
elif weight <= 10:
rate = 3.0
else:
rate = 3.5
total = rate * weight
print(f"Your total package weight was {weight} pounds.")
print(f"Your Selected Shipping was {shipping}.")
print("Your total shipping cost will be $" + format(total, '.2f'))
main()
| true
|
88b954e1465b806c15318999a4715c0e6c7d7cc4
|
renatocrobledo/probable-octo-spork
|
/codingame/src/norm_calculation.py
| 1,538
| 4.65625
| 5
|
'''
You are given an integer matrix of size N * M (a matrix is a 2D array of numbers).
A norm is a positive value meant to quantify the "size/length" of an element. In our case we want to compute the norm of a matrix.
There exist several norms, used for different scenarios.
Some of the most common matrix norms are :
- The norm 1: for each column of the matrix, compute the sum of the absolute values of every element in that column. The norm 1 is the maximum of these sums.
- The infinite norm: for each row of the matrix, compute the sum of the absolute values of every element in that row. The infinite norm is the maximum of these sums.
- The max norm: compute the maximum of the absolute values of every element in the matrix.
Given the matrix, print these three norms.
Input
N the number of rows
M the number of columns
Next N lines: the M values of each element in the row of the matrix
Output
A single line: N_1 N_INF N_MAX
With :
N_1 the norm 1 of the matrix
N_INF the infinite norm of the matrix
N_MAX the max norm of the matrix
'''
# transpose 2D list in Python (swap rows and columns)
n = int(input())
m = int(input())
l = []
whole_max = 0
rows = []
for i in range(n):
row = list(map(lambda x: abs(int(x)),input().split()))
_max = max(row)
if _max > whole_max:
whole_max = _max
rows.append(sum(row))
l.append(row)
cols = []
for t in list(zip(*l)):
cols.append(sum(t))
norm_1 = max(cols)
infinite_norm = max(rows)
max_norm = whole_max
print(f'{norm_1} {infinite_norm} {max_norm}')
| true
|
88963ec18f118fca69d3e26b3b57db8c5a2736cc
|
kundan7kumar/Algorithm
|
/Hashing/basic.py
| 476
| 4.1875
| 4
|
# Python tuple can be the key but python list cannot
a ={1:"USA",2:"UK",3:"INDIA"}
print(a)
print(a[1])
print(a[2])
print(a[3])
#print(a[4]) # key Error
# The functionality of both dictionaries and defualtdict are almost same except for the fact that defualtdict never raises a KeyError. It provides a default value for the key that does not exists.
from collections import defaultdict
d=defaultdict()
d["a"] =1
d["b"] = 2
print(d)
print(d["a"])
print(d["b"])
print(d["c"])
| true
|
43a8fae76b90437274501bafd949b39995401233
|
tongyaojun/corepython-tongyao
|
/chapter02/Test15.py
| 430
| 4.125
| 4
|
#!/usr/bin/python
#sort input numbers
userInput1 = int(input('Please input a number:'))
userInput2 = int(input('Please input a number:'))
userInput3 = int(input('Please input a number:'))
def getBiggerNum(num1, num2):
if num1 > num2:
return num1
else :
return num2
biggerNum = getBiggerNum(userInput1, userInput2)
biggestNum = getBiggerNum(biggerNum, userInput3)
print('The biggest num is:', biggestNum)
| true
|
c328f75f3d0278660d4d544563b5d953af5b7041
|
jjti/euler
|
/Done/81.py
| 2,016
| 4.21875
| 4
|
def path_sum_two_ways(test_matrix=None):
"""
read in the input file, and find the sum of the minimum path
from the top left position to the top right position
Notes:
1. Looks like a dynamic programming problem. Ie, start bottom
right and find the sum of the minimum path from the current square
to the bottom right
"""
matrix = test_matrix
if test_matrix is None:
# import the downloaded matrix
matrix = []
with open("81.input.txt") as matrix_file:
for line in matrix_file:
matrix.append([int(num) for num in line.split(",")])
# initialize distances at None
min_path = [[None] * len(matrix)] * len(matrix)
max_ind = len(matrix) - 1 # it's a square matrix
for i in range(max_ind, -1, -1): # vertical
for j in range(max_ind, -1, -1): # horizontal
if i == max_ind and j == max_ind:
# we're in the bottom right corner
min_path[i][j] = matrix[i][j]
elif j == max_ind and i < max_ind:
# we're along the right side of the matrix
# have to go down
min_path[i][j] = matrix[i][j] + min_path[i + 1][j]
elif j < max_ind and i == max_ind:
# we're along the bottom of the matrix
# have to go right
min_path[i][j] = matrix[i][j] + min_path[i][j + 1]
else:
# we're not up against either side of the matrix
# find the minimum route from this to the right or downwards
min_path[i][j] = matrix[i][j] + min(
[min_path[i + 1][j], min_path[i][j + 1]])
return min_path[0][0]
assert path_sum_two_ways([[131, 673, 234, 103, 18], [201, 96, 342, 965, 150],
[630, 803, 746, 422, 111], [537, 699, 497, 121, 956],
[805, 732, 524, 37, 331]]) == 2427
print(path_sum_two_ways()) # output: 427337 in 0.056 seconds
| true
|
b3cca4d969aa2be4ad517aad8d903ae2826da02d
|
jjti/euler
|
/Done/65.py
| 2,141
| 4.1875
| 4
|
import utils
"""
The square root of 2 can be written as an infinite continued fraction.
The infinite continued fraction can be written, 2**0.5 = [1;(2)], (2) indicates that 2 repeats ad infinitum. In a similar way, 23**0.5 = [4;(1,3,1,8)].
It turns out that the sequence of partial values of continued fractions for square roots provide the best rational approximations.
Let us consider the convergents for 2**0.5.
Hence the sequence of the first ten convergents for 2**0.5 are:
1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, ...
What is most surprising is that the important mathematical constant,
e = [2; 1,2,1, 1,4,1, 1,6,1 , ... , 1,2k,1, ...].
The first ten terms in the sequence of convergents for e are:
2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, ...
The sum of digits in the numerator of the 10th convergent is 1+4+5+7=17.
Find the sum of digits in the numerator of the 100th convergent of the continued fraction for e.
"""
def denom_seq(length=30):
"""
What is most surprising is that the important mathematical constant,
e = [2; 1,2,1, 1,4,1, 1,6,1 , ... , 1,2k,1, ...].
make that seq ^
"""
return [2 * (i / 3) if not i % 3 else 1 for i in range(2, length + 2)]
assert denom_seq(9) == [1, 2, 1, 1, 4, 1, 1, 6, 1]
def convergence_of_e(upper_limit=100):
"""
increment the fraction until we reach upper limit
sum the digits in the numerator after incrementing target number of times
Notes:
1. the multiplier here (in the denom_seq above), is like a multiplier
for the numerator and denominator when calculating the next fraction
2. if p, q is the next numerator and denominator, and we have
a, b and c, d as the n-1 and n fractions:
p = a + multiplier(c)
q = b + multiplier(d)
3. aannndddd the denominator has nothing to do with it...
"""
# a and b are last and current numerators
a, b = 2, 3
for multiplier in denom_seq(upper_limit - 1)[1:]:
a, b = b, a + multiplier * b
return sum(utils.split(b))
assert convergence_of_e(10) == 17
# outputs 272 in 0.05 seconds
print convergence_of_e(100)
| true
|
d6a3a1abfac543f817434f9b903515db63993c02
|
jjti/euler
|
/Done/57.py
| 1,511
| 4.125
| 4
|
import utils
"""
It is possible to show that the square root of two can be expressed as an infinite continued fraction.
2 ** 1/2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
By expanding this for the first four iterations, we get:
1 + 1/2 = 3/2 = 1.5
1 + 1/(2 + 1/2) = 7/5 = 1.4
1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...
The next three expansions are 99/70, 239/169, and 577/408,
but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.
In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?
"""
def SquareOfTwoGenerator(limit=1000):
"""
numerators = 3, 7, 17, 41, 99
denominators = 2, 5, 12, 29, 70
the next numerator is the current numerator + 2 times the last denominator
the next denominator is the sum of the current numerator and denominator
"""
index, num, den = 0, 3, 2
while index < limit:
"""set the next numerator and denominator
return whether the numerator has more digits than the denominator (see above)"""
hit = len(utils.split(num)) > len(utils.split(den))
num, den = num + 2 * den, num + den
index += 1
yield hit
# now run thru the iterator and accumulate all the hits
count = 0
for numerBiggerThanDenom in SquareOfTwoGenerator():
if numerBiggerThanDenom:
count += 1
print(count)
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.