text
stringlengths
37
1.41M
'''O programa abaixo organiza os numeros da tabela ROL de forma crescente''' numero = int(input('Digite um número e [0] para encerrar:')) lista=[numero] while numero != 0: numero = int(input('Digite um número e [0] para encerrar:')) lista.append(numero) print('\033[31m ESSA MERDA ORGANIZADA FICA ASSIM:\033[0;...
# from random import randint import random as rand def random_verb(): random_num = rand.randint(0, 1) print random_num if random_num == 0: print "Lama" return "run" else: print "Lama" return "kayak" def random_noun(): random_num = rand.randint(0,1) print random_...
# String Manipulation # Write Python code that prints out the number of hours in 7 weeks. week =7 days = 7 hr_in_day=24 hr_in_7_week = week*days*hr_in_day print hr_in_7_week # s='' str1 = ('a'+ s ) [1:] str3 = s+ '' str4 = s[0:] print str1 print str3 print str4 s = 'udacity' t = 'bodacious' print s[0:2] + t[3:] sen...
#dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} # print "dict['Name']: ", dict['Name'] # print "dict['Age']: ", dict['Age'] # fill_in_quiz = { "list_easy" :['''__1__ twinkle __2__ star''',["Twinkle", "little"]], "list_mod" :['''Five little __1__ jumping on the __2__''',["monkeys","bed"]], "list_diff" :['''Freedo...
#Write a program that prints #out the numbers 1 to 100 (inclusive). # If the number is divisible by 3, print #Crackle instead of the number. #If it's divisible by 5, print Pop. # If it's divisible by both 3 and 5, print CracklePop. # You can use any language. for x in range(101): if x%3==0 and x%5==0: pri...
#OPERACION DE FORMATO #manipulador de texto nro 16 cad="TE EXTRAÑADO MUCHO" print(cad.rjust(20)) #va correr 20 espacios a la derecha #manipulador de texto nro 17 cad="TE EXTRAÑADO MUCHO" print(cad.center(30)) #me a centrar la cadena #manipulador de texto nro 18 numero="8" print(numero.zfill(4)) #me imprimira cer...
from abc import ABC, abstractmethod class Zoo: def __init__(self, name): self.name = name self._animals = [] def add_animal(self, animal): if not self.is_in_zoo(animal): self._animals.append(animal) def is_in_zoo(self, animal): if len(self._...
a = 13 b = 14 if(a % 2 == 0) and (b % 2 == 0): print('두 수 모두 짝수입니다.') if(a % 2 == 0) or (b % 2 == 0): print('두 수 중 하나 이상이 짝수입니다.')
def false_position(func, a , b): # modified from: https://www.geeksforgeeks.org/program-for-method-of-false-position/ if func(a) * func(b) >= 0: print("You have not assumed right a and b") return -1 maxit = 200 c = a iters = 0 while iters < maxit: iters+=1 ...
#主要是利用了array is sorted 的这个property class Solution(object): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ if len(numbers)==0: return [] start=0 end=len(numbers)-1 whi...
class Solution(object): def helper(self,array,start,end): while start<end: if array[start]!=array[end]: return False start+=1 end-=1 return True def validPalindrome(self, s): """ :type s: str :rtype: bool """ ...
class Solution(object): def DFS(self,nestedList,depth): cursum=0 for ele in nestedList: #if it's a single int if ele.isInteger(): cursum+=depth*ele.getInteger() else: cursum+=self.DFS(ele.getList(),depth+1) return cursum ...
''' A script circle.py that describe a Circle Class ''' import math '''Class''' class Circle(object): ''' Constructor ''' def __init__(self, radius): self.__radius = radius def set_center(self, center): self.__center = center def set_color(self, color): self.__color = color def...
######################################################################## # @author Mike Ames # @author Phil Garza ######################################################################## import random from observer import Observer from observable import Observable from mob_factory import Mob, MonsterTypes ############...
comparisonCount = 0 with open("QuickSort.txt","r") as f: arr = [int(integers.rstrip()) for integers in f.readlines()] def medianOfThree(start,end): length = end - start + 1 middleIndex = int(length/2) - 1 if length % 2 == 0 else int(length/2) middleIndex = start + middleIndex # move middleIndex to c...
#!/usr/bin/python # encoding:utf-8 import urllib, json, urllib2, requests import time import datetime as dt #####define customer class first ####define the customer class class Customer: '''Fields: userID(Str),password(Str),gold(float),deposit(float), upper(float),lower(float),trade(float),build_trade(...
Question:Arrange String characters such that lowercase letters should come first Given input String of combination of the lower and upper case arrange characters in such a way that all lowercase letters should come first. s=input("enter the string") s1="" lower = [] upper = [] for i in s: if i.islower(): ...
""" @author Disha Gupta """ # Import all of the necessary modules. import matplotlib.pyplot as plt import pylab import csv # Define a function to graph the number of retweets each tweet got. def rts(): # Store the file. tweets = "tweets_edited.csv" try: # Try to open the file. da...
print(6) imie = "ola" print(imie) imie = "ola" imie = imie.upper() print(imie) True and True False and True True or 1 == 1 1 != 2
#hw4.py # Peter Podniesinski + ppodnies + H """ hwb Reasoning over code f1. #answer: x=8 y=2. #you start the problem off by seeing x+y==10 #therefore x is between (6,8) and y can be between (2,4) #since x>y. Then you look at the bit wise function assert. #So you should test the possibilities. 8,2 works becau...
# hw8.py # <ppodnies>, <H> # Implement the required classes (all above the ignore_rest line) # so that the testAll function runs without errors. # There are 4 classes to implement: Util, Line, Frog, and RepetitiveFrog. # Be sure not to modify any code below the ignore_rest line! # One of the classes models ...
def flatten(l): if type(l) != type([]): return [l] if l == []: return l else: return flatten(l[0]) + flatten(l[1:]) assert(flatten([1,[2]]) == [1,2]) print "hi2" assert(flatten([1,2,[3,[4,5],6],7]) == [1,2,3,4,5,6,7]) print "hi3" assert(flatten(['wow', [2,[[]]], [True]]) ==['wow', 2, True])...
def maximum(): for x in range(100): for y in range(100): if((x|y) >= max(x,y))==False: print x,y, (x|y), max(x,y) return False return True print maximum()
from opcodes import * class StackFullError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class StackedEmulator(object): """ Stacked is a basic stack machine emulator. The memory architecture and structure follows a Harvard Arch...
import unittest # unittest is a LIBRARY from simple_calc import SimpleCalc # we do not currently have this {file} or this {class}. class Calctest(unittest.TestCase): calc = SimpleCalc() def test_add(self): self.assertEqual(self.calc.add(2, 4), 6) self.assertEqual(self.calc.add(4, 4), 8) ...
'''File Name: writer-bot-ht.py Author: Longxin Li Purpose: this program will print out the random lyrics that follow the Markov chain analysis, and each line has ten words. CS120''' import random # import the random. SEED = 8 NONWORD = '@' random.seed(SEED) # set the random seed. cla...
class Node: def __init__(self, data): self.data = data self.left = None self.right = None class BinaryTree: def __init__(self): self.root = None def create(self, data): if self.root is None: self.root = Node(data) else: temp = self.r...
class Node: def __init__(self, data): self.data = data self.next = None class Linked_list: def __init__(self): self.head = None self.temp = None def push(self, data): node = Node(data) if self.head is None: self.head = node else: ...
def deans_list(grades): empty_dict = {} store = set() for key,value in grades.items(): if value >= 3.5: empty_dict[key] = value print(empty_dict) for key in empty_dict.keys(): store.add(key) print(store) deans_list({"Hermione": 4, "Harry": 3.4, "Ron": 3.4, "Ginny": ...
sandwich_orders = ["Bacon","Beef","cheese","chicken"] finished_sandwiches = [] while sandwich_orders: done = sandwich_orders.pop() print(f"\nI made your {done} sandwich...\n") finished_sandwiches.append(done) print("-- sandwiches that was made --\n") for finished_sandwich in finished_sandwiches: print(...
#dictionary is collection of key-value pairs students = { "key1":"value1" ,"key2":"value2","key3":"value3" } #general syntax of dictionary print(students) alien = {"color":"green","points":100} print(alien) #keys are unique print(alien.get("color")) print(alien["color"]) alien["red"] = 200 alien["black"] = 150 ali...
def print_numbers1(): for i in range(1,5+1): for j in range(i): print(i,end="") j += 1 print() print_numbers1()
dot1 = 4 num = 1 dot2 = 0 for i in range(5): for j in range(5): print("." * dot1,num ,"." * dot2,sep="")#sep= is used to remove unwanted space break dot1 = dot1 - 1 num = num + 1 dot2 = dot2 + 1
def floyds_triangle(n): k= 1 for i in range(1,n+1): for j in range(1,i+1): print(k,end=" ") k = k + 1 print() floyds_triangle(5)
def print_numbers2(): dot = 4 num = 1 for i in range(5): for j in range(5): print("." * dot, f"{num}"*num ,sep="") break dot = dot - 1 num = num +1 print_numbers2()
#write a program to check if given number is odd or even def isEvenOdd(number): if number % 2 == 0: print(number,"is even") else: print(number,"is odd") isEvenOdd(number=int(input("enter a number:"))) #for i in range(0,5): # isEvenOdd(i) #for countdown in 5,10,3,1: #...
# Game - object represents the current game state import random class Game(): # Static Variables ships = ["carrier", "battleship", "cruiser", "submarine", "destroyer"] ship_size = {"carrier": 5, "battleship": 4, "cruiser": 3, "submarine": 3, "destroyer": 2} ship_color = {"carrier": "cyan", "battleship"...
# 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 leafSimilar(self, root1, root2): """ :type root1: TreeNode :type root2: TreeNode :rty...
""" # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children """ class Solution(object): def maxDepth(self, root): """ :type root: Node :rtype: int """ if root is None: ...
""" user_guess = 0 secret_number = 20 user_attempt_number = 1 while user_guess != secret_number and user_attempt_number < 8: # Tell the user what attempt we are on, and get their guess: print("*Atempt:",user_attempt_number) user_input_text = input("Guess what number I am thinking of: ") user_guess = in...
class Dog(): def __init__(self): self.age = 0 self.name = "" self.weight = 0 def bark(self): """ The first parameter of any method in a class must be self. This parameter is required even if the function does not use it. """ print("Woof says", sel...
print("Problem 1") for i in range(10): print("*", end=" ") print("\n") print("Problem 2") for i in range(35): print("*", end=" ") if i == 9 or i == 14: print("\n") print("\n") print("Problem 3") for i in range(10): for j in range(10): print("*", end=" ") print("\n") print("Problem...
#思路:先考虑正常场景写完流程,再补充if语句覆盖异常情况。 testWord=input("请输入测试的单词:") if(len(testWord)<=0): print("这不是一个合法的单词。") elif(testWord.isalpha()==False): print("单词里面有其他字符。") else: changeWord = testWord[1:] + testWord[0] + "ay" print("转换后的单词为:{}".format(changeWord.lower()))
import argparse import sys import io ''' Class CurrencyConvert with 4 attributes field, multiplier, i(input), o(output) and methods as required. ''' class CurrencyConvert(): ''' Function: by using argparse to add 4 arguments field, multiplier, i, o to __init__ function and to parse 4 arguments either from...
#======================= # Author: Susmita Datta # Algorithm: Bubble Sort # Title: bubbleSort # # Time Complexity of Solution: # Best O(n^2); Average O(n^2); Worst O(n^2). # # Sample Input: [8,5,3,1,9,6,0,7,4,2,5] # Sample Output: [0,1,2,3,4,5,5,6,7,8,9] #---------------------------------------- def bubbleSor...
for i in range(100): if i%3 == 0 and i%5== 0 : print ("FizzBuzz"); continue; if i%3 == 0 : print ("Fizz") continue if i%5 == 0 : print ("Buzz") continue print (i)
#Approach 0 # We can sort the two strings # and then sorted_1 == sorted_2 #Approach1 #We use the hashtables def is_anagram (str_1, str_2): #delete white spaces str_1 = str_1.replace(" ","") str_2 = str_2.replace(" ","") if len(str_1) != len (str_2): return False #deal with lowercases ...
''' The composite design pattern maintains a tree data structure to represent part-whole relationships. Here we like to build a recursive tree data structure so that an element of the tree can have its own sub-elements. An example of this problem is creating menu and submenu items. The submenu items can have their ...
#!/usr/bin/env python3 """ Barron finishes cooking while Olivia cleans """ import threading import time def kitchen_cleaner(): while True: print('Olivia cleaned the kitchen.') time.sleep(1) # Threads that are performing background tasks, like garbage collection, can be detached from ...
class User: _all_users = [] def __init__(self, name): """ Constructor of the user class Parameters: name Returns: an instance of the class User """ self._name = name self._type=None self._information = [] self._email = None self._...
""" ALLEN ZHAI, WEI LIN, STEVEN GANDHAM """ class Student: def __init__(self, StLastName, StFirstName, Grade, Classroom, Bus, GPA, TLastName, TFirstName): self.StLastName = StLastName self.StFirstName = StFirstName self.Grade = Grade self.Classroom = Classroom self.Bus = Bus...
# work with the variable 'my_numbers' # my_numbers = [1, 2, 3, 4, 5] print( [num for num in my_numbers if num % 2 == 0])
import pyphen #Programa que calcula el numero de silabas en un texto import re dic = pyphen.Pyphen(lang='es') texto='Hola, como; estas? yo estoy muy bien, y ¿tu vas? (sorpresa)' texto1=re.sub(r'[\?\!\-\¿\;\%\$\#\"\'\,]', '', texto) texto1=re.sub(r'[aeiou]y', 'oi', texto1) print(texto1) a=dic.inserted(texto1) ...
#f(f(x))=f(x) def add_ten(num): return num+10 print add_ten(10) print add_ten(add_ten(10)) ##The above function is not ideempotent the reason is when the function is passed into a function #it should retun the same original result #Example of idempotent print abs(-10) print abs(abs(-10))
# coding: utf-8 # Pemrograman Berbasis Objek # Class and Object # September 03 2018 # We can create "things" with: # - atributes things those "things" have => merupakan barang atau properti yang ada # - methods things those "things" can do => suatu rancangan yang menggunakan properti dari atributes # # Pengertian...
more18 = m20 = man = 0 while True: print('='*30) while True: sexo = continuar = ' ' age = input('Quantos anos? ').strip() if age.isnumeric() == True: age = int(age) break while sexo not in 'mf': sexo = input('Qual o sexo? [M/...
from abc import abstractproperty tempdados = [] dados = [] maior = [] menor = [] while True: name = input('Nome: ').strip().title() peso = float(input('Peso: ')) tempdados.append(name) tempdados.append(peso) dados.append(tempdados[:]) if len(dados) == 1: maior.append...
numbers = list() for cont1 in range(0, 3): numbers.append(int(input(f'Digite o valor para a posiçao {cont1}: '))) print(f'Os valores digitados foram {numbers}') maior = max(numbers) menor = min(numbers) print(f'O menor numero foi {menor} nas posições', end=' ') for i1, val1 in enumerate(numbers): ...
val = float(input('\nDigite um valor em metros: ')) # km hm dam m dm cm mm # 1000 100 10 1 01 001 0001 km = val / 1000 hm = val / 100 dam = val / 10 dm = val * 10 cm = val * 100 mm = val * 1000 print('\n{}m tem:\n{}dam \n{}hm \n{}km '.format(val, dam, hm, km)) print('{}dm \n{}cm ...
from random import randint from os import system as sy while True: sy('cls') usr = '' comp = randint(1, 10) print('# ================================= #') print('# Um numer entre 1 e 10 foi gerado, #') print('# descubra qual é o numero #') print('# =====================...
print() algo = input('Digite qualquer coisa: ') print() #print(algo, 'e um numero?', algo.isnumeric()) if algo.isnumeric() == True: print(algo, 'é um numero!') elif algo.isalpha() == True: print(algo, 'é uma palavra!') elif algo.isspace() == True: print(algo, 'é espaço!')
ant = 0 dep = 1 n = int(input('Quantos numeros quer ver? ')) i = 3 print(ant) print(dep) while i <= n: soma = ant + dep ant = dep dep = soma print(soma) i += 1
n = int(input('Digite um numero inteiro: ')) print('''Escolha uma das bases para conversão [0]Converter para Binario [1]Converter para Octal [2]Converter para Hexadecimal [3]Converter para todas ''') option = int(input('Sua opção: ')) if option == 0: print('{} em binario é: {}'.format(n, bin(n))) el...
aluno = {} aluno['name'] = input('Nome: ').strip().title() aluno['media'] = float(input(f'Média de {aluno["name"]}: ')) if aluno['media'] < 7: aluno['situação'] = 'reprovado' else: aluno['situação'] = 'aprovado' for k, v in aluno.items(): print(f'{k} é igual a {v}')
notam = float(input('Sua nota mensal: ')) notab = float(input('Sua nota bimestral: ')) media = (notam + notab) / 2 print() if media >= 7: print('Parabens voce passou!!!') else: print('Puts, nao foi dessa vez') print('Media: {}'.format(media))
n = int(input('Qual numero voce quer saber a tabuada? ')) ''' print('-'*15) print('| {0} * 1 = {1} |'.format(n, (n * 1))) print('| {0} * 2 = {1} |'.format(n, (n * 2))) print('| {0} * 3 = {1} |'.format(n, (n * 3))) print('| {0} * 4 = {1} |'.format(n, (n * 4))) print('| {0} * 5 = {1} |'.format(n, (n * 5)...
def main(): count = 0 for line in open('3.in'): sides = [int(side) for side in line.split()] sides.sort() print sides if (sides[0] + sides[1]) > sides[2]: count += 1 print count if __name__ == "__main__": main()
''' Take two lists, say for example these two: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists ...
#!/usr/bin/python # -*- coding: UTF-8 -*- from socket import * import os import sys import struct import time import select import binascii def checksum(data): n = len(data) m = n % 2 sum = 0 for i in range(0, n - m, 2): sum += (data[i]) + ((data[i+1]) << 8) if m: sum += (data[-1]) sum = ...
def getwords(filename): words = [] f = open(filename); for line in f.readlines(): words.append(line.split()[0].lower()) return words #words = getwords("wordlist.txt"); #print words
import math input_str = input().split(' ') a = int(input_str[0]) b = int(input_str[1]) gcd = math.gcd(a, b) lcd = (math.fabs(a) * math.fabs(b)) // gcd print(gcd, int(lcd))
#Mobile Money Account print("1. send money") print("2. withdraw money") phone_number = "0546819106" user = input("select choice:\n") if user == "1": print("send Money") print("1. MTN user") print("2. Tigo user") x = input("choice:\n") if x == "1": print("MTN User:") numbe...
from .base import Bracket class Function(Bracket): '''A :class:`~.Bracket` representing a function. A function is defined a-la Python as:: func(expression, **kwargs) where *kwargs* is a dictionary of input parameters. For example, the rolling-standard deviation is defined as...
from numpy import dot, linalg class ols(object): '''The ordinary least squares (OLS) or linear least squares is a method for estimating the unknown parameters in a linear regression model. The matrix formulation of OLS is given by the linear system of equations: .. math:: y = X \beta + \epsilon ....
length = float(input("what is the length of the field?")) width = float(input("what is the width of the field?")) total_area = length * width / 43560 print("The total area is: " , total_area , "acres")
'''Brad Allen. Scratch work.''' import pandas as pd import os from collections import namedtuple import numpy as np class dfs: '''This class employs a depth first search strategy - the main function is explore_branch(), which will traverse a branch until it: (1) uses up too much weight (the "flo...
# Exercise 3 # Fermat’s Last Theorem says that there are no positive integers a, b, and c such that a**n + b**n == c**n for # any values of n greater than 2. # Write a function named check_fermat that takes four parameters—a, b, c and n —and checks to see if Fermat’s theorem holds. If n is greater than 2 and a**n + ...
import random import time print("Welcome To Mallaya Bank:") time.sleep(0.44) print("") print("") print("TO CREATE AN ACCOUNT,WAIT FOR 5 SECONDS WITHOUT TERMINATION") time.sleep(5) print("Enter the Details as per your aadhar card") time.sleep(3) b=int(input("Enter your 16 digit AADHAR NUMBER:")) b = str(b) d = inpu...
import unittest from shopping import Cart, CartItem, Merchandise from shopping.exceptions import InvalidCartItem, InvalidProduct class Base(unittest.TestCase): def setUp(self): self.book = Merchandise(name='book', price=1.99, category='book'...
import unittest from shopping import tokenize from shopping.exceptions import InvalidOrderString text_order_1 = """3 books at 2.99 2 music CD (imported) at 6.29""" text_order_2 = """1 imported perfume at 7.99""" invalid_text_order = """1 perfume 3.99""" class TestTokenize(unittest.TestCase): d...
#It is possible to show that the square root of two can be expressed as an infinite continued fraction. #√ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213... #By expanding this for the first four iterations, we get: #1 + 1/2 = 3/2 = 1.5 #1 + 1/(2 + 1/2) = 7/5 = 1.4 #1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666... #1 + ...
# Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: #1634 = 1**4 + 6**4 + 3**4 + 4**4 #8208 = 8**4 + 2**4 + 0**4 + 8**4 #9474 = 9**4 + 4**4 + 7**4 + 4**4 #As 1 = 1**4 is not a sum it is not included. #The sum of these numbers is 1634 + 8208 + 9474 = 19316. #Fi...
#onsider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. #If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: #1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, ...
# -*- coding: utf-8 -*- from DataTypes import SquareType from Move import Move class Board(object): # Represents de possible directions to move on directions = ((0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1)) def __init__(self, rows, cols): self._boardData = [[SquareType.E...
# -*- coding:utf-8 -*- from Player import Player import random class GreedyRndPlayer(Player): """Jugador que siempre elige la jugada que más fichas come.""" name = 'GreedyRnd' def __init__(self, color): self.movs = 0 self.randomMovs=5 super(GreedyRndPlayer, self).__init__(self.name, color) def random_mov...
''' Description: Write a function called sumIntervals/sum_intervals() that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once. Intervals Intervals are represented by a pair of integers in the form of an array. The first value of the inte...
''' Description: You are given a node that is the beginning of a linked list. This list always contains a tail and a loop. Your objective is to determine the length of the loop. # Use the `next' attribute to get the following node # Example of geeting next node: node.next ''' def count_loop_size( node_of_meet ):...
from flask import Flask, render_template, url_for, request, redirect, jsonify from beginnersMethod import BeginnersCube #https://www.speedsolving.com/wiki/index.php/Kociemba's_Algorithm app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') #the folder is called template for...
import random PlayerName=input("What is your name?") print("Welcome to Clash Of Gladiators, "+PlayerName+"! You're a gladiator being put into fight today!") def start(): print("Note: The Clashes are in a storyline, so if you pick one further on, you will have everything from the list") print("that you have in t...
#!/usr/bin/python import os import sys import json import argparse import re from tax.receipt import Receipt from tax.item import Item RECEIPT_REG = r'(?P<quantity>\d+) (?P<imported>(imported )*)(?P<name>[\w ]+) at (?P<price>\d+.\d+)' def parse_items(items, exempt_dict): "Read input receipt and returns its corr...
import random def what_drink(): questions = { "strong": "Do ye like yer drinks strong?", "salty": "Do ye like it with a salty tang?", "bitter": "Are ye a lubber who likes it bitter?", "sweet": "Would ye like a bit of sweetness with yer poison?", "fruity": "Are ye one for a fruity finish?", ...
""" Uses scraped data to conjugate and declenate German verbs, nouns and adjectives """ import dataset from german_anki.verbix import scrape_verbix DB = dataset.connect('sqlite:///.local/share/Anki2/addons21/german_anki/german.db') VERBS = DB.get_table('verb') NOUNS = DB.get_table('noun') ADJVS = DB.get_table('adjec...
from math import floor def binIsPal(n): collector = [] while(not n == 0): collector.append(str(n % 2)) n = floor(n / 2) return collector == collector[::-1] def isPal(pal): return pal == pal[::-1] palSum = 0 for n in range(1, 1000000, 2): if(isPal(str(n)) and binIsPal(n)): ...
from math import floor from math import sqrt def genPrimes(n): #http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Input n>=6, Returns a list of primes, 2 <= p < n """ correction = (n%6>1) n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6] siev...
'''a,b,c=[int(x) for x in input("Enter three integer numbers").split()] average = (a+b+c)/3 print("Average of the three numbers is:",average) studentid = int(input("Enter Student Id")) name = input("Enter Student Name") marks = float(input("Enter marks scored")) print("ID:",studentid,"Name:",name,"Marks:",marks)''' im...
x,y='12' y,z='32' print(x+y+z) '''charlist="asdfghhkjluotuwrmpbicnbc" password="passw" for current in range(5): a=[i for i in charlist] for x in range(current): a= [y+i for i in charlist for y in a] if password in a: print(f'password is: {a[a.index(password)]'}) exit()...
#Write a Python program to convert a byte string to a list of integers. x = b'ABC' print( ) print(list(x)) #Write a Python program to list the special variables used within the language. s_var_names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split())) print() print( '\n'.joi...
#Write a python programe to print the calander of using month and year import calendar x = int(input("Enter the year : ")) y = int(input("Enter the month : ")) print(calendar.month(x,y)) #Write a Python program to print the following here document print('''i am ashish i am in b.tech. 3red yera student''') #...
lst=[30,40,50,60,70,80] #rempove lst.remove(40) #append lst.append(20) print(lst) #del del(lst[2:]) print(lst) #max print(max(lst)) print(min(lst)) #insert lst.insert(4,30) print(lst) #sort lst.sort() print(lst) lst.sort(reverse=True) print(lst)
def display(name): def message(): return "Wel come to: " result = message()+name return result print(display("Ashish")) #Parameto to another function '''def display(fun): return "hello "+ fun def name(): return "Ashish" print(display(name)) #returning function def display(): def message(...