How to create a range of numbers with a given increment - python

I want to know whether there is an equivalent statement in lists to do the following. In MATLAB I would do the following
fid = fopen('inc.txt','w')
init =1;inc = 5; final=51;
a = init:inc:final
l = length(a)
for i = 1:l
fprintf(fid,'%d\n',a(i));
end
fclose(fid);
In short I have an initial value, a final value and an increment. I need to create an array (I read it is equivalent to lists in python) and print to a file.

In Python, range(start, stop + 1, step) can be used like Matlab's start:step:stop command. Unlike Matlab's functionality, however, range only works when start, step, and stop are all integers. If you want a parallel function that works with floating-point values, try the arange command from numpy:
import numpy as np
with open('numbers.txt', 'w') as handle:
for n in np.arange(1, 5, 0.1):
handle.write('{}\n'.format(n))
Keep in mind that, unlike Matlab, range and np.arange both expect their arguments in the order start, stop, then step. Also keep in mind that, unlike the Matlab syntax, range and np.arange both stop as soon as the current value is greater than or equal to the stop value.
http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html

You can easily create a function for this. The first three arguments of the function will be the range parameters as integers and the last, fourth argument will be the filename, as a string:
def range_to_file(init, final, inc, fname):
with open(fname, 'w') as f:
f.write('\n'.join(str(i) for i in range(init, final, inc)))
Now you have to call it, with your custom values:
range_to_file(1, 51, 5, 'inc.txt')
So your output will be (in the fname file):
1
6
11
16
21
26
31
36
41
46
NOTE: in Python 2.x a range() returns a list, in Python 3.x a range() returns an immutable sequence iterator, and if you want to get a list you have to write list(range())

test.py contains :
#!/bin/env python
f = open("test.txt","wb")
for i in range(1,50,5):
f.write("%d\n"%i)
f.close()
You can execute
python test.py
file test.txt would look like this :
1
6
11
16
21
26
31
36
41
46

I think your looking for something like this:
nums = range(10) #or any list, i.e. [0, 1, 2, 3...]
number_string = ''.join([str(x) for x in nums])
The [str(x) for x in nums] syntax is called a list comprehension. It allows you to build a list on the fly. '\n'.join(list) serves to take a list of strings and concatenate them together. str(x) is a type cast: it converts an integer to a string.
Alternatively, with a simple for loop:
number_string = ''
for num in nums:
number_string += str(num)
The key is that you cast the value to a string before concatenation.

I think that the original poster wanted 51 to show up in the list, as well.
The Python syntax for this is a little awkward, because you need to provide for range (or xrange or arange) an upper-limit argument that is one increment beyond your actual desired upper limit. An easy solution is the following:
init = 1
final = 51
inc = 5
with open('inc.txt','w') as myfile:
for nn in xrange(init, final+inc, inc):
myfile.write('%d\n'%nn)

open('inc.txt','w').write("\n".join(str(i) for i in range(init,final,inc)))

Related

Python for iteration with previous variable

the function is meant to do the follow, "to get the n (non-negative integer) copies of the first 2 characters of a given string. Return the n copies of the whole string if the length is less than 2."
Can anyone tell me what does the substr do in line 12?
I get how it works previously on line 8 (when string is larger than 2), but it looses me on how it works on line 12, where the string is lower than 2.
def substring_copy(str, n):
"""
Method 2
"""
f_lenght = 2
if f_lenght > len(str): # If strings length is larger than 2
f_lenght = len(str) # Length of string will be len(str)
substr = str[:f_lenght] # substr = str[:2] (slice 0 y 1)
# If length is shorter than 2
result = ""
for i in range(n):
result = result + substr
return result
print ("\nMethod 2:")
print(substring_copy('abcdef', 2))
print(substring_copy('p', 3));
If the length of p is 1, then isn't it a case that substr isn't that important and the for loop will run 3 (thanks to 3* in the last line of code)?
Thanks in advance!
I think I got it, substr is important for if there are more than 2 characters in the string. When there are less than 2, substr could have a value of 200; the p string would still be just one p and that would concatenate n times (3 times in this example).
So as you inferred substr is just the substring of length 2 (or less) from the original, which can be the input itself if it's already 2 or less.
It's your "duplication target", basically.
Though I do want to point out that the entire thing is a rather bad style, it is over-complicated and doesn't make good use of python:
str is the python string type (which also acts as a conversion function), it's a builtin, shadowing builtin is a bad idea and str is a common builtin, naming a variable str is terrible style, sometimes it's justifiable, but not here
python slicing is "bounded" to what it's slicing, so e.g. "ab"[:5] will return "ab", unlike regular indexing it does not care that the input is too short, this means the entire mess with f_lenght is unnecessary, you can just
substr = s[:2]
Python strings have an override for multiplication, str * n repeats the string n times, this also works with lists (though that is more risky because of mutability and reference semantics)
So the entire function could just be:
def substring_copy(s, n):
return s[:2] * n
The prompt is also not great because of the ambiguity of the word "character", but I guess we can let that slide

Longest sequence of equal numbers in python

