text stringlengths 37 1.41M |
|---|
#-*-coding:utf-8-*-
class ListNode(object):
def __init__(self,x):
self.val=x
self.next=None
class Solution(object):
def removeNthFromEnd(self,head,n):
res=ListNode(0)
res.next=head
tmp=res
for i in range(0,n):
head= head.next
while head!=None:
... |
#tictoctoe game implemantation
board=["-","-","-",
"-","-","-",
"-","-","-"]
def display_board():
print(board[0] + " | " + board[1] + " | " + board[2])
print(board[3] + " | " + board[4] + " | " + board[5])
print(board[6] + " | " + board[7] + " | " + board[8])
game_still_going=True
... |
from datetime import datetime
hoje = datetime.today().year
ficha = dict()
ficha['nome'] = str(input('Nome: ')).title().strip()
nasc = int(input('Ano de nascimento: '))
ficha['idade'] = hoje - nasc
ficha['ctps'] = int(input('Carteira de Trabalho (0 se não tem): '))
if ficha['ctps'] != 0:
ficha['contratação'] = int(i... |
inicio = int(input('Digite o primeiro termo da sua Progressão Aritmética: '))
razao = int(input('Digite a razão da PA: '))
pa = inicio
termos = 0
cont = 1
mais = 10
while mais != 0:
termos = termos + mais
while cont <= termos:
print('{}'.format(pa), end=' => ')
pa = pa + razao
cont += 1
... |
coleção = [[], []]
for c in range(1, 8):
num = int(input(f'Digite o {c}º valor: '))
if num % 2 == 0:
coleção[0].append(num)
else:
coleção[1].append(num)
print(f'Os valores pares digitados foram: {sorted(coleção[0])}')
print(f'Os valores impares digitados foram: {sorted(coleção[1])}') |
expressao = str(input('Digite um expressão matemática: '))
parentesis = []
for v in expressao:
if v == '(' or v == ')':
parentesis.append(v)
metade1 = []
metade2 = []
if len(parentesis) % 2 == 0:
for c in range(0, int(len(parentesis) / 2)):
metade1.append(parentesis[c])
for c in range(int(le... |
lista = []
for c in range(0, 5):
new = int(input('Digite um valor: '))
if c == 0:
lista.append(new) or new > lista[-1]:
print('Adicionado a última posição.')
else:
pos = 0
while pos < len(lista):
if new <= lista[pos]:
lista.insert(pos, new)
... |
n = int(input('Digite um número para ver sua tabuada: '))
print('-'*12)
for c in range(0,10+1):
print('{} x {:2} = {}'.format(n,c,n*c))
print('-'*12) |
inicio = int(input('Digite o primeiro termo da sua PA? '))
razão = int(input('Digite um número: '))
pa = inicio
cont = 1
termos = 0
mais = 10
while mais != 0:
termos += mais
while cont <= termos:
print('{}'.format(pa), end=' => ')
pa = pa + razão
cont += 1
mais = int(input('Deseja mo... |
d = int(input('Qual é a ditância da sua viagem em Km? '))
preço = d*0.5 if d<=200 else d*0.45
print('O preço da sua viagem é de R${:.2f}'.format(preço))
'''if d <=200:
preço = d*0.5
print('Sua passagem de {}Km custa {} reais. Boa viagem!'.format(d, preço))
else:
preço = d*0.45
print('Sua passagem de {... |
ficha = dict()
ficha['jogador'] = str(input('Nome do jogador: ')).title().strip()
partidas = int(input(f'Quantas partidas {ficha["jogador"]} jogou: '))
gols = []
for c in range(1, partidas + 1):
gols.append(int(input(f'Quantos gols fez na {c}ª partida? ')))
ficha['gols'] = gols[:]
ficha['total'] = sum(gols)
print('... |
sair = False
while sair == False:
a = float(input('Entre com a primeira nota: '))
b = float(input('Entre com a segunda nota: '))
media = (a+b)/2
print('Sua média foi de {:.1f}'.format(media))
if media<5:
print('\033[0;31mREPROVADO\033[m')
elif 5<=media<7:
print('\033[32mRECUPERAÇ... |
from datetime import date
n = int(input('Que ano você quer analisar? Coloque 0 para analisar o ano atual: '))
if n == 0:
n = date.today().year
if n % 4 == 0 and n % 100 !=0 or n % 400 ==0:
print('O ano {} é bissexto.'.format(n))
else:
print('O ano {} não é bissexto.'.format(n))
|
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
"""CNN neural network to predict MNIST classes.
The network architecture are as follows:
64 Conv 5x5 stride=1 ReLU
Max Pooling 2x2 stride=2
64 Conv 5x5 stride=1 ReLU
Max Pooling 2x2 stride=2
FC 512 units ReLU
Softmax 10 units
Reache... |
def fizzBuzz(num):
if num <= 0:
return;
if num % 3 == 0 and num % 5 == 0:
print("FizzBuzz")
elif num % 3 == 0:
print("Fizz")
elif num % 5 == 0:
print("Buzz")
else:
print(num)
num -= 1
fizzBuzz(num)
fizzBuzz(35)
|
def bubbleSort(arr):
for i in range(len(arr) - 1):
for j in range(len(arr) - 1):
print(arr, arr[j], arr[j + 1])
if arr[j] > arr[j + 1]:
temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
return arr
print(bubbleSort([12, 1, 7... |
import secrets
from string import digits, ascii_letters
#genereting normal functions
print(secrets.choice('Choos one from this string'.split()))
print(secrets.randbelow(1000))
print(secrets.randbits(16))
#genereting tokens
print(secrets.token_hex(32))
print(secrets.token_bytes(16))
print(secrets.token_urlsafe(32))
#... |
import unittest
from modules import calculator
class TestCalculator(unittest.TestCase):
def test_add_2_numbers(self):
self.assertEqual("The answer to 8 plus 4 is 12", add_2_numbers(8, 4)) |
alphabet = "abcdefghijklmnopqrstuvwxyz"
def alphabet_position(Char):
for i in range(len(alphabet)):
if Char == alphabet[i] or Char == alphabet[i].upper():
return i
def rotate_character(Char, Rot):
if Char.isalpha():
encrypted = ""
NewCharPos = alphabet_position(Char) + Ro... |
# test cases
matrix1 = [
[1,2,3],
[4,5,6],
[7,8,9]
]
matrix2 = [
[1, 2, 3, 4, 5, 6],
[7, 8, 9,10,11,12],
[13,14,15,16,17,18],
[19,20,21,22,23,24],
[25,26,27,28,29,30],
[31,32,33,34,35,36]
]
# algorithm
def rotate_matrix(matrix, n):
rotated = []
i = len(matrix) * n
x =... |
def freq(n, text):
text = ''.join(i.lower() for i in text if i.isdigit() or i.isalpha()) #String preprocessing
no_dupls = set() #set to remove combination dupls
res_dct = dict() #dict with results
if len(text)==n: #specific case (N = t... |
# solve it_1
# import math
# x = 4
# y = 3
# z = 2
# w = (( x + y * z ) / ( x*y ))**z
# print (w)
#### OR
# v = ( x + y * z ) / ( x*y )
# result = math.pow(v,z)
# print(result)
# solve it_2
# x = input("Silakan masukkan angka berapapun: ") #meminta input dari user n disimpan di variable,
# #input dr user akan s... |
numberOfGames = int(input())
results = [0] * numberOfGames
gameCounter = 0
while gameCounter != numberOfGames:
numberOfRounds = int(input())
player1 = 0
player2 = 0
roundCounter = 0
while roundCounter != numberOfRounds:
result = input()
if ((result == "P R") or (result ... |
#program main
# use StringClass
# implicit none
#
# type(String_) :: string
word = "Hello "
print(word)
word = word + "world!"
print(word)
word = word + "world!" + word + "world!"
print(word)
x = word.lower()
print(x)
x = word.upper()
print(x) |
'''
Implemente as classes Pessoa e Aluno.
A classe Pessoa deve armazenar o nome da pessoa.
A classe Aluno deve herdar da classe Pessoa e armazena o ra e uma lista
com as notas de 5 atividades realizadas durante o semestre.
Os atributos das classes devem ser inicializados nos construtores.
A lista de notas do alun... |
# Python program to code and decode with the help of fractions of lexicon of positive integers k<=n subdivided
# lexicographically by their prime factorization.
# Prime lexicon(lexicon): Whole set of positive integers k<=n subdivided lexicographically by their prime
# factorization, which contains set of multiples of ... |
"""
Used to allow for function and their arguments to be stored.
"""
__all__ = ["Task"]
class Task:
"""
Class used to store function that will be executed
args:
func : the function that will be executes
callback : function that will run when processing has started and finished, callback("... |
import pandas as pd
from sklearn.impute import KNNImputer
def knn(data=None, columns=None, k=3, inplace=False):
"""Performs k-nearest neighbors imputation on the data. The k nearest
neighbors or each subject with missing data are chosen and the average
of their values is used to impute the missing value. ... |
import unittest
from imputena import knn
from test.example_data import *
class TestKNN(unittest.TestCase):
# Positive tests ----------------------------------------------------------
def test_KNN_returning(self):
"""
Positive test
data: Correct data frame (example_df)
The... |
import pandas as pd
from sklearn import linear_model
from sklearn.exceptions import ConvergenceWarning
import logging
import warnings
def logistic_regression(
data=None, dependent=None, predictors=None, regressions='available',
inplace=False):
"""Performs logistic regression imputation on the data... |
import pandas as pd
def interpolation(
data=None, method='linear', direction='both', columns=None,
inplace=False):
"""Performs linear, quadratic, or cubic interpolation on a series or a
data frame. If the data is passed as a dataframe, the operation can be
applied to all columns, by leavin... |
from stack_092 import Stack
def matcher(line):
s = Stack()
for char in line:
if char == "(" or char == "{" or char == "[":
s.push(char)
elif char == ")" or char == "}" or char == "]":
try:
if not s.is_empty:
return False
elif char == ")" and s.t... |
#!/usr/bin/env python
import sys
def pas(s):
tot = 0
a = []
for c in s:
if c.isdigit():
a.append("dig")
if c.islower():
a.append("low")
if c.isupper():
a.append("up")
if c != " ":
if not c.isalnum():
a.append("oth")
a.pop(len(a) - 1... |
#!/usr/bin/env python
import sys
from math import pi
def pie(r):
m = str(r)
n = "{:." + m + "f}"
return(n.format(pi))
def main():
print(pie(sys.argv[1]))
if __name__ == '__main__':
main()
|
from six.moves import input
import random
def main():
word_list, answer_list, word_dict, wrong_list = [], [], {}, []
with open('word.db') as f:
for line in f.readlines():
line_list = line.strip().split()
if len(line_list) < 2:
pass
else:
word = line_list[0]
answer = ' '.join(line_list[1:])
... |
import csv
import numpy as numpy
from messytables import CSVTableSet, type_guess, types_processor, headers_guess, headers_processor, offset_processor
tinyint_min = 0
tinyint_max = 255
smallint_min = -32768
smallint_max = 32767
int_min = -2147483648
int_max = 2147483647
bigint_min = -9223372036854775808
bigi... |
def check_name(name):
if str(name).isalpha():
return True
else:
return False
def check_mail(email):
if '@' in email:
return True
else:
return False
if __name__ == '__main__':
name = input('Please enter your name: ')
if check_name(name):
email = input(... |
import math
e = 2.71828
def fungsi(x):
x = float((e**x) - (4*x))
return x
def fungsiturunan(x):
x = float((e**x) - (4))
return x
x = float(input('Masukkan nilai awal = '))
error = float(input('Masukkan nilai error = '))
perulangan = int(input('Masukkan maksimal pengulangan = '))
itera... |
For this challenge, you need to take a matrix as an input from the stdin , transpose it and print the resultant matrix to the stdout.
Input Format
A matrix is to be taken as input from stdin. On first line you need to tell that how many rows and columns your matrix need to have and these values should be separated by... |
For this challenge, you need to take number of elements as input on one line and array elements as an input on another line and find the second largest array element and print that element to the stdout.
Input Format
In this challenge, you will take number of elements as input on one line and array elements which are... |
import multiprocessing
import ctypes
class SharedMemoryString(object):
'''
Shared Memory Value that lets you work with a mutable string
>>> shared_string = SharedMemoryString(
max_size=1024,
default='hello',
)
>>> with shared_string.get_lock():
... shared_string.set('New V... |
# Demonstrate the usage of namdtuple objects
import collections
def main():
# TODO: create a Point namedtuple
Point = collections.namedtuple("Point", "a b")
point1 = Point(3, 4)
point2 = Point("alon", "bar")
print(point1, point2)
print(point2.b)
# TODO: use _replace to create a new insta... |
class Solution:
def isValid(self, s: str) -> bool:
if s == "":
return True
stack = []
pairs = {"(": ")", "{": "}", "[": "]"}
for char in s:
if char in pairs:
stack.append(char)
else:
if not... |
#!python
from trie import Trie, TrieNode
import unittest
class TrieTest(unittest.TestCase):
def test_init(self):
tree = Trie()
assert tree.size == 0
assert tree.is_empty() is True
tree.insert('hello')
tree.search('hello') == 'hello'
tree.search('state') == None
... |
name = input("Enter your name: ")
number = input("Enter how many times you want to see it: ")
print (str(name) * int(number))
|
## TODO: define the convolutional neural network architecture
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
device_ids = [0, 1]
class Net(nn.Module):
... |
'''
this program is used to check if postal codes are valid and sees where
the postal codes come from
'''
#importing functions
from postal import formatCode
from postal import getProvince
from postal import isValid
'''
formatted = formatCode("m 5P1j 4")
print(formatted)
province = getProvince("M5P 1J4")
print(provin... |
'''This program is used to create a pyramid made out of the desired symbol and height'''
#this function is used to create the list of triangles and then print it
def createTriangularNumber(termNumber, symbol):
#Establishing the variables required.
triangleNumber = 1
triangleList = []
#loops until the... |
def reverse(word):
word = word.lower()
reversedWord = ""
index = len(word) - 1
while index != -1:
if word[index] not in ["a","e","i","o","u"]:
reversedWord += word[index]
index -= 1
print(reversedWord)
reverse("Ihunderbolt") |
'''Reads a bunch of data from a text file. Allows the user to input a upper and lower bound
and takes all the numbers in the text file that meets though criteria. After retreiving
those numbers, it will return the average of all the numbers in the specified range
'''
#function that allows the user to input their desir... |
'''A program to allow the user to input a wavelength in nanometers
and then have a program output the corresponding colour in the
visible spectrum
'''
#import the library to change the colour of the text
from colorama import init, Fore, Back
init()
#function that accepts a wavelength number and then outputs the corres... |
'''
This program is used to allow a user to create a file and write stuff in the file
'''
#allows the user to input the name that they want to name the new file
fileName = input("Enter the file name: ")
#allows the user to input a line of text to put into the file
textInFile = input("Enter a one line text: ")
#add th... |
'''
Allows the user to input variables to solve a linear quadratic system
'''
#Function to more easily check the value of a variable and will output an error if the variable is invalid
def inputChecker(letter):
value = input("Enter the value of parameter " + letter + ": ")
if value == "":
print("The va... |
"""
Course: CSE 251
Lesson Week: 02 - Team Activity
File: team.py
Author: Brother Comeau
Purpose: Playing Card API calls
"""
from datetime import datetime, timedelta
import threading
import requests
import json
# # Include cse 251 common Python files
# import os, sys
# sys.path.append('../../code')
# from cse251 imp... |
"""
Course: CSE 251
Lesson Week: 06
File: assignment.py
Author: <Your name here>
Purpose: Processing Plant
Instructions:
- Implement the classes to allow gifts to be created.
"""
import random
import multiprocessing as mp
import os.path
import time
# Include cse 251 common Python files - Don't change
import os, sys
s... |
"""
Course: CSE 251
Lesson Week: 05
File: assignment.py
Author: <Your name>
Purpose: Assignment 05 - Factories and Dealers
Instructions:
- Read the comments in the following code.
- Implement your code where the TODO comments are found.
- No global variables, all data must be passed to the objects.
- Only the incl... |
def Color(red, green, blue, white=0):
"""Convert the provided red, green, blue color to a 24-bit color value.
Each color component should be a value 0-255 where 0 is the lowest intensity
and 255 is the highest intensity.
"""
return (white << 24) | (red << 16) | (green << 8) | blue
class _LED_Data... |
# Calculating pi to the nth decimal using the Madhava-Leibniz Series
from math import sqrt
print "This program can approximate pi to up to 10 decimal places."
decimal_places = int(raw_input("Enter the number of decimal places for pi: "))
if decimal_places > 10:
raise RuntimeError("This program approximates pi to ... |
from collections import OrderedDict
class LRU_Cache:
def __init__(self, capacity = 5):
assert capacity >= 1, "Capacity should be at least 1."
self.dict = OrderedDict()
self.capacity = capacity
self.size = 0
def get(self, key):
if self.dict.get(key):
self.dic... |
class Node:
def __init__(self, data = None):
self.data = data
self.left = None
self.right = None
self.parent = None
class BinaryTree:
def __init__(self):
self.root = None
def insert(self,item):
if self.root == None:
self.root = Node(item)
else:
self._insert(item, self.root)
def _insert(self, ... |
class SelectionSort:
def ascending(self, array):
sortedArray = []
while array != []:
lowest = array.pop(self.getLowest(array))
sortedArray.append(lowest)
print(sortedArray)
def getLowest(self, array):
lowest = array[0]
for i in array:
... |
def reverseWords(string):
array = string.split()
reverse = " ".join(array[::-1])
return(reverse)
string = "A surprise to be sure but a welcome one"
print(reverseWords(string)) |
#https://www.kaggle.com/c/amazon-employee-access-challenge/forums/t/4797/starter-code-in-python-with-scikit-learn-auc-885
""" Amazon Access Challenge Starter Code
These files provide some starter code using
the scikit-learn library. It provides some examples on how
to design a simple algorithm, including pre-process... |
def yes_or_no(question):
'Asks a question and returns True or False according to the answer.'
while True:
answer = input(question)
if answer == 'yes':
return True
elif answer == 'no':
return False
else:
print('I dont understand, answer yes or no.')
print(yes_or_no('Do you want to continue? '))
if ye... |
birth_number = input('Zadej svoje rodné číslo, prosím. ')
#fce analytující formát rč
def format(birth_number):
intak = int(birth_number[:6])
intak2 = int(birth_number[-4:])
if len(str(intak)) == 6 and birth_number[6] == '/' and len(str(intak2)) == 4:
return True
else:
return False
print(format(birth_number))
... |
from math import ceil, sqrt
from itertools import zip_longest
def cipher_text(plain_text):
plain_text = _cleanse(plain_text)
square_size = int(ceil(sqrt(len(plain_text))))
square = _chunks_of(plain_text, square_size)
return ' '.join([''.join(column)
for column in zip_longest(*squa... |
def find(search_list, value):
low = 0
high = len(search_list) - 1
while low <= high:
middle = (low + high) // 2
if search_list[middle] > value:
high = middle - 1
elif search_list[middle] < value:
low = middle + 1
else:
return middle
rai... |
# -*- coding: utf-8 -*-
from collections import Counter
from threading import Lock, Thread
from time import sleep
from queue import Queue
TOTAL_WORKERS = 3 # Maximum number of threads chosen arbitrarily
class LetterCounter:
def __init__(self):
self.lock = Lock()
self.value = Counter()
def ... |
NUMERAL_MAPPINGS = (
(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 roman(number):
result = ''
for arabic_num, roman_num in NUMERAL_MAPPINGS:
while number >= arabic_... |
def sum_of_multiples(limit, multiples):
return sum(value for value in range(limit)
if any(value % multiple == 0
for multiple in multiples
if multiple > 0))
|
def steps(number):
if number <= 0:
raise ValueError('Only positive integers are allowed')
step_count = 0
while number > 1:
if is_odd(number):
number = number * 3 + 1
else:
number = number / 2
step_count += 1
return step_count
def is_odd(number)... |
class Node:
def __init__(self, value, succeeding=None, previous=None):
self.value = value
self.succeeding = succeeding
self.prev = previous
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def __len__(self):
re... |
"""Functions for creating, transforming, and adding prefixes to strings."""
def add_prefix_un(word):
"""Take the given word and add the 'un' prefix.
:param word: str - containing the root word.
:return: str - of root word prepended with 'un'.
"""
pass
def make_word_groups(vocab_words):
"""... |
"""Functions for implementing the rules of the classic arcade game Pac-Man."""
def eat_ghost(power_pellet_active, touching_ghost):
"""Verify that Pac-Man can eat a ghost if he is empowered by a power pellet.
:param power_pellet_active: bool - does the player have an active power pellet?
:param touching_g... |
class Record:
def __init__(self, record_id, parent_id):
self.record_id = record_id
self.parent_id = parent_id
def equal_id(self):
return self.record_id == self.parent_id
class Node:
def __init__(self, node_id):
self.node_id = node_id
self.children = []
def valida... |
from collections import defaultdict
class School:
def __init__(self):
self.db = {}
self.add = []
def added(self):
result = self.add[:]
self.add = []
return result
def add_student(self, name, grade):
if not self.db.get(name, 0):
self.db[name] =... |
def convert(number):
"""
Converts a number to a string according to the raindrop sounds.
"""
result = ''
if number % 3 == 0:
result += 'Pling'
if number % 5 == 0:
result += 'Plang'
if number % 7 == 0:
result += 'Plong'
if not result:
result = str(number)... |
"""Functions to keep track and alter inventory."""
def create_inventory(items):
"""Create a dict that tracks the amount (count) of each element on the `items` list.
:param items: list - list of items to create an inventory from.
:return: dict - the inventory dictionary.
"""
inventory = {}
ad... |
while True:
h, w = map(int, raw_input().split(' '))
if h == w and h == 0:
break
for a in range(h):
print '#' + '.#'[a == 0 or a == h - 1] * (w - 2) + '#'
print
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 1 09:53:48 2020
@author: ictd
"""
class Book():
def __init__(self,title,author,pages):
self.title=title
self.author=author
self.pages=pages
def __str__(self):
return "Title: {}\nAuthor: {... |
# Default imports
import pandas as pd
data = pd.read_csv('data/house_prices_multivariate.csv')
from sklearn.feature_selection import SelectPercentile
from sklearn.feature_selection import f_regression
# Write your solution here:
def percentile_k_features(df, k=20):
X = df.drop(labels=['SalePrice'], axis=1)
... |
'''
This file contains functions to collect and save 3D scan data as well as visualize it on a heatmap.
'''
import serial
import matplotlib.pyplot as plt
import numpy as np
import time
import pandas as pd
import seaborn as sns
# data collection params
pan_i = 40
pan_f = 130
pan_interval = 5
tilt_i = ... |
#list,set comprehension
my_list=[char for char in "Hello World"]
my_list2=[num for num in range(0,100)]
my_list3=[num**2 for num in range(1,11)]
my_list4=[num**2 for num in range(1,11) if num%2==0] #list=[param for param in iterable condition]
print(my_list)
print(my_list2)
print(my_list3)
print(my_list4)
... |
#!/usr/bin/env python3
#
# output.py
# Author: Patrick Bannister
# Output and formatting for results of L7R dice Monte Carlo
# simulations.
#
class TextOutput:
def __init__(self, stream, step=5, bins=15, delimiter='\t', show_mutator_value=True):
self.stream = stream
self.step = step
self.bins = bins
... |
from math import cos, radians, sin
class Point:
x = 0
y = 0
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __iter__(self):
yield self.x
yield self.y
def __getitem__(self, in... |
"""This module implements the UART_Port class which talks to bioloid
devices using a UART on the pyboard.
"""
import stm
from pyb import UART
class UART_GPIO_Port:
"""Implements a port which can send or receive commands with a bioloid
device using the pyboard UART class. This class assumes that there is
... |
# Problem Set 4B
# Name: <your name here>
# Collaborators:
# Time Spent: x:xx
import string
import copy
### HELPER CODE ###
def load_words(file_name):
'''
file_name (string): the name of the file containing
the list of words to load
Returns: a list of valid words. Words are strings of lowerca... |
#Classes to contruct and manipulate Graphs
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
# function to add an edge to graph
def addEdge(self,u,v):
self.graph[u].append(v)
class Vertex:
def __init__(self):
self.color = 'white'
self.d... |
a=int(input("Enter a value"))
i=0
while(i<a):
print("Hello")
i=i+1
|
""" When the values in a dictionary are collections (lists, dicts, etc.) then in
this case, the value (an empty list or dict) must be initialized the first time
a given key is used. While this is relatively easy to do manually,
the defaultdict type automates and simplifies these kinds of operations.
A... |
# Define a function
def say_hello():
# block belonging to the function.
print('Hello World')
# End of function
say_hello() # call the function
say_hello() # call the function again
# OUTPUT
# python functions_basics.py
# Hello World
# Hello World
|
#!/usr/bin/env python3
proto = ["ssh", "http", "https"]
protoa = ["ssh", "http", "https"]
print(proto)
print(proto[1])
proto.extend('dns') #this line will add d, n and s
protoa.extend('dns') #this line will add d, n and s
print(proto)
proto2 = [22, 80, 443, 53 ] #a list of common ports
proto.extend(proto2) #pass proto ... |
class Parent:
def __new__(cls, val):
return super(Parent, cls).__new__(cls)
def __init__(self, val):
self.val = val + 1
class Child(Parent):
def __new__(cls, val):
return super(Child, cls).__new__(cls, val)
def __init__(self, val):
self.val += 1
c = Child(1)
print(c)
... |
import urllib2, urllib, json
baseurl = "https://query.yahooapis.com/v1/public/yql?"
place=raw_input ("Enter the location\n")
x=str(place)
k=0
print "your choice of location for weather forecasting is "+x
yql_query = '''select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=" '''... |
# Flood fill algorithm
# to create an example with
def makeGrid(width, height):
d = {}
for row in range(height):
for col in range(width):
d[(row, col)] = '.'
return d
rowSize, colSize = 5, 5
grid = makeGrid(rowSize, colSize)
# directions N, NE, E, SE, S, SW, W, NW
dirRow = [-1, -1, ... |
# Dynamic programming coin change problem
def coin_change(coins, n):
"""
Returns the minimum amount of coins to get the sum of n.
Recursive solution.
coins is a tuple or list
n is the sum to get
"""
values = {} # cached results
def solve(x):
if x < 0:
return float... |
# Goldbach's conjecture
from d18_sieve_of_eratosthenes import eratosthenes
from d03_binary_search import binary_search
def prime_sum(n, primes):
"""Return two primes that add up to n."""
if n <= 2 or n % 2 != 0:
return
i = 0
while primes[i] <= n / 2:
difference = n - primes[i]
... |
# You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
#
# You may assume the two numbers do not contain any leading zero, except the number 0 itself.
#
... |
from typing import Any
class ClassUtilities:
"""Classes utilities."""
@staticmethod
def merge_dataclasses(*args) -> Any:
"""Merge two or more dataclasses.
Adapted solution from:
https://stackoverflow.com/questions/9667818/python-how-to-merge-two-class
Args:
a... |
class car(object):
"""
This class creates instance of cars
"""
def __init__(self,c,m):
self.company = c
self.mileage = m
def salutation(self):
print(f"The {self.company} car mileage is about {self.mileage} kmpl")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.