Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #7373 > unrolled thread

Unsupported operand type(s) for +: 'float' and 'tuple'

Started byFrancesc Segura <frsegrev@gmail.com>
First post2011-06-10 03:30 -0700
Last post2011-06-10 21:44 -0400
Articles 7 — 5 participants

Back to article view | Back to comp.lang.python


Contents

  Unsupported operand type(s) for +: 'float' and 'tuple' Francesc Segura <frsegrev@gmail.com> - 2011-06-10 03:30 -0700
    Re: Unsupported operand type(s) for +: 'float' and 'tuple' Tim Chase <python.list@tim.thechases.com> - 2011-06-10 06:38 -0500
      Re: Unsupported operand type(s) for +: 'float' and 'tuple' Francesc Segura <frsegrev@gmail.com> - 2011-06-10 05:12 -0700
    Re: Unsupported operand type(s) for +: 'float' and 'tuple' "Gabriel Genellina" <gagsl-py2@yahoo.com.ar> - 2011-06-10 22:02 -0300
    Re: Unsupported operand type(s) for +: 'float' and 'tuple' "Gabriel Genellina" <gagsl-py2@yahoo.com.ar> - 2011-06-10 22:02 -0300
      Re: Unsupported operand type(s) for +: 'float' and 'tuple' Thomas Rachel <nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915@spamschutz.glglgl.de> - 2011-06-12 19:23 +0200
    Re: Unsupported operand type(s) for +: 'float' and 'tuple' Terry Reedy <tjreedy@udel.edu> - 2011-06-10 21:44 -0400

#7373 — Unsupported operand type(s) for +: 'float' and 'tuple'

FromFrancesc Segura <frsegrev@gmail.com>
Date2011-06-10 03:30 -0700
SubjectUnsupported operand type(s) for +: 'float' and 'tuple'
Message-ID<af752c9e-e949-4bec-a127-05a3fe500cbf@y30g2000yqb.googlegroups.com>
Hello all, I'm new to this and I'm having problems on summing two
values at python.

I get the following error:

Traceback (most recent call last):
  File "C:\edge-bc (2).py", line 168, in <module>
    if (costGG <= cost + T0):
TypeError: unsupported operand type(s) for +: 'float' and 'tuple'

I'm working with networkx and my program is this one:


import networkx as NX
import pylab as P
from math import exp, log
import random
try:
    import matplotlib.pyplot as plt
except:
    raise

##N=27
N=30
ITERATIONS = 60
T0 = 0.5
RO = 0.99
NK = 20

def costG(G):

    bc = NX.edge_betweenness_centrality(G,normalized=True)
    edges = NX.edges(G)

    for i in range(len(edges)):
        total = 0
        cost = 0
        factor = 1

        liedges = list(edges[i])
        linode1 = list(liedges[0])
        linode2 = list(liedges[1])

        distance = (((linode2[0]-linode1[0])%N)^2)+(((linode2[1]-
linode1[1])%N)^2)

        edgecentrality = bc[edges[i]]

        factor = (distance-19790)*(-0.000055586)

        cost = distance*edgecentrality*factor

        total = total + cost

    return(total)

def avedistance(G):




    return (AvgDist)

def costGeasy(G):
    bc = NX.edge_betweenness_centrality(G,normalized=True)
    total = 0
    for i in range(len(bc)):
        total=total+bc.values()[i]

    return (total)


G = NX.grid_2d_graph(N,N,True)

for i in range(N):
    for j in range(N):
        G.add_edge((i,j),((i+1) % N ,(j+1) % N))
        G.add_edge((i,j),((i-1) % N ,(j+1) % N))


NODES=NX.number_of_nodes(G)
nod=NX.nodes(G)
EDGES=NX.number_of_edges(G)
edg=NX.edges(G)

pos={}
for i in range(NODES):
    pos[nod[i]]=(nod[i][0]/(N*1.0),nod[i][1]/(N*1.0))

NX.draw(G,pos,node_color='r',node_size=20,with_labels=False,width=1)
plt.title("Inicial graph, Toroidal 27x27, degree 8")
plt.savefig("initial_grid_malla.png")
plt.show()

