blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
200951dcb80a93c07f7977e6e3ded87a7fd904f1 | AnhellO/DAS_Sistemas | /Ene-Jun-2022/adrian-led-vazquez-herrera/practica_5/P5_2_1.py | 872 | 4.21875 | 4 | #DAS Práctica 5.2.1
from abc import ABC, abstractmethod
class Polygon(ABC):
@abstractmethod
def num_of_sides(self):
pass
class Triangle(Polygon):
def __init__(self):
self.sides=3
def num_of_sides(self):
return self.sides
class Square(Polygon):
def __init__(self):
self.sides=4
def num_of_sides(self):
return self.sides
class Pentagon(Polygon):
def __init__(self):
self.sides=5
def num_of_sides(self):
return self.sides
class Hexagon(Polygon):
def __init__(self):
self.sides=6
def num_of_sides(self):
return self.sides
T=Triangle()
S=Square()
P=Pentagon()
H=Hexagon()
shapes=[T,S,P,H]
for shape in shapes:
print(shape.num_of_sides())
| false |
123a2a8668f3ec4f7e450adb67a93618e91d4027 | AnhellO/DAS_Sistemas | /Ene-Jun-2022/jesus-raul-alvarado-torres/Practica-1/main.py | 408 | 4.3125 | 4 | # Esto es un comentario en Python
# Declaro una variable
x = 5
# Imprimo mi variable
print("x = ", x)
# Operaciones aridmeticas con mi variable
print("x + 5 = ",x + 5) #Suma
print("x - 5 = ",x - 5) #Resta
print("x * 5 = ",x * 5) #Multiplicacion
print("x / 5 = ",x / 5) #Division
print("x % 5 = ",x % 5) #Residuo
print("x // 5 = ",x // 5) #Division entera
print("x^2 = ",x ** 5) #Potencia | false |
4eda1153098fccefd3e311c6dde550759932a719 | AJChestnut/Python-Projects | /14 Requesting 3 Numbers and then Mathing.py | 2,059 | 4.5625 | 5 | # Assignment 14:
# Write a Python program requesting a name and three numbers from the user. The program will need
# to calculate the following:
#
# the sum of the three numbers
# the result of multiplying the three numbers
# divide the first by the second then multiply by the third
# Print a message greeting the user by name and the results of each of the mathematical operations.
#
# You must provide a comment block at the top indicating your name, the course, the section, and
# the date as well as a description of the program. Also, comment as necessary to clearly explain
# what it is you are doing where you are doing it in the program.
# This was the first assignment of my second class on learning Python. It wasa mostly a refresher
# on things that I had already learned from the first class, but there was one significant new
# thing — storing number inputs as integers from the get go. I also did some additional research
# to learn how to round the last answer to a set number of decimal places.
Code:
# Request a name and 3 numbers, perform multiple math fucntions on numbers and display results
# Code by AJChestnut
# July 10, 2020
#ask user for name and store as a variable
print ('Hello, there. What\'s your name?')
userName=input()
#Ask user for 3 numbers and store the int value as variables
print('It\'s nice to meet you,', userName + '.')
print('And now, I am going to need 3 numbers from you.')
print('What is your first favorite number?')
firstNum=int(input())
print('Your second favorite number?')
secondNum=int(input())
print('And lastly, what is your third favorite number?')
thirdNum=int(input())
#mathing for winners
sums=firstNum + secondNum + thirdNum
products=firstNum * secondNum * thirdNum
mixed=firstNum / secondNum * thirdNum
#display math results
print('Thank you,', userName + '.', 'The sum of your favorite numbers is:', sums)
print('The product of your favorite numbers is: ', products)
print('The first number, divided by the second number, then multiplied by the third is: ', round(mixed, 2))
| true |
f955b97f3ab252a2885a441f6c99773cd00efed7 | AJChestnut/Python-Projects | /10 Comma Code.py | 2,169 | 4.4375 | 4 | # Assignment 10:
# Say you have a list value like this:
# listToPrint = ['apples', 'bananas', 'tofu', 'cats']
# Write a program that prints a list with all the items separated by a comma and a space,
# with and inserted before the last item. For example, the above list would print 'apples,
# bananas, tofu, and cats'. But your program should be able to work with any list not just
# the one shown above. Because of this, you will need to use a loop in case the list to
# print is shorter or longer than the above list. Make sure your program works for all
# user inputs. For instance, we wouldn't want to print "and" or commas if the list only
# contains one item.
# The initial while loop that allows a user to input variables to a list was given to us
# by the instructor. We were responsible for creating the rest of the script. The first two
# if statements were the easy part of this assignment for me. If this, do that. Working to
# create the for loop that went through every variable and had a step to change the output
# for the last variable in the list was complicated for me. It took a few different iterations
# before I wrote this one that worked. I've got to admit, I also spent longer than I probably
# should have on deciding to end the list with a period or not.
# Code:
# Comma Code
# Code by AJChestnut
# April 14, 2019
listToPrint = [] #create variable with empty list
while True:
newWord = input("Enter a word to add to the list (press return to stop adding words) > ")
if newWord == "": #If nothing input, stop adding things to list
break
else:
listToPrint.append(newWord) #If something input, add to end of list
if len(listToPrint) == 1: #if only 1 value in list, print value
print(str(listToPrint[0]))
if len(listToPrint) == 2: #If only 2 values, comma not needed just the "and"
print(str(listToPrint[0] + ' and ' + str(listToPrint[1])))
if len(listToPrint) > 2:
for newWord in listToPrint[:-1]: #print item + comma and space until the last value in list
print(str(newWord) + ', ', end='')
print('and ' + str(listToPrint[-1])) #finish list with "and" preceeding final value
| true |
e800aec69c574c6ff705b63f05cd277f2dfe8cb5 | digomes87/tudo-q-der-pra-fazer-js | /py/testesSoltos/listas.py | 1,256 | 4.125 | 4 | # aqui já temos uma lista
type([])
lista1 = [1, 2, 3, 4, 5, 6, 7, 'Diego', 8, 90]
lista2 = ['A', 'B', 'C', 'D']
lista3 = list(range(1, 11))
lista4 = list("ABCDEFGHIJeEEEeee")
lista5 = [2, 432, 12, 54, 65, 3, 56, 234, 24432, 1121]
print(lista1)
print(lista2)
print(lista3)
print(lista4)
print(lista5)
lista5.sort()
print(lista5)
for item in lista4:
item.lower()
print(item)
muitaspalavras = "Aqui uma frase grande e cheia de erros que podem ser corrigidos"
print(muitaspalavras)
muitaspalavras = muitaspalavras.split()
print(muitaspalavras)
outraFrase = "Aqui uma frase, com, muitas, virgulas, que nao, deveriam existir"
outraFrase = outraFrase.split(',')
print(outraFrase)
# converter lista para string
lista6 = ["aqui", '12', "outra", "lista", "porem essa transformamos em string com join"]
lista6 = ' '.join(lista6)
# lista6 = '--'.join(lista6)
print(lista6)
carrinho = []
produto = ''
# while produto != 'sair':
# print("Adicione algum produto a lista ou digite sair para encerrar: ")
# produto = input()
# if produto != 'sair':
# carrinho.append(produto)
#
# for produto in carrinho:
# print(produto)
#
cores = ["branco", "azul", "preto", "marrom"]
for indice, cor in enumerate(cores):
print(indice, cor)
| false |
c052253ac099375f8a3d9046395af382dc0c158b | mitchblaser02/Python-Scripts | /Python 3 Scripts/CSVOrganiser/CSVOrganiser.py | 347 | 4.28125 | 4 | #PYTHON CSV ORGANIZER
#MITCH BLASER 2018
i = input("Enter CSV to sort (1, 2, 3): ") #Get the CSV from the user.
p = i.split(", ") #Turn the CSV into tuple.
o = sorted(p) #Set variable o to a sorted version of p.
for i in range(0, len(o)): #Loop for the amount of entries in o.
print(o[i]) #Print out each entry sepertely (of the sorted "o" tuple.)
| true |
4f80de4e3458af59a67a68e96b6b45e1e26bc1e3 | j-sal/python | /3.py | 1,305 | 4.375 | 4 | '''
Lists and tuples are ordered
Tuples are unmutable but can contain mixed typed items
Lists are mutable but don't often contain mixed items
Sets are mutable, unordered and doesn't hold duplicate items,
sets can also do Unions, Intersections, and Differences
Dictionaries are neat
'''
myList = ["coconut","pear","tomato","apple"]
l2 = ["coconuts","pear","tomato","apple"]
l3 = [56,5,4,3,88,17]
mySet = {2.0, "Joey", ('Pratt')}
mySet2 = {"Jo", 2.0}
myD = {'Spanish level':5,'Eng level':5, 'Chinese level':3,'French level':1.5}
if "apple" in myList:
print("'apple' is on the list and its index is:",myList.index("apple"))
print("The fruit apple appears",myList.count("apple"),"time(s)")
else:
print("'apple' is NOT on the list")
print("potato" in myList)
print(myList)
print(cmp([l2],[myList])) #cmp only in py2, not in py3
l3.pop()
print("after pop:",l3)
l3.sort()
print("l3 after sort: ", l3)
l3.pop()
l3.remove(l3[0])
l3.reverse()
print("after pop, remove index 0, reverse:",l3)
l3.append(3)
print(l3)
l3.insert(1,16) #insert([index],[value])
print(l3)
l3.sort()
print("l3 after sort: ", l3)
print(mySet)
print(mySet | mySet2)
print(mySet & mySet2)
print(mySet - mySet2)
print(mySet ^ mySet2)
print(sorted(list(myD)))
print('Russian' not in myD)
#myD.fromkeys(2[,3]) #to figure out | true |
1147a10ab060451acbfe874b78c698435fa592d5 | zmybr/PythonByJoker | /day01-1.py | 1,456 | 4.125 | 4 | #1.温度转换
#C = float(input('请输入一个温度'))
#print((9/5)*C+32)
#2.圆柱体体积
#import math
#pai=math.pi
#radius = float(input("请输入半径"))
#length = float(input('请输入高'))
#area = radius * radius * pai
#volume = area * length
#print("The area is %.4f"%area)
#print("The volume is %.1f"%volume)
#3.英尺转换
#feet = float(input("请输入英尺"))
#meters = feet * 0.305
#print( "%f feet is %f meters"%(feet,meters))
#4.计算能量
#kg = float(input('Enter the amount of water in kilograms:'))
#init = float(input('Enter the initial temperature:'))
#final = float(input('Enter the final temperature:'))
#Q = kg * (final - init) * 4184
#print("The energy needed is %.1f"%Q)
#5.计算利息
#balance = float(input('请输入差额:'))
#rate = float(input('请输入年利率:'))
#interest = balance * (rate / 1200)
#print('Th interest is %f'%interest)
#6.加速度
#v0,v1,t = eval(input('Enter v0,v1 and t:'))
#a = (v1 - v0)/t
#print('The average acceleration is %.4f'%a)
#7.复利值
#money = float(input("Enter the monthly saving amount:"))
#value = money * (1 + 0.00417)
#i=1
#while i < 6:
# value = (money + value) * (1 + 0.00417)
# i +=1
#print("After the sixth month,the account value is %.2f"%value)
#8.求和
num = int(input("Enter a number between 0 and 1000:"))
sum=0
b=num//100%10
c=num//10%10
a=num%10
sum=a+b+c
print('The sum of the digits is %d'%sum)
| true |
21c3ccc8805b353d1c1d2fe92dcf8fbe613b833c | mahesstp/python | /Day3/OOPS/inheritance.py | 716 | 4.1875 | 4 | #!/usr/bin/python
class Parent:
def __init__(self, x=0, y=0):
self.__x = x
self.__y = y
def setValues(self, val1, val2):
self.__x = val1
self.__y = val2
def printValues(self):
print ('Value of x is ', self.__x )
print ('Value of y is ', self.__y )
class Child(Parent):
def __init__(self, x=0, y=0, z=0):
Parent.__init__(self,x, y)
self.__z = z
def setValues(self, val1, val2, val3):
Parent.setValues(self, val1, val2 )
self.__z = val3
def printValues(self):
Parent.printValues(self)
print ('Value of z is ', self.__z )
def main():
obj = Child(10,20,30)
obj.printValues()
main()
| false |
7e2fe8e98797d2de13f78b3af3ecbbc6af2f24fd | homeah/myPython | /026.py | 382 | 4.15625 | 4 | '''
【程序26】
题目:利用递归方法求5!。
1.程序分析:递归公式:fn=fn_1*4!
2.程序源代码:
'''
'''
def recursion(n):
if n == 1:
return n
else:
return n*recursion(n-1)
print('5!的结果是%d'%recursion(5))
'''
def recursion(n):
return n if n==1 else n*recursion(n-1)
print('5!的结果是%d'%recursion(5))
| false |
6175197774940e0e5727c59210b9ea73139f6119 | MarioAguilarCordova/LeetCode | /21. Merge Two Sorted Lists.py | 1,812 | 4.15625 | 4 | from typing import List
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def printlist(self, list):
itr = list
while itr:
print(list.val + " , ")
itr = itr.next
def mergeTwoLists(list1, list2):
"""
:type list1: Optional[ListNode]
:type list2: Optional[ListNode]
:rtype: Optional[ListNode]
"""
dummy = result = ListNode(0)
while list1 and list2:
if list1.val < list2.val:
result.next = list1
list1 = list1.next
else:
result.next = list2
list2 = list2.next
result = result.next
result.next = list1 or list2
return dummy.next
def main():
list1 = ListNode(1,2)
list2 = ListNode(1,3)
answer = ListNode(0)
answer = mergeTwoLists(list1,list2)
answer.printlist()
main()
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, list1, list2):
"""
:type list1: Optional[ListNode]
:type list2: Optional[ListNode]
:rtype: Optional[ListNode]
"""
dummy = result = ListNode(0)
while list1 and list2:
if list1.val < list2.val:
result.next = list1
list1 = list1.next
else:
result.next = list2
list2 = list2.next
result = result.next
result.next = list1 or list2
return dummy.next
return result | true |
db1dffba9b15cba6aa2536f8f3bc24f6c76bfe55 | allyshoww/python-examples | /exemplos/funcao.py | 1,238 | 4.5 | 4 | # Função é uma sequencia de instruções que realiza uma operação. São blocos de códigos que realizam determinadas tarefas que precisam ser executadas diversas vezes.
# Tem que ser em letras minusculas e underline para espaçamento
# Palavra reservada: def
# Escopo Global: Pode ser acessada por todas as funções que estão presentes no modulo
#!/usr/bin/python3
# Função que printa alguma coisa
def python():
print('Pythonzero')
python()
# Funçao que printa um nome digitado
# Ao se criar uma função, obrigatoriamente a função espera algum parametro. parametro é o valor que será substituido e que está dentro do parenteses na...
# ...primeira linha
def boa_vindas(nome):
print("Seja bem vindo,{}".format(nome))
boa_vindas(input('Coloque seu nome aqui:'))
# Funcao que printa uma variavel (nome = anonimo)
def boa_vindas2(nome='anomimo'):
print("Seja bem vindo, {}".format(nome))
boa_vindas2()
# Utiliza uma variavel para uma função
nome = 'Allyshow'
def welcome():
print('Welcome {}'.format(nome))
welcome()
# Utiliza uma variavel global para uma função
nome = 'Allyshow'
def welcome():
global nome
nome = "Allyson Oliveira"
print('Welcome {}'.format(nome))
welcome()
| false |
8a41efdf82e7a7737cec68b57eba8f5d2f5bce5c | allyshoww/python-examples | /exemplos/classes.py | 893 | 4.4375 | 4 | # Classes definem caracteristicas e o comportamento dos seus objetos. Classe não é objeto.
# Cada caracteristica é representada por um atributo.
# Cada comportamento é estabelecido por um metodo.
# Exemplo:
class Dog():
def __init__(self, nome, raca, idade):
self.nome = nome
self.raca = raca
self.idade = idade
self.energia = 10
self.sede = 10
self.fome = 10
dog1 = Dog('Nina', 'Shitzu', '6')
def latir(self):
print('Latindo...')
def andar(self):
self.energia -= 1
self.fome -= 1
self.sede -= 1
print('Andando...')
def dormir(self):
print('Dormindo ...')
print(dog1.nome, dog1.raca, dog1.idade, sep='\n')
def andar()
print(dog1.nome)
print(dog1.raca)
print(dog1.idade)
print(dog1.nome, '''
energia {}
fome {}
sede {}
'''.format(dog1.energia, dog1.fome, dog1.sede), sep='\n')
| false |
555d058cd1706c702280037b4263de42b8c6c64d | dmserrano/python101 | /foundations/exercises/randomSquared.py | 635 | 4.3125 | 4 | import random;
# Using the random module and the range method, generate a list of 20 random numbers between 0 and 49.
random_numbers = list();
def create_random_list ():
'''
This function creates 20 random numbers from 0-49.
'''
for x in range(0,20):
random_numbers.append(random.randint(0,49));
create_random_list();
print(random_numbers);
# With the resulting list, use a list comprehension to build a new list that contains each number squared. For example, if the original list is [2, 5], the final list will be [4, 25].
squared_list = [each * each for each in random_numbers ];
print(squared_list);
| true |
f38c54d511dddb4daf577c004168368c6d7d94b8 | Fuchj/Python | /src/FirstDay/列表练习/FirstDay.py | 2,017 | 4.15625 | 4 |
"""列表练习"""
#name = "Hello Python Crash Course world!"
#print(name.title())
#name = "ada lovelace"
#print(name.title())
age = 23
#数字和字符串拼接,会发生错误
#message = "Happy " + age + "rd Birthday!"
#使用str 把非字符串的类型转换为字符串
message = "Happy " + str(age) + "rd Birthday!"
print(message)
print("--------------------------------------")
a="ss"
arry=[1,a,"订单",1.2]
print(arry)
print(arry[2])
print(arry[-1])
print(arry[-4])
arry[-1]="我是最后一个"
print(arry)
arry.append("新来的")
print(arry)
print("--------------------------------------")
print(arry)
del arry[-1]
print(arry)
print("-------删除-------------------------------")
#arry.pop(-1)
#print(arry)
#a= arry.pop(-1)
#print(arry);
#print(a)
#arry.append(a);
#print(arry);
arry.append("1");
print(arry)
#打印列表的长度
print("列表arry的长度:"+str(len(arry)))
#----------循环编列列表-------------
print("开始循环遍历")
for x in arry:
print(x)
print("----------range()方法-------------")
#range(1,6)
arry1=list(range(2,11,2))
print(arry1)
#使用列表解析把1~11范围中的数字的平方存放到列表中
arry2= [value**2 for value in range(1,11)]
print(arry2)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#列表的切片操作
arry3=[0,"one",2,"three",4,"five"]
print(arry3)
print(arry3[0:3]) #打印该列表的一个切片,输出也是一个列表,其中包含前单个索引的值
print(arry3[:3])
print(arry3[2:])
print(arry3[-3:-1])#倒数第三个元素到倒数第一个
for x in arry3[0:3]:
print(x)
#列表复制
print("----------列表复制","arry4-------------")
arry4 = ['1', '2', '3','4']
newarry4 = arry4[:]
newarry4two= arry4
print("arry4:")
print(arry4)
print("\nnewarry4 :")
print(newarry4)
print("\nnewarry4two :")
print(newarry4two)
arry4.append("arry4")
newarry4.append("new")
newarry4two.append("ddddd")
print("arry4:")
print(arry4)
print("\nnewarry4 :")
print(newarry4)
print("\nnewarry4two :")
print(newarry4two)
| false |
2b352b8bb78329976f0790e7a499a97e2d2d9dd2 | siawyoung/practice | /problems/zip-list.py | 1,328 | 4.125 | 4 | # Write a function that takes a singly linked list L, and reorders the elements of L to form a new list representing zip(L). Your function should use 0(1) additional storage. The only field you can change in a node is next.
# e.g. given a list 1 2 3 4 5, it should become 1 5 2 4 3
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
def print_all(self):
curr = self
while True:
print(curr)
if curr.next:
curr = curr.next
else:
break
def zip(node):
temp = node
temp1 = node.next
if not temp1:
return node
current_end = None
current_pointer = node
while True:
while True:
if current_pointer.next is current_end:
break
current_pointer = current_pointer.next
current_end = current_pointer
temp.next = current_end
current_end.next = temp1
if temp1.next is current_end:
temp1.next = None
break
temp = temp1
temp1 = temp1.next
current_pointer = temp
a = Node(1)
b = Node(2)
c = Node(3)
d = Node(4)
e = Node(5)
a.next = b
b.next = c
c.next = d
d.next = e
zip(a)
a.print_all() | true |
7c77a7a8c7c90c1f626f96f392f3a9e3e6a58b60 | siawyoung/practice | /problems/delete-single-linked-node.py | 674 | 4.15625 | 4 |
# Delete a node from a linked list, given only a reference to the node to be deleted.
# We can mimic a deletion by copying the value of the next node to the node to be deleted, before deleting the next node.
# not a true deletion
class LinkedListNode:
def __init__(self, value):
self.value = value
self.next = None
def __str__(self):
return str(self.value)
def delete_node(node):
if node.next:
_next = node.next.next
else:
_next = None
node = node.next
node.next = _next
a = LinkedListNode('A')
b = LinkedListNode('B')
c = LinkedListNode('C')
a.next = b
b.next = c
delete_node(b)
print(a)
print(b) | true |
05c6d092439df7574bfb7b265007007b42816154 | siawyoung/practice | /problems/reverse-words.py | 986 | 4.15625 | 4 |
# Code a function that receives a string composed by words separated by spaces and returns a string where words appear in the same order but than the original string, but every word is inverted.
# Example, for this input string
# @"the boy ran"
# the output would be
# @"eht yob nar"
# Tell the complexity of the solution.
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
return self.stack.pop()
def isEmpty(self):
return len(self.stack) == 0
def reverse_words(string):
stack = Stack()
output = []
for i in range(len(string)):
if string[i] == ' ':
while not stack.isEmpty():
output.append(stack.pop())
output.append(' ')
else:
stack.push(string[i])
while not stack.isEmpty():
output.append(stack.pop())
return ''.join(output)
print(reverse_words('the boy ran'))
| true |
9b73167d9095286071a4e5d2b9d61d1643ef874d | bluepine/topcoder | /cracking-the-coding-interview-python-master/3_5_myqueue.py | 1,147 | 4.34375 | 4 | #!/usr/bin/env python
"""
Implement a queue with two stacks in the MyQueue class.
This should never be used, though -- the deque data structure from the
standard library collections module should be used instead.
"""
class MyQueue(object):
def __init__(self):
self.first = []
self.second = []
def size(self):
return len(self.first) + len(self.second)
def add(self, number):
self.first.append(number)
def peek(self):
first = self.first
second = self.second
if len(second):
return second[-1]
while len(first):
second.append(first.pop())
return second[-1]
def remove(self):
first = self.first
second = self.second
if len(second):
return second.pop()
while len(first):
second.append(first.pop())
return second.pop()
def main():
queue = MyQueue()
queue.add(1)
queue.add(2)
queue.add(3)
print queue.size() # 3
print queue.peek() # 1
print queue.remove() # 1
print queue.peek() # 2
if __name__ == '__main__':
main()
| true |
b72125acc6f31cb0d2e9a8e1881137c5d6974ae4 | bluepine/topcoder | /algortihms_challenges-master/general/backwards_linked_list.py | 1,474 | 4.125 | 4 | """
Reverse linked list
Input: linked list
Output: reversed linked list
"""
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def __str__(self):
res = []
node = self.head
while node:
res.append(str(node.data))
node = node.next
return '->'.join(res)
def add(self, node):
if node is None:
return False
if self.head is None:
self.head = node
else:
current = self.head
while current.next:
current = current.next
current.next = node
def add_to_head(self, node):
if node is None:
return False
if self.head is None:
self.head = node
else:
node.next = self.head
self.head = node
def reverse(head):
reversed_list = LinkedList()
current = head
while current:
# make new node so you don't make reference to already
# existing node
reversed_list.add_to_head(Node(current.data))
current = current.next
return reversed_list
nodes = [Node("1"), Node("2"), Node("3"), Node("4"), Node("5"), Node("6")]
list = LinkedList()
for node in nodes:
list.add(node)
head = list.head
print list
reversed = reverse(list.head)
print reversed
| true |
ccb57c809f7dba7cca387727438fbe8631579269 | bluepine/topcoder | /algortihms_challenges-master/general/matrix.py | 1,706 | 4.21875 | 4 | """
1.7.
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and
column is set to 0
Idea:
a) Have an additional matrix and go trough all elements in MxN matrix and set zeroes
b) For each element you go trough - check if it is on a 'zero line' (has zero on
it's column or row - do AND operator and if it is zero - put that element
zero)
"""
def matrix_zero(matrix):
if matrix is None or len(matrix) < 1:
return False
m = len(matrix)
n = len(matrix[0])
init_zeros_x = []
init_zeros_y = []
for i in xrange(m):
for j in xrange(n):
# check if value is initially 0
if matrix[i][j] == 0:
if i not in init_zeros_x:
init_zeros_x.append(i)
if j not in init_zeros_y:
init_zeros_y.append(j)
elif i in init_zeros_x or j in init_zeros_y:
matrix[i][j] = 0
else:
column = [matrix[x][j] for x in xrange(i,m) ]
value_i = reduce(lambda x, y: x and y, column)
value_j = reduce(lambda x, y: x and y, matrix[i][j:])
value = value_i and value_j
if value == 0:
matrix[i][j] = 0
return matrix
matrix = [[1, 2, 1, 3, 2, 1, 1],
[3, 5, 0, 1, 5, 0, 1],
[2, 1, 4, 6, 1, 1, 2],
[5, 1, 1, 1, 0, 1, 1],
[1, 2, 2, 0, 1, 1, 0]]
result = [[1, 2, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[2, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]]
print "method result", matrix_zero(matrix)
print "expected result", result
| true |
8dd5870f0967b67a0ad2b81f71d521e6c6657e4d | bluepine/topcoder | /ctci-master/python/Chapter 1/Question1_3/ChapQ1.3.py | 1,529 | 4.125 | 4 | #Given two strings, write a method to decide if one is a permutation of the other.
# O(n^2)
def isPermutation(s1, s2):
if len(s1)!=len(s2):
return False
else:
for char in s1:
if s2.find(char)==-1:
return False
else:
s2.replace(char,"",1)
return True
# big O complexity depends on python list sort complexity, which should be better than O(n^2)
def isPermutationSort(s1,s2):
#sort both strings, check if they are equal
if len(s1)!=len(s2): return False
return sorted(s1) == sorted(s2)
#O(n)
#using a dict as a hash table to count occurences in s1, then comparing s2 with the dict
def isPermutationHash(s1,s2):
if len(s1) != len(s2):
return False
dic = {}
for char in s1:
dic[char] = dic.get(char, 0) + 1
for char in s2:
if dic.get(char,0) <= 0:
return False
else: dic[char] -= 1
return True
#testing
#permutation
postest1 = ["abcdefgh","abcdefhg"]
#not permutation
negtest2 = ["abcdefgh","gfsdgsdffsd"]
#not permutation
negtest3 = ["abcdefgh","gfsdgsdf"]
#list of all functions to test
funclist = [isPermutation,isPermutationSort,isPermutationHash]
for func in funclist:
print "Testing function " + str(func)
if func(postest1[0],postest1[1]):
print "Test 1 passed"
if not func(negtest2[0],negtest2[1]):
print "Test 2 passed"
if not func(negtest3[0],negtest3[1]):
print "Test 3 passed"
| true |
470543e4625aff4f2aeb99636a0880821f36f7ac | WaltXin/PythonProject | /Dijkstra_shortest_path_Heap/Dijkstra_shortest_path_Heap.py | 2,719 | 4.15625 | 4 | from collections import defaultdict
def push(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
shiftup(heap, 0, len(heap)-1)
def pop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
shiftdown(heap, 0)
return returnitem
return lastelt
# 'heap' is a heap at all indices >= startpos, except possibly for pos. pos
# is the index of a leaf with a possibly out-of-order value. Restore the
# heap invariant.
def shiftup(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if newitem < parent:
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def shiftdown(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2*pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not heap[childpos] < heap[rightpos]:
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2*pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
shiftup(heap, startpos, pos)
def dijkstra(edges, f, t):
g = defaultdict(list)
for l,r,c in edges:
g[l].append((c,r))
q, seen = [(0,f,())], set()
while q:
(cost,v1,path) = pop(q)
if v1 not in seen:
seen.add(v1)
path = (v1, path)
if v1 == t: return (cost, path)
for c, v2 in g.get(v1, ()):
if v2 not in seen:
push(q, (cost+c, v2, path))
return float("inf")
if __name__ == "__main__":
edges = [
("A", "B", 7),
("A", "D", 5),
("B", "C", 8),
("B", "D", 9),
("B", "E", 7),
("C", "E", 5),
("D", "E", 15),
("D", "F", 6),
("E", "F", 8),
("E", "G", 9),
("F", "G", 11)
]
print ("=== Dijkstra ===")
print (edges)
print ("A -> E:")
print (dijkstra(edges, "A", "E"))
print ("F -> G:")
print (dijkstra(edges, "F", "G")) | true |
33b0b54194338915d510c2b76cf0ada76ac053a6 | digvijay-16cs013/FSDP2019 | /Day_03/weeks.py | 429 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 9 15:56:28 2019
@author: Administrator
"""
days_of_week = input('Enter days of week => ') .split(', ')
weeks = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
for index, day in enumerate(weeks):
if day not in days_of_week:
days_of_week.insert(index, day)
days_of_week = tuple(days_of_week)
print(days_of_week)
| true |
4042f285972f9bdf7d7d6c24cbbe8ae4cfe7baaa | digvijay-16cs013/FSDP2019 | /Day_11/operations_numpy.py | 1,309 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 21 23:29:54 2019
@author: Administrator
"""
# importing Counter from collections module
from collections import Counter
# importing numerical python (numpy) abbreviated as np
import numpy as np
# some values
values = np.array([13, 18, 13, 14, 13, 16, 14, 21, 13])
# calculate mean or average of values
mean = np.mean(values)
# calculate median of values
median = np.median(values)
# create a range of values form 21 - 13 using numpy
range_of_values = np.arange(21, 13, -1)
# getting count of each values from the list of "values" and converting the result in the form of dictionary
count = dict(Counter(values))
# finding the maximum occrances of a value
maximum = max(count.values())
# to check printing the value of max ocurrances
#print(count)
# loop to find out the mode of "values"(Number which occurs most frequently)
for key, value in count.items():
# to check if number has maximum ocurrances
if maximum == value:
# set mode = value(which is represented by key)
mode = key
# getting out of the loop once we get the most frequent value
break
# print what we calculated so far
print('Mean =', mean)
print('Median =', median)
print('Mode =', mode)
print('Range =', range_of_values) | true |
35e551aa21266be0b9af0e54b2b205799e5b9b32 | digvijay-16cs013/FSDP2019 | /Day_06/odd_product.py | 332 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 14 14:25:35 2019
@author: Administrator
"""
from functools import reduce
numbers = list(map(int, input('Enter space separated integers : ').split()))
product_odd = reduce(lambda x, y : x * y, list(filter(lambda x: x % 2 != 0, numbers)))
print('product of odd numbers :', product_odd) | true |
9346fd05be19a27fec2239194d70c986cfc3db5e | digvijay-16cs013/FSDP2019 | /Day_01/string.py | 401 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 7 17:44:40 2019
@author: Administrator
"""
# name from user
name = input('Enter first and last name with a space between them : ')
# finding index of space using find method
index = name.find(' ')
# taking first Name and last name separately
first_name = name[:index]
last_name = name[index+1:]
# Printing names
print(last_name + ' ' + first_name)
| true |
689f0134064076fa90882d24fc5af086a42a8978 | digvijay-16cs013/FSDP2019 | /Day_05/regex1.py | 402 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 11 16:04:05 2019
@author: Administrator
"""
# regular expression number
import re
# scan number
float_number = input('Enter anything to check if it is floating point number : ')
# to check match
if re.match(r'^[+-]?\d*\.\d+$', float_number):
# if expression found
print(True)
else:
# if expression not found
print(False) | true |
ad3edf6b16e89cb83c59c1a5c25a03306de64efc | emilianoNM/Tecnicas3 | /Reposiciones/Cuevas Cuauhtle Luis Fernando/Reposicion 13_08_2018/TabladeMultiplicar.py | 242 | 4.125 | 4 | #Este programa crea una tabla de multiplicar con un numero que introduzcas
Numero = int(input("Introduzca el numero que quiera generar la tabla"))
# use for loop to iterate 10 times
for i in range(1,11):
print(Numero,'x',i,'=',Numero*i)
| false |
fe615e7872db45b6fb309c9383f661d9dd1ccb9e | emilianoNM/Tecnicas3 | /RepoEderGLEZ/cumpleaños.py | 304 | 4.125 | 4 |
# coding: utf-8
# In[ ]:
def main():
a_curso = input ("Ingresa el anio en curso: ")
for i in range (3):
nombre = raw_input ("Nombre de la persona: ")
nacimiento = input ("Anio de nacimiento: ")
print nombre, "cumple", (a_curso - nacimiento), "anios en el", a_curso
| false |
98fef15129c66c8a64de2cd051605a7405a202a5 | ElijahMcKay/Blockchain | /standupQ.py | 1,399 | 4.21875 | 4 | """
You've been hired to write the software to count the votes for a local election.
Write a function `countVotes` that receives an array of (unique) names, each one
representing a vote for that person. Your function should return the name of the
winner of the election. In the case of a tie, the person whose name comes last
alphabetically wins the election (a dumb rule to be sure, but the voters don't
need to know).
Example:
```
input: ['veronica', 'mary', 'alex', 'james', 'mary', 'michael', 'alex', 'michael'];
expected output: 'michael'
```
Analyze the time and space complexity of your solution.
"""
inputList = ['veronica', 'mary', 'alex', 'james', 'mary', 'michael', 'alex', 'michael']
def voter_count(array):
winner = 'a'
hashmap = {}
votes = 0
max_votes = []
for name in array:
if name not in hashmap:
hashmap[name] = 1
else:
hashmap[name] += 1
if hashmap[name] > votes:
max_votes = [name]
votes = hashmap[name]
# print('greater than', max_votes)
elif hashmap[name] == votes:
max_votes.append(name)
# print('equals', max_votes)
if len(max_votes) == 1:
winner = max_votes[0]
else:
for name in max_votes:
if name > winner:
winner = name
return winner
print(voter_count(inputList)) | true |
4c0c8b1478e505dd5734d3e902bea1d520dd80bc | paulonteri/google-get-ahead-africa | /exercises/longest_path_in_tree/longest_path_in_tree.py | 1,489 | 4.21875 | 4 | """
Longest Path in Tree:
Write a function that computes the length of the longest path of consecutive integers in a tree.
A node in the tree has a value and a set of children nodes. A tree has no cycles and each node has exactly one parent.
A path where each node has a value 1 greater than its parent is a path of consecutive integers (e.g. 1,2,3 not 1,3,5).
A few things to clarify:
Integers are all positive
Integers appear only once in the tree
"""
class Tree:
def __init__(self, value, *children):
self.value = value
self.children = children
def longest_path_helper(tree, parent_value, curr_length, longest_length):
if not tree:
return longest_length
if tree.value == parent_value + 1:
curr_length += 1
else:
curr_length = 1
longest_length = max(longest_length, curr_length)
for child in tree.children:
longest_length = max(longest_length, longest_path_helper(
child, tree.value, curr_length, longest_length)
)
return longest_length
def longest_path(tree):
if not tree:
return
return longest_path_helper(tree, float('-inf'), 0, 0)
assert longest_path(
Tree(1,
Tree(2,
Tree(4)),
Tree(3))
) == 2
assert longest_path(
Tree(5,
Tree(6),
Tree(7,
Tree(8,
Tree(9,
Tree(15),
Tree(10))),
Tree(12)))
) == 4
| true |
a099cc0e7d05dc81ab396016072ad08e25ab60d3 | attorneyatlawl/Codewars | /Python/Tribonacci_Sequence.py | 282 | 4.1875 | 4 | ''' Tribonacci sequence'''
def tribonacci(signature, n):
while len(signature) < n:
signature.append(sum(signature[-3:]))
return signature[:n]
# Other
def tribonacci(signature, n):
res = signature[:n]
for i in range(n - 3): res.append(sum(res[-3:]))
return res | false |
3eb607c7fc1499c0d2aa9d28e25c8a32549cab54 | celeritas17/python_puzzles | /is_rotation.py | 634 | 4.25 | 4 | from sys import argv, exit
# is_rotation: Returns True if string t is a rotation of string s
# (e.g., 'llohe' is a rotation of 'hello').
def is_rotation(s, t):
if len(s) != len(t):
return False
if not s[0] in t:
return False
count_length = i = 0
t_len = len(t)
while t[i] != s[0]:
i += 1
while count_length < t_len and s[count_length] == t[i%t_len]:
count_length += 1
i += 1
if count_length == t_len:
return True
return False
if len(argv) < 3:
print "Usage: %s <string> <string>\n" % argv[0]
exit(1)
print "%r is%s a rotation of %r\n" % (argv[2], "" if is_rotation(argv[1], argv[2]) else " not", argv[1])
| true |
5fb2788df1a6c3db25a31bfb310813353e6f31db | tjshaffer21/katas | /project_euler/python/p16.py | 575 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Problem 16 - Power digit sum
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?
"""
def pow_sum(x, n):
""" Calculate the sum of the power.
Parameters
x : int : The base integer.
n : int : The power.
Return
int : The sum.
"""
ps = x ** n
s = 0
while ps > 0:
s += ps%10
ps = ps // 10
return s
print("Result: " + str(pow_sum(2, 1000))) # 1366 | true |
8fe165a793c2598d567fb11e5b55d238a1e7d6b1 | UWPCE-PythonCert-ClassRepos/Sp2018-Accelerated | /students/Ruohan/lesson03/list_lab.py | 2,570 | 4.15625 | 4 | #! /usr/bin/env python3
'''Exercise about list'''
#series 1
#Create a list that contains “Apples”, “Pears”, “Oranges” and “Peaches”.
#Display the list
print('============= series 1 ===============')
list_fruit = ['Apples', 'Pears', 'Oranges', 'Peaches']
print(list_fruit)
#Ask the user for another fruit and add it to the end of the list.
#Display the list.
item = input('Enter another fruit: ')
list_fruit.append(item)
print(list_fruit)
#Ask the user for a number and display the number back to the user
#and the fruit corresponding to that number
x = int(input('Enter the number: '))
print(x, list_fruit[x-1])
#Add another fruit to the beginning of the list using “+” and display the list.
item_new = input('Enter another fruit: ')
list_fruit_new = [item_new] + list_fruit
print(list_fruit_new)
#Add another fruit to the beginning of the list using insert() and display the list.
item = input('Enter another fruit: ')
list_fruit_new.insert(0, item)
print('====original list: ', list_fruit_new, '=====')
#Display all the fruits that begin with “P”, using a for loop.
for ft in list_fruit_new:
if ft[0] == 'P':
print(ft)
#Series 2
#Display the list.
print('============= series 2 ===============')
list_fruit_2 = list_fruit_new[:]
print(list_fruit_2)
#Remove the last fruit from the list and display the list
list_fruit_2.pop()
print(list_fruit_2)
#Ask the user for a fruit to delete, find it and delete it.
tgt = input('Enter the fruit you want to delete: ')
idx = list_fruit_2.index(tgt)
list_fruit_2.pop(idx)
print(list_fruit_2)
#Series 3
#Ask the user if he likes the fruit for each fruit in the list and display the list
print('============= series 3 ===============')
list_fruit_3 = list_fruit_new[:]
for fruit in list_fruit_new:
y = input('Do you likes {} ? '.format(fruit.lower()))
while True:
if y == 'no':
list_fruit_3.pop(list_fruit_3.index(fruit))
break
if y == 'yes':
break
else:
y = input("invalid argument, please enter 'yes'or 'no': ")
print(list_fruit_3)
#Series 4
#Make a copy of the list and reverse the letters in each fruit in the copy.
print('============= series 4 ===============')
list_fruit_4 = []
for fruit in list_fruit_new:
fruit = fruit[::-1]
list_fruit_4.append(fruit)
print(list_fruit_4)
#Delete the last item of the original list. Display the original list and the copy.
list_fruit_new.pop()
list_fruit_4 = list_fruit_new[:]
print('original list: ', list_fruit_new)
print('new list: ', list_fruit_4)
| true |
cffa371c3a06d349d8f638195dc9c255abb5c47e | UWPCE-PythonCert-ClassRepos/Sp2018-Accelerated | /students/tammyd/lesson03/strformat_lab.py | 2,226 | 4.375 | 4 | #!/usr/bin/env python3
'''
String Formatting Lab Exercise
'''
#take the following four element tuple: ( 2, 123.4567, 10000, 12345.67)
t = (2, 123.4567, 10000, 12345.67)
#print("My string =", t)
print("Goal: file_002 : 123.46, 1.00e+04, 1.23e+04")
print()
#Task one
#and produce: 'file_002 : 123.46, 1.00e+04, 1.23e+04'
print("Task one")
print("This is file_{:03d} : {:8.2f}, {:.2e}, {:.3g}".format(2, 123.4567, 10000, 12345.67))
print()
#Task Two
#Using your results from Task One, repeat the exercise using an alternate type of format string
print("Task two")
print(f"This is file_{t[0]:003d}: {t[1]:.2f}, {t[2]:.2e}, {t[3]:.3g}.".format(t))
print()
#Task Three
#Dynamically Building up Format Strings
#Rewrite: "the 3 numbers are: {:d}, {:d}, {:d}".format(1,2,3)
print("Task three")
t2 = (1, 2, 3, 4, 5, 6)
l = len(t2)
formatter = "The {} numbers are: ".format(l)
print(formatter + ", ".join(['{}']*l).format(*t2))
#Put your code in a function
def formatter(in_tuple):
l = len(in_tuple)
formatter = "The {} numbers are: ".format(l)
formatter_arbitrary = (formatter + ", ".join(['{}']*l).format(*in_tuple))
return formatter_arbitrary
print()
print("Task three in function")
print(formatter(t2))
print()
#Task Four
#use index numbers to specify positions
print("Task four")
print("Output: '02 27 2017 04 30'")
t4 = (4, 30, 2017, 2, 27)
print("{3:02d}, {4}, {2}, {0:02d}, {1}".format(*t4))
#Task Five
lst = ['oranges', 1.3, 'lemons', 1.1]
print(f"The weight of an {lst[0][:-1]} is {lst[1]} and the weight of a {lst[2][:-1]} is {lst[3]}.")
print(f"The weight of an {lst[0][:-1].upper()} is {lst[1]*1.2} and the weight of a {lst[2][:-1].upper()} is {lst[3]*1.2}.")
#Task six
print('{:20}{:10}{:20}{:8}'.format('First', '$99.01', 'Second', '$88.09'))
data = [('abc', 10, 100),
('def', 20, 2000),
('hij', 30, 30000),
('klm', 40, 400000),
('mno', 50, 5000000),
('pqr', 60, 60000000)
]
for name, age, cost in data:
table = f'Name: {name:<10} Age: {age:<10} Cost: {cost:<10,.2f}'
print(table)
#Bonus
#print the tuple in columns that are 5 charaters wide
t10 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(('{:<5}'*len(t10)).format(*t10))
| false |
daeba6dd81960befa2f59d9d98d9b930a3ff923e | UWPCE-PythonCert-ClassRepos/Sp2018-Accelerated | /students/aravichander/lesson03/strformat_lab.py | 1,052 | 4.1875 | 4 | tuple1 = (2,123.4567,10000, 12345.67)
#print(type(tuple1))
#Spent some time trying to understand the syntax of the string formats
# print("First element of the tuple is: file_{:03}".format(tuple1[0]))
# print("Second element of the tuple is: {0:.2f}".format(tuple1[1]))
# print("Second element of the tuple is: {1:.2f}".format(tuple1))
# print("Third element of the tuple is: {0:.2e}".format(tuple1[2]))
# print("Fourth element of the tuple is: {0:.3g}".format(tuple1[3]))
#print("{:03},{0:.2f},{0:.2e},{0:.2e}".format(tuple1[0],tuple1[1],tuple1[2],tuple1[3]))
#print("file_{:03},{:.2f},{:.2e},{:.3g}".format(tuple1[0],tuple1[1],tuple1[2],tuple1[3]))
#Task Three - not the best formatting but the essence is there!
# def multipletuple(*numbers):
# listlen = len(numbers)
# return "The",listlen,"numbers are {0}".format(numbers)
# print(multipletuple(1,2))
#Task Four
tuple3 = (4, 30, 2017, 2, 27)
#print("{0[3]},{0[4]},{0[2]},{0[0]},{0[1]}".format(tuple3))
#Task Five - don't have Python 3.6
a = 5
b = 10
#f"The sum is: {a+b}."
#Task Six
| true |
2869bbf863d02a4c45295e841b3b6a0ee524eb1e | StefaRueRome/LaboratorioVCSRemoto | /main.py | 433 | 4.15625 | 4 | print("Solución de una ecuación cuadrática")
a=int(input("Ingrese el primer valor:"))
b=int(input("Ingrese el segundo valor:"))
c=int(input("Ingrese el tercer valor:"))
d=(((b*b)-(4*a*c))**1/2)
x1=(((-1*b)+(d**1/2))/2*a)
x2=(((-1*b)-(d**1/2))/2*a)
if d>0:
print("La solución positiva es:",x1,"y la solución negativa es:",x2)
else:
if d==0:
(-1*b)/2*a
else:
if d<0:
print("No existe solución en los números reales")
| false |
e7ac3c7f1d793a46b3f9c3645cb994102c877344 | rayt579/epi_hackathon | /ch16/warmup.py | 1,005 | 4.125 | 4 | '''
Find the maximum sum of all subarrays of a given array of integers
'''
def kadane_algorithm(A):
current_max = A[0]
global_max = A[0]
for i in range(1, len(A)):
current_max = max(A[i], current_max + A[i])
global_max = max(global_max, current_max)
return global_max
import itertools
def find_maximum_subarray(A):
min_sum = max_sum = 0
for running_sum in itertools.accumulate(A):
min_sum = min(min_sum, running_sum)
max_sum = max(max_sum, running_sum - min_sum)
return max_sum
print('Kadane for array: {}'.format(kadane_algorithm([-2, 3, 2, -1])))
print('Kadane for all negative: {}'.format(kadane_algorithm([-2, -3, -2, -1])))
print('Kadane for all positive: {}'.format(kadane_algorithm([2, 3, 2, 1])))
print('MSS for array: {}'.format(find_maximum_subarray([-2, 3, 2, -1])))
print('MSS for all negative: {}'.format(find_maximum_subarray([-2, -3, -2, -1])))
print('MSS for all positive: {}'.format(find_maximum_subarray([2, 3, 2, 1])))
| false |
0d57a53bcb7165dc4d122e213a2a43e9fb208f4b | spoonsandhangers/tablesTablesTables | /table1.py | 1,454 | 4.375 | 4 | """
Creating tables in Tkinter.
There is no table widget but we can use a function from ttk
called treeview.
You must import ttk from tkinter
Then add a Frame to the root window.
Create a Treeview object with the correct number of columns (see other attributes)
Create a list of headings for the columns
iterate through the heading list adding them to the Treeview object
use the insert function to insert more rows when necessary.
"""
from tkinter import *
from tkinter import ttk
root = Tk()
root.title("tables tables tables")
frame = Frame(root)
frame.pack(pady=20)
# sets up the table with the number of columns required
staff = ttk.Treeview(frame, columns=(1,2,3), show='headings', height=8)
staff.pack(side=LEFT)
# list of column headings for the table
myheadings = ["name", "staff id", "Salary"]
# a new type of for loop.
# this uses the enumerate function to produce a count as
# well as iterating through the myheadings list
# count starts at 1 and increments on each loop
# head is set to each value in turn in the myheadings list.
for count, head in enumerate(myheadings, 1):
staff.heading(count, text=head) # this line adds the item in myheading to the next column in the staff table
# this inserts the values shown into a row of the staff table
staff.insert(parent='', index=0, iid=0, values=("sarah", "sj2256", 2000))
# settings for the table
style = ttk.Style()
style.theme_use("default")
style.map("Treeview")
root.mainloop()
| true |
f30401120620f23c26b3a62a26f20d95253512cd | victorrrp/python-avancado | /python 3/aula18_poo/meta.py | 854 | 4.28125 | 4 | '''
EM PYTHON TUDO É UM OBJETO: incluindo classes.
Metaclasses são as 'classes' que criam classes.
type é uma metaclasse??
'''
class Meta(type): #Criando uma metaclasse
def __new__(mcs, name, bases, namespace):
if name == 'A':
return type.__new__(mcs, name, bases, namespace)
if 'b_fala' not in namespace:
print(f'Oi, voce precisa criar o metodo b_fala em {name}')
else:
if not callable(namespace['b_fala']):
print('b_fala precisa ser um metodo, não um atributo. ')
return type.__new__(mcs, name, bases, namespace)
class A(metaclass=Meta): #usando a metaclasse
def fala(self):
self.b_fala()
class B(A):
teste = 'Valor'
def b_fala(self):
print('Oi')
def sei_la(self):
pass
| false |
78a1be7aaefdd04084cc106ac164e29be1a6c79a | victorrrp/python-avancado | /python 3/aula13_poo/app.py | 618 | 4.21875 | 4 | '''
Polimorfismo de sobreposição: é o principio que permite que classes derivadas de uma mesma
superclasse tenham métodos iguais (de mesma assinatura) mas comportamentos
diferentes.
Mesma assinatura = Mesma quatidade e tipo de parâmetros
'''
#exemplo de polimorfismo
from abc import ABC, abstractmethod
class A(ABC):
@abstractmethod
def fala(self, msg): pass
class B(A):
def fala(self, msg):
print(f'B está falando {msg}')
class C(A):
def fala(self, msg):
print(f'C está falando {msg}')
b = B()
c = C()
b.fala('UM ASSUNTO')
c.fala('OUTRO ASSUNTO') | false |
e64e382a1de818cf5d47d3e4af81e0395c5bf769 | anuj0721/100-days-of-code | /code/python/day-1/FactorialRecursion.py | 246 | 4.1875 | 4 | def fact(n):
if (n < 0):
return "not available/exist."
elif (n == 1 or n == 0):
return 1
else:
return n*fact(n-1)
num = int(input("Enter a number: "))
f = fact(num)
print("factorial of",num,"is ",f)
| true |
84e1af8bef6874e22dc74fd31f75913736989c88 | anuj0721/100-days-of-code | /code/python/day-52/minimum_element_of_main_list_that_is_max_of_other_list.py | 1,084 | 4.1875 | 4 | main_list = [number for number in input("Enter Main list values separated by space: ").split()]
list_i = int(input("How many other list you want to enter: "))
for value in range(1,list_i+1):
globals()['my_list%s' %value] = [number for number in input("Enter values separated by space: ").split()]
#find maximum element from all other list.
max_value = int(my_list1[0])
for i in range(1,list_i+1):
for value in globals()['my_list%s' %i]:
if int(value) > max_value:
max_value = int(value)
#create a list from main_list that contains elements that is greater than from all other list.
min_list = []
for value in main_list:
if int(value) > int(max_value):
min_list.append(value)
# Now find the minimu element in newley created list(it contains elements from main_list that is greater than from all other list.)
min_value = int(min_list[0])
for value in min_list:
if int(value) < int(min_value):
min_value = int(value)
print("Minimum number that is greater than all other list, in main list is {}.".format(min_value))
| true |
9f45e0268108c93f6e2b3fb5d323943300db1617 | anuj0721/100-days-of-code | /code/python/day-60/print_stars_in_D_shape.py | 491 | 4.3125 | 4 | rows = int(input("How many rows?: "))
if rows <= 0:
raise ValueError("Rows can not be negative or zero")
cols = int(input("How many columns?: "))
if cols <= 0:
raise ValueError("Columns can not be negative or zero")
for row in range(0,rows):
for col in range(0,cols):
if (((row != 0 and row != rows-1) and (col == 0 or col == cols-1)) or ((row == 0 or row == rows-1) and col < cols-1)):
print("*",end="")
else:
print(end=" ")
print()
| true |
ba423af0aeed7a70d4a96bc3e766042c7f3a0569 | anuj0721/100-days-of-code | /code/python/day-12/FirstNevenNaturalNumbersAndInReverseOrder.py | 232 | 4.21875 | 4 | n = int(input("How many even natural numbers you want?: "))
for i in range(1,((2*n)+1)):
if i%2==0:
print(i,end=" ")
print()
print("In Reverse Order-")
for i in range(2*n,0,-1):
if i%2==0:
print(i,end=" ")
| false |
add852bf6dbf84eb3087e565e6b2f2f2229369c6 | t0futac0/ICTPRG-Python | /Selection/selectionQ2.py | 331 | 4.125 | 4 | ## Write a program that asks the user for their year of birth,
## Checks if they are of legal drinking age
## and tells the user to come into the bar.
age_verification = int(input("What is your year of birth? "))
if age_verification >= 2002:
print("Do a U-Turn!")
else:
print("Please come straight through to the bar!") | true |
d48fff9caca448449499ef613502d239c110ef09 | t0futac0/ICTPRG-Python | /String Manipulation/Python String Manipulation.py | 349 | 4.46875 | 4 | #Python String Manipulation
#Write a program that asks the user for their full name, splits it up into words and outputs each word on a new line.
#For names with 2 words (eg, 'Fred Frank') this would output Fred, then frank on two lines.
full_name = input("Please enter your full name ")
name_list = full_name.split()
for x in name_list:
print(x) | true |
99cd74851c03956263024aa1aa6003a492698a9b | trentwoodbury/anagram_finder | /AnagramChecker.py | 1,012 | 4.21875 | 4 | from collections import Counter
class AnagramChecker:
'''
This is a class that is able to efficiently check if two words are anagrams.
'''
def __init__(self):
self.words_are_anagrams = None
def check_if_words_are_anagram(self, word_1, word_2):
'''
Checks if word_1 and word_2 are anagrams. Returns True of False.
INPUT
word_1, word_2: Counter(word). They look like e.g. {'a':3, 'b':1, 'n':2}
OUTPUT
True/False: whether words are anagrams.
'''
# If words have different number of unique letters, they aren't anagrams
if len(word_1.items()) != len(word_2.items()):
return False
else:
for letter, frequency in word_1.items():
try:
if word_2[letter] == frequency:
pass
else:
return False
except:
return False
return True
| true |
45742e4a60ab176f29b0fa51064e06ddad195d22 | cifpfbmoll/practica-6-python-klz0 | /P6E2_sgonzalez.py | 538 | 4.25 | 4 | # Práctica 6 - EJERCICIOS WHILE Y LISTAS
# P6E2_sgonzalez
# Escribe un programa que te pida números y los guarde en una lista.
# Para terminar de introducir número, simplemente escribe "Salir".
# El programa termina escribiendo la lista de números.
lista = []
numero = int(input("Escribe un número "))
print("Cuando hayas acabado de escribir números, escribe salir \
para finalizar")
while (numero != "salir"):
lista.append(numero)
numero = input("Escribe otro numero ")
print("Los números que has escrito son ", lista)
| false |
b94dac47b5f8622d93785ca4c2ec9930135b524e | lee-shun/learn_py | /section1/params_fun.py | 1,741 | 4.15625 | 4 | #位置参数
def power(x):
return x*x
print('power={}'.format(power(5)))
#默认参数
def power2(x, n=2):
s = 1
for i in range(n):
i += 1
s = s*x
return s
print('power2={}'.format(power2(6)))
#默认参数的坑
def add_end(L=[]):
L.append('endd')
return L
print(add_end())
"""
当函数定义的时候,动态语言已经将L指向了“[]”这块空间,下一次调用
的时候,他不会重新计算所调用的函数,只是使用最开始函数所开辟的,
如果这里的内容被更更改了的话,下一次调用就会使用更改后的值::
动态语言!!!!!!
#所以,默认参数需要指向不变数值
def add_end(L=None):
if L is None:
L = []
L.append('END')
return L
"""
print(add_end())
#可变参数
#组装成为一个tuple
def cal_sum(*number):
s = 0
for n in number:
s = s+n
return s
print(cal_sum(1, 1, 1, 22, 3))
# 如果已经有一个lisst或者tuple,则可以拆开
l1 = [1, 1, 2, 4, 5, ]
print(cal_sum(*l1))
#关键字参数-->组装成为dict
def person(name, **kw):
print("naaaame:", name, "other:", kw)
person('Adam', gender='M', job='Engineer')
#命名关键字参数
def person2(name,*,city,job):
print(name,city,job)
person2('lee',city='beijing',job='hot')
#参数组合
def f1(a,b,c=0,*args,v,**kw):
#必选参数、默认参数、可变参数、命名关键字参数以及关键字参数
print('必选参数a={},b={}'.format(a,b))
print('默认参数c={}'.format(c))
print('可变参数args={}'.format(args))
print('命名关键字参数v={}'.format(v))
print('关键字参数kw={}'.format(kw))
f1(1,2,3,6,7,8,v=9,kw1=10,kw2='12')
| false |
c2e2504487ef0213246eed2e75d3a1a76ed5aaa8 | Alexey-Ushakov/practice | /str_tuple_list_dict_set/str.py | 1,839 | 4.21875 | 4 | a = "hello world" # Это строка
print(len(a)) # len это длинна строки
b = "I have Fun"
print(a+b) # Конотация соединение строк так как нет пробела то соединяет слитно
print(a*3) # Умножение, повторяет строку столько сколькон ам надо раз
# Срезы если нам нужно что то взять из строки
print(a[:5]) # В квадратных скобках указываем через двоеточие Start:Stop:Step
print(a[0:11:2])
print(a[-1]) # Индексы также начинаються с обратной стороны со знаком минус
print(a[-1::-1]) # Таким нехитрым способом мы можем вернуть обратную строку
# Методы строк
print(a.title()) # Все слова будут с большой буквы
a.upper() # все буквы в строке будут большими
a = "+3/4 + 4/8"
print(a.find("+")) # вернет нам индекс найденного Первого Элемента в строке
print(a.find("+", 3)) # если нужен второй элемент то указываем с какого элемента начать поиск
name = "Alexey"
last_name = "Yshakov"
age = 35
print("Walcome " + name + " " + last_name + "!") # Запись строки с подстановкой переменных через конатацию
print("Walcome {} {}!".format(name, last_name)) # Используем метод .format
print("Walcome {1} {0}!".format(name, last_name)) # Используя метод формат и перестановка переменных
print(f"Walcome {name} {last_name}!") # Использование f строки
| false |
d071703773d8586c8f9547d4397f05f179f7e862 | jttyeung/hackbright | /cs-data-struct-2/sorting.py | 2,247 | 4.4375 | 4 | #Sorting
def bubble_sort(lst):
"""Returns a sorted list using a optimized bubble sort algorithm
i.e. using a variable to track if there hasn't been a swap.
>>> bubble_sort([3, 5, 7, 2, 4, 1])
[1, 2, 3, 4, 5, 7]
"""
sorted_list = []
for i in range(len(lst) - 1):
for j in range(len(lst) - 1 - i):
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
return lst
# i = 0, 1, 2, 3, 4, 5
# i range = 0, 5
# j = 0, 1, 2, 3, 4, 5; 0, 1, 2, 3, 4; 0, 1, 2, 3; 0, 1, 2; 0, 1
# j range = 0, 5
def merge_lists(list1, list2):
"""Given two sorted lists of integers, returns a single sorted list
containing all integers in the input lists.
>>> merge_lists([1, 3, 9], [4, 7, 11])
[1, 3, 4, 7, 9, 11]
"""
merged_list = []
while len(list1) > 0 or len(list2) > 0:
if list1 == []:
merged_list.append(list2.pop(0))
elif list2 == []:
merged_list.append(list1.pop(0))
elif list1[0] <= list2[0]:
merged_list.append(list1.pop(0))
else:
merged_list.append(list2.pop(0))
return merged_list
# range 0, 3
# 1 < 4; [1]
##########ADVANCED##########
def merge_sort(lst):
"""
Given a list, returns a sorted version of that list.
Finish the merge sort algorithm by writing another function that takes in a
single unsorted list of integers and uses recursion and the 'merge_lists'
function you already wrote to return a new sorted list containing all
integers from the input list. In other words, the new function should sort
a list using merge_lists and recursion.
>>> merge_sort([6, 2, 3, 9, 0, 1])
[0, 1, 2, 3, 6, 9]
"""
if len(lst) == 1:
return lst
half = int(len(lst)/2)
list1 = merge_sort(lst[:half])
list2 = merge_sort(lst[half:])
return merge_lists(list1, list2)
#####################################################################
# END OF ASSIGNMENT: You can ignore everything below.
if __name__ == "__main__":
import doctest
print
result = doctest.testmod()
if not result.failed:
print "ALL TESTS PASSED. GOOD WORK!"
print
| true |
011419b7055a1fcb8738998c5cd373eb115eb824 | wchen308/practice_algo | /largest_factor.py | 234 | 4.25 | 4 | import math
def largest_factor(n):
"""
Return the largest factor of n that is smaller than n
"""
div = 2
while div <= math.sqrt(n):
if n % div == 0:
return n / div
else:
div += 1
return 1
print(largest_factor(13)) | true |
36058b7dcd271f8672f7265e559935c47c065d7d | Flooorent/review | /cs/leetcode/array/merge_intervals.py | 1,244 | 4.125 | 4 | """
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
"""
def solution(intervals):
"""
time complexity: O(n * log(n)) (sort)
space complexity: O(1)
- l'output ne compte pas
- le sort peut se faire en O(1)
"""
sorted_intervals = sorted(intervals, key=lambda interval: interval[0])
output = []
for interval in sorted_intervals:
if not output or interval[0] > output[-1][1]:
output.append(interval)
else:
output[-1][1] = max(output[-1][1], interval[1])
return output
input1 = [[1, 3], [2, 6], [8, 10], [15, 18]]
output1 = [[1, 6], [8, 10], [15, 18]]
input2 = [[1, 4], [4, 5]]
output2 = [[1, 5]]
input3 = [[1, 3], [8, 10], [2, 6]]
output3 = [[1, 6], [8, 10]]
input4 = [[2, 3], [8, 10], [1, 11]]
output4 = [[1, 11]]
assert(solution(input1) == output1)
assert(solution(input2) == output2)
assert(solution(input3) == output3)
assert(solution(input4) == output4)
| true |
f76fbc46587b2c5c14f7eefcbe1a1f5da3218f05 | khcal1/Python-Basics | /Dinner Party.py | 1,649 | 4.65625 | 5 | '''This program displays the uses of List
Start by inviting three people to a dinner party'''
import os
import sys
import random
guest_list = ['Socrates', 'King Tutt', 'Bas']
for guest in guest_list:
print("{}, Welcome to the party.".format(guest))
'''One person cannot make it to the party.
Delete that person fromt he list and make a new one
inviting someone else and reprint the list'''
print("\nBas cannot make it to the party.\n")
guest_list.remove('Bas')
guest_list.append('Rihanna')
for guest in guest_list:
print("{}, Welcome to the party.".format(guest))
#A bigger dinner table was found. Invite three more guests to the party
guest_list.append('Papa Johns')
guest_list.insert(2,'Judy')
guest_list.insert(3,'Khalil')
print("\n")
for guest in guest_list:
print("{}, Welcome to the party.".format(guest))
'''You just found out you can only invite two guest.
Print a message that apologizes to the guests you cannot invite
while using the pop method to remove the guests from the list telling them they cannot come.
After you are done empty the list and print it'''
print('\n')
uninvited = guest_list.pop()
print("Sorry {}, you are not invited".format(uninvited))
uninvited = guest_list.pop()
print("Sorry {}, you are not invited".format(uninvited))
uninvited = guest_list.pop()
print("Sorry {}, you are not invited".format(uninvited))
uninvited = guest_list.pop()
print("Sorry {}, you are not invited".format(uninvited))
print("\n")
for guest in guest_list:
print("{}, you are still invited.".format(guest))
print("\n")
guest_list.remove('Socrates')
guest_list.remove('King Tutt')
print(guest_list)
| true |
3beea4e5175b907e8ce2e5c5f0e84b6434ba8a97 | jbrandes/PythonPLCLogic | /plc.py | 733 | 4.34375 | 4 |
def AND(IN1, IN2):
if IN1 == "on" and IN2 == "on":
print("motor is on")
else:
print("motor is off")
def NOT(IN1, IN2):
if IN1 == "on":
print("motor is off")
else:
print("motor is on")
def OR(IN1, IN2):
if IN1 or IN2 == "on":
print("motor is on")
else:
print("motor is off")
function = input("Which function would you like to use? AND, OR, NOT ")
IN1 = input("What is your first action? on or off? ")
IN2 = input("What is your second action? on or off ")
print(IN1 + " " + IN2)
if function == "AND":
AND(IN1, IN2)
if function == "OR":
OR(IN1, IN2)
if function == "NOT":
NOT(IN1, IN2)
| false |
3866457894ea4ef4cc1586c71fead89ff192a3e6 | pranaysapkale007/Python | /Basic_Python_Code/Basic Codes/Prime Number.py | 239 | 4.1875 | 4 | # number which is only divisible to itself
# 2, 3, 5, 7, 15, 29
number = 3
flag = False
for i in range(2, number):
if number % i == 0:
flag = True
if flag:
print("Number is not prime")
else:
print("Number is prime")
| true |
2e2f54a81a31c5d557e044b4392a929979b0dc44 | pranaysapkale007/Python | /Basic_Python_Code/Basic Codes/Palindrome.py | 368 | 4.25 | 4 | # String Palindrome
str = 'nayan'
pal_str = str[::-1]
if str == pal_str:
print("String is palindrome")
else:
print("String is not palindrome")
# Number palindrome
number = 12321
rev = 0
num = number
while num != 0:
rem = num % 10
rev = rev * 10 + rem
num = num // 10
if number == rev:
print("Palindrome")
else:
print("Not Palindrome") | false |
36390b2bd3234a89c3d601e26fb3b65ebe76f748 | iftikhar1995/Python-DesignPatterns | /Creational/Builder/ComputerBuilder/SubObjects/hard_disk.py | 895 | 4.25 | 4 | class HardDisk:
"""
HardDisk of a computer
"""
def __init__(self, capacity: str) -> None:
self.__capacity = capacity
def capacity(self) -> str:
"""
A helper function that will return the capacity of the hard disk.
:return: The capacity of the hard disk.
:rtype: str
"""
return self.__capacity
def __str__(self) -> str:
"""
Overriding the magic method to send custom representation
:return: The custom representation of the object
:rtype: str
"""
disk = dict()
disk['Capacity'] = self.__capacity
return str(disk)
def __repr__(self) -> str:
"""
Overriding the magic method to send custom representation
:return: The custom representation of the object
:rtype: str
"""
return self.__str__()
| true |
64e3cc39235c702f5324759a285d73871e86a624 | boris-kolesnikov/python_exercises | /if-elif-else_(or-and).py | 1,559 | 4.21875 | 4 | #Посиановка задачи:
# Определить возрастную категорию по значению возраста
if
#ЕСЛИ возраст < 5:
# print('Baby')
elif
#ИНАЧЕ ЕСЛИ возраст < 12:
# print('Schoolboy')
elif
#ИНАЧЕ ЕСЛИ возраст < 19:
# print('Guy')
else
#ИНАЧЕ:
# print("Возрослый чел")
#-------------------------------------------------------------------------------------------------------------------------
Оператор or, «логическое ИЛИ», возвращает True, если хотя бы одно из условий истинно.
elif current_hour >= 18 and current_hour <= 22:
print('Добрый вечер!')
Оператор and, «логическое И», возвращает True только если оба условия истинны.
elif current_hour <= 5 or current_hour >= 23:
print('Доброй ночи!')
#-------------------------------------------------------------------------------------------------------------------------
Логические операторы можно объединять в составные выражения. В таких выражениях операторы выполняются не в порядке записи, а \
в порядке приоритета: высший приоритет у not, затем выполняется and, а последним — or.
| false |
dc1f8e95e109b452741be9c9e55eb5d2bb286cfd | khinthetnwektn/Python-Class | /Function/doc.py | 622 | 4.28125 | 4 | def paper():
''' 1. There will ve situations where your program has to interest with the user.
For example, you would want to take some results back.'''
''' 2. There will be situations where your program has to interest with the user.
For example, you would want to take some results back. '''
print(paper.__doc__)
def print_max(x, y):
''' Print the maximum of two numbers.
The two values must be integers.
'''
x = int(x)
y = int(y)
if x > y:
print(x, ' is maximum')
elif:
print(y, ' is maximum')
else:
print(x, ' and ', y, ' are equal')
print_max(5, 9)
print(print_max.__doc__)
#==> exception | true |
6372e0d8949a79d7142020d7ccbbd6fe222e8e15 | vasimkachhi/Python_Code_Sneppets | /webCrawlingbs4.py | 1,992 | 4.125 | 4 | """
This code crawls two sites and extracts tables and its content using beautiful soup and urllib2
Crawling or web scrapping example
1) http://zevross.com/blog/2014/05/16/using-the-python-library-beautifulsoup-to-extract-data-from-a-webpage-applied-to-world-cup-rankings/
2) https://en.wikipedia.org/wiki/List_of_state_and_union_territory_capitals_in_India
"""
import urllib2
from bs4 import BeautifulSoup
url = "http://zevross.com/blog/2014/05/16/using-the-python-library-" \
"beautifulsoup-to-extract-data-from-a-webpage-applied-to-world-cup-rankings/"
r = urllib2.urlopen(url)
soup = BeautifulSoup(r, "html.parser")
nested_html = soup.prettify()
data = soup.find("table", {"class": 'sortable'})
datakeylist = []
datadict = []
for row in data.findAll("tr"):
thh = row.findAll('th')
tdd = row.findAll('td')
if thh:
for t in thh:
print t.text
datakeylist.append(t.text)
if tdd:
row = {}
for index, t in enumerate(tdd):
print t.text
row.update({datakeylist[index]: t.text})
datadict.append(row)
print datadict
import urllib2
from bs4 import BeautifulSoup
url = "https://en.wikipedia.org/wiki/List_of_state_and_union_territory_capitals_in_India"
r = urllib2.urlopen(url)
soup = BeautifulSoup(r, "html.parser")
nested_html = soup.prettify()
data = soup.find("table", {"class": 'wikitable sortable plainrowheaders'})
datakeylist = []
datadict = []
for index, row in enumerate(data.findAll("tr")):
thh = row.findAll("th")
tdd = row.findAll('td')
if index < 1:
for t in thh:
datakeylist.append(str(t.text).replace('\n', ' '))
datakeys = datakeylist[:]
datakeylist.pop(1)
else:
roww = {}
missing = row.findNext('a').text
for index1, t in enumerate(tdd):
roww.update({datakeylist[index1]: t.text})
roww.update({datakeys[1]: missing})
datadict.append(roww)
print datadict
| true |
a44243ca5d9fd973635179eadec648c70123479b | diegohsales/EstudoSobrePython | /Any e All.py | 1,825 | 4.15625 | 4 | '''
Python tem duas funções muito interessantes: ANY e ALL.
-> A função 'ANY' recebe uma lista (ou outro objeto interável) e retorna
'True' se algum dos elementos for avaliado como 'True'.
-> Já 'ALL' só retorna 'True' se todos os elementos forem avaliados como 'True' ou se ainda se o iterável está vazio. Veja:
>>> everybody=[1,2,3,4]
>>> anybody=[0,1,0,2]
>>> nobody=[0,0,0,0]
>>> any(everybody)
True
>>> any(nobody)
False
>>> any(anybody)
True
>>> all(everybody)
True
>>> all(nobody) - Aqui retorno false porque o 0 significa como FALSO e o numero 1 como VERDADEIRO, pois isso no ALL dá como FALSE.
False
>>> all(anybody)
False
Sem segredos, certo? Mas essas duas funções junto com os generators permite uma sintaxe muito interessante:
>>> v=[10,12,25,14]
>>> any(n>20 for n in v)
True
>>> all(n>20 for n in v)
False
Veja um exemplo disso num código real:
if all(v<100 for v in values):
msg='Para usar seu cupom de desconto, pelo menos '+
'um dos produtos deve custar mais de R$ 100,00.'
E numa classe real:
class Form:
# ...
def validates(self):
return not any(field.error for field in self.fields)
'''
nomes = ['Carlos', 'Camila', 'Carla', 'Cassiano', 'Cristina', 'Daniel'] #Deu False porque tem o nome Daniel
print(all([nome[0] == 'C' for nome in nomes]))
nomes1 = ['Carlos', 'camila', 'Carla', 'Cassiano', 'Cristina'] #Deu Treu porque todos os nomes começam com C Maiusculo
print(all([nome[0] == 'C' for nome in nomes1]))
print(all([letra for letra in 'b' if letra in 'aeiou'])) #Dá TRUE pois dá como vazio, e dá vazio pois não consta nenhuma letra.
#Um iterável vazio convertido em boolean é FALSE, mas o all() entende como TRUE.
print(any([0,0,0,0,0,1])) #Deu TRUE pois contém o numero 1
print(any([0,0,0,0,0])) #Deu FALSE pois só contém o numero 0 | false |
01d508d1de383063706939f10b4536af1ac98f0c | diegohsales/EstudoSobrePython | /Map.py | 1,278 | 4.4375 | 4 | """
Map
Com Map, fazemos mapeamentos de valores para função.
import math
def area(r):
# Calcula a area de um circulo com um raio 'r'. #
return math.pi * (r ** 2)
print(area(2))
print(area(5.3))
raios = [2, 5, 7.1, 0.3, 10, 44]
#Forma Comum de calcular a área
areas = []
for r in raios:
areas.append((area(r)))
print(areas)
#Forma 2 utilizando MAP
# Map é uma função que recebe dois parâmetros: O primeiro a função, o segundo um iterável. Retorna um Map Object.
areas = map(area, raios)
print(list(areas))
#Forma 3 - Map com Lambda
print(list(map(lambda r: math.pi * (r ** 2), (raios))))
#Após utilizar a função Map depois da primeira utilização do resultado, ele zera.
# Para Fixar - Map
Temos dados iteráveis:
- Dados: a1. a2, ..., an
Temos uma função:
-Função: f(x)
Utilizando a função map(f, dados), onde map irá mapear cada elemento dos dados e aplicar a função.
o Map object: f(a1), f(a2), f(...), f(an)
#Mais um exemplo
cidades = [('Berlin', 29), ('Cairo', 36), ('Bueno Aires', 19), ('Los Angeles', 26), ('Tokio', 27), ('Nova york', 28),
('Londres', 22)]
print(cidades)
# f = 9/5 * c + 32
# Lambda
c_para_f = lambda dado: (dado[0], (9/5) * dado[1] + 32)
print(list(map(c_para_f, cidades)))
""" | false |
cc992a4441c076d3403b1c48de01c215caa24353 | diegohsales/EstudoSobrePython | /Exercicio 02 Herança.py | 1,262 | 4.46875 | 4 | """
Crie a classe Animal com os atributos nome, cor e numero_patas. Crie também o método
exibir_dados, que imprime na tela uma espécie de relatório informando os dados do animal.
Crie uma classe Cachorro que herda da classe Animal e que possui como atributo adicional a raça do cachorro.
Crie também o método exibir_dados, que imprime na tela os dados do cachorro (nome, cor, numero de patas e raça)
"""
class Animal:
def __init__(self, nome, cor, numero_patas):
self.nome = nome
self.cor = cor
self.numero_patas = numero_patas
def exibir_dados(self):
print("--------------------")
print("Nome:", self.nome)
print("Cor:", self.cor)
print("Numero de Patas:", self.numero_patas)
class Cachorro(Animal):
def __init__(self, nome, cor, numero_patas, raca_cachorro):
super().__init__(nome, cor, numero_patas)
self.raca_cachorro = raca_cachorro
def exibir_dados(self):
super().exibir_dados()
print("Raça Cachorro: ", self.raca_cachorro)
animal = Animal("Passarinho", "Azul", 2)
animal.exibir_dados() # exibe os atributos do animal
dog = Cachorro("Rex", "Marrom", 4, "Vira lata")
dog.exibir_dados() # exibe os atributos do cachorro
| false |
5db5a914e667c8b19ae0c67de1ebf085e60931c9 | eclipse-ib/Software-University-Fundamentals_Module | /03-Lists_Basics/2-Strange_zoo.py | 492 | 4.125 | 4 | ## Решение по условие, в което е показано как се сменят отделните елементи в даден лист:
tail = input()
body = input()
head = input()
meerkat = [tail, body, head]
#№ meerkat[0], meerkat[-1] = meerkat[-1], meerkat[0]
meerkat[0], meerkat[2] = meerkat[2], meerkat[0]
print(meerkat)
## Много опростен вариант:
tail = input()
body = input()
head = input()
meerkat = [head, body, tail]
print(meerkat) | false |
6c41734cd5f2e23ee52c2152d3676ff0bb00a42e | durgeshtrivedi/Python | /FlowControl.py | 586 | 4.40625 | 4 | # -*- coding: utf-8 -*-
#%%
def flowControl():
name = input("what is your name")
age = int(input("whats your age,{}".format(name)))
if age > 18:
print("You have the rights for voting")
else:
print("Come after {}".format(18 - age))
if 16 <= age <= 65:
print("Have a good day at work")
parrot = "How are you"
letter = "y"
value = "g"
if letter in parrot :
print("Letter {0} is in Parrot".format(letter))
if value not in parrot:
print("Value {0} is not in parrot".format(value))
| true |
023a932e90e2c2bfcb8f60916bf3f876d6031a8f | ygkoumas/algorithms | /match-game/__main__.py | 1,820 | 4.21875 | 4 | # Simulate a card game called "match" between two computer players using N packs of cards.
# The cards being shuffled.
# Cards are revealed one by one from the top of the pile.
# The matching condition can be the face value of the card, the suit, or both.
# When two matching cards are played sequentially, a player is chosen randomly
# as having declared "match!" first and takes ownership of all the revealed cards.
# Game is continued until pile is exhausted.
from random import randint
from sys import exit
import lib
while True:
try:
N = int(raw_input('Type how many packs of cards to use (N): ').strip())
mc = int(raw_input('Choose matching condition (mc): type "1" for value, "2" for suit, "3" for both: ').strip())
break
except ValueError:
print('That was no valid number. Try again')
# create a pile using N (from input) pacs of cards
cards = lib.Cards(N)
# create two players
player1 = lib.Player()
player2 = lib.Player()
# shuffle the cards
cards.shuffle(cards.cards_number)
# define set of matching conditions
mc_list = ['value'] if mc == 1 else ['suit'] if mc ==2 else ['value', 'suit'] if mc ==3 else exit("%s is not acceptable value for matching condition" % mc)
# play the game
i = 1
while i < cards.cards_number:
mc_value = cards.match(mc_list, i)
if mc_value:
score = i - cards.current_index
# choose a player randomly as having declared "match!"
if randint(0,1) == 0:
player1.score += score
else:
player2.score += score
# update current index for next match
cards.current_index = i
i += 1
i += 1
# print the results of the game
print 'player1: %s cards' % player1.score
print 'player2: %s cards' % player2.score
winner = 'player1' if player1.score > player2.score else 'player2' if player1.score < player2.score else 'none'
print 'The winner is %s' % winner
| true |
a09dd584e8e71badeaba7b5473bea545db030e26 | niuonas/DataStructuresPython | /Range.py | 795 | 4.71875 | 5 | #Sequence representing an arithmetic progression of integers
#Range determines what arguments mean by counting them
# range(stop) - only one element
# range(start,stop) - two elements
# range(start,stop,step) - three elements
range(5) #the value provided as argument is the end of the range but is not included
range(1,5) #you can also give as argument a starting value. The starting value is included
range(1,5,2) #you can also provide a step with which to increment
#example using enumerate:
if __name__ == '__main__':
t = [6,45,32,12]
for p in enumerate(t): #generates a tuple for each element in the list (index,element)
print(p)
#you can use tuple unpacking to access the element + index in the list like this:
for p in enumerate(t):
print(f'')
| true |
922d2a3006bf9c2a159dd9ebce4f127c1e0e5984 | RBazelais/coding-dojo | /Python/python_fundementals/StringAndList.py | 1,698 | 4.28125 | 4 | '''
Find and replace
print the position of the first instance of the word "day".
Then create a new string where the word "day" is replaced
with the word "month".
'''
words = "It's thanksgiving day. It's my birthday,too!"
str1 = words.replace("day", "month")
#print str1
#Min and Max
#Print the min and max values in a list like this one:
#x = [2,54,-2,7,12,98]. Your code should work for any list.
x = [2, 54, -2, 7, 12, 98]
def MinAndMax():
Min = min(x)
Max = max(x)
print "The smallest value is ", Min
print "The largest value is ", Max
#MinAndMax()
#Print the first and last values in a list like this one:
#x = ["hello",2,54,-2,7,12,98,"world"].
#Now create a new list containing only the first and last values in the original list.
#Your code should work for any list.
x = ["hello",2,54,-2,7,12,98,"world"]
def FirstAndLast(x):
newList = []
length = len(x)
newList.append(x[0])
newList.append(x[length-1])
print newList
#FirstAndLast(x)
#New List
#Start with a list like this one: x = [19,2,54,-2,7,12,98,32,10,-3,6].
#Sort your list first. Then, split your list in half.
#Push the list created from the first half to position 0 of the list created from the second half. The output should be: [[-3, -2, 2, 6, 7], 10, 12, 19, 32, 54, 98]. Stick with it, this one is tough!
def makeNewList():
x = [19,2,54,-2,7,12,98,32,10,-3,6]
x.sort()
#[-3, -2, 2, 6, 7, 10, 12, 19, 32, 54, 98]
index = len(x)/2
firstHalf = x[:index]
secondHalf = x[index:]
# colon notation takes a subset of the index
print firstHalf
print secondHalf
secondHalf.insert(0, firstHalf)
print secondHalf
makeNewList()
| true |
ef6582736336126502424ec7a7252b0df6723fa4 | gortaina/100DaysOfCode | /code/Calcuradora_Simples.py | 903 | 4.21875 | 4 |
def start():
print("\n******************* Python Calculator *******************")
print("Selecione o número da operação desejada:\n")
print("1 - Soma")
print("2 - Subtração")
print("3 - Multiplicação")
print("4 - Divisão")
def calcular(option, num1, num2 ):
print("\n")
if option == '1' :
print("%s + %s = %r" %(num1, num2,num1 + num2))
elif option == '2' :
print("%s - %s = %r" %(num1, num2,num1 - num2))
elif option == '3' :
print("%s * %s = %r" %(num1, num2,num1 * num2))
elif option == '4' :
print("%s / %s = %r" %(num1, num2,num1 / num2))
else:
print("\nOpção Inválida!")
start()
option = input("\nDigite sua opção (1/2/3/4): ")
num1 = int(input("\nDigite o primeiro número: "))
num2 = int(input("\nDigite o segundo número: "))
calcular(option,num1,num2)
| false |
2eb391025229727a3c28bc4ccc37d389eff8c234 | Masheenist/Python | /lesson_code/ex42_Is-A_Has-A_Objects_and_Classes/ex42.py | 2,010 | 4.21875 | 4 | # Make a class named Animal that is-a(n) object
class Animal(object):
pass
# Make a class named Dog that is-a(n) Animal
class Dog(Animal):
def __init__(self, name):
# from self, get the name attribute and set it to name
self.name = name
# Make a class named Cat that is-a(n) Animal
class Cat(Animal):
def __init__(self, name):
# from self, get the name attribute and set it to name
self.name = name
# Make a class named Person that is-a(n) object
class Person(object):
def __init__(self, name):
# from self, get the name attribute and set it to name
self.name = name
## from self, get the pet attribute and set it to none
self.pet = None
# Make a class named Employee that is-a Person
class Employee(Person):
def __init__(self, name, salary):
# Have Employee get attributes from Person Object
super(Employee, self).__init__(name)
# from self, get the salary attribute and set it to salary
self.salary = salary
# Make a class named Fish that is-an Object
class Fish(object):
pass
# Make a class named Salmon that is-a Fish
class Salmon(Fish):
pass
# Make a class named Halibut that is-a Fish
class Halibut(Fish):
pass
# Set rover to an instance of class Dog, rover is-a Dog
rover = Dog("Rover")
# Set satan to an instance of class Cat, satan is-a cat
satan = Cat("Satan")
# Set mary to an instance of class Person, mary is-a person
mary = Person("Mary")
# from mary, get the pet attribute and set it to satan
mary.pet = satan
# Set frank to an instance of Class Employee that takes params "Frank" and 120000
frank = Employee("Frank", 120000)
# from frank, get the pet attribute and set it to rover
frank.pet = rover
# Set flipper to an instance of class Fish, flipper is-a Fish
flipper = Fish()
# Set crouse to an instance of class Salmon, crouse is-a Salmon
crouse = Salmon()
# Set harry to an instance of class Halibut, harry is-a Halibut
harry = Halibut()
| true |
b1dce264796bd68b9397b48e5b7a4685827f0745 | Masheenist/Python | /lesson_code/ex20_Functions_and_Files/ex20.py | 1,119 | 4.25 | 4 | # get argv from sys module
from sys import argv
# have argv unpack to argument variables
script, input_file = argv
# fxn takes an open(ed) file as arg & reads it and prints
def print_all(f):
print(f.read())
# seek(0) moves to 0 byte (first byte) in the file
def rewind(f):
f.seek(0)
# readline() reads one line from the file, that line gets concatenated
# with the line_count argument which in our case is an integer.
def print_a_line(line_count, f):
print(line_count, f.readline())
# end functions ===============================================================
# open file and assign
current_file = open(input_file)
print("First, let's print the entire file:\n")
# calls read() on argument
print_all(current_file)
print("Let's rewind, like a tape.")
# rewind just calls .seek(0) on the file
rewind(current_file)
print("Let's print 3 lines:")
current_line = 1
print_a_line(current_line, current_file)
# >>> 1 This is line 1
current_line += 1
print_a_line(current_line, current_file)
# >>> 2 This is line 2
current_line += 1
# >>> 3 This is line 3
print_a_line(current_line, current_file)
| true |
d99f911cf8714289dc500c1f0712f705a7bd34a4 | Masheenist/Python | /lesson_code/ex44_Inheritance_vs_Composition/ex44b.py | 681 | 4.65625 | 5 | # OVERRIDE EXPLICITLY
# =============================================================================
# The problem with having functions called implicitly is sometimes you want
# the child to behave differently.
# In this case we want to override the function in the child, thereby replacing
# the functionality. To do this, just define a function with the same name
# in Child..
class Parent(object):
def override(self):
print("PARENT override()")
class Child(Parent):
def override(self):
print("CHILD override()")
dad = Parent()
son = Child()
dad.override()
son.override()
# Child overrides the function by defining its own version --> line 15 | true |
17bbdd091df55ce376ba30b2412d3a25e3f3d885 | jonathangray92/universe-simulator | /vector.py | 2,100 | 4.34375 | 4 | """
This module contains a 2d Vector class that can be used to represent a point
in 2d space. Simple vector mathemetics is implemented.
"""
class Vector(object):
""" 2d vectors can represent position, velocity, etc. """
#################
# Magic Methods #
#################
def __init__(self, x, y):
""" Vector must be initialized with values. """
self.x = float(x)
self.y = float(y)
def __add__(self, other):
""" Overloads Vector + Vector syntax. """
return Vector(self.x + other.x, self.y + other.y)
def __div__(self, other):
""" Overloads Vector / constant syntax. """
return Vector(self.x / other, self.y / other)
def __iadd__(self, other):
""" Overloads Vector += Vector syntax. """
self.x += other.x
self.y += other.y
return self
def __imul__(self, other):
""" Overloads Vector *= constant syntax. """
self.x *= other
self.y *= other
return self
def __isub__(self, other):
""" Overloads Vector -= Vector syntax. """
self.x -= other.x
self.y -= other.y
return self
def __iter__(self):
""" Allows Vector objects to be converted to tuples, lists. """
yield self.x
yield self.y
def __mul__(self, other):
""" Overloads Vector * constant syntax. """
return Vector(self.x * other, self.y * other)
def __neg__(self):
""" Overloads -Vector syntax. """
return Vector(-self.x, -self.y)
def __rmul__(self, other):
""" Overloads constant * Vector syntax. """
return self.__mul__(other)
def __repr__(self):
""" Returns string representation of vector. """
return '<Vector (%f, %f)>' % (self.x, self.y)
def __sub__(self, other):
""" Overloads Vector - Vector syntax. """
return Vector(self.x - other.x, self.y - other.y)
##################
# Public Methods #
##################
def get_x(self):
""" Getter for x position. """
return self.x
def get_y(self):
""" Getter for y position. """
return self.y
def norm(self):
""" Returns the norm of the vector. """
return (self.x**2 + self.y**2)**(0.5)
def euclidean(a, b):
return ((a.get_x() - b.get_x())**2 + (a.get_y() - b.get_y())**2)**.5 | true |
30fb93535b4d03784f87e40067091aa9c3349b93 | rudyredhat/PyEssTrainingLL | /Ch06/06_01/constructor.py | 1,637 | 4.34375 | 4 | #!/usr/bin/env python3
class Animal:
# here is the class constructor
# special method name with __init__ = with acts as an initializer or constructor
def __init__(self, type, name, sound): # self is the first argument, that whats makes it a obj method
# we have **kwargs and we can set the default values as well
# def __init__(**kwargs):
# self._type = kwargs['type'] if 'type' in kwargs else 'kitten'
# below are the object var with _ in the start
self._type = type
self._name = name
self._sound = sound
# below are the accessors or getters which simply return the value of those object variables
def type(self):
return self._type
def name(self):
return self._name
def sound(self):
return self._sound
def print_animal(o):
if not isinstance(o, Animal):
raise TypeError('print_animal(): requires an Animal')
# here we use those getters to access the variables
print('The {} is named "{}" and says "{}".'.format(o.type(), o.name(), o.sound()))
def main():
# 2 obj from the animal class & intialize with various parameters
# obj is created using the class name or the func name
a0 = Animal('kitten', 'fluffy', 'rwar')
a1 = Animal('duck', 'donald', 'quack')
# we can use **kwargs as well
# a3 = Animal(type='kitten',name='fluffy', sound='rwar')
print_animal(a0)
print_animal(a1)
# directly we are calling here from the constructor
# function parameters = assignments in python
print_animal(Animal('velociraptor', 'veronica', 'hello'))
if __name__ == '__main__': main() | true |
0b65a0a5a1d3446f7156ed36d54c86653f637119 | brentshermana/CompetativeProgramming | /src/puzzles/InterviewKickstart/dynamic_programming/count-ways-to-reach-nth-stair.py | 721 | 4.25 | 4 | # a person can take some number of stairs for each step. Count
# the number of ways to reach the nth step
# there is 1 way to reach the first stair
# there are two ways to reach the second stair
# there are 111 12 21 three ways to reach the third stair
# to formulate this as a table, if we are at step i, which we can reach in I ways,
# and we can move directly to j, J += I
def countWaysToClimb(steps, n):
# step '0' is not actually a step. It's right before the first step
table = [0 for _ in range(n+1)]
table[0] = 1 # one way to do nothing
for i in range(n+1):
for inc in steps:
if i+inc > n:
continue
table[i+inc] += table[i]
return table[n]
| true |
b4186605cdbb29642bd68ee3731379c18b9d770f | brentshermana/CompetativeProgramming | /src/puzzles/leetcode/leetcode_binarytreelongestconsecutivesequence/__init__.py | 1,618 | 4.1875 | 4 | # Given a binary tree, find the length of the longest consecutive sequence path.
#
# The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).
#
# Example 1:
#
# Input:
#
# 1
# \
# 3
# / \
# 2 4
# \
# 5
#
# Output: 3
#
# Explanation: Longest consecutive sequence path is 3-4-5, so return 3.
# Example 2:
#
# Input:
#
# 2
# \
# 3
# /
# 2
# /
# 1
#
# Output: 2
#
# Explanation: Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.
# DONE
# logic: when iterating recursively from parents to children, and given the parent's value and
# the size of the current sequence, we know what the new sequence size is.
# Just keep track of the maximum value.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def longestConsecutive(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.longest = 0
def rec(root, cur_len=0, parent_val=None):
if root == None:
return
elif parent_val == root.val - 1:
new_len = cur_len + 1
else:
new_len = 1
self.longest = max(self.longest, new_len)
rec(root.left, new_len, root.val)
rec(root.right, new_len, root.val)
rec(root)
return self.longest | true |
7427a978ff9bcd065cdc21e70ada6a14f5b823e5 | khinthandarkyaw98/Python_Practice | /random_permutation.py | 681 | 4.15625 | 4 | """
A permutation refers to an arrangement of elements.
e.g. [3,2, 1] is a permutaion of [1, 2, 3] and vice-versa.
The numpy random module provides two methods for this:
shuffle() and permutation().
"""
# shuffling arrays
# shuffle()
from numpy import random
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
random.shuffle(arr)
print(arr)
# generating permutation of arrays
# from numpy import random
# import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(random.permutation(arr))
random.permutation(arr)
print(arr)
# permuatation() returns an re-arranged array( and leaves
# the original array un-changed ) meanwhile shuffle changes | true |
d24a450b4b9645e09fdf19d679997d9c83e03e2c | khinthandarkyaw98/Python_Practice | /python_tuto_functions.py | 1,472 | 4.4375 | 4 | # creating a function
def my_func():
print("Hello")
my_func()
# pass an argument
def my_function(fname):
print(fname + "Refsnes")
my_function('Emil')
# pass two arguments
def my_function(fname, lname):
print(fname + " " + lname)
my_function('Emil', 'Refsnes')
"""
if you do not know how many arguments that will be passed
into your function,
add a * before the parameter name in the function defintion
It receives a tuple of arguments,
can access the items accordingly.
"""
def function(*kids):
print('The youngest child is ' + kids[2])
function('Emil', 'Tobias', 'Linus')
# send arguments with key = value
# order of the arguments does not matter
def my_function(child3, child2, child1):
print('The youngest child is ' + child3)
my_function(child1 = 'Emil', child2 = 'Tobias', child3 = 'Linus')
# keyword arguments are shortened into **kwargs
def my_function(**kid):
print('His name is ' + kid['lname'])
my_function(fname = 'Tobias', lname = 'Refsnes')
def my_function(mylist):
for i in mylist:
print(i)
fruits = ['apple', 'orange', 'strawberry']
my_function(fruits)
def my_function(x):
return 5 * x
print(my_function(3))
# pass statement
def my_function():
pass
# recursion
def tri_ recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print('\n\n Rescursion Example Results')
tri_recursion(6) | true |
ac13bb44dc4a015f00fd70bddc3f9bff608dafaf | khinthandarkyaw98/Python_Practice | /python_tuto_file.py | 1,721 | 4.34375 | 4 | # file
# open('filename','mode')
# opening a file
f = open('file.txt')
# open a file and read as a text
f = open('file.txt', 'rt')
# read the file
f = open('file.txt', 'r')
print(f.read())
# read only parts of the file
f = open('file.txt', 'r')
print(f.read(5))
# return the first characters of the file from 0 to 5
# return Hello
# readline()
f = open('file.txt', 'r')
print(f.readline())
# return the first line in the file
f = open('file.txt', 'r')
print(f.readline())
print(f.readline())
# return the firstline and secondline in the file
# return the whole file--> you have to loop through the file
f = open('file.txt', 'r')
for i in f:
print(x)
# close the file
f = open('file.txt', 'r')
print(f.read())
f.close()
# you have to close the file. Don't forget
# writing to an exsiting file
f = open('file.txt', 'a')
f.write('Now the file has more content!')
f.close()
# open and read the file after the appending
f = open('file.txt', 'r')
print(f.read())
f.close()
# overwrite the content
f = open('file.txt', 'w')
f.write('Oh, I have deleted the content!')
f.close()
# open and read the file after the appending
f = open('file.txt', 'r')
print(f.read())
f.close()
# create a new file
f = open('file2.txt', 'x')
# error occurs if the file already exits
# python delete a file
# to delete a file, you must import the OS module, and run its os.remove() function.
import os
os.remove('file2.txt')
# check if file exists to avoid the error
# import os
if os.path.exists('file2.txt'):
os.remove('file2.txt')
else:
print('The file does not exist')
# Delete an entire folder, use os.rmdir()
# import os
os.rmdir('myfolder')
| true |
a5115410d54da81229153b78e33b869795ffcb46 | khinthandarkyaw98/Python_Practice | /multiple_regression.py | 2,281 | 4.5 | 4 | # predict the CO2 emission of a car based on
# the size of the engine. but
# with multiple regression we can throw in more variables,
# like the weight of the car, to make the prediction more accurate.
import pandas
# the pandas module allows us to read csv files
# and return a DataFrame object
df = pandas.read_csv('cars.csv')
# make a list of the independent values and call this variable x
# put the dependent values in a variable called y
X = df[['Weight', 'Volume']]
y = df['CO2']
# it is common to name the list of independent vaues with a upper case X
# and the list of dependent values with a lower case y
# import sklearn module to use linearRegression()
from sklearn import linear_model
"""
This object has a method called fit() that takes the independent and dependent values as parameters
and fills the regression object with data that describes the relationship
"""
# create a model called LinerRegression()
regr = linear_model.LinearRegression()
# pass independent and dependent variables to fit object
regr.fit(X, y)
# now we have a regression object that are ready to predict
# CO2 values based on a car's weight and volume
# predict the CO2 emission of a car where the weight is 2300 kg, and the volume is 1300 cm
predictCO2 = regr.predict([[2300, 1300]])
# note double [[]] squared brackets
print(predictCO2)
# Coefficient
"""
The coefficient is a factor that describes the relationship
with an unkown variable.
"""
# print the coefficient vaules of the regression object
# import pandas
# from sklearn import linear_model
df = pandas.read_csv('cars.csv')
X = df[['Weight', 'Volume']]
y = df['CO2']
regr = linear_model.LinearRegression()
regr.fit(X, y)
print(regr.coef_)
# predict with weight 3300
# from pandas
# import sklearn import linear_model
df = pandas.read_csv('cars.csv')
X = df[['Weight', 'Volume']]
y = df['CO2']
regr = linear_model.LinearRegression()
regr.fit(X, y)
predictedCO2 = regr.predict([[3300, 1300]])
print(predictedCO2)
# here with 2300 grams of weight : CO2 value = 107.20
# so by using coeff: 107.20 + ( 1000 * 0.00755095) = 114.75968
# The answer is correct. 1000 is the weight difference between the 3300 and 2300
| true |
f287078bdad6f01d1f61cab2b3167ba0538a5d26 | khinthandarkyaw98/Python_Practice | /numpy_summation.py | 703 | 4.3125 | 4 | # add() is done between two elements : return an array
# sum([]) happens over n elements : return an element
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
newarr = np.add(arr1, arr2)
print("add():", newarr)
newarr = np.sum([arr1, arr2])
# note that sum([])
print("sum(): ", newarr)
# Summation over an axis
newarr = np.sum([arr1, arr2], axis = 1)
print("sum() over an axis", newarr)
# cummulative sum : partially adding the elements in array
# The partial sum of [1, 2, 3, 4] would be [1, 1+2, 1+2+3, 1+2+3+4] = [1, 3, 6, 10]
# cumsum()
# import numpy as np
arr = np.array([1, 2, 3])
print("cummulative Sum: ", np.cumsum(arr)) | true |
f6940513aac4dd6e5b640244a6d26fd6c66972bf | mfarukkoc/AlgorithmsDaily | /Problem-10/python_utkryuk.py | 358 | 4.15625 | 4 | '''
Author : Utkarsh Gupta
College : Birla Institute of Technology, Mesra
Year/Department : III/IT
E-Mail Id : utkryuk@gmail.com
'''
def reverseString(inputString):
inputWords = inputString.split()
inputWords = inputWords[::-1]
for index in range(len(inputWords)):
print(inputWords[index], end=' ')
inputString = str(input())
reverseString(inputString)
| false |
2bc5ddd31eb3c8b55ae65c73497831e25fa81ed1 | BorisDundakov/Python--Programming-Basics | /02. Conditional Statements-Lab/02. Greater Number.py | 428 | 4.15625 | 4 | # Да се напише програма, която чете две цели числа въведени от потребителя и отпечатва по-голямото от
# двете.
# Примерен вход и изход
# вход:
# 5
# 3
# Изход:
# 5
first_number = int(input())
second_number = int(input())
if first_number > second_number:
print(first_number)
else:
print(second_number)
| false |
4dae3e9211206ce3f4fc3b3633d13cd2054c57f2 | ahmed-gamal97/Problem-Solving | /leetcode/Reverse Integer.py | 569 | 4.15625 | 4 | # Given a 32-bit signed integer, reverse digits of an integer.
# Example 1:
# Input: 123
# Output: 321
# Example 2:
# Input: -123
#Output: -321
# Example 3:
# Input: 120
# Output: 21
def reverse(x: int) -> int:
result = []
sum = 0
is_neg = 0
if x < 1:
x = x * -1
is_neg = 1
while x != 0:
reminder = x % 10
x = x // 10
sum = sum * 10 + reminder
if sum >= 2 ** 31 - 1 or sum <= -2 ** 31:
return 0
if is_neg:
return sum * -1
return sum
| true |
12c0d1426d06df87835a304862bdd3f83f980001 | daheige/python3 | /part2/yield_demo.py | 1,526 | 4.15625 | 4 | # coding:utf-8
# 在 Python 中,这种一边循环一边计算
# 的机制,称为生成器:generator
# 函数是顺序执行,遇到 return 语句或者最后
# 一行函数语句就返回。而变成 generator 的函数,在每次调用 next() 的时候执行,遇到 yield
# 语句返回,再次执行时从上次返回的 yield 语句处继续执行。
def odd():
print('step1')
yield (1)
print('step2')
yield (2)
o = odd()
print(next(o))
print(next(o))
# 通过迭代器实现反向打印
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
n = self.start
while n > 0:
yield n
n -= 1
def __reversed__(self):
n = 1
while n <= self.start:
yield n
n += 1
print('=====reversed range(1,13)')
for x in reversed(Countdown(12)):
print(x)
# 倒序
print('===倒序===')
for x in Countdown(12):
print(x)
# 同时迭代多个序列zip
# 其实 zip(a, b) 会生成一个可返回元组 (x, y) 的迭代器,其中 x 来自 a,y 来自 b。 一旦其
# 中某个序列到底结尾,迭代宣告结束。 因此迭代长度跟参数中最短序列长度一致。注意理解这句话
# 喔,也就是说如果 a , b 的长度不一致的话,以最短的为标准,遍历完后就结束
# zip()是可以接受多于两个的序列的参数,不仅仅是两个
names = ['daheige', 'xiaoxiao', 'xiaoming']
ages = [12, 15, 35]
for name, age in zip(names, ages):
print(name, age)
| false |
67dad33c948cb704c1e09c22299aac2e5bf53eaf | AMAN123956/Python-Daily-Learning | /Day1/main.py | 560 | 4.4375 | 4 | # Print Function
print():
# example:
print("Hello World!!!")
# " " > Tells that it is not a code but it is a string
# String Manipulation
# You can create a new line using '\n'
print("Hello World!\n Myself Aman Dixit!")
# String Concatenation
print("Hello"+"Aman")
# Input Function
#example
name=input("What is your name?")
type(name) #String By Default
print("Hello"+input("What is Your Name?"))
# Getting Length
# Length Function
len(str) # Note:It doesn't work with integers
# Variable Naming
# examples
#length1 -valid
#1length - not valid
#user_name - valid | true |
91f1517d926936c6e0e54c8685e23db3a754ee45 | AMAN123956/Python-Daily-Learning | /Day10/docstringmain.py | 478 | 4.25 | 4 | #Docstring
# =================================================================
# Uses:
# 1.Can Also be used as multiline-comment
# 2.Are a way to create a little bit of documentation for our function
# 3.Comes after function definition
#example
def format_name(f_name,l_name):
'''Take a first and last name and format it to return a title
case version of the name.'''
name=f_name.title()+l_name.title()
return name
print(format_name("aman","Dixit"))
| true |
8c2fe6dee7e6dbe4dd64751f7c9ce02241923856 | AMAN123956/Python-Daily-Learning | /Day4/lists.py | 407 | 4.3125 | 4 | # Python Lists
# =========================================================================
# Are like array
#Example
fruits=["Aman","Abhishek","Virat"]
# We can use index as negative values
print(fruits[-1])
# it will return Last Value of the List
#Appending items to the end of list
# Syntax: name_of_list.append("item4")
fruits.append("Rohit")
#Length function to get length of List
print(len(fruits)) | true |
7ba10a012f50f3b2e86b97b31570f1090637c288 | CAVIND46016/Project-Euler | /Problem4.py | 592 | 4.125 | 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.
def check_Palindrome(_num):
return str(_num) == str(_num)[::-1];
def main():
product = 0;
listPalin = [];
for i in range(100, 999):
for j in range(100, 999):
product = i * j;
if(check_Palindrome(product)):
listPalin.append(product);
print(str(max(listPalin)));
if(__name__ == "__main__"):
main(); | true |
9869e6edbef66fbf51646c8311167180acca98e6 | kandarp29/python | /py20.py | 407 | 4.15625 | 4 | ojjus = []
b = input("number of elements in the list")
b = int(b)
for i in range(0,b):
c = input("Insert list elements = ")
ojjus.append(c)
print("Your list is " ,ojjus)
def sorting(a):
for j in range(0,b):
if a == ojjus[j]:
print("your element is in the list ")
else:
print("Your element is not in list")
| true |
6da8b025d3ebd4523aac45174c9145a71ff20996 | jessidepp17/hort503 | /assignments/A02/ex06.py | 1,094 | 4.40625 | 4 | # define variables
types_of_people = 10
# x is a variable that ouputs a string with embedded variable
x = f"There are {types_of_people} types of people."
# more variables and their values
binary = "binary"
do_not = "don't"
# y is another sting with embedded variables
y = f"Those who know {binary} and those who {do_not}."
# simple print value from x and y which result in strings since they
# are variables
print(x)
print(y)
# printing strings with x and y variables
print(f"I said: {x}")
print(f"I also said: '{y}'")
# new variables
hilarious = False
# this variable is leaving space open so that I can code any given
# variable later
joke_evaluation = "Isn't that joke so funny?! {}"
# print a string using .format(); you call the joke_evaluation variable
# and then you .format another variable into the joke_evaluation string
print(joke_evaluation.format(hilarious))
# new variables
w = "This is the left side of..."
e = "a string with a right side."
# printing the addition of two variable values; w is the first half of a
# string and e is the other half
print(w + e)
| true |
204113bb64e0651f3d3d725f85c6b500cfd8b4d8 | YashikaNavin/Numpy | /2.NumpyArray.py | 855 | 4.4375 | 4 | import numpy as np
# Creating numpy array
# 1st way:- create a list and then provide that list as argument in array()
mylist=[1,2,3,4,5]
a=np.array(mylist)
print(a)
# 2nd way:- directly pass the list as an argument within the array()
b=np.array([6.5,7.2,8.6,9,10])
print(b)
# Creating one more numpy array
c=np.array(['Hi', 1, 'Hello', 2])
print(c)
# Mathematical operations on array
print(a+10)
print(b-56)
#print(c*2) # can't perform mathematical operations with string data type
print(a*2)
# To know the shape(size) and data type of array
print(a.shape)
print(a.dtype)
print(b.shape)
print(b.dtype)
# Creating 2D array
d=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(d)
print(d.shape)
# Creating 3D array
e=np.array([[[1,2],[3,4]],
[[5,6],[7,8]],
[[9,10],[11,12]]])
print(e)
print(e.shape) | true |
6bfdecf7ceb2e8cb56bfe700e9fc297d4e0db764 | smitacloud/Python3Demos | /02AD/01Collections_container/enum_demo.py | 1,377 | 4.28125 | 4 | '''
Another useful collection is the enum object.
It is available in the enum module, in Python 3.4 and up
(also available as a backport in PyPI named enum34.)
Enums (enumerated type) are basically a way to organize various things.
Let’s consider the User namedtuple. It had a type field.
The problem is, the type was a string.
This poses some problems for us.
What if the user types in Admin because they held the Shift key? Or ADMIN?
Or USER?
Enumerations can help us avoid this problem, by not using strings.
Consider this example:
'''
from collections import namedtuple
from enum import Enum
class Users(Enum):
admin=1
user=2
network_admin=3
employee=4
manager=5
# The list goes on and on...
User = namedtuple('User', 'name age type')
perry = User(name="Perry", age=31, type=Users.admin)
chinky = User(name="Drogon", age=42, type=Users.network_admin)
tom = User(name="Tom", age=75, type=Users.manager)
smita = User(name="Smita", age=30, type=Users.manager)
charlie = User(name="Charlie", age=22, type=Users.employee)
# And now, some tests.
print("Is smita.type == tom.type : ",smita.type == tom.type)
print("charlie.type : ",charlie.type)
#There are three ways to access enumeration members
print("Users(1) : ",Users(1))
print("Users['admin'] : ",Users['admin'])
print("Users.admin : ",Users.admin)
| true |
244e325d5a0e7a09b4803dad17bb82ccf4de5a3e | smitacloud/Python3Demos | /02AD/03Sequence_Operation/generator_object.py | 610 | 4.53125 | 5 | #Generator-Object : Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using the generator object in a “for in” loop (as shown in the above program).
# A Python program to demonstrate use of
# generator object with next()
# A generator function
def simpleGeneratorFun():
yield 1
yield 2
yield 3
# x is a generator object
x = simpleGeneratorFun()
# Iterating over the generator object using next
print(x.__next__()); # before Python 3, next()
print(x.__next__());
print(x.__next__());
| true |
6f301ecfb26f2282a3af41eecbeb60d0ddfc18de | smitacloud/Python3Demos | /loopsAndConditions/Armstrong.py | 752 | 4.53125 | 5 | '''
A positive integer is called an Armstrong number of order n if
abcd... = an + bn + cn + dn + ...
In case of an Armstrong number of 3 digits, the sum of cubes of each digits is equal to the number itself. For example:
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.
'''
# Python program to check if the number provided by the user is an Armstrong number or not
# take input from the user
# num = int(input("Enter a number: "))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number") | true |
13cd22596ee928e94ba041050deaaeaacf8a88c7 | ayman-elkassas/Python-Notebooks | /3-OOP and DSA/6-Stack and queue/Lib/Stack.py | 742 | 4.25 | 4 | class stack:
"""
This is class stack for operations stack
push,pop,top,is_empty,len
"""
def __init__(self):
self._data = []
def push(self,e):
self._data.append(e)
def pop(self):
if self.is_empty():
raise Exception("Empty stack")
return self._data.pop()
def top(self):
if self.is_empty():
raise Exception("Empty Stack")
return self._data[-1]
def is_empty(self):
return len(self._data)==0
def __len__(self):
return len(self._data)
"""
usage:
s=stack()
s.push(5)
s.push(6)
print(len(s))
s.pop()
print(len(s))
s.push(66)
print(s.top())
s.pop()
s.pop()
print(len(s))
"""
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.