text
stringlengths
37
1.41M
age = input("What is your current age?") age = int(age) years_remaining = 90 - age days = years_remaining * 365 weeks = years_remaining * 52 months = years_remaining * 12 print(f"You have {years_remaining} years,{days} days, {weeks} weeks, and {months} months left.")
''' This file takes two input files `flicknamn.csv` and `pojknamn.csv` as per the `example_input.csv` format, joins the content and spits out a single normalized file with all the names that have names that can be writen with only katana ''' import csv import jaconv import re ''' normalize an integer string with or w...
import sys def printSecondHighestAndHighestFunction(listOne): secondLargest = -sys.maxsize-1 largest = -sys.maxsize-1 for value in listOne: if value > secondLargest and value < largest: secondLargest = value if value > largest: secondLargest = largest largest = value print("Second lar...
def get_input(): with open("input.txt") as f: s = f.read().strip() lines = s.split("\n") print(f"num lines = {len(lines)}") total_length = sum(len(line) for line in lines) print(f"avg line length = {round(total_length/len(lines),2)}") return s def grid(s, split = None): if split is...
with open("input.txt") as f: s = f.read().strip().split("\n") # + => + # * => - class P1: def __init__(self, v): self.v = v def __add__(self, o): return P1(self.v + o.v) def __sub__(self, o): return P1(self.v * o.v) ans = 0 for l in s: l = "".join("P1("+x+")" if x.isdigi...
# -*- coding: utf-8 -*- """ Created on Fri Jul 27 15:32:26 2018 @author: shaileeg """ class Animal: def __init__(self, name ="No name"): self._name = name def getName(self): return self._name lion = Animal() monkey = Animal("Tarzan") print(lion.getName()) print(monkey.g...
import random # Gets the value of a coordinate on the grid. def l(r, c, b): return b[r][c] # Places a bomb in a random location. def placeBomb(b): r = random.randint(0, row-1) c = random.randint(0, column-1) # Checks if there's a bomb in the randomly generated location. If not, it puts one t...
import unittest class Node: def __init__(self, key): self.key = key self.is_last_sibling = False # indicate if the node is the last sibling self.left_child = None self.next = None # if the node is last sibling, it points to parent, else it points to right sibling def print_chil...
import unittest class Node: def __init__(self, key, p=None, left_child=None, right_sibling=None): self.key = key self.p = p self.left_child = left_child self.right_sibling = right_sibling def print_tree(node): if node is not None: print(node.key) if node.left_chi...
import unittest class Node: def __init__(self, key): self.key = key self.next = None self.prev = None class CircularDoublyLinkedList: def __init__(self): self.nil = Node(None) self.nil.next = self.nil self.nil.prev = self.nil def list_search(L, k): x = L...
import random import unittest def counting_sort(A, k): B = [0 for _ in range(len(A))] C = [0 for _ in range(k + 1)] for num in A: C[num] = C[num] + 1 # C[i] now contains the number of elements equal to i. for i in range(k): C[i + 1] = C[i + 1] + C[i] # C[i] now contains the num...
# references: # https://realpython.com/python3-object-oriented-programming/ used to learn about python OOP # https://levelup.gitconnected.com/writing-tetris-in-python-2a16bddb5318 used and modified this example for core tetris app (IMPORTANT) # https://www.educative.io/edpresso/how-to-generate-a-random-string-in-python...
#This code was made with the intent of testing the board.py module from board import * def run(): rows=int(input('Insert the number of rows: ')) columns=int(input('Insert the number of columns: ')) mainBoard = Board(rows,columns) while True: print('') print('MENU') prin...
cdevfbrb def bigger(a,b): if a>b: return a else: return b def biggest (a,b,c): return bigger(bigger(a,b),c) def median (a,b,c): f = biggest(a,b,c) if f == a: if c>=b: return c else: return b if f == b: if a>=c: return a else: return c if f == c: if a>=b: return a else: return ...
# Aula 6 - P2 - 12-11-2019 # Estruturas de repetição - FOR <<<<<<< HEAD #--- for simpes usando range com incremento padrão de 1 for i in range (0,10,): print (f'{i}- Padawans HbPy') #--- for simpes usando range com incremento de 2 ======= #--- for simples usando range com incremento padrão de 1 for i in range (0,1...
#--- Exercício 2 - Dicionários #--- Escreva um programa que leia os dados de 11 jogadores #--- Jogador: nome, posição, numero, pernaboa #--- Crie um dicionário para armazenar os dados #--- Imprima todos os joogadores e seus dados lista_jogadores = [] for i in range (1,3): jogador = {} jogadores= {'nome': '',...
#Aula 4_2 13-11-2019 #Boleanas #---- Variável booleana simples com True ou False validador = False #---- Substituição do valor inicial validador = True #----- Criação de variável booleana através de expressão de igualdade idade = 18 validador = ( idade == 18 ) print (validador) #----- Criação de variável booleana at...
import funciones as fnMatriz def main(): #Abrimos el archivo uno text1=open("ejemplo1.txt","r") sentences_text1 = text1.read().lower() sentences_text1 = fnMatriz.extract_words(sentences_text1) #Abrimos el archivo dos text2=open("ejemplo2.txt","r") sentences_text2 = text2.read().lower() sentences_text2 = fnMatr...
# Listas meses = ['Enero', 'Febrero', 'Marzo'] # print(meses[1]) # Si usamos posiciones negativas contará de atras hacia adelante # print(meses[-1]) # Para traer elementos con limites, el primero indica desde donde # y el segundo hasta que sea menor que # print(meses[0:2]) # Para agregar elementos a la Lista meses....
from random import choice import sys def open_and_read_file(file_path): """Takes file path as string; returns text as string. Takes a string that is a file path, opens the file, and turns the file's contents as one string of text. """ # your code goes here open_file = open(file_path) in...
#mega tezky :( #rozdelit pole A do K casti tak aby v se vratilo co nejmensi nejvetsi soucet hodnot v poli #The large sum is the maximal sum of any block. def blocksNo(A, maxBlock): # Initially set the A[0] being an individual block blocksNumber = 1 # The number of blocks, that A could ...
def bubble_sort(a): sort_a = a[:] return sort(sort_a) def sort(b): srted = True for idx, i in enumerate(b): if idx + 1 < len(b): #konec pole if i > b[idx+1]: #porovnani bigger = b[idx] b[idx] = b[idx+1] b[idx+1] = bi...
def day1_split(): with open('day1.txt', 'r') as f: lines = f.read().splitlines() return lines def day1_part1(start=0): freq = start for l in day1_split(): x = int(l) freq += x return freq def day1_part2(start=0): freq = start freqs = set() updates = day1_split...
print ('Введите имя:') x = input() x = str(x) if x == 'Вячеслав': print ('Привет, Вячеслав') else: print ('Нет такого имени') input ('Press Enter to exit')
def quickSort(vect): if len(vect) <= 1: return vect element = vect.pop(0) v1 = [x for x in vect if x < element] v2 = [x for x in vect if x >= element] v1 = quickSort(v1) v2 = quickSort(v2) return v1 + [element] + v2 if __name__ == '__main__': print(quickSort([10, 2, 4, 1, -5, 7]...
# 2019-01-24 # Revision of Python Morsels exercises by Trey Hunner # Get the earliest date from a list of dates in a month-day-year format: def get_earliest(*dates): def date_convert(date): m,d,y = date.split('/') return y,m,d return min(dates, key=date_convert) from collections import Counter import re # Coun...
# Attempt at solving Python Morsels problem: tail # Return the last 'n' items from a sequence 'seq' def tail(seq, n): tail = [] if n < 0: return tail else: for idx,val in enumerate(seq): tail.append(val) if idx >= n: tail.pop(0) return tail
#!/user/bin/python #Created by Brian Schapp, 19 August 2020 import math, random, sys, os, itertools import tkinter as tk from tkinter import messagebox as mbx root = tk.Tk() root.geometry('300x600') board = tk.Canvas(root, height=600, width=300, bg = 'peru') # CODE GENERATION ##############################...
#!/usr/bin/env python # coding=utf-8 a = input("请输入一个数字") if a >=50: print a else: print -a
#David Centeno #5001 Intensive Foundations #Spring 2021 ## Version 3.0 ## # A turtle interperter that has been updated to make use of classes. Assigns certain characters to turtle functions import sys import turtle as t import random class TurtleInterpreter: initialized = False def __init__(self, dx = 800 ,...
#David Centeno #5001 Intensive Foundations import sys import graphicsPlus as gr #Swaps the red and blue values of an image def swapRedBlue( src ): #col gets src's width cols = src.getWidth() #row gets src's height rows = src.getHeight() #iterates through the col and row of srcs pixels. #Its ...
#David Centeno #5001 Intensive Foundations #Spring 2021 ## Version 3.0 ## #A shape file that creates classes to be called for use of drawing shapes in other files. import turtle_interpreter class Shape: def __init__(self, distance = 100, angle = 90, color = (0, 0, 0), istring = '' ): # create a field of se...
from datetime import datetime, timedelta from calelib import Constants def get_deadline(deadline_string): """ Parse string like to datetime object :param deadline_string: string in format "DAY MONTH" :return: string in datetime format """ if len(deadline_string.split(',')) > 1: date,...
""" A set is an unordered collection of items. Every set element is unique (no duplicates) Creating Python Sets A set is created by placing all the items (elements) inside curly braces {}, separated by comma, or by using the built-in set() function. """ # Different types of sets in Python # set of integ...
my_string = 'Hello' print(my_string) my_string1 = "Hello" print(my_string1) my_string = """ Hello, welcome to the world of Python Thank You """ print(my_string) print('What\'s there') name = "nazmul haque" print(name.title()) print(name.upper()) print(name.lower()) first_name = "Akbar"...
##Decimal to Binary # from collections import deque # s=input() # if(s[::1]==s[::-1]): # print("Palindrome") # else: # print("Not") # def dividBy2(n): # s="" # while(n>0): # s=s+(str(n%2)) # n=n//2 # print(s) # print(s[::-1]) # dividBy2(30) ##############################...
class Sudoku: def __init__(self, grid): self.grid = grid # 9x9 matrix with 0s for empty cells def __init__(self): # 9x9 matrix with 0s for empty cells self.grid = [[0 for c in range(9)] for r in range(9)] def at(self, row, col): res = self.grid[row][col] return res...
def is_prime(a): if a == 1: return False for d in range(2,a): if a%d == 0: return False return True a = int(input('Число: ')) if is_prime(a) == True: print('Простое') else: print('не простое')
name = 'Jessie' def hop(start, stop, step): """ Creates a list of numbers from start and with steps :param start: starting number of the list :param step: number of steps to the next number in the list :return: list """ return [i for i in range(start,stop,step)]
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """Implement a single-linked list. Usage: $ python singly_linked_list.py """ from __future__ import absolute_import from __future__ import division from __future__ import print_function class Node(object): """Class to implement a node in a singly-linked list.""" ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """Converts decimal numbers (both integer and real) to binary. Usage: $ python decimal_to_binary.py <decimal_input> Example: $ python decimal_to_binary.py 1901 11101101101 $ python decimal_to_binary.py 3.75 11.11 $ python decimal_to_binary.py 0.6640625 0.10101 """ fr...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """Implementing insertion sort. Insertion sort operates this O(n^2) time complexity on worst case. Insertion sort can be divided in two repeatitive steps. 1. Iterating over each element in the array to place it in its proper position. 2. Moving elements to the right whi...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """Design a system for a parking lot. Assuming there are four sizes of slots in the parking lot for four different sizes of vehicles. If no empty slot can be found for a vehicle's size, the vehicle can be upgraded to a larger size slot. Even if an instance of ParkingLot...
import re # regular expressions import sqlite3 # This is a base class for objects that represent database items. It # implements # the store() method in terms of fetch_id and do_store, which need to be # implemented in every derived class (see Person below for an example). class DBItem: def __init__(self, conn): ...
import tensorflow as tf # A tensor variable with initial value [2.5, 4] b1 = tf.Variable([2.5, 4], tf.float32, name='var_b1') # Placeholders can hold tensors of any shape, if shape is not specified x = tf.placeholder(tf.float32, name='x') b0 = tf.Variable([5.0, 10.0], tf.float32, name='b0') y = b1 * x + b0 # Make t...
def quiz(p, q): if p == False: return False elif q == False: return False else: return True print quiz(True, True) print quiz(True, False) print quiz(False, True) print quiz(False, False) print '------------' p, q = True, True print p and q p, q = True, False print p and q p, q = F...
# "Stopwatch: The Game" # Create an event-driven & interactive # stop-watch game # script author: pk # written 2016/04/16, change line 56 on 04/19 removed one global call in def timer_stop() # -------------------------------------------------- # - import(s) import simplegui # - global binding(s) total_ticks = 0 timer...
""" #- "Zombie Apocalypse" by pdk #- For Coursera: Rice U. Principles of Computing pt.2 #---#----1----#----2----#----3----#----4----#----5----#----6----#----7-2--#----8----#----91234567100 """ import random import poc_grid import poc_queue import poc_zombie_gui EMPTY = 0 FULL = 1 FOUR_WAY = 0 EIGHT_WAY = 1 OBSTACLE ...
#Challenge: Given numbers a, b, and c, #the quadratic equation ax2+bx+c=0 can have #zero, one or two real solutions #(i.e; values for x that satisfy the equation). #The quadratic formula #x=-b +/- sqrt(b2&#8722;4ac)2a #can be used to compute these solutions. #The expression b2 - 4ac is the discriminant #associated with...
# "magic 8-ball" import random def number_to_fortune(number): '''convert 0 through 7 to a fortune text''' fortune_list = ['Yes, for sure!','Probably yes.', 'Seems like yes...','Definitely not!', 'Probably not.','I really doubt it...', 'Not sure, check ...
# Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем # Об окончании ввода данных свидетельствует пустая строка with open(r'data.txt', encoding='utf-8', mode='w') as my_file: while True: line = input('Введите текст построчно(завершить - пустая срока): ...
""" Student code for Word Wrangler game """ import urllib2 import codeskulptor import poc_wrangler_provided as provided WORDFILE = "assets_scrabble_words3.txt" # Functions to manipulate ordered word lists def remove_duplicates(list1): """ Eliminate duplicates in a sorted list. Returns...
from multiprocessing import Process, Queue __author__ = 'Horia Mut' def print_progress(iteration, total, prefix='', suffix='', decimals=2, barLength=100): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required ...
password = 'a123456' x = 3 x = int(x) while x != 0 : word = input('請輸入密碼') if word != password: x = x - 1 if x == 0: break print('密碼錯誤!還剩下',x,'次機會') if word == password: print ('登入成功!') break
Store Let’s say, you have built a store that is filled with different grocery items. You have observed that customers are facing difficulty to find an item. So you have decided to write a program that would make it easy for users to search for items. # Submission Guidelines Create a folder /home/ec2-user/environment/o...
Pokemon You might have played or at least heard about the famous Pokemon game. It's based on the popular Pokemon series. In this assignment, lets try to simulate some pokemon and some trainers to "catch 'em all". # Submission Guidelines Exam Duration - 5 hr 30 mins Create a folder /home/ec2-user/environment/oop/oop_...
# -*- coding: utf-8 -*- """ Created on Mon Feb 22 17:17:54 2021 @author: uia76912 """ max_value_of_series = int(input("Please enter the final value to be considered in fiboniacci series:")) previous_term = 0 current_term = 1 next_term = 0 fibonacci_series = [0,1] sum_of_even_values = 0 while next_ter...
#函数img2vector 将图像转化为向量 def img2vextor(filename): returnVect = zeros((1,1024)) fr = open(filename) for i in range(32): lineStr = fr.readline() for j in range(32): returnVect[0,32*i + j] = int(lineStr[j]) return returnVect testVector = kNN.img2vector('testDigits/0_13...
# 定义一个函数sum_numbers # 能够接受一个num的整数参数 # 计算1+2+...num的结果 def sum_numbers(num): #1.出口 if num == 1: return 1 #2.数字的累加 num + (1...num-1) #假设sun_numbers 能够正确的处理1...num - 1 temp = sum_numbers(num - 1) #两个数字的相加 return num + temp result = sum_numbers(1000) print(resul...
name_list = ["张三","李四","王五","王小二"] #len(length 长度)函数可以统计列表中元素的总数 list_len = len(name_list) print("列表中包含 %d 个元素" %list_len) #count 方法可以统计列表中某一个数据出现的次数 count = name_list.count("张三") print("张三出现了 %d 次" % count) #从列表中删除第一次出现的数据,如果数据不存在,程序会报错 name_list.remove("张三"123) print(name_list)
def Quicksort(array): if len(array) < 2: return array quicksort([15,10]) + [33] + quicksort([]) > [10,15,33] #一个有序的数组 #快速排序 def quicksort(array): if len(array) < 2: return array #基线条件:为空或只包含一个元素的数组是“有序”的 else: pivot = array[0] #递归条件 less = [i for i in ...
class Person: def cry(self): print("I can cry") def speak(self): print("I can speak %s"%(self.word)) tom=Person() tom.cry() tom.word="hahah" tom.speak() class Person1: def __init__(self): self.country="china" self.sex="male" def speak(self): prin...
import string import math from operator import itemgetter alphabet = list(string.ascii_lowercase) def main_menu(): user_word = input("\nWhat word you want to encrypt?\n").lower() while user_word.isalpha() == False: user_word = input("\nType only letters for encryption\n") while True: tr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 30 09:18:40 2017 @author: innersme """ #조건이 있을 때, """ for i in range(1,11): if i%2 == 0: print('%d is even'%i) else: print('%d is odd'%i) """ # 조건이 두 개 있을 때? year = 2231 #and or 사용하기 if (year%4==0 and year%100!=0) or year%...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 3 13:04:18 2017 @author: innersme [야구게임작성] 중복되지 않는 3자리수를 생성한다. 중복되지 않는 임의의 3자리수를 작성한다. 생성된 수와 입력할 수를 비교하여 - 숫자가 같고 자릿수가 틀리면 ball - 숫자가 같고 자릿수가 같으면 strike 비교결과가 3strike이면 종료되는 코드를 작성하시오. """ #num를 입력값으로 받는 import random a = [] #중복되지 않는 n자리수를...
import sqlite3 def createTables(): connection = sqlite3.connect('AllTables.db') ####################################################################################################################### connection.execute("CREATE TABLE Artists(MemId INTEGER NOT NULL PRIMARY KEY, FullName TEXT NOT NULL, P...
# http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python def all_perms(elements): if len(elements) <=1: yield elements else: for perm in all_perms(elements[1:]): for i in range(len(elements)): #nb elements[0:1] works in both st...
def noOfStrings( n ): #The number of bit strings of bit size n is the (n + 2)th Fibonacci number a1, a2 = 1, 0 #Setting intial values for num in range( n + 1 ): temp = a1 a1, a2 = a1 + a2, temp #Calculating the (num + 2)th Fibonacci number, and using that along with the previous to calculate the next return...
# coding=utf-8 # mache einen string mit einem platzhalter # es ist ein begrüßungstring # der platzhalter wird mit einem namen aufgefüllt # und angezeigt name = "Stepen" print "Welcome {}".format(name) # mache einen string mit einem platzhalter # es ist ein begrüßungstring # mit 2 platzhaltern für v...
"""单例模式 """ class single(object): issingle = None isfirstinit = False def __new__(cls): if not single.issingle: cls.issingle = object.__new__(cls) # single.issingle = True return cls.issingle def __init__(self): if not single.isfirstinit: ...
""" 通过对象和类分别访问私有方法 但类无法访问对象的属性,无论是公有还是私有 """ class Person(): def __init__(self, name): self.name = name self.__age = 18 def __secret(self): print("%s 的年龄是 %d" % (self.name, self.__age)) if __name__ == "__main__": p = Person("xiaofang") print(p._Person__age) p._P...
""" 1.创建子类继承自threading.Thread 2.重写run()方法 3.子类对象调用start()方法 """ import threading import time class myThread(threading.Thread): def __init__(self, num): super().__init__() # 重写父类初始化方法,要先调用父类初始化方法 self.num = num print("我是子类初始化方法", num) def run(self): for i in range(5): ...
# #helloFunc # def hello(): # print('Howdy!') # print('Howdy!!!') # print('Hello there.') # hello() # hello() # hello() ################################ # #DEF Statements with Parameters # #helloFunc2 # def hello(name): # print('Hello ' + name) # # hello('Alice') # hello('Franky') ######################...
#!/usr/bin/env python import sys import time # ECS518U # Lab 5 zzz # Have a nap # The snooze time in secs, or forever if no argument is supplied if len(sys.argv) > 1: num_sec = int(sys.argv[1]) inc = 1 else: num_sec = 1 inc = 0 if num_sec % 2: returnCode = 1 else: returnCode = 0 count = 0 # print 'num_sec, i...
# Initialise maxstep as -1 MAXSTEP = -1 # Function to calculate cycle length def calculate_cycle_length(n): #Initial step as 1 steps = 1 while n != 1: steps += 1 if n % 2 == 0: n //= 2 else: n = 3 * n + 1 return steps # Input values start, end = map(int, input().spli...
# q1_display_reverse.py # display integer in reverse order # get input integer = input("Enter integers:") while integer.isalpha(): print("Invalid input!") integer = input("Enter integers:") # display results print(integer[::-1])
import random from datetime import datetime now = datetime.now() value = (input('Hi there, what is your name? ')) print() #line break str1 = (' It is your lucky day today, ' 'as we are going to play a cool game ' 'of Rock:Paper:Scissors!') if now.hour < 12: #defines time of day for greeting print(...
idade = input("Qual sua idade?") print("Você digitou:", idade) #convertendo a string idade no inteiro idade_int idade_int = int(idade) print("Idade string concatenada com 2") print(idade + "2") print("\n\n") print("Idade numérica somada com 2") print(idade_int + 2)
nome = input("Qual seu nome?") idade = input("Qual sua idade?") print("{} tem {} anos".format(nome, idade)) print(nome, " tem ", idade, " anos") print(nome + " tem " + idade + " anos")
# https://leetcode-cn.com/problems/maximum-subarray/ from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: sub_sum = 0 max_sum = nums[0] for i in range(0, len(nums)): sub_sum = max(sub_sum + nums[i], nums[i]) max_sum = max(sub_sum, max_sum) return max...
# https://leetcode-cn.com/problems/longest-consecutive-sequence/ from typing import List class Solution: def longestConsecutive(self, nums: List[int]) -> int: if not nums: return 0 l = set() for i in range(len(nums)): l.add(nums[i]) sorted_nums = sorted(list(l)) res = [] tmp = [] ...
# https://leetcode-cn.com/problems/symmetric-tree/ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: if not root: return True return se...
# https://leetcode-cn.com/contest/weekly-contest-187/problems/destination-city/ from typing import List class Solution: def destCity(self, paths: List[List[str]]) -> str: if not paths: return "" if len(paths) == 1: return paths[0][1] start_city = set() end_city = set() for i in range(0, len(pa...
# https://leetcode-cn.com/problems/linked-list-cycle/ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: if head is None: return False if head.next is None: return Tru...
# https://leetcode-cn.com/contest/weekly-contest-191/problems/maximum-product-of-two-elements-in-an-array/ from typing import List class Solution: def maxProduct(self, nums: List[int]) -> int: if not nums: return 0 max_ = max(nums) max_idx = nums.index(max(nums)) ans = [] for i in range(0, l...
# https://leetcode-cn.com/contest/weekly-contest-189/problems/rearrange-words-in-a-sentence/ class Solution: def arrangeWords(self, text: str) -> str: if not text: return "" text_list = [] for s in text.lower().split(" "): text_list.append([s, len(s)]) after_sort = sorted(text_list, key=lam...
#https://leetcode-cn.com/problems/valid-parentheses/ class Solution: def isValid(self, s: str) -> bool: if not s: return True if len(s) % 2 == 1: return False s = list(s) tmp_1 = [] flag = False for elem in s: if elem=="(" or elem=="[" or elem=="{": tmp_1.append(elem) i...
# https://leetcode-cn.com/problems/reverse-linked-list/ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: if head == None or head.next == None: return head p...
# https://leetcode-cn.com/problems/decode-string/ class Solution: def decodeString(self, s: str) -> str: stk = [] for ch in s: if ch == ']': sub = '' while stk[-1] != '[': sub = stk.pop() + sub stk.pop() n = '' while stk and stk[-1].isdigit(): ...
import socket as s import os # rget -o test1.txt www.w3.org #get users input print "Format: rget -o <output file> http://someurl.domain[:port]/path/to/file" print "Example: rget -o test.txt http://www.google.com/, [:port] is optional" inputCommand = raw_input("Enter command: ") name = inputCommand.split(" ")[2] file...
def set_intersection(arr1,arr2): set1 = set(arr1) set2 = set(arr2) print set1,set2 output = [] for element in set1 : if element in set2 : print element print output.append(element) print output arr1 = [1,2,3,4,4] arr2 = [1,4,4] set_intersection(arr1,arr2)
class Node(object): def __init__(self,data): self .data=data self.next = None a1= Node("A") b1= Node("B") c1= Node("C") d1= Node("D") e1= Node("E") f1= Node("F") g1= Node("G") a1.next= b1 b1.next= c1 c1.next= d1 d1.next= e1 e1.next= f1 f1.next= c1 n1= Node("1") n2= Node("2") n3= Node("3") n4= ...
import operator def odd_occuring(arr): res = arr[0] for i in xrange(1,len(arr)): res =operator.xor(res,arr[i]) print res arr =[2,2,7,6,7,3,3] odd_occuring(arr)
def dup_remove(arr): s1 =set(arr) print s1 dict ={} for i in arr: if dict.has_key(i): s1.remove(i) print s1 else : dict[i]= True print dict print s1 arr = [1,1,2,2,37,4,4,5,5] dup_remove(arr)
# -*- coding: utf-8 -*- from __future__ import unicode_literals import pygame import random import math #initializing the pygame pygame.init() #creating the screen screen = pygame.display.set_mode((800,600)) #adding background background = pygame.image.load('background.png') # whatever we do in...
# -*- coding: utf-8 -*- """ Created on Sun Jul 26 19:28:08 2020 @author: Aditi Agrawal """ year=int(input("Enter year you wish: ")) if((year%400==0) or (year%4==0) and (year%100!=0)): print(year," is leap year") else: print(year," is not leap year")
# Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, # and that keeps both safe from outside interference and misuse. # The best example of encapsulation could be a calculator. # Encapsulation is a mechanisme of hiding data implementations ...
"""Text analysis in Python""" import pandas as pd import nltk from nltk.corpus import stopwords stop = stopwords.words('english') df = pd.read_json("/Users/Joel/Desktop/Tweets/final_poke_tweets.json") def transform_data_for_processing(data): #Transforms twiiter data into a list of words #And removes stop w...
""" This file contains the motion model for a simple differential drive mobile robot. In the robots frame positive x is forward and positive y is to the left. The control commands are forward velocity and angular velocity. Positive angular velocity if considered counterclockwise. """ import numpy as np from params im...
X = [7.47 , 7.48 , 7.49 , 7.50 , 7.51 , 7.52] Y = [1.93 , 1.95 , 1.98 , 2.01 , 2.03 , 2.06] n = len(X) h = X[1] - X[0] def trapezoidal(X , Y , h): area = (Y[1] + Y[0]) * (h / 2) return area if __name__ == "__main__": i = 0 S = 0 while (i < n - 1): x = [X[i] , X[i + 1]] y = [Y[i...