pos=NX.spring_layout(G,iterations=100)
NX.draw(G,pos,node_color='r',node_size=20,with_labels=False,width=1)
plt.title("Inicial graph, Toroidal 27x27, degree 8")
plt.savefig("initial_grid_tor.png")
plt.show()

initGr = G
best_graph = G
best_cost = costG(G)
average_distance = avedistance(G)
initCost = best_cost
initGHist = NX.degree_histogram(G)

##print NX.info(initGr)
##print 'Diameter =  %f ' % (NX.diameter(G))
##print 'Avg Clust Coeff. NetworkX =  %-6.4f ' %
(NX.average_clustering(G))
##print 'Avg Dist. NetworkX =  %-6.4f ' % (average_distance)
##print 'Distribucio de Graus'
##print initGHist
##print 'Cost inicial'
##print initCost

T0 = initCost*0,1

for y in range(NK):
    for x in range(ITERATIONS):
        cost = costG(G)
        if (cost < (best_cost)):
            best_graph = G
            best_cost = cost
        GG = G
        u = random.randint(0,NODES-1)
        while GG.degree(nod[u]) <= 1:
                u = random.randint(0,NODES-1)
        v = random.randint(0,GG.degree(nod[u])-1)
        GG.remove_edge(nod[u],GG[nod[u]].keys()[v])
        a = random.randint(0,NODES-1)
        b = random.randint(0,NODES-1)
        adj=G.adjacency_list()
        while ((nod[b] in adj[a]) or (b == a)):
            a = random.randint(0,NODES-1)
            b = random.randint(0,NODES-1)
        GG.add_edge(nod[a],nod[b])
        while (NX.is_connected(GG) == 0):
            GG = G
            u = random.randint(0,NODES-1)
            while GG.degree(nod[u]) <= 1:
                u = random.randint(0,NODES-1)
            v = random.randint(0,GG.degree(nod[u])-1)
            GG.remove_edge(nod[u],GG[nod[u]].keys()[v])
            a = random.randint(0,NODES-1)
            b = random.randint(0,NODES-1)
            adj=GG.adjacency_list()
            while ((nod[b] in adj[a]) or (b == a)):
                a = random.randint(0,NODES-1)
                b = random.randint(0,NODES-1)
            GG.add_edge(nod[a],nod[b])

        costGG = costG(GG)
        if (costGG <= cost):
            G = GG
        else:
            if (costGG <= cost + T0):
                G = GG

    T0 = T0 * RO
    print 'IT %d' % y
    print 'BEST %f ' % best_cost


best_graph = G
print NX.info(best_graph)
print 'Diameter =  %f ' % (NX.diameter(best_graph))
print 'Avg Clust Coeff. NetworkX =  %-6.4f ' %
(NX.average_clustering(best_graph))
average_distance = avedistance(best_graph)
print 'Avg Dist. NetworkX =  %-6.4f ' % (average_distance)
print 'Distribucio de Graus'
print NX.degree_histogram(best_graph)
print 'Millor Cost'
print best_cost

NX.write_edgelist(best_graph,'optimal-graph.dat')

pos={}
for i in range(NODES):
    pos[nod[i]]=(nod[i][0]/(N*1.0),nod[i][1]/(N*1.0))


NX.draw(best_graph,pos,node_color='r',node_size=20,with_labels=False,width=1)
plt.title("Final graph, Toroidal 27x27, degree 8")
plt.savefig("final_grid_malla.png")
plt.show()

pos=NX.spring_layout(G,iterations=100)
NX.draw(best_graph,pos,node_color='r',node_size=20,with_labels=False,width=1)
plt.title("Final graph, Toroidal 27x27, degree 8")
plt.savefig("final_grid_tor.png")
plt.show()

[toc] | [next] | [standalone]


#7375

FromTim Chase <python.list@tim.thechases.com>
Date2011-06-10 06:38 -0500
Message-ID<mailman.82.1307705938.11593.python-list@python.org>
In reply to#7373
On 06/10/2011 05:30 AM, Francesc Segura wrote:
> Hello all, I'm new to this and I'm having problems on summing two
> values at python.
>
> I get the following error:
>
> Traceback (most recent call last):
>    File "C:\edge-bc (2).py", line 168, in<module>
>      if (costGG<= cost + T0):
> TypeError: unsupported operand type(s) for +: 'float' and 'tuple'
>
> I'm working with networkx and my program is this one:
...
> T0 = initCost*0,1

