text stringlengths 37 1.41M |
|---|
# Python Programme Number 11
# Counter - Demonstration of break and continue statements
# Programmer: Mukul Dharwadkar
# Date: 24 February 2006
count = 0
while True:
count += 1
# Loop should end if count is greater than 10
if count > 10:
break
# We want to skip the number 5
if count == 9:
... |
# Python Programme Number 52
# Error Handling: Demonstrates error handling
# Programmer: Mukul Dharwadkar
# Date: 18 May 2006
# try/except block
try:
num = float(raw_input("Enter a number: "))
except:
print "Something went wrong!"
|
# Python Programme Number 5
# Craps roller using random numbers
# Programmer: Mukul Dharwadkar
# Date: 22 February 2006
import random
# Generate random number from 1 to 6
die1 = random.randrange(6) + 1
die2 = random.randrange(6) + 1
total = die1 + die2
print "You rolled a", die1, "and a", die2, "for a total of", to... |
# Python Programme Number 87
# Magic Methods: Rectangle, accessing properties
# Programmer: Mukul Dharwadkar
# Date: 11 June 2009
class Rectangle(object):
def __init__(self):
self.width = 0
self.height = 0
def setSize(self, size):
self.width, self.height = size
def getSiz... |
# Python Program Number 28
# Backward printing: Implementing strings
# Programmer: Mukul Dharwadkar
# Date: 8 March 2006
message = raw_input("Send your message to the world: ")
position = len(message)
new_message = ""
while position:
new_message += message[position-1]
position -= 1
print new_message
|
# Python Programme Number 70
# Sequence Membership demonstration programme
# Programmer: Mukul Dharwadkar
# Date: 6th December 2006
# Check a user name and PIN code
database = [
["mukul", "1234"],
["shital", "2345"],
["jayant", "3456"],
["nandini", "4567"]
]
user_name = raw_input("Ent... |
# Python Programme Number 30
# Guess the word game: Implementation of tuples and in
# Programmer: Mukul Dharwadkar
# Date: 14 March 2006
import random
# Create a list of words
WORDS = ("sheetal", "delllaptop", "jurassic", "sholay",
"keyboard", "synthesizer", "flatpanel", "refrigerator",
"workhorse")... |
# Python Programme Number 38
# Character Creator
# Programmer: Mukul Dharwadkar
# Date: 19 March 2006
points = 30
ATTRIBUTES = {"Wisdom" : 10, "Strength": 7,
"Health" : 8, "Dexterity" : 8}
choice = 0
response = 0
attrib = []
print \
"""
Hello and welcome.
You have 30 points to spend on... |
# Program to find the LCM with remainders as
# [8, 7, 6, 5, 4, 3, 2, 1] when a number is divided by
# [9, 8, 7, 6, 5, 4, 3, 2] respectively
# Programmer: Mukul Dharwadkar
# Date: 2 May 2020
# Python version 3
Y = 3
remain_list = [8, 7, 6, 5, 4, 3, 2, 1]
div_list = [9, 8, 7, 6, 5, 4, 3, 2]
while True or Y % 2 != 0:
... |
def reverse(word):
letter = ""
r = ""
for i in range(len(word) - 1, -1, -1):
letter = word[i]
r = r + letter
return r
|
import math
from turtle import *
def romanize():
num = int(input('Please input a number less than 100 to convert to roman numerals: '))
roman_num = []
hundred = 0
fifty = 0
ten = 0
five = 0
one = 0
if num > 100:
print('Please enter a number less than 100')
romanize()
else:
hundred = num // 100
fifty... |
import math
odd_string = input('Please enter a string with odd number of characters: ')
if len(odd_string) % 2 == 1:
middle = math.floor(len(odd_string)/2)
# Print the middle character
print(odd_string[middle])
# Print up to middle
print(odd_string[:middle:])
# Print from middle to end
print(odd_string[m... |
english_word = input('Please enter a word: ')
vowels = ('a', 'e', 'i', 'o', 'u')
# Count vowels by comparing it to tuple
vowel_count = 0
for x in english_word:
if x in vowels:
vowel_count += 1
consonant_count = len(english_word) - vowel_count
print('%s has %s vowels and %s consonants' % (english_word, vowel_c... |
a_str = input('Please enter a string: ')
ch = input('Please enter a character: ')
new_string = a_str.replace(ch, '')
print(new_string)
|
'''
Name: Junwoo Shin
NetID: JS8460
Filename: hw8q3.py
Explanation
-----------
First I use the print_shifted_triangle to make the actual triangle. I pass in the shift because i noticed that it was equal to number of rows - 1. I looped over the range of number of triangles and passed in the margin to make the triangle... |
weight = int(input('Please input your weight in kilograms: '))
height = int(input('Please input your height in meters: '))
print('Your BMI is %s' % (weight/(height**2)))
|
import random
import math
# создает матрицу nxm
def generateMatrix():
n = int(input("Input number of rows: "))
m = int(input("Input number of columns: "))
matrix = [[round(random.uniform(-100, 100), 3) for j in range(m)] for i in range(n)]
printMatrix(matrix, "Start matrix: ")
return matrix
# на... |
"""
Given a connected graph with N vertices. The task is to select k vertices from the graph such that all these selected vertices are connected to at least one of the non selected vertex.
There are mutltiple combinations of possible answers print any one of them(preferably first possible combination).
Note: The gra... |
"""
Problem Description
You are given some routes connecting two places.Your task is to connect all the routes given in the form of a graph.
Input:
First line consists of no of places V
second line consists of no of routes U
next U line conists of routes connecting two places x and y
Output:
print the graph formed b... |
import itertools
def list_from_dictionary(filename):
# 辞書ファイルをリストにする
# 辞書の単語を小文字にする
# 辞書の単語に qu が現れたら q に置換する
# dic_list = [line.strip().lower().replace("qu", "q") for line in open(filename)]
# return dic_list
dic_list = list()
for line in open(filename, "r"):
... |
import time
import math
print("We gaan een aantal rekensommen behandelen.")
time.sleep(2)
print("De eerste som is een plus (+) som.")
time.sleep(2)
print("Vul het 1e getal in.")
num1plus = float(input())
time.sleep(1)
print("Vul nu het 2e getal in.")
num2plus = float(input())
time.sleep(1)
print("Het antwoord va... |
from turtle import *
width(5)
screensize(800, 800)
for index in range(10):
if index % 2 == 0:
color("red")
else:
color("blue")
forward(20)
penup()
forward(20)
pendown()
mainloop()
|
favs = ['death note', 'netflix', 'teaching']
print("Hi there, here you favorite things so far")
print("**************************************")
for index, fav in enumerate(favs):
print(index + 1, '.', fav)
print("**************************************")
index = int(input("Favorite position you want to get rid of?... |
s = input("Enter a sequence of number, separated by space:")
words = s.strip().split(' ')
nums = []
for word in words:
nums.append(int(word))
print(nums)
|
numbers = [2018, 1, 5, 0, -10, 20, 15, -7]
sorted_numbers = []
sorting = True
while sorting:
min_numb = min(numbers)
sorted_numbers.append(min_numb)
numbers.remove(min_numb)
if len(numbers) == 0:
sorting = False
print(*sorted_numbers)
|
from turtle import *
shape('turtle')
speed(-1)
color('blue')
pensize('2')
for i in range(6):
for i in range(4):
for i in range(4):
forward(150)
left(90)
left(90)
left(15)
mainloop()
|
def task_4(n):
n = int(n)
if(n < 0 or n > 100):
raise Exception('Число вне допустимого диапазона')
if(n == 13):
raise Exception('Число 13 запрещено')
return n**2
if __name__ == "__main__":
n = input('Введите число от 0 до 100: ')
try:
print('Функция вернула {}'.format(... |
n = None
while(n < 0 or n > 10):
n = int(input('Введите число: '))
print(n**2)
|
'''
x=4
x="john"
print(x)
x = y = z = "Orange"
print(x)
print(y)
print(z)
x = "krishn"
print("python is " + x)
x = "Krishna"
y = "Reddy"
z = x + y
print(z)
'''
x =5
y = 12
print(x + y) |
import sqlite3
class CreateTable:
def createEmployee(self):
conn = sqlite3.connect('Hotel_Management.db')
conn.execute("PRAGMA foreign_keys = 1")
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS employee(
EID TEXT PRIMARY KEY,
... |
balance = 4842
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
# ##
nPaid = 0;
for nCurrentMonth in [1,2,3,4,5,6,7,8,9,10,11,12]:
print("Month: "+str(nCurrentMonth))
print("Minimum monthly payment: " + str(round(monthlyPaymentRate*balance,2)))
nPaid = nPaid + monthlyPaymentRate*balance
balance = ... |
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Checked OK by EDx grader
if aStr!='':
midPoint=len(aStr)/2
midChar=aStr[midPoint]
if midChar==char:
#we're don... |
def make_album(singer, name, number="4") :
album = {"singer":singer, "name":name, "number":number}
return album
while(True) :
print("If you want exit, please enter 'exit' in time")
name = input("Please enter a name: ")
if(name=="exit") :
break;
singer = input("Please enter a singer: ")
if(singer == "exit") :
... |
pizzaes = ["apple pizza", "new aulan", "chese"]
for pizza in pizzaes :
print("I like " + pizza + "!")
print("I really love pizza!") |
# 创建宠物字典
cat = {"name" : "ameko", "host" : "xiamu"}
dog = {"name" : "inuyasha", "host" : "cakome"}
# 将字典存储到列表中
pets = [cat, dog]
# 打印字典信息
for pet in pets :
for name, host in pet.items() :
print(host + " is " + name + " 's host") |
def make_shirt(size="large", word="I love Python") :
print("This shirt's size is " + size + " and word is " + word)
# 默认字样大号
make_shirt()
# 默认字样中号
make_shirt("middle")
# 任意字样大小
make_shirt("small", "Give me out") |
def read_file(word, filename):
try:
with open(filename, encoding='utf-8') as file_object:
contents = file_object.read()
except FileNotFoundError:
print('The file ' + filename + ' is not found')
else:
calculate_words(word, contents)
def calculate_words(word, contents):
count = contents.lower().count(word)
... |
from collections import OrderedDict
word_code = OrderedDict()
word_code['Java'] = 'A strong program language'
word_code['PHP'] = 'The best language'
word_code['C++'] = 'Objected labguage'
for key, value in word_code.items():
print(key+' '+value)
|
#密碼重試程式
#password = 'a123456'
#讓使用者重複輸入密碼
#【最多輸入3次密碼】
#如果正確 就印出"登入成功!"
#不對的話,就印出"密碼錯誤! 還有__次機會"
password = 'a123456'
i = 3 #剩餘機會
while i > 0:
pwd = input('請輸入密碼:')
if pwd == password:
print ('登入成功')
break #逃出迴圈
else:
i = i - 1
print('密碼錯誤! 還有', i , '次機會')
|
"""
Parcial 1 Barrera
"""
def main ():
total = int(input("Ingrese el # de casilleros: "))
abiertos = 0
cerrados = 0
i=1
while i <= total:
divs = divisores(i)
if divs%2 != 0:
print(i, " queda abierto")
abiertos += 1
i+=1
cerrados = tota... |
import pygame # imports PyGame
from pygame.locals import * # imports more stuff from pygame
pygame.init() # initializes PyGame
screen = pygame.display.set_mode((800, 600)) # sets size for screen
pygame.display.set_caption("Blank Screen") # sets the caption of the screen
clock = pygame.time.Clock() # the "clock... |
import random
import time
def max_heapify(arr, n, i):
largest = i
left = 2*i + 1
right = 2*i + 2
# If left child is greater than root -> swap:
if left < n and arr[left] > arr[largest]:
largest = left
# If right child is greater than root -> swap:
if right < n and ar... |
kgcm = input('Enter ur weight(kg) and height(cm): ')
kgcm = kgcm.split(' ')
m = float(kgcm.pop()) * 0.01
kg = float(kgcm.pop())
bmi = kg / (m * m)
if 20 <= bmi and bmi < 25:
print('congrats! yar perfect!')
else:
print('u need a health care...') |
###########################################
# Author: klion26
# Date: 2014/11/08
# Problem: Complex_Number_Algebra
###########################################
# complex addition
# complex number is stored in list [x,y]->x+yi
def add(a, b):
c = []
c.append(a[0]+b[0])
c.append(a[1]+b[1])
retu... |
###########################################
# Author: klion26
# Date: 2014/11/07
# Problem: Tax_Calculator
###########################################
def taxCal(val, tax):
return val*(1+tax)
if __name__ == "__main__":
v = input("Input the cost: ")
tax = input("input the tax rate(0-100): ")
... |
# -*- coding: utf-8 -*-
# 统计文件中的代码,注释,以及空行数目
# filename 表示输入文件的文件名
def codeAnalysis(filename):
# 打开文件
file = open(filename)
# codeLine:代码行数
# emptyLine 空行数目
# commentLine 注释行数
codeLine = 0
emptyLine = 0
commentLine = 0
content = file.readline()
while content :
... |
#1 sum 1 -- 100
print(sum(range(0,101)))
#2 global 修改全局变量
a = 5
def fn():
global a
a = 4
fn()
print(a)
#3 dictionary update and del
dic = {"name":"mj","age":18}
del dic["name"]
#print(dic)
dic2 = {"name":"xn","age":"19"}
dic.update(dic2)
print(dic)
#4 list - remove duplicate
list = [11,12,13,12,15,16,13]
a... |
#!/usr/bin/env python3
import trie
# initialize trie
root = trie.TrieNode('*')
def main(string):
# loop through lines(words) in a file and store in trie
with open("studentMachineDict.txt","r") as afile:
for line in afile:
word=line.rstrip()
# add word to trie
... |
""" Checking the weather seems fairly trivial: Open your web browser, click the address bar, type the URL to a weather website (or search for one and then click the link), wait for the page to load, look past all the ads, and so on.
Actually, there are a lot of boring steps you could skip if you had a program that dow... |
frase = str(input('Digite uma frase: ')).strip().upper()
palavras = frase.split()
print('A variável palavras usando split: ', palavras)
junto = ''.join(palavras)
print('A variável junto usando join: ', junto)
inverso = ''
print('Você digitou a frase {}'.format(frase))
for letra in range(len(junto)-1, -1, -1):
inver... |
# Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e seu antecessor.
n1 = int(input('Digite um número inteiro: '))
s = (n1+1)
a = (n1-1)
print('O número {} possui o sucessor {} e o antecessor {}'.format(n1, s, a)) |
#Crie um programa que leia um número real qualquer e mostre na tela a sua porção inteira
import math
n = float(input('Digite um número qualquer: '))
print('A sua parte inteira é: ', math.trunc(n))
|
# Faça um programa que leia a largura e a altura de uma parede e calcule a sua área.
# Calcule a quantidade necessária para pintar uma parede considerando que cada litro de tinta pinta 2m²
altura = int(input('Digite a altura da parede: '))
largura = int(input('Digite a largura da parede: '))
area = altura*largura
tinta... |
primeiro = int(input('Digite o primeiro termo: '))
razao = int(input('Digite a razão: '))
pa = (razao + primeiro)
cont = 1
termos = 0
while cont < 10:
if cont == 1:
print(primeiro, end=" -> ")
cont += 1
print(pa, end=" -> ")
pa += razao
termos +=1
opção = int(input("\nQuantas termos mais voc... |
for p in range(1, 4):
peso = float(input('Digite o peso da {}ª pessoa: '.format(p)))
if p == 1:
maior = peso
menor = peso
else:
if maior < peso:
maior = peso
if menor > peso:
menor = peso
print('O maior peso informado foi {} kg'.format(maior))
print('O... |
v = float(input('Informe a sua velocidade: '))
if v > 80:
print('Você ultrapassou o limite de velocidade!')
print('A multa aplicada é de R$ {:.2f} reais'. format((v-80)*7))
print('Parabéns você é um ótimo motorista!')
|
print('\033[4;30;45m Olá mundo! sublinhado\033[m')
print('\033[0;30;41m Letra branca e fundo vermelho sem limite')
print('\033[1;31;43m Letra vermelha em negrito e fundo amarelo com limite \033[m')
print('\033[7;30m Letra branca e fundo preto e depois inverte para fundo branco e letra preta\033[m')
a = 3
b = 5
print('O... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 12:49:21 2019
@author: dori
"""
import pandas as pd
import numpy as np
def red(x):
d = {}
d['T'] = np.mean(x['T'])
d['P'] = np.mean(x['P'])
return pd.Series(d, index=d.keys())
data = {}
data['H'] = [0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3]
dat... |
import re
from collections import deque
import itertools as it
def cleave(sequence, rule, missed_cleavages=0, min_length=None):
"""Cleaves a polypeptide sequence using a given rule.
Parameters
----------
sequence : str
The sequence of a polypeptide.
.. note::
The sequence ... |
class Solver(object):
def solve2(self, values):
length = len(values)
for x in range(length):
for y in range(1, length):
first = values[x]
second = values[y]
if first + second == 2020:
return first * second
raise... |
__author__ = "Steven Chaney"
mem = [52]
def store(ch, value):
"""
:param ch: must be a letter
:param value: value to be stored
:postcondition: value has been stored in the memory location
associated with ch
"""
mem[indexOf(ch)] = value
def indexOf(ch):
"""
:param... |
from numpy import *
# Creating a matrix
my_matrix = arange(20).reshape(5,4)
print(my_matrix)
# Concatenating arrays
array_one = array([1, 3])
array_two = array([11, 111, 4])
array_three = array([8,4,3])
print(concatenate((array_one, array_two, array_three)))
# Matrix multiplication
array_one = random.randn(5,5)
arra... |
# http://towersofhanoi.info/Animate.aspx
def hanoi(n, start_pole, end_pole, inter_pole):
# Checks to see if there are still discs left on the pole
if n >= 1:
hanoi(n - 1, start_pole, inter_pole, end_pole) # Call method recursively
print("Disc moves from", start_pole, "to", end_pole, "pole") # ... |
from itertools import combinations
arr = [ 1,1,1,2 ]
mydict = {}
for i, j in enumerate(arr):
if j not in mydict:
mydict[j] = [i]
else:
mydict[j].append(i)
for k, v in mydict.items():
if len(v) > 1:
print(list(combinations(v, 2))) |
row_num = int(input('Please tell me the number of row:'))
row = []
for i in range(row_num) :
row.append(input())
print('--------Output--------')
for j in range(row_num) :
a = list(row[j])
for g in range(len(a)) :
change = a[g]
if change == '*' :
a[g] = 'o'
for k in range(... |
#Sentencias condicionales / conditional statements
edad = 14
m_edad = 18
if edad >= m_edad:
print ("Eres mayor de edad")
if False:
print ("Esto sse ejecuta siempre que sea mayr de edad")
else:
print("Cualquier cosa")
else:
print("No eres mayor de edad")
|
#metodos de las listas
lista = [1, "dos",3]
buscar = 0
#validar si existe elemento en listabusca
if buscar in lista:
lista.index(buscar)
else:
print("No existe el elemento")
#agregar elementos a la lista
lista.append("agregar a lista")
print(lista)
#Cantidad de veces que esta un elemento en una lista
print(... |
'''
Re-factored this solution to use arithmetic sequences.
Now it will work for large numbers, rather than
just numbers under 1,000.
'''
def sum_multiples(factor, in_num):
a_n = (in_num - 1)/factor
sum_3 = a_n * (a_n + 1) / 2 * factor
return sum_3
t = int(raw_input())
while t > 0:
in_... |
def approx_pi(terms):
total = 0
denominator = 3
for x in range(1,terms):
if x%2 == 0:
num1 = 1/float((denominator))
total += num1
else:
num2 = -(1/float((denominator)))
total += num2
denominator += 2
return 4 * (1 + total)
def pi_sig_digits(decpts):
if decpts <= 0:
raise Exception("Accuracy ... |
# 02 - Utilizando estruturas de repetição com variável de controle,
# faça um programa que receba uma string com uma frase informada pelo usuário
# e conte quantas vezes aparece as vogais a,e,i,o,u e mostre na tela,
# depois mostre na tela essa mesma frase sem nenhuma vogal.
# 05 - Refatore o exercício 2, para que uma... |
from abc import ABC, abstractmethod
from tests import tests
class Car(ABC):
def __init__(self, age, price_per_day,make,model,year,premium):
self._age = age
self._price_per_day = pricePerDay
self._make = make
self._model = model
self._year = year
self._premium = premium
@abstractmethod
def get_price(sel... |
# memoized fibonnaci sequence
memo = {}
def fib(n):
if n < 2:
return 1
else:
if n in memo:
return memo[n]
else:
ret = fib(n-1) + fib(n-2)
memo[n] = ret
return ret
if __name__ == '__main__':
for i in range(0,10):
print(fib(i)) |
"""
Os números felizes são definidos pelo seguinte procedimento.
Começando com qualquer número inteiro positivo, o número é substituído pela soma dos quadrados
dos seus dígitos, e repetir o processo até que o número seja igual a 1
ou até que ele entre num ciclo infinito que não inclui um
ou seja a soma dos quadrad... |
import car as car
import world as world
import numpy as np
import random
import time
from matplotlib import pyplot as plt
from matplotlib import colors
def simulate(world, num):
#runs the simulation for num iterations
for n in range(num):
print("n: " + str(n))
world.propogateForwa... |
#CS 102: Memoization for two stamps.
def d_stamper(k, stamps):
if k < 0:
return False
elif k in stamps: ## CHANGE ONLY THIS LINE !! :)
return stamps[k]
else:
ans = d_stamper(k-7, stamps) or d_stamper(k-5,stamps)
stamps[k] = ans
return ans
def main():
n = int... |
class Node:
def __init__(self,initdata=""):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
... |
#CS 102 Spring 2020
# recursive powers
#Compute a^n % m using recursion
#
# In modern cryptography -- the type used by your phone everytime you open it --
# it is essential to be able to compute the remainder when a^n is divided
# by m instantly. And do so when a, n and m are all huge numbers
# (e.g. m is 400 digits... |
from stackprint import Stack
def Mremove_all(self, item):
if self.isEmpty():
print("Queue is empty! None was returned")
return None
else:
val = self.items[self.front]
self.items[self.front] = None
if self.front != self.rear:
if self.front == item:
sel... |
#Matthew Zhang
#CS 102 Spring 2020
#March 3rd
#Program: heading toward nothing
#Calculates how many rounds of subtractions it takes for a randomly generated list of ints to calculate its way down to zero, if possible.
import random
#Function to populate the list with random integers.
def initial(storeNum):
#The n... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 第一行注释是为了告诉Linux/OS X系统,这是一个Python可执行程序,Windows系统会忽略这个注释;
# 第二行注释是为了告诉Python解释器,按照UTF-8编码读取源代码。
# 申明了UTF-8编码并不意味着你的.py文件就是UTF-8编码的,必须并且要确保文本编辑器正在使用UTF-8 without BOM编码。
pass#用于函数定义循环和判断中,相当于一个空语句,在未想好函数如何写时,先写pass编译器不会报错
# 赋值
n, a, b = 0, 0, 1 # n=0,a=0,b=1
a, b = b, a... |
sorted([1,2,4,2,4]) #对可迭代对象排序??????????????
print(int("1011",2))#把字符串转换为整数,其中字符串是二进制表示的
"hello".isalpha() #检测字符串是否只由字母组成.如果字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False。
"qwe".islower()
"WQE".isupper()
"123".isdigit()
l=["12","123","3"]
print(','.join(l))#l为一个list,将list的内容以','为间隔,拼接为一个字符串显示
#对字符串的详细处理看正则表达式部分
import re
r=r... |
from sklearn import datasets
iris = datasets.load_iris()
digits = datasets.load_digits()
# 画出任意两维的数据散点图
from sklearn import datasets
import matplotlib.pyplot as plt
import numpy as np
iris = datasets.load_iris()
irisFeatures = iris['data']
irisFeaturesName = iris['feature_names']
irisLabels = iris['target']
def sc... |
#YouTube Extractor
#Extract YouTube video statistics based on a search query
#Import modules
from googleapiclient.discovery import build
from oauth2client.tools import argparser
import sys
#Input query
#print("Please input your search query")
#q=input()
#Run YouTube Search
#response = youtubeSearch(q, s... |
def inputing(msg):
"""
Ця функція призначена для введення даних користувачем
Args:
msg: рядок, що відобразиться при показі підказки до введення даних
Return:
список елементів. Використовується функцією
notempty(nums, filled)
Raises:
OverflowError
... |
"""Output the lyrics to 'The Twelve Days of Christmas'."""
from collections import namedtuple
Day = namedtuple('Day', 'number gift')
DAYS = [
Day('first', 'a Partridge in a Pear Tree'),
Day('second', 'two Turtle Doves'),
Day('third', 'three French Hens'),
Day('fourth', 'four Calling Birds'),
D... |
"""Convert a phrase to its acronym."""
import re
def abbreviate(words):
"""Return the abbreviation—or acronym—for the words provided."""
pattern = r"""
([A-Z]) # capture the first capital letter
[A-Z']* # followed by zero or more capital letters or apostrophes
"""
return ''.join(re.findall(... |
# -*- coding: utf-8 -*-
# @Author: nevil
# @Date: 2020-08-07 15:49:25
# @Last Modified by: nevil
# @Last Modified time: 2020-08-07 15:49:40
# Python program for Finite Automata
# Pattern searching Algorithm
numChars = 256
def nextForm(PATTERN, M, state, x):
if state < M and x == ord(PATTERN[state]):
... |
ammount = float(input("Enter the ammount of money you have: "))
aplprice = float(input("Enter the price of an apple: "))
napple = int(ammount/aplprice)
change = ammount % aplprice
print(f"You can buy {napple} apples and your change is {change:.2f} pesos.") |
class List_plays:
'''
This class stores and sorts objects of the Play class so that they can be efficiently accessed for processing.
Overall list consisting of three separate lists each of which stores multiple instances of the Play class.
'''
def __init__(self):
self.first_down = [[],[],[],[],[],[],[],[... |
# MODULES AND LIBRARIES
'''
For this assignment, we will practice the use of imports to encrypt and decrypt messages.
The functions are already contained in the files. Your job is to use them to encrypt and decrypt strings. Good luck
'''
import encryption_key
import decode
import encode
#1 Decrypt this message us... |
import random
guesses_made = 0
name = input('Hey there! What is your name?\n')
number = random.randint(1, 100)
print('\nWell %s... I am thinking of a number between 1 and 100.\n' % name)
print('I want you to guess the number.')
print('You have 8 guesses\n')
while guesses_made < 9:
guess = int(input('Make a gues... |
from Objet.point import Point
import math
class Cercle(object):
def __init__(self, centre: Point, rayon: int):
self.centre = centre
self.rayon = rayon
def contient(self, p: Point):
if self.centre.distance(p) <= self.rayon:
return True
else:
return math.... |
import re
str1='abcd11gjgjgj789fjfjflj10jffjf34fkfkf45'
find=re.findall(r'[0-9]+',str1)
print(find)
str1='siddu bagewadi 9880890865 bijapur'
print(re.findall(r'[0-9]+',str1))
|
import re
text='siddu bagewadi Atharv1 bagewadi atharv surabhi bagewadi'
pattern=re.compile(r'siddu')
matches=pattern.match(text)
print(matches)
pattern=re.compile(r'atharv')
matches=pattern.search(text)
print(matches)
|
str = input("Enter a string:")
str = str.upper()
characters = []
vowels = 0
consonants = 0;
frequency = {}
for c in str:
characters.append(c)
for c in characters:
frequency[c] = characters.count(c)
if c in "aeiouAEIOU":
vowels +=1
if c not in "aeiouAEIOU" and c.isalpha():
consonants+=1
f... |
l = [1,2,3,4,5,6,7,8,9,4,5,3,7,7]
l.sort()
duplicate=[]
frequency={}
print("The second maximum number is:",l[-2])
for i in l:
if l.count(i) >1 and i not in duplicate:
duplicate.append(i)
frequency[i] = l.count(i)
print("The duplicate elements are:",duplicate)
freq_list = list(frequency.values())
freq_li... |
myList = ['a', 'b', 'a', 'c', 'd', 'a', 'd', 'z']
elementsInList = len(myList)
print(elementsInList) #Elements in list print
print(myList.count('d')) #Finds the index of the first 'd' in the array
myList.insert(4, 'a')
print(myList, "\n") #Adds another 'a' in front of the 'c'
#Import counter
from collections imp... |
# string = "test"
#
#
# def function_name(param=1, pa=1):
# return param + pa + 2
#
#
# ans = function_name(2, 2)
#
# print(ans)
#
#
# def hello_world_printer():
# print("hello world")
#
#
# hello_world_printer()
#
# def name_printer(param):
# print(param)
#
#
# name = input("enter your name.")
#
# name_pr... |
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
# 5. Write a program to
# (a) read a .csv file in a numpy array and
# (b) write a numpy array to a .csv file.
# (a)Saving a NumPy array... |
#input
l = ['magical unicorns',19,'hello',98.98,'world']
#output
"The list you entered is of mixed type"
"String: magical unicorns hello world"
"Sum: 117.98"
# # input
# 2 = [2,3,1,7,4,12]
# #output
# "The list you entered is of integer type"
# "Sum: 29"
def typeList(x):
newstr = ''
count = 0
for i in x:
if ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.