Accumulate monotonically increasing sequence list to a linear list - python-2.7

Hi I'm new to python and in programming in general.
I have a monotonic list, ex. L = [1,2,3,4,0,1,2,3,4,5,0,1,2,3,4,0,1...]
And whenever the series reaches 0, I would like to take the previous value and add to the remaining of the list so the list becomes linear.
L_sequence = [1,2,3,4,0,1,2,3,4,5,0,1,2,3,4,0,1...]
L_linear = [1,2,3,4,4,5,6,7,8,9,9,10,11,12,13,13,14...]
I know a nasty way to do this, but if any of you have a good solution, you are welcome to share.

I think it should solve your problem:
l = [1,2,3,4,0,1,2,3,4,5,0,1,2,3,4,0,1]
x = []
helperOne = 0
helperTwo = 0
goForIt = False
for i in l:
if i == 0:
goForIt = True
helperTwo = helperOne + helperTwo
if goForIt==True:
t = helperTwo + i
x.append(t)
else:
x.append(i)
helperOne = i
print x
Output:
[1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 9, 10, 11, 12, 13, 13, 14]

Related

Need help on how to let user input a list of numbers

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = int(input("Please enter a number: "))
c = []
for i in a:
if i < b:
c.append(i)
print(c)
Need help I want to allow the user to input their own list of numbers instead of the pre written list in a, i'm sorry if my post is confusing i'm new to coding and this is my first time using stack overflow.
the code is written in Python
Please Use Loop For Multiple Inputs Of Data From User
loop:
input
You Have To Try Following Code
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
c = []
for i in a:
b = int(input("Please enter a number: "))
c.append(b)
print(c)

Finding duplicates in a list/file. [Groovy/Java]

I have an input file where each line is a special record.
I would gladly work on the file level but might be a more convenient way to transfer the file into a list. (each object in the list = each row in the file)
In the input file, there can be several duplicate rows.
The goal: Split the given file/list into unique records and duplicate records, i.e., Records which are present multiple times, keep one occurrence and other duplicate parts store in a new list
I found an easy way how to remove duplicates but never found a way how to store them
File inputFile = new File("....")
inputFile.eachLine { inputList.add(it) } //fill the list
List inputList = [1,1,3,3,1,2,2,3,4,1,5,6,7,7,8,9,8,10]
inputList = inputList.unique() // remove duplicates
println inputList
// inputList = [1, 3, 2, 4, 5, 6, 7, 8, 9, 10]
The output should look like: Two lists/files with removed duplicates and duplicates itself
inputList = [1,3,2,4,5,6,7,8,9,10] //only one ocurance of each line
listOfDuplicates = [1,1,1,3,3,2,7,8] //duplicates removed from original list
The output does not need to correspond with the initial order of items.
Thank you for help, Matt
You could simply iterate over the list yourself:
def inputList = [1,1,3,3,1,2,2,3,4,1,5,6,7,7,8,9,8,10]
def uniques = []
def duplicates = []
inputList.each { uniques.contains(it) ? duplicates << it : uniques << it }
assert inputList.size() == uniques.size() + duplicates.size()
assert uniques == [1,3,2,4,5,6,7,8,9,10] //only one ocurance of each line
assert duplicates == [1,3,1,2,3,1,7,8] //duplicates removed from original list
inputList = uniques // if desired
There are many ways to do this,following is the simplest way
def list = [1,1,3,3,1,2,2,3,4,1,5,6,7,7,8,9,8,10]
def unique=[]
def duplicates=[]
list.each {
if(unique.contains(it))
duplicates.add(it)
else
unique.add(it)
}
println list //[1, 1, 3, 3, 1, 2, 2, 3, 4, 1, 5, 6, 7, 7, 8, 9, 8, 10]
println unique //[1, 3, 2, 4, 5, 6, 7, 8, 9, 10]
println duplicates //[1, 3, 1, 2, 3, 1, 7, 8]
Hope this will helps you
Something very straight-forward:
List inputList = [1,1,3,3,1,2,2,3,4,1,5,6,7,7,8,9,8,10]
def uniques = [], duplicates = []
Iterator iter = inputList.iterator()
iter.each{
iter.remove()
inputList.contains( it ) ? ( duplicates << it ) : ( uniques << it )
}
assert [2, 3, 4, 1, 5, 6, 7, 9, 8, 10] == uniques
assert [1,1,3,3,1,2,7,8] == duplicates
If order of duplicates isn't important:
def list = [1,1,3,3,1,2,2,3,4,1,5,6,7,7,8,9,8,10]
def (unique, dups) = list.groupBy().values()*.with{ [it[0..0], tail()] }.transpose()*.sum()
assert unique == [1,3,2,4,5,6,7,8,9,10]
assert dups == [1,1,1,3,3,2,7,8]
This code should solve the problem
List listOfDuplicates = inputList.clone()
listOfDuplicates.removeAll{
listOfDuplicates.count(it) == 1
}
The more the merrier:
groovy:000> list.groupBy().values()*.tail().flatten()
===> [1, 1, 1, 3, 3, 2, 7, 8]
Group by identity (this is basically a "frequencies" function).
Take just the values
Clip the first element
Combine the lists

