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) prin...
# 使用函数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 d...
# 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删除数据 返回的结果就是删除的...
# 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....
# 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_...
# 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 fro...
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.DataFra...
""" 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("Press...
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 # planeLi...
''' 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...
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"] ...
""" 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 cas...
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 ...
""" 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 s...
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]...
""" 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, It...
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...
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) ...
#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):...
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 fr...
__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").rstri...
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 ...
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 * nu...
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(idad...
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 distribu...
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_paran...
""" 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...
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 nu...
""" 5. Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение. Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение приб...
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 ...
# 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' p...
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 =...
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, se...
'''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" functio...
# -*- coding: utf-8 -*- """ ██████╗ ███████╗███╗ ██╗███████╗████████╗██╗ ██████╗ ██████╗██╗████████╗██╗ ██╗ ██╔════╝ ██╔════╝████╗ ██║██╔════╝╚══██╔══╝██║██╔════╝ ██╔════╝██║╚══██╔══╝╚██╗ ██╔╝ ██║ ███╗█████╗ ██╔██╗ ██║█████╗ ██║ ██║██║ ██║ ██║ ██║ ╚████╔╝ ██║ ██║██╔══╝ ██║╚██╗█...
#! /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...
""" 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?: ")) ...
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 | ^ ...
""" 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 ...
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() ...
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 Eletrogma...
#%% 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 ...
#!/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() m...
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 ...
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(d...
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.or...
#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"...
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) ...
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( ...
''' 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 i...
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: s...
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....
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 sel...
#!/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] ...
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...
#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 l...
# 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: # ^...
# 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 c...
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(schoolNa...
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: ...
''' 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...
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...
#!/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 by...
# 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 ...
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 =...
# -*- 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) pr...
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 ...
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....
# -*- 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 ra...
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 conta...
# -*- 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...
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(...
# 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 inputfi...
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-targ...
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 =...
""" 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 ...
# 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...
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(...
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, Credenti...
#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."""...