Posted by: xSicKxBot - 03-28-2020, 01:00 AM - Forum: Lounge
- No Replies
This Fantastic Game Is Free On iOS And Android For A Limited Time
Over the past couple of weeks, a bunch of publishers have been giving away free games to help keep people occupied while social distancing. While most of the current freebies are for PC, there are a handful of great mobile games up for grabs, too, including one of the very best puzzle games in recent years: Monument Valley 2. Normally selling for $5, Monument Valley 2 is completely free right now on iOS and Android. Developer Ustwo Games announced the promotion with an adorable video clip and message to fans on Twitter.
A sequel to the 2014 breakout hit, Monument Valley 2 has a wealth of excellent maze puzzles that play with your senses thanks to optical illusions and seemingly insurmountable obstacles. It also has a greater emphasis on narrative than its predecessor. In Monument Valley 2, you control Ro and her young child on a journey about personal growth and the sacred bond between mother and daughter.
You don't need to play the first game to enjoy and appreciate Monument Valley 2. Though the subtle ways the two games connect are more poignant if you have knowledge of the original, the maze puzzles themselves are enough to recommend Monument Valley 2. Plus, you can't beat free.
The Elder Scrolls: Blades Gets Reconfirmed For Switch, Launches This Spring
During the latest Nintendo Direct Mini, Bethesda’s mobile port The Elder Scrolls: Blades was briefly highlighted in a sizzle reel towards the end of the presentation. In case you forgot, this game was originally announced for the Switch at E3 last year and then got delayed until early 2020.
Now, according to the latest Nintendo showcase, the free-to-title will be arriving this spring on the Switch eShop. The reason for the delay last November was due to “all the other changes” the development team was currently making to Blades. At the time, Bethesda also wanted to make the Switch version a better and more polished experience overall.
When it does arrive, the Switch release will support motion controls, cross-platform PvP matches, and cross-progression – meaning you can continue your play session on Switch or mobile. An online connection will also be required to play the game.
Will you be taking a look at this free entry of Elder Scrolls when it eventually shows up on Switch? Leave a comment below.
Salim will be directing a new game IP developed by Silver Rain Games, where former BAFTA programme manager Melissa Phillips is serving as head of studio. Silver Rain is taking on "a growing team of developers" for the project.
"The games industry is so inspiring," Salim said. "I grew up in games, so it only feels natural to make the leap into creating them. I want to be able to give back to an industry and audience that has supported me and hopefully bring a fresh perspective to the table."
Doors, once hidden, open on the lunar surface revealing another Seraph Bunker in Rasputin’s network. Guardians have begun exploring it to see what upgrades lie within. And if you’re up for the challenge, there are also new Legendary Lost Sectors available and new weapons to get your hands on.
That’s not all. Lord Saladin is at the Tower and has a new Bow for you to earn along with several opportunities for pinnacle drops. On top of all that, week three of Trials of Osiris begins tomorrow. What map do you think will be featured this week?
World Drops
There were several armor sets added to the engram loot pool with Season of the Worthy. We saw a lot of feedback that, while you were excited to see your favorite armor sets from the past, the fact that none of them had Seasonal mod slots made them feel less desirable and not worth including in your builds.
Good news! We’re adding Seasonal mod slots to these sets in an update next month. The three faction sets will get Season of the Worthy mod slots and the rest of the armor will get either Season of Dawn or Season of the Undying mod slots.
Season of Dawn Mod Slot Added:
Dead End Cure
Retro-Grade TG2
Heiro Camo
Road Complex AA1
Devastation Complex
High-Minded Complex
Season of the Undying Mod Slot Added:
Red Moon Phantom
Mimetic Savior
Thorium Holt
Tangled Web
Prodigal
Frumious
Noble Constant Type 2
Ego Talon IV
Errant Knight
Kerak Type 2
Philomath
All of these sets will be able to use Seasonal mods from the Seasons before and after the Season they are designated above (as explained in a previous TWAB).
The Fixings
We are currently targeting Tuesday, March 31 to deploy Hotfix 2.8.0.2. The main target of this update will be the issue affecting Trials of Osiris challenges not being reset properly. Here’s a quick preview of other fixes coming in this update:
Fixed an issue where upgrades on the Season Pass where only unlocked for one character and will now properly unlock for the entire account.
Fixed an issue where the first weekly clear of a Legendary Lost Sector would not award a powerful drop.
Fixed an issue with Raiju’s Harness that allowed players to hold Whirlwind Guard indefinitely.
Fixed an issue where Titan Season Pass arms ornament would block first person view.
Season Pass SMG and Shotgun will now create Warmind cells with Season Pass ornaments equipped.
Fixed an issue where Sentinel Titans were able to extend Sentinel Shield/Banner Shield by suppressing themselves.
Fixed an issue where players were not getting the correct amount of planetary materials from bunker upgrades.
Aside from the fixes in 2.8.0.2 we’re also continuing to investigate disconnects, crashes, and error codes being reported since 2.8.0 we released. Currently, we are seeing elevated disconnects from the Tower on all platforms but disconnects from other activities seems PC-specific.
The fix we deployed has appeared to resolve the crashes affecting Gambit, but didn’t help with other disconnects. We have made additional attempts at fixing disconnects that haven’t resulted in a decline in error codes and are continuing to work on new fixes for elevated Beaver, Beetle, Anteater, and Rabbit errors. We’ll give you more information as soon as we can.
Twitch Prime Rewards
We continued our monthly rollout of Twitch Prime Rewards today. If you have an active Prime subscription, visit this page to link your Bungie.net account and claim your rewards. After that, they should be available at Amanda Holliday in the Tower. Here’s a look at what you can get this month:
Prometheus Lens – Exotic Weapon
Eye of Osiris – Exotic Weapon Ornament
Tyrant Shell – Exotic Ghost Shell
Fleet Ska IX – Legendary Ship
Player Support Report
Destiny Player Support is constantly tracking known issues in the wild.
This is their report.
TRIALS WEEKLY CHALLENGE RESET TIME
Last weekend, Destiny Player Support noticed an increase in reports about players not receiving powerful rewards from their third, fifth, or seventh Trials of Osiris win. Upon investigation, the team discovered an error in the Weekly Challenge reset time.
Trials of Osiris Weekly Challenges will unlock at 5 PM PDT on Saturdays. At this time, rewards are expected to be reset for players who have been impacted, and rewards will be granted when players reach three, five, or seven wins respectively. In a future patch, we will move this reset to the Friday daily reset.
SEASON OF THE WORTHY SEAL
We have noticed that players have been trying unsuccessfully to unlock a hidden Triumph in the Season of the Worthy Almighty Seal when meeting the requirements. This Triumph is not currently available to unlock but will be so in late April.
RASPUTIN BUNKER BOUNTIES
With the Moon Bunker now unlocked, Destiny Player Support noticed some confusion about the bounties Rasputin offered. Weekly and daily Rasputin bounties are only available on the destination where the Weekly Challenge is active.
CURRENT KNOWN ISSUES
While we continue investigating various known issues, here’s a list of the latest issues that were reported to us in our #Help Forum:
Some players may not receive progress on Crucible and Iron Banner quests and bounties. These are caused by connection issues and continuing to play will progress these objectives.
Rasputin’s Daily Seraph Weapon can only be claimed on the character players were on when Rank 92 of the Season Pass was unlocked – this cannot be claimed on other characters.
The “Lost Classics” Rasputin bounty does not count Crucible matches in the Classic Mix playlist.
For a full list of emergent issues in Destiny 2, players can review our Known Issues article. Players who observe other issues should report them to our #Help forum.
Lights, Camera, Action!
And now we move on to the entertainment portion of our weekly address. This is our chance to pick a few videos created by the community to share with you. As a bonus, their creators get to take home a special emblem and be the envy of their fireteams.
Movie of the Week: Titan Sword
Honorable Mention: Four Horn Gulch
For the best chance at being featured and winning a MotW emblem, get us your video by using the Creations Page. If you do win, please make sure you include a link to your Bungie.net profile in the description of the video.
We got new stuff to do on the Moon and in the Iron Banner this week. Next week, we’ll have an Infamy Bonus available for anyone who wants to play some Gambit.
I had my first flawless Trials run last weekend! Might have to go for it again this weekend since the map is going to be [REDACTED].
BETA: BEDROCK 1.16.0.53 (XBOX ONE / WINDOWS 10 / ANDROID)
The latest Minecraft Beta brings a lot of fixes and stability. While this update is also working towards the Nether Update, some features in Java Edition snapshots may not be included yet.
Remember that only those on Xbox One / Windows 10 / and Android may participate in the Beta builds. You will not be able to join Realms or non-beta players worlds and you will not be able to open worlds opened in the Beta in earlier/current stable builds of Bedrock.
Crashes and Stability
Fixed several crashes that could occur during gameplay
Fixed a crash that could sometimes occur in split-screen when the host saves and quits the game
Fixed stability issues when using some custom character creator skins
Improved performance related to maps in item frames (REALMS-1532)
Take on the Toughest Off-Road Challenge with Overpass on Xbox One
Overpass is a new kind of racing game, where the solution to winning is to be gentle with the throttle to keep some grip and be able to power through mud, rocks, steep slopes and many obstacles.
You’re at the wheel of buggies and quads and must
find a way to finish the track. Yes, the ultimate goal is to do it within the
best time possible, but the first step is to explore and make it to the finish
line. It’s not always so easy to do!
Intense Multiplayer Modes
You can play Overpass in single-player, spending time discovering tracks, trying vehicles and new ways to climb the hills. But at some point, you’ll want to jump into multiplayer modes! The intensity and tension become so enjoyable when you see seven other players trying to cross obstacles faster than you. Things can change so quickly, as leading the race can become difficult if you lose your composure and try to go faster than you should on some parts of the track. Leaderboards will be added shortly after launch and the competition to lead should be intense!
Natural and Artificial Obstacles
You must face many obstacles in the game. Some
are natural, like mud for example, that can easily cause your wheels to spin on
the spot, or rocks, that are tough to cross without causing damages to the
vehicle. Very often, this is combined with steep slopes, increasing again the
difficulty. There are other types of obstacles though, built by men. You will
encounter tree trunks, piles of tires, big pipes, seesaws and many others.
No matter which obstacle you are facing, your
best shot is to analyze it quickly and understand the best way or the best
angle to cross it. Then, you will have to be gentle on the throttle to get
enough power to climb, but not too much if you don’t want to lose grip.
Overpass is available now on the Microsoft Store. The Deluxe edition also gives you access to exclusive vehicles and a special livery to drive with style! For more information or questions about Overpass, you can join us on the official Facebook and Twitter pages. See you off-road!
OVERPASS™ DELUXE EDITION
Bigben Interactive
☆☆☆☆☆9
★★★★★
The DELUXE EDITION includes: – The full OVERPASS™ game – The Expert Vehicles Pack, which contains the Polaris RZR XP 1000 Trails & Rocks, the Arctic Cat Alterra MudPro 700 LTD and the Zordix Rock Crawler – The Smart Start Pack – The pack Drive With Style At the wheel of powerful buggies and quads from top manufacturers, venture off into extreme off-road environments and challenge yourself on the game’s highly technical tracks. Cope with vehicle damage, and negotiate the many natural and artificial obstacles in your way to achieve the best time possible. Carefully select your UTV or ATV, plot your route intelligently, and manage your acceleration and the various differential and drivetrain options to dominate in local and online competitions.
Don’t Miss: Designing Grindstone’s super satisfying board-clearing gameplay
A lot of studios have passion projects they work on between contract work and other projects and every once and a while those projects get to see the light of day. That’s the case for Capybara Games, the creators of Critter Crunch and Below, who originally started the concept for Grindstone more than a decade ago.
“It didn’t change all that much from design to conception, from prototype to what you are playing,” said Capy lead writer and designer Dan Vader. “It dates back before Below, before [Super Time Force]. We were sort of in the mode of making puzzle games. We did [Might & Magic: Clash of Heroes], we did Critter Crunch. Our creative director Kris Piotrowski came up with the idea for this blend of color-matching puzzle mechanics with a physical character on the board that moved around the board with the puzzle movement you’re creating.”
“We always sort of pictured it as a barbarian setting, a brutal setting with a sort of fun cartoonish take on that world,” he added. “We prototyped it with just basic animations and static frames on a grid and it pretty much stayed the same throughout the history of its development.”
Vader highlighted a few changes that happened throughout the design iteration process as multiple developers at Capy worked on the project off and on between other tasks. The main goal was always to create a satisfying feeling whenever the player could pull off a large combo.
Grindstone shares a lot of DNA with other puzzles games. There are still different colored pieces you need to clear, items you can use to make that easier, and enemies that will attack you if you make a mistake. But Capy wanted something slightly less casual. They wanted Grindstone to be challenging but in a meaningful and satisfying way.
Originally the creeps — the little monsters you attack on the board — would be able to deal damage in every direction around them once they went aggro. In the final version, only special enemies would be able to deal damage this way, and the more common creeps could only attack in four directions — up, down, left, and right.
That small change was a bit of a breakthrough for the game’s design. “There was something about it, we kept thinking about why we were so frustrated when we were playing this game,” he said. “It was just so difficult so we took out the diagonal angles, those were so dangerous, and that just freed things up and made the board so much more maneuverable.”
Grindstone is unique compared to other puzzle games in that the player is limited to making moves from their position on the board. It was important for the player to have a number of options to keep the action going and limiting enemy attack patterns helped prevent the player from dying constantly.
Grindstones, the gems that pop out whenever you get a combo greater than nine creeps long, are at the core of making the game work as intended. They help connect combos of two different colors, which is key to building 30 or 40 creep combos. Grindstones, which were just called gems at the start of the project, were also present as a mechanic from early on in development.
“The design had some parts that were related to more traditional mobile puzzle type things, like every move you made, every kill you made was producing coins,” Vader said. “Back then we didn’t have blood and there were coins spraying out everywhere. You were sort of collecting coins whether you made a great chain or not.”
“So we were sort of frustrated and we would test this with new players and they would spend their time making a five chain, a six chain, a seven chain while we wanted to push them to make these bigger chains,” he added. “We realized we were constantly visually rewarding them for anything they did. Anything they made had a reward since we were showering with coins.” That led the team to just focusing on Grindstones as a reward and a currency.
Both adjustments to the currency and enemy attacks made Grindstone play faster and gave the player a fairer reward for completing big chains.
Another product of constant iteration was the overarching design of the levels themselves, where the player has to reach a certain goal (either total amount of matches or enemies killed) before they could leave via a door at the top of the screen. The door is locked all the way up until you hit that goal.
Capy went back and forth on this several times, trying to figure out how to make their level endings unique. “Originally we had the idea of reaching the door, but we struggled to make that intuitive” Vader said. “Then we changed it to whenever you reach the level goal the level just ends like a traditional puzzle game. But we just liked the literal door, having to get to the door safely.”
Vader said the whole idea of risk and reward, of choosing whether or not to go for more combos (or the additional goal of killing a king creep and opening a separate chest) or get out safely was always with the project. But sticking with the door as a way to end the level amplified the risk and reward factor.
“We decided to make the decision to let the player end the level,” he said. “That opened the door up to a lot of interesting moments.” Adding the door to the level means the player has to actually leave before they can beat a level. If they finish an objective and get stuck among increasingly hostile creeps, they could have to start over. That’s at the core of what makes Grindstone so compelling.
One of the biggest challenges to designing a puzzle game with a player character on the board is how limited the player’s options can end up being. Without specially-designed levels that cater to creating combos, the player could get stuck with few options at their disposal and what should be a fun experience can get frustrating quickly.
“Having the player need to calculate where they end takes this out of the more casual puzzle stage,” Vader said. “Having your next move be the only consideration, especially with the creeps originally hitting in eight directions made it quite challenging.”
Vader and the rest of the team did a few things to make sure the possibilities remained open for the player throughout Grindstone‘s 150 levels. One thing was dialing down how many different colors of creep might appear on a single level. “In terms of just balancing the levels, we added some levels with fewer variations of colors,” he said. “Like you might find a level with 50 percent less of a certain color.”
That change made it easier to put together longer combos. Vader said the team also adjusted how fast creeps went aggro per turn. Both options led to a more forgiving atmosphere.
As players progress throughout Grindstone they unlock various costumes and weapons that grant them additional passive and active abilities. Their designs and abilities mirror the enemies and environments you encounter throughout the game.
“One of the very early prototypes we had the single arrow, kind of similar to our delete option in [Might & Magic: Clash of Heroes],” Vader said. “You can delete an unwanted creep, we also had a sword ability that could clear the area around you, and then a jump ability if you were backed into a corner and needed to get to a different spot on the map.”
“We had those locked down,” he added. “We wanted the gear to make the initial objective, like killing 50 creeps, to not be the biggest challenge. Simply opening the door and clearing the room is a task most players could complete. It’s when you get to the chests, crowns, and additional challenges. That’s when we expanded the gear list so players could create their own playstyle as they take on a bigger challenge.”
That led to weapons like the vine sword, a weapon that creates a growing vine capable of killing multiple enemies over the course of a few turns, and the ice arrow that would make aggressive creeps calm. All things to help the player continue to build big combos and something Capy has done in their previous puzzle games.
Adding a lot of weapons became a challenge to design for as the team had to make sure all weapons worked against all enemies, including the various environmental hazards from each level. The son of one developer actually created a spreadsheet and helped test every single weapon in every scenario, which still left some unexpected bugs in the end.
All these changes amounted to one satisfying gameplay system, in which if you keep making moves you’ll be able to set up a large combo and build a rhythm. Some levels may be more challenging than others, but they were never too stifling. “Even when it seems like your stifled in the beginning, the tide can turn pretty quickly,” Vader said. “If you keep making moves and managing the board, especially early on, it will pay off.”
Posted by: xSicKxBot - 03-27-2020, 11:40 AM - Forum: Python
- No Replies
Python List index()
This tutorial shows you everything you need to know to help you master the essential index() method of the most fundamental container data type in the Python programming language.
Definition and Usage: The list.index(value) method returns the index of the value argument in the list. You can use optional start and stop arguments to limit the index range where to search for the value in the list. If the value is not in the list, the method throws a ValueError.
Here’s a short example:
>>> lst = ["Alice", 42, "Bob", 99]
>>> lst.index("Alice")
0
>>> lst.index(99)
3
>>> lst.index(99, 1, 3) Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> lst.index(99, 1, 3)
ValueError: 99 is not in list
In the first line of the example, you create the list lst. You then look up the index of the elements "Alice" and 99. If you use start=1 and stop=3, the value 99 is not found anymore and Python throws a ValueError.
Code Puzzle — Try It Yourself:
Now you know the basics. Let’s deepen your understanding with a short code puzzle—can you solve it?
Returns the index of value in the list. A value appears in the list if the == operator returns True. If the value doesn’t exist in the list, the return value is -1.
start
(Optional.) The index of where you want to start searching in the list. All list elements in front of this position are ignored. This is a positional argument, not a keyword argument.
stop
(Optional.) The index of where you want to stop searching in the list. All list elements after this position are ignored. This is a positional argument, not a keyword argument.
Return value: The method list.index(value) returns an integer value representing the index where the argument value appears in the list. If the value does not appear in the list, the method throws a ValueError.
The time complexity of the count(value) method is O(n) for a list with n elements. The standard Python implementation cPython “touches” all elements in the original list to check if they are equal to the value.
Again, have a look at the reference implementation where you can see these comparison operations element == value in the code:
def count(lst, value): count = 0 for element in lst: count += element == value return count
Thus, the time complexity is linear in the number of list elements.
You can see a plot of the time complexity of the count() method for growing list size here:
The figure shows how the elapsed time of counting a dummy element -99 in lists with growing number of elements grows linear to the number of elements.
If you’re interested in the code I used to generate this plot with Matplotlib, this is it:
import matplotlib.pyplot as plt
import time y = []
for i in [100000 * j for j in range(10,100)]: lst = list(range(i)) t0 = time.time() x = lst.count(-99) t1 = time.time() y.append(t1-t0) plt.plot(y)
plt.xlabel("List elements (10**5)")
plt.ylabel("Time (sec)")
plt.show()
Python List Count Duplicates
How can you count the number of duplicates in a given list?
Problem: Let’s consider an element a duplicate if it appears at least two times in the list. For example, the list [1, 1, 1, 2, 2, 3] has two duplicates 1 and 2.
Solution: You create an empty set duplicates. Then you iterate over the original list and add each element to the set that has a count value of at least 2.
Here’s the code:
def find_dups(lst): dups = set() for el in lst: if lst.count(el)>1: dups.add(el) return dups print(find_dups([1, 1, 1, 2, 2, 3]))
# {1, 2} print(find_dups(["Alice", "Bob", "Alice"]))
# {'Alice'} print(find_dups([1, 2, 3]))
# set()
Note that this algorithm has quadratic time complexity because for each element in the list, you need to count the number of times it appears in the list—each of those count operations has linear time complexity.
How can you count the number of unique values (or strings) in a given list?
Problem: A value is considered unique if it appears only once in the list.
Solution: You count each element in the list and take only those with list.count(element) == 1.
Here’s the code:
def find_uniques(lst): uniques = set() for el in lst: if lst.count(el) == 1: uniques.add(el) return uniques print(find_uniques([1, 1, 2, 3, 3]))
# {2} print(find_uniques(["Alice", "Bob", "Alice"]))
# {'Bob'}
This algorithm has quadratic time complexity because for each element in the list, you need to count the number of times it appears in the list—each of those count operations has linear time complexity.
Python List Count All Elements (Count to Dict)
How can you count all elements in a list and store the result in a dictionary?
Problem: Given is a list. You want to count each element in the list. Then, you want to store the result in a dictionary mapping the elements to their frequencies of appearance (counts). For example, the list [1, 1, 2, 2, 3] should lead to the dictionary {1:2, 2:2, 3:1}.
Solution: You solve this problem using dictionary comprehension. The key is the list element and the value is the frequency of this element in the list. You use the count() method to do this.
This algorithm has quadratic time complexity because for each element in the list, you need to count the number of times it appears in the list—each of those count operations has linear time complexity.
How can you count elements under a certain condition in Python? For example, what if you want to count all even values in a list? Or all prime numbers? Or all strings that start with a certain character? There are multiple ways to accomplish this, let’s discuss them one by one.
Say, you have a condition for each element x. Let’s make it a function with the name condition(x). You can define any condition you want—just put it in your function. For example this condition returns True for all elements that are greater than the integer 10:
But you can also define more complicated conditions such as checking if they are prime numbers.
Python List Count If
How can you count the elements of the list IF the condition is met?
The answer is to use a simple generator expressionsum(condition(x) for x in lst):
>>> def condition(x): return x>10 >>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(condition(x) for x in lst)
2
The result indicates that there are two elements that are larger than 10. You used a generator expression that returns an iterator of Booleans. Note that the Boolean True is represented by the integer value 1 and the Boolean False is represented by the integer value 0. That’s why you can simply calculate the sum over all Booleans to obtain the number of elements for which the condition holds.
Python List Count Greater / Smaller Than
If you want to determine the number of elements that are greater than or smaller than a specified value, just modify the condition in this example:
>>> def condition(x): return x>10 >>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(condition(x) for x in lst)
2
For example, to find the number of elements smaller than 5, use the condition x<5 in the generator expression:
>>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(x<5 for x in lst)
3
Python List Count Zero / Non-Zero
To count the number of zeros in a given list, use the list.count(0) method call.
To count the number of non-zeros in a given list, you should use conditional counting as discussed before:
def condition(x): return x!=0 lst = [10, 11, 42, 1, 2, 0, 0, 0]
print(sum(condition(x) for x in lst))
# 5
Python List Count Lambda + Map
An alternative is to use a combination of the map and the lambda function.
Here’s the code for this one using the wildcard operator in a pattern to count all occurrences of this pattern in the list.
>>> import re
>>> lst = ['Susi', 'Ann', 'Susanne', 'Susy']
>>> pattern = 'Sus.*'
>>> frequency = sum(1 if re.match(pattern, x) else 0 for x in lst)
>>> print(frequency)
3
The generator expression produces a bunch of 1s and 0s—the former if the list element starts with prefix 'Sus' and the latter if it doesn’t. By summing over all elements, you get the number of matches of the wildcard operator.
Python List Count Not Working
The list.count(value) method is very hard to break. Look what I tried to get an error:
>>> lst = [1, 1, 1, 2, 2, 3]
>>> lst.count(1)
3
>>> lst.count(2, 2)
Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> lst.count(2, 2)
TypeError: count() takes exactly one argument (2 given)
>>> lst.count(4)
0
>>> lst.count("1")
0
>>> count(lst)
Traceback (most recent call last): File "<pyshell#22>", line 1, in <module> count(lst)
NameError: name 'count' is not defined
>>>
You have to try really hard to break it. Just consider these tips:
The list.count(value) method takes exactly one argument: the value you want to count. If you define more or less arguments, there will be an error.
The list.count(value) method is just that: a method of a list object. You need to call it on a list object. If you try to call it on another object, it will probably fail. If you try to use it just like that (without the list prefix, i.e., count(value)), it will also fail.
The list.count(value) will return 0 if you put in any object as an argument that does not evaluate to True when compared to the list elements using the == comparison operator. So make sure that the object you want to count really evaluates to True if you compare it against some list elements. You may assume this but it could easily fail to do so.
Python List Reference Count
The Python garbage collector keeps track of the number of times each object in memory is referenced. You call this “reference counting”. All objects that have reference count of zero cannot be reached by your code and, thus, can be safely removed by the garbage collector.
It’s unrelated to Python lists with the one exception: each list element increases the reference count by one because a list really is an array of pointers to the list objects in memory in the cPython implementation.
Python List Count Tuples
How can you count the number of times a given tuple appears in a list?
Simply use the tuple as the input argument value for the list.count(value) method. Here’s an example:
Do you want to improve performance of the list.count(value) method? It’s not easy because the runtime complexity is O(n) with n list elements.
There’s not much you can do about it. Of course, if you need to count the same element multiple times, you can use a cache dictionary to store its result. But this works only if the list has not changed.
You can also sort the list once which takes O(n log n) for n list elements. After that, you can call the implement a count method based on binary search with O(log n) runtime complexity. But if you need to count only a single element, this is not effective.
Interestingly, counting all elements in a list also has O(n) runtime complexity. Why? Because you’ll go over each element and add it to a dictionary if it doesn’t exist already (mapping the element to its counter value, initially 1). If it exists, you simply increment the counter by one.
In this excellent benchmark, you can find the performance of different counting methods. The Counter class seems to have best performance.
Python List Count vs Len
What’s the difference?
The list.count(x) method counts the number of occurrences of the element x in the list.
The len(list) method returns the total number of elements in the list.
Do you have multiple threads that access your list at the same time? Then you need to be sure that the list operations (such as count()) are actually thread safe.
In other words: can you call the count() operation in two threads on the same list at the same time? (And can you be sure that the result is meaningful?)
The answer is yes (if you use the cPython implementation). The reason is Python’s global interpreter lock that ensures that a thread that’s currently working on its code will first finish its current basic Python operation as defined by the cPython implementation. Only if it terminates with this operation will the next thread be able to access the computational resource. This is ensured with a sophisticated locking scheme by the cPython implementation.
The only thing you need to know is that each basic operation in the cPython implementation is atomic. It’s executed wholly and at once before any other thread has the chance to run on the same virtual engine. Therefore, there are no race conditions. An example of such a race condition would be the following: the first thread reads a value from the list, the second thread overwrites the value, and the first thread overwrites the value again invalidating the second thread’s operation.
All cPython operations are thread-safe. But if you combine those operations into higher-level functions, those are not generally thread safe as they consist of many (possibly interleaving) operations.
Where to Go From Here?
The list.count(x) method counts the number of times the element x appears in the list.
If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: Python One-Liners (Amazon Link).
In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code!
OFFICIAL BOOK DESCRIPTION:Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.