Hanwool Codes RSS Tag Admin Write Guestbook
Categories (45)
2025-04-16 04:58:07

What is UNet?

UNet is a deep convolutional neural network architecture originally designed for biomedical image segmentation. It was introduced in the 2015 MICCAI paper titled:

📄 U-Net: Convolutional Networks for Biomedical Image Segmentation
by Olaf Ronneberger, Philipp Fischer, and Thomas Brox [Paper Link]

UNet's core innovation lies in its U-shaped architecture, consisting of a contracting path (encoder) and an expanding path (decoder) with skip connections that merge feature maps from corresponding encoder and decoder layers. This design allows the network to capture context while achieving precise localization, which is crucial for tasks like cell segmentation, tumor boundary detection, and more.


Why UNet?

UNet’s simplicity and effectiveness made it the go-to architecture for medical image segmentation. Its ability to perform well even on small datasets, its flexibility across 2D and 3D medical imaging tasks, and the ease of implementation have led to hundreds of follow-up works and adaptations over the years. Researchers continue to modify and build upon UNet to improve accuracy, efficiency, and generalization across diverse domains.


🔍 About This Blog

This blog aims to showcase the evolution of the UNet family – a timeline of interesting and influential UNet-based architectures from 2015 to the latest publications. Whether you're a researcher, engineer, or enthusiast, this curated collection serves as a reference point and inspiration for exploring semantic segmentation models built upon UNet.


📚 UNet Family Timeline (updated 15/04/2025)

📅 2015

