100% нашли этот документ полезным (1 голос)
10 просмотров

C and Python Applications: Embedding Python Code in C Programs, SQL Methods, and Python Sockets First Edition Philip Joyce download

Документ представляет собой книгу Филипа Джойса о внедрении кода Python в программы на C, методах SQL и сокетах Python. Он охватывает основы программирования на Python и C, а также взаимодействие между ними через SQL. Книга включает практические примеры и упражнения для закрепления материала.

Загружено:

maiuriphyoe
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
100% нашли этот документ полезным (1 голос)
10 просмотров

C and Python Applications: Embedding Python Code in C Programs, SQL Methods, and Python Sockets First Edition Philip Joyce download

Документ представляет собой книгу Филипа Джойса о внедрении кода Python в программы на C, методах SQL и сокетах Python. Он охватывает основы программирования на Python и C, а также взаимодействие между ними через SQL. Книга включает практические примеры и упражнения для закрепления материала.

Загружено:

maiuriphyoe
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
Вы находитесь на странице: 1/ 77

C and Python Applications: Embedding Python Code

in C Programs, SQL Methods, and Python Sockets


First Edition Philip Joyce install download

https://ebookmeta.com/product/c-and-python-applications-
embedding-python-code-in-c-programs-sql-methods-and-python-
sockets-first-edition-philip-joyce/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Optimizing Visual Studio Code for Python Development:


Developing More Efficient and Effective Programs in
Python 1st Edition Sufyan Bin Uzayr

https://ebookmeta.com/product/optimizing-visual-studio-code-for-
python-development-developing-more-efficient-and-effective-
programs-in-python-1st-edition-sufyan-bin-uzayr/

C Python Tricks And Tips 5th Edition 2021

https://ebookmeta.com/product/c-python-tricks-and-tips-5th-
edition-2021/

C Python for Beginners 8th Edition 2021

https://ebookmeta.com/product/c-python-for-beginners-8th-
edition-2021/

Adjusting Course Artemis University 15 1st Edition


Erin R Flynn

https://ebookmeta.com/product/adjusting-course-artemis-
university-15-1st-edition-erin-r-flynn/
How to Become a Data Analyst: My Low-Cost, No Code
Roadmap for Breaking into Tech 1st Edition Nelson

https://ebookmeta.com/product/how-to-become-a-data-analyst-my-
low-cost-no-code-roadmap-for-breaking-into-tech-1st-edition-
nelson/

Lonely Planet Western USA Travel Guide 5th Edition


Lonely Planet

https://ebookmeta.com/product/lonely-planet-western-usa-travel-
guide-5th-edition-lonely-planet/

The Secret Lives of Numbers Numerals and Their


Peculiarities in Mathematics and Beyond Alfred S.
Posamentier

https://ebookmeta.com/product/the-secret-lives-of-numbers-
numerals-and-their-peculiarities-in-mathematics-and-beyond-
alfred-s-posamentier/

Service Learning in Psychology 1st Edition Robert G.


Bringle

https://ebookmeta.com/product/service-learning-in-psychology-1st-
edition-robert-g-bringle/

Hippocrates Now: The ‘Father Of Medicine’ In The


Internet Age 1st Edition Helen King

https://ebookmeta.com/product/hippocrates-now-the-father-of-
medicine-in-the-internet-age-1st-edition-helen-king/
Fidele Jenna Lynn Brown

https://ebookmeta.com/product/fidele-jenna-lynn-brown/
C and
Python
Applications
Embedding Python Code in C Programs,
SQL Methods, and Python Sockets

Philip Joyce
C and Python
Applications
Embedding Python Code in
C Programs, SQL Methods,
and Python Sockets

Philip Joyce
C and Python Applications: Embedding Python Code in C Programs, SQL Methods,
and Python Sockets

Philip Joyce
Crewe, UK

ISBN-13 (pbk): 978-1-4842-7773-7 ISBN-13 (electronic): 978-1-4842-7774-4


https://doi.org/10.1007/978-1-4842-7774-4

Copyright © 2022 by Philip Joyce


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Celestin Suresh John
Development Editor: James Markham
Coordinating Editor: Divya Modi
Cover designed by eStudioCalamar
Cover image designed by Pixabay
Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza,
New York, NY 10004. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or
visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is
Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware
corporation.
For information on translations, please e-mail [email protected]; for reprint, paperback,
or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book’s product page, located at www.apress.com/9781484277737. For more
detailed information, please visit http://www.apress.com/source-­code.
Printed on acid-free paper
Table of Contents
About the Author����������������������������������������������������������������������������������������������������� ix

About the Technical Reviewer��������������������������������������������������������������������������������� xi


Acknowledgments������������������������������������������������������������������������������������������������� xiii

Introduction�������������������������������������������������������������������������������������������������������������xv

Chapter 1: Python Programming������������������������������������������������������������������������������ 1


Definition of Variables������������������������������������������������������������������������������������������������������������������� 1
Real (Float) Numbers��������������������������������������������������������������������������������������������������������������� 5
Characters������������������������������������������������������������������������������������������������������������������������������� 6
Reading in Data����������������������������������������������������������������������������������������������������������������������������� 6
Arrays�������������������������������������������������������������������������������������������������������������������������������������������� 8
Inserting into an Array������������������������������������������������������������������������������������������������������������� 9
Deleting (Removing) from an Array��������������������������������������������������������������������������������������� 10
Searching������������������������������������������������������������������������������������������������������������������������������ 10
Updating an Array������������������������������������������������������������������������������������������������������������������ 11
Appending to an Array����������������������������������������������������������������������������������������������������������� 11
Strings����������������������������������������������������������������������������������������������������������������������������������������� 12
Lists�������������������������������������������������������������������������������������������������������������������������������������������� 14
Reading Entries in a List�������������������������������������������������������������������������������������������������������� 15
Updating a List����������������������������������������������������������������������������������������������������������������������� 16
Deleting an Element from List����������������������������������������������������������������������������������������������� 16
Appending to a List���������������������������������������������������������������������������������������������������������������� 16
Dictionaries��������������������������������������������������������������������������������������������������������������������������������� 17
Creating a Dictionary������������������������������������������������������������������������������������������������������������� 17
Appending to a Dictionary����������������������������������������������������������������������������������������������������� 17
Amending a Dictionary���������������������������������������������������������������������������������������������������������� 18

iii
Table of Contents

Deleting from a Dictionary����������������������������������������������������������������������������������������������������� 19


Searching Through a Dictionary�������������������������������������������������������������������������������������������� 19
Tuples������������������������������������������������������������������������������������������������������������������������������������������ 20
Creating a Tuple��������������������������������������������������������������������������������������������������������������������� 21
Concatenating Two Tuples����������������������������������������������������������������������������������������������������� 22
Creating Nested Tuples���������������������������������������������������������������������������������������������������������� 22
Creating Repeated Tuples������������������������������������������������������������������������������������������������������ 22
Converting a List or a String into a Tuple������������������������������������������������������������������������������� 23
Creating Single-Element Tuple���������������������������������������������������������������������������������������������� 23
Reading Tuple������������������������������������������������������������������������������������������������������������������������ 23
Searching Within a Tuple������������������������������������������������������������������������������������������������������� 23
Deleting a Tuple��������������������������������������������������������������������������������������������������������������������� 24
Using Tuple to Create Variables��������������������������������������������������������������������������������������������� 24
If Then Else��������������������������������������������������������������������������������������������������������������������������������� 25
Loops (For and While)����������������������������������������������������������������������������������������������������������������� 26
For Loops������������������������������������������������������������������������������������������������������������������������������� 26
While Loops��������������������������������������������������������������������������������������������������������������������������� 28
Switches������������������������������������������������������������������������������������������������������������������������������������� 29
Arithmetic Operations Using Numpy������������������������������������������������������������������������������������������� 30
Numpy Calculations��������������������������������������������������������������������������������������������������������������� 34
Mathematical Graph Functions��������������������������������������������������������������������������������������������������� 38
User-Written Functions��������������������������������������������������������������������������������������������������������������� 43
File Access���������������������������������������������������������������������������������������������������������������������������������� 45
Regressions�������������������������������������������������������������������������������������������������������������������������������� 52
Summary������������������������������������������������������������������������������������������������������������������������������������ 57
Exercises������������������������������������������������������������������������������������������������������������������������������������� 57

Chapter 2: C Programming������������������������������������������������������������������������������������� 59
C Program Format����������������������������������������������������������������������������������������������������������������������� 59
Adding Two Numbers������������������������������������������������������������������������������������������������������������������ 60
Multiply and Divide Two Numbers����������������������������������������������������������������������������������������������� 62
For Loops������������������������������������������������������������������������������������������������������������������������������������ 63
iv
Table of Contents

Do While Loops��������������������������������������������������������������������������������������������������������������������������� 65
Switch Instruction����������������������������������������������������������������������������������������������������������������������� 66
If Else������������������������������������������������������������������������������������������������������������������������������������������ 67
If Else If��������������������������������������������������������������������������������������������������������������������������������������� 68
Data Arrays��������������������������������������������������������������������������������������������������������������������������������� 70
Functions������������������������������������������������������������������������������������������������������������������������������������ 81
Strings����������������������������������������������������������������������������������������������������������������������������������������� 86
Structures����������������������������������������������������������������������������������������������������������������������������������� 88
Size of Variables�������������������������������������������������������������������������������������������������������������������������� 91
Goto Command��������������������������������������������������������������������������������������������������������������������������� 92
Common Mathematical and Logical Symbols����������������������������������������������������������������������������� 93
File Access���������������������������������������������������������������������������������������������������������������������������������� 94
Student Records File������������������������������������������������������������������������������������������������������������� 95
Summary���������������������������������������������������������������������������������������������������������������������������������� 105
Exercises����������������������������������������������������������������������������������������������������������������������������������� 106

Chapter 3: SQL in C����������������������������������������������������������������������������������������������� 107


Review of SQL and SQLite��������������������������������������������������������������������������������������������������������� 107
Creating the Database�������������������������������������������������������������������������������������������������������������� 108
Creating a Table������������������������������������������������������������������������������������������������������������������������ 110
Inserting Rows�������������������������������������������������������������������������������������������������������������������������� 113
Insert a Preset Row������������������������������������������������������������������������������������������������������������� 113
Inserting a User-Entered Row���������������������������������������������������������������������������������������������� 114
Selecting Rows������������������������������������������������������������������������������������������������������������������������� 117
Selecting a Row Preset������������������������������������������������������������������������������������������������������� 117
Selecting All Rows��������������������������������������������������������������������������������������������������������������� 120
Selecting Rows by Age�������������������������������������������������������������������������������������������������������� 122
Amending Rows������������������������������������������������������������������������������������������������������������������������ 125
Deleting Rows��������������������������������������������������������������������������������������������������������������������������� 128
Summary���������������������������������������������������������������������������������������������������������������������������������� 130
Exercises����������������������������������������������������������������������������������������������������������������������������������� 130

