text stringlengths 37 1.41M |
|---|
import datetime
int1 = input("What is your current age?")
int2 = input("At what age do you want to retire?")
age = int(int1)
retirement = int(int2)
year = str(datetime.datetime.now().year)
current_year = int(year)
retirement_year = retirement - age
year_of_retirement = current_year + retirement_year
print("You have " + str(retirement_year) + " years until you can retire.")
print("It's " + str(current_year) + ", you can retire in " + str(year_of_retirement)) |
def is_anagram():
word1 = []
word2 = []
print("Enter two words and I'll tell you if they are anagrams:\n")
string1 = input("Enter the first word: \n")
string2 = input("Enter the second word:\n")
# if (string1 == string2):
# print("You have entered the same word trice. Try again.")
# elif (sorted(string1) == sorted(string2)):
# print(string1 + " and " + string2 + " are anagrams.")
# else:
# print("These two words are not anagrams.")
for x in range(len(string1)):
word1.append(string1[x])
for x in range(len(string2)):
word2.append(string2[x])
if(len(word1) == len(word2)):
for letter in word1:
if(letter in word2):
word2.remove(letter)
if (len(word2) == 0):
print(string1 + " and " + string2 + " are anagrams.")
else:
print(string1 + " and " + string2 + " are not anagrams.")
is_anagram() |
#!/usr/bin/python3
def func():
t = int(input())
while t:
t -= 1
input()
a = set(list(map(int, input().split())))
input()
b = set(list(map(int, input().split())))
print("False") if a-b else print("True")
if __name__ == '__main__':
func()
|
class Fractal(object):
def __init__(self, epsilon=0):
pass
def __str__(self):
pass
@staticmethod
def CALCULATE(pos, max_iterations):
x,y = pos
iteration = 0
Z = complex(0, 0)
C = complex(float(x),float(y))
while abs(Z) < 2.0 and iteration < max_iterations:
Z = Z * Z + C
iteration += 1
return iteration
if __name__ == "__main__":
print Fractal.CALCULATE((1,1), 30)
|
#generating a fibonacci seq
from typing import Any, Union
fib = 1
pfib = 0
ppfib = 0
count = 1
while len(str(fib)) < 1000:
count += 1
print(fib)
ppfib = pfib
pfib = fib
fib = pfib + ppfib
print(count)
|
import math
def is_prime(n): # function for if a num is prime
if n <= 1:
return False
max_div = math.floor(math.sqrt(n))
for i in range(2, 1 + max_div):
if n % i == 0:
return False
return True
count = 0
run = True
while run:
for i in range(0,100000000,1):
if is_prime(i) == True:
count += 1
if count == 10001:
print(i)
run = False
else:
continue
|
def find_anagrams(dictionary):
sorted_string_to_anagram = collections.defaultdict(list)
for s in dictionary:
sorted_string_to_anagram[''.join(sorted(s))].append(s)
return [group for group in sorted_string_to_anagram.values() if len(group) >= 2]
|
import streamlit as st
import requests
import json
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
import numpy as np
import modules as md
githublink = '[GitHub Repo](https://github.com/himanshu004/World-Football-Leagues-Dashboard)'
st.sidebar.write('Contribute here: ' + githublink)
st.title('World Football Leagues Dashboard')
st.sidebar.title('Widget Section')
apilink = '[Football Data](https://www.football-data.org/)'
with st.sidebar.beta_expander('About the project'):
st.write('The idea behind this project was motivated by my love for football and curiosity for stats. This project uses RESTful API provided by ',apilink,' which provides football data and statistics (live scores, fixtures, tables, squads, lineups/subs, etc.) in a machine-readable way.')
st.write('Want to contribute?',githublink)
data1 = md.fetch_data1()
area_dict = {}
comp_dict = {}
for i in range(len(data1['competitions'])):
area_dict[data1['competitions'][i]['area']['name']] = 0
comp_dict[data1['competitions'][i]['name']] = 0
for i in range(len(data1['competitions'])):
area_dict[data1['competitions'][i]['area']['name']] += 1
comp_dict[data1['competitions'][i]['name']] += 1
area_df = pd.DataFrame(area_dict.items(), columns=['Country Name', 'Count'])
comp_df = pd.DataFrame(comp_dict.items(), columns=['League Name','Count'])
newwc = st.sidebar.button('New Wordcloud!',key = 1,)
newwc = True
if(newwc):
words = ' '.join(comp_df['League Name'])
wordcloud = WordCloud(stopwords = STOPWORDS, background_color = 'white',width = 820, height = 410).generate(words)
plt.imshow(wordcloud)
st.set_option('deprecation.showPyplotGlobalUse', False)
plt.xticks([])
plt.yticks([])
sns.despine(left = True,bottom = True)
st.pyplot()
newwc = False
st.sidebar.header('General Stats:\n')
show_comp_stats = st.sidebar.checkbox('Country Wise Distribution',key = 1)
if(show_comp_stats):
st.header('Number Of Competitions Per Country:\n')
chosen_nations = st.sidebar.multiselect('Choose Country',area_df['Country Name'],key = 1)
if(len(chosen_nations) == 0):
st.write('Choose a country..')
else:
sub_area_df = area_df[area_df['Country Name'].isin(chosen_nations)].reset_index().drop(['index'],axis = 1)
sub_area_df.index = range(1,len(sub_area_df) + 1)
st.table(sub_area_df)
st.write('\n')
if(sub_area_df.shape[0] != 0):
sns.set_style('whitegrid')
params = {'legend.fontsize': 18,
'figure.figsize': (20, 8),
'axes.labelsize': 22,
'axes.titlesize': 22,
'xtick.labelsize': 22,
'ytick.labelsize': 22,
'figure.titlesize': 22}
plt.rcParams.update(params)
fig, ax = plt.subplots()
ax = sns.barplot(data = sub_area_df,x = 'Country Name',y = 'Count')
if(len(sub_area_df) > 5):
plt.xticks(rotation = 60)
if(len(sub_area_df) > 10):
plt.xticks(rotation = 90)
sns.despine(left = True)
st.pyplot(fig)
show_leagues_per_continent = st.sidebar.checkbox('Football Leagues By Continent',key = 2)
continents = ['Europe','Asia','Africa','North America','South America','Australia']
if(show_leagues_per_continent):
choice = st.sidebar.selectbox('Choose Continent',continents,key = 2,)
write = choice + '\'s football leagues: '
st.header(write + '\n')
md.leaguesDisplay(choice,data1)
show_leagues_per_country = st.sidebar.checkbox('Football Leagues By Country',key = 3)
if(show_leagues_per_country):
helper = list(area_df[~area_df['Country Name'].isin(continents)]['Country Name'])
choice = st.sidebar.selectbox('Choose Country',helper,key = 3,)
write = choice + '\'s football leagues: '
st.header(write + '\n')
md.leaguesDisplay(choice,data1)
st.sidebar.header('Competitions Stats:')
comp_dict = {}
free_tier_list = ['Serie A','Premier','UEFA Champions','European','Ligue 1','Bundesliga','Eridivisie','Primeira Liga','Primera Division','FIFA World Cup']
for i in range(len(data1['competitions'])):
if(data1['competitions'][i]['name'] not in free_tier_list):
continue
comp_dict[data1['competitions'][i]['name']] = data1['competitions'][i]['id']
default = 'Select a Competition'
options = [default]
options = options + list(comp_dict.keys())
svalue = st.sidebar.selectbox('',options,key = 4)
if(svalue != default):
st.title(svalue)
if(st.sidebar.checkbox('Team Info')):
data2 = md.fetch_data2("teams",comp_dict,svalue)
st.header('Number of teams: ' + str(data2['count']))
col1, col2 = st.beta_columns(2)
if(len(data2['teams'])):
for i in range(len(data2['teams'])):
if(i % 2):
col1.subheader(data2['teams'][i]['name'])
if('address' in data2['teams'][i].keys()):
col1.write('Address: ' + data2['teams'][i]['address'])
if('phone' in data2['teams'][i].keys()):
if(data2['teams'][i]['phone'] != None):
col1.write('Phone: ' + (data2['teams'][i]['phone']))
if('website' in data2['teams'][i].keys()):
col1.write('Website: ' + data2['teams'][i]['website'])
if('email' in data2['teams'][i].keys()):
if(data2['teams'][i]['email'] != None):
col1.write('Email: ' + data2['teams'][i]['email'])
if('founded' in data2['teams'][i].keys()):
col1.write('Founded in ' + str(data2['teams'][i]['founded']))
if('venue' in data2['teams'][i].keys()):
if(data2['teams'][i]['venue'] != None):
col1.write('Venue: ' + data2['teams'][i]['venue'])
else:
col2.subheader(data2['teams'][i]['name'])
if('address' in data2['teams'][i].keys()):
col2.write('Address: ' + data2['teams'][i]['address'])
if('phone' in data2['teams'][i].keys()):
if(data2['teams'][i]['phone'] != None):
col2.write('Phone: ' + (data2['teams'][i]['phone']))
if('website' in data2['teams'][i].keys()):
col2.write('Website: ' + data2['teams'][i]['website'])
if('email' in data2['teams'][i].keys()):
if(data2['teams'][i]['email'] != None):
col2.write('Email: ' + data2['teams'][i]['email'])
if('founded' in data2['teams'][i].keys()):
col2.write('Founded in ' + str(data2['teams'][i]['founded']))
if('venue' in data2['teams'][i].keys()):
if(data2['teams'][i]['venue'] != None):
col2.write('Venue: ' + data2['teams'][i]['venue'])
if(st.sidebar.checkbox('Standings')):
st.header('Standings: ')
data2 = md.fetch_data2("standings",comp_dict,svalue)
if(svalue != 'FIFA World Cup'):
type = st.sidebar.radio('',['Total','Home','Away'])
if(type == 'Total'):
df = pd.DataFrame()
for i in range(len(data2['standings'][0]['table'])):
list = []
list.append(data2['standings'][0]['table'][i]['position'])
list.append(data2['standings'][0]['table'][i]['team']['name'])
list.append(data2['standings'][0]['table'][i]['playedGames'])
list.append(data2['standings'][0]['table'][i]['form'])
list.append(data2['standings'][0]['table'][i]['won'])
list.append(data2['standings'][0]['table'][i]['lost'])
list.append(data2['standings'][0]['table'][i]['points'])
list.append(data2['standings'][0]['table'][i]['goalsFor'])
list.append(data2['standings'][0]['table'][i]['goalsAgainst'])
list.append(data2['standings'][0]['table'][i]['goalDifference'])
df = df.append(pd.Series(list),ignore_index = True)
elif(type == 'Home'):
df = pd.DataFrame()
for i in range(len(data2['standings'][1]['table'])):
list = []
list.append(data2['standings'][1]['table'][i]['position'])
list.append(data2['standings'][1]['table'][i]['team']['name'])
list.append(data2['standings'][1]['table'][i]['playedGames'])
list.append(data2['standings'][1]['table'][i]['form'])
list.append(data2['standings'][1]['table'][i]['won'])
list.append(data2['standings'][1]['table'][i]['lost'])
list.append(data2['standings'][1]['table'][i]['points'])
list.append(data2['standings'][1]['table'][i]['goalsFor'])
list.append(data2['standings'][1]['table'][i]['goalsAgainst'])
list.append(data2['standings'][1]['table'][i]['goalDifference'])
df = df.append(pd.Series(list),ignore_index = True)
else:
df = pd.DataFrame()
for i in range(len(data2['standings'][2]['table'])):
list = []
list.append(data2['standings'][2]['table'][i]['position'])
list.append(data2['standings'][2]['table'][i]['team']['name'])
list.append(data2['standings'][2]['table'][i]['playedGames'])
list.append(data2['standings'][2]['table'][i]['form'])
list.append(data2['standings'][2]['table'][i]['won'])
list.append(data2['standings'][2]['table'][i]['lost'])
list.append(data2['standings'][2]['table'][i]['points'])
list.append(data2['standings'][2]['table'][i]['goalsFor'])
list.append(data2['standings'][2]['table'][i]['goalsAgainst'])
list.append(data2['standings'][2]['table'][i]['goalDifference'])
df = df.append(pd.Series(list),ignore_index = True)
df.drop([0],axis = 1,inplace = True)
df.columns = ['Team Name','Matches Played','Last 5 Matches','Won','Lost','Points','Goals For','Goals Against','Difference']
df.index = range(1,len(df) + 1)
st.table(df)
else:
for j in range(0,len(data2['standings']),3):
df = pd.DataFrame()
for i in range(len(data2['standings'][j]['table'])):
list = []
list.append(data2['standings'][j]['table'][i]['position'])
list.append(data2['standings'][j]['table'][i]['team']['name'])
list.append(data2['standings'][j]['table'][i]['playedGames'])
list.append(data2['standings'][j]['table'][i]['form'])
list.append(data2['standings'][j]['table'][i]['won'])
list.append(data2['standings'][j]['table'][i]['lost'])
list.append(data2['standings'][j]['table'][i]['points'])
list.append(data2['standings'][j]['table'][i]['goalsFor'])
list.append(data2['standings'][j]['table'][i]['goalsAgainst'])
list.append(data2['standings'][j]['table'][i]['goalDifference'])
df = df.append(pd.Series(list),ignore_index = True)
st.subheader(data2['standings'][j]['group'])
df.drop([0],axis = 1,inplace = True)
df.columns = ['Team Name','Matches Played','Last 5 Matches','Won','Lost','Points','Goals For','Goals Against','Difference']
df.index = range(1,len(df) + 1)
st.table(df)
if(st.sidebar.checkbox('Scorers')):
data2 = md.fetch_data2('scorers',comp_dict,svalue)
st.subheader('Top 10 Scorers:')
df = pd.DataFrame()
for i in range(len(data2['scorers'])):
list = []
list.append(data2['scorers'][i]['player']['name'])
list.append(data2['scorers'][i]['player']['nationality'])
list.append(data2['scorers'][i]['player']['position'])
list.append(data2['scorers'][i]['team']['name'])
list.append(data2['scorers'][i]['numberOfGoals'])
df = df.append(pd.Series(list),ignore_index = True)
df.index = range(1,len(df) + 1)
df.columns = ['Name','Nationality','Position','Team','Number of Goals']
st.table(df)
st.sidebar.header('Player Stats:')
st.sidebar.write('Coming soooon!!')
|
#Option 4: PyParagraph for Homework 3
#In this challenge, you get to play the role of chief linguist at a local learning academy.
# As chief linguist, you are responsible for assessing the complexity of various passages
# of writing, ranging from the sophomoric Twilight novel to the nauseatingly high-minded
# research article. Having read so many passages, you've since come up with a fairly simple
# set of metrics for assessing complexity.
#Your task is to create a Python script to automate the analysis of any such passage using
# these metrics. Your script will need to do the following:
##Import a text file filled with a paragraph of your choosing.
##Assess the passage for each of the following:
##Approximate word count
##Approximate sentence count
##Approximate letter count (per word)
##Average sentence length (in words)
import re
##reads the text file to one long string
def read_text_file(paragraph_text_file):
user_txt_file_path = "raw_data\\{}".format(paragraph_text_file)
print(user_txt_file_path)
with open(user_txt_file_path, 'r') as f:
paragraph_string = f.read()
##clean up the paragraph string so reads better with later scripts
clean_paragraph_string = paragraph_string.replace("\n\n", " ") #take out any double returns
clean_paragraph_string = paragraph_string.replace("\n", " ") #take out any single returns
clean_paragraph_string = clean_paragraph_string.strip() #take out any trailing or leading spaces on paragraph string
clean_paragraph_string = clean_paragraph_string.replace(" ", " ") #take out an double spaces
#print(clean_paragraph_string) #temporary check
return clean_paragraph_string
##makes calculations on paragraph string for word count, sentence count, letter count, avg sent length
##and prints results to terminal
def paragraph_metrics_terminal(clean_paragraph_string):
##word count and count letters per word avg
words = clean_paragraph_string.split(" ")
#print(words) #temporary check
word_count = len(words)
letters_per_word = [len(word) for word in words] #this is slightly off as will count punctuation
avg_letters_per_word = sum(letters_per_word)/len(letters_per_word)
##sentence count and avg sentence word length
sentences = re.split("\.|\?|!", clean_paragraph_string) #note this does add a sentence if someone has abbrevation Anne V. Coates
sentences.remove('') #remove blank sentence that re.split seems to put at the end
#print(sentences) #temporary check
words_in_sentence = [sentence.split() for sentence in sentences]
#print(words_in_sentence) #temporary check
number_words_in_sentence = [len(row) for row in words_in_sentence]
avg_words_per_sentence = sum(number_words_in_sentence)/len(number_words_in_sentence)
sentence_count = len(sentences)
##print results to terminal(word_count, sentence_count, avg_letters_per_word, avg_words_per_sentence) #temporary check
print("\nParagraph Analysis \n--------------------------")
print("Approximate Word Count: {}".format(word_count))
print("Approximate Sentence Count: {}".format(sentence_count))
print("Approximate Average Letters per Word: {}".format(round(avg_letters_per_word, 1)))
print("Approximate Average Words per Sentence: {}\n\n".format(round(avg_words_per_sentence, 1)))
#this is the main function that references all other functions
#make sure the .txt file is saved to the subfolder raw_data
def main(paragraph_text_file):
paragraph_text_string = read_text_file(paragraph_text_file)
paragraph_metrics_terminal(paragraph_text_string)
##RUN THE ACTUAL PARAGRAPH FILES PROVIDED##
main("paragraph_1.txt")
main("paragraph_2.txt") |
# # Задача 1.Найти площадь и периметр прямоугольного треугольника по двум заданным катетам.
# import math
#
# a = input("Длина первого катета: ")
# b = input("Длина второго катета: ")
#
# a = float(a)
# b = float(b)
#
# c = math.sqrt(a**2 + b**2)
#
# s = (a*b)/2
# p = a + b + c
# #
# print("Площадь треугольника:" + str(s))
# print("Периметр треугольника:"+ str(p))
#
# # Задача2. Найти максимальное число из трех
# # Вводятся три целых числа. Определить какое из них наибольшее.
#
# a = int(input("Введите первое число: "))
# b = int(input("Введите второе число: "))
# m = int(input("Введите третье число: "))
#
# n = a
# if n < b:
# n = b
# if n < m:
# n = m
# print("Наибольшее число:", n)
#
# # Задача 3.Найти площадь прямоугольника, треугольника или круга
# # В зависимости от того, что выберет пользователь, вычислить площадь либо прямоугольника, либо треугольника, либо круга.
# # Если выбраны прямоугольник или треугольник, то надо запросить длины сторон, если круг, то его радиус.
# import math
# choiсe = input("Сделайте выбор: 1 - прямоугольник, 2 - треугольник , 3 - круг - ")
# if choiсe == '1':
# a = int(input("Введите длину стороны a: "))
# b = int(input("Введите длину стороны b: "))
# print("Площадь прямоугольника равна", a*b)
#
# elif choiсe == '2':
# c = int(input("Введите длину одного катета: "))
# d = int(input("Введите длину второго катета: "))
# g = int(input("Введите длину гипотенузы: "))
# p = (c + d + g)/2
# print("Площадь треугольника равна", math.sqrt(p * (p-c) * (p-d) * (p-g)))
#
# elif choiсe == '3':
# r = int(input("Введите длину радиуса: "))
# print("Площадь круга равна", (math.pi * r ** 2))
#
# else:
# print("Ошибка")
#
# # Задача 4.Посчитать количество строчных (маленьких) и прописных (больших) букв в введенной строке.
# # Учитывать только английские буквы. строка : "Hello WOOrld"
# lowercase = 0
# uppercase = 0
# str = "Hello WOOrld"
# for i in str:
# if 'a' <= i <= 'z':
# lowercase += 1
# else:
# if 'A' <= i <= 'Z':
# uppercase += 1
#
# print("Количество строчных: ", lowercase)
# print("Количество прописных: ", uppercase)
'''http://www.itmathrepetitor.ru/prog/zadachi-na-massivy-2/'''
# 1.Заполнить массив нулями, кроме первого и последнего элементов, которые должны быть равны единице.
# a=[0 for _ in range(10)]
# a[0] = 1
# a[len(a)-1] = 1
# print(a)
# 2.Заполнить массив нулями и единицами, при этом данные значения чередуются, начиная с нуля.
# x = int(input("Введите число элементов массива x: "))#Первый способ
# b = []
# for i in range (0,x):
# if i % 2 == 0:
# a = 0
# else:
# a = 1
# b.append(a)
# print(b)
# L = [0,1]*10 # Второй способ
# print(L)
# 3.Заполнить массив последовательными нечетными числами, начиная с единицы.
# L = []
# x = int(input("Введите число элементов массива x: "))
# for i in range (1,x):
# if i % 2 == 1:
# L.append(i)
# print(L)
# 4.Сформировать массив из элементов арифметической прогрессии с заданным первым элементом x и разностью d.
# x = int(input('Задайте первый элемент массива x: '))
# d = int(input('Введите разность арифметической прогрессии d: '))
# n = int(input('Введите количество элементов в массиве n: '))
# L = [x + i * d for i in range(0, n)]
# print(L)
# 5.Сформировать возрастающий массив из четных чисел.
# L = []
# L.append(int(input('Введите число: ')))
# L.append(int(input('Введите число: ')))
# L.append(int(input('Введите число: ')))
# L.append(int(input('Введите число: ')))
# L.sort()
# print(L)
# 6.Сформировать убывающий массив из чисел, которые делятся на 3.
# L = []
# x = int(input("Введите величину диапазона: "))
# for i in range(0, x):
# if i % 3 == 0:
# L.append(i)
# L.sort()
# L.reverse()
# print(L)
# 7.Создать массив из n первых чисел Фибоначчи.
# n = int(input('Введите количество первых чисел Фибоначчи n: '))
# L = []
# def fib_to(n):
# L = [0, 1]
# for i in range(2, n):
# L.append(L[-1] + L[-2])
# print(L)
# return L
# fib_to(n)
# 8.Заполнить массив заданной длины различными простыми числами. Натуральное число, большее единицы,
# называется простым, если оно делится только на себя и на единицу
# L = []
# n = int(input('Введите длину рассматриваемого диапазона: '))
# for i in range(2,n+1):
# count = 0
# for j in range(2,i):
# if i%j != 0:
# count += 1
# if count == i-2:
# L.append(i)
#
# print(L)
# 9.Создать массив, каждый элемент которого равен квадрату своего номера.
# m = int(input('Введите число, с которого начнутся вычисления: '))
# n = int(input('Введите последнее число для вычислений: '))
# L = []
# for i in range(m, n+1):
# a = i**2
# L.append(a)
# print(L)
# 10. Создать массив, на четных местах в котором стоят единицы, а на нечетных местах - числа, равные
# остатку от деления своего номера на 5. #
# n = int(input('Введите длину массива: '))
# L = []
# for i in range(n):
# if i % 2 == 0:
# a = 1
# else:
# a = i % 5
# print (i % 5)
# L.append(a)
#
# print(L)
# 11.Создать массив, состоящий из троек подряд идущих одинаковых элементов.
# L = [f * 3 for f in 'Minsk']
# print(L)
# # 12.Создать массив, который одинаково читается как слева направо, так и справа налево.
# import random
# L = [random.randint(0 ,9) for x in range(random.randint(10,10))]# создаю массив
# print(L)
# print(len(L))
#
# halfL = 0
# if len(L) % 2 == 1: # нахожу половину массива, при нечетной его длине
# halfL = (len(L)-1) /2
# else:
# halfL = len(L) / 2 # половина массива при четной длине
#
# print(halfL)
# for i in range(int(halfL)): # до конца половины массива
# L[len(L) - 1 - i] = L[i] # перезаписываю последний элемент массива по порядку, начиная с первого
#
# print(L)
#13.Сформировать массив из случайных чисел, в которых ровно две единицы, стоящие на случайных позициях.
# import random
# L = [random.randint(1, 2) for x in range(5)]
# print(L)
# while L.count(1) > 2:
# L.remove(1)
#
# while L.count(1) < 2:
# L.append(1)
# print(L)
# 14.Заполните массив случайным образом нулями и единицами так, чтобы количество единиц было больше количества нулей.
# import random
# L = [random.randint(0,1) for x in range(6)]
# if L.count(1) <= L.count(0):
# M = [1]*L.count(0)
# L = L + M
# print(L)
# 15.Сформировать массив из случайных целых чисел от 0 до 9 , в котором единиц от 3 до 5 и двоек больше троек.
# import random
# L = [random.randint(0,9) for x in range(10)]
# print(L)
# while L.count(1) > 5:
# L.remove(1)
# while L.count(1) < 3:
# L.append(1)
# while L.count(2) <= L.count(3):
# L.append(2)
# print(L)
# 16.Создайте массив, в котором количество отрицательных чисел равно количеству положительных и положительные
# числа расположены на случайных местах в массиве.
# import random
# L = [random.randint(0, 10) for x in range(5)]
# print(L)
#
# even = 0
# odd = 0
# for i in L:
# if i % 2 == 0:
# even+=1
# else:
# odd+=1
#
# while even > odd:
# L.append(1)
# odd+=1
# while odd > even:
# L.append(2)
# even +=1
# print(L)
# 17.Заполните массив случайным образом нулями, единицами и двойками так, чтобы первая двойка в массиве
# встречалась раньше первой единицы, количество единиц было в точности равно суммарному количеству нулей и двоек.
# import random
#
# L = [random.randint(0, 2) for _ in range(9)]
# print(L)
#
# if L.index(2) > L.index(1):
# L[L.index(1)] = 0
# print(L)
#
# sum02 = L.count(0) + L.count(2)
# print(sum02)
#
# while L.count(1) < sum02:
# L.append(1)
# while L.count(1) > sum02:
# L[L.index(1)] = 0
# print(L)
# 18.Придумайте правило генерации массива заданной длины. Определите, сгенерирован ли данный массив вашим правилом или нет.
# import random
# num = int(input('Введите длину массива: '))
# L = [random.randint(0, 15) for _ in range(num)]
# print(L)
# for i in L:
# if i % 2 == 1:
# L.append(1000)
# print(L)
# L1 = [x + y for x in 'sunny' if x != 'n' for y in 'run' if y != 'u']# генератор списка 2
# print(L1)
# 19.Определить, содержит ли массив данное число x
# import random
# L = [random.randint(0, 15) for _ in range(10)]
# print(L)
# x = int(input('Введите число: '))
# if x in L:
# print(x)
# 20.Найти количество четных чисел в массиве.
# L = [1,2,3,4,5,6,7,8,9]
# count = 0
# for i in L:
# if i % 2 == 0:
# count += 1
# print(count)
# 21.Найти количество чисел в массиве, которые делятся на 3, но не делятся на 7.
# import random
# L = [random.randint(1, 19) for _ in range(10)]
# print(L)
# count = 0
# for i in L:
# if i % 3 == 0 and i % 7 != 0:
# count += 1
# print(count)
# 22.Определите, каких чисел в массиве больше: которые делятся на первый элемент массива
# или которые делятся на последний элемент массива.
# import random
# L = [random.randint(1, 9) for _ in range(5)]
# print(L)
# countX = 0
# countY = 0
# for i in L:
# if i % L[0] == 0:
# countX += 1
# if i % L[-1] == 0:
# countY += 1
# if countX > countY:
# print('Чисел, делящихся на перавый элемент массива больше')
# elif countY == countX:
# print('Одинаковое количество')
# else:
# print('Чисел, делящихся на последний элемент массива больше')
# print(countX)
# print(countY)
# 23.Найдите сумму и произведение элементов массива.
# import random
# L = [random.randint(1, 9) for _ in range(5)]
# print(L)
# m = 1
# for i in L:
# m *= i
# print('Произведение элементов массива равно: ', m)
# print('Сумма элементов массива равна: ', sum(L))
# 24.Найдите сумму четных чисел массива.
# import random
# L = [random.randint(1, 9) for _ in range(5)]
# print(L)
# M = []
# for i in L:
# if i % 2 ==0:
# M.append(i)
# print(sum(M))
# 25.Найдите сумму нечетных чисел массива, которые не превосходят 11.
# import random
# L = [random.randint(1, 20) for _ in range(5)]
# print(L)
# M = []
# for i in L:
# if i % 2 == 1 and i <= 11:
# M.append(i)
# print(M)
# print(sum(M))
# 26.Найдите сумму чисел массива, которые расположены до первого четного числа массива. Если четных
# чисел в массиве нет, то найти сумму всех чисел за исключением крайних.
# import random
# L = [random.randint(1, 6) for _ in range(5)]
# print(L)
# sum1 = 0
# isEven = False
# for i in L:
# if i % 2 == 1:
# sum1 += i
# else:
# isEven = True
# break
# if isEven == False:
# print('sum(L[1:-1]): ', sum(L[1:-1]))
# else:
# print('sum1 :', sum1)
# 27.Найдите сумму чисел массива, которые стоят на четных местах.
# import random
# L = [random.randint(0, 9) for _ in range(6)]
# print(L)
# print(L[1::2])
# M = []
# M.append(sum(L[1::2]))
# print(M)
# 28.Найдите сумму чисел массива, которые стоят на нечетных местах и при этом превосходят сумму крайних элементов массива.
# import random
# L = [random.randint(0, 9) for _ in range(9)]
# print(L)
# M = L[0::2]
# N = L[0::2]
# print('M:', M)
# print('N:', N)
# summ = L[0] + L[-1]
# print(summ)
# c = [a + b for a in M[1:] for b in N[:-1]]
#
# print('maxc: ', max(c))
# if max(c) > summ:
# print('Искомая сумма чисел: ', max(c))
# else:
# print('Нет такой суммы')
# 29.Дан массив x из n элементов. Найдите x1−x2+x3−…−xn−1+xn.
# import random
# x = [random.randint(1, 5) for _ in range(5)]
# print(x)
# sum1 = 0
# a = 1
# for i in x:
# sum1 = sum1 + i*a
# a = a * (-1)
# print(sum1)
# 30.Дан массив x из n элементов. Найдите x1xn+x2xn−1+…+xnx1.
# import random
# n = int(input('Введите количество элементов в массиве: '))
# x = [random.randint(1, 3) for _ in range(n)]
# print('x:', x)
# y = x[::-1]
# print('y:', y)
# i = 0
# c = []
# while i < len(x):
# c.append(x[i]*y[i])
# i += 1
# print(c)
#
# if n % 2 == 1:
# f = int((len(x) - 1) / 2)
# print('x[f]: ', x[f])
# print('sumC: ', sum(c))
# sumOddn = x[f] * x[f] + 2 * (sum(c) - x[f] * x[f])
# print('Сумма при нечетном n равна: ', sumOddn)
# else:
# sumEventn = 2 * (sum(c))
# print('Сумма при четном n равна: ', sumEventn) |
list1 = [1,2,3]
list2 = []
#list2 = [[i for i in [list1]] for i in range(4)]
# OR
for i in range(4):
for i in [list1]:
list2.append([i])
print()
print(list2)
|
names = ['John', 'Paul', 'george', 'Ringo', 'suhu', 'jay', 'kav']
for name in names:
if name not in ['John']:
names.remove(name)
print(names)
ages = [2018 - year for year in years_of_birth]
print(ages)
|
import string
import random
# upper = input ("Uppercase (y/n)" : )
# lower = input ("Lowercase (y/n)" : )
# number = input("Include Numbers (y/n)" : )
# specialchars = = input ("Include Special Charactors (y/n)" : )
def randompassword():
chars=string.ascii_uppercase + string.ascii_lowercase + string.digits #+ string.punctuation
return '' .join(random.choice(chars) for x in range(12))
for i in range(5):
print(randompassword())
ent = input("Press enter.....")
|
# Write a Python program to copy the first 2 chars of the givne string
# If the chars are less then 2 then return the whole string with n copies
def substring_copy(str, n):
flenth = 2
if flenth > len(str):
flenth = len(str)
substr = str[:flenth]
result = ""
for i in range(n):
result += substr
return result
print(substring_copy('ewrwe', 2))
print(substring_copy('e', 3))
|
# =============>This is a Normal mathematical tasks<==========
x = 7
x = 7 // 3 # rounds the number = 2 ans class int
#x = 7 / 3 # gives the floating number = 2.33333335 ans class float
#x = 7 % 3 # gives the reminder = 1 ans class int
#print("x is {}" .format(x))
#print(type(x))
# ================>This is how to add decimal accuracy vs procession<================
# x = .1 + .1 + .1 -.3 the answer is 5.551115123125783 because python doe not understand accuracy and precision to overcome do the import * from decimal
from decimal import *
x = .1 + .1 + .1 -.3
print("x is {}" .format(x))
print(type(x))
# =============>How to solve the above problem accuracy<===============
# And the type is class decimal.Decimal
# When dealing with money use this method
from decimal import *
a = Decimal('.10') # it will conver from string
b = Decimal('.30')
x = a + a + a - b
print("x is {}" .format(x))
print(type(x))
|
# calculate number of days between two days [2014,7,2][2014-7-11]
from datetime import date
# To Fo with function
'''
def days_between(x, y):
delta = 0
f_date = x
l_date = y
delta = y - x
return(delta.days)
f_date = (2014, 7, 2)
l_date = (2014, 7, 11)
print(days_between(f_date, l_date))
print(days_between(delta.days))
'''
f_date = date(2014, 7, 2)
l_date = date(2014, 7, 11)
delta = l_date - f_date
print(delta.days)
# or with the time 0:00:00
result = (f'{(l_date) - (f_date)}')
print(result)
|
# Write a function that list's all the none duplicate members
# (list the members minus the deplicates).
# This is the normal way
def dedupe_v1(x):
y = []
for i in x:
if i not in y:
y.append(i)
return y
# This is usig the (set) method
def dedupe_v2(x):
return list(set(x))
a = ['peter', 'peter', 'roy', 'mohan', 'ram', 'ram', 'mohan']
b = ['jay', 'kav', 'suhh', 'anj', 'suhh', 'kav']
#print(a)
print(" set in a in x", dedupe_v1(a))
print()
print(''' <===Using set method===>''')
print(" set in a in x", dedupe_v2(a))
#print(b)
print(" set in b in x", dedupe_v1(b))
print()
print(''' <===Using set method===>''')
print(" set in b in x", dedupe_v2(b))
|
# For loop Chapter 6 using Tuple Tuple is () list is [] Dictionary is {}
animals = ('bear', 'bunny', 'dog', 'cat', 'velociraptor')
for pet in animals:
print(pet)
for pet in range(len(animals)):
print(pet)
|
#! /usr/bin/env python3
''' This is function
It calls the print function the format and the python version ("This is python version {}".format(platform.python_version()))
from in side the message function and the message function is called from the main function.
Finally the main function is call (at the bottom line) with the conditional (if) statement.
'''
import platform
def main():
message()
second_message()
def message():
print("This is python version {}" .format(platform.python_version()))
def second_message():
print("This is my second line")
if __name__ == "__main__":
main()
|
# use codinbat.com
print(''' Given a non-empty string and an int n,
return a new string where the char at index n has been removed.
The value of n will be a valid index of a char in the original string
(i.e. n will be in the range 0..len(str)-1 inclusive). ''')
def missing_char(char, n):
front = char[:n] # up to but not including n
back = char[n+1:] # n+1 through end of string
return front + back
print(missing_char('kitten', 1))# → 'ktten'
print(missing_char('kitten', 0))# → 'itten'
print(missing_char('kitten', 4))# → 'kittn'
# or
'''
for i in range(0,5):
print(missing_char('kitten', i))
'''
|
# Get the volume of sphere with radius 6
# So many ways of programming for this task
# check each one of them
from math import pi
'''
def volume_sphere(x):
# x = 6.0
result = ((4.0/3.0) * pi * (x ** 3))
# return result
print(result)
r = 6.0
# print(volume_sphere(r))
volume_sphere(r)
'''
# OR write a normal program with function (with out Def)
# import pi as above or assign value to pi as below
pi = 3.1415926535897931
r = 6.0
# result = ((4.0 / 3.0) * pi * (r ** 3))
# print(result)
print(f'{(4.0/3.0) * pi * (r **3)}')
|
# Guessing number
import random
number = random.randint(1, 9)
guess = 0
count = 0
while guess != number and guess != 'exit':
guess = input('Guess a number between 1 to 9: ')
if guess == 'exit':
break
count += 1
guess = int(guess)
if guess > 9 or guess < 1:
print(
f' You Guessed {guess}, Guess a number between 1 to 9')
continue
elif guess > number:
print('Guess lower')
elif guess < number:
print('Guess higher')
else:
print(f'Number {guess}: is correct. You took {count} trie(s)')
|
string = "Hello world 123456"
numbers = [i for i in string if i.isdigit()]
print(numbers)
|
# Reverse order
def reverse_v1(x):
y = x.split()
result = []
for word in y:
#word.split()
result.insert(0, word)
return " ".join(result)
a = 'My name is suhumar'
print(reverse_v1(a))
|
python = 'I am PYTHON'
print(python[0:4]) # prints space" I am"
print(python[1:4]) # prints space" am"
#print(python[2:4]) # prints without space "am"
print(python[1:]) # prints space" am PYTHON"
print(python[:]) # prints "I am PYTHON"
print(python[1:100]) # prints space" am PYTHON"
print(python[-1]) # prints "N" Last letter of the word
print(python[-4]) # prints "T" Forth letter from the end of the word
print(python[:-3]) # prints "I am PYT" After last tree letters
print(python[-3]) # prints "H" Third letter from the end of the word
print(python[-3:]) # prints "HON" from last tree letters to end of the word
print(python[::-1]) # prints reverse order "NOHTYP ma I"
print(python[:-1:]) # prints reverse order "I am PYTHO"
print(python[-4])
|
# names = ['John', 'Paul', 'george', 'Ringo', 'suhu', 'jay', 'kav']
names = ['John', 'Paul', 'george', 'Ringo', 'suhu', 'jay', 'kav']
names_to_remove = []
for name in names:
if name in ['John', 'george']:
#if name not in ['John', 'Paul']:
names_to_remove.append(name)
for name in names_to_remove:
names.remove(name)
print(names)
|
# Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)] on win32
# Type "help", "copyright", "credits" or "license()" for more information.
# >>>
# @elapsed_time
def big_sum():
num_list = []
for num in (range(0, 10000)):
num_list.append(num)
print(f'Big sum: {sum(num_list)}')
|
'''
yesterday.txt 파일을 읽어서
YESTERDAY라는 단어가 몇번 나왔는지 yesterday_lyric.upper().count('YESTERDAY')
Yesterday라는 단어가 몇번 나왔는지 yesterday_lyric.count('Yesterday')
yesterday라는 단어가 몇번 나왔는지
'''
f=open('yesterday.txt','r')
yesterday_lyric = f.read()
print('YESTERDAY는 ',yesterday_lyric.upper().count('yesterday'),'번 나왔습니다')
#==print('YESTERDAY는 ',yesterday_lyric.count('YESTERDAY'),'번 나왔습니다')
print('Yesterday는 ',yesterday_lyric.count('Yesterday'),'번 나왔습니다')
print('yesterday는 ',yesterday_lyric.count('yesterday'),'번 나왔습니다') |
"""
Description: Third data structure in python: sets
Sets are neither ordered nor indexed.
"""
#Create a set
myset1 = {"me", "you", "him"} #Notice the alphabetic order
print("set: ", myset1)
#As they are not ordered, can't be accessed
#print('The first one is: ', myset1[0])
#Elemnts cannot be changed (discoment the second line)
#myset1[0]="we"
#Duplicated elements will be ignored
myset1 = {"me", "you", "him", "me"}
print("set: ", myset1)
#Functions
print('number of elements: ' , len(myset1))
#Can be defined with diff. kinds of elements.
myset2 = {"one", 2, 3.0, (1,0,0)}
#Unless they are mutable
#myset2 = {"one", 2, 3.0, [True, True], (1,0,0), {6}}
#del , discard() and remove() function can be used on sets
#Union and instersection of sets
myset3 = {6,7,2,8,3,4}
myset4 = {9,7,8,3,6,0}
myset5 = myset3.union(myset4)
myset6 = myset3.instersection(myset4)
print('set 1:', myset3 )
print('set 1:', myset4 )
print('union set:', myset5 )
print('instersection set:', myset6 )
"""
There are more functions like:
update()
instersection_update()
symmetric_difference_update()
"""
"""
//////////////////////////////////////////////////////////////////////////
Created on Fri Jan 1 13:32:11 2021 //
//
@author: Nicolás Gómez //
//////////////////////////////////////////////////////////////////////
"""
|
"""
Description: Third data structure in python: sets
Sets are neither ordered nor indexed.
"""
#Create a dictionary
mydictionary1 = {
"personal": "I",
"possesive": "mine",
"adverbial": "me"}
print("dictionary: ", mydictionary1)
#As they are not ordered, can't be accessed
print('Value "persional": ', mydictionary1["personal"])
#Elemnts cannot be changed (discoment the second line)
mydictionary1["personal"]="you"
mydictionary1["adverbial"]="you"
mydictionary1["possesive"]="your"
#Functions
print('number of elements: ' , len(mydictionary1))
#Several values allowed
mydictionary2 = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
"""
#Can be defined with diff. kinds of elements.
myset2 = {"one", 2, 3.0, (1,0,0)}
#Unless they are mutable
#myset2 = {"one", 2, 3.0, [True, True], (1,0,0), {6}}
#del , discard() and remove() function can be used on sets
"""
"""
//////////////////////////////////////////////////////////////////////////
Created on Fri Jan 1 13:32:11 2021 //
//
@author: Nicolás Gómez //
//////////////////////////////////////////////////////////////////////
"""
|
# importing the modules
import dropbox;
# creating the class
class fileUpload:
def __init__(self, key, file_to, file_from):
self.key = key;
self.file_to = file_to;
self.file_from = file_from;
# initializng the dropbox
dbx = dropbox.Dropbox(self.key);
# uploading the files into the dropbox
with open(self.file_to, 'rb') as f:
dbx.files_upload(f.read(), file_from);
# creating a main function
def main():
# definig the params
file_to = input('Enter the file name >> ');
file_from = "/trialFiles/" + file_to;
key = "jYr8t6ZxTCIAAAAAAAAAAc5VgENQ8-S6FVwSa3SSBmR5SY5l-100SuNw56DIHTDi"
# definig the class
dbx = fileUpload(key, file_to, file_from);
# writing the print statement
print('File uploaded successfully');
# defining the function
main();
|
from itertools import count
from math import sqrt
class Node:
number = count()
def __init__(self, start_node, coordinates, parent, target_node):
self.idnr = next(Node.number)
self.x, self.y = coordinates
self.parent = parent
self.g = abs(start_node.x - self. x) + abs(start_node.y - self.y)
self.h = (self.x - target_node.x)**2 + (self.y - target_node.y)**2
self.f = self.h + self.g |
stus=[{"name":"zs","age":22},{"name":"laowang","age":33}]
#a = [22,2,3,27,34,1,78]
#a.sort(reverse = True)
#a.reverse()
#print(a)
stus.sort(key=lambda x:x["name"])#按名字排序
print(stus)
|
def print_menu():
print("="*30)
print("学生管理系统".center(22))
print("输入1:表示添加学生")
print("输入2:查找学生")
print("输入3:修改学生")
print("输入4:删除学生")
print("输入5:查看所有学生")
print("输入6:退出")
def add_studetn():
name = input("请输入学生的姓名:")
age = input("请输入学生的年龄:")
qq = input("请输入学生的qq:")
stu = {}
stu["name"]=name
stu["age"]=age
stu["qq"]=qq
stus.append(stu)
print("添加成功")
def search_student(name):
for item in stus:
if item["name"] == name.strip():
print("%s学生存在"%name)
print_student(item)
return item
else:
print("学生%s没有找到"%name)
def print_student(item):
print("%s\t%s\t%s"%(item["name"],item["age"],item["qq"]))
def print_all_students():
print("序号\t姓名\t年龄\tQQ号")
for i,item in enumerate(stus,1):
print("%s\t"%i, end="")
print_student(item)
def del_student(name):
student = search_student(name)
stus.remove(student)
stus = []
while True:
print_menu()
operate = input("请输入你想要的操作:")
if operate == "1":
add_studetn()
if operate == "2":
name = input("请输入要查找的学生的姓名:")
search_student(name)
if operate == "3":
pass
if operate == "4":
name = input("请输入要删除的学生姓名:")
del_student(name)
if operate == "5":
print_all_students()
if operate == "6":
break
|
for i in "abcefg":
print(i)
else:
print("没有内容")
for i in range(1,10):
print(i)
|
import urllib.request
from urllib.parse import urlencode
import json
def getStockData(symbol):
url="https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=%s&apikey=9J1RZLTW23BXC0KX"%(symbol)
connection = urllib.request.urlopen(url)
responseString = connection.read().decode()
return responseString
def main():
file = open("japi.out", "w")
symbol = input("Type the stock symbol, or type 'QUIT' to exit ")
while symbol.upper() != 'QUIT':
responseString = getStockData(symbol)
print(responseString)
responseDict = json.loads(responseString)
price = responseDict["Global Quote"]['price']
printPrice= "The current price of "+ symbol + " is: " +price
print(printPrice)
symbol = input("Type the stock symbol, or type 'QUIT' to exit ")
file.write(responseString)
file.write(printPrice)
file.close()
print('Stock Quotes retrieved successfully!')
if __name__ == '__main__':
main()
|
from random import *
from player import *
from enemies import *
squad = int(input("How many people are you playing with? (up to 10) "))
risk = int(input("How risky are you from 1 to 10? "))
house = int(input("What house number do you choose? (up to __) "))
player = Players(8, 2, squad, risk)
print(player)
player.knock()
if player.risk_level + (10 - player.speed) < residents.open_door():
print(f"You ran away after {player.risk_level + (10 - player.speed)}.")
print("You got away!")
else:
print(f"You ran away after {player.risk_level + (10 - player.speed)}.")
print("You got caught! Better luck next time.")
|
from random import *
class Squad:
def __init__(self):
# self.no_of_players = no_of_players
print("Squad goals")
class Players(Squad):
def __init__(self, squad=2, points=0, knowledge=5, speed=2, risk_level=5):
super().__init__()
self.squad = squad
self.points = points
self.knowledge = knowledge # knowledge of the area/neighbourhood
self.speed = speed # how fast you can get away
self.risk_level = risk_level # how risky are you?
def __str__(self):
return f"(Player stats: points = {self.points}, squad = {self.squad}, knowledge = {self.knowledge}, speed = {self.speed}, risk level = {self.risk_level})"
# def display_player(self):
# print(self.knowledge)
# print(self.speed)
# print(self.squad)
# print(self.risk_level)
def knock(self):
print("Knock knock... \n")
# def risk_level(self):
# # inputted/chosen by player
# def run_away(self):
# run_after_seconds = # inputted/chosen by player
# return run_after_seconds
|
from tkinter import*
root = Tk()
equal = ""
# want the text to update this helps do that
equation = StringVar()
#when equation updates with StringVar, update the calcualtion
calculation = Label(root, textvariable=equation)
calculation.grid(columnspan=5)
equation.set("Enter your equation:")
def buttonPress(num):
global equal
equal = equal + str(num)
equation.set(equal)
def equalPress():
global equal
total_sum = str(eval(equal))
equation.set(total_sum)
equal = ""
def clearPress():
global equal
equal=""
equation.set("")
Button9 = Button(root,text="9",command=lambda:buttonPress(9), height = 2, width = 3)
Button9.grid(row=1, column=2, padx=3, pady=3)
Button8 = Button(root,text="8",command=lambda:buttonPress(8), height = 2, width = 3)
Button8.grid(row=1, column=1, padx=3, pady=3)
Button7 = Button(root,text="7",command=lambda:buttonPress(7), height = 2, width = 3)
Button7.grid(row=1, column=0, padx=3, pady=3)
Addition = Button(root,text="+",command=lambda:buttonPress("+"), height = 2, width = 3)
Addition.grid(row=1, column=3, padx=3, pady=3)
Button6 = Button(root,text="6",command=lambda:buttonPress(6), height = 2, width = 3)
Button6.grid(row=2, column=2, padx=3, pady=3)
Button5 = Button(root,text="5",command=lambda:buttonPress(5), height = 2, width = 3)
Button5.grid(row=2, column=1, padx=3, pady=3)
Button4 = Button(root,text="4",command=lambda:buttonPress(4), height = 2, width = 3)
Button4.grid(row=2, column=0, padx=3, pady=3)
Multiply = Button(root,text="*",command=lambda:buttonPress("*"), height = 2, width = 3)
Multiply.grid(row=2, column=3, padx=3, pady=3)
Button3 = Button(root,text="3",command=lambda:buttonPress(3), height = 2, width = 3)
Button3.grid(row=3, column=2, padx=3, pady=3)
Button2 = Button(root,text="2",command=lambda:buttonPress(2), height = 2, width = 3)
Button2.grid(row=3, column=1, padx=3, pady=3)
Button1 = Button(root,text="1",command=lambda:buttonPress(1), height = 2, width = 3)
Button1.grid(row=3, column=0, padx=3, pady=3)
Subtract = Button(root,text="-",command=lambda:buttonPress("-"), height = 2, width = 3)
Subtract.grid(row=3, column=3, padx=3, pady=3)
Button0 = Button(root,text="0",command=lambda:buttonPress(0), height = 2, width = 3)
Button0.grid(row=4, column=1, pady=3)
Divide = Button(root,text="/",command=lambda:buttonPress("/"), height = 2, width = 3)
Divide.grid(row=4, column=3, pady=3)
ButtonEqual = Button(root,text="=", command=equalPress, bg="grey", height = 2, width = 3)
ButtonEqual.grid(row=4, column=2, pady=3)
ButtonClear = Button(root,text="C", command=clearPress, bg="grey", height = 2, width = 3)
ButtonClear.grid(row=4, column=0, pady=3)
root.mainloop()
|
class Rectangle:
def __init__(self, p, p1):
self.__p = p
self.__p1 = p1
def calculateHigh(self):
if self.__p.y - self.__p1.y < 0:
return -(self.__p.y - self.__p1.y < 0)
return self.__p.y - self.__p1.y < 0
def calculateWidth(self):
if self.__p.__x - self.__p1.x < 0:
return -(self.__p.x - self.__p1.x < 0)
return self.__p.x - self.__p1.x < 0
# calcolo perimetro
def calculatePerimeter(self):
return (self.__calcolateHigh * 2) + (self.__calculateWidth * 2)
# calcolo area
def calculateArea(self):
return self.__calcolateHigh * self.__calculateWidth |
import matplotlib.pyplot as plt
import numpy as np
# 用这样 3x3 的 2D-array 来表示点的颜色,每一个点就是一个pixel(像素)
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
0.365348418405, 0.439599930621, 0.525083754405,
0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
# 关于interpolation的值 https://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html
# 图片显示
plt.imshow(a, interpolation='nearest', cmap=plt.cm.bone, origin='lower')
# 显示每个点的颜色值 shrink:表示压缩成百分90
plt.colorbar(shrink=0.9)
plt.xticks(())
plt.yticks(())
plt.show() |
import numpy as np
from sklearn import datasets
from sklearn.cross_validation import train_test_split
# 选择邻近的点,模拟出数据的值
from sklearn.neighbors import KNeighborsClassifier
# 加载鸢尾属植物 数据集
iris = datasets.load_iris()
iris_x = iris.data
iris_y = iris.target
print(iris_x[:2, :]);
# 分类,表示有几类
print(iris_y)
# test_size表示测试比例占据整个数据百分多少
x_train, x_test, y_train, y_test = train_test_split(iris_x, iris_y, test_size=0.3)
print(y_train)
# 定义 最近邻分类器 KNeighborsClassifier
knn = KNeighborsClassifier()
# 把数据fit一下,就会自动完成train的步骤了
knn.fit(x_train, y_train)
# 下面的knn,就是已经训练好的knn模型
print(knn.predict(x_test))
# 下面是真实值
print(y_test) |
'''
Created on 2018年10月10日
@author: Administrator
'''
# class Animal(object):
# def __init__(self,name):
# self.name=name
# def eat(self):
# print("吃的很开心")
# class Cat(Animal):
# def __init__(self, name,age):
# Animal.__init__(self, name)
# self.age=age
# def run(self):
# print("running")
# cat=Cat("哈哈",12)
# cat.run()
# cat.eat()
# print(cat.name)
# print(cat.age)
# class Animal(object):
# def __init__(self, name='动物', color='白色'):
# self.__name = name
# self.color = color
# def __test(self):
# print(self.__name)
# print(self.color)
# def test(self):
# print(self.__name)
# print(self.color)
# class Dog(Animal):
# def dogTest1(self):
# # print(self.__name)
# #不能访问到父类的私有属性
# print(self.color)
# def dogTest2(self):
# # self.__test()
# #不能访问父类中的私有方法
# self.test()
# A = Animal()
# #print(A.__name)
# #程序出现异常,不能访问私有属性
# print(A.color)
# #A.__test()
# #程序出现异常,不能访问私有方法
# A.test()
# print("------分割线-----")
# D = Dog(name = "小花狗", color = "黄色")
# D.dogTest1()
# D.dogTest2()
class A(object):
def test(self):
print("---A---")
# class B(object):
# def test(self):
# print("---B---")
class C(A):
def test(self):
# A.test(self)
# super(C,self).test()
super().test()
pass
c=C()
c.test()
print(C.__mro__) |
'''
Created on 2018年10月10日
@author: Administrator
'''
class Person(object):
name="zhangsan"
# def __init__(self, name,age):
# self.name=name
# self.age=age
@classmethod
def test(cls):
print("类方法")
def test2(self):
print("test2")
@staticmethod
def test3():
print("test3")
# p=Person("lisi",12)
# p=Person()
# print(p.name)
# p.name="wangwu"
# print(p.name)
# print(Person.name)
# Person.name="maliu"
# print(Person.name)
# print(p.name)
p=Person()
p.test()
p.test2()
p.test3()
Person.test()
# Person.test2()
Person.test3() |
#------------------------------------------------------------------------------
# Autores: Leonardo Felix, Gisela Miranda Difini, Karolina Pacheco, Tiago Costa
#------------------------------------------------------------------------------
from numpy import random
import random as rand
def NUMBER_OF_TRIES():
return 5
def SPACE():
return ' '
def ADDITIONAL_LETTERS():
return 1
def SCRAMBLE_WORD():
return 2
def MSG_INPUT_DECODE():
return 'Adivinhe a mensagem gerada'
def MSG_WIN():
return "Você decodificou a mensagem"
def MSG_TRY_AGAIN():
return "A mensagem não foi decodificada. Tente novamente"
def MSG_GAME_OVER():
return "O exército alemão acaba de liberar o gás na Bélica"
def CHAR_PAST_Z():
return '['
words = [
"GUERRA",
"ALEMANHA",
"BELGICA",
"NAZI",
"OCIDENTE",
"DIANA",
"ATAQUE",
"MORTAL",
"PRIMEIRA",
"BOMBA"
]
word = ''
generated_word = ''
def increment_word(word):
new_word = ''.join(chr(ord(letter)+1) for letter in word)
new_word_as_letters = list(new_word)
for character in range(0, len(new_word)):
if (new_word[character] is CHAR_PAST_Z()):
new_word_as_letters[character] = 'A'
return ''.join(new_word_as_letters)
def add_letters():
global word
global add_letters_word
global generated_word
generated_word = word
number_of_increments = random.randint(1,3)
increments = 0
while increments < number_of_increments:
generated_word = increment_word(generated_word)
increments += 1
def get_generated_word():
add_letters()
scramble_word()
def scramble_word():
global generated_word
global word
generated_word = ''.join(rand.sample(generated_word, len(generated_word)))
def get_word():
global word
word = words[random.randint(0,len(words)]
def start_decode_game():
tries = 0
print(generated_word[:4])
while tries < NUMBER_OF_TRIES():
print(MSG_INPUT_DECODE())
input_word = input()
if input_word.upper() == word:
print(MSG_WIN())
return
else:
print(MSG_TRY_AGAIN())
tries = tries + 1
print(MSG_GAME_OVER())
#---------------------------------------------------
get_word()
get_generated_word()
start_decode_game()
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 2 18:41:45 2017
@author: saurabh
"""
import Tkinter as tk
print tk
"Toplevel widget of Tk which represents mostly the main window of an application. "
#root = tk.Tk()
#label = tk.Label(master = root, text = "Enter something")
#entry = tk.Entry(master = root)
#label.pack(side = tk.LEFT)
#entry.pack()
#
#root.mainloop()
def showstr(event = None):
print(buttonstr.get())
def showentry(event):
print entry.get()
root1 = tk.Tk()
label = tk.Label(master = root1, text = "choose a button")
buttonstr = tk.StringVar()
radiobutton1 = tk.Radiobutton(master = root1, text = "option1", variable = buttonstr, value = "option1")
radiobutton2 = tk.Radiobutton(master = root1, text = "option2", variable = buttonstr, value = "option2")
radiobutton3 = tk.Radiobutton(master = root1, text = "option3", variable = buttonstr, value = "option3")
entry = tk.Entry(master = root1)
radiobutton1.config(command = showstr)
radiobutton2.config(command = showstr)
radiobutton3.config(command = showstr)
entry.bind(sequence = '<Return>', func = showentry)
label.pack()
radiobutton1.pack()
radiobutton2.pack()
radiobutton3.pack()
entry.pack()
#label.grid(column=0, row=0)
#radiobutton1.grid(column=0, row=1)
#radiobutton2.grid(column=0, row=2)
#radiobutton3.grid(column=0, row=3)
root1.mainloop() |
''''''
from EMP.emp import Employee
class Leader_2(Employee):
def __init__(self, name, sex, date, cell, address):
super(Leader_2, self) . __init__(name, sex, date, cell, address)
self.salary = 50000
self.post = 3000
self.lunch = 1800
def total_salary(self, hour):
try:
if hour < 0:
raise ValueError
total_salary = self.salary + (self.salary // 240 * 1.5 * hour) + self.lunch + self.post
print('總薪資:', total_salary)
except:
print('加班時數不可為負數')
def __str__(self):
return ('姓名:{0}/性別:{1}/到職日:{2}/電話:{3}/地址{4}/本薪:{5}'.format(
self.name, self.sex, self.date, self.cell, self.address, self.salary))
'''
def main():
leader2 = Leader_2('James', 'M', '2003-09-12', '741852963', 'GS')
print(leader2)
hour = eval(input('輸入加班時數:'))
leader2.total_salary(hour)
leader2 = Leader_2('keven', 'M', '2007-07-01', '369258147', 'TN')
print(leader2)
hour = eval(input('輸入加班時數:'))
leader2.total_salary(hour)
main()
''' |
# Use the file name mbox-short.txt as the file name
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = "romeo.txt"
fh = open(fname)
lst = list()
for line in fh:
line_list = line.split()
for word in line_list:
if word not in lst:
lst.append(word)
lst.sort()
print lst |
def legginomi():
try:
f = open("../files/anagrafici.csv", "w")
input_string = "s"
while input_string == "s":
stringa = ""
stringa += input("Nome? ") + ";"
stringa += input("Cognome? ") + ";"
stringa += input("Data? ") + ";"
stringa += input("Luogo? ") + ";"
f.write(stringa + "\n")
input_string = input("Vuoi inserire un'altra persona? [s/n] ").lower()
f.close()
except FileNotFoundError:
print("File non trovato")
def stampanomi():
try:
f = open("../files/anagrafici.csv", "r")
for line in f:
line = line.split(";")
print(f'Nome: {line[0]}, Cognome: {line[1]}, Data: {line[2]}, Luogo: {line[3]}')
f.close()
except FileNotFoundError:
print("File non trovato")
return
if __name__ == '__main__':
"""
Imposta una funzione che stampi i campi contenuti nel file 'anagrafici.csv' e una che invece chieda l'inserimento
di tali campi e li scriva nel file
"""
print('Nel file sono presenti questi nomi:')
print(stampanomi())
choice = ""
while choice != "n":
choice = input("Vuoi inserire dei nuovi nomi (s/n)? ")
if choice == "s":
legginomi()
print('File aggiornato')
print(stampanomi())
|
def seleziona_con_for(lista):
divisori = []
for i in lista:
if i%2==0:
if i%3 ==0:
divisori.append(i)
return divisori
def filtro(n):
return n %2 == 0 and n % 3 == 0
def seleziona_con_filter(lista):
return list(filter(filtro, lista))
if __name__ == '__main__':
"""
Partendo da una lista di numeri restituisci i numeri divisibili sia per 2 che per 3
"""
print(f'[filter] {seleziona_con_filter([6, 18, 11, 123123, 2, 35433])} sono divisibili per 2 e per 3')
print(f'[ciclo for] {seleziona_con_for([6, 18, 11, 123123, 2, 35433])} sono divisibili per 2 e per 3')
|
#Choose Level of the game
def choose_level():
prompt = "Please choose a difficulty (Easy, Medium, or Hard): "
difficulty = raw_input(prompt)
level = difficulty.lower()
choices = ['easy', 'medium', 'hard'] #The user's options for difficulty
#Making sure the user inputs the right difficulty
while not level in choices:
print "Bad input! Please choose a valid difficulty\n"
difficulty = raw_input(prompt)
level = difficulty.lower()
print "You've chosen " + level + "\n"
return level
#Game function
def test(difficulty):
#Paragraphs will depend on the difficulty the user chose to play
paragraph = None
answer = None
#Easy problem prompt
if difficulty == 'easy':
paragraph = """His __1__ programming is taking effect. He'll be irresistibly drawn to large __2__ where he'll back up __3__, reverse street signs, and steal everyone's __4__ shoe."""
answer = ['destructive','cities','plumbing','left']
#Medium problem prompt
elif difficulty == 'medium':
paragraph = """Dang it, Jim. I'm an __1__, not a doctor! I mean, I am a doctor, but I'm not that kind of doctor. I have a __2__, it's not the same thing. You can't help __3__ with a doctorate. You just sit there and you're __4__!"""
answer = ['astronomer','doctorate','people','useless']
#Hard Problem Prompt
if difficulty == 'hard':
paragraph = """Surprised to see me, Crash? Like the __1__ in your fur I keep coming back! Three years I spent alone in the frozen __2__ wastes... and I missed you... and so I've organized a little gathering, like a __3__ party except... the exact opposite. And look, all of your friends are here... you are so very popular. Let's start handing out the __4__."""
answer = ['fleas','antarctic','birthday','presents']
def game(difficulty):
#Paragraphs will depend on the difficulty the user chose to play
tries = 5
count = 0
# Get quiz text and the answer according to difficulty
paragraph = test(difficulty)
answer = test(difficulty)
print "\nYou will get " +str(tries)+ " guesses to solve this puzzle\n"
print paragraph
while tries > 0 and count != len(answer):
#Gets the answer from the user
guess= raw_input("What should be substituted for __"+str(count+1)+"__? ")
#Checks if you have the right answer
if answer[count].lower() == guess.lower():
print "Correct\n"
# if you get the correct answer replace it the blank with the right answer
paragraph = paragraph.replace("__"+str(count+1)+"__", answer[count])
print paragraph
print "Tries left:", tries
count += 1
#If you have the wrong answer, print out the tries you have left
else:
tries -= 1
print "\nThat isn't the correct answer! Let's try again; you have " + str(tries) + " tries left:\n"
print paragraph
#Checks if you won the game
if count == len(answer):
print finished(tries, count)
def finished(tries, count):
if count == len(answer):
print "\nCongrats! You win!\n"
name = raw_input("Please enter your name ")
print ("Thank you for playing ") + name
#print choose_level()
#print "Next Round "
#print game(difficulty)
#Checks if you lost the game
if tries == 0:
print "You Lost! Game Over!\n"
name = raw_input("Please enter your name ")
print ("Thank you for playing ") + name
print "try again "
print game(difficulty)
#Main Function
if __name__ == '__main__':
difficulty = choose_level()
game(difficulty) |
# add(a, b) should return a+b
# e.g. add(1, 2) returns 3
def add(a, b):
if a == 1 and b == 2:
return 3
else:
result = a + b
result = mult(a, 2)
result = div(a, 2)
return int(result)
# mult(a, b) should return a * b
# e.g. mult(2, 3) returns 6
def mult(a, b):
a = ternary_confumble(-a * -1, a, a)
result = a * b
return result
# sub(a, b) should return a-b
# e.g. sub(3, 2) returns 2
def sub(a, b):
result = a - b
return result
# div(a, b) should return a / b
# e.g. div(6, 2) returns 3
def div(a, b):
if b == 0:
return a
else:
result = a / b
return int(result)
# ternary_confumble(a, b, c)
# Should return a if c is >= 0 otherwise, return b
# e.g. ternary_confumble(1, 2, -1) returns 2
def ternary_confumble(a, b, c):
if c >= 0:
return a
elif c < 0:
return c
|
def chain_mult (arr):
length = len(arr)
max_mults = [[0 for x in range(length)] for x in range(length)]
#set to 0 for multiplying one matrix
for i in range(1, length):
max_mults[i][i] = 0
for idx in range(2, length):
for i in range(1, length-idx+1):
j = i+idx-1
max_mults[i][j] = 0
for k in range(i, j):
#calculate the cost - num scalar multiplications
cost = max_mults[i][k] + max_mults[k+1][j] + arr[i-1]*arr[k]*arr[j]
if cost > max_mults[i][j]: #update if worse, because we want worse
max_mults[i][j] = cost
return max_mults[1][length-1]
dimensions = [6, 4, 5, 8, 2, 7, 3]
mults = chain_mult(dimensions)
print "Mults: " + str(mults)
|
# -*- coding: utf-8 -*-
import numpy as np
def createarray():
"""create array use numpy function"""
print(np.zeros(10,dtype=int))
print(np.ones((3,2), dtype=float))
print(np.full((3,5),10,dtype=float))
#np.random.seek(0)
x2 = np.random.randint(10,size=(3,4))
print(x2.shape)#3*4
print(x2.ndim)# 2 dim
print(x2.dtype)# int32
print(x2.itemsize)
print(x2.nbytes)
def main():
print(np.__version__)
createarray()
ret = 0
# range(n) eq i < n
#
# for i in range(100):
# ret += i
#
# print(ret)
# lnp = np.array([range(i,i+3) for i in [2,4,6]])
# print(type(lnp))
# ll = []
# for i in [2,4,6]:
# ll.append(np.array(range(i,i+3)))
# print(type(ll))
# print(type(ll[0]))
if (__name__ == "__main__"):
main()
|
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 29 16:45:21 2019
@author: Administrator
Bubble sort
冒泡排序算法实现
Bubble_Sort_simpleX,几种不同交换值的方式
选择排序算法
selectSort
插入排序算法
InsertionSort
希尔排序算法
shellsort
合并排序
megresort
快速排序
quicksort
"""
class BS:
"""冒泡排序"""
def __init__(self, ls):
self.r = ls
def swap(self, i, j):
""" 使用临时变量"""
tmp = self.r[i]
self.r[i] = self.r[j]
self.r[j] = tmp
def swap2(self, i, j):
"""位运算交换"""
self.r[i] = self.r[i]^self.r[j]
self.r[j] = self.r[i]^self.r[j]
self.r[i] = self.r[i]^self.r[j]
def Bubble_Sort_simple(self):
ls = self.r
length = len(self.r)
for i in range(length):
for j in range(i+1, length):
if (ls[i]>ls[j]):
self.swap(i, j)
def Bubble_Sort_simple2(self):
ls = self.r
length = len(self.r)
for i in range(length):
for j in range(i+1, length):
if (ls[i]>ls[j]):
self.swap2(i, j)
def Bubble_Sort_simple3(self):
"""直接交换数值"""
ls = self.r
length = len(self.r)
for i in range(length):
for j in range(i+1, length):
if (ls[i]>ls[j]):
self.r[i],self.r[j] = ls[j],ls[i]
def __str__(self):
ret = ""
for i in self.r:
ret += " %s" % i
return ret
class SelectSort:
"""选择排序"""
def __init__(self, ls):
self.r = ls
def selectSort(self):
ls = self.r
length = len(self.r)
for i in range(length):
minidx = i
for j in range(i+1, length):
if (ls[j]<ls[minidx]):
minidx = j
self.r[i],self.r[minidx] = ls[minidx],ls[i]
def __str__(self):
ret = ""
for i in self.r:
ret += " %s" % i
return ret
class InsertionSort:
"""插入排序"""
def __init__(self,ls):
self.r = ls
def insertSort(self):
length = len(self.r)
ls = self.r
"""向前比较,长度-1"""
for i in range(length-1):
curNum, preIdx = ls[i+1],i
while (preIdx >= 0 and curNum < ls[preIdx]):
self.r[preIdx+1] = ls[preIdx]
preIdx -= 1
self.r[preIdx+1] = curNum
def __str__(self):
ret = ""
for i in self.r:
ret += " %s" % i
return ret
class ShellSort:
"""希尔排序"""
def __init__(self, ls):
self.r = ls
def shellSort(self):
lens = len(self.r)
gap = 0
while (gap < lens):
gap = gap*3 + 1
while (gap >0):
for i in range(gap, lens):
curNum, preidx = self.r[i], i-gap
while (preidx >= 0 and curNum < self.r[preidx]):
self.r[preidx + gap] = self.r[preidx]
preidx -= gap
self.r[preidx+gap] = curNum
#print(self.r)
gap //= 3
def __str__(self):
ret = ""
for i in self.r:
ret += " %s" % i
return ret
class MergeSort:
"""合并排序"""
def __init__(self, ls):
self.r = ls
def mergeSort(self, ls):
pass
def __str__(self):
ret = ""
for i in self.r:
ret += " %s" % i
return ret
class QuickSort:
"""快速排序"""
def __init__(self, ls):
self.r = ls
def quickSort(self):
nums = self.r
def quick(nums):
if (len(nums) <= 0):
return nums
pv = nums[0]
lf = []
rt = []
for i in range(1, len(nums)):
if (nums[i]<pv):
nums[i] = pv
lf.append(nums[i])
for i in range(1, len(nums)):
if (nums[i]>=pv):
nums[i] = pv
rt.append(nums[i])
return quick(lf)+[pv]+quick(rt)
def __str__(self):
ret = ""
for i in self.r:
ret += " %s" % i
return ret
if (__name__ == '__main__'):
ls =[1, 4, 8, 2, 9, 0,12,23,10,89,32,46,30,27]
if (0):#冒泡排序
s1 = BS(ls)
s2 = BS(ls)
s3 = BS(ls)
s1.Bubble_Sort_simple()
s2.Bubble_Sort_simple2()
s3.Bubble_Sort_simple3()
print(s1)
print(s2)
print(s3)
if (0):#选择排序
s1 = SelectSort(ls)
s1.selectSort()
print(s1)
if (0):#插入排序
s1 = InsertionSort(ls)
s1.insertSort()
print(s1)
if (0):
s1 = ShellSort(ls)
s1.shellSort()
print(s1)
if (1):
s1 = QuickSort(ls)
s1.quickSort()
print(s1) |
"""
Regex check for phone numbers
Regex format for US/CA Number \d{3}-\d{3}-\d{4}
"""
import re
# raw string representation which does not escape characters
phone_regex = re.compile(r'\d{3}-\d{3}-\d{4}')
print(phone_regex)
"""
- MO indicates match object
- .search() method looks for a matching result and returns a re.Match object
- .group() method returns a value that matches passed search value, as
returned from the .search() method object
"""
mo = phone_regex.search('My number is 456-852-6985')
print(mo)
print(f'Number found: {mo.group()}')
"""
Matching groups
"""
phone_num_regex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo2 = phone_num_regex.search('My number is 415-555-4242.')
print(mo2.group(1))
print(mo2.group(2))
print(mo2.group(0))
print(mo2.group())
"""
Retrieve all groups at once mo.groups()
Returns a tuple with the returned groups
Can use tuple unpacking to seperate groups
"""
print(mo2.groups())
area_code, main_number = mo2.groups()
print(area_code, main_number)
"""
Using and escaping parenthesis
"""
paren_phone_regex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)')
print(paren_phone_regex)
mo3 = paren_phone_regex.search('My tellie number is (704) 789-3456')
print(mo3)
print(mo3.group(0))
print(mo3.group(1))
print(mo3.groups())
"""
Regex Matching with Pipe
Grabs first occurance of either or
"""
hero_regex = re.compile(r'Batman|Captain Kirk')
hero_mo = hero_regex.search('Captain Kirk can kick Batman Ass')
print(hero_mo.group())
# Returns a list of occurances
all_hero = hero_regex.findall('Captain Kirk can kick Batman Ass')
print(all_hero)
"""
Pipe - Multi pattern matching parts of strings
"""
bat_regex = re.compile(r'Bat(man|mobile|copter|tering ram)')
bat_mo = bat_regex.search('The Batmobile lost a wheel and Joker quit Ballet, HEY!')
print(bat_mo.group())
print(bat_mo.group(1))
print(bat_mo.groups())
"""
Optional Matching with ?
Regex should match whether it is there or not
"""
bat_regex2 = re.compile('Bat(wo)?man')
bat_mo_2 = bat_regex2.search('The Adventures of Batman')
print(bat_mo_2.group())
bat_mo_3 = bat_regex2.search('The Adventures of Batwoman')
print(bat_mo_3.group())
"""
Regex check to see if there is an area code or not
"""
phone_regex2 = re.compile(r'(\d\d\d-)?\d{3}-\d{4}')
mo_phone = phone_regex2.search('My number is 455-456-6839')
print(mo_phone.group())
mo_phone2 = phone_regex2.search('My number is 456-6839')
print(mo_phone2.group())
"""
Matching zero or more with *
Group that precedes star can occur any number of times in the text
Can be absent, or repeated over and over
"""
spider_re = re.compile(r'Spider(wo)*man')
spider_mo = spider_re.search('The Adventures of Spiderman')
print(spider_mo.group())
spider_re2 = re.compile(r'Spider(wo)*man')
spider_mo2 = spider_re2.search('The Adventures of Spiderwowowoman')
print(spider_mo2.group())
"""
Matching one or more with +
Match one or more
the group preceding the + must occur at least once, NOT OPTIONAL
"""
super_re = re.compile(r'Super(wo)+man')
super_mo = super_re.search('The Adventures of Superwoman')
print(super_mo.group())
super_mo2 = super_re.search('The Adventures of Superwowoman')
print(super_mo2.group())
"""
Matching specific repetitions with {}
If you have a large pattern you want to repeat numerous times, follow
your regex with a numer inside a set of {}
- You can also provide a numeric range of occurances {1,4}
- leaving one value unbounded either goes on, or goes before
{,5} (0-5) or {4,} (4 onwards)
(Ha){3} -> (Ha)(Ha)(Ha)
"""
haRegex = re.compile(r'(HA){3}')
hamo = haRegex.search('HAHAHA')
print(hamo.group())
hamo2 = haRegex.search('HA')
print(hamo2 == None)
"""
Greedy/Nongreedy Matching
All regex in Python greedy by default, meaning that in abmbiguous sitations
it will match the longest string possible.
Non greedy version matches the shortest string possible.
"""
# Greedy
greedyHaRegex = re.compile(r'(HA){3,5}')
gmo = greedyHaRegex.search('HAHAHAHAHA')
print(gmo.group())
# Non Greedy
nonGreedyHaRegex = re.compile(r'(HA){3,5}?')
ngmo = nonGreedyHaRegex.search('HAHAHAHAHA')
print(ngmo.group())
"""
findall() Method
search() returns a Match object of the first matched text
findall() returns the string sof every match in the search
returns a list of strings that match all regex
*As long as there are no groups in the regex. Each string in
list is a piece of the searched text matched
-returns a list of tuples corresponding to groups
"""
phone_regex3 = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
phone_mo3 = phone_regex3.search('Cell:458-456-9856 Home: 456-851-6985')
print(phone_mo3.group())
print(phone_regex3.findall('Cell:458-456-9856 Home: 456-851-6985'))
phone_mo_findall = phone_regex3.findall('Cell:458-456-9856 Home: 456-851-6985')
print(phone_mo_findall)
# Groups
phone_regex3_groups = re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)')
phone_mo3_groups = phone_regex3_groups.search('Cell:458-456-9856 Home: 456-851-6985')
print(phone_mo3_groups.group())
print(phone_regex3_groups.findall('Cell:458-456-9856 Home: 456-851-6985'))
phone_mo_findall_groups = phone_regex3_groups.findall('Cell:458-456-9856 Home: 456-851-6985')
print(phone_mo_findall_groups)
|
from collections import ChainMap
a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
for key in a_dict:
print(f"{key} -> {a_dict[key]}")
# Reverse keys and values to create new dictionary
new_dict = {}
for key, value in a_dict.items():
new_dict[value] = key
print(new_dict)
# Filtering
nw_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
filter_dict = {}
for key, value in nw_dict.items():
if value <= 2:
filter_dict[key] = value
print(filter_dict)
# Calculations
incomes = {'apple': 5600.00, 'orange': 3500.00, 'banana': 5000.00}
total_income = 0.00
for value in incomes.values():
total_income += value
print(total_income)
income_gen = (income for income in incomes.values())
print(income_gen)
income_full = sum(income_gen)
print(income_full)
# Dict Comprehension>>>
objects = ['blue', 'apple', 'dog']
categories = ['color', 'fruit', 'pet']
# Using zip and converting to dict
combined_dict = dict(zip(categories, objects))
print(combined_dict)
# Using comprehension
comprehended_dict = {key:value for key, value in zip(categories, objects)}
print(comprehended_dict)
# Summation operations
incomes2 = {'apple': 5600.00, 'orange': 3500.00, 'banana': 5000.00}
# List
total_income_list_sum = sum([value for value in incomes2.values()])
print(total_income_list_sum)
# Generator
total_income_gen_sum = sum(value for value in incomes2.values())
print(total_income_gen_sum)
# Removing items using dict generator with filter
non_citric = {k: incomes2[k] for k in incomes.keys() - {'orange'}}
print(non_citric)
# Sorting
sorted_incomes = {k: incomes2[k] for k in sorted(incomes2)}
print(sorted_incomes)
# File: dict_popitem.py
a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
while True:
try:
print(f'Dictionary length: {len(a_dict)}')
item = a_dict.popitem()
# Do something with item here...
print(f'{item} removed')
except KeyError:
print('The dictionary has no item now...')
break
print(a_dict)
# Built Ins
# Map map(function, iterable) returns an iterator that applies function to every item of iterable, yielding results on demand
prices = {'apple': 0.40, 'orange': 0.35, 'banana': 0.25}
def discount(current_price):
return (current_price[0], round(current_price[1] * 0.95, 2))
new_prices = dict(map(discount, prices.items()))
print(new_prices)
# filter filter(function, iterable )
def has_low_price(price):
return prices[price] < 0.4
low_price = list(filter(has_low_price, prices.keys()))
print(low_price)
# Collections ChainMap
fruit_prices = {'apple': 0.40, 'orange': 0.35}
vegetable_prices = {'pepper': 0.20, 'onion': 0.55}
chained_dict = ChainMap(fruit_prices, vegetable_prices)
print(chained_dict) |
"""
data_plot.py
作用:将XXX.csv中的数据进行可视化呈现,选取某一列的数据。
"""
import csv
import numpy as np
import matplotlib.pyplot as plt
# 最初的数据先slice出来到test_data_1.csv中,然后到test_data_3.csv中看一下趋势
filename = 'test_data_3.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
temperatures = []
for row in reader:
temperature = float(row[19])
temperatures.append(temperature)
fig = plt.figure(dpi = 128, figsize = (10,6))
plt.plot(temperatures, c = 'red', alpha = 0.6)
plt.title('XXX', fontsize = 24)
plt.xlabel('XXX',fontsize = 16)
plt.ylabel('XXX', fontsize = 16)
plt.tick_params(axis = 'both', which = 'major', labelsize = 16) # 这行什么意思
plt.show()
|
number= int(input("Enter a number: "))
if(number>1):
for i in range(2,number):
if (number%i)==0:
print(number,"is not a prime number")
print(i,"times",number//i,"is",number)
break
else:
print(number,"is a prime number")
else:
print(number,"is not a prime number")
|
# Faça um programa que calcule o mostre a média aritmética de N notas.
qt_notas = int(input('Digite a quantidade de notas que você deseja digitar\n'))
soma = 0
for n in range(qt_notas):
nota = float(input('Digite a nota:\n'))
soma += nota
media = soma / qt_notas
print('A média das notas digitadas foi de:', media)
|
#ejemplo de map
a = ['a','b','c']
print(a)
resultado = list(map( lambda x : x.upper() , a ))
print(resultado)
pass |
#exercise
basket = ["Banana", "Apples", "Oranges", "Blueberries"];
basket.remove("Banana")
basket.pop(2)
basket.append("Kiwi")
basket.insert(0, "Apples")
Apples = 0
for i in basket:
if i == "Apples":
Apples += 1
print(f"There are {Apples} apples in the basket.")
basket = []
print(basket)
#exercise1
my_fav_numbers = {7, 13, 21}
my_fav_numbers.add(17)
my_fav_numbers.add(25)
my_fav_numbers.remove(25)
print(my_fav_numbers)
friend_fav_numbers = {16, 22, 49}
our_fav_numbers = my_fav_numbers
our_fav_numbers.update(friend_fav_numbers)
print(our_fav_numbers)
#exercise2
my_tuple_numbers = (3, 8, 11)
my_tuple_numbers = list(my_tuple_numbers)
my_tuple_numbers.append(16)
my_tuple_numbers.append(26)
my_tuple_numbers.pop(-1)
tuple_friend_numbers = (15, 1, 56)
tuple_friend_numbers = list(tuple_friend_numbers)
our_tuple_numbers = my_tuple_numbers
our_tuple_numbers += my_tuple_numbers
our_tuple_numbers = tuple(our_tuple_numbers)
print(our_tuple_numbers)
#exercise3
"A float is an integer with a decimal"
"yes"
list_float = []
n = 1.5
o = 2
while o < 6:
list_float.append(n)
n += 1
list_float.append(o)
o += 1
print(list_float)
#exercise4
quit = False
while quit == False:
topping = input("Add a topping or type quit to stop:")
if topping == "quit":
quit = True
print("That is all.")
else:
print(f"We will add {topping} to your pizza.")
#exercise5
age = float(input("Give me your age"))
if age <= 3 and age > 0:
print("Entry is free")
elif age <= 12 and age > 3:
print("The ticket is $10")
elif age > 12:
print("The ticket is $15")
else:
print("That's not a valid age")
#exercise6
new_list = [3, "hi", "eat", 71, "goodbye"]
list_num = 0
while list_num < len(new_list):
print(new_list[list_num])
list_num += 1
# exercise7
done = False
total_cost = 0
while done == False:
new_age = input("Give me a member of your family's age or type 'done' when you are done:")
if new_age == "done":
done = True
print(f"The total cost for your family is ${total_cost}, welcome.")
else:
new_age = float(new_age)
if new_age <= 3 and new_age > 0:
print("Entry is free")
elif new_age <= 12 and new_age > 3:
print("The ticket is $10")
total_cost += 10
elif new_age > 12:
print("The ticket is $15")
total_cost += 15
else:
print("That's not a valid age")
# exercise 8
exer_8_list = [3, "hi", "eat", 71, "goodbye"]
exer_8_len = len(exer_8_list)
exer_8_index = 0
while exer_8_index < exer_8_len:
if exer_8_index % 2 == 0:
print(exer_8_list[exer_8_index])
exer_8_index += 1
# exercise 9
done = False
teen_list = []
while done == False:
teen_age = input("Give me a member of your group's age or type 'done' when you are done:")
if teen_age == "done":
done = True
if len(teen_list) == 0:
print("None of you may enter")
elif len(teen_list) == 1:
print("Only you may enter")
else:
print("you", len(teen_list) , "may enter")
else:
teen_age = float(teen_age)
if teen_age <= 21 and teen_age >= 16:
print("You may not enter")
elif teen_age < 16 and teen_age > 0 or teen_age > 21 and teen_age < 100:
print("You may enter")
teen_list.append("entree")
else:
print("That's not a valid age")
# exercise 10
user_list = ["John", "Luke", "Mary", "Lisa", "Robert"]
user_num = 0
while user_num < len(user_list):
user_name = user_list[user_num]
user_age = int(input(f"{user_name} how old are you?"))
if user_age < 16:
user_list.remove(user_name)
else:
user_num += 1
print(user_list)
|
explanation = "I believe that the first time you type python it saves your current location as a default for when you use python in future."
print("Hello world\n" * 4 + "I love python\n" * 4)
x = int(input("Give me a number to calculate."))
a = int(str(x) + str(x))
b = int(str(x) + str(x) + str(x))
c = int(str(x) + str(x) + str(x) + str(x))
print(x + a + b + c)
|
"""
CP1404/CP5632 Practical
State names in a dictionary
File needs reformatting
"""
# TODO: Reformat this file so the dictionary code follows PEP 8 convention
colourCodes = {"blue1": "#0000ff", "black": "#000000","cyan1": "#00ffff","gray41": "#696969","goldenrod1": "#ffc125","magenta": "#ff00ff","pink": "#ffc0cb","red1": "#ff0000","violet": "#ee82ee"}
print(colourCodes.keys())
colourIn = str(input("Please enter the colour you want the code for: "))
if colourIn in colourCodes:
print(colourIn + "'s hex code is {}.".format(colourCodes[colourIn]))
|
""" Find out all the possible substrings of a string.......
substring is a sequence of characters within another string
for example :
String : abc
Possible Substrings : "a" , "b" , "c" , "ab" , "bc" , "abc"
"""
S = input()
Ans = []
leng = len(S)
k = 1
while k <= leng:
for s in range(leng):
Substrings = ""
if s + k <= leng:
Substrings = Substrings.join(S[s:s+k])
Ans.append(Substrings)
k += 1
print(Ans)
|
class Fiction(Book):
def __init__(self, CatalogueNo, Title, Author, Format, Classification, Genre):
'''inherit Book class with additional attribute, Genre'''
Book.__init__(self, CatalogueNo, Title, Author, Format, Classification)
self.Genre = Genre
def __str__(self):
return ("{0} | {1} | {2} | {3} | {4} | {5}".format(self.CatalogueNo, self.Title, self.Author, self.Format, self.Classification, self.Genre))
class NonFiction(Book):
def __init__(self, CatalogueNo, Title, Author, Format, Classification, DeweyNumber):
'''inherit Book class with additional attribute, Genre'''
Book.__init__(self, CatalogueNo, Title, Author, Format, Classification)
self.DeweyNumber = DeweyNumber
def __str__(self):
return ("{0} | {1} | {2} | {3} | {4} | {5}".format(self.CatalogueNo, self.Title, self.Author, self.Format, self.Classification, self.DeweyNumber))
def UPDATEBOOKS():
# check if BOOK.DAT exists
if not path.isfile("BOOK.DAT"):
print("*Error: The file BOOK.DAT does not exist.*")
return
with open("BOOK.DAT", "r") as infile:
outfile = "UBOOK.DAT"
# display the creation date and number of book data stored in the file
CreationDate, NumberOfBooks = infile.readline().split(" | ")
CreationDate = CreationDate[8:] + CreationDate[3:5] + CreationDate[:2]
print("Creation Date: {0}".format(CreationDate))
print("# Books: {0}".format(NumberOfBooks))
print()
#write creation date and number of book data stored in the file on UBOOK.DAT
print("Creation Date: {0}".format(CreationDate), file=outfile)
print("# Books: {0}".format(NumberOfBooks), file=outfile)
print()
# display the headings
print("{0:<20}{1:<30}{2:<30}{3:<15}{4:<11}{5:<11}{6:<11}"
.format("Catalogue No", "Title", "Author", "Book Type", "Classification", "DeweyNumber", "Genre"))
print('-'*95)
#write headings on UBOOK.DAT
print("{0:<20}{1:<30}{2:<30}{3:<15}{4:<11}{5:<11}{6:<11}"
.format("Catalogue No", "Title", "Author", "Book Type", "Classification", "DeweyNumber", "Genre"), file=outfile)
print('-'*95, file = outfile)
# display the info for each book data stored in the file and write on UBOOK.DAT whilst asking for additional input
for line in infile:
CatalogueNo, Title, Author, Format = line.split(" | ")
getClassification()
if Classification[0] == F:
DeweyNumber = 000.000
getGenre()
elif Classification[0] == N:
Genre = 'NONE'
getDeweyNumber()
Format = str(formatFullName(Format[:-1]))
print("{0:<20}{1:<30}{2:<30}{3:<15}{4:<11}{5:<11}{6:<11}"
.format(CatalogueNo, Title, Author, Format ,Classification, DeweyNumber, Genre))
print("{0:<20}{1:<30}{2:<30}{3:<15}{4:<11}{5:<11}{6:<11}"
.format(CatalogueNo, Title, Author, Format ,Classification, DeweyNumber, Genre),file =outfile)
#write everything into a file
def getClassification():
while True:
Classification = input("Enter Classification: ")
if (Classification.isalpha()):
print()
return Classification
print("*Invalid input. Classification should be alphabetic*")
def getGenre():
while True:
Genre = input("Enter Genre: ")
if (Genreisalpha()):
print()
return Genre
print("*Invalid input. Genre should be alphabetic*")
def getDeweyNumber():
while True:
DeweyNumber = input("Enter DeweyNumber: ")
if (len(DeweyNumber) == 7
and DeweyNumber[3] == '.'):
print()
return DeweyNumber
print("*Invalid input. DeweyNumber is in the form 999.999.*")
|
from selenium import webdriver
from selenium.webdriver.common.by import By
keyword = input("Enter the item you want to search: ")
sort = input('Sorting By: '
'Enter "r" for ratings, '
'"c" for cheapest, '
'"h" for expensive, '
'"s" for standard: ').lower()
number_of_items = int(input("Enter the number of items from 1-40: "))
driver = webdriver.Chrome(executable_path="/Users/loftymier/PycharmProjects/web_automation/chromedriver")
driver.get('https://www.rakuten.co.jp')
def search_():
driver.find_element(By.ID, "sitem").click()
driver.find_element(By.ID, "sitem").send_keys(keyword)
driver.find_element(By.ID, "searchBtn").click()
list_results = driver.find_elements(By.CLASS_NAME, "searchresultitems")
return list_results
|
import math
a = float(input("Digite o valor de a: "))
if (a == 0 ):
print("A equação não é do 2 grau.")
else:
b = float(input("Digite o valor de b: "))
c = float(input("Digite o valor de c: "))
delta = (b ** 2) - 4 * a * c
if delta < 0:
print("Não tem raizes")
elif delta == 0 :
print("A equação possui 1 raiz real")
print(f"O valor de delta é {delta}")
raiz = -b / 2 * a
print(f"A raiz é {raiz}")
else:
print("A equação possui 2 raizes reais.")
print(f"O valor de delta é {delta}")
raiz1 = (-b + math.sqrt(delta)) / (2 * a)
raiz2 = (-b - math.sqrt(delta)) / (2 * a)
print(f"Raiz 1 é {raiz1} e raiz 2 é {raiz2}")
|
#Faça um Programa que leia 4 notas, mostre as notas e a média na tela.
notas = []
for i in range(4):
notas.append(float(input(f'Digite {i+1}ª nota: ')))
soma = 0
for i in (notas):
soma = soma + i
print(i)
print(f'A média é {soma/len(notas)}') |
segundos = int(input())
##Calcular a quantidade de horas
horas = segundos // 3600
##Calcular a quantidade de minutos
temporestante = segundos - (horas * 3600)
minutos = temporestante // 60
##Calcular a quantidade de segundos
segundos = temporestante % 60
print('{}:{}:{}'.format(horas,minutos,segundos)) |
#Um funcionário de uma empresa recebe aumento salarial anualmente: Sabe-se que:
#Esse funcionário foi contratado em 1995, com salário inicial de R$ 1.000,00;
#Em 1996 recebeu aumento de 1,5% sobre seu salário inicial;
#A partir de 1997 (inclusive), os aumentos salariais sempre correspondem ao dobro do percentual do ano anterior. Faça um programa que determine o salário atual desse funcionário. Após concluir isto, altere o programa permitindo que o usuário digite o salário inicial do funcionário.
salario = float(input("Digite o salário: "))
aumento = 1.5
ano = 1996
while ano < 2019:
aumento = aumento * 2
ano = ano + 1
total = (1+aumento) * (salario/100)
print(total)
|
#Você foi contratado para desenvolver um programa que leia o resultado da enquete e informe ao final o resultado da mesma. O programa deverá ler os valores até ser informado o valor 0, que encerra a entrada dos dados. Não deverão ser aceitos valores além dos válidos para o programa (0 a 6). Os valores referentes a cada uma das opções devem ser armazenados num vetor. Após os dados terem sido completamente informados, o programa deverá calcular a percentual de cada um dos concorrentes e informar o vencedor da enquete. O formato da saída foi dado pela empresa, e é o seguinte:
resposta = 1
resultado = [0,0,0,0,0,0]
soma = 0
SO =['Windows Server', 'Unix', 'Linux', 'Netware', 'Mac OS', 'Outro']
while resposta != 0 :
print("Qual o melhor Sistema Operacional para uso em servidores?")
print("As possíveis respostas são : ")
print("1- Windows Server")
print("2- Unix")
print("3- Linux")
print("4- Netware")
print("5- Mac OS")
print("6- Outro")
resposta = int(input("Qual é a resposta? "))
if resposta >0 and resposta < 7:
resultado[resposta-1] = resultado[resposta-1] + 1
soma += 1
print(resultado)
for i in range(6):
print(f'{SO[i]} {resultado[i]} {resultado[i]*100/soma:.0f}') |
import math
a=int(input("Digite o valor de a: "))
b=int(input("Digite o valor de b: "))
c=int(input("Digite o valor de c: "))
delta = b**2 - 4 * a * c
if delta < 0:
print('Impossivel Calcular')
else:
x1 = (-b + math.sqrt(delta))/(2 * a)
x2 = (-b - math.sqrt(delta))/(2 * a)
if delta == 0:
print(x1)
else:
print(x1)
print(x2)
|
import re
def check_username(name):
phone_pattern = re.compile("^1[345678]\d{9}$")
is_phone = phone_pattern.match(name)
if is_phone:
print("是手机号")
return True
else:
email_pattern = re.compile("^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$")
is_email = email_pattern.match(name)
if is_email():
print("是邮箱")
return True
return False
check_username("23") |
"""
insertion_sort.py
This module implements insertion sort on an unsorted list and returns a sorted list.
Insertion Sort Overview:
------------------------
Uses insertion of elements in to the list to sort the list.
Pre: an unsorted list[0,...,n] of integers.
Post: returns a sorted list[0,...,n] in ascending order.
Time Complexity: O(n^2)
Space Complexity: O(n) total
Stable: Yes
Psuedo Code: CLRS. Introduction to Algorithms. 3rd ed.
insertion_sort.sort(list) -> sorted_list
"""
def sort(seq):
for n in range(1, len(seq)):
item = seq[n]
hole = n
while hole > 0 and seq[hole - 1] > item:
seq[hole] = seq[hole - 1]
hole = hole - 1
seq[hole] = item
return seq
|
"""
rabinkarp_search.py
This module implements Rabin-Karp search on a given string.
Rabin-Karp Search Overview:
------------------------
Search for a substring in a given string, by comparing hash values of the strings.
Pre: two strings, one to search in and one to search for.
Post: returns a list of indices where the substring was found
Time Complexity: O(nm)
Psuedo Code: http://en.wikipedia.org/wiki/Rabin-Karp_algorithm
rabinkarp_search.search(searchString, targetString) -> list[integers]
rabinkarp_search.search(searchString, targetString) -> list[empty]
"""
from hashlib import md5
def search(s, sub):
n, m = len(s), len(sub)
hsub_digest = md5(sub).digest()
offsets = []
if m > n:
return offsets
for i in xrange(n - m + 1):
if md5(s[i:i + m]).digest() == hsub_digest:
if s[i:i + m] == sub:
offsets.append(i)
return offsets
|
import random
class Game(object):
def __init__(self):
player1 = Player(self, "Mr. Miyamoto", True)
player2 = Player(self, "Tom", False)
self.players = [player1, player2]
self.current_player = 0
self.winner = None
self.setup()
def clone(self):
g = Game()
g.current_player = self.current_player
g.winner = self.winner
g.board = self.board.clone(self.players)
return g
def setup(self):
self.board = Board()
for p in self.players:
self.setup_player(p)
def setup_player(self, player):
if player.top:
reflect = 1
adjust_x = 0
adjust_y = 0
else:
reflect = -1
adjust_x = 8
adjust_y = 8
pieces = [
(King, 4, 0),
(Rook, 7, 1),
(Bishop, 1, 1),
(Gold_General, 3, 0),
(Gold_General, 5, 0),
(Silver_General, 2, 0),
(Silver_General, 6, 0),
(Knight, 1, 0),
(Knight, 7, 0),
(Lance, 0, 0),
(Lance, 8, 0),
(Pawn, 0, 2),
(Pawn, 1, 2),
(Pawn, 2, 2),
(Pawn, 3, 2),
(Pawn, 4, 2),
(Pawn, 5, 2),
(Pawn, 6, 2),
(Pawn, 7, 2),
(Pawn, 8, 2),
]
def place_piece(klass, x, y):
piece = klass(self.board, player, x * reflect + adjust_x, y * reflect + adjust_y)
for k, x, y in pieces:
place_piece(k, x, y)
def get_current_player(self):
return self.players[self.current_player]
class Board(object):
def __init__(self):
self.width = 9
self.height = 9
self.cells = []
for i in range(self.height):
row = []
for j in range(self.width):
row.append(None)
self.cells.append(row)
def clone(self, players):
b = Board()
for i in range(self.height):
for j in range(self.width):
if self.cells[i][j] is not None:
b.cells[i][j] = self.cells[i][j].clone(b, players)
else:
b.cells[i][j] = None
return b
def set_cell(self, x, y, piece):
self.cells[y][x] = piece
def __str__(self):
s = ""
for i in range(self.height):
for j in range(self.width):
piece = self.cells[i][j]
if piece is None:
s = s + "."
else:
if piece.player.top:
s = s + str(piece)
else:
s = s + str(piece).lower()
s = s + "\n"
return s
def apply_move(self, move):
old_x = move.piece.x
old_y = move.piece.y
new_x = old_x + move.dx
new_y = old_y + move.dy
taken = self.cells[new_y][new_x]
won = False
if taken is not None:
won = taken.die()
self.set_cell(old_x, old_y, None)
move.piece.change_position(new_x, new_y)
self.set_cell(new_x, new_y, move.piece)
return won
def is_move_outside(self, move):
old_x = move.piece.x
old_y = move.piece.y
new_x = old_x + move.dx
new_y = old_y + move.dy
if new_x < 0:
return True
if new_y < 0:
return True
if new_x >= self.width:
return True
if new_y >= self.height:
return True
return False
def is_move_blocked(self, move):
old_x = move.piece.x
old_y = move.piece.y
new_x = old_x + move.dx
new_y = old_y + move.dy
p = self.cells[new_y][new_x]
if p is None:
return False
if move.piece.player == p.player:
return True
return False
def is_move_capture(self, move):
old_x = move.piece.x
old_y = move.piece.y
new_x = old_x + move.dx
new_y = old_y + move.dy
p = self.cells[new_y][new_x]
if p is None:
return False
if move.piece.player != p.player:
return True
return False
def get_pieces(self):
pieces = []
for row in self.cells:
for cell in row:
if cell is not None:
pieces.append(cell)
return pieces
class Piece(object):
def __init__(self, board, player, x, y):
self.board = board
self.x = x
self.y = y
self.board.set_cell(x, y, self)
self.player = player
self.dead = False
def clone(self, board, players):
if players[0].name == self.player.name:
player = players[0]
else:
player = players[1]
p = self.__class__(board, player, self.x, self.y)
return p
def die(self):
self.dead = True
return False
def change_position(self, x, y):
self.x = x
self.y = y
def get_moves(self):
moves = self.get_raw_moves()
def is_ok(move):
return not self.board.is_move_outside(move) and not self.board.is_move_blocked(move)
return filter(is_ok, moves)
class King(Piece):
def __init__(self, board, player, x, y):
Piece.__init__(self, board, player, x, y)
self.name = 'King'
def __str__(self):
return "K"
def die(self):
Piece.die(self)
return True
def get_raw_moves(self):
l = [(0,1), (1,0), (0,-1), (-1, 0), (-1, 1), (1, -1), (-1, -1), (1, 1)]
moves = []
for dx, dy in l:
m = Move(self, dx, dy)
moves.append(m)
return moves
class Rook(Piece):
def __init__(self, board, player, x, y):
Piece.__init__(self, board, player, x, y)
self.name = 'Rook'
def __str__(self):
return "R"
def get_raw_moves(self):
l = [(-1, 0), (0, -1), (0, 1), (1, 0)]
def is_ok(move):
return not self.board.is_move_outside(move) and not self.board.is_move_blocked(move) and not self.board.is_move_capture(move)
moves = []
for dx, dy in l:
i = 1
while True:
m = Move(self, dx*i, dy*i)
moves.append(m)
if not is_ok(m):
break
i = i + 1
return moves
class Bishop(Piece):
def __init__(self, board, player, x, y):
Piece.__init__(self, board, player, x, y)
self.name = 'Bishop'
def __str__(self):
return "B"
def get_raw_moves(self):
l = [(-1, -1), (-1, 1), (1, -1), (1, 1)]
def is_ok(move):
return not self.board.is_move_outside(move) and not self.board.is_move_blocked(move) and not self.board.is_move_capture(move)
moves = []
for dx, dy in l:
i = 1
while True:
m = Move(self, dx*i, dy*i)
moves.append(m)
if not is_ok(m):
break
i = i + 1
return moves
class Gold_General(Piece):
def __init__(self, board, player, x, y):
Piece.__init__(self, board, player, x, y)
self.name = 'Gold General'
def __str__(self):
return "G"
def get_raw_moves(self):
if self.player.top:
dy = 1
else:
dy = -1
l = [(0,1), (0,-1), (-1,0), (1,0), (-1,dy), (1,dy)]
moves = []
for dx, dy in l:
m = Move(self, dx, dy)
moves.append(m)
return moves
class Silver_General(Piece):
def __init__(self, board, player, x, y):
Piece.__init__(self, board, player, x, y)
self.name = 'Silver General'
def __str__(self):
return "S"
def get_raw_moves(self):
if self.player.top:
dy = 1
else:
dy = -1
l = [(-1,1), (1,1), (-1,-1), (1,-1), (0,dy)]
moves = []
for dx, dy in l:
m = Move(self, dx, dy)
moves.append(m)
return moves
class Knight(Piece):
def __init__(self, board, player, x, y):
Piece.__init__(self, board, player, x, y)
self.name = 'Knight'
def __str__(self):
return "N"
def get_raw_moves(self):
if self.player.top:
dy = 2
else:
dy = -2
l = [(1,dy), (-1,dy)]
moves = []
for dx, dy in l:
m = Move(self, dx, dy)
moves.append(m)
return moves
class Lance(Piece):
def __init__(self, board, player, x, y):
Piece.__init__(self, board, player, x, y)
self.name = 'Lance'
def __str__(self):
return "L"
def get_raw_moves(self):
if self.player.top:
dy = 1
else:
dy = -1
l = [(0,dy)]
def is_ok(move):
return not self.board.is_move_outside(move) and not self.board.is_move_blocked(move) and not self.board.is_move_capture(move)
moves = []
for dx, dy in l:
i = 1
while True:
m = Move(self, dx*i, dy*i)
moves.append(m)
if not is_ok(m):
break
i = i + 1
return moves
class Pawn(Piece):
def __init__(self, board, player, x, y):
Piece.__init__(self, board, player, x, y)
self.name = 'Pawn'
def __str__(self):
return "P"
def get_raw_moves(self):
if self.player.top:
dy = 1
else:
dy = -1
l = [(0,dy)]
moves = []
for dx, dy in l:
m = Move(self, dx, dy)
moves.append(m)
return moves
class Player(object):
def __init__(self, game, name, top):
self.name = name
self.game = game
self.top = top
def clone(self, game):
if game.players[0].name == self.name:
return game.players[0]
else:
return game.players[1]
def __str__(self):
return self.name
def get_pieces(self):
def is_mine(p):
return p.player.name == self.name
pieces = filter(is_mine, self.game.board.get_pieces())
return pieces
def get_moves(self):
moves = []
if self.game.winner is not None:
return moves
for piece in self.get_pieces():
moves = moves + piece.get_moves()
return moves
def do_move(self, move):
won = self.game.board.apply_move(move)
self.game.current_player = 1 - self.game.current_player
if won:
self.game.winner = self
return won
class Move(object):
def __init__(self, piece, dx, dy):
self.piece = piece
self.dx = dx
self.dy = dy
def clone(self, game):
px = self.piece.x
py = self.piece.y
p = game.board.cells[py][px]
m = Move(p, self.dx, self.dy)
return m
def __str__(self):
return "%s:%d,%d" % (self.piece, self.dx, self.dy)
def test():
g = Game()
print g.board
for i in xrange(10):
p = g.get_current_player()
print "Player:", p
moves = p.get_moves()
if moves == []:
break
m = moves[random.randrange(0, len(moves))]
p.do_move(m)
print g.board
|
from bs4 import Beautifulsoup
import requests
example_webpage = '''
<html>
<head>
<title>Example Webpage</title>
</head>
<body>
<div class="wrapper">
<p>Content</p>
</div>
</body>
</html>
'''
class Webpage:
def __init__ ( self, url=None, html=None ):
self.url = url if url else None
self.html = html if html else requests.get(url).text
self.soup = BeautifulSoup(self.html, 'html.parser')
def get_title ( self ):
return self.soup.title.string
my_webpage = Webpage( html=example_webpage )
reddit = Webpage( url='https://reddit.com' )
print ( my_webpage.get_title() )
print ( reddit.get_title() ) |
import random
import sys
def show_rules():
print("""
RULES OF THE GAME
If you guess the number correctly ~~~ for every guess you used
and pass out a ~~~ for each remaining guess you have left.
Guess the number on first try, everyone but you drinks 2x your max guesses.
Guess the number correctly and it's a 3 or 7 reverse the order
of dinks consumed and passed out.
Type:
'help' to show these
'quit' to exit game
'restart' to restart
""")
show_rules()
def game():
# generate a random num between 1 and 10
secret_num = random.randint(1, 10)
# reversed if number is special number ( 3 or 7 )
reverse_flag = (True if secret_num == 3 or secret_num == 7 else False )
max_guesses = 3
guess_count = 0
while guess_count < max_guesses:
remaining_guesses = max_guesses - guess_count
# pluralize output message
pluralization = ("" if max_guesses - guess_count == 1 else "es")
try:
# get a number guess from player
guess = int(input("{} remaining guess{}. Guess a number between 1 and 10: ".format(remaining_guesses, pluralization)))
if guess is not range(1, 11): raise Exception
except Exception:
if guess.lower() == "help":
show_rules()
elif guess.lower() == "quit":
sys.exit("Bye!")
elif guess.lower() == 'restart':
game()
else:
print("{} isn't a number!".format(guess))
except Exception:
print('Number out of range')
else:
# correct guess
if guess == secret_num:
# on first try
if guess_count == 0:
if reverse_flag:
print("First try! But the number was {} so you have to take {} drink(s)".format(secret_num, max_guesses * 2))
break
else:
print("First try! Everyone takes {}".format(max_guesses * 2))
break
# after first try
else:
if reverse_flag:
print("Reverse, reverse! Take {} and pass out {} drink(s)".format(remaining_guesses, guess_count))
break
else:
print("You got it! Take {} drink(s) and pass out {}".format(guess_count, remaining_guesses))
break
# incorrect guess
else:
guess_count += 1
if guess_count == max_guesses:
print("You lose. The number was {}. Drink {} sips".format(secret_num, max_guesses))
break
else:
if guess > secret_num:
print("Miss, guess lower!")
else:
print("Miss, guess higher!")
play_again = input("Do you want to play again? Y/n ")
if play_again.lower() != 'n':
game()
else:
print("Bye!")
game()
|
#The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order,
#but it also has a rather interesting sub-string divisibility property.
#Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following:
#d2d3d4=406 is divisible by 2
#d3d4d5=063 is divisible by 3
#d4d5d6=635 is divisible by 5
#d5d6d7=357 is divisible by 7
#d6d7d8=572 is divisible by 11
#d7d8d9=728 is divisible by 13
#d8d9d10=289 is divisible by 17
#Find the sum of all 0 to 9 pandigital numbers with this property.
def is_pandig(x):
a = str(x)
digits = list(int(e) for e in a)
checklist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
if sorted(digits) == checklist:
return True
def is_prim_div(x):
y = str(x)
if int(y[1:4]) % 2 == 0:
if int(y[2:5]) % 3 == 0:
if int(y[3:6]) % 5 == 0:
if int(y[4:7]) % 7 == 0:
if int(y[5:8]) % 11 == 0:
if int(y[6:9]) % 13 == 0:
if int(y[7:]) % 17 == 0:
return True
pandigs = [e for e in range(1000000000,9876543211) if is_pandig(e)]
primdivs = [e for e in pandigs if is_prim_div(e)]
print(f"The sum of all 0 to 9 pandigital numbers with this property is {sum(primdivs)}.") |
# --------------
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# code starts here
#loading data
df = pd.read_csv(path)
#calculating probability of fico credit score is grater that 700
p_a = len(df.fico[df.fico>700])/len(df.fico)
print(p_a)
#calculating probability of perpose is debt_consolation
p_b = len(df.purpose[df.purpose=='debt_consolidation'])/len(df.purpose)
print(p_b)
#creating subset having purpose of debt_consolidation
df1 = df[df.purpose=='debt_consolidation']
#print(df1)
#calculating P(B|A)
p_a_b = (len(df1[df1.fico>700])/len(df))/p_a
p_b_a = (len(df1[df1.fico>700])/len(df))/p_b
#print(p_a_b)
#print(p_b_a)
#checking the result
result = p_b_a == p_a
print(result)
# code ends here
# --------------
# code starts here
#calculate probability for having paid.back.loan == Yes
prob_lp = len(df[df['paid.back.loan']=='Yes'])/len(df)
print(prob_lp)
#calculate probability for having credit.plocy == Yes
prob_cs = len(df[df['credit.policy']=='Yes'])/len(df)
print(prob_cs)
#creating subset
new_df = df[df['paid.back.loan']=='Yes']
#print(new_df)
#calculating P(A|B)
prob_pd_cs = (len(new_df[new_df['credit.policy']=='Yes'])/len(df))/prob_lp
print(prob_pd_cs)
#calculating conditional probability i.e. P(B|A)
bayes = prob_pd_cs*prob_lp/prob_cs
print(bayes)
# code ends here
# --------------
# code starts here
#plot bar graph
df.purpose.value_counts(normalize=True).plot(kind='bar')
#creating subset
df1 = df[df['paid.back.loan']=='No']
#creating bar graph
df1.purpose.value_counts(normalize=True).plot(kind='bar')
plt.show()
# code ends here
# --------------
# code starts here
#calculate median of installment
inst_median = df.installment.median()
print(inst_median)
#calculate mean of installment
inst_mean = df.installment.mean()
print(inst_mean)
#plot histogram for installment
plt.hist(df['installment'])
plt.axvline(inst_mean,color='red')
plt.axvline(inst_median,color='green')
plt.show()
#plot histogram for log annual income
plt.hist(df['log.annual.inc'])
plt.axvline(df['log.annual.inc'].mean(),color='red')
plt.axvline(df['log.annual.inc'].median(),color='green')
plt.show()
# code ends here
|
def nth_row_pascal(n):
"""
:param: - n - index (0 based)
return - list() representing nth row of Pascal's triangle
"""
if n == 0:
return [1]
current_row = [1] # first row
for i in range(1, n+1):
previous_row = current_row
current_row = [1] # add default first element in the list
for j in range(1, i):
# an element at jth position in the current row is
## sum of element at j and j-1 position in the previous row
current_row.append(previous_row[j-1] + previous_row[j])
current_row.append(1) # add default last element in the list
return current_row
if __name__ == '__main__':
num = input('Enter the number of elements: ')
number_list = [x for x in range(int(num))]
print("Pascal's Triangle for {} elements".format(len(number_list)))
for number in number_list:
print(nth_row_pascal(number))
|
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, init_list=None):
self.head = None
if init_list:
for value in init_list:
self.append(value)
def append(self, value):
if self.head is None:
self.head = Node(value)
return
node = self.head
while node.next:
node = node.next
node.next = Node(value)
return
def print_list(self):
if self.head is None:
return None
node = self.head
while node:
print(node.value)
node = node.next
def isCircular(self):
"""
Determine whether the Linked List is circular or not
Args:
linked_list(obj): Linked List to be checked
Returns:
bool: Return True if the linked list is circular, return False otherwise
"""
if self.head is None:
return False
slow = self.head
fast = self.head
while fast and fast.next:
# slow pointer moves one node
slow = slow.next
# fast pointer moves two nodes
fast = fast.next.next
if slow == fast:
return True
return False
def main():
# create linked list
list_values = [3, 5, 19, 34, 2]
linked_list = LinkedList(list_values)
linked_list.append(4)
print('Linked List: ')
linked_list.print_list()
# creating a loop where tail points to second node
print('--- Creating a loop by connecting tail to second node ---')
loop_start = linked_list.head.next
node = linked_list.head
while node.next:
node = node.next
node.next = loop_start
print('Is loop circular? : ', linked_list.isCircular())
if __name__ == '__main__':
main()
|
##################################### Ejercicio 2.1
'''A continuación hemos creado unas variables "tres","tresconseis" y "hola" con unos valores almacenados en ellas. usando la función type debereis almacenar el tipo de datos que corresponde en las variables que creareis vosotros "typeTres", "typeTresConSeis" y "typeHola".'''
tres = 3
tresConSeis = 3.6
hola = "hola mundo"
# YOUR CODE HERE
typeTres = type(tres)
typeTresConSeis = type(tresConSeis)
typeHola = type(hola)
print (typeTres)
print (typeTresConSeis)
print (typeHola)
##################################### Ejercicio 2.2
'''En el siguiente fragmento de código tenemos un input en el que le solicitamos al usuario cuantos litros de agua se ha bebido hoy y se los vamos a restar a la variable "aguaEnDeposito" de modo que tendremos un control de cuando comprar agua.
Realiza una conversión del tipo de datos del input para que sea de tipo int y asígnalo a la variable consumo de modo que podamos hacer la resta.'''
# YOUR CODE HERE
aguaEnDeposito = 50
consumo = input ('¿Cuantos litros de agua has consumido hoy?')
resultado = aguaEnDeposito - int(consumo)
print (f'Quedan {resultado} litros de agua')
##################################### Ejercicio 2.3
'''Modifica las siguientes operaciones añadiendoles paréntesis de modo que el resultado sea el indicado en el comentario. Añade las instrucciones print necesarias para visualizar en pantalla los resultados.'''
# YOUR CODE HERE
primera = (3+2)*5 #25
print (f'Primera: {primera}')
segunda = 3+3**(2+1) #30
print (f'Segunda: {segunda}')
tercera = 3/5-2 #-1.4
print (f'Tercera: {tercera}')
##################################### Ejercicio 2.4
'''El código a continuación tiene un input que solicitará tu nombre y un print que tratará de darte la bienvenida. Modifica la variable bienvenida de modo que concatene tu nombre dentro del mensaje de bienvenida.'''
# YOUR CODE HERE
nombre = input('¿Como te llamas? ')
bienvenida = 'Bienvenid@ : ' + str(nombre) #modifica esta línea
print(bienvenida)
##################################### Ejercicio 3.1
'''A continuación tenemos un input en el que le pediremos un número al usuario y lo guardaremos en la variable entrada. Después, deberemos guardar en la variable mayorQueTres el valor True si ese número es mayor que tres y False en caso contrario. Nota, acordaros de realizar la conversión de tipos en el input'''
# YOUR CODE HERE
entrada = input('Introduce un número:')
##################################### Ejercicio 5.1
'''Define la función holamundo de forma que haga una llamada al comando print con el mensaje 'Hola mundo'. En la celda siguiente haz uso de dicha función.'''
# YOUR CODE HERE
def holamundo():
print('Hola mundo!')
# YOUR CODE HERE
holamundo()
##################################### Ejercicio5.2
'''Define la función miconcatena la cual haga solicite dos parámetros, la función deberá hacer un print concatenando ambos parámetros como cadena.'''
# YOUR CODE HERE
def miconcatena(texto1, texto2):
cadena = texto1 + ' ' + texto2
return cadena
# YOUR CODE HERE
miconcatena('Hola a todos.', 'Soy Mariela')
##################################### Ejercicio 5.3
'''A continuación define la función cuentapalabras la cual tendrá 2 parámetros, el primer parámetro será un texto y el segundo una palabra.
La función deberá devolver usando el comando return el número de veces que aparece la palabra dentro del texto en una variable de tipo entero.
Devolverá 0 si no aparece ninguna vez.
Ejemplo:
cuentapalabras('eran uno dos y tres los valientes', 'eran') 1 cuentapalabras('dos manzanas tres peras dos naranjas', 'dos') 2'''
# YOUR CODE HERE
def cuentapalabras(texto, palabra):
cont = texto.count(palabra)
print (cont)
# YOUR CODE HERE
cuentapalabras('Aquí voy De malas pero voy Haciendo malabares pa pagar la renta', 'voy')
##################################### Ejercicio 5.4
'''Define un módulo constantes.py en la misma carpeta que este ejercicio, en ese módulo deberás definir las constantes:
PI = 3.1416
G = 9.8
E = 2.7183
GR = 1.618033
F = 4.669201
En el código a continuación importa el módulo que acabas de crear y muestra con el comando print los valores que has definido.'''
# YOUR CODE HERE
#constantes.py
PI = 3.1416
G = 9.8
E = 2.7183
GR = 1.618033
F = 4.669201
# YOUR CODE HERE
import constantes
print (constantes.PI)
##################################### Ejercicio 6.1
'''Escribe una función **cambiaprimera** que dada una cadena nos devuelva la misma cadena pero reemplazando todas las veces que aparezca la primera letra por el símbolo $, excepto en esa primera letra.
Ejemplo:
- cambiaprimera('casco')
- -> 'cas$o'
- cambiaprimera('rocodromo')
- -> 'rocod$omo' '''
# YOUR CODE HERE
def cambiaprimera(cadena):
indice = 0
retorno=""
for letra in cadena:
#print (f'Indice: ',indice, ' Letra: ', letra, ' Cadena indice: ', cadena[indice])
if ((letra == cadena[0]) and (indice > 0)):
retorno = retorno + "$"
#print (f'SI -- Vuelta: ', indice, ' - retorno', retorno)
else:
retorno = retorno + letra
#print (f'NO -- Vuelta: ', indice, ' - retorno', retorno)
indice = indice + 1
return (retorno)
# YOUR CODE HERE
print(cambiaprimera("casco"))
##################################### Ejercicio 6.2
'''Escribe una función concatenamal que, dadas dos cadenas nos devuelva una sola cadena combinando ambas unidas por un espacio, pero cambiando las dos primeras letras de cada palabra.
Ejemplo:
concatenamal('casco','polipo')
-> 'posco calipo'
concatenamal('rocodromo','encrucijada')
-> 'encodromo rocrucijada' '''
# YOUR CODE HERE
def concatenamal(palabra1, palabra2):
inicio1 = palabra1[0:2]
inicio2 = palabra2[0:2]
fin1 = palabra1[2:]
fin2 = palabra2[2:]
'''print(palabra1)
print(palabra2)
print(inicio1)
print(inicio2)
print(fin1)
print(fin2)'''
resultado = inicio2 + fin1 + ' ' + inicio1 + fin2
return resultado
# YOUR CODE HERE
print (concatenamal('casco','polipo'))
##################################### Ejercicio 6.3
'''Escribe una función enelmedio que dadas dos cadenas nos devuelva una sola cadena de modo que la segunda quede en el medio de la primera tal y como se muestra en los ejemplos.
Ejemplo:
enelmedio('[::]','polipo')
-> '[:polipo:]'
enelmedio('rocodromo','XXX')
-> 'rocoXXXdromo'
enelmedio('-:..:-','Título')
-> '-:.Título.:-' '''
# YOUR CODE HERE
def enelmedio(palabra1, palabra2):
largo1 = len(palabra1)
mitad = largo1 / 2
parte1 = palabra1[:int(mitad)]
parte2 = palabra1[int(mitad):]
resultado = parte1 + palabra2 + parte2
return resultado
# YOUR CODE HERE
print(enelmedio('-:..:-','Título'))
##################################### Ejercicio 6.4
'''Escribe una función cambiamayus que dadas una cadena nos devuelva la misma cadena cambiando las mayusculas por minúsculas y viceversa.
Ejemplo:
cambiamayus('Castilla')
-> 'cASTILLA'
cambiamayus('ENTretenido')
-> 'entRETENIDO'
cambiamayus('PaliNdrOmo')
-> 'pALInDRoMO' '''
# YOUR CODE HERE
def cambiamayus(palabra):
nuevapal = ''
for letra in palabra:
ind = ord(letra)
#print(f'Cod: ', ind, 'LEtra: ', letra)
if ind >= 65 and ind <= 90:
#Mayus
nuevapal = nuevapal + letra.lower()
else:
nuevapal = nuevapal + letra.upper()
return nuevapal
# YOUR CODE HERE
print(cambiamayus('PaliNdrOmo'))
##################################### Ejercicio 7.1
'''En el archivo adjunto 'quijote.txt' hemos dejado los primeros párrafos del libro que comparte nombre con el archivo.
La función primerafrase(numerodeparrafo) deberá abrir el archivo y devolver el contenido de la primera frase del párrafo indicado (siendo 0 el primer párrafo). La primera frase estará definida por los caracteres que se encuentran en el párrafo hasta llegar al primer símbolo de puntuación (cualquiera del grupo ,.:;), tal y como se muestra en el ejemplo a continuación.
primerafrase(0)
-> 'En un lugar de la Mancha'
primerafrase(2)
-> 'Con estas razones perdía el pobre caballero el juicio' '''
# YOUR CODE HERE
def primerafrase(numerodeparrafo):
fichero = open('quijote.txt', 'r', encoding='utf-8')
texto = fichero.read()
parrafos = texto.split('\n')
while '' in parrafos:
parrafos.remove('')
parrafoseleccionado=parrafos[numerodeparrafo]
pos = 0
lafra = ''
for letra in parrafoseleccionado:
if letra == ',' or letra == '.' or letra == ':' or letra == ';':
#print(parrafoseleccionado[:pos])
lafra = (f'La primera frase del parrafo {numerodeparrafo} es: '+ str(parrafoseleccionado[:pos]))
break
pos = pos + 1
fichero.close()
return(lafra)
primerafrase(7) |
# Uses python3
# Good job! (Max time used: 0.03/5.00, max memory used: 9613312/536870912.)
import sys
def is_greater_or_equal(n,m):
return n + m > m + n
def largest_number(a):
a = sorted(a, reverse=True)
res = ""
while len(a) > 0:
maxDigit = '0'
for digit in a:
if is_greater_or_equal(digit, maxDigit):
maxDigit = digit
res += maxDigit
a.remove(maxDigit)
return res
if __name__ == '__main__':
input = sys.stdin.read()
data = input.split()
a = data[1:]
print(largest_number(a))
|
class Bag(float):
def valid(self):
return self <= 500
def cost(self):
if self.valid():
return 0 if self <= 25 else (1500 * self if self <= 300 else 2500 * self)
class AirPlaneCargo(tuple):
def __init__(self, bags: iter):
self.__bags = bags
self.__length = len(bags)
def number_of_bags(self):
return self.__length
def heaviest(self):
return max(self.__bags)
def lighter(self):
return min(self.__bags)
def med(self):
return sum(self.__bags) / self.__length
def money_income(self):
cop = sum(bag.cost() for bag in self.__bags)
usd = cop * 3400
return cop, usd
def __len__(self):
return self.__length
def number_input(msg):
while True:
try:
return float(input(msg))
except ValueError:
pass
def main():
bags = []
for n in range(15):
weigth = number_input(f"Bag {n+1} weigh: ")
bags.append(Bag(weigth))
cargo = AirPlaneCargo(bags)
print()
print("Number of bags:", cargo.number_of_bags())
print("Heaviest bag:", cargo.heaviest())
print("Lighter bag:", cargo.lighter())
print("Med of weighs:", cargo.med())
print("Incomes:\n\tUSD={}\n\tCOP={}".format(*cargo.money_income()))
if __name__ == '__main__':
main()
|
def main():
rows = int(input("Number of rows: "))
for current_row in range(0, rows+1):
if current_row % 2:
continue
print(int((rows-current_row) / 2)*" " + "@"*current_row + int((rows-current_row) / 2)*" ")
if __name__ == '__main__':
main()
|
def main():
time_ = float(input("Time: "))
speed = float(input("Speed: "))
acceleration = float(input("Acceleration: "))
distance = speed * time_ + ((acceleration * (time_**2)) / 2)
print(distance)
if __name__ == '__main__':
main()
|
def main():
smaller = 0
bigger = 0
while True:
try:
number = float(input("Number: "))
if number > 100:
bigger += 1
elif number < 100:
smaller += 1
except ValueError:
break
print("Smaller: ", smaller)
print("Bigger: ", bigger)
if __name__ == '__main__':
main()
|
def main():
n = int(input("Numero: "))
m = int(input("Numero: "))
sum_ = 0
if n < m:
if n < 0:
n = 0
for number in range(n, m+1):
sum_ += number
print(sum_)
if __name__ == '__main__':
main()
|
def main():
distance = float(input("Distance: "))
days = int(input("Days: "))
if distance > 1000 and days > 7:
discount = 0.85
else:
discount = 1
result = distance * 5000 * discount
if result < 100000:
result = 100000
print(result)
if __name__ == '__main__':
main()
|
# Based on https://www.youtube.com/watch?v=YQc2ysYubYc
# Transform the integer part of the number
def decimal_integer_to_binary(number):
number = int(number)
result = ""
while number != 0:
division = number % 2
if division:
result += "1"
else:
result += "0"
number = int(number / 2)
return result[::-1]
# Transform the decimal part of the number
def decimal_fraction_to_binary(number):
number = number - int(number)
result = ""
while number != 0:
number = number * 2
if int(number) > 0:
number = number - int(number)
result += "1"
else:
result += "0"
return result
def decimal_to_binary(number):
integer_part = decimal_integer_to_binary(number)
decimal_part = decimal_fraction_to_binary(number)
if not len(integer_part):
integer_part = "0"
# when the decimal part wasn't ".0" add to it the dot to verify that
if len(decimal_part):
decimal_part = "." + decimal_part
return integer_part + decimal_part
def main():
number = float(input("Decimal number: "))
binary = decimal_to_binary(number)
print("Binary:", binary)
if __name__ == '__main__':
main()
|
# Based on https://www.youtube.com/watch?v=YQc2ysYubYc
# Transform the integer binary part of the number
def binary_to_decimal_integer(number):
if "." in number:
number = number.split(".")[0]
result = 0
for index, bit in enumerate(number[::-1]):
if bit == "1":
result += 2**index
return result
# Transform the decimal binary part of the number
def binary_to_decimal_fraction(number):
if "." in number:
number = number.split(".")[1]
else:
number = "0"
result = 0
for index, bit in enumerate(number):
result += int(bit) * (2**(-1*(index+1)))
return result
def binary_to_decimal(number):
integer_part = binary_to_decimal_integer(number)
decimal_part = binary_to_decimal_fraction(number)
return integer_part + decimal_part
def decimal_integer_to_octal(number):
number = int(number)
result = ""
while number != 0:
division = number / 8
number = int(division)
result += str(int((division - int(division)) * 8))
return result[::-1]
def decimal_fraction_to_octal(number):
result = ""
number = number - int(number)
while number != 0:
number *= 8
if int(number) > 0:
result += str(int(number))
number = number - int(number)
else:
result += "0"
return result
def decimal_to_octal(number):
integer_part = decimal_integer_to_octal(number)
decimal_part = decimal_fraction_to_octal(number)
if not len(integer_part):
integer_part = "0"
if len(decimal_part):
decimal_part = "." + decimal_part
return integer_part + decimal_part
def binary_to_octal(number):
return decimal_to_octal(binary_to_decimal(number))
def main():
number = input("Binary: ")
result = binary_to_octal(number)
print("Octal:", result)
if __name__ == '__main__':
main()
|
ref = {"A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15}
def hex_to_decimal_integer(number):
if "." in number:
number = number.split('.')[0]
result = 0
for index, multiplier in enumerate(range(len(number) - 1, -1, -1)):
value = number[index]
if value in ref.keys():
value = ref[value]
else:
value = int(value)
result += value * (16 ** multiplier)
return result
# I don't know why but this have a little error margin
def hex_to_decimal_fraction(number):
if "." in number:
number = number.split(".")[1]
else:
number = "0"
result = 0
for index, value in enumerate(number):
if value in ref.keys():
value = ref[value]
else:
value = int(value)
result += int(value) * (16 ** (-1 * (index + 1)))
return result
def hex_to_decimal(number):
integer_part = hex_to_decimal_integer(number)
decimal_part = hex_to_decimal_fraction(number)
return integer_part + decimal_part
def main():
number = input("Hex: ")
result = hex_to_decimal(number)
print("Number:", result)
if __name__ == '__main__':
main()
|
import random
from random import random
import numpy as np
def weighted_choice(objects, weights):
""" returns randomly an element from the sequence of 'objects',
the likelihood of the objects is weighted according
to the sequence of 'weights', i.e. percentages."""
weights = np.array(weights, dtype=np.float64)
sum_of_weights = weights.sum()
# standardization:
np.multiply(weights, 1 / sum_of_weights, weights)
weights = weights.cumsum()
x = random()
for i in range(len(weights)):
if x < weights[i]:
return objects[i]
|
#Looping Problem 8
for n in range(11):
for c in range(n):
print (c, end=" ")
print ()
|
class Cat():
def __init__(self):
self.name = ""
self.color = ""
self.weight = 0
cat = Cat()
cat.name = "Spot"
cat.color = "black"
cat.weight = 16
class Monster():
def __init__(self):
self.name = ""
self.health = 0
def decrease_health(self, amount):
self.health -= amount
if self.health < 0:
print ("The monster died.")
|
#looping problem 2
for n in range(10):
print ("*", end=" ")
print ()
for n in range(5):
print ("*", end=" ")
print ()
for n in range(20):
print ("*", end=" ")
|
def inputs():
a=int(input("Enter first no."))
b=int(input("Enter first no."))
return a,b
a,b=inputs()
if(a>b):
print("{0} is greater than {1}".format(a,b))
elif(b>a):
print("{0} is greater than {1}".format(b,a))
else:
print("They are equal")
|
#!/usr/bin/env python3
# this example is about re-writing URLs. It assumes we are moving a series
# of web sites formt eh domain oldplace.com to the domain newplace.org and
# need to update a document containing a list of URLs.
import re
urls = \
'''The report is <a href = https://docs.oldplace.com/chris/report> here </a>
Access your mailbox <a href = http://mail.oldplace.com/mailbox?id=5432"> here </a>
The full events list is at http://events.oldplace.com/index.html'''
regex = r"(https?)://(\w+)\.oldplace\.com/(\S+)"
newurls = re.sub(regex, r"\1://\2.newplace.org/\3", urls)
print(re.findall(regex, urls)) # debu only
print(newurls) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.