2016

  • V-Net: Fully Convolutional Neural Networks for Volumetric Medical Image Segmentation [paper] [caffe][pytorch]
  • 3D U-Net: Learning Dense Volumetric Segmentation from Sparse Annotation [paper][pytorch]2017
  • H-DenseUNet: Hybrid Densely Connected UNet for Liver and Tumor Segmentation from CT Volumes (IEEE Transactions on Medical Imaging)[paper][keras]
  • GP-Unet: Lesion Detection from Weak Labels with a 3D Regression Network (MICCAI) [paper]2018
  • UNet++: A Nested U-Net Architecture for Medical Image Segmentation (MICCAI) [paper][my-pytorch][keras]
  • MDU-Net: Multi-scale Densely Connected U-Net for biomedical image segmentation [paper]
  • DUNet: A deformable network for retinal vessel segmentation [paper]
  • RA-UNet: A hybrid deep attention-aware network to extract liver and tumor in CT scans [paper]
  • Dense Multi-path U-Net for Ischemic Stroke Lesion Segmentation in Multiple Image Modalities [paper]
  • Stacked Dense U-Nets with Dual Transformers for Robust Face Alignment [paper]
  • Prostate Segmentation using 2D Bridged U-net [paper]
  • nnU-Net: Self-adapting Framework for U-Net-Based Medical Image Segmentation [paper][pytorch]
  • SUNet: a deep learning architecture for acute stroke lesion segmentation and
    outcome prediction in multimodal MRI [paper]
  • IVD-Net: Intervertebral disc localization and segmentation in MRI with a multi-modal UNet [paper]
  • LADDERNET: Multi-Path Networks Based on U-Net for Medical Image Segmentation [paper][pytorch]
  • Glioma Segmentation with Cascaded Unet [paper]
  • Attention U-Net: Learning Where to Look for the Pancreas [paper]
  • Recurrent Residual Convolutional Neural Network based on U-Net (R2U-Net) for Medical Image Segmentation [paper]
  • Concurrent Spatial and Channel ‘Squeeze & Excitation’ in Fully Convolutional Networks [paper]
  • A Probabilistic U-Net for Segmentation of Ambiguous Images (NIPS) [paper] [tensorflow]
  • AnatomyNet: Deep Learning for Fast and Fully Automated Whole-volume Segmentation of Head and Neck Anatomy [paper]
  • 3D RoI-aware U-Net for Accurate and Efficient Colorectal Cancer Segmentation [paper][pytorch]
  • Detection and Delineation of Acute Cerebral Infarct on DWI Using Weakly Supervised Machine Learning (Y-Net) (MICCAI) [paper](Page 82)
  • Fully Dense UNet for 2D Sparse Photoacoustic Tomography Artifact Removal [paper]2019
  • MultiResUNet : Rethinking the U-Net Architecture for Multimodal Biomedical Image Segmentation [paper][keras]
  • U-NetPlus: A Modified Encoder-Decoder U-Net Architecture for Semantic and Instance Segmentation of Surgical Instrument [paper]
  • Probability Map Guided Bi-directional Recurrent UNet for Pancreas Segmentation [paper]
  • CE-Net: Context Encoder Network for 2D Medical Image Segmentation [paper][pytorch]
  • Graph U-Net [paper]
  • A Novel Focal Tversky Loss Function with Improved Attention U-Net for Lesion Segmentation (ISBI) [paper]
  • ST-UNet: A Spatio-Temporal U-Network for Graph-structured Time Series Modeling [paper]
  • Connection Sensitive Attention U-NET for Accurate Retinal Vessel Segmentation [paper]
  • CIA-Net: Robust Nuclei Instance Segmentation with Contour-aware Information Aggregation [paper]
  • W-Net: Reinforced U-Net for Density Map Estimation [paper]
  • Automated Segmentation of Pulmonary Lobes using Coordination-guided Deep Neural Networks (ISBI oral) [paper]
  • U2-Net: A Bayesian U-Net Model with Epistemic Uncertainty Feedback for Photoreceptor Layer Segmentation in Pathological OCT Scans [paper]
  • ScleraSegNet: an Improved U-Net Model with Attention for Accurate Sclera Segmentation (ICB Honorable Mention Paper Award) [paper]
  • AHCNet: An Application of Attention Mechanism and Hybrid Connection for Liver Tumor Segmentation in CT Volumes [paper]
  • A Hierarchical Probabilistic U-Net for Modeling Multi-Scale Ambiguities [paper]
  • Recurrent U-Net for Resource-Constrained Segmentation [paper]
  • MFP-Unet: A Novel Deep Learning Based Approach for Left Ventricle Segmentation in Echocardiography [paper]
  • A Partially Reversible U-Net for Memory-Efficient Volumetric Image Segmentation (MICCAI 2019) [paper][pytorch]
  • ResUNet-a: a deep learning framework for semantic segmentation of remotely sensed data [paper]
  • A multi-task U-net for segmentation with lazy labels [paper]
  • RAUNet: Residual Attention U-Net for Semantic Segmentation of Cataract Surgical Instruments [paper]
  • 3D U2-Net: A 3D Universal U-Net for Multi-Domain Medical Image Segmentation (MICCAI 2019) [paper] [pytorch]
  • SegNAS3D: Network Architecture Search with Derivative-Free Global Optimization for 3D Image Segmentation (MICCAI 2019) [paper]
  • 3D Dilated Multi-Fiber Network for Real-time Brain Tumor Segmentation in MRI [paper][pytorch] (MICCAI 2019)
  • The Domain Shift Problem of Medical Image Segmentation and Vendor-Adaptation by Unet-GAN [paper]
  • Recurrent U-Net for Resource-Constrained Segmentation [paper] (ICCV 2019)
  • Siamese U-Net with Healthy Template for Accurate Segmentation of Intracranial Hemorrhage (MICCAI 2019)

📅 2020

  • U²-Net: Going Deeper with Nested U-Structure for Salient Object Detection (Pattern Recognition 2020) [paper] [pytorch]
  • UNet 3+: A Full-Scale Connected UNet for Medical Image Segmentation (ICASSP 2020) [paper] [pytorch]
  • SA-UNet: Spatial Attention U-Net for Retinal Vessel Segmentation [paper] [pytorch]
  • Multi-level colonoscopy malignant tissue detection with adversarial CAC-UNet[paper] [pytorch]

📅 2021

  • TransUNet: Transformers Make Strong Encoders for Medical Image Segmentation (arXiv 2021) [paper] [pytorch]
  • UNETR: Transformers for 3D Medical Image Segmentation (arXiv 2021) [paper] [pytorch]
  • Swin-Unet: UNet-like Pure Transformer for Medical Image Segmentation [paper] [pytorch]

📅 2022

  • UNeXt: MLP-based Rapid Medical Image Segmentation Network [paper] [pytorch]
  • Focal-UNet: UNet-like Focal Modulation for Medical Image Segmentation [paper] [pytorch]
  • Practical Blind Image Denoising via Swin-Conv-UNet and Data Synthesis [paper] [pytorch]