Best way to shift a list in Python?

I have a list of numbers, let's say :
my_list = [2, 4, 3, 8, 1, 1]
From this list, I want to obtain a new list. This list would start with the maximum value until the end, and I want the first part (from the beginning until just before the maximum) to be added, like this :
my_new_list = [8, 1, 1, 2, 4, 3]
(basically it corresponds to a horizontal graph shift...)
Is there a simple way to do so ? :)
Apply as many as you want,
To the left:
my_list.append(my_list.pop(0))
To the right:
my_list.insert(0, my_list.pop())
How about something like this:
max_idx = my_list.index(max(my_list))
my_new_list = my_list[max_idx:] + my_list[0:max_idx]
Alternatively you can do something like the following,
def shift(l,n):
return itertools.islice(itertools.cycle(l),n,n+len(l))
my_list = [2, 4, 3, 8, 1, 1]
list(shift(my_list, 3))
Elaborating on Yasc's solution for moving the order of the list values, here's a way to shift the list to start with the maximum value:
# Find the max value:
max_value = max(my_list)
# Move the last value from the end to the beginning,
# until the max value is the first value:
while my_list[0] != max_value:
my_list.insert(0, my_list.pop())

Plotting graph of items in list into corresponding category using PyPlot in Python 2.7

I have a list with 10 records, and each record has one or more elements with 3 categories like below:
list = [('0.4', 2, 'doc4.txt'),('0.04', 13, 'doc4.txt'), ('0.5', 4, 'doc4.txt')]
[('0.5', 6, 'doc3.txt'),('0.04', 13, 'doc3.txt'), ('0.5', 4, 'doc3.txt')]
[('0.6', 8, 'doc2.txt')]
[('0.4', 2, 'doc5.txt'), ('1.0', 7, 'doc5.txt')]
[('0.2', 2, 'doc6.txt'), ('0.4', 2, 'doc6.txt'),('0.8', 2, 'doc6.txt'), ('0.34', 5, 'doc6.txt'),('0.76', 4, 'doc6.txt'), ('0.5', 3, 'doc6.txt')]
[('0.3', 7, 'doc9.txt')]
[('0.1', 8, 'doc12.txt')]
[('0.3', 9, 'doc11.txt'),('1.0', 8, 'doc11.txt')]
[('0.9', 7, 'doc22.txt')]
[('0.3', 7, 'doc24.txt')]
You many notice the third category of every record has the same text for each record. There are 10 categories as the list consists of 10 records.
According to the structure of the list:
For example, [('0.6', 8, 'doc2.txt')]
First element, '0.6' represents X-axis value in the range of [0.1 -> 1.0]
Second element of an integer represents Y-axis value in graph
Third element, 'doc2.txt' represents the Category name in graph
The list should be plotted as the image below,
I've been trying with several approaches, but still couldn't figure that out
>>> plt.scatter(*zip(*list))
>>> plt.xlabel('X-Axis')
>>> plt.ylabel('Y-Axis')
>>> plt.show()
I think you can just keep the list as it is and iterate over it. You'd then produce a scatter plot for each sublist in the outer list, as the items from the sublist should share the same marker, color and legend label.
import matplotlib.pyplot as plt
#don't call a variable "list" or "print" or any other python command's name
liste=[[('0.4', 2, 'doc4.txt'),('0.04', 13, 'doc4.txt'), ('0.5', 4, 'doc4.txt')],
[('0.5', 6, 'doc3.txt'),('0.04', 13, 'doc3.txt'), ('0.5', 4, 'doc3.txt')],
[('0.6', 8, 'doc2.txt')],
[('0.4', 2, 'doc5.txt'), ('1.0', 7, 'doc5.txt')],
[('0.2', 2, 'doc6.txt'), ('0.4', 2, 'doc6.txt'),('0.8', 2, 'doc6.txt'), ('0.34', 5, 'doc6.txt'),('0.76', 4, 'doc6.txt'), ('0.5', 3, 'doc6.txt')],
[('0.3', 7, 'doc9.txt')],
[('0.1', 8, 'doc12.txt')],
[('0.3', 9, 'doc11.txt'),('1.0', 8, 'doc11.txt')],
[('0.9', 7, 'doc22.txt')],
[('0.3', 7, 'doc24.txt')]]
markers=[ur"$\u25A1$", ur"$\u25A0$", ur"$\u25B2$", ur"$\u25E9$"]
colors= ["k", "crimson", "#112b77"]
fig, ax = plt.subplots()
for i, l in enumerate(liste):
x,y,cat = zip(*l)
ax.scatter(list(map(float, x)),y, s=64,c=colors[(i//4)%3],
marker=markers[i%4], label=cat[0])
ax.legend(bbox_to_anchor=(1.01,1), borderaxespad=0)
plt.subplots_adjust(left=0.1,right=0.8)
plt.show()
There are multiple issues. You assignment of list makes no sense (presumably you forgot some parentheses). Also, you really shouldn't reuse built-in names like "list". You should not represent floats as strings (your x coordinates). You cannot simply unpack a list into plt.scatter and hope that magically all of these issues work themselves out.
Below some code how to properly pass your data to scatter (I use plot instead of scatter as you can pass plot proper colour names).
import numpy as np
import matplotlib.pyplot as plt
# 'list' is a bad name for a variable as it overwrites the list() built-in function
# -> rename to data
data = [
[('0.4', 2, 'doc4.txt'),('0.04', 13, 'doc4.txt'), ('0.5', 4, 'doc4.txt')],
[('0.5', 6, 'doc3.txt'),('0.04', 13, 'doc3.txt'), ('0.5', 4, 'doc3.txt')],
[('0.6', 8, 'doc2.txt')],
[('0.4', 2, 'doc5.txt'), ('1.0', 7, 'doc5.txt')],
[('0.2', 2, 'doc6.txt'), ('0.4', 2, 'doc6.txt'),('0.8', 2, 'doc6.txt'), ('0.34', 5, 'doc6.txt'),('0.76', 4, 'doc6.txt'), ('0.5', 3, 'doc6.txt')],
[('0.3', 7, 'doc9.txt')],
[('0.1', 8, 'doc12.txt')],
[('0.3', 9, 'doc11.txt'),('1.0', 8, 'doc11.txt')],
[('0.9', 7, 'doc22.txt')],
[('0.3', 7, 'doc24.txt')]
]
# flatten nested list
flat = [item for sublist in data for item in sublist]
# convert strings to numbers
numeric = [(float(x), y, label) for (x, y, label) in flat]
# create a dictionary that maps a label to a set of x,y coordinates
data = dict()
for (x, y, label) in numeric:
if label in data:
data[label].append((x,y))
else:
data[label] = [(x,y)]
# initialise figure
fig, ax = plt.subplots(1,1)
colors = ['blue', 'red', 'yellow', 'green', 'orange', 'brown', 'violet', 'magenta', 'white', 'black']
# populate figure
for color, (label, xy) in zip(colors, data.iteritems()):
x, y = np.array(xy).T
ax.plot(x, y, 'o', label=label, color=color)
ax.set_xlim(0, 1.1)
ax.set_ylim(0, 16)
ax.legend(numpoints=1)
plt.show()

creating list of lists alimented with data from database gives empty list

I'm trying to plot a graph that shows the average call duration every day each minute for 7 days in the same plot, now I'm defining the function that will give me the data asked according to conditions which will be plotted but I'm always getting a list of empty lists.can any one help me tof ind the bug? (acc is just an example of data from the global database)
This is the function:
import time
import calendar
from datetime import datetime
from itertools import repeat
acc=[{u'switch_id': 3, u'hangup_cause_id': 7, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 1), u'duration': 32}, {u'switch_id': 3, u'hangup_cause_id': 10, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 8), u'duration': 20}, {u'switch_id': 3, u'hangup_cause_id': 10, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 10), u'duration': 17}]
t = datetime.now()
y = t.year
m = t.month
d = t.day
donnees=[]
for k in range(7):
try:
m = t.month
data=[]
liste=[]
liste_time=[]
for i in acc:
if (i["start_uepoch"].year == y and i["start_uepoch"].month == m and i["start_uepoch"].day == d-k):
liste.append([i["start_uepoch"],i["duration"]])
for q in range(24):
for mnt in range(60):
liste2=[]
ACD=0
somme_duration=0
n=0
for p in liste:
if (p[0].hour==q and p[0].minute == mnt):
liste2.append(p[1])
temps=p[0]
if len(liste2)!=0:
for j in liste2:
somme_duration+=j
n+=1
ACD=round((float(somme_duration)/n)*100)/100
liste_time.append(calendar.timegm(temps.timetuple()))
data.append(ACD)
else:
liste_time.append(calendar.timegm(temps.timetuple()))
data.append(0)
except:
pass
donnees.append(data)
print donnees
This is due to your try / except condition, if you remove it by settings temps = None after your loop it solves you issue :
import time
import calendar
from datetime import datetime
from itertools import repeat
acc=[{u'switch_id': 3, u'hangup_cause_id': 7, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 1), u'duration': 32}, {u'switch_id': 3, u'hangup_cause_id': 10, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 8), u'duration': 20}, {u'switch_id': 3, u'hangup_cause_id': 10, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 10), u'duration': 17}]
t = datetime.now()
y = t.year
m = t.month
d = t.day
donnees=[]
for k in range(7):
m = t.month
data=[]
liste=[]
liste_time=[]
for i in acc:
if (i["start_uepoch"].year == y and i["start_uepoch"].month == m and i["start_uepoch"].day == d-k):
liste.append([i["start_uepoch"],i["duration"]])
for q in range(24):
for mnt in range(60):
temps = None
liste2=[]
ACD=0
somme_duration=0
n=0
for p in liste:
if (p[0].hour==q and p[0].minute == mnt):
liste2.append(p[1])
temps=p[0]
if temps:
if len(liste2)!=0:
for j in liste2:
somme_duration+=j
n+=1
ACD=round((float(somme_duration)/n)*100)/100
liste_time.append(calendar.timegm(temps.timetuple()))
data.append(ACD)
else:
liste_time.append(calendar.timegm(temps.timetuple()))
data.append(0)
donnees.append(data)
print donnees