Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,150,829 members, 7,810,185 topics. Date: Friday, 26 April 2024 at 10:46 PM

My Python Programming Diary - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / My Python Programming Diary (1458 Views)

My Python Journey / How Can I Set Up Or Run My Python IDE On VS Code On Windows 8 / A Thread For Tutorial On Python Programming (2) (3) (4)

(1) (Reply) (Go Down)

My Python Programming Diary by monikulapo: 1:53pm On Oct 09, 2021
Hello All,

I am currently working through Codewars in order to improve my Python Proficiency before diving into Django.
I provide the problem links, along with my solution for anyone who's interested.
Any suggestions on alternate solutions, logic and best practices would be really appreciated.
Re: My Python Programming Diary by monikulapo: 2:29pm On Oct 09, 2021
Hello house, I expect the code snippet above to return:
Wayne, John, Samson, Mike, Seun,
However, what I get is:
Wayne, John, Samson,
Please, what is going on under the hood ?
a = ['Seun','Mike','Samson','John','Wayne']
j = ''
for i in a:
j = j + a.pop()
j += ', '
print(j)
I was wondering why the a.pop() method isn't working as expected.

Modified:
Okay, so I just learnt that modifying a list while iterating through it could lead to errors like this. It is best to create a new list and add items to it rather than removing items from the existing list.

3 Likes 1 Share

Re: My Python Programming Diary by monikulapo: 12:48pm On Oct 12, 2021
For anyone following, this was what I was solving when I encountered the problem above:
Given: an array containing hashes of names.
Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand. https://www.codewars.com/kata/53368a47e38700bd8300030d/train/python
For example:
namelist([ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'} ])
# returns 'Bart, Lisa & Maggie'

namelist([ {'name': 'Bart'}, {'name': 'Lisa'} ])
# returns 'Bart & Lisa'

namelist([ {'name': 'Bart'} ])
# returns 'Bart'

namelist([])
# returns ''

This is my solution,
def namelist(names):
lnames = [name['name'] for name in names] #Unpack name values from dictionary into a list
flist = lnames[:-2] #flist of names exluding last two elements
elist = lnames[-2:] #elist containing last two elements
eString = ' & '.join(elist) #string of last two elements joined with '&'

if len(lnames) <= 1:
return ''.join(lnames) #returns single element as string
else:
nflist = [name + ',' for name in flist] #create nflist containing comma modified elements from flist
nflist.append(eString) #added last string as an element to nflist
return ' '.join(nflist) #returns list elements as strings

1 Like

Re: My Python Programming Diary by monikulapo: 1:53pm On Oct 12, 2021
In a small town the population is p0 = 1000 at the beginning of a year. The population regularly increases by 2 percent per year and moreover 50 new inhabitants per year come to live in the town. How many years does the town need to see its population greater or equal to p = 1200 inhabitants? https://www.codewars.com/kata/563b662a59afc2b5120000c6/train/python

Here's my solution:
def nb_year(p0, percent, aug, p):
totalp = 0
year = 0
percent = percent / 100
while totalp < p:
totalp = p0 + (p0 * percent) + aug
totalp = int(totalp)
p0 = totalp
year += 1
return year

1 Like

Re: My Python Programming Diary by monikulapo: 2:21am On Oct 14, 2021
Implement a function that accepts 3 integer values a, b, c. The function should return true if a triangle can be built with the sides of given length and false in any other case.
(In this case, all triangles must have surface greater than 0 to be accepted)https://www.codewars.com/kata/56606694ec01347ce800001b/python
Here's my solution:
def is_triangle(a, b, c):
if (a + b > c) and (a + c > b) and (b + c > a):
return True
else:
return False

1 Like

Re: My Python Programming Diary by Gentleman001: 2:35am On Oct 14, 2021
monikulapo:

a = ['Seun','Mike','Samson','John','Wayne']
j = ''

for i in a:
j = j + a.pop()
j += ', '

print(j)
Hello house, I expect the code snippet above to return:
 Wayne, John, Samson, Mike, Seun, 
However, what I get is:
 Wayne, John, Samson, 
Please, what is going on under the hood ?

I know it makes more sense to append i to j on line 5, but I was wondering why the a.pop() method isn't working as expected
Re: My Python Programming Diary by monikulapo: 2:40am On Oct 14, 2021
Gentleman001:

Use for I in range of a.. that should solve the issue
You cannot find the range of a list.
The problem has been solved, and I also provided an explanation for the error.
Next time, to prevent derailing this thread please ensure you test your solutions before suggesting them.

1 Like

Re: My Python Programming Diary by monikulapo: 7:16pm On Oct 14, 2021
https://www.codewars.com/kata/576757b1df89ecf5bd00073b
Build Tower by the following given argument: number of floors (integer and always greater than 0). Tower block is represented as *,
Return a list. For example, a tower of 3 floors looks like the result below
[
' * ',
' *** ',
'*****'
]
and a tower of 6 floors looks like the result below
[
' * ',
' *** ',
' ***** ',
' ******* ',
' ********* ',
'***********'
]
My initial solution:
def tower_builder(n_floors):
tower = []
space = (n_floors * 2) - 1
for i in range(n_floors):
sign = '*' * ((i * 2) + 1)
floor = sign.center(space)
tower.append(floor)
return tower
Played around with list comprehension:
def tower_builder(n_floors):
space = (n_floors * 2) - 1
return [('x' * ((i * 2) + 1)).center(space) for i in range(n_floors)]

Areas for improvement:
Test both scripts to see if list comprehension is faster
Re: My Python Programming Diary by monikulapo: 10:09pm On Oct 15, 2021
Given an array of integers. Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers.
If the input array is empty or null, return an empty array. For input [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15], you should return [10, -65].

My initial Solution:
def count_positives_sum_negatives(arr):
if len(arr) == 0:
return arr

sum = 0
count = 0
for i in arr:
if i > 0:
count += 1
if i < 0:
sum += i

return [count, sum]
Played around with sets, and return statement/expression:
def count_positives_sum_negatives(arr):
total = sum(i for i in arr if i < 0)
count = sum(1 for i in arr if i > 0)
return [count, total] if len(arr) else []

Areas for improvement:
Find the fastest solution
Re: My Python Programming Diary by monikulapo: 4:06pm On Oct 22, 2021
The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:
max_sequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]) should return 6 '[4, -1, 2, 1]'. https://www.codewars.com/kata/54521e9ec8e60bc4de000d6c/train/python