Here, you're setting T0 to the tuple "(initCost*0, 1)" == "(0, 
1)".  I think you mean to use a period instead of a comma.

You then try to add that to a float (cost), and Python doesn't 
like that.  I wouldn't either :)

-tkc

[toc] | [prev] | [next] | [standalone]


#7378

FromFrancesc Segura <frsegrev@gmail.com>
Date2011-06-10 05:12 -0700
Message-ID<bd74bb16-8542-444a-b960-ce9d77ca40fe@y30g2000yqb.googlegroups.com>
In reply to#7375
On 10 jun, 13:38, Tim Chase <python.l...@tim.thechases.com> wrote:
> On 06/10/2011 05:30 AM, Francesc Segura wrote:
>
> > Hello all, I'm new to this and I'm having problems on summing two
> > values at python.
>
> > I get the following error:
>
> > Traceback (most recent call last):
> >    File "C:\edge-bc (2).py", line 168, in<module>
> >      if (costGG<= cost + T0):
> > TypeError: unsupported operand type(s) for +: 'float' and 'tuple'
>
> > I'm working with networkx and my program is this one:
> ...
> > T0 = initCost*0,1
>
> Here, you're setting T0 to the tuple "(initCost*0, 1)" == "(0,
> 1)".  I think you mean to use a period instead of a comma.
>
> You then try to add that to a float (cost), and Python doesn't
> like that.  I wouldn't either :)
>
> -tkc

Thanks a lot, I am a noob retard!

[toc] | [prev] | [next] | [standalone]


#7422

From"Gabriel Genellina" <gagsl-py2@yahoo.com.ar>
Date2011-06-10 22:02 -0300
Message-ID<mailman.117.1307753960.11593.python-list@python.org>
In reply to#7373
En Fri, 10 Jun 2011 07:30:28 -0300, Francesc Segura <frsegrev@gmail.com>
escribió:

> Hello all, I'm new to this and I'm having problems on summing two
> values at python.
>
> I get the following error:
>
> Traceback (most recent call last):
>   File "C:\edge-bc (2).py", line 168, in <module>
>     if (costGG <= cost + T0):
> TypeError: unsupported operand type(s) for +: 'float' and 'tuple'

I see Tim Chase already told you about this error. Let me make a few
comments about the rest.

> try:
>     import matplotlib.pyplot as plt
> except:
>     raise

I guess the above try/except was left from some earlier debugging attempt
- such an except clause is useless, just omit it.

> T0 = 0.5
> RO = 0.99

Perhaps those names make sense in your problem at hand, but usually I try
to use more meaningful ones. 0 and O look very similar in some fonts.

>     for i in range(len(edges)):
>         total = 0
>         cost = 0
>         factor = 1
>        liedges = list(edges[i])
>         linode1 = list(liedges[0])
>         linode2 = list(liedges[1])

list(something) creates a new list out of the elements from `something`.
You're just iterating here, so there is no need to duplicate those lists.
In addition, Python is not C: the `for` statement iterates over a
collection, you don't have to iterate over the indices and dereference
each item:

for liedges in edges:
     linode1 = liedges[0]
     linode2 = liedges[1]


>         distance = (((linode2[0]-linode1[0])%N)^2)+(((linode2[1]-
> linode1[1])%N)^2)

That doesn't evaluate what you think it does. ^ is the "bitwise xor"
operator, and I bet you want **, the "power" operator.


>         total = total + cost
>     return(total)

return is not a function but a statement; those () are unnecesary and
confusing.
And I think you want to initialize total=0 *before* entering the loop;
also, initializing cost and factor is unnecesary.

> def costGeasy(G):
>     bc = NX.edge_betweenness_centrality(G,normalized=True)
>     total = 0
>     for i in range(len(bc)):
>         total=total+bc.values()[i]
>
>     return (total)

bc = NX.edge_betweenness_centrality(G,normalized=True)
values = bc.values()
total = sum(values)
return total

==>