📅 2023

  • DA-TransUNet: Dual Attention Transformer U-Net for Improved Segmentation [paper] [pytorch]
  • Diffusion Transformer UNet: Medical Image Segmentation with Diffusion Models (MICCAI 2023) [paper]
  • Biomedical Image Segmentation Using UNet & Transfer Learning [paper]
  • U-Net v2: Rethinking the Skip Connections of U-Net for Medical Image Segmentation [paper] [pytorch]
  • Music Source Separation Based on a Lightweight Deep Learning Framework (DTTNET: DUAL-PATH TFC-TDF UNET) [paper] [pytorch]
  • Faster Diffusion: Rethinking the Role of the Encoder for Diffusion Model Inference [paper] [pytorch]

📅 2024

  • LightM-UNet: Mamba Assists in Lightweight UNet for Medical Image Segmentation [paper] [pytorch]
  • SelfReg-UNet: Self-Regularized UNet for Enhanced Feature Discrimination [paper]
  • MPU-Net: Modality Preserving U-Net for Multimodal Image Segmentation [paper]
  • VM-UNet: Vision Mamba UNet for Medical Image Segmentation [paper] [pytorch]
  • Semi-Mamba-UNet: Pixel-Level Contrastive and Pixel-Level Cross-Supervised Visual Mamba-based UNet for Semi-Supervised Medical Image Segmentation [paper] [pytorch]
  • SAM2-UNet: Segment Anything 2 Makes Strong Encoder for Natural and Medical Image Segmentation [paper] [pytorch]
  • UltraLight VM-UNet: Parallel Vision Mamba Significantly Reduces Parameters for Skin Lesion Segmentation
  • LKM-UNet: Large Kernel Vision Mamba UNet for Medical Image Segmentation [paper] [pytorch]
  • H-vmunet: High-order Vision Mamba UNet for Medical Image Segmentation [paper] [pytorch]
  • ViM-UNet: Vision Mamba for Biomedical Segmentation [paper] [pytorch]

📅 2025

  • Multi-scale Conv-Attention U-Net: Adaptive Convolution + Attention for Medical Image Segmentation [paper]
  • VMAXL-UNet: Vision Mamba and xLSTM-UNet for Medical Image Segmentation [paper]
2025-04-16 04:25:02

If you’re running a Next.js application on an Ubuntu server, you probably want a clean workflow to update your production app every time you push to GitHub. In this guide, we’ll walk through setting up GitHub webhooks, a small server to receive them, and a deployment script that builds and restarts your app with PM2.


✅ Prerequisites

  • A public or private Ubuntu server
  • Node.js, npm, and PM2 installed
  • A running Next.js app managed by PM2
  • Your app hosted on GitHub (private or public)
  • SSH access to your server

Step 1: Generate SSH Key for GitHub (if needed)

On your Ubuntu server, generate an SSH key so the server can authenticate with GitHub and pull code automatically:

ssh-keygen -t rsa -b 4096 -C "your-github-email@example.com"

Press Enter to accept the default path (~/.ssh/id_rsa).
Now, copy the public key:

cat ~/.ssh/id_rsa.pub

Go to GitHub > Settings > SSH and GPG keys > New SSH key, and paste it in.
Test the connection:

ssh -T git@github.com

You should see a “You’ve successfully authenticated” message.


Step 2: Clone Your Repository

Pick a directory for your app and clone your GitHub repo:

cd /var/www
git clone git@github.com:your-username/your-repo.git
cd your-repo

Install dependencies and build the project:

npm install
npm run build

Start the app with PM2:

pm2 start npm --name "your-app-name" -- start
pm2 save

Step 3: Create the Deployment Script

Create a shell script that will handle updates:

nano ~/deploy.sh

Add this content:

#!/bin/bash

cd /var/www/your-repo

echo "Pulling latest changes..."
git pull origin main

echo "Installing dependencies..."
npm install

echo "Building the app..."
npm run build

echo "Restarting app with PM2..."
pm2 restart your-app-name

echo "Deployment complete!"

Make it executable:

chmod +x ~/deploy.sh

Step 4: Set Up a Webhook Listener

Create a simple Express server that listens for GitHub webhooks:

mkdir ~/webhook && cd ~/webhook
nano server.js

Paste the following code:

const express = require("express");
const { exec } = require("child_process");

const app = express();
app.use(express.json());

