1622815740

# Solving LeetCode’s ‘Swapping Nodes in a Linked List’

Here is an article I wrote on Linked Lists and goes through a LeetCode problem.

Recap, a linked list is a linear collection of nodes where each node points to the next node. Each node has a value property and a next property which references the next node in the list.

This is what makes linked lists a linear data structure. There is a sequence and an order to the list. To get to the end of the list, we must start at the first node (head) and go through all of the nodes in order. The final node (tail) will point to null, indicating that is the end of the list.

## Problem

You are given the head of a linked list, and an integer k.

Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).

## Example

Swapping Nodes

``````Input: head = [1,2,3,4,5], k = 2

Output: [1,4,3,2,5]
``````

1656151740

## Test_cov_console: Flutter Console Coverage Test

Flutter Console Coverage Test

This small dart tools is used to generate Flutter Coverage Test report to console

## How to install

Add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

``````dev_dependencies:
test_cov_console: ^0.2.2
``````

## How to run

### run the following command to make sure all flutter library is up-to-date

``````flutter pub get
Running "flutter pub get" in coverage...                            0.5s
``````

### run the following command to generate lcov.info on coverage directory

``````flutter test --coverage
00:02 +1: All tests passed!
``````

### run the tool to generate report from lcov.info

``````flutter pub run test_cov_console
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
print_cov_constants.dart                    |    0.00 |    0.00 |    0.00 |    no unit testing|
lib/                                         |         |         |         |                   |
test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
``````

## Optional parameter

``````If not given a FILE, "coverage/lcov.info" will be used.
-f, --file=<FILE>                      The target lcov.info file to be reported
-e, --exclude=<STRING1,STRING2,...>    A list of contains string for files without unit testing
to be excluded from report
-l, --line                             It will print Lines & Uncovered Lines only
Branch & Functions coverage percentage will not be printed
-i, --ignore                           It will not print any file without unit testing
-m, --multi                            Report from multiple lcov.info files
-c, --csv                              Output to CSV file
-o, --output=<CSV-FILE>                Full path of output CSV file
If not given, "coverage/test_cov_console.csv" will be used
-t, --total                            Print only the total coverage
Note: it will ignore all other option (if any), except -m
-p, --pass=<MINIMUM>                   Print only the whether total coverage is passed MINIMUM value or not
If the value >= MINIMUM, it will print PASSED, otherwise FAILED
Note: it will ignore all other option (if any), except -m
-h, --help                             Show this help
``````

### example run the tool with parameters

``````flutter pub run test_cov_console --file=coverage/lcov.info --exclude=_constants,_mock
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
``````

### report for multiple lcov.info files (-m, --multi)

``````It support to run for multiple lcov.info files with the followings directory structures:
1. No root module
<root>/<module_a>
<root>/<module_a>/coverage/lcov.info
<root>/<module_a>/lib/src
<root>/<module_b>
<root>/<module_b>/coverage/lcov.info
<root>/<module_b>/lib/src
...
2. With root module
<root>/coverage/lcov.info
<root>/lib/src
<root>/<module_a>
<root>/<module_a>/coverage/lcov.info
<root>/<module_a>/lib/src
<root>/<module_b>
<root>/<module_b>/coverage/lcov.info
<root>/<module_b>/lib/src
...
You must run test_cov_console on <root> dir, and the report would be grouped by module, here is
the sample output for directory structure 'with root module':
flutter pub run test_cov_console --file=coverage/lcov.info --exclude=_constants,_mock --multi
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
---------------------------------------------|---------|---------|---------|-------------------|
File - module_a -                            |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
---------------------------------------------|---------|---------|---------|-------------------|
File - module_b -                            |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
``````

### Output to CSV file (-c, --csv, -o, --output)

``````flutter pub run test_cov_console -c --output=coverage/test_coverage.csv

#### sample CSV output file:
File,% Branch,% Funcs,% Lines,Uncovered Line #s
lib/,,,,
test_cov_console.dart,0.00,0.00,0.00,no unit testing
lib/src/,,,,
parser.dart,100.00,100.00,97.22,"97"
parser_constants.dart,100.00,100.00,100.00,""
print_cov.dart,100.00,100.00,82.91,"29,49,51,52,171,174,177,180,183,184,185,186,187,188,279,324,325,387,388,389,390,391,392,393,394,395,398"
print_cov_constants.dart,0.00,0.00,0.00,no unit testing
All files with unit testing,100.00,100.00,86.07,""``````

