Программирование по змеиному ;)

Очень сложно.

Очень страшно, если бы мы знали что это такое, а мы не знаем что это такое.
 
Очень сложно.

Очень страшно, если бы мы знали что это такое, а мы не знаем что это такое.
🙂
Страшного нет, но вроде всё работает, а коннекта нет
Ладно , проще наверное виртуалку поставить🙂
С ХР SP3
 
1000119583.webp
 
Ладно, хватит 🙂
Поставил ХР, не очень. Поставил 7 с обновлениями - запустилось желаемое 🙂
Завтра продолжу 🙂
Доброй ночи всем! :))
 
Собираюсь завтра прочитать в г. Ломоносов небольшую лекцию "Программирование без математики".

В ней мы постараемся коротко и ясно показать, что такое 1) программа, 2) математика и 3) программирование без математики.

Начнём с программы.

1. Программа

Изобретатель программы, русский просветитель и петербуржец С.Н. Корса́ков, так описал своё изобретение:

Письменность стала первой главной основой общества. Программа станет второй главной основой общества и совершенной второй письменностью (1832, Корсаков).
Слова Корсакова сбылись наполовину - программа прочно заняла место "второй главной основы общества". Будущее программы - стать "совершенной второй письменностью". Не для себя, а для общества.

  • Программа - это совершенная вторая письменность.
Программа всегда оставалась письменностью, как Золушка всегда оставалась собой: в своей комнате, на кухне, незнакомкой на балу и невестой на своей свадьбе с принцем.

Сейчас программа в третьем состоянии - незнакомка на балу. Вот и давайте с ней познакомимся.

Письменность - первая главная основа общества. Она позволила обществу накапливать и передавать знания самого разного вида, и обеспечила все современные блага.

Благодаря письменности мы живём в городах, ездим на машинах, покупаем еду и товары в магазинах, одеты не в звериные шкуры и собрались сегодня 23 января 2025 года в библиотеке им. Рубакина.

У письменность есть много прекрасных свойств, кроме одного - она никогда не была совершенной.

  • Совершенство - это соединение слова и дела.
Когда всё, что можно сказать о каком-то предмете, оказывается выполнено, или совершено, - такая вещь называется "совершенной".

Письменность не соединяет слово и дело, поэтому не даёт совершенства.

Программа соединяет и даёт.

Распишем рождение совершенства по ступеням:

  1. Дело описывает речь. Речь - это слово.
  2. Речь отражается в расчёт. Каждая мысль - в своё выражение расчёта. Отражённый расчёт - это "втора", "второй голос", "двухголосье".
  3. Расчёт разбирается в столбцы узлов, записанные ямками. Ямки + столбцы = ямцы.
  4. Ямцы управляют работой умственной машиной.
  5. Умственная машина выполняют описанную умственную работу - обработку сведений. Слово превращается в дело.
Раньше совершение слова и совершенство письменности обеспечивал человек.

Теперь человеку стала помогать программа.

Давайте кратко рассмотрим пример самой первой программы, созданной Семёном Николаевичем Корсаковым в Петербурге в 1829-1834 годах - Гомеоскоп, или по-русски Знакозор.

%D1%81%D1%82%D1%83%D0%BF%D0%B5%D0%BD%D0%B8.png


Распишем рождение совершенства по ступеням:

  1. Дело описывает речь. Речь - это слово.
  2. Речь отражается в расчёт. Каждая мысль - в своё выражение расчёта. Отражённый расчёт - это "втора", "второй голос", "двухголосье".
  3. Расчёт разбирается в столбцы узлов, записанные ямками. Ямки + столбцы = ямцы.
  4. Ямцы управляют работой умственной машиной.
  5. Умственная машина выполняют описанную умственную работу - обработку сведений. Слово превращается в дело.
Раньше совершение слова и совершенство письменности обеспечивал человек.

Теперь человеку стала помогать программа.

Давайте кратко рассмотрим пример самой первой программы, созданной Семёном Николаевичем Корсаковым в Петербурге в 1829-1834 годах - Гомеоскоп, или по-русски Знакозор.

(продолжение - на лекции завтра, и здесь, но позже.)

Использованные источники:
Втораграм. ПБМ
Комментарий автора:
25 января - день рождение русского изобретателя программы С.Н. Корсакова. отмечаем, чем можем"
 