v
Table of Contents

Chapter 4: SQL in Python�������������������������������������������������������������������������������������� 131


Review of SQL��������������������������������������������������������������������������������������������������������������������������� 131
Create a Table���������������������������������������������������������������������������������������������������������������������� 133
Mechanism for Inserting a Row������������������������������������������������������������������������������������������� 134
Update a Row���������������������������������������������������������������������������������������������������������������������� 139
Delete a Row����������������������������������������������������������������������������������������������������������������������� 148
Read a Table������������������������������������������������������������������������������������������������������������������������ 149
Summary���������������������������������������������������������������������������������������������������������������������������������� 150
Exercises����������������������������������������������������������������������������������������������������������������������������������� 150

Chapter 5: Embedded Python������������������������������������������������������������������������������� 151


Basic Mechanism���������������������������������������������������������������������������������������������������������������������� 151
Plot a 2D Line���������������������������������������������������������������������������������������������������������������������������� 153
Plot Two 2D Lines���������������������������������������������������������������������������������������������������������������������� 155
Plot Trigonometric Curves��������������������������������������������������������������������������������������������������������� 158
Enter Data to Plot���������������������������������������������������������������������������������������������������������������������� 160
2D Center of Mass Plot������������������������������������������������������������������������������������������������������������� 170
Histograms�������������������������������������������������������������������������������������������������������������������������������� 177
Importing a Picture������������������������������������������������������������������������������������������������������������������� 179
Summary���������������������������������������������������������������������������������������������������������������������������������� 181
Exercise������������������������������������������������������������������������������������������������������������������������������������ 181

Chapter 6: Sockets����������������������������������������������������������������������������������������������� 183


A Closer Look at Sockets���������������������������������������������������������������������������������������������������������� 183
Basic Client-Server������������������������������������������������������������������������������������������������������������������� 185
Server-Client Pair to Send-Receive a File��������������������������������������������������������������������������������� 187
Threaded Programs������������������������������������������������������������������������������������������������������������������ 191
Closing Down a Threaded Server���������������������������������������������������������������������������������������������� 194
Chat Programs�������������������������������������������������������������������������������������������������������������������������� 197
Summary���������������������������������������������������������������������������������������������������������������������������������� 199
Exercise������������������������������������������������������������������������������������������������������������������������������������ 199

vi
Table of Contents

Appendix A: Answers to Examples����������������������������������������������������������������������� 201


C
 hapter 1���������������������������������������������������������������������������������������������������������������������������������� 201
Chapter 2���������������������������������������������������������������������������������������������������������������������������������� 206
Chapter 3���������������������������������������������������������������������������������������������������������������������������������� 212
Chapter 4���������������������������������������������������������������������������������������������������������������������������������� 219
Chapter 5���������������������������������������������������������������������������������������������������������������������������������� 223
Chapter 6���������������������������������������������������������������������������������������������������������������������������������� 228

Index��������������������������������������������������������������������������������������������������������������������� 231

vii
About the Author
Philip Joyce has 28 years of experience as a software engineer, working on control of
steel production, control of oil refineries, communications software (pre-Internet), office
products (server software), and computer control of airports. He programs in Assembler,
COBOL, Coral 66, C, and C++ with SQL. He served as a mentor to new graduates in the
Ferranti Company. He obtained an MSc in computational physics (including augmented
matrix techniques and Monte Carlo techniques using Fortran) from Salford University in
1996. He is also a chartered physicist and a member of the Institute of Physics (member
of the Higher Education Group).

ix
About the Technical Reviewer
Swathi Sutrave is a self-professed tech geek. She has been
a subject matter expert for several different programming
languages, including Python, C, and SQL, for corporations,
startups, and universities.

xi
Acknowledgments
Thanks to my wife, Anne, for her support, my son Michael, and my daughter Katharine.
All three have mathematics degrees. Thanks to everyone on the Apress team who helped
me with the publication of this, my third book.

xiii
Introduction
The C and Python programming languages are important languages in many computer
applications. This book will demonstrate how to use the C and Python languages to write
applications in SQL. It will demonstrate how to embed a Python program within a C
program. Finally, the reader will learn how to create Python socket programs which can
communicate with each other on different computers (these are called “sockets”).
A basic familiarity with mathematics is assumed along with some experience of the
basics of computer programs. The first two chapters review the basics of C and Python.
The chapters following these are grouped into SQL techniques, embedded Python, and
sockets applications. There are exercises in each chapter with answers and suggested
code at the end of the book.

xv
CHAPTER 1

Python Programming
This is the first of two chapters in which you’ll review both Python and C programming
languages. A basic understanding of computing and what programs are about is
assumed although no prior knowledge of either Python or C is needed.
In this chapter, we will start with the basics of Python. This will include how items
used in a program are stored in the computer, basic arithmetic formats, handling strings
of characters, reading in data that the user can enter on the command line, etc. Then
we will work up to file access on the computer, which will lead us up to industrial/
commercial-level computing by the end of the book.
If you don’t already have a Python development environment on your computer,
you can download it and the Development Kit, free of charge, from www.python.org/
downloads/. Another way you can access Python is by using Visual Studio. Again, a
version of this can be downloaded.

D
 efinition of Variables
This section looks at the different types of store areas that are used in Python. We refer
to these store areas as “variables.” The different types can be numbers (integers or
decimals), characters, and different types of groups of these (strings, arrays, dictionaries,
lists, or tuples).
In these examples, you can go to the command line and enter “Python” which starts
up the Python environment and produces “>>>” as the prompt for you to enter Python
code.

1
© Philip Joyce 2022
P. Joyce, C and Python Applications, https://doi.org/10.1007/978-1-4842-7774-4_1
Chapter 1 Python Programming

In Python, unlike C, you don’t define the variable as a specific type. The different
types are integer, floating point, character, string, etc. The type is assigned when you give
the variable a value. So try the following code:

>>> a1 = 51
>>> print(type(a1))
We get the output
<class 'int'>
>>>

Here we are defining a variable called “a1” and we are assigning the integer value 51
to it.
We then call the function “print” with the parameter “type” and “a1” and we get the
reply “class ‘int’”. “type” means that we want to display whether the variable is an integer,
floating point, character, string, etc.
We can now exit the Python environment by typing “quit()”.
We will now perform the same function from a program.
Create a file called “typ1a.py”.
Then enter the following two lines of Python code:

a1=51
print(type(a1))

Now on the command line, enter “python typ1a.py”.


And you should get the output

<class 'int'>

which is the same as our first example.


This is just demonstrating the equivalence of the two methods.
Obviously, if you want to run a program with many lines of code and possibly run it
many times, then having the code in a file is more efficient.
We can demonstrate different data types being stored in the same variable using the
following code:

a1=51
print(type(a1))

a1=51.6
print(type(a1))
2
Chapter 1 Python Programming

a1='51'
print(type(a1))

When we run this, we get

<class 'int'>
<class 'float'>
<class 'str'>

The 51 entered is an int. The 51.6 is a float (decimal) type, and ‘51’ is a string.
We can make the results a little clearer if we use print(“a1 is”, type(a1)).
So our program now reads

a1=51
print("a1 is",type(a1))

a1=51.6
print("a1 is",type(a1))

a1='51'
print("a1 is",type(a1))

and the output is

a1 is <class 'int'>
a1 is <class 'float'>
a1 is <class 'str'>

We can put a comment on our line of code by preceding it with the “#” character.

a1='51' #assign string containing 51 to variable a1


print("a1 is",type(a1)) # print the type assigned to a1

Some simple arithmetic operations are shown in the following.


The following code is held in the file “arith1.py”:

arith1a.py

Initialize the variables v1, v2, v3, and v4 with integer values.

v1= 2
v2 = 4
v3 = 7
v4 = 8
3
Chapter 1 Python Programming

Add v1 to v2 and store the result in v5.

v5 = v1 + v2
print(v5)

The result is

You can combine the adding with the print as follows:

print(v1+v2)

Giving the same answer:

Now a subtraction:

v6 = v4 - v3
print(v6)
giving
1

Now a multiplication:

v7 = v4 * v3

print(v7)
giving
56

Now a division:

v8 = v4 / v1
print(v8)
giving
4.0

v10 = v3 % v2 # the % sign means show the remainder of the division


print(v10)
gives
3

4
Chapter 1 Python Programming

Raise by the power 2.

v11 = v2 ** 2
print(v11)
gives
16

Raise to the power held in variable v1.


Here v2 contains 4 and v1 contains 2.

v11 = v2 ** v1
print(v11)
gives
16

Show how Python obeys the rules of BODMAS (BIDMAS).


Here v2 contains 4, v1 contains 2, v3 contains 7, and v4 contains 8.

v11 = v1 + v2 * v4 - v3 # show BODMAS


print(v11)
gives
27

Show how Python obeys the normal algebra rules.

v11 = (v1 + v2) * (v4 - v3)


print(v11)
gives
6

Real (Float) Numbers


This type of number contains a decimal point. So, for the following assignments

V1 = 2
V2 = 3.5
V3 = 5.1
V4 = 6.75

5
Chapter 1 Python Programming

we get

print(type(V1))
<class 'int'>
print(type(V2))
<class 'float'>
print(type(V3))
<class 'float'>
print(type(V4))
<class 'float'>

Characters
In Python, you can also assign characters to locations, for example:

c1 = 'a'
print(type(c1))
produces
<class 'str'>

which means that c1 is classed as a string.


Now that we know what different types of variables we can have, we will look at how
we use them.

Reading in Data
Now that we can display a message to the person running our program, we can ask them
to type in a character, then read the character, and print it to the screen. This section
looks at how the user can enter data to be read by the program.
If we type in the command

vara = input()

the computer waits for the user to type in data.


So if you now enter r5, the computer stores r5 in the variable vara.
You can check this by printing the contents of vara by typing

print(vara)

6
Chapter 1 Python Programming

which prints

r5

We can make this more explicit by using

print("data typed in is:-", vara)


giving
data typed in is:-r5

You can also make the entry command clearer to the user by entering

varb=input(“enter some data to be stored in varb”)

Then, again we can explicitly print out the contents

print("data typed in is:-", varb)


giving
data typed in is:-r5

You have to use int(input) to enter an integer.


Otherwise, it is a string (one or more characters), for example:

n = int(input('Enter a number: '))


you enter 4
>>> print(type(n))
<class 'int'>

# Program to check input


# type in Python

num = input ("Enter number :")


print(num)
#You could enter 5 here and it would store 5 as a string and not as a
number
>>> print(num)
5
>>> print ("type of number", type(num))
type of number <class 'str'>
>>>

7
Chapter 1 Python Programming

#entering a float number (type 'float' before the 'input' command)


