text
stringlengths
37
1.41M
import itertools numbers1 = [1, 2, 3, 4] ### Lista 3-elementowa kombinacja # kombinacja - przyklad 1 print(list(itertools.combinations(numbers1, 3))) # kombinacja - przyklad 2 combinations_list = [] test_list = [] for i in numbers1: for j in numbers1: for k in numbers1: if i != j and i !...
import turtle as t import snake as s import food as f import scoreboard as sb import random import time screen = t.Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("Snake Game") screen.tracer(0) # movement animation-off of single snake bodies snake ...
# https://www.youtube.com/watch?v=IoQ6s80JM0s&index=2&list=PLE3D1A71BB598FEF6 import os import sys import math import pygame import pygame.mixer import random import euclid # from https://pypi.python.org/pypi/euclid from pygame.locals import * # define some basic colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED ...
import RPi.GPIO as GPIO from time import sleep from math import pow GPIO.setmode(GPIO.BOARD) red = 12 yellow = 11 btn1 = 13 btn2 = 15 GPIO.setup(btn1,GPIO.IN,pull_up_down=GPIO.PUD_UP) GPIO.setup(btn2,GPIO.IN,pull_up_down=GPIO.PUD_UP) GPIO.setup(red,GPIO.OUT) GPIO.setup(yellow,GPIO.OUT) pwmR=GPIO.PWM(red,100) pwmY=GPIO....
def minimum_swaps(arr): swap = 0 i = 0 while i < len(arr): # Bug in input data which violates problem constraints if len(arr) == 7 and i == 6: break if arr[i] == (i+1): i += 1 continue arr[arr[i]-1], arr[i] = arr[i], arr[arr[i]-1] s...
import re n, m = map(int, input().split()) matrix = [input() for _ in range(n)] string = '' for i in range(m): for j in range(n): string += matrix[j][i] # print(string) pattern = r"\b[^a-zA-Z0-9]+\b" re.compile(pattern) new_string_list = re.split(pattern, string) new_string = '' for i in new_string_list:...
# Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, sabendo que a # decisão é sempre pelo mais barato. prod1 = float(input("Digite o preço do macarrão: ")) prod2 = float(input("Digite o preço do leite: ")) prod3 = float(input("Digite o preço do pão: ")) if prod1 < prod2 ...
# Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre # o total do seu salário no referido mês, sabendo-se que são descontados 11% para o Imposto de Renda, 8% para o INSS # e 5% para o sindicato, faça um programa que nos dê: # salário bruto. # quanto pagou a...
import collections a_tuple = (1 , 3.14, True, "a string", ["a", "list"]) print(a_tuple) # crashes # a_tuple[1] = 6.28 print(a_tuple[0]) for item in a_tuple: print(item) # named tuples card = collections.namedtuple("Card", ["suit", "value"]) aos = card("Spades", 1) eoc = card("Clubs", 8) print(eoc) print(...
def add_student(students, id, credits): """ Adds the student to a dictionary using the student id as the key. :param students: The dictionary of students. :param id: The student's id. :param credits: The number of credits the student has earned. :return: None. """ student = [id, credit...
import reverse def test_reverse(string, expected): rev = reverse.reverse(string) if rev != expected: print("reverse on '", string, "' failed; should have been:", expected, "but was: ", rev) def test_empty(): test_reverse("", "") def test_single(): test_reverse("a", "a") def...
#!/usr/bin/env python # input url # test the downloaded file has a header that makes sense # go through the downloaded file and check the # input file URL # output filename # image directory import argparse import csv import os import sys try: from urllib.request import urlretrieve except ImportError: from ur...
################################################################################################################################################################## ## ## CS 101 ## Program # 5 ## Name: Harrison Lara ## Email: hrlwwd@mail.umkc.edu ## ## PROBLEM: For this program you will be given the text of 4 diff...
# Done By :: Vivaan Shiromani # Date :: 4th Oct 2021 # Program to implement Bubble Sort Alogorithm in Python. # Time Complexity :: O(n^2) lst=[4,5,-1,-3,5,9,10,11,99] # Output: [-3, -1, 4, 5, 5, 9, 10, 11, 99] # lst=[3,2] # Output: [2,3] # Steps: # 1. Bubble sort means to compare the ith and i+1th element ; if ith...
class kelilingLingkaran(object): def __init__(self, r, p): self.jarijari = r self.phi = p def hitungKeliling(self): return 2 * self.phi * self.jarijari def cetakData(self): print("jari-jari\t: ", self.jarijari) print("phi\t: ", self.phi) def cetakKeliling...
def fibo(): n = int(raw_input("Enter N: ")) a,b = 0,1 print a print b '''i = 2 using while loop while i < n: c = a + b print c a,b= b, c i = i +1''' # using For loop for i in range(2, n): c = a+b print c a,b=b,c
n = int(raw_input("Enter N :")) for i in range(0, n+1, 2): print i
dieta = { "lunes": ["Pollo con mole", "Arroz blanco", "Frijolinis"], "martes": ["Atún", "Fideos"], "viernes": ["Ensalada", "Subway"] } """ print(dieta.keys()) print(list(dieta)) print(dieta.items()) """ # print(list(dieta)) for dia in list(dieta): print(f"La comida del día {dia} es:") for comida i...
compras = [ "Sillón", "Agua", "Cloro", "Brócoli" ] print(f"Total de cosas por comprar: {len(compras)}") print(f"El tercer elemento de la lista es: {compras[2]}") compras[2] = "Manzana" print(compras)
# coding=utf-8 """ 给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。 说明: 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。 示例: 输入: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 输出: [1,2,2,3,5,6] """ def merge(nums1, m, nums2, n): if n < 1: ret...
# coding=utf-8 class IndexedMaxHeap: """ 带索引的大顶堆,支持在logn时间内更新、删除元素 """ def __init__(self): self._data = [None] self._index = dict() self._size = 0 def insert(self, element, weight): """ 向堆中加入元素 :param element: 要加入的元素 :param weight: number,...
# coding=utf-8 """ 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。 说明: 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? 示例 1: 输入: [2,2,1] 输出: 1 """ def single_number(nums): result = 0 for n in nums: result = result ^ n return result ipt = [4, 1, 2, 1, 2] print(single_number(ipt))
# coding=utf-8 class Node: def __init__(self, data): self.data = data self.nextNode = None def __del__(self): del self.data del self.nextNode class LinkedList: def __init__(self, iterable=None): self._firtNode = None self._lastNode = None self._len...
class LinkedList: def __init__(self, item): self.item = item self.next = None def set_next(self, node): self.next = node def print_list(list): i = 0 while list and i < 20: print(list.item, end="") if list.next: print(" -> ", end="") i += 1 ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Getting current date and time """ Created on Tue Jan 10 16:02:50 2017 @author: Creative """ from datetime import datetime # below command shows whole date and time now = datetime.now() print("\n") print(now) print("\n") # getting cammands on date print("DATE : " + str(...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #String accessibilty and storing """ Created on Tue Jan 10 11:52:53 2017 @author: Creative """ name = "Kiran Kumar" age = "19" # here above kiran kumar and 19 are string # now access by index print(name[0] + " has age " + age[1])
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Define variable and print a variable. """ Created on Tue Jan 10 09:38:48 2017 @author: Kiran Kumar """ my_var = 5 print(my_var) a = True b = False print(a) # here below we define function span Python is systematic language def span(): eggs = 12 return eggs p...
#!/bin/python3 # Multiples of 3 and 5 # If we list all the natural numbers below 10 that are multiples of 3 or 5, # we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. import sys def calc_sum(k): n3 = (k-1) // 3 n5 = (k-1) // 5 n15 = (k-1) //...
num_01 = int(input("Please input 1 integer number : ")) num_02 = int(input("Please input 2 integer number : ")) print("add two numbers with using sum() function") print("you can see the result at the next line") print("sum of 2 numbers ({}, {})'s sum result = {}".format(num_01, num_02, sum(num_01, num_02)))
import sys def sqr(x): return x * x def main(n): x = 1 for i in range(1, n): y = sqr(x) + 1 print("sqr(%d) + 1 = %d" % (x, y)) x = y if __name__ == '__main__': n = int(sys.argv[1]) main(n)
import queue import time class Node: def __init__( self, state, parent, direction, depth, cost ): # Contains the state of the node self.state = state # Contains the node that generated this node self.parent = parent # Contains the operation that generated this node ...
#while和else结合使用简单介绍 a=1 while a == 1: print("a==1") a = a + 1 else: print("a != 1") print(a) #简单语句组(若while循环体中只有一个语句,则可和while写在同一行) a=1 while a == 1:a = a + 1 else: print("a != 1") print(a) #break:跳出整个循环体 for i in range(1,10): if i == 5: break print(i) #continu:跳出当前循环而费整个循环体...
""" 分段函数求值 3x-5 (x>1) f(x) = x+2 (-1<=x<=1) 5x +3 (x<-1) """ #分支结构 #x = -2 #if x > 1: # y = 3*x-5 #elif x < -1: # y = 5*x+3 #else: # y = x+2 #print(y) def calculate(x): if x > 1: y = 3*x-5 elif x < -1: y = 5*x+3 else: y = x+2 print(y) calculate(2)
# for i in range(2,5): # print(i) def fib(n): if n ==1: return [0] if n == 2: return [0,1] if n >= 3: fibs = [0,1] print(fibs[-1]) print(fibs[-2]) for i in range(3,n): fibs = fibs.append(fibs[-2]+fibs[-1]) return fibs print(fib(3)...
""" unnitest测试框架 --单元测试覆盖类型: --语句覆盖 --条件覆盖 --判断覆盖 --路径覆盖 --框架介绍 --编写规范 --测试模块首先import unittest --测试类必须继承 unittest.TestCase --测试方法必须以“test_” """ import unittest #定义测试类并继承unittest测试类 class TestStringMethods(unittest.TestCase): #setUp 和 tearDown 方法是在每条测试用例的前后分别进行调用的方法 def setUp(self) -> None:...
def fibonacci_generator(n=None): if n is not None and n <= 0: raise ValueError("parameter 'n' must be positive") first = 0 second = 1 if n == 1: yield first yield first yield second if n is not None: counter = 3 while counter <= n: result = firs...
months_array = { 1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December' } def get_month_name(month): return months_array[month] def get_elem(arr, el): for ...
#Topic:Logistic Regression - Simulated Data #----------------------------- #libraries from sklearn.datasets import make_classification from matplotlib import pyplot as plt from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matr...
#Missing Data #----------------------------- #%Imputation import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sleep1 = pd.read_csv('sleep.csv') sleep1.head() sleep2 = pd.read_csv('https://raw.githubusercontent.com/dupadhyaya/sipPython/master/data/sleep.csv') sleep2 sleep = sle...
f#Matplot Lib -Features #----------------------------- #% import matplotlib.pyplot as plt import numpy as np x = np.linspace(0,10,1000) x #just the plot plt.plot(x, np.sin(x)) #Axis - manual plt.plot(x, np.sin(x)) plt.xlim(-1, 15) plt.ylim(-1.5, 1.5) #Axis - Reverse plt.plot(x, np.sin(x)) plt.xlim(-1, 11) plt.ylim(...
# -*- coding: utf-8 -*- #binomial distribution #The binomial distribution model deals with finding the probability of success of an event which has only two possible outcomes in a series of experiments. For example, tossing of a coin always gives a head or a tail. The probability of finding exactly 3 heads in tossing a...
#Dates - Range #----------------------------- #https://towardsdatascience.com/playing-with-time-series-data-in-python-959e2485bff8 import pandas as pd import numpy as np dtrange1D = pd.date_range('2019-1-1', '2019-7-11', freq='D') dtrange1D dtrange1D.min() #The resulting DatetimeIndex has an attribute freq with a ...
#Topic: #----------------------------- # Import the modules import sys import random ans = True #This generates a random number and prints a different value every time #exit when value entere while ans: question = input("Enter a number (1-8): (press enter to quit) ") answers = random.randint(1,8) ans = True...
# -*- coding: utf-8 -*- """ Created on Tue Jun 4 08:00:01 2019 @author: du """ """ Test for an education/gender interaction in wages ================================================== Wages depend mostly on education. Here we investigate how this dependence is related to gender: not only does gender create an offset...
#Seaborn Heatmap #----------------------------- #%https://seaborn.pydata.org/generated/seaborn.heatmap.html import numpy as np np.random.seed(0) import seaborn as sns sns.set() uniform_data = np.random.rand(10, 12) ax = sns.heatmap(uniform_data) #Change the limits of the colormap: ax = sns.heatmap(uniform_data, vmi...
#Topic: Association Rule Analysis #----------------------------- #libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt #creating sample data TID =[1,2,3,4,6,7,8,9] items = [['I1,I2,I5'], ['I2,I4'], ['I2,I3'], ['I1,I2,I4'], ['I1,I3'], ['I2,I3'],['I1,I2,I3,I5'], ['I1,I2,I3']] items item1 = '...
#Seaborn - CountPlot #----------------------------- #%https://seaborn.pydata.org/generated/seaborn.countplot.html import seaborn as sns sns.set(style="darkgrid") titanic = sns.load_dataset("titanic") ax = sns.countplot(x="class", data=titanic) #values ax = sns.countplot(x="class", hue="who", data=titanic) #horiz ax =...
# -*- coding: utf-8 -*- #Frozen Set #----------------------------- #% #The frozenset() method returns an immutable frozenset object initialized with elements from the given iterable. While elements of a set can be modified at any time, elements of frozen set remains the same after creation. #Due to this, frozen sets c...
# -*- coding: utf-8 -*- #Tuples - collection, ordered, unchangeable/ unmutatble, like list, round bracket tuple1 = (1,2, 'SIP', 'Dhiraj', True) tuple1 #everying like list except changes tuple1[0] = 99 #access tuple1[0] for i in tuple1 : print(i) if 'Dhiraj' in tuple1 : print('Dhiraj is present in tuple') if 'Kouna...
# -*- coding: utf-8 -*- # #----------------------------- #% # -*- coding: utf-8 -*- #Python has excellent libraries for data visualization. A combination of Pandas, numpy and matplotlib can help in creating in nearly all types of visualizations charts. In this chapter we will get started with looking at some simple ch...
#Boxplots and paired differences import matplotlib.pyplot as plt #data from pydataset import data mtcars = data('mtcars') mtcars.head() #Example 1 plt.figure() mtcars.boxplot(column=['mpg']) plt.yticks(5) plt.show(); plt.figure() mtcars.boxplot(column=['mpg','wt']) plt.yticks(5) plt.show(); #Different dataset impo...
#Topic: Clustering - Simple and Data Camp Site #----------------------------- #https://www.datacamp.com/community/tutorials/k-means-clustering-python #https://scikit-learn.org/stable/modules/clustering.html X = [1,1,1,2,1,2,1,2] Y = [4,2,4,1,1,4,1,1] Z = [1,2,2,2,1,2,2,1] import numpy as np import pandas as pd import ...
#Topic:US Crime #----------------------------- #libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt url = "https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/04_Apply/US_Crime_Rates/US_Crime_Rates_1960_2014.csv" crime = pd.read_csv(url) crime.head() crime.info() # pd.to_...
# -*- coding: utf-8 -*- #Matplot Styling #----------------------------- #Python - Chart Styling #The charts created in python can have further styling by using some appropriate methods from the libraries used for charting. In this lesson we will see the implementation of Annotation, legends and chart background. #Addi...
#Label in Scatter Plot #----------------------------- #% import matplotlib.pyplot as plt import numpy as np plt.clf() # using some dummy data for this example xs = np.random.normal(loc=4, scale=2.0, size=10) ys = np.random.normal(loc=2.0, scale=0.8, size=10) plt.scatter(xs,ys) # zip joins x and y coordinates in pairs f...
#Topic: Apple Data #----------------------------- #libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/09_Time_Series/Apple_Stock/appl_1980_2014.csv' apple = pd.read_csv(url) apple.head() app...
# -*- coding: utf-8 -*- #Different ways of importing libraries Z#Python comes with built in functions like x=[1, 4.5, 9] print(x) abs(x) int(x[1]) #takes only 1 value len(x) #they are limited in functionality #need more functions - this comes from libraries or modules #Modules define functions, classes, variables that...
#Topic: Linear Regression Stock Market Prediction #----------------------------- #libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt Stock_Market = {'Year': [2017,2017,2017, 2017,2017,2017,2017,2017, 2017,2017,2017,2017,2016,2016,2016,2016,2016,2016,2016,2016,2016, 2016,2016,2016], 'Mont...
#Topic: Statistics - Covariance #----------------------------- #Covariance provides the a measure of strength of correlation between two variable or more set of variables. The covariance matrix element Cij is the covariance of xi and xj. The element Cii is the variance of xi. #If COV(xi, xj) = 0 then variables are unco...
# -*- coding: utf-8 -*- # Interfaces in the plots #----------------------------- #% #library import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 10, 100) fig = plt.figure() #plot Figure #MATLAB interface #create 1st panel #(row, column, panel) plt.subplot(2, 1, 1) plt.plot(x, np.sin(x)) #create 2n...
#Topic: Correlation, Covariance, #----------------------------- #libraries #The difference between variance, covariance, and correlation is: #Variance is a measure of variability from the mean #Covariance is a measure of relationship between the variability of 2 variables - covariance is scale dependent because it is...
#Topic: Frozen Sets #----------------------------- #The frozenset() method returns an immutable frozenset object initialized with elements from the given iterable. #syntax : frozenset([iterable]) #Frozen set is just an immutable version of a Python set object. While elements of a set can be modified at any time, eleme...
#Topic: Join #----------------------------- #libraries numList = ['1', '2', '3', '4'] seperator = ', ' print(seperator.join(numList)) numTuple = ('1', '2', '3', '4') print(seperator.join(numTuple)) s1 = 'abc' s2 = '123' """ Each character of s2 is concatenated to the front of s1""" print('s1.join(s2):', s1.join(s...
#Topic: Numpy Histogram #----------------------------- #Compute the histogram of a set of data. #https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html #NumPy has a numpy.histogram() function that is a graphical representation of the frequency distribution of data. Rectangles of equal horizontal size...
#String Operations # Sets S1 = {1,2,3} type(S1) S1 S2 = set() type(S2) S2.add(4) S2.add(5) S2 #Empty Set S0=set() # {} creates empty dict, not a set S0 type(S0) #Simple Set S1={'apple','banana',1,2} S1 type(S1) #convert to List ??? L1=set(S1) type(L1) L1 # Set Comprehensions import string s = set(string.ascii_lower...
class Vehiculos(): def __init__(self, marca, modelo): self.marca=marca self.modelo=modelo self.enMarcha=False self.acelera=False self.frena=False def arrancar(self): self.enMarcha=True def acelerar(self): self.acelera=True def frenar(self): self.frena=True def estado(s...
miTupla=("juan", 13, 1, 1995) #imprime 1 print(miTupla[2]) miLista=list(miTupla) # imprime ['juan', 13, 1, 1995] # los corchetes son de lista print(miLista) miTupla2=tuple(miLista) # imprime ('juan', 13, 1, 1995) # los parentecis son de tupla print(miTupla2) #me da true por que existe en la tupla print("juan" in...
def suma( op1, op2 ): print("El resultado de la suma es:", str( op1 + op2 )) def restar( op1, op2 ): print("El resultado de la resta es:", str( op1 - op2 )) def multiplicar( op1, op2 ): print("El resultado de la multiplicacion es:", str( op1 * op2 )) def dividir( op1, op2 ): print("El resultado de la divis...
from tkinter import * raiz=Tk() miFrame=Frame(raiz, width=1200, height=600) miFrame.pack() #aca estoy posicionando los elementos cuadroNombre=Entry(miFrame) cuadroNombre.grid(row=0, column=1) cuadroApellido=Entry(miFrame) cuadroApellido.grid(row=1, column=1) cuadroDireccón=Entry(miFrame) cuadroDireccón.grid(row=2,...
import pickle class Persona(): def __init__(self, nombre, genero, edad): self.nombre = nombre self.genero = genero self.edad = edad print(f"Se ha creado una persona nueva con el nombre de {self.nombre}") # sirve para convertir en cadena de texto # la informacion de un objeto def __str__(se...
import sqlite3 # inicio la conexion miConexion=sqlite3.connect("PrimeraBase") # creo el cursor miCursor=miConexion.cursor() # aca se mete la intruccion sql de crear tabla #-miCursor.execute("CREATE TABLE PRODUCTOS (NOMBRE_ARTICULO VARCHAR(50), PRECIO INTEGER, SECCION VARCHAR(20))") # aca inserto valores en la tabla ...
class Coche(): # constructor de clase def __init__(self): # encapsulo las variables self.__largoChasis=250 self.__anchoChasis=120 self.__enMarcha=False self.__ruedas=4 def arrancar(self,arrancar): # le cambio para lo que le pase por parametro # se lo va a insertar como valor en ...
from bs4 import BeautifulSoup import urllib.request from sys import argv print(""" .|'''.| ||.. ' .... ... .. .... ... ... .... ... .. ''|||. .| '' ||' '' '' .|| ||' || .|...|| ||' '' . '|| || || .|' || || | || || ...
from utils import * assignments = [] def assign_value(values, box, value): """ Please use this function to update your values dictionary! Assigns a value to a given box. If it updates the board record it. """ # Don't waste memory appending actions that don't actually change any values if valu...
#1 def fatorial(n): if(n < 0): raise Exception('Menor que zero') if(n == 0 or n == 1): return 1 return n * fatorial(n - 1) #2 def somatorio(n): if(n == 0): return 0 if(n > 0): return n + somatorio(n-1) if(n < 0): return n + somatorio(n+1) #3 def fibonacc...
# All in-game items class Weapon: def __init__(self): raise NotImplementedError("Do not create raw Weapon objects.") def __str__(self): return self.name class Rock(Weapon): def __init__(self): self.name = "Rock" self.description = "A fist-sized rock, best used against heads." self.damage = 5 self.value ...
def product(a, b): if a < 0: a *= -1 elif b < 0: b *= -1 result = a * b print("Product of", a, "and", b, "equals", result) return result def pre_product(a, b): product_result = product(a,b) if a < 0 and b < 0: product_result *= -1 return product_result
''' Given an undirected graph with n nodes labeled 1..n. Some of the nodes are already connected. The i-th edge connects nodes edges[i][0] and edges[i][1] together. Your task is to augment this set of edges with additional edges to connect all the nodes. Find the minimum cost to add new edges between the nodes such tha...
def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ seen = {} for i in range(len(nums)): if target - nums[i] in seen: return [i, seen[target-nums[i]]] else: seen[nums[i]] = i return 0 nums = [2, 7, 11, ...
def containsDuplicate(nums): """ :type nums: List[int] :rtype: bool """ unique = set(nums) return len(unique) != len(nums) array = [1,1,1,3,3,4,3,2,4,2] print(containsDuplicate(array))
''' A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list. Example 1: Input: {"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1} Explanation: Node 1's va...
def gradingStudents(grades): newgrade=[] for i in range(len(grades)): if grades[i] > 40 and grades[i] <=100: if ((((grades[i]//5)+1)*5)-grades[i]< 3 ): newgrade.append(((grades[i]//5)+1)*5) else: newgrade.append(grades[i]) else: ...
#!/usr/bin/env python """ Data wrangling tool for quickly selecting a winner from Habitica Challenge CSV data. """ # Ensure backwards compatibility with Python 2 from __future__ import ( absolute_import, division, print_function, unicode_literals) from builtins import * import numpy as np import os imp...
# a*3 each 1 year # b*2 each 1 year args = input().split(' ') a = int(args[0]) b = int(args[1]) years = 0 while a <= b: a *= 3 b *= 2 years +=1 print(years)
# -*- coding: utf-8 -*- """ A = {1, 8, 2,4} B = {4, 9, 2, 7} print(A) print(B) print(A|B) print(A&B) print(A-B) print(A^B) thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict['model']) import numpy as np out_arr_1 = np.random.randint(2, 10, 8) print(out_arr_1); out_ar...
def make_album(artist_name, album_title, number=None): album = { "artist".title(): artist_name.title(), "album".title(): album_title.title() } if number: album['number'.title()] = number return album one = make_album('koko', 'wheels on the bus') two = make_album('bobo...
class User: def __init__(self, first_name, last_name, email, title, age, city): self.first_name = first_name self.last_name = last_name self.email = email self.title = title self.age = age self.city = city self.login_attempts = 0 def describe_user(self): ...
#D. Given a list of numbers, return a list where # all adjacent == elements have been reduced to a single element, # so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or # modify the passed in list. test1 = [1, 2, 2, 3] test2 = [2, 2, 3, 3, 3] test3 = [] def remove_adjacent(lists): n=0 w...
#Import and dependencies from selenium import webdriver import time from selenium.webdriver.common.keys import Keys #Here the process of automation is achieved by using the framework Selenium. #Selenium is a portable framework for testing and automating web applications web applications #Path to chromedriver....
# Initializes people set to 69 people = 69 # Initializes cars set to 70 cars = 70 # Initializes buses set to 71 buses = 71 # If cars > people (i.e., if cars > people evaluates to true) if cars > people: # Print the string print "We should take the cars." # Otherwise (if cars > people evaluates to false), if ca...
# Imports argv module from sys from sys import argv # Sets argv to script and filename (i.e. these must be passed when the script is run) script, filename = argv # Prints the string with the raw data fromatter and filename taken from argv inserted print "We're going to erase %r." % filename # Prints the string print ...
# Defines constructor Parent class Parent(object): # Defines function override taking parameter self (i.e., Parent) def override(self): # Prints string when called print "PARENT override()" # Defines constructor Child which inherits from Parent class Child(Parent): # Defines function over...
# Defines constructor Parent class Parent(object): # Defines parent.override() def override(self): # Prints string when called print "PARENT override()" # Defines parent.implicit() def implicit(self): # Prints string when called print "PARENT implicit()" # Defines ...
import pickle from heapq import heappush, heappop from time import sleep # import numpy as np # -------------------------------------- # -------------------------------------- # SLIDING PUZZLE IMPORTS (REPEATED CODE) # -------------------------------------- # -------------------------------------- def tuple_puzzle_t...
class Node(object): def __init__(self, value): self.children = [None]*2 self.val = value def getValue(self): return self.val def getLeft(self): return self.children[0] def getRight(self): return self.children[1] def setLeft(self, n): self.children[...
#!/usr/bin/python import RPi.GPIO as GPIO import os # needed for system callback import Queue import time SWITCH1 = 17 SWITCH2 = 27 LED1 = 22 GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN, pull_up_down = GPIO.PUD_UP) GPIO.setup(27, GPIO.IN, pull_up_down = GPIO.PUD_UP) GPIO.setup(22, GPIO.OUT) ## The Queue modul...
inp = """ I'm sure that the shells are seashore shells. So if she sells seashells on the seashore, The shells that she sells are seashells I'm sure. She sells seashells on the seashore;""" #print(len(inp)) coni = inp.split("\n") #print(coni) length = [] for i in coni: length.append(len(i)) justlen...
file_name = open('she.txt','r') lines = file_name.readlines() new = [] for l in lines: new.append(l.split(" ")) sl = [] for i in range(len(new)): for j in range(len(new[i])): o = new[i].pop() print(o) new[i].insert(j,o) print(new)
from pymysql import connect import os connection = connect( host = os.getenv('MYSQL_HOST'), user = os.getenv('MYSQL_USER'), password = os.getenv('MYSQL_PASSWORD'), db = os.getenv('MYSQL_DATABASE'), charset = 'utf8mb4' ) loop = 0 loop1 = 0 loop2 = 0 while loop == 0: try: menu = int(inpu...
import itertools def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) return itertools.chain.from_iterable( itertools.combinations(s, r) for r in range(len(s)+1) ) def baseline(list_): p = powerset(list_) next(p) ret...