My initial Solution:
def max_sequence(arr):
totalmax = 0
currentmax = 0

for i in arr:
currentmax += i

if totalmax < currentmax:
totalmax = currentmax
if currentmax < 0:
currentmax = 0

return totalmax


Areas for improvement:
Modify script to also return the corresponding array
Re: My Python Programming Diary by LikeAking: 1:58am On Oct 23, 2021
Nice.
Re: My Python Programming Diary by monikulapo: 9:50pm On Oct 29, 2021
https://www.codewars.com/kata/525f50e3b73515a6db000b83/train/python
Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.
create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) # => returns "(123) 456-7890"

Solution:
def create_phone_number(n):
new = [str(i) for i in arr]
bracket = '(' + ''.join(new[:3]) + ')'
mid = ' ' + ''.join(new[3:6]) + '-'
end = ''.join(new[6:])
return bracket + mid + end


Alternate Solution:
This is taking advantage of the fact that the asterick '*' can be used to unpack elements of an iterable as arguments in a function call.
def create_phone_number(n):
return '({}{}{}) {}{}{}-{}{}{}{}'.format(*n)
Re: My Python Programming Diary by LikeAking: 9:20pm On Oct 30, 2021
Nice one.

No forget to hide ur python from Lala.
Re: My Python Programming Diary by monikulapo: 7:16pm On Nov 18, 2021
LikeAking:
Nice one.

No forget to hide ur python from Lala.
cheesy cheesy cheesy
Re: My Python Programming Diary by monikulapo: 7:19pm On Nov 18, 2021
https://www.codewars.com/kata/52c31f8e6605bcc646000082/train/python
Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple like so: (index1, index2). twoSum [1, 2, 3] 4 === (0, 2)

My initial solution:
def two_sum(numbers, target):
indexi = 0
for i in numbers:
indexi += 1
indexj = 0
for j in numbers:
indexj += 1
if i + j == target and indexi != indexj:
indexes = (indexi - 1, indexj - 1)
break
else:
indexes = None
else:
continue
break
return indexes
Re: My Python Programming Diary by Nobody: 8:15pm On Nov 18, 2021
Don’t know if I’m the only one that finds python painful to read sad
Re: My Python Programming Diary by monikulapo: 8:19pm On Nov 18, 2021
Rgade:
Don’t know if I’m the only one that finds python painful to read sad

Why’s that ?
Re: My Python Programming Diary by Nobody: 8:27pm On Nov 18, 2021
monikulapo:


Why’s that ?
No curly braces or semi colons makes it really hard to make out the structure of the code.
So your eyes are doing all the organizing.
Re: My Python Programming Diary by dodgelord: 10:24pm On Jun 29, 2022
I hate python

(1) (Reply)

E-commerce Site Needed / Tutorials On C++ / Learn Cakephp, Php/mysql For Free

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 33
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.