## Use this package as an executable

### Install it

You can install the package from the command line:

``dart pub global activate test_cov_console``

### Use it

The package has the following executables:

``````\$ test_cov_console
``````

## Use this package as a library

### Depend on it

Run this command:

With Dart:

`` \$ dart pub add test_cov_console``

With Flutter:

`` \$ flutter pub add test_cov_console``

This will add a line like this to your package's pubspec.yaml (and run an implicit `dart pub get`):

``````dependencies:
test_cov_console: ^0.2.2``````

Alternatively, your editor might support `dart pub get` or `flutter pub get`. Check the docs for your editor to learn more.

### Import it

Now in your Dart code, you can use:

``import 'package:test_cov_console/test_cov_console.dart';``

example/lib/main.dart

``````import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);

// that it has a State object (defined below) that contains fields that affect
// how it looks.

// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".

final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;

void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}

@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'\$_counter',
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}``````

Author: DigitalKatalis
Source Code: https://github.com/DigitalKatalis/test_cov_console

1622815740

## Solving LeetCode’s ‘Swapping Nodes in a Linked List’

Here is an article I wrote on Linked Lists and goes through a LeetCode problem.

Recap, a linked list is a linear collection of nodes where each node points to the next node. Each node has a value property and a next property which references the next node in the list.

This is what makes linked lists a linear data structure. There is a sequence and an order to the list. To get to the end of the list, we must start at the first node (head) and go through all of the nodes in order. The final node (tail) will point to null, indicating that is the end of the list.

## Problem

You are given the head of a linked list, and an integer k.

Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).

## Example

Swapping Nodes

``````Input: head = [1,2,3,4,5], k = 2

Output: [1,4,3,2,5]
``````

1624320600

## What Is a Linked List?

A linked list is a basic data structure. It is a collection of nodes that connects each node to the next node with a pointer.

Each node consists of two items:

• Data (such as a number)
• Pointer to the next node

Here is an illustration of a linked list

A linked list forms a chain of nodes. Each node holds data and points to the next node. Image by the author.

#programming #coding #python #how to create a linked list in python #create a linked list #linked list

1640973720

## Beyonic API Python Examples.

The beyonic APIs Docs Reference: https://apidocs.beyonic.com/

Discuss Beyonic API on slack

The Beyonic API is a representational state transfer, REST based application programming interface that lets you extend the Beyonic dashboard features into your application and systems, allowing you to build amazing payment experiences.

With the Beyonic API you can:

• Receive and send money and prepaid airtime.
• List currencies and networks supported by the Beyonic API.
• Check whether a bank is supported by the Beyonic API.
• View your account transactions history.
• Use webhooks to send notifications to URLs on your server that when specific events occur in your Beyonic account (e.g. payments).

### Getting Help

For usage, general questions, and discussions the best place to go to is Beyhive Slack Community, also feel free to clone and edit this repository to meet your project, application or system requirements.

To start using the Beyonic Python API, you need to start by downloading the Beyonic API official Python client library and setting your secret key.

Install the Beyonic API Python Official client library

``````>>> pip install beyonic
``````

To set the secrete key install the python-dotenv modeule, Python-dotenv is a Python module that allows you to specify environment variables in traditional UNIX-like “.env” (dot-env) file within your Python project directory, it helps us work with SECRETS and KEYS without exposing them to the outside world, and keep them safe during development too.

Installing python-dotenv modeule

``````>>> pip install python-dotenv
``````

Creating a .env file to keep our secrete keys.

``````>>> touch .env
``````

Inside your .env file specify the Beyonic API Token .

.env file

``````BEYONIC_ACCESS_KEY = "enter your API "
``````

You will get your API Token by clicking your user name on the bottom left of the left sidebar menu in the Beyonic web portal and selecting ‘Manage my account’ from the dropdown menu. The API Token is shown at the very bottom of the page.

#### getExamples.py

``````import os
import beyonic

myapi = os.environ['BEYONIC_ACCESS_KEY']

beyonic.api_key = myapi

# Listing account: Working.
accounts = beyonic.Account.list()
print(accounts)