n = float(input('Enter a number: '))
Enter a number: 3.8
>>> print(type(n))
<class 'float'>
>>> print(n )
3.8

Now that we can enter data manually into the program, we will look at groups of data.

Arrays
An array is an area of store which contains a number of items. So from our previous
section on integers, we can have a number of integers defined together with the same
label. Python does not have a default type of array, although we have different types of
array.
So we can have an array of integers called “firstintarr” with the numbers 2, 3, 5, 7,
11, and 13 in it. Each of the entries is called an “element,” and the individual elements
of the array can be referenced using its position in the array. The position is called the
“index.” The elements in the array have to be of the same type. The type is shown at the
beginning of the array.
The array mechanism has to be imported into your program, as shown as follows:

from array import *


firstintarr = array('i', [2,3,5,7,11])

The ‘i’ in the definition of firstintarr means that the elements are integers.
And we can reference elements of the array using the index, for example:

v1 = firstintarr[3]
print(v1)

This outputs

We can also define floating point variables in an array by replacing the “i” by “f” in
the definition of the array.

8
Chapter 1 Python Programming

So we can define

firstfloatarr = array( 'f', [0.2,4.3,21.9,7.7])

And we can now write

varfloat1 = firstfloatarr[1]
print(varfloat1)

This will store 4.3 into varfloat1.


The array mechanism has to be imported into your program.
So at the start of each program, you need to include the code

from array import *

Once we have our array, we can insert, delete, search, or update elements into the array.
Array is a container which can hold a fix number of items, and these items should
be of the same type. Most of the data structures make use of arrays to implement their
algorithms. The following are the important terms to understand the concept of array:

• Insert

• Delete (remove)

• Search

• Update

• Append

Let’s review them now.

Inserting into an Array


The following code is in the file array3.py:

from array import *

myarr = array('i', [2,3,5,7,11])

myarr.insert(1,13) # this inserts 13 into position 1 of the array (counting


from 0)

for x in myarr:
print(x)
9
Chapter 1 Python Programming

This outputs

2
13
3
5
7
11

Deleting (Removing) from an Array


The following code is in the source code file array4.py:
array4.py

from array import *

myarr = array('i', [2,3,5,7,11])

myarr.remove(2) # this removes the element containing 2 from the array

for x in myarr:
print(x)

This outputs

3
5
7
11

Searching
The following code is in the file array5.py:

from array import *

myarr = array('i', [2,3,5,7,11])

print (myarr.index(3))#this finds the index of the array which contains 3

10
Chapter 1 Python Programming

This outputs

Updating an Array
The following code is in the file array6.py:
array6.py

from array import *

myarr = array('i', [2,3,5,7,11])

myarr[2] = 17) #this updates element 2 with 17

for x in myarr:
print(x)

This outputs

2
3
17
7
11

Appending to an Array
The following code is in the file array9a.py:
array9a.py

from array import *

myarr = array('i', [2,3,5,7,11])

for x in myarr:
print(x)

new = int(input("Enter an integer: "))


myarr.append(new)
print(myarr)

11
Chapter 1 Python Programming

This outputs

2
3
5
7
11

Enter an integer: 19

array('i', [2, 3, 5, 7, 11, 19])

This section has shown the “array” use in Python.

Strings
Strings are similar to the character arrays we discussed in the previous section. They are
defined within quotation marks. These can be either single or double quotes. We can
specify parts of our defined string using the slice operator ([ ] and [:]). As with character
arrays, we can specify individual elements in the string using its position in the string
(index) where indexes start at 0.
We can concatenate two strings using “+” and repeat the string using “*”.
We cannot update elements of a string – they are immutable. This means that once
they are created, they cannot be amended.
The following code:

firststring = 'begin'
print(firststring)
gives
begin

The following code:

one = 1
two = 2
three = one + two
print(three)
#gives
3
12
Chapter 1 Python Programming

The following code:

first = " first "


second= "second"
concat = first + " " + second
print(concat)
#gives
first  second
print("concat: %s" % concat)
gives
concat:  first  second
The following code is in the file tst13a.py
secondstring = "second string"
print(secondstring.index("o")) #gives
3
print(secondstring.count("s")) # count the number of s characters in string
gives
2

print(secondstring[2:9]) # prints slice of string from 2 to 9 giving

cond st
print(secondstring[2:9:1]) #  The general form is [start:stop:step] giving

cond st
print(secondstring[::-1]) # Reverses the string giving

gnirts dnoces

splitup = secondstring.split(" ")


print(splitup) #gives
['second', 'string']

Strings are immutable, so if we tried

second= "second"
second[0]="q"

13
Chapter 1 Python Programming

we get

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: 'str' object does not support item assignment

indicating that we tried to update something (a string in this case) which is immutable.

Lists
Lists are similar to arrays and strings, in that you define a number of elements, which
can be specified individually using the index. With lists, however, the elements can be of
different types, for example, a character, an integer, and a float.
The following code is in the file alist7.py:

firstlist = ['k', 97 ,56.42, 64.08, 'bernard']

We specify the elements within square brackets.


We can then access individual elements in the list using the index (starting from 0),
for example:

print(firstlist[0])
gives
k
print(firstlist[1:3])
gives
[97, 56.42]

We can amend an element in a list.

firstlist[3] = 'plj'
print(firstlist)
giving
['k', 97, 56.42, 'plj', 'bernard']

14
Chapter 1 Python Programming

We can delete an element from a list.

del firstlist[3]
print(firstlist)
giving
['k', 97, 56.42, 'bernard']

We can append an element to the list.

firstlist.append(453.769)
print(firstlist)
giving
['k', 97, 56.42, 'bernard', 453.769]

Reading Entries in a List


The following code is held in the file alist1a.py:
alist1a.py

list1 = ['first', 'second', 'third']


list2 = [1, 2, 3, 4, 5 ]

print ("list1: ", list1)


print ("list1[0]: ", list1[0])
print ("list2: ", list2)
print ("list2[3]: ", list2[3])
print ("list2[:3]: ", list2[:3])
print ("list2[2:]: ", list2[2:])
print ("list2[1:3]: ", list2[1:3])

This outputs

list1:  ['first', 'second', 'third']


list1[0]:  first
list2:  [1, 2, 3, 4, 5]
list2[3]:  4
list2[:3]:  [1, 2, 3]
list2[2:]:  [3, 4, 5]
list2[1:3]:  [2, 3]

15
Chapter 1 Python Programming

Updating a List
The following code is held in the file alist2a.py:

alist2a.py

list1 = [1, 2, 3, 4, 5 ]

print ("list1: ", list1)

list1[1] = 26 #update the second item (counting from zero)

print ("updated list1: ", list1)

This outputs

list1:  [1, 2, 3, 4, 5]
updated list1:  [1, 26, 3, 4, 5]

Deleting an Element from List


The following code is held in the file alist3a.py:

alist3a.py
list1 = [1,2,3,4,5,6]
print (list1)
del list1[4]
print ("Updated list1 : ", list1)

This outputs

[1, 2, 3, 4, 5, 6]
Updated list1 :  [1, 2, 3, 4, 6]

Appending to a List
The following code is held in the file alist4aa.py:

alist4aa.py
list2 = [10,11,12,13,14,15]
print (list2)

16
Chapter 1 Python Programming

new = int(input("Enter an integer: "))


list2.append(new)
print(list2)

This outputs (if you enter 489)

[10, 11, 12, 13, 14, 15]

Enter an integer: 489

[10, 11, 12, 13, 14, 15, 489]

This has shown the use of lists.

Dictionaries
Dictionaries contain a list of items where one item acts as a key to the next. The list is
unordered and can be amended. The key-value relationships are unique. Dictionaries
are mutable.

Creating a Dictionary
In the first example, we create an empty dictionary. In the second, we have entries.

firstdict = {}

or

firstdict ={'1':'first','two':'second','my3':'3rd'}

Appending to a Dictionary
The following code is held in the file adict1a.py:

adict1a.py
#create the dictionary
adict1 = {'1':'first','two':'second','my3':'3rd'}

print (adict1)

17
Chapter 1 Python Programming

print (adict1['two'])   # in the dictionary 'two' is the key to 'second'

adict1[4] = 'four' # we want to add another value called 'four' whose key
is 4

print (adict1)

print (len(adict1)) #this will print the number of key-value pairs

This outputs

{'1': 'first', 'two': 'second', 'my3': '3rd'}


second
{'1': 'first', 'two': 'second', 'my3': '3rd', 4: 'four'}
4

If we want to add value whose key is dinsdale, then we specify it as ‘dinsdale’.


So

adict1['dinsdale'] = 'doug'
print (adict1)

outputs

{'1': 'first', 'two': 'second', 'my3': '3rd', 4: 'four', 'dinsdale': 'doug'}

Amending a Dictionary
The following code is held in the file adict2a.py.
This amends the value whose key is ‘two’ to be '2nd'.

adict2a.py
adict1 = {'1':'first','two':'second','my3':'3rd'}

adict1['two'] = '2nd'

print(adict1)

This outputs

{'1': 'first', 'two': '2nd', 'my3': '3rd'}

18
Chapter 1 Python Programming

Deleting from a Dictionary


The following code is held in the file adict3a.py:

adict3a.py
adict1 = {'1':'first','two':'second','my3':'3rd'}
print(adict1)
del adict1['two'] #this deletes the key-value pair whose key is 'two'
print(adict1)

This outputs

{'1': 'first', 'two': 'second', 'my3': '3rd'}


{'1': 'first', 'my3': '3rd'}

Searching Through a Dictionary


We want to search a dictionary to see if a specific key is contained in it. In this case, we
want to see if ‘a’ and ‘c’ are keys in the dictionary.
In Python

>>> my_dict = {'a' : 'one', 'b' : 'two'}

>>> 'a' in my_dict


TRUE
>>> 'c' in my_dict
FALSE

The following code is held in the file adict5aa.py:

adict5aa.py
print("Enter key to be tested: ")
testkey = input()
my_dict = {'a' : 'one', 'b' : 'two'}
print (my_dict.get(testkey, "none"))

This outputs (if you enter “a” when asked for a key)

Enter key to be tested:


a
one
19
Chapter 1 Python Programming

or outputs (if you enter “x” when asked for a key)

Enter key to be tested:


x
none

We have seen what dictionaries can do. We now look at tuples.

Tuples
A tuple contains items which are immutable. The elements of a tuple can be separated
by commas within brackets or individual quoted elements separated by commas. They
are accessed in a similar way to arrays, whereby the elements are numbered from 0. In
this section, we will look at creating, concatenating, reading, deleting, and searching
through tuples.
For example, define two tuples called firsttup and secondttup:

firsttup = ('a', 'b', 'c', 1, 2, 3)


secondtup = “a”, “b”, 10,  25

The following code refers to the third element of firsttup:

