text
stringlengths
37
1.41M
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Given an array A of size N having distinct elements, the task is to find the next greater element for each element of the array in order of their appearance in the array. If no such element exists, output -1 ''' # Time Complexity: O(n) class Solution(): def ne...
# Author: Omkar Dixit # Email: omedxt@gmail.com # Link: https://leetcode.com/problems/search-a-2d-matrix-ii/ # Time Complexity: O(n + m) class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: row = len(matrix) - 1 col = 0 while self.isValid(row, col, matrix)...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Given an array of integers. Find the minimum number of swaps required to sort the array in non-decreasing order. ''' # Time Complexity: O(nLogn) class Solution: def minSwapsToSort(self, arr): posVal = [*enumerate(arr)] posVal.sort(key=lambda x:x...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Given a graph of V nodes represented in the form of the adjacency matrix. The task is to find the shortest distance of all the vertex's from the source vertex. ''' import heapq class Vertex: def __init__(self, value): self.name = value self.seen...
# Author: Omkar Dixit # Email: omedxt@gmail.com # Link: https://leetcode.com/problems/word-break-ii/ # Time Complexity: import collections import heapq import copy class Solution(object): def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: List[str] :rtype: List[s...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Given a string s, recursively remove adjacent duplicate characters from the string s. The output string should not have any adjacent duplicates. ''' # Time Complexity: O(n) class Solution: def removeDups(self, s, lastRemoved): if len(s) == 0 or len(s) == ...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Given a Binary Tree. Check whether it is Symmetric or not, i.e. whether the binary tree is a Mirror image of itself or not. ''' # Time Complexity: O(n) class BTreeNode: def __init__(self, value): self.value = value self.left = None self...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' In a candy store there are N different types of candies available and the prices of all the N different types of candies are provided to you. You are now provided with an attractive offer. You can buy a single candy from the store and get atmost K other candies ( al...
# Author: Omkar Dixit # Email: omedxt@gmail.com # Link: https://leetcode.com/problems/reverse-linked-list-ii/ # Time Complexity: O(n) n is number of nodes import collections import heapq # Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = v...
# Author: Omkar Dixit # Email: omedxt@gmail.com # Link: https://leetcode.com/problems/sliding-window-maximum/ # Time Complexity: O(n) import collections class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: self.deque = collections.deque() self.result = [] sel...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Given a Binary Tree of size N , You have to count leaves in it. For example, there are two leaves in following tree ''' class Node: def __init__(self, value): self.value = value self.right = None self.left = None class Solution: de...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Given two numbers represented by two linked lists of size N and M. The task is to return a sum list. The sum list is a linked list representation of the addition of two input numbers. ''' # Time Complexity: O(n + m ) class Node: def __init__(self, val): ...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Complete the function to print spiral order traversal of a tree. ''' from collections import defaultdict class TreeNode: def __init__(self, value): self.value = value self.left = None self.right = None class Solution: def getSpiralF...
# Author: Omkar Dixit # Email: omedxt@gmail.com # Link: https://leetcode.com/problems/insert-delete-getrandom-o1/ # Time Complexity: O(n) import random class RandomizedSet(object): def __init__(self): """ Initialize your data structure here. """ self.hashmap = {} self.ar...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' You are given a number N. You have to find the number of operations required to reach N from 0. You have 2 operations available: Double the number Add one to the number ''' class Solution: def minimumOperations(self, n): count = 0 if n <=2: ...
# Author: Omkar Dixit # Email: omedxt@gmail.com # Link: https://leetcode.com/problems/next-greater-element-i/ # Time Complexity: O(m+n) m , n is number of elements in nums1 and nums2 import collections import heapq class Solution(object): def nextGreaterElement(self, nums1, nums2): """ :type num...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Given a string S consisting only '0's and '1's, print the last index of the '1' present in it. ''' # Time Complexity: O(n) class Solution: def lastOne(self, string): index = -1 for i, char in enumerate(string): if char == '1': ...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' URLify: Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: If implementing in Java, please use a...
# Author: Omkar Dixit # Email: omedxt@gmail.com # Link: https://leetcode.com/problems/course-schedule-ii/ # Time Complexity: O(V + E) V is number of courses E is number of prereqs import collections class Solution(object): def findOrder(self, numCourses, prerequisites): """ :type numCourses: int ...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Given two sorted arrays arr1[] and arr2[] in non-decreasing order with size n and m. The task is to merge the two sorted arrays into one sorted array (in non-decreasing order). ''' class Solution: def mergeSortedArrayWithoutSpace(self, arr1, arr2): for i...
# Author: Omkar Dixit # Email: omedxt@gmail.com # link: https://leetcode.com/problems/prison-cells-after-n-days/ # Time Complexity: O(n) class Solution(object): def prisonAfterNDays(self, cells, N): """ :type cells: List[int] :type N: int :rtype: List[int] """ N =...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Given a String of length S, reverse the whole string without reversing the individual words in it. Words are separated by dots. ''' # Time Complexity: O(n) class Solution: def reverseStringWithWords(self, str): return self.reverseStringHelper(str.strip(...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Given an array A and an integer K. Find the maximum for each and every contiguous subarray of size K. ''' # Time Complexity: O(n) class Solution: def maxOIfSubarrayK(self, arr, k): if len(arr) < k: return [] result = [] maxVa...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Given a binary tree, print the bottom view from left to right. A node is included in bottom view if it can be seen when we look at the tree from bottom. ''' from collections import defaultdict class TreeNode: def __init__(self, value): self.value = valu...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Given an array A of N positive integers. Find the sum of maximum sum increasing subsequence of the given array. ''' # Time Complexity: O(n * n) class Solution: def maxIncreasingSumSubsequence(self, arr): result = [] sequence = [] for i i...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Given arrival and departure times of all trains that reach a railway station. Your task is to find the minimum number of platforms required for the railway station so that no train waits. ''' # Time Complexity: O(nLogn) class Solution: def minNumberOfPlatforms(...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' The problem is to count all the possible paths from top left to bottom right of a MxN matrix with the constraints that from each cell you can either move to right or down. ''' # Time Complexity: T(m*n) class Solution: def __init__(self): self.paths = 0 ...
# Author: Omkar Dixit # Email: omedxt@gmail.com #Link: https://leetcode.com/problems/unique-paths-iii/ # Time Complexity: O(3 ^ N) as there will be only 3 directions to be checked for each node as the last direction we wont be checking class Solution(object): def uniquePathsIII(self, grid): """ :...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Given two strings a and b consisting of lowercase characters. The task is to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For e...
import math print("1- Faça todos os exemplos da apostila da Semana #2") print("Hello Word") #-------------------- print('Soma') print(3+5) print(9+12) print(7+32) #------------------ print('N decimais') print(4.5+7.3) print(7.9+18.2) print(3.6+34.1) #------------------ print('Subtracao') print(5-2) print(9-7) print(15-...
import speech_recognition as sr AUDIO_FILE = ("t1 (online-audio-converter.com).wav") # use the audio file as the audio source r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: #reads the audio file. Here we use record instead of #listen audio = r.record(source) try: ...
#!/usr/local/bin/python2.7 # Utilities for scripts from os import remove, path, getcwd, system, listdir, walk, environ from os.path import isfile, isdir, join, dirname, exists, getsize from subprocess import Popen,PIPE # Create the absolute path name from a relative path name def path_name (relative_filename): ...
import torch import torchvision from torch import nn from torch.nn import Linear from torch.utils.data import DataLoader dataset = torchvision.datasets.CIFAR10("./trainingdata/CIFAR10", False, transform=torchvision.transforms.ToTensor()) dataloader = DataLoader(dataset, batch_size=64, drop_last=True) class...
def big_chessboard(n, m): for k in range(n): for j in range(m): for i in range(n): if i % 2 == 0 and k % 2 == 0: print('#' * m, end='') elif i % 2 != 0 and k % 2 != 0: print('#' * m, end='') else: ...
# Write a function that draws a text image of an arrow from the characters '*' # inside a square of size (n) formed by dots. You can assume that (n) is odd. def arrow(n): for i in range(n): for j in range(n): counter = '.' if i == n // 2 or j - i == n // 2 or i + j == n // 2 + (n ...
'''This is a document that contains various tests of the methods written in the String.py document. The use of pytest and pytest fixtures helps make the process run more efficiently. Authors: Anh Than (athan@bates.edu) Thomas Costin (tcostin@bates.edu) Max MacAvoy (mmacavoy@bates.edu) P...
class UnionFind: ''' Initialse n sites with integer names 0 to n-1 ''' def __init__(self, n): self.count = n self.id = [] for i in range(n): self.id.append(i) ''' Add connection between p and q ''' def union(self, p, q): self.validate(p) ...
n = int(input('Кол-во палок: ')) k = int(input('Кол-во бросков: ')) row = ['I' for _ in range(n)] for ind in range(1, k + 1): print('Бросок', ind, '. Сбиты палки с номера', end=' ') left_ind = int(input('')) print('по номер', end=' ') right_ind = int(input('')) row[left_ind - 1:right_ind] = '.' * (r...
list_1 = [] for _ in range(3): num = int(input('Число из первого списка: ')) list_1.append(num) print('Первый список:', list_1) list_2 = [] for _ in range(7): num = int(input('Число из второго списка: ')) list_2.append(num) print('Второй список:', list_2) list_1.extend(list_2) ind = 0 while ind < len(l...
people = { ('Иванова', 'Кира'): 50, ('Петров', 'Иван'): 40, ('Сидоров', 'Никита'): 35, ('Сидорова', 'Алина'): 34, ('Петрова', 'Ольга'): 38, ('Сидоров', 'Павел'): 10, } total_age = 0 inp_surname = input('Введите фамилию: ').title() inp_fem_surname = inp_surname + 'а' for surname_name, age in peop...
max_num = int(input('Введите максимальное число: ')) possible_numbers = set() while True: proposed_numbers = set() answer_str = input('Нужное число есть среди вот этих чисел: ').title() if answer_str == 'Помогите!': break else: proposed_numbers = set(answer_str.split()) answer = ...
num_friends = int(input('Кол-во друзей: ')) num_receipts = int(input('Долговых расписок: ')) friends_list = [] # for _ in range(num_friends): # friends_list.append([0, 0]) # for ind in range(num_receipts): # print('\n', ind + 1, 'расписка:') # to_whom = int(input('Кому: ')) # from_whom = int(input('От ...
def super_zip(data1, data2): data1_list = list(data1) data2_list = list(data2) zip_list = ((data1_list[ind], data2_list[ind]) for ind in range(min(len(data1_list), len(data2_list)))) return zip_list data_1 = 'abcde' data_2 = (9, 8, 7, 6, 5, 4, 3) data_3 = {32, 34, 36, 38, 40, 42, 44} data_4 = [1, 2, 3...
class Person: def __init__(self, name, surname, age): self.__name = name self.__surname = surname self.__age = age def __str__(self): return f'Имя: {self.__name} Фамилия: {self.__surname} Возраст: {self.__age}' class Employee(Person): def __init__(self, name, surname, age)...
def sort_choice(my_list): for i_mn in range(len(my_list)): for i_curr in range(i_mn, len(my_list)): if my_list[i_curr] < my_list[i_mn]: my_list[i_curr], my_list[i_mn] = my_list[i_mn], my_list[i_curr] rollers = int(input('Кол-во коньков: ')) rollers_list = [] for i in range(roll...
people_num = int(input('Кол-во человек: ')) people_list = list(range(1, people_num + 1)) number = int(input('Какое число в считалке? ')) print('Значит, выбывает каждый', number, 'человек') start_poz = 1 while len(people_list) > 1: print('\nТекущий круг людей:', people_list) print('Начало счёта с номера', peopl...
import re if __name__ == '__main__': phone_numbers = ['9999999999', '999999-999', '99999x9999', '8675432123', '865432176', '6543213458'] phone_template = re.compile(r'[8,9]\d{9}') for number_id, phone in enumerate(phone_numbers, start=1): # если установить параметр start функции enumerate равным 1...
def sum_all_numbers(n): sum_all = 0 for k in range(n + 1): sum_all += k return sum_all def sum_digits(n): sum_digit = 0 while n != 0: sum_digit += n % 10 n //= 10 return sum_digit def number_digits(n): number_digit = 0 while n != 0: number_digit += 1 ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 24 15:50:58 2018 @author: anikkengjeruldsen """ #%% # Exercise 1 non-connected nodes ina graph graph={ "a":["b","c"], "b":["d"], "c":["d"], "d":[], "e":[] } def non_connected(g): non_connected_nodes=[] outgoin...
#STONE PAPER SCISSORS from tkinter import* from tkinter.messagebox import* from random import * Options=["STONE","PAPER","SCISSORS"] top=Tk() explanation=""" S T O N E P A P E R S C I S S O R S """ w2=Label(top,text=explanation,anchor=W,bg="red",fg="white",font=("Times New Roman",25),hei...
age_01 = int(input('Enter the age of 1st person :: ')) age_02 = int(input('\nEnter the age of 2nd person :: ')) age_03 = int(input('\nEnter the age of 3rd person :: ')) max_age = (age_01 if (age_01 > age_02 and age_01 > age_03) else (age_02 if(age_02 > age_03 and age_02 > age_01) else age_03)) print('\n\nThe...
#Faça uma Função recursiva que calcule a soma dos digitos de um inteiro positivo n def sd(n): if n <= 9: return n return n % 10 + sd(n//10)
from abc import ABC, abstractmethod from typing import Any, Optional, Sequence class Unit(ABC): """言語単位の基底クラス・""" def __init__(self) -> None: self._text: Optional[str] = None def __post_init__(self) -> None: if self.child_units is not None: for child_unit in self.child_units:...
"""Example code for using the result of named entity recognition. Usage: $ python examples/use_named_entity_recognition.py "太郎は花子が読んでいる本を次郎に渡した。" """ import sys from rhoknp import KNP # Create a KNP instance. knp = KNP() # Apply KNP to a sentence. sent = knp.apply_to_sentence(sys.argv[1]) # Get information. if...
def add2(n1, n2): s = n1 + n2 return s print add2(3, 4) def add2(n1, n2,n3): s = n1 + n2+n3 return s print add2(3, 4,5) def add2(n1, n2,n3,n4): s = n1 + n2+n3+n4 return s print add2(3, 4,5,4)
from Poll import poll import plotly.express as px class chart: """ What Chart Does Chart is a class that takes in a poll object and creates a pie chart using plotly to display the data in a nice way """ """ create_graph takes in a chart object and returns a plotly graph based off of the...
# -*- coding: utf-8 -*- """ Created on Mon Apr 13 15:39:06 2020 @author: Shivam """ class node: def __init__(self,data): self.data = data self.next = None def islistempty(self): if self.head is None: return True return False class LinkedList: def _...
''' 时间复杂度是o(n)空间复杂度是O(n) 其实空间可以降下来 我们可以用两个数去get就好 ''' class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ if n <= 3: return n result = [0,1,2,3] for i in range(4,n+1): result_temp = result[i-1] + result[i-2] ...
''' 这道题 sums 记录 总共车走完全程 从第一个到最后一个 剩下多少汽油 如果大于等于0 说明肯定可以走完 current 意思是 走到第i个站 有多少汽油 如果 剩下的汽油 加上第i个站的汽油 小于下个站的汽油的话 说明走不过去了 需要跳过 ''' class Solution(object): def canCompleteCircuit(self,gas,cost): if sum(gas) - sum(cost) < 0: return -1 sums,current,index = 0,0,0 for i in range(len(ga...
''' 从后往前遍历 用max去记录之前的letter 的value 如果遍历到现在的这个字母 比之前的max小 那说明这是一个组合 total就去减去这个字母的数值 ''' class Solution(object): def romanToInt(self,s): dic = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} max = 0 total = 0 for i in range(len(s) - 1, -1, -1): c = s[i] ...
''' 和349 不一样的是 只要一样的 我们就要添加进result中 我们建立一个字典 把短的那个列表 中每个元素出现的次数找出来 然后遍历第二个列表 发现这个元素如果在字典中的次数大于0 那么就添加进result中 并且字典的计数数字 - 1 ''' import collections class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] ""...
''' ''' class Solution: def wordPattern(self, pattern: str, str: str) -> bool: pattern_dict = {} str_dict = {} str_word = str.split() if len(pattern) != len(str_word): return False for i in range(len(pattern)): if pattern[i] not in pattern_dict: ...
import random lotto = [] od_liczby = 1 do_liczby = 5 ilosc_liczb_do_wylosowania = 5 i = 0 while i < ilosc_liczb_do_wylosowania: r = random.randint(od_liczby, do_liczby) if lotto.count(r) == 0: lotto.append(r) i+=1 print(lotto)
from graphs.graph import * # A function which creates a graph with n vertices, with a path of length n − 1; def graph_path(n): G = Graph(False, n) verts = G.vertices v = verts.pop() while len(verts) > 0: w = verts.pop() f = Edge(v, w) v = w G.add_edge(f) print(G) ...
def gcd(a, b): a, b = abs(a), abs(b) while b != 0: a, b = b, a % b print("gcd: ", a) return a # gcd(3141, 156) def largest_sqaure(length, width): tile_size = gcd(length, width) area = tile_size * tile_size print("area: ", area) #largest_sqaure(12345678, 987654321) def frac(a,...
def bubble_sort(list1): length = len(list1) for i in range(length): for j in range(1,length): if list1[j]<list1[j-1]: list1[j],list1[j-1] = list1[j-1], list1[j] print list1 return list1 def main(): bubble_sort([5,4,10,5,20,64,1,7,2,75,65,44,666,1,2,55,43,2,7,9,5]) if __name__ =='__main__': main()
#chapter_4_palindrome #Write a function which asks the user for a string and prints out #whether the string is a palindrome or not def palindrome_detector(): string = input('Enter a string: ') string_split = string.split() palindrome_detector()
"""Buster World Models This module contains the PlayerStats Class Object, which is a Django model for storing a player's name, score, and time. """ from django.db import models class PlayerStats(models.Model): """Value type that represents a player's name, score, and time for any given session of the game.""" ...
import string class VocabularyValidator: def __init__(self): self.vocabSet = dict() self.__addVocabSet0() self.__addVocabSet1() # type 0: # Fold the corpus to lowercase # and use only the 26 letters of the alphabet [a-z] # return boolean def verify0(self, vocabulary: ...
import math def divisors(n): divs = [1,n] for i in range(2,int(math.sqrt(n))+1): if n%i == 0: divs.extend([i,n/i]) return list(set(divs)) def main(): result = 0 i = 2 while 1: i += 1 tri = i*(i+1)/2 fact = divisors(tri) if len(fact) > 500: print tri, fact break main(...
def is_pandigital(s): digits = set() for c in s: digits.add(int(c)) return digits == set(range(1,10)) def main(): limit = 100000 pans = [] for i in range(1,limit): digits = len(str(i)) num = str(i) counter = 2 while digits < 9: cur = i*counter num += str(cur) digits +=...
from math import * def primes(n): sieve = [True] * n for i in xrange(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1) return [2] + [i for i in xrange(3,n,2) if sieve[i]] def odd_composites(n): prime = primes(n) return [x for x in range(n) if x not in prime and x % 2 != ...
import random a = [] for i in range (100) : a.append(random.randint(1,100)) print("List of numbers") for i in range (100) : print(str(a[i])+" ", end=' ') print("\n\Ascending order") a.sort() for i in range (100) : print(str(a[i])+" ", end = ' ') print("\n\Descending order") a.sort(reverse=True) for i in range ...
#!/usr/bin/env python3 import curses # unix only import time class Player: def __init__(self, name): self.name = name self.isdead = False def take_action(self, action): if (math.random() < .1): die() return "You have died." def die(self): self.isdea...
#Parent class giving basic movement functionality to the characters in the game import pygame import os import sys from pygame import * class Person(pygame.sprite.Sprite): """ Parent class giving basic Life Attributes """ """ This in itself is a child class of Sprite """ def __init__(self): pygame...
with open("input") as f: data = f.readlines() valid = 0 for x in data: mi = int(x.split("-")[0]) ma = int(x.split("-")[1].split(" ")[0]) l = x.split(" ")[1][0] password = x.split(" ")[2][:-1] i = 0 for n in password: if n == l: i+=1 tempval = 0 if i >= mi and i <=...
""" The logic to load a trained model and use it to make predictions """ import json import os from typing import List, Dict import torch from torch.utils.data import DataLoader from tqdm import tqdm from transformers import BertForSequenceClassification, BertTokenizer from bert_examples.classification_dataset import...
def main(): grid_serial_number = 18 max_power_level = -999 max_power_corner = (0, 0) max_power_size = -999 # print(findSquarePowerLevel(1, 1, 5, grid_serial_number)) for x in range(1, 30): for y in range(1, 30): largest_square = 31 - x if x > y else 31 - y if la...
def main(): num_two = 0 num_three = 0 with open('input.txt') as input_file: for line in input_file: letter_freq = dict() two_occurred = False three_occurred = False for letter in line: try: letter_freq[letter] = lett...
""" Name: Jasmin Maizel Final Project subject: Cryptography - Enigma this is the Users file, accesses the database Python Version: 3.7.4 Date: 10.02.2021 """ import functools import hashlib import re import sqlite3 class Users: """ class database of users. it checks the log in, sign in and cr...
# -*- coding:utf-8 -*- import unittest import random import copy class ListNode: def __init__(self, x): self.val = x self.next = None def __repr__(self): return repr(self.val) class List: def __init__(self, head=None): self.head = head def append(self, data): ...
import time import pandas as pd import numpy as np CITY_DATA = { 'Chicago': 'C://Users/Hi55/Downloads/chicago.csv', 'New York City': 'C://Users/Hi55/Downloads/new_york_city.csv', 'Washington': 'C://Users/Hi55/Downloads/washington.csv' } Months=['January', 'February', 'March', 'April'...
#Method for detect platform def detect_platform(): """ Attempt to detect the current platform. Returns : 'Sitara Am35172', 'BeagleBone >=3.8'. """ platform = '' with open('/proc/cpuinfo', 'rb') as f: cpuinfo = f.read().lower() #In this part do it the parameter verification with 'v7l' that #represen...
# Use raw_input to get info from the user nOnes = raw_input('How many ones do you have? ') nFives = raw_input('How many fives do you have? ') nTens = raw_input('How many tens do you have? ') nTwenties = raw_input('How many twenties do you have? ') # Use int to convert the inputted strings to integer values before mult...
list1 = [0, 1, 2, 3, 4, 5, 6, 7, 9, 8] list2 = [10, 11, 12] # list1.append(1000) # print list1.count(2) #list1.extend(list2) #print list1 # print list1.index(4) # list1.insert(2,1000) # print list1 # r = list1.pop() # print "Returned: ", r # print list1 # r = list1.pop(2) # print "Returned: ", r # print list1 #...
# Increment test from FileReadWrite import * # Here is a constant - the name of the data file that we will use throughout DATA_FILE_PATH = 'CountData.txt' # Main program - reads from file, increments a counter, writes to file if not fileExists(DATA_FILE_PATH): # The file was not found, this is the first time we ...
# Adding game version 3 # Save only the score import random from FileReadWrite import * # means import everything as though it were typed here DATA_FILE_PATH = 'GameData.txt' # Start up code if not fileExists(DATA_FILE_PATH): score = 0 print 'Hi, and welcome to the adding game.' else: score = readFile(D...
## Conditioning on other variables import pandas as pd import seaborn as sns import numpy as np import matplotlib.pyplot as plt import matplotlib.style as style style.use("ggplot") # Load Penguins Dataframe penguins = sns.load_dataset("penguins") print("Penguins DataFrame \n") print(penguins.head(15), "\n") # Once ...
### Pandas import pandas as pd ## Read csv file df = pd.read_csv('Pokemon.csv') print(df) print('\n') ## Read excel file # df_xlsx = pd.read_excel('pokemon_data.xlsx') ## Read text file # df_txt = pd.read_csv('pokemon_data.txt', delimiter= '\t') ## Print first 3 row print(df.head(3)) print('\n') ## Print last 3 ro...
### Showing multiple relationships with facets import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns tips = sns.load_dataset("tips") fmri = sns.load_dataset("fmri") # Show all DF print("Tips DF \n") print(tips.head(10), "\n") print("FMRI DF \n") print(fmri.head(10), "\n") s...
x=0 num = int(input("Digite um número inteiro: " )) while num >= x: print(x) x = x+2
#Henrique Lima lista = [] def quantidade(): n = int(input("Digite a quantidade de números: ")) return n def entrada(n): for i in range(n): num = int(input("Número: ")) lista.append(num) def saida(): for x in lista: print("Valor: " ,x) def main(): a = quantidade() ent...
#Autor: Henrique Lima #Data: 25/03/2020 #Ler o número de maçãs compradas e receber o valor da compra. qtd_macas = int(input("Digite o número de maças que foram compradas: ")) if qtd_macas < 12: print(" O valor total da compra é de: %.2f" %(qtd_macas * 1.30), "R$") else: print(" O valor total da compra é de: %...
nota = float(input("Digite a nota do aluno: ")) while nota <0 or nota >10: print("Inválido! Digite outra nota: ") nota = float(input("Digite a nota do aluno: ")) print("Nota válida: " ,nota)
def numero(n): if n > 0: return "P" else: return "N" def main(): x = int(input("Digite um número: ")) print(numero(x)) main()
#Autor: Henrique Lima #Data: 25/03/2020 #Receber três valores de uma equação de segundo grau e calcular o valor do delta e das raízes reais. import math a = float(input("Digite o primeiro valor: ")) b = float(input("Digite o segundo valor: ")) c = float(input("Digite o terceiro valor: ")) delta = ((b ** 2) - (4 * a *...
import numpy as np import pandas as pd import sys """ Takes the chess.csv file from the UCI repository. It one hot encodes the data set. It returns only the largest class "fourteen" (label == 1) and the "five" class(label == -1) inspired by the procedure in the Pang et al. (2016) paper: https://www.jair.org/index.php...
import time import calendar import csv import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: ...
import requests from bs4 import BeautifulSoup as bs import re # pass this library as it has variables which we will use from PIL import Image # import PIL function from library Image #libraries defined outside the class class links(): #add brackets to class #initially passed four different variables which is ill...
arr = [2, 3, 6, 6, 5, 7] print(max([x for x in arr if x != max(arr)]))