验证六度分隔定理 用python 写一段代码 需导入电脑中的数据
时间: 2024-10-11 19:10:28 浏览: 50
六度分隔理论(Six Degrees of Separation),也称为小世界现象,指的是人们通过最多六个人的连接就可以和其他任何一个陌生人建立联系。为了演示这个原理并编写Python代码,我们可以创建一个简单的社交媒体网络节点(people)和他们的朋友列表,然后模拟寻找两个随机用户之间的最短路径。
首先,假设我们有一个CSV文件存储了用户的网络信息,其中包含两列:`user_id` 和 `friends`。这代表每个用户的ID及其关联的朋友ID列表。下面是一个简单的Python脚本示例:
```python
import csv
from collections import defaultdict
# 导入数据
def load_data(file_name):
user_graph = defaultdict(list)
with open(file_name, 'r') as file:
reader = csv.reader(file)
next(reader) # 跳过表头
for row in reader:
user_graph[row[0]].extend(row[1].split(','))
return user_graph
# 模拟寻找路径
def find_path(user_1, user_2, graph):
visited = set()
queue = [(user_1, [])] # 开始队列,初始节点和空路径
while queue:
current_user, path = queue.pop(0)
if current_user == user_2:
return path + [current_user]
visited.add(current_user)
for friend in graph[current_user]:
if friend not in visited:
queue.append((friend, path + [current_user]))
# 使用函数
file_name = "your_data.csv" # 替换为你电脑上实际的文件名
graph = load_data(file_name)
start_user = input("请输入起始用户ID:")
end_user = input("请输入目标用户ID:")
if start_user in graph and end_user in graph:
path = find_path(start_user, end_user, graph)
print(f"从 {start_user} 到 {end_user} 的最短路径是:{path}")
else:
print("用户不在网络中或者输入错误,请确认.")
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)