"How to make a program in Python for counting the number of grains on a chessboard if the number of grains on 1 squar
... e = 1 and then doubles
<think>
Okay, so I need to figure out how to write a Python program that counts the number of grains on a chessboard where
each square starts with one grain and then doubles on each subsequent square. Let me think about this step by
step.

First, I know that a chessboard has 64 squares, right? So, we'll be dealing with squares from 1 to 64. On the
first square, there's 1 grain. The second square has double that, so 2 grains. The third has double of the second,
which is 4 grains, and this pattern continues all the way to the 64th square.

So, essentially, each square's grain count follows a geometric sequence where each term is twice the previous one.
This means that on the nth square, there are 2^(n-1) grains because the first square (n=1) has 2^0 = 1 grain.

But I need to sum all these grains from square 1 to square 64. That's a geometric series sum. The formula for the
sum of a geometric series is S_n = a * (r^n - 1) / (r - 1), where 'a' is the first term, 'r' is the common ratio,
and 'n' is the number of terms.

In this case, a=1, r=2, and n=64. Plugging these into the formula gives S_64 = 1*(2^64 - 1)/(2-1) = (2^64 - 1)/1 =
2^64 - 1.

But since I'm writing a program to calculate this, maybe it's better to use a loop to add up the grains for each
square from 1 to 64. That way, I don't have to rely on remembering the formula and can compute it iteratively.

So here's what I think: Initialize a variable to keep track of the total number of grains, say 'total = 0'. Also,
initialize a variable for the current number of grains on the square, let's call it 'grains = 1'.

Then, loop from 1 to 64 (inclusive). In each iteration, add the current 'grains' value to 'total', and then double
'grains' for the next square.

Wait a minute, that makes sense because starting with grains=1 for the first square. Then after adding it to
total, we multiply by 2 to get grains=2 for the second square, and so on until the 64th square.

But I also need to make sure that my loop runs exactly 64 times, once per each square. Using a for loop with
range(1,65) should work because in Python, range is exclusive of the upper limit.

So putting it all together:

Initialize total =0 and grains=1.

For i in range(1, 65):

add grains to total

multiply grains by 2

At the end, print total.

Alternatively, I can calculate this using the formula directly: total = 2^64 - 1. That's a single line calculation
which is more efficient and avoids loops.

But for educational purposes or understanding the process step by step, implementing it with a loop might be more
illustrative.

Wait, but for such large exponents, how does Python handle big integers? I know that Python can manage arbitrarily
large integers, so 2^64 shouldn't be a problem. However, calculating 2**64 directly is straightforward and
accurate.

But if the number of squares were not fixed, or if we wanted to generalize it for any number of squares 'n', then
using loops would be more flexible.

In this specific case, since the chessboard has exactly 64 squares, using either approach should work. The loop
method makes it clear how the grains accumulate with each square, while the formula gives a direct mathematical
solution.

I think writing both versions could be helpful to cross-verify the results. Let me see:

Using the formula: total = (2 ** 64) - 1

With loops:

total = 0

grains = 1

for _ in range(64):

total += grains

grains *= 2

print(total)

Both methods should give the same result. Let's see what is (2^64)-1 numerically? It's a very large number,
approximately 1.8446744e+19.

Now, let me think about potential issues. For example, does the loop correctly iterate 64 times? Starting with
grains=1, and doubling it each time. The first iteration adds 1 to total (square 1), then grains becomes 2. Second
iteration adds 2 (total now 3) and grains becomes 4, etc., up to the 64th square.

Yes, that should be correct. Alternatively, if I had started with grains=0 and incremented differently, but no,
starting at 1 makes sense for the first square.

Another point: Is the variable name 'grains' clear? Maybe using 'current_grains' would make it more descriptive.
And 'total' is fine as it indicates the cumulative sum.

So to summarize my thought process:

- Understand that each square has double the grains of the previous one, starting at 1.

- Recognize this as a geometric series and remember the formula for its sum.

- Consider implementing both the mathematical formula and iterative loop methods in Python.

- Verify that both approaches should yield the same result.

- Think about variable naming clarity and ensuring the loop runs exactly 64 times to cover all squares on the
chessboard.

Therefore, writing a Python program using a loop seems straightforward and effective for this problem.
</think>

To solve the problem of counting the number of grains on a chessboard where each subsequent square has double the
grains of the previous one (starting with 1 grain on the first square), we can use an iterative approach in
Python. This method involves summing up the grains on each of the 64 squares.

