text
stringlengths
37
1.41M
s = "Мой дядя самых честных правил, Когда не в шутку занемог, Он уважать себя заставил И лучше выдумать не мог" print(" ".join([x for x in s.split() if not x.startswith(("м", "М"))]))
s = "У лукоморья 123 дуб зеленый 456" if 'я' in s: print('Индекс буквы "я" -' ,s.index("я")) else: print('В строке нет буквы "я"') """Определяет есть ли определенная буква в строке и выводит ее индекс""" y = s.count('у') print('Количество букв "у" в строке -', y) """Определяет количество определен...
#!/usr/bin/python from number_filter import filter_even_numbers def read_file(filename): numbers = [] try: file = open(filename, "r") for row in file: filtered_values = filter_even_numbers(row) numbers.extend(filtered_values) file.close() except FileNotFoundError as e: print("The file...
#!/usr/bin/python from jsonreader import read_json_file from jsonwriter import write_json_file from product import Product from inputhandler import get_string_input from inputhandler import get_boolean_input from inputhandler import get_int_input from inputhandler import get_product_info from producthandler import sear...
import unittest from nameutil import handle_name from astronaut import Astronaut class NameUtilTest(unittest.TestCase): def test_handle_single_lastname(self): name = "Martin Bäumer" expected_astronaut = Astronaut("Martin", "Bäumer", None) actual_astronaut = handle_name(name) self.as...
#!/usr/bin/python def capture_age(): correct = False age = 0 while not correct: try: age = int(input("Your age: ")) if age < 0 or age > 120: print("ERROR: Please enter a reasonable age!") else: correct = True except ValueError: print("ERROR: Please enter a numeric ...
#/usr/bin/python def isAnagram(first, second): if len(first) == 0 or len(second) == 0: return False if len(first) != len(second): return False i = 0 while i < len(first): char = first[i] j = 0 char_in_second = 0 while j < len(second): if second[j] == char: char_in_second ...
#!/usr/bin/python def get_pieces(num_pieces): result = "" if num_pieces < 2: result = "piece" else: result = "pieces" return result def get_proper_be(num_leftovers): result = "are" if num_leftovers == 1: result = "is" return result def get_pizzas(num_pizzas): result = "pizzas" if num_pi...
#!/usr/bin/python from product import Product def get_string_input(question): result = '' while len(result) == 0: result = input(question) return result def get_boolean_input(question): alts = [] alts.append("y") alts.append("n") answer = '' while answer not in alts: answer = input(question) ...
#!/usr/bin/python import random from level import Difficulty from comparison_result import ComparisonResult def generate_my_number(difficulty_level): max = 10 if difficulty_level == Difficulty.MEDIUM: max = 50 elif difficulty_level == Difficulty.HARD: max = 100 number = random.randint(0,max) retur...
def addBinary(self, a: str, b: str) -> str: """ 试试直接转换 :param self: :param a: :param b: :return: """ return '{0:b}'.format(int(a, 2) + int(b, 2)) def addBinary1(a: str, b: str) -> str: """ 模拟加法,这种居然不如直接转换快。。。 :param self: :param a: :param b: :return: """ ...
from typing import List def plusOne1(self, digits: List[int]) -> List[int]: """ :type digits: List[int] :rtype: List[int] """ a = "" for i in digits: a += str(i) return list(map(int, str(int(a) + 1))) def plusOne2(digits: List[int]) -> List[int]: """ :type digits: List[in...
def maxSubArray(arr): #complexity O(n^2) max = 0 for i in range(len(arr)): sum = 0 for j in range(i, len(arr)): sum += arr[j] if sum > max: max = sum return max def maxSubArray2(arr): #Kadane’s Algorithm o(n) max1 = 0 max2 = 0 for i in ran...
# Lambda Function: Shorter way to write Fucntions. The common observations are: These functions don’t have a name These functions don’t need indentation or { } to indicate function body for single line functions These functions don’t need return statement for single line functions. The expression is automatically r...
class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: ret_l = [] ret_r = [] for ele in A: if ele%2 == 0: ret_l.append(ele) else: ret_r.append(ele) return ret_l+ret_r # Time: O(N) # Space: O(N) class ...
# Approach 2: Dynamic Programming 2D class Solution: def minPathSum(self, grid: List[List[int]]) -> int: # Time: O(MN) # Space: O(MN) m = len(grid) n = len(grid[0]) dp = [ [ None for c in range(col) ] for r in range(row) ] dp[0][...
class Solution: def countNegatives(self, grid: List[List[int]]) -> int: count = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] < 0: count += 1 return count class Solution: def countNegativ...
''' Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x #...
## Simillar to Two sum problem: # Time: O(N) # Space: O(n) class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: hashmap = {} for i, num in enumerate(numbers): diff = target - num if diff in hashmap: return [hashmap[diff]+1, i+1] ...
def main(): """Get a right password and print asterisks""" password = input("Enter a password: ") while len(password) < 5 or len(password) > 12: print("Invalid password") password = input("Enter a password: ") for char in range (len(password)): print('*', end='') if __name__ == '...
n1=float(input("Ingrese nota 1: " )) n2=float(input("Ingrese nota 2: " )) n3=float(input("Ingrese nota 3: " )) n4=float(input("Ingrese nota 4: " )) nfinal = 0.2*n1 + 0.3*n2 + 0.25*n3 + 0.25*n4 print("La nota definitiva es: ", nfinal)
i = 1 while i <= 5: print(i) i = i + 1 manzanas = 5 cont = 0 print("Se ha iniciado el carrito. En total hay: " + str(cont) + " manzanas") while (cont < manzanas): cont += 1 print("Se ha agregado una manzana a la canasta. Ahora hay " + str(cont) + " manzanas") bandera = True cont = 0 while bande...
# Hacer un código que lea cuatro datos: El código de un estudiante # y las notas de los tres previos de una materia cualquiera; y que # calcule e imprima la nota final de la materia, junto con el código # del estudiante. Este se podrá utilizar para más de un estudiante, # y que informe cuantos perdieron la materia....
## ## Author: Kristina Striegnitz and Daniel W. Wolf ## ## 10-31-2013 ## ## shooting-monsters-task4 ## ## This program shows a player character (orange ball) which can be ## controlled using the 'a'and 'd' keys. It also displays a score. ## #import the modules import pygame import random import math RADIUS = 0 X = 1...
import turtle t = turtle.Screen() s = turtle.Turtle() for i in range(12): s.forward(100) s.backward(100) s.left(30)
print('名片系统'center(30,' ')) print('新增名片'center(30,' ')) print('删除名片'center(30,' ')) print('更改名片'center(30,' ')) print('查找名片'center(30,' ')) cards = [] while True: fun_number = int(input('请选择功能')) if fun_number == 1: flag =0 card ={} name = input('请输入名字') for temp in cards: if name == temp['name']: fla...
def Swapper() : print('swap the data in your files') file1=input('file name 1? ') file2=input('file name 2? ') o1=open(file1,'r') o2=open(file2,'r') d1=o1.read() d2=o2.read() w1=open(file1,'w') w1.write(d2) w2=open(file2,'w') w2.write(d1) Swapper()
import dataclasses @dataclasses.dataclass class Node: def __post_init__(self): # values used in the finder self.cleanup() def __lt__(self, other): """ nodes are sorted by f value (see a_star.py) :param other: compare Node :return: """ return se...
def f(x): answer = 0 for i in range(1, x): if i % 3 == 0 or i % 5 == 0: answer += i return answer print(f(10)) print(f(1000))
def int_to_roman(input): """ Convert an integer to a Roman numeral. """ if not isinstance(input, type(1)): raise Exception('expected integer, got %s' % type(input)) if not 0 < input < 400000: raise Exception('Argument must be between 1 and 399999') ints = (1000, 900, 500, 400, 100, 90...
import math import sympy import itertools from math import * from fractions import gcd def is_square(n): return int(sqrt(n)) == sqrt(n) # r < d < q # a > b , a/b = c # because d^2 = q*r # cb^2 < cab < ca^2 # n = cabca^2 + cb^2 = a^3*c*2*b + b^2*c = a*a*a*c*c*b + b*b*c L = 10 ** 12 progressiveSquares = set() su...
from fractions import Fraction import itertools import sys class NumberTheory(): def __init__(self, n): self.n = n self.prime_list = self.__init_prime_list(n // 2)[::-1] self.largest_prime_divisor_list = self.__init_largest_prime_divisor_list(n) def __init_prime_list(self, n): ...
import math, sympy, time, multiprocessing, itertools import numpy as np def is_bouncy(x): # Takes a number. True if it's bouncy, False if not. digits = [int(i) for i in str(x)] directions = [] for i in range(0, len(digits)-1): if digits[i] > digits[i+1]: # print("down ") d...
# 变量信息 import string import random def INT(): num=random.randint(0,999) return num def FLOAT(): fl=random.uniform(0,999) fln=round(fl,2) return fln def UPPERCASE(): S= string.ascii_uppercase R= random.choice(S) return R def LOWERCASE(): s=string.ascii_lo...
from __future__ import print_function from IPython.display import clear_output def display_board(board): clear_output() row = '' for idx,column in enumerate(board): #print(idx) idx += 1 column = str(column) if str(column) == 'X' or str(column) == 'O' else idx if( (idx % 3) ...
def qsort0(X=[5,14,2,3,9,10,6,1,4,7,13]): # a list '''Recursive implementation of quicksort''' def qsort0_rec(X,L,R): if (R > L): pivot = X[R] # Just choose the right-most element of X as pivot Xp,i = _partition(X[L:R], pivot)#This implementation uses sentinels X[L:(R...
n = int(input()) limit = (n+1) * 60 * 60 count = 0 for i in range(limit): hour = i // (60 * 60) # print(hour) remain = i % (60 * 60) time = remain // 60 remain = remain % 60 second = remain result = str(hour) + ":" + str(time) + ":" + str(second) + "초" if result.__contains__(str(3)): ...
# 계단 함수 import numpy as np import matplotlib.pyplot as plt a = np.array([-1.0, 1.0, 2.0]) print('a : ' + str(a)) b = a > 0 print('b : ' + str(b)) c = b.astype(np.int) print('c : ' + str(c)) def step_function(x): return np.array(x > 0, dtype=np.int) print('step_function(a) : ' + str(step_function(a))) x = np.a...
import sqlite3 import sqlite3 connection = sqlite3.connect('src/mydata.db') cursor = connection.cursor() # create_tabel = "create table if not exists users(id integer primary key ,username text,password text)" # create_tabel = "create table if not exists item_model(id integer primary key AUTOINCREMENT,name text ,pri...
import re class RomanNumerals: def __init__(self): self.dict = {1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC', 50: 'L', 40: 'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'} def to_roman(self, num): # из int в roman result = '' for key, value in self.dict.item...
fileName = input('Enter a filename: ') try: fileHandle = open(fileName) except: # Here's the Easter Egg if 'na na boo boo' in fileName: print("NA NA BOO BOO TO YOU! You have been punk'd!") else: print('Please enter a valid filename') quit() lineCount = 0 for line in fileHandle: l...
fileName = input('Enter a filename: ') try: fileHandle = open(fileName) except: print('Please enter a valid filename') quit() count = 0 for line in fileHandle: if 'From' in line: words = line.split() email = words[1] print(email) count = count + 1 print('There were', count, '...
class Node(object): def __init__(self, value=None, next=None): self.value, self.next = value, next class LinkedList(object): def __init__(self, maxsize=None): self.maxsize = maxsize self.root = Node() self.length = 0 self.tail_node = None def __len__(self): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 30 17:13:28 2020 @author: lu270 """ def gcd(): a=int(input('a=')) b=int(input('b=')) if a>=b: a,b=(a,b) a,b=(b,a) try: r=a%b while r != 0: a=b b=r r...
import sys import json kind = input("Which kind of data? (單字(w) 慣用語(p)) ") num = input("How many? ") if kind is 'w': print("Please use data_record_db.py") """ if len(sys.argv) == 2: file = open(sys.argv[1], 'a') else: file = open('json_words', 'a') print("日文\t中文\t漢字") fo...
# string_to_hex_utf8.py from ast import literal_eval str = "0xAAA" # convert the string to the integer convert_str = literal_eval(str) # print the value and type of the convert_str print(convert_str) print("type", type(convert_str)) # pass the convert_str to the hex () method hex_value = hex(convert_str) print(hex_v...
num1 = int(input('Digite o numero: ')) num2 = int(input('Digite o numero: ')) num3 = int(input('Digite o numero: ')) ma2 = None if num1 > num2 and num1 > num3: ma = num1 if num2 > num3: ma2 = num2 else: ma2 = num3 elif num2 > num1 and num2 > num3: ma = num2 elif num3 > num2 and num3 > ...
num = int(input('Digite o primeiro numero')) num2 = int(input('Digite o segundo numero')) num3 = int(input('Digite o terceiro numero')) ma = None if num > num2 and num > num3: ma = num elif num2 > num1 and num2 > num3: ma = num2 elif num3 > num2 and num3 > num1: ma = num3 print(ma)
temp_c = float(input('Digite a temperatura em c: ')) print('A temperatua em C é:', temp_c * 9/5 + 32)
h_mes = float(input('Digite qtd de horas por mes')) valor_h = float(input('Digite o valor da sua hora')) print('O valor final é:', (h_mes * valor_h))
# -*- coding: utf-8 -*- # 이진 분류를 위한 데이터 셋 정의 X_data = [1,2,3,4,5,6,7,8,9,10] y_data = [0,0,0,1,0,1,1,1,1,1] import tensorflow as tf X = tf.placeholder(tf.float32, shape=[None]) y = tf.placeholder(tf.float32, shape=[None]) w = tf.Variable(0.0) b = tf.Variable(0.0) # 텐서플로우를 활용하여 # 이진 데이터를 분류하는 방법 # 1. 선형방정식을 사용하여 값을...
# -*- coding: utf-8 -*- """ class Car: honk = '빵빵' def info(self, color, year): print("color : %s , year : %d" format(color, year)) 위와 같이 클래스 메소드의 첫 번째 인수로 self를 써 줘야하만 해당 메소드(여기선 info)를 인스턴스의 메소드로 사용할 수 있게 됩니다. self는 간단히 말하면 이 메소드를 부르는 객체(my_car)가 해당 클래스(Car)의 인스턴스인지 확인해주기 위한 장치입니다. 하...
# -*- coding: utf-8 -*- """ Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, -1, 1] s...
# -*- coding: utf-8 -*- # Set 타입 내부의 데이터 삭제 # - remove, pop 메소드를 사용 numbers = set([1,2,3,4,5,6,7,8,9]) # 1. remove 메소드 사용 # - 특정 데이터를 삭제하는 경우 사용 # - 삭제만 수행(삭제된 값을 반환하지 않음) numbers.remove(5) print(numbers) r_value = numbers.remove(8) print(numbers) # remove 메소드는 삭제한 결과를 반환하지 않으므로 # r_value 에는 None 값이 대입됩니다. print(f"r...
# -*- coding: utf-8 -*- # Set 타입 내부의 데이터 접근방법 # Set 타입은 기본적으로 데이터의 직접 접근을 # 허용하지 않습니다. # Set 타입에 저장된 데이터는 리스트 타입으로 # 변환할 수 있으며, 리스트로 변환된 이후 # 인덱스 연산을 사용하여 값에 접근할 수 있음 # Set 타입의 변수 생성 msg_set = set("Hello Python~!") # Set 타입의 변수를 리스트 타입으로 변환 # - list(set변수명) msg_list = list(msg_set) print(msg_set) print(msg_list) ...
# -*- coding: utf-8 -*- # 리스트 내부에 저장된 요소들을 정렬하는 방법 # - sort 메소드를 사용하여 처리할 수 있음 numbers = [5,1,3,2,9,6,7,8] print(numbers) # 리스트 내부의 요소들을 오름차순 정렬하는 예제 # sort 메소드 사용 numbers.sort() print(numbers) # sort 메소드의 reverse 매개변수의 값을 True로 # 지정하여 내림차순 정렬을 수행할 수 있음 numbers.sort(reverse=True) print(numbers) # 리스트 변수의 reverse 메소...
import functools @functools.total_ordering class Record: """ Container class storing record of a mathematician in the graph. """ def __init__(self, name, institution=None, year=None, id=None): """ Record class constructor. Parameters: name: string containing mathe...
while True: print("Welcome to the elevator") floor_select = int(input("Please select floor 1-10: ")) if floor_select > 10 or floor_select < 1: print("Invalid entry, Try again") else: current_floor = int(input("Enter the current floor: ")) if floor_select==current_floor: ...
# 1. Create three variables in a single line and assign values to them in such a manner that each one of them belongs to a different data type. a, b, c = 1, 2.01, 'string' # 2. Create a variable of type complex and swap it with another variable of type integer a = 1+2j b = 12 a, b = b, a print(a) print(b) # 3. Swap t...
import sqlite3 # GENERATES NEW USER ID # def make_id(db_filename, table_name): connection = sqlite3.connect(f"DATABASE/{db_filename}.db") cursor = connection.cursor() # Return last ID key = cursor.execute(f"SELECT ID from {table_name} ORDER BY ID DESC LIMIT 1") # Fetch data value = key.fetc...
# -*- coding: utf-8 -*- # 用来测试append和insert和extend等list操作 li = ["a","b","third","z","s"] li.append("new") print li #尾部追加元素 append ,注意是单个 li.insert(2,"new2") print li #定位插入insert , 也是单个元素 list中的元素可以重复,也就是说可以有两个new, li2 = ["one","two"] li.extend(li2) # extend合并列表 print li print li.extend(["ff","de"]) li.extend("345") ...
from collections import Counter from typing import List class Food: def __init__(self, ingredients: List[str], allergens: List[str]): self.ingredients = set(ingredients) self.allergens = set(allergens) def __repr__(self): return f"{self.ingredients} (contains {self.allergens})" @...
class Adapter: def __init__(self, n: int): self.joltage = n self.valid_connections = set(range(self.joltage - 3, self.joltage)) def __repr__(self): return f"Adapter({self.joltage})" class Chain: def __init__(self, filename: str): with open(filename) as f: numbe...
# Multiple Linear Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values # Encoding the Independent Variable from sklearn.preprocessing i...
"""Advent of code day 7 Represent bags as connections (directed graph) - search connections for bag names - count bags """ import re import numpy as np def search_second_bg(second_bag): """Search second bag for its number and colour""" sb = re.search("([0-9]+) (.*?) bag", second_bag) if sb: out ...
import nltk from nltk.corpus import stopwords class StopwordRemoval(): def fromList(self, text): """ Sentence Segmentation using the Punkt Tokenizer Parameters ---------- arg1 : list A list of lists where each sub-list is a sequence of tokens representing a sentence Returns ------- list A ...
my_list = [1, 5, 10, 2, 3, 100, 50] print(f'Исходный список - {my_list}') new_list = [my_list[el] for el in range(len(my_list)) if my_list[el] > my_list[el-1]] print(f' Новый список - {new_list}')
import pandas as pd import requests as r ## Data collection ## url = "https://en.wikipedia.org/wiki/Template:COVID-19_pandemic_data" req = r.get(url) # Get the specfic table data from the url data_list = pd.read_html(req.text) target_df = data_list[0] # data is in index 0 ## Data Cleaning ## # Change columns names t...
from random import randint from typing import Tuple from logic import init_field, is_empty_ceil, set_ceil, is_win, is_available_ceil def print_field(field: list): for row in field: for ceil in row: print(ceil, end=" ") print() def get_step(field: list, player_symbol: str): size ...
""" nlp_utils.py A collection of universally applicable util functions for the (pre-)processing of input text (files). """ FOOTNOTE_CHARS = ['[', ']'] PUNCTUATION_CHARS = [',', '.', ':', '?', '!', '"', "'", ';'] class TextCleaner: """ Offers various functions to clean up text. """ def __init__(self, ...
''' A Class that defines a team. A team holds a name string, and holds an array (members) of Athletes in it. ''' import Athlete import json import os class Team: def __init__(self, name, members): self.name = name self.members = members def printTeam(self): for i in self.members: ...
from graphExamples import * from collections import deque def hillClimbing(G, start, end, distToGoal=100): """ G: graph start: start node end: end node distToGoal = heuristic for start to end distance """ if start==end: return end visited = set() # node stack = deque() # doubly linked list used ...
# Name - Sarthak Sanjay Sonpatki # Day-10 # Print following a pattern without using any loop. (Hint use recursive functions) # # Examples : # # Input: n = 16 # Output: 16, 11, 6, 1, -4, 1, 6, 11, 16 # # Input: n = 10 # Output: 10, 5, 0, 5, 10 def pattern(n): print(n) if n<=0: return ...
n = 10 if n >= 0: fn2 = 0 # Initialize f(n-2). print(fn2,end=',') if n >= 1: fn1 = 1 # Initialize f(n-1). print(fn1,end=',') for i in range(2,n+1): # Here is where we iterate from 2:n. fn = fn1 + fn2 # Recurrence relation is f(n) = f(n-1) + f(n-2). print(fn,end=','...
def summation(a,b): total = 0 for n in range(a,b+1): total += n return total primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] if __name__ == '__main__': print('Testing function summation():...', end='') total = summation(1,100) if (total == 5050): print('OK') ...
#!/usr/bin/env python3 # The previous line is the shebang line to define to use python3 # (effort for PEP 8 style compliance, check with pycodestyle) # load important modules import numpy as np import matplotlib as plt import matplotlib.pyplot as plt # load the modules that will be used for the regression vs. percept...
class Parent: def __init__(self, last_name, eye_colour): print "Parent Init Called" self.last_name = last_name self.eye_colour = eye_colour def show_info(self): print "Last Name: "+self.last_name print "Eye Colour: "+self.eye_colour class Child(Parent): def __init__...
import sqlite3 class createDatabase(): def user(self): conn = sqlite3.connect('./database/project.db') c = conn.cursor() c.execute('PRAGMA foreign_keys = ON') c.execute('CREATE TABLE IF NOT EXISTS user(\ id_User INTEGER PRIMARY KEY AUTOINCREMENT,\ email_...
def solution(x, y): x_upper = x+y-1 sum_x_upper = 1 i = 1 while i < x_upper: i+=1 sum_x_upper+=i return str(sum_x_upper-(x_upper-x)) print(solution(5,10))
class Orden (): """ Clase Orden recibe LIST de computadora """ contadorOrdenes=0 def __init__(self,computadora): Orden.contadorOrdenes += 1 self.contadorOrdenes = Orden.contadorOrdenes self.__idOrden= self.contadorOrdenes self.__computadoras = computadora ...
#KATA: Format a string of names like 'Bart, Lisa & Maggie'. import unittest class TestUM(unittest.TestCase): def setUp(self): pass def test_5_names(self): #self.assertEqual(namelist([{'name': 'Bart'},{'name': 'Lisa'},{'name': 'Maggie'},{'name': 'Homer'},{'name': 'Marge'}]), 'Bart, Lisa, Ma...
#Filename: q5_upper_to_lower.py #Author: Tan Di Sheng #Created: 20130123 #Modified: 20130123 #Description: This program is used to convert an uppercase letter #from standard input to a lowercase letter by making use of its ASCII value #or vice versa print("""This application is used to convert an uppercase letter to a...
# -*- coding: utf-8 -*- """ Created on Mon Feb 18 19:15:57 2019 @author: Shihab """ t=int(input()) for case in range(t): inputs=input().split() print("Case "+str(case+1)+": "+inputs[len(inputs)//2])
def menu(): #prompt the user to enter 1 to invoke enterAllMarksOfAStudentToStorage #prompt the user to enter 2 to invoke displayAllReports #prompt the user to enter 3 to quit the program kbinput = input("Enter 1 to store student details\n" + "Enter 2 to display student report\n" + "Ente...
import multiprocessing as mp # import pathos.multiprocessing as pm import time import counter import printer # If the queue is empty then the exit was not requested def exit_requested(requestQueue): return not requestQueue.empty() def counter_worker(thousands, pause, exitRequest, pipelineOut): """ This...
"""Code to play the game 'Tetris'""" import matplotlib.pyplot as plt from matplotlib import colors import numpy as np import copy import math #game_height = 20 #game_width = 10 #grid = np.zeros(20,10) class tetromino: #Might need to add 'null tetrominoes' here later types = { "Oshape...
import itertools import math def get_product(num_pairs: int, target: int) -> int: with open('input.txt') as f: numbers = [int(line.strip()) for line in f] pairs = itertools.combinations(numbers, num_pairs) valid_pairs = [pair for pair in pairs if sum(pair) == target] if len(valid_pairs) > 0: valid_pair = val...
# This file contains code to learn how to write data to a file using python # This is also known as storing data in flat files # The type of files can be .csv, .json or even .txt # Other ways to store data is to store data inside a database # For now we are focusing on storing data in files # To read from/write to a...
ock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' ...
#CEDERJ - SÃO FIDELIS - FUNDAMENTOS DE PROGRAMAÇÃO #WANDERSON C. SOUZA print('Faça um programa que leia o nome de um vendedor, o seu salário fixo e o total de vendas efetuadas por ele no mês (em dinheiro).') print('Sabendo que este vendedor ganha 15% de comissão sobre suas vendas efetuadas, informar o total a receber n...
import json # import pandas as pd import requests # import urllib.request def getResponseFromUrl(url): headers = {'Content-Type': 'application/json'} response = requests.get(url, headers=headers) if response.status_code == 200: return response.content.decode('utf-8') else: return None ...
class menu: def __init__(self): self.menu = {'Burger':'60','French Fries':'80','Chicken Wings':'90'} def show(self): print (self.menu) def add(self,i,n): self.menu[i]=n c=menu() while(1): ch=int(input("Enter your Choice as\n1.To Di...
from sklearn.datasets.mldata import fetch_mldata from sklearn.linear_model import SGDClassifier import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import confusion_matrix from sklearn.model_selection import cross_val_score dataset = fetch_mldata('MNIST original') #Importing the Data from the dat...
from tkinter import * from tkinter import messagebox import sqlite3 # Create LogIn Screen tk = Tk() # Create Parent tk.title("Log In") # Create Title for the Screen tk.geometry("400x150") # Set the Size for the Screen tk.resizable(False, False) # Set the Screen NOT Resizable tk.iconbitmap("images\\ArtVisionIcon.ic...
population = 10000000; # exmaple a. if population < 10000000: print(population) b. 10000000 <= population <= 35000000 (and -> &&, or -> ||) if population >= 10000000 and population <= 35000000: print(population) c. if (population / land_area) > 100: print('Densely populated') d. if (population / land_area) ...
# 2-a. index = 0 smallest = L[0] for i in range(1, len(L)): if L[i] < smallest: index = i smallest = L[i] # 2-b. def min_index(L): """ (list) -> (object, int) Return a tuple containing the smallest item from L and its index. >>> min_index([4, 3, 2, 4, 3, 6, 1, 5]) (1, 6) """ index =...
print("="*20) a = float(input("Digite o valor da A: ")) print("="*20) b = float(input("Digite o valor de B: ")) print("="*20) import numpy as np import matplotlib.pyplot as plt eixo_x = [] eixo_y = [] for x in np.arange(0, 5, 1/10): y = (a*x) + b eixo_x.append(x) eixo_y.append(y) plt.pl...
sexo = str(input("Sexo[M/F]: ")).upper() while sexo not in "MF": print("DÍGITO INVÁLIDO") sexo = str(input("Digite novamente o sexo[M/F]: ")).upper() print("FIM!")
valor = float(input("Valor da casa: R$")) sal = float(input("Salário do comprador: R$")) tempo = int(input("Quantos anos de financiamento? ")) valor_emprest = valor / (tempo*12) valor_sal = sal * (30/100) if valor_sal < valor_emprest: print("Para pagar uma casa de {} em {} anos a prestação será de R${:.2f}".f...
import random import time escolha = int(input("""Suas opções: [0] PEDRA [1] PAPEL [2] TESOURA Qual é a sua jogada? """)) result = random.randint(0, 2) print("JO") time.sleep(1) print("KEN") time.sleep(1) print("PÔ") time.sleep(1) if escolha == 0 and result == 1: print("-="*12) print("Jogador j...