Python Forum

Full Version: Help with my code (simple)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone.
Im trying to make a function that blend randomly the words in a sentence.
Made some checks with print command... ignore it.
Im quite new with python so feel free to advice me what ive done wrong.

Here is my code; it seems like ive done it ok, but something go wrong when I run it :/

import random

def BlendString():
  string = input ("Enter a sentence: \n")
  s = string.split()

  i=0

  newstring = s 

  print (newstring)

  rand = random.sample(range(0,len(s)),len(s))
  print (rand)

  while len(s)-1 > i:
    newstring[i] = s[rand[i]]
    print (newstring)
    i+=1
  
  
BlendString()
Can you provide the output you get and explain what is wrong with it compared to what you would like the result to be?
sure.

here is the code(change the while loop to len(s) > i without the minus(-)) :

import random
 
def BlendString():
  string = input ("Enter a sentence: ")
  s = string.split()
 
  i=0
 
  newstring = s 
 
  print ("this is the string Ive entered " +str(newstring))
 
  rand = random.sample(range(0,len(s)),len(s))
  print ("\n\nthis is the random sequance that should be: " +  str(rand)+"\n")
 
  while len(s) > i:
    newstring[i] = s[rand[i]]
    print (newstring)
    i+=1
   
   
BlendString()
ive entered - "0 1 2 3" as a string to be blend, so that the rand will actually show the final sequence.
here is the output:

Output:
Enter a sentence: 0 1 2 3 this is the string Ive entered ['0', '1', '2', '3'] this is the random sequance that should be: [1, 2, 3, 0] ['1', '1', '2', '3'] ['1', '2', '2', '3'] ['1', '2', '3', '3'] ['1', '2', '3', '1']


The problem here is the last string(digit in this case...) that dont turn to 0 as expected.

I wish i explained myself clear, english isnt my native :)
Thanks!
The main Problem here is, that the list you save in newstring is not copied. The variable s and newstring are holding the same reference:
def blend():
      string = input("Enter: ")
      s = string.split()
      newstring = s#list(s)
      rand = random.sample(range(0, len(s)), len(s))
      print rand
      for i, ind in enumerate(rand):
          print "######## %i Try ########" % (i+1)
          print "newstring_list: %s"%str(newstring)
          print "old_string_list %s"%str(s)
          newstring[i] = s[ind]
      return newstring
         

In [2]: blend()
Enter: "1 2 3 4"
[3, 2, 0, 1]
######## 1 Try ########
newstring_list: ['1', '2', '3', '4']
old_string_list ['1', '2', '3', '4']
######## 2 Try ########
newstring_list: ['4', '2', '3', '4']
old_string_list ['4', '2', '3', '4']
######## 3 Try ########
newstring_list: ['4', '3', '3', '4']
old_string_list ['4', '3', '3', '4']
######## 4 Try ########
newstring_list: ['4', '3', '4', '4']
old_string_list ['4', '3', '4', '4']
Out[2]: ['4', '3', '4', '3']
So while copying you already altered the original list. Make a copy of your list by using list:
def blend():
      string = input("Enter: ")
      s = string.split()
      newstring = list(s)
      rand = random.sample(range(0, len(s)), len(s))
      for i, ind in enumerate(rand):
          newstring[i] = s[ind]
      return newstring
or by having an empty list:
def blend():
      string = input("Enter: ")
      s = string.split()
      newstring = []
      rand = random.sample(range(0, len(s)), len(s))
      for ind in rand:
          newstring.append(s[ind])
      return newstring
OK thank you!

Just to make sure - enumerate is equal to i+=1, right?

Just exposed to a very simple solution I wanted to share:

random.shuffle(newstring)
Make the code way easier.
That's right, random.shuffle is way easier, unfortunately I forgot about it, so I didn't mentioned it before. sry about that :D
enumerate takes a list you want to iterate through and gives you the value hold at a position and its corresponding index.
so if you have a list like list_test = ["a", "b", "c", "d"] and you call enumerate(list_test) it makes an iterable enumerate object giving you values like you would get with [(0,"a"), (1, "b"), (2, "c"), (3, "d")]. It is just a simple trick to get the values and the indices at the same time while iterating over a list :)