text stringlengths 37 1.41M |
|---|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeZeroSumSublists(self, head: ListNode) -> ListNode:
temp = dummy = ListNode('dummy')
dummy.next = head
while temp.next:
... |
from typing import List
class Solution:
def isValid(self, s: str) -> bool:
stack: List[str] = []
d = {')': '(', ']': '[', '}': '{'}
for c in s:
if stack and c in d and stack[-1] == d[c]:
stack.pop()
else:
stack.append(c)
retur... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
def backtrack(curr=[i for i in range(1, n+1)]):
if len(curr) == 0:... |
#encoding=utf-8
#快速排序
#算法分析:一列无序的列表中,取列表第一个元素为基准数据。
#设置两个变量,i = 0, j = len(list) - 1。
#从后面向前比较(j = j - 1),如果该数据比基准数据小,则将该数据跟基准数据交换。
#从前面向后比较(i = i + 1),如果该数据比基准数据大,则将该数据跟基准数据交换。
#然后递归执行。
def QuickSort(listValue, start, end):
"""
"""
if start < end:
i, j = start, end
baseNumber = listValue[i]
while i < j:
... |
def dictdiff(d1, d2):
d1_keys = set(d1.keys())
d2_keys = set(d2.keys())
all_keys = d1_keys.union(d2_keys)
diff = {}
for key in all_keys:
d1_value = d1.get(key)
d2_value = d2.get(key)
if d1_value != d2_value:
diff[key] = [d1_value, d2_value]
return diff
|
from collections import deque
class MaxStack():
def __init__(self):
self._items = deque()
self._max_stack = deque()
def push(self, item):
if not self._max_stack or item >= self.max():
self._max_stack.append(item)
self._items.append(item)
def pop(self):
... |
from collections import defaultdict
class School:
def __init__(self):
self._students = defaultdict(list)
def add_student(self, name, grade):
self._students[grade].append(name)
def roster(self):
roster_by_grade = []
for grade in sorted(self._students.keys()):
r... |
from collections import deque
import pytest
# Approach 1
# class MinStack:
# def __init__(self):
# self._stack = deque()
# self._min_stack = deque()
# self._current_min = None
#
# def push(self, item):
# self._stack.append(item)
#
# def pop(self):
# popped_item = s... |
# Time Complexity: O(n)
# Space Complexity: O(1)
def is_palindrome(s):
left = 0
right = len(s) -1
s = s.lower()
while left < right:
left_char, right_char = s[left], s[right]
if not left_char.isalnum():
left += 1
continue
if not right_char.isalnum():
... |
# Time complexity: O(n)
# Space complexity: O(n)
def dominant_index_approach_1(nums):
max_num = max(nums)
for num in nums:
if num != max_num and num*2 > max_num:
return -1
return nums.index(max_num)
|
from collections import Counter
# Time Complexity: O(n)
# Space Complexity: O(n)
def first_uniq_char(s):
char_counts = Counter(s)
for i, char in enumerate(list(s)):
if char_counts[char] == 1:
return i
return -1
|
# Time Cost: O(n)
# Space Cost: O(n)
def climb_stairs(n):
if n == 1:
return 1
paths = [0] * n
paths[0], paths[1] = 1, 2
for i in range(2, n):
paths[i] = paths[i-1] + paths[i-2]
return paths[n-1]
|
import random
# while running is true
running = True
while running:
# Create a random integer between 0 and 5
s = random.randint(0,5)
# If the integer is less than 3
if s < 3:
# Print this
print('It is too small, starting over.')
# Reset the next interation of the loop
# ... |
# 4. Пользователь вводит целое положительное число.
# Найдите самую большую цифру в числе.
# Для решения используйте цикл while и арифметические операции.
user_number = int(input('Введите целое положительное число:'))
max_number = user_number % 10
user_number = user_number // 10
print(max_number)
print(user_numb... |
import statistics as stat
import sys
import datetime
import matplotlib.pyplot as plt
TIMES_FILENAME = "times.txt"
YTICK_OFFSET = 10
MIN_TIME_THRESHOLD = "23:00"
def getTimeValue(time):
#time = sanitiseTime(time) # Sanitise time first
hour = int(time[0:2])
minute = int(time[3:])
timeVal = (hour * 60)... |
"""This module only contains the Movie class"""
import webbrowser
class Movie():
"""A structure that stores all the basic information of a movie"""
def __init__(self, title, storyline, poster_image_url,
trailer_youtube, lead_actors, imdb_rating):
""""""
self.title = ... |
class Graph(object):
"""docstring for Graph"""
def __init__(self, matrix, s, t):
self.matrix = matrix
self.s = s
self.t = t
self.size = len(matrix[0])
def link(self, u, v):
self.matrix[u][v] = 1
def dfs(graph, current_node, parent_list, parent_set):
if current... |
import unittest
from searches.dijkstras import dijkstras
from structures.graph import WeightedGraph
class TestDijkstras(unittest.TestCase):
def test_basic_dij(self):
graph = WeightedGraph()
graph.add_edge('a','b',1)
graph.add_edge('a','c',4)
graph.add_edge('b','c',2)
self... |
import unittest
from algorithms.math.convert_base import convert_base, convert_digit_to_int
class TestConvertBase(unittest.TestCase):
def test_convert_digit_valid(self):
for i in range(10):
self.assertEqual(i, convert_digit_to_int(str(i)))
for c,v in [('a',10),('b',11),('c',12),('d',13... |
def first_missing_positive(nums):
"""
Find the first missing positive integer in a list of integers.
This algorithm sorts the array by making swaps
and ignoring elements that are greater than the length
of the array or negative.
If the element is equal to the current index (start) then
it... |
from collections import deque
def breadth_first_search(grid, start, target):
"""
Search a 2d grid for a given target starting at start.
Args:
grid: the input grid as a List[List]
start: the start grid in format (x,y) zero index
target: the target value to find in the grid
Retur... |
from functools import reduce
def factorial(n: int):
"""
Factorial algortihm using dynamic programming.
Args:
n: the factorial number to find
Returns:
The factorial number for n (n!). Input
of 0 or less will output 0.
"""
# base case, reduce must have non-empty lis... |
def radixsort(ar: list, base=10):
"""
"""
def create_buckets(ar, iteration):
buckets = [[] for x in range(0,base)]
for num in ar:
digit = (num // (base ** iteration)) % base
buckets[digit].append(num)
return buckets
def create_list(buckets):
num... |
import unittest
from algorithms.math.factorial import factorial
from algorithms.math.fibonacci import fibonacci_dp, fibonacci_recursive
class test_math(unittest.TestCase):
def test_factorial(self):
self.assertEqual(factorial(0), 0)
self.assertEqual(factorial(1), 1)
self.assertEqual(factori... |
from threading import Lock
from constants import *
# *************************************************
# ROAD
# *************************************************
class Lane:
def __init__(self, length, next_lane, pass_colors):
self.lock = Lock()
self.q = []
self.length = length
se... |
# Python3 program to add two numbers
# Ask user for first number
number1 = input("Enter the first number: ")
# Ask user for second number
number2 = input("Enter the second number: ")
# Adding two floating point numbers
sumOfNumbers: float = float(number1) + float(number2)
# Print the sum of two numbers
print("Sum of... |
#!/usr/bin/env python3
""" Create a class Poisson that represents a poisson distribution"""
_e = 2.7182818285
class Poisson:
""" represents a poisson distribution """
def __init__(self, data=None, lambtha=1.0):
"""
initialize - initialize poisson distribution
@data: to estimate the di... |
#!/usr/bin/env python3
"""performs back propagation over a pooling layer of a neural network"""
import numpy as np
def conv_backward(dZ, A_prev, W, b, padding="same", stride=(1, 1)):
"""performs back propagation over a pooling layer of a neural network
@dz: np.ndarray shape(m, h_new, w_new, c_new) containing ... |
#!/usr/bin/env python3
"""Function that performs the Monte Carlo Algorithm"""
import numpy as np
from collections import defaultdict
def monte_carlo(env, V, policy, episodes=5000,
max_steps=100, alpha=0.1, gamma=0.99):
"""Performs the Monte Carlo Algorithm
@env: the openAI environment instance... |
#!/usr/bin/env python3
"""builds a modified version of the LeNet-5 architecture using tensorflow"""
import tensorflow as tf
def lenet5(x, y):
"""builds a modified version of the LeNet-5 architecture using tensorflow
@x: tf.placeholder - shape(m, 28, 28, 1) input images for the network
@m: number of i... |
#!/usr/bin/env python3
"""Normalize an unactivated output of a neural network
using batch normalization """
import numpy as np
def batch_norm(Z, gamma, beta, eps):
""" Normalize an unactivated output of a neural network
using batch normalization
@Z: numpy.ndarray - shape (m, n) should be normalized
... |
#!/usr/bin/env python3
"""Shuffle X and Y to help against over fitting"""
import numpy as np
def shuffle_data(X, Y):
""" Shuffles X and Y to help against over fitting
@X: numpy.ndarray of shape (m, nx) to shuffle
@m: number of data points
@nx: number of features in X
@Y: numpy.ndarray shap... |
#!/usr/bin/env python3
"""
Return the transpose of a 2D matrix
"""
def matrix_transpose(matrix):
"""function that returns the transpose of a 2D matrix"""
new_matrix = []
for i in range(len(matrix[0])):
new_matrix.append([])
for x in range(len(matrix)):
new_matrix[i].append(... |
"""
file: entry.py
description: the entry(node) used for the linked hashtable
language: python3
author: Dongyu Wu, Chenghui Zhu
"""
class ChainNode:
"""
The ChainNode class represents each single entry containing its obj and
links to other entries
"""
__slots__ = "_obj", "_prev", "_link", "_chain"
... |
from collections import deque
# stacking/tumpukan (first in last out)
data = [1, 2, 3, 4, 5]
print(data)
data.append(6)
print('data masuk :',6)
print(data)
data.append(7)
print('data masuk :',7)
print(data)
stack = data.pop()
print('data terakhir dihapus :',stack)
print(data)
print('='*100)
# queue/antrian (first in ... |
# tambahan method untuk mengakses List
merkHp = ['oppo', 'samsung', 'sony', 'asus']
# tambah isi list sesuai urutan
merkHp.append('apple')
print(merkHp)
# tambah isi list sesuai keinginan
merkHp.insert(2,'asus')
print(merkHp)
# menghitung jumlah isi list yang sama
hitung = merkHp.count('asus')
print(hitung)
# perpanjan... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 11 22:11:01 2019
@author: utsav
"""
# Import pandas
import pandas as pd
# Read the file into a DataFrame: df
df = pd.read_csv('C:\\Users\\utsav\\Desktop\\Python_Data_Sets_Data_Camp\\Cleaning Data in Python\\dob_job_application_filings_subset.csv ')
h = df["Bor... |
from tkinter import *
root = Tk()
root.geometry("600x400")
list_name = ["Mickey mouse", "Elsa", "Anna", "Donald duck"]
dict_student = { "name" : "Shinchan",
"age" : "5"}
try:
print(list_name[5])
print(dict_student["mom"])
except IndexError :
messagebox.... |
# Brute Foraces a shift cipher
#spent 30 min
def readCipherText(filename):
with open(filename, 'r') as f:
ciphertext = f.read().strip()
return ciphertext
def characterToInt(char):
return ord(char) - 65
def intToChar(num):
return chr(num + 65)
def decipherChar(key, character):
return i... |
import itertools
class Card:
def __init__(self, number, suit):
self.number = number
self.suit = suit
@property
def json(self):
return {
'number': self.number,
'suit': self.suit
}
def __eq__(self, other):
return self.number == other.numb... |
# 题目1
str1 = '大家好,我的名字叫:'
str2 = '黑羽白月'
print(str1 + str2)
# 题目2
name = input('输入你的名字:')
age = input('输入你的年龄:')
print(f'你的名字是:{name}, 你的年龄是{age}')
|
import turtle
import math
import tkinter
class Draw:
drawNr = 0
def __init__(self,canvas,scales):
#Variables
self.nr = Draw.drawNr
#Init turtle
pen = turtle.RawTurtle(canvas)
pen.speed(0)
pen.color('white','white')
pen.goto(0,0)
canvas.delete("all... |
def calculate_loss(x,y,m,b):
y_predicted = [m * x_value + b for x_value in x]
loss = 0
for i in range(len(y)):
loss += (y[i] - y_predicted[i]) ** 2
return loss
x_values = [4, 3, 2]
y_values = [6, 2, 4]
print(calculate_loss(x_values,y_values,1,0))
print(calculate_loss(x_values,y_values,2,1))
|
# -*- coding: utf-8 -*-
"""
Created on Fri May 8 09:01:31 2020
@author: Yenny
"""
import calendar
from tkinter import *
root = Tk()
labels = [['Mon','Tue','Wed','Thu','Fri','Sat','Sun']]
MonthCal = calendar.monthcalendar(2020, 3)
for i in range(len(MonthCal)):
labels.append(MonthCal[i])
for r in range(len(MonthC... |
# 我用 Python 打扑克牌
suits = ['♠', '♦', '♥', '♣']
def want_card(card):
if card[0:2] == "黑桃":
suit = suits[0]
number = card[2]
elif card[0:2] == "方片":
suit = suits[1]
number = card[2]
elif card[0:2] == "红心":
suit = suits[2]
number = card[2]
elif card[0:2] == "梅... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 26 13:12:55 2019
@author: Administrator
"""
def decision(cards,face_up_card):
# 确定对面上家出牌的颜色和数字
face_up_color = face_up_card.split(" ")[0]
face_up_number = face_up_card.split(" ")[1]
# 确认你手中的牌
for card in cards:
if card.split(" ")[0] == fa... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 8 09:03:41 2020
@author: Yenny
"""
import calendar
import tkinter as tk
root = tk.Tk()
def LabelCal(Year, Month):
# 首行放置“年、月”的位置
label = tk.Label(root,text=str(Year)+"年")
label.grid(row=0,column=2)
label = tk.Label(root,text=str(Month)+"月")
label.gr... |
class Famous:
def __init__(self,name):
self.name = name
def __repr__(self):
# 下方判断 self.name 是否为 "鲁迅"
if self.name == "鲁迅":
return "{}:在我的后园,可以看见墙外有两株树。".format(self.name)
# 下方判断 self.name 是否为 "海明威"
if self.name == "海明威":
return "{}:世界是个美好的地方,值得为它奋斗。".format(self.name)
if self.n... |
'''
我们来计算一段文本中,各个字符的出现次数。
比如在 "我是我自己" 这段文本中,"我" 出现2次,"是"、"自"、"己" 各出现1次。
1.创建空字典 char_count;
2.用for循环遍历 text,令其中元素为 char_count 的键,值为 0;
3.再次for循环遍历 text,每到一个元素,令 char_count[元素] += 1;
4.输出:char_count。
'''
text = "上海自来水来自海上"
char_count = {}
for char in text:
char_count[char] = 0
for char in text:
char_count... |
'''
三角形内角和为 180度;
四边形内角和为 360度;
五边形内角和为 540度;
……
那么,n边形的内角和为多少度?
已知:n边形内角和公式 (n-2) * 180:
1.请写一个函数 degree(),参数为 side,当n边形的边数为 side 时,输出n边形内角和;
2.调用函数 degree(),令 side = 6。
'''
# 我用 Python 计算任意多变形内角和
def degree_n(side):
angle = (side-2)*180
print(angle)
degree_n(6)
|
'''
我们随机抛掷一个六面骰子1000次,每个面会有怎样的概率分布?
'''
import random
side_num = range(0,6)
side_count = {"1":0,"2":0,"3":0,"4":0,"5":0,"6":0}
roll_time = 1000
for play in range(0,roll_time):
dice = random.choice(list(side_count.keys()))
side_count[dice] += 1
for side, count in side_count.items():
print("数字{}的概率为{}".f... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 16 08:43:15 2019
@author: Administrator
"""
# 作业
def solution(s, first, second):
loc_second = s.index(second)
s = s[::-1]
loc_first = len(s)-s.index(first)+1
return loc_first<loc_second
print(solution("a rabbit jumps joyfully", "a", "j"))
print(so... |
'''
房贷计算器 I 等额本息还款
老张打算买一套房子,贷款100万,计划分30年还完。
已知年利率在4.9%,假设老张用等额本息还款,每月要还多少钱?
注:等额本息还款是指:还款期内,每月偿还同等数额的贷款(包括本金和利息),计算公式如下(也可参考代码中的注释部分):
每月还款额度 =(贷款本金×月利率×(1+月利率)^还款月数) ÷((1+月利率)^还款月数-1)
我们来建立一个计算 等额本息 还款的函数吧:
1.创建函数 pay_loan(),设置三个参数 loan,months,year_rate。分别对应贷款金额、还款月数、年利率;
2.函数主体内,创建变量 month_rate = year_rate/1... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 17 09:33:44 2019
创建一个对列表执行奇偶变换n次的函数。
每个奇偶变换:
每个奇数整数加2(+2)。
每个偶数整数减2(-2)。
"""
def solution(lst, n):
for i in range(len(lst)):
if lst[i]%2 == 0:
lst[i] = lst[i]-2*n
else:
lst[i] = lst[i]+2*n
return lst
print(solution([3, 4, 9... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 15 16:52:30 2019
你需要创建一个带有两个参数的函数:
(1)玩家的手中牌的列表
(2)牌桌上当前 面朝上的牌
如果玩家可以进行游戏,则该函数将返回True;
如果玩家必须从牌组中抽取,则该函数将返回False。
如果有以下情况,玩家可以进行游戏:
他们的卡片与面朝上卡片的颜色相同。
他们的卡号与面朝上卡的号码相同。
"""
def solution(hand,face):
color_face = face.split(" ")[0]
number_face = face.split(" ")[... |
dictionary = {'test':'test_value', 'europe':'eur', 'dollar':'usd', 'ruble':'rub'}
keys = list(dictionary.keys())
new_key = 0
print('FOR')
for new_key in range(len(dictionary)):
key = keys[new_key]+str(len(keys[new_key]))
value = dictionary[keys[new_key]]
dictionary.pop(keys[new_key])
dictionary.update(... |
# importing the necessary opencv libraries
import cv2
# reading the image using the opencv
img = cv2.imread('./images/portrait.jpg', cv2.IMREAD_COLOR)
# function which takes the image and converts to pencil sketch
def convert_to_pencil_sketch(img_rgb, canvas=None):
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2G... |
#f = open("My New File.txt","x")
# if f:
# print("File is successfully creat.")
import os
f = open("My New File.txt","a+")
if f:
print("File is succesfully open.")
#print(f.read())
f.write("this is python.\n")
f.writelines("hello.\n My file is made in python \n")
#print(f.read())
os.remove("My New File.t... |
a=int(input("Enter your AGE : "))
print("You can vote.") if(a>=18) else print("You can not vote.")
|
a=int(input("Enter value of A"))
b=int(input("Enter value of B"))
print("Your first value is",a)
print("Your Second value is",b)
print("Your Sum is")
c=a+b
print("\t",c)
print("Your Substraction is")
c=a-b
print("\t",c)
c=a*b
print("Your mutification is \t",c)
c=a/b
print("Your sum is \t",c)
c=a//b
print("Your ... |
# Class to make a neural net
def load_data(tetrode_number):
"""
Get data with labels, split into training and test set.
"""
X_train, X_valid, X_test, y_train, y_valid, y_test = formatData(tetrode_number,BASENAME,CONV)
X_train = X_train.reshape(X_train.shape[0],1,X_train.shape[1])
X_valid... |
n=int(input('Enter dec: '))
h=hex(n)
h=h.replace('0x','')
print('Its Hex is: '+h.upper())
input()
|
def imprime_linha(n):
linha = ""
for i in range(0,n):
linha += f"{n} "
return linha
numero = int(input("Digite um número: "))
for i in range(1, numero+1):
print(imprime_linha(i))
|
import random
def flip():
total_heads = 0
total_tails = 0
count = 0
while count < 100:
coin = random.randint(1, 2)
if coin == 1:
total_heads += 1
elif coin == 2:
total_tails += 1
count += 1
print "Heads =", total_heads
print "T... |
#O(w*n*log(n)) time | O(wn) space
def groupAnagrams(words):
anagrams = {}
for word in words:
sortedWord= "".join(sorted(word))
if sortedWord in anagrams:
anagrams[sortedWord].append(word)
else:
anagrams[sortedWord] = [word]
return list(anagrams.values())
gro... |
#! usr/bin/env python3
#Math Program that calculates and prints value according to given formula
import math
#Constant variables
C = 50
H = 30
#variable D should be input as comma separated value
I = input ("Enter comma separated values\n")
#print(I.split(","))
Q=[]
#formula
for d in I.split(","):
q= math.sqrt(... |
import hashlib
input_str = 'ckczppom'
i = 1
while True:
hash_str = input_str + str(i)
hash_val = hashlib.md5(hash_str.encode()).hexdigest()
if hash_val[:5] == '00000':
print("The number that produces five zeros hash value is {}.".format(i))
print("The hash value is {}.".format(hash_val))
... |
# Coursera, Applied Data Science with Python, University of Michigan
# Course 1, Introduction to Data Science in Python
# Week 4: Answering Questions with Messy Data
# A demo of the unreliability of p-values and how easy it is to generate
# datasets with statistically significant difference using random numbers
impo... |
# Coursera, Google IT Automation with Python
# Course 6, Automating Real-World Tasks with Python
# Week 2, Interacting with Web Services
import os
import requests
def main():
source_dir = 'files'
os.chdir(source_dir)
for path in os.listdir():
if path.endswith('.txt'):
payload = text_to_dict(path)
response ... |
# Coursera, Google IT Automation with Python
# Course 6, Automating Real-World Tasks with Python
# Week 4, FINAL PROJECT
import os
import mimetypes
import smtplib
from email.message import EmailMessage
def create_email(params, attachment=None):
"""Generates the message to be emailed and returns it"""
message = Em... |
from time import sleep
from random import randint
lista = []
jogos = []
cont = 1
print(f'{"":-^40}')
print(f'{"MEGA SENA":^40}')
print(f'{"":-^40}')
qtd = int(input('Digite quantos jogos deseja fazer: '))
for i in range(qtd):
while len(lista) < 6:
n = randint(1, 60)
if n not in lista:
... |
n = input('Digite um valor: ')
print(n.isnumeric())
print(n.isalnum())
print('Está em caixa alta? {}'.format(n.isupper()))
"""
Para retornar o tipo primitivo de um objeto basta utilizar a função type como vemos a seguir
print(type('nome do objeto'))
print(n.isnumeric)
print(n.isalpha)
print(n.isaln... |
v1 = 0
lista = []
matriz = []
line = 30
for i in range(1, 3):
for v in range(1, 3):
v1 = int(input(f'Digite o valor [{i}][{v}]: '))
lista.append(v1)
matriz.append(lista[:])
lista.clear()
print(f'-' * line)
print('Matriz gerada')
for i in range(1, 3):
for v in range(1, 3):
prin... |
largura = float(input('Digite a largura da parede: '))
altura = float(input('Digite a altura da parede: '))
area = altura * largura
tinta = area / 2
print('A área da parede é de {:.2f}m².'.format(area))
print('A quantidade de tinta necessária para pintar a parede é {:.2f}l.'.format(tinta))
|
preco = float(input('Digite o valor do produto: '))
print('''
========== Opções de pagamento ==========
1 em dinheiro ou cheque
2 à vista no cartão
3 em 2x no cartão
4 em 3x ou mais vezes no cartão
''')
pagamento = int(input('Digite a opção de pagamento: '))
if pagamento == 1:
valor = preco... |
multiplicacao = 0
while True:
numero = int(input('Digite um número [numero negativo para sair]: '))
print('-=-' * 20)
if numero < 0:
break
print(f'Tabuada de {numero} é:')
for tabuada in range(1, 11):
multiplicacao = tabuada * numero
print(f'{numero} x {tabuada:2} = {multip... |
lista = []
while True:
lista.append(int(input('Digite um numero: ')))
opcao = str(input('Deseja continuar? [S/N]: ')).strip().upper()[0]
print(f'{"":-^40}')
if opcao in 'N':
break
lista.sort(reverse=True)
print(f'Foram digitados {len(lista)} números.')
print(f'A lista dos valores em ordem de... |
from random import randint
from time import sleep
soma = cont = 0
jescolha = ''
print('Jogo do PAR ou IMPAR, está pronto caro jogador?')
print('Carregando...')
sleep(1)
while True:
computador = randint(0, 21)
jogador = int(input('Digite um número entre 1 e 20: '))
while jescolha not in 'PI':
jesc... |
escolha = int(input('Digite algum número positivo: '))
for i in range(1, 11):
print('{} x {:2} = {:6}'.format(escolha, i, escolha*i))
|
from time import sleep
opcao = 0
soma = 0
mult = 0
def menu():
print('''Digite uma das opções
1 - Somar números
2 - Multiplicar números
3 - Maior número
4 - Novos números
5 - Sair do programa
''')
n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o ... |
l = [0] * 3
for i in range(3):
l[i] = float(input('Digite o {}º lado: '.format(i+1)))
if l[0] < l[1] + l[2] and l[1] < l[2] + l[0] and l[2] < l[1] + l[0]:
if l[0] == l[1] and l[0] == l[2]:
print('Todos as medidas são iguais, por isso o triângulo formado é o Equilátero.')
elif l[0] == l[1] or l[1] ... |
nome = input('Digite seu nome: ')
sexo = input('Digite somente as iniciais do seu sexo(M/F): ')
azul = '\033[1;34m'
amarelo = '\033[1;33m'
if sexo=='M' or sexo=='m':
print('{}Olá {}, seja muito bem vindo!'.format(azul, nome))
elif sexo=='F' or sexo=='f':
print('{}Olá {}, seja muito bem vinda!'.format(amarelo, ... |
soma = p1 = p2 = 0
expressao = str(input('Digite a expressão matemática: '))
for p in expressao:
if p == '(' or p == ')':
soma += 1
if soma % 2 == 0 and soma != 0:
print('Expressão válida!')
else:
print('Expressão inválida, tente novamente!')
|
"""
implement a module for huffman encoding and decoding
endcode into cmp file first write the decode dictionary needed for decoding
then write the data
for instance if the input is "h" and code is h : 0 encoded file will be
h:0
0
"""
from bitarray import bitarray
class Stack():
"""
Stack implementation usi... |
people={1:{'name':'john','age':'27','sex':'male'},2:{'name':'Marie','age':'22','sex':'Female'}}
#list checking
print(people)
print(people[1])
print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex'])
people[3]={}#declaring a new list element
#entering values in new list elements
people[3]['nam... |
class Automobile:
def __init__(self,make,model,mileage,price):
self.__make=make
self.__model=model
self.__mileage=mileage
self.__price=price
def set_make(self,make):
self.__make=make
def set_model(self,model):
self.__model=model
def set_mileage(s... |
password=str(input("Enter your Password : "))
if(password.__eq__("prospero")):
print("valid")
else:
print("invalid")
|
numero1=int(input("enter first value "))
numero2=int(input("enter second value "))
if numero1 % 2==0:
print("Es par ")
# para el "for" debo usar siempre una variable nueva. Así evito que se reescriba la variable.
for numero in range(numero1,numero2):
if numero % 2==0:
print( str(numero) + " is even "... |
fruit = 'banana'
pos = fruit.find('na')
banana.upper()
banana.lower()
greet = ' Hello Bob '
nstr = greet.replace('Bob','Jane')
print greet.replace('o','X')
greet.lstrip()
greet.rstrip()
greet.strip()
line='Please have a nice day'
line.startswith('Please')
## Parsing the txt
data='From stephen.marquard@uct.ac.za Sat Ja... |
count=0
total=0
while True:
inp = raw_input('Enter a number: ')
# Don't Count here!
if inp == 'Done': break
if len(inp)<1 : break #check for empty line#
# Do the work
try:
num = float(inp)
except:
print 'invalid input'
continue
count=count+1
total=total+num
... |
from gpiozero import LED
from time import sleep
led = LED(17)
while True:
led.on()
sleep(1)
led.off()
sleep(1)
#Button
from gpiozero import Button
from time import sleep
button = Button(2)
while True:
if button.is_pressed:
print("Pressed")
else:
print("Released")
sleep(1... |
import re
import csv
# тестовые выборки на башкирском и мокшанском языке
# функция преобразует текст в массив слов
def to_words(text):
words = text.split()
for i in range(len(words)):
words[i] = words[i].strip('!,.?\(\):;\'\"\[\]-')
words[i] = words[i].lower()
for word in words:
... |
# Uses python3
import sys
#from collections import namedtuple
#from operator import attrgetter
#Segment = namedtuple('Segment', 'start end')
def optimal_points(segments):
points = []
segments = sorted(segments, key=lambda x: x[1])
# segments = sorted(segments, key=attrgetter('end'))
# print(segments)
min_righten... |
# Uses python3
#import sys
'''
def fibonacci_partial_sum_naive(from_, to):
sum = 0
current = 0
next = 1
for i in range(to + 1):
if i >= from_:
sum += current
current, next = next, current + next
return sum % 10
'''
def get_period(m):
a = 0
b = 1
c = a+b
for i ... |
import math
class Vec:
def __init__( self, x, y ):
self.x,self.y = float(x),float(y)
def __add__(self, other ):
return Vec( self.x+other.x, self.y+other.y )
def __sub__(self, other ):
return Vec( self.x-other.x, self.y-other.y )
def __mul__(self, other ):
return Vec( self.x*other, self.y*other )
def __rmu... |
def CountBinaryOnes (num):
ones = 0
while num:
ones += num & 1
num >>= 1
return ones
x = int (input ("Enter the first number to be checked ") )
y = int (input ("Enter the second number to be checked ") )
first = CountBinaryOnes(x)
second = CountBinaryOnes(y)
bit_bal = first - second
if b... |
# tipe data float
a = 10.5
# tipe data integer
b = 10
# tipe data string
c = "100"
d = a + b
print(d)
e = str(a) + c
print(e)
matakuliah = "Pemrograman Jaringan"
f = "0.5"
angkaF = float(f)
g = "10"
angkaG = int(g)
h = f + g
|
#!/usr/bin/python
import numpy as np
import yaml
import math
from operator import itemgetter
import pprint
def dijkstras(occupancy_map, x_spacing, y_spacing, start, goal):
"""
Implements Dijkstra's shortest path algorithm
Input:
occupancy_map - an N by M numpy array of boolean values (represented
... |
import numpy as np
# sigmoid function
def nonlin(x, deriv=False):
if (deriv == True):
return x * (1 - x)
return 1 / (1 + np.exp(-x))
def nn():
# input dataset
X = np.array([[0, 0, 1],
[0, 1, 1],
[1, 0, 1],
[1, 1, 1]])
# output dataset
y = np.... |
'''
knn.py
An crude implementation of a simple k Nearest Neighbors classifier.
kNN is one of the simplest classification algorithms available. It works by classifying
items base on the closest training examples in a given feature space. For example,
picture a map of California with two pins in it -- one in Los Angele... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.