1597014000

Minimum cost required to convert all Subarrays of size K to a single element

Given an array arr[] consisting of N integers and an integer K, the task is to find the minimum cost required to make each element of every subarray of length K equal. Cost of replacing any array element by another element is the absolute difference between the two.

Examples:

Input: A[] = {1, 2, 3, 4, 6}, K = 3
Output: 7
Explanation:
Subarray 1: Cost to convert subarray {1, 2, 3} to {2, 2, 2} = |1-2| + |2-2| + |3-2| = 2
Subarray 2: Cost to convert subarray {2, 3, 4} to {3, 3, 3} = |2-3| + |3-3| + |4-3| = 2
Subarray 3: Cost to convert subarray {3, 4, 6} to {4, 4, 4} = |3-4| + |4-4| + |6-4| = 3
Minimum Cost = 2 + 2 + 3 = 7/
Input: A[] = {2, 3, 4, 4, 1, 7, 6}, K = 4
Output: 21

Approach:

To find the minimum cost to convert each element of the subarray to a single element, change every element of the subarray to the median of that subarray. Follow the steps below to solve the problem:

To find the median for each running subarray efficiently, use a multiset to get the sorted order of elements in each subarray. Median will be the middle element of this multiset.
For the next subarray remove the leftmost element of the previous subarray from the multiset, add the current element to the multiset.
Keep a pointer mid to efficiently keep track of the middle element of the multiset.
If the newly added element is smaller than the previous middle element, move mid to its immediate smaller element. Otherwise, move mid to its immediate next element.
Calaculate cost of replacing every element of the subarray by the equation | A[i] – medianeach_subarray |.
Finally print the total cost.
Below is the implementation for the above approach:

C++

// C++ Program to implement

// the above approach

#include <bits/stdc++.h>

using namespace std;

// Function to find the minimum

// cost to convert each element of

// every subarray of size K equal

int minimumCost(vector arr, int n,

``````            int k)
``````

{

``````// Stores the minimum cost

int totalcost = 0;

int i, j;

// Stores the first K elements

multiset<int> mp(arr.begin(),

arr.begin() + k);

if (k == n) {

// Obtain the middle element of

// the multiset

auto mid = next(mp.begin(),

n / 2 - ((k + 1) % 2));

int z = *mid;

// Calculate cost for the subarray

for (i = 0; i < n; i++)

totalcost += abs(z - arr[i]);

// Return the total cost

}

else {

// Obtain the middle element

// in multiset

auto mid = next(mp.begin(),

k / 2 - ((k + 1) % 2));

for (i = k; i < n; i++) {

int zz = *mid;

int cost = 0;

for (j = i - k; j < i; j++) {

// Cost for the previous

// k length subarray

cost += abs(arr[j] - zz);

}

totalcost += cost;

// Insert current element

// into multiset

mp.insert(arr[i]);

if (arr[i] < *mid) {

// New element appears

// to the left of mid

mid--;

}

if (arr[i - k] <= *mid) {

// New element appears

// to the right of mid

mid++;

}

// Remove leftmost element

// from the window

mp.erase(mp.lower_bound(arr[i - k]));

// For last element

if (i == n - 1) {

zz = *mid;

cost = 0;

for (j = i - k + 1;

j <= i; j++) {

// Calculate cost for the subarray

cost += abs(zz - arr[j]);

}

totalcost += cost;

}

}

// Return the total cost

}
``````

}

// Driver Code

int main()

{

``````int N = 5, K = 3;

vector<int> A({ 1, 2, 3, 4, 6 });

cout << minimumCost(A, N, K);
``````

}

Output:

7

Time Complexity: O(NlogN)

Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #greedy #mathematical #sorting #cpp-multiset #median-finding #sliding-window #subarray

1655243220

A Weather_widget Used for Flutter with Many Custom Config

weather_widget

Simple weather related widget, which can be freely combined to form a variety of weather backgrounds

Getting Started

depend

``````dependencies:
weather_widget: ^1.0.6
``````

Weatherwidget is easy to use, just add weatherwidget to start using

``````WeatherWidget(
size:Size.infinite,
weather:'Sunny',
sunConfig:SunConfig()
),
``````

This will add a sunny day using the default settings

or other weather type
(Note: Raindrops and snowflakes need to specify the default number, and they will move randomly within the range)

``````WeatherWidget(
size:Size.infinite,
weather:'Cloudy',
cloudConfig:CloudConfig()
),