return sum(bc.values())


> pos={}
> for i in range(NODES):
>     pos[nod[i]]=(nod[i][0]/(N*1.0),nod[i][1]/(N*1.0))

In Python version 2.x, 1/3 evals to 0, but that's a mistake; it is fixed
in the 3.x version. If you put this line at the top of your script:
   from __future__ import division
then 1/3 returns 0.3333...
When you actually want integer division, use //, like 1//3

So we can rewrite the above as:

   from __future__ import division
...
for node in nod:
     pos[node] = (node[0] / N, node[1] / N)

Another way, not relying on true division:

divisor = float(N)
for node in nod:
     pos[node] = (node[0] / divisor, node[1] / divisor)

or even:

pos = dict((node, (node[0] / divisor, node[1] / divisor)) for node in nod)


> for y in range(NK):
>     for x in range(ITERATIONS):
>         cost = costG(G)
>         if (cost < (best_cost)):
>             best_graph = G
>             best_cost = cost
>         GG = G

Again, I think this doesn't do what you think it does. GG = G means "let's
use the name GG for the object currently known as G". GG is not a "copy"
of G, just a different name for the very same object. Later operations
like GG.remove_edge(...) modify the object - and you'll see the changes in
G, and in best_graph, because those names all refer to the same object.
I think you'll benefit from reading this:
http://effbot.org/zone/python-objects.htm

>         a = random.randint(0,NODES-1)
>         b = random.randint(0,NODES-1)
>         adj=G.adjacency_list()
>         while ((nod[b] in adj[a]) or (b == a)):
>             a = random.randint(0,NODES-1)
>             b = random.randint(0,NODES-1)
>         GG.add_edge(nod[a],nod[b])

As above, I'd avoid using indexes, take two random nodes using
random.sample instead, and avoid adjacency_list():

while True:
     a, b = random.sample(nod, 2)
     if b not in G[a]:
       break
GG.add_edge(a, b)

