blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
dadbdd33b087e16ffcbb985b8b28e1e215f5fc53
|
Sandro37/Introducao_ao_python-CURSO-Digital_Innovation-One
|
/aula02.py
| 1,172
| 4.25
| 4
|
#O que são variáveis e como manipulá-las através
# de operadores aritméticos e interação com o osuário
valorA = int(input("Entre com o primeiro valor: "))
valorB = int(input("Entre com o segundo valor: "))
soma = valorA + valorB
subtracao = valorA - valorB
multiplicacao = valorA * valorB
divisao = valorA / valorB
restoDivisao = valorA % valorB
print(soma)
print(subtracao)
print(multiplicacao)
print(divisao)
print(restoDivisao)
print("soma: " + str(soma))
print("________________________________________")
print("Soma: {}".format(soma))
print("Substração: {}".format(subtracao))
print("Multiplicação: {}".format(multiplicacao))
print("Divisão: {}".format(divisao))
print("Resto da divisão: {}".format(restoDivisao))
print("________________________________________________________________")
x = '1'
soma2 = int(x) + 1
print("Soma convertida = {}".format(soma2))
print("________________________________________________________________")
print("soma: {soma}. \nSubtração: {sub}\nMultiplicacao: {multiplicacao}\nDivisão: {div}\nResto da Divisão: {resto}".format(soma=soma, sub=subtracao,multiplicacao=multiplicacao,div=divisao,resto=restoDivisao))
| false
|
4f532cd9216766b1dfdb41705e9d643798d70225
|
Sandro37/Introducao_ao_python-CURSO-Digital_Innovation-One
|
/aula05.py
| 1,138
| 4.125
| 4
|
#como organizar os dados em uma lista ou tupla
# e realizar operações com elas
lista = [12,20,1,3,5,7]
lista_animal = ['cachorro', 'gato', 'elefante']
# print(lista_animal[1])
soma = 0
for x in lista:
soma += x
print(soma)
print(sum(lista))
print(max(lista))
print(min(lista))
print(max(lista_animal))
print(min(lista_animal))
# nova_lista = lista_animal * 3
#
# print(nova_lista)
if 'gato' in lista_animal:
print('Existe um gato na lista')
else:
print('Não existe um gato na lista')
if 'lobo' in lista_animal:
print('Existe um lobo na lista')
else:
print('Não existe um lobo na lista. Será incluido')
lista_animal.append('lobo')
print(lista_animal)
lista_animal.pop()
print(lista_animal)
lista_animal.remove('elefante')
print(lista_animal)
#ordenando lista
lista_animal.sort()
lista.sort()
print(lista_animal)
print(lista)
# reverse
lista_animal.reverse()
lista.reverse()
print(lista_animal)
print(lista)
# tuplas (imutável)
tupla = (1,10,12,14,20,185)
print(len(tupla))
tupla_animal = tuple(lista_animal)
print(tupla_animal)
lista_numerica = list(tupla)
print(lista_numerica)
| false
|
db0efc096311e8d2bd40a9f845af2a4ee2a38caf
|
mhelal/COMM054
|
/python/evennumberedexercise/Exercise4_6.py
| 525
| 4.3125
| 4
|
# Prompt the user to enter weight in pounds
weight = eval(input("Enter weight in pounds: "))
# Prompt the user to enter height
feet = eval(input("Enter feet: "))
inches = eval(input("Enter inches: "))
height = feet * 12 + inches
# Compute BMI
bmi = weight * 0.45359237 / ((height * 0.0254) * (height * 0.0254))
# Display result
print("BMI is", bmi)
if bmi < 18.5:
print("Underweight")
elif bmi < 25:
print("Normal")
elif bmi < 30:
print("Overweight")
else:
print("Obese")
| false
|
b37520ed33b2fef924c8ea17c96d34799b78cc37
|
TimKillingsworth/Codio-Assignments
|
/src/dictionaries/person_with_school.py
| 306
| 4.34375
| 4
|
#Create dictionary with person information. Assign the dictionary to the variable person
person={'name':'Lisa', 'age':29}
#Print out the contents of person
print(person)
#Add the school which Lisa attends
person['school'] = 'SNHU'
#Print out the contents of person after adding the school
print(person)
| true
|
5dff174f4164bb5933de55efcf58c74152287e51
|
TimKillingsworth/Codio-Assignments
|
/src/dictionaries/list_of_dictionary.py
| 336
| 4.59375
| 5
|
#Create a pre-populated list containing the informatin of three persons
persons=[{'name':'Lisa','age':29,'school':'SNHU'},
{'name': 'Jay', 'age': 25, 'school': 'SNHU'},
{'name': 'Doug', 'age': 27, 'school': 'SNHU'}]
#Print the person list
print(persons)
#Access the name of the first person
print(persons[1]['name'])
| false
|
47f7f996f21d85e5b7613aa14c1a6d2752faaa82
|
zaidjubapu/pythonjourney
|
/h5fileio.py
| 1,969
| 4.15625
| 4
|
# file io basic
'''f = open("zaid.txt","rt")
content=f.read(10) # it will read only first 10 character of file
print(content)
content=f.read(10) # it will read next 10 character of the file
print(content
f.close()
# must close the file in every program'''
'''f = open("zaid.txt","rt")
content=f.read() # it will read all the files
print(1,content) # print content with one
content=f.read()
print(2,content) # it will print only 2 because content are printed allready
f.close()'''
'''if we want to read the file in a loop with
f = open("zaid.txt","rt")
for line in f:
print(line,end="")'''
# if want to read character in line by line
'''f = open("zaid.txt","rt")
content=f.read()
for c in content:
print(c)'''
#read line function
'''f = open("zaid.txt","rt")
print(f.readline()) # it wiil read a first line of the file
print(f.readline()) # it will read next line of the file it will give a space because the new line wil already exist in that
f.close()'''
# readlines functon wil use to create a list of a file with 1 line as 1 index
'''f = open("zaid.txt","rt")
print(f.readlines())'''
# writ functions
'''f=open("zaid.txt","w")
f.write("hello how are you") # replce the content with what we have written
f.close()'''
'''f=open("zaid1.txt","w") # the new file wil come with name zaid1
f.write("hello how are you") # the new file will created and the content will what we have written
f.close()'''
# append mode in write
'''f=open("zaid2.txt","a") # the new file wil come with name zaid1 and will append the character at the end how much we run the program
a=f.write("hello how are you\n") # the new file will created and the content will what we have written
print(a) # it will display the no of character in the file
f.close()'''
#if want to use read and write function simultaneously
f=open("zaid.txt","r+") #r+ is used for read and write
print(f.read())
f.write("thankyou")
f.write("zaid")
f.close()
| true
|
014987c11429d51e6d1462e3a6d0b7fb97b11822
|
zaidjubapu/pythonjourney
|
/enumeratefunction.py
| 592
| 4.59375
| 5
|
'''enumerate functions: use for to easy the method of for loop the with enumerate method
we can find out index of the list
ex:
list=["a","b","c"]
for index,i in enumerate(list):
print(index,i)
'''
''' if ___name function :
print("and the name is ",__name__)# it will give main if it is written before
if __name__ == '__main__': # it is used for if we want to use function in other file
print("hello my name is zaid")'''
'''
join function:
used to concatenat list in to string
list=["a","b","c","d"]
z=" and ".join(list) #used to concatenate the items of the sting
print(z)'''
| true
|
50e523c196fc0df4be3ce6acab607f623119f4e1
|
zaidjubapu/pythonjourney
|
/h23abstractbaseclassmethod.py
| 634
| 4.21875
| 4
|
# from abc import ABCMeta,abstractmethod
# class shape(metaclass=ABCMeta):
# or
from abc import ABC,abstractmethod
class shape(ABC):
@abstractmethod
def printarea(self):
return 0
class Rectangle(shape):
type= "Rectangle"
sides=4
def __init__(self):
self.length=6
self.b=7
# def printarea(self):
# return self.length+self.b
harry=Rectangle() # if we use abstract method before any function. then if we inherit the class then it gives an errr
# untill that method is not created inside that class
# now it wil give error
# we cant create an object of abstract base class method
| true
|
dfc07a2dd914fa785f5c9c581772f92637dea0a7
|
zaidjubapu/pythonjourney
|
/h9recursion.py
| 1,167
| 4.28125
| 4
|
'''
recursive and iterative method;
factorial using iterative method:
# using iterative method
def factorialiterative(n):
fac=1
for i in range(n):
print(i)
fac=fac*(i+1)
return fac
# recusion method which mean callingthe function inside the function
def factorialrecursion(n):
if n==1:
return 1
else:
z= n * factorialrecursion(n-1)
return z
n=int(input("enter the fact n0"))
print("the factorial iteration is", factorialiterative(n))
print("the factorial recursion is", factorialrecursion(n))
print(factorialrecursion(3))'''
# fibonaccis series:0 1 1 2 3 5 8 13 which adding the backwaard two numbers
'''
def fibonacci(n):
if n==1:
return 0
elif n==2:
return 1
elif n==3: # if we want 3 addition
return 1
return fibonacci(n-1) + fibonacci(n-2)# + fibonacci(n-3) if we want 3 addition in line
n=int(input("enter the nuber"))
print(fibonacci(n))'''
def factorialrecursion(n):
if n==1:
return 1
else:
z= n + factorialrecursion(n-1)
return z
n=int(input("enter the fact n0"))
print("the factorial iteration is", factorialrecursion(n))
| false
|
22773f2a2796ae9a493020885a6e3a987047e7f8
|
Pegasus-01/hackerrank-python-works
|
/02-division in python.py
| 454
| 4.125
| 4
|
##Task
##The provided code stub reads two integers, a and b, from STDIN.
##Add logic to print two lines. The first line should contain the result of integer division, a// b.
##The second line should contain the result of float division, a/ b.
##No rounding or formatting is necessary.
if __name__ == '__main__':
a = int(input())
b = int(input())
intdiv = a//b
floatdiv = a/b
print(intdiv)
print(floatdiv)
| true
|
139d9c55627188c10bc2304695fd3c66c700ceb2
|
shudongW/python
|
/Exercise/Python40.py
| 507
| 4.25
| 4
|
#-*- coding:UTF-8 -*-
#笨办法学编程py3---字典
cities ={'CA':'San Francisco','MI':'Detroit','FL':'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
def find_city(themap, state) :
if state in themap:
return themap[state]
else:
return "Not found."
cities['_find'] = find_city
while True :
print("State? (ENTER to quit)", end = " ")
state = input("> ")
if not state : break
city_found = cities['_find'](cities,state)
print(city_found)
| false
|
a0c6ea7a8f1310a36a81b72c6edf4214def0ae62
|
BarunBlog/Python-Files
|
/14 Tuple.py
| 468
| 4.375
| 4
|
tpl = (1, 2, 3, "Hello", 3.5, [4,5,6,10])
print(type(tpl)," ",tpl,"\n")
print(tpl[5]," ",tpl[-3])
for i in tpl:
print(i, end=" ")
print("\n")
#converting tuple to list
li = list(tpl)
print(type(li),' ',li,"\n")
tpl2 = 1,2,3
print(type(tpl2)," ",tpl2)
a,b,c = tpl2
print(a," ",b," ",c)
t = (1)
print(type(t))
t1 = (1,)
print(type(t1))
'''
difference between tuple & list
Can not overwrite vales in tuple
'''
tpl3 = (1,2,3, [12,10], (14,15), 20)
print(tpl3)
| false
|
5a4c0c930ea92260b88f0282297db9c9e5bffe3f
|
BarunBlog/Python-Files
|
/Learn Python3 the Hard Way by Zed Shaw/13_Function&Files_ex20.py
| 1,236
| 4.21875
| 4
|
from sys import argv
script, input_file = argv
def print_all(f):
print(f.read())
def rewind(f):
f.seek(0)
'''
fp.seek(offset, from_what)
where fp is the file pointer you're working with; offset means how many positions you will move; from_what defines your point of reference:
0: means your reference point is the beginning of the file
1: means your reference point is the current file position
2: means your reference point is the end of the file
if omitted, from_what defaults to 0.
'''
def print_a_line(line_count, f):
print(line_count, f.readline())
'''
readline() reads one entire line from the file.
fileObject.readline( size );
size − This is the number of bytes to be read from the file.
The fle f is responsible for maintaining the current position in the fle after each readline() call
'''
current_file = open(input_file)
print("First let's print the whole file:\n")
print_all(current_file)
print("Now let's rewind, kind of like a tape.")
rewind(current_file)
print("Let's print three lines:")
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
| true
|
b6fefcbd7ae15032f11a372c583c5b9d7b3199d9
|
BarunBlog/Python-Files
|
/02 String operation.py
| 993
| 4.21875
| 4
|
str1 = "Barun "
str2 = "Hello "+"World"
print(str1+" "+str2)
'''
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
'''
str3 = 'I don\'t think so'
print(str3)
print('Source:D \Barun\Python files\first project.py')
# raw string changed heres
print(r'Source:D \Barun\Python files\first project.py') # r means rush string..
#raw string stays the way you wrote it
str4 = str1+str2
print(str4)
print(str1 * 5)
x = ' '
print(str2.find('World'),x,str2.find('Word'))
print(len(str2))
print(str2.replace('Hello','hello')) # replace returns string but don't replace parmanently
print(str2,"\n")
new_str2 = str2.replace('H','h')
print(new_str2)
print(str2)
str5 = "Hello World!"
print(str5)
del str5
#print(str5) # it will give an error
st1 = "Barun Bhattacharjee"
st2 = "Hello World!"
li = st2.split(" ")
print(li)
st3 = li[0] +' '+ st1
print(st3)
st4 = st2.replace("World!", st1)
print(st4)
| true
|
047dd0b26413c4e4130f551a9aec46fafafd753f
|
AnkitAvi11/100-Days-of-Code
|
/Strings/union.py
| 973
| 4.1875
| 4
|
# program to find the union of two sorted arrays
class Solution :
def find_union(self, arr1, arr2) :
i, j = 0, 0
while i < len(arr1) and j < len(arr2) :
if arr1[i] < arr2[j] :
print(arr1[i], end = " ")
i+=1
elif arr2[j] < arr1[i] :
print(arr2[j], end = " ")
j += 1
elif arr1[i] == arr2[j] :
print(arr1[i], end = " ")
i += 1
j += 1
if i == len(arr1) :
for el in arr2[j:] :
print(el, end = " ")
else :
for el in arr1[i:] :
print(el, end = " ")
def main() :
t = int(input())
for _ in range(t) :
arr1 = list(map(int, input().split()))
arr2 = list(map(int, input().split()))
solution = Solution()
solution.find_union(arr1, arr2)
if __name__ == '__main__' :
main()
| false
|
6c727ec6706b42ea057f264ff97d6f39b7481338
|
AnkitAvi11/100-Days-of-Code
|
/Day 11 to 20/MoveAllnegative.py
| 798
| 4.59375
| 5
|
"""
python program to move all the negative elements to one side of the array
-------------------------------------------------------------------------
In this, the sequence of the array does not matter.
Time complexity : O(n)
space complexity : O(1)
"""
# function to move negatives to the right of the array
def move_negative(arr : list) -> None :
left = 0;right = len(arr) - 1
while left < right :
if arr[left] < 0 :
while arr[right] < 0 : right-=1
# swap the two ends of the array
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
else :
left += 1
# driver code
if __name__ == "__main__":
arr = [1,2,-1,3,5,-2,7,8]
move_negative(arr)
print(arr)
| true
|
9f076e1b7465ff2d509b27296a2b963dd392a7f9
|
kishoreramesh84/python-75-hackathon
|
/filepy2.py
| 523
| 4.28125
| 4
|
print("Reading operation from a file")
f2=open("newfile2.txt","w")
f2.write(" Hi! there\n")
f2.write("My python demo file\n")
f2.write("Thank u")
f2.close()
f3=open("newfile2.txt","r+")
print("Method 1:")
for l in f3: #Method 1 reading file using loops
print(l,end=" ")
f3.seek(0) #seek is used to place a pointer to a specific location
print("\nMethod 2:")
print(f3.read(10))#Method 2 it reads 10 character from file
f3.seek(0)
print("Method 3:")
print(f3.readlines())#Method 3 it prints the text in a list
f3.close()
| true
|
492503ce1d085ca365be4934606c8746e41c9d3e
|
rodrikmenezes/ProjetoEuler
|
/4 LargestPalindromeProduct2.py
| 1,041
| 4.1875
| 4
|
# =============================================================================
# A palindromic number reads the same both ways. The largest palindrome made
# from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
# =============================================================================
import numpy as np
def palindromos():
''' Retorna uma lista de números palíndromos formados
pela multiplicação entre outros dois números de dois dígitos'''
palindromos = []
for i in range(1, 1000):
for j in range(1, 1000):
p = i * j
s = str(p)
l = len(s)
cont = 0
n = int(np.floor(l/2))
for w in range(0, n):
ww = (w+1) * (-1)
if s[w] == s[ww]:
cont += 1
if cont == n:
palindromos.append(p)
return list(sorted(set(palindromos)))
# Resposta
print(max(palindromos()))
| false
|
5a91c22b5ee87704cc8991bd6dab3eb2b2684d8b
|
ivanvi22/repository_name
|
/HelloWorld.py
| 323
| 4.1875
| 4
|
# программа для вывода "Hello World"
car_color = 'wite'
car_type = 'masda'
car_count = 2
print("Укажите цвет машины:")
car_color = input()
print("Укажите тип машины:")
car_type = input()
print("You have " + str(car_count) + ' ' + car_color + ' ' + car_type)
print(2 ** 3)
| false
|
5bbce3aaa6c5a5d38b2a2848ce856322107a8c91
|
mirsadm82/pyneng-examples-exercises-en
|
/exercises/06_control_structures/answer_task_6_2a.py
| 1,788
| 4.34375
| 4
|
# -*- coding: utf-8 -*-
"""
Task 6.2a
Make a copy of the code from the task 6.2.
Add verification of the entered IP address.
An IP address is considered correct if it:
- consists of 4 numbers (not letters or other symbols)
- numbers are separated by a dot
- every number in the range from 0 to 255
If the IP address is incorrect, print the message: 'Invalid IP address'
The message "Invalid IP address" should be printed only once,
even if several points above are not met.
Restriction: All tasks must be done using the topics covered in this and previous chapters.
"""
ip_address = input("Enter ip address: ")
octets = ip_address.split(".")
correct_ip = True
if len(octets) != 4:
correct_ip = False
else:
for octet in octets:
if not (octet.isdigit() and int(octet) in range(256)):
correct_ip = False
break
if not correct_ip:
print("Invalid IP address")
else:
octets_num = [int(i) for i in octets]
if octets_num[0] in range(1, 224):
print("unicast")
elif octets_num[0] in range(224, 240):
print("multicast")
elif ip_address == "255.255.255.255":
print("local broadcast")
elif ip_address == "0.0.0.0":
print("unassigned")
else:
print("unused")
# second version
ip = input("Enter IP address")
octets = ip.split(".")
valid_ip = len(octets) == 4
for i in octets:
valid_ip = i.isdigit() and 0 <= int(i) <= 255 and valid_ip
if valid_ip:
if 1 <= int(octets[0]) <= 223:
print("unicast")
elif 224 <= int(octets[0]) <= 239:
print("multicast")
elif ip == "255.255.255.255":
print("local broadcast")
elif ip == "0.0.0.0":
print("unassigned")
else:
print("unused")
else:
print("Invalid IP address")
| true
|
86fc4bc0e652ee494db883f657e918b2b056cf3e
|
mirsadm82/pyneng-examples-exercises-en
|
/exercises/04_data_structures/task_4_8.py
| 1,107
| 4.125
| 4
|
# -*- coding: utf-8 -*-
"""
Task 4.8
Convert the IP address in the ip variable to binary and print output in columns
to stdout:
- the first line must be decimal values
- the second line is binary values
The output should be ordered in the same way as in the example output below:
- in columns
- column width 10 characters (in binary
you need to add two spaces between columns
to separate octets among themselves)
Example output for address 10.1.1.1:
10 1 1 1
00001010 00000001 00000001 00000001
Restriction: All tasks must be done using the topics covered in this and previous chapters.
Warning: in section 4, the tests can be easily "tricked" into making the
correct output without getting results from initial data using Python.
This does not mean that the task was done correctly, it is just that at
this stage it is difficult otherwise test the result.
"""
ip = "192.168.3.1"
octets = ip.split(".")
output = """
{0:<10}{1:<10}{2:<10}{3:<10}
{0:08b} {1:08b} {2:08b} {3:08b}"""
print(output.format(int(octets[0]), int(octets[1]), int(octets[2]), int(octets[3])))
| true
|
b3cfe1ba6b28715f0f2bccff2599412d406fd342
|
n001ce/python-control-flow-lab
|
/exercise-5.py
| 670
| 4.40625
| 4
|
# exercise-05 Fibonacci sequence for first 50 terms
# Write the code that:
# 1. Calculates and prints the first 50 terms of the fibonacci sequence.
# 2. Print each term and number as follows:
# term: 0 / number: 0
# term: 1 / number: 1
# term: 2 / number: 1
# term: 3 / number: 2
# term: 4 / number: 3
# term: 5 / number: 5
# etc.
# Hint: The next number is found by adding the two numbers before it
# Program to display the Fibonacci sequence up to n-th term
n1, n2 = 0, 1
count = 0
print("Fibonacci sequence:")
while count < 50:
print(f"term: {count} / number: {n1}")
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
| true
|
061aa64d7b81d640feac402dd1840ec8e80b1c7c
|
advancer-debug/Daily-learning-records
|
/数据结构与算法记录/习题解答记录/链表/offero6_test.py
| 2,482
| 4.125
| 4
|
# -*- coding = utf-8 -*-
# /usr/bin/env python
# @Time : 20-11-28 下午2:02
# @File : offero6_test.py
# @Software: PyCharm
# 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
# 方法一递归法
# 利用递归: 先走至链表末端,回溯时依次将节点值加入列表 ,这样就可以实现链表值的倒序输出。
# python算法流程
# 递推阶段: 每次传入 head.next ,以 head == None(即走过链表尾部节点)为递归终止条件,此时返回空列表 [] 。
# 回溯阶段: 利用 Python 语言特性,递归回溯时每次返回 当前 list + 当前节点值 [head.val] ,
# 即可实现节点的倒序输出。
# 复杂度分析:
#
# 时间复杂度 O(N): 遍历链表,递归 N 次。
# 空间复杂度 O(N): 系统递归需要使用 O(N) 的栈空间。
# Definition for singly-linked list.
# 1.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseprint(self, head: ListNode)->List[int]:
return self.reverseprint(head.next)+[head.val] if head else []
# 2.
class Solution:
def reverseprint(self, head: ListNode)->List[int]:
p, rev = head, None
while p:
rev, rev.next, p = p, rev, p.next
result = []
while rev:
result.append(rev.val)
rev = rev.next
return result
# 辅助栈法
# 解题思路:
# 链表特点: 只能从前至后访问每个节点。
# 题目要求: 倒序输出节点值。
# 这种 先入后出 的需求可以借助 栈 来实现。
# 算法流程:
# 入栈: 遍历链表,将各节点值 push 入栈。(Python 使用 append() 方法,Java借助 LinkedList 的addLast()方法)。
# 出栈: 将各节点值 pop 出栈,存储于数组并返回。(Python 直接返回 stack 的倒序列表,Java 新建一个数组,通过 popLast() 方法将各元素存入数组,实现倒序输出)。
# 复杂度分析:
# 时间复杂度O(N):入栈和出栈共使用O(N)时间。
# 空间复杂度O(N):辅助栈stack和数组res共使用 O(N)的额外空间。
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
stack = []
while head:
stack.append(head.val)
head = head.next
return stack[::-1] # stack.reverse() return stack
| false
|
8d980ed029b0dc74e4dc6aa0e7785d6af0f95fa7
|
NiharikaSinghRazdan/PracticeGit_Python
|
/Code_Practice/list_exercise.py
| 512
| 4.21875
| 4
|
# Convert string into list
mystring="This is the new change"
mylist = []
for letter in mystring:
mylist.append(letter)
print(mylist)
# Change string into list with different convert format and in one line
mystring1="Hi There"
mylist1 =[letter for letter in mystring1]
print(mylist1)
# Check other usage of this new one liner format to convert string into list
#Check the odd no in list
mylist2=[num for num in range(0,11) if num%2==0]
print(mylist2)
mylist2=[num**2 for num in range(0, 11)]
print(mylist2)
| true
|
bc76d2ae44f894254a3e24c0b53c61db5039f4ff
|
NiharikaSinghRazdan/PracticeGit_Python
|
/Code_Practice/arbitary_list.py
| 1,556
| 4.1875
| 4
|
#retrun the list where the passed arguments are even
def myfunc(*args):
mylist=[]
for item in args:
if item%2==0:
mylist.append(item)
else:
continue
print(mylist)
print(myfunc(-2,4,3,5,7,8,10))
# return a string where every even letter is in uppercase and every odd letter is in lowercase
def myfunct(*args):
mylist1=[]
for item in args:
# find the index of the items
index=args.index(item)
if (item==item.upper() and index%2==0) or (item==item.lower() and index%2!=0):
mylist1.append(item)
print(mylist1)
print(myfunct('A','B','C','D','e',"f"))
# check the index of the list and verify that even is in uppercase and odd index is in lower case
def myfunc1(*args):
mystring=' '
mystring_t=args[0]
print(len(mystring_t))
for item in range(len(mystring_t)):
if (item%2==0):
mystring=mystring+mystring_t[item].upper()
else:
mystring=mystring+mystring_t[item].lower()
print(mystring)
print(myfunc1("supercalifragilisticexpialidocious"))
# print the argument in upper and lowercase alternate
def myfunc2(*args):
mystring_total=args[0]
c_string=' '
for item in mystring_total:
index1=mystring_total.index(item)
if (index1%2==0):
item=item.upper()
c_string=c_string+item
else:
item=item.lower()
c_string=c_string+item
print(mystring_total)
print(c_string)
print(myfunc2("AbcdEFGHijKL"))
| true
|
37b1dce3bcbe2da05065e677491797983588c285
|
dankolbman/NumericalAnalysis
|
/Homeworks/HW1/Problem1.py
| 520
| 4.21875
| 4
|
import math
a = 25.0
print("Squaring a square-root:")
while ( math.sqrt(a)**2 == a ):
print('sqrt(a)^2 = ' + str(a) + ' = ' + str(math.sqrt(a)**2))
a *= 10
# There was a rounding error
print('sqrt(a)^2 = ' + str(a) + ' != ' + str(math.sqrt(a)**2))
# Determine the exponent of the float
expo = math.floor(math.log10(a))-1.0
# Reduce to only significant digits
b = a/(10**expo)
print("Ajusting decimal placement before taking the square-root:")
print('sqrt(a)^2 = ' + str(a) + ' = ' + str((math.sqrt(b)**2)*10**expo))
| true
|
33d08154e946264256f7810254cd09f236622718
|
bravacoreana/python
|
/files/08.py
| 409
| 4.34375
| 4
|
# if <condition> :
# when condition is true
if True:
print("it's true")
if False:
print("it's false")
number = input("input a number >>> ")
number = int(number)
if number % 2 == 0:
print("even")
if number % 2 != 0:
print("odd")
if number < 10:
print("less than 10")
elif number < 20:
print("less than 20")
elif number < 30:
print("less than 30")
else:
print("hahaha")
| false
|
bfc1710b45ac38465e6f545968f2e00cd535d2dc
|
Tarun-Rao00/Python-CodeWithHarry
|
/Chapter 4/03_list_methods.py
| 522
| 4.21875
| 4
|
l1 = [1, 8, 7, 2, 21, 15]
print(l1)
l1.sort() # sorts the list
print("Sorted: ", l1)
l1.reverse() #reverses the list
print("Reversed: ",l1)
l1.reverse()
print("Reversed 2: ",l1)
l1.append(45) # adds to the end of the list
print ("Append", l1)
l2 = [1,5, 4, 10]
l1.append(l2) # l2 (list) will be added
print("Append 2", l1)
l1.insert(0, 100) # Inserts 100 at 0-(position)
print("Inserted", l1)
l1.pop(2) # removes item from position 2
print("Popped", l1)
l1.remove(7) # removes 7 from the list
print("Removed", l1)
| true
|
0ab24f03f7919f96e74301d06dd9af5a377ff987
|
Tarun-Rao00/Python-CodeWithHarry
|
/Chapter 2/02_operators.py
| 548
| 4.125
| 4
|
a = 34
b = 4
# Arithimatic Operator
print("the value of 3+4 is ", 3+4)
print("the value of 3-4 is ", 3-4)
print("the value of 3*4 is ", 3*4)
print("the value of 3/4 is ", 3/4)
# Assignment Operators
a = 34
a += 2
print(a)
# Comparision Operators
b = (7>14)
c = (7<14)
d = (7==14)
e = (7>=14)
print(b)
print(c)
print(d)
print(e)
# Logical Operators
boo1 = True
bool2 = False
print("The value of bool1 and bool2 is", (boo1 and bool2))
print("The value of bool1 and bool2 is", (boo1 or bool2))
print("The value of bool1 and bool2 is", (not bool2))
| true
|
d31f727127690b2a4584755c941cd19c7452d9e4
|
Tarun-Rao00/Python-CodeWithHarry
|
/Chapter 6/11_pr_06.py
| 221
| 4.15625
| 4
|
text = input("Enter your text: ")
text1 = text.capitalize()
num1 = text1.find("Harry")
num2 = text1.find("harry")
if (num1==-1 and num2==-1):
print("Not talking about Harry")
else:
print("Talking about Harry")
| true
|
406ad197c1a6b2ee7529aaa7c6ea5a86e10114de
|
carrenolg/python-code
|
/Chapter12/optimize/main.py
| 896
| 4.25
| 4
|
from time import time, sleep
from timeit import timeit, repeat
# main
def main():
"""
# measure timing
# example 1
t1 = time()
num = 5
num *= 2
print(time() - t1)
# example 2
t1 = time()
sleep(1.0)
print(time() - t1)
# using timeit
print(timeit('num = 5; num *= 2', number=1))
print(repeat('num = 5; num *= 2', number=1, repeat=3))
"""
# Algorithms and Data Structures
# build a list in different ways
def make_list_1():
result = []
for value in range(1000):
result.append(value)
return result
def make_list_2():
result = [value for value in range(1000)]
return result
print('make_list_1 takes', timeit(make_list_1, number=1000), 'seconds')
print('make_list_2 takes', timeit(make_list_2, number=1000), 'seconds')
if __name__ == '__main__':
main()
| true
|
c5333727d54b5cb7edff94608ffb009a29e6b5f4
|
nikita5119/python-experiments
|
/cw1/robot.py
| 1,125
| 4.625
| 5
|
# A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer.
# Example:
# If the following tuples are given as input to the program:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# Then, the output of the program should be:
# 2
position=[0,0]
while True:
a= input("enter the direction and steps :")
if not a:
break
direction, steps= a.split(' ')
steps=int(steps)
if (direction== "up"):
position[0]= position[0]+steps
elif (direction=="down"):
position[0]=position[0]-steps
if (direction=="right"):
position[1]=position[1]+steps
elif (direction=="left"):
position[1]=position[1]-steps
print(position)
distance=(position[0]**2+position[1]**2)**(1/2)
print(distance)
| true
|
6e468bf7c8d0d37233ee7577645e1d8712b83474
|
TameImp/compound_interest_app
|
/test_calc.py
| 929
| 4.125
| 4
|
'''
this programme test the compound interest calculator
'''
from calc import monthly_compounding
def test_tautology():
assert 3 == 3
#test that investing no money generates no returns
def test_zeros():
#initialise some user inputs
initial = 0
monthly = 0
years = 0
annual_rate = 0
#calculate a final sum
final_sum = monthly_compounding(initial, monthly, years, annual_rate)
#test out
assert final_sum == 0
def test_cash():
initial = 1000
monthly = 100
years = 10
annual_rate = 0
#calculate a final sum
final_sum = monthly_compounding(initial, monthly, years, annual_rate)
#test out
assert final_sum == 13000
def test_rate():
initial = 1000
monthly = 100
years = 2/12
annual_rate = 12
# calculate a final sum
final_sum = monthly_compounding(initial, monthly, years, annual_rate)
#test out
assert final_sum == 1221.1
| true
|
e0ee6d13b199a167c7cf72672876ff5d4b6e1b99
|
LuisPereda/Learning_Python
|
/Chapter03/excercise1.py
| 420
| 4.1875
| 4
|
# This program parses a url
url = "http://www.flyingbear.co/our-story.html#:~:text=Flying%20Bear%20is%20a%20NYC,best%20rate%20in%20the%20city."
url_list = url.split("/") # Parsing begins at character (/)
domain_name = url_list[2] # Dictates at which character number parsing begins
print (domain_name.replace("www.","")) # Deletes a specific character or string of characters and replaces them with desired input
| true
|
61e27a466ee3a9d70062faf23f32d2a5ec427c7c
|
NickLuGithub/school_homework
|
/Python/課堂練習/b10702057-課堂練習3-1-1.py
| 1,755
| 4.15625
| 4
|
print("第一題");
print(1 == True);
print(1 == False);
print();
print(0 == True);
print(0 == False);
print();
print(0.01 == True);
print(0.01 == False);
print();
print((1, 2) == True);
print((1, 2) == False);
print();
print((0, 0) == True);
print((0, 0) == False);
print();
print('string' == True);
print('string' == False);
print();
print('0' == True);
print('0' == False);
print();
print('' == True);
print('' == False);
print();
print([0, 0] == True);
print([0, 0] == False);
print();
print({0} == True);
print({0} == False);
print();
print({} == True);
print({} == False);
print();
print("第二題");
x = True;
y = False;
print(x == True);
print(x == False);
print();
print(y == True);
print(y == False);
print();
print(x and y == True);
print(x and y == False);
print();
print(x or y == True);
print(x or y == False);
print();
print(x + y== True);
print(x + y== False);
print();
print(x - y== True);
print(x - y== False);
print();
print(x * y== True);
print(x * y== False);
print();
print(y / x== True);
print(y / x == False);
print();
print("第三題");
inx = input("輸入X")
if inx == "True":
x = True
if inx == "False":
x = False
iny = input("輸入Y")
if iny == "True":
y = True
if iny == "False":
y = False
print(x == True);
print(x == False);
print();
print(y == True);
print(y == False);
print();
print(x and y == True);
print(x and y == False);
print();
print(x or y == True);
print(x or y == False);
print();
print(x + y== True);
print(x + y== False);
print();
print(x - y== True);
print(x - y== False);
print();
print(x * y== True);
print(x * y== False);
print();
print(y / x== True);
print(y / x == False);
print();
| false
|
d6aead41f21280a466324b5ec51c9c86a57c35e6
|
NickLuGithub/school_homework
|
/Python/課堂練習/b10702057-課堂練習7-1.py
| 802
| 4.15625
| 4
|
print("1")
list1 = [1,2,3,4]
a = [5, 6, 7, 8]
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
print("2")
list1 = [1,2,3,4]
a = 'test'
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
print("3")
list1 = [1,2,3,4]
a = ['a', 'b', 'c']
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
print("4")
list1 = [1,2,3,4]
a = '阿貓'
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
print("5")
list1 = [1,2,3,4]
a = ['阿貓', '阿狗']
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
print("6")
list1 = [1,2,3,4]
a = 0
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
| false
|
f8b8f879cccda263a09997fb5132ab52fa827e4a
|
liuduanyang/Python
|
/廖大python教程笔记/jichu.py
| 1,733
| 4.3125
| 4
|
# python编程基础
a = 100
if a >= 0:
print(a)
else:
print(-a)
# 当语句以冒号:结尾时,缩进的语句视为代码块(相当于{}内的语句)
# Python程序是大小写敏感的
# 数据类型和变量
'''
数据类型:整数
浮点数
字符串('' 或 ""括起来的文本)
"I'm OK"包含的字符是I,',m,空格,O,K这6个字符
'I\'m \"OK\"!' 表示的字符串内容是:I'm "OK"!
布尔值(在Python中,可以直接用True、False表示布尔值(请注意大小写),也可以通过布尔运算计算出来)
>>> True
True
>>> False
False
>>> 3 > 2
True
>>> 3 > 5
False
>>> True and True
True
>>> True and False
False
>>> False and False
False
>>> 5 > 3 and 3 > 1
True
>>> not True
False
>>> not False
True
>>> not 1 > 2
True
or 的就不写了
空值 空值是Python里一个特殊的值,用None表示
'''
# 转义字符\可以转义很多字符,比如\n表示换行,\t表示制表符,字符\本身也要转义,所以\\表示的字符就是\
# Python还允许用r''表示''内部的字符串默认不转义 >>> print(r'\\\t\\') 输出:\\\t\\
'''
>>> print('''line1
... line2
... line3''')
line1
line2
line3
'''
# 变量
#同一个变量可以反复赋值,而且可以是不同类型的变量
# 常量
# 常量就是不能变的变量,比如常用的数学常数π就是一个常量。在Python中,通常用全部大写的变量名表示常量:PI = 3.14159265359
# 其实常量也是变量,可以改变值
# 除法
# 用/得到的值是浮点数
# 用//得到的值是整数(只取结果的整数部分)
# 取余
10 % 3
#得 1
| false
|
ff6f55f92091a43f543d07553876fde61b780da8
|
liuduanyang/Python
|
/廖大python教程笔记/diedai.py
| 1,360
| 4.3125
| 4
|
# 迭代 (Iteration)
# 如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们称为迭代
# Python的for循环不仅可以用在list或tuple上,还可以作用在其他可迭代对象上 比如dict、字符串、
# 或者一些我们自定义的数据类型
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print(key)
# b
# a
# c
# 因为字典存储是无序的 所以每次得到的顺序可能会不同
# for key in d 迭代key-value的key
# for value in d.values() 迭代value
# for k, v in d.items() 迭代key-value
for value in d.values():
print(value)
for k, v in d.items():
print(k)
print(v)
# 对字符串进行迭代
for num in 'Liuduanyang':
print(num)
# 通过collections模块的Iterable类型判断一个对象是否是可迭代对象
from collections import Iterable
print(isinstance('abc', Iterable))
# True
print(isinstance([1,2,3], Iterable))
# True
print(isinstance(123, Iterable))
# False
# 可通过某个个例来判断该数据类型是否是可迭代对象
# 如果要对list实现类似Java那样的下标循环怎么办?Python内置的enumerate函数可以把一
# 个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身
for i, value in enumerate(['A', 'B', 'C']):
print(i, value)
# 0 A
# 1 B
# 2 C
| false
|
57cf0f1364b7d4d2c0c3f3b8a8c869be4f7a261a
|
liuduanyang/Python
|
/廖大python教程笔记/dict.py
| 2,204
| 4.28125
| 4
|
# 字典
# Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)
# 存储,具有极快的查找速度。这种查找速度都非常快,不会随着字典大小的增加而变慢
d={'Michael':95,'Bob':75,'Tracy':85}
print(d['Michael'])
# 95
# 除了上述初始化方法外,还可以通过key来放入数据
d['Adam']=67
print(d['Adam'])
print(d)
# 67
# {'Adam': 67, 'Michael': 95, 'Bob': 75, 'Tracy': 85}
# 一个key只能对应一个value,所以,多次对一个key放入value,后面的值会把前面的值冲掉
d['Adam']=67
d['Adam']=99
print(d['Adam'])
# 99
# 通过in判断key是否存在
print('Tracy' in d)
# True
# 通过dict提供的get方法,如果key不存在,可以返回None,或者自己指定的value
print(d.get('Bob'))
# 75
print(d.get('Mary'))
# None
# 返回None的时候Python的交互式命令行不显示结果
print(d.get('Mary',0))
# 0
# Mary不在时返回0 如果不指定0 则返回None且在交互命令行不显示
# 删除一个key,用pop(key)方法,对应的value也会从dict中删除
d.pop('Bob')
print(d)
#{'Michael': 95, 'Tracy': 85, 'Adam': 99}
# dict内部存放的顺序和key放入的顺序是没有关系的
'''
和list比较,dict有以下几个特点:
查找和插入的速度极快,不会随着key的增加而变慢;
需要占用大量的内存,内存浪费多。
而list相反:
查找和插入的时间随着元素的增加而增加;
占用空间小,浪费内存很少。
所以,dict是用空间来换取时间的一种方法。
dict可以用在需要高速查找的很多地方,在Python代码中几乎无处不在,正确使用dict非常重要,需要牢记的
第一条就是dict的key必须是不可变对象。
这是因为dict根据key来计算value的存储位置,如果每次计算相同的key得出的结果不同,那dict内部就完全混
乱了。这个通过key计算位置的算法称为哈希算法(Hash)。
要保证hash的正确性,作为key的对象就不能变。在Python中,字符串、整数等都是不可变的,因此,可以放心
地作为key。而list是可变的,就不能作为key
'''
| false
|
9a915e306d84c786fd2290dc3180535c5773cafb
|
schase15/cs-module-project-iterative-sorting
|
/src/searching/searching.py
| 1,967
| 4.375
| 4
|
# Linear and Binary Search assignment
def linear_search(arr, target):
# Go through each value starting at the front
# Check to see if it is equal to the target
# Return index value if it is
# Return -1 if not found in the array`
for i in range(len(arr)):
if arr[i] == target:
return i
return -1 # not found
# Write an iterative implementation of Binary Search
# If the target is in the array, return the index value
# If the target is not in the array, return -1
def binary_search(arr, target):
# Set first and last index values
first = 0
last = len(arr) -1
# What is our looping criteria? What tells us to stop looping
# If we see that the index position has gone past the end of the list we stop
# If the value from the array is equal to the target, we stop
while first <= last:
# Compare the target element to the midpoint of the array
# Calculate the index of the midpoint
mid = (first + last) //2 # The double slash rounds down
# If the midpoint element matches our target, return the midpoint index
if target == arr[mid]:
return mid
# If the midpoint value is not equal to the target, decide to go higher or lower
if target < arr[mid]:
# If target is less than the midpoint, toss all values greater than the midpoint
# Do this by moving the search boundary high point down to one below the midpoint
last = mid -1
if target > arr[mid]:
# If target is greater than the midpoint, toss all values less than the midpoint
# Move the search boundary low point up to one above the midpoint
first = mid + 1
# Repeat this loop unitl the end of the array has been reached
# When the mid index has surpassed the length of the list
# If target is not found in the list, return -1
return -1
| true
|
227bfbed621544f32bbddd18299c8fd0ea29fe0a
|
daisy-carolin/pyquiz
|
/python_test.py
| 989
| 4.125
| 4
|
x = [100,110,120,130,140,150]
multiplied_list=[element*5 for element in x]
print(multiplied_list)
def divisible_by_three():
x=range(10,100)
for y in x:
if y%3==0:
print(y)
x = [[1,2],[3,4],[5,6]],
flat_list = []
for sublist in x:
for num in sublist:
flat_list.append(num)
print(flat_list)
def smallest():
list1=[2,7,3,9,10]
list1.sort()
print("Smallest element is:",(list1))
def mylist():
x = ['a','b','a','e','d','b','c','e','f','g','h']
mylist = list(dict.fromkeys(mylist))
print(mylist)
def divisible_by_seven():
x=range(100,200)
for y in x:
if y%7==0:
print(y)
def Students():
year_of_birth=2021-"age"
for student in Students:
[{"age": 19, "name": "Eunice"},
{"age": 21, "name": "Agnes"},
{"age": 18, "name": "Teresa"},
{"age": 22, "name": "Asha"} ]
print("Hello {} you were born in year {}".format("name","year"))
| false
|
996da01a75f050ffcdb755c5c5f2b16fb1ec8f1c
|
Shmuco/PY4E
|
/PY4E/ex_05_02/ex_05_02.py
| 839
| 4.15625
| 4
|
##### 5.2 Write a program that repeatedly prompts a user for integer numbers until
#the user enters 'done'. Once 'done' is entered, print out the largest and
#smallest of the numbers. If the user enters anything other than a valid number
#catch it with a try/except and put out an appropriate message and ignore the
#number. Enter 7, 2, bob, 10, and 4 and match the output below.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
fnum =float(num)
except:
print ("Invalid input")
continue
if largest is None:
largest = fnum
elif fnum > largest:
largest = fnum
if smallest is None:
smallest = fnum
elif smallest > fnum:
smallest = fnum
print("Maximum", largest, "Minumum", smallest)
| true
|
48f85e68fcdd06ca468437c536ac7e27fd20ef77
|
endreujhelyi/zerda-exam-python
|
/first.py
| 431
| 4.28125
| 4
|
# Create a function that takes a list as a parameter,
# and returns a new list with every second element from the original list.
# It should raise an error if the parameter is not a list.
# Example: with the input [1, 2, 3, 4, 5] it should return [2, 4].
def even_elements(input_list):
if type(input_list) == list:
return [input_list[i] for i in range(len(input_list)) if i % 2 == 1]
else:
raise TypeError
| true
|
8fe7e9ee5da57e056d279168bc8c34789779109a
|
cainiaosun/study
|
/测试/UI自动化/测试工具__Selenium/selenium/Phy/class.py
| 1,134
| 4.3125
| 4
|
class Person:
'''Represents a person.'''
population = 0
def __init__(self,name,age):
'''Initializes the person's data.'''
self.name = name
self.age = age
print '(Initializing %s)' % self.name
# When this person is created, he/she
# adds to the population
Person.population += 1
def __del__(self):
'''I am dying.'''
print '%s says bye.' % self.name
Person.population -= 1
if Person.population == 0:
print 'I am the last one.'
else:
print 'There are still %d people left.' %Person.population
def sayhi(self):
print "Hi,my name is %s %s"% (self.name,self.age)
def howMany(self):
'''Prints the current population.'''
if Person.population == 1:
print 'I am the only person here.'
else:
print 'We have %d persons here.' %Person.population
print Person.population
test1=Person("sunhongbin","28")
test1.sayhi()
test1.howMany()
test2=Person("lihua","30")
test2.sayhi()
test2.howMany()
test1.sayhi()
test1.howMany()
del test1
del test2
| false
|
40eb347ec2a99811529a9af3aa536a16618d0ad3
|
DoranLyong/CSE-python-tutorial
|
/Coding-Test/CodeUp/Python/036_number.py
| 345
| 4.375
| 4
|
"""
[ref] https://codeup.kr/problem.php?id=1036
Question:
1. take one English letter
2. print it out as the decimal value of the ASCII code table.
"""
letter = input()
print(ord(letter))
"""
Program to find the ASCII value of a character:
https://beginnersbook.com/2019/03/python-program-to-find-ascii-value-of-a-character/
"""
| true
|
58dce475f4c94e14c6d58a4ee3c1836e34c82f21
|
DoranLyong/CSE-python-tutorial
|
/Coding-Test/CodeUp/Python/037_number.py
| 319
| 4.125
| 4
|
"""
[ref] https://codeup.kr/problem.php?id=1037
Question:
1. take one decimal ineger
2. print it out in ASCII characters
"""
num = int(input())
print(chr(num))
"""
Program to find the ASCII value of a character:
https://beginnersbook.com/2019/03/python-program-to-find-ascii-value-of-a-character/
"""
| true
|
173631da2b89f158a22cde74defe44465acce1b6
|
wuhuabushijie/sample
|
/chapter04/4_1.py
| 488
| 4.125
| 4
|
'''鸭子类型,多态'''
class Cat:
def say(self):
print("I am a cat")
class Dog:
def say(self):
print("I am a dog")
def __getitem__(self):
return "bob8"
class Duck:
def say(self):
print("I am a duck")
animal_list = [Cat,Dog,Duck]
for animal in animal_list:
animal().say()
a = ["bob1","bob2"]
b = ["bob2","bob3"]
name_tuple=("bob4","bob5")
name_set=set()
name_set.add("bob6")
name_set.add("bob7")
a.extend(name_tuple)
print(a)
| false
|
4fcabbe7be3110a9ee278b5321eaa30319c9d7a7
|
pri-nitta/firstProject
|
/CAP3/calorias.py
| 1,093
| 4.21875
| 4
|
#1 – O projeto HealthTrack está tomando forma e podemos pensar em algoritmos que possam ser reaproveitados
# quando estivermos implementando o front e o back do nosso sistema.
# Uma das funções mais procuradas por usuários de aplicativos de saúde é o de controle de calorias ingeridas em um dia.
# Por essa razão, você deve elaborar um algoritmo implementado em Python em que o usuário informe quantos
# alimentos consumiu naquele dia e depois possa informar o número de calorias de cada um dos alimentos.
# Como não estudamos listas nesse capítulo você não deve se preocupar em armazenar todas as calorias digitadas,
# mas deve exibir o total de calorias no final.
alimentos = int(input("Digite quantos alimentos você consumiu hoje: "))
i = 1
total = int(0)
print("==============================================")
while i <= alimentos:
calorias = int(input(f"Digite a quantidade de calorias do {i}º alimento: "))
i = i + 1
total = calorias + total
print("==============================================")
print(f"O total de calorias ingerido hoje é: {total}")
| false
|
ae78936d1135929125080769c5fc815465e57728
|
ALcot/-Python_6.26
|
/script.py
| 351
| 4.1875
| 4
|
fruits = ['apple', 'banana', 'orange']
# リストの末尾に文字列「 grape 」を追加
fruits.append('grape')
# 変数 fruits に代入したリストを出力
print(fruits)
# インデックス番号が 0 の要素を文字列「 cherry 」に更新
fruits[0] = 'cherry'
# インデックス番号が 0 の要素を出力
print(fruits[0])
| false
|
3442780fcf656417aa119190f13137e61db8d005
|
jamessandy/Pycon-Ng-Refactoring-
|
/refcator.py
| 527
| 4.21875
| 4
|
#Example 1
num1 = 4
num2 = 4
result = num1 + num2
print(result)
#Example 2
num1 = int(input('enter the firExamst number:'))
num2 = int(input('enter the second number:'))
result = num1 + num2
print('your answer is:', result)
#Example 3
num1 = int(input('Enter number 1:'))
num2 = int(input('Enter number 2:'))
result = num1 + num2
print(result)
#Example 4
def add (x, y):
return x + y
num1 = int(input('Enter number 1:'))
num2 = int(input('Enter number 2:'))
result = add(num1, num2)
print('your answer is:', result)
| true
|
4d9729e57e5e19855bd13b71df3b21ed4d00d98b
|
Tuhgtuhgtuhg/PythonLabs
|
/lab01/Task_1.py
| 651
| 4.21875
| 4
|
from math import sqrt
while True:
m = input("Введіть число \"m\" для обчислення формули z=sqrt((m+3)/(m-3)): ")
if ( m.isdigit()):
m = float(m)
if (m<=-3 or m > 3):
break
else:
print("""Нажаль число "m" повинно лежати у такому проміжку: m ∈ (-∞;-3]U(3;∞) !!!
Спробуйте ще раз!""")
else:
print("""Нажаль введена інформація не є числом!\nСпробуйте ще раз!""")
z = sqrt((m+3)/(m-3))
if (z == -0.0 or z == 0.0 ):
z = 0
print( "z = " + str(z))
| false
|
e130159211e4dc6092a9943fa6a1c9422d058f68
|
mclark116/techdegree-project
|
/guessing_game2.py
| 2,321
| 4.125
| 4
|
import random
history = []
def welcome():
print(
"""
____________________________________
Welcome to the Number Guessing Game!
____________________________________
""")
def start_game():
another = "y"
solution = random.randint(1,10)
value = "Oh no! That's not a valid value. Please chose a number between 1 and 10."
attempt = 0
while another == "y":
try:
prompt = int(input("Pick a number between 1 and 10: "))
except ValueError:
print(value)
else:
if prompt > solution:
if prompt > 10:
print(value)
else:
print("It's lower!")
attempt +=1
elif prompt < solution:
if prompt < 1:
print(value)
else:
print("It's higher!")
attempt +=1
elif prompt == solution:
attempt +=1
if attempt == 1:
print("\nGot it! It took you {} try!".format(attempt))
else:
print("\nGot it! It took you {} tries!".format(attempt))
print("Game Over!")
history.append(attempt)
solution = random.randint(1,10)
attempt = 0
another = input("Would you like to play again? y/n ")
if another.lower()=="y":
print("\nHigh Score: {}".format(min(history)))
elif another.lower()!="y":
if another.lower()=="n":
print("\nGame Over! Thanks for playing.")
break
else:
while another.lower !="y" or "n":
print("Please choose y or n")
another = input("Would you like to play again? y/n ")
if another.lower()=="y":
print("\nHigh Score: {}".format(min(history)))
break
elif another.lower()!="y":
if another.lower()=="n":
break
welcome()
start_game()
| true
|
cf7554340e039e9c317243a1aae5e5f9e52810f9
|
IraPara08/raspberrypi
|
/meghapalindrom.py
| 412
| 4.3125
| 4
|
#Ask user for word
wordinput = input("Please Type In A Word: ")
#Define reverse palindrome
reverseword = ''
#For loop
for x in range(len(wordinput)-1, -1, -1):
reverseword = reverseword + wordinput[x]
#Print reverse word
print(reverseword)
#Compare
if wordinput == reverseword:
print("This is a palindrome!")
else:
print("This is not a palindrome:(")
#TA-DA
print("Ta-Da!")
| true
|
fed78ccbb8a565e936cacbac817485c26ab84383
|
domlockett/pythoncourse2018
|
/day03/exercise03_dl.py
| 458
| 4.28125
| 4
|
## Write a function that counts how many vowels are in a word
## Raise a TypeError with an informative message if 'word' is passed as an integer
## When done, run the test file in the terminal and see your results.
def count_vowels(word):
vowels=('a','e','i','o','u')
count= 0
for i in word:
if type(word)!=str:
raise TypeError, "Make sure your input is a string."
if i in vowels:
count+=1
return count
| true
|
2074006981e41d2e7f0db760986ea31f6173d181
|
ladas74/pyneng-ver2
|
/exercises/06_control_structures/task_6_2a.py
| 1,282
| 4.40625
| 4
|
# -*- coding: utf-8 -*-
"""
Task 6.2a
Make a copy of the code from the task 6.2.
Add verification of the entered IP address.
An IP address is considered correct if it:
- consists of 4 numbers (not letters or other symbols)
- numbers are separated by a dot
- every number in the range from 0 to 255
If the IP address is incorrect, print the message: 'Invalid IP address'
The message "Invalid IP address" should be printed only once,
even if several points above are not met.
Restriction: All tasks must be done using the topics covered in this and previous chapters.
"""
ip = input('Введите IP адрес: ')
#ip = '10.1.16.50'
ip_list = ip.split('.')
correct_ip = False
if len(ip_list) == 4:
for oct in ip_list:
if oct.isdigit() and 0 <= int(oct) <= 255: #in range(256) вместо 0 <= int(oct) <= 255
correct_ip = True
else:
correct_ip = False
break
if correct_ip:
oct1 = ip_list[0]
if 1 <= int(oct1) <= 223:
print("unicast")
elif 224 <= int(oct1) <= 239:
print("multicast")
elif ip == '255.255.255.255':
print("local broadcast")
elif ip == '0.0.0.0':
print("unassigned")
else:
print("unused")
else:
print('Invalid IP address')
| true
|
27cc3bbaffff82dfb22f83be1bcbd163ff4c77f1
|
ladas74/pyneng-ver2
|
/exercises/05_basic_scripts/task_5_1.py
| 1,340
| 4.3125
| 4
|
# -*- coding: utf-8 -*-
"""
Task 5.1
The task contains a dictionary with information about different devices.
In the task you need: ask the user to enter the device name (r1, r2 or sw1).
Print information about the corresponding device to standard output
(information will be in the form of a dictionary).
An example of script execution:
$ python task_5_1.py
Enter device name: r1
{'location': '21 New Globe Walk', 'vendor': 'Cisco', 'model': '4451', 'ios': '15.4', 'ip': '10.255.0.1'}
Restriction: You cannot modify the london_co dictionary.
All tasks must be completed using only the topics covered. That is, this task can be
solved without using the if condition.
"""
name_switch = input('Введите имя устройства: ')
london_co = {
"r1": {
"location": "21 New Globe Walk",
"vendor": "Cisco",
"model": "4451",
"ios": "15.4",
"ip": "10.255.0.1",
},
"r2": {
"location": "21 New Globe Walk",
"vendor": "Cisco",
"model": "4451",
"ios": "15.4",
"ip": "10.255.0.2",
},
"sw1": {
"location": "21 New Globe Walk",
"vendor": "Cisco",
"model": "3850",
"ios": "3.6.XE",
"ip": "10.255.0.101",
"vlans": "10,20,30",
"routing": True,
},
}
print(london_co[name_switch])
| true
|
70e15b366634efea90e939c6c169181510818fdb
|
Sushantghorpade72/100-days-of-coding-with-python
|
/Day-03/Day3.4_PizzaOrderCalculator.py
| 881
| 4.15625
| 4
|
'''
Project Name: Pizza Order
Author: Sushant
Tasks:
1. Ask customer for size of pizza
2. Do they want to add pepperoni?
3. Do they want extra cheese?
Given data:
Small piza: $15
Medium pizza: $20
Large pizza: $ 25
Pepperoni for Small Pizza: +$2
Pepperoni for medium & large pizza: +$3
Extra cheese for any size pizza: +$1
'''
print("Welcome to python pizza deliveries!!!")
size = input("What size pizza do you want? S,M or L? ")
add_pep = input("Do you want pepperoni? Y or N: ")
extra_cheese = input("Do you want extra cheese? Y or N: ")
#Price size wise:
bill = 0
if size == "S":
bill += 15
elif size == "M":
bill += 20
else:
bill += 25
if add_pep == "Y":
if size == "S":
bill += 2
else:
bill += 3
if extra_cheese == "Y":
bill += 1
print(f"Your final bill is ${bill}")
| true
|
0d5f545e7bacef8184a4224ad8e9816989ab6e2e
|
Long0Amateur/Self-learnPython
|
/Chapter 2 Loops/Chapter 2 (loops).py
| 633
| 4.46875
| 4
|
# Example 1
for i in range(5):
print('i')
print(sep='')
#Example 2
print('A')
print('B')
for i in range (5):
print('C')
print('D')
print('E')
print(sep='')
#Example 3
print('A')
print('B')
for i in range (5):
print('C')
for i in range (5):
print('D')
print('E')
print(sep='')
#Example 4
for i in range(3):
print(i+1,'--Hello')
print(sep='')
#Example 5
for i in range(5,0,-1):
print(i, end='')
print('Blast off!!!')
print(sep='')
#Example 6
for i in range(4):
print('*'*6)
print(sep='')
#Example 7
for i in range(4):
print('*'*(i+1))
| false
|
9b4a03cec322c2c28438a0c1df52d36f1dfce769
|
Long0Amateur/Self-learnPython
|
/Chapter 5 Miscellaneous/swapping.py
| 297
| 4.21875
| 4
|
# A program swaps the values of 3 variables
# x gets value of y, y gets value of z, and z gets value of x
x = 1
y = 2
z = 3
hold = x
x = y
y = hold
hold = y
y = z
z = hold
hold = z
z = x
z = hold
print('Value of x =',x)
print('Value of y =',y)
print('Value of z =',z)
| true
|
0e41bd56ce0c6b4761aa3bf3f86b181ea7b70697
|
Tuman1/Web-Lessons
|
/Python Tutorial_String Formatting.py
| 1,874
| 4.28125
| 4
|
# Python Tutorial: String Formatting - Advanced Operations for Dicts, Lists, Numbers, and Dates
person = {'name':'Jenn', 'age': 23}
# WRONG example
# Sentence = 'My name is ' + person['name'] + ' and i am ' + str(person['age']) + ' years old.'
# print(Sentence)
# Sentence = 'My name is {} and i am {} years old.'.format(person['name'], person['age'])
# print(Sentence)
# Sentence = 'My name is {1} and i am {0} years old.'.format(person['name'], person['age'])
# print(Sentence)
# tag = "h1"
# text = "This is a headline"
#
# Sentence = '<{0}><{1}></{0}>'.format(tag, text)
# print(Sentence)
# Sentence = 'My name is {1[name]} and i am {0[age]} years old.'.format(person, person)
# print(Sentence)
# class Person():
# def __init__(self, name, age):
# self.name = name
# self.age = age
#
# p1 = Person('Jack', '33')
#
# Sentence = 'My name is {0.name} and i am {0.age} years old.'.format(p1)
# print(Sentence)
# Sentence = 'My name is {name} and i am {age} years old.'.format(name = "Garold", age = "33")
# print(Sentence)
#One of the most convinient way to print dictionary
# Sentence = 'My name is {name} and i am {age} years old.'.format(**person)
# print(Sentence)
#Formatting number
# for x in range(1, 11):
# sentence = "The value is {:03}".format(x)
# print(sentence)
# pi = 3.14159265
#
# sentence = 'Pi is equal to {:.2f}'.format(pi)
# print(sentence)
# sentence = '1 Mb is equal to {:,.2f} bytes'.format(1000**2)
# print(sentence)
import datetime
my_date = datetime.datetime(2016,9,24,12,30,45)
# print(my_date)
# Example what we need -> March 01 2016
# sentence = '{:%B %d, %Y}'.format(my_date)
# print(sentence)
# Example what we need -> March 01, 2016 fell on a Tuesday and was the 061 day of the year.
sentence = '{0:%B %d, %Y} fell on a {0:%A} and was the {0:%j} day of the year.'.format(my_date)
print(sentence)
| false
|
280d6a67ced86fdb7c8f4004bb891ee7087ad18c
|
Ngyg520/python--class
|
/正课第二周/7-30/(重点理解)self对象.py
| 1,556
| 4.21875
| 4
|
"""
座右铭:路漫漫其修远兮,吾将上下而求索
@project:正课第二周
@author:Mr.Yang
@file:self对象.PY
@ide:PyCharm
@time:2018-07-30 14:04:03
"""
class Student(object):
def __init__(self,name,age):
self.name=name
self.age=age
# print('self=',self)
def show(self):
print('调用了show函数')
# print('self=',self)
#self其实本身指代的就是一个对象,这个对象是Student类类型的,self具体指代的是Student哪一个对象,是由Student中的哪一个对象在使用属性或者函数(方法)来决定的
print(Student('张三','20'))
#对象调用中间不能有其他语句,要不每调用一次,就是重新声明,重新声明就是重新分配内存地址
stu =Student('张三','20')
stu.show()
stu_1=stu
print(stu)
print(stu_1)
# stu.show()
stu_one=Student('李四','22')
# stu_one.show()
#对象的内存具有唯一性,两个不同的对象内存是不一样的
#stu和Student('张三','20')之间的关系:
#第一步:当Student('张三','20')执行完毕的时候,实际上已经实例化出来了一个对象,与此同时对象在内存当中已经产生
#第二步:将内存中已经产生的这个对象赋值给了stu这个变量(指针),使用这个变量(指针)来代替Student('张三','20')这个对象来执行函数的调用,属性的调用
#指针是用于指向一个对象的内存地址,方便去操作对象,管理对象.
#一个对象的内存地址可以由多个指针进行指向,但是一个指针只能指向一个对象的内存地址.
| false
|
23b0fbe3cba25c9ef37ddbad2bb345086e63e6be
|
Ngyg520/python--class
|
/正课第二周/7-31/对象属性的保护.py
| 2,251
| 4.21875
| 4
|
"""
座右铭:路漫漫其修远兮,吾将上下而求索
@project:正课第二周
@author:Mr.Yang
@file:对象属性的保护.PY
@ide:PyCharm
@time:2018-07-31 09:26:31
"""
#如果有一个对象,当需要对其属性进行修改的时候,有两种方法:
#1.对象名.属性名=属性值------------------>直接修改(不安全)
#2.对象名.方法名( )--------------------->间接修改
#为了更好的保护属性的安全,也就是不让属性被随意的修改,一般的处理方式:
#1,将属性定义为私有属性
#2.添加一个可以调用的方法(函数),通过调用方法来修改属性(还可以在方法中设置一些属性的条件)
class People(object):
#私有属性
def __init__(self,name,age,weight):
#python设置私有属性,需要在属性前加两个_
self.__name=name
self.__age=age
self._weight=weight
#由于私有属性只能在类的内部使用,想要在外部获取私有属性的值,可以通过定义函数来完成
def get_name(self):
return self.__name
#添加修改属性
def set_name(self,name):
if isinstance(name,str):#(属性,限制)
self.__name=name
else:
raise ValueError('name is not"str"type!')
p1=People('张三','20','180')
name=p1.get_name()
print(name)#打印出私有属性
# print(p1.__name)#私有属性无法直接调用
p1.set_name('李四')
print(p1.get_name())#对私有属性进行修改,并且要满足限制"str"
#一般也将_weight这种视为私有属性,不会再类的外部进行访问
print(p1._weight)
#面试题:
#python单_和双_的区别?
#1.__方法名__:内建方法,用户不能这样定义.例如:__init__
#2.__变量名(属性名):全私有属性(变量)/全保护属性(变量).只有类对象自己能访问,子类并不能访问这个属性
#3._变量名(属性名):半保护属性(变量),只有类对象和子类对象能访问到这些变量
#虽然从意义上讲单下划线和双下划线的变量(属性)都属于私有变量(属性),理论上外界不能访问的,但是Python并没有那么严格,仍然是可以强制访问的,因此python的私有仅仅是意义上的私有,只是种规范,可以不遵守
print('强制访问:',p1._People__name)
| false
|
a62a4f8dfa911c1f3bde259e14efe019c5b7ddc1
|
Ngyg520/python--class
|
/预科/7-23/生成器函数.py
| 1,580
| 4.125
| 4
|
"""
座右铭:路漫漫其修远兮,吾将上下而求索
@project:预科
@author:Mr.Yang
@file:生成器函数.PY
@ide:PyCharm
@time:2018-07-23 14:34:00
"""
#生成器函数:当一个函数带有yieid关键字的时候,那么他将不再是一个普通的函数,而是一个生成器generator
#yieid和return;这俩个关键字十分的相似,yieid每次只返回一个值,而return则会把最终的结果一次返回
#每当代码执行到yieid的时候就会直接将yieid后面的值返回出,下一次迭代的时候,会从上一次遇到yieid之后的代码开始执行
def test():
list1=[]
for x in range (1,10):
list1.append(x)
return list1
res=test()
print(res)
def test_1():
for x in range (1,10):
yield x
generator=test_1()
print(generator)
print(next(generator))
print(next(generator))
print(next(generator))
#生成器函数的例子:母鸡下蛋
#1,一次性把所有的鸡蛋全部下下来.
#如果一次把所有的鸡蛋全部下下来,一是十分占地方,而是容易坏掉.
def chicken_lay_eggs():
#鸡蛋筐列表
basket=[]
for egg in range (1,101):
basket.append(egg)
return basket
eggs =chicken_lay_eggs()
print('一筐鸡蛋:',eggs)
#这样做的好处:第一是省地方,第二是下一个吃一个,不会坏掉
def chicken_lay_eggs_1():
for egg in range(1,101):
print('战斗母鸡正在下第{}个蛋'.format(egg))
yield egg
print('我把第{}个蛋给吃了!'.format(egg))
eggs_1=chicken_lay_eggs_1()
print(next(eggs_1))
print(next(eggs_1))
print(next(eggs_1))
| false
|
c4c6d1dfddde4594f435a910147ee36b107e87b9
|
Pakizer/PragmatechFoundationProject
|
/tasks/7.py
| 303
| 4.15625
| 4
|
link[https://www.hackerrank.com/challenges/py-if-else/problem]
n = input('Bir eded daxil edin :')
n=int(n)
if n%2==0 and n>0:
if n in range(2,5):
print('Not Weird')
if n in range(6,20):
print ('Weird')
else:
print('Not Weird')
else:
print('Weird')
| false
|
edfd81e4cbd96b77f1666534f7532b0886f8ec4e
|
himashugit/python_dsa
|
/func_with_Arg_returnvalues.py
| 617
| 4.15625
| 4
|
'''
def addition(a,b):
result = a+b
return result # this value we're sending back to main func to print
def main():
a = eval(input("Enter your number: "))
b = eval(input("Enter your 2ndnumber: "))
result = addition(a,b) # calling addition func & argument value and storing in result
print(f' "the addition of {a} and {b} is {result}"')
main() # calling main func
'''
def multiply_num_10(value):
#result = value*10
#return result
return value*10
def main():
num=eval(input("Enter a number:"))
result=multiply_num_10(num)
print("The value is: ", result)
main()
| true
|
c9361ac9212e8bd0441b05a26940729dd6915861
|
itsMagondu/python-snippets
|
/fib.py
| 921
| 4.21875
| 4
|
#This checks if a certain number num is a number in the fibbonacci sequence.
#It loops till the number is the sequence is either greater or equal to the number in the sequence.
#Thus we validate if the number is in the fibonacci sequence.
import sys
tot = sys.stdin.readline().strip()
try:
tot = int(tot)
except ValueError:
pass
def fibTest(f0,f1,f,num):
f0 = f1
f1 = f
f = f0+f1
if int(f) < int(num):
f0,f1,f,num = fibTest(f0,f1,f,num)
else:
if f == int(num):
print "IsFibo"
else:
print "IsNotFibo"
return f0,f1,f,num
def getFibnumber(f0,f1):
return f0+f1
while tot:
num = sys.stdin.readline().strip()
f0 = 0
f1 = 1
f = getFibnumber(f0,f1)
try:
num = int(num)
if num != 0 or num != 1:
fibTest(f0,f1,f,num)
tot -= 1
except ValueError:
pass
| true
|
5ebb8cf419dd497c64b1d7ac3b22980f0c33b790
|
sberk97/PythonCourse
|
/Week 2 - Mini Project Guess number game.py
| 2,289
| 4.21875
| 4
|
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import random
import simplegui
# helper function to start and restart the game
def new_game():
# initialize global variables used in your code here
global secret_number
global times
times = 7
print "You have 7 guesses"
secret_number=random.randrange(0,99)
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
global secret_number
global times
times = 7
print "You have 7 guesses"
secret_number=random.randrange(0,99)
print "Restarting the game, range now is[0,100)"
def range1000():
# button that changes the range to [0,1000) and starts a new game
global secret_number
global times
times = 10
print "You have 10 guesses"
secret_number=random.randrange(0,999)
print "Restarting the game, range now is[0,1000)"
def input_guess(guess):
# main game logic goes here
guess=int(guess)
print "Guess was %s" % (guess)
if guess==secret_number:
print "Correct"
new_game()
elif guess > secret_number:
print "Lower"
global times
if times > 0:
times -= 1
print "You have %s guesses left" % (times)
else:
print "You are out of guesses, the secret number was %s, new game begins" % (secret_number)
new_game()
elif guess < secret_number:
print "Higher"
if times > 0:
times -= 1
print "You have %s guesses left" % (times)
else:
print "You are out of guesses, the secret number was %s, new game begins" % (secret_number)
new_game()
else:
print "Error"
# create frame
frame=simplegui.create_frame("Guess game", 300, 300)
input=frame.add_input("Input", input_guess, 50)
# register event handlers for control elements and start frame
button1=frame.add_button("Range is [0,100)", range100, 100)
button2=frame.add_button("Range is [0,1000)", range1000, 100)
frame.start()
# call new_game
new_game()
# always remember to check your completed program against the grading rubric
| true
|
8d82910e342182c0c6856ffe129bb94ad3391c39
|
Evgeniy-code/python
|
/prob/calculator.py
| 521
| 4.3125
| 4
|
#!/usr/bin/env python3
a = float(input("введите первое число:"))
what = input("что делаем (+:-:*:/):")
b = float(input("введите второе число:"))
if what == "+":
d = a + b
print("равно:" + str(d))
elif what == "-":
d = a - b
print("равно:" + str(d))
elif what == "*":
d = a * b
print("равно:" + str(d))
elif what == "/":
d = a / b
print("равно:" + str(d))
else:
print("введено неверное значение")
| false
|
5c4362ae8eea49bd105ae1f0ffced5d62aba12ed
|
ArnoldKevinDesouza/258327_Daily_Commits
|
/Dict_Unsolved02.py
| 209
| 4.5
| 4
|
# Write a Python program to convert a list into a nested dictionary of keys
list = [1, 2, 3, 4]
dictionary = current = {}
for name in list:
current[name] = {}
current = current[name]
print(dictionary)
| true
|
3963dccc95056b06715cf81c7a8eab7091c682a5
|
ArnoldKevinDesouza/258327_Daily_Commits
|
/If_Else_Unsolved04.py
| 314
| 4.15625
| 4
|
# Write a program to get next day of a given date
from datetime import date, timedelta
import calendar
year=int(input("Year:"))
month=int(input("\nMonth:"))
day=int(input("\nDay:"))
try:
date = date(year, month, day)
except:
print("\nPlease Enter a Valid Date\n")
date += timedelta(days=1)
print(date)
| true
|
dd652b879fd1162d85c7e3454f8b724e577f5e7e
|
Einsamax/Dice-Roller-V2
|
/main.py
| 2,447
| 4.375
| 4
|
from time import sleep
import random
#Introduce user to the program
if __name__ == "__main__": #This does a good thing
print ("*" * 32)
print("Welcome to the Dice Roller!".center(32))
print ("*" * 32)
print()
sleep(1)
def roll_dice(diceamnt, diceint): #Defines function roll_dice
dicetotal = 0 #Reset dicetotal
for i in range(diceamnt): #Repeat for desired amount of dice rolled
diceroll = random.randint(1, diceint) #Roll based on type of dice selected
print(diceroll) #Print each roll as they are rolled
sleep(1)
dicetotal = dicetotal + diceroll #Add each dice roll to the total
return dicetotal
rolling=True
while rolling: #Repeats the loop upon each roll unless exited by user
choosing = True
while choosing:
#Prompt user to chose their dice type
print("*" * 32)
print("Which type of dice would you like to roll?")
sleep(1)
print("You may select from D2, D3, D4, D6, D8, D10, D12, D20, and D100!")
sleep(1)
print("You may also type 'exit' to leave the program.")
dicetype = str(input()) # User enters the type of dice they wish to roll
if dicetype == "exit": #User wishes to exit the program
sleep(1)
print("Thank you for rolling your luck!")
sleep(2)
rolling = False # exits the while loop
elif dicetype == "D2" or dicetype == "D3" or dicetype == "D4" or dicetype == "D6" or dicetype == "D8" or dicetype == "D10" or dicetype == "D12" or dicetype == "D20" or dicetype == "D100":
diceint = int(dicetype[1:]) #Extracts the dicetype as an integer
choosing = False
else:
print("Uh oh! It looks like you entered an invalid dice type!")
sleep(1)
#exit() #Exits the program because exiting the loop wasn't working lmao
sleep(1)
print("How many", dicetype, "would you like to roll?")
diceamnt = int(input()) # User enters number of dice to roll
sleep(1)
dicetotal = roll_dice(diceamnt, diceint) #Set the returned value to dicetotal
print("You rolled a total of", dicetotal, "!") #Print the total in a clear statement
sleep(2)
| true
|
c6aadc50833356e4ce23f7f2a898634ff3efd4a7
|
dsimonjones/MIT6.00.1x---Introduction-to-Computer-Science-and-Programming-using-Python
|
/Week2- Simple Programs/Lecture4- Functions/Function isIn (Chap 4.1.1).py
| 611
| 4.1875
| 4
|
# -*- coding: utf-8 -*-
"""
@author: ali_shehzad
"""
"""
Finger exercise 11: Write a function isIn that accepts two strings as
arguments and returns True if either string occurs anywhere in the other,
and False otherwise. Hint: you might want to use the built-in str
operation in.
"""
def isIn(str1, str2):
if len(str1) > len(str2): #We're comparing which string is longer and then checking to see
if str2 in str1: #if the shorter string is present in the longer string
return True
else:
if str1 in str2:
return True
return False
| true
|
3bc103df43f3b4e607efa104b1e3a5a62caa1469
|
LaurenShepheard/VsCode
|
/Learningpython.py
| 1,227
| 4.375
| 4
|
for i in range(2):
print("hello world")
# I just learnt how to comment by putting the hash key at the start of a line. Also if I put a backslash after a command you can put the command on the next line.
print\
("""This is a long code,
it spreads over multiple lines,
because of the triple quotaions and brackets""")
# A string is a sequence of one or more characters surrounded by quotes ' "", like above. It's data type is str.
print('This is a String but if you are using numbers the data type is int and called integer')
b = 100
print(b)
print(2+2)
# Numbers with a decimal are called a float and act like ints. True and false are bool data type called booleans.
print(2/2)
print("The number above is a constant as its value does not change whereas the b is a variable as I assigned it a value using the assignment operator =, doing this you can do math")
a = 50
y = a + b
print(y)
a = a + 1
# The above is an example of incrementing a variable, you can decrement it by using - as well. You can also skip putting the a like below.
a += 1
y = a + b
print(y)
print("Now the number changes because I incremented the variable.")
Nick = "A really cool guy who is probably a jedi but who really knows"
print(Nick)
| true
|
20b609e21199215965d79601920124905c16ef2d
|
katesem/data-structures
|
/hash_table.py
| 884
| 4.25
| 4
|
'''
In Python, the Dictionary data types represent the implementation of hash tables. The Keys in the dictionary satisfy the following requirements.
The keys of the dictionary are hashable i.e. the are generated by hashing function which generates unique result for each unique value supplied to the hash function.
The order of data elements in a dictionary is not fixed.
So we see the implementation of hash table by using the dictionary data types
'''
# accessing data with keys in hash table :
hash_table = {1 :'one', 2 : 'two', 3 : 'three', 4 : 'four'}
hash_table[1] # -> one
hash_table[4] # -> four
#adding items:
hash_table[5] = 'five'
# updating dictionary:
hash_table[4] = 'FOUR'
print(hash_table)
#deleting items:
del hash_table[1] # remove entry with key 'Name'
hash_table.clear(); # remove all entries in dict
del hash_table ; # delete entire dictionary
| true
|
02aa151e60891f3c43b27a1091a35e4d75fe5f7d
|
mshalvagal/cmc_epfl2018
|
/Lab0/Python/1_Import.py
| 1,610
| 4.375
| 4
|
"""This script introduces you to the useage of Imports in Python.
One of the most powerful tool of any programming langauge is to be able to resuse code.
Python allows this by setting up modules. One can import existing libraries using the import function."""
### IMPORTS ###
from __future__ import print_function # Only necessary in Python 2
import biolog
biolog.info(3*'\t' + 20*'#' + 'IMPORTS' + 20*'#' + 3*'\n')
# A generic import of a default module named math
import math
# Now you have access to all the functionality availble
# in the math module to be used in this function
print('Square root of 25 computed from math module : {}'.format(math.sqrt(25)))
# To import a specific function from a module
from math import sqrt
# Now you can avoid referencing that the sqrt function is from
# math module and directly use it.
print('Square root of 25 computed from math module by importing only sqrt function: ', sqrt(25))
# Import a user defined module
# Here we import biolog : Module developed to display log messages for the exercise
biolog.info('Module developed to display log messages for the exercies')
biolog.warning("When you explicitly import functions from modules, it can lead to naming errors!!!""")
# Importing multiple functions from the same module
from math import sqrt, cos
# Defining an alias :
# Often having to reuse the actual name of module can be a pain.
# We can assign aliases to module names to avoid this problem
import datetime as dt
biolog.info("Here we import the module datetime as dt.")
# Getting to know the methods availble in a module
biolog.info(dir(math))
| true
|
42f37b58b8e3b4583208ea054d30bef34040a6ed
|
inshaal/cbse_cs-ch2
|
/lastquest_funcoverload_Q18_ncert.py
| 1,152
| 4.1875
| 4
|
"""FUNCTION OVERLOADING IS NOT POSSIBLE IN PYTHON"""
"""However, if it was possible, the following code would work."""
def volume(a): #For volume of cube
vol=a**3
print vol, "is volume of cube"
def volume(a,b,c): #volume of cuboid |b-height
vol=a*b*c
print vol, "is volume of cuboid"
def volume(a,b): #volume of cylinder |a-radius|b-height
from math import pi
vol= pi*(a**2)*b
print vol, "is volume of cylinder"
a=raw_input("Enter dimension1: ")
b=raw_input("Enter dimension2: ")
c=raw_input("Enter dimension3: ")
volume(a,b,c)
'''
Notice Python takes the latest definition of that function. So if all three values are provided for a,b & c Python will give an error
stating it takes only 2 arguments but 3 given.
'''
'''
EXTRA PART FOR - (Not Required)
ta=bool(a)
tb=bool(b)
tc=bool(c)
if ta:
a=float(a)
if not (tb and tc):
volume(a)
elif tb and (not tc):
b=float(b)
volume(a,b)
elif (tb and tc):
b=float(b)
c=float(c)
volume(a,b,c)
'''
"""It's possible using module/s: https://pypi.python.org/pypi/overload"""
| true
|
6335c93ef76e37891cee92c97be29814aa91eb21
|
Leonardo612/leonardo_entra21
|
/exercicio_01/cadastrando_pessoas.py
| 992
| 4.125
| 4
|
"""
--- Exercício 1 - Funções
--- Escreva uma função para cadastro de pessoa:
--- a função deve receber três parâmetros, nome, sobrenome e idade
--- a função deve salvar os dados da pessoa em uma lista com escopo global
--- a função deve permitir o cadastro apenas de pessoas com idade igual ou superior a 18 anos
--- a função deve retornar uma mensagem caso a idade informada seja menor que 18
--- caso a pessoa tenha sido cadastrada com sucesso deve ser retornado um id
--- A função deve ser salva em um arquivo diferente do arquivo principal onde será chamada
"""
#=== escopo global
pessoas = []
def cadastrar_pessoas(nome, sobrenome, idade):
if idade < 18:
print("Idade não permitida!")
else:
pessoa = {'nome': nome,'sobrenome': sobrenome,'idade': idade}
pessoa['i_d'] = len(pessoas) + 1
pessoas.append(pessoa)
print("Pessoa cadrastrada!")
return pessoas
| false
|
109d7adc06ec9c8d52fde5743dbea7ffb262ab33
|
edenizk/python_ex
|
/dict.py
| 1,321
| 4.21875
| 4
|
def main():
elements = {"hydrogen": 1, "helium": 2, "carbon": 6}
print("print the value mapped to 'helium'",elements["helium"]) # print the value mapped to "helium"
elements["lithium"] = 3 # insert "lithium" with a value of 3 into the dictionary
print("elements = ",elements)
print("is there carbon = ", "carbon" in elements)
print("get dilithum = ",elements.get("dilithium"))
print("get hydrogen = ",elements.get('hydrogen'))
print("there is no dilithium ? ", elements.get("dilithium") is None)
n = elements.get("dilithium")
print("there is no dilithium ? ", n is None)
print("there is no dilithium ? ", n is not None)
print("type of elements = ", type(elements))
animals = {'dogs': [20, 10, 15, 8, 32, 15], 'cats': [3,4,2,8,2,4], 'rabbits': [2, 3, 3], 'fish': [0.3, 0.5, 0.8, 0.3, 1]}
print(sorted(animals))
elements2 = {"hydrogen": {"number": 1,
"weight": 1.00794,
"symbol": "H"},
"helium": {"number": 2,
"weight": 4.002602,
"symbol": "He"}}
print("hydrogen weight = ",elements2['hydrogen']['weight'])
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a == b)
print(a is b)
print(a == c)
print(a is c)
main()
| false
|
579a2fbc1f237e1207be37752963d17f2011b629
|
edenizk/python_ex
|
/ifstatement.py
| 866
| 4.15625
| 4
|
def main():
phone_balance = 10
bank_balance = 50
if phone_balance < 10:
phone_balance += 10
bank_balance -= 10
print(phone_balance)
print(bank_balance)
number = 145
if number % 2 == 0:
print("Number " + str(number) + " is even.")
else:
print("Number " + str(number) + " is odd.")
age = 35
free_up_to_age = 4
child_up_to_age = 18
senior_from_age = 65
concession_ticket = 1.25
adult_ticket = 2.50
if age <= free_up_to_age:
ticket_price = 0
elif age <= child_up_to_age:
ticket_price = concession_ticket
elif age >= senior_from_age:
ticket_price = concession_ticket
else:
ticket_price = adult_ticket
message = "Somebody who is {} years old will pay ${} to ride the bus.".format(age, ticket_price)
print(message)
| true
|
b404e386aa86f7e7a8abfdbbfb1a7e678920e420
|
sn-lvpthe/CirquePy
|
/02-loops/fizzbuzz.py
| 680
| 4.15625
| 4
|
print ("Dit is het FIZZBUZZ spel!")
end = input("""\nWe gaan even na of een getal deelbaar is door 3 OF 5 .\nOf door 3 EN 5.\n
Geef een geheel getal in tussen 1 en 100: """)
# try-except statement:
# if the code inside try fails, the program automatically goes to the except part.
try:
end = int(end) # convert string into number
for num in range(1, end+1):
if num % 3 == 0 and num % 5 == 0:
print ("FIZZBUZZ-3-5")
elif num % 3 == 0:
print ("\tfizz-3")
elif num % 5 == 0:
print ("\t\tbuzz-5")
else:
print(num)
except Exception as e:
print("Sorry. Ik lust alleen HELE getallen!")
| false
|
1fb7b06f3ed69f53268c4b1f6fc0a39702f8274c
|
mishra-atul5001/Python-Exercises
|
/Search.py
| 574
| 4.15625
| 4
|
Stringy = '''
Suyash: Why are you wearing your pajamas?
Atul: [chuckles] These aren't pajamas! It's a warm-up suit.
Suyash: What are you warming up for Bro..!!?
Atul: Stuff.
Suyash: What sort of stuff?
Atul: Super-cool stuff you wouldn't understand.
Suyash: Like sleeping?
Atul: THEY ARE NOT PAJAMAS!
'''
print(Stringy)
def countWord(word,st):
st = st.lower()
count = st.count(word)
return print(word + ' repeats ' + str(count) + ' times')
print('What word do you want to search for?')
userWord = input()
countWord(userWord,Stringy)
#Atul Mishra
#SRM Univ.
| true
|
cc8e5d5db27730063c43f01ef610dcea40ec77df
|
lacra-oloeriu/learn-python
|
/ex15.py
| 552
| 4.125
| 4
|
from sys import argv# That is a pakege from argv
script, filename = argv#This is define the pakege
txt= open(filename)#that line told at computer ...open the file
print(f"Here's your file {filename}:")#print the text...and in {the name of file to open in extension txt}
print ( txt.read())
print("Type the filename again:")#print the text.."Type the fil....again"
file_again = input ( " > ")# the name of file
txt_again = open ( file_again)#open file again
print (txt_again.read())#printeaza continutul fisierului ...prin the cont of file again
| true
|
af1191998cf3f8d5916e22b8b55da7766bead003
|
huynhirene/ICTPRG-Python
|
/q1.py
| 241
| 4.28125
| 4
|
# Write a program that counts from 0 to 25, outputting each number on a new line.
num = 0
while num <= 26:
print(num)
num = num + 1
if num == 26:
break
# OR
for numbers in range(0,26):
print(numbers)
| true
|
113cddca4472e40432caf9672fdc4ce22f25fb86
|
fjctp/find_prime_numbers
|
/python/libs/mylib.py
| 542
| 4.15625
| 4
|
def is_prime(value, know_primes=[]):
'''
Given a list of prime numbers, check if a number is a prime number
'''
if (max(know_primes)**2) > value:
for prime in know_primes:
if (value % prime) == 0:
return False
return True
else:
raise ValueError('List of known primes is too short for the given value')
def find_all_primes(ceil):
'''
find all prime numbers in a range, from 2 to "ceil"
'''
known_primes = [2, ]
for i in range(3, ceil+1):
if is_prime(i, known_primes):
known_primes.append(i)
return known_primes
| true
|
77f47d8da94d71e0e7337cf8dc9e4f3faa65c31a
|
orozcosomozamarcela/Paradigmas_de_Programacion
|
/recursividad.py
| 1,132
| 4.125
| 4
|
# 5! = 5 * 4! = 120
# 4! = 4 * 3! = 24
# 3! = 3 * 2! = 6
# 2! = 2 * 1! = 2
# 1! = 1 * 0! = 1
# 0! = 1 = 1
#% * 4 * 3 * 2 * 1
def factorial (numero):
if numero == 0 :
return 1
else:
print ( f "soy el { numero } " )
#recur = factorial(numero -1)
#da = recur * numero
#return da
# LOS PRINTS SON UTILIUZADOS EN ESTE CAS PARA MOSTRAR COMO ES LA RECURSIIDAD, CON UN PRINT ESTARIA BIEN. LA RECURSIVIDAD SE DA DE ARRIBA PARA ABAJO Y CUANDO HAY UN RETURN VUELVE DE ABAJO PARA ARRIBA.
# DESDE recur hasta return se puede achicar a solo una linea y va a hacer lo mismo, quedaria asi:
return factorial ( numero - 1 ) * numero
print(factorial(5))
# OTRO EJEMPLO MAS: EJEMPLO DE FIBONACCI, es una doble recursion basicamente.
#fibonacci(0) = 1
#fibonacci(1) = 1
#fibonacci(n) = fibonacci(n-1)+fobonacci(n-2):
#TRADUCIDO EN PYTHON LUCE ASI:
def sacarFibonacci ( numero ):
if numero == 0 or numero == 1 :
return 1
else:
return sacarFibonacci ( numero - 1 ) + sacarFibonacci ( numero - 2 )
print(sacarFibonacci ( 10 ))
| false
|
a3c2ac4234daefa2a07898aa9cce8890ca177500
|
orozcosomozamarcela/Paradigmas_de_Programacion
|
/quick_sort.py
| 1,025
| 4.15625
| 4
|
def quick_sort ( lista ):
"""Ordena la lista de forma recursiva.
Pre: los elementos de la lista deben ser comparables.
Devuelve: una nueva lista con los elementos ordenados. """
print ( "entra una clasificación rápida" )
if len ( lista ) < 2 :
print ( "devuelve lista con 1 elemento" )
return lista
menores , medio , mayores = _partition ( lista )
print ( "concatena" )
return quick_sort ( menores ) + medio + quick_sort ( mayores )
def _partition ( lista ):
"""Pre: lista no vacía.
Devuelve: tres listas: menores, medio y mayores. """
pivote = lista [ 0 ]
menores = []
mayores = []
for x in range ( 1 , len ( lista )):
print ( f" pivote: { pivote } , valor: { lista [ x ] } " )
if lista [ x ] < pivote:
menores.append ( lista [ x ])
else:
mayores.append ( lista [ x ])
return menores , [ pivote ], mayores
print( quick_sort ([ 7 , 5 , 3 , 12 , 9 , 2 , 10 , 4 , 15 , 8 ]))
| false
|
44cc5b20276024979f97fb31cd221b90ba78e351
|
Mahdee14/Python
|
/2.Kaggle-Functions and Help.py
| 2,989
| 4.40625
| 4
|
def maximum_difference(a, b, c) : #def stands for define
"""Returns the value with the maximum difference among diff1, diff2 and diff3"""
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
return min(diff1, diff2, diff3)
#If we don't include the 'return' keyword in a function that requires 'return', then we're going to get a special value
#called 'Null'
def least_dif(a ,b, c):
"""Docstring - Finds the minimum value with the least difference between numbers"""
diff1 = a - b
diff2 = b - c
diff3 = a - c
return min(diff1, diff2, diff3)
print(
least_dif(1, 10, 100),
least_dif(1, 2, 3),
least_dif(10, 20, 30)
)
#help(least_dif)
print(1, 2, 3, sep=" < ") #Seperate values in between printed arguments #By default sep is a single space ' '
#help(maximum_difference)^^^
#Adding optional arguments with default values to custom made functions >>>>>>
def greet(who="Mahdee"):
print("Hello ", who)
print(who)
greet()
greet(who="Mahdee")
greet("world")
#Functions applied on functions
def mult_by_five(x, y):
return 5 * x + y
def call(fn, *arg):
"""Call fn on arg"""
return fn(*arg)
print(call(mult_by_five, 1, 1) , "\n\n")
example = call(mult_by_five, 1, 3)
print(example)
def squared_call(fn, a, b, ans):
"""Call fn on the result of calling fn on arg"""
return fn(fn(a, b), ans)
print(
call(mult_by_five, 3, 6),
squared_call(mult_by_five, 1, 1, 1),
sep='\n', # '\n' is the newline character - it starts a new line
)
def mod_5(x):
"""Return the remainder of x after dividing by 5"""
return x % 5
print(
'Which number is biggest?',
max(100, 51, 14),
'Which number is the biggest modulo 5?',
max(100, 51, 14, key=mod_5),
sep='\n',
)
def my_function():
print("Hello From My Function!")
my_function()
def function_with_args(name, greeting):
print("Hello, %s, this is an example for function with args, %s" % (name, greeting))
function_with_args("Mahdee", "Good Morning")
def additioner(x, y):
return x + y
print(additioner(1, 3))
def list_benefits():
return "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to connect and share code together"
def build_sentence(info):
return "%s , is a benefit of functions" % info
def name_the_benefits_of_functions():
list_of_benefits = list_benefits()
for benefit in list_of_benefits:
print(build_sentence(benefit))
name_the_benefits_of_functions()
#Exercise
def to_smash(total_candies, n_friends=3):
"""Return the number of leftover candies that must be smashed after distributing
the given number of candies evenly between 3 friends.
>>> to_smash(91)
1
"""
return total_candies % n_friends
print(to_smash(91))
x = -10
y = 5
# # Which of the two variables above has the smallest absolute value?
smallest_abs = min(abs(x), abs(y))
def f(x):
y = abs(x)
return y
print(f(0.00234))
| true
|
6b6dae17b4cdb0af548f79350deb1e6657084552
|
IamHehe/TrySort
|
/1.bubble_sort.py
| 603
| 4.15625
| 4
|
# coding=utf-8
# author: dl.zihezhu@gmail.com
# datetime:2020/7/25 11:23
"""
程序说明:
冒泡排序法
(目标是从小到大排序时)
最好情况:顺序从小到大排序,O(n)
最坏情况:逆序从大到小排序,O(n^2)
平均时间复杂度:O(n^2)
空间复杂度:O(1)
"""
def bubbleSort(arr):
for i in range(1, len(arr)):
for j in range(0, len(arr) - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
if __name__ == "__main__":
lis = [3, 4, 2, 1, 6, 5]
print(bubbleSort(lis))
| false
|
0ab3c263766f174b04f319ba773a14e1e56170da
|
IamHehe/TrySort
|
/5.merge_sort.py
| 2,389
| 4.15625
| 4
|
# coding=utf-8
# author: dl.zihezhu@gmail.com
# datetime:2020/7/26 12:31
"""
程序说明:
归并排序
(目标是从小到大排序时)
最好情况:O(n log n)
最坏情况:O(n log n)
平均时间复杂度:O(n log n)
空间复杂度:自上到下:因为需要开辟一个等长的数组以及使用了二分的递归算法,所以空间复杂为O(n)+O(log n)。自下向上:O(1)
稳定
"""
# 自上向下分,递归
def merge_sort(arr):
if len(arr) < 2:
return arr
middle = len(arr) // 2
left, right = arr[0:middle], arr[middle:] # 分
return merge(merge_sort(left), merge_sort(right)) # 治:递归而下 # 共有log n +1 层即时间复杂度为# O(n * log n)
def merge(left, right):
res = [] # 这里相当于开辟了同等大小的空间,使得空间复杂度为O(n)
while left and right: # O(n)
if left[0] <= right[0]:
res.append(left.pop(0))
else:
res.append(right.pop(0))
while left: # O(n)
res.append(left.pop(0))
while right: # O(n)
res.append(right.pop(0))
return res
# 归并排序,新增自下至上的迭代,通过扩展步长weight进行
# 参考:https://www.pythonheidong.com/blog/article/453039/
def BottomUp_merge_sort(a):
n = len(a)
b = a[:] # 深拷贝一个a
width = 1 # 步长
while width < n: # 步长小于列表长度
start = 0 # 起始位置
while start < n:
mid = min(n, start + width) # n只有在最后start+width超过整个句子的长度的时候才会被选取
end = min(n, start + (2 * width))
BottomUp_Merge(a, b, start, mid, end)
start += 2 * width
a = b[:] # 使用合并排序后的结果作为下一次迭代的基础
width *= 2 # 2 4 8 16 这样的方式获取
return a
def BottomUp_Merge(a, b, start, mid, end):
i = start
j = mid
for k in range(start, end):
if i < mid and (j >= end or a[i] <= a[j]): # j>=end 即后面的不尽兴操作,直接复制
b[k] = a[i]
i += 1
else:
b[k] = a[j]
j += 1
if __name__ == "__main__":
lis = [3, 4, 2, 1, 6, 5]
print(merge_sort(lis))
lis = [3, 4, 2, 1, 6, 5]
lis = BottomUp_merge_sort(lis)
print(lis)
| false
|
d990ed78e1ecc5dd47c002e438d23400c72badba
|
mochadwi/mit-600sc
|
/unit_1/lec_4/ps1c.py
| 1,368
| 4.1875
| 4
|
# receive Input
initialBalance = float(raw_input("Enter your balance: "))
interestRate = float(raw_input("Enter your annual interest: "))
balance = initialBalance
monthlyInterestRate = interestRate / 12
lowerBoundPay = balance / 12
upperBoundPay = (balance * (1 + monthlyInterestRate) ** 12) / 12
while True:
balance = initialBalance
monthlyPayment = (lowerBoundPay + upperBoundPay) / 2 # bisection search
for month in range(1,13):
interest = round(balance * monthlyInterestRate, 2)
balance += interest - monthlyPayment
if balance <= 0:
break
if (upperBoundPay - lowerBoundPay < 0.005): # TOL (tolerance)
# Print result
print "RESULT"
monthlyPayment = round(monthlyPayment + 0.004999, 2)
print "Monthly Payment to pay (1 Year): $", round(monthlyPayment, 2)
# recalculate
balance = initialBalance
for month in range(1,13):
interest = round(balance * monthlyInterestRate, 2)
balance += interest - monthlyPayment
if balance <= 0:
break
print "Months needed: ", month
print "Your balance: $", round(balance, 2)
break
elif balance < 0:
# Paying too much
upperBoundPay = monthlyPayment
else:
# Paying too little
lowerBoundPay = monthlyPayment
| true
|
fbaf789fbe6bfaede28d2b2d3a6a1673e229f57b
|
bledidalipaj/codefights
|
/challenges/python/holidaybreak.py
| 2,240
| 4.375
| 4
|
"""
My kids very fond of winter breaks, and are curious about the length of their holidays including all the weekends.
Each year the last day of study is usually December 22nd, and the first school day is January 2nd (which means that
the break lasts from December 23rd to January 1st). With additional weekends at the beginning or at the end of the
break (Saturdays and Sundays), this holiday can become quite long.
The government issued two rules regarding the holidays:
The kids' school week can't have less than 3 studying days. The holidays should thus be prolonged if the number of
days the kids have to study before or after the break is too little.
If January 1st turns out to fall on Sunday, the following day (January 2nd) should also be a holiday.
Given the year, determine the number of days the kids will be on holidays taking into account all the rules and weekends.
Example
For year = 2016, the output should be
holidayBreak(year) = 11.
First day of the break: Friday December 23rd.
Last day of the break: Monday January 2nd.
Break length: 11 days.
For year = 2019, the output should be
holidayBreak(year) = 16.
First day of the break: Saturday December 21st.
Last day of the break: Sunday January 5th.
Break length: 16 days.
*** Due to complaints, I've added a hidden Test outside of the range. The Year now goes to 2199 ***
[time limit] 4000ms (py)
[input] integer year
The year the break begins.
Constraints:
2016 ≤ year ≤ 2199.
[output] integer
The number of days in the break.
# Challenge's link: https://codefights.com/challenge/yBwcdkwQm5tAG2MJo #
"""
import calendar
def holidayBreak(year):
first_day = 23
last_day = 31 + 1
# first day of the break
weekday = calendar.weekday(year, 12, 23)
if weekday == 0:
first_day -= 2
elif weekday == 1:
first_day -= 3
elif weekday == 2:
first_day -= 4
elif weekday == 6:
first_day -= 1
# last day of the break
weekday = calendar.weekday(year + 1, 1, 1)
if weekday == 6 or weekday == 5:
last_day += 1
elif weekday == 4:
last_day += 2
elif weekday == 3:
last_day += 3
elif weekday == 2:
last_day += 4
return last_day - first_day + 1
| true
|
0bad5a8a7ee86e45043ef0ddf38406a9ee4d1032
|
pmayd/python-complete
|
/code/exercises/solutions/words_solution.py
| 1,411
| 4.34375
| 4
|
"""Documentation strings, or docstrings, are standard ways of documenting modules, functions, methods, and classes"""
from collections import Counter
def words_occur():
"""words_occur() - count the occurrences of words in a file."""
# Prompt user for the name of the file to use.
file_name = input("Enter the name of the file: ")
# Open the file, read it and store its words in a list.
# read() returns a string containing all the characters in a file
# and split() returns a list of the words of a string “split out” based on whitespace
with open(file_name, 'r') as f:
word_list = f.read().split()
# Count the number of occurrences of each word in the file.
word_counter = Counter(word_list)
# Print out the results.
print(
f'File {file_name} has {len(word_list)} words ({len(word_counter)} are unique).\n' # f-strings dont need a \ character for multiline usage
f'The 10 most common words are: {", ".join([w for w, _ in word_counter.most_common(10)])}.'
)
return word_counter
# this is a very important part of a module that will only be executed
# if this file is calles via command line or the python interpreter.
# This if statement allows the program to be run as a script by typing python words.py at a command line
if __name__ == '__main__':
words_occur()
| true
|
95b308d6bdb204928c6b014c8339c2cc8693b7d7
|
pmayd/python-complete
|
/code/exercises/most_repeating_word.py
| 870
| 4.3125
| 4
|
import doctest
def most_repeating_word(words: list) -> str:
"""
Write a function, most_repeating_word, that takes a sequence of strings as input. The function should return the string that contains the greatest number of repeated letters. In other words:
for each word, find the letter that appears the most times
find the word whose most-repeated letter appears more than any other
Bonus:
- make function robust (empty list, etc)
- add parameter to count all leters, only vowels or only consonants
Examples:
>>> most_repeating_word(['aaa', 'abb', 'abc'])
'aaa'
>>> most_repeating_word(['hello', 'wonderful', 'world'])
'hello'
>>> words = ['this', 'is', 'an', 'elementary', 'test', 'example']
>>> most_repeating_word(words)
'elementary'
"""
pass
if __name__ == "__main__":
doctest.testmod()
| true
|
59483e49c3cdf8fe1cf1871ec439b25ffd4daf15
|
lisandroV2000/Recuperatorio-programacion
|
/ACT3.py
| 784
| 4.15625
| 4
|
#3. Generar una lista de números aleatoriamente y resuelva lo siguiente:
#a. indicar el rango de valores de la misma, diferencia entre menor y mayor
#b. indicar el promedio
#c. ordenar la lista de manera creciente y mostrar dichos valores
#d. ordenar la lista de manera decreciente y mostrar dichos valores
#e. hacer un barrido que solo muestre los número impares no múltiplos de 3
from random import randint
numeros = []
for i in range (0,100):
numero1 = randint(1,100)
numeros.append(numero1)
numeros.sort()
print ("El menor de la lista es",numeros[0])
print ("El mayor de la lista es",numeros[99])
print(numeros)
for lista in range (0,99):
if (lista % 9==0, lista % 5==0, lista % 7==0,lista % 3==0):
print(lista)
| false
|
111c536fba28296ec4f2a93ab466360e57d839d6
|
paul0920/leetcode
|
/question_leetcode/215_5.py
| 1,471
| 4.25
| 4
|
# Bucket sort algorithm
# Average time complexity: O(n)
# Best case: O(n)
# Worst case: O(n^2)
# Space complexity: O(nk), k: bucket count
# Bucket sort is mainly useful when input is uniformly distributed over a range
# Choose the bucket size & count, and put items in the corresponding bucket
nums = [3, 2, 1, 5, 6, 4]
# k = 2
# nums = [3, 2, 3, 1, 2, 4, 5, 5, 6]
# k = 4
# nums = [2, 200, 6, 9, 10, 32, 32, 100, 101, 123]
def bucket_sort(alist, bk_size):
largest = max(alist)
length = len(alist)
size = bk_size
# size = largest / length
# if size < 1:
# size = 1
print "bucket size:", size
buckets = [[] for _ in range(length)]
for i in range(length):
j = int(alist[i] / size)
print "i:", i, "j:", j, "length:", length
if j < length:
buckets[j].append(alist[i])
elif j >= length:
buckets[length - 1].append(alist[i])
print buckets
print ""
# Use insertion sort to sort each bucket
for i in range(length):
insertion_sort(buckets[i])
result = []
for i in range(length):
result += buckets[i]
return result
def insertion_sort(alist):
for i in range(1, len(alist)):
key = alist[i]
j = i - 1
while j >= 0 and key < alist[j]:
alist[j + 1] = alist[j]
j = j - 1
alist[j + 1] = key
arr = bucket_sort(nums, 3)
print ""
print "the sorted array:", arr
| true
|
0aa9a7c64282a574374fb4b9e9918215f0f013ec
|
paul0920/leetcode
|
/question_leetcode/48_2.py
| 509
| 4.1875
| 4
|
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
print row
m = len(matrix)
n = len(matrix[0])
# j only loops until i
for i in range(m):
for j in range(i):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# j only loops until n / 2
for i in range(m):
for j in range(n / 2):
matrix[i][j], matrix[i][n - j - 1] = matrix[i][n - j - 1], matrix[i][j]
# matrix[i][j], matrix[i][~j] = matrix[i][~j], matrix[i][j]
print ""
for row in matrix:
print row
| false
|
65b13cf4b6251e6060c8ccf34a63ab703f93fd2b
|
paul0920/leetcode
|
/pyfunc/lambda_demo_1.py
| 251
| 4.15625
| 4
|
my_list = [1, 5, 4, 6]
print map(lambda x: x * 2, my_list)
print (lambda x: x * 2)(my_list)
print my_list * 2
# A lambda function is an expression, it can be named
add_one = lambda x: x + 1
print add_one(5)
say_hi = lambda: "hi"
print say_hi()
| false
|
d94c3e993bd855c950dfe809dba92957b40c4a20
|
JimiofEden/PyMeth
|
/Week 1/TEST_roots_FalsePosition.py
| 470
| 4.25
| 4
|
import roots_FalsePosition
import numpy
'''
Adam Hollock 2/8/2013
This will calculate the roots of a given function in between two given
points via the False Position method.
'''
def f(x): return x**3+2*x**2-5*x-6
results = roots_FalsePosition.falsePosition(f,-3.8,-2.8,0.05)
print results
results = roots_FalsePosition.falsePosition(f,-1.3,-0.9,0.05)
print results
results = roots_FalsePosition.falsePosition(f,1.8,2.3,0.05)
print results
print numpy.roots([1, 2, -5, -6])
| true
|
e579fadc31160475af8f2a8d42a20844575c95fa
|
mitalshivam1789/python
|
/oopfile4.py
| 940
| 4.21875
| 4
|
class A:
classvar1= "I am a class variable in class A."
def __init__(self):
self.var1 = "I am in class A's constructor."
self.classvar1 = "Instance variable of class A"
self.special = "Special"
class B(A):
classvar1="I am in class B"
classvar2 = "I am variable of class B"
def __init__(self):
#super().__init__()# as we call this then the values of var1 and classvar1 will change as per class A instance
self.var1 = "I am in class B's constructor."
self.classvar1 = "Instance variable of class B"
# values of var1 and classvar1 will change again
super().__init__() #as we call this then the values of var1 and classvar1 will change as per class A instance
# if we comment 1st one then from here the values of var1 and classvar1 will not change
a = A()
b= B()
print(b.classvar1)
print(b.classvar2)
print(b.special,b.var1)
| true
|
4ecd4d3a20e875b9c0b5019531e8858f4722b632
|
victorbianchi/Toolbox-WordFrequency
|
/frequency.py
| 1,789
| 4.5
| 4
|
""" Analyzes the word frequencies in a book downloaded from
Project Gutenberg """
import string
def get_word_list(file_name):
""" Reads the specified project Gutenberg book. Header comments,
punctuation, and whitespace are stripped away. The function
returns a list of the words used in the book as a list.
All words are converted to lower case.
"""
#loading file and stripping away header comment
f = open(file_name,'r')
lines = f.readlines()
curr_line = 0
while lines[curr_line].find('START OF THIS PROJECT GUTENBERG EBOOK') == -1:
curr_line += 1
lines = lines[curr_line+1:]
#remove excess
for i in range(len(lines)):
lines[i] = lines[i].strip().translate(string.punctuation).lower()
while '' in lines:
lines.remove('')
words = []
for line in lines:
line_words = line.split(' ')
words = words + line_words
return words
def get_top_n_words(word_list, n):
""" Takes a list of words as input and returns a list of the n most frequently
occurring words ordered from most to least frequently occurring.
word_list: a list of words (assumed to all be in lower case with no
punctuation
n: the number of words to return
returns: a list of n most frequently occurring words ordered from most
frequently to least frequentlyoccurring
"""
word_counts = {}
for word in word_list:
if word not in word_counts:
word_counts[word] = 1
else:
word_counts[word] += 1
ordered_by_frequency = sorted(word_counts, key=word_counts.get, reverse=True)
return ordered_by_frequency[:n+1]
if __name__ == "__main__":
result = get_word_list('pg32325.txt')
list = get_top_n_words(result, 100)
print(list)
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.