text stringlengths 37 1.41M |
|---|
# file: dirlist.py
# Author: Nikhil Gorantla
# Data: 1/Jan/2018
# Description: This is simple Directory listing program and which give the size of the files in the given directory
#!/usr/bin/python3
import os
dirName = input("Enter the Directory name to list the size of the files: ")
for fil... |
# file: archiving.py
# Author: Nikhil Gorantla
# Data: 14/Jan/2018
# Description: This python program helps to tar archive several 100's of log files.
#!/usr/bin/python3
import os
import tarfile
import sys
dPath = input("Enter the directory name to archive the file: ")
os.chdir(dPath)
# Add... |
"""Simple calculator
Usage:
app.py <operation> <number1> <number2>
app.py (-h | --help)
Arguments
number1 First Number
number2 Second Number
Options:
-h --help Show this screen.
"""
from docopt import docopt
if __name__ == '__main__':
args = docopt(__doc__, version='Simple calculator')
functi... |
"""
Following program get as input
city name and print the temperature
and humidity of that city.
"""
import requests
def get_request_jason(url):
resp = requests.get(url)
if resp.status_code != 200:
# This means something went wrong.
raise requests.RequestException('GET ERROR {}'.format(r... |
def has_unique_char(string):
alph = [False for x in range(129)]
for char in string:
if(alph[ord(char)]):
return False
alph[ord(char)] = True
return True
print(has_unique_char('apple'))
print(has_unique_char('pear'))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Animals(object):
def __init__(self,name = 'wang san'):
self.name = name
def run(self):
print ('%s is runing...'%(self.name))
class Dog(Animals):
pass
class Cat(Animals):
pass
dog = Dog('lili')
dog.run()
|
#HCD
#Add Two Numbers
#9/4/18
numone=input('First Number: ')
numtwo=input('Second Number: ')
ione=int(numone)
itwo=int(numtwo)
total=ione+itwo
print("%i plus %i equals %i"%(ione,itwo,total))
#---------------------------------------------------
numone=int(input('First Number: '))
numtwo=int(input('Second Number: '))
pr... |
#Python code to demonstrate
#conversion of list of ascii values
#to string
#Initialising list
ini_list= [118, 101, 114, 115, 101, 95, 115, 107, 95, 100, 101, 112, 108, 111, 121, 109, 101, 110, 116]
# Printing initial list
print ("Initial list", ini_list)
# Using Naive Method
res = ""
for val in ini_list:
r... |
from StackQueue.stack_queue import Stack,Queue
if __name__ == "__main__":
while True:
num = int(input("**************Menu Driven**************\n1.Implementing Stack\n2.Implementing Queue\n3.Exit\n"))
if num == 1:
s = Stack()
while True:
n = int(input("1.... |
import numpy as np
x = int(input("enter number of rows: "))
y = int(input("enter number of columns: "))
matrix = lambda : [list(map(int,input().strip().split())) for _ in range(x)]
for i in range(2):
print("matrix: ", i + 1)
if i==0:
mat1=np.array(matrix())
elif i==1:
mat2=np.array(matrix... |
mutex,full,empty,x = 1,0,3,0
def wait(s):
global mutex,full,empty,x
s -=1
return s
def signal(s):
global mutex,full,empty,x
s += 1
return s
def producer():
global mutex,full,empty,x
mutex = wait(mutex)
full = signal(full)
empty = wait(empty)
x +=1
print("Producer pro... |
class Family:
def show_family(self):
print("This is Cujoh Family:")
class Father(Family):
fathername = ""
def show_father(self):
print(self.fathername)
class Mother(Family):
mothername = ""
def show_mother(self):
print(self.mothername)
class Child(Father, M... |
def findDuplicate(nums):
nums.sort()
l = 0; r = 1
while r < len(nums):
if nums[r] == nums[l]:
return nums[r]
else:
l += 1
r = l+1
print findDuplicate([1,1]) |
def lengthOfLastWord(s):
array = s.split()
if len(array) == 0:
return 0
else:
return len(array[-1])
print lengthOfLastWord('') |
import collections
def intersect(nums1,nums2):
cnt = collections.Counter()
for val in nums1:
cnt[val] += 1
ans = []
for val in nums2:
if cnt.has_key(val) and cnt[val] > 0:
ans.append(val)
cnt[val] -= 1
return ans
print intersect([1,2,3,2,1,1], [2,3,2,2,1,1])
|
def moveZeros(nums):
for x in nums:
if x == 0:
nums.remove(x)
nums.append(x)
print nums
moveZeros([0,1,0,3,12]) |
def compareVersion(version1, version2):
v1 = list(); v2 = list()
if '.' not in version1:
v1.append(version1)
v1.append('0')
else:
v1 = version1.split('.', 1)
if '.' not in version2:
v2.append(version2)
v2.append('0')
else:
v2 = version2.split('.', 1)
if int(v1[0]) > int(v2[0]):
return 1... |
def getSum(a, b):
p, g, i = a ^ b, a & b, 1
while True:
if (g << 1) >> i == 0:
return a ^ b ^ (g << 1)
if ((p | g) << 2) >> i == ~0:
return a ^ b ^ ((p | g) << 1)
p, g, i = p & (p << i), (p & (g << i)) | g, i << 1
print getSum(3,2) |
"""
Split the dataset into training and test set with split being (80, 20)
Cross-validation will choose random people from the training set and do so
for k-different folds.
"""
from sklearn.cross_validation import train_test_split
from sklearn.cross_validation import cross_val_score
from sklearn.cross_validation impor... |
# import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
class Overview:
"""
This class instantiates an object that provides an overview of a data frame.
Example:
>> overview = Overview(df)
# get summary statistics
>> overview.summary_stats()
## check for missing values... |
#@author: github.com/guidoenr4
#@date: 07-09-2020
import bcolors, time
from random import randrange
def test_cases(cases):
changing, staying = 0, 0
bcolors.print_warning("Testing..")
for i in range(0, cases):
correct, choice = new_case()
if not choice == correct : changing+=1
... |
from preprocess import *
from lm_train import *
from math import log
def log_prob(sentence, LM, smoothing=False, delta=0, vocabSize=0):
"""
Compute the LOG probability of a sentence, given a language model and whether or not to
apply add-delta smoothing
INPUTS:
sentence : (string) The PROCESSED sentence whos... |
from cell import Cell
from typing import List, Tuple
import pygame
from settings import *
import math
surface = pygame.Surface(size)
surface.fill(WHITE)
class FlatBoard:
"""
_board:
A 2 dimensional board that has a size length * length.
Each unit of the board is a size 1 Cell.
"""
_bo... |
# Python script to show RankList starting from Rank 1 in Terminal
# Author : Pranay Ranjan
from urllib import urlopen
from json import load
response = urlopen(" http://codeforces.com/api/user.ratedList?activeOnly=")
json_obj = load(response)
for obj in json_obj['result']:
print("Handle : "+obj['handle'])
print("R... |
#"""Sample code to read in test cases:
import sys
test_cases = open(sys.argv[1], 'r')
def rtrip(s):
parts=[int(y) for x,y in [s.strip().split(',') for s in [x for x in s.split(';') if len(x)>1]]]
parts.sort()
for i in range(len(parts)-1,0,-1):
parts[i] -= parts[i-1]
print(','.join(str(x) for x in parts))
for tes... |
#"""Sample code to read in test cases:
import sys
test_cases = open(sys.argv[1], 'r')
human='This program is for humans'
res=['Still in Mama\'s arms'] * 3 + ['Preschool Maniac'] * 2 + ['Elementary school'] * 7 + ['Middle school' ] * 3 + ['High school' ] * 4 + ['College'] * 4 + ['Working for the man' ] * 43 ... |
#"""Sample code to read in test cases:
import sys
test_cases = open(sys.argv[1], 'r')
def bal(s):
prev,d,ml,mr=None,0,0,0
for c in s:
if '('==c:
if ':' == prev: ml += 1
else: d += 1
elif ')'==c:
if ':' == prev:
mr += 1
else:
if d > 0: d -= 1
else:
if ml > 0: ml -= 1
else:
... |
class Solution():
# Ex 1
# Pascal triangle.
def generate_pascal_triangle(self, rows_num):
if (rows_num == 0):
return []
else:
result = [[1]]
for i in range(1, rows_num):
result.append([0] * (i + 1))
for k in range(i + 1):
... |
import os
def bubbleSort(array, n):
for i in range(0, n-1):
#last i items are in order, inner loop doesnt need to look at them
for j in range(0,n-1-i):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
print(array)
array = [2,1,6,4, 8, 10, 100, -24]
n = len(array)
print(array)
... |
"""
Spiking Neural Network Solver for Constraint Satisfaction Problems.
This package has been developed by Gabriel Fonseca and Steve Furber at The University of Manchester as part of the
paper:
"Using Stochastic Spiking Neural Networks on SpiNNaker to Solve Constraint Satisfaction Problems"
Submitted to the journa... |
def reverse(x):
if abs(x) > 2**31 -1:
return 0
if x >= 0:
if int(str(x)[::-1]) > 2**31 -1:
return 0
return int(str(x)[::-1])
if x < 0:
y = abs(x)
if int(str(y)[::-1]) > 2**31 -1:
return 0
return -int(str(y)[::-1])
print(reverse(100000)... |
# LANG : Python 3.5
# FILE : 01-simple-linear-regression.py
# AUTH : Sayan Bhattacharjee
# EMAIL: aero.sayan@gmail.com
# DATE : 27/JULY/2018
# INFO : How does hot soup sale change in winter based on temperature?
# : Here, we do linear regression with ordinary least squares
from __future__ import print_function
imp... |
# Problem: Receive miles and convert to kilometers
# kilometers = miles * 1.60934
# Enter Miles 5
# 5 miles equals 8.04 kilometers
# Ask the user to input the number of miles and assign it to the miles variable
miles = input("Enter the number of miles you wish to convert: ")
# Convert from string to integer
miles ... |
#!/usr/bin/python
#-*- coding:utf-8 -*-
#对训练数据和测试数据 进行过滤 生成字典文件 并去除 非法字符
import codecs,collections,sys
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
def read_data(filename):
fp = codecs.open(filename,'r','utf8');
wordlist = list();
taglist = list();
idx = 0;
while True:
line = fp.readline().strip('\r\n');
... |
# Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple (see Tuples and Sequences). Before the variable number of arguments, zero or more normal arguments may occur.
def write_multiple_items(file, separ... |
# The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index.
stack = [3, 4, 5]
print (stack)
st... |
#Operator: +, -, /, *, // (floor division), % (remainder)
print ("2 + 2 = ")
print (2 + 2)
print('')
print ("50 - 5*6 = ")
print (50 - 5*6)
print('')
print ("(50 - 5*6) / 4 = ")
print ((50 - 5*6) / 4)
print('')
print ("8 / 5 = ") #division always returns a floating point number
print (8/5)
print('')
print ("17 / 3... |
# -*- coding: utf-8 -*-
"""
Shows some attacks that can be done against this program.
The different Hijacks were attacks to which we defended. This program is surely
vulnerable to many possible attacks, but not these ones.
Created on Wed May 5 18:02:12 2021
@author: Joachim Favre & Alberts Reisons
"""
impo... |
#!/usr/bin/env python3
# RyanWaltersDev Jun 14 2021 -- introducing the break statement
# Initial prompt
prompt = "\nPlease enter the name of a city you have visited: "
prompt += "\n(Enter 'quit' when you are finished.) "
# While loop with break
while True:
city = input(prompt)
if city == 'quit':
brea... |
#!/usr/bin/env python3
# RyanWaltersDev Jun 16 2021 -- Filling a dictionary with user input
# Empty dictionary
responses = {}
# Set a flag to indicate that polling is active.
polling_active = True
while polling_active:
#Prompt for the person's name and response
name = input("\nWhat is your name? ")
respo... |
"""
Uzrakstiet Python programmu, lai iegūtu
starpību starp ievadīto skaitli un 17.
Ja skaitlis ir lielāks par 17, iegūstiet absolūtās starpības dubultu.
"""
def starpiba(a,b):
starpiba=a-b
return starpiba
a=float(input("Ievadi skaitli:"))
print(starpiba(a,17)) |
class Parent():
def __init__(self, last_name, eye_color):
print("Parent constructor called")
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print "Last name -",self.last_name
print "Eye color -",self.eye_color
teruzane = Parent("Utada","nebula")
print teruzane.last_name
class ... |
import urllib
folder = r"C:\Users\natal\Documents\Web Dev Nanodegree\0_Programming_Foundations\MiniProjects"
movie = "\movie_quotes.txt"
profane = "\list_of_bad_words.txt"
wdyl = "http://www.wdyl.com/profanity?q="
def read_text(path):
quotes = open(path)
contents = quotes.read()
quotes.close()
return contents
def... |
"""lostc.combine
Global combine functions
"""
def combination(items, sequential=True):
"""Generate a combination.
- items: a list like object
- sequential: need sequential? True/False
Return a combination generated from items.
Example:
data = [1, 2]
combination(data) ... |
def show_magicians(printed_names):
for printed_name in printed_names:
print(printed_name.title())
def make_great(changed_lists):
for i in range(4):
#####先用变量i来作为一个标志,然后用range()函数创建0、1、2、3四个数字,
#####用来对应魔术师姓名列表的四个姓名,最后用for循环将姓名之前加上”The Great”,循环结束后返回
changed_lists[i] = 'the Great ' + changed_lis... |
import csv
import sys
def bubbleSort(list_1):
for i in range(len(list_1)-1):
for j in range(len(list_1)-1):
if list_1[j]>list_1[j+1]:
temp = list_1[j]
list_1[j]=list_1[j+1]
list_1[j+1]=temp
def ortalama(list):
top,index=0,0
leng = len(list... |
#!/usr/bin/python
import sys
import datetime
# compute the time difference between the first and the last visit for each host
prev_host = ''
count = 0
# initialize start time and end time for the host
start_time = datetime.datetime(datetime.MAXYEAR, 12, 31)
end_time = datetime.datetime(datetime.MINYEAR, 1, 1)
for l... |
#!/usr/bin/python
import sys
import re
# mapper emits student name and his/her grade point average(gpa)
if __name__ == '__main__':
name = ''
grade = 0
gpa = 0
for line in sys.stdin:
line = line.strip().split()
# check if the student takes more than 4 courses
if len(line) > 6:
gpa = 0
grade = 0
nam... |
# age = int(input('Enter your age:'))
# if age < 10:
# print('your are young stargn one')
# elif age < 40:
# print('the fire is you is strong, strange one')
# else:
# print('you are wise beyond doubt, strange one')
meaty = input('Do you eat meat? (y/n')
if meaty == 'y':
print('you meaty... |
def squares_by_comp(n):
return [k**2 for k in range(n) if k % 3 == 1]
def squares_by_loop(n):
"""Re-wrote the squares_by_comp function to return the squares by loop instead"""
liste = []
for number in range(n):
if number % 3 == 1:
liste.append(number**2)
return liste
if __nam... |
SUITS = ('C', 'S', 'H', 'D')
VALUES = range(1, 14)
def deck_loop():
deck = []
for suit in SUITS:
for val in VALUES:
deck.append((suit, val))
return deck
def deck_comp():
"""This function returns a deck of cards where 1 equals ace and
13 equals king etc. C is clubs, S is spade... |
# printing board
def boardt(board):
print('\n'*20)
print(' | |')
print(' ' + board[7] + ' | ' + '' + board[8] + ' |' + ' ' + board[9])
print(' | |')
print('------------')
print(' | |')
print(' ' + board[4] + ' | ' + '' + board[5] + ' | ' + ' ' + board[6])
print(' | |')
... |
import pandas
import numpy
import sklearn
import sklearn.model_selection
import sklearn.linear_model
import matplotlib.pyplot as pyplot
from matplotlib import style
import pickle
data = pandas.read_csv("student-mat.csv", sep=';')
data = data[["G1", "G2", "G3", "studytime", "failures", "absences", "age", "freetime", "D... |
'''
Dada una concesionaria de autos, un cliente va a solicitar un presupuesto,
debe preguntarsele:
*Nombre y apellido del comprador.
*Marca
*Puertas
*Color
Marcas posibles y sus precios:
1. Ford: $100000
2. Chevrolet: $120000
3. Fiat: $80000
Por la cantidad de puertas se añade un precio:
2: $50000
4: $65000
5: $7... |
import pygame
from pygame.sprite import Group
from ship import Ship
class Scoreboard:
"""Report score information."""
def __init__(self, game):
""""""
self.settings = game.settings
self.screen = game.screen
self.screen_rect = self.screen.get_rect()
self.stats = game.s... |
a=input("enter the value:")
while(a!='q'):
print("Enter another value")
a=input()
|
# dynamic array similar to build-in list data structure in python
import ctypes
class DynamicArray:
def __init__(self):
self._n = 0 # current total numbers in array
self._size = 1 # underlaying size of array, increased by double every time
self._array = self._make_array(self._size) # u... |
# implementing priority queue using heapq
import heapq
class Item:
def __init__(self,name):
self._name = name
def __str__(self):
return 'Item({!r})'.format(self._name)
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push(self, item... |
# diameter of tree
# diameter is longest distance between two nodes of tree
# diameter does not need to pass from root
class Node:
def __init__(self,val):
self.left = None
self.right = None
self.val = val
def height(root):
if root is None:
return 0
else:
return 1 + ... |
# Generate all subsets
# adding each element in one row, i.e for cur_comb call recursively for adding element and not adding element
# complexity 2^n
class Solution:
def generateSubsets(self,arr,cur_comb,n):
if n == 0: # base condition to end
print(cur_comb)
else:
self.g... |
"""
list uses dynamic allocation inside, this can be evident from fixed size of object when new elements are added.
Internally it allocates memeory greater than it requested.
"""
import sys
test_list = []
iteration = 25
for i in range(iteration):
n = len(test_list)
size = sys.getsizeof(test_list) # get the si... |
""" min oriented priority queue implemented with binary heap array based implementation """
from python_priority_queue import PriorityQueueBase
class HeapPriorityQueue(PriorityQueueBase):
def _parent(self,j):
return (j - 1) // 2
def _left(self,j):
return 2*j + 1
def _right(self,j):
... |
# import XML libraries
import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom
import HTMLParser
# Function to create an XML structure
def make_problem_XML(
problem_title='Missing title',
problem_text=False,
label_text='Enter your answer below.',
description_text=False,
answers=[{'corr... |
"""
This File Contains Menu for Customer Account Operations
pylint Score--9.08
"""
# pylint: disable-msg=C0103
from customer import Customer
def open_account_interface():
"""
Prompt User to Enter valid account no and Customer Name
:return: Customer instance for Current User
"""
while True:
... |
#!/usr/bin/python
import csv
class Account(object):
def __init__(self):
""" Initilize Account object
to default value
"""
self.account_no=-1
self.account_type=""
self.balance=-1
def set_account(self,a_id,a_type,a_balance):
""" Sets values of all attributes... |
class Account:
# whole currency units only
# need to read & store balance value
def __init__(self, filepath):
with open(filepath, 'r') as file:
self.balance = int(file.read()) # instance variable / property
self.filepath = filepath
def withdraw(self, amount):
... |
# coding: utf8
def fizz_buzz(value):
# Comprobamos el tipo de la variable
tipo_de_la_variable = type(value) # int, float, str, dict, list, etc...
if tipo_de_la_variable not in (int, float):
raise TypeError
# Comprobamos que sea divisible por 5 y por 3
if value % 3 == 0 and value % 5 == ... |
#load numpy as np
import numpy as np
#method1 - use slice
a_array = np.arange(10) ##[0 1 2 3 4 5 6 7 8 9]
s = slice(2,7)
print(a_array[s]) ##[2 3 4 5 6]
#method2 - array[start, stop, step]
a_array = np.arange(10) ##[0 1 2 3 4 5 6 7 8 9]
print(a_array[2:7]) ##[2 3 4 5 6]
#step = 2
print(a_array[2:7:2]) ##[2 4 6]
#2 ... |
def chunks(l, n):
"""
Yields chunks of size n from the list l.
"""
for i in range(0, len(l), n):
yield l[i: i+n] |
import pygame
import random
import math
# initialize window
pygame.init()
words = ['CHETAN', 'CRICKET', 'DEVELOPER', 'ELEPHANT','PYGAME', 'PYTHON']
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Hangman Game")
logo = pygame.image.load('hangman.png')
pygame.display.set_icon(logo)
Letter_fo... |
#!/usr/bin/python3
def print_arg(long):
for num_arg in range(1, long):
print("{:d}: {:s}".format(num_arg, sys.argv[num_arg]))
if __name__ == "__main__":
import sys
long = len(sys.argv)
if long == 1:
print("{:d} arguments.".format(long - 1))
elif long == 2:
print("{:d} arg... |
#!/usr/bin/python3
def print_last_digit(number):
print(int(str(number)[-1]), end="")
return int(str(number)[-1])
|
#!/usr/bin/python3
"""appends a string at the end of a text file
"""
def append_write(filename="", text=""):
"""appened string at end
"""
with open(filename, mode="a") as data_file:
return data_file.write(text)
|
#!/usr/bin/python3
"""module to write file
"""
def write_file(filename="", text=""):
"""write file with text input
"""
with open(filename, "w", encoding="utf-8") as data_file:
return data_file.write(text)
|
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import matplotlib.pyplot as plt
r = input('Enter the name of the image you want: ')
def array_to_image(r):
img=mpimg.imread(r)
imgplot = plt.imshow(img)
plt.show()
array_to_image(r)
#img.shape
#http://matplotlib.org/users/image_tut... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'Mad Dragon'
__mtime__ = '2018/12/28'
# 我不懂什么叫年少轻狂,只知道胜者为王
┏┓ ┏┓
┏┛┻━━━┛┻┓
┃ ☃ ┃
┃ ┳┛ ┗┳ ┃
┃ ┻ ┃
┗━┓ ┏━┛
┃ ┗━━━┓
... |
import random
class RandomGenerator:
def __init__(self):
pass
"""returns a random number betweeen [x, y), returns an integer if both ranges are integers"""
@staticmethod
def range(x, y):
if type(x) == int and type(y) == int:
return random.randrange(x, y)
return random.random() * (y - x) + x
@staticme... |
def conversor(tipo_moneda, tasa_conversion_dolares):
pesos = input("¿Cuantos pesos " + tipo_moneda + " deseas convertir a dolares? ")
pesos = round(float(pesos), 2)
tasa_conversion_dolares = tasa_conversion_dolares
dolares = round((pesos / tasa_conversion_dolares), 2)
print("$" + str(pesos) + "... |
import random
def run():
opciones = ('piedra', 'papel', 'tijeras')
puntos_maquina = 0
puntos_jugador = 0
for i in range(0, 3):
jugador = input('Selecciona piedra, papel o tijeras ').lower().strip()
maquina = opciones[random.randint(0, 2)]
if(jugador == maquina):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@file : permutation_list.py
@time : 20/2/16 14:13
@author : leizhen
@contact : leizhen8080@foxmail.com
@doc : 对迭代进行排列组合
"""
from itertools import permutations, combinations, combinations_with_replacement
# itertools 模块提供了三个函数
# 便利一个集合中语速的所有可能排列或组合
ite... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'leizhen'
__mtime__ = '2017/8/10'
# code is far away from bugs with the god animal protecting
I love animals. They taste delicious.
┏┓ ┏┓
┏┛┻━━━┛┻┓
┃ ☃ ┃
┃ ┳┛ ┗┳ ┃
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Time : 2020/8/1 08:56
# @Author : Lei Zhen
# @Contract: leizhen8080@gmail.com
# @File : using_threading_lock.py
# @Software: PyCharm
# code is far away from bugs with the god animal protecting
I love animals. They taste delicious.
┏┓ ┏┓
... |
# coding=utf-8
from collections import Iterable
if __name__ == '__main__':
print isinstance('abc', Iterable)
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print key
for value in d.itervalues():
print value
for value in d.iteritems():
print value
print isinstance(d, Iterabl... |
import abc
class Database(object):
"""Generic Database object, every different database connection should
implement these functions."""
__metaclass__ = abc.ABCMeta
DATABASE: str
connection: any
@abc.abstractmethod
def connect(self, config, setup):
pass
@abc.abstractmethod
... |
print("enter 2 nos")
a=input()
b=input()
c=a*b
print('Product='+str(c))
|
#-*- coding: utf-8 -*-
import re
import time
from os import system
from datetime import datetime
import random
import pesquisa
from responder import responder
from pesquisa import defina, definicao
def main():
frase = ''
nome = str(input('Bot: Diga-me seu nome: '))
botNome = str(input('Bot: Agora o meu nome por gen... |
class Ciclos:
def __init__ (self):
pass
def usoFor(self,):
dat = ["Daniel", 50, True]
num = (2,5.6,4,1)
doc = {'nombre': 'Daniel', 'edad': 50, 'fac': 'faci'}
lisNota = [(30,40),[20,40],(50,40)]
lisAlum = [{"nombre":"Erick","ExmF":70},{"nombre":"Yady","Ex... |
numeros = input().split()
A = int(numeros[0])
B = int(numeros[1])
print (abs(A-B)) |
D = int (input())
print (D)
notas = [100, 50, 20, 10, 5, 2, 1]
for i in notas:
print ("{} nota(s) de R$ {},00".format(int(D/i), i))
D = D%i |
num = input().split()
num = [int(i) for i in num]
[print(i) for i in sorted(num)]
print("")
[print(i) for i in num] |
r = float (input ())
π = 3.14159
area = π * r * r
print ("A=%.4f" %area) |
vetor = []
for i in range(5):
num = float(input())
if num%2==0:
vetor.append(num)
print(str(len(vetor)) + ' valores pares') |
def add(a,b):
result = a + b
return result
def sub(a,b):
result = a - b
return result
def mul(a,b):
result = a * b
return result
|
from functools import wraps
class greater_than_zero(object):
def __init__(self, function):
print("greater_than_zero.__init__")
self.function = function
self.__name__ = 'greater_than_zero'
def __call__(self, *args, **kwargs):
print("greater_than_zero.__call__({},{})".format(arg... |
"""
Advent of code day two
Reference: https://adventofcode.com/2016/day/2
"""
import os
INPUT_DIRECTORY = "../inputs/"
INPUT_FILE_EXTENSION = "_input.txt"
KEYBOARD_PART_ONE = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
KEYBOARD_PART_TWO = [
[None, None, 1, None, None],
[None, 2, 3, 4, None],
[5, 6, 7... |
sen=input("enter a sentence:").split()
s=" "
for i in range(len(sen)):
sen[i]=sen[i][::-1]
s=s.join(sen)
print(s)
|
class Solution:
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# dp[index] denotes the maximum amount of money consisting money nums[index]
# dp[index] = nums[index] + max(dp[index - 2], dp[index - 3])
dp = [0 for i in range(l... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
symmetric = [True]
... |
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
# zero denotes the index of the first zero
# nonZero denotes the index of the first non-zero element after the first zero
... |
class Solution:
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
# dp[row][col] denotes the minimum sum of all numbers along the path from top left to grid[row][col]
# dp[row][col] = min(dp[row - 1][col], dp[row][col - 1]) + grid[ro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.