### Approach
The problem is essentially about calculating the sum of a geometric series where each term doubles the previous
one. The chessboard has 64 squares, starting with 1 grain on the first square and doubling for each subsequent
square.

The approach involves:
1. Initializing variables to keep track of the total grains (`total`) and the current number of grains on each
square (`grains`).
2. Using a loop to iterate over each of the 64 squares, adding the current number of grains to the total and then
doubling the grains for the next square.
3. After completing the loop, print out the total number of grains.

This method ensures that we systematically accumulate the grains from each square without relying on complex
mathematical formulas, making it easy to understand and verify.

### Solution Code

```python
total = 0
grains = 1

for _ in range(64):
total += grains
grains *= 2

print("Total number of grains:", total)
```

### Explanation
- **Initialization**: We start with `total` set to 0, which will hold the cumulative sum of all grains. The
variable `grains` is initialized to 1, representing the grains on the first square.
- **Loop Through Squares**: Using a for loop that runs exactly 64 times (once for each square), we add the current
number of grains (`grains`) to `total`. After adding, we double the value of `grains` for the next iteration.
- **Output the Result**: After the loop completes, we print the total number of grains accumulated across all
squares.

This approach efficiently calculates the total grains using a simple iterative method, ensuring clarity and
correctness."
Попросил я решить известную задачу на 64 клеточках 🙂
Рассуждает прикольно 🙂
 
Qwen2.5-Plus



User profile
"How to make a program in Python for counting the number of grains on a chessboard if the number of grains on 1 squar


profile

Qwen2.5-Plus
Certainly! The problem you're referring to is a classic one: the "wheat and chessboard" problem. According to the legend, if you place one grain of wheat on the first square of a chessboard, two grains on the second square, four grains on the third square, and so on (doubling the number of grains on each subsequent square), how many grains of wheat will be on the entire chessboard?


A standard chessboard has 64 squares. Let's write a Python program that calculates the total number of grains on the chessboard.


Here's the step-by-step approach:


  1. Start with 1 grain on the first square.
  2. Double the number of grains for each subsequent square.
  3. Sum the number of grains on all 64 squares.

Here’s the Python code to achieve this:


python
Copy



1
2
3
4
5
6
7
8
9
10
11
12
13



def count_grains_on_chessboard():
total_grains = 0
grains_on_current_square = 1

for square in range(1, 65): # Chessboard has 64 squares, indexed from 1 to 64
total_grains += grains_on_current_square
print(f"Square {square}: {grains_on_current_square} grains")
grains_on_current_square *= 2 # Double the grains for the next square

return total_grains

total_grains = count_grains_on_chessboard()
print(f"Total number of grains on the chessboard: {total_grains}")




Explanation:​

  • We initialize total_grains to 0, which will hold the sum of grains on all squares.
  • grains_on_current_square starts at 1 (for the first square).
  • We loop through each square from 1 to 64.
  • For each square, we add the current number of grains (grains_on_current_square) to total_grains.
  • After adding the grains for the current square, we double the number of grains for the next square.
  • Finally, we print the total number of grains on the chessboard.

Output:​

The output will show the number of grains on each square and the total number of grains on the chessboard. The final result should be:



Copy



1


Total number of grains on the chessboard: 18446744073709551615




This large number is 264−1, which represents the sum of a geometric series where each term is double the previous one, starting from 1.


You can run this code in any Python environment to see the results.
















AI-generated content may contain inaccuracies.
Qwen"
...это в вебе, от Али-Бабы
 
...пятничное, на подумать.
И мне, и всем 😉
 

Новые комментарии

LGBT*

В связи с решением Верховного суда Российской Федерации (далее РФ) от 30 ноября 2023 года), движение ЛГБТ* признано экстремистским и запрещена его деятельность на территории РФ. Данное решение суда подлежит немедленному исполнению, исходя из чего на форуме будут приняты следующие меры - аббривеатура ЛГБТ* должна и будет применяться только со звездочкой (она означает иноагента или связанное с экстремизмом движение, которое запрещено в РФ), все ради того чтобы посетители и пользователи этого форума могли ознакомиться с данным запретом. Символика, картинки и атрибутика что связана с ныне запрещенным движением ЛГБТ* запрещены на этом форуме - исходя из решения Верховного суда, о котором было написано ранее - этот пункт внесен как экстренное дополнение к правилам форума части 4 параграфа 12 в настоящее время.

Назад
Сверху