text stringlengths 37 1.41M |
|---|
# 아래와 같은 입력에 대한 출력을 제공하는 프로그램을 작성하시오.
# 문제. 4 unpaired tag finder아래와같은입력에대한출력을제공하는프로그램을작성하시오.
# 예시 1)Input: "<div><div><b></b></div></p>"
# Output: div
# 예시 2)Input: "<div>abc</div><p><em><i>test test test</b></em></p>"
# Output: i
input_string = input("태그 입력:")
tag_list = []
tag_str = ""
for x in in... |
"""An incomplete Huffman Coding module, for use in COSC262.
Richard Lobb, April 2021.
"""
import re
HAS_GRAPHVIZ = True
try:
from graphviz import Graph
except ModuleNotFoundError:
HAS_GRAPHVIZ = False
class Node:
"""Represents an internal node in a Huffman tree. It has a frequency count,
minimum... |
# coding=utf-8
def extract_data_from_post(post):
"""
Extract likes_count, shares_count, comments_count from post
:param post: facebook post
:return: int, int, int
"""
# The number of reactions, shares, comments of a specific post
reactions_count = 0
shares_count = 0
comments_count ... |
a = int(input('valor a: '))
b = int(input('valor b: '))
c = int(input('valor c: '))
if a == b == c:
print('todos os lados são igual é escaleno\ne')
elif a == b or b == c or c == a:
print('dois lados são iguais é Isósceles\ne')
elif a != b != c:
print('todos os lados são direfentes é Escaleno\ne')
if a < ... |
num = int(input('digite um numero até 4 digitos'))
uni = num // 1 % 10
dez = num // 10 % 10
cen = num // 100 % 10
mil = num // 1000 % 10
print('unidade é {}\n'
'dezena é {}\n'
'centena é {}\n'
'milhar é {}\n'
''.format(uni, dez, cen, mil)) |
import sqlite3, datetime, time
from pycpfcnpj import gen, cpfcnpj
#pip install pycpfcnpj ou interpretador: procurar por: pycpfcnpj
while True:
connection = sqlite3.connect('cafeteria.db')
c = connection.cursor()
opcao = int(input('digite 1 para cadastro de cliente\n'
'digite 2 para... |
import math
#ou
#from math import trunc
numero = float(input('digite numero real'))
print('o valor digitado foi {}'
' e a porção inteira é {}'
''.format(numero, math.trunc(numero)))
|
valorcasa = float(input('valor da casa?'))
salario = float(input('seu salario?'))
print('mensalidade poderá ser até R$ {}'.format(salario*0.7))
quantidadeanos = int(input('quantidade de anos'))
print('a quant de meses é {}'.format(quantidadeanos*12))
print('parabéns vc poderar comparar a casa'
if (valorcasa/(q... |
bea = 0
for c in range(0, 6):
num = int(input('digite'))
if num % 2 == 0:
bea += num
print(bea) |
import datetime
from funcao_aleatorias import falar, adicionar_tarefa, ler_tarefas
# definir o nome da assistente virtual
nome_assistente = "Milena a sua mocinha gostosa."
# obter a data e hora atual
agora = datetime.datetime.now()
# perguntar ao usuário o que ele quer fazer
falar(f"Olá, Douglas, eu sou a ... |
#obtained_num = int(input("Please provide a number to simply output: "))
# print(obtained_num)
print('INPUT OBTAINED:: ' + input('Please provide a val to simply output'))
|
a_tuple = (100, 200, 300)
b_tuple = (500, 600, 700)
print(a_tuple)
print(a_tuple[0])
print(a_tuple[-1])
#del a_tuple
# print(a_tuple)
a, b, c = a_tuple
print(f'a: {a}, b: {b}, c: {c}')
print(a_tuple[:2])
print(a_tuple[1:])
print(a_tuple[:])
print(a_tuple + b_tuple)
|
import sys
import pygame
pygame.init()
# Set the window size
size = 600, 500
w, h = size
screen = pygame.display.set_mode(size)
BLACK = 0, 0, 0
RED = 255, 0, 0
GREEN = 0,255,0
GRAY = 150, 150, 150
YELLOW = 255, 255, 0
r = 25
BALL_COLOR = RED
BALL_RADIUS = 20
WALL_COLOR = GRAY
HOME_COLOR = GREE... |
import cv2
import numpy as np
# Function that applies Sobel x or y,
# then takes an absolute value and applies a threshold.
def abs_sobel_thresh(img, orient, sobel_kernel, grad_thresh):
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Take the derivative in x or y given orient = 'x' o... |
<<<<<<< HEAD
my_string = "This is a string!"
print(my_string.upper())
# Or more concisely
print("This is a string!".lower())
=======
my_string = "This is a string!"
print(my_string.upper())
# Or more concisely
print("This is a string!".lower())
>>>>>>> 2ab29db80d2817a1c80482a26ac9c1190fd392c6
#COMMENT |
import sys
# algorithm for http://www.geeksforgeeks.org/printing-brackets-matrix-chain-multiplication-problem/
# algorithm for print best parenthesis in matrix multiplication
class HoldName:
def __init__(self, name):
self.name = name
def printParenthesis(i: int, j: int, n: int, backets, name: HoldName):... |
class Solution:
def isPalindrome(self, x: int) -> bool:
s = str(x)
num = len(s)
if num % 2 != 0:
s = s[:num//2] + s[num//2 + 1:]
s1 = s[:num//2]
s2 = s[num//2:]
s2 = s2[::-1]
flag = True
for i in range(len(s1)):
if s1[i] != s2... |
class Solution:
def reverse(self, x: int) -> int:
if x >= 2 ** 31 - 1 or x <= -2 ** 31: return 0
sol = str(x)
if x >= 0:
sign = str()
else:
sign = sol[0]
sol = sol[1:]
sol = sol[::-1]
if int(sol) >= 2 ** 31 - 1 or int(sol) <= -2... |
# Cargamos los datos de Iris desde Scikit-learn
# Graficamos
# Importamos las librerias necesarias
from matplotlib import pyplot as plt
from sklearn.datasets import load_iris
# Un aspecto sutil, es que al establecer una métrica entre frases, puede resultar que una frase es
# repetida más de dos ocasiones, ejemplo “... |
#!/usr/bin/env python3
# coding:utf-8
class Student(object):
count = 0
books = []
def __init__(self,name,age):
self.name = name
self.age = age
pass
s = Student('Saotao', 25)
s.books.extend(["python","java"])
print('student\'s name is: %s, age is: %d' %(s.name,s.age))
print('student boo... |
class Node():
def __init__(self, value, height=None):
self.value = int(value)
self.parent = None
self.left = None
self.right = None
self.height = height
class binaryTree():
def __init__(self, height):
self.root = Node(2**height - 1, height)
self.current_... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
str = input("快点输入:")
print "你刚才输入的内容是:", str
'''
输出结果:
快点输入:[x*7 for x in range(13,18,2)]
你刚才输入的内容是: [91, 105, 119]
'''
|
# -*- coding:utf-8 -*-
#! /bin/env python3
__author__ = 'weekend27'
# variable args
def hello(greeting, *args):
if (len(args)==0):
print('%s!' % greeting)
else:
print('%s, %s!' % (greeting, ', '.join(args)))
hello('Hi') # => greeting='Hi', args=()
hello('Hi', 'Johnson') # => greeting='Hi... |
class Avion:#Tipos de aviones existentes
__numero_avion = 0#generador de id automatico del avion
def __init__(self, nombre, capacidad, precio, clase):
self.__ID = Avion.__numero_avion
self.__nombre = nombre#Nombre del modelo
self.__capacidad = int(capacidad)
sel... |
from Lab2.Node import Node
class LinkedList(object):
head = None
tail = None
size = 0
def __init__(self, node: Node = None):
if node is None:
self.head = None
self.tail = None
self.size = 0
return
if node.next is None:
self.h... |
# For all questions, use the following class definitions
class MaxHeap(object):
# Constructor
def __init__(self):
self.tree = []
# --------------------------------------------------------------------------------------------------------------
# Problem 19
# ----------------------------------... |
def get_smallest_key_at_d(root, d):
cur = root
while cur is not None:
if d == 0:
return cur.key[0]
d -= 1
cur = cur.left
return 1 |
class HashTable:
# Builds a hash table of size 'size'
def __init__(self, size):
self.table = [[] for i in range(size)]
def hash(self, k):
return k % len(self.table)
# Inserts k in the appropriate bucket if k is not already there
def insert(self, k):
loc = self.hash(k)
... |
# For all questions, use the following class definitions
import math
class BinaryTreeNode:
def __init__(self, item=0, left=None, right=None):
self.item = item
self.left = left
self.right = right
class BinarySearchTree:
def __init__(self):
self.root = None
def height(sel... |
class Section1:
# Given a non-negative int n, return the number
# of digits in n that are less than or equal
# to 5 - Use recursion - no loops.
# Example1: count(285) -> 2
# Example2: count(565891) -> 3
@staticmethod
def count(n: int) -> int:
if n <= 5:
return 1
... |
################################################################################
# Input Capture Unit
#
# Created by VIPER Team 2015 CC
# Authors: G. Baldi, D. Mazzei
################################################################################
import pwm
import icu
import streams
#create the serial port using d... |
import intervals as I
def fun(x):
return x**2-x
stanga = raw_input('Alegeti capatul din stanga al intervalului: ')
st=float(stanga)
dreapta = raw_input('Alegeti capatul din dreapta al intervalului: ')
dr=float(dreapta)
interval=I.closed(st, dr)
print interval
i=1
rezultate=[]
while i<=6:
... |
def fibonacci(n):
if n < 2: return n
return fibonacci(n-2) + fibonacci(n-1)
n = int(input())
print(fibonacci(n)) |
#!python
class MinHeap(object):
"""A MinHeap is an unordered collection with access to its minimum item,
and provides efficient methods for insertion and removal of its minimum."""
def __init__(self):
"""Initialize this min heap with an empty list of items"""
self.items = []
def __repr__(self):
"""Return ... |
class Tree23:
def __init__(self):
self.root = None
def insert(self, item):
if self.root == None:
self.root = Node23(None, item, None)
else:
new = self.root.insert(item)
if new != None:
self.root = new
def searchFor(self, item):
if self.root == None:
return False
else:
return self.root... |
from task.utils import *
from task.exceptions import WrongCityNameError
import requests
from textwrap import indent
COUNTRY_CITY_URL = "https://public.opendatasoft.com/api/records/1.0/search/?dataset=worldcitiespop&q={}&facet=country"
COUNTRY_CURRENCY_URL = 'https://restcountries.eu/rest/v2/name/{}?fullText=true'
de... |
#coding: utf-8
#codes
f=open("test.txt","r")
f2=open("test2.txt","w")
# print(f.read())
for line in f:
if "让我掉下眼泪的" in line:
line=line.replace("让我掉下眼泪的","让我们彼此掉下眼泪的")
f2.write(line)
else:
f2.write(line)
f.close()
f2.close()
|
animals = ['cat', 'dog', 'monkey']
for animal in animals:
print(animal)
# Prints "cat", "dog", "monkey", each on its own line.
animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
print('#%d: %s' % (idx + 1, animal))
# Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line
nums... |
# -*- coding: utf-8 -*-
WORDLIST_FILENAME = 'words-utf8.txt'
HEBREW_WORDS = [w.split()[0] for w in file(WORDLIST_FILENAME, 'r').readlines()]
KALPI_WORDS = ['אמת', 'זך', 'ףץ', 'ל', "נז", "ג", "יז", "י", "יץ", "רק", "מחל", "קץ", "שס", "קנ", "ף", "ני", "ודעם", "פה", "כ", "זץ", "נץ", "מרצ", "ע", "טב", "ז"]
def initial_fo... |
from itertools import combinations
from Warehouse import Warehouse, is_Subset
from typing import List
from solution1 import findCheapest_simple
# combine a list of warehouse into one single big 'warehouse'
def combineSuppliers(suppliers: List[Warehouse]) -> (dict, int):
ret = {}
# and compute their total ship... |
startRange = int(input("Enter the starting range of input"))
endRange = int(input("Enter the ending range of input"))
lists = []
for i in range(startRange,endRange+1) :
count = 0;
if i != 1:
for j in range(2,i) :
if i % j == 0 :
count = 1
break;
... |
num=int(input("Enter the number to whelter it is armstrong number or not"))
temp=num
count = 0
output=0
lists=[]
while temp > 0 :
count =count + 1
lists.append(temp%10)
temp=int(temp/10)
for i in lists:
output = int(output + pow(i,count))
#print(output)
if(num == output):
print('{} ... |
principle = int(input("Enter the total amount"))
rate = int(input("Enter the interest"))
n = int(input("Enter the total number of years"))
output = (principle * rate * n)/100
print(int(output))
|
people = {
'geetha': ' used to tell lot of lies ',
'deepak':' dont know what to say ',
'arthi':" used to make fun out of others"
}
for name,story in people.items() :
print('{} : {}'.format(name,story))
======================================
def display_facts(facts):
for fact in facts:
pr... |
class Account:
def __init__(self,owner,deposit):
self.owner=owner
self.deposit=deposit
def __str__(self):
return f'Account owner: {self.owner}\nAccount balance: ${self.deposit}'
def depositt(self,amount_added):
self.deposit = self.depos... |
# -*- encoding:utf8 -*-
# http://www.pythonchallenge.com/pc/def/equality.html
# http://www.pythonchallenge.com/pc/def/linkedlist.php
# http://wiki.pythonchallenge.com/index.php?title=Level3:Main_Page
import re
import requests
import BeautifulSoup
url = 'http://www.pythonchallenge.com/pc/def/equality.html'
html = re... |
"""Helper functions used across multiple scripts."""
__author__ = "Kris Jordan <kris@cs.unc.edu>"
from datetime import datetime
def date_prefix(suffix: str) -> str:
"""Generate a date prefixed string given a suffix.
Args:
suffix: Will follow the date and a dash.
Returns:
A str in t... |
#!/usr/bin/env python3
# hamming — generates bits with the hamming encoding
# Usage:
# py hamming.py -number N
# N — number of bits in an encoded sequence, default — random from 11 to 20
import random
import argparse
import math
def get_print_form(list: list) -> str:
for index in range(len(list)):
... |
#1) Write a Python script to merge two Python dictionaries
Colors1 = {"Pink":"Purple",
"Blue":"Violet",
"Black":"White"}
Colors2 = {"Orange":"Yellow",
"Red":"maroon",
"Brown":"Green"}
Colors1.update(Colors2)
print(Colors1)
#2) Write a Python program to remove a key f... |
#Day 2 : String Practice
#How to print a value?
print("30 days 30 hour challenge")
print('30 days 30 hour challenge')
#Assigning String to Variable:
Hours = "thirty"
print(Hours)
#Indexing using String:
Days = "Thirty days"
print(Days[3])
#How to print the particular character from certain text?
Chal... |
import time
import sys
def print_pause(message_to_print):
print(message_to_print)
sys.stdout.flush()
time.sleep(3)
def valid_input(prompt,option1, option2):
while True:
response = input(prompt).lower()
if option1 in response:
break
elif option2 in response:
... |
'''
Insertion Sort
* like a card game
* pick an element and insert it into sorted sequence
'''
def insertionSort(arr):
# traverse through 1 to len(arr)
for idx in range(1, len(arr)):
current_val = arr[idx]
# move elements of arr[0..i-1], that are
# greater than key, to one position ahe... |
'''
# Tree
* essential data structure for storing hierarchial data with a directed flow
* similar to linked lists and graphs, trees are composed of nodes which hold data.
* Nodes store references to zero or more other tree nodes
* `root`, `parent`, `child`, `sibling` node
* a node with no children: `leaf` node
* each n... |
from math import *
#these work even without math import
my_num = 9
print(str(my_num) + " my favourite no.")
print(abs(my_num*(-1)))
print(max(1,2,3,4,5)) #same for min
print(pow(9,3)) #float o/p
print(round(2.3456))
#these require math import
print(floor(3.7))
print(ceil(3.7))
print(sqr... |
name = input("Enter your name: ") #by default, user input is considered as a string
age = input("Enter your age: ")
print("Hello " + name + ", you are " + age + " years old!")
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = float(num1) + float(num2)
print("Addition is " + str(r... |
from datetime import date
def date_from_isoformat(isostring):
"""
Converts an isostring to date
:param isostring: The date-string
:return: The date created from string
"""
parts = isostring.split("-")
return date(int(parts[0]), int(parts[1]), int(parts[2]))
def is_between(check, start, end):
"""
C... |
# small_decimal=range(0,10)
# print(small_decimal)
# my_range=small_decimal[::2]
# print(my_range)
# print(my_range.index(4))
deciam=range(0,100)
my_range=deciam[3:40:3]
for i in my_range:
print(i)
print('='*50)
for i in range(3,40,3):
print(i)
print(my_range==range( 3,40,3)) |
string="1234567890"
# for i in string:
# print(i)
my_iterator=iter(string)
print(my_iterator)
for i in range(1,11):
print(next(my_iterator))
# for i in my_iterator:
# print(next(i)) |
shopping_list=['milk','pasta','eggs','spam','bread','rice']
item_to_find="spam"
found_at=None
for index in range(len(shopping_list)):
if shopping_list[index]==item_to_find:
found_at=index
break
if found_at is not None:
print(f"Item found at position {found_at}")
else:
print(f"{item_to_fin... |
shopping_list=['milk','pasta','eggs','spam','bread','rice']
item_to_find="spam"
found_at=None
if item_to_find in shopping_list:
found_at=shopping_list.index(item_to_find)
if found_at is not None:
print(f"item found at position {found_at}")
else:
print(f"{item_to_find} not found ") |
shopping_list=['milk','pasta','eggs','spam','bread','rice']
item_to_find="pasta"
found_at=None
for index in range(len(shopping_list)):
if shopping_list[index]==item_to_find:
found_at=index
print(f"Item found at position {index}") |
def uses_only(word, characters):
for letter in word:
if letter not in characters:
return False
return True
file = open("words.txt")
num = 0
for line in file:
word = line.strip()
if uses_only(word, 'a c e f h l o') == True:
print(word)
num = num + 1
print(num)
# Yes, there are about 188 words m... |
day=1
month=1
year=1900
week=1
sum=0
sum1=0
month_tab={1:31,3:31,5:31,7:31,8:31,10:31,12:31,9:30,4:30,6:30,11:30}
months=range(1,13)
del months[1]
while year<=2000:
if week>7:
week=week-7
if month==2:
if (year==2000) or (year%100!=0 and year%4==0):
if day>29:
day=day-... |
from random import random, seed, randint, randrange, choice,sample
from datetime import datetime
#1. random shnowng rand numbers between 0 < x < 1
for _ in range(5):
print(random(), end= ' ')
#2. seeding showing the generated rand numbers doe not change if the see number its the same
seed(20)
print ("first Numbe... |
a=int(input("Masukkan Angka A : "))
b=int(input("Masukkan Angka B : "))
c=int(input("Masukkan Angka C : "))
if a > b and a > c:
print(a,"Terbesar dari 3 bilangan yang diinputkan")
elif b > a and b > c:
print(b,"Terbesar dari 3 bilangan yang diinputkan")
else:
print(c,"Terbesar dari 3 bilangan yang diinput... |
def ExtractSubSquence(aList):
"""This Function takes a list of numbers and extracts the longest sub sequence \n
of numbers that are in ascending order"""
subSequence = []
counter = 0 #keeps track of the length of the sub sequences to find the longest
for i in range(len(aList)):
... |
import random
# Demo of basic input in python
# name = input("Enter your name: ")
# print("Hello " + name)
# Demo of a program that computes for an area of a circle
# radius = float(input("Enter the radius: "))
# area = 3.14 * (radius**2)
# print("The area of the Circle is: " + str(area))
# Demo of a program that com... |
import timeit
CACHE = dict()
def factorial(n: int) -> int:
if n == 0:
return 1
else:
return n * factorial(n - 1)
def run_factorial(n: int)-> int:
cached = CACHE.get(n)
if cached:
return cached
if n == 0:
return 1
else:
result = n * factorial(n - 1)
... |
from dataclasses import dataclass
@dataclass()
class Contact:
name: str
addresses: list = None
def __str__(self):
return f'{self.__dict__}'
def __iadd__(self, other):
if isinstance(other, Address):
self.addresses.append(other)
return self
def __contains__(self... |
distance_meters = int(input("Input distance in metres: "))
distance_kilometers = int(distance_meters/1_000)
distance_miles = float(distance_meters/1608)
distance_nautical_miles = float(distance_meters/1852)
print(f'Distance in meters: {distance_meters}')
print(f'Distance in kilometers: {distance_kilometers}')
print(f'... |
# def is_odd(n):
# return n % 2 == 1
# a = list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# print(a)
# def not_empty(s):
# return s and s.strip()
# a = list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
# print(a)
#### filter
# def _odd_iter():
# n = 1
# while True:
# n = n + 2
# ... |
from cs50 import get_float
change = get_float("How much change are you owed?\n")
while change < 0:
change = get_float("How much change are you owed?\n")
coins_number = 0
while change > 0.0:
coins_number += 1
if change >= 0.25:
change -= 0.25
elif change >= 0.1:
change -= 0.1
elif cha... |
import re
import random
import wikipedia
from collections import defaultdict
class MessageParser(object):
"""This is a basic class to do some very basic parsing of messages and
returning strings for specific inputs.
"""
def __init__(self):
"""Constructor:
Initialise the user dictionary... |
import math
class Coord:
def __init__(self, x, y, dir):
self.x = x
self.y = y
self.dir = dir
def __str__(self):
return "X: {0}, Y: {1}, D: {2}".format(self.x, self.y, self.dir)
def update(self, x, y, dir):
self.x = x
self.y = y
self.dir = dir
def updateXY(self, x, y):
self... |
"""Module for classes representing a PokerGame player and table of players"""
import random
import sys
from Action import Action, InvalidActionException
from Hand import Hand
from PokerException import PokerException
from Utils import assertInstance, UserSelection
####################################################... |
"""Class for ranking poker hands"""
from Cards import Rank
from PokerException import PokerInternalException
from PokerRank import PokerRank
from Ranker import RankerBase
class LowRanker(RankerBase):
"""Given a Hand, return its PokerRank for low.
Ignores straights and flushes (i.e. wheel is best low hand).""... |
#!/usr/bin/python3
# - * - encode: utf-8 - * -
import sys, re
input_file = sys.argv[1]
word_to_search = sys.argv[2]
with open(input_file, 'r') as f:
lines = f.readlines()
f.close()
for line in lines:
array = re.findall(word_to_search, line)
if word_to_search in array:
words = line.split()
... |
# Question Link: https://www.hackerrank.com/challenges/py-set-add/problem
n=int(input())
s= set('')
for i in range (0,n):
st=input();
s.add(st);
count =0
for _ in s:
count+=1
print(count)
|
"""
File to contain LWR Class
"""
import numpy as np
# import data and assign each control and GT data point a unique ID
def load_data(file_name, header, footer, cols):
"""
Function to import data from a file
Input:
file_name = Full file names
header = number of header rows s... |
import pyttsx3 # for text to speech
import speech_recognition # for recognition of speech
import wikipedia # for wikipedia summary
import webbrowser # for working with web browsers
from datetime import * # for time related stuffs
from time import sleep # for sleep function
import sys # for own python envir... |
ab = { "lufubo":23,
"chengming":34,
"yangg":45}
print("lufubo's age %s" % ab["lufubo"])
ab["lufubo"] = 99
print("lufubo's age %s" % ab["lufubo"])
print("ab len %d" % len(ab))
#del ab["lufubo"]
print("ab len %d" % len(ab))
for name, age in ab.items():
print("name %s age:%d" % (name, age))
print(... |
name = "Lucian" #Har skapat variablen name och tilldelat det värdet Lucian
age = 17 #skapat variablen age och tilldelat det värdet 29
print(f"Hello {name} you are {age} year old")
side = float(input("Ange kvadratens sida"))
area = side**2
omkrets = 4*side
print(f"kvadratens area är {area} a.e. och kvadraten omkr... |
def palindromes_of_length_n(n):
middle = list(map(str, range(10))) if n%2==1 else ['']
outer = ['']
if n != 1:
outer = list(map(str, range(10**(n//2-1), 10**(n//2))))
result = []
for x in outer:
for y in middle:
result.append(x + y + x[::-1])
return result
def palindromes_of_length_under_n(n=7):
result ... |
a=int(input("Number of students"))
marks_in_bme=[]
name=[]
for i in range (a):
h=input("Enter name of students")
name.append(h)
i=int(input("Enter marks"))
marks_in_bme.append(i)
print(name)
print(marks_in_bme)
result=zip(name,marks_in_bme)
result_set=set(result)
print(result_set)
|
#! /usr/bin/env python3
import numpy as np
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.filedialog as tkfdlg
class PolygonDrawer:
"""Shows a Tk window on which a rectangle can be drawn."""
def __init__(self):
"""Builds and shows the window."""
# Set up root window
sel... |
class SessionView:
"""SessionView base class
This class defines an API for session views.
Session views should be created by subclassing this class
and implementing the necessary methods.
"""
@classmethod
def create(cls, *args, **kwargs):
"""Create a new SessionView instance and re... |
import sys
import re
def weird_list(string, n):
return [word for word in re.split(r"[\W|_]+", string) if len(word) > n]
if __name__ == "__main__":
if len(sys.argv) != 3:
print("ERROR")
else:
try:
print(weird_list(str(sys.argv[1]), int(sys.argv[2])))
except ValueError:... |
"""N-queens puzzle
The N-queens problem is about placing N chess queens on an N*N chessboard so that
no two queens threaten each other. A solution requires that no two queens share the
same row, column diagonal or anti-diagonal.The problem's target is try to find how
many solutions exist.
"""
import time
from z3 im... |
import random
class NotecardPseudoSensor:
def __init__(self, card):
self.card = card
# Read the temperature from the Notecard’s temperature
# sensor. The Notecard captures a new temperature sample every
# five minutes.
def temp(self):
temp_req = {"req": "card.temp"}
temp_rsp = self.card.Transact... |
"""Create a Car class that has the following characteristics:
1. It has a gas_level attribute. 2. It has a constructor (__init__ method) that takes a float representing the
initial gas level and sets the gas level of the car to this value. 3. It has an add_gas method that takes a single
float value and adds this amoun... |
import numpy as np
class Solver():
def __init__(self, dim):
self.dim = dim
self.queen_pos = [] #saves x and y coordinate of each queen
self.solution_map = np.zeros((dim, dim))
#I found 5 different patterns to place queens depending of dimension
if dim%2 != ... |
import numpy as np
import cv2
#from matplotlib import pyplot as plt
import gdal
import osr
from gdalconst import *
import time
import sys
import os
def pixel2coord(ds, x, y):
"""Returns global coordinates to pixel center using base-0 raster index"""
'''
GeoTransform() returns a tuple where (X, Y) are corner coordi... |
# Given two binary trees, write a function to check if they are equal or not.
# Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:r... |
# https://leetcode.com/problems/encode-and-decode-tinyurl/description/
class Codec:
def __init__(self):
self.encode_map = dict()
self.decode_map = dict()
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
... |
# https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: Li... |
# https://leetcode.com/problems/island-perimeter/
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid:
return 0
self.number_of_rows = len(grid)
self.number_of_columns = len(... |
# https://leetcode.com/problems/battleships-in-a-board/description/
class Solution(object):
def countBattleships(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
self.visited = set()
count = 0
for r in range(len(board)):
for... |
# https://leetcode.com/problems/pascals-triangle-ii/discuss/
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
if rowIndex == 0: return [1]
if rowIndex == 1: return [1,1]
res = [1]
prevRow = self.getRow(... |
# https://leetcode.com/problems/print-binary-tree/description/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def printTree(self, root):
"""
:type root... |
# https://leetcode.com/problems/longest-univalue-path/description/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def longestUnivaluePath(self, root):
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.