WeatherWidget(
size:Size.infinite,
weather:'Rainy',
rainConfig:RainConfig(
rainNum:'the num of raindrops you want'
)
),

WeatherWidget(
size:Size.infinite,
weather:'Snowy',
snowConfig:SnowConfig(
snowNum:'the num of snowflakes you want'
)
),

WeatherWidget(
size:Size.infinite,
weather:'Thunder',
thunderConfig:ThunderConfig()
),``````

Of course, each config contains other settings, such as the range, size, length, falling speed and color of random raindrops. You can use them to create hailstones and other weather features
If the default weather is not enough, you can use individual widgets and stack() widget to piece together the desired weather
Like this sunset breeze, etc

These are include in this widget
background

``````    BackgroundWidget（List<Color>,size）
``````

cloud

``````    CloudWidget (Color)
``````

A single random raindrop

``````RainWidget (
@required rainRangeXStart, #X-axis starting point of raindrop random occurrence
@required rainRangeXEnd,
@required rainRangeYStart,
@required rainRangeYEnd,
@required durationRangeStartMill,  #Minimum time to fall
@required durationRangeEndMill,
rainLength,
rainWidth,
rainColor,
rainCurve  #Curve of falling animation
)
``````

A single random snowflake

``````SnowWidget (
this.snowAreaXStart,  #X-axis starting point of snowflake random occurrence
this.snowAreaXEnd,
this.snowWaveRangeMin,    #The minimum floating distance of snowflakes
this.snowWaveRangeMax,
this.snowFallSecMin,  #Minimum time of snowflake falling
this.snowFallSecMax,
this.snowWaveSecMin,  #Minimum time for snowflake to float
this.snowWaveSecMax,
this.snowSize,
this.snowColor,
this.snowAreaYStart,   #Y-axis point of snowflake occurrence
this.snowAreaYEnd,
this.waveCurve,        #Floating animation curve
)
``````

A single flash

``````ThunderWidget (
this.flashMillStart,   #Minimum flashing time
this.flashMillEnd,
this.pauseMillStart,   #Minimum interval time
this.pauseMillEnd,
this.blurStyle,        #blur model
this.blurSigma,
this.points,
this.color,
this.width
)
``````

a single wind

``````WindWidget (
this.pauseMillStart,    #Minimum interval time
this.pauseMillEnd,
this.windPositionY,     #Y-axis point of wind occurrence
this.windSlideMill,     #Passing time
this.windColor,
this.windWidth,
this.windSlideXEnd,
this.windSlideXStart,
this.windGap,           #line spacing in a wind
this.blurStyle,
this.blurSigma
)
``````

Using sunny weather by set the WeatherWidget background config in a sunConfig()

Use this package as a library

Depend on it

Run this command:

With Flutter:

`` \$ flutter pub add weather_widget``

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

``````dependencies:
weather_widget: ^1.0.6``````

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

Import it

Now in your Dart code, you can use:

``````import 'package:weather_widget/WeatherWidget.dart';
import 'package:weather_widget/example/main.dart';``````

example/main.dart

``````import 'package:flutter/material.dart';
import 'package:weather_widget/WeatherWidget.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(
primarySwatch: Colors.blue,
),
home: WeatherWidget(
size: Size.infinite,
weather: 'Thunder',
thunderConfig:ThunderConfig(
thunderWidth:12
)
)
);
}
}``````

Author: Carendule
Source Code: https://github.com/carendule/WeatherWidget

1597014000

Minimum cost required to convert all Subarrays of size K to a single element

Given an array arr[] consisting of N integers and an integer K, the task is to find the minimum cost required to make each element of every subarray of length K equal. Cost of replacing any array element by another element is the absolute difference between the two.

Examples:

Input: A[] = {1, 2, 3, 4, 6}, K = 3
Output: 7
Explanation:
Subarray 1: Cost to convert subarray {1, 2, 3} to {2, 2, 2} = |1-2| + |2-2| + |3-2| = 2
Subarray 2: Cost to convert subarray {2, 3, 4} to {3, 3, 3} = |2-3| + |3-3| + |4-3| = 2
Subarray 3: Cost to convert subarray {3, 4, 6} to {4, 4, 4} = |3-4| + |4-4| + |6-4| = 3
Minimum Cost = 2 + 2 + 3 = 7/
Input: A[] = {2, 3, 4, 4, 1, 7, 6}, K = 4
Output: 21

