0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonのclass変数をCの静的変数のように使うテストプログラム '101回目のプロポーズ'

Last updated at Posted at 2023-12-02

class変数をCのstatic宣言された変数のように、静的変数として使ってみるテスト。
101回めのプロポーズ。ドラマの設定とはちょっと違いますが。

class herに101回呼び出したら'Yes'を返す関数ansを作ります。
メインからxを'Yes'が返ってくるまで呼び出します。
'Yes'が返ってきたら終了です。
ここでは、クラス変数を使ってますが、インスタンス変数は使ってません。

propose.py
#!/usr/bin/python3

import random

class her:
    counter=0
    def __init__(self):
        random.seed()
        return
    def ans():
        her.counter+=1
        if her.counter==101:
            return "Yes"
        return "mmm" if random.randrange(10)<7 else "No"

if __name__=="__main__":
    trial=0
    her()
    while 1:
        trial+=1
        print(f"{trial}回目")
        print("Me: Marry me please.")
        ans=her.ans()
        print(f"She: {ans}.")
        if ans=="Yes":
            break
    print("We are just married.")

Cで書くとこのようになります。

propose.c
#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>
#include	<time.h>

void	her_init() {
	srand((unsigned)time(NULL));
	return;
}

char	*her_ans() {
	static int counter=1;
	return counter++==101?"Yes":(rand()%10<7?"mmm":"No");
}
int main() {
	int trial=0;
	char *ans;
	her_init();
	while (1) {
		trial++;
		printf("%d回目\n",trial);
		printf("Me: Marry me please.\n");
		ans=her_ans();
		printf("She: %s.\n",ans);
		if (strcmp(ans,"Yes")==0)
			break;
		}
	printf("We are just married.\n");
}

0
0
12

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?