我刚刚完成了哈佛 CS50P 在线课程,我的第一个项目是尝试开发一个程序来计算多项式函数的 y 值。我知道我的代码可能很糟糕
我刚刚完成了在线哈佛 CS50P 课程,我的第一个项目是尝试开发一个程序来计算多项式函数的 y 值。我知道我的代码可能优化得很糟糕,而且有一个库已经可以完成我正在做的事情,但这不是我真正的重点。我正在尝试做一些无论如何都能奏效的事情。
import math
equation = input("Equation: ").strip().lower().replace(" ", "")
value = input("Value of x: ")
chars = []
exponents = []
mults = []
sums = []
subs = []
divs = []
sqrts = []
result = 0
for char in equation:
if char == "x":
char = char.replace("x", value)
chars.append(char)
else:
chars.append(char)
for op in range(len(chars)):
if chars[op] == "^":
exponents.append(1)
elif chars[op] == "*":
mults.append(op)
elif chars[op] == "+":
sums.append(op)
elif chars[op] == "-":
subs.append(op)
elif chars[op] == "/":
divs.append(op)
elif chars[op] == "v":
sqrts.append(op)
for exponent in range(len(exponents)):
expResult = int(chars[exponents[exponent] - 1]) ** int(chars[exponents[exponent] + 1])
chars[exponents[exponent] - 1] = expResult
chars.remove(chars[exponents[exponent]])
chars.remove(chars[exponents[exponent]])
exponents.remove(1)
result += float(expResult)
for sqrt in range(len(sqrts)):
sqrtResult = int(chars[sqrts[sqrt] - 1]) * math.sqrt(int(chars[sqrts[sqrt] + 1]))
chars[sqrts[sqrt] - 1] = sqrtResult
chars.remove(chars[sqrts[sqrt]])
chars.remove(chars[sqrts[sqrt]])
result += float(sqrtResult)
for mult in range(len(mults)):
multResult = int(chars[mults[mult] - 1]) * int(chars[mults[mult] + 1])
chars[mults[mult] - 1] = multResult
chars.remove(chars[mults[mult]])
chars.remove(chars[mults[mult]])
result += float(multResult)
for div in range(len(divs)):
divResult = int(chars[mults[mult] - 1]) * int(chars[mults[mult] + 1])
chars[divs[div] - 1] = divResult
chars.remove(chars[divs[div]])
chars.remove(chars[divs[div]])
result += float(divResult)
print(result)
print(chars)
print(exponents)
我仍在开发它的第一步。但是,每当我输入一个包含多个操作的函数时,我都会得到 IndexError: list index out of range
.
例如:
Equation: x^3^3
Value of x: 2
Traceback (most recent call last):
File "/Users/vinisiqueira/graphingCalc/graphingCalc.py", line 38, in <module>
expResult = int(chars[exponents[exponent] - 1]) ** int(chars[exponents[exponent] + 1])
~~~~~~~~~^^^^^^^^^^
IndexError: list index out of range
当我将 for 循环改为仅迭代一次时,我得到:
Equation: 2^3^2
Value of x: 2
8.0
[8, '^', '2']
[1]
所以这意味着,对于第一次操作,它是有效的,但是当再次执行完全相同的操作时,它会失败。
如果这段代码不清楚的话,我深感抱歉,但如果有任何帮助我将不胜感激。
谢谢
所以我尝试向活动添加一个新对象并将其存储在本地存储中,代码如下所示 pushObjectWisata(selectedIndex, selectedObjectId) async { PengunjungModel dataObjectWi...
所以我试图向活动添加一个新对象并将其存储在本地存储中,代码如下所示
pushObjectWisata(selectedIndex, selectedObjectId) async {
PengunjungModel dataObjectWisata = listObjectWisata
.firstWhere((element) => element.id == selectedObjectId);
listAktifitas[selectedIndex].dataAktifitas!.add(dataObjectWisata);
await saveListAktifitas(listAktifitas);
}
但我收到此错误:
[错误:flutter/runtime/dart_vm_initializer.cc(41)] 未处理的异常:将对象转换为可编码对象失败:“listActivities”实例
listAktifitas 本身是一个具有多级对象的列表。模型如下所示
class listActivities {
String? namaAktifitas;
int? statusAktifitas;
int? countActivity;
String? thumbnail;
List<PengunjungModel>? dataAktifitas;
listActivities({
this.namaAktifitas,
this.statusAktifitas,
this.countActivity,
this.thumbnail,
this.dataAktifitas,
});
factory listActivities.fromJson(Map<String, dynamic> json) => listActivities(
namaAktifitas: json['namaAktifitas'].toString(),
countActivity: json['countActivity'],
statusAktifitas: json['statusAktifitas'],
thumbnail: json['thumbnail'].toString(),
dataAktifitas: List<PengunjungModel>.generate(
json['dataAktifitas'].length,
(index) => PengunjungModel.fromJson(
json['dataAktifitas'][index] ?? <String, dynamic>{}),
),
);
static List<listActivities> fromJsonList(dynamic jsonList) {
final listAktifitas = <listActivities>[];
if (jsonList == null) return listAktifitas;
if (jsonList is List<dynamic>) {
for (final json in jsonList) {
listAktifitas.add(
listActivities.fromJson(json),
);
}
}
return listAktifitas;
}
factory listActivities.fromRawJson(String str) =>
listActivities.fromJson(jsonDecode(str));
String toRawJson() => jsonEncode(toJson());
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['namaAktifitas'] = namaAktifitas;
data['statusAktifitas'] = statusAktifitas;
data['countActivity'] = countActivity;
data['thumbnail'] = thumbnail;
data['dataAktifitas'] = dataAktifitas;
return data;
}
}
如您所见,它与另一个列表 pengungungModel List 有关系。模型如下所示:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:sbh_v2/model/pariwisata/foto.dart';
import 'package:sbh_v2/model/pariwisata/kategori_pengunjung.dart';
class PengunjungModel {
String? title;
int? id;
String? harga_terendah;
String? harga_tertinggi;
String? deskripsi;
String? jam_buka;
String? jam_tutup;
String? alamat;
String? fasilitas;
double? lat;
double? lng;
List<Foto>? list_foto = <Foto>[];
KategoriPengunjung? kategoriPengunjung;
PengunjungModel(
{this.id,
this.title,
this.harga_terendah,
this.harga_tertinggi,
this.deskripsi,
this.alamat,
this.list_foto,
this.jam_tutup,
this.jam_buka,
this.fasilitas,
this.lat,
this.lng,
this.kategoriPengunjung});
factory PengunjungModel.fromJson(Map<String, dynamic> json) =>
PengunjungModel(
id: json['id'],
title: json['title'] ?? "-",
alamat: json['alamat'] ?? "-",
jam_buka: json['jam_buka'] ?? "-",
jam_tutup: json['jam_tutup'] ?? "-",
fasilitas: json['fasilitas'],
lat: double.parse(json['lat'] ?? '0'),
lng: double.parse(json['lng'] ?? '0'),
harga_terendah: json['harga_terendah'] ?? "",
harga_tertinggi: json['harga_tertinggi'] ?? "",
deskripsi: json['deskripsi'] ?? "-",
list_foto: List<Foto>.generate(
json['foto'].length,
(index) => Foto.formJson(
json['foto'][index] ?? <String, dynamic>{},
),
),
kategoriPengunjung: KategoriPengunjung.fromJson(
json['kategori_layanan_pengunjung'] ?? <String, dynamic>{}),
);
factory PengunjungModel.fromRawJson(String str) =>
PengunjungModel.fromJson(jsonDecode(str));
}
基本上,我尝试将具有特定 id 的 pengunjungModel 数据对象添加到具有特定索引的 listAktifitas 中...
在 pushObjectWisata 中我尝试打印 selectedIndex 和 selectedObjectId 并且它工作正常。但是当我尝试打印 dataObjectWisata 时它返回该错误并且当我将 dataObjectWisata 添加到 listAktivitas 时也会发生同样的事情。
我不知道我不明白什么。但也许这是因为这两个的模型。
请帮帮我...谢谢