Approach:

To find the minimum cost to convert each element of the subarray to a single element, change every element of the subarray to the median of that subarray. Follow the steps below to solve the problem:

To find the median for each running subarray efficiently, use a multiset to get the sorted order of elements in each subarray. Median will be the middle element of this multiset.
For the next subarray remove the leftmost element of the previous subarray from the multiset, add the current element to the multiset.
Keep a pointer mid to efficiently keep track of the middle element of the multiset.
If the newly added element is smaller than the previous middle element, move mid to its immediate smaller element. Otherwise, move mid to its immediate next element.
Calaculate cost of replacing every element of the subarray by the equation | A[i] – medianeach_subarray |.
Finally print the total cost.
Below is the implementation for the above approach:

C++

// C++ Program to implement

// the above approach

#include <bits/stdc++.h>

using namespace std;

// Function to find the minimum

// cost to convert each element of

// every subarray of size K equal

int minimumCost(vector arr, int n,

``````            int k)
``````

{

``````// Stores the minimum cost

int totalcost = 0;

int i, j;

// Stores the first K elements

multiset<int> mp(arr.begin(),

arr.begin() + k);

if (k == n) {

// Obtain the middle element of

// the multiset

auto mid = next(mp.begin(),

n / 2 - ((k + 1) % 2));

int z = *mid;

// Calculate cost for the subarray

for (i = 0; i < n; i++)

totalcost += abs(z - arr[i]);

// Return the total cost

}

else {

// Obtain the middle element

// in multiset

auto mid = next(mp.begin(),

k / 2 - ((k + 1) % 2));

for (i = k; i < n; i++) {

int zz = *mid;

int cost = 0;

for (j = i - k; j < i; j++) {

// Cost for the previous

// k length subarray

cost += abs(arr[j] - zz);

}

totalcost += cost;

// Insert current element

// into multiset

mp.insert(arr[i]);

if (arr[i] < *mid) {

// New element appears

// to the left of mid

mid--;

}

if (arr[i - k] <= *mid) {

// New element appears

// to the right of mid

mid++;

}

// Remove leftmost element

// from the window

mp.erase(mp.lower_bound(arr[i - k]));

// For last element

if (i == n - 1) {

zz = *mid;

cost = 0;

for (j = i - k + 1;

j <= i; j++) {

// Calculate cost for the subarray

cost += abs(zz - arr[j]);

}

totalcost += cost;

}

}

// Return the total cost

}
``````

}

// Driver Code

int main()

{

``````int N = 5, K = 3;

vector<int> A({ 1, 2, 3, 4, 6 });

cout << minimumCost(A, N, K);
``````

}

Output:

7

Time Complexity: O(NlogN)

Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #greedy #mathematical #sorting #cpp-multiset #median-finding #sliding-window #subarray

1600596000

Improve Your Cost Management with AWS Saving Plans

The adaptability and flexibility of today’s cloud services present a lot of opportunities to cut infrastructure costs. Amazon Web Services and its plethora of services let you set up any kind of cloud environment for any type of application, without forcing you to make long-term commitments. At the very least, you don’t have to make a big initial investment to set up your cloud environments.

AWS resources are designed to make deploying cloud-native applications easy and affordable. Affordability is always important for businesses because cost-efficient applications guarantee higher returns on cloud investment. The way AWS services are set up allows for easy scaling of apps and cloud resource usage, but keeping your cloud environment efficient is not without its challenges.

#aws #amazon web services #cost #cost optimization #cost analysis #cost management #cost analytics #aws costs

1624430282

Banking App Development Cost - 8 Hidden Factors

Since 1994, Digital banking has been here. It is a very long time, but digital banking through mobile devices is entirely new to the banking industry. It all started when Atom became the first digital-only bank in the UK.

Nowadays, Tech-savvy customers expect corporations to support their digital movement, and because of this, almost every industry has adopted technologies to stay relevant with these modern customers. Most of the newbies who plan to develop a banking app have two questions in mind: “What is the cost of developing a banking application” and “Which hidden factors affect the cost of developing a banking app?”

You can get all the answers to these questions here, because this article will take you through the cost of developing a banking app, the features of banking apps, and much other pertinent information. After reading this, you will be able to plan better for your mobile banking app development. But before directly jumping into the cost of mobile banking app development, let’s take a look at the global digital payment market size of mobile banking.

Global Digital Payment Market Size

