Skip to main content
 首页 » 编程设计

python之具有概率集的随机和弦创建器不会将相同的音符打印两次

2024年11月24日7jpfss

以 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)

请您参考如下方法:

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

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()