(mmm, I'm unsure of the adjacency test, I've used networkx some time ago
but I don't have it available right now)

-- 
Gabriel Genellina

[toc] | [prev] | [next] | [standalone]


#7423

From"Gabriel Genellina" <gagsl-py2@yahoo.com.ar>
Date2011-06-10 22:02 -0300
Message-ID<mailman.118.1307754006.11593.python-list@python.org>
In reply to#7373
En Fri, 10 Jun 2011 07:30:28 -0300, Francesc Segura <frsegrev@gmail.com>
escribió:

> Hello all, I'm new to this and I'm having problems on summing two
> values at python.
>
> I get the following error:
>
> Traceback (most recent call last):
>   File "C:\edge-bc (2).py", line 168, in <module>
>     if (costGG <= cost + T0):
> TypeError: unsupported operand type(s) for +: 'float' and 'tuple'

I see Tim Chase already told you about this error. Let me make a few
comments about the rest.

> try:
>     import matplotlib.pyplot as plt
> except:
>     raise

I guess the above try/except was left from some earlier debugging attempt
- such an except clause is useless, just omit it.

> T0 = 0.5
> RO = 0.99

Perhaps those names make sense in your problem at hand, but usually I try
to use more meaningful ones. 0 and O look very similar in some fonts.

>     for i in range(len(edges)):
>         total = 0
>         cost = 0
>         factor = 1
>        liedges = list(edges[i])
>         linode1 = list(liedges[0])
>         linode2 = list(liedges[1])

list(something) creates a new list out of the elements from `something`.
You're just iterating here, so there is no need to duplicate those lists.
In addition, Python is not C: the `for` statement iterates over a
collection, you don't have to iterate over the indices and dereference
each item:

for liedges in edges:
     linode1 = liedges[0]
     linode2 = liedges[1]


>         distance = (((linode2[0]-linode1[0])%N)^2)+(((linode2[1]-
> linode1[1])%N)^2)

That doesn't evaluate what you think it does. ^ is the "bitwise xor"
operator, and I bet you want **, the "power" operator.


>         total = total + cost
>     return(total)

return is not a function but a statement; those () are unnecesary and
confusing.
And I think you want to initialize total=0 *before* entering the loop;
also, initializing cost and factor is unnecesary.

> def costGeasy(G):
>     bc = NX.edge_betweenness_centrality(G,normalized=True)
>     total = 0
>     for i in range(len(bc)):
>         total=total+bc.values()[i]
>
>     return (total)

bc = NX.edge_betweenness_centrality(G,normalized=True)
values = bc.values()
total = sum(values)
return total

==>

return sum(bc.values())


> pos={}
> for i in range(NODES):
>     pos[nod[i]]=(nod[i][0]/(N*1.0),nod[i][1]/(N*1.0))

In Python version 2.x, 1/3 evals to 0, but that's a mistake; it is fixed
in the 3.x version. If you put this line at the top of your script:
   from __future__ import division
then 1/3 returns 0.3333...
When you actually want integer division, use //, like 1//3

So we can rewrite the above as:

   from __future__ import division
...
for node in nod:
     pos[node] = (node[0] / N, node[1] / N)

Another way, not relying on true division:

divisor = float(N)
for node in nod:
     pos[node] = (node[0] / divisor, node[1] / divisor)

or even:

pos = dict((node, (node[0] / divisor, node[1] / divisor)) for node in nod)


> for y in range(NK):
>     for x in range(ITERATIONS):
>         cost = costG(G)
>         if (cost < (best_cost)):
>             best_graph = G
>             best_cost = cost
>         GG = G

Again, I think this doesn't do what you think it does. GG = G means "let's
use the name GG for the object currently known as G". GG is not a "copy"
of G, just a different name for the very same object. Later operations
like GG.remove_edge(...) modify the object - and you'll see the changes in
G, and in best_graph, because those names all refer to the same object.
I think you'll benefit from reading this:
http://effbot.org/zone/python-objects.htm

>         a = random.randint(0,NODES-1)
>         b = random.randint(0,NODES-1)
>         adj=G.adjacency_list()
>         while ((nod[b] in adj[a]) or (b == a)):
>             a = random.randint(0,NODES-1)
>             b = random.randint(0,NODES-1)
>         GG.add_edge(nod[a],nod[b])

As above, I'd avoid using indexes, take two random nodes using
random.sample instead, and avoid adjacency_list():

while True:
     a, b = random.sample(nod, 2)
     if b not in G[a]:
       break
GG.add_edge(a, b)

(mmm, I'm unsure of the adjacency test, I've used networkx some time ago
but I don't have it available right now)

-- 
Gabriel Genellina

[toc] | [prev] | [next] | [standalone]


#7490

FromThomas Rachel <nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915@spamschutz.glglgl.de>
Date2011-06-12 19:23 +0200
Message-ID<it2smk$38r$1@r03.glglgl.eu>
In reply to#7423
Am 11.06.2011 03:02 schrieb Gabriel Genellina:
>
> Perhaps those names make sense in your problem at hand, but usually I try
> to use more meaningful ones.

Until here we agree.

 > 0 and O look very similar in some fonts.

That is right - but who would use such fonts for programming?


Thomas

[toc] | [prev] | [next] | [standalone]


#7427

FromTerry Reedy <tjreedy@udel.edu>
Date2011-06-10 21:44 -0400
Message-ID<mailman.121.1307756700.11593.python-list@python.org>
In reply to#7373
On 6/10/2011 6:30 AM, Francesc Segura wrote:
> Hello all, I'm new to this and I'm having problems on summing two
> values at python.
>
> I get the following error:
>
> Traceback (most recent call last):
>    File "C:\edge-bc (2).py", line 168, in<module>
>      if (costGG<= cost + T0):
> TypeError: unsupported operand type(s) for +: 'float' and 'tuple'
>
> I'm working with networkx and my program is this one:

[snip about 100 lines]

Before posting code that does not work, it is a good idea to reduce to 
to some minimum needed to exhibit the problem. If you had done that, you 
may well have found the answer.

In this specific case, you should have searched for all lines making 
assignments to the names causing a problem. This is easier to do by eye 
with a minimal example. Or, use a search function for 'T0 =' (or 'T0=' 
if needed, but it is not) with Find Next and the second hit is the 
offending line ("T0 = initCost*0,1").

-- 
Terry Jan Reedy

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web