firsttup[2]
gives
c

The following code refers to the third element of firsttup:

firsttup[3]
gives
1
secondtup = "a", "b", 10,  25

The following code refers to the second element of secondtup:

secondtup[1]
gives
b

20
Chapter 1 Python Programming

The following code refers to the third element of secondtup:

secondtup[2]
gives
10

We can also use negative indices to select from the end and work backward, for
example,

secondtup[-1]

which gives

25
secondtup[-2]

which gives

10

Tuples cannot be amended.


So if we had

firsttup = ('a', 'b' 'c', 1, 2, 3)


firsttup[3] = 9

we would get

  File "<stdin>", line 1, in <module>

TypeError: 'tuple' object does not support item assignment

Creating a Tuple
# An empty tuple
empty_tuple = ()
print (empty_tuple)
()

# Creating non-empty tuples

# One way of creation


tup = 'first', 'second'
21
Chapter 1 Python Programming

print(tup)
('first', 'second')

# Another for doing the same


tup = ('first', 'second')
print(tup)
('first', 'second')

Concatenating Two Tuples


# Code for concatenating 2 tuples

tuple1 = (0, 1, 2, 3)
tuple2 = ('first', 'second')

# Concatenating above two


print(tuple1 + tuple2)
(0, 1, 2, 3, 'first', 'second')

Creating Nested Tuples


# Code for creating nested tuples

tuple1 = (0, 1, 2, 3)
tuple2 = ('first', 'second')
tuple3 = (tuple1, tuple2)
print(tuple3)
gives
((0, 1, 2, 3), ('first', 'second'))

Creating Repeated Tuples


# Code to create a tuple with repetition

tuple3 = ('first',)*3
print(tuple3)
gives
('first', 'first', 'first')

22
Chapter 1 Python Programming

Converting a List or a String into a Tuple


# Code for converting a list and a string into a tuple

list1 = [0, 1, 2]
print(tuple(list1))
(0, 1, 2)
print(tuple('first')) # string 'first'
('f', 'i', 'r', 's', 't')

Creating Single-Element Tuple


# Creating tuple with single element (note that we still require the comma)
t=(1,)
print(t)
gives
(1,)

Reading Tuple
# Reading from start (index starts at zero)
tup1=(2,3,4,5,6,7)
tup[3]
gives
5

# Reading from  end (index starts at -1)


tup1[-1]
gives
7

Searching Within a Tuple


# Search
tup1=(2,3,4,5,6,7)
print (6 in tup1) # this tests if 6 is contained in tup1
gives

23
Chapter 1 Python Programming

True
print (9 in tup1)
gives
False

Deleting a Tuple
# Deleting a complete Tuple
del tup1
print(tup1)
gives

NameError: name 'tup1' is not defined

Using Tuple to Create Variables


# define our tuple as
aTuple = (10, 20, 30, 40)
# Now we can assign each of its elements to separate variables
a, b, c, d = aTuple
print(a)
gives
10
print(b)
gives
20
print(c)
gives
30
print(d)
gives
40

We have covered definitions and uses of different types of variables in this section.
We will now look at the use of “if” statements.

24
Chapter 1 Python Programming

If Then Else


When a decision has to be made in your program to either do one operation or the other,
we use if statements.
These are fairly straightforward. Basically, we say

if (something is true)
        Perform a task

This is the basic form of if.


We can extend this to say

if (a condition  is true)
      Perform a task
else if it does not satisfy the above condition
      Perform a different task

Here is some Python code to demonstrate this:

number = 5
if number > 3:
   print('greater than 3')

number = 5
if number > 3:
   print('greater than 3')
else:
   print('not greater than 3')

Type in this code into a program and run it. It should come as no surprise that the
output is

greater than 3

You could modify the program so that you input the number to be tested, but don’t
forget that for this code you need number = int(input (“Enter number :”)) to enter a
number.
This section has shown the importance of “if” statements in programming. Now we
will look at loops.

25
Chapter 1 Python Programming

Loops (For and While)


When we were doing many calculations in a program, it could be a bit of a chore to do
a similar thing with, say, ten numbers. We could have done it by repeating similar code
ten times. We can make this a bit simpler by writing one piece of code but then looping
round the same piece of code ten times. This is called a “for loop.” We will also look at
“while” loops.

For Loops
Here is an example of how a for loop can help us.
The statement is

'for x in variable
     Carry out some code'

So if we have a variable as the following


forloopvar1 = [20, 13, 56, 9]
we can say

for x in forloopvar1: # go through forloop1 and place each element  in x


    print(x)  #this is the only instruction within the loop

outputs

20
13
56
9

The “range” instruction in Python has the general format


range(start, stop, step)
where
“start” is the start value of the index. Default is 0.
“stop” is 1 less than the last index to be used.
“step” is by how much the index is incremented. Default is 1.
Here is an example using the “range” instruction.
The program goes round the for loop starting with variables number and total set to 1.

26
Chapter 1 Python Programming

Within the loop, it multiplies the current value of the number by the running total. Then
it adds 1 to the number. So it is working out 1*2*3*4*5*6*7*8*9*10 or “10 factorial” (10!).

number = 1
total = 1
for x in range(10): ): #so here start is 0 (default), stop is 10-1, and
step is 1
         total = total * number
        number = number + 1
print(total)

This outputs

3628800

which you can check with your scientific calculator is 10 factorial.

for x in range(3, 6): # starts with 3 and ends with 6-1


    print(x)

This outputs

3
4
5

We can also have a list of values instead of a range, as shown in the next program.
This goes through the values and finds the index position of the value 46. We can see
that 46 is in position 9 (counting from 0).

forloopvar1 = [20, 13, 56, 9, 32, 19, 87, 51, 70, 46, 56]
count = 0
for x in forloopvar1:
     if x == 46:
           break
          count = count + 1
print(count)

This outputs

27
Chapter 1 Python Programming

While Loops
The logic of “while” loops is similar to our for loops.
Here, we say

'while x is true
      Carry out some code'

So we could have the following code which keeps adding 1 to count until count is no
longer less than 10. Within the loop, the user is asked to enter integers. These are added
to a total which is printed out at the end of the loop.

total = 0;
number = 0
# while loop goes round 10 times
while number < 10 :

      # ask the user to enter the integer number


      n = int(input('Enter a number: '))

      total = total + n
      number = number + 1
print('Total Sum is = ', total)

So if the user enters the number shown in the following, we get the total:

Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
Enter a number: 6
Enter a number: 7
Enter a number: 8
Enter a number: 9
Enter a number: 10
Total Sum is =  55

We have seen the importance of loops in this section. Our next section looks at
switches.

28
Chapter 1 Python Programming

Switches
In C programming, there is an instruction used widely called “switch.” However, because
there is no switch statement in Python, this section will demonstrate some code that can
be included into your programs to perform the same function.
A switch jumps to a piece of code depending on the value of the variable it receives.
For instance, if you had to perform different code for people in their 30s to that for
people in their 40s and different to people in their 50s, we could have the following code.
Here we have the value in “option” which determines which code we jump to.
The code for this function is in the file aswitch3.py:

aswitch3.py
def switch(option):
     if option == 30:
                print("Code for people in their 30s")
     elif option == 40:
                print("Code for people in their 40s")

     elif option == 50:

               print("Code for people in their 50s")

    else:
        print("Incorrect option")
#main code in the program where you enter 30,40 or 50 and the function
'switch' is called which uses the appropriate number as shown.
optionentered = int(input("enter your option (30, 40 or 50 : ) "))
switch(optionentered)
running this program and entering '50' gives
enter your option : 50
Code for people in their 50s

This section has shown how to perform a switch in Python. We now move onto an
important library of functions in Python. This is called “numpy.”

29
Chapter 1 Python Programming

Arithmetic Operations Using Numpy


Numpy is a library of mathematical functions that can be included into your Python
program. It is useful in manipulating arrays, reading text files, and working with
mathematical formulas. Numpy can be installed in various ways. One way is using “pip”
from the command line as shown as follows:

pip install numpy

It is particularly useful in manipulating matrices (or arrays with extra dimensions).


The arrays we have looked at so far are one-dimensional arrays. In this section, we will
look at arrays with more dimensions. A one-dimensional array can also be called a “rank
1 array.”

onedarray = array('i', [10,20,30,40,50])

We import numpy into our program using “import numpy”, and we assign a link for
our program. Here we define the link as “np” so the full line of code is

import numpy as np

The numpy function “shape” returns the dimensions of the array. So if your array
was defined as

b = np.array([[1,2,3],[4,5,6]])

then the array would be a 2x3 matrix (two rows and three columns) as shown as follows:

[[1 2 3]
[4 5 6]]

So if you now type

print(b.shape)

you would get

(2, 3)

as the shape.
The code for this function is in the file numpy1.py:

30
Chapter 1 Python Programming

import numpy as np

a = np.array([1, 2, 3])   # Create a rank 1 array


print(type(a))            # Prints "<class 'numpy.ndarray'>"
print(a.shape)            # Prints "(3,)"
print(a[0], a[1], a[2])   # Prints "1 2 3"
a[0] = 5                  # Change an element of the array
print(a)                  # Prints "[5, 2, 3]"

b = np.array([[1,2,3],[4,5,6]])    # Create a rank 2 array

#1 2 3
#4 5 6
# reference elements counting from 0
# so b[1, 2] is row 1 (2nd row) column 2 (3rd column)
#so if you print b[1, 2] you get 6
print("b[1, 2] follows")
print(b[1, 2])

print(b.shape)                     # Prints "(2, 3)" 2 rows 3 columns


print(b[0, 0], b[0, 1], b[0, 2])   # Prints "1 2 3"
print(b[1, 0], b[1, 1], b[1, 2])   # Prints "4 5 6"
print(b[0, 0], b[0, 1], b[1, 0])   # Prints "1 2 4"

The normal mathematical representation of a matrix is as shown as follows:

This is what we have defined in the preceding code using the following line of code:

b = np.array([[1,2,3],[4,5,6]])    # Create a rank 2 array

Matrix arithmetic can be understood by looking at real-life examples. The following


are tables of three people working for a computer company. The first table shows how
many laptops and how many printers each person sells in a month.

31
Chapter 1 Python Programming

In Store Sale

Person     Laptops     Printers
Joe         4          5
Mary        6         7
Jen         7          9

The next table shows how many laptops and printers each person has sold online.
Online Sale

Person     Laptops     Printers
Joe           6           22
Mary          21          24
Jen           41          17

These tables can be represented by matrices as shown in the following. We add each
term in the first matrix to the corresponding term in the second matrix to give the totals
shown in the third matrix.

The next table shows the total of laptops and printers sold by each person:
Total/Overall Sale

Person    Laptops     Printers
Joe         10          27
Mary        27         31
Jen         48          26

If each person doubles their total sales the following month, we can just multiply
their current sales total by 2 as shown as follows:

32
Chapter 1 Python Programming

We now look at their totals for the first month and have another table containing the
cost of a laptop and the cost of a printer.
Total Sales

Person      Laptops     Printers           Cost/Item list with cost


Joe          10          27                    Laptop          200
Mary         27          31                   Printer          25
Jen          48          26

We can work out how much money each person makes for the company my
multiplying their total number of sales of a laptop by its cost. Then we multiply their total
number of sales of printers by its cost and then add these two together. The table and the
corresponding matrix representations of this are shown as follows:

             Sales Cost
Joe         10x200 + 27x25 = 2975
Mary        27x200 + 31x25 = 3875
Jen         48x200 + 26x25 = 4775

There is a rule when multiplying matrices. The number of columns in the first matrix
has to be equal to the number of rows of the second matrix.
So if we say that a matrix is 2x3 (two rows and three columns), then it can multiply a
3x2 or a 3x3 or a 3.4, etc. matrix. It cannot multiply a 2x3 or 2x4 or 4x2 or 4x3, etc.

In the multiplication in the preceding diagram, we see it is (3x2) x (2x1) producing a


(3x1) matrix.

33
Exploring the Variety of Random
Documents with Different Content
the three ages of the Danes; though, on the other hand, he
relegates all the dolmens and such like monuments to a prehistoric
"Joter," or giant race, who preceded, according to his views, Odin
and his true Scandinavians, to whom he ascribes all the truly historic
monuments.
In addition to the difficulties arising from the paucity of information
regarding the monuments, the Scandinavians have not yet made up
their minds with regard to their early chronology. Even the vast
collections contained in the ponderous tomes of Langebeck and
Suhm[322] are far from sufficing for the purpose; and such authors
as Saxo Grammaticus[323] write with an easy fluency too
characteristic of our own Jeffrey of Monmouth, and others who bury
true history under such a mass of fables as makes it extremely
difficult to recover what we are really seeking for. Patient industry,
combined with judicious criticism, would, no doubt, clear away most
of the obscurities which now disfigure this page of mediæval history;
but, meanwhile, the Scandinavian annals are as obscure as the Irish,
and more uncertain than the contemporary annals of England.
Of the history of Scandinavia anterior to the Christian era, absolutely
nothing is known. It is now no longer admissible to believe in a
historic Odin, whom all the mediæval historians represent as living in
the first century B.C., and as the founder of those families who play
so important a part in the subsequent histories of our own as well as
of the whole group of Northern nations. The modern school of
Germans has discovered that Odin was a god who lived in the sky in
pre-Adamite times, and never condescended to visit our sublunary
sphere. It is now rank heresy to assume that during the thousand
years which elapsed between his pretended date and that of our
earliest MSS. the wild imaginings of barbarous tribes may not have
gathered round the indistinct form of a national hero, transferred
him back to a mythic age, and endowed him with the attributes and
surroundings of a god. As the Germans have decreed this, it is in
vain to dispute it, and not worth while to attempt it here, as for our
present purposes it is of the least possible consequence.
About the Christian era there is said to have been a king, called
Frode I., who, as he never was deified, may have had a tomb on
earth, and might, if that could be identified, be allowed to head our
list. Between him and Harald Harfagar, who, in 880, conquered
Norway and came into distinct contact with British history in the
Orkneys, we have several lists of kings, more or less complete, and
with dates more or less certain.[324] That there were kings in those
days, no one will probably dispute, nor perhaps is the succession of
the names doubtful; and if the dates err to the extent of even fifty
years or so, it is of little consequence to our argument. The
monuments extend so far down, and to kings whose dates are so
perfectly ascertained, that it is of no importance whether the earlier
ones are assigned to dates forty or fifty years too early or too late.
Their fixation may be left to future research, as it has no direct
bearing on the theory we are now trying to investigate.

Battle-fields.
The chief of the Scandinavian monuments, and the most interesting
for our present object, comprise those groups of stones which mark
battle-fields. Not only are their dates generally known with sufficient
precision to throw considerable light on the question of the antiquity
of such monuments in general, but they also illustrate, if they do not
determine, the use of many of the groups of stones we meet with in
other countries. Sjöborg devotes ten plates in his first volume to
these battle-fields, illustrating twice that number of battles which
occurred between the fifth and the twelfth centuries after Christ.
99. View of Battle-field at Kongsbacka. From Sjöborg.

The first of these, at Kongsbacka, near the coast in Halland, though


of somewhat uncertain date, is worth quoting from its similarity to
the alignments on Dartmoor, Ashdown, Karnac, and elsewhere,
though, unfortunately, no plan or dimensions are given. On the hills
beyond is a tumulus called the grave of Frode, and on the plain a
conspicuous stone bears his name; but whether this was Frode V.
(400) or some other Frode is not clear. Sjöborg assigns it to a date
about 500, and there seems very little reason to doubt he is at least
approximatively correct.[325]
The second battle-field illustrated is similar to the last, except in the
form of the stones, which seem to belong to a different
mineralogical formation.[326] They are plainly, however, seen to be
arranged in circles and lines, and are even more like forms with
which we are familiar elsewhere. It is said to represent a battle-field
in which the Swedish king Adil fought the Danish Snio, and in which
the latter with the chiefs Eskil and Alkil were slain. As all these
names are familiarly known in the mediæval history of these
countries there can be no great difficulty in ascribing this battle also
to about the same age as that at Kongsbacka.
With the third we tread on surer ground. No event in the history of
these lands is better known than the fight on the Braavalla Heath, in
Östergothland, where the blind old king, Harald Hildetand, met his
fate in the year 736, or 750 according to others. As the Saga tells
us, Odin had, when the king was young, taught him a form of tactics
which gave him a superiority in battle over all his enemies; but the
god having withdrawn his favour from him, he fell before the
prowess of his nephew, Sigurd Ring, to whom the god had
communicated the secret of the battle array. It does not appear to
admit of doubt that the circles shown in the cut in the opposite page
were erected to commemorate this event, and that they contain the
bodies of those who were slain in this action; and if this is so, it
throws considerable light on the battle-fields of Moytura, illustrated
woodcuts Nos. 54 to 61. The circles on Braavalla are generally from
20 to 40 feet in diameter, and consequently are, on the average,
smaller than those at Moytura; they are also more numerous, unless
we adopt Petrie's suggestion,[327] that there must originally have
been at least two hundred in the Irish field; and if so, it is the
smaller ones that would certainly be the first to be cleared away, so
that the similarity may originally have been greater than it now is—
so great, indeed, as to render it difficult to account for the fact that
two battle-fields should have been marked out in a manner so
similar when so long a time as seven centuries had elapsed between
them. As it does not appear possible that the date of the Braavalla
fight can be shifted to the extent of fifty years either way, are we
deceiving ourselves about Moytura? Is it possible that it represents
some later descent of Scandinavian Vikings on the west coast of
Ireland, and that the cairn on Knocknarea—

"High and broad,


By the sailors over the waves
To be seen afar,
The beacon of the war renowned"[328]—

which they built up during ten days—is really the grave of some
Northern hero who fell in some subsequent fight at Carrowmore?
That all these are monuments of the same class, and belong, if not
to the same people, at least to peoples in close contact with one
another, and having similar faiths and feelings, does not appear to
admit of doubt. When, however, we come to look more closely at
them, there are peculiarities about them which may account for even
so great a lapse of time. The Braavalla circles are smaller, and on the
whole perhaps, we may assume, degenerate. There are square and
triangular graves, and other forms, which, so far as we know, are
comparatively modern inventions, and, altogether, there are changes
which may account for that lapse of time; but that more than seven
centuries elapsed between the two seems to be most improbable.

100. Part of the Battle-field of Braavalla Heath. From


Sjöborg.

101. Harald Hildetand's Tomb at Lethra.[329]

To return, however, to King Hildetand. According to the saga, "After


the battle the conqueror, Sigurd Ring, caused a search to be made
for the body of his uncle. The body when found was washed and
placed in the chariot in which Harald had fought, and transported
into the interior of a tumulus which Sigurd had caused to be raised.
Harald's horse was then killed and buried in the mound with the
saddle of Ring, so that the king might at pleasure proceed to
Walhalla either in his chariot or on horseback. Ring then gave a
great funeral feast, and invited all the nobles and warriors present to
throw into the mound great rings and noble armour, in honour of the
king Harald. They then closed up the mound with care."[330] This
mound still exists at Lethra's Harald, capital in Seeland. It was
mentioned by Saxo Grammaticus in 1236,[331] and described and
drawn by Olaus Wormius in 1643;[332] and no one ever doubted its
identity, till recently the Museum authorities caused excavations to
be made. Unfortunately some "wedges of flint" have been found in
the earth which was extracted from the chamber, from which
Worsaae and his brother antiquaries at once concluded that "it is
beyond all doubt merely a common cromlech of the stone period"
[333] —a conclusion that seems to me the reverse of logical. No one,
I presume, doubts that King Hildetand was buried in a tumulus with
rings and arms; and if this tumulus was regarded historically as his,
for the last 600 years, and traditionally so from the time of his
death, it is incumbent upon the antiquaries to show how worthless
these traditions and histories are, and to point out where he really
rests. To form an empirical system and to assert—which they cannot
prove—that no flint implements were used after a certain prehistoric
date, and that consequently all mounds in which flint implements are
found are prehistoric, seems most unreasonable, to say the least of
it. It would be surely far more philosophical to admit that flint may
have been used down to any time till we can find some reason for
fixing a date for its discontinuance. In this instance an "instantia
crucis" would be to dig into some of the circles at Braavalla, and see
if any flints are to be found there. No metal was found at Moytura,
though metal was, if history is to be depended upon, then commonly
used, and flint implements were probably not found because those
who opened the tombs were not aware of its importance. Pending
this test, the form of the grave may give us some indication of its
age. It is an oblong barrow, with an external dolmen at one end,
and with a row of ten stones on each side, the two end ones being
taller than the rest. A similar mound, known as the Kennet long
barrow, exists at Avebury,[334] so similar indeed that if this tomb at
Lethra is historical so certainly is the English example. If, on the
other hand, either can be proved to belong to the long forgotten
past, the other must also he consigned to the same unsatisfactory
limbo.
The barrow at West Kennet was carefully explored in 1859 by Dr.
Thurnam, and the results of his investigation fully detailed in a paper
in the 'Archæologia,' vol. xxxviii., from which the following particulars
are abstracted, together with some others from a second paper, "On
Long Barrows," by the same author, in vol. xlii. of the same
publication.
Externally it is a mound measuring 336 feet in length by 75 feet at
its broadest part. Originally it was surrounded by what is called a
peristalith of tall stones, between which, it is said, a walling of
smaller stones can still be detected. On its summit, as at Lethra, was
an external dolmen over the principal chamber of the tomb. The
chamber was nearly square in form, measuring 8 feet by 9, and
approached by a passage measuring 15 feet by 3 feet 6 inches in
width; and its arrangement is in fact the same as that of the Jersey
tumulus (woodcut No. 11), and, as Sir John Lubbock remarks, "very
closely resembles that of a tumulus" he had just been describing, of
the Stone age, in the island of Möen, "and, in fact, the plan of
passage graves generally."[335]
102. Long Barrow, Kennet, restored by Dr. Thurnam.
'Archæologia,' xlii.