I tried to generate the longest sequence of equal numbers in python, but it doesn't work
def lista_egale(lst1 = input("numbers go here ")):
l = 0
lst1 = []
maxi = -9999
prev_one = None
lmax = -9999
for current in lst1:
if prev_one == current:
l += 1
else:
l = 1
if l > lmax:
lmax = l
maxi = current
prev_one = current
print("longest sequence is ", lmax, " and ", maxi)
lista_egale()
Input:
1 2 2 2 2 3 4 5 6 2 2 2
Expected Output:
longest sequence is 4 and 2
I was going to write up the same concern about your default argument, but that would at least work correctly the first time it is called. This function does not. Everyone jumped on that common problem, and failed to notice the next line. Let's look another look at this abridged version of your code:
irrelevant = input("numbers go here ")
def lista_egale(lst1 = irrelevant):
# while it is true that your default argument is bad,
# that doesn't matter because of this next line:
lst1 = []
for current in lst1:
# unreachable code
pass
To clarify, since your reply indicates this is not clear enough, it doesn't matter what value was passed in to lst1 if you immediately overwrite it with an empty list.
(for others reading this:) Separating out what I labeled "irrelevant" is not quite identical, but I'm trying to point out that the input was overwritten.
I don't think this function should take user input or have a default argument at all. Let it be a function with one job, and just pass it the data to work on. User input can be collected elsewhere.
Based on Barmar's note, and the principle of using only unmutable default values, your code should look something more like this:
def lista_egale(inp1 = None):
if not inp1:
inp1 = input("numbers go here ")
# optionally do some error checking for nonnumerical characters here
lst1 = [int(i) for i in inp1.split(" ")]
# rest of your code here
lista_egale()
Basically, input returns a string value, and you need to convert it into a list of integers first before you start working on it.
You can swap out the list comprehension for map(int, inp1.split(" ")) as it will do the same (but you can't iterate through a map more than once unless you wrap it in a list() function first).
Secondly, avoid setting mutable default arguments as (in short) can lead to weird results when rerunning the same function multiple times.

Remove numbers from list which contains some particular numbers in python

Given List:
l = [1,32,523,336,13525]
I am having a number 23 as an output of some particular function.
Now,
I want to remove all the numbers from list which contains either 2 or 3 or both 2 and 3.
Output should be:[1]
I want to write some cool one liner code.
Please help!
My approach was :
1.) Convert list of int into list of string.
2.) then use for loop to check for either character 2 or character 3 like this:
A=[x for x in l if "2" not in x] (not sure for how to include 3 also in this line)
3.) Convert A list into integer list using :
B= [int(numeric_string) for numeric_string in A]
This process is quiet tedious as it involves conversion to string of the number 23 as well as all the numbers of list.I want to do in integer list straight away.
You could convert the numbers to sets of characters:
>>> values = [1, 32, 523, 336, 13525]
>>> number = 23
>>> [value for value in values
... if set(str(number)).isdisjoint(set(str(value)))]
[1]
You're looking for the filter function. Say you have a list of ints and you want the odd ones only:
def is_odd(val):
return val % 2 == 1
filter(is_odd, range(100))
or a list comprehension
[x for x in range(100) if x % 2 == 1]
The list comprehension in particular is perfectly Pythonic. All you need now is a function that returns a boolean for your particular needs.

Displaying A List to a Certain Decimal - Python 3.x

I'm having trouble displaying my list in a money format ($0000.00)
priceList = [1,2,3,4,5,6,7,8,9,10]
for i in range (10):
priceList[i] = random.uniform(1,1000)
print (priceList)
If I try
print ('%.02d' %(priceList))
Python returns
TypeError: %d format: a number is required, not list
You cannot print a list this way, you need to print each list item. A list comprehension works well here:
[print('%.02f' % i) for i in priceList]
You need to put the printing inside your for loop:
priceList = [1,2,3,4,5,6,7,8,9,10]
for i in range(10):
priceList[i] = random.uniform(1,1000)
print("${:07.02f}".format(priceList[i]))
In 07.02f, 07 says to make sure that the string is at least 7 characters long. The 0 is there because if the string is less than 7 characters, that is the character to be used to make it 7 characters. 02 before the f means that there should be at least two characters after the decimal point. The 0 is there so that if there are fewer than two characters, it will be used to fill it in.
Because you are trying to do that operation over a list. You need to do it on each element in your list. Try this:
Also, I think you want to use %.02f and not %.02d
print(' '.join('%.02f' % (x) for x in priceList))
Output:
728.08 289.73 117.96 29.70 562.40 255.97 213.55 235.08 436.10 654.54
If you want it just as a list, you can simply do this only:
print(['%.02f' % x for x in priceList])
You should be using proper Python 3 format strings. You can do something like this:
import random
priceList = [1,2,3,4,5,6,7,8,9,10]
for i in range (10):
priceList[i] = random.uniform(1,1000)
moneyList = list(map(lambda x: "${:07.02f}".format(x), priceList))
print(moneyList) # => output:
"""
['$294.90', '$121.71', '$590.29', '$45.52', '$319.40', '$189.03', '$594.63', '$135.24', '$645.56', '$954.57']
"""

Adding Numbers to a list using variable

I'm doing a programming question and I need a bit of help.
I have a variable where I type in a number and then that number and all the numbers before it go in a list.
For example:
I pick 10 and put it in a variable
And all numbers from 1 - 10 are put in a list
Here is my code:
Top_Num = int(input('Top Number'))
Nums = []
Now lets say I chose 10 for the Top_Num, how do I put 10 numbers into the list?
Thanks.
You can actually use Pythons built in range(int) function to do exactly this.
If you want the array to start at 1 and include the input number, you can use
Nums = list(range(1, Top_Num + 1))
The first argument of 1 indicates the start value of the array, and the second argument Top_Num + 1 is the number that the array goes up to (exclusive).
Nums = [num for num in range(1, Top_Num + 1)]
It uses list comprehensions too, which is (kinda) an important concept in python.

Categories