app.post("/webhook", (req, res) => {
  const payload = req.body;

  if (payload.ref === "refs/heads/main") {
    console.log("Push to main detected. Starting deployment...");
    exec("bash ~/deploy.sh", (err, stdout, stderr) => {
      if (err) {
        console.error(`Deployment error: ${err.message}`);
        return res.status(500).send("Deployment failed.");
      }
      console.log(stdout);
      console.error(stderr);
      res.status(200).send("Deployment complete.");
    });
  } else {
    res.status(200).send("Push ignored (not main branch).");
  }
});

const PORT = 4000;
app.listen(PORT, () => {
  console.log(`Webhook server listening on port ${PORT}`);
});

Initialize and install dependencies:

npm init -y
npm install express

Start the server using PM2:

pm2 start server.js --name webhook
pm2 save

Step 5: Open the Webhook Port (Optional)

If your firewall is active, allow the webhook port:

sudo ufw allow 4000

Step 6: Set Up GitHub Webhook

In your GitHub repo:

  1. Go to Settings > Webhooks > Add webhook
  2. Payload URL:
    http://your-server-ip:4000/webhook
  3. Content type:
    application/json
  4. Leave secret empty (or handle it in code if using)
  5. Events: Just the push event
  6. Save webhook

Step 7: Test the Deployment Flow

Make a small commit to the main branch:

git add .
git commit -m "Test auto-deploy"
git push origin main

Then monitor the webhook log:

pm2 logs webhook

You should see output indicating that the deployment script was triggered, the app was rebuilt, and restarted via PM2.


What Are the Advantages of Using This Webhook Setup?

  1. Hands-Free Deployment
    Every time you push to the main branch, your app automatically updates — no need to SSH into the server, pull manually, or restart services.

  2. Fast Feedback Loop
    Code changes go live in seconds, keeping development and production in sync. This is especially useful for small teams or solo developers.

  3. No External CI/CD Needed
    You don’t need to rely on tools like GitHub Actions, Jenkins, or CircleCI. Everything runs locally on your own server, which is great for simplicity and control.

  4. Customizable Deployment Logic
    You have full control over the deployment process. Want to run tests, update environment variables, or notify Slack? Just add it to your deploy.sh.

  5. Lightweight & Resource-Friendly
    Unlike full CI/CD tools that require containers or background jobs, this setup runs with minimal overhead — just a simple Express server and PM2.

  6. Works with Private Repos
    Since you're using SSH keys to authenticate with GitHub, this works equally well with private repositories.

  7. Secure by Design
    You can lock down access to the webhook port, use GitHub IP whitelisting, and add secret token verification for even more security.

  8. Great for VPS and Self-Hosted Environments
    Whether you're using DigitalOcean, Hetzner, Linode, or your own machine, this approach is ideal for traditional Ubuntu-based deployments.

'Web Development' 카테고리의 다른 글

Fixing JS and CSS Not Loading in Next.js on GitHub Pages  (0) 2025.04.10
2025-04-10 04:45:54

If you're deploying your Next.js 13+ app to GitHub Pages and running into issues where your JavaScript and CSS aren't loading, you're not alone. This issue usually comes down to how GitHub Pages handles static files — especially those in folders that start with an underscore like /_next.

Let me walk you through how to fix it step-by-step. 👇

 


 

🧠 The Problem

 

By default, GitHub Pages uses Jekyll, which ignores folders starting with _, like:

/_next/static/...

 

This means your app's static assets (JS, CSS) won't be served — resulting in a broken site with missing styles and scripts. 😵

 


 

The Solution

 

1. Add .nojekyll file

This file disables Jekyll processing on GitHub Pages.

You can add this manually in the out folder after next export, or automatically via a script:

 

touch out/.nojekyll

 

Or use shx to make it cross-platform compatible (for Windows users):

npm install --save-dev shx

 

2. Install gh-pages

 

You’ll need the gh-pages package to deploy the out folder to your GitHub Pages branch.

Install it with:

npm install --save-dev gh-pages

 

This tool will handle publishing your static site to the correct branch (typically gh-pages or main).

 

3. Update next.config.js

 

Configure your app for static export:

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'export', // Static export for GitHub Pages
  basePath: '',     // Leave empty for username.github.io
};

module.exports = nextConfig;

 

If you're deploying to a project page (e.g., username.github.io/my-app), set:

basePath: '/my-app',
assetPrefix: '/my-app',

 

 

4. Update your package.json scripts