When opened, six original interments were found in the chamber,


under a stratum of black, sooty, greasy matter, 3 to 9 inches in
thickness, and which, Dr. Thurnam remarks, "could never have been
disturbed since the original formation of the deposit" (p. 413). Two
of these had their skulls fractured during lifetime; the others were
entire. To account for this, Dr. Thurnam takes considerable pains to
prove that slaves were sometimes sacrificed at the funeral of their
masters, but he fails to find any instance in which they were killed
by breaking their heads; and if they were to serve their master in
the next world, even a savage would be shrewd enough to know
that cracking his skull was not the way to render him useful for
service either in this world or the next. No such mode of sacrifice
was ever adopted, so far as I know.[336] But supposing it was so, all
the six burials in this tomb seem to have been nearly equal, and
equally honourable, and why, therefore, all their skulls were not
broken is not clear. If on the other hand we assume that it is the
grave of six persons who were slain in battle, two by blows on the
head, and four by wounds in the body, this surely would be a
simpler way of accounting for the facts observed. Even, however, if
we were to admit that these men with the broken heads were
sacrificed, this would by no means prove the grave to be prehistoric.
Quite the contrary, for we know from the indisputable authority of a
decree of Charlemagne that human sacrifices were practised by the
pagan Saxons as late, certainly, as 789,[337] and were sufficiently
frequent to constitute one of the first crimes against which he
fulminated his edicts. The fact is that neither historians nor
antiquaries seem quite to realise the state of utter barbarism into
which the greater part of Europe was plunged between the collapse
of the Roman Empire and the revival of order under Charlemagne.
Christianity no doubt had taken root in some favoured spots, and
some bright lights shone out of the general darkness, but over the
greater part of Europe pagan rites were still practised to such an
extent as easily to account for any heathen practice or any ancient
form of sepulture which may be found anywhere existing.
To return, however, to our long barrow. Under a piece of Sarsen
stone, but on the skull of one of the principal persons interred here
(No. 4), were found two pieces of black pottery (fig. 8, page 415),
which Dr. Thurnam admits may be of the Roman age. Other
fragments of the same vessel were found in other parts of the tomb,
and also fragments of pottery (figs. 14 to 17), not British, but to
which he hesitates to assign an age. So far as I can judge, it seems
just such pottery as the less experienced British potters would form,
on Roman models, after the departure of that people. But this is
immaterial; for beyond the chamber, and deeper consequently into
the tumulus, were found fragments of undoubted Roman pottery. So
far, therefore, everything favours the view that it was the sepulchre
of persons slain in battle, after the departure of the Romans; for we
can hardly believe that a battle would be fought, and such a tomb
raised over the slain, during their occupation; and if so, as the
pottery proves it could not be before, a choice of a date is fixed
within very narrow limits. It may either have been in 450,
immediately after the departure of the Romans, or in 520, the date
of the battle of Badon Hill, which is the time at which, I believe, it
was reared. So far as the general argument is concerned, it is of no
consequence which date is chosen. Against this conclusion we have
to place the following facts. First, no trace of iron or bronze, or of
metal of any sort, was found in the tomb. Secondly, at least 300 flint
fragments were found in it. Some of these were mere chippings,
some cones, but many were fairly formed flint implements (figs. 10
to 13),[338] not belonging to the oldest type, but such as antiquaries
are in the habit of ascribing to the pre-metal Stone age. In addition
to these, the quantity of coarse native pottery was very remarkable.
No whole vessels were found, but broken fragments that would form
fifty vessels were heaped in a corner; and there were corresponding
fragments in another corner. Dr. Thurnam tries to explain this by
referring to the passage in the grave scene in 'Hamlet,' where our
great dramatist speaks of "shards, flints, and pebbles," which should
be thrown into the graves of suicides; the use of which, he adds, "in
mediæval times may be a relic of paganism." It does not, however,
seem to occur to him that, if such a custom was known in the
sixteenth century, it would be likely to have been in full force in the
sixth. It is strange enough that such a custom, even if only referred
to suicides, should have survived a thousand years of such
revolutions and changes of religion as England was subjected to in
those days; but that it should be known to Christians, after 3000 or
4000 years' disuse, seems hardly possible.
No argument, it appears to me, can be drawn from the different
kinds of pottery found in the tomb. If any one will take the trouble of
digging up the kitchen midden of a villa built within the last ten
years, in a previously uninhabited spot, he will probably find
fragments of an exquisite porcelain vase which the housemaid broke
in dusting the drawing-room chimney-piece. He will certainly find
many fragments of the stoneware used in the dining-room, and with
them, probably, some of the coarser ware used in the dairy, and
mixed with these innumerable "shards" of the flower-pots used in
the conservatory. According to the reasoning customary among
antiquaries, this midden must have been accumulating during 2000
or 3000 years at least, because it would have taken all that time, or
more, before the rude pottery of the flower-pots could have been
developed into the exquisite porcelain of the drawing-room vase.
The argument is, in fact, the same as that with respect to the flints.
It may be taken for granted that men used implements of bone and
stone before they were acquainted with the use of metal; but what
is disputed is that they ceased to use them immediately after
becoming familiar with either bronze or iron. So with earthenware:
men no doubt used coarse, badly formed, and badly burnt pottery
before they could manufacture better; but, even when they could do
so, it is certain that they did not cease the employment of pottery of
a very inferior class; and we have not done so to the present day. To
take one instance among many. There are in the Museum of the
Society of Antiquaries at Edinburgh a series of vessels, hand-made
and badly burnt, and which might easily be mistaken—and often are
—for those found in prehistoric tombs. Yet they were made and used
in the Shetland Islands in the last and even in the present century.
The truth of the matter seems to be that, as in the case of a find of
coins, it is the date of the last piece that fixes the time of the
deposit. There may be coins in it a hundred or a thousand years
older, but this hoard cannot have been buried before the last piece
which it contains was coined. So it is with this barrow. The presence
of Roman or post-Roman pottery in an avowedly undisturbed
sepulchre fixes, beyond doubt, the age before which the skeletons
could not have been deposited where they were found by Dr.
Thurnam. The presence of flints and coarse pottery only shows, but
it does so most convincingly, how utterly groundless the data are on
which antiquaries have hitherto fixed the age of these monuments.
It proves certainly that flints and shards were deposited in tombs in
Roman or post-Roman times; and if there is no mistake in Dr.
Thurnam's data, this one excavation is, by itself, sufficient to prove
that the Danish theory of the three ages is little better than the
"baseless fabric" of—if not "a vision"—at least of an illusion, which,
unless Dr. Thurnam's facts can be explained away, has no solid
foundation to rest upon.
If any systematic excavations had been undertaken in the
Scandinavian long barrows, it would not, perhaps, be necessary to
adduce English examples to illustrate their age or peculiarities.
Several are adduced by Sjöborg, but none are reported as opened.
This one, for instance, is externally like the long barrow at West
Kennet, and, if Sjöborg's information is to be depended upon, is one
of several which mark the spot where Frode V. (460-494) landed in
Sweden, where a battle was fought, and those who fell in it were
buried in these mounds, or where the Bauta stones mark their
graves. If this is so, the form of the long barrow with its peristalith
was certainly not unknown in the fifth century; and there is no
improbability of its being employed in England also in that age. In
settling these questions, however, the Scandinavians have an
immense advantage over us. All their mounds have names and
dates; they may be true or they may be false, but they give a
starting-point and an interest to the enquiry which are wanting in
this country, but which, it is hoped, will one day enable the
Northmen to reconstruct their monumental history on a satisfactory
basis.

103. Long Barrow at Wiskehärad, in Halland. From a


drawing by Sjöborg.

In most cases antiquaries in this country have been content to


