Coverage for pysource_minimize/_minimize_value.py: 93%

63 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2024-03-25 08:14 +0100

1import ast 

2 

3from ._minimize_base import MinimizeBase 

4 

5 

6class MinimizeValue(MinimizeBase): 

7 

8 allow_multiple_mappings = True 

9 

10 def minimize_stmt(self, stmt): 

11 self.minimize(stmt) 

12 

13 def minimize(self, o): 

14 method_name = "minimize_" + type(o).__name__ 

15 if hasattr(self, method_name): 

16 getattr(self, method_name)(o) 

17 else: 

18 for child in ast.iter_child_nodes(o): 

19 self.minimize(child) 

20 

21 def minimize_Constant(self, constant: ast.Constant): 

22 if isinstance(constant.value, bool): 

23 if constant.value is True: 23 ↛ exitline 23 didn't return from function 'minimize_Constant', because the condition on line 23 was never false

24 self.try_attr(constant, "value", False) 

25 elif isinstance(constant.value, float): 

26 v = constant.value 

27 l = 0.0 

28 

29 while l != v: 29 ↛ exitline 29 didn't return from function 'minimize_Constant', because the condition on line 29 was never false

30 m = (l + v) / 2 

31 if self.try_attr(constant, "value", m): 

32 if v == m: 32 ↛ 33line 32 didn't jump to line 33, because the condition on line 32 was never true

33 break 

34 v = m 

35 else: 

36 if l == m: 

37 break 

38 l = m 

39 

40 elif isinstance(constant.value, int): 

41 v = constant.value 

42 l = 0 

43 

44 while l != v: 44 ↛ exitline 44 didn't return from function 'minimize_Constant', because the condition on line 44 was never false

45 m = (l + v) // 2 

46 if self.try_attr(constant, "value", m): 

47 if v == m: 47 ↛ 48line 47 didn't jump to line 48, because the condition on line 47 was never true

48 break 

49 v = m 

50 else: 

51 if l == m: 

52 break 

53 l = m 

54 

55 elif isinstance(constant.value, (str, bytes)): 

56 

57 value_type = type(constant.value) 

58 

59 def try_list(l): 

60 if value_type is str: 

61 v = value_type().join(l) 

62 else: 

63 v = bytes(l) 

64 result = self.try_attr(constant, "value", v) 

65 return result 

66 

67 def without(before, l, after): 

68 

69 if try_list(before + after): 

70 return [] 

71 elif len(l) == 1: 

72 return l 

73 else: 

74 return devide(before, l, after) 

75 

76 def devide(before, l, after): 

77 if not l: 

78 return [] 

79 

80 mid = len(l) // 2 

81 

82 a, b = l[:mid], l[mid:] 

83 a = without(before, a, b + after) 

84 b = without(before + a, b, after) 

85 return a + b 

86 

87 devide([], list(constant.value), [])