text stringlengths 37 1.41M |
|---|
def counter(preffix, n):
some_lamb = lambda : None
for a in range(n):
yield some_lamb, a
for preffix, a in counter(preffix='buy', n=3):
print(preffix, a)
for preffix, a in counter(preffix='buy', n=3):
print(preffix, a) |
# 3. Написать функцию, которая...
html = '''
<html>
<body>
<p>Some text..</p>
<ul id='some_list'>
<li>Ненужный элемент</li>
</ul>
<p>Some text..</p>
<ul id='menu'>
<li>Изделия</li>
<li>Функциональность</li>
<li>Ист... |
# Функции
# Простая
def hello():
print('Hello!')
# Функция с аргументами
def hello(arg1, arg2, arg3):
pass # ничего не делает
hello(1, 2, 3)
# Функция с аргументами
def hello(arg1, arg2, arg3):
print('Hello:', arg1, arg2, arg3)
ret = hello(10, 20, 30)
print('ret:', ret)
# Функция с выводом
... |
a = 0
if a > 10:
a = -a
else:
a = a
a = 0
a = 'BOLSHE' if a > 10 else 'MENSHE'
print( a )
a = 20
a = a > 10 and 'BOLSHE' or 'MENSHE' # !!!
print( a ) |
# coding: utf-8
# 1. Исправить ошибки в этом программном коде
n = 0
def smart_task():
global n ## +
n += 1
print( 'start of smart_task #{}'.format(n) )
def other_task(param_1, param_2): ## ++
if param_1 == None:... |
# https://app.codility.com/demo/results/trainingVKJR3W-P6R/
def solution(A, B):
# write your code in Python 3.6
stack = []
N = len(A)
for fish in range(N):
if not stack:
stack.append(fish)
continue
prev_fish = stack[-1]
if B[fish] == B[prev_fish] or not B... |
import sqlite3
from _sqlite3 import Error
from _sqlite3 import OperationalError
import pandas as pd
from pandas import DataFrame
import os
import sys
"""
A program that can create a database if it does not already exist, creates tables with a specific format,
ability to import .csv files into tables if the fo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 13 22:48:56 2017
@author: christophergreen
Square digit chains
Problem 92
A number chain is created by continuously adding the square of the digits in a number to form a
new number until it has been seen before.
For example,
44 → 32 → 13 → 10 → ... |
# 2_CharStrCount.py
# by Prometheus111
# for a given string, calculate the number of occurrences of a character in it
# that is read from the keyboard
s = 'Here is your own text!' #we have the string s
print(s) #output the string s
a = input('Input the character: ')
n = ... |
def add(x, y):
#code
output = (x + y)
return output
def subtract(x, y):
#code
output = (x - y)
return output
def multiply(x, y):
#code
def divide(x, y):
#code
def power(x, y):
#code
output = (x ** y)
return output
#User input
#Calculator logic
#Output |
# This program will implement an FSA to accept the string "ABACCB".
word = input("Enter a string: ") #Asks the user to input a string
state = 1
for c in (word):
if state == 1 and c == 'C':
state = 1
elif state == 1 and c == 'A':
state = 2
elif state == 2 and c == 'B':
... |
def two_to_one(two_tuple, width) -> int:
"""map 2-space to 1-space
"""
x, y = two_tuple
return width * x + y + 1
def one_to_two(n, width) -> (int, int):
"""map 1-space to 2-space
"""
return (n//width - int(n % width == 0), (n - 1) % width)
def find_neighbors(index, width, height... |
#!/usr/bin/env python
# -*-coding:utf-8-*-
#time : 2020-02-21
#@Author : limeng
#@Email : 2421712196@qq.com
#@Note : 类似黑客帝国的代码雨效果
#导入系统文件库
import pygame
import random
from pygame.locals import *
from random import randint
#定义窗体参数及加载字体文件
SCREEN_WIDTH = 900 #窗体宽度
SCREEN_HEIGHT = 600 #窗体高度
LOW_SPEED = 4 ... |
import time
class Solution:
#n = input('please write your number:')
def happynumber(self,n:int):
unhappy = set()
while n not in unhappy and n != 1:
unhappy.add(n)
n = self.GetSqureSum(n)
print(unhappy)
#return n == 1
def GetSqureSum(self,n:int):
... |
import csv
import math
# from operator import add
'''
readAllSamples is a user defined function. It is used to read all the sample of CSV file. It takes filename as an argument as well as test row count to make a test set from the file. This function returns a train set and a test set.
'''
def readAllSamp... |
import turtle
class TurtleInstance(turtle.Turtle):
def __init__(self, name="", color="black"):
turtle.Turtle.__init__(self)
self.setName(name)
self.setColor(color)
self.speed(0)
self.penup()
pass
def setName(self,name):
self.name = name
def setColor(se... |
a = 3
b = 5
b = a + b
print(b)
x = 4
y = 5
z = x / y #use the / to get the output in floating point
print(z)
print(5 // 4) #use the // to get the output in int
print(2 ** 3)
print(7 % 2)
print(x + 3j) #Complex data type which means real + imaginary numbers
print("Dividing 4 by 3 using Integer division(4//3): ", 4 // 3)... |
print("Hello!")
i = 10
f = 0.10
s = "Hi There"
i1 = 99999999999999999999999999999
f1 = -0.00000000000000000000000000111111111
c = 'j1'
print(c)
print(f1, i1)
name = input("Enter your name: ")
print(name)
age = (int)(input("Enter the age: "))
print(age)
investment = (float)(input("Enter the amount to be invested: "))
pr... |
# URL: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
# Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
# (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
# Find the minimum element.
# You may assume no duplicate exists in the array.
# Examp... |
day = (input("Enter the day the call started at:"))
time = float(input("Enter the time the call started at (hhmm):"))
minutes = float(input("Enter the duration of the call (in minutes):"))
if day == "mon" or \
day == "tue" or \
day == "wed" or \
day == "thu" or \
day == "fri" or \
... |
print("Please enter the amount of money to convert: ")
dollar = int(input("# of Dollars: ")) * 100
cents = int(input("# of cents: "))
total = (dollar + cents) / 100
quarters = total // .25
r1 = (total - (quarters * .25))
dimes = r1 // 0.1
r2 = (r1 - (dimes * 0.1))
nickels = (r2 // .05)
r3 = (r2 - (nickels * .05))
... |
class MinimaxAgent(MultiAgentSearchAgent):
"""
Your minimax agent (question 1)
"""
def getAction(self, game_state):
"""
Returns the best minimax action from the current game_state using
self.depth and self.evaluationFunction.
Here are some method calls that are usefu... |
# snehal shilvant
# a_55
# tuple
Weights = (70, 80, 45, 50)
print(Weights)
# tuple "Weights" Cant be be modified because tuples are immutable.
Weights_New = (70,80, 48, 50)
print(Weights_New)
Maximum_variable = max(Weights_New)
Minimum_variable = min(Weights_New)
print("Maximum variable is:", Maximum_variable)
prin... |
# snehal Shilvant
# A-55
# day 4 Problem stmt 3
list = [1, 2, 3,1, (1,3), [1,3], {1,3}, {1,3}, [1,3], [1,3], (1,3), {1,3}, (1,3), {1,3},[1,3],{1,3}]
print(list)
print("list of 1 is :", list.count(1))
print("list of 2 is :", list.count(2))
print("list of 3 is:", list.count(3))
print("list of list is :", list.count([1... |
fruit = {"apple" : 5, "pear" : 3, "banana" : 4, "pineapple" : 1, "cherry" : 20}
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' }
dict.update(dict2)
print ("Value : %s" % dict) |
import math
import sys
# variável para determinar em qual menu o usuário estará
comando = 0
# mensagem inicial de boas vindas
print('Bem-vindo ao Sistema de Mercadinho!\n')
# função para exibir o menu inicial
def mostrar_menu():
print('1. Inciar uma nova compra')
print('2. Adicionar produto ao catálogo')
... |
import file_handler
class Dictionary:
@staticmethod
def word_search(word_dict, word_search):
for key, value in word_dict.items():
if word_search == key:
print(value)
def main():
'''
Creates a Dictionary object, calls load_data to populate dictionary from
a fi... |
from card import *
from wallet import *
def main():
'''
main controller class. Runs user through main menu and allows them to call
wallet methods to modify the wallet
:return:
'''
cards_ = generate_card_slots()
wallet = Wallet(cards_)
user_input = None;
while user_input != "q":
... |
import re;
a = "My name is Bibash. My name will always be Bibash.";
print(a);
print(re.sub("Bibash","Biplov",a));
b=r"I am\r\r!"
print(b);
|
from graphics import *
window = GraphWin("DDA line diagram",400,400)
def dda(x1,y1,x2,y2):
dx = x2 - x1
dy = y2 - y1
if abs(dx) > abs(dy):
stepsize = dx
elif abs(dx) < abs(dy):
stepsize = dy
x_inc = dx/stepsize
y_inc = dy/stepsize
x_new = x1
y_new = y1
for i in range(1,stepsize+1):
x_old = x_new
y_... |
import re;
pattern = r"(.+) \1";
if re.match(pattern,"spam spam"):
print("Match1");
if re.match(pattern,"$5 $5"):
print("Match2");
if re.match(pattern,"aa dd"):
print("Match3");
else:
print("No Match");
pattern =r"\D+\d";
# \d = didgits
# \s = whitespace'
# \w = word characters
#big letters are opposite t... |
import re;
if re.match("spam","aspamspamspam"):
print("Match");
else:
print("No Match");
if re.search("spam","aaaspamaaspamaaaspam"):
print("Match");
print(re.search("spam","aaaspamaaspamaaaspam").group());
print(re.search("spam","aaaspamaaspamaaaspam").start());
print(re.search("spam","aaaspamaaspamaaasp... |
class Animal:
def __init__(self,name,color):
self.name=name;
self.color=color;
class Cat(Animal):
def pur(self):
print("Meow");
class Dog(Animal):
def bark(self):
print("Bark");
def main():
a=Dog("Ema","Red");
print(a.color);
a.bark();
main();
|
++++++++++++++
class Vector:
def __init__(self,x,y):
self.x=x;
self.y=y;
def __add__(self,z):
return Vector(self.x+z.x , self.y+z.y);
def main():
a= Vector(1,2);
b= Vector(3,4);
result=a+b;
print("("+str(result.x)+","+str(result.y)+")");
main();
|
from graphics import *
win = GraphWin("Shapes", 1000, 1000)
win.setBackground("pink")
#rectangle
rec = Rectangle(Point(100,100), Point(450,350))
rec.draw(win)
rec.setWidth(5)
rec.setFill("green")
rec.setOutline("brown")
center = rec.getCenter() #returns center
corner1 = rec.getP1() #re... |
a = [4,5,6,1,8,4,7,8]
key = int(input("Enter the integer to search: "))
b = 0
for i in range(len(a)):
if a[i] == key:
print("Found")
b = 1
if b == 0:
print("NotFound")
|
from tkinter import *
class Application(Frame):
def __init__(self, cord):
super(Application, self).__init__(cord)
self.grid()
self.create_widget()
def create_widget(self):
#creating label
self.lbl = Label(self, text = "What do you want to eat?").grid(row=0, column=0, sticky=W)
self.lbl2 = Label(self, te... |
#!/usr/bin/python3
__author__ = 'Alan Au'
__date__ = '2020-02-24'
'''
Problem: Given an input string, code a function that prints all the permutations of the string.
This problem will return n! results, so for testing purposes, keep it small.
Also, repeat characters will generate repeat permutations.
Th... |
#coding:utf-8
import random
def solve_0(string = "stressed"):
print string[::-1]
def solve_1(string = u"パタトクカシーー"):
print string[::2]
def solve_2(str1 = u"パトカー", str2 = u"タクシー"):
print ''.join([a+b for a,b in zip(str1,str2)])
def solve_3(string = "Now I need a drink, alcoholic of course, after the heavy ... |
"""
prompts before redirecting to google
can open apps from the search menu
"""
# imports
import speech_recognition as sr
import wolframalpha
import wikipedia
import requests
import webbrowser
import time
import pyttsx3
import http.client as http
import pyautogui
# necessities
appId = '' # get the wolfram alpha app ... |
from queue import PriorityQueue
def contains(lista,valor,key=lambda x: x[1]):
for i in range(len(lista)):
if key(lista[i])==valor:
return i
return -1
class BacktrackingFinder:
def __init__(self,context):
self.context=context
self.contador=0
def find(self,origen,des... |
import math
def max_list_iter(int_list):
"""finds the max of a list of numbers and returns the value (not the index)
If int_list is empty, returns None. If list is None, raises ValueError"""
if int_list == None:
raise ValueError
if not int_list:
return None
m = int_list[0]
for i in range... |
'''
Lista de Exercícios 5
'''
# Exercício 1
nome=input('Qual o seu nome completo?')
print(nome.upper())
print(nome.lower())
palavras=nome.split()
print(''.join(palavras))
nome1=''.join(nome.split())
print(len(nome1))
print(len(palavras[0]))
# Exercício 2
num = input('Digite um numero entre 0 e 999')
n... |
'''
Aula 12
'''
#como mudar a cor, da fonte e do fundo, utilizando o padrao ANSI
print('\033[0;32;41mTeste de cor\033[m')
print('\033[2;35;43mTeste de cor\033[m')
print('\033[1;31;45mTeste de cor\033[m')
n = 10
print('O numero é: \033[1;31m{}\033[m'.format(n))
print('O numero é: {}{}{}'.format('\033[31m'... |
'''
Curso de python
Aula 09: Utilizacao de modulos, bibliotecas e funcoes
'''
import math
import emoji
num = int(input('Digite um numero '))
raiz = math.sqrt(num)
print('Numero {} - Raiz {:.2f}'.format(num,raiz))
print('Numero {} - Raiz {:.2f}'.format(num,math.ceil(raiz)))
print('Numero {} - Raiz {:.2f}... |
import random
#variables
y = 0
tries_message = "you tried %s times"
#get the number
number = int(random.randint(0, 1000))
# screen message
print("A random number will be generated")
print("Guess the Random number and you win!")
# collect user input
user_value = int(input('enter in a guess: '))
while (user_value !=... |
def maxSubArray(nums):
a = c = nums[0]
end = 0
begin = 0
for i in range(1, len(nums)):
if a+nums[i] >= nums[i]:
a = a + nums[i]
else:
a = nums[i]
begin = i
if a >= c:
c = a
end = i
else:
c = c
re... |
'''
219. 存在重复元素 II
给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的 绝对值 至多为 k。
示例 1:
输入: nums = [1,2,3,1], k = 3
输出: true
示例 2:
输入: nums = [1,0,1,1], k = 1
输出: true
示例 3:
输入: nums = [1,2,3,1,2,3], k = 2
输出: false
'''
# 下面代码会报超出时间限制
class Solution:
def containsNearbyDuplicate(self, nums: Li... |
# coding:utf-8
'''
551. 学生出勤记录 I
给定一个字符串来代表一个学生的出勤记录,这个记录仅包含以下三个字符:
'A' : Absent,缺勤
'L' : Late,迟到
'P' : Present,到场
如果一个学生的出勤记录中不超过一个'A'(缺勤)并且不超过两个连续的'L'(迟到),那么这个学生会被奖赏。
你需要根据这个学生的出勤记录判断他是否会被奖赏。
示例 1:
输入: "PPALLP"
输出: True
示例 2:
输入: "PPALLL"
输出: False
'''
class Solution:
def checkRecord(self, s: str) -> bool... |
# coding:utf-8
'''
572. 另一个树的子树
给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。
示例 1:
给定的树 s:
3
/ \
4 5
/ \
1 2
给定的树 t:
4
/ \
1 2
返回 true,因为 t 与 s 的一个子树拥有相同的结构和节点值。
示例 2:
给定的树 s:
3
/ \
4 5
/ \
1 2
/
0
给定的树 t:
4
/ \
... |
'''
21. 合并两个有序链表
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
22
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNod... |
#coding:utf-8
'''
637. 二叉树的层平均值
给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.
示例 1:
输入:
3
/ \
9 20
/ \
15 7
输出: [3, 14.5, 11]
解释:
第0层的平均值是 3, 第1层是 14.5, 第2层是 11. 因此返回 [3, 14.5, 11].
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
... |
'''
1410. HTML 实体解析器
「HTML 实体解析器」 是一种特殊的解析器,它将 HTML 代码作为输入,并用字符本身替换掉所有这些特殊的字符实体。
HTML 里这些特殊字符和它们对应的字符实体包括:
双引号:字符实体为 " ,对应的字符是 " 。
单引号:字符实体为 ' ,对应的字符是 ' 。
与符号:字符实体为 & ,对应对的字符是 & 。
大于号:字符实体为 > ,对应的字符是 > 。
小于号:字符实体为 < ,对应的字符是 < 。
斜线号:字符实体为 ⁄ ,对应的字符是 / 。
给你输入字符串 text ,请你实现一个 HTML 实体解析器,返回解析器解析后的结... |
import calendar
import itertools
import operator
import random
import string
months = calendar.month_name[1:]
#enumerate
print list(enumerate("abcdefg"))
print list(enumerate("abcdefg", start=2))
cardinal_directions = ['north', 'south', 'east', 'west']
for idx, direction in enumerate(cardinal_directions):
prin... |
import operator
import time
# https://www.python.org/dev/peps/pep-0318/
def log_args(func):
def new_func(*args, **kwargs):
print 'arguments: {} {}'.format(args, kwargs)
return func(*args, **kwargs)
return new_func
def double_args(func):
def new_func(*args, **kwargs):
doubled_args ... |
if not 0:
print "zero value ints are False"
if not 0.0:
print "zero value floats are False"
if not None:
print "None is False. Use is/is not to check for None."
if not False:
print "False is False"
if not '':
print "empty strings are False"
if not []:
print "empty lists are False"
if not (... |
#!/usr/bin/env python
# coding: utf-8
# # <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 2</font>
#
# ## Download: http://github.com/dsacademybr
# ## Exercícios Cap02
# In[2]:
# Exercício 1 - Imprima na tela os números de 1 a 10. Use uma lista para armazenar os números.
lista1 = [1,2,3,4,... |
#!/usr/bin/env python3
def parse_instructions(input_list):
return [instruction.split(' ') for instruction in input_list]
def execute(instruction_list):
program_count = 0
accumulator = 0
instructions_executed = set()
while True:
if program_count in instructions_executed:
return ... |
a=int(input("Enter number a:"))
b=int(input("Enter number b:"))
c=int(input("Enter number c:"))
p=b**2-4*a*c
m=2*a
if p<0:
print("Roots are imaginary")
else:
print(“First root is:”, ((-b+ p)/m)), ”Second root is:”, ((-b-p)/m))
|
global score
score = 0 #this is to keep track of the score
def scorend(): #this function is the printing out of the final score for the user
if score<11:
print "You got ",score," out of 18 you get an F"
if 14>score>11:
print "You got ",score," out of 18 you get a C"
if 16>score>14:
p... |
import linkedlist
def SumLists(l1, l2):
return ConvertListToNumber(l1) + ConvertListToNumber(l2)
def ConvertListToNumber(l):
base = 10
multiplier = 1
number = 0
current = l.head
while current:
number += current.value * multiplier
multiplier *= base
current = current.next
return number
def S... |
class Remove: # Heuristic class is defined here
def __init__(self,scoreremove,weightremove,numberofremoves):
# scores and weight are defined here
self.scoreremove = scoreremove # 8
self.weightremove = weightremove # 8
self.numberofremoves = numberofremoves # number of iteratio... |
import numpy as np
def nullspace_basis(A):
"""
Uses singular value decomposition to find a basis of the nullsapce of A.
"""
V = np.linalg.svd(A)[2].T
rank = np.linalg.matrix_rank(A)
Z = V[:,rank:]
return Z |
def word_count(fpath):
fopen = open(fpath)
fstr = fopen.read()
for i in fstr:
if not ((i >= 'a' and i <= 'z') or (i >= 'A' and i <= 'Z') or i == ' '):
fstr = fstr.replace(i, ' ')
fresult = fstr.split()
fopen.close()
#return len(fresult)
return fresult
fpath = raw_input("... |
"""
Implementing a Random Tree (RT) learner
@Name : Nidhi Nirmal Menon
@UserID : nmenon34
"""
import pandas as pd
import numpy as np
class RTLearner(object):
def __init__(self,leaf_size,verbose=False):
self.leaf_size=leaf_size
self.verbose=verbose
self.learner=[]
def author(self):
... |
from abc import ABC, abstractmethod
class Stmt:
class Visitor(ABC):
@abstractmethod
def visit_expression_stmt(self, stmt): pass
@abstractmethod
def visit_block_stmt(self, stmt): pass
@abstractmethod
def visit_print_stmt(self, stmt): pass
@abstractmethod
def visit_let_stmt(se... |
import csv
import random
import math
import operator
#Load the IRIS dataset csv file and convert the data into a list of lists (2D array) , make sure the data file is in the current working directory
#Randomly split dataset to training and testing data
def loadDataset(filename, split, trainingSet=[], testSet... |
from functools import wraps
from time import time
def timer(fn):
@wraps(fn)
def wrap(*args, **kw):
time_start = time()
result = fn(*args,**kw)
time_end = time()
print('function:{}\took:{} \n args:{} \n kwargs:{}'\
.format(fn.__name__,time_end-time_start,args,kw))
... |
# import the libraries to access data
from sklearn import datasets, neighbors
# load in the data into a variable 'digits'
digits = datasets.load_digits()
# separate the loaded data into the feature vectors x and their corresponding labels y
x_digits = digits.data
y_digits = digits.target
# find the number of instan... |
#!/usr/bin/env python
def merge(a, b):
s = []
i = 0
j = 0
for k in xrange(len(a) + len(b)):
try:
a[i]
except IndexError: # reached end of a
return s + b[j:]
try:
b[j]
except IndexError: # reached end of b
return s + a[i... |
import time
def bubble_sort(a_list):
n = len(a_list)
if n <= 1:
return a_list
for i in range(n - 2):
if a_list[i] > a_list[i + 1]:
a_list[i], a_list[i + 1] = a_list[i + 1], a_list[i]
return a_list
if __name__ == '__main__':
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20... |
import sys
import time
#I changed this
a = 2
b = 0.2 # slower time between characters getting spaced out
c = 0.08 # quicker time between characters getting printed
def intro():
print("\n")
time.sleep(a)
string_1 = '"Very well, remember to answer truthfully... Or don\'t, either way you\'ll pro... |
'''
tarea # 6 de programacion 3 Alexander Cerrud 8-850-2381
'''
import unittest
class registro:
try:
def registro(self,usuario,edad):
usuario=input("escribe tu nombre")
edad=input("escribe tu edad")
return {"usuario:":usuario,"apellido":usuario+"Baso","edad:":edad}
... |
'''
An interpreter for #if/#elif conditional expressions.
The interpreter evaluates the conditional expression and returns its truth value.
'''
import re
def toInt(numAsStr):
'Convert a C-style number literal to a Python integer.'
if (not type(numAsStr) is str):
return numAsStr # Forward everything t... |
## the main function is one which will always be called and takes
## the users initial input and decides what to do with it
def main():
og = input().split()
go = ""
command = og[0]
og = og[1:]
for x in range(0, len(og)):
go = go + og[x]
if command == "solve":
solve(go)
## solv... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 18 18:24:09 2019
@author: vikram
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 24 09:41:13 2019
@author: vikram
for regular regular expression basics
https://www.geeksforgeeks.org/regular-expression-python-examples-se... |
# https://medium.com/python-features/using-locks-to-prevent-data-races-in-threads-in-python-b03dfcfbadd6
import threading
# Accumulate total count of all processed items
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
# By using a lock, we can have th... |
matrizA = [[0,0,0], [0,0,0], [0,0,0]]
matrizB = [[0,0,0], [0,0,0], [0,0,0]]
soma = [[0,0,0], [0,0,0], [0,0,0]]
for linha in range(0, 3):
for colunas in range(0, 3):
matrizA[linha][colunas] = int(input(f'Digite um valor para a Matriz A: '))
print('**' * 30)
for linha in range(0, 3):
for colunas in r... |
from random import randint
numeros = (randint(1,10),randint(1,10),randint(1,10),randint(1,10),randint(1,10))
print(f'Os valores sorteados foram:', end=' ')
for n in numeros:
print(f'{n}',end=' ')
print('\n'f'O maior valor foi {max(numeros)}.')
print(f'O menor valor foi {min(numeros)}.')
|
x = int(input("Digite um número inteiro: "))
print("""Escolha a base para conversão:
[ 1 ] Binário
[ 2 ] Octal
[ 3 ] Hexadecimal""")
opcao = int(input("Sua opção: "))
if opcao == 1:
print("{} convertido para Binário é igual {}".format(x, bin(x)[2:]))
elif opcao == 2:
print("{} convertido para Octal é igual {}"... |
n = int(input("Digite um número: "))
n2 = int(input("Digite outro número: "))
soma = n+n2
print("A soma de {} mais {} é {}".format(n,n2,soma))
|
print("="*40)
print(" 10 TERMOS DE UMA PROGRESSÃO ARITMÉTICA")
print("="*40)
t = int(input("Digite o primeiro termo: "))
r = int(input("Digite a razão: "))
for c in range(0,10):
print(t,end=" ")
t = t + r
print("ACABOU") |
l = int(input("Qual a largura da parede: "))
a = int(input("Qual a altura da parede: "))
a = l*a
tinta = a/2
print("Para pintar essa parede, você precisará de {:.0f} latas de tinta".format(tinta)) |
salario = int(input("Informe o valor do seu salário: R$ "))
salario10 = salario + (salario * 0.10)
salario15 = salario + (salario * 0.15)
if salario >= 1250:
print("O seu salário reajustado será R${:.2f}\n".format(salario10))
else:
print("O seu salário reajustado será R${:.2f}\n".format(salario15)) |
x = int(input("Digite o valor correspondente ao lado de um quadrado: "))
X = x*4
Y = x**2
print("perímetro:", X, "- área:", Y)
|
a = 3
b = a
print(f'A variável B = {b} recebe o valor da variável A = {a}')
print('***' *30)
a = 6
print(f'Alteramos o valor da variável A para {a}, o valor da variável B permanece sendo o valor da variável A do começo do código = {b}')
print('***' *30)
a = [3,4,5]
b = a
print(a,b)
b[1] = 8
print(a,b)
print('***' *... |
lista = ['Joe', 'Sue', 'Hani', 'Sofia']
nome = input('Digite seu nome: ')
if nome in lista:
print('Login:', nome)
print('Você está logado!')
else:
print('Login:', nome)
print('Acesso negado! ') |
numero = int(input("Digite um número inteiro "))
unidade = numero % 10
numero = (numero - unidade) // 10
dezena = numero % 10
print("O dígito das dezenas é", dezena)
|
n = int(input('Digite o valor de n: '))
conta = 0
impar = 1
while conta < n:
print(impar)
conta += 1
impar += 2
|
def media(x,y):
return (x+y)/2
nota1 = eval(input('Digite o valor da nota 1: '))
nota2 = eval(input('Digite o valor da nota 2: '))
resultado = media(nota1,nota2)
print(resultado) |
n = int(input("Digite um número: "))
contador = 0
for c in range(1,n+1):
if n == 2 or n == 5 or n == 9 or n % 2 != 0:
print("{} é primo.".format(c))
else:
print("{} não é primo.".format(c))
|
def fat(n):
if n == 0:
print(1)
else:
res = n * fat(n-1)
print(res)
n = input('Digite o valor de n: ')
fat(n) |
def upper_first_char(s):
return s[0].upper() + s[1:]
def camel_case(s):
# remove punctuation, lower case, split by spaces
split = s.replace('.', ' ').lower().split()
# capitalize first letter of preceding words
for idx, word in enumerate(split):
if (idx > 0):
split[idx] = upper... |
#Test scoreboard notice
import leaderboard
import turtle
import random
import math
playerName = input('What is your name')
Colours = ['Pink', 'lightblue', 'white']
colour = random.choice(Colours)
shape = 'circle'
size = 4
timer = 5
timerFinished = False
counter_interval = 1000
font = ('Courier New', 20, 'bold')
s... |
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mapping = { ')':'(' , '}':'{', ']':'[' }
for bracket in s:
if bracket in mapping:
top_element = stack.pop() if stack else '#'
... |
class Solution:
def isUgly(self, num: int) -> bool:
rem2 = 0
rem3 = 0
rem5 = 0
if num == 0:
return False
else:
while num%2 == 0:
rem2 = num%2
num = num/2
while num%3 == 0:
... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
'''
1. create a head
'''
curr = Lis... |
import string
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
for i in paragraph:
if i in string.punctuation:
paragraph = paragraph.replace(i, ' ')
listOfWordsinParagraph = paragraph.lower().split()
... |
d = {"a": 1, "b": 2, "c": 3}
a = d["a"]
b = d["b"]
sumlist = a + b
print(sumlist)
print(d["a"] + d["b"]) |
a=[1,2,3]
for index, item in enumerate(a):
print("Item %s has index %s" % (item,index))
for index, item in enumerate(a):
print("%s %s" % (index,item)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.