text stringlengths 37 1.41M |
|---|
'''
-----------------------------
EJERCICIO N°4
Más sobre listas
-----------------------------
Calcularemos la suma de todos los valores en la lista miLista
-----------------------------
'''
# MÉTODO 1
miLista = [10, 1, 8, 3, 5]
suma = 0
for i in range(len(miLista)):
suma += miLista[i]
print(suma)
'''
# MÉTODO ... |
from timeit import timeit
from typing import *
@timeit
def part1(inputValues: List[List[str]]) -> int:
return count_trees(inputValues, 1, 3)
# Right 1, down 1.
# Right 3, down 1.
# Right 5, down 1.
# Right 7, down 1.
# Right 1, down 2.
@timeit
def part2(inputValues: List[List[str]]) -> int:
return count_tre... |
"""
PROBLEM STATEMENT
-----------------
link: https://www.hackerrank.com/challenges/pangrams
"""
import sys
f = sys.stdin
s = f.readline().strip()
unique_chars = set()
for char in s:
unique_chars.add(char.lower())
for i in range(ord('a'), ord('z') + 1):
if not chr(i) in unique_chars:
print("not pan... |
"""
PROBLEM STATEMENT
------------------
Two kingdoms are at war. Kingdom 1 has N soldiers (numbered as 1 to N) and the war goes on for K days. Each day only one soldier from each kingdom fights.
Kingdom 1 can select one soldier from soldier number Ni to Nj. Ni and Nj are provided to you for each day.
Selection crite... |
height = float(input("please enter your height in meters \n"))
weight = float(input("please enter your weight in kg's \n"))
bmi = weight / (height ** 2)
bmi =round(bmi,2)
print("your bmi is " + str(bmi))
if(bmi<=18.5):
print("You are underweight")
elif(bmi<=25):
print("you have a norml weight")
elif(bmi<30):
... |
import random
def hard(random_number,attempt):
while attempt!=0:
user_input = int(input("please guess any input you think "))
if(user_input==random_number):
print("CONGRATULATION ! you have find the correct number🥳")
return
elif(random_number>user_input):
... |
# normal function
# def greet():
# print("hello")
# print("hello")
# print("world")
# greet()
# user input function
def greet_with_name(name):
print(f"you name is {name}")
print(f"how are you {name}")
print(f"whats up {name}?")
# greet_with_name("miku")
greet_with_name(input("enter your name"... |
def create_enemies():
i=3
enemies = ["alien","monsters","vampires"]
if i >5:
price =enemies[1]
print(f"enemies are {enemies[0]}")
print(price)
# print(price) |
# Keyword Method with iterrows()
# {new_key:new_value for (index, row) in df.iterrows()}
#TODO 1. Create a dictionary in this format:
# {"A": "Alfa", "B": "Bravo"}
#TODO 2. Create a list of the phonetic code words from a word that the user inputs.
import pandas
data = pandas.read_csv("E:\\python on udemy\\Day26\\na... |
you = input("Please eneter your name here : \n")
you = you.lower()
pat = input("Please eneter your partner name here : \n")
pat = pat.lower()
name = you + pat
print (name)
t= name.count("t")
r= name.count("r")
u= name.count("u")
e= name.count("e")
true = t+ r+ u+ e
l= name.count("l")
o= name.count("o")
v= name.count(... |
height = int(input("please enter your height in centimeter \n"))
bill=0
age = int(input("please enter your age \n"))
if(height>=120):
print("you can have a rollar coster ride")
if(age<12):
print("your ticket price is $7")
bill=7
elif(age<18):
print("your ticket price is $10")
... |
input1=[15,27,12]
def quick_sort(array):
if len(array) <= 1:
return array
pivot = array[0]
tail = array[1:]
left_side=[i for i in tail if i >= pivot]
right_side=[i for i in tail if i < pivot]
return quick_sort(left_side)+[pivot]+quick_sort(right_side)
print(quick_sort(input1)) |
"""
This module has functions associated with analyzing the geometry of a molecule.
It can be run as a script with an xyz file.
"""
import os
import argparse
import numpy
def open_xyz(xyz_filename):
"""
This function opens xyz file, separates the coordinates and the symbols and recasts the coordinates a... |
def main():
while True:
try:
x = int(input('Enter a positive number:\n'))
print(iter_fib(x))
break
except ValueError:
continue
def rec_fib(x):
"""Recursive implementation of Fibonacci's algorithm."""
if x < 0:
raise ValueError("Only po... |
name = input("What is your name? ")
print(name)
size_input = input("How big is your house is sqaure feet? ")
squareFeet = int(size_input)
squareMeters = squareFeet /10.8
print(f"The size of your house is {squareMeters:.2f} sq meters")
##The point .2f will format the syntax to two decimal places |
#A first class function just means that functions can be passed as arguments to functions.
def calculate(*values, operator):
return operator(*values)
def divide(dividend, divisor):
if divisor != 0:
return dividend / divisor
else:
return "You fool!"
##Passing the divide as the value of the ... |
import functools
user = {"username": "jose", "access_level": "admin"}
##This replaces line 20, now the get_admin_password is replaced by secure_function
##make_secure is the decarator while secure_function is just a function
def make_secure(func):
##Keeps the name of the original function (get_admin_secure)
@f... |
friends = {"Bob", "Rolf", "Anne"}
abroad = {"Bob", "Anne"}
##If building a one element set, put a comma after to show that it is not doing any math
localFriends = friends.difference(abroad)
##This takes the elements of abroad and subtracts them from the friends elements
localFriendsEXAMPLE = abroad.difference(friend... |
users = [
(0, "Bob", "password"),
(1, "Rolf", "bob123"),
(2, "Jose", "longp4assword"),
(3, "username", "1234"),
]
usernameMapping = {user[1]: user for user in users}
##This gets the username for user[1] and associating that name with the whole user tuple for each user
##The user name becomes the keys ... |
def max(x,y):
if x > y:
print(x)
elif y > x:
print(y)
max(5,6) |
#!/usr/bin/env python
"""
@author: camilla eldridge
"""
import sys
input_file=sys.argv[1]
output_file=sys.argv[2]
fasta_file=open(input_file, 'r')
fasta_lines=fasta_file.read().split('>')[0:]
unique_sequences=open(output_file,'w')
def remove_complete_duplicates(fasta_lines):
outputlist=[]
setofuniq... |
from scipy.integrate import simps
import random
import numpy as np
import matplotlib.pyplot as plt
def mysimps(y, x=None, dx=1, axis=-1):
'''
Integrate y(x) using samples along the given axis and the composite
Simpson's rule. This method needs at least 3 point, so if the number
of point is 2... |
student_score = list()
i = 1
print('請依序輸入五個人的成績')
while i < 6:
score = int(input('請輸入成績'))
student_score.append(score)
i = i + 1
print('所有輸入的成績',student_score)
print('平均分數是:', sum(student_score)/len(student_score))
print('最高分數是:', max (student_score))
print('最低分數是:', min (student_score))
|
#!/usr/bin/env python3
# Created by: Teddy Sannan
# Created on: November 2019
# This program takes user input
# and calculates the volume of a pyramid
def volume_caclculation(base, height):
# This function uses the input to calculate and print the answer
# process
volume = base ** 2 * height / 3
# o... |
alphabet = "abcdefghijklmnopqrstuvwxyz"
numbers = "1234567890"
print ("Encryption tool")
choice = input ("Encrypt, Decrypt or Quit: ")
if choice.lower() == "encrypt":
plaintext = input ('Enter Message: ')
cipher = ''
key = input ('Enter Key: ')
key = int (key)
for c in plaintext:
if c in alp... |
string1=input()
string2=input()
string2+=string2
if string1 in string2:
print('Yes')
else:
print('No') |
string1=input()
string2=input()
dic={}
for i in string1:
if i not in dic.keys():
dic[i]=1
else:
dic[i]+=1
for j in string2:
if j not in dic.keys():
print('Not permutation')
else:
dic[j]-=1
if max(dic.values())==0 and min(dic.values())==0:
print('permutated')
... |
#coding=utf-8
import os
import os.path
import sys
def test_movimiento_de_archivos(file_name, is_valid):
'''Chequea que el archivo pasado por parámetro sea pasado al directorio
correcto'''
if is_valid.upper() == "TRUE":
is_valid = True
else:
is_valid = False
if is_valid:
prefix = "procesados/procesadas/"
... |
import sqlite3
import pandas as pd
conn = sqlite3.connect('buddymove_holidayiq.sqlite3')
df = pd.read_csv('buddymove_holidayiq.csv')
df.columns = df.columns.str.replace(" ", "_")
curs = conn.cursor()
curs.execute('DROP TABLE review;')
df.to_sql('review', conn)
q1 = 'SELECT COUNT(*) FROM review'
rows = curs.execu... |
print("Програма, яка визначає чи є натуральне число, парним або закінчується число на 5 що ввів користувач")
num = int(input("Введіть ваше число = "))
if num == 0:
print("Ваше число дорівнює нулю")
elif num % 10 == 5:
print("Ваше число закінчується на 5")
elif num % 2 == 0:
print("Ваше число парне")
else:
... |
import csv
import pandas as pd
def main():
class_list = {
'car' : '1',
'bus' : '2',
'van' : '3',
'others' : '4',
}
column_name = ['class_name','id']
classes = ['car','bus','van','others']
class_list = []
for (i,item) in enumerate(classes):
value = (item, ... |
"""Animacion de la cola."""
class anCola(object):
"""docstring for anCola."""
def __init__(self, sup, us):
"""Intancia."""
super(anCola, self).__init__()
posInicial = [10, 400]
self.v = sup
self.usuario = us
self.cola = []
self.caja = crear_caja(4)
... |
class BestCourse:
# this is a class
website = 'www.cleverprogrammer.com' # tied directly to a class (not to any object)
def __init__(self,name):
self.name = name
python = BestCourse('Learn Python Programming')
math = BestCourse('Learn Basic Mathematics')
# python and math are both an object
... |
import io
import re
fname=input("enter filename:")
f=open(fname)
line=f.readline()
#print(line)
while line != "":
y = line[::-1]
print(y)
line= f.readline()
|
"""
Exercício 03
Preencha uma lista com 5 nomes de pessoas, informados pelo usuário.
a) Criar uma função que recebe como parâmetro de entrada a lista
e uma posição (índice) dessa lista e retorna o nome que
está nessa posição.
- Essa função deve gerar e tratar uma exceção do tipo
IndexError caso o índice não
exista na l... |
'''
简单要求:
自己写一个加密程序,能够加密的内容是英文和汉字。同时加密并且解密
就是说,一段话中既有中文又有英文,标点符号不用处理。
加密规则,获取ascii码数字,中间用|分割
# 思路提示:
print(ord("我"))
print(chr(25105))
扩展内容:自定义规则玩起来
规则:
加密:先将字符转化为ASCII码对应的十进制数,再针对不同的字符按照各个不同的公式的转化为不同的数据,加上类型进行存储
解密:根据不同类型及公式,进行反向转化
不足:
1、转化公式比较随机,没什么逻辑,其他人看... |
import math
import os
import random
import re
import sys
# Complete the staircase function below.
def staircase(n):
for i in range(0,n):
p=n-i-1
g=i+1
if p!=0:
p=n-i-2
print " "*p,
else:
pass
print "#"*g,
print "\n",
if __nam... |
class Solution:
def searchMatrix(self, matrix, target):
#edge case
if len(matrix)==0:
return False
m=len(matrix)
n=len(matrix[0])
i=0
j=n-1
#traversing through array
while i<m and j>=0:
#condition where target is found
... |
# 坐标
class Coordinate(object):
"""docstring for Coordition"""
def __init__(self, arg):
super(Coordition, self).__init__()
self.arg = arg
# 点
class Point(object):
"""docstring for Point"""
def __init__(self, arg):
super(Point, self).__init__()
self.arg = arg
# 线
class Line(object):
"""docstring for Line"... |
# 核酸
# 脱氧核糖核酸类 DNA
class DeoxyribonucleicAcid(object):
"""docstring for DeoxyribonucleicAcid"""
def __init__(self, name):
super(DeoxyribonucleicAcid, self).__init__()
self.name = name
# 核糖核酸类 RNA
class RibonucleicAcid(object):
"""docstring for RibonucleicAcid"""
def __init__(self, name):
super(RibonucleicAc... |
# Project 1
# Step 5
# Numerical Simulation Model
# Model.py
#
# Jessica Nordlund
# Faith Seely
#
##################################
# IMPORT STATEMENTS
##################################
import numpy as np
import matplotlib.pyplot as plt
import math
import time
# GLOBAL VARIABLES
#################################... |
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]
a = list(set(a))
b = list(set(b))
l = []
for i in a:
if i in b:
l.append(i)
print(list(set(l)))
|
import numpy as np
import matplotlib.pyplot as plt
from basic_linear_model import LinearModel
if __name__ == '__main__':
x_train = [0.04, 0.08, 0.12]
y_train = [0.2, 0.4, 0.6]
W = 1.0
weight_list = []
mse_list = []
linear_model = LinearModel(x_train, y_train)
for W in np.arange(0.01, 1.1,... |
# -*- coding: utf-8 -*-
"""
Parses csv files containing distances and scales and outputs JSON object file
"""
import pandas as pd
import numpy as np
def read_dist(filename):
"""
Reads distance from distance table produced by Arseny's script.
return: list containing lists (i.e. dist[0][3])
"""
f = open(filename, ... |
income = int(input('enter your income '))
costs = int(input('enter your costs '))
pure = income - costs
if income < costs:
print(f'income lower than costs by {pure}')
elif income > costs:
print(f'your pure income equals {pure}')
profitability = pure / income
print(f'your profitability = {profitability:.... |
with open('num3_file_L5.txt', 'r', encoding='utf-8') as file:
average_salary = 0
names_salary = file.readlines()
print('names whose salaries are less than 20 thousand:')
for i in names_salary:
average_salary += int(i.split()[1])
if int(i.split()[1]) < 20000:
print(i.split()[0... |
class Car:
def __init__(self, speed, color, name, is_police=False):
self.speed = speed
self.color = color
self.name = name
self.is_police = is_police
def show_speed(self):
return self.speed
def go(self):
print('start key')
def stop(self):
print... |
# 6. Реализовать два небольших скрипта:
# а) итератор, генерирующий целые числа, начиная с указанного,
# б) итератор, повторяющий элементы некоторого списка, определенного заранее.
# Подсказка: использовать функцию count() и cycle() модуля itertools.
# lastОбратите внимание, что создаваемый цикл не должен быть бесконе... |
#!/user/bin/env python
# -*- coding: utf-8 -*-
# @property 的使用
class Student(object):
@property
def score(self):
return self.__score
@score.setter
def score(self, value):
if(0 < value < 100):
self.__score = value
else :
raise ValueError("score must between 0~100")
lix = Student()
lix.score = 90
# l... |
"""16 - Faça um algoritmo que leia os valores de COMPRIMENTO, LARGURA e ALTURA e apresente
o valor do volume de uma caixa retangular. Utilize para o cálculo a fórmula VOLUME = COMPRIMENTO * LARGURA * ALTURA."""
def volume(comprimento, largura, altura):
print('O volume é {:.2f}'.format(comprimento * largura * altur... |
"""5 - Ler um valor e escrever se é positivo ou negativo (considere o valor zero como positivo), se é par ou ímpar"""
def par_ou_impar(numero):
if numero % 2 == 0:
print('Par!')
else:
print('Impar!')
def positivo_ou_negativo(numero):
if numero >= 0:
print('Positivo!')
else:
... |
"""4 - Faça um programa que receba um valor que é o valor pago, um segundo valor que é o preço do produto e
retorne o troco a ser dado. (modifique para receber um valor de desconto e subtraia do valor do produto)"""
while True:
try:
valor_pago = float(input('Digite o valor pago: '))
if valor_pago >... |
from Imovel import Imoveis
class Menu:
imovel = Imoveis()
while True:
print('----------------Imobiliária Tabajara----------------\n'
'1 - Adicionar imóvel\n'
'2 - Listar imóvel\n'
'3 - Listar todos os imóveis\n'
'4 - Alterar imóvel\n'
... |
"""6 - Faça um algoritmo que leia um nº inteiro e mostre uma mensagem indicando se este número é par ou ímpar, e se é positivo ou negativo"""
def par_ou_impar(numero):
if numero % 2 == 0:
print('Par!')
else:
print('Impar!')
def positivo_ou_negativo(numero):
if numero >= 0:
print('... |
def compare_strings(string1, string2):
if not isinstance(string1, str) or not isinstance(string2, str):
return 0
elif string1 == string2:
return 1
elif len(string1) > len(string2):
return 2
elif string2 == 'learn':
return 3
cs = compare_strings('11231313','le... |
# Make a class LatLon that can be passed parameters `lat` and `lon` to the
# constructor
# YOUR CODE HERE
class LatLon:
def __init__(self, lat, lon):
self.lat = lat
self.lon = lon
# class Robot:
# def __init__(self, name, color, weight): # constructor function syntax in python. We still need ... |
def steps(array):
if len(array) == 0:
return 0
pivot = array[0]
count = 0
lesser = []
greater = []
for element in array:
count += 1
if element < pivot:
lesser.append(element)
elif element > pivot:
greater.append(element)
return count + steps(lesser) + steps(greater)
a=list(map(int, input().split()... |
n=int(input())
a=[list(map(int, input().split())) for _ in range(n)]
if any(a[i][0]!=a[i][1] for i in range(n)):
print('rated')
elif a==list(reversed(sorted(a))):
print('maybe')
else:
print('unrated')
|
import RPi.GPIO as GPIO #Add the GPIO library to a Python sketch
import time #Add the time library to a Python sketch
def clearLED():
GPIO.output(8,GPIO.LOW) #Set LED pin 8 to LOW
GPIO.output(10,GPIO. LOW) #Set LED pin 10 to LOW
GPIO.output(12,GPIO. LOW) #Set LED pin 12 to LOW
GPIO.output(16,GPIO. LOW) #Set L... |
# 890457906
# Alexander Sigler
# Question 2
class Student:
def __init__(self, firstname, lastname):
self._firstName = firstname # Assign instance variable
self._lastName = lastname # Assign instance variable
self.compareKey = '_firstName' # Default value for compare
def ... |
import random
def bubblesort(data):
for index in range(len(data) - 1):
swap = False
for index2 in range (len(data) - index - 1):
if data[index2] > data[index2 + 1]:
data[index2], data[index2 + 1] = data[index2 + 1], data[index2]
swap = True
if sw... |
import tkinter
import re
import tkinter.messagebox
Calculator=tkinter.Tk()
Calculator.title("Calculator")
#The size of the window
Calculator.geometry("400x400+0+0")
#Do not let the user to change the size of the page
Calculator.resizable(False,False)
'''Label'''
#Add a entry to our window and set it to ... |
print('Sample assignment')
#定义一个 元组(不可变的,不可以编辑或更改元组,即不可修改元素的内容)
shoplist=['apple','mango','carrot','banana']
#mylist 只是指向同一对象的另一种名称
mylist=shoplist
del shoplist[0]
print('shoplist is',shoplist)
print('mylist is',mylist)
#shoplist 和 mylist 输出了同样的结果,因此我们确认它们指向的是同一个对象
print('Copy by making a full slice')
mylist=shop... |
def powersum(power,*args):
''' Return the sum of each raised to the specified power.'''
total=0
for i in args:
total+=pow(i,power)
return total
print(powersum(2,3,4)) |
#print 总是会以一个不可见的“新一行”字符( \n )结尾
age=20
name='kyle'
print('{0} was {1} years old when he wrote this book'.format(name,age))
print('Why is {0} playing that python?'.format(name))
print('{} was {} years old when he wrote this book'.format(name,age))
print('Why is {} playing that python?'.format(name))
#对于浮点数 '0.333' ... |
# 通过算法判断,打印1900到2100间(包括1900和2100)的所有闰年
years = range(1900, 2101, 1)
def is_leap_year(year):
''' 判断一个年份是否为闰年
year 代表一个正确的年份
年份是4的倍数而不是100的倍数的年份是闰年
年份是400的倍数的年份是闰年。
'''
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
return True
else:
return False
for year in ... |
# textentrydialog.py
# Simple dialog for entering a string.
# Note: Not based on wxPython's TextEntryDialog.
from dialog import Dialog
from textbox import TextBox
from label import Label
from keys import keys
class TextEntryDialog(Dialog):
def __init__(self, parent, title="Enter some text", prompt="Enter some te... |
import pandas
def read_csv(path, columns=None):
df = pandas.read_csv(path, sep=";", usecols=columns)
return df
def sort_dates(sequence) -> dict:
res = {}
for (key, value) in sorted(sequence.items()):
res[key] = value
return res
def filter_on_threshold(sequences, threshold) -> dict:
res = {}
for ... |
'''
Created on 22 Mar 2018
@author: olaska
'''
import pandas as pd
import csv
import json
import requests
#DataFrame is created from file get from url
df=pd.read_json('url.someaddress')
#this allow to change name columns from original file
df.columns=['col_1','col_2','col_3','etc']
#DataFrame transformed into csv fil... |
bill = float(input("How much is the bill?"))
service = input("How was the service: GOOD, FAIR, BAD?").upper()
guests = int(input("How many people?"))
goodtip = float(.20 * bill)
fairtip = float(.15 * bill)
badtip = float(.10 * bill)
goodtotal = float(goodtip + bill)
fairtotal = float(fairtip + bill)
badtotal = float(b... |
# user input for box size
#number = 4
#for n in range(0,4):
# print("*" * number)
# user input border box
#num1 = int(input("How big is the box?"))
width = int(input('Width? '))
height = int(input('Height? '))
# draw the top border
print('*' * width)
print("*" * height)
|
dog_age = int(input("Input dog's age: ")) # Do not change this line
begin_human_age = 15
if dog_age == 1:
print("Human age: ", begin_human_age)
if dog_age == 2:
human_age=begin_human_age+9
print("Human age: ",human_age)
if dog_age >= 3 and dog_age <= 16:
human_age_2 = (begin_human_age)+((4*dog_age)... |
quiz = (input("Input f|a|b (fibonacci, abundant or both): "))
if quiz == "f":
length = int(input("Input the length of the sequence: "))
a = 0
b = 1
print("Fibonacci Sequence:")
print("-------------------")
print(a)
print(b)
for i in range (2,length):
c = a + b
... |
#
# [1] Two Sum
#
# https://leetcode.com/problems/two-sum/description/
#
# algorithms
# Easy (38.94%)
# Total Accepted: 1.1M
# Total Submissions: 2.9M
# Testcase Example: '[2,7,11,15]\n9'
#
# Given an array of integers, return indices of the two numbers such that they
# add up to a specific target.
#
# You may assume... |
def factorial(number):
if not isinstance(number,int):
raise TypeError("numara sayi değil")
if not number >= 0:
raise ValueError("sayi 0 dan küçük olmamalı")
def inner_factorial(number):
if number <= 1:
return 1
return number * inner_factorial(number-1)
ret... |
# -*- coding: utf-8 -*-
### first count all aa base number, then caculate average sequence number ###
filein = open("psc_cluster_file_sorted/ortholog_sorted341.fasta", "r")
dic, k, v = {}, '', []
for i in filein:
if i.startswith('>'):
dic[k] = v
k = i[1:-1]
v = []
els... |
import db
class Recipe(object):
recipeCnt = 0
def __init__(self,name,ingredients):
self.Name = name.lower()
self.Ingredients = ingredients
Recipe.recipeCnt += 1
def display_count(self):
print "Recipe Count: ", Recipe.recipeCnt
def need_ingredients(self):
print "SELF.IN: ",self.Ingredients
missing = ... |
#!/usr/bin/env python
# coding: utf-8
# In[22]:
H,W = input("縦の長さと横の長さを入力してください").split()
H=int(H)
W=int(W)
if(3<= H <= 300 and 3<= W <= 300):
for y in range(H):
y+=1
x=0
for x in range (W):
x+=1
if(y==1 or x==1 or y==H or x==W):
print("#",end ="")
... |
#!/usr/bin/env python
# coding: utf-8
# In[8]:
s=str(input())
p=str(input())
a=0
if(1<=len(p)<=len(s)<=100):
a = set(s) & set(p)
if(a!=0):
print("Yes")
else:
print("No")
# In[ ]:
|
# Create a list called instructors
instructors = []
# Add the following strings to the instructors list
# "Colt"
# "Blue"
# "Lisa"
instructors.append("Colt")
instructors.append("Blue")
instructors.append("Lisa")
# Remove the last value in the list
instructors.pop()
# Remove the first value in the list
instr... |
num = input("How many times do I have to tell you: ")
phrase = "Clean your room!"
if num:
times = int(num)
for x in range(times):
print(phrase.upper())
|
'''
kombucha_song = make_song(5, "kombucha")
next(kombucha_song) # '5 bottles of kombucha on the wall.'
next(kombucha_song) # '4 bottles of kombucha on the wall.'
next(kombucha_song) # '3 bottles of kombucha on the wall.'
next(kombucha_song) # '2 bottles of kombucha on the wall.'
next(kombucha_song) # 'Only 1 bottle of... |
# flesh out intersection pleaseeeee
def intersection(list1, list2):
return list(set(list1) & set(list2))
print(intersection([1, 2, 3], [2, 3, 4])) # [2, 3]
print(intersection(['a', 'b', 'z'], ['x', 'y', 'z'])) # ['z']
|
'''
Exercise Involving Closures
Write a function called letter_counter which accepts a string and returns a function. When the inner function is invoked it should accept
a parameter which is a letter, and the inner function should return the number of times that letter appears. This inner function should be
case ins... |
'''
This is another trickier exercise. Don't feel bad if you get stuck or need to move on and come back later on!
Write a function called mode. This function accepts a list of numbers and returns the most frequent number in the list of numbers.
You can assume that the mode will be unique.
mode([2,4,1,2,3,3,4,4,5,4,... |
'''
sevens = get_unlimited_multiples(7)
[next(sevens) for i in range(15)]
# [7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98, 105]
ones = get_unlimited_multiples()
[next(ones) for i in range(20)]
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
'''
def get_unlimited_multiples(num=1):
... |
'''
list_check([[],[1],[2,3], (1,2)]) # False
list_check([1, True, [],[1],[2,3]]) # False
list_check([[],[1],[2,3]]) # True
'''
def list_check(input_list):
for i in input_list:
if type(i) != list:
return False
return True
print(list_check([[],[1],[2,3], (1,2)])) # False
print(list_check([1... |
'''
Write a function called min_max_key_in_dictionary which returns a list with the lowest key in the dictionary and the highest key in the
dictionary. You can assume that the dictionary will have keys that are numbers.
min_max_key_in_dictionary({2:'a', 7:'b', 1:'c',10:'d',4:'e'}) # [1,10]
min_max_key_in_dictionary... |
print("Hey, how's it going?")
msg = ""
while "you win" not in msg.lower():
msg = input()
print(msg)
print("HA HA, I Win!")
|
'''
Write a function called truncate that will shorten a string to a specified length, and add "..." to the end. Given a string and a number
n, truncate the string to a shorter string containing at most n characters. For example, truncate("long string", 5) should return a 5
character truncated version of "long strin... |
'''
SOLUTION: mode
Mode Solution
This is another trickier exercise. Don't feel bad if you were unable to complete it!
I start by defining the function, which accepts a single argument we'll call collection .
Next, I create a new dictionary that maps items in the collection to the number of times they appear in the c... |
Quicksort_test.py
import timeit
def test1(array=["Xavier","Galarza","Henny"]):
less = []
equal = []
greater = []
if len(array) > 1:
pivot = array[0]
for x in array:
if x < pivot:
less.append(x)
elif x == pivot:
equ... |
# * Matching and Extracting Data
# import re
# x = 'My 2 favorite numbers are 19 and 42'
# y = re.findall('[0-9]+', x)
# print(y)
# y = re.findall('[AEIOU]+', x)
# print(y)
# * Warning: Greedy MAtching
# import re
# x = 'From: Using the : character'
# y = re.findall('^F.+:', x)
# print(y)
# * Non-Greddy Matching
# i... |
# * Counting Pattern
# counts = dict()
# print('Enter a line of text:')
# line = input('')
# words = line.split()
# print('Words:', words)
# print('Counting...')
# for word in words:
# counts[word] = counts.get(word, 0) + 1
# print('Counts', counts)
# * Define Loops and Dictionaries
# counts = {'chuck': 1, 'fr... |
# * Best Friends: Strings and Lists
# abc = 'With three words'
# stuff = abc.split()
# print(stuff)
# print(len(stuff))
# print(stuff[0])
# print(stuff)
# for w in stuff:
# print(w)
# * Split
# line = 'A lot of Spaces'
# etc = line.split()
# print(etc)
# line = 'first;second;third'
# thing = line.... |
# * While loop
n = 5
while n > 0:
print(n)
n = n - 1
print('Blastoff')
print(n)
# ! An Infinite Loop
# n = 5
# while n > 0:
# print('Lather')
# print('Rinse')
# print('Dry off')
# * Breaking Out of a Loop
# while True:
# line = input('> ')
# if line == 'done':
# break
# print(line... |
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
re... |
#定义空字符串
s=""
if s:
print("s 不是空字符串")
else:
print("s 是空字符串")
#定义空列表
my_list = []
if my_list:
print("my_list 不是空列表")
else:
print("my_list 是空列表")
#定义空字典
my_dict = {}
if my_dict:
print("my_dict 不是空字典")
else:
print("my_dict 是空字典")
my_set = {}
print(type(my_set)) |
#去除重复的字符串
s = input("输入n个字符串,用逗号分隔:")
lists = list((s.split(",")))
print(lists)
newdict = {}
for item in lists:
newdict[item] = item
klist = list(newdict.keys())
print(klist)
#print(dict(lists))
|
def fn(a:int,b:bool,c:str='hello')->int:
'''这是一个文档示例--函数 返回值 int fn()->int
函数参数:
a:作用 类型 int 不是强制,主要用于说明int
b:作用 类型 bool
c:作用 类型 str 默认 hello
'''
return 10
print(fn.__doc__) #只输出说明的部分没有help函数的返回来的详细
#help(fn)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.