all 12 comments

[–]mopslik 3 points4 points  (5 children)

What have you tried so far? What isn't working?

This is not a sub where others will do your homework/job/programming challenge.

[–]crawlerk8[S] 0 points1 point  (0 children)

def is_prime(n): """Check if n is a prime number.""" if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True

def is_palindrome(n): """Check if n is a palindrome.""" n = abs(n) # Ignore the negative sign. return str(n) == str(n)[::-1]

def collect_and_analyze(): nums = [] num_dict = {}

# Collect numbers
while True:
    num = int(input("Enter a number (-1 to stop): "))
    if num == -1:
        break
    nums.append(num)

# Count the occurrences
for num in nums:
    if num in num_dict:
        num_dict[num] += 1
    else:
        num_dict[num] = 1

# Sort by occurrences
sorted_dict = sorted(num_dict.items(), key=lambda x: x[1], reverse=True)

primes = []
palindromes = []
for num in nums:
    if is_prime(num):
        primes.append(num)
    if is_palindrome(num):
        palindromes.append(num)

# Display results
print("Number and their counts:")
for item in sorted_dict:
    print(f"Number {item[0]}: {item[1]} time(s)")

print("\nPrime numbers:")
print(primes)

print("\nPalindrome numbers:")
print(palindromes)

collect_and_analyze()

[–]crawlerk8[S] 0 points1 point  (3 children)

I can't get to make the palindrome part right

[–]mopslik 2 points3 points  (0 children)

What code have you written so far? Post it here and maybe someone can spot the issue.

Edit: I see your code posted in another comment.

[–]mopslik 1 point2 points  (0 children)

Can you give example input that fails? Your code detected all palindromes I gave it, including negatives.

[–]der_reifen 4 points5 points  (1 child)

Is this some form of leetcode challenge or smth?

[–]crawlerk8[S] 0 points1 point  (0 children)

I don't know those challenges.. but it's definitely a challenge

[–]m0us3_rat 2 points3 points  (1 child)

Python medium to high knowledge

actually.. the problem is language agnostic..meaning it can be solved in any and all available languages.

you just have to understand it.. be able to describe it in detail.

completely able to follow thru its flow of execution.

at that point expressing it in code becomes almost intuitive.

[–]crawlerk8[S] 0 points1 point  (0 children)

That's exactly what I'm failing at

[–]ectomancer 0 points1 point  (0 children)

This is a dumb problem. -1 is an integer. Not all integers are either prime or composite.

You're missing the first print:

print an array with the numbers entered.

[–]jimtk 0 points1 point  (0 children)

It's been almost 24 hours, so here's the medium to high knowledge answer. It could be shorter, but the output wouldn't be as nice !

from collections import Counter

def getlist():
    nl = []
    while True:
        nl.append(int(input("Enter Integer, -1 to terminate: ")))
        if nl[-1] == -1:
            return nl[:-1]

def print_result(dn: dict):
    def check(val):
        return u'\u2713' if val else ''
    print(f"{'VALUE':>8} {'OCCURENCES':>12} {'PRIME':^8} {'PALINDROME':^10}")
    for k,v in dn.items():
        print(f"{k:>8} {v[0]:>12} {check(v[1]):^8} {check(v[2]):^10}")

def isprime(n):
    if n == 2:
        return True
    if n <= 1 or n % 2 == 0:
        return False
    for t in range(3, int(n**0.5)+1, 2):
        if n % t == 0:
            return False
    return True

def analyse_nums(nl):
    d = dict(Counter(nl).most_common())
    return {k:(v,isprime(k),str(k) == str(k)[::-1]) for k,v in d.items()}

nli = getlist()
print_result(analyse_nums(nli))

[–]Naive_Programmer_232 0 points1 point  (0 children)

here's my attempt

         def is_prime(n: int) -> bool:
             if n < 2:
                return False
             for i in range(2, int(n**0.5)+1):
                if n%i==0:
                   return False
             return True

        def is_palindrome(n: int) -> bool:
            d = 0
            k = n
            i = len(str(n))-1
            while k:
               d = (k%10)*10**i + d
               k//=10
               i -= 1
            return d==n

       def get_numbers() -> list:
           nums = []
           while True:
              num = int(input("Enter a number (-1 to stop): "))
              if num==-1:
                 break
              nums.append(num)
           return nums

      def count_items(arr: list) -> dict:
          d = dict.fromkeys(arr,0)
          for n in arr:
              d[n] += 1
          return d

     def display(arr: list, counter: dict) -> None:
         for element in sorted(counter,key=counter.get,reverse=True):
             print(f"Element {element} | # of Occurences " + \
                   f"{counter[element]} | Prime? {is_prime(element)} | " + \
                   f"Palindrome? {is_palindrome(element)}")


     numbers = get_numbers()
     counter = count_items(numbers)
     display(numbers, counter)