text
stringlengths
37
1.41M
'''Crie um programa que leia varios numeros inteiros pelo teclado. O programa só vai parar quando o usuario digiitar o valor 999. que é a condiçao de parada.No final mostre quantos numeros foram digitados e qual foi a soma entre eles''' total = 0 n2 = 0 while True: total = total+1 n = int(input('Digite um numero')) n1 = n n2 = (n1+n2) n2 = n2 if n == 999: break print(f'total de numeros digitados forão: {total-1}') print(f'A soma dos numeros digitados foi:{n2-999}')
'''faça um programa que calcula a soma entre todos os numeros impares que são multiplos de três e que se encontram no intervalo de 1 até 500''' soma = 0 cont = 0 for c in range(1,501,2): if c %3 == 0:#se divisivel por 3 é multiplo de 3 sendo resto =0 então é multiplo de 3 soma += c # no caso aqui é um acumulador soma recebe c + soma a cada repitição cont += 1# no caso contador cont recebe cont +1 em cada repetição print('A soma de todos os {} valores solicitados é {}'.format(cont,soma))
from math import floor,ceil,sqrt cateto_op = float(input('entre com o valor do cateto oposto')) cateto_ad = float(input('entre com o valor do cateto adjacente')) soma_dos_lados_do_triangulo_retangulo_ao_quadrado = ((cateto_op**2)+(cateto_ad**2)) Raiz_quadrada_da_soma_dos_Lados_ao_quadrado = sqrt(soma_dos_lados_do_triangulo_retangulo_ao_quadrado) print ('O valor da ipotenusa é {:.2f}'.format(Raiz_quadrada_da_soma_dos_Lados_ao_quadrado))
import matplotlib.pyplot as plt #create lists of x and y values x = [1,2,3,4] y = [5,7,4,6] plt.plot(x,y) # plot x and y using default line style and color plt.xlabel('x label') plt.ylabel('y label') plt.title('Default Arguments\nLine Style & Color') # everything is drawn in the background, call show to see it plt.show()
# lesson 5c - arbitrary number of arguments # arbitrary arguments, *args def some_function(*names): print('there are ' + str(len(names)) + ' names') for n in names: print(n) # call some_function. some_function('Bart', 'Homer', 'Marge', 'Lisa')
import matplotlib.pyplot as plt #create lists of x and y values x = [1,2,3,4] y1 = [5,7,4,6] y2 = [-1, -2, 3, 0] plt.plot(x,y1, 'r+-') # color='red', marker='+', linestyle='-' plt.plot(x, y2, 'bo--') # color='blue', marker='o', linestyle='--' plt.xlabel('x') plt.ylabel('y') plt.title('Multiple Lines with legend') plt.legend(['y1', 'y2']) # everything is drawn in the background, call show to see it plt.show()
""" University of Liege ELEN0062 - Introduction to machine learning Project 1 - Classification algorithms """ #! /usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import argparse import sys from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from data import make_data1, make_data2 from plot import plot_boundary def get_sets(nb_samples, nb_training_set, seed, which): """ Return the training and testing sets for a given number of samples, a proportion of training set, a seed and for a dataset Arguments: nb_sample: the number of samples in the dataset nb_training_set: size of the training set seed: the seed used to make some random operations which: which dataset should be used Return: The result of the function train_test_split on the part X and y of the dataset, the proportion of the training set and learning set and on the seed. """ if which == 1: dataset = make_data1(nb_samples, random_state = seed) else: dataset = make_data2(nb_samples, random_state = seed) proportion_training_set = nb_training_set/nb_samples return train_test_split(dataset[0], dataset[1], train_size=proportion_training_set, test_size=1-proportion_training_set , random_state=seed) # (Question 1) if __name__ == "__main__": # Definition of the dataset set size, the training set size and the different depths of the decision tree dataset_size = 2000 trainingSet_size = 150 depth = [1, 2, 4, 8, None] # Construction of the decision tree, predictions with it and computation of its accuracy five times for each depth # The data from the decision tree with a certain depth and with the best accuracy are plotted for i in range(2): accuracies = [] best_accuracy = 0 for j in range(len(depth)): accuracies.append([]) for j in range(5): # Get the sets (testing and training) x_train_sample, x_test_sample, y_train_sample, y_test_sample = get_sets(dataset_size, trainingSet_size, j, i+1) for k in range(len(depth)): # Get the decision tree from the training sample decisionTree = DecisionTreeClassifier(max_depth = depth[k], random_state = j).fit(x_train_sample, y_train_sample) # Predictions done from the training samples prediction = decisionTree.predict(x_test_sample) # Compute the accuracy accuracy = accuracy_score(y_test_sample, prediction) accuracies[k].append(accuracy) # Plot the best accuracy if accuracy > best_accuracy: to_plot = [decisionTree, x_test_sample, y_test_sample, accuracy] best_accuracy = accuracy if j == 4: fname = "DTC_depth=" + str(depth[k]) + "_ds=" + str(i+1) title = "Decision Tree Classifier with a depth of " + str(depth[k]) \ + " with an accuracy of %0.4f" %to_plot[3] plot_boundary(fname, to_plot[0], to_plot[1], to_plot[2], 0.1, title) # Compute the average accuracies over 5 generations of the dataset for j in range(5): avg_accuracy = sum(accuracies[j])/5 deviation = np.std(accuracies[j]) print("From dataset %d:" %(i+1)) print("Depth = " + str(depth[j])) print("Average accuracy = %0.4f" %avg_accuracy) print("Deviation = %0.4f" %deviation) print()
from os import name import plotly.figure_factory as ff import plotly.graph_objects as go import statistics import random import pandas as pd import csv df = pd.read_csv("studentMarks.csv") data = df["Math_score"].tolist() mean = statistics.mean(data) std_deviation = statistics.stdev(data) def random_set_of_mean(counter): dataset = [] for i in range(0,counter): random_index = random.randint(0,len(data)-1) value = data[random_index] dataset.append(value) mean = statistics.mean(dataset) return mean mean_list = [] for i in range(0,1000): set_of_means = random_set_of_mean(100) mean_list.append(set_of_means) std_deviation = statistics.stdev(mean_list) first_std_deviation_start, first_std_deviation_end = mean-std_deviation , mean+std_deviation second_std_deviation_start, second_std_deviation_end = mean-(2*std_deviation) , mean+(2*std_deviation) third_std_deviation_start, third_std_deviation_end = mean-(3*std_deviation) , mean+(3*std_deviation) df= pd.read_csv("data3.csv") data = df["Math_score"].tolist() mean_of_sample3 = statistics.mean(data) print("mean of sample3:-", mean_of_sample3) fig = ff.create_distplot([mean_list], ["student marks"], show_hist=False) fig.add_trace(go.Scatter(x=[mean, mean], y=[0, 0.17], mode="lines", name="MEAN")) fig.add_trace(go.Scatter(x=[mean_of_sample3,mean_of_sample3], y=[0,0.17],name="MEAN OF STUDENT WHO GOT FUNSHEET")) fig.add_trace(go.Scatter(x=[second_std_deviation_end,second_std_deviation_end], y=[0,0.17],mode="lines",name="STANDARD DEVIATION")) fig.add_trace(go.Scatter(x=[third_std_deviation_end,third_std_deviation_end], y=[0,0.17],mode="lines",name="STANDARD DEVIATION")) fig.show()
a=int(input("Enter The value of a")) b=int(input("Enter The value of b")) c=int(input("Enter The value of c")) if a>b: print(f'The value of a is {a} is > value of b {b}') elif b>c: print(f'The value of b is {b} is > value of c {c}') else: print(f'The value of c is {c} is > value of a {a}')
import numpy as np import pandas as pd # 从列表创建,指定行、列索引 df = pd.DataFrame([10, 20, 30, 40], columns=['numbers'], index=['a', 'b', 'c', 'd']) print(df) # 添加新的列数据 df['floats'] = (1.5, 2.5, 3.5, 4.5) df['names1'] = ('Yves', 'Guido', 'Felix', 'Francesc') print(df) # 以列为单位修改数据 df['floats'] = 2.0 print(df) df.floats = 22.0 print(df) # 从新的DataFrame对象直接添加。 df['names2'] = pd.DataFrame(['Yv', 'Gu', 'Fe', 'Fr'], index=['d', 'a', 'b', 'c']) print(df) # Missing Data ms = df.join(pd.DataFrame([1, 4, 9, 16], index=['a', 'b', 'c', 'y'], columns=['squares',])) print(ms) ms = df.join(pd.DataFrame([1, 4, 9, 16], index=['a', 'b', 'c', 'y'], columns=['squares',]), how='outer') print(ms) # 删除某列 del df['names2'] print(df)
import numpy as np import pandas as pd df = pd.DataFrame([10, 20, 30, 40], columns=['numbers'], index=['a', 'b', 'c', 'd']) df['floats'] = (1.5, 2.5, 3.5, 4.5) df['names1'] = ('Yves', 'Guido', 'Felix', 'Francesc') df['names2'] = pd.DataFrame(['Yv', 'Gu', 'Fe', 'Fr'], index=['d', 'a', 'b', 'c']) # 添加新的DataFrame对象。 print(df) # 索引 print("打印索引和列名:") print(df.index) print(df.columns) # 选择行 print("不同方式选择行:") print(df.loc['b']) # 通过索引访问元素,之前是df.ix['b'],但已经不推荐使用旧的方法。 print(df.loc[['a', 'b']]) # 索引多个元素。 print(df.loc[df.index[0:3]]) # 使用index对象来索引多个元素。 print(df['a':'c']) # 选择'a', 'b', 'c'三行 print(df[0:1]) # 选择第1列 —— 'a'。 print("按条件选择行例1:") print(df[df.floats > 3.0]) # 选择列'floats'值大于3.0的那些行 print("按条件选择行例2:") conditions = [] for f in df.floats: if f > 3.0: conditions.append(True) else: conditions.append(False) print(df[conditions]) match_condition = pd.Series(conditions, index=df.index) print(df[match_condition]) print("按条件选择行例3:") condition = df.floats > 3.0 print(df[condition]) # 选择列 print("不同方式选择列:") print(df.names1) print(df['names1']) print(df[['names1','names2']])
def linha1(): print('=' * 60) def linha2(): print('*' * 80) linha1() print('O LIVRO DE TOT') linha1() # Ambientação do jogo. print('''Uma pequena arca que contem um livro e uma adaga de ouro está em algum lugar do Egito. O deus Seth é capaz de qualquer coisa pelo livro, que pode torná-lo o Senhor do Mundo, causando a ruína da humanidade. Somente você pode ajudar a mudar essa história. ''') linha2() print ("""\n _ __ - / __ \/ / _ - | | ' | (_) | _L/L | __ / / _LT/l_L_ \ \ __ / _LLl/L_T_lL_ - _T/L _LT|L/_|__L_|_L_ _Ll/l_L_ _TL|_T/_L_|__T__|_l_ _TLl/T_l|_L_ _LL|_Tl/_|__l___L__L_|L_ _LT_L/L_|_L_l_L_ _'|_|_|T/_L_l__T _ l__|__|L_ _Tl_L|/_|__|_|__T _LlT_|_Ll/_l_ _|__[ ]__|__|_l_L_ jjs_ ___ _LT_l_l/|__|__l_T _T_L|_|_|l/___|_ _|__l__|__|__|_T_l_ ___ _ . ";;:;.;;:;.;;;;_Ll_|__|_l_/__|___l__|__|___l__L_|_l_LL_ . .:::.:::..:::.";;;;:;;:.;.;;;;,;;:,;;;.;:,;;,;::;:".' . ,::.:::.:..:.: ::.::::;..:,:::,::::.::::.:;:.:.. . .:.:::.:::.:::: .::.::. :::.::::..::..:.::. . . . ::.:.: :. .::: ::::.::.:::.::...:. .:::. . .:. .. . ::.. .: ::. ::::.:: ::::::. . . :. .. :::.::: ::.::::. ::. . . . .:. :.. :::. ::..: :. nn_r nn_r . : .:::.:: ::..: . /l(\ /l)\ nn_r . ::. :. : : .. `'"`` ``"`` /\(\ . . .:. . : . ' "`` . :. . . . . n""") print(''' Dimitri é um arqueólogo do Rio de Janeiro. É muito curioso e isso pode, o que pode ser um pouco perigoso. Alice é uma matemática do Pernambuco. É extramamente inteligente e adora desafios. Miguel é um arquiteto nascido na Bahia. A sua coragem o leva a lugares inimagináveis. ''') linha2() # Início da história e escolha dos personagens. def personagem(): print('Escolha o seu personagem: ') print('(A) Dimitri | (B) Alice | (C) Miguel') linha2() escolha = input(': ').upper() linha2() if escolha == 'A': print(''' O Dimitri é um arqueólogo brasileiro e ganhou uma bolsa de doutorado da Universidade do Cairo, no Egito, com todos os gastos de passagem e moradia e demais despesas por conta do governo egípcio. No entanto, apesar de ser o seu sonho, você nunca se candidatou a tal vaga. E aí, vai aceitar a oferta? Digite SIM ou NÃO?''') linha2() elif escolha == 'B': print(''' A Alice é uma matemática brasileira e ganhou uma bolsa de doutorado da Universidade do Cairo, no Egito, com todos os gastos de passagem e moradia e demais despesas por conta do governo egípcio. No entanto, apesar de ser o seu sonho, você nunca se candidatou a tal vaga. E aí, vai aceitar a oferta? Sim ou não?''') linha2() elif escolha == 'C': print(''' O Miguel é uma arquiteto brasileira e ganhou uma bolsa de doutorado da Universidade do Cairo, no Egito, com todos os gastos de passagem e moradia e demais despesas por conta do governo egípcio. No entanto, apesar de ser o seu sonho, você nunca se candidatou a tal vaga. E aí, vai aceitar a oferta? Sim ou não? ''' ) linha2() else: print('Opção inválida. Fim de jogo.') personagem1() personagem() #Locais da hitória resposta = input(': ').upper() if resposta == 'SIM': print('Uhul! Pegue as malas e partiu Egito') else: print('fim de jogo') # História print('''Seguindo os conselhos do reitor Amon, após chegar ao Egito e antes das aulas começarem, o ideal é iniciar uma adaptação ao país e visitar a redondeza. Escolha onde quer ir (a)Esfinge de Gizé, (b)Museu (c)Pirâmides''') def local1(): print(''' Eu sou um número de quatro dígitos. O primeiro dígito é 1/2 do último. O segundo dígito é três vezes o primeiro. Já o terceiro é o segundo dígito mais três. Multiplique tudo por dois, em que ano eu nasci?''') resposta = int(input(': ')) if resposta == 2724: print(' Você chegou ao destino' ) else: ('Fim fe jogo') def local2(): print('''As pirâmides de Quéops, a pedra mais leve pesa 500 kg e a mais pesada, 6 toneladas! ') (v) Verdadeiro (f) falso''') resposta = int(input(': ')) if not resposta == 'v': print(' Errado' ) else: ('Você chegou ao seu destino') def local3(): print(''' Os tesouros de qual faraó se encontram no museu? A) Amenhotep III | B) Tutankhamon| C) Amarna''') resposta = input(': ').upper() if resposta == 'B': print(' Você chegou ao seu destino' ) else: ('Errado') onde_ir = input(': ') if onde_ir == 'A': print(local1()) elif onde_ir == 'B': print(local2()) elif onde_ir == 'C': print(local3()) else: ('Escolha Inválida.') #História print(''' Chegando ao local e vendo toda aquela gente, uma escrita antiga na parede te chama atenção… mas… ela não faz parte da exposição. Ninguém se quer presta a atenção nela. Mas com os seus conhecimentos em você logo identifica os hieróglifos e percebe se tratar de um enigma. ''') linha2() print('''Tente acertar o número para ler o enígma. Dica: é um número de 1 a 10''') num = 8 n = 1 tentativa = 3 print('Você só terá 3 chances.') while n <= tentativa: chute = int(input('arrisque o seu número: ')) if chute == num: print('Você acertou! Leia a mensagem') print('F1lh0 d3 T0t, r3t0rne 4 e22e me2m0 loc4l d0is tmp0s 4pós a cheg4d4 da n01te') linha2() break n = n + 1 print('A que horas seria isso? A) 18hs00| B) 20hs00| C) 22hs00| D) 00hs00| ') linha2() hora_certa = input(': ').upper() if hora_certa == 'B': print('Vá até o local') linha2() else: print('Você errou! A sua mochila foi roubada') print(''' Ao voltar para hospedagem você recebe uma carta anônima marcando um encontro. O local é na Esfinge de Gizé, às 20h00, para recuperar os pertences. No entanto, algo parece muito suspeito, pois o sítio arquelógico não abre a noite. ''') print(''' Ao chegar ao local, você ouve um som que parece ter saído da esfinge, o que parece ser loucura. No mesmo instante, uma passagem se abre para dentro da Esfinge de Gizé, e a estátua de Anúbis te dá uma xarada, se a resolver, você terá uma passagem segura para dentro do da esfinge, se não...''') print(local1()) print('Para ter uma entrada segura, responda o enigma.') print('''A sabedoria que corre no seu sangue nos une por um ancestral em comum. Eu sou o entendimento dos homens, eu sou a escrita. Os egípcios me chamam de: A) Bhrami| B) Nahuatl| C) Hieróglifo| ''') linha2() resposta = input(': ').upper() if resposta == 'C': print('Siga em frente') else: ('Uma armadilha te decaptou. Fim de jogo!') linha2() print( ''' "Que bom que você leu a minha mensagen!" Dentro da esfinge, um pouco atordoado. Uma garota encapuzada fala sobre coisas em que você tem certeza ser algum tipo de trote da universidade. Uma ordem secreta do tempo dos faraós, que ajuda os deuses egípcios a manterem o equilíbrio na terra? E agora a ordem precisa da sua ajuda?? Por quê ??? A mensagem na parede foi dela pra mim? Ela se apresenta como Nefertari. ''') linha2() print( ''' Nefertare fala sobre um livro. “...existe um livro de encantamento do deus Tot, o deus da sabedoria. Esse livro contem detalhes de como derrotar Set. Precismos que você nos ajude a roubá-lo e traduza o livro, afinal o artefato só pode ser lido por um descendente do próprio deus.” Ma menina te mostra um pedaço de papiro''') linha2() def museux(): print('A) Castelo de Salah Al-din |B) Museu Egípcio |C) Grande Museu Egípcio ') resposta = input(': ').upper() if resposta == 'A': print('Vá até o museu!') def papiro(): num = 7 n = 1 tentativa = 3 print('''' Por ser da descendênca de Tot, o papiro é legível somente para você. Mas para ler, resolva o enígma: "O sistema de numeração egípcio baseava-se em quantos números chave? "''') while n <= tentativa: chute = int(input('arrisque o seu número: ')) if chute == num: print('Você acertou! Leia a mensagem') print('No novo tempo, os filhos dos antigos guardam as histórias dos grandes a margem Nilo, lá também estará o meu livro. ') print(museux()) break n = n + 1 #Final da história linha1() print(''' Já dentro do museu, você e Nefertiti ouvem um barulho de carro chegando. Mas o local está fechado. Quem mais estaria lá seria?. Espera… é o reitor?''') print(''' O reitor Amon pede a sua ajuda, mas Nerfetiti diz que é armação, o que fazer? Ele parece tão atordoado! Nesse momento, o próprio deus Seth se materializa, ele manipula o=as intensões do reitor, que parece um zumbi. E confessa que tudo fazia parte do plano dele para que o você pudesse chegar ao egito. A bolsa de estudos abrir a arca com o livro. Então você tem o que parece ser a melhor ideia da noite: Corre até a arca, abre traduzindo a simbologia de Tot, pega o livro e a adaga de ouro. Ambos gritam para você jogar o livro para eles, mas você não sabe o que fazer... ''') linha1() def final(): resposta_final = input(''' A) Uso a adaga contra Seth. B) Entrgo a adaga a nerfetiti. C) Entrego o livro a nerfetiti. D) Abro o livro. E) Sai correndo os artefatos. F) Entrego o livro a Amon. ''').upper() linha2() if resposta_final =='A': linha1() print('Seth te segurou pelo pescoço e te desarma. O deus te ergueu como se não fosse nada e você morreu.') print('VOCÊ PERDEU! FIM DE JOGO') linha1() elif resposta_final =='B': linha1() print('Nefertari agradesce e se volta contra você. Ela te mata.') print('VOCÊ PERDEU! FIM DE JOGO') linha1() elif resposta_final =='C': linha1() print('Em um ato surpreedente, Nerfertati joga o livro para Seth. Ela o enganou. O mundo está sob o domínio do deus.') print('VOCÊ PERDEU! FIM DE JOGO') linha1() elif resposta_final =='D': linha1() print('Amon diz para vc ler a ultima página. O próprio deus Tot é invocado e luta contra Seth') print('Parabén! Você salvou o mundo.') print(''' Amon me explica que a Ordem realmente existe, mas nefertiti foi uma traidora que se rendeu a ganância de seth e traiu seus companheiros. Como o reitor é descendente de hórus e menbro da ordem, ele é quem cuida do oráculo que descobriu que, num passado muito distante. Tot se apaixonou por uma mortal e seus descendentes foram mortos e perseguidos. Os poucos sobrevivente imigraram para o continente americano e que você é o último.''') linha1() elif resposta_final == 'E': linha1() print('Seth se materializa na sua frente. O deus rasga a sua garganta.') print('VOCÊ PERDEU! FIM DE JOGO') linha1() elif resposta == 'F': linha1() print(''' Entrega o livro a Seth mas... me entrega uma página rasgada. A ultima página que contem o encantamento. Eu leio, Tot é invocado e derrota. ''') print('Parabén! Você salvou o mundo.') print(''' Amon me explica que a Ordem realmente existe, mas nefertiti foi uma traidora que se rendeu a ganância de seth e traiu seus companheiros. Como o reitor é descendente de hórus e menbro da ordem, ele é quem cuida do oráculo que descobriu que, num passado muito distante. Tot se apaixonou por uma mortal e seus descendentes foram mortos e perseguidos. Os poucos sobrevivente imigraram para o continente americano e que você é o último.''') linha1() else: linha1() print('Você falhou!') linha1() final()
'''利用BuildTree, 进行Depth_First_Search: Preoder; inorder; postorder''' from 树.BuildTree import BinaryTree class BinaryTree2(BinaryTree): def preorder(self,root): #先序遍历 node = root if node == None: return print(node.data) self.preorder(node.lchild) self.preorder(node.rchild) def inorder(self,root): #中序遍历 node = root if node == None: return self.inorder(node.lchild) print(node.data) self.inorder(node.rchild) def postorder(self,root): #后续遍历 node = root if node == None: return self.postorder(node.lchild) self.postorder(node.rchild) print(node.data) if __name__ == '__main__': arr = [] for i in range(10): arr.append(i) #print('arr:',arr) tree = BinaryTree2() for i in arr: tree.add(i) tree.preorder(tree.root) print('先序遍历') tree.inorder(tree.root) print('中序遍历') tree.postorder(tree.root) print('后续遍历')
'''给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。 找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 说明:你不能倾斜容器,且 n 的值至少为 2。 示例: 输入: [1,8,6,2,5,4,8,3,7] 输出: 49 ''' '''粗略解释:矩阵要求两条垂直线的距离越远越好,垂直线的长度越长也好。故,比较 左右两端的高度,将较短高度的那条线像前/后移动一位''' class Solution: def maxArea(self,height): maxV = 0 i= 0 j = len(height)-1 while i < j: maxV = max(maxV,(j-i)*min(height[i],height[j])) if height[i] > height[j]: j-=1 else: i+=1 return maxV if __name__=='__main__': s = Solution() print(s.maxArea([1,8,6,2,5,4,8,3,6]))
# 姓名排序 # 输入 stopword = '' str = [] i = input() while i != stopword: str.append(i) i = input() print ('str是:', str ) #一维数组 # 提取姓氏 for j in range(len(str)): str[j]=str[j].split() #转为二位数组;注:二维数组的创建方式,见Two-dimensional.py print ('str is: ', str) str2 = [] for j in range(len(str)): str2.append(str[j]) print('str2是: ' , str2) # 以字典形式统计姓氏 dict = {} for j in range(len(str)): if str[j][0] not in dict: dict[str[j][0]] = 1 #将姓氏的数量以字典的姓氏储存起来 #print(str[j][0]) #print(dict) else: dict[str[j][0]] += 1 print (len(dict)) # 姓氏排序 str3 = [] for k in sorted(dict,key=dict.__getitem__,reverse=True): str3.append(k) print ('str3是:', str3) # 排序 str4 = [] for a in str3: for j in range(len(str)): if str[j][0] == a: str4.append(str[j][:]) print('str4: ', str4) # 输出 for j in range (len(str)): for a in range(2): print(str4[j][a],end=' ') print('')
'''给出两个非空的链表用来表示两个非负的整数。其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 示例: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 is None: return l2 if l2 is None: return l1 l3 = ListNode(0) # 引用ListNode类定义类一个链表节点并赋给l3 res = l3 flag = 0 while l1 and l2: temp = 0 temp = l1.val + l2.val + flag l1 = l1.next l2 = l2.next temp_pre = ListNode(temp % 10) flag = int(temp / 10) res.next = temp_pre res = res.next if l1: while l1: temp = 0 temp = l1.val + flag l1 = l1.next temp_pre = ListNode(temp % 10) flag = int(temp // 10) res.next = temp_pre res = res.next if l2: while l2: temp = 0 temp = l2.val + flag l2 = l2.next temp_pre = ListNode(temp % 10) flag = int(temp // 10) res.next = temp_pre res = res.next if flag: res.next = ListNode(1) return l3.next
A = [1,3,2,4,10] for elem in A: h = elem * elem A.append(h) A.reverse() print(A)
a = input('Введите палиндром на проверку '); def is_palindrome(string): return string == ''.join(reversed(string)) print(is_palindrome(a))
cities=["İzmir","Antalya","Ankara","İstanbul","Sakarya"] print(cities[3]) print(cities[-1]) ##Sondan başlar print(cities[:2]) print(cities[:-1]) cities[1]="Eskişehir" print(cities) cities.append("Ordu") ##Sona ekler print(cities) cities.insert(0,"Kars") print(cities) del cities[0] ##Silinen şeye ulaşılamaz print(cities) cities=["İzmir","Antalya","Ankara","İstanbul","Sakarya"] print(cities) cities.pop() print(cities) cities2=cities.pop() print(cities2) cities=["İzmir","Antalya","Ankara","İstanbul","Sakarya"] cities.remove("Ankara") print(cities) cities=["izmir","antalya","ankara","istanbul","sakarya"] print(cities) cities.sort() ##Alfabetik sıralama print(cities) cities.sort(reverse=True) ##Alfabe tersten sıralama print(cities) cities=["izmir","antalya","ankara","istanbul","sakarya"] print(cities) print(sorted(cities)) print(cities) numbers=[11,22,33,56] print(min(numbers)) print(max(numbers)) print(sum(numbers)) ##Toplamları cities=["tokyo","madrid","londra","kiev"] print(cities.index("londra")) ##Sırasını verir print("ankara" in cities) ##Listede oup olmadığını kontrol print("tokyo" in cities) for a in cities: print(a) cities=["tokyo","madrid","kiev","londra"] for a in cities: print(f"Gezilemeyen yer : {a}") str_cities= "tokyo,madrid,kiev" print(str_cities) my_list=str_cities.split(", ") ## tırnak içindeki şeye göre ayırır print(my_list) str_email = "faruk0799@gmail.com" my_list2=str_email.split("@") print(my_list2) for a in range(1,10): print(a) for b in range(2,21,2): print(b) numbers=list(range(1,11)) print(numbers) numbers= [number for number in range(1,11)] print(numbers) cities=["ankara","izmir","afyon"] print(cities) cities2=cities[:] print(cities2) cities.append("artvin") print(cities) print(cities2)
def kare(x): return x**2 x= int(input("Karesini istediğiniz sayıyı giriniz : ")) print(f"Girilen {x} sayısının karesi {kare(x)}") x=int(input("Lütfen sayı giriniz: ")) y=int(input("Lütfen bir sayı daha griniz: ")) top = lambda x,y:x+y çarp = lambda x,y : x*y print(f"Girilen sayıların toplamı : {top(x,y)} , çarpımı : {çarp(x,y)}") def multiply(mylist): mult = 1 for x in mylist: mult *=x return mult list1=[3,5,6,10] print(multiply(list1)) def fakt(a): if a==0: return 1 else: return a*fakt(a-1) a=int(input("Sayı gir : ")) print(fakt(a)) def cube_c(a): return 12*a def cube_(a): return 6*a**2 def cube_v(a): return a**3 a=int(input("Kenar uzunluğu gir : ")) print(f"Kenarı {a} olan küpün çevresi : {cube_c(a)}, alanı : {cube_a(a)}, hacmi : {cube_v(a)}")
class Car: def __init__(self,brand,model,year): self.brand = brand self.model = model self.year = year def brandmodel(self): return f"Araba markası {self.brand} ve modeli {self.model}" car_1 = Car("BMW","i5",2010) car_2 = Car("Audi","x6",2012) print(car_1) print(car_1.brand) print(car_1.brandmodel()) class Movie: def __init__(self,name,director): self.name = name self.director = director movie_1 = Movie("Full Metal Jacket","Kubrick") movie_2 = Movie("Babel","Irarutu") print(movie_1.name) print(movie_2.director) class Student: school_name = "X Lisesi" #Class Variable number_of_students = 0 def __init__(self,name,age,grades): self.name=name #Instance Variable self.age=age self.grades=grades Student.number_of_students +=1 def average(self): return sum(self.grades)/len(self.grades) def schoolName(self): return f"Okulumuzun adı {self.school_name}" student_1 = Student("Faruk",21,[80,60,50]) student_2 = Student("Mevlüt",20,[80,40,70]) print(Student.school_name) print(student_1.schoolName()) print(Student.__dict__) print(student_1.__dict__) print(Student.number_of_students) print(student_1.average()) print(student_2.average()) #Class değişkenleri daha geneli kapsar. Instance değişkenler ise # verilen özelliklere göre daha spesifiktir. İkisi de class'ta # tanımlanırlar. # Class variable sadece bir nesneyi tutar, Instance variable ise # birden fazla nesneyi tutar.
#!/usr/bin/python #!enconding:UTF-8 def aproximacion (n): sumatorio = 0.0 for i in range (1, n+1): xi = (i-0.5)/float(n) fxi = 4/(1 + (xi**2)) sumatorio += fxi c = sumatorio/float(n) return c from math import pi print 'El valor de PI con 35 decimales: %.35f\n' % pi import sys veces = int (sys.argv[2]) intervalo = int (sys.argv[1]) while intervalo <= 0: print 'No se puede calcular PI aproximado con el intervalo introducido' intervalo = int (raw_input('Introduzca un nuevo intervalo: ')) l = [] print 'i. PI35DT lista i PI35DT - lista i' print '\n' for vez in range (1, veces+1): x = aproximacion (intervalo*vez) l = l + [x] dif = abs(pi - x) print '%d. %.35f %.35f %.35f' % (vez, pi, x, dif) print '\n' print l
import pprint # In order to print matrices prettier import scipy as sc import scipy.linalg # Linear Algebra Library contained in Scipy matrix_A = sc.array([[7,4],[3,5]]) # given matrix A P, L, U = scipy.linalg.lu(matrix_A) # returns the result of LU decomposition to the variables P, L, and U print("Original matrix A:") pprint.pprint(matrix_A) # implies a pivoting(reordering) rows(or columns) in case it is needed print("Pivoting matrix P:") pprint.pprint(P) # lower-triangular matrix of A print("L:") pprint.pprint(L) # upper-triangular matrix of A print("U:") pprint.pprint(U)
#Factorial test def calculateFactorial(factorial): num = 1 for x in range(factorial, 1, -1): num = num * x return num val = input("Enter your value: ") print ('Factorial of ' + str(val) + ' is: ' + str(calculateFactorial(int(val))))
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import re ############ # Alphabet # ############ # we will use alphabet for text cleaning and letter counting def define_alphabet(): base_en = 'abcdefghijklmnopqrstuvwxyz' special_chars = ' !?¿¡' german = 'äöüß' italian = 'àèéìíòóùú' french = 'àâæçéèêêîïôœùûüÿ' spanish = 'áéíóúüñ' czech = 'áčďéěíjňóřšťúůýž' slovak = 'áäčďdzdžéíĺľňóôŕšťúýž' all_lang_chars = base_en + german + italian + french + spanish + czech + slovak small_chars = list(set(list(all_lang_chars))) small_chars.sort() big_chars = list(set(list(all_lang_chars.upper()))) big_chars.sort() small_chars += special_chars letters_string = '' letters = small_chars + big_chars for letter in letters: letters_string += letter return small_chars,big_chars,letters_string ######## # Plot # ######## def print_confusion_matrix(confusion_matrix, class_names, figsize = (10,7), fontsize=14): """Prints a confusion matrix, as returned by sklearn.metrics.confusion_matrix, as a heatmap. Arguments --------- confusion_matrix: numpy.ndarray The numpy.ndarray object returned from a call to sklearn.metrics.confusion_matrix. Similarly constructed ndarrays can also be used. class_names: list An ordered list of class names, in the order they index the given confusion matrix. figsize: tuple A 2-long tuple, the first value determining the horizontal size of the ouputted figure, the second determining the vertical size. Defaults to (10,7). fontsize: int Font size for axes labels. Defaults to 14. Returns ------- matplotlib.figure.Figure The resulting confusion matrix figure FROM: https://gist.github.com/shaypal5/94c53d765083101efc0240d776a23823 """ df_cm = pd.DataFrame( confusion_matrix, index=class_names, columns=class_names, ) fig = plt.figure(figsize=figsize) try: heatmap = sns.heatmap(df_cm, annot=True, fmt="d") except ValueError: raise ValueError("Confusion matrix values must be integers.") heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize) heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right', fontsize=fontsize) plt.title('Confusion Matrix') plt.ylabel('True label') plt.xlabel('Predicted label') return fig ################################### # Data cleaning utility functions # ################################### # we will create here several text-cleaning procedures. # These procedure will help us to clean the data we have for training, # but also will be useful in cleaning the text we want to classify, before the classification by trained DNN # remove XML tags procedure # for example, Wikipedia Extractor creates tags like this below, we need to remove them # <doc id="12" url="https://en.wikipedia.org/wiki?curid=12" title="Anarchism"> ... </doc> def remove_xml(text): return re.sub(r'<[^<]+?>', '', text) # remove new lines - we need dense data def remove_newlines(text): return text.replace('\n', ' ') # replace many spaces in text with one space - too many spaces is unnecesary # we want to keep single spaces between words # as this can tell DNN about average length of the word and this may be useful feature def remove_manyspaces(text): return re.sub(r'\s+', ' ', text) # and here the whole procedure together def clean_text(text): text = remove_xml(text) text = remove_newlines(text) text = remove_manyspaces(text) return text ################# # Preprocessing # ################# # this function will get sample of texh from each cleaned language file. # It will try to preserve complete words - if word is to be sliced, sample will be shortened to full word def get_sample_text(file_content,start_index,sample_size): # we want to start from full first word # if the firts character is not space, move to next ones while not (file_content[start_index].isspace()): start_index += 1 #now we look for first non-space character - beginning of any word while file_content[start_index].isspace(): start_index += 1 end_index = start_index+sample_size # we also want full words at the end while not (file_content[end_index].isspace()): end_index -= 1 return file_content[start_index:end_index] # we need only alpha characters and some (very limited) special characters # exactly the ones defined in the alphabet # no numbers, most of special characters also bring no value for our classification task # (like dot or comma - they are the same in all of our languages so does not bring additional informational value) # count number of chars in text based on given alphabet def count_chars(text, alphabet): alphabet_counts = [] for letter in alphabet: count = text.count(letter) alphabet_counts.append(count) return alphabet_counts # process text and return sample input row for DNN # note that we are counting separatey: # a) counts of all letters regardless of their size (whole text turned to lowercase letter) # b) counts of big letters only # this is because German uses big letters for beginning of nouns so this feature is meaningful def get_input_row(content,start_index,sample_size, alphabet): sample_text = get_sample_text(content,start_index,sample_size) counted_chars_all = count_chars(sample_text.lower(), alphabet[0]) counted_chars_big = count_chars(sample_text, alphabet[1]) all_parts = counted_chars_all + counted_chars_big return all_parts
#!/usr/bin/env python3 import string import sys import re def read_input(file): for line in file: line = line.lower() line = re.sub('[^a-zA-Z0-9 \n]','',line) yield line.split() def main(separator='\t'): data = read_input(sys.stdin) for words in data: for word in words: print(word, separator, 1) if __name__ == "__main__": main()
n=input() count=0 for x in range (0,len(n)): if (n[x]==" "): count=count+1 else: count=count print (count)
s=str(input()) if (s=='Monday' or s=='Tuesday' or s=='Wednesday' or s=='Thursday' or s=='Friday'): print("no") elif (s=='Saturday' or s=='Sunday'): print("yes") else: print("invalid")
i=int(raw_input()) for x in range(1,i+1): print("Hello")
h=int(input()) y=input().split() l=input().split() if(sorted(l)==y): print("yes") else: print("no")
#!/usr/bin/env/python # This is a typing test application created in python # Created by Raymond Ho on Aug 4, 2014 import time import sys # Open file, and store each line into list. List = [] total_words = 0 with open(sys.argv[1], 'r') as f: List = f.read().splitlines() # Count the words in the list. for line in List: total_words += len(line.split()) # Prompt user to begin typing, and start timer. raw_input("Press enter to begin test.\n>> ") start_time = time.time() mistakes = {} for line in List: print line response = raw_input(">> ") # Split lines into words, and count the mistakes. word_response = response.split() word_line = line.split() for i in range(0, len(line.split())): if word_response[i] != word_line[i]: mistakes[word_response[i]] = word_line[i] # Calculate time elapsed and convert into minutes. elapsed_time = time.time() - start_time wpm = (total_words / elapsed_time) * 60 accuracy = (total_words - len(mistakes)) / float(total_words) * 100 print print("Your words per minute is: %i." % wpm) print("Your accuracy: %i%%" % accuracy) print ("Total words: %s." % total_words) print("Total errors: %i." % len(mistakes)) for key, val in mistakes.items(): print "You entered: '%s' : Should be: '%s'" % (key, val)
def collatz_steps(number): assert isinstance(number, int), "The input should be an integer" assert number > 0, "The input should be larger than 0" steps = 0 while number > 1: steps += 1 if number % 2: number = number*3 + 1 else: number /= 2 return steps
a="Hello" print(a*3) print(a[0]) ## String negative index print(a[-1]) ##String Slicing- Works with index only. ##output is ell as starts with 1, ends at 3. Last index is not inclusive print(a[1:4]) print(a[2:5]) ## Comparison Operator ## Compares Ascii value, Starts with first chartacter.. Expect result at first non matching charatcer print("hello"<"jello") ## In Operator - Checks first substring present in next string or not print("e" in a) print("x" in a) print("e" not in a) print("x" not in a) #######Escape Sequence######################################## print("Hello \\ World") print("Hello \' World") print("Hello \" World") #\b removes last character before this sequence character print("Hello\bWorld") a="a\b"+"bc"+"cd" print(a) #op bccd # For Formatting as new paragraph print("Hello\fWorld") #For new line character print("Hello\nWorld") #For tab character print("Hello\tWorld") th #################String Function############################### s="hello" print(s.upper()) T="HELLLO" print(s.lower()) # Count - No of occurence of character print(s.count("l")) print(s.replace("l","w"))
## Accepting a number from user num= input("Please enter number ") print(num) #Input will accept only number or float ## To accept strig use raw_input string= raw_input("Please enter a string ") print("Hello "+string)
for a in ['abc','def','xyz']: message="Hi "+a+" How are you?" print(message) for i in range(5): print('i is at',i) print(range(4)) print(range(2,4)) print(range(2,11,5)) ###################################################################### number=0 while number != 42: number=input("Plz input number")
import pygame pygame.init() win=pygame.display.set_mode( (500,500)) pygame.display.set_caption("First Game") x=50 y=50 w=40 h=60 vel =5 run =True while run: pygame.time.delay(100) for event in pygame.event.get(): if event.type == pygame.QUIT: run=False keys=pygame.key.get_pressed() if keys[pygame.K_LEFT]: x-=vel if keys[pygame.K_RIGHT]: x +=vel if keys[pygame.K_DOWN]: y +=vel if keys[pygame.K_UP]: y -=vel # cor do fundo win.fill((45,12,34)) # desnhar um rectang( precisamos de tres parametros(1-ctx, 2(cor-rgb) 3=[medidas do rectangulo]) # drawing a rect angle( surface:{where you want to draw[in this case is in the displa]}, color, rect_[x,y,w,h] pygame.draw.rect(win,(255,0,0),(x,y,w,h)) # to display the designs we need to update de display pygame.display.update() pygame.quit()
Attack = input("Are we being Attacked!!??").lower() if(Attack == "yes") or (Attack == "y"): print("We are being attaked!!!Attack Back!!!") elif (Attack == "no") or (Attack == "n"): print("They are friendly invite them for tea!") else: print("You must answer us!!! Or we will be attacked!!")
from datetime import * import time #hello class DifferenceTimes(): def __init__(self, tasks): self.startTimes = [] self.endTimes = [] self.differenceTimes = [] self.tasks = int(tasks) self.create_array_length() def create_array_length(self): for i in range(self.tasks): self.startTimes.append(0) self.endTimes.append(0) self.differenceTimes.append(0) print len(self.startTimes) def get_start_times(self): for i in range(self.tasks): self.startTimes[i] = datetime.now() def get_end_times(self): for i in range(self.tasks): self.endTimes[i] = datetime.now() def get_difference_times(self): for i in range(self.tasks): difference = (self.endTimes[i] - self.startTimes[i]).seconds self.differenceTimes[i] = difference
'''O arquivo Controller terá as requisições do usuário''' import mysql.connector conexao = mysql.connector.connect( host="localhost", user="root", password="1234", database = "loja" ) def mostrarAoUsuario(): acao = conexao.cursor() comando = input("O que deseja fazer no Banco de Dados: ") if comando == "mostrar": acao.execute("SELECT * FROM produto") result = acao.fetchall()#Essa função busca todas as linhas da última instrução executada print(result)
class max_heap2: def __init__(self, capacity): self.data = [0] * (capacity + 1) self.capacity = capacity self.count = 0 def is_full(self): return self.count == self.capacity def insert(self, v): assert not self.is_full() print("insert", v) self.count += 1 self.data[self.count] = v self._shift_up(self.count) def _shift_up(self, index): if index <= 1: print("shift up finished, index = ", index, ', heap data is : ', end = " ") [print(self.data[i], end = " ") for i in range(1, self.count + 1)] print(", count : ", self.count) return print("shift up, index = ", index) parent = index // 2 if self.data[index] > self.data[parent]: self.data[index], self.data[parent] = self.data[parent], self.data[index] [print(self.data[i], end = " ") for i in range(1, self.count + 1)] print(", count : ", self.count) self._shift_up(parent) else: print("shift up finished, index = ", index, ", heap data is : ", end = " ") [print(self.data[i], end = " ") for i in range(1, self.count + 1)] print(", count : ", self.count) def extra_max(self): assert self.count > 0 v = self.data[1] self.data[1] = self.data[self.count] self.count -= 1 self._shift_down(1) return v def _shift_down(self, i): left = i * 2 if left > self.count: return max_index = left right = left + 1 if right <= self.count: if self.data[right] > self.data[left]: max_index = right if self.data[max_index] > self.data[i]: self.data[max_index], self.data[i] = self.data[i], self.data[max_index] self._shift_down(max_index)
#!/usr/bin/env python from enum import Enum, unique @unique class Colour(Enum): black=0 red=1 class Postion(): def __init__(self,xAxis,yAxis): self.xAxis = xAxis self.yAxis = yAxis class Chess(): def __init__(self,colour,xAxis,yAxis): self.colour = colour self.xAxis = xAxis self.yAxis = yAxis self.postion = Postion(xAxis,yAxis) def __str__(self): return "x:%s y:%s colour:%s " % (self.xAxis,self.yAxis,self.colour) class Chessboard(): """ """ #longNum make the num of x, latNum make the num of y def __init__(self,xAxis,yAxis,gobangNum=5): if xAxis<3 or yAxis<2 : raise ValueError("chessboard's xAxis or yAxis lt 10") self.xAxis = xAxis self.yAxis = yAxis self.points = [[None for _ in range(xAxis)] for _ in range(yAxis)] self.gobangNum = gobangNum def move(self,chess): if chess.xAxis < 0 or chess.xAxis > self.xAxis - 1: raise ValueError("chess's x-axis postion is wrong") if chess.yAxis < 0 or chess.yAxis > self.yAxis - 1: raise ValueError("chess's y-axis postion is wrong") point = self.points[chess.yAxis][chess.xAxis] if not point is None: raise ValueError("this postion already exists a chess already") self.points[chess.yAxis][chess.xAxis] = chess return self.__checkWin(chess) def getChess(self,postion): if postion.xAxis < 0 or postion.yAxis < 0: return None if postion.xAxis > self.longNum - 1 or postion.yAxis > self.latNum - 1: return None return self.points[postion.yAxis][postion.xAxis] def __checkWin(self,chess): xpoint = chess.xAxis ypoint = chess.yAxis xlinkedBeads = 0 _xlinkedBeads = 0 ylinkedBeads = 0 _ylinkedBeads = 0 xylinkedBeads = 0 _xylinkedBeads = 0 x_ylinkedBeads = 0 _x_ylinkedBeads = 0 xlinkedBeadsFlag = True _xlinkedBeadsFlag = True ylinkedBeadsFlag = True _ylinkedBeadsFlag = True xylinkedBeadsFlag = True _xylinkedBeadsFlag = True x_ylinkedBeadsFlag = True _x_ylinkedBeadsFlag = True for i in range(1,self.gobangNum): xltZ = xpoint - i < 0 xgtM = xpoint + i > len(self.points[0]) - 1 yltZ = ypoint - i < 0 ygtM = ypoint + i > len(self.points) - 1 XpointChess = None if xgtM else self.points[ypoint][xpoint + i] _XpointChess = None if xltZ else self.points[ypoint][xpoint - i] YpointChess = None if ygtM else self.points[ypoint + i][xpoint] _YpointChess = None if yltZ else self.points[ypoint - i][xpoint] XYpointChess = None if xgtM or ygtM else self.points[ypoint + i][xpoint + i] _XYpointChess = None if xltZ or ygtM else self.points[ypoint + i][xpoint - i] X_YpointChess = None if xgtM or yltZ else self.points[ypoint - i][xpoint + i] _X_YpointChess = None if xltZ or yltZ else self.points[ypoint - i][xpoint - i] # x if (XpointChess != None and XpointChess.colour == chess.colour) and xlinkedBeadsFlag: xlinkedBeads = xlinkedBeads + 1 else: xlinkedBeadsFlag = False if (_XpointChess != None and _XpointChess.colour == chess.colour) and _xlinkedBeadsFlag: _xlinkedBeads = _xlinkedBeads + 1 else: _xlinkedBeadsFlag = False # y if (YpointChess != None and YpointChess.colour == chess.colour) and ylinkedBeadsFlag: ylinkedBeads = ylinkedBeads + 1 else: ylinkedBeadsFlag = False if (_YpointChess != None and _YpointChess.colour == chess.colour) and _ylinkedBeadsFlag: _ylinkedBeads = _ylinkedBeads + 1 else: _ylinkedBeadsFlag = False; # xy if (_X_YpointChess != None and _X_YpointChess.colour == chess.colour) and _x_ylinkedBeadsFlag: _x_ylinkedBeads = _x_ylinkedBeads +1 else: _x_ylinkedBeadsFlag = False if (XYpointChess != None and XYpointChess.colour == chess.colour) and xylinkedBeadsFlag: xylinkedBeads = xylinkedBeads + 1 else: xylinkedBeadsFlag = False # x_y if (_XYpointChess != None and _XYpointChess.colour == chess.colour) and _xylinkedBeadsFlag: _xylinkedBeads = _xylinkedBeads + 1 else: _xylinkedBeadsFlag = False; if (X_YpointChess != None and X_YpointChess.colour == chess.colour) and x_ylinkedBeadsFlag: x_ylinkedBeads = x_ylinkedBeads + 1 else: x_ylinkedBeadsFlag = False if xlinkedBeads + _xlinkedBeads >= self.gobangNum - 1 or ylinkedBeads + _ylinkedBeads >= self.gobangNum - 1 or _x_ylinkedBeads + xylinkedBeads >= self.gobangNum - 1 or _xylinkedBeads + x_ylinkedBeads >= self.gobangNum - 1: return True return False def __str__(self): boardStr = '' for xpoints in self.points[::-1]: for point in xpoints: if not point is None: boardStr = boardStr + str(point.colour.value) + ' ' else: boardStr = boardStr + 'x ' boardStr = boardStr + '\n' return boardStr try: chessboard = Chessboard(5,5,3) chess0 = Chess(Colour.black,0,0) chess1 = Chess(Colour.black,0,1) chess2 = Chess(Colour.black,2,2) chess3 = Chess(Colour.black,3,3) chess4 = Chess(Colour.black,4,4) chess5 = Chess(Colour.black,5,5) chessboard.move(chess0) chessboard.move(chess1) chessboard.move(chess2) chessboard.move(chess3) #chessboard.move(chess5) #chessboard.move(chess4) if chessboard.move(chess4): print("win!!!") print(chessboard) except ValueError as ve: print(str(ve))
from typing import List import csv from ipaddress import IPv4Address from event_parser.event import Event from event_parser.gender import Gender from event_parser.person import Person def ip_anonymization(ip: IPv4Address) -> IPv4Address: ''' This function will anonymize a given IPV4 adress by setting the last byte to 0. In this way, most of the information is preserved but cannot be linked to an individual person. Input: IPv4 adress to anonymize Output: Anonymized IPv4 adress ''' # Conversion of the IP to its string format ip_bytes = ip.exploded.split('.') # Put the last byte to 0 ip_bytes[-1] = '0' # Reform the IPv4 adress return IPv4Address('.'.join(ip_bytes)) def gender_normalization(text: str = None) -> Gender: ''' This function will normalize an input text to match a specific Gender category. Input: Data text Output: Gender category ''' if not text: return Gender.not_given elif text.lower() in ["male", "female"]: return getattr(Gender, text.lower()) else: return Gender.other def read_events(path: str) -> List[Event]: ''' This function will read and parse a csv file as a list of Event objects Input: path to csv file Output: list of Event objects ''' events = list() with open(path) as data_file: data = csv.reader(data_file) next(data) # skip the header for row in data: person = Person( first_name=row[1], last_name=row[2], gender=gender_normalization(row[4]), email=row[3] ) events.append(Event(id=row[0], person=person, ip_adress=row[5])) return events
# A Command Line dynamic TIC TAC TOE GAME. # Requirements:- Python3. # TIC TAC TOE Board is dynamic can be of any size. # 2 Player game Player1 will choose 'X' position and Player2 will choose 'O' position on the game board. # A winner s chosen if all the input('X'/'O') in a row/column/diagonal are same. # Program gives the Winner/No winner. # Once the game finishes, user are asked to play again or want to quit. from colorama import Fore, Back, Style, init import os import time init() # Defining a clear function to make our game screen clean. def clear(): os.system('cls') # Function to draw our game board based on user input def game(game_map, player, row, col, cr): try: # Checking if user input position is already taken if game_map[row][col] != 0: print("This position is already occupied, Choose another!!") print() return False clear() # printing the column values on the gameboard print(" "+" ".join([str(x) for x in range(len(game_map))])) if player != 0: game_map[row][col] = player # enumerate function is used to print row indexes # replacing all 0 to "", 1 to 'X' and 2 to '0' for count, row in enumerate(game_map): colored_row = "" for item in row: if item == 0: colored_row += " " elif item == 1: colored_row += Fore.GREEN + ' X ' + Style.RESET_ALL elif item == 2: colored_row += Fore.MAGENTA + ' O ' + Style.RESET_ALL print(count, colored_row) print() return game_map # handling Out of range error except IndexError as e: print("Error: Did you enter row/column as ({})?".format(cr), e) print() return False # handling input type error except TypeError as e: print("Error: Did you pass the correct parameters for list:", e) print() return False # function to decide winner def win(current_game): # Horizontal Winner def all_same(l): if l.count(l[0]) == len(l) and l[0] != 0: return True else: return False for row in current_game: if all_same(row): print("Player {} is the winner horizontally!".format(row[0])) return True # Vertical Winner column = range(len(current_game)) for col in column: check = [] for row in current_game: check.append(row[col]) if all_same(check): print("Player {} is the winner vertically!".format(check[0])) return True # Diagonal Winner Type1 ((0,2), (1,1), (2,0)) diags1 = [] for col, row in enumerate(reversed(range(len(current_game)))): diags1.append(current_game[row][col]) if all_same(diags1): print("Player {} is the winner diagonally!".format(diags1[0])) return True # Diagonal Winner Type2 ((0,0), (1,1), (2,2)) diags = [] for ix in range(len(current_game)): diags.append(current_game[ix][ix]) if all_same(diags): print(f"Player {diags[0]} is the winner diagonally!") return True return False # main loop play = True while play: players = [1, 0] # p = [1,2] game_size = int(input("Enter the tic_tac_toe game size:")) game_boards = [[0 for i in range(game_size)] for i in range(game_size)] choice_range = ", ".join([str(i) for i in range(game_size)]) game_won = False game(game_boards, 0, 0, 0, choice_range) choice = 0 total_turn_possible = game_size * game_size while not game_won: if total_turn_possible >=1: current_player = choice + 1 played = False while not played: time.sleep(.5) print("Current_Player:", current_player) # Collecting the row and column choices of current player row_choice = int(input(f"Which row do you want to choose player{current_player}? choice range - ({choice_range}):")) column_choice = int(input(f"Which column do you want to choose player{current_player}? choice range - ({choice_range}):")) g = game(game_boards, current_player, row_choice, column_choice, choice_range) if g: played = True # Checking for any winner game_won = win(g) # reversing the turn between player1 and player2 choice = players[choice] else: game_won = True print("No Winners!!!") total_turn_possible -= 1 # Asking if user want to replay... replay = input("press 'N' to quit or any other key to continue:") if replay == 'N' or replay == 'n': print("Bye!!!") play = False else: print() print("_________restarting_________") print()
def createBoard(): board = [0, 4, 4, 4, 4, 4, 4, 0, 4, 4, 4, 4, 4, 4] return board #prints out the currentboard def printBoard(board): print('\n') print(' 13 12 11 10 9 8 7') print('\n') secondLine = '' for x in range(8, 14): secondLine = ' ' + str(board[x]) + secondLine secondLine = ' ' + secondLine print(secondLine) if board[0] > 9: print(str(board[0]) + ' ' + str(board[7])) else: print(str(board[0]) + ' ' + str(board[7])) fourthLine = ' ' for x in range(1,7): if board[x] > 9: fourthLine += str(board[x]) + ' ' else: fourthLine += str(board[x]) + ' ' print(fourthLine) print('\n') print('0 1 2 3 4 5 6 ') print('\n') return board #nice def legalMove(board, position, player): #checks if the inputted number is a legal move for that player. #player is a number if board[int(position)] == 0: return False else: if player == 1: if int(position) >= 1 and int(position) <= 6: return True else: return False elif player == 2: if int(position) >= 8 and int(position) <= 13: return True else: return False def doMove(board, position, player): #do the move from the board on the inputted position, with the inputted player #check player status by either oddCount or evenCount #even count must match the position selected. 8-13 is player 2. 1-6 is player 1. # print(board) if player == 1: addSwitch = False for x in range(board[position]): #for x in the range of the position's number, add 1 to each consecutive pocket #if this number becomes higher than 13, revert back to 0 #fix #fix!!!! index = position + 1 + x if (index) > 13: # board[index] += 1 # else: index -= 14 if addSwitch == False: if index == 0: addSwitch == True # for y in range(position-x): # if (index) > 13: # index -= 14 # board[index + 1 + y] += 1 # break # print(x-position-1) #fix next line. # inverse relationship, when the position is 10 add 2, when 9 add 1, when 8 add none # print(index) # print(x-position) # print(board[position]) # print(position) #figure out a less arbitrary number than #must factor distance from the spot, then the actual number of beads, and which spot is chosen. #... #each spot is a certain distance 0, and the board[position], just adds a little more as it gets bigger #values of 9 can only start adding from the 5th spot, but values of 10 can start adding from the 4th, and values of 11, from the 3rd, and so on. #8 in the 6th spot, board[1] += 1 | lowest-level #9 in the 5th spot, board[1] += 1 #9 in the 6th spot, board[2] += 1 #10 in the 4th spot, board[1] += 1 #10 in the 5th spot, board[2] += 1 #10 in the 6th spot, board[3] += 1 #11 in the 3rd spot, board[1] += 1 #11 in the 4th spot, board[2] += 1 #11 in the 5th spot, board[3] += 1 #12 in the 4th spot, board[3] += 1 #12 in the 5th spot, board[4] += 1 #13 in the 1st spot, board[1] += 1 #13 in the 2nd spot, board[2] += 1 #13 in the 3rd spot, board[3] += 1 #13 in the 4th spot, board[4] += 1 #14 in the 1st spot, board[2] += 1 #14 in the 2nd spot, board[3] += 1 #14 in the 3rd spot, board[4] += 1 #14 in the 4th spot, board[5] += 1 if (board[position]+position) >= 14: board[(board[position]+position)-13]+= 1 # print(board[position]+position) # board[(board[position]-(position)] += 1 # board[-((position+1)-(board[position]))] else: board[index]+= 1 else: if index == 7: addSwitch == False # board[index+1] += 1 else: board[index+1]+= 1 board[position] = 0 elif player == 2: #store a count, if the cuont is greater than 7, skip. if index at beginning within player's range, then don't add. #if position for x in range(board[position]): #for x in the range of the position's number, add 1 to each consecutive pocket #if this number becomes higher than 13, revert back to 0 index = position + 1 + x if (index) > 13: # board[index] += 1 # else: index -= 14 if index == 7: # print(x) # still buggy. if (board[position]+position) >= 14: board[(board[position]+position)-13]+= 1 # board[index+(x-position)] += 1 else: board[index]+= 1 board[position] = 0 # print(board) return board def isGameOver(board, player): #checks the current player, and if the current player has no moves, perform a victory condition. #check for a list of zeros in the player's range. # use a sum funtion, and if the sum of the numbers is 0, return True. if player == 1: for x in range(1,7): if board[x] != 0: return False return True elif player == 2: for x in range(8,14): if board[x] != 0: return False return True def runGame(board, player): # board = createBoard() printBoard(board) # currentPlayer = 1 #wrap entire code in the isGameOver function, only run code if isGameOver == false... # position = input # can probably clean this if isGameOver(board, player) == False: if player == 1: #catch error, if inputted text is not a number, request a number, 'sorry the move {{input}} is invalid for player {{x}}' position = input('Enter a move for player 1: ') #do I need to convert to int, and check if convertable? #include legal move, then reprint while (int(position) > 6 or int(position) < 1) or legalMove(board, position, player) == False: print('Sorry, the move ' + position + ' is invalid for player 1.') printBoard(board) position = input('Enter a move for player 1: ') if legalMove(board, position, player) == True: newBoard = doMove(board, int(position), player) runGame(newBoard, 2) else: pass elif player == 2: position = input('Enter a move for player 2: ') while (int(position) > 13 or int(position) < 8) or legalMove(board, position, player) == False: print('Sorry, the move ' + position + ' is invalid for player 2.') printBoard(board) position = input('Enter a move for player 2: ') if legalMove(board, position, player) == True: newBoard = doMove(board, int(position), player) runGame(newBoard, 1) else: if board[0] < board[7]: victory = 'Player 1 wins, ' + str(board[7]) + ' to ' + str(board[0]) else: victory = 'Player 2 wins, ' + str(board[0]) + ' to ' + str(board[7]) print(victory) runGame(createBoard(), 1) #AI. #how to pipe a series of numbers so that I can test my game? # #test a exampleboard with the 1st player 0'd out, and then a second test with the 2nd player 0'd out. # testboard1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] # print(isGameOver(testboard1, 2)) #linux pipe command #foo < file.txt. the pipe is the 'less than' symbol: '<' #The A.I. hacking Mancala # pick moves that equal the number of moves it takes to perfectly match to board[7] if player 1, or board[0] if player 2. # or pick a move with a 0 on it if it would benefit player. # check which slots currently have more. # emergency mode, moderate mode, safe mode. # moderate mode, make good decisions, # consider not allowing points to be added to the other side. As much as possible, don't let it go to the other side of the board. # build a favorable block # build a favorable position # if nothing is a perfect match, create a perfect match, by building one by one. # keep checking if no moves available. Go for a lead. If no moves available, and myStore is bigger, clear it out # try not to give points to the opponent, # give points to the opponent, if the opponent's store is all 0, and your store is less than # however, don't give beads to the opponent if the opponent's store is less than. # if opponent picks a 0 option, looks for the 0 option as well. # keep going and ensure that at the end, once one member's board fully empties, and search to win the game. # try not to use large numbers. dangerous. # give the opponent 1s on their first pocket
import re # 1. For simple literal patterns, text = 'yeah, but no, but yeah, but no, but yeah' text1 = text.replace('yeah', 'yep') print(text1) # --->Output: yep, but no, but yep, but no, but yep # 2.For more complicated patterns, use the sub() # functions/methods in the re module. # if you want to convert 11/05/2021 to 2021-11-05 today = 'today is 11/05/2021. my bday is 21/05/2021' changed_pattern = re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', today) print(changed_pattern) # --->Output: today is 2021-11-05. my bday is 2021-21-05 """ If you’re going to perform repeated substitutions of the same pattern, consider compiling it first for better performance. """ datepattern = re.compile(r'(\d+)/(\d+)/(\d+)') changed_pattern = datepattern.sub(r'\2-\3-\2', today) print(changed_pattern) # ---> Output: today is 05-2021-05. my bday is 05-2021-05 # 3.Case-Insensitive search and replace text = 'UPPER PYTHON, lower python, Mixed Python' search_python = re.findall('python', text, flags=re.IGNORECASE) print(search_python) # -->Output: ['PYTHON', 'python', 'Python'] repace_python_to_cobra = re.sub('python', 'cobra', text, flags=re.IGNORECASE) print(repace_python_to_cobra) # --> Output: UPPER cobra, lower cobra, Mixed cobra # 4. some string functions text = "Avinash" print(text.upper()) # -->Output : AVINASH print(text.lower()) # -->Output: avinash print(text.capitalize()) # --> Output: Avinash # 5. Unicode s1 = 'Spicy gravy\u00f1o' print(s1) # -->Output: Spicy gravyño # 6. striping unwanted charecters from string # white space straping s = ' hello universe 1\n' print(s) # --> Output: hello universe 1 s_without_space = s.strip() print(s_without_space) # ---> Output: hello universe 1 s_without_left_space = s.lstrip() print(s_without_left_space) # ---> Output:hello universe 1 s_without_right_space = s.rstrip() print(s_without_right_space) # --->Output: hello universe 1 # charecter striping t = '----------hello--------universe========' print(t) # -->Output:----------hello--------universe == == == == strip_dash = t.strip('-') print(strip_dash) # -->Output:hello--------universe == == == == strip_equlas = t.strip('=') print(strip_equlas) # -->Output:----------hello--------universe strip_dash_and_equals = t.strip('-=') print(strip_dash_and_equals) # -->Output:hello--------universe # 7. cleaning up text s = 'pýtĥöñ\fis\tawesome\r\n' print(s) # -->Output:pýtĥöñ # is awesome remap = { ord('\t'): " ", ord('\f'): " ", ord('\r'): None, # deleted ord('\n'): " ", } a = s.translate(remap) print(a) # -->Output:pýtĥöñ is awesome # 8 . Aligning text string text = "Hello Universe" align_left = text.ljust(20) print(align_left) # --> output: 'Hello Universe ' align_right = text.rjust(20) print(align_right) # --> otput: ' Hello Universe' align_center = text.center(20) print(align_center) # --> Output: ' Hello Universe ' # 9. fill space align_left = text.ljust(20, '-') print(align_left) # --> output: Hello Universe------ align_right = text.rjust(20, '*') print(align_right) # --> otput:******Hello Universe align_center = text.center(20, '#') print(align_center) # --> Output: ###Hello Universe### # 10. format function can also be used to easily align align_right = format(text, '>20') print(align_right) # --> otput: ' Hello Universe' align_left = format(text, '<20') print(align_left) # --> output: 'Hello Universe ' align_center = format(text, '=^20') print(align_center) # --> Output: ===Hello Universe=== # 11.format function can be used with numbers too x = 1.23456 align_right = format(x, '$>10') print(align_right) # -->output:$$$1.23456 # truncate the number truncated_text = format(x, '*^10.2f') print(truncated_text) # -->Output: ***1.23***
from datetime import datetime from datetime import datetime, timedelta weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] def getPrevious_byDay(dayname, start_date=None): if start_date is None: start_date = datetime.today() day_num = start_date.weekday() day_num_target = weekdays.index(dayname) days_ago = (7 + day_num - day_num_target) % 7 if days_ago == 0: days_ago = 7 target_date = start_date - timedelta(days=days_ago) return target_date today = datetime.today() print(today) # ---> 2021-06-09 20:48:51.212291 prev_monday_date = getPrevious_byDay('monday') print(prev_monday_date) # ---> 2021-06-07 20: 49: 41.197876 print(getPrevious_byDay('wednesday')) # ---> 2021-06-02 20:51:09.433183 #============================================# # Relativedelta function from defaultutil # #============================================#
#===============# # 1.Time Delta # #===============# from datetime import datetime from datetime import timedelta a = timedelta(days=2, hours=6) b = timedelta(hours=4.5) c = a+b print(c) # ---> Output: 2 days, 10: 30: 00 # print days in c print(c.days) # ---> Output: 2 # print hours in c print(c.seconds/3600) # ---> Output: 10.5 # print total hours print(c.total_seconds()/3600) # ---> output: 58.5 #==============# # 2.Datetime # #==============# # import date time from datetime a = datetime(2012, 9, 23) print(a+timedelta(days=10)) # ---> Output: 2012-10-03 00:00:00 b = datetime(2021, 6, 12) d = b-a print(d) # ---> Output: 3184 days, 0: 00: 00 now = datetime.today() print(now) # time after 10 min after_ten_min = now+timedelta(minutes=10) print(after_ten_min)
import string # 1. interpolate string using format method message = '{name} has {n} messages...' new_message = message.format(name='Avinash', n=20) print(new_message) # ---> Avinash has 20 messages... # 2. interpolate string using format_map() and vars() message = '{student} has unique id : {id}' student = 'Avinash' id = 9 new_message = message.format_map(vars()) print(new_message) # ---> Avinash has unique id : 9 # 3 . define a class the pass the instance to vars() class Info: def __init__(self, student, id): self.student = student self.id = id a = Info('sam', 12) new_message = message.format_map(vars(a)) print(new_message) # ---> sam has unique id : 12 # 4. some interesting string interpolation student = 'Avinash' id = 41 s = string.Template('$student has $id messages.') new_s = s.substitute(vars()) print(new_s) # ---> Avinash has 41 messages.
items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Instead of doing manually we can set qa slic options print(items[2:4]) # ---> [2, 3] # slice(start,end,step) # a sile [2:4] a = slice(2, 4) # b slice [4: ] b = slice(4, 8, 2) print(items[a]) # ---> [2, 3] print(items[b]) # ---> [4, 6] # here b is an instance of slice so we can perform # b.start # b.end # b.step
import random #1.定级 # s= [] # s= input('Enter scores:').split() # def score(s): # bests = sorted(s) # best = bests[-1] # best = int(best) # for _ in s: # i=int(_) # if i>=best-10: # print(i,' is A') # elif i>=best-20: # print(i,' is B') # elif i>=best-30: # print(i,' is C') # elif i>=best-40: # print(i,' is D') # else: # print(i,' is F') # score(s) ############################################################################# #2.逆序读取 # def ni(): # l1=[ i for i in range(10)] # print(l1[::-1]) # ni() ############################################################################# #3.统计数字个数 # l1=[] # l1=input('Enter integers bewteen 1 and 100:').split() # def Tj(): # l3=[] # for _ in l1: # _ = int(_) # l3.append(_) # l2=sorted(set(l3)) # for _ in l2: # print(_,'occurs',l3.count(_),'times') # Tj() ############################################################################ #4.分析成绩 # s = input('>>').split() # def sorce(): # l1=[] # i=0 # a=0 # b=0 # for _ in s: # i +=1 # _ = int(_) # l1.append(_) # P = sum(l1)/i # for _ in l1: # if _ >= P: # a+=1 # else: # b+=1 # print(a,b) # sorce() ########################################################################### #5.统计单个数字 # def Tj(): # counts=[0,0,0,0,0,0,0,0,0,0] # for _ in range(0,1000): # a = random.randint(0,9) # counts[a] = counts[a]+1 # print(counts) # Tj() ########################################################################### #6.最小元素下标 # lst = input('>>').split() # def indexOfSmallestElement(lst): # l1=[] # i=1 # a=0 # for _ in lst: # _ = int(_) # l1.append(_) # while i<len(l1): # if l1[i]<l1[a]: # a=i # i+=1 # print(a) # indexOfSmallestElement(lst) ########################################################################### #7.随机数字选择器 # b={} # def shuffle(n): # global b # c=[] # while len(b)<=len(n)-1: # a=random.choice(n) # c.append(a) # b=set(c) # d=list(b) # d.sort(key=c.index) # print(d) # shuffle([0,1,2,3,4,5,6,7,8,9]) ########################################################################### #8.消除重复 # lst=input('Enter ten numbers:').split() # def eliminateDuplicates(lst): # l1=set(lst) # print('The distinct numbers are:',l1) # eliminateDuplicates(lst) ########################################################################### #9.有序么(好像得用while) # lst=input('Enter list:').split() # def isSorted(lst): # l1=[] # for _ in lst: # l1.append(_) # l1 = sorted(l1) # if l1==lst: # print('The list is already sorted') # return True # else: # print('The list is not sorted') # isSorted(lst1) ########################################################################### #10.冒泡排序 # lst = input('>>').split() # def Mp(): # l1=[] # b=0 # for _ in lst: # _ = int(_) # l1.append(_) # n=len(l1) # for _ in l1: # for i in range(0,n-b-1): # if l1[i]>l1[i+1]: # l1[i],l1[i+1]=l1[i+1],l1[i] # b+=1 # print(l1) # Mp() ########################################################################## #11优惠券问题 # ############################################################################# #12检测四个连续相等的数 # def isConsecutiveFour(n): # d=[] # for i in str(n): # b=0 # for a in str(n): # if a==i: # b+=1 # d.append(b) # e=set(d) # if 4 in e: # e.remove(4) # print('yes') # isConsecutiveFour([666644441]) ############################################################################## ############################################################################## #1检测ssn # import re # def ssn(n): # a=re.sub('\D','',n) # if len(a) == 9: # print('Valid SSN') # else: # print('Invaild SSN') # ssn('111-11-1111') ############################################################################## # 2检测第一个字符串是否是第二个的字串 # def chuan(s,n): # a=n.find(s) # if a>=0: # print('yes') # else: # print('no') # chuan('1','123') ############################################################################# # 3密码合法(8个字符,包含英文和数字,至少包含两个数字) # import re # def mima(n): # a=re.sub('\D','',n) # print(a) # if len(n)>=8 and n.isalnum() == True and len(a)>=2: # print('vaild password') # else: # print('invalid password') # mima('12aabal1') ############################################################################# # 4输入字符串显示字母数 # def countletters(s): # zi=[] # for i in s: # b=0 # for a in s: # if a == i: # b+=1 # zm=str(a)+'出现了'+str(b)+'次' # zi.append(zm) # zi_=set(zi) # zi__=sorted(list(zi_)) # for i_ in zi__: # print(i_) # countletters('icosnvowvinwbeuiboivn') ############################################################################ # 5按手机键盘的位置字母转数字(大小写全写,懒得写了) # def getNumber(n): # for i in n: # if i=='a' or i=='A' or i=='b' or i=="B" or i=='c' or i=='C': # print('2',end='') # elif i=='d'or i=='e' or i=='f'or i=='F': # print('3',end='') # elif i=='g'or i=='h' or i=='i': # print('4',end='') # elif i=='j' or i=='k' or i=='l': # print('5',end='') # elif i=='m' or i=='n' or i=='o': # print('6',end='') # elif i=='p' or i=='q' or i=='r' or i=='s': # print('7',end='') # elif i=='t' or i=='u' or i=='v': # print('8',end='') # elif i=='w' or i=='x' or i=='y' or i=='z': # print('9',end='') # else : # print(i,end='') # print() # getNumber('1-800-Flowers') # getNumber('1800flowers') ########################################################################### # 6反向字符串 # def reverse(s): # s_=s[::-1] # print(s_) # reverse('000dvnnoinvisn') ########################################################################### #8检测ISBN-13 # def isbn(n): # b=[] # for i in str(n): # b.append(i) # b_=[int(x) for x in b ] # c=10-(b_[0]+3*b_[1]+b_[2]+3*b_[3]+b_[4]+3*b_[5]+b_[6]+3*b_[7]+b_[8]+3*b_[9]+b_[10]+3*b_[11])%10 # if c==10: # print(str(n)+'0') # else: # print(str(n)+str(c)) # isbn(978013213080) # isbn(978013213079) ###########################################################################
""" 初版:2018-12-30 Flaskのパッケージをインストールしておきます pip install Flask """ # pipでインストールするもの from flask import Flask, render_template, url_for, request, redirect # はじめから入っているもの import sys import os import sqlite3 # データベースファイルのパス DB_PATH = "../notes.db" # データベースファイルのサイズ file_size = 0 # Pythonのバージョンを確認、表示 version = sys.version app = Flask(__name__) def dbaccess(): """ データベースのConnectionとCursorを作成して返す """ # もしファイルがなければテーブルを作る if not os.path.isfile(DB_PATH): create_table() # Connection があれば、 conn = sqlite3.connect(DB_PATH) # Cursor オブジェクトを作り cursor = conn.cursor() # その execute() メソッドを呼んで SQL コマンドを実行することができます # ファイルサイズの取得 global file_size file_size = os.path.getsize(DB_PATH) / 1024 return conn, cursor def create_table(): """ もしデータベースファイルがなければ新規にテーブルを作る関数 """ conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() # executeメソッドでSQL文を実行する cursor.execute(""" CREATE TABLE `category` ( `id` integer, `name` text, PRIMARY KEY(`id`) ); """) # executeメソッドでSQL文を実行する cursor.execute(""" CREATE TABLE `memo` ( `id` integer, `category_id` integer, `title` text, `detail` text, PRIMARY KEY(`id`) ); """) conn.commit() cursor.close() conn.close() @app.route("/") def index(): """ トップページや検索など """ conn, cursor = dbaccess() # キーワード検索 q = request.args.get("q", default="", type=str) # カテゴリ絞り込み id = request.args.get("id", default=0, type=int) # 返すリスト lists = [] # タイトル page_title = "メモ (Flask版)" # 検索文字 word = q # 検索とカテゴリ絞り込みは同時にできない仕様 if q != "": # 検索なら cursor.execute(""" SELECT t.id, t.category_id, c.name, t.title FROM memo as t LEFT OUTER JOIN category as c ON t.category_id = c.id WHERE c.name LIKE ? OR t.title LIKE ? OR t.detail LIKE ? ORDER BY t.id DESC; """, ("%"+q+"%", "%"+q+"%", "%"+q+"%")) lists = cursor.fetchall() page_title = q elif id != 0: # カテゴリ絞り込みなら cursor.execute(""" SELECT t.id, t.category_id, c.name, t.title FROM memo as t LEFT OUTER JOIN category as c ON t.category_id = c.id WHERE t.category_id = ? ORDER BY t.id DESC; """, (id,)) lists = cursor.fetchall() # カテゴリ名を取得 page_title = lists[0][2] else: # 普通のトップページ cursor.execute(""" SELECT t.id, t.category_id, c.name, t.title FROM memo as t LEFT OUTER JOIN category as c ON t.category_id = c.id ORDER BY t.id DESC; """) # 全件取得は c.fetchall() # 一つ一つ取り出す場合はfetchoneを使います。 lists = cursor.fetchall() # dbから切断 cursor.close() conn.close() # 辞書に変数を詰め込む dic = { "page_title": page_title, "file_size": file_size, "word": word, "version": version, "lists": lists } return render_template("index.html", dic=dic) @app.route("/memo_insert", methods=["POST", "GET"]) def memo_insert(): """ 新規入力 """ conn, cursor = dbaccess() if request.method == "POST": category_id = request.form["category_id"] title = request.form["title"] detail = request.form["detail"] # エラー用 maxid = 1 try: cursor.execute(""" INSERT INTO memo (category_id, title, detail) VALUES (?,?,?); """, (category_id, title, detail)) conn.commit() # 今INSERTした行のidを取得 cursor.execute("""SELECT max(id) as maxid FROM memo;""") # タプルなので maxid = cursor.fetchone()[0] except: conn.rollback() finally: cursor.close() conn.close() # 編集画面にリダイレクト return redirect(url_for("memo_update", id=maxid)) # getなら else: # カテゴリをselect化 cursor.execute("""SELECT * FROM category;""") lists = cursor.fetchall() cursor.close() conn.close() # 辞書に変数を詰め込む dic = { "page_title": "新規追加", "version": version, "lists": lists } return render_template('memo_insert.html', dic=dic) @app.route("/memo_update/<int:id>", methods=["POST", "GET"]) def memo_update(id): """ 更新・削除 """ if request.method == "POST": delete = 0 try: delete = int(request.form["delete"]) except: pass category_id = request.form["category_id"] title = request.form["title"] detail = request.form["detail"] conn, cursor = dbaccess() # 削除 if delete == 1: try: cursor.execute("""DELETE FROM memo WHERE id=?;""", (id,)) conn.commit() except: conn.rollback() finally: cursor.close() conn.close() # トップページにリダイレクト return redirect(url_for("index")) # 更新 else: try: cursor.execute(""" UPDATE memo SET category_id = ?, title = ?, detail = ? WHERE id = ?; """, (category_id, title, detail, id)) conn.commit() except: conn.rollback() finally: cursor.close() conn.close() conn, cursor = dbaccess() # カテゴリをselect化 cursor.execute("""SELECT * FROM category;""") lists = cursor.fetchall() cursor.execute(""" SELECT t.category_id, c.name, t.title, t.detail FROM memo as t LEFT OUTER JOIN category as c ON t.category_id = c.id WHERE t.id = ?; """, (id,)) category_id, name, title, detail = cursor.fetchone() cursor.close() conn.close() # 辞書に変数を詰め込む dic = { "page_title": "編集", "version": version, "lists": lists, "id": id, "category_id": category_id, "title": title, "detail": detail } return render_template("memo_update.html", dic=dic) @app.route("/detail/<int:_id>") def detail(_id): """ 詳細表示 """ conn, cursor = dbaccess() cursor.execute(""" SELECT t.id, t.category_id, c.name, t.title, t.detail FROM memo as t LEFT OUTER JOIN category as c ON t.category_id = c.id WHERE t.id = ?; """, (_id,)) id, category_id, name, title, detail = cursor.fetchone() cursor.close() conn.close() # 辞書に変数を詰め込む dic = { "page_title": title, "version": version, "id": id, "category_id": category_id, "name": name, "title": title, "detail": detail } return render_template("detail.html", dic=dic) @app.route("/category", methods=["POST", "GET"]) def category(): """ カテゴリ編集画面 """ if request.method == "POST": name = request.form["name"] conn, cursor = dbaccess() try: cursor.execute( """INSERT INTO category (name) VALUES (?);""", (name,)) conn.commit() except: conn.rollback() finally: cursor.close() conn.close() conn, cursor = dbaccess() cursor.execute("""SELECT * FROM category;""") lists = cursor.fetchall() cursor.close() conn.close() # 辞書に変数を詰め込む dic = { "page_title": "カテゴリ編集画面", "version": version, "lists": lists } return render_template('category.html', dic=dic) @app.route("/category_update", methods=["POST"]) def category_update(): """ カテゴリ更新 """ if request.method == "POST": id = request.form["id"] name = request.form["name"] if id != "" and name != "": f = "ok" conn, cursor = dbaccess() try: cursor.execute( """UPDATE category SET name=? WHERE id=?;""", (name, id)) conn.commit() except: conn.rollback() f = "ng" finally: cursor.close() conn.close() return f return "ng" @app.route("/category_delete", methods=["POST"]) def category_delete(): """ カテゴリ削除 """ if request.method == "POST": id = request.form["id"] if id != "": conn, cursor = dbaccess() f = "ok" try: cursor.execute("""DELETE FROM category WHERE id=?;""", (id,)) conn.commit() except: conn.rollback() f = "ng" finally: cursor.close() conn.close() return f return "ng" @app.route("/vacuum") def vacuum(): """ SQLiteの空き領域開放 """ conn, cursor = dbaccess() try: cursor.execute("""VACUUM;""") conn.commit() except: conn.rollback() finally: cursor.close() conn.close() # トップページにリダイレクト return redirect(url_for("index")) if __name__ == '__main__': app.run(debug=True)
from matplotlib import pyplot as plt from graph import Greengraph def plotGraph(start, end, steps, out=None): """ Generate a greeting string for a person. Parameters ---------- start: str Start city. end: str End city. steps: int Gives number of images to process between start and end. out: str Specifies output file for graph. If not given then graph will be displayed. Returns ------- Nothing """ mygraph=Greengraph(start, end) data = mygraph.green_between(steps) plt.plot(data) plt.xlabel("steps") plt.ylabel("proportion of green pixels") plt.title("Greengraph from "+start+" to "+end) if out: plt.savefig(out) else: plt.show()
import tkinter import tkinter.messagebox from tkinter import Tk,Label,Entry,Button,END,LEFT,RIGHT from tkinter import * import math root = Tk() l1=Label(root,text="Enter per day saving amount: ").pack() e1=Entry(root,bd=10) e1.pack() l2=Label(root,text="How Many Years you want to Save ? : ").pack() e2=Entry(root,bd=10) e2.pack() root.geometry("600x400") root.title("Saving Calculator By DMT H4CK3R") root.configure(bg='SeaGreen1') def cal(): a=int(e1.get()) b=int(e2.get()) month = a*30 months = month*6 year = month*12 iyear = year*b l1=Label(root,text=('Monthly: ',int(month),'Rs'),fg='red',font=("Helvetica", 25)).pack() l2=Label(root,text=('6 months: ',int(months),'Rs'),fg='red',font=("Helvetica", 25)).pack() l3=Label(root,text=('yearly: ',int(year),'Rs'),fg='red',font=("Helvetica", 25)).pack() l4=Label(root,text=(b,'year: ',int(iyear),'Rs'),fg='red',font=("Helvetica", 25)).pack() def clear1(): e1.delete(0,END) def clear2(): e2.delete(0,END) def ex(): root.withdraw() b1=Button(root,text='Calculate',command=cal,bg='SeaGreen3',height=2,width=10) b1.pack() b2=Button(root,text='Clear-1',command=clear1,bg='SeaGreen3',height=2,width=10) b2.pack(side=LEFT) b3=Button(root,text='Clear-2',command=clear2,bg='SeaGreen3',height=2,width=10) b3.pack(side=RIGHT) b3=Button(root,text='Exit',command=ex,bg='SeaGreen3',height=2,width=10) b3.pack(side=BOTTOM) root.mainloop()
Python 2.7.6 (default, Jun 22 2015, 18:00:18) [GCC 4.8.2] on linux2 Type "copyright", "credits" or "license()" for more information. >>> x = 5 >>> if x<10: print('Smaller') Smaller >>> if x>20: print('Bigger') >>> if x>20: print('Bigger') print('Finis') >>> >>> x=5 >>> if x==5: print("Equals 5") Equals 5 >>> if x>4: print("Greater than 4") Greater than 4 >>> if x>=5: print("Greater than or equals 5") Greater than or equals 5 >>> if x<6: print("Less than 6") Less than 6 >>> if x!=6: print("Not equal 6") Not equal 6 >>> x=5 >>> print("Before 5") Before 5 >>> if x==5 SyntaxError: invalid syntax >>> if x == 5: print("Is 5") print("Is still 5") print("Third 5") Is 5 Is still 5 Third 5 >>> print("Afterwards 5") Afterwards 5 >>> print("Before 6") Before 6 >>> if x==6: print("Is 6") print("Is still 6") print("Third 6") >>> print("Afterwards 6") Afterwards 6 >>> x=5 >>> if x>2: print("Bigger than 2") print("Still bigger") print("Done with 2") SyntaxError: invalid syntax >>> ================================ RESTART ================================ >>> Bigger than 2 Still bigger Done with 2 >>> for i in range(5): print(i) if i>2: print("Bigger than 2") print("Done with i",i) print("All done") SyntaxError: invalid syntax >>> ================================ RESTART ================================ >>> 0 ('Done with i', 0) 1 ('Done with i', 1) 2 ('Done with i', 2) 3 Bigger than 2 ('Done with i', 3) 4 Bigger than 2 ('Done with i', 4) All done >>> ================================ RESTART ================================ >>> More than one Less than 100 All done >>> ================================ RESTART ================================ >>> Bigger All done >>> ================================ RESTART ================================ >>> Traceback (most recent call last): File "/home/agneta/RTR105/piemers1.py", line 1, in <module> if x<2: NameError: name 'x' is not defined >>> ================================ RESTART ================================ >>> Medium All done >>> ================================ RESTART ================================ >>> LARGE All done >>>
zodiac_animals = ["Bear", "Cat", "Dog", "Dolphin", "Antelope", "Gila Monster", "Orangutan", "Rat", "Rooster", "Sheep", "Giraffe", "Puffin"] print ("In which year were you born?") year = None while year == None: try: year = int(input()) except: print ("Please enter an integer year.") year_remainder = year%12 print ("Your Zodiac animal is the " + zodiac_animals[year_remainder] + ".")
def answer(food, grid): if len(grid) == 0 or len(grid[0]) == 0: raise Exception("Invalid grid. Don't do this to me, man.") if (food > 200): raise Exception("That's too much food. 200 max") best_path = best_path_from(0, 0, food, grid) if best_path == 201: return -1 else: return best_path def best_path_from(x, y, food, grid): #print ("exploring room " + str(x) + ", " + str(y)) this_square_cost = grid[y][x] max_y = len(grid) - 1 max_x = len(grid[0]) - 1 if this_square_cost > food: print ("ran out of food in square " + str(x) + ", " + str(y)) return 201 food = food - this_square_cost next_rooms = [] if x != max_x: next_rooms.append((x+1, y)) #print ("exploring right") if y != max_y: next_rooms.append((x, y+1)) #print ("exploring down") if len(next_rooms) == 0: #print ("found a way out with " + str(food) + " food remaining") return food return min([best_path_from(room[0], room[1], food, grid) for room in next_rooms])
import math def n_choose_m(n, m): return math.factorial(n)/(math.factorial(n-m)*math.factorial(m)) class TreeNode(): def __init__(self, value, left, right): self.left = left self.right = right self.value = value def build_order_possibilities(self): #one side of the tree doesn't care about the order of the other #so one side's nodes can be inserted in to the build array at #any point between the other side- simply total nodes choose one side (left or right) #this gives us the number of possibilities for build orders of the combined tree #but that side could already be a combined tree with multiple posible build orders #so, recursively factor in the possibilities of the left and right trees! child_count = self.size() - 1 left_size = 0 if (self.left != None): left_size = self.left.size() left_possibilities = 1 if (self.left != None): left_possibilities = self.left.build_order_possibilities() right_possibilities = 1 if (self.right != None): right_possibilities = self.right.build_order_possibilities() return n_choose_m(child_count, left_size) * left_possibilities * right_possibilities def size(self): if (self.left == None and self.right == None): return 1 if (self.left == None): return self.right.size() + 1 if (self.right == None): return self.left.size() + 1 return self.left.size() + self.right.size() + 1 def insert(self, node): if (node.value < self.value): if (self.left == None) : self.left = node else: self.left.insert(node) else: if (self.right == None): self.right = node else: self.right.insert(node) def answer(seq): if (len(seq) == 1): return 1 root = TreeNode(seq[0], None, None) for bunny_age in seq[1:]: root.insert(TreeNode(bunny_age, None, None)) return str(int(root.build_order_possibilities()))
import math def answer(N, K): return str(recursive_answer(N, K)) #memoized recursive method will perform similarly to tabular method memoized_calls = {} def recursive_answer(N, K): if (N, K) in memoized_calls: return memoized_calls[N, K] if K == N-1: memoized_calls[N, K] = int(math.pow(N, N-2)) return int(math.pow(N, N-2)) #there are n(n-1)/2 possible tunnels #there are n(n-1)/2 choose k choices of tunnel possible #subtract the number of choices that exclude warrens to find answer possible_choices = n_choose_m(N*(N-1)//2, K) for i in range(N-1): unconnected_choices = 0 #we can shave off unnecessary solutions #i referenced Marko Riedel's math stackexchange post #(http://math.stackexchange.com/questions/689526/how-many-connected-graphs-over-v-vertices-and-e-edges/690422#690422) for j in range(max ( [( K - int ((float(1)/2) * (i+1) * i) ), 0] ), K-i+1): unconnected_choices += n_choose_m( (N-1-i)*(N-2-i)/2, j ) * recursive_answer(i + 1, K - j) possible_choices -= n_choose_m(N-1, i)*unconnected_choices memoized_calls[N, K] = possible_choices return possible_choices memoized_binomials = {} def n_choose_m(n, m): if (n, m) in memoized_binomials: return memoized_binomials[n, m] if (m > n): return 0 binomial = int(math.factorial(n)) / int((math.factorial(n-m)*math.factorial(m))) memoized_binomials[n, m] = binomial return binomial
def answer(numbers): seen_pirates = [] current_pirate = 0 while current_pirate not in seen_pirates: seen_pirates.append(current_pirate) current_pirate = numbers[current_pirate] return len(seen_pirates[seen_pirates.index(current_pirate):])
def answer(heights): if len(heights) <= 1: return 0 divide = max(heights) divide_index = heights.index(divide) left = heights[:divide_index] right = heights[divide_index+1:] right.reverse() return held_water(left) + held_water(right) def held_water(heights): #consider a hut group with a wall on the right side #the water it holds is equal to the water from the max height hut #to the huts below it, from the max height hut to the wall on the right #that max height hut then becomes a wall to the right for the huts #to the left of it, and we use the same process on those huts to the left if len(heights) <= 1: return 0 divide = max(heights) divide_index = heights.index(divide) left = heights[:divide_index] right = heights[divide_index:] held_water_total = 0 for height in right: held_water_total = held_water_total + (divide - height) return held_water_total + held_water(left)
import numpy as np class NaiveBayes(object): def __init__(self,num_class,feature_dim,num_value): """Initialize a naive bayes model. This function will initialize prior and likelihood, where prior is P(class) with a dimension of (# of class,) that estimates the empirical frequencies of different classes in the training set. likelihood is P(F_i = f | class) with a dimension of (# of features/pixels per image, # of possible values per pixel, # of class), that computes the probability of every pixel location i being value f for every class label. Args: num_class(int): number of classes to classify feature_dim(int): feature dimension for each example num_value(int): number of possible values for each pixel """ print("num_class", num_class) print("num_value", num_value) print("feature_dim", feature_dim) self.num_value = num_value self.num_class = num_class self.feature_dim = feature_dim self.prior = np.zeros((num_class)) self.likelihood = np.zeros((feature_dim,num_value,num_class)) def train(self,train_set,train_label): """ Train naive bayes model (self.prior and self.likelihood) with training dataset. self.prior(numpy.ndarray): training set class prior (in log) with a dimension of (# of class,), self.likelihood(numpy.ndarray): traing set likelihood (in log) with a dimension of (# of features/pixels per image, # of possible values per pixel, # of class). You should apply Laplace smoothing to compute the likelihood. Args: train_set(numpy.ndarray): training examples with a dimension of (# of examples, feature_dim) train_label(numpy.ndarray): training labels with a dimension of (# of examples, ) """ print("line 40, begin to train") total = train_label.shape[0] dim = train_set.shape[1] k = 0.1 ## need to change for i in range(total): label = train_label[i] self.prior[label] += 1 print('self.prior assign finished') for i in range(total):#iterate through all the test case label = train_label[i] denominator = self.prior[label] + k*self.num_value addingcomponent = 1.0 / denominator for j in range(dim): value = train_set[i][j] self.likelihood[j][value][label] += addingcomponent print('likelihood assign finished') for i in range(self.num_class): #iterate through all the class denominator = self.prior[i] + k*self.num_value self.likelihood[:,:,i] += k / denominator self.prior[i] = self.prior[i] / total self.prior[i] = np.log(self.prior[i]) print('likelihood modify finished') self.likelihood = np.log(self.likelihood) # YOUR CODE HERE print(self.prior) pass def test(self,test_set,test_label): """ Test the trained naive bayes model (self.prior and self.likelihood) on testing dataset, by performing maximum a posteriori (MAP) classification. The accuracy is computed as the average of correctness by comparing between predicted label and true label. Args: test_set(numpy.ndarray): testing examples with a dimension of (# of examples, feature_dim) test_label(numpy.ndarray): testing labels with a dimension of (# of examples, ) Returns: accuracy(float): average accuracy value pred_label(numpy.ndarray): predicted labels with a dimension of (# of examples, ) """ print("line 79, begin to test") accuracy = 0 pred_label = np.zeros((len(test_set))) # YOUR CODE HERE total = test_label.shape[0] dim = test_set.shape[1] num_class = self.num_class highest= {} lowest = {} for i in range(num_class): highest[i]=(0,-1000000) lowest[i] =(0,1000000) for i in range(total): #calculate for the first class pred = 0 map = self.prior[0] for d in range(dim): value = test_set[i][d] map += self.likelihood[d][value][0] for label in range(1,num_class): probability = self.prior[label] for d in range(dim): value = test_set[i][d] probability += self.likelihood[d][value][label] if probability > map: map = probability pred = label if test_label[i]==pred and probability > highest[test_label[i]][1]: highest[test_label[i]]=(i,probability) if test_label[i]==pred and probability < lowest[test_label[i]][1]: lowest[test_label[i]]=(i,probability) pred_label[i] = pred if test_label[i] == pred: accuracy+=1 accuracy = accuracy / total print(accuracy) print('highest:',highest) print('lowest:',lowest) return accuracy, pred_label pass def save_model(self, prior, likelihood): """ Save the trained model parameters """ np.save(prior, self.prior) np.save(likelihood, self.likelihood) def load_model(self, prior, likelihood): """ Load the trained model parameters """ self.prior = np.load(prior) self.likelihood = np.load(likelihood) def intensity_feature_likelihoods(self, likelihood): """ Get the feature likelihoods for high intensity pixels for each of the classes, by sum the probabilities of the top 128 intensities at each pixel location, sum k<-128:255 P(F_i = k | c). This helps generate visualization of trained likelihood images. Args: likelihood(numpy.ndarray): likelihood (in log) with a dimension of (# of features/pixels per image, # of possible values per pixel, # of class) Returns: feature_likelihoods(numpy.ndarray): feature likelihoods for each class with a dimension of (# of features/pixels per image, # of class) """ # YOUR CODE HERE feature_likelihoods = np.zeros((likelihood.shape[0],likelihood.shape[2])) # dim by num of class d = self.feature_dim c = self.num_class for dim in range(d): for label in range(c): for k in range(128,256): feature_likelihoods[dim][label] += self.likelihood[dim][k][label] return feature_likelihoods
import random list = [random.randint(1, 9999) for _ in range(10)] print("before sorted:", list) list.sort() print("after sorted:", list) list.reverse() print("after reversed:", list)
import random import time from typing import List def shell_sort(a: List[int]) -> None: n = len(a) h = n // 2 while h > 0: for i in range(h, n): tmp = a[i] j = i - h while j >= 0 and a[j] > tmp: a[j + h] = a[j] j -= h a[j + h] = tmp h //= 2 if __name__ == "__main__": print("shell sort") num = int(input("number of elements: ")) x = [random.randint(0, num) for _ in range(num)] print(x) start = time.time() shell_sort(x) end = time.time() print("sorted!") print(x) print(end - start)
def change_string(strn: str) -> str: strn = strn * 5 return strn strn = "keio" print("before function, strn ==", strn) strn2 = change_string(strn) print("after function, strn ==", strn) print(" strn2 ==", strn2)
from backend_dij import * import numpy as np import math import sys ''' print("The start and end coordinates should lie between 200 x 300 area.") startRow = int(input("Enter the x-coordinate for start node: ")) startCol = int(input("Enter the y-coordinate for start node: ")) goalRow = int(input("Enter the x-coordinate for goal node: ")) goalCol = int(input("Enter the y-coordinate for goal node: ")) radius = int(input("Enter the radius for the robot : ")) clearance = int(input("Enter the clearance for the robot : ")) ''' startRow = 10 startCol = 10 goal1Row = 475 goal1Col = 100 goal1per = 30 goal2Row = 450 goal2Col = 680 goal2per = 50 goal3Row = 200 goal3Col = 500 goal3per = 20 radius = 1 clearance = 1 # take start and goal node as input start = (startRow, startCol) e = (goal1Row, goal1Col) f = (goal2Row, goal2Col) g = (goal3Row, goal3Col) print("\n Start point:", start) print("\n Contamination points (x co-ordinate, y co-rodinate, contamination percent) Before Prioritizing based on Contamination percentage") print((goal1Row, goal1Col, goal1per)) print((goal2Row, goal2Col, goal2per)) print((goal3Row, goal3Col, goal3per)) #Calculate Centroid x = int((goal1Row + goal2Row + goal3Row ) / 3) y = int((goal1Col + goal2Col + goal3Col ) / 3) goal = (x,y) A = {goal1per: e, goal2per: f, goal3per: g} l=list(A.items()) l.sort() l.reverse() print("\n The Priority Queue based on Contamination Percent", l) goal1 = (l[0][1]) print("\n contamination Point 1: ",goal1) goal2 = (l[1][1]) print("\n contamination Point 2: ",goal2) goal3 = (l[2][1]) print("\n contamination Point 3: ",goal3) print("\n Centroid for all the contamination point is: ",goal) step1 = Step(start, goal, None, clearance, radius) step2 = Step(goal, goal1, None, clearance, radius) step3 = Step(goal1, goal2, None, clearance, radius) step4 = Step(goal2, goal3, None, clearance, radius) print("\n Step 1: To Calculate the path to Centroid") print("\n .") print("\n .") print("\n .") if(step1.IsValid(start[0], start[1])) and (step1.IsValid(goal[0], goal[1])) and (step1.obstacle(start[0],start[1]) == False) and (step1.obstacle(goal[0], goal[1]) == False): (explored, backstates, path_step1) = step1.Dij() step1.animate(explored, backstates, "C:/Users/13017/Desktop/Output/proj5/path/step1.avi") print("\nOptimal path found. Distance is " + str(path_step1)) if(path_step1 == float('inf')): print("\nNo optimal path found.") else: pass else: print("The entered nodes are outside the map or in the obstacle ") print("\n ") print("\n ") print("\n ") print("\n Step 2: To Calculate the path to Contamination point 1") print("\n .") print("\n .") print("\n .") if(step2.IsValid(goal[0], goal[1])) and (step2.IsValid(goal1[0], goal1[1])) and (step2.obstacle(goal[0],goal[1]) == False) and (step2.obstacle(goal1[0], goal1[1]) == False): (explored, backstates, path_step2) = step2.Dij() step2.animate(explored, backstates, "C:/Users/13017/Desktop/Output/proj5/path/step2.avi") print("\nOptimal path found. Distance is " + str(path_step2)) if(path_step2 == float('inf')): print("\nNo optimal path found.") else: pass else: print("The entered nodes are outside the map or in the obstacle ") print("\n ") print("\n ") print("\n ") print("\n Step 3: To Calculate the path to Contamination point 2") print("\n .") print("\n .") print("\n .") if(step3.IsValid(goal1[0], goal1[1])) and (step3.IsValid(goal2[0], goal2[1])) and (step3.obstacle(goal1[0],goal1[1]) == False) and (step3.obstacle(goal2[0], goal2[1]) == False): (explored, backstates, path_step3) = step3.Dij() step3.animate(explored, backstates, "C:/Users/13017/Desktop/Output/proj5/path/step3.avi") print("\nOptimal path found. Distance is " + str(path_step3)) if(path_step3 == float('inf')): print("\nNo optimal path found.") else: pass else: print("The entered nodes are outside the map or in the obstacle ") print("\n ") print("\n ") print("\n ") print("\n Step 4: To Calculate the path to Contamination point 3") print("\n .") print("\n .") print("\n .") if(step4.IsValid(goal2[0], goal2[1])) and (step4.IsValid(goal3[0], goal3[1])) and (step4.obstacle(goal2[0],goal2[1]) == False) and (step4.obstacle(goal3[0], goal3[1]) == False): (explored, backstates, path_step4) = step4.Dij() step4.animate(explored, backstates, "C:/Users/13017/Desktop/Output/proj5/path/step4.avi") print("\nOptimal path found. Distance is " + str(path_step4)) if(path_step4 == float('inf')): print("\nNo optimal path found.") else: pass else: print("The entered nodes are outside the map or in the obstacle ") print("\n .") print("\n .") print("\n .") print("\n Path Planning Completed")
# All of the utility classes, methods, and functions are contained here. Where most of the math actually happens. # ---DISCLAIMER--- # Most of the things in this file are formulas I Googled, code that was part of the example bot (like Vector3), or from # the RLBot community. That being said, I did put a lot of time into researching and understanding the code. # A lot of the math is above my level, so the fact that I understand most of whats happening was a win in my book. import math # Never changing map values GOAL_WIDTH = 1900 FIELD_LENGTH = 10280 FIELD_WIDTH = 8240 boosts = [ [3584, 0, 0], [-3584, 0, 0], [3072, 4096, 0], [3072, -4096, 0], [-3072, 4096, 0], [-3072, -4096, 0]] # Basically python arrays but with some added functionality to work like math vectors. Was part of # example RLBot program and so I decided to use it as well. class Vector3: def __init__(self, data): self.data = data def __add__(self, value): return Vector3([self.data[0] + value.data[0], self.data[1] + value.data[1], self.data[2] + value.data[2]]) def __sub__(self, value): return Vector3([self.data[0] - value.data[0], self.data[1] - value.data[1], self.data[2] - value.data[2]]) def __mul__(self, value): return self.data[0] * value.data[0] + self.data[1] * value.data[1] + self.data[2] * value.data[2] def magnitude(self): return math.sqrt((self.data[0] * self.data[0]) + (self.data[1] * self.data[1]) + (self.data[2] * self.data[2])) def normalize(self): mag = self.magnitude() if mag != 0: return Vector3([self.data[0] / mag, self.data[1] / mag, self.data[2] / mag]) else: return Vector3([0, 0, 0]) class Matrix2: def __init__(self, data): self.data = data def __mul__(self, value): return Vector3([value.data[0] * self.data[0][0] + value.data[1] * self.data[1][0], value.data[0] * self.data[0][1] + value.data[1] * self.data[1][1], 0]) ROTATE = Matrix2([[0, -1], [1, 0]]) class obj: def __init__(self): self.location = Vector3([0, 0, 0]) self.velocity = Vector3([0, 0, 0]) self.rotation = Vector3([0, 0, 0]) self.rvelocity = Vector3([0, 0, 0]) self.local_location = Vector3([0, 0, 0]) self.boost = 0 def quad(a, b, c): inside = (b ** 2) - (4 * a * c) if inside < 0 or a == 0: return 0.1 else: n = ((-b - math.sqrt(inside)) / (2 * a)) p = ((-b + math.sqrt(inside)) / (2 * a)) if p > n: return p return n # crudely predicts where the ball will be in a given amount of time, doesnt take things like walls into account # doesn't work too well def future(ball, time): x = ball.location.data[0] + (ball.velocity.data[0] * time) y = ball.location.data[1] + (ball.velocity.data[1] * time) z = ball.location.data[2] + (ball.velocity.data[1] * time) return Vector3([x, y, z]) # calculates how long till the ball hits the ground def timeZ(ball): rate = 0.97 return quad(-325, ball.velocity.data[2] * rate, ball.location.data[2] - 92.75) def dpp(target_loc, target_vel, our_loc, our_vel): target_loc = toLocation(target_loc) our_loc = toLocation(our_loc) our_vel = toLocation(our_vel) d = distance2D(target_loc, our_loc) if d != 0: return (((target_loc.data[0] - our_loc.data[0]) * (target_vel.data[0] - our_vel.data[0])) + ( (target_loc.data[1] - our_loc.data[1]) * (target_vel.data[1] - our_vel.data[1]))) / d else: return 0 def to_local(target_object, our_object): x = (toLocation(target_object) - our_object.location) * our_object.matrix[0] y = (toLocation(target_object) - our_object.location) * our_object.matrix[1] z = (toLocation(target_object) - our_object.location) * our_object.matrix[2] return Vector3([x, y, z]) def rotator_to_matrix(our_object): r = our_object.rotation.data CR = math.cos(r[2]) SR = math.sin(r[2]) CP = math.cos(r[0]) SP = math.sin(r[0]) CY = math.cos(r[1]) SY = math.sin(r[1]) matrix = [] matrix.append(Vector3([CP * CY, CP * SY, SP])) matrix.append(Vector3([CY * SP * SR - CR * SY, SY * SP * SR + CR * CY, -CP * SR])) matrix.append(Vector3([-CR * CY * SP - SR * SY, -CR * SY * SP + SR * CY, CP * CR])) return matrix def radius(v): return 139.059 + (0.1539 * v) + (0.0001267716565 * v * v) def ballReady(agent): ball = agent.ball if abs(ball.velocity.data[2]) < 150 and timeZ(agent.ball) < 1: return True return False def ballProject(agent): goal = Vector3([0, -sign(agent.team) * FIELD_LENGTH / 2, 100]) goal_to_ball = (agent.ball.location - goal).normalize() difference = agent.me.location - agent.ball.location return difference * goal_to_ball def sign(x): if x <= 0: return -1 else: return 1 def cap(x, low, high): if x < low: return low elif x > high: return high else: return x def steer(angle): final = ((10 * angle + sign(angle)) ** 3) / 20 return cap(final, -1, 1) def angle2(target_location, object_location): difference = toLocation(target_location) - toLocation(object_location) return math.atan2(difference.data[1], difference.data[0]) def velocity2D(target_object): return math.sqrt(target_object.velocity.data[0] ** 2 + target_object.velocity.data[1] ** 2) def toLocal(target, our_object): if isinstance(target, obj): return target.local_location else: return to_local(target, our_object) def toLocation(target): if isinstance(target, Vector3): return target elif isinstance(target, list): return Vector3(target) else: return target.location def distance2D(target_object, our_object): difference = toLocation(target_object) - toLocation(our_object) return math.sqrt(difference.data[0] ** 2 + difference.data[1] ** 2)
# Definitions def show(): print() print(f" 0 1 2 ") print("--------------") for i, row in enumerate(field): row_str = f"{i}| " + " | ".join(row) + " |" print(row_str) print("__") print() #--------------------------- # Делаем ход def ask(): while True: try: x, y = map(int, input(" ваш ход: ").split()) if 0 > x or x > 2 or 0 > y or y > 2: # <=2 and 0<= y<=2: print("Координаты вне диапозона!") elif field[x][y] != " ": print("ячейка не доступна.") else: return x, y except: print("ошибка при обработке.") #--------------------------- def chek_win(): winner=" " for i in range(3): if field[0][i]!=" "and field[0][i]==field[1][i]==field[2][i]: winner=field[0][i] for i in range(3): if field[i][0]!=" "and field[i][0]==field[i][1]==field[i][2]: winner=field[i][0] if field[0][0]!=" "and field[0][0]==field[1][1]==field[2][2]: winner=field[0][0] if field[2][0]!=" "and field[2][0]==field[1][1]==field[0][2]: winner=field[2][0] if winner!=" ": show() print(f" Ура {winner} победа!") return True# игра крестики нолики # создаем поле # ============================================================================================= while True: field = [[" "] * 3 for i in range(3)] step = 0 while True: step += 1 show() if step % 2 == 1: print("Ходит x") else: print("Ходит o") x, y = ask() if step % 2 == 1: field[x][y] = "x" else: field[x][y] = "o" # если ничья if chek_win(): break if step == 9: print("НИЧЬЯ") break if str(input("Хотитите сыграть еще раз? Нажмите Y, если Да.")).lower!="y": break
# Copyright (c) 2021 D.Damian # Released under the MIT license # ************************************************************************************************ # check if range of numbers contains any palindrome (number which look the same when read forward and backward) # Example numbers: 59395 # ************************************************************************************************ var_1 = input("What is the minimum number of the range:") var_2 = input("What is the maximum number of the range:") m = 1 for i in range(int(var_1), int(var_2)): product = i * m n = product temp=n rev=0 while(n>0): dig=n%10 rev=rev*10+dig n=n//10 if(temp==rev): print(product, "The number is a palindrome!")
import os os.system("cls") i=5 for j in range(i): x=int(input("Wpisz liczby, którą chciałbyś podnieść do kwadratu: ")) print(x*x)
from Tkinter import * root= Tk() labelframe= LabelFrame(root,text="This is a Labelframe") labelframe.pack(fill="both", expand="yes") left= Label(labelframe,text="Inside the LabelFrame") left.pack() root.mainloop() #also try expand="no" and see
from Tkinter import * root=Tk() frame= Frame(root) frame.pack() bottomframe= Frame(root) bottomframe.pack(side= BOTTOM) redbutton= Button(frame,text="Red", fg="red") redbutton.pack(side= RIGHT) brownbutton= Button(frame,text="Brown", fg="Brown") brownbutton.pack(side= LEFT) bluebutton= Button(frame,text="Blue", fg="Blue") bluebutton.pack(side= LEFT) blackbutton= Button(bottomframe,text="Black", fg="Black") blackbutton.pack(side= BOTTOM) root.mainloop() #change side and see
from itertools import imap from random import uniform def monte_carlo_integrate(func, xmin, xmax, num_points=100): """Performs definite integration on :param func:. The range is specified by the range :param xmin: < :param xmax: :param num_points: defines the resolution of the grid. Higher numbers will yield more accurate results, at the cost of time. .. note:: Increasing num points will have diminishing returns. Error ~= 1 / sqrt(:param num_points:) """ ymin, ymax = get_min_max_for_func(func, xmin, xmax) rectangle_area = (ymax - ymin) * (xmax - xmin) points = make_random_points((xmin, ymin), (xmax, ymax), num_points) ratio_under_curve = num_under_curve(func, points) / float(num_points) return rectangle_area * ratio_under_curve def num_under_curve(func, coordinates): """# points in :param coordinates: falling under the curve :param func:.""" def is_under_curve(xy): x, y = xy true_y = func(x) if true_y > 0 and y >= 0 and y < true_y: return 1 if true_y < 0 and y <= 0 and y > true_y: return -1 return 0 return sum(imap(is_under_curve, coordinates)) def get_min_max_for_func(func, xmin, xmax, num_points=100000): """Get the minimum and maximum values for the given function and range. ..note: This is an approximation. """ def frange(start, stop, step): """Like xrange, but works with floats.""" while start < stop: yield start start += step step = (xmax - xmin) / float(num_points) min_val, max_val = 0, 0 for y in imap(func, frange(xmin, xmax, step)): if y < min_val: min_val = y elif y > max_val: max_val = y return min_val, max_val def make_random_points(min_corner, max_corner, num_points): """Returns random coordinate pairs in the rectangle defined.""" xmin, ymin = min_corner xmax, ymax = max_corner return ((uniform(xmin, xmax), uniform(ymin, ymax)) \ for i in xrange(num_points))
# Dictionaries and sets are both data collections in python ## Dicts? ### sets? # dicts are another way to manage data but can be a little more dynamic # Dict works as a JEY and VALUE # KEY = the refernce of the object # VALUE = What is the data storage mechanism you need to use # Dynamic as it we have lists, and another dict inside a dict # Syntax - name = {} as use {} brackets to declare a Dict # Key = Value # Key students_1 = {"name": "James", "stream": "Devops", "Completed_lessons" : 4, "Completed_lessons_names": ["Data types", "Git and Github", "Operators", "Lidts and tuples"]} # Lets check if we have got the syntax right and print the dict # print(students_1) # print(type(students_1)) # print(students_1["stream"]) # This is how we can fetch the value saved in the key called "stream" # print(students_1["Completed_lessons_names"][1]) # # print the second last index of the key completed_lessons_names:[] # # print(students_1["Completed_lessons_names"][-2]) # # # Could we apply CRUD on a Dict? # # Print the second last value in the dict # # students_1["Completed_lessons"] = 3 # print(students_1["Completed_lessons"]) # # students_1["Completed_lessons_names"].remove("Operators") # print(students_1["Completed_lessons_names"]) # We have some bulletin methods that we can use with dict # To print all the keys keys() # print(students_1.keys()) # To print all the values # print(students_1.values()) # Sets are also Data collection # Syntax name = {" ", " ", " "} # What is the diff between sets and dict? # Sets are unordered shopping_list = {"eggs", "tea", "milk"} # 0 1 2 print(shopping_list) car_parts = {"engine", "wheels", "windows"} print(car_parts) # Can we add anything to a set? car_parts.add("seats") # Can we reomve an item? car_parts.discard("wheels") print(car_parts)
import matplotlib.pyplot as plt # pyplot is used to plot a chart from sklearn import datasets # datasets are used as a sample dataset, contains set that has number recognition data from sklearn import svm # for the sklearn Support Vector Machine digits = datasets.load_digits() # digits variable loaded with digit dataset print(digits.data) # features (actual data) print(digits.target) # label assigned to data clf = svm.SVC() # specify the classifier using defaults clf = svm.SVC(gamma=0.001, C=100) # specify the classifier # load all but the last 10 data points and use for training # X contains all of the "coordinates" and y is the "target" or "classification" # X has pixel data, y is the number that the pixels form X, y = digits.data[:-10], digits.target[:-10] clf.fit(X, y) # train print("Prediction: ", clf.predict(digits.data[-5].rehape(1,-1))) # predict what the 5th from last element is # visualization plt.imshow(digits.images[-5], cmap=plt.cm.gray_r, interpolation='nearest') plt.show() # adjusting gamma # larger values increase speed, lower accuracy # speed changes by factors of 10 clf = svm.SVC(gamma=0.01, C=100) clf.fit(X, y) # train print("Prediction: ", clf.predict(digits.data[-5].rehape(1,-1)) # predict what the 5th from last element is # less accurate clf = svm.SVC(gamma=0.0001, C=100) clf.fit(X, y) # train print("Prediction: ", clf.predict(digits.data[-5].reshape(1,-1)) # predict what the 5th from last element is
#Day 19 of 100 days of code #Removing Loops """ This method is also dependent on Floyd’s Cycle detection algorithm. Detect Loop using Floyd’s Cycle detection algorithm and get the pointer to a loop node. Count the number of nodes in loop. Let the count be k. Fix one pointer to the head and another to a kth node from the head. Move both pointers at the same pace, they will meet at loop starting node. Get a pointer to the last node of the loop and make next of it as NULL. """ class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self,data): node = Node(data) node.next = self.head self.head = node def printList(self): temp = self.head while(temp): print(temp.data) temp = temp.next print() def detectAndRemoveLoop(self): slowP = fastP = self.head while(slowP and fastP and fastP.next): slowP = slowP.next fastP = fastP.next.next if slowP ==fastP: self.removeLoop(slowP) return "Loop found and sorted" return "No loop found" def removeLoop(self,loopN): #Iniliazing pointers p1 = loopN p2 = loopN #finding lengeth of loop k = 1 while(p1.next != p2): p1 =p1.next k+=1 p1 = self.head #moving other pointer at k node p2 = self.head for i in range(k): p2 = p2.next #finding start of loop while(p2 != p1): p1 = p1.next p2 = p2.next #finding end of the loop while(p2.next !=p1): p2 = p2.next #removing loop p2.next = None def modifiedRemoveLoop(self): if self.head is None: return if self.head.next is None: return slow = self.head fast = self.head # Move slow and fast 1 and 2 steps respectively slow = slow.next fast = fast.next.next # Search for loop using slow and fast pointers while (fast is not None): if fast.next is None: break if slow == fast: break slow = slow.next fast = fast.next.next # if loop exists if slow == fast: slow = self.head while (slow.next != fast.next): slow = slow.next fast = fast.next # Sinc fast.next is the looping point fast.next = None # Remove loop #Testing list1 = LinkedList() list1.push(0) list1.push(2) list1.push(2) list1.push(4) list1.push(5) list1.push(6) list1.printList() #creating loop for test list1.head.next.next.next.next.next.next = list1.head.next.next list1.detectAndRemoveLoop() list1.printList() list1.head.next.next.next.next.next.next = list1.head.next.next list1.modifiedRemoveLoop() list1.printList()
#Day 21 of 100 days of code #Circular LinkedList """ Circular linked list is a linked list where all nodes are connected to form a circle. There is no NULL at the end. A circular linked list can be a singly circular linked list or doubly circular linked list. """ """ Advantages of Circular Linked Lists: 1) Any node can be a starting point. We can traverse the whole list by starting from any point. We just need to stop when the first visited node is visited again. 2) Useful for implementation of queue. Unlike this implementation, we don’t need to maintain two pointers for front and rear if we use circular linked list. We can maintain a pointer to the last inserted node and front can always be obtained as next of last. 3) Circular lists are useful in applications to repeatedly go around the list. For example, when multiple applications are running on a PC, it is common for the operating system to put the running applications on a list and then to cycle through them, giving each of them a slice of time to execute, and then making them wait while the CPU is given to another application. It is convenient for the operating system to use a circular list so that when it reaches the end of the list it can cycle around to the front ofthe list. 4) Circular Doubly Linked Lists are used for implementation of advanced data structures like Fibonacci Heap. """ class Node: def __init__(self,data): self.data = data self.next = None class circularLinkedList: def __init__(self): self.head = None def push(self,data): node = Node(data) temp = self.head node.next= self.head #we need to change the last node next and head if self.head is not None: while(temp.next != self.head): temp = temp.next temp.next = node else: node.next = node self.head = node def printList(self): temp = self.head if self.head is not None: while(1): print(temp.data) temp = temp.next #circular that's why we have to check for head if(temp ==self.head): break print() ##Spliting List in Two haves """ 1) Store the mid and last pointers of the circular linked list using tortoise and hare algorithm. 2) Make the second half circular. 3) Make the first half circular. 4) Set head (or start) pointers of the two linked lists. """ def splitList(cList,cList1,cList2): slowP = cList.head fastP = cList.head #Base cases if slowP is None: print("Can not process empty List.") return #Checking if there are only 2 node if cList.head.next == cList.head: print("There are only two nodes.") return while(fastP.next != cList.head and fastP.next.next != cList.head): fastP=fastP.next.next slowP = slowP.next #Finding the last node if(fastP.next.next == cList.head): fastP = fastP.next #Creating list 2 cList2.head = slowP.next fastP.next = cList2.head #Creating list1 cList1.head = cList.head slowP.next = cList.head #Testing cList = circularLinkedList() cList1 = circularLinkedList() cList2 = circularLinkedList() cList.push(1) cList.push(2) cList.push(3) cList.push(4) cList.printList() splitList(cList,cList1,cList2) cList1.printList() cList2.printList()
#DAY 10 OF 100 DAYS OF CODE #Dates import datetime """ A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects. """ x= datetime.datetime.now() print(x,"\n") print(x.year,"\n") #getting year print(x.strftime("%A"),"\n") #getting day #Creating Datetime y = datetime.datetime(2021,2,17) print(y,"\n") #strftime() """ The datetime object has a method for formatting date objects into readable strings. The method is called strftime(), and takes one parameter, format, to specify the format of the returned string %a Weekday, short version Wed %A Weekday, full version Wednesday %w Weekday as a number 0-6, 0 is Sunday 3 %d Day of month 01-31 31 %b Month name, short version Dec %B Month name, full version December %m Month as a number 01-12 12 %y Year, short version, without century 18 %Y Year, full version 2018 %H Hour 00-23 17 %I Hour 00-12 05 %p AM/PM PM %M Minute 00-59 41 %S Second 00-59 08 %f Microsecond 000000-999999 548513 %z UTC offset +0100 %Z Timezone CST %j Day number of year 001-366 365 %U Week number of year, Sunday as the first day of week, 00-53 52 %W Week number of year, Monday as the first day of week, 00-53 52 %c Local version of date and time Mon Dec 31 17:41:00 2018 %x Local version of date 12/31/18 %X Local version of time 17:41:00 %% A % character % %G ISO 8601 year 2018 %u ISO 8601 weekday (1-7) 1 %V ISO 8601 weeknumber (01-53) """ print(x.strftime("%B"),"\n") print(x.strftime("%a"),"\n") #Python Math #Built in math functions #min() and max() print(min(2,5,1),"\n") print(max(2,5,1),"\n") #abs() to get positive number print(abs(-5.23),"\n") #pow() to get power print(pow(6,2),"\n") #Math Module import math print(math.sqrt(49),"\n") #getting root print(math.ceil(1.4),"\n") #getting the ceiling number print(math.floor(1.4),"\n") #getting the floor number print(math.pi,"\n") #getting the constant pi #Pyhton JSON import json x = '{"name":"shasha","age":23}' #Json string print(type(x),"\n") y = json.loads(x) #parsing json stirng to pyhton dictionary print(y["age"],"\n") x = {"name":"shasha","age":23} print(type(x),"\n") #Dictionary to json y = json.dumps(x,indent =4) print(y,"\n") """ you can cahnge any data type to json using dumps() """ print(json.dumps(True),"\n") #Format Json x = { "name": "John", "age": 30, "married": True, "divorced": False, "children": ("Ann","Billy"), "pets": None, "cars": [ {"model": "BMW 230", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1} ] } print(json.dumps(x),"\n") #no format print(json.dumps(x,indent=4),"\n") #indent print(json.dumps(x,indent=4,separators=("."," = ")),"\n") #using separators print(json.dumps(x,indent=4,separators=("."," = "),sort_keys=True),"\n") #sorting
#DAY 14 0F 100 DAYS OF CODE #Linked List Continue class Node: def __init__(self, data=None): self.data =data self.next= None class LinkedList: #initalizing head def __init__(self): self.head = None #Inserting at Begining def push(self, newData): newNode = Node(newData) newNode.next = self.head self.head = newNode #Deleting Linked List at a given position """ If the node to be deleted is the root, simply delete it. To delete a middle node, we must have a pointer to the node previous to the node to be deleted. So if positions are not zero, we run a loop position-1 times and get a pointer to the previous node. """ def deleteNode(self,position): #checking if it's empty if self.head ==None: print("List is empty \n") return #storing head temp = self.head #Position is head if position ==0: self.head = temp.next temp =None return #Finding Position for i in range(position-1): temp = temp.next if temp or temp.next is None: print("List doesn't have that postion \n") return #Postion found next= temp.next.next #creating next temp.next =None #deleting node temp.next = next #unlicking the node #Print Linked List def printList(self): temp = self.head while(temp): print(temp.data) temp =temp.next print("") #Finding Length """ Pointer need to be used to get the length """ def listLength(self): temp = self.head count =0 while (temp): count+=1 temp =temp.next return count #Finding element def findElement(self,key): temp = self.head while(temp): if(temp.data==key): print("Element Found \n") return temp=temp.next print("Element not Found \n") return #Using above Codes list1 = LinkedList() list1.push(6) list1.push(3) list1.push(2) list1.push(1) list1.printList() #print List list1.deleteNode(0) #delting List list1.printList() #print List #Deleting Linked List """ In Python, automatic garbage collection happens, so deleting a linked list is easy. Just need to change head to null. """ list1.head = None list1.push(5) list1.push(6) list1.printList() #print List print(list1.listLength(),"\n") #getting length list1.findElement(6) list1.findElement(1)
#DAY 9 OF 100 DAYS OF CODE #Inheritance """ Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class. """ class Person: #Parent class def __init__(self,name,lName): self.name= name self.lName= lName def getPerson(self): print(self.name,self.lName,"\n") class Student(Person): #Child class inheriting parent pass s1 = Student("shasha","Jenson") s1.getPerson() class Teacher(Person): def __init__(self,name,lName): #Child can have it's own properties self.name=name self.lName = lName t1 = Teacher("Sha","Son") t1.getPerson() #super() """ By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent. """ class Footballer(Person): def __init__(self,name,lName): super().__init__(name,lName) def goal(self): #child can have it's own method print("Fantasic Goal by ",self.name,"\n") f1 = Footballer("Ronaldo","7") f1.getPerson() f1.goal() #Iterators """ An iterator is an object that contains a countable number of values. An iterator is an object that can be iterated upon, meaning that you can traverse through all the values. Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__(). Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from. """ myTuple = ("apple","banana","cherry") myIter = iter(myTuple) print(next(myIter),"\n") print(next(myIter),"\n") print(next(myIter),"\n") """ you can user any iterable to retun an iterator """ myStr = "apple" myIter1= iter(myStr) print(next(myIter1),"\n") print(next(myIter1),"\n") print(next(myIter1),"\n") #Looping through an Iterator for x in myStr: print(x) print("") """ The for loop actually creates an iterator object and executes the next() method for each loop. """ #Creating class as an Iterator class MyNumbers: def __iter__(self): self.a =1 return self def __next__(self): if self.a<=20: x= self.a self.a += 1 return x else: raise StopIteration #using to stop the iteration n1 = MyNumbers() myIter2 = iter(n1) for x in myIter2: print(x) print("\n") #Scope """ A variable is only available from inside the region it is created. This is called scope. """ #Local Scope """ A variable created inside a function belongs to the local scope of that function, and can only be used inside that function. """ def myFunc(): c = 100 return c print(myFunc(),"\n") #Global Scope """ A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local. """ x = 200 def myFunc1(): return x print(myFunc1(),"\n") def myFunc2(): global x #using global keyword to update global variable x=100 return "Changed global" print(myFunc2(),x,"\n") #Module """ Consider a module to be the same as a code library. A file containing a set of functions you want to include in your application. """ #Creating Module """ To create a module just save the code you want in a file with the file extension .py """ import Module1 as m1 #importing module as m1 ans = m1.myFunc(4)(4) #using module function print(ans,"\n") """ The module can contain functions, as already described, but also variables of all types. """ person = m1.person1 print(person,"\n") """ You can choose to import only parts from a module, by using the from keyword. """ from Module1 import person1 as p1 print(p1,"\n")
#Day 16 of 100 days of code #Linked List Continue class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None #Reverse In a group """ Reverse the first sub-list of size k. While reversing keep track of the next node and previous node. Let the pointer to the next node be next and pointer to the previous node be prev. head->next = reverse(next, k) ( Recursively call for rest of the list and link the two sub-lists ) Return prev ( prev becomes the new head of the list) """ def reverseGroup(self, head, k): if head == None: return None current = head next = None prev = None count = 0 # Reverse first k nodes of the linked list while(current is not None and count < k): next = current.next current.next = prev prev = current current = next count += 1 # Fixing next if next is not None: head.next = self.reverseGroup(next, k) # prev is new head of the input list return prev # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Print the LinkedList def printList(self): temp = self.head while(temp): print (temp.data) temp = temp.next #Reverse a linked list """ Initialize three pointers prev as NULL, curr as head and next as NULL. Iterate through the linked list. In loop, do following. Before changing next of current, store next node next = curr->next Now change next of current This is where actual reversing happens curr->next = prev Move prev and curr one step forward prev = curr curr = next """ def reverseList(self): prev = None temp = self.head while(temp): next = temp.next temp.next = prev prev = temp temp = next self.head = prev # Code to Run Above llist = LinkedList() llist.push(9) llist.push(8) llist.push(7) llist.push(6) llist.push(5) llist.push(1) print ("Given linked list") llist.printList() llist.head = llist.reverseGroup(llist.head, 4) print ("\nReversed Linked list") llist.printList()
class Dino: @staticmethod def exe1(): print("al carajo 1") def exe2(self): print("al carajo 2") class Car(Dino): wheels = 0 def __init__(self, color, x, func): self.color = color self.f = func Car.wheels = x while (True): print("yey") Dino.exe1() din = Dino() din.exe2() f = lambda x: x+1 #print(f(2)) print(Car.wheels) car = Car("red", 5, f) print(Car.wheels) print(car.color) print(car.f(50))
# -*- coding: utf-8 -*- """ @author: Michał Worsowicz """ import requests from http.server import HTTPServer, BaseHTTPRequestHandler from sys import argv from urllib.parse import urlparse import json class Server_Application(BaseHTTPRequestHandler): """ Class to represent a server application which lists repositories (with stars) and returns the total number of stars for a given user. Methods: do_GET() -> parses username from an URL, sends a GET request to GitHub API, extracts data needed and returns them in a form of JSON file. In case of status code different to 200 (OK), it sends response with a given code. """ def do_GET(self): url_query = urlparse(self.path).query query_components = dict(query.split("=") for query in url_query.split("&")) user = query_components["user"] request = requests.get('https://api.github.com/users/' + user + '/repos') if (request.status_code != 200): self.send_response(request.status_code) self.end_headers() return repos = request.json() stars_count = 0; info = {} info['repositories'] = [] for i,r in enumerate(repos): info['repositories'].append({ 'name': r['name'], 'stars_no' : r['stargazers_count'] }) stars_count += r['stargazers_count'] info['total_stars'] = stars_count self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(bytes(json.dumps(info), 'utf-8')) if __name__ == "__main__": """ Main function, establishes HTTPServer on a given host:port and handles requests Variables: host -> name of the host, localhost by default, port -> number of port, 80 by default Those values can be changed by passing argument in a form host:port """ host = 'localhost' port = 80 if len(argv) > 1: arg = argv[1].split(':') host = arg[0] port = int(arg[1]) print('Listening on http://' + str(host) + ':' + str(port) + '\n') server = HTTPServer((host, port), Server_Application) server.serve_forever()
from math import radians, cos, sin, asin, sqrt class Location: """ Object representation of latitude and longitude in Decimal Degrees format Decimal Degrees format: (+|-)degree where (+) indicates N and E, (-) indicates S and W degree° (N|S|E|W) Degrees and Decimal Minutes format: degree° minute′ (N|S|E|W) Degrees Minutes and Seconds format: degree° minute′ second″ (N|S|E|W) (+|-)degreeº (+|-)minute' (+|-)second'' (N|S|E|W) --> (+|-) depends on directions """ NOTATIONS = { 'degree': ['\u00b0', '\u00ba'], 'min': ['\u2032', "'", "`"], 'sec': ['\u2033', "''"], 'pos_dir': ['N', 'E'], 'neg_dir': ['S', 'W'] } def __init__(self, lat_str, long_str): assert lat_str != '' assert long_str != '' self.lat_deg, self.lat_min, self.lat_sec, self.lat_dir = x = \ self._extract_format(lat_str) # print(f'{x=}') # print(f'{self.lat_deg=}') self.long_deg, self.long_min, self.long_sec, self.long_dir = \ self._extract_format(long_str) def _extract_format(self, input_format: str): """ Return tuple of degree, minute, second and direction. If `input_format` doesn't have some particular value, that value will be replace with empty string. """ elements = input_format.split(' ') minute, second, direction = '', '', '' for ele in elements: last_char = ele[-1:] if last_char in self.NOTATIONS['degree']: degree = float(ele[:-1]) if last_char in self.NOTATIONS['min']: try: minute = float(ele[:-1]) except ValueError: pass if last_char in self.NOTATIONS['sec']: second = float(ele[:-1]) elif ele[-2:] in self.NOTATIONS['sec']: second = float(ele[:-2]) if last_char.upper() in self.NOTATIONS['pos_dir'] or last_char.upper() in self.NOTATIONS['neg_dir']: direction = last_char.upper() try: # print(f'{input_format=} {degree=} {minute=} {second=} {direction=}') return degree, minute, second, direction except UnboundLocalError: degree = float(input_format) return degree, 0, 0, '' def _convert_to_decimal_degrees(self, deg, min, sec, dir): try: deg = float(deg) except TypeError: deg = 0 # except ValueError: # print(f'{deg=}') # raise try: min_deg = min / 60 except TypeError: min_deg = 0 # except ValueError: # deg = 0 try: sec_deg = sec / 3600 except TypeError: sec_deg = 0 # except ValueError: # deg = 0 total_degree = sum([deg, min_deg, sec_deg]) if dir in self.NOTATIONS['neg_dir']: total_degree = abs(total_degree) * -1 return total_degree def get_lat_long(self, dd=True, ddm=False, dms=False): """ Return tuple of latitude and longitude in the format specified by key. """ if dd: # print(f'{self.lat_deg=}') lat = self._convert_to_decimal_degrees( self.lat_deg, self.lat_min, self.lat_sec, self.lat_dir ) long = self._convert_to_decimal_degrees( self.long_deg, self.long_min, self.long_sec, self.long_dir ) return round(lat, 6), round(long, 6) def __str__(self): lat = [self.lat_deg, self.lat_min, self.lat_sec, self.lat_dir] lat = [str(x) for x in lat if x != ""] lat_str = " ".join(lat) long = [self.long_deg, self.long_min, self.long_sec, self.long_dir] long = [str(x) for x in long if x != ""] long_str = " ".join(long) return f'{lat_str} / {long_str}' def calculate_distance(self, other): # get lat, long in decimal degree format lat1, lon1 = self.get_lat_long(dd=True) lat2, lon2 = other.get_lat_long(dd=True) return calculate_distance(lat1, lon1, lat2, lon2) def calculate_distance(lat1, lon1, lat2, lon2): # The math module contains a function named # radians which converts from degrees to radians. lon1 = radians(lon1) lon2 = radians(lon2) lat1 = radians(lat1) lat2 = radians(lat2) # Haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2 c = 2 * asin(sqrt(a)) # Radius of earth in kilometers. Use 3956 for miles r = 6371 # calculate the result return c * r if __name__ == '__main__': # check at: https://www.pgc.umn.edu/apps/convert/ # test cases l2 = Location("-14º -15' -59'' S", "-170º -40' -59'' W") l3 = Location("40° 26.767′ N", "40° 26.767′ W") l4 = Location("40.446° N", "40.446° W") l5 = Location("40° 26′ 46″ N", "40° 26′ 46″ E") print(l2) print(l2.get_lat_long()) print("--------------------") print(l4) print(l4.get_lat_long()) print("--------------------") print(f"distance between l2 and l4 = {l2.calculate_distance(l3)}")
numero = int(input("Digite um número : ")) sucessor = numero + 1 antecessor = numero - 1 print("Sucessor do número {} é {} ".format(numero, sucessor)) print("Antecessor do número {} é {} ".format(numero, antecessor))
km = float(input("Quantos km você rodou com o carro alugado ? ")) dias = float(input("Por quantos dias você alugou o carro ? ")) km2 = ( km * 0.15 ) dias2 = dias * 60 total = km2 + dias2 print(" Você deve pagar R${:.2f} pelo dias que alugou, e R${:.2f} pelos kilometros rodados com o carro ! \n O total a pagar é {:.2f} ".format(dias2, km2, total))
n1 = int(input("Digite um número para ver sua tabuada : ")) n11 = n1 * 1 n12 = n1 * 2 n13 = n1 * 3 n14 = n1 * 4 n15 = n1 * 5 n16 = n1 * 6 n17 = n1 * 7 n18 = n1 * 8 n19 = n1 * 9 n110 = n1 * 10 print('-' * 12) print("{} x 1 = {:2} ".format(n1, n11)) print("{} x 2 = {:2} ".format(n1, n12)) print("{} x 3 = {:2} ".format(n1, n13)) print("{} x 4 = {:2} ".format(n1, n14)) print("{} x 5 = {:2} ".format(n1, n15)) print("{} x 6 = {:2} ".format(n1, n16)) print("{} x 7 = {:2} ".format(n1, n17)) print("{} x 8 = {:2} ".format(n1, n18)) print("{} x 9 = {:2} ".format(n1, n19)) print("{} x 10 = {} ".format(n1, n110)) print('-' * 12)
# GENERATE Bilangan Prima # Bil Prima : Hanya Bisa di bagi 1 dan dirinya sendiri, Contoh : 5 hanya bisa dibagi 1 dan 5 # Bukan Prima : Contoh 6 : bisa dibagi 1 ,2 ,3, 6 # Definisikan Fungsi sederhana untuk cek apakah bilangan tersebut prima contoh : is_prime(4) def is_prime(num): for i in range(2, num): if num % i == 0: return False return True def get_prime(max_prime_num): list_bil_prima = [] for num in range(2, max_prime_num): if is_prime(num): list_bil_prima.append(num) return list_bil_prima max_input = int(input("Cari Bilangan Prima Sampai : ")) print("LIST ALL PRIME NUM: ", get_prime(max_input))
# Umur 0 - 5 -> Terlalu kecil untuk Sekolah # Umur 6 - 12 -> Pergi ke SD print => SD Kelas 1 - SD Kelas 6 # Umur 13 - 15 -> Pergi ke SMP print => SMP Kelas 1 - SMP Kelas 3 # Umur 16 - 18 -> Masuk SMA # Jika Mampu selesaikan tidak kurang dari 14 baris umur = eval(input("Masukkan Umur : ")) if umur <= 5: print("Terlalu kecil untuk Sekolah") elif 6 <= umur <= 12: kelas = umur - 5 print(f'SD Kelas {kelas}') elif 13 <= umur <= 15: kelas = umur - 12 print(f'SMP Kelas {kelas}') elif 16<= umur <= 19: print("Masuk SMA") else: print("Masuk Kuliah")
import math import random # Generate random list with value between 1 - 9 # Create initial List # use forloop # use list append and random module to the initial list # Print Result
# for x in range(1,1001): # if x%2 == 1: # print x # for x in range(5,1000001): # if x%5 == 0: # print x # sum = 0 # for count in a: # sum += count # print sum # print sum/len(a) def counting(): for x in range(1,2001): if x%2 == 1: y = "odd" else: y = "even" print "number is {}. This is an {} number.".format(x, y) def multiply(list,z): new = [] for x in list: new.append(x * z) return new import random chance = random.randint(0,1) def coin_toss(): head = 0 tail = 0 for x in range (1,5001): chance = random.randint(0,1) if chance == 0: head += 1 print "Attempt #{}: throwing a coin... It's a head! ... got {} head(s) so far and {} tails(s) so far".format(x,head,tail) else: tail += 1 print "Attempt #{}: throwing a coin... It's a Tail! ... got {} head(s) so far and {} tails(s) so far".format(x,head,tail) coin_toss() y = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"] def draw_stars(array): for idx, item in enumerate(array): print idx # draw_stars(y) users = { 'Students': [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ], 'Instructors': [ {'first_name' : 'Michael', 'last_name' : 'Choi'}, {'first_name' : 'Martin', 'last_name' : 'Puryear'} ] } def displayStudents(users): y= 0 for x in users['Students']: length = len(x['first_name']+x['last_name']) print "{} - {} {} - {}".format(y, x['first_name'], x['last_name'], length) y += 1 print 'Instructors' y = 1 for x in users['Instructors']: length = len(x['first_name']+x['last_name']) print "{} - {} {} - {}".format(y, x['first_name'], x['last_name'], length) y += 1 for key, value in users.items(): print key counter = 1 for i in range(len(value)): First = value[i]['first_name'] Last = value[i]['last_name'] length = len(First+Last) print '{} - {} {} - {}'.format(counter, First.upper(), Last.upper(), length) counter += 1 '''BUBBLE SORT''' def bubble(x): for i in range(len(x)-1): for j in range(len(x)-i-1): if x[j]>x[j+1]: (x[j],x[j+1]) = (x[j+1],x[j]) '''SELECTION SORT''' def selection(x): for i in range(len(x)): min = i for j in range(i,len(x)): if x[j] < x[min]: min = j (x[i],x[min]) = (x[min],x[i]) '''INSERTION SORT''' def insertion(x): for i in range(1,len(x)): swap = i for j in range(i-1,-1,-1): if x[swap] < x[j]: (x[swap],x[j]) = (x[j],x[swap]) swap -= 1 print x '''Threes and Fives''' def threesFives(): for x in range (100, 4000001): if x%3==0 and x%5==0: continue elif x%3==0: print x elif x%5==0: print x '''Generate Coin Change''' import math def generatechange(x): coins = ['quarters', 'dimes', 'nickels', 'pennies'] change = {'quarters': 25, 'dimes': 10, 'nickels': 5, 'pennies': 1} remainder = x for x in coins: print x value = change[x] number = math.floor(remainder/value) if number >= 1: change[x] = number remainder = remainder - (number * value) else: change[x] = 0 print "{} coins can be represented by:".format(x) for x in coins: print "{}: {}".format(x, change[x]) def messyMath(num): sum = 0 count = 0 for x in range (1, num+1): count +=1 if count == (float(num)/3): return -1 if count % 3 == 0: continue elif count % 7 == 0: sum += x sum += x return sum def bars(): for x in range(1,13): print x print 'chick' print 'boom' print 'chick' def Fibonacci(x): if x == 0: return 0 elif x == 1: return 1 else: return Fibonacci(x-1) + Fibonacci(x-2) def sumtoOne(num): if len(str(num)) ==1: return num sum = 0 for x in range (len(str(num))): number = int(str(num)[x]) sum += number return sumtoOne(sum) def isprime(num): for x in range(2, int(math.sqrt(num))+1): if num%x==0: return False return True def sweatshirtPricing(num): total = num * 20 discount = 0 if num == 2: discount = .09 elif num == 3: discount = .19 elif num >= 4: discount = .35 return math.ceil(total*(1-discount)) def extractDigit(num, digit): string = str(num) length = len(string) if digit >= length: return 1 return string[length-digit-1] def sigfig(num): num = abs(num) while num < 1: num = num*10 while num > 10: num = num/10 return int(math.floor(num)) '''gaming Fundamentals''' import random def rollOne(): return random.randint(1,6) def playfives(num): x = num while x>0: number = rollOne() if number == 5: print "that's good luck" x -= 1 def playStats(): x = 8 min = 6 max = 1 while x>0: number = rollOne() if number < min: min = number if number > max: max = number x -= 1 return min, max def playStats2(): x = 8 sum = 0 min = 6 max = 1 while x>0: number = rollOne() if number < min: min = number if number > max: max = number x -= 1 sum += number return min, max, sum def playStats3(num): x = num sum = 0 min = 6 max = 1 while x>0: number = rollOne() if number < min: min = number if number > max: max = number x -= 1 sum += number return min, max, sum def playStats4(num): x = num sum = 0 min = 6 max = 1 while x>0: number = rollOne() if number < min: min = number if number > max: max = number x -= 1 sum += number return min, max, sum def playStats20(): sum = 0 min = 20 max = 1 count = 0 prev = 0 number = random.randint(1,20) while prev != number: count += 1 if number < min: min = number if number > max: max = number prev = number number = random.randint(1,20) sum += number return min, max, sum, sum/count '''ARRAYS''' array = [1,2,3,4,5,6,6,7,8,9,10] def pushFront(arr, num): arr.append(arr[len(arr)-1]) for x in range(len(arr)-2,-1,-1): arr[x+1] = arr[x] arr[0] = num return arr def popFront(arr): for x in range (0, len(arr)-1): arr[x]=arr[x+1] arr.pop() return arr def insertAt(arr, idx, num): arr.append(arr[len(arr)-1]) for x in range(len(arr)-2,idx-1,-1): arr[x+1] = arr[x] arr[idx] = num return arr def removeAt(arr, idx): if idx > len(arr)-1: return 'idx too large' for x in range (idx, len(arr)-1): arr[x]=arr[x+1] arr.pop() return arr def swapPairs(arr): length = len(arr) if len(arr) % 2 != 0: length -= 1 for x in range (0, length, +2): (arr[x], arr[x+1]) = (arr[x+1], arr[x]) return arr def removedupes(arr): value = arr[len(arr)-1] for x in range(len(arr)-2, -1, -1): if arr[x] == value: removeAt(arr, x) value = arr[x] return arr array = [1,2,3,4,5,6,6,7,8,9,10] def mintoFront(arr): min = 0 for x in range (1,len(arr)): if arr[x] < arr[min]: min = x pushFront(arr, arr[min]) removeAt(arr, min+1) return arr def reverse(arr): for x in range (0, len(arr)/2): temp = arr[x] arr[x] = arr[len(arr)-1-x] arr[len(arr)-1-x] = temp return arr def rotate(arr, shift): x = shift%len(arr) while x >0: y = arr[len(arr)-1] pushFront(arr, y) arr.pop() x -= 1 return arr def filter(arr, min, max): for x in range(len(arr)-1, -1, -1): if arr[x]< max and arr[x]>min: removeAt(arr,x) print arr return arr def concat(arr, arr2): newarr = [] for x in range(0, len(arr)): newarr.append(arr[x]) for x in range(0, len(arr2)): newarr.append(arr2[x]) return newarr array2 = [-2,0,2,5,-7,3,-2,4,9] def skyline(arr): newarr = [] min = 0 for x in range(0, len(arr)): if arr[x]>min: newarr.append(arr[x]) min = arr[x] return newarr def removeNegs(arr): for x in range(len(arr)-1, -1, -1): if arr[x]<0: removeAt(arr, x) return arr def secondtolast(arr): if len(arr)<2: return null return arr[len(arr)-2] def secondLargest(arr): if len(arr)<2: return null max = arr[0] max2 = arr[0] for x in range(1, len(arr)): if arr[x]>max: max = arr[x] for x in range(1, len(arr)): if arr[x]>max2 and arr[x]<max: max2 = arr[x] return max2 def findLast(arr, n): if len(arr) < n: return null return arr[len(arr)-n] array2 = [-2,0,2,5,-7,3,-2,4,9] def NLargest(arr, n): if len(arr)<2: return null max = arr[0] for x in range(1, len(arr)): if arr[x]>max: max = arr[x] for j in range(0,n-1): max2 = arr[0] for x in range(1, len(arr)): if arr[x]>max2 and arr[x]<max: max2 = arr[x] print max, 'newmax' max = max2 return max def isCreditCardValid(arr): last = arr.pop() sum = 0 for x in range(len(arr)-1, -1, -2): arr[x] = arr[x] * 2 if arr[x] > 9: arr[x] = arr[x] - 9 for x in range(0, len(arr)): sum += arr[x] sum += last if sum % 10 == 0: return True else: return False def shuffle(arr): for x in range(1,100): a = random.randint(0,len(arr)-1) b = random.randint(0,len(arr)-1) (arr[a], arr[b]) = (arr[b], arr[a]) return arr def removeRange(arr, n, m): for x in range (m, n-1, -1): removeAt(arr, x) return arr def intermedSums(arr): sum = 0 for x in range(0, len(arr)): sum += arr[x] if x>0 and x%10==0: sum -= arr[x] insertAt(arr, x, sum) sum = 0 if x%10==0: return arr else: arr.append(sum) return arr array = ['kim','george',7,10] def doubles(arr): for x in range(0, len(arr)*2, +2): insertAt(arr, x+1, arr[x]) return arr def zipit(arr, arr2): newarr = [] if len(arr) > len(arr2): long = len(arr) else: long = len(arr2) for x in range(0, long): try: newarr.append(arr[x]) except: pass try: newarr.append(arr2[x]) except: pass return newarr '''CHAPTER 4 - STRINGS''' def removeblanks(str): newstr = '' letter = str.split(' ') for x in letter: newstr += x return newstr def getDigits(str): num = '' dict = { '1':'', '2':'', '3':'', '4':'', '5':'', '6':'', '7':'', '8':'', '9':'', '0':'', } for x in str: if x in dict.keys(): num += x return int(num) def acronyms(str): newstr = '' if str[0] != ' ': newstr += str[0].upper() for x in range(1,len(str)): if str[x] != ' ' and str[x-1] == ' ': newstr += str[x].upper() return newstr def countNonSpace(str): count = 0 for x in str: if x != ' ': count += 1 return count def removeShortString(str, length): words = str.split(' ') print words for x in range(len(words)-1, -1, -1): if len(words[x]) < length: removeAt(words, x) return words def reversestring(str): newstr = '' for x in range(len(str)-1, -1, -1): newstr += str[x] return newstr array2 = ['Nope!','Its','Kris','starting','with','K!',('instead','of','chris','with','c'),'.'] def removeEven(arr): for x in range(len(arr)-1,-1,-1): if len(arr[x]) > 1: removeEven(arr[x]) elif len(arr[x]) % 2 == 0: removeAt(arr,x) return arr def ParesValid(str): count = 0 for x in (str): if x == '(': count += 1 elif x == ')': count -= 1 if count == -1: return False if count != 0: return False return True def BracesValid(str): bracesStack = [] for x in (str): if x == '(' or x == '{' or x == '[': bracesStack.append(x) elif x == ')' or x == '}' or x == ']': if x == ')' and bracesStack[len(bracesStack)-1] == '(': bracesStack.pop() elif x == '}' and bracesStack[len(bracesStack)-1] == '{': bracesStack.pop() elif x == ']' and bracesStack[len(bracesStack)-1] == '[': bracesStack.pop() else: return False if len(bracesStack) == 0: return True else: return False def isPalendrome(str): for x in range(0,len(str)): if str[x] != str[len(str)-1-x]: return False return True alphabet = 'abcdefghijklmnopqrstuvwxyz' def createAlphHash(alphabet): alphDict = {} for x in alphabet: alphDict[x]='' return alphDict 8925 def isPalenIgnoreSpace(str): alphDict = createAlphHash(alphabet) str = str.lower() str = str.split() str = ''.join(str) y = len(str)-1 for x in range(0,len(str)/2): while str[y] not in alphDict: y -= 1 if x not in alphDict: pass if str[x] != str[y]: return False y -= 1 return True def findComplement(num): """ :type num: int :rtype: int """ num = str(bin(num)) newnum = '' for x in range(2, len(num)): if num[x] == '1': newnum += '0' else: newnum += '1' return int(newnum, base=2) [1,2,2,3,3,4,7,8] def findDisappearedNumbers(nums): """ :type nums: List[int] :rtype: List[int] """ dict = {} missing = [] for x in range(1,len(nums)+1): dict[x]=False for y in (nums): if y in dict.keys(): dict[y]=True for key,value in dict.iteritems(): if not value: missing.append(key) return missing # print findDisappearedNumbers([1,2,2,3,3,4,7,8]) # INEFFICIENT def findDisappearedNumbers(nums): """ :type nums: List[int] :rtype: List[int] """ # For each number i in nums, # we mark the number that i points as negative. # Then we filter the list, get all the indexes # who points to a positive number for i in range(len(nums)): print i print nums[i] index = abs(nums[i]) - 1 nums[index] = - abs(nums[index]) print nums[index], 'nums' print index, 'index' print nums return [i + 1 for i in range(len(nums)) if nums[i] > 0] # print findDisappearedNumbers([4,3,2,7,8,2,3,1]) # INEFFICIENT def singleNumber(nums): dict = {} for x in range(len(nums)): if nums[x] in dict.keys(): dict[nums[x]]=True else: dict[nums[x]]=False for key,value in dict.iteritems(): if not value: return dict def singleNumber(nums): dict = {} for x in range(len(nums)): if nums[x] in dict.keys(): del dict[nums[x]] else: dict[nums[x]]=False for key,value in dict.iteritems(): return key # print singleNumber([1]) import timeit start = timeit.default_timer() stop = timeit.default_timer() def constructRectangle(area): x = math.ceil(math.sqrt(area)) while area % x !=0: x+=1 return [int(x),int(area/x)] def singleNumber2(nums): res = 0 for num in nums: res ^= num print res return res nums1 = [1,25,3,6,2,5,6,34,63] nums2 = [1,252,5,6,63,724,2,9,5] nums1 = set(nums1) nums2 = set(nums2) print nums1&nums2
# Given a positive integer num, write a function which returns True if num is a perfect square else False. class Solution(object): def isPerfectSquare(self, num): """ :type num: int :rtype: bool """ sqrt = 0 x = 0 while sqrt < num: x += 1 sqrt = x ** 2 if sqrt == num: return True return False
def bubblesort(array): swaps = True ### Short Bubble: breaks if no swaps for i in range(len(array)): swaps = False for x in range(len(array)-i-1): if array[x+1]<array[x]: swaps = True temp = array[x+1] array[x+1] = array[x] array[x] = temp return array
# You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. class Solution(object): def islandPerimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ sum = 0 for x in range (0, len(grid)): print x print grid[x] for i in range (0, len(grid[x])): if grid[x][i] == 1: sum += 4 if x != 0: #Don't check top if grid[x-1][i] == 1: sum -= 1 if x != len(grid)-1: #Don't check bottom if grid[x+1][i] == 1: sum -= 1 if i != 0: #Don't check left if grid[x][i-1] == 1: sum -= 1 if i != len(grid[x])-1: #don't check right if grid[x][i+1] == 1: sum -= 1 return sum
def main(): ''' Objective : To display percentage of marks scored by the student Input Parameters: None Return Value : None ''' totalMarks = 0 nSubjects = 0 while True: marks = input('Marks for subject ' + str(nSubjects + 1) + ':') if marks == '': #End of input break marks = float(marks) if marks < 0 or marks > 100: print('INVALID MARKS !!') continue # Marks to be entered again nSubjects = nSubjects + 1 totalMarks+= marks percentage = totalMarks / nSubjects print('Total marks:', int(totalMarks)) print('Number of subjects:', nSubjects) print('Percentage:', round(percentage,2)) if __name__ == '__main__': main()
a=3 def f(): def g(): global a a=4 print('inside g, global a=',a) g() a=5 print('inside f, local a=',a) f() print('outside of all functions definitions a=',a)
nums = list(range(1, 5)) doubled = [ y * 2 for y in nums ] print(nums) print(doubled) # need a square root function from math import sqrt # generate numbers for "o" (opposite of a right triangle) in range 1-13 inclusive # for each of those, generate values for "a" (adjacent side) in range 1 - one-less-than opposite side # calculate the hypotenuse h and store it using the "walrus" assignment operator # the colon-equals / walrus / assignment operator forms an expression that has the value that's assigned # so we can continue to compute using it # then test to see if that hypotenuse value is a perfect integer, and if (and only if) it is # then we put the resulting triplet of o, a, and h into the resulting list # result a small set of perfect integer sided right-angled triangles triangles = [ (o, a, h) for o in range (1, 14) for a in range(1, o) if int(h := sqrt(o * o + a * a)) == h ] print(triangles)
def mypower(x,n): if n==0: return 1 temp = mypower(x,n/2) if n%2==1: return temp*temp*x else: return temp*temp def power(x,n): if n==0: return 1 neg = False if x<0: neg = True x *= float(-1) if n<0: x = float(1)/x n *= (-1) result = mypower(x,n) if neg and n%2==1: return (-1)*result return result def main(): print "Base : %s , Exponent : %s ::::: Result : %s" %(2, 3, power(2, 3)) print "Base : %s , Exponent : %s ::::: Result : %s" % (2, -3, power(2, -3)) print "Base : %s , Exponent : %s ::::: Result : %s" % (-2, 3, power(-2, 3)) print "Base : %s , Exponent : %s ::::: Result : %s" % (-2, -3, power(-2, -3)) if __name__=='__main__': main()
name = input('Qual seu nome? ').strip() name_list = name.split() print(name_list[0]) print(name_list[len(name_list)-1])
print('=====Desafio 2=====') month = input('Qual seu mês de nascimento ?') day = input('Qual seu dia de nascimento ?') yaer = input('Qual seu ano de nascimento ?') print('Tu nasceu em', day, 'de', month,'de', yaer)
# =========Desafio 20========== # Embaralhando nomes import random name1 = str(input("Infome o primeiro aluno: ")) name2 = str(input("Infome o segundo aluno: ")) name3 = str(input("Infome o terceiro aluno: ")) name4 = str(input("Infome o quarto aluno: ")) names = [name1,name2,name3,name4] sort = random.shuffle(names) print("A ordem de saida é: ") print(names)