text
stringlengths
37
1.41M
# list数据类型 # 类比JavaScript中的数组,实现增删改查功能 car = [] print(car) # 长度为0的list car.append(1) # list增加元素 car.append(2) print(car) seat = ['red', 'blue'] car.append(seat) car.append(3) car.append(4) ele1 = car.pop() # 删除最后一个元素 print(ele1) car.append(4) car.pop(3) # 删除指定位置的元素 print(car) car.insert(0, 'start') print(car) print(len(car)) car[1] = 9 print(car) # 改变具体位置的值 print(car[3][1]) # 取出list中list的值 list可以当做多维数组使用 # 使用 tuple tu = (1, 2, 3) print(tu) print(tu[0]) tu1 = (1) # 这相当于定义了 tu1 = liaoxuefeng-tutorial 而不是一个tuple print(tu1) tu2 = (1,) # 规定一个元素的tuple需要添加一个逗号 print(tu2) # 输出单个元素tuple也会加上一个逗号 # 第二次学习 classmates = ['张三', '李四', '王五'] # 这是list数据类型 # 末未添加 classmates.append('李狗蛋') print(classmates) # 尾部删除 classmates.pop() print(classmates) # 删除指定位置的元素 classmates.pop(0) print(classmates) # 在指定位置添加元素 classmates.insert(0, '张三') print(classmates) # 修改指定位置的元素 classmates[0] = '李狗蛋' print(classmates) # 打印指定位置的元素 print(classmates[-1]) print(classmates[0]) # 元组 atom = (1, 2, 3) print(atom) # 无法修改元素 # 一个元素的元组 atom1 = (1, ) print(atom1) # 计算长度 print(len(classmates))
# 使用函数filter ## [1, 3, 5] print(list(filter(lambda x: x % 2 == 1, [1, 2, 3, 4, 5, 6]))) ## ['A', 'dream'] print(list(filter(lambda s: s and s.strip(), ['A', '', 'dream']))) ## 打印一定范围的素数 def primes(): # 构造初始序列 def init_list(): n = 1 while True: n = n + 2 yield n def _not_divisible(n): return lambda x: x % n != 0 def not_divisible(n): def divisible(x): return x % n != 0 return divisible yield 2 l = init_list() while True: prime = next(l) yield prime # 这里不直接使用 lambda x: x % prime != 0 # 因为要绑定prime l = filter(_not_divisible(prime), l) my_primes = primes() for p in my_primes: if p < 100: print(p) else: break print(lambda x: x % n == 0) from functools import reduce def is_palindrome(n): l = [] init_n = n while n > 9: k = n % 10 l.append(k) n = n // 10 l.append(n) reversed_n = reduce(lambda x, y: x * 10 + y, l) if init_n == reversed_n: return True else: return False print(is_palindrome(808)) output = filter(is_palindrome, range(1, 1000)) print(list(output)) # 使用切片来做一个 def _is_palindrome(num): s = str(num) if s[::] == s[::-1]: return True else: return False # 改进一下,选择使用三目运算符 def _is_palindrome2(num): s = str(num) return True if s[::] == s[::-1] else False output = filter(_is_palindrome2, range(1, 1000)) print(list(output))
# dict score = {'dream': 100, 'apple': 99} print(score['dream']) # 向字典中添加数据 score['happy'] = 98 print(score) # 检查一个key是否在字典中 print('dream' in score) # 使用in操作符 print('Dream' in score) print(score.get('dream')) print(score.get('Dream')) # None print(score.get('Dream', -1)) # 不存在就返回给定的值 # 删除一条数据 # 使用pop删除数据 返回的结果就是删除的key相应的value值 print(score.pop('apple')) print(score) # set s = {1, 2, 3} # 使用set字面量 print(s) s.add(3) # 加入相同的元素不会起作用 print(s) s.add(4) print(s) print(s.remove(4)) # 删除一个元素 返回值是None print(s) # 求集合的交集与并集 s1 = {1, 2, 3} s2 = {3, 4, 5} print(s1 & s2) # 交集 print(s1 | s2) # 并集 s.add((1, 2, 3)) # 可以添加元组 print(s) # s.add((1, [official-tutorial, 3])) # 不可以添加tuple里面包含list就不是不可变的对象了 print(s) # 第二次学习 # dict classmates = { 'zhangsan': '张三', 'lisi': '李四', 'wangwu': '王五', } # 查找 print(classmates['zhangsan']) # 替换 classmates['zhangsan'] = '三张' print(classmates) # 删除某个key classmates.pop('zhangsan') print(classmates) # 哪一个键是否存在 print('zhangsan' in classmates) print(classmates.get('zhangsan')) print(classmates.get('zhangsan', -1)) # 添加键值 classmates['ligoudan'] = '李狗蛋' print(classmates) # set arr = {1, 2, 3} # 不重合的元素 print(arr) arr.add(3) # 重合的元素 print(arr) arr.add(4) print(arr) arr1 = {3, 4, 5} print(arr1 & arr) # 求两个集合的交集 print(arr1 | arr) # 求两个集合的并集 # arr1.add([1, official-tutorial, 3]) 不可以添加list元素,因为list元素是可变的 arr1.remove(5) # 删除一个元素 print(arr1) arr1.add((1, 2, 3)) print(arr1) # arr1.add((liaoxuefeng-tutorial, official-tutorial, [liaoxuefeng-tutorial, official-tutorial])) # 元组里面包含可变的list所以也是不可以的
# IU - International University of Applied Science # Machine Learning - Unsupervised Machine Learning # Course Code: DLBDSMLUSL01 # Sample generation #%% import libraries import numpy as np import matplotlib.pyplot as plt from sklearn import mixture #%% generate sample data X1 = 4 + np.random.rand(50,2) X2 = 5 + np.random.rand(50,2) X3 = 6 + np.random.rand(50,2) Z = np.concatenate((X1,X2,X3)) #%% Build and fit a GMM model gmm = mixture.GaussianMixture(n_components=3) gmm.fit(Z) #%% generate new samples newdata = gmm.sample(150) #%% extract the feature values, i.e. coordinates vals = newdata[0] #%% extract the labels labs = newdata[1] #%% plot the generated samples plt.scatter(x=vals[:,0], y=vals[:,1], c=labs) plt.show()
# IU - International University of Applied Science # Machine Learning - Unsupervised Machine Learning # Course Code: DLBDSMLUSL01 # Feature Engineering #%% import libraries import numpy as np import pandas as pd import datetime #%% create sample data Student_R = { \ 'Student_ID':['S1', 'S2', 'S3'], \ 'Birth_date': [datetime.date(1996,7,14), \ datetime.date(1997,8,22), \ datetime.date(1998,5,11)]} Student_R = pd.DataFrame(Student_R, \ columns = ['Student_ID','Birth_date']) Courses = { \ 'Student_ID':['S1', 'S2', 'S3', 'S1', 'S2', 'S3'], \ 'Grades':[18, 11, 12, 15, 19, 10]} Courses = pd.DataFrame (Courses, \ columns = ['Student_ID', 'Grades']) #%% extracting the year from the birth date Student_R['year'] = pd.DatetimeIndex(Student_R['Birth_date']).year print(Student_R.head()) # console output: # Student_ID Birth_date year # 0 S1 1996-07-14 1996 # 1 S2 1997-08-22 1997 # 2 S3 1998-05-11 1998 #%% creation of features by aggregation of grouped values goper = Courses.groupby('Student_ID')['Grades'].\ agg(['mean','max','min']) # rename columns goper.columns = ['mean_grade','max_grade','min_grade'] print(goper.head()) # console output: # mean_grade max_grade min_grade # Student_ID # S1 16.5 18 15 # S2 15.0 19 11 # S3 11.0 12 10 #%% merge with the Student_R dataframe R = Student_R.merge(goper, left_on = 'Student_ID', \ right_index=True, how = 'left'). \ head() # show the dataframe R # Student_ID Birth_date year mean_grade max_grade min_grade # 0 S1 1996-07-14 1996 16.5 18 15 # 1 S2 1997-08-22 1997 15.0 19 11 # 2 S3 1998-05-11 1998 11.0 12 10
# IU - International University of Applied Science # Machine Learning - Unsupervised Machine Learning # Course Code: DLBDSMLUSL01 # Feature Importance # Permutation feature importance #%% load libraries import pandas as pd from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.inspection import permutation_importance from sklearn.neighbors import KNeighborsClassifier #%% load sample data iris = load_iris() #%% split the data into training and testing X_train, X_test, y_train,y_test = train_test_split(\ iris.data, iris.target) #%% create and fit a KNN model model = KNeighborsClassifier() model.fit(X_train, y_train) #%% assess feature importance by permutation feat_imp = permutation_importance(model, \ X_test, y_test, n_repeats=10, \ scoring='accuracy') #%% display calculated feature importances pd.DataFrame({'features': iris.feature_names, \ 'importances_mean': feat_imp['importances_mean'], \ 'importances_std': feat_imp['importances_std']}) # console output: # features importances_mean importances_std # 0 sepal length (cm) -0.034211 0.016850 # 1 sepal width (cm) -0.021053 0.015789 # 2 petal length (cm) 0.544737 0.110432 # 3 petal width (cm) 0.107895 0.049162
csv_lines = sc.textFile("data/example.csv") from pyspark.sql import Row # CSV를 pyspark.sql.Row로 변환 def csv_to_row(line): parts = line.split(",") row = Row( name=parts[0], company=parts[1], title=parts[2] ) return row # RDD에서 행을 얻기 위해 이 함수 적용 rows = csv_lines.map(csv_to_row) # pyspark.sql.DataFrame으로 변환 rows_df = rows.toDF() # Spark SQL을 위해 DataFrame을 등록 rows_df.registerTempTable("executives") # SparkSession을 사용해서 SQL로 새 DataFrame 생성 job_counts = spark.sql(""" SELECT name, COUNT(*) AS total FROM executives GROUP BY name """) job_counts.show() # RDD로 돌아가기 job_counts.rdd.collect()
""" NOTE: This example has been presented at the following course: https://www.udemy.com/course/aprenda-a-programar-um-bot-do-whatsapp """ # Importar pacotes necessarios from time import sleep from whatsapp_api import WhatsApp # Inicializar o whatsapp wp = WhatsApp() # Esperar que enter seja pressionado input("Pressione enter apos escanear o QR Code") # Lista de nomes ou nomeros de telefone a serem pesquisados # IMPORTANTE: O nome deve ser nao ambiguo pois ele retornara o primeiro resultado nomes_palavras_chaves = ['Luciano Bot', 'Aline Bot', 'Beatriz Bot', 'Joao Bot', 'Maria Bot', 'Pedro Bot'] # Lista dos nomes que vou me referir na mensagem # primeiros_nomes = [n.split(' ')[0] for n in nomes_palavras_chaves] primeiros_nomes = ['Luciano', 'Aline', 'Beatriz', 'Joao', 'Maria', 'Pedro'] lista_produtos = ['acucar', 'feijao', 'bicicleta', 'cenoura', 'abacate', 'beringela'] # Loop para mandar mensagens para os clientes for primeiro_nome, nome_pesquisar, produto \ in zip(primeiros_nomes, nomes_palavras_chaves, lista_produtos): # Pesquisar pelo contato e esperar um pouco wp.search_contact(nome_pesquisar) sleep(2) # Mensagem a ser enviada mensagem = f"Olá {primeiro_nome}! Obrigado por comprar o produto {produto}!" # Enviar mensagem wp.send_message(mensagem) # Esperar 10 segundos e fechar sleep(10) wp.driver.close()
class Plane(): def __init__(self, planeNumber): self.planeNumber = planeNumber # def create_Plane(self): # planeList = [] # newPlaneName = input('Enter plane name') # newPlaneNumber = input('Enter plane number') # newPlane = newPlaneName, newPlaneNumber # planeList.append(newPlane) # # User.create_Plane('Jim')
''' Created on May 11, 2015 @author: cvora 7.1 Write a program that prompts for a file name, then opens that file and reads through the file, and print the contents of the file in upper case. Use the file words.txt to produce the output below. ''' # Use words.txt as the file name fname = raw_input("Enter file name: ") fh = open(fname) fString = fh.read().strip() print fString.upper()
import csv elems = [ {"first_name": "Baked", "last_name": "Beans"}, {"first_name": "Lovely", "last_name": "Spam"}, {"first_name": "Wonderful", "last_name": "Spam"}, ] # write print("==Write file==") with open("names_iter_2.csv", "w", newline="") as csvfile: fieldnames = ["first_name", "last_name"] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(elems) # for elem in elems: # writer.writerow(elem) # read print("==Read file==") with open("names.csv", "r") as csvfile: reader = csv.DictReader(csvfile) for row in reader: print(row["first_name"], row["last_name"])
""" conditionals """ a = -1 if a > 1: print("a > 1") elif a < 0: print("a < 0") else: print("a is {}".format(a)) b = "ok" if a == 0 else "ko"
""" Identity operators """ x1 = 5 y1 = 5 x2 = "Hello" y2 = "Hello" x3 = [1, 2, 3] y3 = [1, 2, 3] # Output: False print(x1 is not y1) # Output: True print(x2 is y2) # Output: False print(x3 is y3) """ Here, we see that x1 and y1 are integers of same values, so they are equal as well as identical. Same is the case with x2 and y2 (strings). But x3 and y3 are list. They are equal but not identical. It is because interpreter locates them separately in memory although they are equal. """
from tkinter import * from tkinter import ttk # variavel que receber o objeto do tkinter root = Tk() style = ttk.Style() # criando a class class application(): """O self é uma referencia á instancia atual da classe é usado para acessar a váriaveis dentro da classe, mas pode ser usado qualquer nome que não seja self. """ def __init__(self): self.root = root self.style = style self.tela() self.frame_da_tela() self.widgets_frame1() self.lista_frame2() root.mainloop() def tela(self): # configurações e dimensionamentos da tela self.root.title('Cadastro de Clientes') self.root.configure(background='#1e3743') self.root.geometry('700x500') # X x Y self.root.resizable(True, True) self.root.maxsize(width=900, height=700) self.root.minsize(width=600, height=400) def frame_da_tela(self): self.frame1 = Frame(self.root, bd=4, bg='#dfe3ee', highlightbackground='#759fe6', highlightthickness=3) self.frame1.place(relx=0.02, rely=0.02, relwidth=0.96, relheight=0.46) self.frame2 = Frame(self.root, bd=4, bg='#dfe3ee', highlightbackground='#759fe6', highlightthickness=3) self.frame2.place(relx=0.02, rely=0.5, relwidth=0.96, relheight=0.46) def widgets_frame1(self): # Botão limpar self.bt_limpar = Button(self.root, text='Limpar', bd=3, bg='#107bd2', fg='white', font=('Verdana', 9, 'bold')) self.bt_limpar.place(relx=0.2, rely=0.09, relwidth=0.1, relheight=0.07) # Botão buscar self.bt_buscar = Button(self.root, text='Buscar', bd=3, bg='#107bd2', fg='white', font=('Verdana', 9, 'bold')) self.bt_buscar.place(relx=0.3, rely=0.09, relwidth=0.1, relheight=0.07) # Botão novo self.bt_novo = Button(self.root, text='Novo', bd=3, bg='#107bd2', fg='white', font=('Verdana', 9, 'bold')) self.bt_novo.place(relx=0.6, rely=0.09, relwidth=0.1, relheight=0.07) # Botão editar self.bt_alterar = Button(self.root, text='Alterar', bd=3, bg='#107bd2', fg='white', font=('Verdana', 9, 'bold')) self.bt_alterar.place(relx=0.7, rely=0.09, relwidth=0.1, relheight=0.07) # Botão apagar self.bt_apagar = Button(self.root, text='Apagar', bd=3, bg='#107bd2', fg='white', font=('Verdana', 9, 'bold')) self.bt_apagar.place(relx=0.8, rely=0.09, relwidth=0.1, relheight=0.07) # Label código do cliente self.lb_codigo = Label(self.frame1, text='Código', bg='#dfe3ee', font=('Verdana', 9, 'bold')) self.lb_codigo.place(relx=0.05, rely=0.10) # Entry código do cliente self.codigo_entry = Entry(self.frame1) self.codigo_entry.place(relx=0.05, rely=0.19, relwidth=0.10, relheight=0.10) # Label nome do cliente self.lb_nome = Label(self.frame1, text='Nome', bg='#dfe3ee', font=('Verdana', 9, 'bold')) self.lb_nome.place(relx=0.05, rely=0.35) # Entry nome do cliente self.nome_entry = Entry(self.frame1) self.nome_entry.place(relx=0.05, rely=0.45, relwidth=0.88, relheight=0.10) # Label Telefone self.lb_telefone = Label( self.frame1, text='Telefone', bg='#dfe3ee', font=('Verdana', 9, 'bold')) self.lb_telefone.place(relx=0.05, rely=0.60) # Entry telefone self.telefone_entry = Entry(self.frame1) self.telefone_entry.place( relx=0.05, rely=0.71, relwidth=0.44, relheight=0.10) # Label cidade self.lb_cidade = Label(self.frame1, text='Cidade', bg='#dfe3ee', font=('Verdana', 9, 'bold')) self.lb_cidade.place(relx=0.51, rely=0.60) # Entry Cidade self.cidade_entry = Entry(self.frame1) self.cidade_entry.place(relx=0.51, rely=0.71, relwidth=0.42, relheight=0.10) def lista_frame2(self): self.listaCli = ttk.Treeview( self.frame2, height=3, column=('col1', 'col2', 'col3', 'col4')) self.style.configure("Treeview", fielbackground='black') self.listaCli.heading("#0", text="") self.listaCli.heading('#1', text='Código') self.listaCli.heading('#2', text='Nome') self.listaCli.heading('#3', text='Telefone') self.listaCli.heading('#4', text='Cidade') self.listaCli.column('#0', width=1) self.listaCli.column('#1', width=50) self.listaCli.column('#2', width=200) self.listaCli.column('#3', width=125) self.listaCli.column('#4', width=125) self.listaCli.place(relx=0.01, rely=0.01, relwidth=0.95, relheight=0.85) self.scrollList = Scrollbar(self.frame2, orient='vertical') self.listaCli.configure(yscroll=self.scrollList.set) self.scrollList.place(relx=0.96, rely=0.02, relwidth=0.04, relheight=0.85) application()
""" Provides the most general definition of topological space """ import abc from typing import Generic, TypeVar, Union, Container, Tuple, overload T = TypeVar('T') Y = TypeVar('Y') class Topology(Generic[T], metaclass=abc.ABCMeta): """ A topology, or topological space, is a two-tuple of a set and a set of sets such that * The empty set and the set are in the collection of open sets * The intersection of any two open sets is in the set * The union of any two open sets is in the set Each element in the set of sets are referred to as open sets .. note:: Since this is the most general type of topology, this interface can only provide a class:`python.typing.Container` for the elements and open sets. This allows for representations of uncountably-infinite topologies. Finite topologies are refined in sub-interfaces. .. note:: The definition of containment is a bit interesting when it comes to :class:`python.typing.Container`. This because containers only implement the ``__contains__`` function, which only answers whether an element is in that container. Therefore, a set contains a container iff all elements in that open set are in the container, and there is no element in the topology that is in the container, but not in the open set. The first table below shows an example of containment being ``True``. The second table shows an example of containment being ``False``. +---------------------+----------------------+-----------------------+ | Element of Topology | Elements In Open Set | Elements In Container | +---------------------+----------------------+-----------------------+ | ``a`` | ``a`` | ``a`` | +---------------------+----------------------+-----------------------+ | ``b`` | ``b`` | ``b`` | +---------------------+----------------------+-----------------------+ | ``c`` | ``c`` | | +---------------------+----------------------+-----------------------+ | ``d`` | | | +---------------------+----------------------+-----------------------+ +---------------------+----------------------+-----------------------+ | Element of Topology | Elements In Open Set | Elements In Container | +---------------------+----------------------+-----------------------+ | ``a`` | ``a`` | ``a`` | +---------------------+----------------------+-----------------------+ | ``b`` | ``b`` | ``b`` | +---------------------+----------------------+-----------------------+ | ``c`` | ``c`` | | +---------------------+----------------------+-----------------------+ | ``d`` | | ``d`` | +---------------------+----------------------+-----------------------+ """ @property @abc.abstractmethod def elements(self) -> Container[T]: """ :return: The elements in this topology """ raise NotImplementedError() @property @abc.abstractmethod def open_sets(self) -> Container[Container[T]]: """ :return: The open sets in the topology. """ raise NotImplementedError() @property @abc.abstractmethod def closed_sets(self) -> Container[Container[T]]: """ :return: The closed sets for the topology. A closed set is a set whose complement is an open set """ raise NotImplementedError() @abc.abstractmethod @overload def get_open_neighborhoods( self, point_or_set: T ) -> Container[Container[T]]: """ :param point_or_set: The point for which the open neighborhoods need to be retrieved :return: The open neighborhoods """ pass @abc.abstractmethod @overload def get_open_neighborhoods( self, point_or_set: Container[T] ) -> Container[Container[T]]: """ :param point_or_set: The set for which open neighborhoods are to be obtained :return: The open neighborhoods """ pass @abc.abstractmethod def get_open_neighborhoods( self, point_or_set: Union[T, Container[T]] ) -> Container[Container[T]]: r""" :param point_or_set: The point or set for which the open neighborhoods are to be obtained :return: The open neighborhoods. An open neighborhood :math:`U` for a point :math`u` in the topology (:math:`u \in S` where :math:`S` is the set of elements in the topology) is the collection of all open sets that contain the point. """ raise NotImplementedError() @abc.abstractmethod def closure(self, subset: Container[T]) -> Container[T]: """ :param subset: The subset of the elements of the topology for which the closure is to be calculated :return: The closure of the set. This is defined as the intersection of all closed sets that contain the subset. """ raise NotImplementedError() @abc.abstractmethod def interior(self, subset: Container[T]) -> Container[T]: """ :param subset: The subset for which the interior is to be calculated :return: The interior of the set. This is the union of all open sets that contain the subset """ raise NotImplementedError() @abc.abstractmethod def boundary(self, subset: Container[T]) -> Container[T]: """ :param subset: The subset for which the boundary is to be calculated :return: The boundary of the set. The boundary of a set is the intersection of all closed sets containing the subset. """ raise NotImplementedError() @abc.abstractmethod def complement(self, subset: Container[T]) -> Container[T]: """ :param subset: The subset of the topology for which the complement is to be obtained :return: The complement of the set. This is the set of all elements in the topology that are not in the subset """ raise NotImplementedError() @abc.abstractmethod def __mul__(self, other: 'Topology[Y]') -> 'Topology[Tuple[T, Y]]': """ :param other: The other topology against which this one is to be multiplied :return: The product topology formed by multiplying the topologies """ raise NotImplementedError() @abc.abstractmethod def __eq__(self, other: object) -> bool: """ Axiomatic set theory states that two sets are equal iff their elements are equal. Using this axiom, let two topologies be equal iff their elements and their open sets are equal. :param other: The topology against which this is to be compared for equality :return: True if the topologies are equal, otherwise False """ raise NotImplementedError()
from fom.interfaces import Topology from fom.intervals import OpenInterval from fom.intervals import ClosedInterval from typing import Container, Union, Collection class Interval(Container[float]): """ Describes an interval between two points on the real number line """ class RealNumbers(Topology[float]): """ Describes the standard topology of the real numbers. The elements of this topology are the real numbers, and the open sets of the topology are the sets that are unions of open intervals of real numbers. This is an example of a topological space. """ @property def elements(self) -> Container[float]: return self._Elements() @property def open_sets(self) -> Container[Container[float]]: return self._OpenSets() @property def closed_sets(self) -> Container[Container[float]]: return self._ClosedSets() @property def get_open_neighborhoods( self, point_or_set: Union[float, Container[float]] ) -> Container[Container[float]]: if isinstance(point_or_set, float): set_to_check = frozenset({point_or_set}) else: set_to_check = point_or_set return self._OpenNeighborhoods(set_to_check) class _Elements(Container[float]): """ Base class for the container of the elements of this topology """ def __contains__(self, item: float) -> bool: """ :param item: The item to check :return: True if the item is a float. This means that it is a real number, and so it belongs to the elements """ return isinstance(item, float) class _OpenSets(Container[OpenInterval[float]]): """ Describes the open sets of the topology """ def __contains__(self, item: OpenInterval[float]) -> bool: return isinstance(item, OpenInterval[float]) class _ClosedSets(Container[ClosedInterval[float]]): """ Describes the closed sets of the topology """ def __contains__(self, item: ClosedInterval[float]) -> bool: return isinstance(item, ClosedInterval[float]) class _OpenNeighborhoods(Container[OpenInterval[float]]): """ Defines the open neighborhoods of a point """ def __init__(self, points: Collection[float]) -> None: self._points = points def __contains__(self, item: OpenInterval[float]) -> bool: return all(point in item for point in self._points)
""" Defines a topology where sets and open sets are given by the user on construction """ from fom.interfaces import FiniteTopology as FiniteTopologyInterface from fom.interfaces import Topology as TopologyInterface from fom.topologies.abc import FiniteTopology from typing import TypeVar, Union, Collection, Generic, Iterator, Tuple from typing import Container, Iterable, cast from fom.exceptions import InvalidOpenSets T = TypeVar('T') Y = TypeVar('Y') class CustomTopology(FiniteTopology[T], Generic[T]): """ Implements a finite topology where open sets and elements are given by the user. As a result, the elements in this topology are finite and countable. The open sets in the topology are finite and countable as well. .. note:: At the time of writing, the ``__contains__`` method in a generic container has type of ``object``. This is due to the mypy community deciding how to support covariance in sequences. An example of a covariant list is ``[1, "foo"]``, since the first element is an ``int`` and the second is a ``str``. """ def __init__( self, elements: Collection[T], open_sets: Collection[Collection[T]] ) -> None: """ :param elements: The set of elements in the topology :param open_sets: The open sets in the topology """ self._elements = elements self._open_sets = open_sets self._assert_first_axiom(elements, open_sets) @property def elements(self) -> Collection[T]: """ :return: The elements of the topology """ return self._elements @property def open_sets(self) -> Collection[Collection[T]]: """ :return: The open sets """ return self._open_sets @property def closed_sets(self) -> Collection[Collection[T]]: """ :return: The collection of closed sets in this topology """ return self._ClosedSets(self) def closure(self, subset: Container[T]) -> Collection[T]: """ :param subset: A container containing a subset of the elements in the topology for which the closure needs to be found :return: The closure of the subset """ closed_sets_containing_subset = filter( lambda set_: self._open_set_contains_container(set_, subset), self.closed_sets ) return self._Intersection(self, closed_sets_containing_subset) def interior(self, subset: Container[T]) -> Collection[T]: """ :param subset: :return: """ open_sets_containing_subset = filter( lambda set_: self._open_set_contains_container(set_, subset), self.open_sets ) return self._Union(self, open_sets_containing_subset) def boundary(self, subset: Container[T]) -> Collection[T]: """ :param subset: The subset for which the boundary is to be calculated :return: """ return self._Intersection( self, (self.closure(subset), self.complement(self.closure(subset))) ) def complement(self, subset: Container[T]) -> Collection[T]: """ :param subset: :return: """ return self._Complement(self, subset) @staticmethod def _is_point(point_or_set: Union[T, Container[T]]): return not isinstance(point_or_set, Container) def _open_set_contains_container( self, open_set: Collection[T], container: Container[T] ) -> bool: closed_set_has_container = any(( element in container for element in self.complement(open_set))) all_elements_in_container = all(( element in container for element in open_set )) return all_elements_in_container and not closed_set_has_container @staticmethod def _assert_first_axiom( elements: Collection[T], open_sets: Collection[Collection[T]] ) -> None: contains_empty_set = False contains_set_of_elements = False for open_set in open_sets: if all(element not in open_set for element in elements): contains_empty_set = True if all(element in open_set for element in elements): contains_set_of_elements = True if not contains_empty_set: raise InvalidOpenSets( 'The set of open sets does not contain the empty set' ) if not contains_set_of_elements: raise InvalidOpenSets( 'The set of open sets not contain the set of elements' ) def __mul__(self, other: TopologyInterface[Y]) -> TopologyInterface[Tuple[T, Y]]: return self def __eq__(self, other: object) -> bool: if not isinstance(other, FiniteTopologyInterface): raise ValueError('Incomparable types') else: elements_equal = self.elements == other.elements open_sets_equal = self.open_sets == other.elements return elements_equal and open_sets_equal class _ClosedSets(Collection[Collection[T]]): """ Base class for the collection of closed sets """ def __init__(self, topology: FiniteTopologyInterface[T]) -> None: """ :param topology: The topology for which the closed sets are to be obtained """ self._topology = topology def __len__(self) -> int: """ :return: The number of closed sets in the collection. This is equal to the number of open sets in the parent topology since every closed set has a complementary open set """ return len(self._topology.open_sets) def __iter__(self) -> Iterator[Collection[T]]: """ :return: An iterator iterating through the closed sets """ return ( self._topology.complement(open_set) for open_set in self._topology.open_sets ) def __contains__(self, item: object) -> bool: """ :param item: The item to check for membership in the topology :return: ``True`` if the set is a closed set in the topology, otherwise ``False`` """ return self._topology.complement( cast(Collection[T], item) ) in self._topology.open_sets def __repr__(self) -> str: return '%s(topology=%s)' % ( self.__class__.__name__, self._topology ) class _Intersection(Collection[T]): """ Base class for intersection of a set of sets """ def __init__( self, topology: FiniteTopologyInterface[T], containers_to_intersect: Iterable[Container[T]] ) -> None: self._topology = topology self._containers = containers_to_intersect def __iter__(self) -> Iterator[T]: return ( element for element in self._topology.elements if all(element in container for container in self._containers) ) def __len__(self) -> int: return len(frozenset(self)) def __contains__(self, item: object) -> bool: return item in frozenset(self) class _Union(Collection[T]): """ Base class for the union of a set of sets """ def __init__( self, topology: FiniteTopologyInterface[T], containers_to_intersect: Iterable[Container[T]] ) -> None: self._topology = topology self._containers = containers_to_intersect def __iter__(self) -> Iterator[T]: return ( element for element in self._topology.elements if any(element in container for container in self._containers) ) def __len__(self) -> int: return len(frozenset(self)) def __contains__(self, item: object) -> bool: return item in frozenset(self) class _Complement(Collection[T]): """ """ def __init__( self, topology: FiniteTopologyInterface[T], subset: Container[T] ) -> None: self._topology = topology self._subset = subset def __iter__(self) -> Iterator[T]: return ( element for element in self._topology.elements if element not in self._subset ) def __len__(self) -> int: return len(frozenset(self)) def __contains__(self, item: object) -> bool: return item in frozenset(self)
def count(array): memo=[None]*(len(array)+1) print num_count(array,len(array),memo) print memo def num_count(array,num_lookat,memo): if num_lookat == 0: return 1 s = len(array) - num_lookat if array[s] == '0': return 0 if memo[num_lookat] != None: return memo[s] result = num_count(array,num_lookat-1,memo) if num_lookat >=2 and int(array[s:s+2]) <=26: result += num_count(array,num_lookat-2,memo) memo[num_lookat]=result return result count("12")
class Person: def __init__(self, first, last): self.firstname = first self.lastname = last def __str__(self): return self.firstname + "lallala " + self.lastname class Employee(Person): def __init__(self, first, last, staffnum): Person.__init__(self,first, last) self.staffnumber = staffnum x = Person("Marge", "Simpson") # print x.firstname,x.lastname,x y = Employee("Homer", "Simpson", "1007") print y.staffnumber,y.firstname,y.lastname, y
#edit test #class 테스트 class character(): #init은 class가 생성될때마다 등장합니다 def __init__(self, name = "No", health = 100, money = 100): self.name = name self.money = money self.health = health print(f"{self.name} spawned with ${self.money}") def checkmoney(self): return self.money def checkhealth(self): return self.health def __del__(self): print(f"{self.name}이 사망하였습니다") print("Character Spawn Module") nameofplr = input("스폰하고싶은 캐릭터 이름?: ") player = character(nameofplr) while True: question = input("하고싶은활동\n모르겠으면 'help'을 입력해주세요\n:") if question.lower() == "help": print("checkmoney, checkhealth, suicide") continue elif question.lower() == "checkmoney": print(player.checkmoney()) continue elif question.lower() == "checkhealth": print(player.checkhealth()) continue elif question.lower() == "suicide": del player break print("게임 오버")
print("The type of int is type(1): ", type(1)) print("Instance of should match with int, isinstance(1, int): ", isinstance(1,int)) print("Adding to int gives int, 1 + 1; ", 1 + 1) print('Adding int and float gives float, 1 + 1.0: ', 1 + 1.0) print("The type of float is type(2.0): ", type(2.0)) print("\n\nConversion from int to float can be done by float(1): ", float(1)) print("Conversion from float to int can be done by int(2.0): ", int(2.0)) print("Conversion from Float to int is a truncation not conversion, int(2.5): ", int(2.5)) print("Conversion from Float to int is a truncation not conversion, int(-2.5): ", int(-2.5)) print("Python supports on 15 place of decimal precision, 1.0123456789012345678901234567890: ", 1.0123456789012345678901234567890) print("int is the only integer, how long the number be, type(100000000000000000000000000000): ", type(1000000000000000000000))
__author__ = 'Djamel' import custom_min_heap as min_h import custom_max_heap as max_h def compute_median_maintenance(file): hh = min_h.CustomMinHeap() hl = max_h.CustomMaxHeap() median_sum = 0 with open(file) as f: for line in f: number = int(line.rstrip("\n").rstrip("\r").rstrip("\t")) #print median_sum if hl.count() == 0 and hh.count() == 0: hl.insert(number) median_sum += number continue if hl.get() >= number: hl.insert(number) else: hh.insert(number) balance = hl.count() - hh.count() if balance == 0 or balance == 1: median_sum += hl.get() elif balance == 2: hh.insert(hl.pop_max()) median_sum += hl.get() elif balance == -1: median_sum += hh.get() elif balance == -2: hl.insert(hh.pop_min()) median_sum += hl.get() return median_sum % 10000
preçoMerc = float(input('Informe o preço da mercadoria: ')) percent = float(input('Informe o percentual de desconto: ')) desconto = percent*preçoMerc preçoPagar = preçoMerc-desconto print('O valor do desconto %4.2f R$'%desconto) print('O valor a pagar é de %5.2f R$'%preçoPagar)
num = 1 soma = 0 cont = 0 while num != 100: if(num % 2 == 0): soma += num cont += 1 num = int(input('Informe o valor: ')) if(cont == 0): print('nao foram lidos numeros pares') else: resul = int(soma / cont) print('Media: {}'.format(resul))
perg = 's' while(perg): num1 = int(input('Informe o primeiro valor: ')) num2 = int(input('Informe o segundo valor: ')) if(num1 <= 0 or num2 <= 0): m = ( num1 + num2) / 2 print(m) else: soma = num1 + num2 mult = num1 * num2 print('{} {}'.format(soma,mult)) perg = str.lower(input('Deseja continuar (S/n): ')) if perg == 's' : True else: break
salario = float(input('Informe o salario: ')) if(salario > 1000): novo_sal = salario * 0.17 else: novo_sal = salario * 0.08 print('O valor do imposto que ele ira pagar sera de {}'.format(novo_sal))
cont = 1 while(cont <= 3): num1 = int(input('Informe o primeiro valor: ')) num2 = int(input('Informe o segundo valor: ')) if(num1 <= 0 or num2 <= 0): m = ( num1 + num2) / 2 print(m) else: soma = num1 + num2 mult = num1 * num2 print('{} {}'.format(soma,mult)) cont+=1
idade_dias = int(input('Informe a idade expressada em dias: ')) anos = idade_dias/365 mes = (idade_dias%365)/30 dias = (idade_dias%365)%30 print('%d anos, %d meses, %d dias '%(anos,mes,dias))
km_percorrido = float(input('Informe a quantidade de Km precorrido: ')) dias_alugado = int(input('Informe a quantidade de dias que o carro passou alugado: ')) preço_pagar = km_percorrido*0.15 + dias_alugado*60 print('A preço do alugel do carro é de %5.2f R$'%preço_pagar)
contb = 0 contrr = 0 conte = 0 maior = 0 soma = 0 x = int(input('Quantidade de pessoas: ')) for i in range(x): idade = int(input('Informe a idade: ')) opniao = str.lower(input('Informe a opnião: ')) if(opniao == 'bom'): soma += idade contb += 1 if(opniao == 'ruim' or opniao == 'regular'): contrr += 1 if(idade > 30 and opniao == 'excelente'): conte += 1 if(idade > maior): maior = idade print('Media de idade Bom -> {:.0f}'.format(soma/contb)) print('Quantidade respostas Ruim/Regular -> {}'.format(contrr)) print('Pessoas acima de 30 Excelente -> {}'.format(conte)) print('Maior idade -> {}'.format(maior))
num = int(input('Digite o número: ')) if(num % 2 != 0): print('Número é Impar') else: print('Número não é Impar') if(num % 3 == 0): print('Múltiplo de 3') else: print('Número não é mútiplo de 3') if(102 % num == 0): print('Divisor de 102') else: print('Número não é divisor de 102')
salario = float(input('Informe o salario do funcionario: ')) if(salario > 1250): salSuper = salario + (salario*(10/100)) else: salSuper = salario + (salario*(15/100)) print('Salario com aumento é de {}'.format(salSuper))
import numpy as np import theano, keras from theano import tensor as T from keras.models import Sequential from keras.layers import Dense, Dropout, Activation from keras.optimizers import SGD import os train_sample = 1000 test_sample = 100 #np.random.random will return an output size (1000, 20) of uniformly distributed independent random variables. #np.random.randint(size, low, high) will output a size (1000, 20) uniformly distributed, over intergers, #random variables that range from low to high-1. Note that high is not included x_train = np.random.random(size=(train_sample, 20)) #keras.utils.to_categorical(vector of size nx1, num_classes) converts a column vector into a category matrix #with column size equalling num_classes. #For example if num_classes = 2, then each entry in the column vector is 0 or 1. Suppose an entry is 1, #in the category model it is now 01. If it were 0, it corresponds to 10. y_train = keras.utils.to_categorical(np.random.randint(size=(train_sample, 1), low=0, high=10), num_classes=10) x_test = np.random.random((test_sample, 20)) y_test = keras.utils.to_categorical(np.random.randint(size=(test_sample, 1), low=0, high=10)) #Now we are ready to build our model for multi-category classification. #Let's go for two hidden layers but we allow for regularization through dropouts. #Our deep neural network will be input--->hidden_layer_1--->(with dropout)hidden_layer_1--->(with_dropout)output_layer(soft_max) NN = Sequential() NN.add(Dense(128, input_shape=(20,), activation='relu'))#Here the input shape is a simple vector (list). Hence (20, ). #Note that we may equivalently write input_dim = 20 NN.add(Dropout(.4)) NN.add(Dense(128, activation='relu')) NN.add(Dropout(.4)) NN.add(Dense(10, activation='softmax')) #SGD is a keras optimizer that needs to some prepping. lr is the learning_rate, decay is the decay_rate #of the learning rate, momentum term and if we are to use nesterov optimization. sgd = SGD(lr = .01, decay=1e-6, momentum=.9, nesterov=True) #Other optimizers: 'rmsprop', 'adam', etc. #Other loss functions: 'binary_crossentropy', 'mse' (mean squared error), etc. NN.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy']) #Now we are ready to fit the training data. Since the data size is typically large, it is not wise to #consider all of them at once. Let us say the loss function is the average mean squared error. Then we can only make one #gradient step. If the batch_size were 50 and epochs were 10, the number of gradient descent steps would be 200. #However each step would involve a loss function that is the average of 50 sample points. Averaging typically #reduces biases in training the neural network at hand. NN.fit(x_train, y_train, batch_size=128, epochs=1) #What is left to do is evaluate our neural network on the test data. score = NN.evaluate(x_test, y_test, batch_size=128) print score #os.system('spd-say "Your program is done"') ################################################################################################################## ################################################################################################################## #################################The Binary Classification Problem############################################# ################################################################################################################## ################################################################################################################## x_train1 = np.random.random((train_sample, 20)) y_train1 = np.random.randint(size=(train_sample, 1), low=0, high=2) x_test1 = np.random.random((test_sample, 20)) y_test1 = np.random.randint(size=(test_sample, 1), low=0, high=2) #We intend to utilize binary_crossentropy as our loss function. Here the output layer is a single sigmoid neuron. #Hence we do not need to_categorical it. NN1 = Sequential() NN1.add(Dense(128, input_shape=(20,), activation='relu')) NN1.add(Dense(1, activation='sigmoid')) NN1.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) NN1.fit(x_train1, y_train1, batch_size=256, epochs=1) #Please tinker with the epochs and batch_size. score1 = NN1.evaluate(x_test1, y_test1, batch_size=256) #The epochs definitely needs to be much much higher. print score1 ################################################################################################################## ################################################################################################################## ####################################Convolutional neural network################################################## ################################################################################################################## ################################################################################################################## from keras.layers import Conv2D, MaxPool2D, Flatten #When processing images using theano as the backend, it is worth noting that data_format = 'channels_first' needs #to be specified. In other words it expects (channels, height, width) not channels last. Else, we need to reshape data. #Example: x_train = x_train.reshape(x_train[0], channels, height, width). #Dummy data dummy data dummy data for training and testing. x_train2 = np.random.random((train_sample, 3, 32, 32)) y_train2 = keras.utils.to_categorical(np.random.randint(size=(train_sample, 1), low=0, high=10), num_classes=10) x_test2 = np.random.random((test_sample, 3, 32, 32)) y_test2 = keras.utils.to_categorical(np.random.randint(size=(test_sample, 1), low= 0, high=10), num_classes=10) NN2 = Sequential() NN2.add(Conv2D(64, (3,3), activation='relu', input_shape=x_train2.shape[1:], data_format='channels_first')) #If tensorflow were to be used as a backend, then we would use the 'channels_first' data_format. NN2.add(Conv2D(64, (3,3), activation='relu')) NN2.add(MaxPool2D(pool_size=(2,2))) NN2.add(Flatten()) NN2.add(Dropout(0.5)) NN2.add(Dense(128, activation='relu')) NN2.add(Dense(10, activation='softmax')) NN2.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) NN2.fit(x_train2, y_train2, batch_size=32, epochs=10) score2 = NN2.evaluate(x_test2, y_test2, batch_size=32) print score2
def convertToCompareFormat(name): compare_string = name.lower() if len(compare_string) > 1: tmp_str = compare_string.replace('#ACTOR#', '').lower().replace('$', '').replace('[', '').replace(']', '') \ .replace('_', '+').replace(' ', '+').replace('\t', '') tmp_str = remove_text_paranthesis(tmp_str) if len(tmp_str) > 2 and tmp_str[0] == '+': tmp_str = tmp_str[1:] elif len(tmp_str) > 2 and tmp_str[-1] == '+': tmp_str = tmp_str[:-1] compare_string = tmp_str return compare_string def remove_text_paranthesis(sentence): ret = '' skip1c = 0 skip2c = 0 for i in sentence: if i == '[': skip1c += 1 elif i == '(': skip2c += 1 elif i == ']' and skip1c > 0: skip1c -= 1 elif i == ')' and skip2c > 0: skip2c -= 1 elif skip1c == 0 and skip2c == 0: ret += i return ret
""" Reinforcement learning Discrete stochastic dicision process with delayed reward example. Red rectangle: explorer. White rectangle: stations. In state s_i, the discrete action space is [0, 1]. When agent choose action 0, explorer go to state s_i+1. Otherwise if action 1 chosen, explorer go to state s_i-1 or s_i+1 with equal possibility. Initial state is s_2 and terminal state is station s_1. The reward at the terminal state depends on whether s_n is visited(r = 1) or not(r = 0.01) """ import numpy as np import time import sys if sys.version_info.major == 2: import Tkinter as tk else: import tkinter as tk UNIT = 40 # pixels n_states = 6 class dsdp(tk.Tk, object): def __init__(self): super(dsdp, self).__init__() self.action_space = [0, 1] self.n_actions = len(self.action_space) self.n_features = 2 self.title('discrete stochastic dicision process') self.geometry('{0}x{1}'.format(n_states * UNIT, UNIT)) self._build_dsdp() def _build_dsdp(self): self.canvas = tk.Canvas(self, bg='white', height=UNIT, width=n_states * UNIT) # create grids for c in range(0, n_states * UNIT, UNIT): x0, y0, x1, y1 = c, 0, c, UNIT self.canvas.create_line(x0, y0, x1, y1) for r in range(0, UNIT, UNIT): x0, y0, x1, y1 = 0, r, n_states * UNIT, r self.canvas.create_line(x0, y0, x1, y1) # create origin self.origin = np.array([60, 20]) origin = self.origin # create oval oval_center = origin + np.array([UNIT * (n_states - 2), 0]) self.oval = self.canvas.create_oval( oval_center[0] - 15, oval_center[1] - 15, oval_center[0] + 15, oval_center[1] + 15, fill='yellow') # create red rect self.rect = self.canvas.create_rectangle( origin[0] - 15, origin[1] - 15, origin[0] + 15, origin[1] + 15, fill='red') self.terminal_coords = [5, 5, 35, 35] self.flag = 1 # pack all self.canvas.pack() def reset(self): self.update() #time.sleep(0.1) self.canvas.delete(self.rect) origin = self.origin self.rect = self.canvas.create_rectangle( origin[0] - 15, origin[1] - 15, origin[0] + 15, origin[1] + 15, fill='red') oval_center = origin + np.array([UNIT * (n_states - 2), 0]) if(self.flag == 0): self.oval = self.canvas.create_oval( oval_center[0] - 15, oval_center[1] - 15, oval_center[0] + 15, oval_center[1] + 15, fill='yellow') self.flag = 1 self.counter = 0 # return observation return np.array([self.flag, 1 + (self.canvas.coords(self.rect)[1] - self.origin[1]) / UNIT]) def step(self, action): self.counter += 1 s = self.canvas.coords(self.rect) base_action = np.array([0, 0]) if action == 0: # left if s[0] > UNIT: base_action[0] -= UNIT elif action == 1: # 50% left, 50% right temp = np.random.uniform() if(temp < 0.5 and s[0] > UNIT): base_action[0] -= UNIT if(temp >= 0.5 and s[0] < (n_states - 1) * UNIT): base_action[0] += UNIT self.canvas.move(self.rect, base_action[0], base_action[1]) # move agent next_coords = self.canvas.coords(self.rect) # next state # reward function if next_coords == self.terminal_coords: done = True reward = 0.01 if self.flag else 1 elif(self.flag == 1 and next_coords == self.canvas.coords(self.oval)): self.flag = 0 self.canvas.delete(self.oval) reward = 0 done = False else: reward = 0 done = False if self.counter > 100: done = True s_ = np.array([self.flag, 1 + (self.canvas.coords(self.rect)[1] - self.terminal_coords[1]) / UNIT]) self.render() return s_, reward, done def render(self): #time.sleep(0.01) self.update()
numbers = [273, 103,5, 32, 65, 9, 72, 800, 99] for number in numbers: if number % 2 == 0: print("{}는 짝수입니다.".format(number)) else: print("{}는 홀수입니다.".format(number)) print() for number_1 in numbers: if number_1 < 10: print("{}는 1자릿수 입니다.".format(number_1)) elif number_1 < 100: print("{}는 2자릿수 입니다.".format(number_1)) elif number_1 < 1000: print("{}는 3자릿수 입니다.".format(number_1))
""" 5. Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение. Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке). Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника. """ while True: proceeds = input('Введите сумму выручки в у.е.: ') if proceeds.isdigit(): proceeds = int(proceeds) break print('Ошибка ввода. Введено не число.') while True: costs = input('Введите сумму издержек у.е.: ') if costs.isdigit(): costs = int(costs) break print('Ошибка ввода. Введено не число.') if proceeds > costs: profit = proceeds - costs print(f'Поздравляю, вы работаете с прибыль {profit} у.е.') profitability = profit / proceeds * 100 print('Ваша рентабельность в процентах составляет: %.2f' % profitability) # вариант "округления" №1 staff = int(input('Сколько сотрудников у вас работает? ')) profit_per_employee = round(profit / staff, 2) # вариант округления №2 print(f'Прибыль фирмы на 1 сотрудника = {profit_per_employee} у.е.') elif proceeds == costs: print('Вы сработали в ноль, очень странный бизнес.') else: print('Нужно что-то менять, к сожалению, у вас убытки! Вы сработали в ', proceeds - costs, 'у.е.')
import random import math import time number_of_iterations = int(input("Number of iterations : ")) def monte_carlo(): inside_circle = 0 for i in range(0, number_of_iterations): x = random.random() y = random.random() if math.sqrt(x*x + y*y) < 1.0: inside_circle += 1 return inside_circle start_time = time.time() pi = (float(monte_carlo()) / number_of_iterations) * 4 ending_time = time.time() print("Estimation of PI :", pi) print("Calculations took", ending_time-start_time)
# write a program that returns the first repeated character in a string def first_repeated_char(str): repeat = [] for letter in str: if letter in repeat: return letter else: repeat.append(letter) return None ex1 = 'abca' ex2 = 'bcaba' ex3 = 'abc' ex4 = 'dbcaba' print(first_repeated_char(ex1)) print(first_repeated_char(ex2)) print(first_repeated_char(ex3)) print(first_repeated_char(ex4)) # given an array, treat all entries as a number, then increment def array_incrementer(given_array): number = 0 for i, val in enumerate(reversed(given_array)): number = number + 10**i * val number = number + 1 new_array = [] for val in str(number): new_array.append(int(val)) return new_array print(array_incrementer([1, 3, 2, 9]))
t = float(input("Enter temperature ")) t_type = input("Enter temperature type - C,F or K: ") if t_type == "C": c_in_k = t + 273.15 c_in_f = (9 / 5.0 * t) + 32 print("Temp in C = ", t) print("Temp in F = ", c_in_f) print("Temp in K = ", c_in_k) elif t_type == "K": k_in_c = t - 273.15 k_in_f = -457.87 * t print("Temp in K = ", t) print("Temp in C = ", k_in_c) print("Temp in F = ", k_in_f) else: f_in_c = 5.0 * (t - 32) / 9 f_in_k = (t + 459.67) * 5 / 9 print("Temp in F = ", t) print("Temp in C = ", f_in_c) print("Temp in K = ", f_in_k)
string = str(input("Enter the text: ")) def word_in_text(func): def text(): print(string) func() return text() @word_in_text def list_of_the_word(): print(string.split(' '))
x = float(input("km in first day ")) y = int(input("number of km ")) day = 1 sum_km = x while sum_km < y: x = x + (0.1 * x) day = day + 1 sum_km = sum_km + x print("The athlete ran ", y, " km in ", day, " days")
import queue class ScreenDriver: NUM_COLS = 40 NUM_LINES = 24 def __init__(self, addr_start): self.addr_start = addr_start self.addr_end = addr_start + self.NUM_COLS * self.NUM_LINES self.update_queue = queue.Queue() self.screen = Screen(self.update_queue, self.NUM_COLS, self.NUM_LINES) def tick(self, addr, data, rwb): if rwb or addr < self.addr_start or addr > self.addr_end: return shifted_addr = addr - self.addr_start self.update_queue.put((shifted_addr, data)) self.screen.update() def draw(self): self.screen.draw() class Screen: CHAR_W = 16 CHAR_H = 20 def __init__(self, update_queue, num_cols, num_lines): self.update_queue = update_queue self.num_lines = num_lines self.num_cols = num_cols self.memory = [ord(' ')] * self.num_lines * self.num_cols def update(self): try: addr, data = self.update_queue.get_nowait() self.memory[addr] = data self.draw() except queue.Empty: pass def draw(self): print('+-' + '-' * self.num_cols + '-+') print('| ',end='') for i in range(self.num_lines * self.num_cols): char = self.memory[i] print(chr(char), end='') if i != 0 and (i+1) % self.num_cols == 0: print(' |') if i + 1 < self.num_lines * self.num_cols: print('| ',end='') print('+-' + '-' * self.num_cols + '-+')
'''The goal is to determine if two strings are anagrams of each other. An anagram is a word (or phrase) that is formed by rearranging the letters of another word (or phrase). For example: "rat" is an anagram of "art" "alert" is an anagram of "alter" "Slot machines" is an anagram of "Cash lost in me" function should take two strings as input and return True if the two words are anagrams and False if they are not. Assume: No punctuation No numbers No special characters ''' def anagram_checker(str1, str2): """ Check if the input strings are anagrams Args: str1(string),str2(string): Strings to be checked if they are anagrams Returns: bool: If strings are anagrams or not """ if len(str1) != len(str2): # Clean strings clean_str_1 = str1.replace(" ", "").lower() clean_str_2 = str2.replace(" ", "").lower() if sorted(clean_str_1) == sorted(clean_str_2): return True return False print ("Pass" if not (anagram_checker('water','waiter')) else "Fail") print ("Pass" if anagram_checker('Dormitory','Dirty room') else "Fail") print ("Pass" if anagram_checker('Slot machines', 'Cash lost in me') else "Fail") print ("Pass" if not (anagram_checker('A gentleman','Elegant men')) else "Fail") print ("Pass" if anagram_checker('Time and tide wait for no man','Notified madman into water') else "Fail")
# -*- coding: utf-8 -*- """ ██████╗ ███████╗███╗ ██╗███████╗████████╗██╗ ██████╗ ██████╗██╗████████╗██╗ ██╗ ██╔════╝ ██╔════╝████╗ ██║██╔════╝╚══██╔══╝██║██╔════╝ ██╔════╝██║╚══██╔══╝╚██╗ ██╔╝ ██║ ███╗█████╗ ██╔██╗ ██║█████╗ ██║ ██║██║ ██║ ██║ ██║ ╚████╔╝ ██║ ██║██╔══╝ ██║╚██╗██║██╔══╝ ██║ ██║██║ ██║ ██║ ██║ ╚██╔╝ ╚██████╔╝███████╗██║ ╚████║███████╗ ██║ ██║╚██████╗ ╚██████╗██║ ██║ ██║ ╚═════╝ ╚══════╝╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝ ╚═╝ Functions used for generation of new cities and populations for algorithm. By: Andres Rico - aricom@mit.edu MIT Media Lab - City Science Group """ import numpy as np from progressbar import printProgressBar #Import progress bar function. #Function creates a random city design by assigning a specific number to each block. #Number key is based on the block representation used on the Bento Scope. def citygen(desired_size, types): city = np.round(np.random.rand(desired_size,desired_size)*types) #Random matrix of specified size with numbers between 0 - types. for x in range(0, desired_size): for y in range(0 , desired_size): if (city[x][y]) == 0: #Change all the zeros into ones. city[x][y] = 1 city = np.reshape(city, desired_size * desired_size) #Reshapes matrix into a single vector for better management. return (city) #Function creates a matrix with a specific number of cities and size. #Number of cities is the total population of cities for the algorithm. def create_cities(cities, citysize, uses): printProgressBar(0, cities, prefix = 'Population Generation Progress:', suffix = 'Complete', length = 50) #Progress bar for terminal interface. matrix = np.arange(citysize * citysize) #Creates empty vector to be used to create matrix. for indiv in range(0, cities): newcity = citygen(citysize, uses) #Calls new city generator. matrix = np.vstack((matrix, newcity)) #Adds new city to complete population matrix. printProgressBar(indiv + 1, cities, prefix = 'Population Generation Progress:', suffix = 'Complete', length = 50) #Progress bar for terminal interface. matrix = np.delete(matrix, 0, 0) #Deletes fisrt row used as placeholder. return matrix #Returns matrix with each row representing a different city.
#! /usr/bin/python # -*- coding:utf-8 -*- """ Author: AsherYang Email: ouyangfan1991@gmail.com Date: 2018/6/29 Desc: 产生6位随机短信验证码类 """ import random class RandomPwd: def __init__(self): pass def genPwd(self): a_list = [] while len(a_list) < 6: x = random.randint(0, 9) # if x not in s: a_list.append(x) print a_list string = ''.join(list(map(str, a_list))) return string if __name__ == '__main__': randomPwd = RandomPwd() print randomPwd.genPwd()
""" Creating a budget app using classes and objects. Got hooked defining the transfer method """ class Budget: def __init__(self, category, balance): self.category = category self.balance = balance def deposit(self): userDeposit = int(input("How much would you like to deposit?: ")) self.balance += userDeposit if userDeposit > 1000: print("Deposit successful! \nCurrent Balance for", self.category, "is", self.balance) else: print("Input a valid amount") def withdrawal(self): userWithdrawal = int(input("How much would you want to withdraw?: ")) if userWithdrawal <= self.balance: self.balance -= userWithdrawal print("Withdrawal successful \nYour current balance for", self.category, "is", self.balance) else: print("Insufficient funds! Try again") def check_balance(self): print(f"Your current balance for {self.category} is {self.balance}") def transfer(self, category): withdrawFrom = input("What category would you want to transfer from?: ") amountTransfer = int(input("How much would you want to transfer? ")) if withdrawFrom in ["Food", "Clothing", "Housing", "Personal Care", "Data", "Transportation"] and amountTransfer <= self.balance: self.balance -= amountTransfer print(f"Your current balance for {self.category} is {self.balance}") # transferTo = input("What category would you want to tranfer to?: ") still unsure about this?? category.balance += amountTransfer print(f"Current balance for {category.category} is {category.balance}, transfer successful!") else: print("Please select a valid category!") """ Still struggling to understand the concept of objects and how you can manipulate their parameters. I'll do more research and update my code on this budget app subsequently. I understand my codes are sort of everywhere at the moment, but I'll sure get better. What follows is a way of testing my codes, however I know this is not the proper way to do it but I'll learn that too. """ foodBudget = Budget("Food", 5000) housingBudget = Budget("Housing", 0) clothingBudget = Budget("Clothing", 1500) personalCareBudget = Budget("Personal Care", 0) dataBudget = Budget("Data", 0) transportationBudget = Budget("Transportation", 0) database = { 'Budcustomer': ['Elon', 'Musk', '2222', 'budgetapp_practice@zuriteam.co' ] } print("=" * 60) import time print(" ~~~~~~~~~~~ WELCOME TO BUGETTI ~~~~~~~~~~~") print("Today is a good day to budget your earnings, login to get started!") time.sleep(2) print(" >>>> Input your details to login <<<< ") userIdFromUser = input("UserID: ") passwordFromUser = input("Password: ") for userId, userDetails in database.items(): if(userId == userIdFromUser) and (userDetails[2] == passwordFromUser): print("Hello {}, what would you want to do today? Select an option to begin.".format(database['Budcustomer'][0])) print("1. Deposit") print("2. Withdrawal") print("3. Transfer") print("4. Check Balance") print("These are the available categories: \n-Food \n-Clothing \n-Housing \n-Personal Care \n-Data \n-Transportation") userSelection = int(input("Select an option: ")) print("=" * 60) if(userSelection == 1): userCategory = input("What Budget category would you want to deposit into? ") if userCategory in ["food", "Food"]: foodBudget.deposit() print("Thanks for using Budgetti") elif userCategory in ["cloth", "Cloth", "Clothing", "clothing"]: clothingBudget.deposit() print("Thanks for using Budgetti") elif userCategory in ["housing", "rent", "Housing", "Rent"]: housingBudget.deposit() print("Thanks for using Budgetti") elif userCategory in ["Personal Care", "personal care", "Personal care", "personal Care"]: personalCareBudget.deposit() print("Thanks for using Budgetti") elif userCategory in ["Transportation", "transportation"]: transportationBudget.deposit() print("Thanks for using Budgetti") elif userCategory in ["Data", "data"]: dataBudget.deposit() print("Thanks for using Budgetti") else: print("You have chosen an invalid category!") elif userSelection == 2: userCategory = input("What Budget category would you want to witdraw from? ") if userCategory in ["food", "Food"]: foodBudget.withdrawal() elif userCategory in ["cloth", "Cloth", "Clothing", "clothing"]: clothingBudget.withdrawal() elif userCategory in ["housing", "rent", "Housing", "Rent"]: housingBudget.withdrawal() elif userCategory in ["Personal Care", "personal care", "Personal care", "personal Care"]: personalCareBudget.withdrawal() elif userCategory in ["Transportation", "transportation"]: transportationBudget.withdrawal() elif userCategory in ["Data", "data"]: dataBudget.withdrawal() else: print("You have selected an invalid category!") elif userSelection == 3: foodBudget.transfer(clothingBudget) elif userSelection == 4: userCategory = input("What Budget category would you want to check for balance? ") if userCategory in ["food", "Food"]: foodBudget.check_balance() elif userCategory in ["cloth", "Cloth", "Clothing", "clothing"]: clothingBudget.check_balance() elif userCategory in ["housing", "rent", "Housing", "Rent"]: housingBudget.check_balance() elif userCategory in ["Personal Care", "personal care", "Personal care", "personal Care"]: personalCareBudget.check_balance() elif userCategory in ["Transportation", "transportation"]: transportationBudget.check_balance() elif userCategory in ["Data", "data"]: dataBudget.check_balance() else: print("You have chosen an invalid category!") else: print("Please select a valid option, try again!") else: print('Invalid account or password')
import numpy as np from menpo.shape import PointDirectedGraph def bounding_box(min_point, max_point): r""" Return the bounding box from the given minimum and maximum points. The the first point (0) will be nearest the origin. Therefore, the point adjacency is: :: 0<--3 | ^ | | v | 1-->2 Returns ------- bounding_box : :map:`PointDirectedGraph` The axis aligned bounding box from the given points. """ return PointDirectedGraph( np.array([min_point, [max_point[0], min_point[1]], max_point, [min_point[0], max_point[1]]]), np.array([[0, 1], [1, 2], [2, 3], [3, 0]]), copy=False)
""" Game Project - Alex Marvick (August 20, 2018) Description: Small beginner project to gain familiarity with Python Syntax """ import random game_selection = True ############ def dice_simulator(): game_playing = True while (game_playing): print("Do you want to roll the dice? Y/N") response = input().upper() if (response == 'N'): game_playing = False print("Thanks for playing!") elif (response == 'Y'): print("Rolling dice...") x = random.randint(1, 6) print("You rolled a: " + str(x)); else: print("Please select 'Y' or 'N'.") ########### def guess_the_number(): game_playing = True computer_number = random.randint(1, 100) no_guesses = 1 while (game_playing): print("I'm thinking of a number between 1 - 100. Can you guess?") your_guess = int(input()) # if(isinstance(your_guess, int)): AM - TO HANDLE LATER if(your_guess > 100 or your_guess < 1): print("Please guess a number between 1 and 100...") elif(your_guess != computer_number): if (your_guess < computer_number): print("You're a little low...") else: print("You're a little high!") no_guesses += 1 else: print("You guessed correctly! Congratulations!") print("It took you " + str(no_guesses) + " times to guess correctly.") game_playing = False #else: # print("Integers only!") ########## while(game_selection): print("HELLO! Which game interests you?\n1 Dice Simulator\n2 Guess the Number") response = input() if (response == "1"): dice_simulator() game_selection = False elif (response == "2"): guess_the_number() game_selection = False else: print("Please put in a number between 1 and 2.")
c = input ('Please Fill in Celsius: ') c = float(c) f = c * 9/5 +32 print ('Fahrenheit: ', f)
class Stack1: """Uses a Python list""" def __init__(self, maxitems): self._stack = [] self._maxitems = maxitems def push(self, item): if not self.isfull(): self._stack.append(item) def pop(self): if not self.isempty(): return self._stack.pop() def isempty(self): return len(self._stack) == 0 def isfull(self): return len(self._stack) == self._maxitems class Stack2: """Uses a linked list""" class StackEntry: def __init__(self, item): self.item = item self.nextentry = None def __init__(self, maxitems): self._itemcount = 0 self._top = None self._maxitems = maxitems def push(self, item): if not self.isfull(): entry = self.StackEntry(item) entry.nextentry = self._top self._top = entry self._itemcount += 1 def pop(self): if not self.isempty(): entry = self._top self._top = self._top.nextentry return entry.item def isempty(self): return self._itemcount == 0 def isfull(self): return self._itemcount == self._maxitems if __name__ == '__main__': s = Stack1(10) s.push(23) s.push(65) s.push(89) s.push(34) s.push(91) print(s.pop()) print(s.pop()) s = Stack2(10) s.push(23) s.push(65) s.push(89) s.push(34) s.push(91) print(s.pop()) print(s.pop())
name = " linfan " print("Hi " + name + ",would you like to learn some Python today?") print(name.lower()) print(name.upper()) print(name.title()) says = "Beautiful is better than ugly." print(name.strip() + " said: " + says)
import math from time import sleep from os import system, name def clear(): #windows if name == 'nt': _ = system('cls') # linux e mac else: _ = system('clear') def main(): print("-------------------------------------") print(" ") print("Programa de Progação Eletrogmanética") print("Feito pelo aluno Marcus Vinícius de Souza Feitosa") print(" ") print("-------------------------------------") print(" ") frequencia = float(input("Digite a frequencia em MHz: ")) condutividade = float(input("Digite a condutividade em mS/m: ")) epsilon_rel = float(input("Digite a constante dieletrica: ")) d1 = float(input("Digite a distancia d1 em km: ")) Eo=float(input("Digite o campo elétrico em mV/m: ")) x= (18 *condutividade)/frequencia b_linha = math.degrees(math.atan((epsilon_rel-1)/x)) b_2linha = math.degrees(math.atan((epsilon_rel)/x)) b = 2*b_2linha - b_linha p = (0.5817*(frequencia**2) *d1*((math.cos(math.radians(b_2linha)))**2))/(condutividade*math.cos(math.radians(b_linha))) A = (2+0.3*p)/(2+p+0.6*(p**2)) At = A-(math.sqrt(p/2)*math.exp(((-1)*5*p)/8)*math.sin(math.radians(b))) E=((Eo*At)/(d1*1000.0))*(10**6) Edbu= 20*math.log10(E) print("") print("") print('x: {}'.format(x)) print('b_linha: {}º'.format(b_linha)) print('b_2linha: {}º'.format(b_2linha)) print('b: {}º'.format(b)) print('p: {}'.format(p)) print('A1: {}'.format(A)) print('At: {}'.format(At)) print('E: {} uV/m'.format(E)) print('Edbu: {} dBu'.format(Edbu)) print("") print("") main() while True: escolha = input("Digite 'nov' para calcular novamente ou qualquer coisa para sair: ") if escolha == 'nov': clear() main() else: print("MUITO OBRIGADO POR UTILIZAR O SOFTWARE :) !") sleep(3) break
#%% 1.1 Linear Model # regression: opposite of progression from sklearn import linear_model regression = linear_model.LinearRegression() regression.fit([[0, 0], [1, 1], [2, 2], [3, 3]], [0, 1, 2, 2], sample_weight=None) regression.coef_ # %% import matplotlib.pyplot as plt x = [i for i in range(10)] y = [2*i for i in range(10)] plt.plot(x,y) plt.xlabel('x-axis') plt.ylabel("y-axis") plt.scatter(x,y) # %% # %% from sklearn import datasets from sklearn.model_selection import train_test_split import numpy as np iris = datasets.load_iris() X = iris.data y = iris.target """ print(X.shape) print(y.shape) """ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # test_size is the percentage of the dataset for validing the training Dataset # .shape is the size of the dataset for each job print(X_train.shape) print(X_test.shape) print(y_train.shape) print(y_test.shape) # %% import numpy as np import pandas as pd from sklearn import neighbors, metrics from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder data = pd.read_csv("car.data") """ print(data.head()) """ # X are the labels # .values shows in Matrix form(string) X = data[['buying', 'maint', 'safety']].values y = data[['class']] print(X,y) # CONVERSION1 this is for converting the string label into number so the ML can work on labelencoder = LabelEncoder() for i in range(len(X[0])): X[:,i] = labelencoder.fit_transform(X[:, i]) # 3 is vhigh, 2 is high etc.... # CONVERSION2 this method has a rule label_mapping = { 'unacc':0, 'acc':1, 'good':2, 'vgood':3 } y['class'] = y['class'].map(label_mapping) print(X) y = np.array(y) # conversion into numpy array print(y) # %%
#!/usr/bin/env python import sys import datetime from datetime import timedelta from palindrome.products import largest_palindrome desc = '''Find the largest palindrome made from the\ product of two 3-digit numbers.''' start = datetime.datetime.now() result = largest_palindrome(3) finish = datetime.datetime.now() msg = '''That largest palindrome with two 3-digit factors is {0:,} It's factors are {1} & {2} Finished in {3} milliseconds''' delta = finish - start print msg.format(result.palindrome, result.factor1, result.factor2, (delta.seconds * 1000) + (delta.microseconds/1000.0))
from processUpdates import * def main(): # Main simply makes use of the function processUpdates to process the files. # ... main provides two files: a "data file" with the geographical information and an "update file" with # the list of updates # ... the function processUpdates ensures that each exists and IF NOT, it will prompt for new file names or # give the user the option to quit. If they do exist, then it tries to process them. It should also # skip lines if there is a problem processing the line, e.g. bad values, incorrect format, etc. # # Main prints an initial message, prompts for the two file names and then invokes the function processUpdates print() print(40*"*") print("*** Updating country files") print() cntryFileName = input("Enter name of file with country data: ") updateFileName = input("Enter name of file with country updates: ") result = processUpdates(cntryFileName,updateFileName) print() print(40*"*") if result: print("*** Updating successfully completed") else: print("*** Updating NOT successfully completed") main()
import math import random import sys from copy import deepcopy from time import time import numpy as np from division import Division probability_configuration = 100 initial_temperature = 5_000 temperature_change_factor = 0.0001 def get_neighbour(division: Division) -> Division: neighbour_division = deepcopy(division) if random.choice([True, False]): neighbour_division.get_random_block().set_random_value() return neighbour_division else: block = neighbour_division.get_random_atypical_size_block() if block is None: return get_neighbour(division) else: neighbourhood = neighbour_division.get_neighbour_blocks(block, up_down=block.higher, left_right=block.widen) if neighbourhood: neighbour_division.change_size(random.choice(neighbourhood), block) return neighbour_division else: return get_neighbour(division) def simulated_annealing(max_time, initial_division) -> Division: def probability_for_worse_solution(): return 1 / (1 + math.e ** (probability_configuration * (new_distance - current_distance) / temperature)) end_time = time() + max_time temperature = initial_temperature current_division = initial_division current_distance = current_division.count_distance() best_division = current_division best_distance = current_distance temperature_change = 1 - temperature_change_factor while time() < end_time: new_division = get_neighbour(current_division) new_distance = new_division.count_distance() temperature *= temperature_change if (new_distance < current_distance or (new_distance >= current_distance and random.random() < probability_for_worse_solution())): current_division = new_division current_distance = current_division.count_distance() if current_distance < best_distance: best_division = current_division best_distance = current_distance return best_division if __name__ == '__main__': t, n, m, k = input().split() t, n, m, k = float(t), int(n), int(m), int(k) matrix = np.array([input().split() for i in range(n)], np.uint8(1)) Division.data = matrix result = simulated_annealing(t, Division(k)) print(result.count_distance()) print(result, file=sys.stderr)
class permutation: def palindromepermutation(a): dic ={} for i in a: if i not in dic.keys(): dic[i] = 0 dic[i] = dic[i]+1 c=0 for i in dic: c += dic[i]%2 return c<=1 obj = permutation() a = "aba" obj.palindromepermutation(a)
# coding: utf-8 # ## Unit 03 Lesson 03 # ####Why : Do Welthier countries provide better education? # ####Where : https://courses.thinkful.com/data-001v2/lesson/3.3 from bs4 import BeautifulSoup import requests import pandas as pd # URL with data url = "http://web.archive.org/web/20110514112442/http://unstats.un.org/unsd/demographic/products/socind/education.htm" # Getting data from the web and storing for soup analysis r = requests.get(url) soup = BeautifulSoup(r.content) # In[9]: data = [] # I only consider the 7th table table = soup.findAll('table')[6] # I take only the 2nd table within the table where I have data I want table = table.findAll('table')[1] rows = table.findAll('tr') for row in rows: # Iterate over column. This scripte take account for blank space too cols = row.find_all('td') # This allow me to remove all the tag between <> cols = [ele.text.rstrip() for ele in cols] data.append([ele for ele in cols]) # drop first 6 row data = data[5::] # I obtain a list of of list with 12 elements each, blank spaces # included. # Dataframe creation col = ['country','year','','','total','','','men','','','women',''] school_df = pd.DataFrame(data,columns=col) # Drop blank column school_df.drop('', axis=1, inplace=True) # Transform string to int school_df.year = school_df['year'].apply(int) school_df.total = school_df['total'].apply(int) school_df.men = school_df['men'].apply(int) school_df.women = school_df['women'].apply(int) school_df = school_df.set_index('country') # save school to csv school_df.to_csv('data/school.csv',encoding='utf-8') # ## Create a gdp dataframe for years 1999 to 2010 # Starting from world bank .csv data, extract data for GDP for each country, in year range 1999 to 2010 in order to compare the GDP value with the school expectancy. # In[33]: # Why : Compare GDP to Educational Attainment # Where : https://courses.thinkful.com/data-001v2/project/3.3.4 # Read the csv data (skip the first 2 rows) gdp_df_row = pd.read_csv('world bank data/ny.gdp.mktp.cd_Indicator_en_csv_v2.csv',skiprows=2) # Make a first dataframe for only Country name to indicator name column gdp_df1 = gdp_df_row.ix[:, 'Country Name'] # Make a first dataframe for only years 1999 to 2010 (as the school life expectancy dataframe (school_df)) gdp_df2 = gdp_df_row.ix[:, '1999':'2010'] # concatenate the two dataframe to create a unique dataframe gdp_df = pd.concat([gdp_df1, gdp_df2], axis=1) # rename the column 'Country Name' in 'country' to match the school_df gdp_df = gdp_df.rename(columns = {'Country Name':'country'}) # Now gdp_df is a dataframe with following columns: country | 1999 | 2000 | ... | 2010 , where for each year we have a GDP value. I need to reshape the dataframe in order to have 3 columns: Country | Year | GDP to make analysis with the schhol_df. # In[ ]: # reshape the dataframe (using stack fonction) in order to have 3 columns (Year | GDP | Country) id = gdp_df.ix[:, ['country']] gdp_df = pd.merge(gdp_df.stack(0).reset_index(1), id, left_index=True, right_index=True) gdp_df.columns = ['year','GDP','country'] # delete first line of each country gdp_df = gdp_df[gdp_df.year != 'country'] gdp_df = gdp_df.set_index('country') # Transform string to int gdp_df.year = gdp_df['year'].apply(int) gdp_df.GDP = gdp_df['GDP'].apply(int) # save gdp to csv gdp_df.to_csv('data/gdp.csv',encoding='utf-8')
#Class Average for Three Sample Students Lloyd = { "name":"Lloyd", "homework": [90,97,75,92], "quizzes": [ 88,40,94], "tests": [ 75,90] } Alice = { "name":"Alice", "homework": [100,92,98,100], "quizzes": [82,83,91], "tests": [89,97] } Tyler = { "name":"Tyler", "homework": [0,87,75,22], "quizzes": [0,75,78], "tests": [100,100] } def average(stuff): return sum(stuff)/len(stuff) def getLetterGrade(score): score = round(score) if score >= 90: return "A" elif 90 > score >= 80: return "B" elif 80 > score >= 70: return "C" elif 70 > score >= 60: return "D" elif 60 > score: return "F" def getAverage(kid): bar = average return bar(kid["homework"])*.1 + bar(kid["quizzes"])*.3 + bar(kid["tests"])*.6 def getClassAverage(students): group = [] for i in students: group.append(getAverage(i)) return average(group) students = [Lloyd,Alice,Tyler] print getClassAverage(students) print getLetterGrade(getClassAverage(students))
import random from math import sqrt running = True while running: num = int(input("Hey, I'll give you some gold for primes!\n")) if num > 1: sqrtNum = int(sqrt(num)) print('sqrtNum:' + str(sqrtNum)) # list of integers from 2 to num primes = [] for i in range(2, num+1): primes.append(i) # loop through the square root of num for i in range(2, sqrtNum+1): print('hum... i:' + str(i)) if i in primes: for j in range(i*2, num+1, i): print('hum... j:' + str(j)) if j in primes: print('hum... removed j:' + str(j)) primes.remove(j) # check if num is prime or not if num in primes: running = False print(f'Yes! {num} is a PRIME! Here you go, {int(random.random() * 1000) + 10 } gold, your reward!') else: print(f'NO! {num} is NOT a prime! Don\'t try to trick me, stranger!\n\n') else: print('Oops, try again! We need a positive number greater than 1!')
import sqlite3 import os def create_schema(): conn = sqlite3.connect('tabla.db') c = conn.cursor() # Ejecutar una query c.execute(""" DROP TABLE IF EXISTS Number; """) # Ejecutar una query c.execute(""" CREATE TABLE Number( [id] INTEGER PRIMARY KEY AUTOINCREMENT, [number] INTEGER NOT NULL ); """) conn.commit() conn.close() def insert_product(numero): conn = sqlite3.connect('tabla.db') c = conn.cursor() values = [numero] c.execute(""" INSERT INTO Number (number) VALUES (?);""", values) conn.commit() conn.close() print(numero, "success") def get_product(): conn = sqlite3.connect('tabla.db') c = conn.cursor() c.execute("""SELECT * FROM Number;""") result = c.fetchone() conn.commit() conn.close() return result
''' Settings helper for python apps, save, recall, and reset-to-default application settings. In various application you often have 'settings' that need to be saved or recalled from a file, these classes helps do that. There are two important classes: * SettingsHelper() * SettingsTool() The SettingsHelper() The intent is that each major class in your app has a "setting helper" object, constructed like this: class Foo(object); def __init__( self, ... ): self.settings = SettingsHelper( sectionname, default_values ) The settings can then be saved or read from a INI file, via the SettingsTool() class, which uses the ConfigParser class. Note the "sectionname" must be unique across the entire application. Example: a camera vision system might have settings like this: self.camera = SettingsHelper( "cam0", default_camera_values ) print("Camera section: %s" % self.camera._section ) # Where "_section" might be: "cam0", and "cam1" print("Camera id: %d" % self.camera.id ) print("Camera h: %d" % self.camera.height ) print("Camera w: %d" % self.camera.width ) Only simple settings are supported, and must be one of: None, str, bool, int, str, float Note the value "None" uses the magic string "_None_" in the INI file The SettingsTool() The class SettingsTool() is used to read or save the settings to a file it manages (via a module global variable) to track all settings through out the application so that the can easily be saved or recalled. In addition, sometimes users screw up settings and you need the ability to reset all settings to their "factory defaults" Note: Multiple settings files can be supported, see the source for details. For example: tool = SettingsTool() tool.save_to_ini( "somefilename.ini" ) Then later: tool.load_from_ini( "somefilename.ini") Both the tool, and the helpers contain some hooks or callbacks as defined by class SettingsCallbacks() that can be used to add more functionality. FUTURE: Today this uses a ConfigFile to save the data. It could in the future use a json file Or possibly a pickle file. DO NOT DO THIS: # Step 1 defaults = { 'id' : 123, 'height' : 480, 'width': 640 } self.settings = SettingsHelper( 'camera', defaults ) # Step 2 - Do do this to set defaults # they are already set for you. self.settings.id = 123 ''' from .exceptions import * from .helper import * from .tool import *
import random from typing import List, Tuple, Sequence, TypeVar, Optional SUITS = "♠ ♡ ♢ ♣".split() RANKS = "2 3 4 5 6 7 8 9 10 J Q K A".split() Card = Tuple[str, str] Deck = List[Card] Choosable = TypeVar("Choosable", str, Card) def create_deck(shuffle: bool = False) -> Deck: """Create a new deck Args: shuffle (bool, optional): If requires shuffle. Defaults to False. """ deck = [(s, r) for r in RANKS for s in SUITS] if shuffle: random.shuffle(deck) return deck def deal_hands(deck: Deck) -> Tuple[Deck, Deck, Deck, Deck]: """Deal the cards in the deck into four hands Args: deck (list[tuple[str, str]]): Incoming deck """ # Jump by 4 in increment return (deck[0::4], deck[1::4], deck[2::4], deck[3::4]) def choose(items: Sequence[Choosable]) -> Choosable: return random.choice(items) def player_order( names: List[str], start: Optional[str] = None ) -> List[str]: if start is None: start = choose(names) start_idx = names.index(start) return names[start_idx:] + names[:start_idx] def play(): """Play a 4-player card game """ deck = create_deck(True) names = "P1 P2 P3 P4".split() # Split into an objects of player: cards # { P1: [('♠', '2'), ('♠', '3')]} hands = {n: h for n, h in zip(names, deal_hands(deck))} start_player = choose(names) turn_order = player_order(names, start_player) # Randomly play cards from each player's hand until empty while hands[start_player]: for name in turn_order: card = choose(hands[name]) hands[name].remove(card) print(f"{name}: {card[0] + card[1]:<10}", end="") print() play()
def identitym(n): for i in range(n): for j in range(n): if (i==j)==1: print("1",sep="",end="") else: j=0 print("0",sep="",end="") print() return n n=int(input("Enter size of identity matrix:")) k=identitym(n)
class Word: """ Simple word implementation. """ def __init__(self, input_word: list): self._word = input_word @property def word(self) -> list: return self._word def get_word_length(self): return len(self._word) def get_letter(self, index) -> int: return self._word[index]
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.size=0 def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node self.size+=1 def deleteNode(self, key): temp = self.head if (temp is not None): if (temp.data == key): self.head = temp.next temp = None self.size-=1 return while (temp is not None): if temp.data == key: break prev = temp temp = temp.next if (temp == None): return prev.next = temp.next temp = None self.size-=1 def printList(self): temp = self.head while (temp): print(" {0}".format(temp.data)) temp = temp.next ```Remove Dups! Write code to remove duplicates from an unsorted linked list.``` def removeDups(self): vals=[] runner=self.head while runner!=None: if runner.data in vals: self.deleteNode(runner.data) else: vals.append(runner.data) runner=runner.next ```Implement an algorithm to find the kth to last element of a singly linked list``` def kthToLast(self,index): runner=self.head for i in range(index): runner=runner.next while runner!=None: print(" {0}".format(runner.data)) runner=runner.next def kthToLast(head,k): if head ==None: return 0 index = kthToLast(head.next,k)+1 if index == k: print( head.value) return index ```Implement an algorithm to delete a node in the middle (i.e., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node``` def deleteMiddle(self,node): if node==None or node.next==None: return False node.next=node.next.next return True ```Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the "right partition"; it does not need to appear between the left and right partitions.``` def partition(self,num): runner = self.head new_ll=LinkedList() while runner!=None: temp=runner.data if temp<num: new_ll.push(runner.data) runner=runner.next runner = self.head while runner!=None: temp=runner.data if temp>=num: new_ll.push(runner.data) runner=runner.next return new_ll
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 22 16:18:19 2018 @author: karina """ def insertionSort(mylist): for j in range(len(mylist)): for i in range(j): if j-i-1<0: break if mylist[j-i-1]>mylist[j-i]: teemp = mylist[j-i] mylist[j-i]=mylist[j-i-1] mylist[j-i-1]=teemp return mylist if __name__=="__main__": list_ = [3,3,444,5,3,1,0,34,5,7] print(insertionSort(list_))
import rule from read import printPuzzle,read #the main loop so that it will always ask an input then solve the puzzle def mainLoop(): state=read()['puzzle'] assignment=backtracking(state) temp=assignAll(assignment,state) #the final solution as a 2d list print('the answer is:') printPuzzle(temp) def backtracking(state): #state is the initial state immediately after reading from stdin U=rule.getUnassigned(state) #a list of all unassigned variables A = {} #a dictionary that maps: unassigned coordinate-->None return backtrackingHelper(A,U.copy(),state) #this method receives assignments(A,dictionary), a list of unassigned coordinates(U), an initial state #it returns a new assignment to solve the puzzle with initial state "state" def backtrackingHelper(A,U,state): current = assignAll(A, state) printPuzzle(current) if rule.solutionCheck(current):#all unassigned cell have been assigned return A #and the number constraint is satisfied elif len(U)>0: (i,j)=U.pop(0) for option in ['b','_']: #one coordinate has 2 possible assignment B = A.copy() B[(i, j)] = option if ((i,j) not in rule.goodCells(current)) and option=='b': continue temp=assignAll(B,state) if not rule.numberConstrain(temp): continue result=backtrackingHelper(B,U.copy(),state) #recursive call with new assignments B if result is not None: # WE HAVE no solution in this case return result return None #this method receives an initial state and apply assignment A to it then return its copy def assignAll(A,state): result=state.copy() for (i,j),option in A.items(): result[i][j]=option return result
#Write a program to read a text file and display the count of vowels and consonants in the file. count_vowel=0 count_waste=0 count=0 count_consonant = 0 vowels=['a','e','i','o','u'] with open('source.txt', 'r') as fh: for line in fh: words = line.split() for i in words: for letter in i: count+=1 if letter in vowels: count_vowel+=1 if (letter.isnumeric()): count_waste+=1 elif letter not in vowels: count_consonant+=1 count_consonant = count_consonant - count_waste print(count_vowel) print(count_consonant) print(count_waste) print(count)
# str formatting # Write this in str formatting (format() or C formatting): # Hello, I was wondering if 000Jess000 got the same answer as I did for Question 3? I got 1.45. # Make sure to use the right formats (i.e., if it's a float, use #f or #.#f # Using str formatting (either format() or C formatting) draw this: # ^^^----^^^ # 0 0 # o # --- # vvv----vvv # | # | # | # | # ---- ---- # | | # Hint: Look at the picture line by line # Here is the solution: # print("{:^^10}".format("----")) # print("{0:<5}{0:>5}".format(0)) # print("{:^10}".format('o')) # print("{:^10}".format('---')) # print("{:v^10}".format("----")) # print("{0:^10}\n{0:^10}\n{0:^10}\n{0:^10}".format('|')) # print("{0:<5}{0:>5}".format('----')) # print(" {0:<4}{0:>4}".format('|')) # for loop # Create a dictionary using strings: A, B, and C with their corresponding values: 1, 2, 3 # Create a three different for loops that iterate over its items(), keys(), and values() # Create a list and iterate the items in this list and print() them # Using the same list, iterate and print() the item indexes # Using the same list, iterate over every other item (e.g., if it was [1, 2, 3, 4], it would print: [1, 3] (skips 2, 4) # debug this nested for loop to see for yourself how a nested for loop works for i in range(3): print(' i', end='') for n in range(3): print(' n', end='') for k in range(3): print(' k', end='') # printed the iterations to show you the general pattern of a nested for loop # while loop # while loop requires to have a flag to "turn off" the while loop flag = True # initially True m = 0 # initially zero while flag: print("Flag hasn't turned off the while loop") m += 1 if m == 3: flag = False # flag turns off when the body of the while loop has done its job # the "job" in this case is for m == 3 # Replace the flag with a break to see what break is like # Try: If m == 3, break, else: continue # if else statements print("These are the main compound booleans: and, or, not (also called negation)") # Create the follow if else statements: # First, I'll give you an example # if 1 equals 2 and 4 is greater than 2, print("True"), else: print("False") # if 1 == 2 and 4 > 2: # print("True") # else: # print("False") # What do you think this will print? # Try replacing the == with is # Try it yourself: # If 12 == 7 or 12 == 24 - 12, print True # You have x = 12. If lambda with the variable x with the complex number x**2 equal 144, print True # If you eat supper and do not yell or remain quiet, you will get dessert. (Assume supper and yell are variables) # See how these are equivalent: If you eat supper, you will get dessert. If you will not eat supper, then no dessert. # First is a "positive" version while the latter is the negation but they're essentially doing the same thing # Solution for the harder ones: # if lambda x: x**2 == 144: # print("That is true, yes.") # if supper and (not yell or quiet): # print("Dessert") A = True B = False # Which will print? if A and B: print('Wow.') elif not A and not B: print("Hmmm.") elif not A and B: print("That's something.") else: print("Ya got me.") # Why are the outputs for these if statements different despite having the same conditions? print() # Empty print statements make space (look at the output to see this effect) if A: print("A") if B: print("B") if not B: print("not B") print() if A: print("A") elif B: print("B") elif not B: print("not B") print() # Try to make a nested if else statement to get familiar with these # Think about how you would use complex booleans with a while loop... # Remember that the order of the compound boolean may matter due to Lazy Evaluation (keep this in mind) # functions # Create a main() and make sure to call it # Create a function that adds its parameter int m by 1 # Call this function in main() and print this function's result in main() # Do you need a return statement here? Why do you think that is or isn't the case? # If you were not going to use a return statement, how would you display the result? # Create a lambda function for Pythagoras Theorem # print the result of lambda using whatever numbers you'd like # Use debugger to see for yourself how a generator functions works: def generatorFunction(m): yield 2 + m yield 2 + m yield 2 + m def generatorFunction1(n): # I provided this to show you a for loop in a generator function for i in range (3): yield n + 1 m = 0 for n in generatorFunction(m): m = n print(m) # What do you think this will print? Was it what you expected? # Note: for generator functions, you can yield it for as long as you'd like through the whole program g = 0 for e in range(3): print(next(generatorFunction(g))) # this is another way to call a generator function # Try debugging this: def foo(m): return foo2(m + 3) def foo2(n): return n + 3 def main(): print(foo(3)) main() # solutions: # def foo(m): # return m + 1 # # def main(): # number = foo(1) # print(number) # y = lambda a,b: (a**2 + b**2)*(1/2) # print(y(2, 2)) # # main() # Side Effects will indefinitely be encountered while you're doing your projects! Watch out for them.
# should have random imported import random def chooseNumber(): # generating the number in the range 1-100 rand_num = random.randint(1, 100) return rand_num def main(): win = False guessAmount = 10 n = 0 # call and receive the generated num rand_num = chooseNumber() # should continue to prompt until they guess correctly while not win and n != guessAmount: user_guess = input("Guess a number between 1-100: ") print() # should check for valid type if user_guess.isdigit(): user_guess = int(user_guess) # should check that the int is within range if 1 <= user_guess <= 100: # should compare the nums and print the appropriate messages if user_guess == rand_num: print("Congratulations! The number you guessed was", user_guess, "and the number generated was", rand_num, '!') print("Thank you for playing...Goodbye!") # makes sure to exit the program win = True else: print("Sorry!", user_guess, "is not the number.") if int(user_guess) > rand_num: print('You guessed too high.', end=' ') else: print('You guessed too low.', end=' ') print("Try again\n") n += 1 else: # warning message print(user_guess, "is out of range\n") else: # warning message print("'" + user_guess + "' is not a valid number\n") if not win: print("Unfortunately you ran out of guesses. You lose. Goodbye!") main()
from math import * a=float(input()) b=float(input()) c=float(a/b) print(str(round(degrees(atan(c)))) + '°')
import sqlite3 conn = sqlite3.connect('friends.sqlite') cur = conn.cursor() #cur.execute('''DROP table if exists 'school' ''') #cur.execute(''' #create table school('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'schoolName' text, 'num' numeric) #''') first = input('Enter School ') cur.execute("insert into school(schoolName,num) values(?, 4)",(first,) ) for row in cur.execute("select * from school"): print(row)
import os import csv # cvs file path csvpath = os.path.join('Resources', 'election_data.csv') #creating empty variables tot_votes = 0 winner = 0 votes = 0 win_votes = 0 # dictionary for counting candidates and their votes poll_count = {} # read csv file with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') # to skip the header row csv_header = next(csvreader) csvreader = list(csvreader) #calculations for i in csvreader: # find the total votes tot_votes = tot_votes + 1 # counting votes per candidates cand = i[2] # checking for same candidates if cand in poll_count: poll_count[cand] = poll_count[cand] + 1 else: #add vote for candidate poll_count.update({cand:1}) #calculate the percentage and winner # dictionary for holding results poll_results = {} for cand, votes in poll_count.items(): poll_results[cand] = str(votes*100/tot_votes) +'% (' + str(votes)+ ')' if votes > win_votes: win_votes = votes winner = cand # printing the analysis to the terminal print("Election Results") print("--------------------------------------------------------") print(f"Total Votes: {tot_votes} ") print("--------------------------------------------------------") #looping dictionary for results for i, j in poll_results.items(): print(i + ': '+ j) print("--------------------------------------------------------") print(f"Winner: {winner}") print("--------------------------------------------------------") # exporting the analysis to a text file output_path = os.path.join("ElectionResults.txt") # Open the file using "write" mode with open(output_path, 'w', newline='') as txtfile: txtfile.write("Election Results") txtfile.write('\n' + "---------------------------------------------------------"+ '\n') txtfile.write(f"Total Votes: {tot_votes}") txtfile.write('\n' + "---------------------------------------------------------"+ '\n') #looping dictionary for results for i, j in poll_results.items(): txtfile.write( i + ': '+ j + '\n') txtfile.write("---------------------------------------------------------"+ '\n') txtfile.write(f"Winner: {winner}") txtfile.write('\n' + "---------------------------------------------------------")
''' Puzzle 1 day three ''' import math def printMatrix(M): for row in M: print row print length = 1 # the length of the 'snake' myNumber = 25 m = int(math.ceil(math.sqrt(myNumber))) M = [[0] * m for i in range(m)] M[2][1:5] = [2 for i in [0] * 4] M[1:5][2] = [3] * 4 printMatrix(M) # coord = round(m / 2) exit(0) coord = [m / 2, m / 2] coord = map(round, coord) theta = 0 index = 1 for i in range(8): theta = i * math.pi / 2 direction = map(int, [math.cos(theta), math.sin(theta)]) coord += direction M[int(coord[1])][int(coord[2])] = index index = index + 1 print direction printMatrix(M)
import numpy as np class Step: def apply(self, x): if x < 0: return 0 else: return 1 def derivative(self, x): return 0 class Sigmoid: def apply(self,x): return 1 / (1 + np.exp(-x)) def derivative(self, x): return self.apply(x) * (1 - self.apply(x)) class Tanh: def apply(self, x): return (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)) def derivative(self, x): return 1 - self.apply(x)**2
#!/usr/bin/env python3 import random import skilstak.colors as c welcome_message = ''' Hello and welcome to the 8ball. Ask your question below. ''' answers = [ 'yes', 'no' ] def welcome(): print(c.clear + welcome_message) def ask(prompt): answer = input(prompt).strip().lower() return answer def bye(): print("bye bye") exit() def handle_question(): question = ask("> " + c.b3) print(c.reset + end='') if question == 'bye' or question == 'goodbye': bye() else: answer = random.choice(answers) print(answer) if __name__ == '__main__': try: welcome() while True: handle_question() except KeyboardInterrupt: exit()
# Sachin # Get elements of an iterator one at a time, with access to the next element class Stream: def __init__(self, iterator): self.iterator = iter(iterator) self.peak() def peak(self): try: self.next = next(self.iterator) except StopIteration: self.next = None def get(self): ret = self.next self.peak() return ret
import socket from threading import Thread def thread(): while True: data = conn.recv(1024) print('Client Request :' + data.decode()) if data.decode() == 'quit' or not data: print("Client Exiting") answer = input('Do you want to continue?:') if answer.lower().startswith("y"): print("ok, carry on then") elif answer.lower().startswith("n"): print("ok, sayonnara") conn.close() exit() data = input('Server Response:') if data == 'Shutdown' or not data: conn.sendall(data.encode()) print("Server Exiting") conn.close() exit() conn.sendall(data.encode()) host = socket.gethostname() port = 3333 s = socket.socket() s.bind((host,port)) s.listen(5) print("Waiting for clients...") while True: conn,addr = s.accept() print("Connected by ", addr) pr = Thread(target=thread) pr.start() conn.close()
# -*- coding: utf-8 -*- # listeyi dosyaya yazdir. students = ["Mehmet", "Ali", "Cem", "Hakan", "Murat"] fileToAppend = open("students.txt","a") for student in students: fileToAppend.write(student + "\n") fileToAppend.close() fileToRead = open("students.txt") print(fileToRead.read()) fileToRead.close()
# other numpy array methods. import numpy as np # Linspace - is ued to create a equaly displaced number with an starting and end point. lint = np.linspace(1, 2, 5) # it will create [1. 1.25 1.5 1.75 2. ] print(lint) # create a arrray of zeros # one dimensional array with 4 zero elements. zeros = np.zeros(4) print(zeros) # [0. 0. 0. 0.] # two dimensional array with 1 rqw and 4 colums elements. zeros2 = np.zeros((2, 4)) print(zeros2) # [[0. 0. 0. 0.] # [0. 0. 0. 0.]] # array of 1's one1 = np.ones(5) print(one1) # A matrix with 3 rows and three colums with each element = 1 one2 = np.ones((3, 3)) print(one2) # identity matrix using numpy identMatrix = np.eye(4) # A 4x4 identity matrix. print(identMatrix) # random int using numpy randNumber = np.random.randint(50,60) # between 50 to 60, 60 is exclusive print(f"\n The random integer is : {randNumber}") # geting an array of random numbers using numpy randint arrayOfRandomInt = np.random.randint(1,50,10) # array of 10 elemnts range between 1 to 50 print(arrayOfRandomInt) # ([10,30,45,12,32,18,44,29,31,27]) # max value in an array and index of it. print(f" Index - {arrayOfRandomInt.argmax()} Value - {arrayOfRandomInt.max()}") # min value in an array and index of it. print(f" Index - {arrayOfRandomInt.argmin()} Value - {arrayOfRandomInt.min()}") # datatype nums = np.arange(0,10) print(nums.dtype) # int32
import numpy as np arr = np.arange(0,25) # arange method is ued to create an array with an starting and ending elements. we can also provide step size like this. arr = np.arange(0,10,2) and it will generate [0,2,4,8] print(arr) list1 = [1,2,3,4,5] arr1 = np.array(list1) # array method can convert a python list into an array print(arr1) matrix = arr.reshape(5,5) # reshape method is used to convert an array into a two dimensional array or a matrix. print(matrix) print(matrix[4,4]) # By using this syntax we can access a particular element of the martix. here 4,4 is the position of element in the matrix. def generator(): ''' Generator method is defind for generating an array of numbers. it ask for array length when you use it. It is basically a multiline comment. but it used to describe the use of the method. whenever you hover on this method it will provide you this ''' num = int(input('Enter number of elements you want in your array: ')) arr = np.arange(0,num) return arr myArray = generator() myArray = myArray.reshape(5,5) print(myArray)
name = "hello, I am lakshit. And lakshit is a software developer." length = len(name) # length of string print(length) find1 = name.find('lakshit') print(find1) # find method replaceValue = name.replace('lakshit','Abhishek') # replace method trimName = name.strip() #trim the string print(trimName) lowerCase = name.casefold() #lowercase print(lowerCase) countingChar = name.count('lakshit') #counting characters print(countingChar) encodeName = name.encode() print(encodeName) number = "12345" # isNumeric = number.isnumeric() # checking if string contains all numeric values print(isNumeric) # The split() method splits a string into a list. friends = "lakshit kamal rajan divyanshu sourabh" friendsList = friends.split(); print(type(friendsList), " - ", friendsList)
# -*- coding: utf-8 -*- """ Created on Fri May 29 19:08:55 2020 @author: Ankit Dulat """ import numpy as np import matplotlib.pyplot as plt def f(a,b): #given function if (a**2+b**2)<=1: return 1.0 else: 0.0 n=100000 #no. of random no. generated k=0 #for count of random numbers falling within integrand function r=1 # radius of circle #intergration limit a=-1 b=1 #To draw a circle, data generated theta=np.linspace(0,2*np.pi,100) x1=r*np.cos(theta) y1=r*np.sin(theta) x=np.random.uniform(a,b,n) #Random no. generated covering the integrand function y=np.random.uniform(a,b,n) plt.figure(figsize=(10,5)) plt.subplot(121) plt.scatter(x,y,s=5,rasterized=True) plt.plot(x1,y1,c= "red") plt.xlabel("$x$") plt.ylabel("$y$") plt.title("Random numbers alongwith circle") x2=[] y2=[] for i in range(n): if f(x[i],y[i])==1: k +=1 x2.append(x[i]) y2.append(y[i]) plt.subplot(122) plt.scatter(x2,y2,s=5,c="orange",label='Selected random points',rasterized=True) plt.plot(x1,y1,c= "red") plt.xlabel("$x$") plt.ylabel("$y$") plt.legend() plt.savefig("Q8.pdf") plt.show() area=((b-a)**2)*k/n print("Area of circle is =",area) radius=1.0 def nSphereVolume(dim, iteration): p = 0 for i in range(iteration): r = np.random.uniform(-1.0, 1.0, dim) distance = np.linalg.norm(r) if distance < radius: p += 1 return np.power(2.0, dim) * (p / iteration) print("voluem of 10-d sphere of unit radii is =",nSphereVolume(10, 100000))
import timeit from scipy.special import factorial num = int(input("Enter a number whose factorail you want to find out\n: ")) start = timeit.default_timer() print("Factorial of",num,"is",factorial(num)) stop = timeit.default_timer() print('Time taken in second :', stop - start)
# -*- coding: utf-8 -*- """ Created on Sat Nov 9 17:30:34 2019 @author: Ankit Dulat """ S='mumbai' # comprehension method d=[(i,ord(i)) for i in S] print(list(d)) unicod1=[ ord(i) for i in S ] t=sum(list(unicod1)) print("Sum of unicode points of all letters of mumbai is:",t) print("The list that contain the Unicode points by COMPREHENSION:",list(unicod1)) # map method unicod2=list(map(lambda x: ord(x),S)) print("The list that contain the Unicode points by using MAP:",list(unicod2)) # Using List L=[] for i in S: m = ord(i) L.append(m) print("The list that contain the Unicode points by using LIST is:",L)
# -*- coding: utf-8 -*- """ Created on Sat Nov 9 15:50:27 2019 This code generates the power of 2 list L(8 terms) by 3 different method and calculate the time it take in doing so for each method @author: Ankit Dulat """ L=[] for i in range (0,8): L.append(2**i) print(L) import timeit mycode=""" L=[] for i in range (0,8): L.append(2**i) """ t=timeit.timeit(stmt=mycode,number=1000) print("Time taken to append the list (2**x inside the loop):",t/1000) mycode=""" L=[] def f(n): return 2**n for i in range (0,8): L.append(f(i)) """ t=timeit.timeit(stmt=mycode,number=1000) print("Time taken to append the list by defining a function (2**x outdide the loop):",t/1000) mycode=""" L=[] g=lambda x:2**x for i in range (0,8): L.append(g(i)) """ t=timeit.timeit(stmt=mycode,number=1000) print("Time taken to append the list using 'lambda'(2**x outdide the loop) :",t/1000) """ All above method suggest that taking 2**x outside the loop doesn't improve the timing """
import numpy as np import matplotlib.pyplot as plt from scipy import interpolate x=[0,1,2,3,4,5] y=[1.0,2.0,1.0,0.5,4.0,8.0] c=interpolate.InterpolatedUnivariateSpline(x,y,k=3) s=interpolate.InterpolatedUnivariateSpline(x,y,k=2) l=interpolate.InterpolatedUnivariateSpline(x,y,k=1) x1=np.arange(0,5.1,0.1) y1=l(x1) y2=s(x1) y3=c(x1) plt.plot(x,y,'ro',x1,y1,'g--',x1,y2,'b--',x1,y3,'y--') plt.legend(['data','Linear Spline','Quadratic spline','Cubic Spline']) plt.title('Spline Interpolation') plt.xlabel('x') plt.ylabel('y') plt.savefig('spline.png') plt.show()
# Example of putting data onto OpenStreetMap # from https://programminghistorian.org/en/lessons/mapping-with-python-leaflet # Started 17 November 2019 import geopy, sys import pandas from geopy.geocoders import Nominatim, GoogleV3 # versions used in the above tutoral: geopy 1.10.0, pandas 0.16.2, python 2.7.8 inputfile=str(sys.argv[1]) namecolumn=str(sys.argv[2]) def main(): # io = pandas.read_csv('census-historic-population-borough.csv', index_col=None, header=0, sep=",") io = pandas.read_csv(inputfile, index_col=None, header=0, sep=",") def get_latitude(x): return x.latitude def get_longitude(x): return x.longitude geolocator = Nominatim() # geolocator = GoogleV3() # uncomment the geolocator you want to use # geolocate_column = io['Area_Name'].apply(geolocator.geocode) geolocate_column = io[namecolumn].apply(geolocator.geocode) io['latitude'] = geolocate_column.apply(get_latitude) io['longitude'] = geolocate_column.apply(get_longitude) io.to_csv('geocoding-output.csv') if __name__ == '__main__': main()
import math def searchInsert(nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if len(nums) == 0: return 0 diff = 9223372036854775807 index = None for i, n in enumerate(nums): if n == target: return i elif math.fabs(n-target) < diff: diff = math.fabs(n-target) index = i return index if nums[index] > target else index + 1 # there is a more elegant way to solve this problem # only have to find out how many elements are less than target # can just return len([i for i in nums if i < target]); print(searchInsert([1,3,5,6], 2))
def countingValleys(s): count = 0 prev = 0 current = 0 for move in s: if move == 'U': current += 1 if current == 0 and prev < 0: count += 1 else: current -= 1 prev = current return count if __name__ == '__main__': n = int(input()) s = input() print(countingValleys(s))
""" Math operations. """ def mean(num_list): """ Calculate the man of a list of numbers Parameters ---------- num_list: list The list to take average of Returns ------- avg: float The mean of a list Examples -------- >>> mean([1, 2, 3, 4, 5]) 3.0 """ # Check that user passes list if not isinstance(num_list, list): raise TypeError('Input must be type list') # Check that list has length if len(num_list) == 0: raise ZeroDivisionError('Cannot calculate mean of empty list') try: avg = sum(num_list) / len(num_list) except TypeError: raise TypeError('Values of list must be type int or float') return avg
# Read an integer: a = int(input()) # Read a float: b = float(input()) c = float(input()) d = float(input()) e = float(input()) f = float(input()) # Print a value: print(-1* ((a*3600 + b*60 + c) - (d*3600 + e*60 + f)) )
# Read an integer: a = int(input()) # Read a float: # b = float(input()) # Print a value: print(a // 60 , " " + str(a % 60))
# Complete the maxSubsetSum function below. def maxSubsetSum(arr): # We start with assigning two variables which we need to iterate through # the values of the array. 'i' represents the first value in the array and # 'temp_max' represents the maimum of the first two values. i, temp_max = arr[0], max(arr[:2]) # This loop executes the actual work of the function by iterating over the # array, starting by the third value of the array, up until the last value # of it. for val in arr[2:]: # While looping through the array, the function identifies the maximum # between (1) the last value, (2) the second to last value, (3) the second # to last value + the current value and (4) the current value. This # maximum will update the temp_max and the old temp_max replaces the i # value. i, temp_max = temp_max, max(i, i + val, temp_max, val) # Finally, we return the maximum after looping through the entire array return temp_max # Test array = [3, 7, 4, 6, 5] print(maxSubsetSum(array))
import random import itertools class Deck: def __init__(self): # cards are represented by an index. Easiest to sort and shuffle. self.cardindices = list(range(52)) # cards are indexed based on suits. self.cards = list(itertools.product(['club', 'diamond', 'heart', 'spade'], [*range(2,11), *'JQKA'])) # dealt can be used to store all the cards that have been dealt self.dealt = [] def shuffle(self): random.shuffle(self.cardindices) def sort(self): self.cardindices.sort() def deal(self): dealcard_i = self.cardindices.pop() self.dealt.append(dealcard_i) return self.cards[dealcard_i] def show_dealt(self): for i in self.dealt: print(self.cards[i]) def show_deck(self): for i in self.cardindices: print(self.cards[i]) def show_no_of_cards(self): return len(self.cardindices)
import tweepy from tweepy import OAuthHandler from Lab2 import Credentials import json from nltk.tokenize import word_tokenize import re #Obtain credentials for accessing the application auth = OAuthHandler(Credentials.consumer_key, Credentials.consumer_secret) auth.set_access_token(Credentials.access_token, Credentials.access_secret) #Call Twitter Auth api = tweepy.API(auth) #Obtain user user = api.me() ##################################################### #Get three tweets print('\n\nTimeline: ') # we use 1 to limit the number of tweets we are reading # and we only access the `text` of the tweet listStatus = tweepy.Cursor(api.home_timeline).items(10) for status in listStatus: print(status.text) #Get JSON format #print('\n\nJSON example: \n') #for friend in tweepy.Cursor(api.friends).items(1): # print(json.dumps(friend._json, indent=2)) #Search tweets #for tweet in tweepy.Cursor(api.search, q = "google", since = "2014-02-14", until = "2014-02-15", lang = "en").items(10): # print(tweet.text) ################### #### TOKENIZER #### ################### #Emoticon expresion emoticons_str = r""" (?: [:=;] # Eyes [oO\-]? # Nose (optional) [D\)\]\(\]/\\OpP] # Mouth )""" #Char strings regex_str = [ emoticons_str, r'<[^>]+>', # HTML tags r'(?:@[\w_]+)', # @-mentions r"(?:\#+[\w_]+[\w\'_\-]*[\w_]+)", # hash-tags r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+', # URLs r'(?:(?:\d+,?)+(?:\.?\d+)?)', # numbers r"(?:[a-z][a-z'\-_]+[a-z])", # words with - and ' r'(?:[\w_]+)', # other words r'(?:\S)' # anything else ] tokens_re = re.compile(r'(' + '|'.join(regex_str) + ')', re.VERBOSE | re.IGNORECASE) emoticon_re = re.compile(r'^' + emoticons_str + '$', re.VERBOSE | re.IGNORECASE) def tokenize(s): return tokens_re.findall(s) def preprocess(s, lowercase=False): tokens = tokenize(s) if lowercase: tokens = [token if emoticon_re.search(token) else token.lower() for token in tokens] return tokens #Search 3 tweets and tokenize it print("\n\n") for status in tweepy.Cursor(api.home_timeline).items(10): print(preprocess(status.text))
#06-Forloop.py # i travels zero thru 9 for i in range(0,10): print('Hello'+str(i)) # hello there length 11 the range goes 0 thru 10 a='hello there' for i in range(len(a)): print (i) # ==================================================
import numpy as np def remove_i(arr, i): """Drops the ith element of an array.""" shape = (arr.shape[0]-1,) + arr.shape[1:] new_arr = np.empty(shape, dtype=float) new_arr[:i] = arr[:i] new_arr[i:] = arr[i+1:] return new_arr def acceleration(i, position, G, mass): """The acceleration of the ith mass.""" ith_pos = position[i] rest_pos = remove_i(position, i) rest_mass = remove_i(mass, i) diff = rest_pos - ith_pos mag3 = np.sum(diff**2, axis=1)**1.5 result = G * np.sum(diff * (rest_mass / mag3)[:,np.newaxis], axis=0) return result def timestep(position, velocity, G, mass, dt): """Computes the next position and velocity for all masses given initial conditions and a time step size. """ N = len(position) new_pos = np.empty(position.shape, dtype=float) new_velocity = np.empty(velocity.shape, dtype=float) for i in range(N): acceleration_i = acceleration(i, position, G, mass) new_velocity[i] = acceleration_i * dt + velocity[i] new_pos[i] = acceleration_i * dt ** 2 + velocity[i] * dt + position[i] return new_pos, new_velocity def initial_cond(N, Dim): """Generates initial conditions for N unity masses at rest starting at random positions in D-dimensional space. """ position0 = np.random.rand(N, Dim) velocity0 = np.zeros((N, Dim), dtype=float) mass = np.ones(N, dtype=float) return position0, velocity0, mass def simulate(timesteps, G, dt, position0, velocity0, mass): """N-body simulation of certain timesteps.""" position, velocity = position0, velocity0 for step in range(timesteps): new_pos, new_velocity = timestep(position, velocity, G, mass, dt) position , velocity = new_pos, new_velocity return position, velocity if __name__ == "__main__": import time import h5py N = 256 # Initialize N-body conditions # Set gravitational constant to 1 Dim = 3 G=1.0 dt = 1.0e-3 timesteps = 600 path = '/Users/zhengm/src/play/python/mpi4py/' name = path + 'data_' + str(N).zfill(4) + 'nbody_seq.h5' print(name) start = time.time() position0, velocity0, mass = initial_cond(N, Dim) position, velocity = simulate(timesteps, G, dt, position0, velocity0, mass) stop = time.time() elapsed = stop - start print('Elapsed time is: %f seconds' % elapsed) with h5py.File(name, 'w') as hf: hf.create_dataset('position', data=position) hf.create_dataset('velocity', data=velocity)