According to GlobalNewsWire, by 2026, the Global Digital Payment Market size is estimated to reach \$175.8 billion, rising at a market growth of 20% CAGR during the forecast period.

Around 23% of millennials use mobile banking apps daily.
Around 49.2% of total smartphone users use mobile banking apps.
41% of Americans said that mobile banking apps had minimized their concerns about managing finances.

Data Source: Statista

As you can see, the data clearly indicates that the percentage of smartphone users are increasing day-by-day. Therefore, by engaging in your own mobile banking app development currently, you will be able to take advantage of the growth in mobile users. But, the cost of developing a banking application depends on so many factors like the platform, features, technologies, and so on.

Mobile banking app development cost

Cost of developing a banking app depends on various factors. To give you a rough idea of the mobile banking application development cost, the total development time for a fully-featured app sums to 3760 hours. Considering hourly rate for fintech projects of \$25, the cost of developing a feature-loaded banking app stands around \$94k.

Banking Application Development Cost depends on different phases such as:

• Research and Planning
• UI/UX Design
• Development
• Testing
• Maintenance and Support

8 Hidden Factors of Costs of Mobile Banking App Development

It’s not easy to imagine an app that does not utilize this necessary mobile capability. Push notifications always increase your users’ engagement with your mobile banking app and encourage the desired action. Push notifications are of three types:

2. The Application-based notifications indicate when the mobile banking app requires the user’s attention, whether related to the password change requests or document submissions.

3. Promotional notifications are to grab the attention of customers to offer discounts and attractive deals.

2. Chatbot Integration

For most users, mobile banking has a steep learning curve, and due to that, the customer will require immediate assistance on various occasions. Hence, creating a chatbot for customer service is the best way for many institutions to improve their customer service availability. The chatbots will save you a lot of time and money, whilst providing customer support 24/7. But this feature has a separate development process, and therefore you have to pay separately for this.

3. Servers

Servers are where your mobile banking app will be hosted. If you are not with the largest enterprises, you will want to outsource hosting from Amazon, Azure, or Google, which will result in more costs.

4. Content Delivery Network

A CDN is a system that is used to deliver content to the app based on the origin of the content, the content delivery server, and the geographic location of the particular user. In simple words, if you have users across the globe, and they have to keep coming back to one far off location to access the content, then the app will not perform in a good way. So, if you want your mobile banking app to perform effectively, you should use a content delivery network, because it reduces the app loading time and also increases the responsiveness of the app.

5. Development Tools

If you want to use paid deployment tools like iBuildApp, Appy Pie, and IBM MobileFirst, to develop your mobile banking apps, you will need to subscribe to them over the lifespan of your app. This will also affect your banking app development cost.

As we all know, both platforms constantly release updates, and those updates require maintenance. Depending on the extent of maintenance required, the cost in the long-term can sometimes be significant.

7. APIs

Every mobile app usually has multiple third-party APIs that they interact with, especially at the enterprise level. If you make changes to any of these applications, they will require periodic maintenance of your APIs. For instance, Facebook updated their API version four times in 2016; now, what if you want to integrate with Facebook? You will need to update your app to accommodate those changes.

8. Bugs

As you know, every app has bugs, and not even a single developer can assure you that there will be no bugs in the future in your app. It’s just that sometimes they go undiscovered for months or even years. User communities are not kind to apps that are slow to address the issues that they have reported.

Conclusion

The cost of banking application development not only depend on the features of the banking application, but they are also heavily affected by the hidden factors I have mentioned. The primary issue with mobile banking app development cost is the amount of individual components that you need to gather. Each of them can cost thousands of dollars, and these costs will continue throughout the lifespan of your app. However, the rewards that come from a successful mobile banking app development project are huge.

Pro Tip: The cost of developing a banking application greatly depends on the hourly rates of programmers and the expertise of the team. FinTech experts are able to complete these projects much more efficiently.

#banking app development cost #banking application development cost #cost of developing a banking app #cost of developing a banking application #mobile banking app development cost #mobile banking application development cost

1658370036

Weather App in Python | Tkinter – GUI

In this tutorial, you will learn about how to create a GUI Weather App in Python. It uses Open Weather Map API to fetch the latest weather information of cities and places around the globe. Also, we will be implementing the weather app with GUI (Graphical User Interface) rather than the traditional boring ways, which are widely available, showing output in CLI(Command Line Interface).

Code for Weather App in Python – GUI