"scripts": {
  "dev": "next dev",
  "build": "next build",
  "export": "next export",
  "postexport": "shx touch out/.nojekyll",
  "deploy": "next build && npm run postexport && gh-pages -d out --nojekyll --cname https://yourusername.github.io"
}

 

📝 Replace https://yourusername.github.io with your GitHub URL.

 

 


 

🏁 Deployment Command

npm run deploy

 

Boom 💥 — your Next.js site should be live and functional!

 


 

🔄 GitHub Pages Branch Setup

  1. Go to GitHub → Settings → Pages
  2. Source: Deploy from branch
  3. Branch: gh-pages, folder: / (root)
  4. Save ✅

 

🔗 Bonus Tips

  • Use --cname for custom domains
  • Use proper basePath if using a project subfolder
  • Automate deploys with GitHub Actions

📦 Example Repo

 

Check out: https://github.com/sky4689524/sky4689524.github.io

 

GitHub - sky4689524/sky4689524.github.io

Contribute to sky4689524/sky4689524.github.io development by creating an account on GitHub.

github.com


 

🧰 Tools Used

 

2023-03-10 05:50:32

Collections.OrderedDict() | HackerRank

 

Collections.OrderedDict() | HackerRank

Print a dictionary of items that retains its order.

www.hackerrank.com

Goal

 

You are the manager of a supermarket.
You have a list of N items together with their prices that consumers bought on a particular day.
Your task is to print each item_name and net_price in order of its first occurrence.

 

Solution

 

You use collections.OrderedDict() function to solve this task.

Thid script reads an integer value n from standard input, which represents the number of items in the dictionary.

A loop then runs n times to read item names and their corresponding net prices from standard input. 

The input is split into words, and the script checks if each word is numeric or not.

If the word is numeric, the script assigns it to the net_price variable,

otherwise, it appends it to a list called item_name.

After iterating over the words, the item_name list is joined to create a string representation of the item name. 

Then, the script checks if the item name already exists in the ordered_dictionary

If it does, the script adds the new net price to the existing net price of the item. 

Otherwise, the script creates a new key-value pair in the ordered_dictionary.


Finally, the script iterates over the ordered_dictionary and prints each item name and its net price

Since OrderedDict() maintains the order of the keys, the items are printed in the same order 

in which they were inserted into the dictionary.

# Collections.OrderedDict()

# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import OrderedDict

ordered_dictionary = OrderedDict()

n = int(input())

for i in range(n):
    
    item_name = []
    net_price = 0
    
    for x in input().split():
        if x.isnumeric():
            net_price = int(x)
        else:
            item_name.append(x)
            
    item_name = " ".join(item_name)
            
    if item_name in ordered_dictionary:
        ordered_dictionary[item_name] += net_price
        
    else:
        ordered_dictionary[item_name] = net_price


for k, v in ordered_dictionary.items():
    print(k, v)
2023-03-08 03:14:27

Collections.namedtuple() | HackerRank

 

Collections.namedtuple() | HackerRank

You need to turn tuples into convenient containers using collections.namedtuple().

www.hackerrank.com

 

Goal

 

Dr. John Wesley has a spreadsheet containing a list of student's IDs, marks, class and name.
Your task is to help Dr. Wesley calculate the average marks of the students.

Print the average marks of the list corrected to 2 decimal places.

 

Solution

 

You use collections.namedtuple()  to solve this task.

 

This code takes input from the standard input (STDIN) in the following format:

  • The first line contains an integer n, which represents the number of students.
  • The second line contains space-separated strings representing the columns of the table.
  • The following n lines contain space-separated values representing the data for each student.

The first line of code reads the integer value n from the standard input and stores it in the variable n.

The second line reads the column names from the standard input 

and converts them into a list of strings using the split() method. 

The index() method is then used to find the index of the 'MARKS' column, which is stored in the variable colum.

The for loop iterates n times, and for each iteration, 

it reads the input data for a student, splits the input string into a list of values using the split() method, 

and adds the value in the 'MARKS' column to the variable average.

Finally, the average of the 'MARKS' column is calculated 

by dividing the sum of all the values in the 'MARKS' column by n.

The result is then printed to the standard output (STDOUT) using the format() method

with a precision of two decimal places.

 

# Collections.namedtuple()

# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
colum = input().split().index('MARKS')
average = 0.0