appeal to the convenient fiction of secondary interments to account
for the perplexing contradictions in which their system everywhere
involves them. In the instance of the Kennet long barrow there is no
excuse for such a suggestion. All the interments were of one age,
and that undoubtedly the age of the chamber in which they were
found, and the pottery and flints could not have been there before
nor introduced afterwards. Indeed, I do not know a single instance
of an undoubtedly secondary interment, unless it is in the age of
Canon Greenwell's really prehistoric tumuli. When he publishes his
researches, we shall be in a condition to ascertain how far they bear
on the theory.[339] In the chambered tumuli secondary interments
seem never to occur; and nothing is more unlikely than that they
should. As Dr. Thurnam himself states: "In three instances at least
Mr. Cunnington and Sir R. C. Hoare found in long barrows skeletons
which, from their extended position and the character of the iron
weapons accompanying them, were evidently Anglo-Saxon."[340] A
simple-minded man would consequently fancy that they were Anglo-
Saxon graves, for what can be more improbable than that the proud
conquering Saxons would be content to bury their dead in the
graves of the hated and despised Celts whom they were busy in
exterminating.[341]
If the above reasoning is satisfactory and sufficient to prove that the
long barrow at West Kennet is of post-Roman times, it applies also
to Rodmarton, Uley, Stoney Littleton, and all the Gloucestershire
long barrows which, for reasons above given (ante, page 164), we
ventured to assign to a post-Roman period; and à fortiori it carries
with it King Hildetand's tomb at Lethra. It is true we have not the
same direct means of judging of its date as we have of our own
monuments. The Danes treat with such supreme contempt any
monument that does not at once fall in with their system, that they
will not even condescend to explore it. So soon as Worsaae found
some "flint wedges" in the tomb, he at once decreed that it was
prehistoric, and that it was no use searching farther; and we are
consequently left to this fact and its external similarities for our
identification. Here, again, is a difficulty. The two drawings above
given (woodcuts Nos. 101 and 102) may show them too much alike
or exaggerate differences. The one is an old drawing from nature,
the other a modern restoration; still the essential facts are
undoubted. Both are chambered long barrows, ornamented by rows
of tall stones, either partially or wholly surrounding their base, and
both have external dolmens on their summit, and both contain flint
implements. If this is so, the difficulty is rather to account for so little
change having taken place in 230 years than to feel any surprise at
their not being identical. The point upon which we wish to insist here
is that they are both post-Roman, and may consequently belong to
any age between Arthur and Charlemagne.
The remaining battle-fields of which representations are given in
Sjöborg are scarcely so interesting as that at Braavalla, which with
the tomb of the king slain there are landmarks in our enquiry. If
those circles on Braavalla Heath do mark the battle-field, and that
tomb at Lethra is the one in which the blind old king was laid—
neither of which facts I see any reason for doubting—all difficulties
based on the assumed improbability of the monuments being so
modern as I am inclined to make them are removed, and each case
must stand or fall according to the evidence that can be adduced for
or against its age. To return, however, to the battle-fields given by
Sjöborg. Figures 43 and 44 represent two groups of circles and
Bauta stones near Hwitaby, in Malmö. These are said to mark two
battle-fields, in which Ragnar Lothbrok gained victories over his
rebellious subjects in Scania: Sjöborg says in 750 and 762, as he
adopts a chronology fifty years earlier than Suhm. But be this as it
may, there does not seem any reason for doubting but that these
stones do mark fields where battles were fought in the eighth
century, and that Ragnar Lothbrok took part in them. These groups
are much less extensive than those at Braavalla, but are so similar
that they cannot be distant from them in age.
At Stiklastad, in Norway, in the province of Drontheim, a battle was
fought, in 1030, between Knut the Great and Olof the Holy; and
close to this is a group of forty-four circles of stones, which Sjöborg
seems, but somewhat doubtfully, to connect with this battle. But
about the next one (fig. 49) there seems no doubt. The Danish
prince Magnus Henricksson killed Erik the Holy, and was slain by Carl
Sverkersson, in the year 1161, at Uppland, in Denmark; and the
place is marked by twenty stone circles and ovals, most of them
enclosing mounds and two square enclosures, 30 to 40 feet in
diameter. They are not, consequently, in themselves very important,
but are interesting, if the adscription is correct, as showing how this
heathenish custom lasted even after Christianity must have been
fairly established in the country. Another group (fig. 51) is said to
mark the spot where, in 1150, a Swedish heroine, Blenda, overcame
the Danish king Swen Grate, and the spot is marked by circles and
Bauta stones; one, in front of a tumulus, bears a Runic inscription,
though it merely says that Dedrik and Tunne raised the stone to
Rumar the Good.
Only one other group need be mentioned here. On a spot of land, in
the island of Freyrsö, off the entrance of the Drontheim Fiord, in the
year 958, Hakon, the son of Harald Harfagar, overthrew his
nephews, the sons of Erik Blodoxe, in three battles. The first and
second of these, as shown in the plan (woodcut No. 104), are
marked by cairns and mounds; and the third by eight large barrows,
three of which are of that shape known in Scandinavia as ship
barrows, and measure from 100 to 140 feet in length. There are also
three tumuli at 4 in the woodcut, in one of which one of Erik
Blodoxe's sons is said to be buried. It is not clear whether the five
large mounds that stud the plain do not cover the remains of those
also who fell in this fight. It does not appear that any excavations
have been made in them. The interest of this battle-field to us is not
so much because it shows the persistence of this plan of marking
battle-fields at so late a date—later ones have just been quoted—but
because all the actors in the scene are familiar to us from the part
they took in the transactions in the Orkneys in the tenth century. If
they, in their own country, adhered to these old-world practices, we
should not be astonished at their having erected circles or buried in
mounds in their new possessions. It is true that none of these
Scandinavian circles can compare in extent with the Standing Stones
of Stennis or the Ring of Brogar, but this would not be the first time
that such a thing has happened. The Greeks erected larger and, in
proportion to the population, more numerous Doric temples in Sicily
than they possessed in their own country; and the Northmen may
have done the same thing in Orcadia, where they possessed a
conquered, probably an enslaved, race to execute these works.
104. Battle-field at Freyrsö. From Sjöborg, vol. i. pl. 16.

Tumuli.
The number of sepulchral mounds in Scandinavia is very great, and
some of them are very important; but, so far as I can ascertain, very
few have been explored, and, until interrogated by the spade,
nothing can well be less communicative than a simple mound of
earth. A map of their distribution might, no doubt, throw
considerable light on the ethnography of the country, and tell us
whether the Finns or Lapps were their original authors, or whether
the Slaves or Wends were their introducers; and, lastly, whether the
true Scandinavians brought them with them from other lands, or
merely adopted them from the original inhabitants, in which case
they can only be treated as survivals. Funereal pomp, or tomb-
building of any sort, is so antagonistic to the habits of any people so
essentially Teutonic as the Scandinavians were and are, that we
cannot understand their adopting these forms, or indeed stone
circles or monuments of any class, in a country where they had not
previously existed. If we assume that the modern Scandinavians
were German tribes who conquered the country from the Cimbri or
the earlier Lapps and Finns, and did so as warriors, bringing no
women with them, the case is intelligible enough. Under these
circumstances, they must have intermarried with the natives of the
country, and would eventually, after a few generations, lose much of
their individual nationality, and adopt many of the customs of the
people among whom they settled, using them only in a more
vigorous manner and on a larger scale than their more puny
predecessors had been able to adopt.[342] It is most improbable that
the "Northmen," if Germans—as indeed their language proves them
to be—should ever have invented such things as tumuli, dolmens,
circles, or any other such un-Aryan forms, in any country where they
had not existed previously to their occupying it; but that as
immigrants they should adopt the customs of the previous occupants
of the land is only what we find happening everywhere. The
settlement of these points will be extremely interesting for the
ethnography of Northern Europe, and ought not to be difficult
whenever the problem is fairly grappled with. In the meanwhile, all
that the information at present available will enable us to do here is
to refer to some tumuli whose contents bear more or less directly on
the argument which is the principal object of this work.
The first of these is the triple group at Upsala, now popularly known
as the graves of Thor, Wodin, and Freya. It may illustrate the
difficulty of obtaining correct information regarding these
monuments to state that, even so late as 1869, Sir John Lubbock,
who is generally so well informed, and had such means of obtaining
information, did not know that they had been opened.[343] I was
aware of a passage in Marryatt's travels in Sweden in which, writing
on the spot, he asserts that one of them had been opened, and that
"in its 'giant's chamber' were found the bones of a woman, and,
among other things, a piece of a gold filagree bracelet, richly
ornamented in spiral decoration, some dice, and a chessman, either
the king or a knight."[344] Wishing, however, for further information,
I obtained an introduction to Mr. Hans Hildebrand, who gave me the
following information. Subsequently I received a letter from
Professor Carl Säve, of Upsala, who kindly abstracted for me the
only published accounts of the excavations as they appeared in a
local paper at the time. These were forwarded to me by Professor
Geo. Stephens, of Copenhagen, who also was so obliging as to
translate them. They are so interesting that I have printed them, as
they stand, as Appendix B. From these two documents the following
account is compiled, and may be thoroughly depended upon.
One of the mounds, known as that of Wodin, was opened, in 1846,
under the superintendence of Herr Hildebrand, the royal antiquary of
Sweden. It was soon found that the mounds were situated on a
ridge of gravel, so that the tunnel had to take an upward, direction.
At the junction of the natural with the artificial soil, a cairn was
found of closely compacted stones, each about as large as a man
could lift. In the centre of the cairn the burial urn was found in the
grave-chamber, containing calcined bones, ashes, fragments of
bronze ornaments destroyed by fire, and a fragment of a gold
ornament delicately wrought. Within the cairn, but a little away from
the urn, were found a heap of dogs' bones, equally calcined by fire,
and fragments of two golden bracteates. "The workmanship of the
gold ornaments," Herr Hildebrand adds, "closely resembles that of
the gold bracteates of the fifth or sixth centuries, and, with the
fragments of these peculiar ornaments themselves, settles a date
before which these mounds could not have been raised." How much
later they may be, it is not easy to conjecture, without at least
seeing the bracteates, which do not seem to have been published.
With a little local industry, I have very little doubt, not only that the
date of these tombs could be ascertained, but the names of the
royal personages who were therein buried, probably in the sixth or
seventh century of our era.
"The tombs of Central Sweden," Herr Hildebrand adds, "are
generally constructed in the same way, the urn containing the bones
being placed on the surface of the soil, at the place of cremation or
elsewhere, as the case may be. Generally, nothing is found with
them but an iron nail, or some such trifling object"—a curious and
economical reminiscence of the extravagant customs of their
predecessors. According to him, "almost every village in Sweden,
with the exception of those in some mountain-districts and the most
northern provinces, has a tomb-field quite close to the side of the
houses. The antiquities found in the mounds of these tomb-fields all
belong to the Iron age. The tombs of the earlier ages have no
connection with the homesteads of the present people."
How far these tombs extend downwards in date cannot be
ascertained without a much more careful examination than they
have yet been subjected to. It may safely, however, be assumed that
they continued to be used till the conversion of the inhabitants to
Christianity, and probably even for some considerable time
afterwards, for such a custom is not easily eradicated.
It would be as tedious as unprofitable to attempt to enumerate the
various mounds which have been opened, for their contents throw
little or no light on our enquiry; and being distributed in cases in the
museum, not according to their localities or traditions, but according
to their systematic classes, it is almost impossible to restore them
now to their places in history.
105. Dragon on King Gorm's Stone, Jellinge. From 'An.
Nord. Oldkund.' xii. 1852.

At Jellinge, however, on the east coast of Jutland, there are two


