text
stringlengths
37
1.41M
d ={'a' : 1,'b' : 2,'c' :3} for key in d: print(key, d[key]) print(d) d.clear() print(d) thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.popitem() print(len(d)) for x in thisdict: print(x) print(thisdict[x])
# Create a string and break it in exactly 140 characters headlines = ["Local Bear Eaten by Man", "Legislature Announces New Laws", "Peasant Discovers Violence Inherent in System", "Cat Rescues Fireman Stuck in Tree", "Brave Knight Runs Away", "Papperbok R...
# -*- coding: utf-8 -*- import scipy as sp import scipy.stats as st def friedman_test(*args): """ Performs a Friedman ranking test. Tests the hypothesis that in a set of k dependent samples groups (where k >= 2) at least two of the groups represent populations with different median values. ...
M = [] noOfRows = int(input("enter row value: ")) noOfColumns = int(input("enter column value: ")) for i in range(noOfRows): R = [] for j in range(noOfColumns): element = int(input(f"enter number {j+1} ")) R.append(element) M.append(R) def displayMatrix(): for i in range(noOf...
""" Problem 0.8.3: tuple_sum(A,B) input: list A and B of the same length, where each element in each list is a pair(x,y) of numbers output: list of pairs(x,y) in which the first element of the ith pair is the sum of the first element of the ith pair in A and the first element of the ith pair in B example: given lists ...
output = 0 with open('..//input.txt', 'r') as input: for line in input.readlines(): # print(line) output += int(line) print(output)
import sqlite3 """ Setup Parameters """ sqlite_file = '../../data/database/deeplearning.sqlite' table_name = 'tweets' column_names = ['Id', 'Time', 'Author', 'Text', 'Hashtags', 'Mentions', 'Replies', 'Favourites', 'Retweets'] column_types = ['INTEGER', 'TEXT', 'TEXT', 'TEXT', 'TEXT', 'TEXT', 'INTEGER'...
# A Function in Python is used to utilize the code in more than one place in a program. It is also called method or procedures. Python provides you many inbuilt functions like print(), but it also gives freedom to create your own functions. def func1(): print("I am learning python function") # Significance of Ind...
var1 = "python!" var2 = "Programmer league" print ("var1[0]:",var1[0]) print ("var2[1:5]:",var2[1:5]) print ("y" in var1) print ("p" not in var1) print (f"Hello {var1} {var2}") # string format name = 'python' number = 99 print ('%s %d' %(name, number)) x = "Guru" y = "99" print (x*2) # Python String replace() Metho...
# Calendar module in Python has the calendar class that allows the calculations for various task based on date, month, and year. On top of it, the TextCalendar and HTMLCalendar class in Python allows you to edit the calendar and use as per your requirement. import calendar c = calendar.TextCalendar(calendar.SUNDAY) #...
def Merge(dict1, dict2): dict2.update(dict1) dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4} Merge(dict1, dict2) print(dict2)
''' Venn diagram plotting routines. Copyright 2012, Konstantin Tretyakov. http://kt.era.ee/ Licensed under MIT license. This package contains routines for plotting area-weighted two- and three-circle venn diagrams. There are four main functions here: :code:`venn2`, :code:`venn2_circles`, :code:`venn3`, :code:`venn3_...
''' Write a script that accepts a directory as an argument as well as a container name. The script should upload the contents of the specified directory to the container (or create it if it doesn't exist). The script should handle errors appropriately. (Check for invalid paths, etc.) ''' import pyrax import os def a...
import string def to_rna(sequence): pairs = list(sequence) rna = [] for pair in pairs: rna.append(convert(pair)) rna_sequence = "".join(rna) if len(rna_sequence) == len(sequence): return rna_sequence return "" def convert(pair): if pair == "C": return "G" elif pair == "G": return "C" ...
from functools import reduce def largest_product(number_string, nums): length = len(number_string) - nums + 1 if length <= 0 or nums < 0: raise ValueError if nums == 0: return 1 products = [] for i in range(length): sub_string = number_string[i:i+nums] int_list = [int(x) for x in sub_strin...
""" If the file is a directory, create a directory with the same name in usr, if it doesn't exist if the file is not a directory, just create a symbolic link pointing to the file. """ # see in Packages/<package_name> import os import sys import glob import errno import textwrap from os.path import join, realpath, ab...
from cs50 import get_int def main(): credit = get_int("Number: ") # check to see if the number is too short to be a credit card if (digits(credit) < 13): print("INVALID") return # check if card is valid by calling check_sum function - card is syntactically valid if this is true ...
cake_tuples = [(7, 160), (3, 90), (2, 15)] capacity1 = 20 def max_monetay_value(cake_tuples, bag_capacity): # allocate list which will represent max_monetay value of all capacities up to and including desired one: list_capacities = [0]*(bag_capacity + 1) for current_capacity in range(bag_capacity +1): ...
class Node: def __init__(self, data): self.value = data self.left = None self.right = None def insert(self, data): if self.value == data: return False elif data < self.value: if self.left: return self.left.insert(data) ...
'''A crack team of love scientists from OkEros (a hot new dating site) have devised a way to represent dating profiles as rectangles on a two-dimensional plane. They need help writing an algorithm to find the intersection of two users' love rectangles. They suspect finding that intersection is the key to a matching ...
""" https://en.wikipedia.org/wiki/Knapsack_problem http://stackoverflow.com/questions/3420937/algorithm-to-find-which-number-in-a-list-sum-up-to-a-certain-number https://www.topcoder.com/community/data-science/data-science-tutorials/dynamic-programming-from-novice-to-advanced/ task list = [1,2,3,10] sum = 12 res...
from random import randint def ran(): return randint(1,5) def rand7(): while True: roll1 = ran() roll2 = ran() outcome_number = (roll1 - 1)*5 + (roll2 - 1) + 1 print(outcome_number) if outcome_number == 7 or outcome_number == 1: break if outcome_numb...
# coding=utf-8 # Suppose we could access yesterday's stock prices as a list, where: # # The indices are the time in minutes past trade opening time, which was 9:30am local time. # The values are the price in dollars of Apple stock at that time. # So if the stock cost $500 at 10:30am, stock_prices_yesterday[60] = 500. #...
__author__ = 'bkapusta' ''' Your queue should have an enqueue and a dequeue function and it should be "first in first out" (FIFO). ''' class queue_with_2_stacks: def __init__(self): # create 2 stacks self.in_stack = [] self.out_stack = [] def enqueue(self, item): # append new it...
"""Common types and functions.""" # Classes # ======= class Direction: Fwd = 1 Rvs = 2 class TurnDirection: Cw = 1 Ccw = 2 class Point(object): def __init__(self, x, y): self.X = x self.Y = y def __str__(self): return '(' + str(self.X) + ',' + str(self.Y) + ')' ...
class DoubleStack(): def __init__(self, size=10): self.arr = list(range(10)) self.top1 = -1 self.top2 = size + 1 self.size = size def push1(self, data): if self.top2 - 1 > self.top1: self.top1 += 1 self.arr[self.top1] = data else: ...
# Implement two stack in one Arry class TwoStack(object): def __init__(self, size = 10): self.arr= list(range(size)) self.top1 = -1 self.top2 = size self.size = size def push1(self,data): if self.top1 < self.top2-1 : #condition for overflow self.top1 +=1 ...
class Employee: raise_percentage = 1.05 number_of_employee = 0 ''' raise is a class variable shared by all instance of class ''' def __init__(self, name, sal): self.name = name self.sal = sal Employee.number_of_employee +=1 def raise_salary(self): return sel...
from BinarySearchTree import BinarySearchTree, Node import copy ''' 1. Insertion Logic 2. Search a node 3. creating Mirror image of tree 4 . delete a Node from tree 5. check tree2 is mirror image of tree1 6. path root to each leaf node ''' class CompleteBinaryTree(BinarySearchTree): ''' most of tree travers...
import unittest from code_to_test import add, subtract, divide class TestBasic(unittest.TestCase): def test_add(self): self.assertEqual(add(5, 4), 9) self.assertEqual(add('sudh','anshu'),'sudhanshu') def test_subtract(self): self.assertEqual(subtract(7,3),4) def test_divide(self...
class Employee: raise_percentage = 1.05 number_of_employee = 0 ''' raise is a class variable shared by all instance of class ''' def __init__(self, name, last, sal): self.name = name self.last = last self.sal = sal Employee.number_of_employee +=1 @property ...
##Given an array of integers, find the pair of adjacent elements ##that has the largest product and return that product. def adjacentElementsProduct(inputArray): largestProduct = -1000000000 for i in range(0, len(inputArray) - 1): if inputArray[i] * inputArray[i+1] > largestProduct: ...
def allLongestStrings(inputArray): longest = 0 lst = [] if len(inputArray) == 1: return(inputArray) else: for word in inputArray: if len(word) > longest: longest = len(word) for word in inputArray: if len(word) == longest: ...
# import nltk # # # def clean_str(raw): # raw_words = nltk.word_tokenize(raw) # # Clean words # words = [word for word in raw_words if len(word) > 1] # words = [word for word in words if word.isalpha()] # words = [w.lower() for w in words if w.isalnum()] # # Stop words # #stopwords = set(nlt...
import textwrap # textwrap.fill(text, width=70, **kwargs) # Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph. fill() is shorthand for # "\n".join(wrap(text, ...)) def wrap(string, max_width): return textwrap.fill(string,max_width)
# 每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友, # 今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。 # 其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后, # 他随机指定一个数m,让编号为0的小朋友开始报数。 # 每次喊到m-1的那个小朋友要出列唱首歌, # 然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始, # 继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演, # 并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。 # 请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1) ...
from pygame import * MONSTER_SPEED = 2 LEFT_IMAGE = image.load('blocks_sprites/monster0.png') RIGHT_IMAGE = image.load('blocks_sprites/monster1.png') class Monster(sprite.Sprite): def __init__(self, x, y, left_vel=MONSTER_SPEED, up_vel=3, max_length_up=15): sprite.Sprite.__init__(self) self.reac...
import random import math #portfolio class Portfolio: def __init__(self): #initial three portfolio props self.cash = 0.0 self.stock = {} self.mutualFunds={} self.propToUse = None self.history = "\n\nportfolio's ledger\n \n" #adding cash to the...
from math import atan print("arctan aprēķināšana") x = float(input("Lūdzu ievadiet argument x:")) y = atan(x) print("atan(%.2f) = %.2f"%(x,y)) print(" ---") print(" \\") print(" \\") print("arctan=x/sqr(1+x*x)") print(" /") print(" ...
#!/usr/bin/python3 from Rook_class import Rook from Piece_class import Piece from Position_class import Position from Board_class import Board from King_class import King import sys def main(): chessboard = Board() chessboard.board_init() black_turn = False king_checked = False game_over = False ...
class Position: def __init__(self, x, y): '''Defines a coordinate on the chessboard, where the x axis changes with columns, and the y axis changes with rows.''' self.column = x self.row = y def __str__(self): '''Allows the print command to be used to print out a Po...
c=input() if(ord(c)<65): print("Invalid") elif(c=='a' or c=='e' or c=='i' or c=='o' or 'u'): print("Vowel") else: print("Consonant")
from tkinter import * # math function def add(a, b): return a+b def sub(a, b): return a - b def mul(a, b): return a * b def div(a, b): return a / b def mod(a, b): return a % b def lcm(a, b): L = a if a > b else b while L <= a*b: if L % a == 0 ...
import os import sys from tkinter import * from tkinter import filedialog print("\nPython version: ", sys.version, "\n") def main(): location_of_folders = input('Where do you want the folders: ') name_of_folders = input("What should the prefix for the folders be: ") number_of_folders = int(inp...
def only_ints(int1, int2): if type(int1) == int: if type(int2) ==int: return True else: return False else: return False print(only_ints(1, 2))
from stop_words import get_stop_words stop_words = set(get_stop_words('en')) def convert_text_to_set_without_stop(text): _set = set() for token in text.split(' '): if token and token.lower() not in stop_words: _set.add(token) return _set
# Leetcode Problem 23 # Name: "Merge k Sorted Lists" # Difficulty: Hard # URL: https://leetcode.com/problems/merge-k-sorted-lists/ # Date: 2020-07-25 from typing import List from python3 import ListNode # My opinion on this problem is that it is a lot like a SumK problem where an efficient implementation of Sum2 is ...
# Leetcode Problem 3 # Name: "Longest Substring Without Repeating Characters" # Difficulty: Medium # URL: https://leetcode.com/problems/longest-substring-without-repeating-characters/ # Date: 2020-07-24 class Solution: def lengthOfLongestSubstring(self, s: str) -> int: history = list() max_length...
# Leetcode Problem 4 # Name: "Median of Two Sorted Arrays" # Difficulty: Hard # URL: https://leetcode.com/problems/median-of-two-sorted-arrays/ # Date: 2020-07-24 from typing import List class Solution: def median(self, lst: List[int]) -> float: length = len(lst) mid = int(length/2) if le...
class Student: def __init__(self, name, surname, gender): self.name = name self.surname = surname self.gender = gender self.finished_courses = [] self.courses_in_progress = [] self.grades = {} def rate_lecturer(self, lecturer, course, grade): if isinstanc...
import numpy as np import matplotlib.pyplot as plt class GaussPlay: """Gaussian Data Creation and functional tool.""" def __init__(self): """ Constructor: to instantiate the data. """ self.data = np.random.randn(2, 200) def scatter(self): """ Scatter Plot ...
from sys import argv import string script, filename = argv text = open(filename) word_count = {} # for loop by line: checking for words, adding to dictionary for line in text: line = line.rstrip().lower() for punc in string.punctuation: line= line.replace(punc," ") words = line.split() fo...
for index in range(0,101): if index % 3 == 0 : print( str(index) + " " + "fizz") if index % 5 == 0: print( str(index) + " " + "buzz") if index % 5 == 0 and index % 3 == 0: print( str(index) + " " + "fizzbuzz")
""" Given a m * n matrix of ones and zeros, return how many square submatrices have all ones. Example 1: Input: matrix = [ [0,1,1,1], [1,1,1,1], [0,1,1,1] ] Output: 15 Explanation: There are 10 squares of side 1. There are 4 squares of side 2. There is 1 square of side 3. Total number of squares = 10 + 4 ...
def Merge(arr, p, q, r): l_size = q - p + 1 r_size = r - q arr_left = arr[p:q+1] arr_right = arr[q+1:r+1] i = 0 j = 0 k = p while (i < l_size) and (j < r_size): if (arr_left[i] > arr_right[j]): arr[k] = arr_right[j] j += 1 else: arr[...
# Remove non-ASCII characters in CSV file import sys import re if __name__ == '__main__': if len(sys.argv) < 2: print('Please specify a CSV file') sys.exit(1) input_file = sys.argv[1] print('Input file: {}'.format(input_file)) if input_file.endswith('.csv'): output_file = inp...
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. # ask user for the temperature and convert to a string in 1 step far = float(input("What is the temperature? ")) # convers...
""" This script generates google search queries and uses requests to go get the HTML from the google search page. This was the most time-consuming step in the process. Certain lines are commented out as evidence of debugging and to help me remember what I had already done. Anyways, this script ma...
#!/usr/bin/python3 """ Min value """ def factor(num): """ Return factors of number """ prime_list = [] value = num i = 1 while value != 1: i += 1 if value % i == 0: while (value % i == 0 and value != 1): value /= i prime_list.append(i) ...
# # Functional Programing (Separation of concerns) # # - Pure functions # # - # # - # # # # Pure functions # # - Given the same input, it will always return # # the same output that is, every time we give # # - Function should not produce any side effects # # def multiply_by2(li): # new_list = [] # ...
def multiply(num1, num2): try: return num1 * num2 except (ValueError, TypeError): return 'Please input correct value' def divide(num1, num2): try: return num1 / num2 except (ValueError, TypeError): return 'Please input correct value' except ZeroDivisionError: ...
# # Generators # # we never create a list in memory if use # # generator like this # print((range(0, 100))) # # instead of when we use memory, like this: # print(list(range(0, 100))) # # # def make_list(num): # what we do here: list(range(num)) # result = [] # for item in range(num): # result.append(it...
# Heard on the Street # Q4.17 # payoff = final dice result # player chooses when to stop import random def play_game(turn): is_next = True remaining_turn = turn while is_next: payoff = random.randint(1,6) remaining_turn += -1 is_next = (remaining_turn > 0) and not(terminate(payoff...
# You are given a set A and other n sets. # Your job is to find whether set A is a strict superset of each of the N sets. # Print True, if A is a strict superset of each of the N sets. Otherwise, print False. # A strict superset has at least one element that does not exist in its subset. # Example # Set (1,3,4) i...
# You are given a string . # Your task is to find out whether is a valid regex or not. # Input Format # The first line contains integer , the number of test cases. # The next lines contains the string . # Constraints # Output Format # Print "True" or "False" for each test case without quotes. # Sample Input ...
# Given the names and grades for each student in a Physics class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. # Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line. # Input For...
# You are given a string S and width w. # Your task is to wrap the string into a paragraph of width w. # Input Format # The first line contains a string, S. # The second line contains the width, w. # Constraints # Output Format # Print the text wrapped paragraph. # Sample Input 0 # ABCDEFGHIJKLIMNOQRSTUVWXYZ #...
# Check Tutorial tab to know how to to solve. # Task # Given an integer, n, perform the following conditional actions: # If n is odd, print Weird # If n is even and in the inclusive range of to , print Not Weird # If n is even and in the inclusive range of to , print Weird # If n is even and greater than , print N...
# Задача 4 (опциональная) # Необходимо сократить дробь, записанную в римской системе счисления (числа от 1 до 999). # Римская система счисления: '''https://ru.wikipedia.org /wiki/%D0%A0%D0%B8%D0%BC%D1%81%D0%BA%D0%B8%D0%B5_%D1%86%D0%B8%D1%84%D1%80%D1%8B ''' # Ввод: "II/IV" # Вывод: "I/II" # Ввод: "XXIV/VIII" # Вывод...
""" # Python实用函数 # 包含函数: print_with_style() ----- 拓展print()函数,使其输出时可以携带样式 print_spend_time()装饰器 ----- 获取某函数执行时所消耗的时间 """ from functools import wraps from datetime import datetime def print_with_style(*args, style='', **kwargs): """带样式的打印,它是对print()函数的拓展. # 参数: style:要使用的样式,它可以是以下值:(多个样式之间用加号'+'...
#! /usr/bin/env python """ I was going to implement this in `C++`, but this algorithm is on the front page of Python website. (really!) So, much like my Haskell quicksort implementation, I feel obliged to include this bottom-up fibonacci memoization example.""" def fibonacci(n: int) -> int: a = 0 b = 1 ...
import pandas as pd import sqlite3 # Load the XLSX file into a pandas dataframe df = pd.read_excel('./OI - Copy of LumberFut.xlsx') #dropping the cols which does not have any value df.drop(df[df.Open == "-"].index, inplace=True) #collecting the list of columns col_list = df.columns[1:] #converting them to numeric f...
from lxml import html, etree import requests # functions def build_dictionary_stopwords(string, word_dictionary): """ turns a string into individual, all lowercase words and places them into a dictionary to count them. Includes stopwords""" append_string = "" j = 0 for i in rang...
from tkinter import * from tkinter.ttk import * root = Tk() dolar = StringVar() txtdolar = Entry(root, textvariable = dolar) txtdolar.pack() resultado = StringVar() lblResultado = Label(root, text = '',font = ("Arial", 25), textvariable = resultado) lblResultado.pack() combo = Combobox(root) combo['values'] = ("L...
# ~~~~~~~~~~~~~~~~~~~~~~~~ # Práctica 3: Saul Azcona # ~~~~~~~~~~~~~~~~~~~~~~~~ # 1- Hacer una función que potencie un número x a la y valor = 10 potencia = 2 # Definición de la función con 2 parámetros def pontenciar(a, b): x = a ** b return print(x) pontenciar(valor, potencia) # 2- Realizar una función q...
class person: countinsatnce=0 def __init__(self,fname,lname,age): person.countinsatnce +=1 self.fname=fname self.lname=lname self.age=age @classmethod def countinsatnce(cls): print(f"heloo you call this function in {cls.countinsatnce} and name is{cls.__name__...
########################################## # # KNN.py # Juan Andres Carpio # Naomi Serfaty # ########################################## import math #Function that calculates the Eucledian distance between two points #In: #A: first array #B: second array #Out: #Eucledian distance between them def distance(A,B,named=F...
''' Pravesh Gaire 7/6/2019 Finds the shortest path from a point to another point in mxn grid A* Algorithm TO DO: Neighbours needs to be generalized ''' # Func to check if a cell is valid or not def isValid(x, y): return (x< ROW and x>=0 and y<COL and y>=0) # Func to check if a cell is blocked or not...
def maxSubArray(nums): if len(nums) == 0: return None if len(nums) == 1: return nums[0] max_num = nums[0] num = nums[0] for i in range(1, len(nums)): if max_num < nums[i]: #动态规划找到各个子序列max_num max_num = nums[i] elif max_num >= nums[i]: ...
from math import log def trie_worst_space(c, n, l, s): if c == 0: return -1 if s == 0: if l == 0: return -1 if n == 0: return c ** l foo = 0 cur = n for level in xrange(l, -1, -1): if log(cur * 1.0) / log(c * 1.0) > level - 1.0...
import os, csv, smtplib, ssl message = """Subject: Testing Python Message Capabilities Hi {name}, welcome to the world of python... """ from_address = os.environ.get("EMAIL_HOST_USER") password = os.environ.get("EMAIL_HOST_PASSWORD") get_file = input("""Enter File Name Plus Extension, E.g: contacts.csv ...
def shortest_formula(n): characters = ("0","1","2","3","4","5","6","7","8","9","+","*","**",")","(") i = 1 formulas = [""] while True: formulas = add_perms(formulas, characters) for f in formulas: try: if eval(f) == n: return f, i ...
#!/usr/bin/python # encoding: utf-8 # -*- coding: utf8 -*- """ Created by PyCharm. File Name: LinuxBashShellScriptForOps:decodingNonASCII.py Version: 0.0.1 Author: Guodong Author Email: dgdenterprise@gmail.com URL: https://github.com/DingGuodong/L...
''' Дан массив целых (в том числе отрицательных) чисел. Нужно на языке Python написать функцию, выдающую минимальное произведение, которое можно составить из двух чисел этого массива. ''' from random import randint from sys import maxsize def minMult(l): min_item = max_item = l[0] min_mult = maxsize for ...
#coding=gbk class List(list): def __init__(self): 'ظԶַʵ' def find(self,word): l=len(self) ll=hash(word) fir=0 end=l-1 if fir>end: # self.insert(0,word) return False elif fir<end: #not empty, need to compare ...
class Laboratorio(): def __init__(self, producto): self.producto = producto class Producto(): def __init__(self, nombre, porcentaje): self.nombre = nombre self.porcentaje = porcentaje def get_nombre(self): return self.nombre def get_porcentaje(self): return sel...
import time for i in range(0,101,2): time.sleep(0.1) print(f'{"-"*i:<100}{i:>6.2f}% ',end="\r") """ 单行输出 end="\r" 或者 print(f'\r{"-"*i:<100}{i:>6.2f}% ',end="") 格式化字符串的用法: f-string 格式化字符串以 f 开头,后面跟着字符串,字符串中的表达式用大括号 {} 包起来,它会将变量或表达式计算后的值替换进去 如:f' 字符串{变量:[填充符号| <>^左右中对齐 | .数字f 保留几位小数 | 数字d 保留几位整数不够填充符号] } ...
""" The standard 52-card pack can be stripped to make a deck of: - 32 cards (A, K, Q, J, 10, 9, 8, 7 of each suit), - 28 cards (7s omitted), or - 24 cards (7s and 8s omitted). TODO: In some games, a joker is added. The highest trump is the jack of the trump suit, called the "right bower." The second-highe...
# 1) Design model (3wr) # 2) Construct loss and optimizer # 3) Training loop # - forward pass: ocmpute prediction # - backward pass: gradients # - update weights import torch import torch.nn as nn # f = w * x # f = 2 * x X = torch.tensor([1,2,3,4], dtype=torch.float32) Y = torch.tensor([2,4,6,8], dtype=torch.float...
#NIM:71200539 #Nama:Deon Bintang Sanjaya #Universitas Kristen Duta Wacana """ Bu Rini ingin memisahkan jumlah murid-muridnya berdasarkan gender, buatlah program tersebut dengan output berupa dictionary input:jumlah laki-laki & perempuan laki2=10 perempuan=15 proses:integer tadi digabung dengan string tuple ...
#!/bin/python3 import os # Complete the repeatedString function below. def repeatedString(s, n): len_str = len(s) cnt_a = s.count('a') * (n // len_str) cnt_a += s[slice(n % len_str)].count('a') return(cnt_a) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() ...
#!/usr/bin/python3 # coding: utf-8 # Exercício 1: # * Criar um programa para converter um valor em segundos em horas, minutos e segundos # Requisitos Exercício 1: # * O programa deve pedir os segundos ao utilizador e guardar em uma variável # * De seguida o programa deverá calcular o total de horas, minutos e segundo...
""" 函数 函数的目的:代码复用 函数,就是指为一段实现特定功能的代码“取”一个名字,以后即可通过该名字来执行(调用)该函数。 输入:0个或多个参数 返回:0个或多个值 定义函数的语法: def function_name(形参列表): pass [return [返回值]] """ def sum_and_avg(a, b, message="sum and average", *args, **kwargs): """ 说明文档:求和 均值函数 a: 位置参数 b: 位置参数 message="su...
sentence=raw_input() placeholder=[0]*26 for x in sentence: CODE_X=ord(x) placeholder[CODE_X-97]+=1 Max_freq=max(placeholder) Min_Freq=min([x for x in placeholder if x>0]) Max_Freq_COUNT=sum([1 for x in placeholder if x==Max_freq]) Min_Freq_COUNT=sum([1 for x in placeholder if x==Min_Freq]) if Max_freq==Min_Freq...
""" repeatStr(6, "I") // "IIIIII" repeatStr(5, "Hello") // "HelloHelloHelloHelloHello" """ def repeat_str(repeat, string): return (string*repeat) print("Enter String") string=input() print("Enternumber of times to repeat") repeat=int(input()) print(repeat_str(repeat,string))
""" Return the number (count) of vowels in the given string. We will consider a, e, i, o, and u as vowels for this Kata. The input string will only consist of lower case letters and/or spaces. """ def getCount(inputStr): num_vowels = 0 vows=['a','e','i','o','u'] # your code here for i in inputStr: ...
# -*- coding:utf-8 -*- #ϵͳ from sys import argv script, input_file = argv #庯print_all def print_all(f): print f.read() #庯rewind seekֻǶλ0λ޷ֵ def rewind(f): f.seek(0) #庯print_a_line readlineȡļһ def print_a_line(line_count,f): print line_count,f.readline() #ļ current_file = open(input_file) print "First let's pri...
from argparse import ArgumentParser, FileType import json5 import os import glob import pandas as pd args = ArgumentParser('''./combine_passed_variants.py', description='This program is a simple one to combine the output files containing the variants that passed HGVS normalization into one csv file. Example usage: ./...
# Rolando Josue Quijije Banchon # Software # #Tercer semestre #Tarea 13 de ejercicios de pagina web """Ejercicio 13 Elabore pseudocódigo para el caso en que se desean escribir los números del 1 al 100.""" class Tarea13: def __init__ (self): pass def Variables(self): print("_________________...
# Rolando Josue Quijije Banchon # Software # #Tercer semestre #Tarea 6 de ejercicios de pagina web """EJEMPLO 6: Dado el sueldo de un empleado, encontrar el nuevo sueldo si obtiene un aumento del 10% si su sueldo es inferior a $600, en caso contrario no tendrá aumento.""" class Tarea6: def __init__(self): ...