for i in range(n):
    data = input().split()
    average += float(data[colum])


print('{:.2f}'.format(average / n))
2023-03-01 03:30:00

Exceptions | HackerRank

 

Exceptions | HackerRank

Handle errors detected during execution.

www.hackerrank.com

 

Goal

 

You are given two values  a and b.
Perform integer division and print a / b .

 

Solution

 

We use Exceptions to handle errors for this task. 

Here is code explanation.

It reads the input from standard input and then loops for n times, 

where n is the number entered as the first input.

Inside the loop, it reads two integers from the input, performs integer division, and prints the result. 

 

However, if there is a ZeroDivisionError, 

it prints a custom error message saying "Error Code: integer division or modulo by zero"

If there is a ValueError, it prints "Error Code:" followed by the error message.

 

The try block contains the code that might raise an exception

and the except block is where the exception is handled. 

In this code, there are two except blocks, one for ZeroDivisionError and another for ValueError.

 

The ZeroDivisionError occurs when dividing by zero, which is not possible in arithmetic. 

The ValueError occurs when the input cannot be converted to an integer

such as when the input is a string or a floating-point number.

 

By handling these exceptions, the code prevents the program from crashing 

and provides a useful error message to the user.

# Exceptions

# Enter your code here. Read input from STDIN. Print output to STDOUT
for i in range(int(input())):
    
    try:
        values = input().split()
        print(int(int(values[0]) / int(values[1])))
        
    except ZeroDivisionError as ze:
        print("Error Code: integer division or modulo by zero")
        #print("Error Code:",ze) if you use this one, Error Code: division by zero. it is not correct answer for them.
    
    except ValueError as ve:
        print("Error Code:",ve)
2023-02-25 04:51:49

DefaultDict Tutorial | HackerRank

 

DefaultDict Tutorial | HackerRank

Create dictionary value fields with predefined data types.

www.hackerrank.com

 

Goal

 

The first line contains integers, n and m separated by a space.
The next  lines contains the words belonging to group A.
The next  lines contains the words belonging to group B.

Output m lines.
The i-th line should contain the 1-indexed positions of the occurrences of the i-th word separated by spaces.

 

 

Solution

 

We can practice with defaultdict to solve this task. 

Importing the defaultdict class from the collections module 

and creating a defaultdict object d that will hold the input values.

 

Taking two inputs separated by a space and storing them in x and y.

 

Then using a for loop to iterate int(x) times, taking input values

and appending them to the 'A' key of the defaultdict object d.

 

Similarly, for int(y) times, taking input values

and appending them to the 'B' key of the defaultdict object d.

 

Taking two inputs separated by a space and storing them in x and y

 

Then using a for loop to iterate int(x) times, taking input values 

and appending them to the 'A' key of the defaultdict object d

 

Similarly, for int(y) times, taking input values and appending them to the 'B' key of the defaultdict object d.

 

# DefaultDict Tutorial

# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import defaultdict

d = defaultdict(list)

x, y = input().split()

for i in range(int(x)):
    d['A'].append(input())


for j in range(int(y)):
    d['B'].append(input())

for i in range(len(d['B'])):
    
    value = d['B'][i]
    
    matches = [k+1 for k in range(0,len(d['A'])) if value == d['A'][k]]
    
    if len(matches) == 0:
        print("{}".format(-1))
    else:
        print(*matches,sep=' ')
2023-02-24 04:02:50

Introduction to Sets | HackerRank

 

Introduction to Sets | HackerRank

Use the set tool to compute the average.

www.hackerrank.com

 

Goal

 

Ms. Gabriel Williams is a botany professor at District College.

One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her greenhouse.

 

Task : You are given array of all the plants of height. You need to compute the average.

 

Solution

 

You need to use set data structure to solve this task.

 

Here is a step-by-step explanation of how this function works:


First, the input list is converted to a set using the set() function.

This removes any duplicate values from the input list, as sets only store unique values.

The length of the resulting set is computed using the len() function and stored in the total_length variable.
The sum of the values in the set is computed using the sum() function and stored in the total_values variable.
The average is computed by dividing the total_values by the total_length, and the result is returned.

 

# Introduction to Sets

def average(array):
    # your code goes here
    set_array = set(array)
    total_length = len(set_array)
    total_values = sum(set_array)
    
    return total_values / total_length
        


