Hello,
I am a python newbie and I am trying to accommodate to the basics.
What's the python equivalent for the following Java snippet ?

Java:

public class Main {
    public static void main(String args[]){
	int a,b,c;
	a= (int) (Math.random()*100);
	c=0;
	while((b=(int)(Math.random()*100))!=a){
	    c+=1;
	}
	System.out.println(c);
    }
}

I was trying to create something similar in python, but I've encountered some errors.
This is the Python code with errors:

import random

a=int(random.triangular(1,100))
c=0
while(b=int(random.triangular(1,100))!=a:
      c+=1
print(c)
William Hemsworth commented: A perfect first post. +5

Recommended Answers

All 5 Replies

In python, x = y is a statement. It can't be used as an expression. You should write

import random
a =int(random.triangular(1,100))
c = 0
while True:
    b = int(random.triangular(1, 100))
    if b == a:
        break
    else:
        c += 1
print(c)

Thanks!

More exotic

from itertools import takewhile, count
c = sum(1 for b in takewhile(lambda x: x != a, (int(random.triangular(1, 100)) for x in count())))

More exotic

from itertools import takewhile, count
c = sum(1 for b in takewhile(lambda x: x != a, (int(random.triangular(1, 100)) for x in count())))

You actually think that is more exotic? Wow.

Less exotic

import random

def random_tri():
    return int(random.triangular(1,100))

a=random_tri()
c=0
while random_tri() != a:
      c+=1
print(c)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.