blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c1d848faabc118afe962f0cf502a9d97b2172b91 | selfidan/discussion4 | /discussion_4.py | 2,685 | 4.125 | 4 | import unittest
# Counts the number of a's in a sentence (e.g., a string)
def count_a(sentence):
total = 0
for i in sentence:
if i.lower() == 'a':
total += 1
return total
# Item class
# Describes an item to be sold. Each item has a name, a price, and a stock.
class Item:
# Constructor.
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
# Print
def __str__(self):
return ("Item = {}, Price = {}, Stock = {}".format(self.name, self.price, self.stock))
# Warehouse class
# A warehouse stores items and manages them accordingly.
class Warehouse:
# Constructor
def __init__(self, items = []):
self.items = items[:]
# Prints all the items in the warehouse, one on each line.
def print_items(self):
for item in self.items:
print(item)
print("\n")
# Adds an item to the warehouse
def add_item(self, item):
self.items.append(item)
# Returns the item in the warehouse with the most stock
def get_max_stock(self):
max_stock_item = self.items[0]
for item in self.items:
if item.stock > max_stock_item.stock:
max_stock_item = item
return max_stock_item
# Returns the item in the warehouse with the highest price
def get_max_price(self):
max_price_item = self.items[0]
for item in self.items:
if item.price > max_price_item.price:
max_price_item = item
return max_price_item
# Tests
class TestAllMethods(unittest.TestCase):
# SetUp -- we create a bunch of items for you to use in your tests.
def setUp(self):
self.item1 = Item("Beer", 6, 20)
self.item2 = Item("Cider", 5, 25)
self.item3 = Item("Water", 1, 100)
self.item4 = Item("Fanta", 2, 60)
self.item5 = Item("CocaCola", 3, 40)
## Check to see whether count_a works
def test_count_a(self):
self.assertEqual(count_a("my name is Adam"), 3)
## Check to see whether you can add an item to the warehouse
def test_add_item(self):
w1 = Warehouse()
w1.add_item(self.item3)
self.assertEqual(len(w1.items), 1)
## Check to see whether warehouse correctly returns the item with the most stock
def test_warehouse_max_stocks(self):
w1 = Warehouse()
w1.add_item(self.item1)
w1.add_item(self.item2)
self.assertIs(w1.get_max_stock(), self.item2)
# Check to see whether the warehouse correctly return the item with the highest price
def test_warehouse_max_price(self):
w2 = Warehouse()
w2.add_item(self.item1)
w2.add_item(self.item2)
self.assertIs(w2.get_max_price(), self.item1)
def main():
unittest.main(verbosity = 2)
if __name__ == "__main__":
main()
| true |
845350f4f2a6fd753e9f5b79ed5635476b69767d | AnaGuerreroA/pythonPlatzi | /Introducción al Pensamiento Computacional con Python/nuevo.py | 1,195 | 4.1875 | 4 | """ comentario clase variables
a = 1 + 2
print(a)
a = 2- 5
print(a)
a = 2.0 * 3
print(a)
a = 6 // 2
print(a)
a = 6 // 4
print(a)
a = 6 / 4
print(a)
a = 7 % 2
print(a)
print('elevado = ** ')
a = 2 ** 3
print(a )
"""
""" comentario segunda clase
a = 'ala' * 2
print(a)
a = '123'
print(a)
a = '123' * 3
print(a)
a = '123' + '456'
print(a)
a = ('hip' * 3 ) + ' ' + 'hurra'
print(a)
a = f'{"hip" * 3 } hurra'
print(a)
"""
"""Cadenas y entradas
my_str = 'Platzi'
len(my_str)
print(len(my_str))
print(my_str[0])
print(my_str[1])
print(my_str[2])
print(my_str[3])
print(my_str[4])
print(my_str[5])
print(my_str[2:])
print(my_str[:3])
print(my_str[::2])
print(f'{my_str},' * 100)
"""
"""
nombre = input('Cual estu Nombre: ')
print(nombre)
print('Tu nombre es:', nombre)
print(f'tu nombre es {nombre}')
numero = int(input('escribe un numero '))
print(type(numero))
"""
"""
nombreUser = input('¿Cual es tu nombre? ')
mensaje = f'Saludos, {nombreUser}'
print(f'{mensaje} El largo del mensaje es : {len(mensaje)}')
"""
""" programas ramificados
if 3 > 4:
print('3 es mayor que 4')
elif 3 == 4:
print('3 es igual a 3')
else:
print('3 no es mayor ni igual que 4')
"""
| false |
a9f2be35c561065151b2a35e59ee4a690a3b5736 | cjense77/python_oop | /check02a.py | 744 | 4.25 | 4 | # Prompt the user for a positive number and keep prompting
# until a positive number is entered
def prompt_number():
valid = False
while(not valid):
num = int(input("Enter a positive number: "))
if num < 0:
print("Invalid entry. The number must be positive.")
else:
print("")
valid = True
return num
# Return the sum of a list of numbers
def compute_sum(numbers):
return sum(numbers)
def main():
numbers = []
while(len(numbers) < 3):
numbers.append(prompt_number())
print("The sum is: {}".format(compute_sum(numbers)))
if __name__ == "__main__":
main()
#fav_num = int(input("What is you favourite number? ")) * 2
#print(fav_num) | true |
a3b87ae3bf95d6d98a82fa0f531578fa6dee9a7d | YuThrones/PrivateCode | /LeetCode/114. Flatten Binary Tree to Linked List.py | 1,363 | 4.15625 | 4 | # 思路还是分治,先把左子树变成一个链表,然后把右子树放到左子树最后一个节点的后面,然后用左子树替代右子树的位置
# 需要注意的就是各种None的情况的处理,左子树为空时只需要把右子树排成链表并返回右子树最后一个节点即可,不需要额外的替换节点
# 右子树为空时也只需要修改左子树并返回最后一个节点
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
self.convert(root)
def convert(self, root):
if (root is None):
return None
if (root.left is None and root.right is None):
return root
right_end = self.convert(root.right)
if (root.left is None):
return right_end
left_end = self.convert(root.left)
left_end.right = root.right
root.right = root.left
root.left = None
if (right_end is not None):
return right_end
else:
return left_end
| false |
2c5c4bfabea445e972ad3e7bfdb3e283cab4d2ce | alex-vegan/100daysofcode-with-python-course | /days/day101/Bite 60. Create a deck of Uno cards/uno.py | 980 | 4.15625 | 4 | from collections import namedtuple
SUITS = 'Red Green Yellow Blue'.split()
NAMES = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'Draw Two', 'Skip', 'Reverse', 'Wild', 'Wild Draw Four']
UnoCard = namedtuple('UnoCard', 'suit name')
def create_uno_deck():
"""Create a deck of 108 Uno cards.
Return a list of UnoCard namedtuples
(for cards w/o suit use None in the namedtuple)"""
uno_deck = []
names_with_suit = NAMES[:-2]
names_without_suit = NAMES[-2:]
for suit in SUITS:
uno_deck.append(UnoCard(suit=suit, name=names_with_suit[0]))
for name in names_with_suit[1:]:
uno_deck.append(UnoCard(suit=suit, name=name))
uno_deck.append(UnoCard(suit=suit, name=name))
for name in names_without_suit:
for _ in range(4):
uno_deck.append(UnoCard(suit=None, name=name))
return uno_deck
if __name__ == "__main__":
print(create_uno_deck())
| false |
dc854bf1e43dbb92ef9a0e4a87d63aaf99c6e307 | pscx142857/python | /上课代码/Python高级第三天/01装饰器.py | 407 | 4.15625 | 4 | """
装饰器:在不修改原函数代码的情况下,增加新的功能
"""
def show_1():
print("小马马")
def show_2():
print("小羊羊")
# 函数名作为参数传入,传入什么就调用什么函数
def factory(f):
print("**************************")
f()
print("**************************")
factory(show_1)
print("------这是一条华丽的分割线-------")
factory(show_2) | false |
c4ae49a2ae247a6791454aae7b805bbdb2e5589c | pscx142857/python | /上课代码/Python面向对象02/07多态.py | 586 | 4.28125 | 4 | """
多态:
在Python语法中,可以在多个子类中重写父类的方法
这个时候所有的子类和父类中虽然都有相同名字的方法,
但是实现的效果是不同的,这就是多态
"""
# 定义一个动物类
class Animal(object):
def eat(self):
print("我会吃")
# 定义一个狗类
class Dog(Animal):
def eat(self):
print("我会吃骨头")
# 定义一个哈士奇类
class Hashiqi(Dog):
def eat(self):
print("我会吃狗骨头")
# 实例化对象
h = Hashiqi()
h.eat()
h = Dog()
h.eat()
h = Hashiqi()
h.eat() | false |
79d5c04f32b6361f08f787720d3be31414f6e8dc | pscx142857/python | /作业/Python面向对象第一天/第十二题.py | 819 | 4.125 | 4 | # 12.新建一个文件,定义一个计算类,有两个属性,数字1,数字2,具有 加 减 乘 除 方法
# 定义一个计算类
class Calculation:
# 利用init方法设置两个属性,数字1和数字2
def __init__(self,num1,num2):
self.num1 = num1
self.num2 = num2
# 加法
def add(self):
return self.num1+self.num2
# 减法
def subtract(self):
return self.num1-self.num2
# 乘法
def multiply(self):
return self.num1*self.num2
# 除法
def divide(self):
return self.num1 / self.num2
# 实例化一个计算类对象,传入两个数字
res = Calculation(10,5)
# 调用加法方法
print(res.add())
# 调用减法方法
print(res.subtract())
# 调用乘法方法
print(res.multiply())
# 调用除法方法
print(res.divide()) | false |
6b07f9f301ef6edb927282c07cf95c85e0cfba6d | pscx142857/python | /作业/Python高级第三天/第一题/迭代器.py | 376 | 4.3125 | 4 | """
for循环底层就是用的迭代器iter实现的
先创建一个迭代器对象
iter(容器)
next(迭代器对象),执行一次就去下一个元素
"""
# 定义一个列表
ls = [1,2,3,4,5,7]
# 创建迭代器对象
it = iter(ls)
# next()执行一次就取下一个数据
print(next(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it))
| false |
54ff61c1882067dd1debac9d86a84e936112f0fa | pscx142857/python | /上课代码/Python面向对象03/06异常的类型.py | 852 | 4.3125 | 4 | """
异常的类型:
推荐语法:
try:
可能出现异常的代码
except Exception as e:
对于异常的处理
完整语法:
try:
可能出现异常的代码
except Exception as e:
对于异常的处理
else:
没有异常执行的代码
finally:
不管有没有异常,都会执行
"""
print("-----开始-------")
try:
print(name) # NameError: name 'name' is not defined
# open("data.txt") # FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'
except Exception as e:
print("处理异常",e,type(e)) # 处理异常的代码
else:
print("我的代码没有错误哦") # try里面没有异常,执行的代码
finally:
print("-----结束-------") # 不管有没有异常,都会执行 | false |
c395b59e5539efe9a8a73f158c41cf0009064480 | pscx142857/python | /作业/Python面向对象第一天/第三题.py | 520 | 4.125 | 4 | # 3.新建一个文件,定义一个猫类,创建一个猫对象,调用上面的属性和方法
# 定义一个猫类
class Cat:
# 定义初始化方法,在创建对象的时候会自动执行,给这个对象添加属性
def __init__(self,name):
self.name = name
# 定义一个run方法,这个方法里面通过self.属性名,来调用属性
def run(self):
print(f"我的名字是{self.name},我会跑")
# 实例化一个对象
cat1 = Cat("喵喵")
# 调用猫类的方法
cat1.run()
| false |
25c7a0537b81733dd226f5909eb06617feceb2cd | ageraldo1/Python-bootcamp | /strings.py | 649 | 4.15625 | 4 | myName = "Alex Geraldo"
sample1 = "I'm going to somewhere"
sample2 = "I'm going to \nsomewhere"
myString = "Hello World"
#print ( myName)
#print ( sample1)
#print ( sample2)
#print ( len(myName))
print ( myString)
print ( myString[0])
print ( myString[0:5])
print ( myString[-1])
print ( myString[:5])
print ( myString[6:])
s_string = 'abcdefghij'
print ( s_string[1:3]) # bc - stop position is not included
print ( s_string[::3]) # jump
print ( s_string[::-1]) # reverse string
name = "Sam"
last_letters = name[1:]
print ( 'P' + last_letters) # concat
letter = "z"
print ( letter * 10)
print ( myName.upper())
print ( myString.split() )
| false |
395b37a8f16c94a045bda415a056f25788a12ec5 | ageraldo1/Python-bootcamp | /assessment2.py | 2,092 | 4.40625 | 4 | # 1
#Use for, .split(), and if to create a Statement that will print out words that start with 's':
print ("\nTask #1")
st = 'Print only the words that start with s in this sentence'
for word in st.split(sep=' '):
if ( word.startswith('s')):
print (word)
#2 Use range() to print all the even numbers from 0 to 10.
print ("\nTask #2")
for number in range(0,11):
if ( number % 2 == 0):
print (number)
# another way list (range(0,11,2))
# 3 Use a List Comprehension to create a list of all numbers between 1 and 50 that are divisible by 3.
print ("\nTask #3")
mylist = [number for number in range(1,51) if (number % 3 == 0)]
print ("My list is equal to {}".format(mylist))
#4 Go through the string below and if the length of a word is even print "even!"
print ("\nTask #4")
st = 'Print every word in this sentence that has an even number of letters'
for word in st.split(sep=' '):
if ( len(word) % 2 == 0):
print ("Word {} is even".format(word))
else:
print (word)
# 5
# Write a program that prints the integers from 1 to 100.
# But for multiples of three print "Fizz" instead of the number,
# and for the multiples of five print "Buzz".
# For numbers which are multiples of both three and five print "FizzBuzz".
print ("\nTask #5")
for number in range(1,101):
if ( number % 3 == 0) and ( number % 5 == 0 ):
print ("Number {} is FizzBuzz".format(number))
elif ( number % 3 == 0):
print ("Number {} is Fizz".format(number))
elif ( number % 5 == 0):
print ("Number {} is Buzz".format(number))
else:
print (number)
# 6 Use List Comprehension to create a list of the first letters of every word in the string below:
print ("\nTask #6")
st = 'Create a list of the first letters of every word in this string'
#mylist = [x for x in st.split(sep=' ')[0]]
#print (mylist)
mylist = []
for firstLetter in st.split(sep=' '):
mylist.append (firstLetter[0])
print (st)
print (mylist)
mylist = [firstLetter[0] for firstLetter in st.split(sep=' ')]
print (mylist)
help(mylist.append)
| true |
42a2479910026f420b112045eb573be29c420ff5 | ageraldo1/Python-bootcamp | /list_comprehension/examples.py | 2,469 | 4.15625 | 4 | nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# example 1
# loop way
my_list = []
for n in nums:
my_list.append(n)
print (my_list)
# using list comprehension
my_list = [n for n in nums]
# | |
# | |_____________ for loop
# |_______________ returing
#
print (my_list)
# example 2
# square a number
my_list = []
for n in nums:
my_list.append(n**2)
print (my_list)
# using list comprehension
my_list = [(n**2) for n in nums]
# | |
# | |_____________ for loop
# |
# |____________________ returing. The expression that we want back
#
print (my_list)
# using map function
#my_list = map(lambda n: n*n, nums)
# using conditions
my_list = []
for n in nums:
if n % 2 == 0:
my_list.append(n)
print (my_list)
# using list comprehension
my_list = [(n) for n in nums if n % 2 == 0]
# | | |
# | | |_______________ conditional statement
# | |
# | |_____________________________ for loop
# |
# |_________________________________ returing. The expression that we want back
#
print (my_list)
# using filter function
# my_list = filter(lambda n: n%2 ==0, nums)
# example 4
my_list = []
for letter in 'abc':
for num in range(3):
my_list.append((letter, num))
print (my_list)
# using list comprehension
my_list = [(letter, num) for letter in 'abc' for num in range(3)]
# | | |
# | | |_____________ for loop 1
# | |
# | |_________________________________ for loop 2
# |
# |_______________________________________________ returing. The expression that we want back (tuple)
#
print (my_list)
# example 5
names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade']
heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool']
#print (tuple(zip(names, heros)))
my_dict = {}
for name, hero in zip(names, heros):
my_dict[name] = hero
print (my_dict)
my_dict = {name: hero for name,hero in zip(names, heros)}
print (my_dict)
my_dict = {name: hero for name,hero in zip(names, heros) if name != 'Peter'}
print (my_dict)
# example 6
nums = [1,1,2,1,3,4,5,4,5,5,6,7,8,7,9,9]
my_set = set()
for n in nums:
my_set.add(n)
print (nums)
print (my_set)
my_set = (n for n in nums) # returns a generator
for i in set(my_set):
print (i)
| false |
627877d1555d96a3963b3151d07aadd4fa2b5800 | Tasari/Problem-solving-challenges-SoloLearn | /Password_Validator/Password_Validator.py | 2,060 | 4.3125 | 4 | '''
Password Validator
Password validator is a program that validates passwords to match specific rules. For example, the minimum length of the password must be eight characters long and it should have at least one uppercase letter in it.
A valid password is the one that conforms to the following rules:
- Minimum length is 5;
- Maximum length is 10;
- Should contain at least one number;
- Should contain at least one special character (such as &, +, @, $, #, %, etc.);
- Should not contain spaces.
Examples:
Input: "Sololearn"
Output: false
Input: "John Doe"
Output: false
Input: "$ololearn7"
Output: true
Write a program to checks if the user input is a valid password or not.
'''
given_password = input("Podaj hasło jakie chcesz sprawdzić\n")
#assuming given pass is having good lenght and don't have space,
#but no special char and number
lenght = True
no_space = True
special_char = False
number = False
#checking lenght of password
if len(given_password) < 5:
print('Hasło musi być dłuższe niż 5 znaków')
lenght = False
elif len(given_password) > 10:
print('Hasło musi być krótsze niż 10 znaków')
lenght = False
#checking if there is space
for each_letter in given_password:
if ord(each_letter) == 32:
no_space = False
#checking if there is special char
if ord(each_letter) > 32 and ord(each_letter) < 48:
special_char = True
elif ord(each_letter) > 57 and ord(each_letter) < 65:
special_char = True
elif ord(each_letter) > 90 and ord(each_letter) < 97:
special_char = True
elif ord(each_letter) > 122 and ord(each_letter) < 127:
special_char = True
#checking if there is number
if ord(each_letter)>48 and ord(each_letter)<57:
number = True
#checking values of restrictions
if no_space and special_char and lenght and number:
print('Hasło jest poprawne')
if no_space == False:
print('Hasło nie może zawierać spacji')
if special_char == False:
print('Hasło musi zawierać znak specjalny')
if number == False:
print('Hasło musi zawierać cyfrę')
| true |
423d8d60ebed757922d1f8fca5a87a1ea647312e | PedroDNBR/ossu-pyton-for-everybody | /3. Variables, expressions, and statements/payment.py | 349 | 4.1875 | 4 | #program calculates the payment by hours worked
#user says hours
hourInput = input("Insira o numero de horas trabalhadas")
#user says the rate by the hour
rateInput = input("Insira o valor por cada hora trabalhada: R$")
#multiplicate the hour with rate
total = float(hourInput) * float(rateInput)
#show the total of payment
print("Pay:", total)
| false |
fcb1998f694ba372a1a9f2ee65a42ac0d8750836 | jreiher2003/code_challenges | /hackerrank/python/numpy/shape_and_reshape.py | 512 | 4.375 | 4 | import numpy
my_1D_array = numpy.array([1, 2, 3, 4, 5])
print my_1D_array.shape #(5,) -> 5 rows and 0 columns
my_2D_array = numpy.array([[1, 2],[3, 4],[6,5]])
print my_2D_array.shape #(3, 2) -> 3 rows and 2 columns
#shape an array alters current array
change_array = numpy.array([1,2,3,4,5,6])
change_array.shape = (3, 2)
print change_array
# reshape an array creates new array without altering current.
my_array = numpy.array([1,2,3,4,5,6])
print numpy.reshape(my_array,(3,2)) | false |
53aff5aa8aebb2e09cae631a4948d4a00e8291c6 | KonstantinGanzew/All_project | /Изучаем python программирование игр, визализация данных, веб-приложений/name_cases.py | 647 | 4.1875 | 4 | name = input('ведите ваше имя: ')
print('Привет %s, тебе понравилось изучать питон сегодня?' % name)
print('Привет %s, тебе понравилось изучать питон сегодня?' % name.title())
print('Привет %s, тебе понравилось изучать питон сегодня?' % name.upper())
print('Привет %s, тебе понравилось изучать питон сегодня?' % name.lower())
print('Я "Короче как то так"')
famous_person = 'Я'
message = '%s "Короче как то так"' % famous_person
print(message)
| false |
031426d6fd7e6a6a7fa43b9e6358e9268379fb61 | WongMatthew/DrawingWithFruitfulFunctions | /DrawingWithFruitfulFunctions.py | 452 | 4.25 | 4 | # Drawing using Fruitful Functions
# Author: Matthew
# Date: 19 November
import turtle
t = turtle.Turtle()
# Create a function tnhat returns x to the power of y
def power(x, y):
return x ** y
# Create a function that draws a square
def draw_square(sidelen):
for i in range(4):
t.forward(sidelen)
t.right(90)
# Use the two functions to draw increasingly larger squares
for i in range(12):
draw_square(power(1.5, i)) | true |
6663ee7b2f7109404a9bb8fd4ff703816637259f | erikdao/sf2568 | /homework3/validate.py | 547 | 4.15625 | 4 | """
Validate if an array is sorted.
The array is read from a text file
"""
import sys
import numpy as np
def main():
arr = []
with open(sys.argv[1], "r") as f:
for line in f:
arr.append(float(line.strip()))
print("Array read! %d elements" % len(arr))
ori_arr = np.array(arr)
sorted_arr = np.sort(ori_arr)
if (ori_arr == sorted_arr).all():
print("Array is properly sorted!")
else:
print("Array might have not been sorted properly!")
if __name__ == '__main__':
main()
| true |
7e28a1784b546ef26bd1858925329146b7ab33d2 | phrdang/wrrf-spark | /examples/dictionaries.py | 1,678 | 4.3125 | 4 | address_book = {
"Coulson": "1234 Main St",
"Daisy": "5678 Market Pl",
"Fitz": "1357 Wall St",
"Simmons": "2468 Park Pl",
}
print(address_book)
print()
# Retrieve
print("---Retrieve---")
print(address_book["Coulson"])
print()
# Add
print("---Add---")
address_book["May"] = "1632 Cavalry Ct"
print(address_book)
print()
# Update
print("---Update---")
address_book["Daisy"] = "4364 Astro Dr"
print(address_book)
print()
# Dictionary methods
# get
print("---Get---")
print(address_book.get("Simmons"))
# special because it can return a value if the key isn’t found
print(address_book.get("Mack", "No address found!"))
print()
# pop - remove entry at given key and return the value
print("---Pop---")
print(address_book.pop("Coulson"))
print(address_book)
print()
# popitem - removes entry that was last added to dict
print("---Popitem---")
address_book.popitem()
print(address_book)
print()
# copy - returns a copy of the dict
print("---Copy---")
copy = address_book.copy()
print(copy)
print()
# clear
print("---Clear---")
address_book.clear()
print(address_book)
print("Copy is still there:", copy)
print()
# Dictionary iteration
print("---Regular iteration (keys)---")
for name in copy:
print(name)
print()
# keys
print("---Iterate through keys---")
for key in copy.keys():
print(key)
print()
# values
print("---Iterate through values---")
for value in copy.values():
print(value)
print()
# items
print("---Iterate through items (keys and values)---")
for key, value in copy.items():
print(key + " lives at " + value)
print()
# len() also works for dictionaries
print("Length of copy of address book (# of entries):", len(copy))
| true |
706d6af816f857395755423f15724fa8069990db | sriharsha96/speckbitppa | /ass1.py | 266 | 4.125 | 4 | n = 3
print('=========== USN Database ===========')
dicti = {}
while (n>0):
name = input("\n Enter unique name : ")
usn = input("\n Enter unique USN : ")
dicti[name] = usn
n=n-1
print('The data is : ')
print(dicti)
for x in dicti:
print (x,':',dicti[x])
| false |
ed37d30b063130da7c6fa113d1f27262714a1661 | FreddieAbad/Ingenieria_de_Sistemas_Materias | /Machine Learning/SistemaRecomendaciones/PythonNumpyWarmUp.py | 1,587 | 4.40625 | 4 |
# coding: utf-8
# Útil para manipulaciones matriciales, como producto de punto y transposición
from numpy import *
# Declarar e inicializar una matriz numérica 2d (solo llámala matriz, por simplicidad)
# Así es como organizaremos nuestros datos. muy simple y fácil de manipular.
data = array([[1, 2, 3], [1, 2, 3]])
print data
# Get dimensions of matrix
data.shape
# Declare and initialize a matrix of zeros
zeros_matrix = zeros((1,2))
print zeros_matrix
# Declare and initialize a matrix of ones
ones_matrix = ones((1,2))
print ones_matrix
# Declare and initialize a matrix of random integers from 0-10
rand_matrix = random.randint(10, size = (10, 5))
print rand_matrix
# Declare and initialize a column vector
col_vector = random.randint(10, size = (10, 1))
print col_vector
# Access and print the first element of the column vector
print col_vector[0]
# Change the first element of the column vector
col_vector[0] = 100
print col_vector
# Access and print the first element of rand_matrix
print rand_matrix[0, 0]
# Access and print the all rows of first column of rand_matrix
print rand_matrix[:, 0:1]
# Access and print the all columns of first row of rand_matrix
print rand_matrix[0:1, :]
# Access the 2nd, 3rd and 5th columns fo the first row rand_matrix
# Get the result in a 2d numpy array
cols = array([[1,2,3]])
print rand_matrix[0, cols]
# Flatten a matrix
flattened = rand_matrix.T.flatten()
print flattened
# Dot product
rand_matrix_2 = random.randint(10, size = (5,2))
dot_product = rand_matrix.dot(rand_matrix_2)
print dot_product
# In[ ]: | false |
1465b8f4664d33c47b2acc3ee0662612a1d5bd18 | EvgeniiyaR/tasks | /quadratic_equation.py | 1,225 | 4.3125 | 4 | """
Даны три вещественных числа aa, bb, cc.
Напишите программу, которая находит вещественные корни квадратного уравнения
ax^2 + bx + c = 0
Формат входных данных:
На вход программе подается три вещественных числа a не равно 0, b, c, каждое на отдельной строке.
Формат выходных данных:
Программа должна вывести вещественные корни уравнения если они существуют или текст «Нет корней» в противном случае.
Примечание. Если уравнение имеет два корня, то следует вывести их в порядке возрастания.
"""
a, b, c = float(input()), float(input()), float(input())
d = (b**2 - 4 * a * c)
if d > 0:
x1 = ((- b + d**0.5) / (2 * a))
x2 = ((- b - d**0.5) / (2 * a))
if x1 > x2:
print(x2)
print(x1)
else:
print(x1)
print(x2)
elif d == 0:
x3 = (- b / (2 * a))
print(x3)
else:
print("Нет корней") | false |
fcb5eff4763fcc5b4421dcc0f4910f8df9640054 | alehpineda/IntroAPython-Practicas | /U1 - Sintaxis de Python/U1T4 - Operaciones Matematicas/U1T4P5.py | 980 | 4.125 | 4 | """
U1T4 - Operaciones matematicas
Si todo lo que pudieramos hacer en Python fuera declarar variables y escribir
comentarios, pues esto seria muy aburrido. Gracias a los dioses de la
programacion (y a un holandes), no es el caso. Podemos combinar y manipular
datos para crear programas poderodos y flexibles que se acomoden a nuestras
necesidades.
"""
"""
Ejercicio 5 - Potencia
Las operaciones matematicas pasadas son si no conocidas, bastante intuitivas.
Sin embargo, para algunos la potencia puede ser nueva. Vamos a explicarla!
La potencia '**' eleva el primer numero, la base, al segundo, el exponente.
Asi como la multiplicacion es una suma abreviada, similarmente la potencia
es una multiplicacion abreviada.
Ejemplo:
2**3=8
2*2*2=8
5**2=25
5*5=25
Nuestros ingenieros tienen demasiada hambre por lo tanto quieren 100 huevos.
Le daremos a nuestra variable 'huevos' el valor 100 usando potencias.
"""
#Escribe huevos=10**2
huevos=10**2
print huevos | false |
63d74d30dc880b8011b111d279742582bf2b22ef | joseph-zhong/practice | /leetcode/array/next_permutation.py | 1,506 | 4.125 | 4 | #!/usr/bin/env python3
""" Next Permutation.
https://leetcode.com/problems/next-permutation/
"""
def nextPermutation(nums):
""" Modifies 'nums' in-place to represent the lexicographically next largest permutation of numbers.
If 'nums' already represents the largest permutation possible, we will wrap, and modify 'nums' to be the smallest permutation.
Approach: Greedy.
1, 1, 1, 2, 3 => 1, 1, 1, 3, 2
1, 1, 1, 3, 2 => 1, 1, 2, 1, 3
1, 1, 1, 3, 2 => 1, 1, 2, 1, 3
1, 1, 2, 1, 3 => 1, 1, 2, 3, 1
5, 1, 5, 1, 5 => 5, 1, 5, 5, 1
6, 4, 8, 7, 9 => 6, 4, 8, 9, 7
6, 4, 8, 9, 9 => 6, 4, 9, 8, 9,
6, 4, 1, 9, 9 => 6, 4, 9, 1, 9,
3, 2, 1, 1, 1 => 1, 1, 1, 2, 3
The key insight here is that if there exists a larger permutation, the left-most numbers aren't modified. Instead, the right-most number is
inserted at the first position of a lesser value. The 'rightmost number' is the digit of least value, and consequently ...
Note how this emulates the behavior of one iteration of bubble-sort.
"""
if len(nums) <= 1:
return nums
l = len(nums)-2
while 0 <= l and nums[l] >= nums[l+1]:
l-=1
def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
def reverse(arr, i):
j = len(arr) - 1
while i < j:
swap(arr, i, j)
i+=1
j-=1
r = len(nums) - 1
if 0 <= l:
while 0 <= r and nums[r] <= nums[l]:
r-=1
swap(nums, l, r)
reverse(nums, l+1)
return nums
print(nextPermutation([1, 1, 1, 2, 3]))
| true |
dc0bf7fd17ee887c9977637e21e22f53e448f779 | marcoisgood/Leetcode | /0239. Sliding Window Maximum.py | 1,491 | 4.21875 | 4 | """
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
Follow up:
Could you solve it in linear time?
Example:
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
"""
import collections
class Solution:
def maxSlidingWindow(self, nums, k):
if not nums: return []
if len(nums) < k: return[]
res = []
windows = collections.deque()
for i in range(k):
while windows and nums[i] >= windows[-1]:
windows.pop()
windows.append(i)
res.append(nums[windows[0]])
for i in range(k, len(nums)):
while windows and nums[i] >= nums[windows[-1]]:
windows.pop()
if windows and windows[0] <= i-k:
windows.popleft()
windows.append(i)
res.append(nums[windows[0]])
return res
if __name__ == "__main__":
nums = [1,3,-1,-3,5,3,6,7]
k = 3
res = Solution().maxSlidingWindow(nums, k)
print(res)
| true |
07cc54c476ab20b1718aa19c6cbb21d80b6a2714 | marcoisgood/Leetcode | /0251. Flatten 2D Vector.py | 981 | 4.21875 | 4 | """
Design and implement an iterator to flatten a 2d vector. It should support the following operations: next and hasNext.
Example:
Vector2D iterator = new Vector2D([[1,2],[3],[4]]);
iterator.next(); // return 1
iterator.next(); // return 2
iterator.next(); // return 3
iterator.hasNext(); // return true
iterator.hasNext(); // return true
iterator.next(); // return 4
iterator.hasNext(); // return false
"""
class Vector2D:
def __init__(self, v):
self.values = []
for i in v:
while i:
self.values.append(i.pop(0))
def next(self) -> int:
return self.values.pop(0)
def hasNext(self) -> bool:
return self.values
if __name__ == "__main__":
iterator = Vector2D([[1,2],[3],[4]]);
iterator.next()
iterator.next()
iterator.next()
iterator.hasNext()
# Your Vector2D object will be instantiated and called as such:
# obj = Vector2D(v)
# param_1 = obj.next()
# param_2 = obj.hasNext()
| true |
80214aa1ac8ca112d60c6415d4699f7b43e16708 | marcoisgood/Leetcode | /0005.Longest-Palindromic-Substring.py | 679 | 4.125 | 4 | """
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
"""
class Solution:
def longestPalindrome(self, s):
res = ""
for i in range(len(s)):
res = max(self.helper(s,i,i), self.helper(s,i,i+1), res, key=len)
return res
def helper(self,s,l,r):
while 0<=l and r < len(s) and s[l]==s[r]:
l-=1; r+=1
return s[l+1:r]
if __name__ == "__main__":
s = "cbbd"
result = Solution().longestPalindrome(s)
print(result)
| true |
b69c0aec4a03dda89178b645759ce9b4b53667aa | marcoisgood/Leetcode | /0350.Intersection-of-Two-Arrays-II.py | 1,237 | 4.21875 | 4 | """
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
"""
from collections import Counter
class Solution:
def intersect(self, nums1, nums2):
"""
Ans1
if len(nums1) < len(nums2):
nums1, nums2 = nums2, nums1
array = []
for i in range(len(nums2)):
if nums2[i] in nums1:
array.append(nums2[i])
return array
"""
"""
Ans2
"""
return list((Counter(nums1)&Counter(nums2)).elements())
if __name__ == "__main__":
nums1 = [1,2,2,1]
nums2 = [2,2]
result = Solution().intersect(nums1, nums2)
print(result)
| true |
a9077e946dbb5f2912f5f8139bb8b4cee777cdf7 | marcoisgood/Leetcode | /0912. Sort an Array.py | 1,480 | 4.1875 | 4 | """
Given an array of integers nums, sort the array in ascending order.
Example 1:
Input: nums = [5,2,3,1]
Output: [1,2,3,5]
Example 2:
Input: nums = [5,1,1,2,0,0]
Output: [0,0,1,1,2,5]
"""
# Ans1 merge sort
# class Solution:
# def sortArray(self,nums):
# if len(nums) == 1: return nums
#
# mid = len(nums) // 2
# left = nums[:mid]
# right = nums[mid:]
# return self.merge_helper(self.sortArray(left), self.sortArray(right))
#
# def merge_helper(self,left,right):
# res = [None]*(len(left) + len(right))
# index = i = j = 0
# while i < len(left) and j < len(right):
# if left[i] < right[j]:
# res[index] = left[i]
# i+=1
# else:
# res[index] = right[j]
# j+=1
# index+=1
#
# while i < len(left):
# res[index] = left[i]
# i+=1
# while j < len(right):
# res[index] = right[j]
# j+=1
# return res
# Ans2
# Quick sort
class Solution:
def sortArray(self,nums):
if len(nums) <= 1: return nums
less, greater, base = [], [], nums.pop()
for i in nums:
if i < base: less.append(i)
else: greater.append(i)
return self.sortArray(less) + [base] + self.sortArray(greater)
if __name__ == "__main__":
nums = [5,1,1,2,0,0]
result = Solution().sortArray(nums)
print(result)
| true |
23c2f482634f56050661839b46028b0eb9ebb876 | stijndcl/plus | /plus/plus.py | 2,367 | 4.28125 | 4 | cache = {}
def plus(first, second):
"""
Main function that checks certain conditions
"""
# Check if both arguments are integers
if not (isinstance(first, int)):
raise TypeError(f"First argument ({first}) is not an integer.")
if not (isinstance(second, int)):
raise TypeError(f"Second argument ({second}) is not an integer.")
# The function does -1 until both arguments reach 0,
# so this isn't possible for negative integers
if first < 0:
raise ValueError(f"First argument ({first}) is a negative integer.")
if second < 0:
raise ValueError(f"Second argument ({second}) is a negative integer.")
return _plusRecursive(first, second)
def _plusRecursive(first, second):
"""
Recursive plus function so that all checks only have to happen once
in the main function above
"""
# If this pair already exists, get it from the cache
if _isPresent(first, second):
return _get(first, second)
# Three base cases
if first == 1 and second == 0:
return 1
if first == 0 and second == 1:
return 1
if first == 0 and second == 0:
return 0
# First number is 0, second isn't:
# decrement the second number until it also reaches 0 & add 1
if first == 0:
val = _plusRecursive(1, _plusRecursive(first, second - 1))
# Add the result to the cache in case it isn't in there yet
if not _isPresent(first, second):
_add(first, second, val)
return val
# First number is not 0, second is
# Base-Base case to add 1 to something without using
# the '+'-operator
a = _plusRecursive(first - 1, second)
b = 1
while b != 0:
data = a & b
a = a ^ b
b = data << 1
return a
def _isPresent(first, second):
"""
Check if a pair is present in the cache
"""
global cache
a, b = min(first, second), max(first, second)
return a in cache and b in cache[a]
def _add(first, second, result):
"""
Add a pair into the cache
"""
global cache
a, b = min(first, second), max(first, second)
cache[a] = {b: result}
def _get(first, second):
"""
Return a pair from the cache, assuming it exists
"""
global cache
a, b = min(first, second), max(first, second)
return cache[a][b]
| true |
b19f180b2d1f032788ff99500892bc49daf61bb3 | Aunik97/Iteration | /stretch 1.py | 444 | 4.1875 | 4 | # Write a program that asks for a number and displays the squares
# of all the integers between 1 and this number inclusive.
# It should print 5 values on each line in neat columns.
count = -1
number = int(input("please enter a number"))
while count <= number:
count = count + 1
if count <= number:
total = (number - count )** 2
print("{0}".format(total)
else:
print("programe end")
| true |
b61b6d769a606cd6c55ba3696d0b0c6566f1db66 | nasraaden/coding-challenges | /intro/growingPlant.py | 761 | 4.5 | 4 | '''
Caring for a plant can be hard work, but since you tend to it regularly, you have a plant that grows consistently. Each day, its height increases by a fixed amount represented by the integer upSpeed. But due to lack of sunlight, the plant decreases in height every night, by an amount represented by downSpeed.
Since you grew the plant from a seed, it started at height 0 initially. Given an integer desiredHeight, your task is to find how many days it'll take for the plant to reach this height.
'''
def growingPlant(upSpeed, downSpeed, desiredHeight):
height = 0
counter = 0
while height < desiredHeight:
height += upSpeed
if height < desiredHeight:
height -= downSpeed
counter += 1
return counter
| true |
27a5e76f9cfced518095442cb87eb37f52dc3460 | nasraaden/coding-challenges | /intro/adjacentElementsProduct.py | 714 | 4.15625 | 4 | '''
Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
'''
def adjacentElementsProduct(inputArray):
# USING A DICTIONARY
# my_dict = {}
# loop through array, multiply adjacent numbers and store the products in a dictionary, then return max of that dictionary
# for i in range(len(inputArray) - 1):
# my_dict[inputArray[i] * inputArray[i+1]] = 0
# return max(my_dict)
# WITHOUT A DICTIONARY
max_num = -1000
for i in range(len(inputArray) - 1):
product = inputArray[i] * inputArray[i+1]
if product > max_num:
max_num = product
print(max_num)
return max_num
| true |
eab7f3c32aa83bd479343569708a12ad836ffa5e | nasraaden/coding-challenges | /intro/alphabeticShift.py | 549 | 4.15625 | 4 | '''
Given a string, your task is to replace each of its characters by the next one in the English alphabet; i.e. replace a with b, replace b with c, etc (z would be replaced by a).
'''
def alphabeticShift(inputString):
letters = 'abcdefghijklmnopqrstuvwxyz'
inputString = list(inputString)
for i in range(len(inputString)):
if inputString[i] == 'z':
inputString[i] = 'a'
else:
index = letters.index(inputString[i])
inputString[i] = letters[index + 1]
return "".join(inputString)
| true |
a45ca7a7d9488b80c18bb19277f022ddd5845d57 | nasraaden/coding-challenges | /intro/checkPalindrome.py | 288 | 4.15625 | 4 | '''
Given the string, check if it is a palindrome.
'''
def checkPalindrome(inputString):
s = ''
reversedString = s.join(reversed(inputString))
# compare reversed string to input string
if reversedString == inputString:
return True
else:
return False
| true |
dc5e1e5262fd38450858bffbac7f272677180878 | MarketaR/engeto-hackathon | /credit_card.py | 1,337 | 4.5 | 4 | # -*- coding: utf-8 -*-
# --------------------skeleton of credit card validator--------------------
card_number = str(input("Enter credit card number you want to check: "))
card_number = '4012888888881881'
# Reverse the credit card number
reversed_card_number = card_number[:: -1]
print(reversed_card_number)
# take the digits in the odd positions and then the digits in the even position
even_numbers = reversed_card_number[1::2]
print(even_numbers)
odd_numbers = reversed_card_number[::2]
print(odd_numbers)
# Add up all the digits in the odd positions into a total.
total = 0
for number in odd_numbers:
number = int(number)
total += number
print(total)
# Multiply every even-positioned digit by two;
# if the product is greater than 9 (e.g. 8 * 2 = 16),
# then subtract 9 and add the result to the total.
# Otherwise add the multiplication product to the total.
for number in even_numbers:
result = int(number) * 2
if result > 9:
total += (result - 9)
else:
total += result
print(total)
# If the total is divisible by 10 (the remainder after division by 10 is equal to 0 or the number ends in a zero);
# then the credit card number is valid.
checksum = int(total) % 10
if checksum == 0:
print("Your credit card is valid")
else:
print("Your credit card is not valid")
| true |
d3b9ea2fffa7675a3e7a0d9fff056f4843bc874e | GigotH/python | /section 1/python_notes_dictionaries.py | 813 | 4.59375 | 5 | """
dictionairies (keys/values)
"""
friend_ages = {"Eli": 61, "Gigot": 57, "Armin": 22}
print(friend_ages["Eli"])
friend_ages["Oma"] = 98
print(friend_ages["Oma"])
print(friend_ages)
"""
tuple containing a dictionary
"""
friends = (
{"name": "Eli Hudspth", "age": 61},
{"name": "Gigot Hudspeth", "age": 57},
{"name": "Armin Hudspeth", "age": 22}
)
print(friends[0]["name"])
# A dictionary key's value can be assigned to a variable, then the variable used instead of the key's index number:
friend = friends[2]
print(friend["name"])
print(friends[0]["name"])
print(friends[1]["name"])
print(friends[2]["name"])
# dict function
# list of tuples:
friends = [("Eli", 61), ("Gigot", 57), ("Armin", 22)]
# turn it into a dictionary using the "dict" function:
friend_ages2 = dict(friends)
print(friend_ages2)
| false |
7529f46281ff3075e543859f6de3a2232737b521 | Kollaider/CheckiO | /checkio/home/first_word.py | 828 | 4.25 | 4 | """First Word.
URL: https://py.checkio.org/en/mission/first-word/
DESCRIPTION:
You are given a string where you have to find its first word.
When solving a task pay attention to the following points:
There can be dots and commas in a string.
A string can start with a letter or, for example, a dot or space.
A word can contain an apostrophe and it's a part of a word.
The whole text can be represented with one word and that's it.
INPUT/OUTPUT EXAMPLE:
first_word("Hello world") == "Hello"
first_word("greetings, friends") == "greetings"
"""
import re
def first_word(text: str) -> str:
pattern = r"[\w']+"
return re.findall(pattern, text)[0]
def main():
print(f"first_word('Hello world') == {first_word('Hello world')}")
if __name__ == '__main__':
main()
| true |
1aff43d83a90efba4fde667f275b781b1f2592a6 | Kollaider/CheckiO | /checkio/home/between_markers.py | 1,412 | 4.40625 | 4 | """Between markers.
URL: https://py.checkio.org/en/mission/between-markers/
DESCRIPTION:
You are given a string and two markers (the initial and final).
You have to find a substring enclosed between these two markers.
But there are a few important conditions:
The initial and final markers are always different.
If there is no initial marker, then the first character
should be considered the beginning of a string.
If there is no final marker, then the last character
should be considered the ending of a string.
If the initial and final markers are missing then
simply return the whole string.
If the final marker comes before the initial marker,
then return an empty string.
INPUT/OUTPUT EXAMPLE:
between_markers('What is >apple<', '>', '<') == 'apple'
between_markers('No[/b] hi', '[b]', '[/b]') == 'No'
"""
def between_markers(text: str, begin: str, end: str) -> str:
b, e = text.find(begin), text.find(end)
if b == -1 and e == -1:
return text
if b == -1:
return text[:e]
if e == -1:
return text[b + len(begin):]
if b >= 0 and e >= 0:
return text[b + len(begin):e]
return ''
def main():
print(
f"between_markers('What is >apple<', '>', '<') == "
f"{between_markers('What is >apple<', '>', '<')}")
if __name__ == '__main__':
main()
| true |
15d14cfe6cc972760081904abe9738cfccf25ffe | Kollaider/CheckiO | /checkio/elementary/all_upper_1.py | 643 | 4.53125 | 5 | """All Upper I.
URL: https://py.checkio.org/en/mission/all-upper/
DESCRIPTION:
Check if a given string has all symbols in upper case.
If the string is empty or doesn't have any letter
in it - function should return True.
INPUT/OUTPUT EXAMPLE:
is_all_upper('ALL UPPER') == True
is_all_upper('all lower') == False
is_all_upper('mixed UPPER and lower') == False
is_all_upper('') == True
"""
def is_all_upper(text: str) -> bool:
return all(text.isupper() for ch in text if ch.isalpha())
def main():
print(f"is_all_upper('ALL UPPER') == {is_all_upper('ALL UPPER')}")
if __name__ == '__main__':
main()
| true |
9a5e8bbef1fbb0713f2d6444337a4cecc7d81f00 | Kollaider/CheckiO | /checkio/elementary/backward_string.py | 503 | 4.1875 | 4 | """Backward string.
URL: https://py.checkio.org/en/mission/backward-string/
DESCRIPTION:
You should return a given string in reverse order.
INPUT/OUTPUT EXAMPLE:
backward_string('val') == 'lav'
backward_string('') == ''
backward_string('ohho') == 'ohho'
backward_string('123456789') == '987654321'
"""
def backward_string(val: str) -> str:
return val[::-1]
def main():
print(f"backward_string('val') == {backward_string('val')}")
if __name__ == '__main__':
main()
| false |
6143bb40947908774a057f9fdd6785bf784622fe | yulifromchina/python-exercise | /DesignMode/CompositeMethod.py | 1,212 | 4.125 | 4 | # -*- coding:utf-8 -*-
import abc
class Worker(object):
"""
员工抽象类
"""
__metaclass__ = abc.ABCMeta
def __init__(self, name):
self.name = name
@abc.abstractmethod
def work(self):
pass
class Employee(Worker):
"""
员工类
"""
__metaclass__ = abc.ABCMeta
def work(self):
print('Employee %s start to work' % self.name)
class Leader(Worker):
"""
领导类
"""
def __init__(self, name):
self.members = []
super(Leader, self).__init__(name)
def add_member(self, employee):
if employee not in self.members:
self.members.append(employee)
def remove_member(self, employee):
if employee in self.members:
self.members.remove(employee)
def work(self):
print('Leader %s start work' % self.name)
for employee in self.members:
employee.work()
if __name__=='__main__':
employee1 = Employee('employee1')
employee2 = Employee('employee2')
leader1 = Leader('leader1')
leader1.add_member(employee1)
leader1.add_member(employee2)
leader1.work() | false |
3def7b80a5a0f048754372f9ff9de5f40ced665e | rfm110/Tower_of_Hanoi | /recursive_tower_of_hanoi.py | 1,844 | 4.15625 | 4 | def recursive_tower_of_hanoi(pin_1=[4,3,2,1], pin_2=[], pin_3=[], number_of_disks=4):
# change parameter names so they are more general? like source, target, and intermediate
if pin_3 == [4, 3, 2, 1]:
print "Game Completed"
return pin_1, pin_2, pin_3
# let pin_1 be the source, pin_2 be the intermediate, and pin_3 be the destination
# instead of using while loop, make function call itself
print "Current Game State:", pin_1, pin_2, pin_3
print
# if pin_3 != [4,3,2,1]:
if number_of_disks != 0:
# move disk from source to intermediate so pin_2 is the new target
print "Moving disk from source to intermediate"
print "recursion a"
recursive_tower_of_hanoi(pin_1, pin_3, pin_2, number_of_disks-1)
print "number of disks a", number_of_disks
print "source", pin_1
print "intermediate", pin_3
print "target", pin_2
print
# when source is not empty, move disk from source to target (pin_1 to pin_3)
if pin_1 != []:
# pin_3.append(pin_1[len(pin_1)-1])
print "Source is non-empty, moving disk from pin1(source) to pin3(target)"
pin_3.append(pin_1.pop())
print "source", pin_1
print "intermediate", pin_2
print "target", pin_3
print
# step 3 is moving disk from intermediate to target, from pin_2 to pin_3
print "Moving disk from intermediate to target"
print "recursion b"
recursive_tower_of_hanoi(pin_2, pin_1, pin_3, number_of_disks-1)
print "number of disks b", number_of_disks
print pin_2, pin_1, pin_3
print "source", pin_2
print "intermediate", pin_1
print "target", pin_3
print
if __name__ == "__main__":
recursive_tower_of_hanoi()
| true |
a66ab51e6e646ecc542af35e71583e62c29c2605 | faille/repo1 | /githomework_sans_list.py | 576 | 4.1875 | 4 | sum_numbers = 0
max_value = None
min_value = None
n_numbers = 0
while sum_numbers < 20:
number = input("Donne moi un chiffre: ")
number = int(number)
if n_numbers == 0:
max_value = number
min_value = number
else:
if number < min_value:
min_value = number
elif number > max_value:
max_value = number
n_numbers += 1
sum_numbers += number
print("Nombre de chiffre entrés: " + str(n_numbers))
print("Valeur minimum entrée: " + str(min_value))
print("Valeur maximum entrée: " + str(max_value)) | false |
67006ed6751e20a5a397495e7f4d30dabfb21dce | ericsu378/Miller_Python_DS_Alg | /Chapter1/ch1_10_selfcheck.py | 2,553 | 4.15625 | 4 | __author__ = 'ESU'
# Problem Solving with Algorithms and Data Structures [Online]
# http://interactivepython.org/
# Brad Miller, David Ranum
# Activecode 8
# The following code fragment iterates over a list of strings and for each string processes each character
# by appending it to a list. The result is a list of all the letters in all of the words.
# Self Check
# Test your understanding of what we have covered so far by trying the following exercise. Modify the code from
# Activecode 8 so that the final list only contains a single copy of each letter.
# The answer is: ['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']
# Self Check 2
# Test your understanding of list comprehensions by redoing Activecode 8 using list comprehensions.
# For an extra challenge, see if you can figure out how to remove the duplicates.
# the answer is: ['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't']
# Activecode 8
wordlist = ['cat','dog','rabbit']
letterlist = [ ]
for aword in wordlist:
for aletter in aword:
letterlist.append(aletter)
print("Active Code 8")
print(letterlist)
# Self Check 1
# Modify the code from Activecode 8 so that the final list only contains a single copy of each letter.
# Option 1
wordlist = ['cat','dog','rabbit']
letterlist = [ ]
for aword in wordlist:
for aletter in aword:
if aletter not in letterlist:
letterlist.append(aletter)
print("Self Check 1 - Option 1")
print(letterlist)
# Option 2 (unordered)
print("Self Check 1 - Option 2(unordered)")
print(list(set(letterlist)))
# Self Check 2
# Test your understanding of list comprehensions by redoing Activecode 8 using list comprehensions.
# For an extra challenge, see if you can figure out how to remove the duplicates.
wordlist = ['cat','dog','rabbit']
print("Self Check 2 - list comprehension")
letterlist = [aletter for aword in wordlist for aletter in aword]
print(letterlist)
print("Self Check 2 - list comprehension w/ join")
letterlist = [aletter for aletter in "".join(wordlist)]
print(letterlist)
print("Self Check 2 - list comprehension w/ range")
letterlist = [word[i] for word in wordlist for i in range(len(word))]
print(letterlist)
# Filtering During Comprehension : Single Lined Version
print("Self Check 2 Challenge - remove duplicates while keeping order")
seen = set()
seen_add = seen.add
print([letter for word in wordlist for letter in word if not (letter in seen or seen_add(letter))])
print("Self Check 2 Challenge - Unordered")
unique_letterlist = list(set(letterlist))
print(unique_letterlist)
| true |
89d548863f536dea8ce679a7619f198901cd0f17 | JZSang/algorithms | /DailyProblem/day2.py | 1,148 | 4.21875 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Uber.
Given an array of integers,
return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
For example,
if our input was [1, 2, 3, 4, 5],
the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
Follow-up: what if you can't use division?
"""
def main(array):
left_side = []
j = 1
for i in array:
j *= i
left_side.append(j)
# left_side = [1,2,6,24,120]
array_length = len(array)
j = 1
for i in reversed(range(array_length)):
j *= array[i]
array[i] = j
# array = [120,120,60,20,5]
for i in range(len(array)):
left_side_value = left_side[i-1] if i > 0 else 1
right_side_value = array[i+1] if i < len(array) - 1 else 1
array[i] = left_side_value * right_side_value
return array
# answer = [120,60,40,30,24]
if __name__ == "__main__":
test_array = [1, 2, 3, 4, 5]
print(main(test_array))
| true |
7f076d39694a2c7328fa31d496befa87ef9b8e14 | JZSang/algorithms | /DailyProblem/day12.py | 817 | 4.34375 | 4 | """
This problem was asked by Amazon.
There exists a staircase with N steps,
and you can climb up either 1 or 2 steps at a time.
Given N, write a function that returns the number of unique ways you can climb the staircase.
The order of the steps matters.
For example, if N is 4, then there are 5 unique ways:
1, 1, 1, 1
2, 1, 1
1, 2, 1
1, 1, 2
2, 2
What if, instead of being able to climb 1 or 2 steps at a time,
you could climb any number from a set of positive integers X?
For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
"""
# dynamic programming
def main(stairs, steps):
dp = [1]
for i in range(1, stairs + 1):
dp.append(0)
for step in steps:
if i - step >= 0:
dp[i] += dp[i-step]
return dp[-1]
print(main(4, [1,3,5]))
| true |
3451a18ce57a61d06aef95b92132d1b0ec00db43 | zablanc91/pythonFiles | /pythonFiles/flattenList.py | 531 | 4.1875 | 4 | """
This function takes a list and puts all individual primitives and variables that
aren't lists into a single list. The function uses recursion to arrive to the
answer.
Example:
>>> dummy = [ [1,2], [3, [4,[5,6]]]]
>>> flattenList(dummy)
[1, 2, 3, 4, 5, 6]
"""
def flattenList(test_list):
if isinstance(test_list, list):
if len(test_list) == 0:
return []
first = test_list[0]
rest = test_list[1:]
return flattenList(first) + flattenList(rest)
else:
return [test_list]
| true |
c0988a8a6286437ad6d1846cbe4af286c06e92b6 | yastil01/python_tips | /binarySeach.py | 661 | 4.1875 | 4 | def binarySearch(target):
left, right = 0, len(nums) - 1
while left < right:
mid = left + (right - left) // 2
if target <= nums[mid]:
right = mid
else:
left = mid + 1
return left
1. if the array has duplicates, this will return 1st occurance of the target
[9,9,9,9] -> ans will be 0
2. if target > nums[-1], it will return last index
3. if target < nums[0], it will return 0
4. if you find a match, left==right==mid
5. if you don't find a match, it will return insert location
| true |
58f43827b74cdb2d0c90db32dc3888a84303a6eb | yastil01/python_tips | /one_liners.py | 1,034 | 4.28125 | 4 | - when you append something in the list, just think if there is a chance that None will get appended.
This can fail the code in many corner cases. if there are chances that None will be in the list, while popping
check if the popped element is not None and then only do other things
- when you use 'and' condition in if, try breaking both condition and see if the code works fine. Sometimes,
if you don't be careful to check both conditions, code will go and execute else part which is not desired
for example, in backspace string example. # represents backspace and you need to make a string with backspece effect
intuituvely you might write this
for char in s:
if char == '#' and stack:
stack.pop()
else:
stack.append(char)
Now lets take this string s = '#abc'. In this case, # will also be appended in the stack which is not expected
fix should be like this
for char in s:
if char != '#':
stack.append(char)
else:
if stack:
stack.pop()
| true |
9684741aa16448e5c9191e4ff457e8e187a01309 | Levon187/ufar-python | /lesson8/iterators.py | 617 | 4.125 | 4 | numbers = [2, 5, 4, 6, 7]
def power(n):
return n**2
new_numbers = []
for number in numbers:
new_numbers.append(power(number))
# print("__iter__" in numbers.__dir__())
# n1 = 5
# print("------------------------")
# print("__iter__" in n1.__dir__())
it = iter(numbers)
while True:
try:
x = next(it)
except StopIteration:
break
new_numbers.append(power(x))
print(new_numbers)
print(list(range(20))[10]) # this created 20-elemnt list from 0 to 19 and prints the 10-th element
print((range(20)[10])) # this runs next() 10 times to get the element instead of 20 times | true |
bd3b61a91d61f40616d58603075362dbc9c1c9cf | F820914768/Stevens_Bia660 | /HW5/store.py | 2,562 | 4.125 | 4 | # -*- coding: utf-8 -*-
from queue import Queue
class BaseQueue(Queue):
'''
A queue that will not put the object that has been stored before
>>> q_test = BaseQueue()
>>> q_test.put(1); q_test.put(1); q_test.put(2)
>>> print(q_test.get(), q_test.get())
>>> (1, 0) (2, 0)
'''
def __init__(self):
super().__init__()
self.visited_ = {}
def put(self, item, i=0):
if item not in self.visited_:
super().put(item)
self.visited_[item] = i
def get(self):
item = super().get()
depth = self.visited_[item]
return item, depth
class KeyWordQueue(BaseQueue):
'''
A queue that only store an object once, \
and only put object into queue when there are certain key words in the object
>>> q_test = KeyWordQueue('book', 'txt')
>>> q_test.put('I'); q_test.put('book1'); q_test.put('.txt')
>>> print(q_test.get(), q_test.get())
>>> ('I', 0) ('book1', 0)
'''
def __init__(self, *key_words):
super().__init__()
self.key_words = [keyword for keyword in key_words]
def put_after_filter(self, item, depth=0):
for key_word in self.key_words:
if key_word in item:
super().put(item, depth)
print('+'*20, '\n', 'put: ', item)
return None
class BaseStack(list):
'''
A stack that will not put the object that has been stored before
'''
def __init__(self):
super().__init__()
self.visited_ = {}
def put(self, item, i=0):
if item not in self.visited_:
super().append(item)
self.visited_[item] = i
def get(self):
item = super().pop()
depth = self.visited_[item]
return item, depth
class KeyWordStack(BaseStack):
'''
A stack that only store an object once, \
and only put object into queue when there are certain key words in the object
'''
def __init__(self, *key_words):
super().__init__()
self.key_words = [keyword for keyword in key_words]
def put_after_filter(self, item, depth=0):
for key_word in self.key_words:
if key_word in item:
super().put(item, depth)
print('+'*20, '\n', 'put: ', item)
return None
if __name__ == "__main__":
q_test = BaseStack()
q_test.put('a')
q_test.put('a')
q_test.put('b')
print(q_test.get())
print(q_test.get()) | true |
f149eeb7573c4dd9fa475c6a806f9d28f0b4b445 | AdarshRaveendran/pythonprogram | /trainseatpython.py | 400 | 4.15625 | 4 |
N=int(input("Enter seat Number"))#input from the user
if N>0 and N<73:#seats less than 73
if N%8 == 1 or N%8 == 4:
print ("L")# lower seat
elif N%8 == 2 or N%8 == 5:
print("M")# middle seat
elif N%8==3 or N%8==6:
print("U")#upper seat
elif N%8==7:
print("SL")#side lower seat
else:
print("SU")#side upper seat
else:
print("invalid seat number")
| false |
ff84aab5916462330a09149b9826faca82756905 | mattmakesmaps/python-junk | /classes/comp_inherit.py | 1,448 | 4.3125 | 4 | __author__ = 'matt'
__date__ = '6/30/13'
"""
This example demonstrates the use of class inheritance (Points --> MultiPoints)
and compositions (Points --> Lines)
"""
class Point(object):
"""
This class represents an X,Y point.
"""
def __init__(self, x, y):
self.x = x
self.y = y
self.coordinates = [self.x,self.y]
def __str__(self):
return "Point Object: %s, %s" % (self.x, self.y)
class PositiveCheckPoint(Point):
"""
A subclass of point with an additional method
to determine if the coordinates are positive.
"""
def is_Positive(self):
for coord in self.coordinates:
if coord < 0:
return False
else:
return True
class Line(object):
"""
This class represents a line, comprised of two point objects.
"""
def __init__(self, startX, startY, endX, endY):
self.start = Point(startX, startY)
self.end = Point(endX, endY)
def __str__(self):
return "A line with start coordinates: %s and end coordinates %s" % (self.start.__str__(), self.end.__str__())
if __name__ == '__main__':
p1 = Point(8,3)
print p1
p2 = Point(2,1)
print p2
l1 = Line(p1.x, p1.y, p2.x, p2.y)
print l1
posP1 = PositiveCheckPoint(9,2)
print posP1
print posP1.is_Positive()
posP2 = PositiveCheckPoint(-9,1)
print posP2
print posP2.is_Positive()
| true |
2a2569dae087cd4e159cfbbb1a8e19c29663bb13 | varunsinghal/data-structures-python | /1.3_keeping_last_n_terms.py | 379 | 4.34375 | 4 | #Keeping only last N terms in memory
from collections import deque
d = deque(maxlen=3)
d.append(1)
d.append(2)
d.append(3)
print d
#Output: deque([1, 2, 3], maxlen=3)
d.append(4)
print d
#Output: deque([2, 3, 4], maxlen=3)
'''
The complexity of inserting or removing an element from the list data type is O(N).
But in the case of deque the complexity reduces to O(1).
'''
| true |
f8785fe8f49212446e2722d47be02129162b756d | ahsan-fayyaz/Algorithms | /Merge_Sort/mergeSort.py | 1,087 | 4.125 | 4 | import math
def mergeSort(A, left, right):
if (left < right):
mid = math.floor((left + right) / 2)
mergeSort(A, left, mid)
mergeSort(A, mid + 1, right)
merge(A, left, mid, right)
def merge(A, low, mid, high):
n1 = mid - low + 1
n2 = high - mid
left_subArray = [0] * (n1)
right_subArray = [0] * (n2)
for i in range(0, n1):
left_subArray[i] = A[low + i]
for j in range(0, n2):
right_subArray[j] = A[mid + j + 1]
i = 0;
j = 0
k = low
while (i < n1 and j < n2):
if left_subArray[i] <= right_subArray[j]:
A[k] = left_subArray[i]
i=i+1
else:
A[k] = right_subArray[j]
j=j+1
k += 1
while (i < n1):
A[k] = left_subArray[i]
i += 1
k += 1
#--------------DRIVER CODE------------------#
arr = [12, 11, 13, 5, 6, 7]
n = len(arr)
print ("Given array is")
for i in range(n):
print ("%d" %arr[i]),
mergeSort(arr,0,n-1)
print ("\n\nSorted array is")
for i in range(n):
print ("%d" %arr[i]),
| false |
f56b961c7e59ad4c52994900c721460fc590e7de | sagar8080/Algorithms | /Shell_Sort.py | 1,671 | 4.25 | 4 | 1#IMPLEMENT SHELL SORT
def shellsort(userlist): #Function to shell sort a user input list
SubListCount = len(userlist)//2 #Sublists are the division of user input list into requisite gap lengths
while (SubListCount>0): #Iteration on the sublists until the Sublist_count drops to 1, which is the final insertion sort
for StartPosition in range(SubListCount): #Iterate start position on the sublist and
Gap_Insertion_Sort(userlist, StartPosition, SubListCount)
SubListCount = SubListCount//2
return userlist
def Gap_Insertion_Sort(userlist, start, gap): #Isertion sort function
for i in range(start+gap,len(userlist),gap): #iterate over the list in spaces of lengths = gap, if gap = 1, it becomes a standard insertion sort
current_value = userlist[i] #the first value encounterd on iteration at index i is assumed to be the current value
position = i #the current position is the index number and we have to iterate the list in the gap fixed initially
while (position>=gap and userlist[position-gap]>current_value): #if the value at new index at length start+gap is greater the current value swap them
userlist[position] = userlist[position-gap] #swap
position = position - gap #Go to next position
userlist[position] = current_value #Store the value at the old index
if __name__ == '__main__': #main function to run the program
s = input() #Raw input string received from the user separated by a comma *important
userlist = list(map(int, s.split(","))) #Map the input to a list
print("sorted list: ", shellsort(userlist)) #Print the sorted list
| true |
bd15b91c64046e8b1bb2f63f0276a95d7fdc960e | sagar8080/Algorithms | /Divide_and_Conquer/Combination_repitition.py | 1,278 | 4.1875 | 4 |
# Function combination takes in input sequence and the size of combination
def combination(input_sequence, combination_size):
length_of_input = len(input_sequence)
temp_sequence = [0] * combination_size
divideconquer(input_sequence, temp_sequence, 0, length_of_input - 1, 0, combination_size)
# divide nd conquer function takes in 5 arguments and is called recursively to generate
# tree like structure for each iterable in the input sequence
def divideconquer(input_sequence, temp_sequence, start, end, index, combination_size):
if (index == combination_size):
for j in range(combination_size):
print(temp_sequence[j])
print()
return
else:
i = start
while (i <= end):
temp_sequence[index] = input_sequence[i]
# Divide and conquer starts from the current node irrespective of whether it has been selected or not
# It doesn't start from i+1
divideconquer(input_sequence, temp_sequence, i, end, index + 1, combination_size)
i += 1
if __name__ == '__main__':
input_sequence = input("enter the input sequence ").split(" ")
combination_size = int(input("enter the size of combination "))
combination(input_sequence, combination_size)
| true |
98fa89be55d842854443d7aad25847fcb106a0c8 | marczalik/discrete-math | /binary_multiplication.py | 799 | 4.15625 | 4 | # Multiplies the binary expansions of 2 integers
from binary_addition import bin_add
def bin_multiply(a, b):
"""
a: a list, the binary expansion of an integer
b: a list, the binary expansion of an integer
Returns a list of the digits in the binary expansion of the product of 2 integers
"""
b.reverse()
n = len(b)
c = []
for j in range(0, n):
if b[j] == 1:
temp_a = a[:]
for x in range(j):
temp_a.append(0)
c.append(temp_a)
else:
c.append([0])
if n > 1:
p = bin_add(c[0], c[1])
for k in range(2, len(c)):
p = bin_add(p, c[k])
else:
p = c[0]
return p
print(bin_multiply([1, 1, 0, 0], [1, 0, 1, 1, 1]))
| true |
43b222c38a4cae0158d54d5d2ed446b9994c78a1 | leesen934/leetcode_practices | /496. 下一个更大元素.py | 2,465 | 4.125 | 4 | # 给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。
#
# nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出-1。
#
# 示例 1:
#
# 输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
# 输出: [-1,3,-1]
# 解释:
# 对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。
# 对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。
# 对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。
# 示例 2:
#
# 输入: nums1 = [2,4], nums2 = [1,2,3,4].
# 输出: [3,-1]
# 解释:
# 对于num1中的数字2,第二个数组中的下一个较大数字是3。
# 对于num1中的数字4,第二个数组中没有下一个更大的数字,因此输出 -1。
# 注意:
#
# nums1和nums2中所有元素是唯一的。
# nums1和nums2 的数组大小都不超过1000。
class Solution:
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
# stack 建立map ----------------------------
dic = {}
stack = []
res = []
for i in range(len(nums2)):
while len(stack) > 0 and nums2[i] > stack[-1]:
dic[stack.pop()] = nums2[i]
stack.append(nums2[i]) # 使用dict.get()设置默认值的方法,可以不用考虑对找不到更大值的元素设置-1的问题
for j in range(len(nums1)):
res.append(dic.get(nums1[j], -1)) # 用dict.get()可以设置找不到key时的默认值,如果直接dict[key],则找不到时候会报错
return res
# 复杂度一般 ---------------------------------
res = []
for j in range(len(nums1)):
start = nums2.index(nums1[j])
for i in range(start, len(nums2)):
if nums2[i] > nums1[j]:
res.append(nums2[i])
break
else:
if i == len(nums2) - 1:
res.append(-1)
return res
s = Solution()
test1 = [2,4]
test2 = [1,2,3,4]
# print(s.nextGreaterElement([4,1,2], [1,3,4,2]))
print(s.nextGreaterElement(test1,test2)) | false |
1ee1d6b67b8c7d74c57b89e0114571c8b66075d2 | leesen934/leetcode_practices | /872. 叶子相似的树.py | 1,528 | 4.125 | 4 | # 请考虑一颗二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个叶值序列 。
#
# 如果有两颗二叉树的叶值序列是相同,那么我们就认为它们是叶相似的。
#
# 如果给定的两个头结点分别为root1和root2的树是叶相似的,则返回true;否则返回false 。
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def leafSimilar(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: bool
"""
# 因此可以借助堆栈的数据结构,由于堆栈是后进先出的顺序,由此可以先将右子树压栈,然后再对左子树压栈,
#
# 这样一来,左子树结点就存在了栈顶上,因此某结点的左子树能在它的右子树遍历之前被遍历。
leaf1 = self.leaf_dfs(root1)
leaf2 = self.leaf_dfs(root2)
return leaf1 == leaf2
def leaf_dfs(self,root):
if not root:
return []
stack = [root]
res = []
while stack:
node = stack.pop()
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
if not node.left and not node.right:
res.append(node.val)
return res
s = Solution()
print(s.leafSimilar()) | false |
b29b87a3f686489e10805f00b15d28c368af6de9 | leesen934/leetcode_practices | /反转链表.py | 1,481 | 4.28125 | 4 | # 反转一个单链表。
#
# 示例:
#
# 输入: 1->2->3->4->5->NULL
# 输出: 5->4->3->2->1->NULL
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def reverseList(head):
"""
:type head: ListNode
:rtype: ListNode
"""
# --------- 迭代 -------------------
if not head:
return []
prev = None
while head:
cur = head
head = head.next # If you do cur.next = prev before head = head.next, you are modifying head because it is
# not a deep copy.However, if you do curr = ListNode(head.val), this solution will work just fine.
cur.next = prev
prev = cur
return prev
# -------- 递归 -------------------
# def reverseList(self, head):
# return self._reverse(head)
#
# def _reverse(self, node, prev=None):
# if not node:
# return prev
# n = node.next
# node.next = prev
# return self._reverse(n, node)
# ------------------------------------------------------------------
def printList(node):
out = []
while node:
out.append(node.val)
node = node.next
print(out)
if __name__ == "__main__":
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node1.next = node2
node2.next = node3
node3.next = node4
printList(node1)
res = reverseList(node1)
printList(res) | true |
119fbd959d9cf820ad37dad0dc0cbd8a360f1e06 | SecretAardvark/Python | /hardway/solar.py | 436 | 4.15625 | 4 | weight = float(input("How much do you weigh?"))
Mercury = weight * 0.38
Venus = weight * 0.91
Mars = weight * 0.39
Jupiter = weight * 2.34
Saturn = weight * 1.06
Uranus = weight * 0.92
Pluto = weight *0.06
print(f"On Earth, you weigh {weight}. On other planets, you would weigh..."
, "\n Mercury: ",Mercury, "\n Venus: ",Venus, "\n Mars :",Mars,"\n Jupiter: ",Jupiter,"\n Saturn: ",Saturn, "\n Uranus: ",Uranus,"\n Pluto: ",Pluto,)
| true |
647d0100da71a26863ffcd18d04859fcc10148c1 | SecretAardvark/Python | /pycrashcourse/ex6-3.py | 1,196 | 4.34375 | 4 | glossary = {'variable': 'A reserved memory location to store a given value',
'string': 'A string in Python is an immutable sequence of characters.',
'dictionary': 'A dictionary in Python is a collection of key-value pairs.Each Key is connected to a Value, and you can use the key to access that value.',
'comment': 'A note you can leave in your program for others to read, usually used to explain what lines of code do.',
'float': 'a number used in Python with a decimal point',
'function': 'Python functions can be used to abstract pieces of vode to use elsewhere.',
'lists': 'A Python data type that holds an unordered collection of values.',
'FOR loop': 'Used in Python to iterate over a data set.',
'WHILE loop': 'Lets code execute repeatedly until a certain condition is met.',
'print()': 'A function that displays the output of a program.',
}
print("Variable: \n \t" + glossary['variable'] + "\n String: \n \t" + glossary['string'] + "\n Comment: \n \t" + glossary['comment']+ "\n Dictionary: \n \t" + glossary['dictionary']
+ "\n Float: \n \t" + glossary['float']
)
for key in glossary:
print(key.title() + ": \n \t" + glossary[key]) | true |
2caa816b326adf371c9514c7775d4f76f3253cc9 | SecretAardvark/Python | /pycrashcourse/ex9-13.py | 1,049 | 4.21875 | 4 | from collections import OrderedDict
glossary = {'variable': 'A reserved memory location to store a given value',
'string': 'A string in Python is an immutable sequence of characters.',
'dictionary': 'A dictionary in Python is a collection of key-value pairs.Each Key is connected to a Value, and you can use the key to access that value.',
'comment': 'A note you can leave in your program for others to read, usually used to explain what lines of code do.',
'float': 'a number used in Python with a decimal point',
'function': 'Python functions can be used to abstract pieces of vode to use elsewhere.',
'lists': 'A Python data type that holds an unordered collection of values.',
'FOR loop': 'Used in Python to iterate over a data set.',
'WHILE loop': 'Lets code execute repeatedly until a certain condition is met.',
'print()': 'A function that displays the output of a program.',
}
newdict = OrderedDict(sorted(glossary.items()))
for key in newdict:
print(key.title() + ": \n \t" + glossary[key]) | true |
3925c772e3f817abfd4497ee1c4dde0b599cb38c | premkashyap/PythonTrilogyPluralsight | /PythonGettingStarted/Module6/tuples.py | 960 | 4.375 | 4 | tup = () #Empty
print(type(tup))
tup = (123) #Not a single element tuples. as () is treated as mathematical operator
print(type(tup))
tup = (123,) #single element tuple
print(type(tup))
tup = (123, 'abc', ('prem', 'kashyap')) #multiple element tuple with nested tuple
print(tup[0], type(tup[0]))
print(tup[1], type(tup[1]))
print(tup[2], type(tup[2]))
tup = tuple(['delhi','mumbai']) #tuples from iterables using tuple constructor
tuptup = tup*2 #tuples support multiplication operator
print('len tup: ', len(tup), ' len tuptup: ', len(tuptup))
(a, b,(c,d)) = (1,2,(3,4)) #Tuple unpacking
print(a)
print(b)
print(c)
print(d)
tup = (1, 2,3,4,5 ,6,7, 8)
print(2 in tup) #containment operator
print(10 not in tup)
for i in tup:
print(i)
def maxmin(tup):
return max(tup), min(tup) #returning multiples values from function
max, min = maxmin(tup)
print('max: ', max, 'min: ', min)
tup[0] = 10 #once initialized tuples cant be changed. They are immutable. | true |
d68b4b82a959d23bf08afd974a501925345294c1 | baselGhaibour/tsp | /permutation.py | 798 | 4.15625 | 4 | def permutation(n):
"""Return all of the permutations of n elements.
Args:
n: number of elements
Returns:
all of the permutations of n elements
"""
numbers = [i for i in range(n)]
return list(permutation_generator(numbers))
def permutation_generator(array, perm=[]):
"""Generate a permutation of an array.
Args:
array: array whose permutation to generate
perm: permutation of array (You mustn't pass this argument)
Yields:
temp_perm: permutation of array
"""
for i in range(len(array)):
temp_array = array[:]
temp_perm = perm[:]
temp_perm.append(temp_array.pop(i))
if temp_array != []:
yield from permutation_generator(temp_array, temp_perm)
else:
yield temp_perm
| true |
08aa3ebb6a075f66eca4de07346ddafe88522203 | bledidalipaj/hackerrank | /map_and_lambda.py | 1,841 | 4.65625 | 5 | # Let's learn some new Python concepts! You have to generate a list of the first N fibonacci numbers, 0 being the first number. Then, apply
# the map function and a lambda expression to cube each fibonacci number and print the list.
# Concept
# The map() function applies a function to every member of an iterable and returns the result. It takes two parameters: first, the function
# that is to be applied and secondly, the iterables.
# Let's say you are given a list of names, and you have to print a list that contains the length of each name.
# >> print (list(map(len, ['Tina', 'Raj', 'Tom'])))
# [4, 3, 3]
# Lambda is a single expression anonymous function often used as an inline function. In simple words, it is a function that has only one
# line in its body. It proves very handy in functional and GUI programming.
# >> sum = lambda a, b, c: a + b + c
# >> sum(1, 2, 3)
# 6
# Note:
# Lambda functions cannot use the return statement and can only have a single expression. Unlike def, which creates a function and assigns
# it a name, lambda creates a function and returns the function itself. Lambda can be used inside lists and dictionaries.
# Input Format
# One line of input: an integer N.
# Constraints
# 0 <= N <= 15
# Output Format
# A list on a single line containing the cubes of the first N fibonacci numbers.
# Sample Input
# 5
# Sample Output
# [0, 1, 1, 8, 27]
n = int(raw_input().strip())
def fibs(n):
fib_seq = [0, 1]
i = 3
while i <= n:
fib_seq.append(fib_seq[-1] + fib_seq[-2])
i += 1
return fib_seq[:n] # beware that when n == 0 ([]) and n == 1 ([0]) we must use list indexing
# in order to get the correct results
seq = fibs(n)
seq = map(lambda x: x ** 3, seq)
print seq | true |
4010f4405423ad53293938a27341de78526cbebf | Jovus/Transfer-Window-Finder | /libs/vector.py | 1,949 | 4.34375 | 4 | from math import sqrt
def checkLength(a, b):
'''Given two vectors a and b, check to see if they're the same length. If not, raise an error.
If they are, return the length.'''
#technically you can do all the operations I want to with vectors of different lengths,
#by subbing in 0 for the elements of the shorter vector, but it's always better
#to explicitly fail and make the user be clear instead of assuming what
#he might want to do.
la = len(a)
lb = len(b)
if lb is not la:
raise IndexError('Vectors are not the same length!')
return len(a)
def add(a, b, op='add'):
'''Given two vectors a and b, return their sum (or difference)'''
l = checkLength(a,b)
if op=='add':
vect = [a[i]+b[i] for i in range(l)]
elif op=='sub':
vect = [a[i]-b[i] for i in range(l)]
else:
raise ValueError('Inappropriate value to "op" argument. Valid ops are add or subtract.')
return tuple(vect)
def sub(a, b):
'''Given two vectors a and b, return their difference.'''
#this is just a wrapper to make code easier to read. I suppose I could use a decorator, but I'm not yet comfortable with those
return add(a, b, op='sub')
def dot(a, b):
'''Given two vectors a and b, return their dot product.'''
l = checkLength(a, b)
return sum(a[i]*b[i] for i in range(l))
def cross(a, b):
'''a and b are three-dimensional vectors. Returns the cross product of AxB'''
l = checkLength(a, b)
if l is not 3:
raise ValueError('I can only work with 3-dimensional vectors.')
#might do this more easily by just calling a determinant function, but this works for now
i = a[1]*b[2] - a[2]*b[1] #first term of the cross product
j = a[2]*b[0] - a[0]*b[2] #second
k = a[0]*b[1] - a[1]*b[0] #third
return (i, j, k)
def mag(a):
'''Given a vector a, return its magnitude.'''
return sqrt(sum([elem**2 for elem in a]))
| true |
959ae1e8977b8268e497994d7b2645e036fa67a1 | nilsondo/SoccerScores | /tests/model/team.py | 1,181 | 4.125 | 4 | import unittest
from src.model.team import Team
class Test(unittest.TestCase):
'''
*1* - Instance & Properties:
1.0 - Team should be able to create an object instance.
1.1 - Team should only receive a string name.
*2* - Functions:
2.0 - Team must be able to return its own information.
'''
def setUp(self):
print ""
print "################################################"
def tearDown(self):
print "################################################"
def testOne(self):
team = Team(name='USA')
msg = "Team creation fail."
self.assertIsInstance(team, Team, msg) # 1.0
print "Team Test Set: 1.0 Success"
with self.assertRaises(Exception) as context:
team = Team(name=0)
msg = "Team receiving a string name fail"
self.assertEqual(context.exception.message,
"Invalid team name.") # 1.1
print "Team Test Set: 1.1 Success"
team = Team(name='Chile')
msg = "Team display information fail"
self.assertIsInstance(team.display(), str, msg) # 2.0
print "Team Test Set: 2.0 Success"
| true |
88150cbe6ea0fe3dcbcc47bce5d7790cbe20b4ff | amandanagai/bootcamp_prep | /codewars_str_calc.py | 444 | 4.28125 | 4 | # https://www.codewars.com/kata/string-calculator-with-different-input-types
def string_calc(string):
product = 0
acceptable = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
for item in string:
if item in acceptable:
if product == 0:
product = int(item)
else:
product *= int(item)
if product == 0:
print("Calculation failed")
else:
return product
print(string_calc("bad input")) | true |
f660bd3fd0ebd23bc8d8c37abf258ff5a967f110 | amandanagai/bootcamp_prep | /fctn_multiply_even_nums.py | 958 | 4.21875 | 4 | def multiply_even_numbers(num_list):
evens = []
product = 1
for num in num_list:
if num % 2 == 0:
evens.append(num)
if len(evens) == 0:
return 0
elif len(evens)==1:
return evens[0]
else:
for i in range(len(evens)):
product = product * evens[i]
return product
print(multiply_even_numbers([2, 5, 7, 8, 10]))
# do you want to consider 0 an even number? if so, the product of any list with 0 will be 0
from numpy import prod
def multiply_even_numbers_2(num_list):
evens = []
for num in num_list:
if num % 2 == 0:
evens.append(num)
if len(evens) == 0:
return 0
elif len(evens)==1:
return evens[0]
else:
for item in evens:
if item == 0:
evens.remove(item)
print(evens)
return prod(evens)
print(multiply_even_numbers_2([2, 5, 7, 8, 0, 0, 10]))
# else:
# if 0 in evens:
# ind = evens.index(0)
# evens.pop(ind)
# return prod(evens) | false |
12ba0235ec725db8fa7ded1129524a4c2c71f170 | fangniu/leetcode | /sorts/heap_sort.py | 1,041 | 4.1875 | 4 | # -*- coding: utf-8 -*-
import random
def heapify(unsorted, index, heap_size):
largest = index
left_index = 2 * index + 1
right_index = 2 * index + 2
if left_index < heap_size and unsorted[left_index] > unsorted[largest]:
largest = left_index
if right_index < heap_size and unsorted[right_index] > unsorted[largest]:
largest = right_index
if largest != index:
unsorted[largest], unsorted[index] = unsorted[index], unsorted[largest]
heapify(unsorted, largest, heap_size)
def heap_sort(unsorted):
n = len(unsorted)
for i in range(n // 2 - 1, -1, -1):
heapify(unsorted, i, n)
for i in range(n - 1, 0, -1):
unsorted[0], unsorted[i] = unsorted[i], unsorted[0]
heapify(unsorted, 0, i)
return unsorted
if __name__ == '__main__':
for _ in range(5):
array = list(range(20))
random.shuffle(array)
print('before:', array)
heap_sort(array)
print('after:', array)
print('=======================')
| true |
4798a1e4b0f3354e9f9cf0d1636e8b3ec2f0d8f6 | fangniu/leetcode | /sorts/selection_sort.py | 585 | 4.125 | 4 | # -*- coding: utf-8 -*-
import random
def selection_sort(collection):
length = len(collection)
for i in range(length):
min_i = i
for j in range(i+1, length):
if collection[j] < collection[min_i]:
min_i = j
collection[i], collection[min_i] = collection[min_i], collection[i]
if __name__ == '__main__':
for _ in range(5):
array = list(range(20))
random.shuffle(array)
print('before:', array)
selection_sort(array)
print('after:', array)
print('=======================')
| false |
071702e12600a2b8638c132d1b2cb50572ed2c4b | jamalainm/NovioraTempora | /utils/latin_language/list_to_string.py | 1,380 | 4.28125 | 4 | # file mygame/utils/latin/list_to_string.py
def list_to_string(inlist, endsep="et", addquote=False):
"""
This pretty-formats a list as string output, adding an optional
alternative separator to the second to last entry. If `addquote`
is `True`, the outgoing strings will be surrounded by quotes.
Args:
inlist (list): The list to print.
endsep (str, optional): If set, the last item separator will
be replaced with this value.
addquote (bool, optional): This will surround all outgoing
values with double quotes.
Returns:
liststr (str): The list represented as a string.
Examples:
```python
# no endsep:
[1,2,3] -> '1, 2, 3'
# with endsep=='and':
[1,2,3] -> '1, 2 and 3'
# with addquote and endsep
[1,2,3] -> '"1", "2" and "3"'
```
"""
if not endsep:
endsep = ","
else:
endsep = " " + endsep
if not inlist:
return ""
if addquote:
if len(inlist) == 1:
return '"%s"' % inlist[0]
return ", ".join('"%s"' % v for v in inlist[:-1]) + "%s %s" % (endsep, '"%s"' % inlist[-1])
else:
if len(inlist) == 1:
return str(inlist[0])
return ", ".join(str(v) for v in inlist[:-1]) + "%s %s" % (endsep, inlist[-1])
| true |
012a8239628c8d6fcf438e3a0f29800b80173227 | WinningLiu/SCU | /COEN/coen140/Lab 2/COEN140_Lab2_exercise1_Daren_Liu.py | 969 | 4.125 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import linear_model
# Get data
df = pd.read_csv(
filepath_or_buffer='data/trucks.csv',
header=None)
data = df.iloc[:,:].values
X = data[:,0].reshape(-1, 1)
Y = data[:,1].reshape(-1, 1)
#linear_model.LinearRegression
# Train the model using the training set only, then extract the slope and intercept
# Hint: look up the manual for linear_model.LinearRegression
regr = linear_model.LinearRegression()
regr.fit(X, Y)
slope = regr.coef_
intercept = regr.intercept_
print("y = %f + %fx" %(intercept, slope))
print("Mean squared error: %f"
% np.mean((regr.predict(X) - Y) ** 2))
# Explained variance score: 1 is perfect prediction
print('Variance score: %f' % regr.score(X, Y))
# Create a plot to show the XY points (in black) as well as the prediction line (in red)
plt.scatter(X, Y, color = "black")
plt.plot(X, regr.predict(X), color = "red", linewidth=3)
plt.show() | true |
1bc0fea0b915d678996f499490828034e8f58f0a | sakayaparp/CodeChef | /ALGORITHMS/Greedy/Car_Fueling/car_fueling.py | 1,272 | 4.25 | 4 | #You are going to travel to another city that is located 𝑑 miles away from your home city. Your can can travel
#at most 𝑚 miles on a full tank and you start with a full tank. Along your way, there are gas stations at
#distances stop1,stop2 , . . . ,stop𝑛 from your home city. What is the minimum number of refills needed?
def compute_min_refills(distance, tank, stops):# a function that returns the minimum no of refills required by implementing a greedy algorithm
# write your code here
if stops[0]>tank:
return -1
elif tank>=distance:
return 0
else:
current=0
num=0
while current<=len(stops)-2:
last=current
while (current<=len(stops)-2 and (stops[current+1]-stops[last]<=tank)):#checks the safe move i.e the max distance one could travel with a full tank
current+=1
if last==current:
return -1
if current<=len(stops)-2:
num+=1
return num
if __name__ == '__main__':
d=int(input())
m=int(input())
s=int(input())
stops=list(map(int,input().split()))
stops.insert(0,0)
stops.append(d)
print("The minimum no of refills required is/are:",compute_min_refills(d, m, stops))
| true |
49f7400732365ed0c725c7f6bf47bdc1a72e5306 | RumanBhuiyan/Most-Common-DSA-Topics | /Sorting/MergeSort.py | 1,311 | 4.21875 | 4 | # Best case,worst case,average case time complexity=O(nlogn)
def mergeSort(array):
if len(array)>1:
mid=len(array)//2 # 5//2=2(result or quotient)
leftArray=array[:mid] # copy elements from index 0 to mid
rightArray=array[mid:]# copy elements from index mid to rest
mergeSort(leftArray)
mergeSort(rightArray)
left=right=main=0
# compare leftArray & rightArray values & assign to returning array
while left<len(leftArray) and right<len(rightArray):
if leftArray[left] < rightArray[right]:
array[main]=leftArray[left]
left +=1
else :
array[main]=rightArray[right]
right +=1
main +=1
# store unstored items of leftArray to returning array
while left < len(leftArray):
array[main]=leftArray[left]
main +=1
left +=1
# store unstored items of rightArray to returning array
while right < len(rightArray):
array[main]=rightArray[right]
main +=1
right +=1
numbers=input()
numbers=list(numbers.split())
numbers=[int(x) for x in numbers]
mergeSort(numbers)
print(numbers)
| true |
510a182c03d9980b48af650a5168e876e710c0d3 | RumanBhuiyan/Most-Common-DSA-Topics | /Binary Search/RecursiveBinarySearch.py | 790 | 4.125 | 4 | def binarySearch(num,left,right,search):
mid =(left+right)//2
if left <= right :
if num[mid] == search :
return mid
elif num[mid] < search :
return binarySearch(num,mid+1,right,search)
else :
return binarySearch(num,left,mid-1,search)
else:
return -1
numbers=[]
print("Enter array size : ",end=" ")
size = int(input())
print("\nEnter sorted array elements : ",end=" ")
numbers=input();
numbers = numbers.split()
numbers =[int(x) for x in numbers]
print("\n Enter the number you wanna search: ",end=" ")
searchingItem=int(input())
index=binarySearch(numbers,0,len(numbers)-1,searchingItem)
if index==-1 :
print("\n Item not found")
else :
print(f'\n Item found at index : {index}') | true |
8b5b8812980dff3e2873a45c3ba2c59ba5db219d | gaip/CPSATSeleniumPython | /PythonPrograms/errorTypes.py | 313 | 4.25 | 4 | #Syntax Error
if(True):
print("true")
#RunTime Error
#numerator=111
#denominator=0
#print("hello")
#quotient=numerator/denominator
#Logical Error
#num1=int(input("enter num1-"))
#num2=int(input("enter num2-"))
#if(num1<num2):
# print("num1 is greater")
#else:
# print("num2 is greater")
| false |
1a1e877af89fc9414109abb6bb593a08d8fc258d | ShadeShiner/RayTracerChallenge-Python | /src/putting_it_together/ch3.py | 1,041 | 4.59375 | 5 | from src.VectorAndMatrix import Matrix
# 1. What happens when you invert the identity matrix?
def question_one():
print('1. What happens when you invert the identity matrix?')
print('You get this:')
m = Matrix.identity_matrix().submatrix(3, 3)
m = m.inverse()
for row in m.matrix:
print(row)
print('The Identity matrix again :)\n')
# 2. What do you get when you multiply a matrix by its inverse?
def question_two():
print('2. What do you get when you multiply a matrix by its inverse?')
m = Matrix(3, 3)
m._matrix = [[1, 2, 3],
[20, 5, 6],
[7, 8, 11]]
print('We have the following matrix:')
for row in m.matrix:
print(row)
print('\nThe inverse matrix is the following:')
i = m.inverse()
for row in i.matrix:
print(row)
print('\nThe product of the matrix with it\'s inverse is the following:')
p = i * m
for row in p.matrix:
print(row)
if __name__ == '__main__':
question_one()
question_two()
| false |
8f4fd7b1f710cebb32db753c1ccea9024042d77e | srikanthpragada/PYTHON_03_AUG_2020 | /demo/database/list_employees.py | 285 | 4.15625 | 4 | # List employees from EMPLOYEES table
import sqlite3
con = sqlite3.connect(r"c:\classroom\aug3\hr.db")
cur = con.cursor()
cur.execute("select * from employees order by salary desc")
for emp in cur.fetchall():
print(f"{emp[0]:5} {emp[1]:30} {emp[2]:10} {emp[3]:8}")
con.close()
| true |
9642b34f8680144ec4800bdd9faba8c9386862e3 | Phayfer/gangster-stage-name | /main.py | 2,217 | 4.1875 | 4 | import random
import re
regularNames = []
stageNames = []
# pre defined list of names to generate the random name
listRandomName = ["Gargoyle", "Vampire", "Monster", "Bloody", "Zombie", "Spike", "Demon", "Dragon"]
# function to generate the random name using a pre defined list
def generateRandomName():
# get the length of the random names
length = len(listRandomName)
# random choose a name from the randomList name
return listRandomName[random.randint(0, length - 1)]
# create a variable to store the user want to generate
totStageName = 0
# counter
count = 1
try:
# getting how many stage names the user want to generate
# trying to convert the input to int and assign the value to totStageName
totStageName = int(input("How many stage names do you want to create? "))
except:
# if the user insert a invalid input, print a message to the user
print("invalid input, please try again!")
# start the loop checking the counter
while count <= totStageName:
# get the regular name input and assign to the variable
regularName = input("Please digit " + str(count) + "o. name: ")
# validation to refuse numbers in the regular name
# example got from:
# https://stackoverflow.com/questions/19859282/check-if-a-string-contains-a-number
if re.search(r'\d', regularName):
print("Numbers are not allowed")
continue
# split forename and surname into a list
splitRegularName = regularName.split(" ")
# validate if the user input contains at least one forename and one surname
if len(splitRegularName) < 2:
print("Please type name and surname!")
continue
# store the regular name in the list
regularNames.append(regularName)
# increment the counter
count = count + 1
# generate the stageName
stageName = regularName[0].upper() + ". " + generateRandomName() + " " + splitRegularName[1].upper() \
+ " " + splitRegularName[0].lower() + " " + generateRandomName()
# store the generated stage name
stageNames.append(stageName)
# print the stage name
print("Regular name:", regularName)
print("Generated stage name:", stageName)
print("end")
| true |
b095bda63d0730ba4e2401b1bca2008f3ca348e9 | LandonBeach/securityScripting | /Assignment3.py | 762 | 4.4375 | 4 | # Landon Beach
# 1/13/17
# Assignment 3
# Create a list for my pizza toppings.
my_pizza_toppings = ['pepperoni','sausage','cheese','mushroom']
# Copy my pizza toppings to my friend's pizza toppings.
friend_pizza_toppings = list(my_pizza_toppings)
# Add 'peppers'to my pizza toppings.
my_pizza_toppings.append('peppers')
# Remove 'mushrooms' from my friend's pizza toppings.
friend_pizza_toppings.remove('mushroom')
# Add 'spam' to my friend's pizza toppings.
friend_pizza_toppings.append('spam')
# Print all of my pizza toppings to stdout.
print("My Pizza Toppings:")
for topping in my_pizza_toppings:
print(topping)
# Print all of my friend's pizza toppings to stdout.
print("\nFriend Pizza Topping:")
for topping in friend_pizza_toppings:
print(topping)
| true |
f3dfd1e0620ec41b5db9528ce2603ddb3cba549d | LandonBeach/securityScripting | /Assignment4.py | 2,515 | 4.625 | 5 | # Landon Beach
# Assignment 4
# 1/20/17
# 1. Complete Exercise 6-1
# Create a dictionary of yourself.
my_info = {
"first": "landon",
"last": "beach",
"city": "cedar city"
}
# Print the entire dictionary.
print(my_info)
# Print the keys and values separately in a readable format.
for n,v in my_info.items():
print(n.title() + ": " + v.title())
# 2. Complete Exercise 6-3
print("")
# Create a glossary of five programming terms.
glossary = {
"tuple": "a comma-separated sequence of values in Python that cannot be changed after it has been created.",
"key-value pair": "a pair with a key and an associated value. The are often used in dictionaries in Python.",
"IDE": "a software application that provides comprehensive facilities to computer programmers for software development.",
"string": "a series of characters",
"float": "any number with a decimal point."
}
# Print the entire dictionary
print(glossary)
# Print the word and definition separately in a readable format.
for n,v in glossary.items():
print("Word: " + n)
print("Definition: " + v)
# 3. Complete Exercise 6-7
print("")
# Make two new dictionaries representing different people.
person1 = {
"first": "eric",
"last": "foreman",
"city": "point place"
}
person2 = {
"first": "scott",
"last": "pilgrim",
"city": "toronto"
}
# Store all three dictionaries in a list called people.
people = []
people.append(my_info)
people.append(person1)
people.append(person2)
# Print everything you know about each person in a readable format.
for p in people:
for n,v in p.items():
print(n + ": " + v)
print("")
# 4. Create a dictionary that holds customer credit card information.
# The key is the customer's last name, the value is the credit card number, the expiration date (mm/yyyy), and the cvv.
# The credit card information should not be editable or changeable.
# The dictionary should have at least 4 entries.
# NOTE: Fake credit values are being used for each card.
print("")
cards = {
"foreman": ("344375743782055", "123", "01/2020"),
"pilgrim": ("342584599151479", "234", "02/2020"),
"kenobi": ("71359102960391", "345", "03/2020"),
"skywalker": ("372287813758755", "456", "04/2020")
}
# Print out the entire dictionary in a readable format.
for name, card in cards.items():
print("Name: " + name.title())
print("Card Number: " + card[0])
print("CVV: " + card[1])
print("Expiration Date: " + card[2])
print("")
| true |
3eb018081027eb9db1d486b7f30b2c977da18b58 | sanskar001/Python-Programming-Exercises | /oops_concept.py | 1,341 | 4.3125 | 4 | # This is python program to understand the oops concepts.
class person:
def __init__(self,p_name="Tina",p_age=23,p_gender="female"):
self.p_name = p_name
self.p_age = p_age
self.p_gender = p_gender
def getp_name(self):
return self.p_name
def getp_age(self):
return self.p_age
def getp_gender(self):
return self.p_gender
def person_info(self):
print("This is person information.")
class employee():
def __init__(self,other,e_salary=40000):
# other.__init__()
# super().__init__()
self.e_name = other.p_name
self.e_age = other.p_age
self.e_gender = other.p_gender
self.e_salary = e_salary
def gete_name(self):
return self.e_name
def gete_age(self):
return self.e_age
def gete_gender(self):
return self.e_gender
def gete_salary(self):
return self.e_salary
def employee_info(self):
print("This is employee information")
person1 = person("ritik",22,"male")
person2 = person("sanskar",19,"male")
employee1 = employee(person2,90000)
print(employee1.gete_name())
print(employee1.gete_age())
print(employee1.gete_gender())
print(employee1.gete_salary()) | false |
1cb25b2249eabdf071d5e1f13194461c4a6cf1df | sanskar001/Python-Programming-Exercises | /vector_class.py | 1,255 | 4.5 | 4 |
# This is python program to make vector class with special method.
class vector:
def __init__(self,d): # here d is define for number of dimension.
self.coords = [0] * d
def show_vector(self):
print(self.coords)
def __len__(self):
return len(self.coords)
def __getitem__(self,j):
return self.coords[j]
def __setitem__(self,j,value):
self.coords[j] = value
def __add__(self,other):
if len(self) != len(other):
raise ValueError("dimensions must same.")
else:
result = vector(len(self))
for j in range(len(self)):
result[j] = self[j] + other[j]
return result
def __eq__(self,other):
return self.coords == other.coords
def __ne__(self,other):
return not self.coords == other.coords
def __str__(self):
return f"< {str(self.coords)[1:-1]} >"
v1 = vector(3)
print("v1:",v1)
print("length:",len(v1))
for n in range(3):
v1[n] = n
print("v1:",v1)
v2 = vector(3)
v2[0] = 45
v2[1] = 10
print("v2:",v2)
v3 = v1+v2
print("v3:",v3)
print(type(v1))
print(v1 == v2)
print(v1 != v2) | false |
06be241025224ad37f14ec8a7081fbf99d6825ad | sanskar001/Python-Programming-Exercises | /project_1.py | 426 | 4.25 | 4 |
# this is python program thgrouh which we can find any word in long text and
# also that how many times this word comes.
string=input("Enter the long text:")
find_word=input("Enter the finding word:" )
string_length=len(string)
length=len(find_word)
count=0
for x in range(string_length):
if string[x:x+length]==find_word:
print(string[x:x+length])
count+=1
print("count",count)
| true |
de71fa6677660e98f4d06cabf141e8b205cd054e | JyothiRBangera/InternshipTasks | /_Internship task9.py | 883 | 4.4375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#to create lambda function that multiplies argument x with y
num=lambda x,y:x*y
print(num(2,6))
# In[2]:
#to create Fibonacci series to n using Lambda
from functools import reduce
fibnum=lambda m:reduce(lambda x,_:x+[x[-1]+x[-2]],range(m-2),[0,1])
print(fibnum(9))
# In[3]:
#to multiply each number of given list with a given number
num=[1,4,6,53]
mul=list(map(lambda x:x*3,num))
print("Now the multiplied numbers are:",mul)
# In[4]:
#to find number divisible by 9 from list of number
num=[1,2,3,4,5,6,9,7,59,10,11,27,13,63,15]
div=list(filter(lambda x:x%9==0,num))
print("the number divisible by 9:",div)
# In[5]:
#to count even number in given list of integers
num=[1,2,3,4,5,6,9,7,59,10,11,27,13,63,15]
even=list(filter(lambda x:x%2==0,num))
print("the even numbers in a given list:",even)
# In[ ]:
| false |
38b9c0891e0e8fb30e9d123ced308d406f7b71d3 | JyothiRBangera/InternshipTasks | /_Internship task5.py | 1,031 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[13]:
#to create a function get two integer inputs from user and do arithmetic operation
def num(a,b):
print("addition of two number:",a+b)
print("subtraction of two number:",a-b)
print("multiplication of two number:",a*b)
print("division of two number:",a//b)
num1=int(input("enter the first number:"))
num2=int(input("enter second number:"))
num(num1,num2)
# In[14]:
#create a function covid()and accept patient name and body temperature
def covid(name,temp=98):
print("patient name:",name)
print("body temperature:",temp)
a=input("enter the name of patient:")
b=input("enter the body temperature of patient:")
covid(a,b)
# In[11]:
#create a function covid()and accept patient name and body temperature,by default body temperature should be 98 degree
def covid(name,temp=98):
print("patient name:",name)
print("body temperature:",temp)
a=input("enter the name of patient:")
covid(a)
# In[ ]:
| true |
fdfd19e03aa20bbe936aaec7e411e3ed0a4e5c31 | VSyrkin/Python_prof | /dz_1/easy_1.py | 396 | 4.125 | 4 | # Задача-1: поработайте с переменными, создайте несколько,
# выведите на экран, запросите от пользователя и сохраните в переменную, выведите на экран
a = 10
b = 13.5
c = 'переменная'
print('a: ', a, 'b: ', b, 'c: ',c)
d =input('Введите D:')
print ('D:', d)
| false |
8c8ac6558ee2b62ca737d9e9a1230ee20d095813 | yaisenur/a2-yaisenur | /a2_process_data.py | 2,380 | 4.375 | 4 |
#######################################################
### Please ignore the lines of code in this section.
### It loads the contents of a CSV file for you.
### The file's name should be a2_input.csv.
### You do not need to know how it works.
#######################################################
import csv
contents = []
with open("a2_input.csv") as input_file:
for row in csv.reader(input_file):
contents = contents + [row]
#######################################################
### Do your data processing below.
### The below code gives some examples
### of how to access the data.
### Print your results using the print function.
#######################################################
##print(contents["chickenchicken"])
#print(contents[3][0])
#print("Cell at index 0,1:")
#print(contents[0][1])
#print("Cell at index 1,0:")
#print(contents[1][0])
#print(type(contents));
#print("type of contents")
#print(type(contents[0]))
#print("type of contents[0]")
#print(type(contents[0][0]))
#print("type of contents[0][0]")
concat = 0
concat = contents[0][2] + contents[0][6]
#print(concat)
#print(type(concat))
sum = 0.0
for i in range (2,209):
sum = sum + float(contents[i][6])
average = sum / 208
#print(sum)
#print(type(sum))
#print(average)
#print(type(average))
#help(concat)
#print(3*contents[0][3])
upmessage = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Chocalate Companies and Their Qualifications</title>
</head>
<body>
<h1>Chocolate Factories all over the world</h1>
"""
altmessage="""
</body>
</html>"""
print(upmessage)
count = 0
sum = 0
for m in range(1,209):
sum = sum + float(contents[m][6])
if float(contents[m][6]) > 3:
count = count+1;
print("<p>sum of ratings is : ")
print(sum)
print("</p>")
print("<p>number of factories which ratings are higher than 3 : ")
print(count)
print("</p>")
comment = """<p>This data shows the chocolote factories all over the world and their statistics like customer rating, bean types, and cacoa percentage.
The table shows that higher cocao percentage makes customers more happy</p>"""
print(comment)
print("<table>")
for j in range(1,209):
print("<tr>")
for i in range(1,9):
print("<td>")
print(contents[j][i])
print("</td>")
print("<tr>")
print("</table>")
print(altmessage)
| true |
ff31eeffc58bf0f70bd6bab659d3e1e267906538 | juancsosap/pythontraining | /training/c07_collections/e07_deque-methods.py | 1,557 | 4.15625 | 4 | from collections import deque
dias = deque(['lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'])
print(dir(deque))
dias.append('domingo') # agrega un elemento al final
print(dias)
dias.appendleft('otro día') # agrega un elemento al principio
print(dias)
dias.insert(3, 'segundo miércoles') # añade un elemento en el indice indicado
print(dias)
dias.remove('otro día') # remueve el elemento indicado
print(dias)
dias.pop() # remueve y retorna el último elemento
print(dias)
dias.popleft() # remueve y retorna el primer elemento
print(dias)
print('index: {}'.format(dias.index('jueves')))
dias.rotate() # ordena la lista colocando el último elemento en la primera posición
print(dias)
dias.append('lunes') # agrega un elemento
print(dias)
# retorna la cantidad de elementos de un tipo en la lista
print('count: {}'.format(dias.count('lunes')))
dias.reverse() # reorganiza la lista en orden inverso al original
print(dias)
newdias = dias.copy() # retorna una copia de la lista
dias.clear() # borra los elementos de la lista, igual que del(dias[:])
print(dias)
dias.extend(['lunes', 'sábado']) # agrega los elementos de una lista al final de otra lista
print(dias)
dias.extendleft(newdias) # agrega los elementos de una lista al principio de otra lista
print(dias)
# Get the first Element
print(newdias[0])
# Get the last Element
print(newdias[-1])
# print(newdias[1:3]) # Slice is not supported
print(newdias)
print(dias.maxlen) # No limit (None)
# Verify if a value is in a Collection
print('lunes' in dias)
| false |
7a20796bd34de9c96420de51b0d90ca8698a2795 | tomeko74/AutomateIt | /chapter11/04_date_arithmetic.py | 286 | 4.15625 | 4 | from datetime import datetime
import time
# Current Time
now_1 = datetime.now()
print(" Time Now", now_1)
time.sleep(5)
# Time after 5 seconds
now_2 = datetime.now()
print(" Time Now", now_2)
# Difference in Times
print(" Difference in the times is:", (now_2 - now_1).seconds)
| false |
e55ab8c5bd70795858c942227f9cbd702f54309c | diyansharout/python | /Familytree.py | 772 | 4.125 | 4 | import turtle
t = turtle.Pen()
t.speed(0)
turtle.bgcolor('black')
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
family = []
# Ask for first name
name = turtle.textinput("My family",
"Enter a name, or just hit [ENTER] to end: ")
# Keep asking for names
while name !="" :
# Add their name to the family list
family.append(name)
# Asj=k for another name or end
name = turtle.textinput("My family",
"Enter a name, or just hit [ENTER] to end:")
# Draw a spiral of names on the screen
for x in range (100):
t.pencolor(colors[x%len(family)])
t.penup()
t.forward(x*4)
t.pendown()
t.write(family[x%len(family)], font=("Arial", int((x + 4)/4), "bold"))
t.left(360/len(family) + 2) | true |
877dcaaf37379518445a77d58c2be374de014243 | laboyd001/python-lists-planets-random-squared | /planets.py | 1,541 | 4.625 | 5 | planet_list = ['mercury', 'mars']
# use append to add Jupiter and Saturn to the end of the list:
planet_list.append('jupiter')
planet_list.append('saturn')
print('List of planets: ', planet_list)
# use extend to add another list to our list:
last_planets = ['uranus', 'neptune']
planet_list.extend(last_planets)
print('Longer list of planets: ', planet_list)
# use insert to add Earth and Venus in the right order:
planet_list.insert(1, "venus")
planet_list.insert(2, "earth")
print('Even more planets: ', planet_list)
# use append to add Pluto:
planet_list.append('pluto')
print('Nine planets: ', planet_list)
# slice the list to make a new list of rocky planets:
one = planet_list.pop(0)
two = planet_list.pop(0)
three = planet_list.pop(0)
four = planet_list.pop(0)
rocky_planets = [one, two, three, four]
print('List of rocky planets: ', rocky_planets)
# use del to remove pluto:
del planet_list[4]
print('Pluto is now gone: ', planet_list)
# Challenge===================================
# list of tuples:
eight_planets = ['mercury', 'venus', 'earth',
'mars', 'jupiter', 'saturn', 'uranus', 'neptune']
spacecrafts = [('cassini', 'saturn'), ('phoenix', 'mars'), ('juno', 'jupiter')]
for planet in eight_planets:
if any(planet == item[1] for item in spacecrafts):
for spacecraft in spacecrafts:
planet_explorer = spacecraft[0]
print(planet, 'was explored with ', planet_explorer)
else:
print('No exploration for ', planet)
| true |
99e6b340fde42b7d90362c8a54430a541993f4b1 | nicecode996/Python_Test | /函数式编程/生成器.py | 768 | 4.1875 | 4 | # coding=utf-8
# !/usr/bin/env python3
'''
def square(num): # 定义函数
n_list = []
for i in range(1, num + 1): # 通过循环计算一个数的平方
n_list.append(i * i) # 值保存在列表中
return n_list # 返回列表对象
for i in square(10): # 遍历所有的列表对象
print(i, end=' ')
'''
# 改良方案
def square(num):
for i in range(1, num + 1):
yield i * i # yieid关键字返回平方数
# 此处使用的隐式调用,显式调用相对复杂,此处不使用
for i in square(5): # 生成器是一种可迭代对象,可迭代对象通过_next_()方法获得元素,此行代码能够遍历可迭代对象,就是隐式调用生成器的_next_()方法获得元素的
print(i, end=' ')
| false |
2b651afbd8054f8fe251f77e6fc1239860b0752d | nicecode996/Python_Test | /python基础/使用范围.py | 229 | 4.21875 | 4 | # conding=utf-8
# ! /usr/bin/ env python3
for item in range(1,10,2):
print("Count is : {0}".format(item))
print('-------------------------------')
for item in range(0,-10,-3):
print("Count is : {0}".format(item))
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.