Without further ado, let’s get right into the code setup for creating our GUI weather app in Python

1. Install and Import Tkinter

We begin with installing the required libraries using the pip package manager. Enter the below commands in your command line or terminal to install the modules.

We need to install:

• Request: to fetch data from API
• Tkinter: to make our Weather app GUI (Graphical User Interface) based.
• DateTime: to change the time from API to a different format
``````pip install tkinter
pip install datetime
pip install requests
pip install json``````

After installing the required libraries from the terminal, we now move to our Python file to code. We start with importing the libraries as:

``````from tkinter import *
import requests
import json
from datetime import datetime``````

2. Initialize the Tkinter Window

As a next step, we initialize our GUI window using the Tkinter module.

``````#Initialize Window

root =Tk()
root.geometry("400x400") #size of the window by default
root.resizable(0,0) #to make the window size fixed
#title of our window

3. OpenWeatherMap API

In our code, we will be using Open Weather API (free tier) to get the current weather information which is accurate and latest.

• To do so, go to OpenWeatherMap website and create an account.
• After creating your account, go to profile and then “My API keys“.
• This will open a webpage for your API Key, as shown below, copy it for later use in code in the next step.

Open Weather Map API

4. Weather Function

Here, comes the part where we add functionality to our code. This part is the most crucial in getting correct weather information, as this involves fetching data from the API and displaying it in an accurate format.

We code the most important function of this code, which is for displaying weather, we do so as in the code:

``````city_value = StringVar()

def showWeather():

#Enter you api key, copies from the OpenWeatherMap dashboard
api_key = "eda2b2s6d#sd65f4de7c4b8"  #sample API

# Get city name from user from the input field (later in the code)
city_name=city_value.get()

# API url
weather_url = 'http://api.openweathermap.org/data/2.5/weather?q=' + city_name + '&appid='+api_key

# Get the response from fetched url
response = requests.get(weather_url)

# changing response from json to python readable
weather_info = response.json()

tfield.delete("1.0", "end")   #to clear the text field for every new output

#as per API documentation, if the cod is 200, it means that weather data was successfully fetched

if weather_info['cod'] == 200:
kelvin = 273 # value of kelvin

#-----------Storing the fetched values of weather of a city

temp = int(weather_info['main']['temp'] - kelvin)                                     #converting default kelvin value to Celcius
feels_like_temp = int(weather_info['main']['feels_like'] - kelvin)
pressure = weather_info['main']['pressure']
humidity = weather_info['main']['humidity']
wind_speed = weather_info['wind']['speed'] * 3.6
sunrise = weather_info['sys']['sunrise']
sunset = weather_info['sys']['sunset']
timezone = weather_info['timezone']
cloudy = weather_info['clouds']['all']
description = weather_info['weather'][0]['description']

sunrise_time = time_format_for_location(sunrise + timezone)
sunset_time = time_format_for_location(sunset + timezone)

#assigning Values to our weather varaible, to display as output

weather = f"\nWeather of: {city_name}\nTemperature (Celsius): {temp}°\nFeels like in (Celsius): {feels_like_temp}°\nPressure: {pressure} hPa\nHumidity: {humidity}%\nSunrise at {sunrise_time} and Sunset at {sunset_time}\nCloud: {cloudy}%\nInfo: {description}"
else:
weather = f"\n\tWeather for '{city_name}' not found!\n\tKindly Enter valid City Name !!"

tfield.insert(INSERT, weather)   #to insert or send value in our Text Field to display output``````

As a final step to adding functionality, we add a function to change the time format, this function checks for the local time as compared to the UTC(Universal Time Coordinated) in which the API gives the output to the time format as per our location. Ex. UTC to IST.

``````def time_format_for_location(utc_with_tz):
local_time = datetime.utcfromtimestamp(utc_with_tz)
return local_time.time()``````

5. Coding the GUI (frontend elements)

We now start to code the elements as per the GUI, for heading, text, labels, buttons, etc.

To start with, we code the text field for the City Name we want the weather for, along with the label to indicate so:

• We use the Label method to generate a label of text to indicate the purpose of the input field for city name.
• Entry method is used to make an entry field for input of city name, to check its weather.
• The textvaraible widget is used to store the inputted value, in the variable named: city_value
• Other than these widgets we have also applied some styling to our code, by font size, color, etc.
``````city_head= Label(root, text = 'Enter City Name', font = 'Arial 12 bold').pack(pady=10) #to generate label heading

