text
stringlengths
37
1.41M
import string #importing stringle module to get string constant import random #module implements pseudo-random number generators for various distributions import pickle #The pickle module implements binary protocols for serializing and de-serializing info={} #creating a empty dictionary # with open("game.p...
import tensorflow as tf def create_feature_columns(dataframe,lable_column_name): ''' Creates Tensorflow Feature_column and returns the feature_columns from the Datafram dataset ''' NUMERICAL_COLUMN_NAMES = ['age','fare'] CATECORICAL_COLUMN_NAMES =list(dataframe.columns.unique()) CATECORIC...
# Python Software Foundation # https://docs.python.org/2.7/tutorial/inputoutput.html 7.2.1. Methods of File Objects # The rest of the examples in this section will assume that a file object # called f has already been created. # To read a file’s contents, call f.read(size), which reads some quantity # of data and ret...
# Functions can also be called using keyword arguments of the form kwarg=value. print "if you put", voltage, "volts through it." print "-- Lovely plumage, the", type print "-- It's", state, "!" # accepts one required argument (voltage) and three optional arguments # (state, action, and type). pa...
""" Задание 2. Предложите фундаментальные варианты оптимизации памяти и доказать (наглядно, кодом, если получится) их эффективность Например, один из вариантов, использование генераторов """ from memory_profiler import profile from memory_profiler import memory_usage import timeit def work_with_indexes(): array...
class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def ...
""" CODE CHALLENGE: LOOPS Delete Starting Even Numbers delete_starting_evens(lst) """ #Write your function here def delete_starting_evens(lst): i = 0 while i < len(lst): if lst[i] % 2 != 0: return lst[i:] else: i += 1 continue return [] #Uncomment the lines below when your function is ...
""" Given an unsorted integer array, find the smallest missing positive integer. Example 1: Input: [1,2,0] Output: 3 Example 2: Input: [3,4,-1,1] Output: 2 Example 3: Input: [7,8,9,11,12] Output: 1 Note: Your algorithm should run in O(n) time and uses constant extra space. """ class Solution: def firstMissing...
""" insert number x in the List(ordered) with appropriate index (ordered) """ def solution(L, x): for i in range(0,len(L)): if x < L[i]: L.insert(i,x) return L else: continue L.insert(len(L),x) return L
# checks to see if a given system is satisfies the additive property of linear systems # Algorithm # given an input signal x1[n], the output response produced is y1[n] and # given an input signal x2[n], the output response produced is y2[n], # then for an input signal x3[n] = x1[n] + x2[n], the output response y3[n] =...
import random as r guess_count = 0 result = 'false' def easy(): even = [] for num in range(1, 20): if num % 2 == 0: even.append(num) even_gen = r.choice(even) return even_gen def intermediate(): odd = [] for num in range(1, 20): if num % 2 != 0: odd.a...
#A tic - tac -toe game (using minimax algorithm) #import clear screen function from special_func import clear,sleep #setup steps_win = 3; number_rows = 3; number_columns = 3; AI_player = "X"; hu_player = "O"; #global var list_spots_origin = []; ###################### def Start(number_rows,number_c...
class Pocket: def __init__(self, balance): self.balance = balance def __str__(self): return ("Account balance : %d" % self.balance) def deposit(self, amount): if (type(amount) == float and amount > 0): self.balance += amount return True else: ...
x = input("What is your name?\t") print( "Hello" + " " + ( str (x) ) + " " + ( str ( len (x) ) ) )
# coding=utf8 import json class MyDict(dict): """ A **Python** _dict_ subclass which tries to act like **JavaScript** objects, so you can use the **dot notation** (.) to access members of the object. If the member doesn't exist yet then it's created when you assign something to it. Brackets notation (d['foo'...
#encoding=utf-8 class Solution: ''' @param integer[] nums @return integer ''' # del nums[i] is o(n) 时间复杂度 def removeDuplicates1(self, nums): i = 0 while i < (len(nums) - 1): if nums[i] is nums[i+1]: del nums[i] else: i += 1...
#encoding=utf-8 """ # Author: Acer # Created Time: 星期二 6/ 2 23:20:05 2015 # File Name: 061-RotateList.py # Description: # @param: # @return: """ class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def rotateList(self, head, k): if not head or...
import numpy as np import sympy as sp def mprint(A): for i in A: print(i) print('\n') # Dot product function from scratch def dprod(v1, v2): return sum((a * b for a, b in zip(v1, v2))) # Write a function to do matrix vector multiplication from scratch: def mvprod(M, v): result = [] for...
#pascal naming convention class Point: #constructor def __init__(self, x, y): self.x = x self.y = y def move(self): print('move') def draw(self): print('draw') #creating object point1 = Point(10,20) #point1.x = 10; print(point1.x) point1.draw()
numbers = [5, 2, 1, 9, 8, 9] uniques = [] for number in numbers: if number not in uniques: uniques.append(number) print(uniques) # numbers = [5, 2, 1, 9, 8, 9] # numbers.sort() # ctr =1 # for i in numbers: # if numbers[ctr] == i: # numbers.remove(i) # ctr += 1 # print(numbers)
""" checkout the decorators function and syntax "at @" """ example_user = {'username': "randomuser", "access_level": "admin"} """ Example 1 approching decorators secure password """ # def get_admin_password(): # return 12345 # def secure_function(secure_func): # if example_user["access_level"] == 'admin': # ...
# Library System - a small library system to describe and keep track of books using dictionaries. # Name: Ruarai Kirk # Student ID: D17125381 # Course: DT265A # Below are the specific functions of the Library System: # A Python function that prints details about all the books in the library. def print_all(dict)...
filename = "input.txt" data = [] data_part2 = [] filehandle = open(filename, 'r') while True: line = filehandle.readline() if not line: break line = line.strip() parts = line.split(":") constraints = parts[0].split(" ") occurence_counts = constraints[0].split("-") ...
""" loop2 """ N = 2 while N <= 10: print(N) N = N + 2 print("Goodbye!")
class Student: def __init__(self,roll,name): self.roll=roll self.age="16" self.name=name def printdetails(self): print("student name "+self.name) print("student age "+self.age) print("student roll no. "+self.roll) S1 = Student("28","Simar") S1.pr...
print "How old are you?", age = raw_input(34) print "How tall are you?", height = raw_input("6'2") #add '6\'2"' to make feet and inces show print "How much do you weigh?", weight = raw_input(185) print "So, you're %r old, %r tall, and %r heavy." % (34, "6'2", 185) #why can't I list the height like before??
def get_length(dna): """ (str) -> int Return the length of the DNA sequence dna. >>> get_length('ATCGAT') 6 >>> get_length('ATCG') 4 """ return len(dna) def is_longer(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna1 is longer than DNA sequenc...
#!/usr/bin/python3 class Me(): def __init__(self, first, last, height, weight, age): self.first = first self.last = last self.height = height self.weight = weight self.age = age # def __str__(self): def loose_weight(self): return self.weight - 5 new_me = Me...
# encoding=utf-8 import random import matplotlib.pyplot as plt import numpy as np import math SAMPLING_NUM = 10000 CANDIDATE_NUM = 20 def check_success(candidates, stop_time): max_in_observation = max(candidates[:stop_time]) chosen = 0 for i in range(stop_time, len(candidates)): if candidates[i]...
#!/usr/bin/python ''' (1) as an exercise, take a list of random integers and sort them into ascending order using your own code if you cannot think of a way to sort the list into order using python that you know, do an internet search for "bubble sort algorithm" the code below gets you started with a list of random un...
#!/usr/bin/python ''' read in every line from a csv file into a list calculate the sum of each column ''' import sys inp = sys.argv[1] data = [] f = open(inp) #read in column headings header = f.readline().strip().split(',') for line in f: #split into columns cols = line.strip().split(',') #conve...
# Faça um programa que percorre uma lista com o seguinte formato: # [['Brasil', 'Italia', [10, 9]], ['Brasil', 'Espanha', [5, 7]], ['Italia', 'Espanha', [7,8]]]. # Essa lista indica o número de faltas que cada time fez em cada jogo. Na lista acima, no jogo entre # Brasil e Itália, o Brasil fez 10 faltas e a Itália fez ...
# Define a procedure, biggest, that takes three # numbers as inputs and returns the largest of # those three numbers. # 1 method def bigger(a,b): if a>b: return a return b def biggest(a,b,c): return bigger(bigger(a,b),c) # 2 method ### return max(a,b,c) # 3 method ''' if b<a or c<a: ...
import numpy as np # Manejo de arrays con numpy # Arreglo desde el 5 hasta el 19 con salto de 3 arreglo_uno = np.arange(5, 20, 3) print("Arreglo general de salto de 3:\n {}\n\n".format(arreglo_uno)) # Matriz de ceros 10x2 matriz_ceros = np.zeros(shape=(10, 2)) print("Arreglo ceros 10x2:\n {}\n\n".format(matriz_ceros)...
def make_incrementor(n): return lambda x: x + n x = int(raw_input("Please enter an integer: ")) f = make_incrementor(x) print f(0) print f(1)
from contextlib import ExitStack from itertools import chain, zip_longest from typing import Generator, List def merge_sorted_files(file_list: List) -> Generator[int, None, None]: """Generator that merge two lists""" with ExitStack() as stack: files = [stack.enter_context(open(fname)) for fname in fil...
import turtle as t from random import randint as rint t.shape("turtle") t.pensize(5) t.colormode(255) t.bgcolor("black") t.tracer(False) for x in range(700): t.color(rint(0,255),rint(0,255),rint(0,255)) t.circle(2*(1+x/4),5) t.speed(20) t.tracer(True)
"""" Module 07 - My Web Scraping learning example """ import requests from bs4 import BeautifulSoup class WebScrap: """ This example parses Quotes from http://quotes.toscrape.com/ """ def __init__(self, arg_url): self.url = arg_url self.bs_html = BeautifulSoup(requests.get(self.url).text, 'lx...
str_var='MyString' int_var = 1 fl_var = 12.5 print('Variable name: "{0}", value: "{1}", type:{2}'.format('str_var', str_var, type(str_var))) print('Variable name: "{0}", value: "{1}", type:{2}'.format('int_var', int_var, type(int_var))) print('Variable name: "{0}", value: "{1}", type:{2}'.format('fl_var', fl_var, type...
""" LEGB Local, Enclosing, Global, Built-In Decoration Demonstration from lesson """ from datetime import datetime from functools import wraps from time import sleep #### Example 1 print('========= Example 1') def my_decorator(func): print('Come to decor=', func) @wraps(func) def wrapper(*args, **kwarg...
isbn = [9, 7, 8, 0, 9, 2, 1, 4, 1, 8] loop_count = 0 while loop_count < 3: num = int(input()) isbn.append(num) loop_count += 1 count = 0 for x in range(0, len(isbn)): if count % 2 == 1: isbn[x] *= 3 count += 1 isbn_val = 0 for x in range(0, len(isbn)): ...
def snakes_ladders(): pos = 0 while pos != 100: roll = int(input()) pos += roll if roll == 0: return "You Quit!" if pos == 54: pos = 19 if pos == 90: pos = 48 if pos == 99: pos = 7...
def sum_to_ten(): die1 = int(input()) die2 = int(input()) if die1 > 9: die1 = 9 if die2 > 9: die2 = 9 correct = 0 for x in range(1, die1 + 1): for i in range(1, die2 + 1): if x + i == 10: correct += 1 total...
'''Convert file sizes to human-readable form. Available functions: approximate_size(size, a_kilobyte_is_1024_bytes) takes a file size and returns a human-readable string Examples: >>> approximate_size(1024) '1.0 KiB' >>> approximate_size(1000, False) '1.0 KB' ''' SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB',...
from matplotlib import pyplot as plt for i in range(0,10): plt.plot([0,i+1],[10-i,0]) for i in xrange(0,-10,-1): plt.plot([0,i-1],[10+i,0]) for i in range(0,10): plt.plot([0,i+1],[-10+i,0]) for i in range(0,10): plt.plot([0,-i-1],[-10+i,0]) plt.plot([0,0],[-10,10]) plt.plot([-10,10],[0,0]) plt.ylabel('some numbers'...
STOCK_PORTFOLIO = {} STOCKS_WATCHLIST = ['SNAP', 'UBER', 'MSFT', 'ABNB', 'AAPL']; STOCKS_WATCHLIST.sort() MAX_STOCK_QTY = 2 #the max amount of shares willing to hold per stock MAX_UNIT_PRICE = 100.0 #the max unit price willing to buy per share PREV_STOCK_PRICES = {} def main(stock_prices): """ Strategy: tit f...
class ProbableTournamentTree(): """ the probable tournament tree details the likely winners of games from the round of 16 on """ MAX_LEVEL = 4 class Node(): def __init__(self, left, right, winner=None): self.left = left self.right = right self.winner = wi...
def strsort(a_string): return ''.join(sorted(a_string)) # print(strsort('python')) def even_odd_sum(sequence): my_list = [] sum_odd = 0 sum_even = 0 for nr in sequence: if sequence.index(nr) % 2 == 0: sum_odd += nr else: sum_even += nr my_list.append(s...
import string def gematria_dict(): return {char: index for index, char in enumerate(string.ascii_lowercase,1)} GEMATRIA = gematria_dict() def gematria_for(word): return sum(GEMATRIA.get(one_char, 0) for one_char in word) def gematria_equal_words(input_word): our_s...
import time def word_count(filename): counts = { 'characters': 0, 'words': 0, 'lines': 0 } unique_words = set() for one_line in open(filename): counts['lines'] += 1 counts['characters'] += len(one_line) counts['words'] += len(one_line.split()) u...
#!/bin/python3 import math import os import random import re import sys # Complete the isValid function below. def isValid(s): # Iterate and count how many times string occured character_dict = {} for character in s: if character in character_dict: character_dict[character] += 1 ...
def split_and_join(line): # write your code here # "split(" ")" method -> splits a string into a list by using space as delimiter split_line = line.split(" ") # "join()" method -> joins each element of an iterable (such as list, string and tuple) by a string separator (the string on which the join() met...
# Reverse L1 and L2. # Amalgamate each digit of the reversed listNodes into two seperate numbers # Return the sum of those two numbers class ListNode: def __init__(self, x): self.val = x self.next = None l1 = ListNode(2) l1n2 = ListNode(4) l1n3 = ListNode(3) l1.next = l1n2 l1n2.next = l1n3 l2 = ...
''' Created on Feb 11, 2015 @author: adudko ''' from sys import version_info class DishType(): ENTREE = 1 SIDE = 2 DRINK = 3 DESSERT = 4 class Dish(): def __init__(self, type, name): self.type = type self.name = name def __eq__(self, other): #should be repla...
def hanoi(n, _from, _by, _to): if(n == 1): print("{} {}".format(_from, _to)) return hanoi(n - 1, _from, _to, _by) print("{} {}".format(_from, _to)) hanoi(n - 1, _by, _from, _to) n = int(input()) if(n != 0): print(pow(2, n) - 1) hanoi(n, 1, 2, 3)
def binarySearch(arr, l, r, x): while l <= r: mid = l + (r - l) // 2; # Check if x is present at mid if arr[mid] == x: return mid # If x is greater, ignore left half elif arr[mid] < x: l = mid + 1 # If x is smaller, ignore right half else: r = mid - 1 # If we reach here, then...
def coinChange_Combination_amount_respect(denom, amount, lastDenomIndex, ans): if amount == 0: print(ans) return for i in range(lastDenomIndex, len(denom)): if amount >= denom[i]: coinChange_Combination_amount_respect(denom, amount - denom[i], i, ans + str(denom[i])) def co...
import RPi.GPIO as GPIO # Define a callback function that will be called by the GPIO # event system: def onButton(channel): if channel == 23: print("Button",channel,"was pressed!") # Setup GPIO23 as input with internal pull-up resistor to hold it HIGH # until it is pulled down to GND by the connected butt...
import calendar import time ticks = time.time() #time intervals are floating point numbers in units of seconds. Particular instants in time are #expressed in seconds since 12:00am January 1 1970 print("no of ticks since 12:00am January 1 1970 is : " ,ticks) localtime = time.localtime(time.time()) print(localtime) loca...
string = input("enter string") vowels = ['a','e','i','o','u'] string = string.casefold() count = 0 for char in string: if char in vowels: count = count + 1 print(count)
"""items = [1,2,3,4,5] squared = [] for x in items: squared.append(x**2) print(squared)""" squared = [] items = [2,3,4,5] def sqr(x): values = x**2 squared.append(values) list(map(sqr,items)) print(squared)
class person: def __init__(self,id): print("our class is crated" ,id) self.id=id def __del__(self): classname = person.__name__ myclassname = self.__class__.__name__ print("our class is destroyed",classname,myclassname) def setfullname(self,firstname,lastname): ...
import itertools ,random deck = list(itertools.product(range(1,14),['spade','Heart','Diamond','Club'])) random.shuffle(deck) print("you got") for i in range(5): print(deck[i][0],"of",deck[i][1]) """ 00 01 10 11 20 21 30 31 40 41 (1,2,3,4,5,6,7,8,9,10,11,12,13) , ['spade','Heart','Diamond','Club'} """
import math """import random a=math.tan(0) print(a) randomnum = random.randrange(0,100) while (not randomnum == 15): print(randomnum ,' ', end = '') randomnum = random.randrange(0,100)""" i = 0 while (i<=20): if(i%2==0): print(i ,"is even num") i+=1 continue else: i+=...
#Factorial de N(1 * 2 * 3 ... * n) CON ITERATIVIDAD def fact(x): result = 1 i = 1 while i != x+1: result = result * i i += 1 return result #1 * 5 * print(fact(10))
''' Data Type int / 정수 float / 소수 str / 문자 bool / True/False ex) a = 3 b = 3.1 c = "Hello" type(a) type(b) type(c) print(a) print(type(a)) a = "3" a = int(a) a = str(a) Type change #str -> int #int -> str #float -> int etc 연산 +, -, *, **, /, // ,% 부등호 >,<, ==, <=, >=, != Variable ? 변하는...
import random def selectMark(): mark = '' while(mark != 'X' and mark != 'O'): mark = input("Select X or O :") mark = mark.upper() if(mark == 'X'): return ['X', 'O'] else: return ['O', 'X'] def selectTurn(): if(random.randint(0,1) == 0): return 'person' e...
''' #if 문 조건이 만족할때 if 문 안에 명령어를 실행 ex) a = 3 if(a == 3): print("a is 3") Q. 숫자를 키보드로 부터 입력받아 짝수 인지 홀수 인지 구분하는 프로그램 개발 Q. 숫자를 입력받아 1이면 덧셈 계산 수행, 2이면 뺄셈, 3이면 곱셈, 4이면 나눗셈, 5이면 나머지를 구하는 프로그램 개발 # and, or and ? 조건이 모두 참일때 참이 된다. or ? 조건 중 하나만 참이면 참이 된다. if(): elif(): else: 은 짝을 이뤄서 프로그램에 맞게 코드를 구현한다. ''' a ...
''' This is a program to implement the judgy hexagons from real life. Idea by Aileen Liang/Hanting Li Implemented in Python by Owen Fei Tutorial on judgy hexagons in real life: First, draw like 8 nested hexagons. Connect all the points with 6 lines. Label each of the lines with a trait (should be the traits ...
import sqlite3 from urllib.request import urlopen import requests import pandas as pd #Definening URLs friends_url="https://snap.stanford.edu/data/facebook_combined.txt.gz" people_url="https://people.cam.cornell.edu/md825/names.txt" #Read URLs into Python people=pd.read_csv(people_url,header=None) friend=pd.read_csv(...
# -*- coding: utf-8 -*- """ Created on Tue Oct 22 04:46:51 2019 @author: Chris Mitchell A vector class for mathematical usage. This vector is defined to be useful in seeing the operations of vector calculus and linear algebra. Other Python libraries such as NumPy have much more efficient vector and matrix operations....
#!/usr/bin/env python # -*- coding: utf-8 -*- import os def val_nota(v): if(v!=1 and v!=2 and v!=4 and v!=8 and v!=16 and v!=32): print("ERRO Nº4 - Valor da nota inválido!") return False return True def main(demo): #demo = "The Simpsons:d=4,o=5,b=160:c.6,e6,f#6,8a,g.6,e6,c6,8a,8f#,8f#,...
def binary_search(lst,item): found = False lower = 0 higher = len(lst)-1 lst.sort() while lower <= higher and not found: mid = (lower + higher)//2 print("Searching for the number :"+str(lst[lower:higher])) print("The lower number is: "+str(lst[lower])+"List index is: "+str(lower)) print("The middle numbe...
def set_x(): x = 2 return None #print(set_x()) #print(list(map(int,"123"))) items = ['Banana', 'Apple', 'Orange' ] qty = [1, 2, 3] print(list(zip(items, map(lambda x: x*10, qty))))
import pandas as pd import numpy as np import string pd.set_option('display.max_columns', None) df = pd.read_csv("starbucks_store_worldwide.csv") # print(df.info()) # ca cn groupd = df.groupby(by=["Country","State/Province"])[["Country"]].count() # print(groupd.loc[['CN'],"Country"]) # CNdf = # print(CNdf) df_index...
arv = float(input("Palun sisesta ruudu külg")) arv = arv * 4 print("Ruudu ümbermõõt on",arv) külg_1 = float(input("Sisesta esimese külje pikkus")) külg_2 = float(input("Sisesta teise külje pikkus")) print("Ristküliku ümbermööt on",(külg_1+külg_2) * 2,"cm")
import math class Sudoku(): def __init__(self, lista): self.table = lista self.tablero_original = [] for i in range(len(self.table)): for j in range(len(self.table)): if (self.table[i][j] != "x"): self.tablero_original.append((i, j)) de...
#!/usr/bin/python3 class Student: def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): if type(attrs) == list: dic = {} for x in attrs: if ...
class NoFly: def fly(self): return "Cannot fly" class NoSound: def make_sound(self): return "..." class Duck(NoFly, NoSound): def __init__(self, name="Duck"): self.name = name def fly(self): return print(" ".join((self.name, '-', super().fly()))) def make_sound(...
import json """ This module is used to make sure the mail isn't from a non allowed email address and the destination is a valid email address Return values : 100 : The destination address is whitelisted and the sending address is not blacklisted 0 : The destination address isn't whitelisted (sender won't be checked in...
import random user_choice = 0 comp_choice = 0 def user_choose(): print("") choice = input("Choose any one from Rock[r/R], Paper[p/P], Scissor[s/S]: ") if choice in ["Rock", "r", "rock", "ROCK", "R"]: choice = "r" elif choice in ["Paper", "p", "paper", "PAPER", "P"]: choice = "p" ...
# Python program to print Prime Numbers Between 1 to 20 firstNumber =1 lastNumber =20 print("Prime Numbers Between 1 to 20 are :") while firstNumber<=lastNumber: for i in range(lastNumber+1): if i==lastNumber: firstNumber +=1 # print("number now ", number) for j in range(2, lastNumb...
# Python program to check whether a number is prime number # 2,3,5,7,11,13,17,19 number = int(input("Enter a number ")) if(number<=1): print("Enter number greater than 1") else: for i in range(2,number): if(number%i)==0: print(number ," is not a Prime ") break else: ...
""" Python 2 2-player Battleship Author: Pairode Jaroensri Last visited: August 2016 """ import os os.system('clear') board1 = [] # Show to the other player board1_content = [] # Show to owner board2 = [] board2_content = [] for x in range(8): board1.append(["O"] * 8) board1_content.append(["O"] * 8) board...
""" Author: Pairode Jaroensri Last revision: March 3, 2018 This program plots the CPU temperature in real time with the poll rate of FREQUENCY Hz and plotting up to TIME_LENGTH seconds back. FREQUENCY is best kept under 5 Hz. Dependencies: lm-sensors, matplotlib, tkinter Usage: python3 plot_cpu_temp.py [-h] [frequen...
#!/usr/bin/python3 import time import calendar #获取时间戳,使用time.time()是时间戳 ticks = time.time() print("当前时间戳为:",ticks) #获取本地时间,通过localtime()可以将时间戳显示为年月日时分秒 localtime = time.localtime(time.time()) print("本地时间为:",localtime) #通过time.asctime()对获取的时间进行处理,显示为 星期 月份 日 时间 年份 的便于浏览样式 localtime1 = time.asctime(localtime) print("本地时...
def getduplicate_numbers(my_number_list): non_duplicate_list = [] duplicate_list = [] for number in my_number_list: if number not in non_duplicate_list: non_duplicate_list.append(number) else: duplicate_list.append(number) #Append the missing number to the list of du...
#Using the word import to import the random function import random #shuffle is also part of random, which allows a word to be shuffled from random import shuffle #Set the original word so that the code can compare what it is later originword='jason' #Create a list so that the word can be shuffled, shuffle only works ...
##CHANGES -V1.0## #NA - Beginning of the code! import turtle import math #creating a new screen window = turtle.Screen() #set backbground to black window.bgcolor("black") #Name window A mAze game window.title("A Maze game") #How big the window should be window.setup(700,700) #A class is a definition of an object ...
import sys def read_stdin_col(col_num): """ Function that reads an input file from stdin, takes a column number and converts the numbers in the column to a list Arguments --------- col_num : int Column number to read from stdin and convert to list Returns ------- ...
from article import Article import os class Warehouse: def __init__(self): self.run = True self.spaces = { "a1": None, "a2": None, "a3": None, "b1": None, "b2": None, "b3": None } self.weight = 0 self.occ...
#Mathematische Formel zur Berechnung des Pascalschen Dreiecks: #Im Prinzip ist das Pascalsche Dreieck die Darstellung der Binomialkoeffizienten. #Es ergibt sich also, dass der untergeordnete Wert die Summe der darübergeordneten Elemente ist. list1 = [[1]] list2 = [] count = 0 print("Hallo mein Name ist Bob! \nIch wer...
"""Implimentation of the recursive binary search algorithm. Uses the divide-and-conquer method to find an element in a list. """ def binary_search(lst: list, left: int, right: int, target: int): if right >= left: mid = left + (right - left) // 2 #print(mid) if lst[mid] == target: ...
sqr = [] for i in range(1, 11): sqr.append(i**2) print(sqr) sqr1 = [i**2 for i in range(1, 11)] print(sqr1) neg = [] for j in range(1, 11): neg.append(-j) print(neg) neg1 = [-j for j in range(1, 11)] print(neg1) names = ["neeraj", "kumar", "chauhan"] first = [] for name in names: first.append(name[0]) pri...
class Laptop: def __init__(self, brand, model, price): self.brand = brand self.model = model self.price = price self.name = brand + " " + model l1 = Laptop("dell", "n5010", 45000) l2 = Laptop("lenovo", "l3451", 30000) print(l1.brand) print(l2.brand) print(l1.name)
s = {"a", "b", "c"} if "a" in s: print("present") else: print("not present") for i in s: print(i) s1 = {1, 2, 3, 4, 5, 6, 7} s2 = {4, 5, 6, 7, 8, 9, 10} union = s1 | s2 intersection = s1 & s2 print(union) print(intersection)
num = int(input("Enter number upto which you want sum : ")) sum = 0 for i in range(1, num + 1): sum = sum + i print(f"Sum = {sum}")
num = int(input("Enter an +ve integer : ")) def cube(n): c = {} for i in range(1,n+1): c[i] = i**3 return c print(cube(num))
fruits1 = ["grapes", "banana", "apple", "mango"] fruits2 = ("grapes", "banana", "apple", "mango") fruits3 = {"grapes", "banana", "apple", "mango"} print(sorted(fruits1)) print(fruits1) print(sorted(fruits2)) print(fruits2) print(sorted(fruits3)) print(fruits3) names = [ {"name" : "neeraj", "age" : 23}, {"name" ...
num = [1, 2, 3, 4] square = list(map(lambda a : a**2, num)) print(square) names = ["Neeraj", "Kumar", "Chauhan"] length = list(map(len, names)) print(length)