if __name__ == '__main__':
    n = int(input())
    arr = list(map(int, input().split()))
    result = average(arr)
    print(result)
2023-02-23 04:14:37

itertools.permutations() | HackerRank

 

itertools.permutations() | HackerRank

Find all permutations of a given size in a given string.

www.hackerrank.com

 

Goal

 

You are given a string S.

Your task is to print all poissible permutations of size K of the string in lexicographic sorted order.

 

Solution

 

You need to use itertools.permutations(iterable[, r]) method to solve this task. 

 

The itertools module in Python provides a number of powerful functions for working with iterable objects.

One of these functions is permutations(), which generates all possible permutations of an iterable object. 

The input() function is used to read a line of input from standard input, 

and the split() method is used to split the input line into a list of strings. 

The first element in the list is the string that we want to generate permutations for, 

and the second element is the length of the permutations that we want to generate.

The permutations() function is called with two arguments: 

the first is the string that we want to generate permutations for, and the second is the length of the permutations. 

The list() function is called to convert the result to a list. The list of permutations is stored in the perm variable.

The perm list is iterated over using a for loop, and a new string is created for each permutation.

The join() method is used to concatenate the elements of the permutation into a string,

and the resulting string is appended to the results list.
Once all the permutations have been generated, 

the sorted() function is called to sort the results list in lexicographic order. 

The join() method is used to concatenate the sorted strings together with a newline character, 

and the resulting string is printed to standard output.

# itertools.permutations()
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import permutations

com = input().split()

perm = list(permutations(com[0], int(com[1])))

results = []

for element_set in perm:
    
    tmp = ""
    
    for element in element_set:
        tmp += element
        
    results.append(tmp)
    
print('\n'.join(sorted(results)))
2023-02-22 05:00:19

https://www.hackerrank.com/challenges/collections-counter/problem

 

collections.Counter() | HackerRank

Use a counter to sum the amount of money earned by the shoe shop owner.

www.hackerrank.com

 

Goal

 

You are given X number of shoes and a list containing the size of each shoe.

Additoinally, you are give N number of customers who are willing to pay X(i) amount of money only if they get the shoe their desired size.

 

So, you need to compute how much money you can earn.

 

You need to use collection.Counter() function to solve this task.

 

Solution

 

The script you provided uses the collections library in Python to solve a problem related to sales of shoes.

The problem involves keeping track of the available shoe sizes and the prices of shoes, and then calculating the total amount of money earned by selling shoes to a group of customers.

The script starts by importing the Counter function from the collections library.

The Counter function is used to count the frequency of elements in a list.

Next, the script prompts the user to input the number of shoes in stock and their sizes. The input() function is used to take user input, and the int() and map() functions are used to convert the resulting string of shoe sizes into a list of integers.

The number of shoes in stock is assigned to the variable n_shoes, and the list of shoe sizes is assigned to the variable shoe_sizes.

The script then prompts the user to input the number of customers and the size and price of the shoes they wish to purchase.

The input() function is used to take user input, and the int() and map() functions are used to convert the resulting string of size and price into two separate integers.

The number of customers is assigned to the variable n_customers, and the total price of all shoes sold is assigned to the variable total_price.

A for loop is then used to iterate over each customer.

For each customer, a Counter object is created using the shoe_sizes list. The Counter object counts the frequency of each shoe size in the shoe_sizes list.

The customer's desired shoe size and its price are then read from standard input and assigned to the variables size and price, respectively.

If the desired shoe size is in the shoe_sizes list, the price of the shoe is added to the total_price variable, and the desired shoe size is removed from the shoe_sizes list using the remove() method.

Finally, the total price of all shoes sold is printed to standard output using the print() function.

 

In summary, the script uses the Counter function from the collections library to count the frequency of shoe sizes in a list of shoes, and uses a for loop to sell shoes to customers and calculate the total price of all shoes sold. This script can be useful in scenarios where it is necessary to keep track of inventory and sales in a retail environment.

 

# collections.Counter()
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import Counter

n_shoes = int(input())

shoe_sizes = list(map(int, input().split()))

n_customers = int(input())
total_price = 0

for i in range(n_customers):
    shoes_collection = Counter(shoe_sizes)
    
    size, price = list(map(int, input().split()))
    
    if size in shoes_collection.keys():
        total_price += price
        shoe_sizes.remove(size)
    

print(total_price)


Hanwool Codes. Designed by 코딩재개발.