mounds, always known traditionally as those of Gorm the Old and
his queen Thyra Danebod—the Beloved. The date of Gorm's death
seems now to be accepted as 950 A.D.;[345] but it is not clear
whether he erected the tomb himself, or whether it is due to the
filial piety of his son Harald Blaatand, or Blue-Tooth, and in which
case its date would be 968.[346] Saxo Grammaticus at least tells us
that he buried his mother in the tumulus, and then set a whole army
of men and oxen at work to remove from the Jutland shore an
immense stone—a little rock—and bring it to the place where his
mother lay inhumed.[347] That stone still exists, and has sculptured
on one side a dragon, which calls forcibly to our mind that found on
Maes-Howe (woodcut No. 85), and on the other side a figure, which
is, no doubt, intended to represent Christ on the cross. On the two
sides are Runic inscriptions, in which he records his affection for his
father and mother and his conversion to the Christian faith.
So far as I can ascertain, the tomb of King Gorm has not yet been
opened. That of Thyra was explored many years ago—in 1820
apparently; but no sections or details have been published, so that it
is extremely difficult to ascertain even the dimensions. Engelhardt
reports the height as 43 feet, and the diameter as 240 feet;[348]
Worsaae gives the height as 75 feet, and the diameter as 180 feet,
and he is probably correct.[349] But in Denmark anything that cannot
be put into a glass case in a museum is so completely rejected as
valueless that no one cares to record it. When entered, it was found
that it had been plundered probably in the middle ages, and all that
remained were the following articles:—A small silver goblet, lined
with gold on the inside, and ornamented with interlaced dragons on
the exterior; some fibulæ, tortoise-shaped, and ornamented with
fantastic heads of animals; some buckle-heads, and other objects of
no great value. The chamber in which these objects were found
measured 23 feet in length by 8 feet 3 inches in width, and was 5
feet high;[350] the walls and roof, formed of massive slabs of oak,
were originally, it appears, hung with tapestries, but these had
nearly all perished.
Not only are these monuments of Gorm and Thyra interesting in
themselves, and deserving of much more attention than the Danes
have hitherto bestowed upon them, but they are most important in
their bearing on the general history of monuments of this class. In
the first place, their date and destination are fixed beyond dispute,
and this being so, the only ground is taken away on which any à
priori argument could be based with regard to the age of any mound
anterior to the tenth century. As soon as it is realised that sepulchral
mounds have been erected in the tenth century, it is impossible to
argue that it is unlikely or improbable that Silbury Hill or any other
mound in England may not belong to the sixth or any subsequent
century down to that time. The argument is, however, even more
pertinent with reference to Maes-Howe and other tumuli in the
Orkneys. If the Scandinavian kings were buried in "howes" down to
the year 1000—I believe they extend much beyond that date—it is
almost certain that the Orcadian Jarls were interred in similar
mounds down at least to their conversion to Christianity (A.D. 986).
Whether Maes-Howe was erected as a sepulchre for the sons of
Ragnar Lothbrok, as John Stuart seems to infer from the inscriptions,
[351] or of Havard Earl, as I have above attempted to show, is of
little consequence to the general argument. That it was the grave of
a Scandinavian Jarl, erected between 800 and 1000 A.D., seems
quite certain, and my own impression is that it is almost as certainly
the tomb of the individual Jarl to whom I have ventured to ascribe it.
As before mentioned, no argument against these views can be
drawn from the fact that Thyra's tomb is lined with slabs of oak,
while the chamber at Maes-Howe is formed with stone. The
difference of the two localities is sufficient to account for this.
Denmark has always been famous for its forests, and especially on
the shores of the Baltic, at Jellinge, wood of the noblest dimensions
was always available, whereas the stone of the country was hard
and intractable. In the Orkneys, on the other hand, there is
absolutely no timber of natural growth big enough to afford a good-
sized walking-stick, and stone is not only everywhere abundant, but
splits easily into slabs, self-faced, and most easily worked, so that
stone, and stone only, would be the material employed in the
Orkneys for that purpose, as wood would also be the best and most
available material in Denmark.
If, before leaving this branch of the subject, we turn back for a few
minutes to the Irish monuments, we are now in a position to judge
more correctly of the probabilities of the case than we were.
Assuming the three-chambered tumulus at New Grange to have
been erected between the years 200 and 400, and Maes-Howe and
Jellinge between 800 and 1000 A.D., we have a period of from five
to six, it may possibly be seven, centuries between these
monuments. Is this more than is sufficient to account for the
difference between them, or is it too little? It is not easy to give a
categorical answer to such a question, but judging from the
experience gained from other styles, in different parts of the world,
the conclusion generally would be that the time is in excess of what
is required. That there was progress, considerable progress indeed,
made in the interval between the Irish and Scandinavian
monuments, cannot be denied, but that it should have required five
centuries to achieve this advance is hardly what would be expected,
and it would be difficult to quote another example of a progress so
slow. Yet it is hardly possible to bring down New Grange to the age
of St. Patrick (A.D. 436), and as difficult to carry back Maes-Howe
beyond Ragnar Lothbrok (794 at the extreme), and between these
dates there are only 358 years; but we must certainly add something
at either one end or the other; and if we do this, we obtain an
amount of progress so slow that it would be almost unaccountable,
but upon the assumption that they are the works of two different
peoples. At the time the sepulchre on the Boyne was erected,
Ireland was energetically and rapidly progressive, and her arts were
more flourishing than might have been expected from her then state
of civilization. When Maes-Howe was erected, the native population
was poor and perishing, and as the lordly Vikings would hardly
condescend to act as masons themselves, they did the best they
could with the means at their disposal. Explain it, however, as we
may, it seems impossible to allow a longer time between the mounds
at Jellinge and Stennis and those on the Boyne than has been
accorded above; and as it seems equally difficult to bring them
nearer to one another, the probability seems to be in favour of the
dates already assigned to them.
To return, however, from this digression; besides those just
mentioned, Denmark possesses a nearly complete series of royal
tombs such as are not to be found in any other country of Europe.
Even Worsaae acknowledges the existence of that of Frode
Frodegode, who lived about the Christian era, of Amlech, near Wexio
—Shakespeare's Hamlet, of Humble, and Hjarne,[352] besides those
of Hildetand, and Gorm and Thyra, already mentioned. If the Danes
would only undertake a systematic examination of these royal
sepulchres, it might settle many of the disputed points of mediæval
archæology. To explore tombs to which no tradition attaches may
add to the treasures of their museums, but can only by accident
elucidate either the history of the country or the progress of its arts.
If ten or twelve tombs with known names attached to them were
opened, one of two things must happen: either they will show a
succession and a progress relative to the age of their reputed
occupants, or no such sequence will be traceable. In the first case
the gain to history and archæology would be enormous, and it is an
opportunity of settling disputed questions such as no other country
affords. If, on the other hand, no such connection can be traced,
there is an end of much of the foundations on which the reasoning
of the previous pages is based, but in either case such an enquiry
could not fail to throw a flood of light on the subject which we were
trying to elucidate. The fear is that all have been rifled. The
Northmen certainly spared none of the tombs in the countries they
conquered, and our experience of Maes-Howe and Thyra's tomb
would lead us to fear that after their conversion to Christianity they
were as little inclined to spare those of their own ancestors. All they
however cared for were the objects composed of precious metals; so
enough may still be left for the less avaricious wants of the
antiquary.

Dolmens.
So far as is at present known, there are not any tumuli of
importance or any battle-fields marked with great stones in the
north of Germany; but the dolmens there are both numerous and
interesting, and belong to all the classes found in Scandinavia, and,
so far as can be ascertained, are nearly identical in form. Nothing,
however, would surprise me less than if it should turn out that both
barrows and Bauta stones were common there, especially in the
island of Rügen and along the shores of the Baltic as far east as
Livonia. The Germans have not yet turned their attention to this
class of their antiquities. They have been too busy sublimating their
national heroes into gods to think of stones that tell no tales.
Whenever they do set to work upon them, they will, no doubt, do it
with that thoroughness which is characteristic of all they attempt.
But as the investigation will probably have to pass through the solar
myth stage of philosophy, it may yet be a long time before their
history reaches the regions of practical common sense.
No detailed maps having been published, it is extremely difficult to
feel sure of the distribution of these monuments in any part of the
northern dolmen region; but the following, which is abstracted from
Bonstetten's 'Essai sur les Dolmens,' may convey some general
information on the subject, especially when combined with the map
(p. 275), which is taken, with very slight modifications, from that
which accompanied his work.
According to Bonstetten there are no dolmens in Poland, nor in
Posen. They first appear on the Pregel, near Königsberg; but are
very rare in Prussia, only two others being known, one at
Marienwerder, the other at Konitz. In Silesia there is one at Klein-
Raden, near Oppeln; another is found in the district of Liegnitz, and
they are very numerous in the Uckermark, Altmark, in Anhalt, and
Prussian Saxony, as well as in Pomerania and the island of Rügen.
They are still more numerous in Mecklenburg, which is described as
peculiarly rich in monuments of this class. Hanover possesses
numerous dolmens, except in the south-eastern districts, such as
Göttingen, Oberharz, and Hildesheim. To make up for this, however,
in the northern districts, Lüneburg, Osnabrück, and Stade, at least
two hundred are found. The grand-duchy of Oldenburg contains
some of the largest dolmens in Germany; one of these, near
Wildesheim, is 23 feet long; another, near Engelmanns-Becke, is
surrounded by an enclosure of stones measuring 37 feet by 23, each
stone being 10 feet in height, while the cap stone of a third is 20
feet by 10. In Brunswick there were several near Helmstädt, but
they are now destroyed. In Saxony some rare examples are found as
far south as the Erzgebirge, and two were recently destroyed in the
environs of Dresden. Keeping along the northern line, we find them
in the three northern provinces of Holland, Gröningen, Ober-Yssel,
and especially in Drenthe, where they exist in great numbers, but
none to the southward of these provinces, and nowhere do they
seem to touch the Rhine or its bordering lands; but a few are found
in the grand-duchy of Luxembourg as in a sort of oasis, halfway
between the southern or French dolmen region and that of northern
Germany.
From the North German districts they extend through Holstein and
Schleswig into Jutland and the Danish isles, but are most numerous
on the eastern or Baltic side of the Cimbrian peninsula, and they are
also very frequent in the south of Sweden and the adjacent islands.
Dolmens properly so called are not known in Norway, but, as above
mentioned, cairns and monuments of that class, are not wanting
there.
The value of this distribution will be more easily appreciated when
we have ascertained the limits of the French field, but meanwhile it
may be convenient to remark that, unless the dolmens can be traced
very much further eastward, there is a tremendous gulf before we
reach the nearest outlyers of the eastern dolmen field. There is a
smaller, but very distinct, gap in the country occupied by the Belgæ,
between it and the French field, and another, but practically very
much smaller one, between it and the British isles. This is a gap
because the intervening space is occupied by the sea; but as it is
evident from the distribution of all the northern dolmens in the
proximity to the shores and in the islands that the people who
erected them were a sea-faring people, and as we know that they
possessed vessels capable of navigating these seas, it is practically
no gap at all. We know historically how many Jutes, Angles, Frisians,
and people of similar origin, under the generic name of Saxons,
flocked to our shores in the early centuries of the Christian era, and
afterwards what an important part the Danes and Northmen played
in our history, and what numbers of them landed and settled in
Great Britain, either as colonists or conquerors, at different epochs,
down to at least the eleventh century. If, therefore, we admit the
dolmens to be historic, or, in other words, that the erection of
megalithic monuments was practised during the first ten centuries
after the Christian era, we have no difficulty in understanding where
our examples came from, or to whom they are due. If, on the other
hand, we assume that they are prehistoric, we are entirely at sea
regarding them or their connection with those on the continent. The
only continental people we know of who settled in Britain before the
Roman times were the Belgæ, and they are the only people between
the Pillars of Hercules and the Gulf of Riga who, having a sea-board,
have also no dolmens or megalithic remains of any sort. All the
others have them more or less, but the Northern nations did not, so
far as we know, colonise this country before the Christian era.

As all the Northern antiquaries have made up their minds that these
dolmens generally belong to the mythic period of the Stone age, and
that only a few of them extend down to the semi-historic age of
bronze, it is in vain to expect that they would gather any traditions
or record any names that might connect them with persons known
in history. We are, therefore, wholly without assistance from history
or tradition to guide us either in classifying them or in any attempt
to ascertain their age, while the indications which enable us to
connect them with our own, or with one another, are few and far
between.

Вам также может понравиться