Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with my code (simple)
#1
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()
Reply
#2
Can you provide the output you get and explain what is wrong with it compared to what you would like the result to be?
Reply
#3
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!
Reply
#4
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
Reply
#5
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.
Reply
#6
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 :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with simple code JacobSkinner 1 337 Mar-18-2024, 08:08 PM
Last Post: deanhystad
  I have a code which is very simple but still I cannot detect what's wrong with it max22 1 491 Nov-07-2023, 04:32 PM
Last Post: snippsat
  help me simple code result min and max number abrahimusmaximus 2 916 Nov-12-2022, 07:52 AM
Last Post: buran
  Simple encoding code ebolisa 3 1,462 Jun-18-2022, 10:59 AM
Last Post: deanhystad
  How would you (as an python expert) make this code more efficient/simple coder_sw99 3 1,818 Feb-21-2022, 10:52 AM
Last Post: Gribouillis
  Simple code question about lambda and tuples JasPyt 7 3,345 Oct-04-2021, 05:18 PM
Last Post: snippsat
  My simple code don't works !! Nabi666 1 1,620 Sep-06-2021, 12:10 PM
Last Post: jefsummers
Sad SyntaxError: from simple python example file from mind-monitor code (muse 2) warmcupoftea 4 2,854 Jul-16-2021, 02:51 PM
Last Post: warmcupoftea
  Plotting sum of data files using simple code Laplace12 3 3,062 Jun-16-2021, 02:06 PM
Last Post: BashBedlam
  Help with isinstance command (very simple code) Laplace12 2 2,014 Jul-30-2020, 05:26 AM
Last Post: Laplace12

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020