首页 > 解决方案 > 随机和弦创建器的概率集不会打印相同的音符两次

问题描述

创建受 SUN RA 爵士音乐启发的和弦发生器。我正在尝试创建一个非常可定制的和弦发生器。到目前为止,我可以给它提供笔记并在我的对象“笔记”中给出这些笔记的设置概率。我遇到的问题是当它生成序列时,我有时会得到相同的音符。是否有某种方法可以在每个打印行之间创建一个 if 语句,以排除从前一个渲染中选择的任何随机音符,以便下一个音符不能与前一个音符相同?

我尝试在每个打印行之间自己写一个 if 语句,但这很尴尬,所以我宁愿不分享。

import random
import numpy as np
class Note:

    def __init__(self, name, note):
        self.name = name
        self.gender= np.random.choice(["c", "e", "g", "b"],1,[0.5, .2, 0.1, 0.2])[0]



c = Note('c', 'yourNote')
d = Note('d', 'yourNote')
e = Note('e', 'yourNote')
f = Note('f', 'yourNote')
Your_Chord = Note(c.name, c.gender)
print(Your_Chord)
print(c.gender)
print(d.gender)
print(e.gender)
print(f.gender)

标签: python

解决方案


我认为你错过的主要事情是某种方式来跟踪最新的笔记,然后确保它没有被选中。我添加了一个类变量来跟踪最后一个音符,并添加了一个临时字典,每次都可以从中挑选。我希望这对你的疯狂爵士乐有所帮助!

import numpy as np

# dict with the notes and weights
notes = {"c":0.5, "e":0.2, "g":0.1, "b":0.2}

class Note:
    _last_note = 'start'
    def __init__(self, name, note):
        self.name = name
        # here we temporarily create a dict without the last note in it
        new_notes = {k: notes[k] for k in set(list(notes.keys())) - set(Note._last_note)}
        self.gender = np.random.choice(list(new_notes.keys()-Note._last_note),1,list(new_notes.values()))[0]
        print("init ",self.gender,Note._last_note)
        Note._last_note = self.gender

    def print_chord(self):
        print("print chord ",self.name,self.gender)



c = Note('c', 'yourNote')
d = Note('d', 'yourNote')
e = Note('e', 'yourNote')
f = Note('f', 'yourNote')
Your_Chord = Note(c.name, c.gender)

Your_Chord.print_chord()

print(c.gender)
print(d.gender)
print(e.gender)
print(f.gender)

c.print_chord()
d.print_chord()
e.print_chord()
f.print_chord()

推荐阅读