text
stringlengths
37
1.41M
# Min heap, the keys of parent nodes are less than or equal to those of the # children and the lowest's key is in the root node class Heap: # The init method or constructor def __init__(self, howMany): self.maxSize = howMany # maximum number of items that can be stored self.graphToHeap = {} ...
"""A library to load the MNIST image data.""" import pickle import gzip import os import numpy as np import matplotlib.pyplot as plt from sklearn.decomposition import PCA def load_data(): """Return the MNIST data as a tuple containing the training data and the test data. The ``training_data`` is...
# import pyspark class Row from module sql from pyspark.sql import * from pyspark import * from pyspark import SparkContext import pyspark sc = SparkContext(appName="csv2") # Create Example Data - Departments and Employees # Create the Departments department1 = Row(id='123456', name='Computer Science') department2 =...
def two_sort(array): x = [x[0] for x in sorted(array)] print(x) for el in x: many = x.count(el) if many > 1: print(x.count(el), "litera:", el) # c x[el] for i in range(many): x.remove(el) # print(x.count(el), "litera:", el) ...
def filter_list(l): x = [x for x in l if type(x) == type(1)] print(x) return x filter_list([1,2,'a','b',123]) def filter_1(l): x = [x for x in l if isinstance(x, int)] print(x) return x filter_1([1,2,'aasf','1','123',123]) def filter_2(l): x = list(filter(lambda x: isinstance(x, int),l))...
# coding: UTF-8 import chainer from chainer import Variable import numpy as np # numpyの配列を作成 input_array = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32) print(input_array) # Variableオブジェクトを作成 x = Variable(input_array) print(x.data) # 計算 # y = x * 2 + 1 y = x ** 2 + 2 * x +1 # y'=2*x+2 print(y.data) # 微分値を求める ...
#!/usr/bin/env python3 # Michal Glos # Polynomial class # # The objective of this project is to create polynomial # class, with python "magic" methods equal, not equal # adding, power and string representation. Implementation # should also include its derivative, its value when x is constant # and differention ...
from tkinter import * root = Tk() def myClick(): myLabel = Label(root, text = "You Clicked!!") myLabel.pack() myButton = Button(root, text = "Click Me!", fg = "white", bg = "black", padx = 20, pady = 20, command=myClick) myButton.pack() root.mainloop()
#! /usr/bin/env python import argparse import sys from brew.utilities.temperature import fahrenheit_to_celsius from brew.utilities.temperature import celsius_to_fahrenheit def main(args): if args.fahrenheit and args.celsius: print("Must provide only one of Fahrenheit or Celsius") sys.exit(1) ...
# 1. Add 2 numbers a = 10 b = 25 print(a+b) # 2. Try to add integer with string and see the output c = '15' # print(a+c) This line makes an error by the different data types print(a+int(c)) # 3.Print variable and strings in one line with the help of f string print(f"The c variable is: {c}") # 4.How ...
class Solution: ''' 执行结果:通过 执行用时:40 ms, 在所有 Python3 提交中击败了63.88%的用户 内存消耗:15.1 MB, 在所有 Python3 提交中击败了5.24%的用户 ''' def generateMatrix(self, n): matrix = [[0] * n for i in range(n)] i,j = 0,0 val = 1 right_boundary = n - 1 down_boundary = n - 1 left_b...
class Solution: def rotate(self, matrix): length = len(matrix) matrix_copy = [[0] * length for i in range(length)] for i in range(length): k = 0 for j in reversed(range(length)): matrix_copy[i][k] = matrix[j][i] k += 1 #拷贝数组 ...
class Solution: ''' 执行结果:通过 执行用时:48 ms, 在所有 Python3 提交中击败了16.48%的用户 内存消耗:15.1 MB, 在所有 Python3 提交中击败了69.19%的用户 两次二分法 ''' def searchMatrix(self, matrix, target): if matrix[0][0] > target: return False if matrix[-1][-1] < target: return False def ...
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: ''' 执行结果:通过 执行用时:36 ms, 在所有 Python3 提交中击败了99.04%的用户 内存消耗:14.8 MB, 在所有 Python3 提交中击败了75.49%的用户 一次通过Nice!!!这种题还是得好好画图,看清楚各种特殊情况。 ''' de...
class ListNode:#单链表 def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1, l2): int1 = 0 int2 = 0 i = 0 while l1: int1 += l1.val * (10**i) i += 1 l1 = l1.next ...
''' 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。 注意:答案中不可以包含重复的三元组。 示例 1: 输入:nums = [-1,0,1,2,-1,-4] 输出:[[-1,-1,2],[-1,0,1]] 示例 2: 输入:nums = [] 输出:[] 示例 3: 输入:nums = [0] 输出:[] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/3sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' cl...
print('This is Visual Studio Code!') #计算a+b,a-b a = input('input number a :') a = int(a)#强制类型转换 b = input('input number b :') b = int(b)#强制类型转换 c = a + b d = a - b print('a + b = %d a - b = %2d' % (c,d) ) #转义字符使用 print('I\'m learning Python 3.8') #不转义使用 print(r'默认\\不转义\\') #多行打印 print('''多行测试 line1 line2 line3 ''...
''' Given
 an 
arbitrary
 ransom
 note
 string 
and 
another 
string 
containing 
letters from
 all 
the 
magazines,
 write 
a 
function 
that 
will 
return 
true 
if 
the 
ransom 
 note 
can 
be 
constructed 
from 
the 
magazines ; 
otherwise, 
it 
will 
return 
false. 

 Each 
letter
 in
 the
 magazine 
string 
can
...
#Enter the price of the House you wish to Buy print("Enter the house price") price = float(input()) #Enter the first name print("Enter the first name:") first_name = input() #Enter the last name print("Enter the last name:") #Enter spouse's or partner's first and last name last_name = input() print("Ent...
class grandparent: def __init__(self,h): self.house= h; def grandparenthousepro(self): print("grandparent house is :"+ self.house) class parent(grandparent): def __init__(self,c): self.car = c; super().__init__(h); def parenthousepro(self): print("parent house prop...
#class decleration with methods and veriables class pythontraning: #class decleration board = "white board" #class variable def bookwriting(self,name): #instance method decleration print("i am writing of book"+str(name)); def listening(self,name): print('i am listening the class perfectly'+str(name)); ...
# https://www.youtube.com/watch?v=dO-HQOAUTyA&list=PLuhNJgi9DRWUS-nAXaXUNWtFvW2574-Tu&index=13 # Алгоритм Евклида # Greatest common divisor (gcd) # (a, b) = (a - b, b) # def gcd(a, b): # while a != 0 and b != 0: # if a > b: # a = a % b # else: # b = b % a # return a + b...
def fib(n): if n == 0 or n == 1: return 1 else: return fib(n-1) + fib(n-2) for n in range(0,7): print(fib(n)) print("===") foo = fib del fib for n in range(0,7): print(foo(n)) print("===")
#Python Module to check for input system arguments, it takes care of all of the input values and processes them ready for use by #POSTREC. It also takes care of any "nonsense values" ie values that are not feasible to use, ormay have been entered in error. #It also provides help messages for how to use the program in...
#Use sequence list name_b = ['sunvo','pongpan','SunvoDz'] name_b.append('Mahasarakham') #add last print(name_b) name_b.insert(0,'Tn.Group') #add first print(name_b) name_b.pop() #Delete last print(name_b) name_b.pop(1) #Delete array[1] print(name_b) number = ['0','1','2','5','4'] number.sort() print(number)...
a = ['one','two','tree','four','five'] for test in a: print(test) b = 0 while b<20: b+=1 print("loop %d" %b) for test_demo in range(5,10): print(test_demo) print('\n') for test_demo in range(5,10+1): print(test_demo) print('\n') for test_demo in range(0,10,2): print(test_demo) print('\n') for test...
import string def l_fileline(n): with open("words1.txt", "w") as file: alph = s.ascii_upper l = [alph[i:i + n] + "\n" for i in range(0, len(alph), n)] file.writelines(l) l_fileline(n)(3)
def hyp(string): x = sorted(string) print(*x , sep = '-') hyp(input().split('-'))
line = input() words = line.split(' ') numbers = [int(i) for i in words] numbers.sort(key = lambda x: x == 0) print(numbers)
line = input() words = line.split(' ') numbers = [int(i) for i in words] altitudes = [] al = 0 for i in range(len(numbers)): al = al + numbers[i] altitudes.append(al) max = 0 for i in range(len(altitudes)): if(altitudes[i] > max): max = altitudes[i] print(max)
num = 120 def test(num): if num < 0: raise ValueError('El número es negativo') return num def retest(num): if test(num) > 100: print('OK') retest(-1)
def words(string): words_string = string.split() word_count = {} for i in words_string: if i.isdigit(): i = int(i) if word_count.get(i): word_count[i] += 1 else: word_count[i] = 1 return word_count print (words("olly 12 12 12...
def ari_geo(A): length = len(A) for i in range(1, length+1): if A[i+1] - A[i] == A[i+2] - A[i+3]: return "arithmetic" elif A[i+1] / A[i] == A[i+2] / A[i+1]: return "geometric" elif A == None: return 0 else: return -1 print a...
people = [ ('Joe',78), ('Janet',83), ('Brian',67) ] def super_sum(*args): return sum(args) def hello_again(name,age): return " I am {} and {} years old" def max_min(A): ''' Returns max value - min value e.g. [10, 20, -5, 6] ''' max_, min_ = A[0],A[0] for i in A: if i > max_: m...
def sum_list(numlist): sum_l = 0 for num in numlist: sum_l += num return sum_l print sum_list([10,8,0,2])
class Asteroid: def __init__(self, x, y): self.x = x self.y = y class Robot: def __init__(self, x, y, asteroid, direction): self.x = x self.y = y self.direction = direction self.asteroid = asteroid if self.x > self.asteroid.x: raise MissAster...
import functools def multiplier(l: list): if isinstance(l, list) and all(isinstance(i, (int, float)) for i in l): return functools.reduce(lambda a, b: a * b, l) raise ValueError('The given data is invalid.')
def print_str_analytics(str): printable = 0 a_num = 0 a_bet = 0 dec = 0 lower = 0 upper = 0 w_space = 0 for i in str: if i.isprintable() == True: printable += 1 if i.isalnum() == True: a_num += 1 if i.isalpha() == True: a_bet +=...
# 数组中的第K个最大元素 # 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 # # 示例 1: # # 输入: [3,2,1,5,6,4] 和 k = 2 # 输出: 5 class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ if not nums: ...
class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ b = "" length = 2**31 if len(strs) == 0: return "" for i in strs: le = len(i) if le < length: ...
# 奇偶链表 # 给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。 # # 请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。 # # 示例 1: # # 输入: 1->2->3->4->5->NULL # 输出: 1->3->5->2->4->NULL # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x ...
# 分数到小数 # 给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数。 # # 如果小数部分为循环小数,则将循环的部分括在括号内。 # # 示例 1: # # 输入: numerator = 1, denominator = 2 # 输出: "0.5" class Solution(object): def fractionToDecimal(self, numerator, denominator): """ :type numerator: int :type denominator: int :...
# 两数相加 # 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 # # 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 # # 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 # # 示例: # # 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) # 输出:7 -> 0 -> 8 # 原因:342 + 465 = 807 # Definition for singly-linked list. class ListNode(object): def __init__(self, x)...
# 全排列 # 给定一个没有重复数字的序列,返回其所有可能的全排列。 # # 示例: # # 输入: [1,2,3] # 输出: # [ # [1,2,3], # [1,3,2], # [2,1,3], # [2,3,1], # [3,1,2], # [3,2,1] # ] class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] self...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def addnode(self, head, x): for i in x: s = ListNode(i) head.next = s head = head.next class Solution: def mergeTwoLists(self...
class rect: x, y = 0, 0 def __init__(): print("사각형생성") class rect1(rect): def size(self, x,y): return x * y class rect2(rect): def size(x,y): return x * y rect_type = input("사각형의 종류\n 1)직사각형 2) 평행사변형 :") if rect_type == '1' : rec1 = rect1()
import turtle as t t = t.Turtle() t.shape("turtle") n=60 # t.bgcolor("black") t.color("green") t.speed(0) for x in range(n): t.circle(80) t.left(360/n) input() print("end")
import turtle as t t = t.Turtle() t.shape("turtle") for x in range(15) : t.forward(50) t.right(190) t.forward(50) print("hello 하이!") input()
import unittest import palindrome class TestPalindrome(unittest.TestCase): def test_palindromeness(self): value = palindrome.is_palindrome('racecar') self.assertEqual(value, True) def test_notpalindromeness(self): value = palindrome.is_palindrome('hello') self.assertEqual(val...
# Найдите три ключа с самыми высокими значениями в словаре my_dict = {'a':500, 'b':5874, 'c': 560,'d':400, 'e':5874, 'f': 20} # Первый вариант: import operator max_elem =dict(sorted(my_dict.items(),key=operator.itemgetter(1),reverse=True)) i = 0 for key,value in max_elem.items(): if i <3: pri...
# Выведите первый и последний элемент списка. import random data_list = [random.randint(1,50) for i in range(1,11)] print(data_list) print('Первый элемент : ',data_list[0]) print('Последний элемент : ',data_list[-1])
# Вывести элементы меньше пяти # Первый вариант: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] for i in a: if i < 5 : print(i) # Второй вариант: import functools print(list(filter(lambda i: i < 5,a))) # Третий вариант: print([i for i in a if i < 5])
##Crea un programa que use la lista de números que está adjunta y reciba un número del usuario. Tu programa buscará en la lista la suma que sea igual al número que ingresó el usuario. lista=[5, 2, 3, 1, 6, 7, 90, 4, 3, 8] num = int(input()) x={} list=[] for x in lista: for y in lista: if x == y: ...
import numpy as np def equalize_histogram(image): """Generate an new image with an equalized histogram from the given image. Note: currently, it only supports transformations for grayscale images. # TODO: Add support for normalization. Paramters --------- image: np.ndarray The input...
from enum import Enum from random import choice Gesture = Enum( value="Gesture", names= [ ("F","finger"), ("P","proffer"), ("S","snap"), ("W","wave"), ("D","digit"), ("K","stab"), ("N","nothing"), ("c","clap") # ("d","2 handed digit"), # ("w","2 handed wave"), # ("s","2 handed...
# -*- coding: utf-8 -*- """ Created on Wed Apr 19 21:21:21 2017 @author: Brandon """ # Part 1 - Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Churn_Modelling.csv') # Consider pd.get_dummies() X = dat...
#!/usr/bin/python import curses import random import time from math import sqrt # initialization stdscr = curses.initscr() curses.start_color() curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_BLAC...
print("Hola Mundo!") print("Bienvenid@ haremos una suma ") try: w=int(input("Dame un número ")) e=int(input("Dame un segundo número ")) print("La suma de "+str(w)+"+"+str(e)+"="+str(w+e)) except ValueError: print("Ingresa un dato invalida.Intenta de nuevo")
# -*- coding: utf-8 -*- def get_check_code(fcode): """ Get final check digit with mod 11, 10 encryption algorithm :param fcode: top 14 digits of registration number :type fcode: str or list of int :return: final check digit :rtype: int """ fcode = list(map(int, fcode)) assert len(f...
#!/usr/bin/env python # coding=utf-8 Table = { '1975' : 'Holy Grail', '1979' : 'Life of Brian', '1983' : 'The meaning of Life'} x = '1979' Table[x] = 'Little women' y = Table[x] print y
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # load dataset fashion_mnist = tf.keras.datasets.fashion_mnist (X_train, Y_train), (X_test, Y_test) = fashion_mnist.load_data() X_train, X_test = X_train / 255, X_test / 255 print('The train dataset is of shape: {0}'.format(X_train.shape)) prin...
def SimpleSymbols(str): # code goes here prev = '' prev_is_letter = False for c in str: if prev_is_letter and c != '+': return 'false' if 'a' <= c <= 'z': prev_is_letter = True if prev != '+': return 'false' else: pr...
from datetime import datetime def date_time(time: str) -> str: dt = datetime.strptime(time, '%d.%m.%Y %H:%M') # univesal solution return dt.strftime(f'%d %B %Y year %H hour{(dt.hour != 1)*"s"} %M minute{(dt.minute != 1)*"s"}').lstrip("0").replace(" 0", " ") # on linux # return dt.strftime(f'%-d ...
def long_repeat(line): """ length the longest substring that consists of the same char """ # your code here if len(line) == 0: return 0 cur = line[0] curlen = 0 max = 0 for c in line: if c == cur: curlen += 1 else: cur = c ...
#Uses python3 import sys import queue from math import sqrt from heapq import heapify, heappush, heappop class priority_dict(dict): """Dictionary that can be used as a priority queue. Keys of the dictionary are items to be put into the queue, and values are their respective priorities. All dictionary met...
class ClassName(object): college="East clg"#class shared by all instances """docstring for ClassName""" def __init__(self,name): #instance variable unique to each instance super(ClassName, self).__init__() self.name=name d=ClassName("Millan") print(d.name) print(d.college) #share by all classname ...
a = "Hello Milu" print(len(a)) #len() method is use for geting the length
thisDict = { "Brand":"Tata", "Model":"Nano", "Year": "2013" } for x,y in thisDict.items(): print(x,y)
print ("Задание 2") def everything(n, s_n, b_d, c, em, tel): return ["Вы", n, s_n, "рождены",b_d, ", живете в населенном пункте ", c,'. Ваш email', em, ",телефон", tel] name = input('Введите ваше имя ') surmane = input("Введите вашу фамилию ") bd = input("Ваша дата рождения ") city = input ("В каком городе вы ...
from collections import deque import sys mystack = deque() def show(s): print(mystack) while(1): print("[1] for pushing onto stack.") print("[2] for popping from stack.") print("[3] to exit.") user_io = int(input('Enter your choice:')) if(user_io == 1): x = int(input('Enter number...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 29 07:49:54 2019 @author: saadmashkoor """ """upper_confidence_bound.py - Reinforcement Learning using UCB to solve the multi-armed bandit problem in the context of ads and clickthrough rates""" # Import libraries import numpy as np import pandas...
class A: name="" def __init__(self,a,b): self.a=a self.b=b def __str__(self): return f"{self.a} and {self.b}" @classmethod def test(cls): return cls(3,4) if __name__=="__main__": a=A(2,3) b=A.test() print(b.__dict__) print(a.__dict__)
class USA: def capital(self): print("The capital of usa is washington") def icon(self): print("Statue of liberty") def language(self): print("The language of USA is english") class India: def capital(self): print("The capital of india is delhi") def icon(self): ...
import unittest from main import compound_words class EnglishWordTestCase(unittest.TestCase): def setUp(self): self.input_sequence = ['paris', 'applewatch', 'ipod', 'amsterdam', 'bigbook', 'orange', 'waterbottle'] def test_gives_correct_output(self): self.assertEqual(compound_words(self.input_...
dict_list = ["water","big","apple","watch","banana","york","amsterdam","orange","macintosh","bottle","book"] input_list = ["paris","applewatch","ipod","amsterdam","bigbook","orange","waterbottle", "booking"] dict_set = set(dict_list) input_set = set(input_list) compound_words = set([]) for word in dict_set: for ...
def factorial(x): current = 1 for i in range(1,x+1): current = i * current return current def sumofdigits(x): current = 0 for i in str(x): current += int(i) return current print sumofdigits(factorial(100))
def load_file(filename): f = open(filename, "r") return f.readlines() def sudoku(): sudoku_grids = [] grid = [] for i in load_file("/Users/sam/Desktop/python/Project Euler/p096_sudoku.txt"): if i[0:4] == 'Grid': continue else: grid.append(list(i.strip('\n')))...
import math def triangular(x): a = 1 while type(a) == int: t = a * (1 + a) / 2 if len(factors(t)) >= x: return t else: a += 1 def factors(x): flist = [] for i in range(1,int(math.sqrt(x)) + 1): if x % i == 0: flist.append(i) ...
def digit_sum(x): y = 0 for i in str(x): y += int(i) return y largest = 0 for a in range(1,100): for b in range(1,100): d = digit_sum(a ** b) if d > largest: largest = d print(largest)
def nextfibs(list1): l = len(list1) return list1[l-1] + list1[l-2] def newfibnumber(x): fibs = [1,1] curret_fib = 2 while len(str(curret_fib)) < x: fibs.append(curret_fib) curret_fib = nextfibs(fibs) return fibs print(len(newfibnumber(1000)) + 1)
# 5. Программа запрашивает у пользователя строку чисел, разделенных пробелом. # При нажатии Enter должна выводиться сумма чисел. # Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. # Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме. # Но если вместо числа вводитс...
# Напишите программу, доказывающую или проверяющую, что для множества натуральных чисел выполняется # равенство: 1+2+...+n = n(n+1)/2, где n - любое натуральное число. n = int(input('Введите любое натурльное число: ')) print(f'1+2+...+{n} = {sum(range(0, n+1))}\n' f'n(n+1)/2 = {n * (n+1) / 2}\n' f'Равенст...
list_num = [] num1 = list_num.append(int(input('Введите первое число: '))) num2 = list_num.append(int(input('Введите второе число: '))) num3 = list_num.append(int(input('Введите третье число: '))) list_num.sort() print(f'Число {list_num[1]} - среднее')
bit_and = 5 & 6 bit_or = 5 | 6 bit_xor = 5 ^ 6 bit_left = 5 << 2 bit_right = 5 >> 2 print(f'Выполним логические побитовые операции над числами 5 и 6:\n' f'5 = {bin(5)}\n' f'6 = {bin(6)}\n' f'5 & 6 = {bin(bit_and)} or {bit_and}\n' f'5 | 6 = {bin(bit_or)} or {bit_or}\n' f'5 ^ 6 = {bin(bit_x...
# In[10]: import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # In[11]: #importando datos data = np.loadtxt("resultados_schro.txt", dtype = type(0.0)) # In[12]: #metodo para animacion fig = plt.figure() ax = plt.axes(xlim=(-60,60), ylim=(-0.01,0.01)) line, = ax.plot([], ...
""" Calculate ionic densities consistent with the Poisson-Bolzmann equation. Copyright 2019 Simulation Lab University of Freiburg Author: Lukas Elflein <elfleinl@cs.uni-freiburg.de> """ import numpy as np import matplotlib.pyplot as plt import scipy.constants as sc import decimal np.random.seed(74) def debye(rho_bu...
#Esto es comentario equisde print("Hola Mundo!") print("Adios Mundo!") 5+1 print(4+6) print(5-2) print(3*4) print(20/4) #precedencia de operadores print(5+8*(3+2)) #Tipos de datos print(type(2)) print(type(8.62)) print(type("Texto")) print(type('Texto')) print(type("5")) #Variables mensaje = "Esto es un mensaje" p...
# for item in iterator: # do something with the item my_fruits = ['apple','orange','grapes'] for fruit in my_fruits: if fruit == 'apple' or fruit == 'grapes': print(f'Sudharsan likes {fruit}') else: print(f'Sudharsan does not like {fruit}') for index in range(len(my_fruits)): if my_fr...
weight = 75 address ="103 vaniyambadi" import os,pandas print(type(weight)) print(type(address)) print(type(os)) print(type(os.path.join)) print(address.upper()) print(weight.upper())
from collections import Counter counter = Counter(a=4,b=3,c=2) print(counter) name = Counter('sudharsan') print(name) new_counter =Counter(a=2,b=3) counter.subtract(new_counter) print(counter) counter.update(a=4,b=1) print(counter) from collections import namedtuple # a tuple in which we can access the values via...
''' Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it ''' import time def timer(function): def wrapper(*args,**kwargs): startTime = time.time() result=function(*args,**kwargs) endTime = time.time() t...
vegetables =['ladies finger','potato','beans', 'brinjal'] def containsI(str): if 'i' in str.lower(): return True def strRev(str): return str[::-1] result = list(filter(containsI,vegetables)) print(result) # using filter and map togeather result = tuple(map(strRev,filter(containsI,vegetables))) print(r...
chars = [ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz' ] arr_len = 2 alpha_len = 26 # Find out if character is a letter & if so, return it's indices # Not allowed to use the inbuilt find function def find(char): for i in range(arr_len): for j in range(alpha_len): if char =...
#encoding: UTF-8 # Autor: Roberto Téllez Perezyera, A01374866 ### Descripcion: Este programa calcula la distancia recorrida por un auto a la velocidad que indique el usuario, así # como el tiempo requerido para que se recorran 500 kilómetros. # A partir de aquí escribe tu programa strVel = input ("Introduce con núme...
class BinaryTreeList: def __init__(self, value = None): self.value = value self.left = None self.right = None def add(self, val): if val <= self.value: if self.left: self.left.add(val) else: self.left = BinaryTreeList(val...
from collections import Counter with open("input.txt") as f: entries = [ line for line in f.read().split("\n\n") ] def part1(entries): count = 0 for entry in entries: count += len(Counter(entry.replace("\n", "")).keys()) return count def part2(entries): count = 0 ...
def longestDigitsPrefix(inputString): result = "" for e in inputString: if e.isdigit(): result += e else: break return result
def avoidObstacles(inputArray): inputArray.sort() step = 1 location = 0 while True: if location not in inputArray: if location < max(inputArray): location += step else: return step else: step += 1 location = ...
def adjacentElementsProduct(inputArray): result = inputArray[0] * inputArray[1] for i in range(len(inputArray)-1): num = inputArray[i] * inputArray[i+1] result = num if num > result else result return result
# -*- coding: utf-8 -*- """ Created on Fri Dec 6 09:56:09 2019 @author: Paul """ import copy def read_data(filename): """ Reads orbital map file into a list """ data = [] f = open(filename, 'r') for line in f: data += line.strip().split('\n') f....