inp_city = Entry(root, textvariable = city_value,  width = 24, font='Arial 14 bold').pack() #entry field``````

We code a Check Weather Button, on which we click to check the weather of the user inputted city:

• We give our button some styling, along with the name – ‘Check Weather’. We use the ‘command‘ widget, which shows what function (here, showWeather function) would run on the click (key press) of the button, as coded in the previous step.
``Button(root, command = showWeather, text = "Check Weather", font="Arial 10", bg='lightblue', fg='black', activebackground="teal", padx=5, pady=5 ).pack(pady= 20)``

After adding this, we add the output elements in our code. The elements on which our Weather information would be displayed.

• Yet again, we add a label to title our result in the following text box
• To display the output we use a text field, which gets its value, every time the “Check Weather” button is pressed. This envokes the function to check weather info fetched from the API after processing, [output from the showWeather function]
``````weather_now = Label(root, text = "The Weather is: ", font = 'arial 12 bold').pack(pady=10)

tfield = Text(root, width=46, height=10)
tfield.pack()``````

On execution of our code, the Tkinter displays this as output:

Weather App Frontend In Python

Final Code for GUI Weather App in Python

``````from tkinter import *
import requests
import json
from datetime import datetime

#Initialize Window

root =Tk()
root.geometry("400x400") #size of the window by default
root.resizable(0,0) #to make the window size fixed
#title of our window

# ----------------------Functions to fetch and display weather info
city_value = StringVar()

def time_format_for_location(utc_with_tz):
local_time = datetime.utcfromtimestamp(utc_with_tz)
return local_time.time()

city_value = StringVar()

def showWeather():
#Enter you api key, copies from the OpenWeatherMap dashboard
api_key = "eda2b2s6d#sd65f4de7c4b8"  #sample API

# Get city name from user from the input field (later in the code)
city_name=city_value.get()

# API url
weather_url = 'http://api.openweathermap.org/data/2.5/weather?q=' + city_name + '&appid='+api_key

# Get the response from fetched url
response = requests.get(weather_url)

# changing response from json to python readable
weather_info = response.json()

tfield.delete("1.0", "end")   #to clear the text field for every new output

#as per API documentation, if the cod is 200, it means that weather data was successfully fetched

if weather_info['cod'] == 200:
kelvin = 273 # value of kelvin

#-----------Storing the fetched values of weather of a city

temp = int(weather_info['main']['temp'] - kelvin)                                     #converting default kelvin value to Celcius
feels_like_temp = int(weather_info['main']['feels_like'] - kelvin)
pressure = weather_info['main']['pressure']
humidity = weather_info['main']['humidity']
wind_speed = weather_info['wind']['speed'] * 3.6
sunrise = weather_info['sys']['sunrise']
sunset = weather_info['sys']['sunset']
timezone = weather_info['timezone']
cloudy = weather_info['clouds']['all']
description = weather_info['weather'][0]['description']

sunrise_time = time_format_for_location(sunrise + timezone)
sunset_time = time_format_for_location(sunset + timezone)

#assigning Values to our weather varaible, to display as output

weather = f"\nWeather of: {city_name}\nTemperature (Celsius): {temp}°\nFeels like in (Celsius): {feels_like_temp}°\nPressure: {pressure} hPa\nHumidity: {humidity}%\nSunrise at {sunrise_time} and Sunset at {sunset_time}\nCloud: {cloudy}%\nInfo: {description}"
else:
weather = f"\n\tWeather for '{city_name}' not found!\n\tKindly Enter valid City Name !!"

tfield.insert(INSERT, weather)   #to insert or send value in our Text Field to display output

#------------------------------Frontend part of code - Interface

inp_city = Entry(root, textvariable = city_value,  width = 24, font='Arial 14 bold').pack()

Button(root, command = showWeather, text = "Check Weather", font="Arial 10", bg='lightblue', fg='black', activebackground="teal", padx=5, pady=5 ).pack(pady= 20)

#to show output

weather_now = Label(root, text = "The Weather is:", font = 'arial 12 bold').pack(pady=10)

tfield = Text(root, width=46, height=10)
tfield.pack()

root.mainloop()``````

Conclusion

That’s it for the tutorial. Hope you have learned well how to make a Weather App in Python and that too with a level up by coding an Interface Based script along with API call (Open Weather Map) and Tkinter.

Weather App in Python using Tkinter module