#Listing currencies: Not working yet.
'''
supported_currencies = beyonic.Currency.list()
print(supported_currencies)

Supported currencies are: USD, UGX, KES, BXC, GHS, TZS, RWF, ZMW, MWK, BIF, EUR, XAF, GNF, XOF, XOF
'''

#Listing networks: Not working yet.
"""
networks = beyonic.Network.list()
print(networks)
"""

#Listing transactions: Working.
transactions = beyonic.Transaction.list()
print(transactions)

#Listing contact: Working.
mycontacts = beyonic.Contact.list()
print(mycontacts)

#Listing events: Not working yet.
'''
events = beyonic.Event.list()
print(events)

Error: AttributeError: module 'beyonic' has no attribute 'Event'
'''
``````

Docker file

``````FROM python:3.8-slim-buster

COPY . .

COPY ./requirements.txt ./requirements.txt

WORKDIR .

RUN pip install -r requirements.txt

CMD [ "python3", "getExamples.py" ]
``````

Build docker image called demo

``````>>> docker build -t bey .
``````

Run docker image called demo

``````>>>docker run -t -i bey
``````

Now, I’ll create a Docker compose file to run a Docker container using the Docker image we just created.

``````
version: "3.6"
services:
app:
build: .
command: python getExamples.py
volumes:
- .:/pythonBeyonicExamples
``````

Now we are going to run the following command from the same directory where the docker-compose.yml file is located. The docker compose up command will start and run the entire app.

``````
docker compose up
``````

### Output

NB: The screenshot below might differ according to your account deatils and your transcations in deatils.

To stop the container running on daemon mode use the below command.

``````docker compose stop
``````

Output

Contributing to this repository. All contributions, bug reports, bug fixes, enhancements, and ideas are welcome, You can get in touch with me on twitter @HarunMbaabu.

Author: HarunMbaabu
Source Code: https://github.com/HarunMbaabu/BeyonicAPI-Python-Examples

1622127960

## Linked List in Data Structure

In computer science, we refer to the format of storing data on storage devices as a data structure. An array is the collection of data stored in contiguous memory locations.

This makes accessibility very easy but it leads to not so efficient use of memory because the smaller chunks of memory that are left between earlier stored data are not used.

But what if you need more efficient utilization of your memory. Here dynamic data structures come into the picture. Dynamic data structures as the name suggest do not have a fixed memory size.

They can shrink or grow themselves by deallocating or allocating the memory respectively, as and when required.

#### Linked List in Data Structure

A linked list is the most basic type of dynamic data structure. A linked list is a linear collection of data where the order of elements is not given by their physical memory address. The user stores the data in blocks of memory called nodes.

Each node has two parts. The first part contains the data and the second part points towards the next node. It contains the address of the next node in the actual memory.

Singly-linked lists are the most basic and easy to implement linked lists. Each node stores the data at random memory locations and contains a pointer that points to the next node in the memory.

Each node contains data and two pointers. One point to the previous node and the other points to the next node. This makes doubly-linked traversable both forward and backward.

Just like a singly linked list, here also each node is linked to the next only with a slight modification. In a circular linked list, the last node of the list is pointed to the first node forming a loop. So we can reach the previous node by traversing forward.

#### Singly Linked list in Data Structure

A singly linked list as we have seen contains multiple nodes in which the earlier node points at the next node except the last node. A node has two parts, the first one contains the data and the second part contains the address of the next node.

#### Creating Node in Linked List

C program for creating a Linked List Node:

struct node { int data; // data to store in node struct node *next; //NULL for last node }

The previous part of the first node and the next part of the last node will always have NUL

#### Need of Pointers in Linked List

Unlike arrays, in a linked list, memory allocation takes place at runtime and therefore memory location of each node is random. Each node can be present anywhere in the memory and to access them, each node has the address of its next node stored with it.

This forms a kind of link between every node. This is the additional pointer that we need because if the link is not present or it’s broken, the memory locations will be lost.

• Insert: Insert the node at any position. Worst-case time complexity O(1).
• Delete: Delete the node at any position. Worst-case time complexity O(1).
• **Search: **Search for a specific node in the list. The worst-case time complexity O(n).
• Display: Display a complete list. The worst-case time complexity O(n).