blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
9b61e058456fea325b31a8c0b8dd1147386ca13c
Abdul-Nassar/Think-Python-Class
/Class-Exercises/move_rectangle.py
1,057
3.765625
4
import sys import copy import math import rectangle def distance_bw_points(p1, p2): dx = p1.x - p2.x dy = p1.y - p2.y dist = math.sqrt(dx**2 + dy**2) return dist def move_rect(rect, dx, dy): rect.corner.x +=dx rect.corner.y +=dy def move_rect_copy(rect, dx, dy): new = copy.deepcopy(rect) move_rect(new, dx, d...
b43c445e44ff002790bcacde8a5875a5e26e2bd6
Asana-sama/Learn3
/Task2.py
873
3.75
4
# Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: # имя, фамилия, год рождения, город проживания, email, телефон. # Функция должна принимать параметры как именованные аргументы. # Реализовать вывод данных о пользователе одной строкой. def exe_1(**user): return list(u...
f9b878398930791cbfa962ac6b395d0a89b3907c
AlexSin63/labi
/lab1_4_v5.py
1,334
4
4
# Лабораторная №1 задание 4 вариант 5 # Для каждого четного по номеру элемента списка A найти его # сумму со следующим элементом и записать эти суммы в новый список B. import random n = int(input("Введите количество элементов в списке:\n")) r0 = int(input("Введите минимальное значение элемента в списке:\n")) rn = int...
6a6a358206c08443f0d06f34d337308840980a05
KahlilMonteiro-lpsr/class-samples
/problemset4.py
4,635
4.03125
4
# shapeDrawer.py # draws user-input shapes in random places on the screen # with random sizes and colors # bring in the packages of functions we need import random import turtle # -------- functions start here ---------------- # make a triangle with random length, color and position with angle of 120 def regular_tr...
8a7ca63588fe433cec479c98a6d7fa6d5dca3efe
KahlilMonteiro-lpsr/class-samples
/drawTeeFigure.py
514
3.78125
4
import turtle def drawTee(myTurtle): count = 0 while count < 4: drawFourTees(myTurtle) count = count + 1 def drawFourTees(myTurtle): myTurtle.forward(200) myTurtle.backward(50) myTurtle.right(90) myTurtle.forward(50) myTurtle.backward(100) myTurtle.forward(50) myTurtle.right(90) myTurtle.forward(150) ...
432837c767c5e70345065bb820fdd03c531c671d
KahlilMonteiro-lpsr/class-samples
/remotecontrol.py
1,451
4.28125
4
import turtle from Tkinter import * # create the root Tkinter window and a Frame to go in it root = Tk() frame = Frame(root) # create our turtle shawn = turtle.Turtle() # create a design myTurtle = turtle.Turtle() def pentagon(myTurtle, size): five = 0 myTurtle.color('green') while five < 5: myTurtle.forward(10...
dbc3d6ff6ae5f905ba23aa3ac062cd6151703825
moon0331/FluentPython
/1장. 파이썬 데이터 모델/1.2 특별 메서드는 어떻게 사용되나?.py
926
4.125
4
from math import hypot class Vector: def __init__(self, x=0, y=0): self.x = x self.y = y def __repr__(self): return 'Vector(%r %r)' % (self.x, self.y) # 문자열 명확해야, 가능하면 표현된 객체를 재생성하는 데 필요한 소스와 동일해야 # __repr__ vs __str__ : 둘중 하나만 구현해야 한다면 __repr__ 구현해라 # __str__ 구...
a9749426f2af289805d94f2848db84097c5c6502
bhayru01/Python-Exercises
/findMissingElement.py
2,760
4.21875
4
""" Find the Missing Element Problem Consider an array of non-negative integers. A second array is formed by shuffling the elements of the first array and deleting a random element. Given these two arrays, find which element is missing in the second array. Here is an example input, the first array is shuffled and...
cbd9192592af59a2f5e6c63dd93344c32c5c1fc1
bhayru01/Python-Exercises
/Queue_With_2_Stacks.py
869
4.3125
4
""" Implement a Queue - Using Two Stacks Use a Python list data structure as your Stack. """ ##This class implements a Queue using two Stacks # class Queue2Stacks(): def __init__(self): self._stack1 = [] self._stack2 = [] def enqueue(self, element): self._stack1.append(element) # AP...
aaa2319d84c1a28e98881ce6cf86f6e7096b83a4
ShroukMansour/Musicly
/Models/Artist.py
1,218
3.5625
4
import sqlite3 from SqliteDB.sqlite import sqlite class Artist(): # con = sqlite3.connect("E:\FCI\Fourth year\Concepts\Assignments\Musicly\SqliteDB\musicly_new.db") con = sqlite3.connect("C:\\Users\\Aya Essam\\anaconda3\\MusiclyNew\\Musicly\\SqliteDB\\musicly_new.db") c = con.cursor() def __init__(se...
8917d91c407a0268edb9e8ac147ca639f4abfba6
PeterSzakacs/convnet_euso
/src/net/samples/mnist.py
2,505
3.625
4
""" Convolutional Neural Network for MNIST dataset classification task. References: Y. LeCun, L. Bottou, Y. Bengio, and P. Haffner. "Gradient-based learning applied to document recognition." Proceedings of the IEEE, 86(11):2278-2324, November 1998. Links: [MNIST Dataset] http://yann.lecun.com/exdb/mnist...
94e1456803e501fa9bc9c67f4aa25b54efa9c6b4
PeterSzakacs/convnet_euso
/src/utils/common_utils.py
3,861
3.53125
4
import collections import numpy as np # functions to check if a passed value represents an interval with an upper and # lower bound. Legal types of value include: # - (tuple or list) of int (length 2) # - numpy.ndarray with shape (2) # - range(object) -> the upper and lower bounds correspond to start and stop p # ...
e9ac26a9555125adeb6acbb17e38c4b40f0b3498
cervthecoder/scratch_code
/begginning_cerv/piskovrky_backup.py
5,491
3.671875
4
grid = [ ["", "", ""], ["", "", ""], ["", "", ""] ] x = False taken_positions = ["[1][1]", "[1][2]", "[1][2]", "[2][2]", "[3][2]", "[1][3]", "[2][3]", "[3][3]", "[1][1]"] def lock_position_1(): global x_input_1 global y_input_1 global taken_positions if ("[" + x_input_1 + "]" + "[" + y...
3be017184746f02ff625589fa3214eba87453903
cervthecoder/scratch_code
/begginning_cerv/variables.py
225
3.84375
4
name_1 = "Jack" name_2 = "Ted" count_1 = "60" count_2 = "50" print("" +name_1+ " had "+count_1+" apples") print(""+name_2+" had "+count_2+ " apples") print("how many did they have together?") print("they've had 55 apples")
4b6a626795c358ac9f6be79456066eb7f6628b63
cervthecoder/scratch_code
/begginning_cerv/Intermediate_lists.py
670
4
4
lucky_numbers = [5, 8, 11, 20, 24, 31, 43, 43] #some random numbers friends = ["John", "Mike", "David", "Danny", "Joel", "Karen"] #random people friends2 = friends.copy() #copy the list friends.append("Creed") #this add something on the end of the list friends.insert(1, "Robin") #this will add it into the list and d...
8cd445b934f8a6c70fea03f393f3028a8c8ae81a
Codefreak69/Number_Guessing_game
/main.py
823
3.890625
4
import random randNmber = random.randint(1,100) Guess = 0 userGuess = None while(userGuess != randNmber): userGuess = int(input("Enter your Guess: ")) Guess += 1 if userGuess == randNmber: print("EUREKA!!!!!!!!You guessed it right!!") else: print("BRUHHH!!! You guessed the ...
aeab455542fbd0e94424b5ad24e3c2917f661565
Kyrylo-Kotelevets/HangmanGame
/hangman.py
2,076
3.90625
4
from word_generator import * class Hangman: """ Class with main functions for Hangman game """ FILLER = '_' def __init__(self): self.__game_over = None self.__word = list(get_random_word()) self.__mask = [Hangman.FILLER] * len(self.__word) self.__guessed_letters = set() ...
8233f51e5dbdb300ea9ad9cbdc5ea20185a2d849
faultuser/self.code
/algorithm/sorts/selection_sort.py
833
3.96875
4
# ============================================================================= # Author: falseuser # Created Time: 2019-10-29 17:31:50 # Last modified: 2019-10-29 17:47:24 # Description: 选择排序 # 从前往后扫描,找到未排序序列中的最小值,然后放到已排序序列的末尾 # ============================================================================= def sort(c...
815cb8ea3630da0b5093e2cc3172e45c4a3e2fe6
faultuser/self.code
/leetcode/013/13.py
1,010
3.546875
4
# ============================================================================= # Author: falseuser # Created Time: 2019-06-27 10:25:54 # Last modified: 2019-06-27 10:32:30 # Description: 13.py # ============================================================================= class Solution: def romanToInt(self, s: ...
2d24d8c10ac38bf987ced780e25cc0ccbb95b186
faultuser/self.code
/algorithm/sorts/insertion_sort.py
858
4.0625
4
# ============================================================================= # Author: falseuser # Created Time: 2019-10-29 15:50:52 # Last modified: 2019-10-29 16:06:37 # Description: 插入排序 # 从后向前比较,已排序的放在前面 # ============================================================================= def sort(collection): #...
da2273764e16e40836a36a75986642f0d94f2d15
maiconbischoff/aulasPython
/app_python/aula11.py
835
4.125
4
#trabalhando com exceptions lista = [1, 10] arquivo = open('teste.txt', 'r') try: texto = arquivo.read() divisao = 10 / 0 #numero = lista[3] #x = a #print('fechando arquivo') #arquivo.close() except ZeroDivisionError: #classe do python de exception por divisao por zero print('Nao é possivel ...
4a5a31bc09ead701c93b6198acf89daa9e813920
abhishektayal/casebook
/post_indexing.py
1,194
3.765625
4
import string import re def stop_words(word_list,stop_words_list): line_stop_words = [] #stop_words = "a","i","it","am","at","on","in","of","to","is","so","too","my","the","and","but","are","very","here","even","from","them","then","than","this","that","though" #this part removes the stop words for the li...
b9319500e28875f92a12b4edfd71f6d65f93a735
elducati/bootcampcohort19
/max_min_number.py
459
4.125
4
def find_max_min(num_list): for i in num_list: max_num = max(num_list) #finds the maximum number on the list min_num = min(num_list) #finds the minimum number on the list # assigns to variable max_min_num the list of the result of max_num and min_num max_min_num = [min_num, max_num]...
f409cc2cabc3ce0768766a01871e5891fdd72c51
elducati/bootcampcohort19
/binary_search.py
913
3.640625
4
class BinarySearch(): def __init__(self, the_length, step): self.alist = [i for i in range(0 + step, the_length * step, step)] self.length = the_length self.step = step self.first = 2 self.last = self.length self.counter = 0 self.found = False sel...
1eaf60824aaebadf2c42a774a768ee214f027e2f
mutterbucket/NetworkSecurity
/OneTimePad/OneTimePad.py
860
3.84375
4
alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' '] print("Welcome to the One Time Pad key finder!") ciphertext = input("Enter your ciphertext: \n") ciphertext = ciphertext.upper() plaintext = input("Enter the pla...
1b49d3f00a7da312d00d331b653a47319d0395e9
RimerAPY/Python
/task_1_6.py
446
4
4
#Задача «Следующее и предыдущее» #Условие #Напишите программу, которая считывает целое число и выводит текст, #аналогичный приведенному в примере (пробелы важны!). a=int(input()) print('The next number for the number',a,'is',str(a+1)+'.') print('The previous number for the number',a,'is',str(a-1)+'.')
e22f80e05f125ab61184fafc9b8a1517da79313b
vansssa/python_assignment
/assignment8.py
91
3.53125
4
def fib() : a,b = 0,1 while b > 0 : yield b a,b = b,a + b f = fib() print f.next()
7582890d60e4b0c0eea7ad4494bcc4ee2e2c751f
NayaradeSousa/first-steps
/Beginner/kickanumber.py
1,218
4.1875
4
""" Generating a value randomly, keeps that value, and gives the user five chances to guess the value generated. """ import random as rd if __name__ == '__main__': while True: print("Would you like to guess the number I drew? [Y/N]") answer = input() if answer == "N" or answer == "n": ...
84153f583e7368b7fb3ea7f4cb2d359699d25b89
Akbhobhiya/Algorithms-DSA
/lab0/prob4.py
579
4.125
4
n=int(input('Enter the size of Array:')) list=[] for i in range(n): a=int(input()) list.append(a) def bubble(list): for i in range(n): for j in range(n): if list[j]>list[i]: x=list[i] list[i]=list[j] list[j]=x def selection(list): for i in range(n): p=list[i] for j in range(n): if list[j]>li...
817037df34e5ecbdb0aab5a42a9a1b2e6db55471
Akbhobhiya/Algorithms-DSA
/lab2/problem2.py
692
4.03125
4
class Stack: # A constructor that initialises an empty stack def __init__(self): self.elements = [] # Push item on the Stack def push(self,item): self.elements.append(item) # Pop the Stack def pop(self): return self.elements.pop() # Check if the Stack has any it...
6334a887eec637d9f936cf4d316ba66558999ceb
valenca/coverage
/Docs/hilbert.py
2,146
3.640625
4
#!/usr/bin/env python """ turtle-example-suite: tdemo_fractalCurves.py This program draws two fractal-curve-designs: (1) A hilbert curve (in a box) (2) A combination of Koch-curves. The CurvesTurtle class and the fractal-curve- methods are taken from the PythonCard example scripts for turtle-graphics. "...
7735ecc467f58aad78a9820e65c73001017262ce
CODavies/Python_Dietel
/Chapter2/Investment_Return.py
193
3.78125
4
p = int(input("Enter your principal amount: ")) r = 0.07 n = int(input("Enter your number of years: ")) rate = (1 + r) ** n a = p * rate print("Your amount at the end of ", n, "years is: ", a)
8d0378315f403fc4732c91761c5ff2fe4cf697ee
dsqx71/flow_stereo
/data/dataset.py
28,555
3.53125
4
import glob import os from PIL import Image import cv2 import numpy as np from .config import cfg from . import data_util TAG_FLOAT = 202021.25 TAG_CHAR = 'PIEH' class DataSet(object): """The base class of a dataset. The formats and organizations of datasets are often different from each other. The design ...
cde144632b9035e56f5a8d7f4d57e9d62509add9
Zyufin/spellcheck
/wordgen.py
1,179
3.734375
4
#!/usr/bin/env python import sys sys.path.append('~/Downloads') import spellcheck as spellchecker import random def gen_word(word): vowels = set(['a','e','i','o','u','y']) char_list = list(word) length = len(char_list) p = 1.0 / length for i in range(length): if random.random() <= p: ...
fb537648d07c0e951a0f03d8c0a51f899b55cf10
rbyelyy/simple_code_challenges
/codeeval/matrix_rotation.py
529
3.59375
4
# coding=utf-8 import sys def read_from_file(path): """ Sum of company_name_for_converting.txt in the file :rtype : object """ with open(path, 'r') as infile: return [_ for _ in infile] if __name__ == "__main__": # file_content = read_from_file('/Users/rbyelly/Downloads/sandbox/myre...
fcb0a868ebb7f023829cc0ce92cbdd1b061e4ed5
rbyelyy/simple_code_challenges
/hackerrank/candals.py
1,172
4.125
4
# -*- coding: utf-8 -*- """ You are in-charge of the cake for your niece's birthday and have decided the cake will have one candle for each year of her total age. When she blows out the candles, she’ll only be able to blow out the tallest ones. Your task is to find out how many candles she can successfully blow out. F...
9ec8c0b86d5889af5a2dd705a44ab1b5bda2ae7e
rbyelyy/simple_code_challenges
/hackerrank/time_format.py
668
3.953125
4
#!/bin/python """ Given a time in -hour AM/PM format, convert it to military (24-hour) time. Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock. """ from __future__ import print_function # !/bin/python from __future...
b9e4c10b979fa60930900e3e7f65ba652cdcd345
Naveenramkumar/DataAnalysisUsingPython
/PythonFinalExam/Analysis/Analysis3.py
3,939
3.59375
4
#Analysis 3: Predict the gases mean in future - Based on Linear regression import matplotlib.pyplot as plt import calendar import pylab as pl import pandas as pd from datetime import datetime import argparse import sys import csv if len(sys.argv) != 2: print("Invalid call to the script : Please provide year and mon...
4edc554ec85cc8d072d2a37911320d81c5ce9ee4
somming/data-structure-with-python
/Algorithm/stack_problem_3_2.py
851
3.953125
4
# push와 pop 두 가지 연산과 함께 최솟값을 반환하는 min을 갖춘 스택을 구현 # push, pop, min은 O(1)시간에 처리되도록 구현하시오 class Stack: def __init__(self): self.container = list() self.minnum = None #들어올때마다 최솟값을 비교하여 갱신 def push(self,data): self.container.append(data) if not self.minnum: self.minnum = data elif data < self.minnum: se...
c2b04aacb85340b4ac919e918b76c2948eed0378
somming/data-structure-with-python
/DataStructure/queue.py
453
3.875
4
class Queue: def __init__(self): self.container = list() def push(self,data): self.container.append(data) def pop(self): return self.container.pop(0) def empty(self): if not self.container: return True else: return False def peek(self): return self.container[0] if __name__ == "__main__"...
e4dc2a34f6a2aaa88a5db8dd8f1ff23cd8d351ca
jbgour/Multi_Agent_Systems_Negotiation_Project
/communication/preferences/CriterionValue.py
716
3.984375
4
#!/usr/bin/env python3 class CriterionValue: """CriterionValue class. This class implements the CriterionValue object which associates an item with a CriterionName and a Value. """ def __init__(self, item, criterion_name, value): """Creates a new CriterionValue. """ self.__item...
683da5c1f2200a3dea6124f31eb4d3e2ee1f9e7a
Duck-the-dev/HangMan
/main.py
1,691
3.9375
4
import random import words import art # Step 1 word_list = words.word_list logo = ''' _ | | | |__ __ _ _ __ __ _ _ __ ___ __ _ _ __ | '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \ | | | | (_| | | | | (_| | | | | | | (_| ...
061eb67854c629786d82b2c0eedcd77240448f22
ABHIINAV12/project-euler
/Summation of primes.py
251
3.859375
4
def isprime(a): if a==2: return 1 if a%2==0: return 0 curr=2 while(curr*curr<=a): if a%curr==0: return 0 curr+=1 return 1 def main(): ans=0 for i in range(2,2000000): if isprime(i): ans+=i print(ans) main()
790d98e00bb0145128e134623287e9008f58d3a6
lirui-ML/my_leetcode
/Algorithms/162_Find_Peak_Element/Find_Peak_Element.py
2,327
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 描述:寻找峰值(难度:medium) 峰值元素是指其值大于左右相邻值的元素。 给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。 数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。 你可以假设 nums[-1] = nums[n] = -∞。 示例 1: 输入: nums = [1,2,3,1] 输出: 2 解释: 3 是峰值元素,你的函数应该返回其索引 2。 示例 2: 输入: nums = [1,2,1,3,5,6,4] 输出: 1 或 5 解释: ...
6497eb5e5b26c12a8110b2f9f89ea39180af30c9
lirui-ML/my_leetcode
/Algorithms/15_3Sum/3Sum.py
1,864
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 描述:三数之和 (难度:中等) 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。 注意:答案中不可以包含重复的三元组。 示例: 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/3sum 著作权归领...
18351b102250c725708807d91ec94f88fba7a31f
lirui-ML/my_leetcode
/Interview/01_04.py
1,670
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 描述:回文排列(easy) 给定一个字符串,编写一个函数判定其是否为某个回文串的排列之一。 回文串是指正反两个方向都一样的单词或短语。排列是指字母的重新排列。 回文串不一定是字典当中的单词。 示例1: 输入:"tactcoa" 输出:true(排列有"tacocat"、"atcocta",等等) """ class Solution: def canPermutePalindrome(self, s: str) -> bool: """借助hashmap数据结构""" from...
d9545e0e4a0b421fab40e826209948701fb25343
lirui-ML/my_leetcode
/Algorithms/113_Path_Sum_II/Path_Sum_II.py
3,530
3.84375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 描述:路径总和 II 给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。 说明: 叶子节点是指没有子节点的节点。 示例: 给定如下二叉树,以及目标和 sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 返回: [ [5,4,11,2], [5,8,...
c034609793204dc7f47fa0ffd8280b3c3fa74c20
lirui-ML/my_leetcode
/Algorithms/120_Triangle/Triangle.py
2,122
3.828125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 描述:三角形最小路径和,难度(medium) 给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。 例如,给定三角形: [ [2], [3,4], [6,5,7], [4,1,8,3] ] 自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。 说明: 如果你可以只使用 O(n) 的额外空间(n 为三角形的总行数)来解决这个问题,那么你的算法会很加分。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/probl...
23073922b33e56ecada21cce2317a7578cb61172
lirui-ML/my_leetcode
/Algorithms/79_Word_Search/Word_Search.py
2,446
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 描述:单词搜索,难度(medium) 给定一个二维网格和一个单词,找出该单词是否存在于网格中。 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。 示例: board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] 给定 word = "ABCCED", 返回 true. 给定 word = "SEE", 返回 true. 给定 word = "A...
0b1ae675c2d58b6be0e8d258d1371d9a3f986899
lirui-ML/my_leetcode
/toffer/question_1.py
1,526
3.890625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 剑指 Offer 56 - I. 数组中数字出现的次数 一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。 示例 1: 输入:nums = [4,1,4,6] 输出:[1,6] 或 [6,1] 示例 2: 输入:nums = [1,2,10,4,1,4,3,3] 输出:[2,10] 或 [10,2] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/shu-zu-zhong-s...
5cedf351749b47c657f17e86b1cde281d438353f
lirui-ML/my_leetcode
/Algorithms/24_Swap_Nodes_in_Pairs/Swap_Nodes_in_Pairs.py
1,552
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 描述:两两交换链表中的节点,难度(medium) 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 示例: 给定 1->2->3->4, 你应该返回 2->1->4->3. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # Definition for singly-link...
d18ba9fab9b1c62e3484557c508e1c232c4672d0
deepu426/dice-game
/dicegame.py
806
3.71875
4
import random import banner red='\033[31m' bold='\033[01m' disable='\033[02m' underline='\033[04m' blue='\033[34m' banner.banner() y=2 def roll(player): n=random.randint(1,6) print( f"player {player} value is {n} \n") while True: print(red+"do you want play the game") x=input("yes/no ==>") if x in "yes": tr...
fa1bc5240c8c739e549be7c7a24a6e4170b416ee
LrsNate/M2LI-AnaSynt
/03_spellcheck_compounds/automaton.py
3,634
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import cPickle class Automaton: """ A generic finite-state machine """ def __init__(self, bounded=True): self.transitions = {} self.end_states = {} self.last_state = 1 self.bounded = bounded def learn_rule(self, toke...
d02c66c071663e4ed415764b7ab639656fae68d7
dopplerchase/ATMS-597-SP-2020
/ATMS-597-SP-2020-Project-1/SUBMISSION.py
4,521
3.953125
4
import numpy as np class MrT: """ Authors: Randy J. Chase, David Laferty and Alex Adams MrT is a temperature conversion module. It can convert to any of the 4 major temperature units (F,C,K and R). Supported datatypes: 1) float 2) int 3) list of floats/ints 4) np.array of floats/ints...
1681f182195acc9327986310791230087f520a2b
MapleStory-Archive/maplepy
/maplepy/game/square.py
1,202
3.5
4
import pygame SQUARE_DELTA = 1 SQUARE_SIZE = (50, 50) SQUARE_COLOR = (255, 0, 0) class Square(pygame.sprite.Sprite): def __init__(self): # pygame.sprite.Sprite super().__init__() self.image = pygame.surface.Surface(SQUARE_SIZE) self.image.fill(SQUARE_COLOR) ...
21b6c291e1d2506b1224f4dcb7a9e48e9135174a
IhebChatti/holbertonschool-interview
/0x09-utf8_validation/0-validate_utf8.py
827
3.921875
4
#!/usr/bin/python3 """[method that determines if a given data set represents a valid UTF-8 encoding.] """ def validUTF8(data): """[validUTF8] Args: data ([ a list of integers]): [set can contain multiple characters] Returns: [boolean]: [True if data is a valid UTF-8 encoding, else re...
04d5e00f3169158f829c2976e15b09b25e908fe8
tomchambers2/moodtracker-vision
/test.py
405
3.890625
4
#!/usr/bin/python print "blah" import SimpleCV # from SimpleCV import * # Initialize the camera # cam = Camera() # # Loop to continuously get images # while True: # # Get Image from camera # img = cam.getImage() # # Make image black and white # img = img.binarize() # # Draw the text "Hello World...
54de6c9475059c422d1bde8404cba6c66842eae6
jeremy-wickman/Flush-Simulator
/flush-simulator.py
1,466
3.59375
4
#HOW MANY UNTIL I GET A FLUSH? import random def get_non_negative_int(prompt): while True: try: value = int(raw_input(prompt)) except ValueError: print("Sorry, that's not a valid response") continue if value < 0: print("Sorry, your response ...
4df6a30b049d37e57a9b756a6012a9042e2e7a7c
HAS-Tools-Fall2020/homework-alexamarco
/week3_lists_starter.py
5,115
4.34375
4
# Start code for assignment 3 # this code sets up the lists you will need for your homework # and provides some examples of operations that will be helpful to you # %% # Import the modules we will use import os import numpy as np import pandas as pd import matplotlib.pyplot as plt # %% # ** MODIFY ** # Set the file n...
583925954c93cadb1b8e2814a7c8f37acc296eef
anqitu/MDPTeam15-Algo
/Algo/exploration.py
20,655
3.625
4
from Algo.fastest_path import * """This module defines the Exploration class that handles the exploration algorithm, along with Exceptions used.""" class Exploration: """ This class defines and handles the exploration algorithm. """ def __init__(self, robot, start_time, is_arrow_scan, exploration_limit...
1dc934ad408d2f2e3c279376777a35036b8880cc
JohnnyHowe/slow-engine-2
/sample_programs/player_movement.py
915
3.796875
4
""" Sample program for the SlowEngine. Shows off basic 2D player movement. No bells or whistles. """ import slowEngine import pygame class Game: player = None def __init__(self): self.player = Player() def run(self): while True: self.run_frame() def run_frame(self): ...
6146969b7bd35e4f6178b14281b5a97b7405dafc
HarshRangwala/Python
/python prc/PRACTICAL1F.py
415
4.0625
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 5 21:57:09 2018 @author: Harsh """ def fact(n): if n==1: return n else: return n*fact(n-1) num=int(input("Please Input Here")) if num<0: print("Sorry,only positive numbers accepted") elif num==0: print("The factorial of 0 is 1!") else...
0a39c3021607a61f6f387ef2eca22e400d558bd1
HarshRangwala/Python
/python practice programs/GITpractice33.py
425
4.03125
4
# -*- coding: utf-8 -*- """ Created on Fri Jun 15 17:17:30 2018 @author: Harsh """ ''' Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No". ''' accstr = str(input("Please input here::")) def inpstr(accstr): if (accstr == 'yes') or (accstr ...
45c59cf411b1cac833ef04e97c63477b56db9665
HarshRangwala/Python
/5 Days of Coding Challenges/5 days coding challenge- Number of partitions of a number.py
435
3.703125
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 24 17:38:53 2020 @author: Anuj """ n = int(input("Enter the number : ")) partitions = [] def compositions(remainder, start = 1): if remainder == 0: print(" + ".join(partitions),"=", n) else: for add in range(start, remainder + 1): part...
ebb96e9f6e504a5e33e8b284bea3c8c310beab33
HarshRangwala/Python
/python prc/PRACTICAL2C.py
216
3.5
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 7 22:33:38 2018 @author: Harsh """ def histogram(inputlist1): for i in range (0, len(inputlist1)): print(inputlist1[i]*'*') List = [4,9,7] histogram(List)
dbb85ee65692ddbb9d1cfc2e9e84f963c46cf5b9
HarshRangwala/Python
/5 Days of Coding Challenges/5 days coding challenge- date.py
743
3.546875
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 28 13:30:41 2020 @author: Anuj """ #Problem 2 A dicti = {'01':13,'02':14,'03':15,'04':16,'05':17,'06':18,'07':19,'08':20,'09':21,'10':22,'11':23,'12':12} s = '08:26PM' if s.endswith('AM'): if s.startswith('12'): s1=s[:8] bb=s1.replace('12','00') ...
bee3e27a6d864bd84db38afa9edd7799f02bbf5c
HarshRangwala/Python
/python practice programs/GITpractice35.py
277
4.09375
4
# -*- coding: utf-8 -*- """ Created on Fri Jun 15 20:20:06 2018 @author: Harsh """ ''' Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10]. ''' li = [1,2,3,4,5,6,7,8,9,10] sqnum = map(lambda x: x**2, li) print(sqnum)
60acc197d9bba6c18ae734732994da3bb5c1f1f2
HarshRangwala/Python
/python practice programs/GITpractice2.py
379
4.125
4
# -*- coding: utf-8 -*- """ Created on Fri Jun 8 18:21:30 2018 @author: Harsh """ '''The results should be printed in a comma-separated sequence on a single line. Suppose the following input is supplied to the program: 8 Then, the output should be: 40320 ''' def fact(x): if x==0: return 1 return x*fa...
77474ea435164931d6bbb6aa5ed971deac64e462
HarshRangwala/Python
/python prc/PRACTICAL2B.py
284
3.59375
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 7 17:03:50 2018 @author: Harsh """ modelx = str(input("Please input here::\n\t")) print("The result obtained is::\t\n\t",len(modelx)) Modely = list(input("Please input list here::")) print("The result obtained is::\t\n\t",len(Modely))
7067d4936b74e0ad1d2477f43b597a3b4aeeddfe
WesleyFerreira01/ExerciciosCurso
/imc.py
2,584
3.5625
4
def imc(peso,altura): imc = peso / (altura*altura) return imc def class_imc(sexo,peso,altura): valor_imc = imc(peso,altura) if sexo == 'm': if valor_imc < 20.7: return "Abaixo do peso" elif valor_imc >= 20.7 and valor_imc < 26.4: return "Peso normal" ...
d237c19eccd45af207d4211074ed93b3bccc2e42
ander-garcia/theegg_ai
/tarea_33/pokemon.py
1,201
3.6875
4
class Pokemon(): def __init__(self, nombre, vida, ataque, turno): self.nombre = nombre self.vida = vida self.ataque = ataque self.turno = turno @staticmethod def combate(pokemon1, pokemon2, turno_inicial=1): print( f"Comienza el combate entre {pokemon1.n...
453af87ded814faea2f42ff5ff1f1a88aba1189c
banaconda88/reading-sensor-data
/Untitled.py
654
3.671875
4
#!/usr/bin/env python # coding: utf-8 # In[2]: file = open("sensordata.txt") data = file.read().split() # In[18]: final = [] for d in data: if int(d) >= 200 or int(d)<= -200: continue else: final.append(int(d)) print(final) a = sum(final)/len(final) print(a) final = [] for d in data: ...
20576cf5618464b6c0bbadec7537fe9dd9f234a8
w21180239/Gomuku_zero
/src/reversi_zero/lib/bitboard.py
4,468
3.625
4
# 有巨大问题!!!! import numpy as np BLACK_CHR = "O" WHITE_CHR = "X" EXTRA_CHR = "*" def get_num(length): re = 1 for i in range(length - 1): re <<= 1 re += 1 return re def board_to_string(black, white, with_edge=True, extra=None): """ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1...
264ac7b871d5d45e6e21ba473de6d3a0090dd784
Rotha-Vichet/pythonForBoottCamp
/06_countingsum.py
314
4.15625
4
sum = 0 while True: number = input("enter a number:") if number != "stop": if number.isdecimal(): number = int(number) sum += number else: print("please input valid number") else: print(f"The sum number is ", sum) break
e0a0daeb50c998d31f2dd81986f64fd6b54a416c
Rotha-Vichet/pythonForBoottCamp
/09_random.py
127
3.796875
4
import random for i in range(1): randomNum = random.randint(5, 10) print("random number is:", randomNum)
e7d7fe601e6ec73a4df47fbc75994e4e863bd804
Surya123234/CCC-Solutions
/S2/S2_2016.py
683
3.796875
4
question = int(input()) # 1 = min total speed, 2 = max total speed N = int(input()) # total citizens in each country # input Dcit = input().split() Pcit = input().split() # turning each element to an integer for i in range(N): Dcit[i] = int(Dcit[i]) Pcit[i] = int(Pcit[i]) #sorting Dcit.sort() P...
ee5e5128e8bc366f430a717363cb2dc1162bcf66
Ashish-Abhinav/Remote-Python
/test.py
143
3.75
4
first_number=input("Enter 1st no. = ") second_number=input("Enter 2nd no. = ") out=int(first_number)-int(second_number) print("Output = ",out)
092f762526a8f5bcdbc3f5dffdd9bdae98f065c7
idama73/python
/GraphCurrency.py
1,324
3.5
4
#Name: Arnold Okumagba #Title: Currency History #Abstract: Plots the data that is retrieved from a JSON data that gets pulled #from fixer.io and plots them in a graph of the previous 10 days with the different #currency fluctuation of selected currency. import matplotlib import datetime import urlGrab matplot...
e9fecea6109fbcd5b5782b76395f03fa72259225
Dexx-electronic/Python
/Uno/uno.py
3,482
3.59375
4
import random """ Build deck """ def buildDeck(): deck = [] colours = ["R", "G", "Y", "B"] values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "D2", "Skip", "Rev"] for colour in colours: for value in values: cardVal = f"{colour} {value}" deck.append(cardVal) if (value ...
e5835ca933983d221e2f32f1ee58494b00572e5f
daniel-enere/pymodules
/triangle.py
431
3.828125
4
def area(base,height): return base*height/2 def perimeter(side1, side2, side3): '''(n1, n2, n3) -> number >>> perimeter(4,5,7) 16 >>> perimeter(5.5,8,9.4) 22.9 ''' return base*height*volume def semiperimeter(side1, side2,side3): '''(number1, number2, number3) -> float >>> semip...
5f81236859633ae6763823f250f02e481351cdf6
yilinli22/HM02
/japan_china_india.py
1,048
3.96875
4
import pandas as pd from matplotlib import pyplot as plt import plotly.express as px # import data and create lists of x-variable data = pd.read_csv('data/countries.csv') japan = data[data.country == 'Japan'] china = data[data.country == 'China'] india = data[data.country == 'India'] # print ('japan=', japan) # print(j...
1aaadef9bd7f44b9123e16966f91967121ac72e6
superslach/CalendrierGregorien
/Calendrier.py
2,446
4.0625
4
from FonctionCalendrier import * # Import de toutes les fonctions de FonctionCalendrier verification = False while verification == False : date = input("Saisir une date sous la forme JJ/MM/AAAA ou JJ-MM-AAAA (Date française) : ") # saisie de la date sous la forme JJ/MM/AAAA if date.__contains__("/"): ...
e681f53594ce0c383160ed486ead6427551216b2
weifengliu/LeetCode
/lc729.py
1,139
3.703125
4
class Node: def __init__(self, s, e): self.s = s self.e = e self.left = None self.right = None class MyCalendar: def __init__(self): self.root = None def book(self, start, end): """ :type start: int :type end: int :rtype: bool ...
050529fa98ddd8c251e3bda688214ca99dd75565
rdecarreau/maze
/node.py
1,604
3.96875
4
class Node: ABOVE = "above" BELOW = "below" LEFT = "left" RIGHT = "right" def __init__(self, index, location): """ This Node will contain its own index in the Maze hashmap as well as all indexes of neighboring nodes. :param index: """ self.index = index ...
48a4b6e38f3cd67fb1451ad5aa910c7a59a89a25
panfayang/ProjectEuler
/euler7.py
437
3.546875
4
def checkprime(p): n = [] for m in range(2,int(p**0.5)+1): if p % m ==0: break return False elif m == int(p**0.5): return True def prime(no): m = 0 for i in range(2, 1000000): if checkprime(i) is True: m = m + 1 elif no == m: break return (i-1) print checkprime(5) print prime(99...
78e60596c8c3b13fa5a7a7fef683ca359900cc02
LVO3/python-2021
/ham8.py
325
3.53125
4
#positive.py def positive(l): result = [] for i in l: if i > 0: result.append(i) return result print(positive([-1, -3, 2, 0, -5, 6])) #함수를 사용해서 더욱더 간단하게 만들기 #filter1.py def sositive(x): return x > 0 print(list(filter(sositive, [-1, -3, 2, 0, -5, 6])))
848e276f97b64c66e8e6ef6b2e60cf7da38bbfb8
LVO3/python-2021
/listc.py
80
3.796875
4
a = [1,2,3,4] result = [] for num in a: result.append(num * 3) print(result)
861d6614db4523c6abbb1c03b4eea7b8bd623c6d
LVO3/python-2021
/list4.py
92
3.5
4
result = [x * y for x in range(2, 10) for y in range(1, 10) if x % 2 == 0] print(result)
2cb24e1cddaf9cadb797fa0bf61513bb18c7f705
g-tejas/MiniMax
/src/helper_functions.py
4,431
3.859375
4
import numpy as np def convert_input(x): if x == 1: return (0,0) elif x == 2: return (0,1) elif x == 3: return (0,2) elif x == 4: return (1,0) elif x == 5: return (1,1) elif x == 6: return (1,2) elif x == 7: return (2,0) elif x == ...
58950638fbdb4db1bfab2fac1eb53f78725bdea3
10xsai/algorithms
/sorting_algorithms/selection_sort.py
220
3.921875
4
def sort(array): if len(array)<2: return n = len(array) for i in range(n-1): for j in range(i+1, n): if array[i] > array[j]: array[i], array[j] = array[j], array[i]
f981f786ce0c16e6be9204001f1194595b913c69
paulghaddad/exercism
/python/twelve-days/twelve_days.py
1,443
3.578125
4
DAY_PHRASE_MAPPING = { 1: "first", 2: "second", 3: "third", 4: "fourth", 5: "fifth", 6: "sixth", 7: "seventh", 8: "eighth", 9: "ninth", 10: "tenth", 11: "eleventh", 12: "twelfth", } DAY_CLAUSE_MAPPING = { 1: "a Partridge in a Pear Tree", 2: "two Turtle Doves", ...
4f4400e173e2ae0b44524f43b41bab761d405c1f
paulghaddad/exercism
/python/triangle/triangle.py
550
3.5625
4
SIDES_FOR_TYPE = {"equilateral": 1, "isoceles": 2, "scalene": 3} def is_equilateral(sides): return is_kind("equilateral")(sides) def is_isosceles(sides): return is_kind("isoceles")(sides) or is_equilateral(sides) def is_scalene(sides): return is_kind("scalene")(sides) def is_kind(type): return l...
05ddf0ac89f38cf4d08c28e1284c52ea2ceac429
OchiengHosea/advancedpython
/pandas/multiple_contexts_io.py
224
3.5
4
# Commonly used when converting a file data from one format to another # this needs to have two contexts # one for reading the file and one for writting import re pattern_text = r'\[(?P<date>\d+-\d+-\d+ \d+:\d+:\d+, \d+)\]'
55a533003ad189a3895b81f751ca1ef64aa6baca
ShahiHub/SmartHealthyBuildings
/lab1/good_bye.py
374
3.890625
4
###Hello World! ###The file prints hello world! statement import random def print_bye(text): ###The function prints hello world ###input: string ###output: Boolean n = random.randint(1,25) for i in range(n): print(text) return True def main(): text = "Good Bye Cruel World!!!" ...
5c7d0a3494001e418bcc4160e41d067b188ee833
sukanto-m/Meme-Generator
/src/MemeGenerator/MemeEngine.py
1,123
3.734375
4
"""The meme engine to draw text on images.""" import os import random from PIL import Image, ImageDraw, ImageFont class MemeEngine(): """Draw text on the image.""" def __init__(self, out_dir): """Initialise variables.""" self.out_dir = out_dir if not os.path.exists(out_dir): ...
e1bac32e50aeb867c43b22f7449c75baecad3580
anusha790/Student-Management-System
/stud2.py
2,195
3.59375
4
import tkinter as tk import stud as st root = tk.Tk() root.title("Student Management") heading_label = tk.Label(root,font = ('arial',20,'bold'),text = " STUDENT MANAGEMENT SYSTEM ", pady = 20,padx = 20) heading_label.grid(row=0, column=1) heading_label1 = tk.Label(root,font = (...
2971afff8926a97431d18449f4e0375826362b70
valentinasil/lesson6
/lesson6/problem2.py
304
3.71875
4
name= input('What is your name? ') print('Nice to meet you '+name+ ', my name is chatbot.') years= input ('How old are you? ') print('Wow,'+years+ ' years old! I was born today.') feeling= input('How are you feeling today?' ) print('Glad to hear you are feeling' +feeling+ ". That is wonderful to hear!")
b19106a87d6ca5dd6d2721e73a94883d52582006
ryankirkman/tote
/game/branches/net/gamestate/world.py
2,682
3.546875
4
from __future__ import division from collision import CollisionDetector from event import Event class World(object): """ This class represents the game world, including the map and all objects contained within it. """ def __init__(self): self.objects = [] self.objects_h...
8c9d2611595ca8698ffc3c3888afa2cd30353c62
Lingyu94/Foundation-Studies-of-Python
/input()函数.py
394
3.90625
4
# 开发者:Lingyu # 开发时间:2020/11/30 20:31 a1 = input('请输入第一个加数:') # input(str) a2 = input('请输入第二个加数:') print(type(a1), type(a2)) print(float(a1) + float(a2)) a1 = int(input('请输入第一个加数:')) a2 = int(input('请输入第二个加数:')) print(type(a1), type(a2)) print(a1 + a2) # 字符串格式不能执行加法算法
0b81749b93a4e12cc4f9f065c47a17670ea5e8f1
FidelElie/cliMate
/climate/lib/converters.py
3,552
4.6875
5
""" """ def map_int(to_int) -> int: """Maps value to integer from a string. Parameters ---------- to_int: various (usually str) Value to be converted to integer Returns ------- mapped_int: int Value mapped to integer. Examples -------- >>> number_one = "1" ...