In this article, we are going to discuss how to create a weather app using tkinter. The GUI app will tell us the current weather of a particular city along with temperature details along with other details.

Modules required:

• Tkinter: It is a built-in python library for making GUI using tkinter toolkit.
• Requests: It is a library which helps in fetching the data with the help of URL. It can be installed using the below command:
``pip install requests``

Approach:

Firstly, we have to use a weather API for fetching the data from the Open Weather Map website by generating an API key, and then we need to create a configuration file to store the key. And finally using that configuration file in the python script.

Steps to generate an API key:

• Login in the Open Weather Map
• Go to the API section. Then in the Current Weather Data section click on the Api doc.
• Now in the API Call section, we have the link of api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}
• Click on the API key on the link it will direct to the page from where you can get the key. The generated key looks like this:

Steps to create the Configuration file:

• Create a file named config.ini.
• Write key name enclosed in closed brackets in it here [gfg].
• Create a variable key(here key) and paste the key you copied as shown below:

Steps to create the Python script:

• Import modules.
``````# import required modules
from configparser import ConfigParser
import requests
from tkinter import *
from tkinter import messagebox
``````
• We have to first make the body of the GUI with the help of tkinter.
``````# create object
app = Tk()

app.title("Weather App")

app.geometry("300x300")

# add labels, buttons and text
city_text = StringVar()
city_entry = Entry(app, textvariable=city_text)
city_entry.pack()

Search_btn = Button(app, text="Search Weather",
width=12, command=search)
Search_btn.pack()

location_lbl = Label(app, text="Location",
font={'bold', 20})
location_lbl.pack()

temperature_label = Label(app, text="")
temperature_label.pack()

weather_l = Label(app, text="")
weather_l.pack()

app.mainloop()
``````
• Read the config.ini file and then load the key and URL in the program.
``````# extract key from the
# configuration file
config_file = "config.ini"
config = ConfigParser()
api_key = config['gfg']['api']
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid={}'
``````
• Make a getweather() function to get the weather of a particular location.
``````# explicit function to get
# weather details
def getweather(city):
result = requests.get(url.format(city, api_key))

if result:
json = result.json()
city = json['name']
country = json['sys']
temp_kelvin = json['main']['temp']
temp_celsius = temp_kelvin-273.15
weather1 = json['weather'][0]['main']
final = [city, country, temp_kelvin,
temp_celsius, weather1]
return final
else:
print("NO Content Found")
``````
• Search function so that we can get the output weather details.
``````# explicit function to
# search city
def search():
city = city_text.get()
weather = getweather(city)

if weather:
location_lbl['text'] = '{} ,{}'.format(weather[0], weather[1])
temperature_label['text'] = str(weather[3])+" Degree Celsius"
weather_l['text'] = weather[4]

else:
messagebox.showerror('Error', "Cannot find {}".format(city))
``````

Below is the complete program:

``````# import required modules
from configparser import ConfigParser
import requests
from tkinter import *
from tkinter import messagebox

# extract key from the
# configuration file
config_file = "config.ini"
config = ConfigParser()
api_key = config['gfg']['api']
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid={}'

# explicit function to get
# weather details
def getweather(city):
result = requests.get(url.format(city, api_key))

if result:
json = result.json()
city = json['name']
country = json['sys']
temp_kelvin = json['main']['temp']
temp_celsius = temp_kelvin-273.15
weather1 = json['weather'][0]['main']
final = [city, country, temp_kelvin,
temp_celsius, weather1]
return final
else:
print("NO Content Found")

# explicit function to
# search city
def search():
city = city_text.get()
weather = getweather(city)
if weather:
location_lbl['text'] = '{} ,{}'.format(weather[0], weather[1])
temperature_label['text'] = str(weather[3])+" Degree Celsius"
weather_l['text'] = weather[4]
else:
messagebox.showerror('Error', "Cannot find {}".format(city))

# Driver Code
# create object
app = Tk()
app.title("Weather App")
app.geometry("300x300")

# add labels, buttons and text
city_text = StringVar()
city_entry = Entry(app, textvariable=city_text)
city_entry.pack()
Search_btn = Button(app, text="Search Weather",
width=12, command=search)
Search_btn.pack()
location_lbl = Label(app, text="Location", font={'bold', 20})
location_lbl.pack()
temperature_label = Label(app, text="")
temperature_label.pack()
weather_l = Label(app, text="")
weather_l.pack()
app.mainloop()
``````

#python #gui #tkinter