Cosmic Horror and Sci-Fi are two ways to talk about Dolmen. It is a third person action game with RPG elements but with a lovecraftian plot that calls players to find what's behind the darkest secret of the universe! A forgotten planet called Revion Prime will be the place where the action takes part. And it won't be easy: Adaptation and exploration will be your main weapons as you craft new items and equipments from your enemies' carcasses! Every step can be your last one!
Use your experience points to improve yourself and face what no human has ever faced. After all, quoting David Hume: "The life of man is of no greater importance to the universe than that of an oyster." Maybe he was right Or not.
Posted by: xSicKxBot - 06-03-2022, 08:42 AM - Forum: Python
- No Replies
How to Add Two Lists Element-wise in Python
Rate this post
Summary: The most pythonic approach to add two lists element-wise is to use zip() to pair the elements at the same positions in both lists and then add the two elements. Here’s a quick look at the solution: [x + y for x, y in zip(li_1, li_2)]. An alternate proposition to this without using zip: [li_1[i]+li_2[i] for i in range(len(li_smaller))]
Problem Formulation
Problem Statement: Given two lists, how will you add the two lists element-wise?
Example: Consider that you have the following lists:
Challenge: How will you perform an element-wise addition of the two lists as shown below:
Solution 1: The Naive Approach
Approach:
The basic solution to this problem is to find out the length of the smaller list.
Then use a for loop to iterate across all the items of each list. Note that the range of iteration will be determined by the length of the smaller list.
In every iteration, select an element from each list with the help of its index and then add them up.
You can store the output generated in each iteration within another list and finally display the resultant list as an output.
Code:
# Given Lists
li_1 = [2, 4, 6]
li_2 = [1, 3, 5, 15]
res = [] # resultant list to store the output # Find the smaller list
li_smaller = li_1 if len(li_2) > len(li_1) else li_2 for i in range(len(li_smaller)): # add each item from each list one by one res.append(li_1[i] + li_2[i])
print(res)
Output:
[3, 7, 11]
The above solution can further be compressed with the help of a list comprehension, as shown below:
# Given Lists
li_1 = [2, 4, 6]
li_2 = [1, 3, 5, 15] # Find the smaller list
li_smaller = li_1 if len(li_2) > len(li_1) else li_2 res = [li_1[i]+li_2[i] for i in range(len(li_smaller))]
print(res)
Let’s try to understand the working principle behind the list comprehension used in the above snippet.
The first part is the expression. In the above snippet, li_1[i]+li_2[i] is the expression that denotes the element-wise addition of the two lists. The second part represents the context which represents the counter variable i that ranges from 0 until the length of the smaller list. It is basically keeping track of the index of each element in the lists.
Approach: A more pythonic solution to the given problem is to pass both the lists into the zip() method. This returns a tuple consisting of elements in pairs that are at the same position in each list. Once you get the pair of elements, you can simply add them up. All of this can be performed within a list comprehension.
Code:
li_1 = [2, 4, 6]
li_2 = [1, 3, 5, 15]
res = [x + y for x, y in zip(li_1, li_2)]
print(res) # OUTPUT: [3, 7, 11]
An advantage of using this approach over the previous solution is not only is it a more pythonic way of adding the two lists, but it also eliminates the necessity to explicitly find out the length of the smaller list in case the two lists have different lengths.
A Quick Recap to Zip():
The zip() function takes an arbitrary number of iterables and aggregates them to a single iterable, a zip object. It combines the i-th values of each iterable argument into a tuple. Hence, if you pass two iterables, each tuple will contain two values. If you pass three iterables, each tuple will contain three values. For example, zip together lists [1, 2, 3] and [4, 5, 6] to [(1,4), (2,5), (3,6)]. Read More: Python Zip — A Helpful Illustrated Guide
Finding Sum of Two Lists Element-wise for list of lists
li = [[1, 2, 3], [4, 5, 6]]
res = [a + b for a, b in zip(*li)]
print(res) # [5, 7, 9]
Python facilitates us with many predefined functions for numerous mathematical, logical, relational, bitwise etc operations. These functions are contained within the operator module. One such function is add(a,b), which returns the result of the addition of the two arguments, i.e., a+b.
The map() function transforms one or more iterables into a new one by applying a “transformator function” to the i-th elements of each iterable. The arguments are the transformator function object and one or more iterables. If you pass n iterables as arguments, the transformator function must be an n-ary function taking n input arguments. The return value is an iterable map object of transformed, and possibly aggregated, elements.
Approach: Pass the input lists and the add() function within the built-in method map(). The add() method will simply add the elements of the two lists and then return an iterable. This iterable can then be converted to a list using the list constructor.
Until now, all the solutions considered the length of the smaller list. What if you want to add the elements considering the length of the larger list. In other words, consider the following scenario:
Given:
li_1 = [2, 4, 6] li_2 = [1, 3, 5, 15]
Expected Output:
[3, 7, 11, 15]
Approach: To deal with this scenario, you can use the zip_longest method of the itertools module. Not only will this method group the elements at the same position in each list, but it also allows you to take the remaining elements of the longer list into consideration.
Pass the two lists within the zip_longest() function and assign 0 the fillvalue parameter.
If all the items from the smaller list get exhausted, then the remaining values will be filled by the value that has been assigned to the fillvalue parameter.
Finally, perform the addition of elements at the same position that have been paired by the zip_longest method using the sum() function.
Code:
from itertools import zip_longest
li_1 = [2, 4, 6]
li_2 = [1, 3, 5, 15]
res = [sum(x) for x in zip_longest(li_1, li_2, fillvalue=0)]
print(res)
If you have two lists that have the same length, then using Numpy can be your best bet. There are two ways of implementing the solution that you need. Let’s have a look at them one by one:
The + Operator
You can simply create two numpy arrays from the two lists and then find their sum using the + operator. Easy peasy!
import numpy as np
li_1 = [2, 4, 6]
li_2 = [1, 3, 5]
a = np.array(li_1)
b = np.array(li_2)
print(a+b) # [ 3 7 11]
numpy.add
The alternate formulation to the above solution is to use the numpy.add() method instead of directly using the + operator.
Phew! We unearthed a wealth of solutions to the given problem. Please feel free to use any solution that suits you. Here’s a general recommendation to use the above approaches:
Using zip is probably the most pythonic approach when you have simple lists at your disposal.
In case you do not wish to use zip, you can simply use a list comprehension as discussed in the first solution.
For lists with different lengths, you may use the zip_longest method to solve your problem.
Posted by: xSicKxBot - 06-03-2022, 08:42 AM - Forum: Lounge
- No Replies
Madden NFL 23 Preorders Are Live: Get A $15 Gift Card With Your Order
Another football season is right around the corner, and that means another installment in the long-running Madden franchise is gearing up for release. Madden NFL 23 is scheduled for an August 19 kickoff on PS4, PS5, Xbox One, Xbox Series X|S, and PC, and there are a bunch of great incentives for reserving your copy early. There are also two editions of the game up for grabs--here’s what you need to know before preordering Madden NFL 23.
Madden NFL 23 Preorder Bonuses
Madden NFL 23 has a few interesting preorder bonuses. If you preorder the All-Madden edition before July 22, you’ll get an All-Madden Team Elite Player and an 87 OVR player for your elite team. You’ll also get early access to Challenges starting on August 16.
Preorder the standard edition and you’ll get two Elite Team Players, All Madden Gear, and a Madden Strategy Item for Ultimate Team.
This one is a bit different from the usual GOG freebies, you need to only claim the pack above and check out, and you will receive the Warhammer 40,000: Chaos Gate game and the extra goodies content.
We are welcoming everyone to join our discord[discord.gg]. We are more active there on finding giveaways, small or large, and there are daily raffles you can participate.
[www.indiegala.com] The Wunder Gate Bundle is LIVE! Uncertainty turns into serendipity with this wonderful indie selection: SHUT IN, Wunderling DX, Gate to Site 8, Zom Tom, Firelight Fantasy: Vengeance, 3D PUZZLE - Farm House.
[indiegala.com] What better way to relax than listening to some tunes with your friends? The Dream Beats Bundle is about to end, but not before bringing you the chance to grab a few extra copies for your pals during the Happy Hour.
What if vampires were real? What if these bloodthirsty predators lived hidden among us, meticulously and skilfully hatching ancient conspiracies? And what if you became one of them? In Vampire: The Masquerade - Swansong, you play as these alluring monsters in a sophisticated world where the lines between the real and supernatural are always blurred.
Hazel Iversen, the Swan, is the new Prince of the Boston Camarilla. An iron hand in a velvet glove, she intends to assert her power and respect the Masquerade, the vampiric law designed to ensure humans never learn of the existence of these creatures of the night. But nothing works as planned. With rumours of plots, murders and power struggles, you must work in the shadows to protect your Sect in a frantic investigation that plunges Boston into chaos.
Play as 3 vampires who are over a hundred years old. Progress through the game through their intertwined destinies, deal with their different points of view and use their character sheets to try to separate the truth from the lies. Each character has their own abilities and vampiric disciplines that you can upgrade individually to suit your preferred approach.
Will you choose intimidation, seduction or stealth? It's your decision, as long as you can sate your Hunger for blood.
With its unique approach to gameplay, Swansong puts emphasis on the consequences of your actions in both the investigation and your social interactions with characters. Analyse each situation carefully because your decisions can have huge consequences on your heroes' lives and the fate of the Boston Camarilla.
As you may already well know, it’s easy to get started with Java on OCI. Following the Java motto ‘write once, run anywhere’, we are adding an exciting new destination for your applications to run on: powerful 64-bit Arm systems running on the Oracle Cloud Infrastructure (OCI). A perfect match for our high-performant Oracle Java SE runtime for 64-bit Arm systems!
Posted by: xSicKxBot - 06-02-2022, 08:39 AM - Forum: Python
- No Replies
How to Convert List of Lists to Tuple of Tuples in Python?
5/5 – (1 vote)
Question: Given a list of lists such as [[1, 2], [3, 4]]. How to convert it to a tuple of tuples such as ((1, 2), (3, 4))?
If you’re in a hurry, here’s the most Pythonic way to convert a nested list to a nested tuple:
Use a generator expression with the built-in tuple() function to convert a list of lists to a tuple of tuples like so: tuple(tuple(x) for x in my_list).
Here’s a graphic on how to convert back and forth between nested list and nested tuples:
But there’s more to it! Studying the different methods to achieve the same goal will make you a better coder.
So keep reading!
Method 1: Tuple Comprehension + tuple()
The recommended way to convert a list of lists to a tuple of tuples is using generator expression in combination with the built-in tuple() function like so: tuple(tuple(x) for x in my_list).
Here’s a concrete example:
lists = [[1, 2], [3, 4], [5, 6]]
tuples = tuple(tuple(x) for x in lists) print(tuples)
# ((1, 2), (3, 4), (5, 6))
Try It Yourself:
This approach is simple and effective. The generator expression defines how to convert each inner list (x in the example) to a new tuple element.
The first argument of the map() function is the tuple function name.
This tuple() function converts each element on the given iterablelists (the second argument) into a tuple.
The result of the map() function is an iterable too, so you need to convert it to a tuple before printing it to the shell because the default string representation of an iterable is not human-readable.
Method 3: Simple For Loop with append() and tuple()
To convert a list of lists to a tuple of tuples, first initialize an empty “outer” list and store it in a variable.
Then iterate over all lists using a simple for loop and convert each separately to a tuple.
Next, append each result to the outer list variable using the list.append() builtin method in the loop body.
Finally, convert the list of tuples to a list tuple of tuples using the tuple() function.
The following example does exactly that:
lists = [[1], [2, 4, 3], [6, 5]] tmp = []
for t in lists: tmp.append(tuple(t))
tuples = tuple(tmp) print(tuples)
# ((1,), (2, 4, 3), (6, 5))
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.